Use generic ACP adapter for registry sessions
- Route ACP registry through the shared generic adapter - Simplify cursor adapter session setup and model selection - Preserve cursor-specific extension handling in the cursor layer
This commit is contained in:
1 parent
1d1d67c4bd
commit
4e10a99aa9
5 files changed
+866
-260
No files matched your search
@@ -126,8 +126,8 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
|
||||
const adapter = yield* makeGenericAcpAdapter(
|
||||
{
|
||||
enabled: effectiveConfig.enabled,
|
||||
binaryPath: effectiveConfig.command || "acp",
|
||||
customModels: effectiveConfig.customModels,
|
||||
command: effectiveConfig.command || "acp",
|
||||
args: effectiveConfig.args,
|
||||
},
|
||||
{
|
||||
provider: DRIVER_KIND,
|
||||
@@ -135,12 +135,6 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
|
||||
environment: processEnv,
|
||||
readyReason: "ACP session ready",
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
spawn: ({ cwd, environment: spawnEnv }) => ({
|
||||
command: effectiveConfig.command.trim(),
|
||||
args: effectiveConfig.args,
|
||||
cwd,
|
||||
...(spawnEnv ? { env: spawnEnv } : {}),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -65,7 +65,6 @@ import {
|
||||
} from "../acp/AcpRuntimeModel.ts";
|
||||
import { makeAcpNativeLoggers } from "../acp/AcpNativeLogging.ts";
|
||||
import { applyCursorAcpModelSelection, makeCursorAcpRuntime } from "../acp/CursorAcpSupport.ts";
|
||||
import { makeGenericAcpRuntime } from "../acp/GenericAcpSupport.ts";
|
||||
import {
|
||||
CursorAskQuestionRequest,
|
||||
CursorCreatePlanRequest,
|
||||
@@ -88,23 +87,6 @@ export interface CursorAdapterLiveOptions {
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
readonly provider?: ProviderDriverKind;
|
||||
readonly readyReason?: string;
|
||||
readonly spawn?: (input: {
|
||||
readonly settings: CursorSettings;
|
||||
readonly cwd: string;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}) => {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
};
|
||||
readonly normalizeModel?: (model: string | null | undefined) => string;
|
||||
readonly applyCursorModelOptions?: boolean;
|
||||
readonly cursorExtensions?: boolean;
|
||||
readonly authMethodId?: string | undefined;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
/**
|
||||
* Selections are honored when `modelSelection.instanceId` matches this value.
|
||||
* Defaults to the legacy built-in instance id (`cursor`).
|
||||
@@ -262,8 +244,6 @@ function applyRequestedSessionConfiguration<E>(input: {
|
||||
readonly options?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
|
||||
}
|
||||
| undefined;
|
||||
readonly normalizeModel: (model: string | null | undefined) => string;
|
||||
readonly applyCursorModelOptions: boolean;
|
||||
readonly mapError: (context: {
|
||||
readonly cause: import("effect-acp/errors").AcpError;
|
||||
readonly method: "session/set_config_option" | "session/set_mode";
|
||||
@@ -271,30 +251,16 @@ function applyRequestedSessionConfiguration<E>(input: {
|
||||
}): Effect.Effect<void, E> {
|
||||
return Effect.gen(function* () {
|
||||
if (input.modelSelection) {
|
||||
if (input.applyCursorModelOptions) {
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime: input.runtime,
|
||||
model: input.modelSelection.model,
|
||||
selections: input.modelSelection.options,
|
||||
mapError: ({ cause }) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
method: "session/set_config_option",
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
const normalizedModel = input.normalizeModel(input.modelSelection.model);
|
||||
if (normalizedModel !== "default") {
|
||||
yield* input.runtime.setModel(normalizedModel).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
method: "session/set_config_option",
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime: input.runtime,
|
||||
model: input.modelSelection.model,
|
||||
selections: input.modelSelection.options,
|
||||
mapError: ({ cause }) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
method: "session/set_config_option",
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const requestedModeId = resolveRequestedModeId({
|
||||
@@ -338,11 +304,6 @@ export function makeCursorAdapter(
|
||||
options?: CursorAdapterLiveOptions,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const providerKind = options?.provider ?? PROVIDER;
|
||||
const readyReason = options?.readyReason ?? "Cursor ACP session ready";
|
||||
const normalizeModel = options?.normalizeModel ?? resolveCursorAcpBaseModelId;
|
||||
const applyCursorModelOptions = options?.applyCursorModelOptions ?? true;
|
||||
const cursorExtensions = options?.cursorExtensions ?? true;
|
||||
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
@@ -404,7 +365,7 @@ export function makeCursorAdapter(
|
||||
event: {
|
||||
id: crypto.randomUUID(),
|
||||
kind: "notification",
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
createdAt: observedAt,
|
||||
method,
|
||||
threadId,
|
||||
@@ -437,7 +398,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
payload,
|
||||
@@ -454,7 +415,7 @@ export function makeCursorAdapter(
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || ctx.stopped) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({ provider: providerKind, threadId }),
|
||||
new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(ctx);
|
||||
@@ -474,7 +435,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.exited",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
payload: { exitKind: "graceful" },
|
||||
});
|
||||
@@ -484,16 +445,16 @@ export function makeCursorAdapter(
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== providerKind) {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${providerKind}' but received '${input.provider}'.`,
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (!input.cwd?.trim()) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: "cwd is required and must be non-empty.",
|
||||
});
|
||||
@@ -519,7 +480,7 @@ export function makeCursorAdapter(
|
||||
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
|
||||
const acpNativeLoggers = makeAcpNativeLoggers({
|
||||
nativeEventLogger,
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
|
||||
@@ -535,58 +496,20 @@ export function makeCursorAdapter(
|
||||
? yield* options.resolveSettings
|
||||
: cursorSettings;
|
||||
|
||||
const spawn = options?.spawn
|
||||
? options.spawn({
|
||||
settings: effectiveCursorSettings,
|
||||
cwd,
|
||||
...(options.environment ? { environment: options.environment } : {}),
|
||||
})
|
||||
: undefined;
|
||||
const acp = yield* (
|
||||
cursorExtensions
|
||||
? makeCursorAcpRuntime({
|
||||
cursorSettings: effectiveCursorSettings,
|
||||
...(options?.environment ? { environment: options.environment } : {}),
|
||||
...(spawn ? { spawn } : {}),
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...acpNativeLoggers,
|
||||
})
|
||||
: makeGenericAcpRuntime({
|
||||
spawn:
|
||||
spawn ??
|
||||
(() => {
|
||||
const fallback = options?.spawn?.({
|
||||
settings: effectiveCursorSettings,
|
||||
cwd,
|
||||
...(options.environment ? { environment: options.environment } : {}),
|
||||
});
|
||||
if (fallback) return fallback;
|
||||
return {
|
||||
command: effectiveCursorSettings.binaryPath,
|
||||
args: [],
|
||||
cwd,
|
||||
...(options?.environment ? { env: options.environment } : {}),
|
||||
};
|
||||
})(),
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...(options?.authMethodId ? { authMethodId: options.authMethodId } : {}),
|
||||
...(options?.clientCapabilities
|
||||
? { clientCapabilities: options.clientCapabilities }
|
||||
: {}),
|
||||
...acpNativeLoggers,
|
||||
})
|
||||
).pipe(
|
||||
const acp = yield* makeCursorAcpRuntime({
|
||||
cursorSettings: effectiveCursorSettings,
|
||||
...(options?.environment ? { environment: options.environment } : {}),
|
||||
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: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
@@ -594,97 +517,92 @@ export function makeCursorAdapter(
|
||||
),
|
||||
);
|
||||
const started = yield* Effect.gen(function* () {
|
||||
if (cursorExtensions) {
|
||||
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: providerKind,
|
||||
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: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolved },
|
||||
});
|
||||
return { answers: resolved };
|
||||
}),
|
||||
);
|
||||
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
|
||||
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 };
|
||||
}),
|
||||
);
|
||||
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/create_plan",
|
||||
"cursor/update_todos",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.proposed.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
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",
|
||||
if (ctx) {
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
extractTodosAsPlan(params),
|
||||
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(
|
||||
@@ -715,7 +633,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
@@ -732,7 +650,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
@@ -754,7 +672,7 @@ export function makeCursorAdapter(
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(providerKind, input.threadId, "session/start", error),
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -763,15 +681,13 @@ export function makeCursorAdapter(
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: undefined,
|
||||
modelSelection: cursorModelSelection,
|
||||
normalizeModel,
|
||||
applyCursorModelOptions,
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(providerKind, input.threadId, method, cause),
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
|
||||
const now = yield* nowIso;
|
||||
const session: ProviderSession = {
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
providerInstanceId: boundInstanceId,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
@@ -810,7 +726,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
@@ -822,7 +738,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
@@ -855,7 +771,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
@@ -873,7 +789,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
@@ -894,21 +810,21 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { resume: started.initializeResult },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { state: "ready", reason: readyReason },
|
||||
payload: { state: "ready", reason: "Cursor ACP session ready" },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { providerThreadId: started.sessionId },
|
||||
});
|
||||
@@ -924,7 +840,7 @@ export function makeCursorAdapter(
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = normalizeModel(model);
|
||||
const resolvedModel = resolveCursorAcpBaseModelId(model);
|
||||
yield* applyRequestedSessionConfiguration({
|
||||
runtime: ctx.acp,
|
||||
runtimeMode: ctx.session.runtimeMode,
|
||||
@@ -936,10 +852,8 @@ export function makeCursorAdapter(
|
||||
model,
|
||||
options: turnModelSelection?.options,
|
||||
},
|
||||
normalizeModel,
|
||||
applyCursorModelOptions,
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(providerKind, input.threadId, method, cause),
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
@@ -952,7 +866,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: { model: resolvedModel },
|
||||
@@ -970,7 +884,7 @@ export function makeCursorAdapter(
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
@@ -979,7 +893,7 @@ export function makeCursorAdapter(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
@@ -996,7 +910,7 @@ export function makeCursorAdapter(
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
@@ -1008,7 +922,7 @@ export function makeCursorAdapter(
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(providerKind, input.threadId, "session/prompt", error),
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1023,7 +937,7 @@ export function makeCursorAdapter(
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
@@ -1047,7 +961,7 @@ export function makeCursorAdapter(
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(providerKind, threadId, "session/cancel", error),
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1063,7 +977,7 @@ export function makeCursorAdapter(
|
||||
const pending = ctx.pendingApprovals.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
method: "session/request_permission",
|
||||
detail: `Unknown pending approval request: ${requestId}`,
|
||||
});
|
||||
@@ -1081,7 +995,7 @@ export function makeCursorAdapter(
|
||||
const pending = ctx.pendingUserInputs.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
method: "cursor/ask_question",
|
||||
detail: `Unknown pending user-input request: ${requestId}`,
|
||||
});
|
||||
@@ -1100,7 +1014,7 @@ export function makeCursorAdapter(
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
});
|
||||
@@ -1141,7 +1055,7 @@ export function makeCursorAdapter(
|
||||
const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
|
||||
|
||||
return {
|
||||
provider: providerKind,
|
||||
provider: PROVIDER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession,
|
||||
sendTurn,
|
||||
|
||||
@@ -1,38 +1,743 @@
|
||||
import * as nodePath from "node:path";
|
||||
|
||||
import {
|
||||
type CursorSettings,
|
||||
ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
type ProviderUserInputAnswers,
|
||||
RuntimeRequestId,
|
||||
type ThreadId,
|
||||
TurnId,
|
||||
EventId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DateTime,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
FileSystem,
|
||||
PubSub,
|
||||
Random,
|
||||
Scope,
|
||||
Semaphore,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { makeCursorAdapter, type CursorAdapterLiveOptions } from "./CursorAdapter.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
import { acpPermissionOutcome, mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
|
||||
import { type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
|
||||
import {
|
||||
makeAcpAssistantItemEvent,
|
||||
makeAcpContentDeltaEvent,
|
||||
makeAcpPlanUpdatedEvent,
|
||||
makeAcpRequestOpenedEvent,
|
||||
makeAcpRequestResolvedEvent,
|
||||
makeAcpToolCallEvent,
|
||||
} from "../acp/AcpCoreRuntimeEvents.ts";
|
||||
import { makeAcpNativeLoggers } from "../acp/AcpNativeLogging.ts";
|
||||
import { parsePermissionRequest } from "../acp/AcpRuntimeModel.ts";
|
||||
import { makeGenericAcpRuntime } from "../acp/GenericAcpSupport.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import { type ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
|
||||
type GenericAcpAdapterSettings = Pick<CursorSettings, "enabled" | "binaryPath" | "customModels">;
|
||||
const GENERIC_ACP_RESUME_VERSION = 1 as const;
|
||||
|
||||
type GenericAcpAdapterOptions = Omit<
|
||||
CursorAdapterLiveOptions,
|
||||
"applyCursorModelOptions" | "authMethodId" | "clientCapabilities" | "cursorExtensions"
|
||||
> & {
|
||||
export interface GenericAcpAdapterSettings {
|
||||
readonly enabled: boolean;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface GenericAcpAdapterOptions {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly instanceId: typeof ProviderInstanceId.Type;
|
||||
readonly authMethodId?: string | undefined;
|
||||
readonly instanceId: ProviderSession["providerInstanceId"];
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
readonly readyReason?: string;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
};
|
||||
readonly authMethodId?: string | undefined;
|
||||
readonly normalizeModel?: (model: string | null | undefined) => string;
|
||||
}
|
||||
|
||||
interface PendingApproval {
|
||||
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
|
||||
}
|
||||
|
||||
interface PendingUserInput {
|
||||
readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
|
||||
}
|
||||
|
||||
interface GenericAcpSessionContext {
|
||||
readonly threadId: ThreadId;
|
||||
session: ProviderSession;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly acp: AcpSessionRuntimeShape;
|
||||
notificationFiber: Fiber.Fiber<void, never> | undefined;
|
||||
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
|
||||
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
|
||||
readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
activeTurnId: TurnId | undefined;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parseGenericResume(raw: unknown): { sessionId: string } | undefined {
|
||||
if (!isRecord(raw)) return undefined;
|
||||
if (raw.schemaVersion !== GENERIC_ACP_RESUME_VERSION) return undefined;
|
||||
if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
|
||||
return { sessionId: raw.sessionId.trim() };
|
||||
}
|
||||
|
||||
function settlePendingApprovalsAsCancelled(
|
||||
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.forEach(
|
||||
pendingApprovals.values(),
|
||||
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
|
||||
function settlePendingUserInputsAsEmptyAnswers(
|
||||
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
|
||||
): Effect.Effect<void> {
|
||||
return Effect.forEach(
|
||||
pendingUserInputs.values(),
|
||||
(pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
|
||||
export function makeGenericAcpAdapter(
|
||||
settings: GenericAcpAdapterSettings,
|
||||
options: GenericAcpAdapterOptions,
|
||||
) {
|
||||
return makeCursorAdapter(
|
||||
{
|
||||
...settings,
|
||||
apiEndpoint: "",
|
||||
},
|
||||
{
|
||||
...options,
|
||||
applyCursorModelOptions: false,
|
||||
cursorExtensions: false,
|
||||
normalizeModel: options.normalizeModel ?? ((model) => model?.trim() || "default"),
|
||||
},
|
||||
);
|
||||
return Effect.gen(function* () {
|
||||
const providerKind = options.provider;
|
||||
const readyReason = options.readyReason ?? "ACP session ready";
|
||||
const normalizeModel = options.normalizeModel ?? ((model) => model?.trim() || "default");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const nativeEventLogger =
|
||||
options.nativeEventLogger ??
|
||||
(options.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
|
||||
const sessions = new Map<ThreadId, GenericAcpSessionContext>();
|
||||
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 nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
|
||||
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
|
||||
|
||||
const getThreadSemaphore = (threadId: string) =>
|
||||
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
|
||||
const existing = current.get(threadId);
|
||||
if (existing) return Effect.succeed([existing, current] as const);
|
||||
return Semaphore.make(1).pipe(
|
||||
Effect.map((semaphore) => {
|
||||
const next = new Map(current);
|
||||
next.set(threadId, semaphore);
|
||||
return [semaphore, next] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
|
||||
|
||||
const requireSession = (
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<GenericAcpSessionContext, ProviderAdapterSessionNotFoundError> => {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || ctx.stopped) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({ provider: providerKind, threadId }),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(ctx);
|
||||
};
|
||||
|
||||
const stopSessionInternal = (ctx: GenericAcpSessionContext) =>
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) return;
|
||||
ctx.stopped = true;
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
|
||||
if (ctx.notificationFiber) {
|
||||
yield* Fiber.interrupt(ctx.notificationFiber);
|
||||
}
|
||||
yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
|
||||
sessions.delete(ctx.threadId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.exited",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
payload: { exitKind: "graceful" },
|
||||
});
|
||||
});
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== providerKind) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${providerKind}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (!input.cwd?.trim()) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "startSession",
|
||||
issue: "cwd is required and must be non-empty.",
|
||||
});
|
||||
}
|
||||
|
||||
const command = settings.command.trim();
|
||||
if (!settings.enabled || command.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "startSession",
|
||||
issue: "ACP command is not configured.",
|
||||
});
|
||||
}
|
||||
|
||||
const cwd = nodePath.resolve(input.cwd.trim());
|
||||
const existing = sessions.get(input.threadId);
|
||||
if (existing && !existing.stopped) {
|
||||
yield* stopSessionInternal(existing);
|
||||
}
|
||||
|
||||
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),
|
||||
);
|
||||
let ctx!: GenericAcpSessionContext;
|
||||
|
||||
const acpNativeLoggers = makeAcpNativeLoggers({
|
||||
nativeEventLogger,
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
const resumeSessionId = parseGenericResume(input.resumeCursor)?.sessionId;
|
||||
const acp = yield* makeGenericAcpRuntime({
|
||||
spawn: {
|
||||
command,
|
||||
args: settings.args,
|
||||
cwd,
|
||||
...(options.environment ? { env: options.environment } : {}),
|
||||
},
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...(options.authMethodId ? { authMethodId: options.authMethodId } : {}),
|
||||
...(options.clientCapabilities
|
||||
? { clientCapabilities: options.clientCapabilities }
|
||||
: {}),
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const started = yield* Effect.gen(function* () {
|
||||
yield* acp.handleRequestPermission((params) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId =
|
||||
params.options.find((option) => option.kind === "allow_always")?.optionId ??
|
||||
params.options.find((option) => option.kind === "allow_once")?.optionId;
|
||||
if (typeof autoApprovedOptionId === "string" && autoApprovedOptionId.trim()) {
|
||||
return {
|
||||
outcome: {
|
||||
outcome: "selected" as const,
|
||||
optionId: autoApprovedOptionId.trim(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
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 });
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
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: providerKind,
|
||||
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(providerKind, input.threadId, "session/start", error),
|
||||
),
|
||||
);
|
||||
|
||||
const initialModelSelection =
|
||||
input.modelSelection?.instanceId === options.instanceId
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
if (initialModelSelection?.model) {
|
||||
const model = normalizeModel(initialModelSelection.model);
|
||||
if (model !== "default") {
|
||||
yield* acp
|
||||
.setModel(model)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(
|
||||
providerKind,
|
||||
input.threadId,
|
||||
"session/set_config_option",
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const now = yield* nowIso;
|
||||
const session: ProviderSession = {
|
||||
provider: providerKind,
|
||||
providerInstanceId: options.instanceId,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
cwd,
|
||||
model: initialModelSelection?.model,
|
||||
threadId: input.threadId,
|
||||
resumeCursor: {
|
||||
schemaVersion: GENERIC_ACP_RESUME_VERSION,
|
||||
sessionId: started.sessionId,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
ctx = {
|
||||
threadId: input.threadId,
|
||||
session,
|
||||
scope: sessionScope,
|
||||
acp,
|
||||
notificationFiber: undefined,
|
||||
pendingApprovals,
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
activeTurnId: undefined,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
const notificationFiber = 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: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
payload: event.payload,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: providerKind,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
ctx.notificationFiber = notificationFiber;
|
||||
sessions.set(input.threadId, ctx);
|
||||
sessionScopeTransferred = true;
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { resume: started.initializeResult },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { state: "ready", reason: readyReason },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
payload: { providerThreadId: started.sessionId },
|
||||
});
|
||||
|
||||
return session;
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
const turnId = TurnId.make(crypto.randomUUID());
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === options.instanceId
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = normalizeModel(model);
|
||||
if (model !== undefined && resolvedModel !== "default") {
|
||||
yield* ctx.acp
|
||||
.setModel(resolvedModel)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(
|
||||
providerKind,
|
||||
input.threadId,
|
||||
"session/set_config_option",
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: { model: resolvedModel },
|
||||
});
|
||||
|
||||
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
|
||||
if (input.input?.trim()) {
|
||||
promptParts.push({ type: "text", text: input.input.trim() });
|
||||
}
|
||||
if (input.attachments && input.attachments.length > 0) {
|
||||
for (const attachment of input.attachments) {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
promptParts.push({
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
|
||||
const result = yield* ctx.acp
|
||||
.prompt({ prompt: promptParts })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(providerKind, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
|
||||
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
model: resolvedModel,
|
||||
};
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: providerKind,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (threadId) =>
|
||||
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) =>
|
||||
mapAcpToAdapterError(providerKind, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
const pending = ctx.pendingApprovals.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
method: "session/request_permission",
|
||||
detail: `Unknown pending approval request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.decision, decision);
|
||||
});
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
answers,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
const pending = ctx.pendingUserInputs.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: providerKind,
|
||||
method: "elicitation/create",
|
||||
detail: `Unknown pending user-input request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.answers, answers);
|
||||
});
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
return { threadId, turns: ctx.turns };
|
||||
});
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
numTurns,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: providerKind,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
});
|
||||
}
|
||||
const nextLength = Math.max(0, ctx.turns.length - numTurns);
|
||||
ctx.turns.splice(nextLength);
|
||||
return { threadId, turns: ctx.turns };
|
||||
});
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
withThreadLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* stopSessionInternal(ctx);
|
||||
}),
|
||||
);
|
||||
|
||||
const listSessions = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (ctx) => ({ ...ctx.session })));
|
||||
const hasSession = (threadId: ThreadId) =>
|
||||
Effect.sync(() => {
|
||||
const ctx = sessions.get(threadId);
|
||||
return ctx !== undefined && !ctx.stopped;
|
||||
});
|
||||
const stopAll = () => Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
|
||||
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
|
||||
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
provider: providerKind,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
} satisfies ProviderAdapterShape<ProviderAdapterError>;
|
||||
});
|
||||
}
|
||||
@@ -382,7 +382,7 @@ const makeAcpSessionRuntime = (
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
if (options.resumeSessionId && initializeResult.agentCapabilities?.loadSession === true) {
|
||||
const loadPayload = {
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
|
||||
@@ -2,7 +2,6 @@ import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/cont
|
||||
import { Effect, Layer, Scope } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import {
|
||||
CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
@@ -25,9 +24,6 @@ export interface CursorAcpRuntimeInput extends Omit<
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly spawn?: AcpSpawnInput;
|
||||
readonly authMethodId?: string;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
}
|
||||
|
||||
export interface CursorAcpModelSelectionErrorContext {
|
||||
@@ -59,12 +55,9 @@ export const makeCursorAcpRuntime = (
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn:
|
||||
input.spawn ??
|
||||
buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment),
|
||||
authMethodId: input.authMethodId ?? "cursor_login",
|
||||
clientCapabilities:
|
||||
input.clientCapabilities ?? CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment),
|
||||
authMethodId: "cursor_login",
|
||||
clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
|
||||
Reference in new issue
Block a user