This commit is contained in:
Julius Marminge committed 2026-08-14 11:22:49 +02:00
1 parent 90d0f40790
commit 7c0d40fefe
14 files changed
+1297 -1059

No files matched your search

@@ -12,7 +12,6 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Result from "effect/Result";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveApiModelId } from "@t3tools/shared/model";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import {
query as claudeQuery,
@@ -377,50 +376,13 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
function buildInitialClaudeProviderSnapshot(claudeSettings: ClaudeSettings): ServerProvider {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
slashCommands: [],
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Claude is disabled in T3 Code settings.",
},
});
}
return buildServerProvider({
provider: PROVIDER,
enabled: true,
checkedAt,
models,
slashCommands: [],
probe: {
installed: true,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Checking Claude availability...",
},
});
}
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
return resolveApiModelId(modelSelection);
switch (modelSelection.options?.contextWindow) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
}
}
function toTitleCaseWords(value: string): string {
@@ -1002,7 +964,7 @@ export const ClaudeProviderLive = Layer.effect(
Stream.map((settings) => settings.providers.claudeAgent),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
buildInitialSnapshot: buildInitialClaudeProviderSnapshot,
initialSnapshot: makePendingClaudeProvider,
checkProvider,
});
}),
+480 -365
View File
@@ -6,6 +6,7 @@
import {
ApprovalRequestId,
type CursorModelOptions,
EventId,
type ProviderApprovalDecision,
type ProviderInteractionMode,
@@ -23,12 +24,17 @@ import {
DateTime,
Deferred,
Effect,
Exit,
Fiber,
FileSystem,
Layer,
Queue,
Option,
PubSub,
Random,
Scope,
Semaphore,
Stream,
SynchronizedRef,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import type * as EffectAcpSchema from "effect-acp/schema";
@@ -118,6 +124,7 @@ interface PendingUserInput {
interface CursorSessionContext {
readonly threadId: ThreadId;
session: ProviderSession;
readonly scope: Scope.Closeable;
readonly acp: AcpSessionRuntimeShape;
notificationFiber: Fiber.Fiber<void, never> | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
@@ -237,6 +244,55 @@ function resolveRequestedModeId(input: {
);
}
function applyRequestedSessionConfiguration<E>(input: {
readonly runtime: AcpSessionRuntimeShape;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode | undefined;
readonly modelSelection:
| {
readonly model: string;
readonly options?: CursorModelOptions | null | undefined;
}
| undefined;
readonly mapError: (context: {
readonly cause: import("effect-acp/errors").AcpError;
readonly method: "session/set_config_option" | "session/set_mode";
}) => E;
}): Effect.Effect<void, E> {
return Effect.gen(function* () {
if (input.modelSelection) {
yield* applyCursorAcpModelSelection({
runtime: input.runtime,
model: input.modelSelection.model,
modelOptions: input.modelSelection.options,
mapError: ({ cause }) =>
input.mapError({
cause,
method: "session/set_config_option",
}),
});
}
const requestedModeId = resolveRequestedModeId({
interactionMode: input.interactionMode,
runtimeMode: input.runtimeMode,
modeState: yield* input.runtime.getModeState,
});
if (!requestedModeId) {
return;
}
yield* input.runtime.setMode(requestedModeId).pipe(
Effect.mapError((cause) =>
input.mapError({
cause,
method: "session/set_mode",
}),
),
);
});
}
function selectAutoApprovedPermissionOption(
request: EffectAcpSchema.RequestPermissionRequest,
): string | undefined {
@@ -271,9 +327,12 @@ export function makeCursorAdapter(
stream: "native",
})
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const sessions = new Map<ThreadId, CursorSessionContext>();
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
@@ -301,7 +360,28 @@ export function makeCursorAdapter(
);
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
const getThreadSemaphore = (threadId: string) =>
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
current.get(threadId),
);
return Option.match(existing, {
onNone: () =>
Semaphore.make(1).pipe(
Effect.map((semaphore) => {
const next = new Map(current);
next.set(threadId, semaphore);
return [semaphore, next] as const;
}),
),
onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
});
});
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
const logNative = (
threadId: ThreadId,
@@ -383,7 +463,7 @@ export function makeCursorAdapter(
if (ctx.notificationFiber) {
yield* Fiber.interrupt(ctx.notificationFiber);
}
yield* Effect.ignore(ctx.acp.close);
yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
sessions.delete(ctx.threadId);
yield* offerRuntimeEvent({
type: "session.exited",
@@ -395,355 +475,395 @@ export function makeCursorAdapter(
});
const startSession: CursorAdapterShape["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
}
if (!input.cwd?.trim()) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: "cwd is required and must be non-empty.",
});
}
withThreadLock(
input.threadId,
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
}
if (!input.cwd?.trim()) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: "cwd is required and must be non-empty.",
});
}
const cwd = nodePath.resolve(input.cwd.trim());
const cursorModelSelection =
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
}
const cwd = nodePath.resolve(input.cwd.trim());
const cursorModelSelection =
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
}
const cursorSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.cursor),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
let ctx!: CursorSessionContext;
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
const acpNativeLoggers = makeAcpNativeLoggers({
nativeEventLogger,
provider: PROVIDER,
threadId: input.threadId,
});
const acp = yield* makeCursorAcpRuntime({
cursorSettings,
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
...acpNativeLoggers,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
);
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.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(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 };
}),
const cursorSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.cursor),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
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;
}),
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
yield* Effect.addFinalizer(() =>
sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
);
yield* acp.handleExtNotification(
"cursor/update_todos",
CursorUpdateTodosRequest,
(params) =>
let ctx!: CursorSessionContext;
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
const acpNativeLoggers = makeAcpNativeLoggers({
nativeEventLogger,
provider: PROVIDER,
threadId: input.threadId,
});
const acp = yield* makeCursorAcpRuntime({
cursorSettings,
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
...acpNativeLoggers,
}).pipe(
Effect.provideService(Scope.Scope, sessionScope),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
);
const started = yield* Effect.gen(function* () {
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/update_todos",
"cursor/ask_question",
params,
"acp.cursor.extension",
);
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
const requestId = ApprovalRequestId.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(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",
"cursor/update_todos",
);
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",
);
if (input.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.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(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),
),
);
yield* applyRequestedSessionConfiguration({
runtime: acp,
runtimeMode: input.runtimeMode,
interactionMode: undefined,
modelSelection: cursorModelSelection,
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
const now = yield* nowIso;
const session: ProviderSession = {
provider: PROVIDER,
status: "ready",
runtimeMode: input.runtimeMode,
cwd,
model: cursorModelSelection?.model,
threadId: input.threadId,
resumeCursor: {
schemaVersion: CURSOR_RESUME_VERSION,
sessionId: started.sessionId,
},
createdAt: now,
updatedAt: now,
};
ctx = {
threadId: input.threadId,
session,
scope: sessionScope,
acp,
notificationFiber: undefined,
pendingApprovals,
pendingUserInputs,
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
stopped: false,
};
const nf = yield* Stream.runDrain(
Stream.mapEffect(acp.getEvents(), (event) =>
Effect.gen(function* () {
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(
ctx,
event.payload,
event.rawPayload,
"acp.jsonrpc",
"session/update",
);
return;
case "ToolCallUpdated":
yield* logNative(
ctx.threadId,
"session/update",
event.rawPayload,
"acp.jsonrpc",
);
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
rawPayload: event.rawPayload,
}),
);
return;
case "ContentDelta":
yield* logNative(
ctx.threadId,
"session/update",
event.rawPayload,
"acp.jsonrpc",
);
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
}),
);
return;
}
}),
);
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.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(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),
),
);
),
).pipe(Effect.forkChild);
const now = yield* nowIso;
const session: ProviderSession = {
provider: PROVIDER,
status: "ready",
runtimeMode: input.runtimeMode,
cwd,
model: cursorModelSelection?.model,
threadId: input.threadId,
resumeCursor: {
schemaVersion: CURSOR_RESUME_VERSION,
sessionId: started.sessionId,
},
createdAt: now,
updatedAt: now,
};
ctx.notificationFiber = nf;
sessions.set(input.threadId, ctx);
sessionScopeTransferred = true;
ctx = {
threadId: input.threadId,
session,
acp,
notificationFiber: undefined,
pendingApprovals,
pendingUserInputs,
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
stopped: false,
};
yield* offerRuntimeEvent({
type: "session.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { resume: started.initializeResult },
});
yield* offerRuntimeEvent({
type: "session.state.changed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { state: "ready", reason: "Cursor ACP session ready" },
});
yield* offerRuntimeEvent({
type: "thread.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { providerThreadId: started.sessionId },
});
const nf = yield* Stream.runDrain(
Stream.mapEffect(acp.events, (event) =>
Effect.gen(function* () {
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(
ctx,
event.payload,
event.rawPayload,
"acp.jsonrpc",
"session/update",
);
return;
case "ToolCallUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
rawPayload: event.rawPayload,
}),
);
return;
case "ContentDelta":
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
}),
);
return;
}
}),
),
).pipe(Effect.forkChild);
ctx.notificationFiber = nf;
sessions.set(input.threadId, ctx);
yield* offerRuntimeEvent({
type: "session.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { resume: started.initializeResult },
});
yield* offerRuntimeEvent({
type: "session.state.changed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { state: "ready", reason: "Cursor ACP session ready" },
});
yield* offerRuntimeEvent({
type: "thread.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { providerThreadId: started.sessionId },
});
return session;
});
return session;
}).pipe(Effect.scoped),
);
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
@@ -753,12 +873,19 @@ export function makeCursorAdapter(
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyCursorAcpModelSelection({
yield* applyRequestedSessionConfiguration({
runtime: ctx.acp,
model,
modelOptions: turnModelSelection?.options,
mapError: ({ cause }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_config_option", cause),
runtimeMode: ctx.session.runtimeMode,
interactionMode: input.interactionMode,
modelSelection:
model === undefined
? undefined
: {
model,
options: turnModelSelection?.options,
},
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
@@ -768,23 +895,6 @@ export function makeCursorAdapter(
updatedAt: yield* nowIso,
};
const requestedModeId = resolveRequestedModeId({
interactionMode: input.interactionMode,
runtimeMode: ctx.session.runtimeMode,
modeState: yield* ctx.acp.getModeState,
});
if (requestedModeId) {
yield* Effect.ignore(
ctx.acp
.setMode(requestedModeId)
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_mode", error),
),
),
);
}
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
@@ -907,6 +1017,7 @@ export function makeCursorAdapter(
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
@@ -974,10 +1085,13 @@ export function makeCursorAdapter(
});
const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* stopSessionInternal(ctx);
});
withThreadLock(
threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* stopSessionInternal(ctx);
}),
);
const listSessions: CursorAdapterShape["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
@@ -993,10 +1107,13 @@ export function makeCursorAdapter(
yield* Effect.addFinalizer(() =>
Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
),
);
const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
return {
provider: PROVIDER,
capabilities: { sessionModelSwitch: "in-session" },
@@ -1011,9 +1128,7 @@ export function makeCursorAdapter(
listSessions,
hasSession,
stopAll,
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
streamEvents,
} satisfies CursorAdapterShape;
});
}
@@ -1,9 +1,20 @@
import * as path from "node:path";
import * as os from "node:os";
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
import {
buildCursorProviderSnapshot,
buildCursorCapabilitiesFromConfigOptions,
buildCursorDiscoveredModelsFromConfigOptions,
discoverCursorModelCapabilitiesViaAcp,
discoverCursorModelsViaAcp,
getCursorFallbackModels,
getCursorParameterizedModelPickerUnsupportedMessage,
parseCursorAboutOutput,
@@ -13,6 +24,37 @@ import {
resolveCursorAcpConfigUpdates,
} from "./CursorProvider.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
const wrapperPath = path.join(dir, "fake-agent.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
.join("\n");
const script = `#!/bin/sh
${envExports}
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
return wrapperPath;
}
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const content = await readFile(filePath, "utf8");
if (content.trim().length > 0) {
return content;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
const parameterizedGpt54ConfigOptions = [
{
type: "select",
@@ -90,6 +132,64 @@ const parameterizedClaudeConfigOptions = [
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const parameterizedClaudeModelOptionConfigOptions = [
{
type: "select",
currentValue: "claude-opus-4-6",
options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
category: "model",
id: "model",
name: "Model",
},
{
type: "select",
currentValue: "high",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
],
category: "thought_level",
id: "reasoning",
name: "Reasoning",
},
{
type: "select",
currentValue: "max",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
{ name: "Max", value: "max" },
],
category: "model_option",
id: "effort",
name: "Effort",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
category: "model_config",
id: "fast",
name: "Fast",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: ":icon-brain:", value: "true" },
],
category: "model_config",
id: "thinking",
name: "Thinking",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const sessionNewCursorConfigOptions = [
{
type: "select",
@@ -132,6 +232,21 @@ const sessionNewCursorConfigOptions = [
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const baseCursorSettings: CursorSettings = {
enabled: true,
binaryPath: "agent",
apiEndpoint: "",
customModels: [],
};
const emptyCapabilities = {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
} as const;
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
expect(
@@ -142,6 +257,56 @@ describe("getCursorFallbackModels", () => {
});
});
describe("buildCursorProviderSnapshot", () => {
it("downgrades ready status to warning when ACP model discovery times out", () => {
expect(
buildCursorProviderSnapshot({
checkedAt: "2026-01-01T00:00:00.000Z",
cursorSettings: baseCursorSettings,
parsed: {
version: "2026.04.09-f2b0fcd",
status: "ready",
auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
},
discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
}),
).toMatchObject({
status: "warning",
message: "Cursor ACP model discovery timed out after 15000ms.",
models: [],
});
});
it("preserves provider error state while appending discovery warnings", () => {
expect(
buildCursorProviderSnapshot({
checkedAt: "2026-01-01T00:00:00.000Z",
cursorSettings: {
...baseCursorSettings,
customModels: ["claude-sonnet-4-6"],
},
parsed: {
version: "2026.04.09-f2b0fcd",
status: "error",
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
models: [
{
slug: "claude-sonnet-4-6",
isCustom: true,
},
],
});
});
});
describe("buildCursorCapabilitiesFromConfigOptions", () => {
it("derives model capabilities from parameterized Cursor ACP config options", () => {
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual(
@@ -177,6 +342,23 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
}),
);
});
it("prefers the newer model_option effort control over legacy thought_level", () => {
expect(
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
).toEqual({
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "max", label: "Max", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
});
});
});
describe("checkCursorProviderStatus", () => {
@@ -226,6 +408,91 @@ describe("checkCursorProviderStatus", () => {
});
});
describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await makeMockAgentWrapper();
const models = await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
});
it("closes the ACP probe runtime after discovery completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
);
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog).toContain("SIGTERM");
});
});
describe("discoverCursorModelCapabilitiesViaAcp", () => {
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
const existingModels: ReadonlyArray<ServerProviderModel> = [
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
];
const models = await Effect.runPromise(
discoverCursorModelCapabilitiesViaAcp(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
existingModels,
).pipe(Effect.provide(NodeServices.layer)),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
});
});
describe("parseCursorAboutOutput", () => {
it("parses json about output and forwards subscription metadata", () => {
expect(
@@ -377,4 +644,16 @@ describe("resolveCursorAcpConfigUpdates", () => {
]),
).toEqual([{ configId: "fast", value: "false" }]);
});
it("writes Cursor effort changes through the newer model_option config when available", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, {
reasoning: "max",
thinking: false,
}),
).toEqual([
{ configId: "effort", value: "max" },
{ configId: "thinking", value: "false" },
]);
});
});
@@ -298,7 +298,7 @@ type EventBaseInput = {
raw: {
source: "opencode.sdk.event",
payload: input.raw,
} as unknown as ProviderRuntimeEvent["raw"],
},
}
: {}),
};
@@ -10,9 +10,14 @@ import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
@@ -57,6 +62,23 @@ const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
provider: "opencode",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
const fakeCursorAdapter: CursorAdapterShape = {
provider: "cursor",
capabilities: { sessionModelSwitch: "in-session" },
@@ -81,6 +103,7 @@ const layer = it.layer(
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
@@ -95,13 +118,15 @@ it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
const openCode = yield* registry.getByProvider("opencode");
const cursor = yield* registry.getByProvider("cursor");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
assert.equal(openCode, fakeOpenCodeAdapter);
assert.equal(cursor, fakeCursorAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeAgent", "cursor"]);
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
}),
);
@@ -32,6 +32,7 @@ import {
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
const registry = yield* ProviderInstanceRegistry;
@@ -43,7 +44,12 @@ const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(fun
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter, yield* CursorAdapter];
: [
yield* CodexAdapter,
yield* ClaudeAdapter,
yield* OpenCodeAdapter,
...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []),
];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>