fix(cursor): serialize request settlement
This commit is contained in:
1 parent
f9f3ed7e35
commit
ec4f561392
2 files changed
+436
-178
No files matched your search
@@ -60,7 +60,10 @@ exec ${JSON.stringify(mockAgentCommand)} ${mockAgentArgs.map((arg) => JSON.strin
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
async function makeTerminalCallbackWrapper(kind: "permission" | "question") {
|
||||
async function makeTerminalCallbackWrapper(
|
||||
kind: "permission" | "question",
|
||||
promptOutcome: "success" | "failure" | "hang" = "success",
|
||||
) {
|
||||
const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-terminal-"));
|
||||
const wrapperPath = NodePath.join(dir, "fake-agent.mjs");
|
||||
const callback =
|
||||
@@ -109,6 +112,7 @@ async function makeTerminalCallbackWrapper(kind: "permission" | "question") {
|
||||
import readline from "node:readline";
|
||||
const callback = ${JSON.stringify(callback)};
|
||||
const kind = ${JSON.stringify(kind)};
|
||||
const promptOutcome = ${JSON.stringify(promptOutcome)};
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
@@ -118,10 +122,17 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
} else if (message.method === "session/new") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "terminal-callback-session" } });
|
||||
} else if (message.method === "session/prompt") {
|
||||
const response = { jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } };
|
||||
const messages = kind === "question" ? [response, callback] : [callback];
|
||||
const response =
|
||||
promptOutcome === "failure"
|
||||
? { jsonrpc: "2.0", id: message.id, error: { code: -32603, message: "prompt failed" } }
|
||||
: { jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } };
|
||||
const messages =
|
||||
promptOutcome === "hang"
|
||||
? [callback]
|
||||
: kind === "question" && promptOutcome === "success"
|
||||
? [response, callback]
|
||||
: [callback, response];
|
||||
process.stdout.write(messages.map(JSON.stringify).join("\\n") + "\\n");
|
||||
if (kind === "permission") setTimeout(() => send(response), 10);
|
||||
} else if (message.id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: {} });
|
||||
}
|
||||
@@ -1168,6 +1179,137 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a pending callback when the terminal prompt fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-terminal-failure");
|
||||
const events: Array<ProviderRuntimeEvent> = [];
|
||||
const requested = yield* Deferred.make<ApprovalRequestId>();
|
||||
const resolved = yield* Deferred.make<void>();
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeTerminalCallbackWrapper("permission", "failure"),
|
||||
);
|
||||
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) return Effect.void;
|
||||
events.push(event);
|
||||
if (event.type === "request.opened") {
|
||||
return Deferred.succeed(requested, ApprovalRequestId.make(String(event.requestId))).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
if (event.type === "request.resolved") {
|
||||
return Deferred.succeed(resolved, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "fail with a pending permission",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const requestId = yield* Deferred.await(requested);
|
||||
const sendTurnExit = yield* Fiber.await(sendTurnFiber);
|
||||
yield* Deferred.await(resolved);
|
||||
const lateResponseExit = yield* adapter
|
||||
.respondToRequest(threadId, requestId, "accept")
|
||||
.pipe(Effect.exit);
|
||||
assert.equal(sendTurnExit._tag, "Failure");
|
||||
assert.equal(lateResponseExit._tag, "Failure");
|
||||
assert.deepStrictEqual(
|
||||
events
|
||||
.filter(
|
||||
(event) =>
|
||||
event.type === "request.opened" ||
|
||||
event.type === "request.resolved" ||
|
||||
event.type === "turn.completed",
|
||||
)
|
||||
.map((event) => event.type),
|
||||
["request.opened", "request.resolved"],
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a pending callback when sendTurn is interrupted", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-terminal-fiber-interruption");
|
||||
const events: Array<ProviderRuntimeEvent> = [];
|
||||
const requested = yield* Deferred.make<ApprovalRequestId>();
|
||||
const resolved = yield* Deferred.make<void>();
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeTerminalCallbackWrapper("permission", "hang"),
|
||||
);
|
||||
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) return Effect.void;
|
||||
events.push(event);
|
||||
if (event.type === "request.opened") {
|
||||
return Deferred.succeed(requested, ApprovalRequestId.make(String(event.requestId))).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
if (event.type === "request.resolved") {
|
||||
return Deferred.succeed(resolved, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "interrupt with a pending permission",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const requestId = yield* Deferred.await(requested);
|
||||
yield* Fiber.interrupt(sendTurnFiber);
|
||||
yield* Deferred.await(resolved);
|
||||
const lateResponseExit = yield* adapter
|
||||
.respondToRequest(threadId, requestId, "accept")
|
||||
.pipe(Effect.exit);
|
||||
assert.equal(lateResponseExit._tag, "Failure");
|
||||
assert.deepStrictEqual(
|
||||
events
|
||||
.filter(
|
||||
(event) =>
|
||||
event.type === "request.opened" ||
|
||||
event.type === "request.resolved" ||
|
||||
event.type === "turn.completed",
|
||||
)
|
||||
.map((event) => event.type),
|
||||
["request.opened", "request.resolved"],
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves a pending question before completing a normally returned turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
|
||||
@@ -124,6 +124,12 @@ interface PendingUserInput {
|
||||
readonly resolutionOffered: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
interface CallbackLifecycle {
|
||||
readonly semaphore: Semaphore.Semaphore;
|
||||
generation: number;
|
||||
admissionOpen: boolean;
|
||||
}
|
||||
|
||||
interface CursorSessionContext {
|
||||
readonly threadId: ThreadId;
|
||||
session: ProviderSession;
|
||||
@@ -139,44 +145,25 @@ interface CursorSessionContext {
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
promptsInFlight: number;
|
||||
readonly callbackLifecycle: CallbackLifecycle;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
function settlePendingApprovalsAsCancelled(
|
||||
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
|
||||
function settlePendingCallbacks(
|
||||
approvals: ReadonlyArray<PendingApproval>,
|
||||
userInputs: ReadonlyArray<PendingUserInput>,
|
||||
): Effect.Effect<void> {
|
||||
const pendingEntries = Array.from(pendingApprovals.values());
|
||||
return Effect.forEach(
|
||||
pendingEntries,
|
||||
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
|
||||
{
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function settlePendingUserInputsAsEmptyAnswers(
|
||||
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
|
||||
): Effect.Effect<void> {
|
||||
const pendingEntries = Array.from(pendingUserInputs.values());
|
||||
return Effect.forEach(
|
||||
pendingEntries,
|
||||
(pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
|
||||
{
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function settlePendingCallbacksBeforeTurnCompletion(
|
||||
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
|
||||
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
|
||||
): Effect.Effect<void> {
|
||||
const approvals = Array.from(pendingApprovals.values());
|
||||
const userInputs = Array.from(pendingUserInputs.values());
|
||||
return Effect.gen(function* () {
|
||||
yield* settlePendingApprovalsAsCancelled(pendingApprovals);
|
||||
yield* settlePendingUserInputsAsEmptyAnswers(pendingUserInputs);
|
||||
yield* Effect.forEach(
|
||||
approvals,
|
||||
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
yield* Effect.forEach(
|
||||
userInputs,
|
||||
(pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
yield* Effect.forEach(approvals, (pending) => Deferred.await(pending.resolutionOffered), {
|
||||
discard: true,
|
||||
});
|
||||
@@ -478,12 +465,21 @@ export function makeCursorAdapter(
|
||||
|
||||
const stopSessionInternal = (ctx: CursorSessionContext) =>
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) return;
|
||||
ctx.stopped = true;
|
||||
yield* settlePendingCallbacksBeforeTurnCompletion(
|
||||
ctx.pendingApprovals,
|
||||
ctx.pendingUserInputs,
|
||||
const shouldStop = yield* Effect.uninterruptible(
|
||||
ctx.callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) return false;
|
||||
ctx.stopped = true;
|
||||
ctx.callbackLifecycle.admissionOpen = false;
|
||||
yield* settlePendingCallbacks(
|
||||
Array.from(ctx.pendingApprovals.values()),
|
||||
Array.from(ctx.pendingUserInputs.values()),
|
||||
);
|
||||
return true;
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!shouldStop) return;
|
||||
if (ctx.notificationFiber) {
|
||||
yield* Fiber.interrupt(ctx.notificationFiber);
|
||||
}
|
||||
@@ -527,6 +523,11 @@ export function makeCursorAdapter(
|
||||
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const callbackLifecycle: CallbackLifecycle = {
|
||||
semaphore: yield* Semaphore.make(1),
|
||||
generation: 0,
|
||||
admissionOpen: false,
|
||||
};
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
@@ -593,49 +594,77 @@ export function makeCursorAdapter(
|
||||
),
|
||||
);
|
||||
const started = yield* Effect.gen(function* () {
|
||||
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
|
||||
mapExtensionFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/ask_question",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
|
||||
const resolutionOffered = yield* Deferred.make<void>();
|
||||
pendingUserInputs.set(requestId, { answers, resolutionOffered });
|
||||
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);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolved },
|
||||
});
|
||||
yield* Deferred.succeed(resolutionOffered, undefined).pipe(Effect.ignore);
|
||||
pendingUserInputs.delete(requestId);
|
||||
return { answers: resolved };
|
||||
}),
|
||||
),
|
||||
yield* acp.handleExtRequest(
|
||||
"cursor/ask_question",
|
||||
CursorAskQuestionRequest,
|
||||
(params) => {
|
||||
const callbackGeneration = callbackLifecycle.generation;
|
||||
return mapExtensionFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/ask_question",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
|
||||
const resolutionOffered = yield* Deferred.make<void>();
|
||||
const pending: PendingUserInput = { answers, resolutionOffered };
|
||||
return yield* Effect.gen(function* () {
|
||||
const admitted = yield* callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (
|
||||
!callbackLifecycle.admissionOpen ||
|
||||
callbackLifecycle.generation !== callbackGeneration ||
|
||||
ctx?.stopped
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
pendingUserInputs.set(requestId, pending);
|
||||
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,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
if (!admitted) {
|
||||
return { answers: {} };
|
||||
}
|
||||
const resolved = yield* Deferred.await(answers);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolved },
|
||||
});
|
||||
return { answers: resolved };
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => pendingUserInputs.delete(requestId)).pipe(
|
||||
Effect.andThen(Deferred.succeed(resolutionOffered, undefined)),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
|
||||
mapExtensionFailure(
|
||||
@@ -687,8 +716,9 @@ export function makeCursorAdapter(
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* acp.handleRequestPermission((params) =>
|
||||
mapExtensionFailure(
|
||||
yield* acp.handleRequestPermission((params) => {
|
||||
const callbackGeneration = callbackLifecycle.generation;
|
||||
return mapExtensionFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
@@ -699,6 +729,17 @@ export function makeCursorAdapter(
|
||||
if (input.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
|
||||
if (autoApprovedOptionId !== undefined) {
|
||||
const admitted = yield* callbackLifecycle.semaphore.withPermit(
|
||||
Effect.sync(
|
||||
() =>
|
||||
callbackLifecycle.admissionOpen &&
|
||||
callbackLifecycle.generation === callbackGeneration &&
|
||||
!ctx?.stopped,
|
||||
),
|
||||
);
|
||||
if (!admitted) {
|
||||
return { outcome: { outcome: "cancelled" as const } };
|
||||
}
|
||||
return {
|
||||
outcome: {
|
||||
outcome: "selected" as const,
|
||||
@@ -712,55 +753,78 @@ export function makeCursorAdapter(
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
const resolutionOffered = yield* Deferred.make<void>();
|
||||
pendingApprovals.set(requestId, {
|
||||
const pending: PendingApproval = {
|
||||
decision,
|
||||
resolutionOffered,
|
||||
kind: permissionRequest.kind,
|
||||
});
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
permissionRequest.detail ??
|
||||
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
|
||||
"[unserializable params]",
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: params,
|
||||
}),
|
||||
);
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
}),
|
||||
);
|
||||
yield* Deferred.succeed(resolutionOffered, undefined).pipe(Effect.ignore);
|
||||
pendingApprovals.delete(requestId);
|
||||
return {
|
||||
outcome:
|
||||
resolved === "cancel"
|
||||
? ({ outcome: "cancelled" } as const)
|
||||
: {
|
||||
outcome: "selected" as const,
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
},
|
||||
};
|
||||
return yield* Effect.gen(function* () {
|
||||
const admitted = yield* callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (
|
||||
!callbackLifecycle.admissionOpen ||
|
||||
callbackLifecycle.generation !== callbackGeneration ||
|
||||
ctx?.stopped
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
pendingApprovals.set(requestId, pending);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
permissionRequest.detail ??
|
||||
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
|
||||
"[unserializable params]",
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: params,
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
if (!admitted) {
|
||||
return { outcome: { outcome: "cancelled" as const } };
|
||||
}
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
outcome:
|
||||
resolved === "cancel"
|
||||
? ({ outcome: "cancelled" } as const)
|
||||
: {
|
||||
outcome: "selected" as const,
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
},
|
||||
};
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => pendingApprovals.delete(requestId)).pipe(
|
||||
Effect.andThen(Deferred.succeed(resolutionOffered, undefined)),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
@@ -806,6 +870,7 @@ export function makeCursorAdapter(
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
promptsInFlight: 0,
|
||||
callbackLifecycle,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
@@ -937,15 +1002,58 @@ export function makeCursorAdapter(
|
||||
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
// A sendTurn while a prompt is in flight is a steer: the agent folds
|
||||
// the new prompt into the ongoing work, so the active turn id is
|
||||
// reused instead of opening a new turn.
|
||||
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
|
||||
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
|
||||
// Count this prompt immediately so a superseded in-flight prompt
|
||||
// resolving from here on does not settle the turn; the matching
|
||||
// decrement is the `ensuring` below.
|
||||
ctx.promptsInFlight += 1;
|
||||
const candidateTurnId = TurnId.make(yield* randomUUIDv4);
|
||||
const admission = yield* ctx.callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) {
|
||||
return yield* new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}
|
||||
const startsTurn = ctx.promptsInFlight === 0;
|
||||
if (startsTurn) {
|
||||
ctx.callbackLifecycle.generation += 1;
|
||||
ctx.callbackLifecycle.admissionOpen = true;
|
||||
ctx.activeTurnId = candidateTurnId;
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.promptsInFlight += 1;
|
||||
return {
|
||||
generation: ctx.callbackLifecycle.generation,
|
||||
startsTurn,
|
||||
turnId: ctx.activeTurnId ?? candidateTurnId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const { generation, startsTurn, turnId } = admission;
|
||||
let promptFinalized = false;
|
||||
|
||||
const finalizePrompt = (
|
||||
onLastPrompt?: () => Effect.Effect<void, ProviderAdapterRequestError>,
|
||||
): Effect.Effect<boolean, ProviderAdapterRequestError> =>
|
||||
Effect.uninterruptible(
|
||||
ctx.callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (promptFinalized) return false;
|
||||
promptFinalized = true;
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
if (ctx.promptsInFlight !== 0 || ctx.callbackLifecycle.generation !== generation) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ctx.callbackLifecycle.admissionOpen = false;
|
||||
yield* settlePendingCallbacks(
|
||||
Array.from(ctx.pendingApprovals.values()),
|
||||
Array.from(ctx.pendingUserInputs.values()),
|
||||
);
|
||||
if (!ctx.stopped && onLastPrompt) {
|
||||
yield* onLastPrompt();
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
@@ -966,17 +1074,13 @@ export function makeCursorAdapter(
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
ctx.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
if (steeringTurnId === undefined) {
|
||||
if (startsTurn) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -1054,48 +1158,46 @@ export function makeCursorAdapter(
|
||||
model: resolvedModel,
|
||||
};
|
||||
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another is
|
||||
// in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
yield* settlePendingCallbacksBeforeTurnCompletion(
|
||||
ctx.pendingApprovals,
|
||||
ctx.pendingUserInputs,
|
||||
);
|
||||
}
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* finalizePrompt(() =>
|
||||
makeEventStamp().pipe(
|
||||
Effect.flatMap((stamp) =>
|
||||
offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(finalizePrompt().pipe(Effect.ignore)));
|
||||
});
|
||||
|
||||
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
|
||||
yield* Effect.uninterruptible(
|
||||
ctx.callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
ctx.callbackLifecycle.admissionOpen = false;
|
||||
yield* settlePendingCallbacks(
|
||||
Array.from(ctx.pendingApprovals.values()),
|
||||
Array.from(ctx.pendingUserInputs.values()),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
@@ -1120,7 +1222,14 @@ export function makeCursorAdapter(
|
||||
detail: `Unknown pending approval request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.decision, decision);
|
||||
const accepted = yield* Deferred.succeed(pending.decision, decision);
|
||||
if (!accepted) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/request_permission",
|
||||
detail: `Approval request is no longer pending: ${requestId}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const respondToUserInput: CursorAdapterShape["respondToUserInput"] = (
|
||||
@@ -1138,7 +1247,14 @@ export function makeCursorAdapter(
|
||||
detail: `Unknown pending user-input request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.answers, answers);
|
||||
const accepted = yield* Deferred.succeed(pending.answers, answers);
|
||||
if (!accepted) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "cursor/ask_question",
|
||||
detail: `User-input request is no longer pending: ${requestId}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const readThread: CursorAdapterShape["readThread"] = (threadId) =>
|
||||
|
||||
Reference in new issue
Block a user