servicify

This commit is contained in:
Julius Marminge committed 2026-04-17 16:44:48 -07:00
1 parent e43002eaf1
commit d4511012f4
11 files changed
+1728 -1424

No files matched your search

+166 -158
View File
@@ -27,10 +27,10 @@ import {
Layer,
Queue,
Random,
Scope,
Stream,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { defineExtNotification, defineExtRequest } from "effect-acp/client";
import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -42,7 +42,7 @@ import {
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
} from "../Errors.ts";
import { makeAcpSessionRuntime, type AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
import { AcpSessionRuntime, type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
import {
makeAcpContentDeltaEvent,
@@ -92,7 +92,7 @@ interface PendingUserInput {
interface CursorSessionContext {
readonly threadId: ThreadId;
session: ProviderSession;
readonly acp: AcpSessionRuntime;
readonly acp: AcpSessionRuntimeShape;
notificationFiber: Fiber.Fiber<void, never> | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
@@ -379,158 +379,22 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
threadId: input.threadId,
});
const acp = yield* makeAcpSessionRuntime({
spawn: spawnOptions,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
authMethodId: "cursor_login",
...acpNativeLoggers,
handlers: {
extRequests: {
"cursor/ask_question": defineExtRequest(CursorAskQuestionRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
),
"cursor/create_plan": defineExtRequest(CursorCreatePlanRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/create_plan",
params,
"acp.cursor.extension",
);
yield* offerRuntimeEvent({
type: "turn.proposed.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
payload: { planMarkdown: extractPlanMarkdown(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/create_plan",
payload: params,
},
});
return { accepted: true } as const;
}),
),
},
extNotifications: {
"cursor/update_todos": defineExtNotification(CursorUpdateTodosRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/update_todos",
params,
"acp.cursor.extension",
);
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
params,
"acp.cursor.extension",
"cursor/update_todos",
);
}
}),
),
},
requestPermission: (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"session/request_permission",
params,
"acp.jsonrpc",
);
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
},
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
const acpContextScope = yield* Scope.make("sequential");
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
spawn: spawnOptions,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
authMethodId: "cursor_login",
...acpNativeLoggers,
}).pipe(
Layer.provide(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
),
),
).pipe(
Effect.provideService(Scope.Scope, acpContextScope),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
@@ -541,6 +405,150 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
}),
),
);
const acp = yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
const started = yield* Effect.gen(function* () {
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
);
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/create_plan",
params,
"acp.cursor.extension",
);
yield* offerRuntimeEvent({
type: "turn.proposed.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
payload: { planMarkdown: extractPlanMarkdown(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/create_plan",
payload: params,
},
});
return { accepted: true } as const;
}),
);
yield* acp.handleExtNotification(
"cursor/update_todos",
CursorUpdateTodosRequest,
(params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/update_todos",
params,
"acp.cursor.extension",
);
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
params,
"acp.cursor.extension",
"cursor/update_todos",
);
}
}),
);
yield* acp.handleRequestPermission((params) =>
Effect.gen(function* () {
yield* logNative(input.threadId, "session/request_permission", params, "acp.jsonrpc");
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.makeUnsafe(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
);
return yield* acp.start();
}).pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
),
);
const now = yield* nowIso;
const session: ProviderSession = {
@@ -552,7 +560,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
threadId: input.threadId,
resumeCursor: {
schemaVersion: CURSOR_RESUME_VERSION,
sessionId: acp.sessionId,
sessionId: started.sessionId,
},
createdAt: now,
updatedAt: now,
@@ -626,7 +634,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { resume: acp.initializeResult },
payload: { resume: started.initializeResult },
});
yield* offerRuntimeEvent({
type: "session.state.changed",
@@ -640,7 +648,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { providerThreadId: acp.sessionId },
payload: { providerThreadId: started.sessionId },
});
return session;
@@ -8,7 +8,7 @@ import { it } from "@effect/vitest";
import { Effect, Stream } from "effect";
import { describe, expect } from "vitest";
import { makeAcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
import type * as EffectAcpProtocol from "effect-acp/protocol";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -18,18 +18,11 @@ const bunExe = "bun";
describe("AcpSessionRuntime", () => {
it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
Effect.gen(function* () {
const runtime = yield* makeAcpSessionRuntime({
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
});
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
expect(runtime.initializeResult).toMatchObject({ protocolVersion: 1 });
expect(runtime.sessionId).toBe("mock-session-1");
expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
expect(started.sessionId).toBe("mock-session-1");
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
@@ -46,25 +39,28 @@ describe("AcpSessionRuntime", () => {
}
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("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);
}),
});
it.effect("logs ACP requests from the shared runtime", () => {
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
yield* runtime.setModel("composer-2");
yield* runtime.prompt({
@@ -93,29 +89,32 @@ describe("AcpSessionRuntime", () => {
).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) =>
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
requestLogger: (event) =>
Effect.sync(() => {
protocolEvents.push(event);
requestEvents.push(event);
}),
},
});
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
@@ -135,25 +134,37 @@ describe("AcpSessionRuntime", () => {
).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,
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
});
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
protocolLogging: {
logIncoming: true,
logOutgoing: true,
logger: (event) =>
Effect.sync(() => {
protocolEvents.push(event);
}),
},
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "acp-runtime-"));
const requestLogPath = path.join(tempDir, "requests.ndjson");
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
expect(error._tag).toBe("AcpRequestError");
@@ -181,6 +192,23 @@ describe("AcpSessionRuntime", () => {
).toBe(false);
rmSync(tempDir, { recursive: true, force: true });
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
env: {
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
});
+260 -127
View File
@@ -1,4 +1,15 @@
import { Cause, Effect, Exit, Queue, Ref, Scope, Stream } from "effect";
import {
Cause,
Deferred,
Effect,
Exit,
Layer,
Queue,
Ref,
Scope,
ServiceMap,
Stream,
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpClient from "effect-acp/client";
import * as EffectAcpErrors from "effect-acp/errors";
@@ -33,7 +44,6 @@ export interface AcpSessionRuntimeOptions {
readonly version: string;
};
readonly authMethodId: string;
readonly handlers?: Omit<EffectAcpClient.AcpClientHandlers, "sessionUpdate">;
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
readonly protocolLogging?: {
readonly logIncoming?: boolean;
@@ -50,7 +60,7 @@ export interface AcpSessionRequestLogEvent {
readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
}
export interface AcpSessionRuntime {
export interface AcpSessionRuntimeStartResult {
readonly sessionId: string;
readonly initializeResult: EffectAcpSchema.InitializeResponse;
readonly sessionSetupResult:
@@ -58,6 +68,25 @@ export interface AcpSessionRuntime {
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
readonly modelConfigId: string | undefined;
}
export interface AcpSessionRuntimeShape {
readonly handleRequestPermission: EffectAcpClient.AcpConnectionShape["handleRequestPermission"];
readonly handleElicitation: EffectAcpClient.AcpConnectionShape["handleElicitation"];
readonly handleReadTextFile: EffectAcpClient.AcpConnectionShape["handleReadTextFile"];
readonly handleWriteTextFile: EffectAcpClient.AcpConnectionShape["handleWriteTextFile"];
readonly handleCreateTerminal: EffectAcpClient.AcpConnectionShape["handleCreateTerminal"];
readonly handleTerminalOutput: EffectAcpClient.AcpConnectionShape["handleTerminalOutput"];
readonly handleTerminalWaitForExit: EffectAcpClient.AcpConnectionShape["handleTerminalWaitForExit"];
readonly handleTerminalKill: EffectAcpClient.AcpConnectionShape["handleTerminalKill"];
readonly handleTerminalRelease: EffectAcpClient.AcpConnectionShape["handleTerminalRelease"];
readonly handleSessionUpdate: EffectAcpClient.AcpConnectionShape["handleSessionUpdate"];
readonly handleElicitationComplete: EffectAcpClient.AcpConnectionShape["handleElicitationComplete"];
readonly handleUnknownExtRequest: EffectAcpClient.AcpConnectionShape["handleUnknownExtRequest"];
readonly handleUnknownExtNotification: EffectAcpClient.AcpConnectionShape["handleUnknownExtNotification"];
readonly handleExtRequest: EffectAcpClient.AcpConnectionShape["handleExtRequest"];
readonly handleExtNotification: EffectAcpClient.AcpConnectionShape["handleExtNotification"];
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly events: Stream.Stream<AcpParsedSessionEvent, never>;
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
readonly prompt: (
@@ -83,10 +112,35 @@ export interface AcpSessionRuntime {
readonly close: Effect.Effect<void>;
}
export const makeAcpSessionRuntime = (
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
type AcpStartState =
| { readonly _tag: "NotStarted" }
| {
readonly _tag: "Starting";
readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
}
| { readonly _tag: "Started"; readonly result: AcpStartedState };
export class AcpSessionRuntime extends ServiceMap.Service<
AcpSessionRuntime,
AcpSessionRuntimeShape
>()("t3/provider/acp/AcpSessionRuntime") {
static layer(
options: AcpSessionRuntimeOptions,
): Layer.Layer<
AcpSessionRuntime,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
> {
return Layer.effect(AcpSessionRuntime, makeAcpSessionRuntime(options));
}
}
const makeAcpSessionRuntime = (
options: AcpSessionRuntimeOptions,
): Effect.Effect<
AcpSessionRuntime,
AcpSessionRuntimeShape,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
> =>
@@ -97,6 +151,7 @@ export const makeAcpSessionRuntime = (
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 startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
const logRequest = (event: AcpSessionRequestLogEvent) =>
options.requestLogger ? options.requestLogger(event) : Effect.void;
@@ -148,102 +203,43 @@ 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) =>
handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
params: notification,
}),
},
}).pipe(Effect.provideService(Scope.Scope, runtimeScope));
const acpContext = yield* Layer.build(
EffectAcpClient.layerFromChildProcessHandle(child, {
...(options.protocolLogging?.logIncoming !== undefined
? { logIncoming: options.protocolLogging.logIncoming }
: {}),
...(options.protocolLogging?.logOutgoing !== undefined
? { logOutgoing: options.protocolLogging.logOutgoing }
: {}),
...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
}),
).pipe(Effect.provideService(Scope.Scope, runtimeScope));
const initializePayload = {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: options.clientInfo,
} satisfies EffectAcpSchema.InitializeRequest;
const initializeResult = yield* runLoggedRequest(
"initialize",
initializePayload,
client.initialize(initializePayload),
const acp = yield* Effect.service(EffectAcpClient.AcpConnection).pipe(
Effect.provide(acpContext),
);
const authenticatePayload = {
methodId: options.authMethodId,
} satisfies EffectAcpSchema.AuthenticateRequest;
yield* runLoggedRequest(
"authenticate",
authenticatePayload,
client.authenticate(authenticatePayload),
yield* acp.handleSessionUpdate((notification) =>
handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
params: notification,
}),
);
let sessionId: string;
let sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
if (options.resumeSessionId) {
const loadPayload = {
sessionId: options.resumeSessionId,
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.LoadSessionRequest;
const resumed = yield* runLoggedRequest(
"session/load",
loadPayload,
client.loadSession(loadPayload),
).pipe(Effect.exit);
if (Exit.isSuccess(resumed)) {
sessionId = options.resumeSessionId;
sessionSetupResult = resumed.value;
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
client.createSession(createPayload),
);
sessionId = created.sessionId;
sessionSetupResult = created;
}
} else {
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 getStartedState = Effect.gen(function* () {
const state = yield* Ref.get(startStateRef);
if (state._tag === "Started") {
return state.result;
}
return yield* new EffectAcpErrors.AcpTransportError({
detail: "ACP session runtime has not been started",
cause: new Error("ACP session runtime has not been started"),
});
});
const validateConfigOptionValue = (
configId: string,
value: string | boolean,
@@ -306,64 +302,201 @@ export const makeAcpSessionRuntime = (
value: string | boolean,
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
validateConfigOptionValue(configId, value).pipe(
Effect.flatMap(() => {
Effect.flatMap(() => getStartedState),
Effect.flatMap((started) => {
const requestPayload =
typeof value === "boolean"
? ({
sessionId,
sessionId: started.sessionId,
configId,
type: "boolean",
value,
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
: ({
sessionId,
sessionId: started.sessionId,
configId,
value: String(value),
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
return runLoggedRequest(
"session/set_config_option",
requestPayload,
client.setSessionConfigOption(requestPayload),
acp.setSessionConfigOption(requestPayload),
).pipe(Effect.tap((response) => updateConfigOptions(response)));
}),
);
const startOnce = Effect.gen(function* () {
const initializePayload = {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
},
clientInfo: options.clientInfo,
} satisfies EffectAcpSchema.InitializeRequest;
const initializeResult = yield* runLoggedRequest(
"initialize",
initializePayload,
acp.initialize(initializePayload),
);
const authenticatePayload = {
methodId: options.authMethodId,
} satisfies EffectAcpSchema.AuthenticateRequest;
yield* runLoggedRequest(
"authenticate",
authenticatePayload,
acp.authenticate(authenticatePayload),
);
let sessionId: string;
let sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse;
if (options.resumeSessionId) {
const loadPayload = {
sessionId: options.resumeSessionId,
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.LoadSessionRequest;
const resumed = yield* runLoggedRequest(
"session/load",
loadPayload,
acp.loadSession(loadPayload),
).pipe(Effect.exit);
if (Exit.isSuccess(resumed)) {
sessionId = options.resumeSessionId;
sessionSetupResult = resumed.value;
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
acp.createSession(createPayload),
);
sessionId = created.sessionId;
sessionSetupResult = created;
}
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
acp.createSession(createPayload),
);
sessionId = created.sessionId;
sessionSetupResult = created;
}
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
const nextState = {
sessionId,
initializeResult,
sessionSetupResult,
modelConfigId: extractModelConfigId(sessionSetupResult),
} satisfies AcpStartedState;
return nextState;
});
const start = Effect.gen(function* () {
const deferred = yield* Deferred.make<
AcpSessionRuntimeStartResult,
EffectAcpErrors.AcpError
>();
const effect = yield* Ref.modify(startStateRef, (state) => {
switch (state._tag) {
case "Started":
return [Effect.succeed(state.result), state] as const;
case "Starting":
return [Deferred.await(state.deferred), state] as const;
case "NotStarted":
return [
startOnce.pipe(
Effect.tap((result) =>
Ref.set(startStateRef, { _tag: "Started", result }).pipe(
Effect.andThen(Deferred.succeed(deferred, result)),
),
),
Effect.onError((cause) =>
Deferred.failCause(deferred, cause).pipe(
Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
),
),
),
{ _tag: "Starting", deferred } satisfies AcpStartState,
] as const;
}
});
return yield* effect;
});
return {
sessionId,
initializeResult,
sessionSetupResult,
modelConfigId: extractModelConfigId(sessionSetupResult),
handleRequestPermission: acp.handleRequestPermission,
handleElicitation: acp.handleElicitation,
handleReadTextFile: acp.handleReadTextFile,
handleWriteTextFile: acp.handleWriteTextFile,
handleCreateTerminal: acp.handleCreateTerminal,
handleTerminalOutput: acp.handleTerminalOutput,
handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
handleTerminalKill: acp.handleTerminalKill,
handleTerminalRelease: acp.handleTerminalRelease,
handleSessionUpdate: acp.handleSessionUpdate,
handleElicitationComplete: acp.handleElicitationComplete,
handleUnknownExtRequest: acp.handleUnknownExtRequest,
handleUnknownExtNotification: acp.handleUnknownExtNotification,
handleExtRequest: acp.handleExtRequest,
handleExtNotification: acp.handleExtNotification,
start: () => start,
events: Stream.fromQueue(eventQueue),
getModeState: Ref.get(modeStateRef),
prompt: (payload) => {
const requestPayload = {
sessionId,
...payload,
} satisfies EffectAcpSchema.PromptRequest;
return runLoggedRequest("session/prompt", requestPayload, client.prompt(requestPayload));
},
cancel: client.cancel({ sessionId }),
setMode: (modeId) => {
const requestPayload = {
sessionId,
modeId,
} satisfies EffectAcpSchema.SetSessionModeRequest;
return runLoggedRequest(
"session/set_mode",
requestPayload,
client.setSessionMode(requestPayload),
);
},
prompt: (payload) =>
getStartedState.pipe(
Effect.flatMap((started) => {
const requestPayload = {
sessionId: started.sessionId,
...payload,
} satisfies EffectAcpSchema.PromptRequest;
return runLoggedRequest("session/prompt", requestPayload, acp.prompt(requestPayload));
}),
),
cancel: getStartedState.pipe(
Effect.flatMap((started) => acp.cancel({ sessionId: started.sessionId })),
),
setMode: (modeId) =>
getStartedState.pipe(
Effect.flatMap((started) => {
const requestPayload = {
sessionId: started.sessionId,
modeId,
} satisfies EffectAcpSchema.SetSessionModeRequest;
return runLoggedRequest(
"session/set_mode",
requestPayload,
acp.setSessionMode(requestPayload),
);
}),
),
setConfigOption,
setModel: (model) =>
setConfigOption(extractModelConfigId(sessionSetupResult) ?? "model", model).pipe(
getStartedState.pipe(
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
Effect.asVoid,
),
request: (method, payload) =>
runLoggedRequest(method, payload, client.extRequest(method, payload)),
notify: client.extNotification,
request: (method, payload) => runLoggedRequest(method, payload, acp.request(method, payload)),
notify: acp.notify,
close,
} satisfies AcpSessionRuntime;
} satisfies AcpSessionRuntimeShape;
});
function sessionConfigOptionsFromSetup(
@@ -8,42 +8,41 @@ import { Effect } from "effect";
import { describe, expect } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import { makeAcpSessionRuntime } from "./AcpSessionRuntime.ts";
import { AcpSessionRuntime } from "./AcpSessionRuntime.ts";
describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => {
it.effect("initialize and authenticate against real agent acp", () =>
Effect.gen(function* () {
const runtime = yield* makeAcpSessionRuntime({
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
authMethodId: "cursor_login",
});
expect(runtime.initializeResult).toBeDefined();
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.initializeResult).toBeDefined();
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
authMethodId: "cursor_login",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("session/new returns configOptions with a model selector", () =>
Effect.gen(function* () {
const runtime = yield* makeAcpSessionRuntime({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
});
const result = runtime.sessionSetupResult;
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
const result = started.sessionSetupResult;
console.log("session/new result:", JSON.stringify(result, null, 2));
expect(typeof runtime.sessionId).toBe("string");
expect(typeof started.sessionId).toBe("string");
const configOptions = result.configOptions;
console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2));
@@ -55,22 +54,29 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
expect(typeof modelConfig?.id).toBe("string");
}
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("session/set_config_option switches the model in-session", () =>
Effect.gen(function* () {
const runtime = yield* makeAcpSessionRuntime({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
});
const newResult = runtime.sessionSetupResult;
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
const newResult = started.sessionSetupResult;
const configOptions = newResult.configOptions;
let modelConfigId = "model";
@@ -93,6 +99,21 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
}
}
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
args: ["acp"],
cwd: process.cwd(),
},
cwd: process.cwd(),
clientInfo: { name: "t3-probe", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
});