@devries-cameron20 / t3code Mirror · read-only / commits / 143ab1606d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 23:15 UTC

fix(acp): settle native foreground work independently (#21616)

Co-authored-by: Wout Stiens <71498452+StiensWout@users.noreply.github.com>

Julius Marminge committed Oct 19, 2026 at 20:57 UTC 143ab1606dc6d9fbbd91869904a4c19fe3b694e8
1 file changed +330 -72
packages/provider-acp/src/server/adapter.ts
+330 -72
@@ -327,6 +327,8 @@ export interface AcpAdapterV2Flavor {
327 readonly terminateRuntimeProcessGroupOnInterrupt?: boolean;
328 readonly preserveRuntimeOnSettledInterrupt?: boolean;
329 readonly enablePostSettleContinuation?: boolean;
330 + /** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */
331 + readonly followAgentWorkState?: boolean;
332 /**
333 * Grok CLI currently accepts and vision-processes image blocks while still
334 * reporting the capability as false; without this override, screenshot turns
@@ -1039,6 +1041,7 @@ interface ActiveAcpTurn {
1041 finalizedStatus: "completed" | "interrupted" | "failed" | "cancelled" | null;
1042 promptSettled: boolean;
1043 promptSettledStatus: "completed" | "interrupted" | "failed" | "cancelled" | null;
1044 + workAccepted: boolean;
1045 readonly promptWireSettled: Deferred.Deferred<void, never>;
1046 backgroundFinalizeGeneration: number;
1047 }
@@ -1493,6 +1496,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1496 input.runtimePolicy;
1497 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
1498 const activeTurn = yield* Ref.make<ActiveAcpTurn | null>(null);
1499 + let pendingStopCloseTurn: ActiveAcpTurn | null = null;
1500 + let followsAgentWorkState = false;
1501 + let agentWork: Extract<
1502 + EffectAcpSchema.SessionUpdate,
1503 + { sessionUpdate: "state_update" }
1504 + > | null = null;
1505 + const agentRequests = new Set<object>();
1506 + let turnAttached = yield* Deferred.make<boolean>();
1507 const activeSessionId = yield* Ref.make<string | null>(null);
1508 const contextUsageBySessionId = yield* Ref.make(
1509 new Map<string, ThreadTokenUsageSnapshot>(),
@@ -1510,6 +1521,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1521 } | null>(null);
1522 const activeSessionSetup =
1523 yield* Ref.make<AcpSessionRuntime.AcpSessionRuntimeStartResult | null>(null);
1524 + const setActiveSessionSetup = Effect.fnUntraced(function* (
1525 + setup: AcpSessionRuntime.AcpSessionRuntimeStartResult,
1526 + ) {
1527 + followsAgentWorkState =
1528 + flavor.followAgentWorkState === true &&
1529 + continuationRequests !== undefined &&
1530 + setup.initializeResult.protocolVersion === 2;
1531 + agentWork = null;
1532 + agentRequests.clear();
1533 + yield* Ref.set(activeSessionSetup, setup);
1534 + });
1535 const activeSelection = yield* Ref.make<ModelSelection | null>(null);
1536 const activeInteractionMode = yield* Ref.make<ProviderInteractionMode | null>(null);
1537 const promptInstructionStates = yield* Ref.make(new Map<string, T3AcpInstructionState>());
@@ -1879,7 +1901,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1901 const handleRuntimeTerminationAtGeneration = (runtimeGeneration: number) =>
1902 runRuntimeCallbackAtGeneration(
1903 runtimeGeneration,
1882 - Ref.set(runtimeRestartRequired, true),
1904 + Effect.gen(function* () {
1905 + yield* Ref.set(runtimeRestartRequired, true);
1906 + if (!followsAgentWorkState) return;
1907 + agentWork = { sessionUpdate: "state_update", state: "idle", stopReason: "error" };
1908 + const context = yield* Ref.get(activeTurn);
1909 + if (context !== null)
1910 + yield* finalizeTurn(
1911 + context,
1912 + "failed",
1913 + makeProviderFailure({ class: "transport_error" }),
1914 + );
1915 + }),
1916 ).pipe(Effect.asVoid);
1917 const makeRuntimeInput = (
1918 runtimeGeneration: number,
@@ -3816,6 +3849,89 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3849 return true;
3850 });
3851
3852 + const settleIdleWork = Effect.fnUntraced(function* (context: ActiveAcpTurn) {
3853 + if (
3854 + !followsAgentWorkState ||
3855 + context.finalized ||
3856 + (!context.workAccepted && !context.interrupted) ||
3857 + agentWork?.state !== "idle" ||
3858 + agentRequests.size > 0
3859 + )
3860 + return;
3861 + const work = agentWork;
3862 + // Native close sends cancelled idle before acknowledging the user's Stop.
3863 + if (work.stopReason === "cancelled" && pendingStopCloseTurn === context) {
3864 + context.interrupted = true;
3865 + }
3866 + const failure =
3867 + work.stopReason === "error"
3868 + ? (flavor.promptFailure?.(
3869 + new EffectAcpErrors.AcpRequestError({
3870 + code: work.error?.code ?? -32603,
3871 + errorMessage: work.error?.message ?? "Provider turn failed.",
3872 + ...(work.error?.data === undefined ? {} : { data: work.error.data }),
3873 + }),
3874 + ) ?? makeProviderFailure({ message: work.error?.message, class: "provider_error" }))
3875 + : undefined;
3876 + yield* finalizeTurn(
3877 + context,
3878 + failure !== undefined
3879 + ? "failed"
3880 + : work.stopReason === "cancelled"
3881 + ? "cancelled"
3882 + : "completed",
3883 + failure,
3884 + );
3885 + });
3886 +
3887 + const awaitRequestTurn = Effect.fnUntraced(function* (generation: number) {
3888 + if (!followsAgentWorkState) return true;
3889 + while (true) {
3890 + const waiting = yield* runRuntimeCallbackAtGeneration(
3891 + generation,
3892 + Effect.gen(function* () {
3893 + if (yield* Ref.get(stoppedRunQuarantine)) return false;
3894 + if ((yield* Ref.get(activeTurn)) !== null) return null;
3895 + const sessionId = yield* Ref.get(activeSessionId);
3896 + if (sessionId !== null) yield* offerContinuationRun(sessionId);
3897 + return turnAttached;
3898 + }),
3899 + );
3900 + if (Option.isNone(waiting)) return yield* Effect.never;
3901 + if (waiting.value === false) return false;
3902 + if (waiting.value === null) return true;
3903 + if (!(yield* Deferred.await(waiting.value))) return false;
3904 + }
3905 + });
3906 +
3907 + const holdingAgentRequest =
3908 + (generation: number) =>
3909 + <A, E, R>(effect: Effect.Effect<A, E, R>) =>
3910 + Effect.suspend(() =>
3911 + !followsAgentWorkState
3912 + ? effect
3913 + : Effect.acquireUseRelease(
3914 + runRuntimeCallbackAtGeneration(
3915 + generation,
3916 + Effect.sync(() => {
3917 + const token = {};
3918 + agentRequests.add(token);
3919 + return token;
3920 + }),
3921 + ),
3922 + (token) => (Option.isNone(token) ? Effect.never : effect),
3923 + (token) =>
3924 + runRuntimeCallbackAtGeneration(
3925 + generation,
3926 + Effect.gen(function* () {
3927 + if (Option.isSome(token)) agentRequests.delete(token.value);
3928 + const context = yield* Ref.get(activeTurn);
3929 + if (context !== null) yield* settleIdleWork(context);
3930 + }),
3931 + ).pipe(Effect.asVoid),
3932 + ),
3933 + );
3934 +
3935 const handleSessionUpdate = Effect.fnUntraced(function* (
3936 notification: EffectAcpSchema.SessionNotification,
3937 ) {
@@ -3878,7 +3994,42 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3994 providerThread,
3995 });
3996 }
3881 - return;
3997 + if (update.sessionUpdate !== "state_update") return;
3998 + }
3999 + if (
4000 + followsAgentWorkState &&
4001 + !(yield* Ref.get(stoppedRunQuarantine)) &&
4002 + notification.sessionId === (yield* Ref.get(activeSessionId))
4003 + ) {
4004 + if (update.sessionUpdate === "state_update") agentWork = update;
4005 + if (
4006 + update.sessionUpdate === "user_message" ||
4007 + update.sessionUpdate === "user_message_chunk"
4008 + ) {
4009 + agentWork = { sessionUpdate: "state_update", state: "running" };
4010 + if (context !== null) {
4011 + context.workAccepted = true;
4012 + if (!context.finalized) return;
4013 + }
4014 + }
4015 + if (
4016 + context !== null &&
4017 + update.sessionUpdate === "state_update" &&
4018 + update.state === "idle"
4019 + ) {
4020 + yield* settleIdleWork(context);
4021 + } else if (
4022 + context === null &&
4023 + !(yield* Ref.get(stoppedRunQuarantine)) &&
4024 + (acpRootSessionUpdateIngestsOutput(notification) ||
4025 + update.sessionUpdate === "user_message" ||
4026 + update.sessionUpdate === "user_message_chunk" ||
4027 + (update.sessionUpdate === "state_update" && update.state === "running"))
4028 + ) {
4029 + yield* Ref.update(wakeBuffer, (current) => [...current, notification]);
4030 + yield* offerContinuationRun(notification.sessionId);
4031 + return;
4032 + }
4033 }
4034 if (
4035 context?.finalized === true &&
@@ -4664,62 +4815,73 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
4815 } as const;
4816 });
4817
4667 - const requestUserInputWithAdmission = (
4668 - generation: number,
4669 - request: Effect.Effect<AcpAdapterV2UserInputRequest>,
4670 - transportRequestId: string,
4671 - ) =>
4672 - runRuntimeCallbackAtGeneration(
4673 - generation,
4674 - request.pipe(
4675 - Effect.flatMap((value) =>
4676 - beginUserInputRequest(value, generation, transportRequestId),
4818 + const requestUserInputWithAdmission = Effect.fn(
4819 + "AcpAdapterV2.requestUserInputWithAdmission",
4820 + )(
4821 + function* (
4822 + generation: number,
4823 + request: Effect.Effect<AcpAdapterV2UserInputRequest>,
4824 + transportRequestId: string,
4825 + ) {
4826 + if (!(yield* awaitRequestTurn(generation))) {
4827 + return { answers: null, acknowledgeNativeResponse: Effect.void };
4828 + }
4829 + return yield* runRuntimeCallbackAtGeneration(
4830 + generation,
4831 + request.pipe(
4832 + Effect.flatMap((value) =>
4833 + beginUserInputRequest(value, generation, transportRequestId),
4834 + ),
4835 ),
4678 - ),
4679 - ).pipe(
4680 - Effect.flatMap((pending) => {
4681 - if (Option.isNone(pending)) return Effect.never;
4682 - const { answers, requestId, transportRequestId } = pending.value;
4683 - return Deferred.await(answers).pipe(
4684 - Effect.flatMap((result) =>
4685 - runRuntimeCallbackAtGeneration(generation, Effect.succeed(result)).pipe(
4686 - Effect.flatMap((checked) =>
4687 - Option.isSome(checked)
4688 - ? Effect.succeed({
4689 - acknowledgeNativeResponse: acknowledgeNativeResponse(
4690 - generation,
4691 - transportRequestId,
4692 - ),
4693 - answers: checked.value,
4694 - })
4695 - : Effect.never,
4836 + ).pipe(
4837 + Effect.flatMap((pending) => {
4838 + if (Option.isNone(pending)) return Effect.never;
4839 + const { answers, requestId, transportRequestId } = pending.value;
4840 + return Deferred.await(answers).pipe(
4841 + Effect.flatMap((result) =>
4842 + runRuntimeCallbackAtGeneration(generation, Effect.succeed(result)).pipe(
4843 + Effect.flatMap((checked) =>
4844 + Option.isSome(checked)
4845 + ? Effect.succeed({
4846 + acknowledgeNativeResponse: acknowledgeNativeResponse(
4847 + generation,
4848 + transportRequestId,
4849 + ),
4850 + answers: checked.value,
4851 + })
4852 + : Effect.never,
4853 + ),
4854 ),
4855 ),
4698 - ),
4699 - Effect.ensuring(
4700 - runRuntimeCallbackAtGeneration(
4701 - generation,
4702 - Effect.gen(function* () {
4703 - yield* Ref.update(pendingRuntimeRequests, (current) => {
4704 - const updated = new Map(current);
4705 - updated.delete(String(requestId));
4706 - return updated;
4707 - });
4708 - }),
4709 - ).pipe(Effect.asVoid),
4710 - ),
4711 - );
4712 - }),
4713 - Effect.mapError(
4714 - (cause) =>
4715 - new EffectAcpErrors.AcpTransportError({
4716 - detail: "Failed to handle ACP user input request",
4717 - cause,
4718 - }),
4719 - ),
4720 - );
4856 + Effect.ensuring(
4857 + runRuntimeCallbackAtGeneration(
4858 + generation,
4859 + Effect.gen(function* () {
4860 + yield* Ref.update(pendingRuntimeRequests, (current) => {
4861 + const updated = new Map(current);
4862 + updated.delete(String(requestId));
4863 + return updated;
4864 + });
4865 + }),
4866 + ).pipe(Effect.asVoid),
4867 + ),
4868 + );
4869 + }),
4870 + );
4871 + },
4872 + Effect.mapError(
4873 + (cause) =>
4874 + new EffectAcpErrors.AcpTransportError({
4875 + detail: "Failed to handle ACP user input request",
4876 + cause,
4877 + }),
4878 + ),
4879 + );
4880
4881 const cancelPendingRuntimeRequests = Effect.fnUntraced(function* () {
4882 + const waiting = turnAttached;
4883 + turnAttached = yield* Deferred.make<boolean>();
4884 + yield* Deferred.succeed(waiting, false);
4885 const requests = yield* Ref.modify(pendingRuntimeRequests, (current) => [
4886 [...current.values()],
4887 new Map<string, PendingRuntimeRequest>(),
@@ -5310,13 +5472,20 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5472 yield* userInput.acknowledgeNativeResponse;
5473 return response ?? ({ outcome: { outcome: "cancelled" } } as const);
5474 }
5475 + const dispositionFor = (policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy) =>
5476 + (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, params);
5477 + if (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") {
5478 + if (!(yield* awaitRequestTurn(handlerGeneration)))
5479 + return { outcome: { outcome: "cancelled" } } as const;
5480 + }
5481 const admitted = yield* runRuntimeCallbackAtGeneration(
5482 handlerGeneration,
5483 Effect.gen(function* () {
5316 - const context = yield* activeContext;
5317 - const disposition = (flavor.permissionDisposition ?? acpPermissionDisposition)(
5318 - context.input.runtimePolicy,
5319 - params,
5484 + const context = followsAgentWorkState
5485 + ? yield* Ref.get(activeTurn)
5486 + : yield* activeContext;
5487 + const disposition = dispositionFor(
5488 + context?.input.runtimePolicy ?? latestRuntimePolicy,
5489 );
5490 if (disposition === "allow") {
5491 const optionId = selectAutoApprovedPermissionOption(params);
@@ -5341,7 +5510,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5510 return {
5511 _tag: "Pending" as const,
5512 pending: yield* beginApprovalRequest(
5344 - context,
5513 + yield* activeContext,
5514 params,
5515 handlerGeneration,
5516 transportRequestId,
@@ -5426,6 +5595,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5595 cause,
5596 }),
5597 ),
5598 + holdingAgentRequest(handlerGeneration),
5599 ),
5600 );
5601 yield* targetRuntime.handleElicitation((params, requestContext) =>
@@ -5561,7 +5731,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5731 } as const);
5732 yield* userInput.acknowledgeNativeResponse;
5733 return response;
5564 - }),
5734 + }).pipe(holdingAgentRequest(handlerGeneration)),
5735 );
5736 if (flavor.registerExtensions !== undefined) {
5737 yield* flavor.registerExtensions({
@@ -5857,7 +6027,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6027 return yield* startAcpRuntime(input.threadId);
6028 });
6029 yield* Ref.set(activeSessionId, started.sessionId);
5860 - yield* Ref.set(activeSessionSetup, started);
6030 + yield* setActiveSessionSetup(started);
6031 rememberTerminalEnvironment(started.sessionId, yield* readMcpContext(input.threadId));
6032 const capabilities = negotiatedCapabilities(flavor.capabilities, started);
6033 const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true;
@@ -6513,7 +6683,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6683 if (needsSessionActivation) {
6684 const activated = yield* activateSession(requestedSessionId, turnInput.threadId);
6685 yield* Ref.set(activeSessionId, activated.sessionId);
6516 - yield* Ref.set(activeSessionSetup, activated);
6686 + yield* setActiveSessionSetup(activated);
6687 yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy);
6688 yield* Ref.set(activeSelection, turnInput.modelSelection);
6689 yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode);
@@ -6550,7 +6720,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6720 // Continuation turns attach to wake traffic the agent already produced
6721 // after the prior root turn settled; do not re-prompt the ACP session.
6722 const isContinuationTurn =
6553 - postSettleContinuationEnabled && acpIsProviderContinuationMessage(turnInput.message);
6723 + (postSettleContinuationEnabled || followsAgentWorkState) &&
6724 + acpIsProviderContinuationMessage(turnInput.message);
6725 const isAppOwnedWakeTurn = acpIsAppOwnedWakeTurn(turnInput.message);
6726 if (!isAppOwnedWakeTurn) {
6727 yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set());
@@ -6629,6 +6800,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6800 finalizedStatus: null,
6801 promptSettled: false,
6802 promptSettledStatus: null,
6803 + workAccepted: false,
6804 promptWireSettled,
6805 backgroundFinalizeGeneration: 0,
6806 };
@@ -6696,6 +6868,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6868 createdAt: startedAt,
6869 updatedAt: startedAt,
6870 });
6871 + const attached = turnAttached;
6872 + turnAttached = yield* Deferred.make<boolean>();
6873 + yield* Deferred.succeed(attached, true);
6874 // Every attach ends the deferred-terminal contract, but only the
6875 // queued provider continuation owns wake traffic. A user turn may
6876 // start before that continuation and must leave its buffer intact.
@@ -6708,13 +6883,28 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6883 reports: new Map([...reports].filter(([key]) => !offered.has(key))),
6884 offered: noWakeReports.offered,
6885 }));
6711 - const drainedWakeCount = yield* Ref.modify(wakeBuffer, (current) => {
6886 + const takeWakeBuffer = Ref.modify(wakeBuffer, (current) => {
6887 const next: Array<EffectAcpSchema.SessionNotification> = [];
6888 return [
6889 current.filter((notification) => notification.sessionId === requestedSessionId),
6890 next,
6891 ] as const;
6717 - }).pipe(
6892 + });
6893 + if (followsAgentWorkState) {
6894 + yield* runtimeCallbackPermit.withPermit(
6895 + Effect.gen(function* () {
6896 + const liveWork = agentWork;
6897 + yield* Effect.forEach(yield* takeWakeBuffer, handleSessionUpdate, {
6898 + discard: true,
6899 + });
6900 + agentWork = liveWork;
6901 + context.workAccepted = true;
6902 + yield* settleIdleWork(context);
6903 + }),
6904 + );
6905 + return;
6906 + }
6907 + const drainedWakeCount = yield* takeWakeBuffer.pipe(
6908 Effect.tap((drained) =>
6909 Effect.forEach(drained, handleSessionUpdate, {
6910 concurrency: 1,
@@ -6766,7 +6956,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6956 runRuntimeCallbackAtGeneration(
6957 promptGeneration,
6958 Effect.gen(function* () {
6769 - if (context.finalized) return;
6959 + if (context.finalized || followsAgentWorkState) return;
6960 const status =
6961 result.stopReason === "cancelled"
6962 ? context.interrupted
@@ -6795,9 +6985,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6985 promptGeneration,
6986 Effect.gen(function* () {
6987 if (context.finalized) return;
6988 + const error = Cause.findError(cause);
6989 + // Native close rejects prompts cancelled before insertion with -32800.
6990 + const interrupted =
6991 + context.interrupted ||
6992 + (pendingStopCloseTurn === context &&
6993 + Result.isSuccess(error) &&
6994 + error.success._tag === "AcpRequestError" &&
6995 + error.success.code === -32800);
6996 yield* finalizeTurn(
6997 context,
6800 - context.interrupted ? "interrupted" : "failed",
6998 + interrupted ? "interrupted" : "failed",
6999 flavor.promptFailure?.(Cause.squash(cause)) ??
7000 makeProviderFailure({
7001 cause: Cause.squash(cause),
@@ -6911,9 +7109,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7109 : flavor.getModelContextWindow?.(selection, session);
7110 },
7111 }),
6914 - ...(postSettleContinuationEnabled
7112 + ...(postSettleContinuationEnabled || followsAgentWorkState
7113 ? {
7114 hasPendingBackgroundWork: Effect.gen(function* () {
7115 + if (
7116 + followsAgentWorkState &&
7117 + (agentWork?.state === "running" ||
7118 + agentWork?.state === "requires_action" ||
7119 + agentRequests.size > 0)
7120 + )
7121 + return true;
7122 if ((yield* Ref.get(wakeBuffer)).length > 0) return true;
7123 if (yield* Ref.get(continuationRequested)) return true;
7124 if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true;
@@ -7003,7 +7208,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7208 threadInput.providerThread.appThreadId,
7209 ).pipe(Effect.tapError(() => restorePreviousItemIdentity));
7210 yield* Ref.set(activeSessionId, activated.sessionId);
7006 - yield* Ref.set(activeSessionSetup, activated);
7211 + yield* setActiveSessionSetup(activated);
7212 const nextSelection = threadInput.modelSelection ?? input.modelSelection;
7213 const nextRuntimePolicy = threadInput.runtimePolicy ?? input.runtimePolicy;
7214 yield* configureSession(activated, nextSelection, nextRuntimePolicy);
@@ -7058,6 +7263,53 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7263 return yield* Effect.gen(function* () {
7264 const transition = yield* Effect.gen(function* () {
7265 const interruptContext = yield* Ref.get(activeTurn);
7266 + if (
7267 + followsAgentWorkState &&
7268 + turnInput.requestRuntimeRestart === true &&
7269 + (interruptContext === null ||
7270 + interruptContext.providerTurnId === turnInput.providerTurnId)
7271 + ) {
7272 + // ACP cancel leaves native children alive; close confirms session-wide Stop.
7273 + pendingStopCloseTurn = interruptContext;
7274 + const closed = yield* runtime.closeSession().pipe(
7275 + Effect.timeoutOption("10 seconds"),
7276 + Effect.mapError(
7277 + (cause) =>
7278 + new ProviderAdapter.ProviderAdapterProtocolError({
7279 + driver,
7280 + detail:
7281 + "The agent refused to close its session; background work may still run",
7282 + cause,
7283 + }),
7284 + ),
7285 + );
7286 + if (Option.isNone(closed)) {
7287 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
7288 + driver,
7289 + detail:
7290 + "The agent did not confirm session close; background work may still run",
7291 + });
7292 + }
7293 + yield* runtimeCallbackPermit.withPermit(
7294 + Effect.gen(function* () {
7295 + // Callbacks can settle the turn while close is awaiting confirmation.
7296 + const context = yield* Ref.get(activeTurn);
7297 + const carryover = yield* Ref.get(carryoverSubagents);
7298 + yield* Ref.set(stoppedRunQuarantine, true);
7299 + yield* Ref.set(runtimeRestartRequired, true);
7300 + agentWork = null;
7301 + agentRequests.clear();
7302 + yield* quarantineStoppedRun();
7303 + if (context !== null) context.interrupted = true;
7304 + yield* cancelPendingRuntimeRequests();
7305 + yield* terminalizeCarryoverSubagents(carryover);
7306 + if (context !== null) {
7307 + yield* finalizeTurn(context, "interrupted");
7308 + }
7309 + }),
7310 + );
7311 + return undefined;
7312 + }
7313 const softSteerCandidate =
7314 flavor.preserveRuntimeOnSettledInterrupt === true &&
7315 turnInput.requestRuntimeRestart !== true &&
@@ -7209,7 +7461,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7461 teardownBarrier,
7462 settledSoftInterrupt,
7463 };
7212 - });
7464 + }).pipe(
7465 + Effect.ensuring(
7466 + Effect.sync(() => {
7467 + pendingStopCloseTurn = null;
7468 + }),
7469 + ),
7470 + );
7471 if (transition === undefined) return;
7472 const {
7473 context,
@@ -7407,7 +7665,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7665 yield* readMcpContext(snapshotInput.providerThread.appThreadId),
7666 );
7667 yield* Ref.set(activeSessionId, activated.sessionId);
7410 - yield* Ref.set(activeSessionSetup, activated);
7668 + yield* setActiveSessionSetup(activated);
7669 yield* Ref.set(activeSelection, null);
7670 yield* Ref.set(activeInteractionMode, null);
7671 }
@@ -7469,7 +7727,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7727 );
7728 yield* Ref.set(runtimeRestartRequired, false);
7729 yield* Ref.set(activeSessionId, candidate.sessionId);
7472 - yield* Ref.set(activeSessionSetup, candidate);
7730 + yield* setActiveSessionSetup(candidate);
7731 yield* Ref.set(activeSelection, null);
7732 yield* Ref.set(activeInteractionMode, null);
7733 yield* Ref.set(promptInstructionStates, new Map());
@@ -7569,7 +7827,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7827 yield* readMcpContext(forkInput.targetThreadId),
7828 );
7829 yield* Ref.set(activeSessionId, forked.sessionId);
7572 - yield* Ref.set(activeSessionSetup, forked);
7830 + yield* setActiveSessionSetup(forked);
7831 yield* Ref.set(activeSelection, null);
7832 yield* Ref.set(activeInteractionMode, null);
7833 itemIdentityVersion = 2;