The best way to control Claude Code, Codex and more from any computer or phone
fix(antigravity): recover threads after a lost thinking signature (#28889)
Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
shivam committed
Nov 19, 2026 at 03:17 UTC
f9a3c38c50586977a375d93de77250cddfc8f039
9 files changed
+401
-80
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+87
-8
@@ -1336,6 +1336,10 @@ describe("AcpAdapterV2", () => {
1336
);
1337
it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () =>
1338
Effect.gen(function* () {
1339
+ const checking = yield* Deferred.make<void>();
1340
+ const releaseCheck = yield* Deferred.make<void>();
1341
+ const cancelled = yield* Deferred.make<void>();
1342
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
1343
const instanceId = ProviderInstanceId.make("acp-test-prompt-outcome");
1344
const threadId = ThreadId.make("thread-acp-prompt-outcome");
1345
const quota = {
@@ -1345,6 +1349,12 @@ describe("AcpAdapterV2", () => {
1349
retryable: true,
1350
resetAt: "2030-01-01T00:00:00.000Z",
1351
} as const;
1352
+ const poisoned = {
1353
+ class: "provider_error",
1354
+ message: "Saved history is unusable.",
1355
+ code: "INVALID_THINKING_SIGNATURE",
1356
+ retryable: true,
1357
+ } as const;
1358
// The runtime ordinal of each prompt, and the session each check watched.
1359
const promptRuntimes: Array<number> = [];
1360
const promptTexts: Array<string> = [];
@@ -1358,14 +1368,27 @@ describe("AcpAdapterV2", () => {
1368
watchPromptOutcome: (sessionId) =>
1369
Effect.sync(() => {
1370
watchedSessions.push(sessionId);
1361
- const failed = watchedSessions.length === 1;
1362
- return () => Effect.succeed(failed ? quota : undefined);
1371
+ const outcome =
1372
+ watchedSessions.length === 1
1373
+ ? { failure: quota, threadDisposition: "reusable" as const }
1374
+ : watchedSessions.length >= 3
1375
+ ? { failure: poisoned, threadDisposition: "broken" as const }
1376
+ : undefined;
1377
+ const interrupted = watchedSessions.length === 4;
1378
+ return () =>
1379
+ interrupted
1380
+ ? Deferred.succeed(checking, undefined).pipe(
1381
+ Effect.andThen(Deferred.await(releaseCheck)),
1382
+ Effect.as(outcome),
1383
+ )
1384
+ : Effect.succeed(outcome);
1385
}),
1386
makeRuntime: makeMockRuntime({
1387
childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
1388
mockAgentPath: yield* bundledMockAgentPath,
1389
wrapRuntime: (runtime, runtimeOrdinal) => ({
1390
...runtime,
1391
+ cancel: Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid),
1392
prompt: (payload) =>
1393
Effect.sync(() => {
1394
promptRuntimes.push(runtimeOrdinal);
@@ -1409,19 +1432,20 @@ describe("AcpAdapterV2", () => {
1432
ordinal,
1433
}),
1434
);
1412
- const events = yield* runtime.events.pipe(
1413
- Stream.takeUntil((event) => event.type === "turn.terminal"),
1414
- Stream.runCollect,
1435
+ return Array.from(
1436
+ yield* runtime.events.pipe(
1437
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
1438
+ Stream.runCollect,
1439
+ ),
1440
);
1416
- return events.at(-1);
1441
});
1442
1419
- const failed = yield* runTurn(1);
1443
+ const failed = (yield* runTurn(1)).at(-1);
1444
if (failed?.type !== "turn.terminal" || failed.status !== "failed") {
1445
return assert.fail("expected a failed terminal");
1446
}
1447
assert.deepEqual(failed.failure, quota);
1424
- const completed = yield* runTurn(2);
1448
+ const completed = (yield* runTurn(2)).at(-1);
1449
assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed");
1450
assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime");
1451
// The fresh runtime has no record of what reached the agent, so it sends T3's notes again.
@@ -1429,6 +1453,61 @@ describe("AcpAdapterV2", () => {
1453
assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default");
1454
assert.equal(watchedSessions.length, 2);
1455
assert.equal(watchedSessions[0], watchedSessions[1]);
1456
+
1457
+ // Poisoned native history marks the thread broken; its persisted error row is never resumed.
1458
+ const poisonedEvents = yield* runTurn(3);
1459
+ const broken = poisonedEvents.at(-1);
1460
+ if (broken?.type !== "turn.terminal" || broken.status !== "failed") {
1461
+ return assert.fail("expected a failed terminal");
1462
+ }
1463
+ assert.deepEqual(broken.failure, poisoned);
1464
+ assert.equal(broken.threadDisposition, "broken");
1465
+ const brokenThread = poisonedEvents.findLast(
1466
+ (event) => event.type === "provider_thread.updated",
1467
+ );
1468
+ assert.equal(
1469
+ brokenThread?.type === "provider_thread.updated"
1470
+ ? brokenThread.providerThread.status
1471
+ : null,
1472
+ "error",
1473
+ );
1474
+ const resumed = yield* Effect.result(
1475
+ runtime.resumeThread({
1476
+ threadId,
1477
+ providerThread: { ...providerThread, status: "error" },
1478
+ modelSelection,
1479
+ runtimePolicy,
1480
+ }),
1481
+ );
1482
+ assert.equal(
1483
+ resumed._tag === "Failure" ? resumed.failure._tag : null,
1484
+ "ProviderAdapterResumeThreadError",
1485
+ );
1486
+
1487
+ const turn = yield* Effect.forkChild(runTurn(4));
1488
+ yield* Deferred.await(checking);
1489
+ const stop = yield* Effect.forkChild(
1490
+ runtime.interruptTurn({
1491
+ providerThread,
1492
+ providerTurnId: idAllocator.derive.providerTurn({
1493
+ driver: ACP_TEST_DRIVER,
1494
+ nativeTurnId: acpScopedNativeId(instanceId, `${watchedSessions[3]}:turn:4`),
1495
+ }),
1496
+ }),
1497
+ );
1498
+ yield* Deferred.await(cancelled);
1499
+ yield* Deferred.succeed(releaseCheck, undefined);
1500
+ const interruptedEvents = yield* Fiber.join(turn);
1501
+ yield* Fiber.join(stop);
1502
+ const interrupted = interruptedEvents.at(-1);
1503
+ assert.equal(
1504
+ interrupted?.type === "turn.terminal" ? interrupted.status : null,
1505
+ "interrupted",
1506
+ );
1507
+ assert.equal(
1508
+ interrupted?.type === "turn.terminal" ? interrupted.threadDisposition : null,
1509
+ "broken",
1510
+ );
1511
}).pipe(Effect.provide(layerTest)),
1512
);
1513
it.live("retains returned usage when Stop finalizes before the prompt callback", () =>
apps/server/src/orchestration-v2/Orchestrator.ts
+3
-2
@@ -2722,6 +2722,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2722
const deliveryProviderThread = canResumeAcrossInstances
2723
? {
2724
...queuedProviderThread,
2725
+ status: activeProviderThread.status,
2726
nativeThreadRef: activeProviderThread.nativeThreadRef,
2727
nativeConversationHeadRef: activeProviderThread.nativeConversationHeadRef,
2728
nativeMetadata: activeProviderThread.nativeMetadata,
@@ -2913,7 +2914,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2914
const providerThread: OrchestrationV2ProviderThread = {
2915
...deliveryProviderThread,
2916
providerSessionId,
2916
- status: "not_loaded",
2917
+ status: deliveryProviderThread.status === "error" ? "error" : "not_loaded",
2918
firstRunOrdinal: queuedProviderThread.firstRunOrdinal ?? ordinal,
2919
lastRunOrdinal: ordinal,
2920
handoffIds: appendContextHandoffId(
@@ -8815,7 +8816,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8816
: null;
8817
const providerThread: OrchestrationV2ProviderThread = {
8818
...ensuredProviderThread,
8818
- status: "active",
8819
+ status: ensuredProviderThread.status === "error" ? "error" : "active",
8820
firstRunOrdinal: ensuredProviderThread.firstRunOrdinal ?? ordinal,
8821
lastRunOrdinal: ordinal,
8822
handoffIds: [
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+15
-3
@@ -2986,11 +2986,20 @@ effectIt.effect("does not mistake a failed state read for a superseded run", ()
2986
}),
2987
);
2988
2989
-effectIt.effect(
2990
- "signs out the existing native provider before opening the newly selected provider",
2991
- () =>
2989
+effectIt.effect.each(["not_loaded", "error"] as const)(
2990
+ "signs out the existing native provider before opening the newly selected provider with status %s",
2991
+ (providerThreadStatus) =>
2992
Effect.gen(function* () {
2993
const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });
2994
+ const initial = harness.projection();
2995
+ harness.setProjection({
2996
+ ...initial,
2997
+ providerThreads: initial.providerThreads.map((thread) =>
2998
+ thread.id === "new-provider-thread"
2999
+ ? { ...thread, status: providerThreadStatus }
3000
+ : thread,
3001
+ ),
3002
+ });
3003
3004
yield* harness.start;
3005
yield* harness.start;
@@ -3016,6 +3025,9 @@ effectIt.effect(
3025
]);
3026
expect(projection.providerTurns).toEqual([]);
3027
expect(projection.checkpoints).toEqual([]);
3028
+ expect(
3029
+ projection.providerThreads.find((thread) => thread.id === "new-provider-thread")?.status,
3030
+ ).toBe(providerThreadStatus);
3031
}),
3032
);
3033
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+19
-4
@@ -686,7 +686,12 @@ export const layer: Layer.Layer<
686
},
687
providerThreadUpdate: {
688
...providerThread,
689
- status: providerThread.nativeThreadRef === null ? "not_loaded" : "idle",
689
+ status:
690
+ providerThread.status === "error"
691
+ ? "error"
692
+ : providerThread.nativeThreadRef === null
693
+ ? "not_loaded"
694
+ : "idle",
695
updatedAt: now,
696
},
697
});
@@ -842,6 +847,12 @@ export const layer: Layer.Layer<
847
run,
848
checkpointScope,
849
});
850
+ const brokenNativeThread = providerThread.status === "error";
851
+ // Opened without the broken native id, a session that was not live starts fresh.
852
+ const opensFreshSession =
853
+ brokenNativeThread &&
854
+ providerThread.nativeThreadRef !== null &&
855
+ !(yield* providerSessions.isLive(providerSessionId));
856
const sessionResult = yield* Effect.result(
857
providerSessions.open({
858
threadId: projection.thread.id,
@@ -851,7 +862,7 @@ export const layer: Layer.Layer<
862
...(existingSessionProjection === undefined
863
? {}
864
: { resumeFromSession: existingSessionProjection }),
854
- ...(providerThread.nativeThreadRef?.nativeId == null
865
+ ...(providerThread.nativeThreadRef?.nativeId == null || brokenNativeThread
866
? {}
867
: { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
868
...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
@@ -1158,6 +1169,7 @@ export const layer: Layer.Layer<
1169
const createdAt = yield* DateTime.now;
1170
const history = yield* projectionStore.getTurnStartHistory(input.threadId);
1171
const boundary = contextBoundaryOrdinal({ runs: projection.runs, turnItems: history });
1172
+ const from = Math.max(1, boundary);
1173
const handoff = yield* contextHandoffService.prepareProviderHandoff({
1174
threadId: projection.thread.id,
1175
targetRunId: run.id,
@@ -1166,7 +1178,7 @@ export const layer: Layer.Layer<
1178
toProviderThreadId: providerThread.id,
1179
fromProviderInstanceId: providerThread.providerInstanceId,
1180
toProviderInstanceId: run.providerInstanceId,
1169
- coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
1181
+ coveredRunOrdinals: { from, to: Math.max(from, run.ordinal - 1) },
1182
strategy: "full_thread_summary",
1183
runs: projection.runs,
1184
items: [
@@ -1536,7 +1548,10 @@ export const layer: Layer.Layer<
1548
providerSessionId,
1549
// Clear the native ref to force a fresh session while preserving row identity.
1550
existingProviderThread: { ...providerThread, nativeThreadRef: null },
1539
- forceNewNativeThread: true,
1551
+ // A fresh session that never loaded the broken history needs no replacement.
1552
+ ...(opensFreshSession && resumed._tag === "Failure"
1553
+ ? {}
1554
+ : { forceNewNativeThread: true }),
1555
}),
1556
);
1557
if (replacement === undefined) return undefined;
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+142
-14
@@ -58,6 +58,7 @@ import * as EffectOutbox from "../EffectOutbox.ts";
58
import * as ProjectionReplay from "./ProjectionReplay.ts";
59
import * as ProjectionStore from "../ProjectionStore.ts";
60
import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
61
+import * as ProviderSessionManager from "../ProviderSessionManager.ts";
62
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
63
import {
64
CLAUDE_MODEL_SELECTION,
@@ -116,6 +117,7 @@ function makeTestAdapter(input: {
117
>;
118
readonly failure?: ReturnType<typeof makeProviderFailure>;
119
readonly failedRunOrdinals?: ReadonlySet<number>;
120
+ readonly brokenRunOrdinals?: ReadonlySet<number>;
121
readonly interruptedRunOrdinals?: ReadonlySet<number>;
122
readonly cancelledRunOrdinals?: ReadonlySet<number>;
123
readonly holdRunOrdinal?: number;
@@ -132,6 +134,8 @@ function makeTestAdapter(input: {
134
readonly backgroundTasksEndWithProcess?: true;
135
readonly backgroundWork?: Ref.Ref<boolean>;
136
readonly closedSessions?: Ref.Ref<ReadonlyArray<string>>;
137
+ /** Like ACP: opening resumes the initial native id, and forcing a new thread restarts the runtime. */
138
+ readonly runtimeStarts?: Ref.Ref<ReadonlyArray<string>>;
139
// ACP cannot truncate, so its rollback answers with a fresh, empty native session.
140
readonly rollback?: "truncates" | "replaces_native_thread";
141
}): ProviderAdapter.ProviderAdapterV2["Service"] {
@@ -144,6 +148,12 @@ function makeTestAdapter(input: {
148
Effect.gen(function* () {
149
if (input.holdOpenSession !== undefined) yield* Deferred.await(input.holdOpenSession);
150
const events = yield* PubSub.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
151
+ if (input.runtimeStarts !== undefined) {
152
+ yield* Ref.update(input.runtimeStarts, (starts) => [
153
+ ...starts,
154
+ sessionInput.initialNativeThreadId ?? "new",
155
+ ]);
156
+ }
157
if (input.closedSessions !== undefined) {
158
const closedSessions = input.closedSessions;
159
yield* Effect.addFinalizer(() =>
@@ -197,6 +207,9 @@ function makeTestAdapter(input: {
207
}),
208
ensureThread: (threadInput) =>
209
Effect.gen(function* () {
210
+ if (threadInput.forceNewNativeThread && input.runtimeStarts !== undefined) {
211
+ yield* Ref.update(input.runtimeStarts, (starts) => [...starts, "replacement"]);
212
+ }
213
const createdAt = yield* DateTime.now;
214
const generation =
215
input.nativeThreadGeneration === undefined
@@ -229,6 +242,7 @@ function makeTestAdapter(input: {
242
resumeThread: ({ providerThread }) =>
243
Effect.gen(function* () {
244
if (
245
+ (input.brokenRunOrdinals !== undefined && providerThread.status === "error") ||
246
input.failResume ||
247
(input.failResumeOnce !== undefined &&
248
(yield* Ref.getAndSet(input.failResumeOnce, false)))
@@ -427,7 +441,9 @@ function makeTestAdapter(input: {
441
}),
442
}
443
: { status: terminalStatus, failure: null }),
430
- threadDisposition: "reusable",
444
+ threadDisposition: input.brokenRunOrdinals?.has(turnInput.runOrdinal)
445
+ ? "broken"
446
+ : "reusable",
447
},
448
];
449
const reportedUsage = input.tokenUsageByRunOrdinal?.[turnInput.runOrdinal];
@@ -443,6 +459,17 @@ function makeTestAdapter(input: {
459
},
460
});
461
}
462
+ if (input.brokenRunOrdinals?.has(turnInput.runOrdinal)) {
463
+ yield* PubSub.publish(events, {
464
+ type: "provider_thread.updated",
465
+ driver: input.driver,
466
+ providerThread: {
467
+ ...turnInput.providerThread,
468
+ status: "error",
469
+ updatedAt: eventTime,
470
+ },
471
+ });
472
+ }
473
for (const event of providerEvents) {
474
yield* PubSub.publish(events, event);
475
}
@@ -2307,7 +2334,8 @@ describe("orchestration v2 provider switching", () => {
2334
it.live.each(
2335
(
2336
[
2310
- ["failed", false, false, false],
2337
+ ["failed", false, false, false, false],
2338
+ ["failed", false, false, false, true],
2339
["failed", true, true, true],
2340
["interrupted", false, true, false],
2341
["interrupted", true, false, true],
@@ -2315,13 +2343,13 @@ describe("orchestration v2 provider switching", () => {
2343
["cancelled", true, true, false],
2344
] as const
2345
).map(
2318
- ([status, queued, returning, native]) =>
2346
+ ([status, queued, returning, native, broken]) =>
2347
[
2320
- `${status} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`,
2321
- { status, queued, returning, native },
2348
+ `${status}${broken ? " broken" : ""} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`,
2349
+ { status, queued, returning, native, broken },
2350
] as const,
2351
),
2324
- )("hands off %s", ([, { status, queued, returning, native }]) =>
2352
+ )("hands off %s", ([, { status, queued, returning, native, broken }]) =>
2353
Effect.gen(function* () {
2354
const cwd = yield* checkpointWorkspace(`handoff-${status}-${queued}-${returning}`);
2355
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
@@ -2331,6 +2359,7 @@ describe("orchestration v2 provider switching", () => {
2359
const sourceOrdinal = returning ? 2 : 1;
2360
const sourceSelection = returning ? CLAUDE_MODEL_SELECTION : CODEX_MODEL_SELECTION;
2361
const targetSelection = returning ? CODEX_MODEL_SELECTION : CLAUDE_MODEL_SELECTION;
2362
+ const generation = yield* Ref.make(0);
2363
const originalPrompt = "Keep the release marker violet and preserve the existing API.";
2364
const partialResponse = "I checked the API and found the release configuration.";
2365
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters(
@@ -2353,6 +2382,12 @@ describe("orchestration v2 provider switching", () => {
2382
...(modelSelection.instanceId === sourceSelection.instanceId
2383
? {
2384
failedRunOrdinals: new Set(status === "failed" ? [sourceOrdinal] : []),
2385
+ ...(broken
2386
+ ? {
2387
+ brokenRunOrdinals: new Set([sourceOrdinal]),
2388
+ nativeThreadGeneration: generation,
2389
+ }
2390
+ : {}),
2391
interruptedRunOrdinals: new Set(status === "interrupted" ? [sourceOrdinal] : []),
2392
cancelledRunOrdinals: new Set(status === "cancelled" ? [sourceOrdinal] : []),
2393
holdRunOrdinal: sourceOrdinal,
@@ -2466,8 +2501,17 @@ describe("orchestration v2 provider switching", () => {
2501
yield* dispatch("back", "Finish the remaining work", sourceSelection);
2502
yield* waitForRun(sourceOrdinal + 2, "completed");
2503
const back = (yield* Ref.get(capturedTurns)).at(-1)!;
2469
- assert.notInclude(back.text, originalPrompt);
2470
- assert.notInclude(back.text, partialResponse);
2504
+ if (broken) {
2505
+ const source = (yield* Ref.get(capturedTurns)).find(
2506
+ (turn) => turn.modelSelection.instanceId === sourceSelection.instanceId,
2507
+ )!;
2508
+ assert.notEqual(back.nativeThreadId, source.nativeThreadId);
2509
+ assert.include(back.text, originalPrompt);
2510
+ assert.include(back.text, partialResponse);
2511
+ } else {
2512
+ assert.notInclude(back.text, originalPrompt);
2513
+ assert.notInclude(back.text, partialResponse);
2514
+ }
2515
}).pipe(
2516
Effect.provide(
2517
ProviderReplayHarness.layerWithRegistry(
@@ -4129,15 +4173,23 @@ describe("orchestration v2 provider switching", () => {
4173
}),
4174
);
4175
4132
- it.live.each(["immediately", "behind a running turn"] as const)(
4176
+ it.live.each([
4177
+ "immediately",
4178
+ "behind a running turn",
4179
+ "and recovers it after it breaks",
4180
+ "and recovers it after it breaks and the server restarts",
4181
+ ] as const)(
4182
"starts a fresh provider session %s and never hands earlier runs to a later provider",
4183
(variant) =>
4184
Effect.gen(function* () {
4136
- const queued = variant !== "immediately";
4137
- const key = queued ? "queued" : "immediate";
4185
+ const queued = variant === "behind a running turn";
4186
+ const restarted = variant === "and recovers it after it breaks and the server restarts";
4187
+ const broken = restarted || variant === "and recovers it after it breaks";
4188
+ const key = queued ? "queued" : restarted ? "restarted" : broken ? "broken" : "immediate";
4189
const cwd = yield* checkpointWorkspace(`fresh-context-${key}`);
4190
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
4191
const closedSessions = yield* Ref.make<ReadonlyArray<string>>([]);
4192
+ const runtimeStarts = yield* Ref.make<ReadonlyArray<string>>([]);
4193
// A queued start has nobody to refuse, so a busy session must stay up.
4194
const backgroundWork = yield* Ref.make(queued);
4195
const started = yield* Deferred.make<void>();
@@ -4151,11 +4203,18 @@ describe("orchestration v2 provider switching", () => {
4203
responseByRunOrdinal: {},
4204
capturedTurns,
4205
closedSessions,
4206
+ runtimeStarts,
4207
backgroundWork,
4208
nativeThreadGeneration: yield* Ref.make(0),
4209
...(queued
4210
? { holdFirstTurn: started, releaseFirstTurn: release, holdRunOrdinal: 2 }
4211
: {}),
4212
+ ...(broken
4213
+ ? {
4214
+ failedRunOrdinals: new Set([3]),
4215
+ brokenRunOrdinals: new Set([3]),
4216
+ }
4217
+ : {}),
4218
}),
4219
makeTestAdapter({
4220
instanceId: CODEX_MODEL_SELECTION.instanceId,
@@ -4249,6 +4308,22 @@ describe("orchestration v2 provider switching", () => {
4308
// Claude hosts one native thread per session, so an idle old one is closed.
4309
assert.deepEqual(yield* Ref.get(closedSessions), queued ? [] : [firstSession.id]);
4310
yield* Ref.set(backgroundWork, false);
4311
+ let startsBeforeRecovery = 0;
4312
+ if (broken) {
4313
+ if (restarted) {
4314
+ const brokenProjection = yield* orchestrator.getThreadProjection(freshThreadId);
4315
+ const brokenThread = brokenProjection.providerThreads.find(
4316
+ (thread) => thread.id === brokenProjection.thread.activeProviderThreadId,
4317
+ )!;
4318
+ assert.equal(brokenThread.status, "error");
4319
+ const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
4320
+ yield* sessions.close(brokenThread.providerSessionId!);
4321
+ }
4322
+ startsBeforeRecovery = (yield* Ref.get(runtimeStarts)).length;
4323
+ yield* send("epsilon", CLAUDE_MODEL_SELECTION);
4324
+ yield* worker.drain();
4325
+ yield* waitForIdle(freshThreadId);
4326
+ }
4327
yield* send("delta", CODEX_MODEL_SELECTION);
4328
yield* worker.drain();
4329
yield* waitForIdle(freshThreadId);
@@ -4277,6 +4352,27 @@ describe("orchestration v2 provider switching", () => {
4352
if (queued) {
4353
assert.equal(turnFor("gamma").providerThreadId, turnFor("beta").providerThreadId);
4354
}
4355
+ if (broken) {
4356
+ const recovered = turnFor("epsilon");
4357
+ assert.equal(recovered.providerThreadId, turnFor("beta").providerThreadId);
4358
+ assert.notEqual(recovered.nativeThreadId, turnFor("beta").nativeThreadId);
4359
+ assert.include(recovered.text, "Prompt beta");
4360
+ assert.notInclude(recovered.text, "Prompt alpha");
4361
+ assert.notInclude(recovered.text, "Prompt zero");
4362
+ // The broken native id is never reopened; a reopened session starts fresh only once.
4363
+ assert.deepEqual(
4364
+ (yield* Ref.get(runtimeStarts)).slice(startsBeforeRecovery),
4365
+ restarted ? ["new"] : ["replacement"],
4366
+ );
4367
+ const recoveredRun = projection.runs.find(
4368
+ (run) => run.userMessageId === `message:fresh-context:${key}:epsilon`,
4369
+ )!;
4370
+ assert.equal(
4371
+ projection.contextHandoffs.find((handoff) => handoff.targetRunId === recoveredRun.id)!
4372
+ .coveredRunOrdinals.from,
4373
+ 3,
4374
+ );
4375
+ }
4376
const codexTurn = turnFor("delta");
4377
assert.notEqual(codexTurn.providerThreadId, turnFor("zero").providerThreadId);
4378
assert.include(codexTurn.text, "Prompt beta");
@@ -4410,6 +4506,8 @@ describe("orchestration v2 provider switching", () => {
4506
responseByRunOrdinal: {},
4507
capturedTurns,
4508
nativeThreadGeneration: yield* Ref.make(0),
4509
+ failedRunOrdinals: new Set([5]),
4510
+ brokenRunOrdinals: new Set([5]),
4511
}),
4512
]);
4513
const threadId = ThreadId.make("thread:scheduled-fresh-user-chat");
@@ -4457,6 +4555,7 @@ describe("orchestration v2 provider switching", () => {
4555
["compaction", false],
4556
["scheduled-after-compaction", true],
4557
["user-third", false],
4558
+ ["user-fourth", false],
4559
] as const) {
4560
if (name === "compaction") {
4561
// The user's run compacts, so later dispatches no longer read the first scheduled run's message.
@@ -4507,6 +4606,21 @@ describe("orchestration v2 provider switching", () => {
4606
// The scheduled run's fresh session must not replace the user's conversation.
4607
assert.equal(turnFor("user-second")!.nativeThreadId, turnFor("user-first")!.nativeThreadId);
4608
assert.equal(turnFor("user-third")!.nativeThreadId, turnFor("user-first")!.nativeThreadId);
4609
+ // The user's session broke; recovery reads the whole thread, so scheduled runs do not cut it.
4610
+ const recovered = turnFor("user-fourth")!;
4611
+ assert.equal(recovered.providerThreadId, turnFor("user-first")!.providerThreadId);
4612
+ assert.notEqual(recovered.nativeThreadId, turnFor("user-first")!.nativeThreadId);
4613
+ assert.include(recovered.text, "user-first");
4614
+ assert.include(recovered.text, "user-third");
4615
+ const projection = yield* orchestrator.getThreadProjection(threadId);
4616
+ const recoveredRun = projection.runs.find(
4617
+ (run) => run.userMessageId === "message:scheduled-fresh-user-chat:user-fourth",
4618
+ )!;
4619
+ assert.equal(
4620
+ projection.contextHandoffs.find((handoff) => handoff.targetRunId === recoveredRun.id)!
4621
+ .coveredRunOrdinals.from,
4622
+ 1,
4623
+ );
4624
}).pipe(
4625
Effect.provide(
4626
ProviderReplayHarness.layerWithRegistry(
@@ -4643,6 +4757,7 @@ describe("orchestration v2 provider switching", () => {
4757
it.live.each([
4758
["automatic", "Claude"],
4759
["queue.resume", "compatible Codex"],
4760
+ ["queue.resume", "broken compatible Codex"],
4761
] as const)(
4762
"delivers a queued PR update on the current provider through %s (%s)",
4763
([delivery, target]) =>
@@ -4651,7 +4766,9 @@ describe("orchestration v2 provider switching", () => {
4766
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
4767
const started = yield* Deferred.make<void>();
4768
const release = yield* Deferred.make<void>();
4654
- const compatible = target === "compatible Codex";
4769
+ const compatible = target !== "Claude";
4770
+ const broken = target === "broken compatible Codex";
4771
+ const generation = yield* Ref.make(0);
4772
const selection = {
4773
...(compatible
4774
? { ...CODEX_MODEL_SELECTION, instanceId: ProviderInstanceId.make("codex-alternate") }
@@ -4663,7 +4780,7 @@ describe("orchestration v2 provider switching", () => {
4780
...CodexProviderCapabilitiesV2,
4781
context: {
4782
...CodexProviderCapabilitiesV2.context,
4666
- canConsumeHandoffSummaries: false,
4783
+ canConsumeHandoffSummaries: broken,
4784
},
4785
}
4786
: ClaudeProviderCapabilitiesV2;
@@ -4678,6 +4795,9 @@ describe("orchestration v2 provider switching", () => {
4795
holdFirstTurn: started,
4796
releaseFirstTurn: release,
4797
failedRunOrdinals: new Set([1]),
4798
+ ...(broken
4799
+ ? { brokenRunOrdinals: new Set([1]), nativeThreadGeneration: generation }
4800
+ : {}),
4801
failure: makeProviderFailure({
4802
message: "Usage limit reached",
4803
class: "usage_limit",
@@ -4691,6 +4811,9 @@ describe("orchestration v2 provider switching", () => {
4811
modelSelection: selection,
4812
responseByRunOrdinal: {},
4813
capturedTurns,
4814
+ ...(broken
4815
+ ? { brokenRunOrdinals: new Set<number>(), nativeThreadGeneration: generation }
4816
+ : {}),
4817
}),
4818
];
4819
const layerRegistry = compatible
@@ -4828,7 +4951,12 @@ describe("orchestration v2 provider switching", () => {
4951
assert.equal(executed.providerThreadId, turns[1]!.providerThreadId);
4952
assert.equal(executed.nativeThreadId, turns[1]!.nativeThreadId);
4953
}
4831
- if (compatible) {
4954
+ if (broken) {
4955
+ assert.notEqual(executed.nativeThreadId, turns[0]!.nativeThreadId);
4956
+ assert.isFalse(executed.nativeThreadHasTurns);
4957
+ assert.include(executed.text, "Original work");
4958
+ }
4959
+ if (compatible && !broken) {
4960
assert.equal(executed.nativeThreadId, turns[0]!.nativeThreadId);
4961
assert.isEmpty(after.contextHandoffs);
4962
}
apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts
+45
-20
@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";
6
import * as FileSystem from "effect/FileSystem";
7
import * as Path from "effect/Path";
8
import type * as EffectAcpSchema from "effect-acp/compat";
9
+import type { OrchestrationV2ProviderFailure } from "@t3tools/contracts";
10
11
import { watchAntigravityPromptOutcome } from "./AntigravityTurnOutcome.ts";
12
@@ -32,10 +33,19 @@ const RATE_LIMIT_ERROR = errorPayload(
33
const INVALID_ARGUMENT_ERROR = errorPayload(
34
"Error 400, Message: Request contains an invalid argument., Status: INVALID_ARGUMENT, Details: []",
35
);
36
+// Vertex Claude rejects a resumed history whose saved thinking block lost its signature.
37
+const MISSING_SIGNATURE_ERROR = errorPayload(
38
+ 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0.thinking.signature: Field required"},"request_id":"req_vrtx_test"}, Status: INVALID_ARGUMENT, Details: []',
39
+);
40
+const INVALID_SIGNATURE_ERROR = errorPayload(
41
+ 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.3.content.0: Invalid `signature` in `thinking` block"}}, Status: INVALID_ARGUMENT, Details: []',
42
+);
43
// The model's reply quoting the agent's quota notice is an ordinary planner response.
44
const QUOTED_NOTICE = Buffer.from(
45
"Usage Limit Reached\n\nYou have reached your current quota for this period. Your limit will reset in 1 hour.",
46
);
47
+const reusable = (failure: OrchestrationV2ProviderFailure) =>
48
+ ({ failure, threadDisposition: "reusable" }) as const;
49
50
describe("watchAntigravityPromptOutcome", () => {
51
it.effect("fails only turns whose own steps end in an upstream error", () =>
@@ -83,13 +93,13 @@ describe("watchAntigravityPromptOutcome", () => {
93
[USER_INPUT, input],
94
[ERROR_MESSAGE, QUOTA_ERROR],
95
]),
86
- {
96
+ reusable({
97
class: "usage_limit",
98
message: "You have reached your Antigravity quota for this period.",
99
code: "RESOURCE_EXHAUSTED",
100
retryable: true,
101
resetAt: "1970-01-01T01:00:00.000Z",
92
- },
102
+ }),
103
);
104
// The earlier error step is outside this turn.
105
assert.isUndefined(
@@ -109,26 +119,35 @@ describe("watchAntigravityPromptOutcome", () => {
119
[USER_INPUT, input],
120
[ERROR_MESSAGE, RATE_LIMIT_ERROR],
121
]),
112
- {
122
+ reusable({
123
class: "usage_limit",
124
message: "Resource has been exhausted (e.g. check quota).",
125
code: "RESOURCE_EXHAUSTED",
126
retryable: true,
127
resetAt: "1970-01-01T00:00:42.000Z",
118
- },
128
+ }),
129
);
130
assert.deepEqual(
131
yield* turn([
132
[USER_INPUT, input],
133
[ERROR_MESSAGE, INVALID_ARGUMENT_ERROR],
134
]),
125
- {
135
+ reusable({
136
class: "provider_error",
137
message: "Request contains an invalid argument.",
138
code: "INVALID_ARGUMENT",
139
retryable: false,
130
- },
140
+ }),
141
);
142
+ // A saved thinking block without a valid signature fails every later prompt.
143
+ for (const error of [MISSING_SIGNATURE_ERROR, INVALID_SIGNATURE_ERROR]) {
144
+ const outcome = yield* turn([
145
+ [USER_INPUT, input],
146
+ [ERROR_MESSAGE, error],
147
+ ]);
148
+ assert.equal(outcome?.failure.code, "INVALID_THINKING_SIGNATURE");
149
+ assert.equal(outcome?.threadDisposition, "broken");
150
+ }
151
// A completed tool keeps its usage, and the turn still fails.
152
assert.equal(
153
(yield* turn(
@@ -142,7 +161,7 @@ describe("watchAntigravityPromptOutcome", () => {
161
stopReason: "end_turn",
162
usage: { inputTokens: 40, outputTokens: 5, totalTokens: 45 },
163
},
145
- ))?.class,
164
+ ))?.failure.class,
165
"usage_limit",
166
);
167
assert.isUndefined(
@@ -152,12 +171,15 @@ describe("watchAntigravityPromptOutcome", () => {
171
]),
172
);
173
// The agent maps the SDK's QUOTA_EXHAUSTED stop reason to `refusal`.
155
- assert.deepEqual(yield* turn([], { stopReason: "refusal" }), {
156
- class: "usage_limit",
157
- message: "You have reached your Antigravity quota for this period.",
158
- code: "QUOTA_EXHAUSTED",
159
- retryable: true,
160
- });
174
+ assert.deepEqual(
175
+ yield* turn([], { stopReason: "refusal" }),
176
+ reusable({
177
+ class: "usage_limit",
178
+ message: "You have reached your Antigravity quota for this period.",
179
+ code: "QUOTA_EXHAUSTED",
180
+ retryable: true,
181
+ }),
182
+ );
183
}).pipe(Effect.provide(NodeServices.layer)),
184
);
185
@@ -193,19 +215,22 @@ describe("watchAntigravityPromptOutcome", () => {
215
const linked = yield* watchAntigravityPromptOutcome(profileDirectory, own);
216
append(peer, ERROR_MESSAGE, QUOTA_ERROR);
217
assert.isUndefined(yield* linked({ stopReason: "end_turn" }));
196
- assert.equal((yield* linked({ stopReason: "refusal" }))?.class, "usage_limit");
218
+ assert.equal((yield* linked({ stopReason: "refusal" }))?.failure.class, "usage_limit");
219
220
// An unreadable log gives no evidence, but the agent's typed refusal still fails the turn.
221
yield* fs.remove(path.join(conversations, `${own}.db`));
222
yield* fs.writeFileString(path.join(conversations, `${own}.db`), "not a database");
223
const corrupt = yield* watchAntigravityPromptOutcome(profileDirectory, own);
224
assert.isUndefined(yield* corrupt({ stopReason: "end_turn" }));
203
- assert.deepEqual(yield* corrupt({ stopReason: "refusal" }), {
204
- class: "usage_limit",
205
- message: "You have reached your Antigravity quota for this period.",
206
- code: "QUOTA_EXHAUSTED",
207
- retryable: true,
208
- });
225
+ assert.deepEqual(
226
+ yield* corrupt({ stopReason: "refusal" }),
227
+ reusable({
228
+ class: "usage_limit",
229
+ message: "You have reached your Antigravity quota for this period.",
230
+ code: "QUOTA_EXHAUSTED",
231
+ retryable: true,
232
+ }),
233
+ );
234
}).pipe(Effect.provide(NodeServices.layer)),
235
);
236
});
apps/server/src/provider/acp/AntigravityTurnOutcome.ts
+48
-19
@@ -20,6 +20,10 @@ const MAX_ERROR_PAYLOAD_BYTES = 16_384;
20
// The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it.
21
const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s;
22
const QUOTA_EXHAUSTED = /\breason:QUOTA_EXHAUSTED\b/;
23
+// Claude rejects a saved thinking block without a valid signature. It sits in the native
24
+// history, so every later prompt to that session fails the same way.
25
+const INVALID_THINKING_SIGNATURE =
26
+ /\bmessages\.\d+\.content\.\d+(?:\.thinking\.signature: Field required|: Invalid `signature` in `thinking` block)/;
27
const RESET_TIMESTAMP = /\bquotaResetTimeStamp:([^\s\]]+)/;
28
const RESET_DELAY = /\bquotaResetDelay:((?:\d+(?:\.\d+)?(?:ns|us|µs|μs|ms|h|m|s))+)(?=[\s\]])/;
29
// google.rpc.RetryInfo, which plain rate limits carry instead of a quota reset.
@@ -106,7 +110,12 @@ function turnFailure(
110
stopReason: EffectAcpSchema.StopReason,
111
step: LastStep | undefined,
112
now: DateTime.Utc,
109
-): OrchestrationV2ProviderFailure | undefined {
113
+):
114
+ | {
115
+ readonly failure: OrchestrationV2ProviderFailure;
116
+ readonly threadDisposition: "reusable" | "broken";
117
+ }
118
+ | undefined {
119
const errorText =
120
step?.type === ERROR_STEP_TYPE
121
? new TextDecoder().decode(step.payload ?? new Uint8Array())
@@ -115,30 +124,50 @@ function turnFailure(
124
if (errorText === undefined && stopReason !== "refusal") return undefined;
125
const text = errorText ?? "";
126
const apiError = API_ERROR.exec(text);
127
+ const reusable = (failure: OrchestrationV2ProviderFailure) =>
128
+ ({ failure, threadDisposition: "reusable" }) as const;
129
if (stopReason === "refusal" || QUOTA_EXHAUSTED.test(text)) {
119
- return makeProviderFailure({
120
- class: "usage_limit",
121
- message: "You have reached your Antigravity quota for this period.",
122
- code: apiError?.[3] ?? "QUOTA_EXHAUSTED",
123
- retryable: true,
124
- resetAt: resetAtFrom(text, now) ?? null,
125
- });
130
+ return reusable(
131
+ makeProviderFailure({
132
+ class: "usage_limit",
133
+ message: "You have reached your Antigravity quota for this period.",
134
+ code: apiError?.[3] ?? "QUOTA_EXHAUSTED",
135
+ retryable: true,
136
+ resetAt: resetAtFrom(text, now) ?? null,
137
+ }),
138
+ );
139
+ }
140
+ if (INVALID_THINKING_SIGNATURE.test(text)) {
141
+ return {
142
+ failure: makeProviderFailure({
143
+ class: "provider_error",
144
+ message:
145
+ "Antigravity's saved conversation can no longer be sent to the model. The next message starts a fresh Antigravity session with this thread's context.",
146
+ code: "INVALID_THINKING_SIGNATURE",
147
+ retryable: true,
148
+ }),
149
+ threadDisposition: "broken",
150
+ };
151
}
152
if (apiError === null) {
128
- return makeProviderFailure({
129
- class: "provider_error",
130
- message: "Antigravity stopped this turn because of an error.",
131
- });
153
+ return reusable(
154
+ makeProviderFailure({
155
+ class: "provider_error",
156
+ message: "Antigravity stopped this turn because of an error.",
157
+ }),
158
+ );
159
}
160
const [, httpStatus, message, status] = apiError;
161
const rateLimited = httpStatus === "429" || status === "RESOURCE_EXHAUSTED";
135
- return makeProviderFailure({
136
- class: rateLimited ? "usage_limit" : "provider_error",
137
- message: message!.trim(),
138
- code: status ?? null,
139
- retryable: rateLimited || Number(httpStatus) >= 500,
140
- resetAt: resetAtFrom(text, now) ?? null,
141
- });
162
+ return reusable(
163
+ makeProviderFailure({
164
+ class: rateLimited ? "usage_limit" : "provider_error",
165
+ message: message!.trim(),
166
+ code: status ?? null,
167
+ retryable: rateLimited || Number(httpStatus) >= 500,
168
+ resetAt: resetAtFrom(text, now) ?? null,
169
+ }),
170
+ );
171
}
172
173
const conversationSegments = ["antigravity-acp", "conversations"];
packages/provider-acp-registry/src/server/adapter.ts
+15
-1
@@ -34,6 +34,7 @@ import * as Option from "effect/Option";
34
import * as Schema from "effect/Schema";
35
import type * as Scope from "effect/Scope";
36
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
37
+import type * as EffectAcpSchema from "effect-acp/compat";
38
import * as EffectAcpErrors from "effect-acp/errors";
39
40
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
@@ -261,7 +262,20 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
262
: {}),
263
// glm-acp-agent is the one agent whose per-turn usage a live probe has verified.
264
...(registryAgentId === "glm-acp-agent" ? { reportsPerTurnPromptUsage: true } : {}),
264
- ...(watchKimiPromptOutcome === undefined ? {} : { watchPromptOutcome: watchKimiPromptOutcome }),
265
+ ...(watchKimiPromptOutcome === undefined
266
+ ? {}
267
+ : {
268
+ watchPromptOutcome: (sessionId: string) =>
269
+ Effect.map(
270
+ watchKimiPromptOutcome(sessionId),
271
+ (check) => (result: EffectAcpSchema.PromptResponse) =>
272
+ Effect.map(check(result), (failure) =>
273
+ failure === undefined
274
+ ? undefined
275
+ : { failure, threadDisposition: "reusable" as const },
276
+ ),
277
+ ),
278
+ }),
279
...(registryAgentId === "mistral-vibe"
280
? { registerExtensions: registerMistralVibeAcpExtensions }
281
: {}),
packages/provider-acp/src/server/adapter.ts
+27
-9
@@ -339,6 +339,11 @@ export function acpPerTurnPromptUsage(
339
};
340
}
341
342
+interface AcpPromptOutcomeFailure {
343
+ readonly failure: OrchestrationV2ProviderFailure;
344
+ readonly threadDisposition: "reusable" | "broken";
345
+}
346
+
347
export interface AcpAdapterV2Flavor {
348
readonly buildAttachmentPrompt?: (input: {
349
readonly text: string;
@@ -353,14 +358,13 @@ export interface AcpAdapterV2Flavor {
358
/**
359
* Runs before `session/prompt`. The returned check sees a prompt the agent ended
360
* without an error or cancel, and reports a failure its stop reason hid. A reported
356
- * failure restarts the runtime before the next turn.
361
+ * failure restarts the runtime before the next turn. A `broken` thread's native
362
+ * history is unusable, so the next turn falls back to a fresh session.
363
*/
364
readonly watchPromptOutcome?: (
365
sessionId: string,
366
) => Effect.Effect<
361
- (
362
- result: EffectAcpSchema.PromptResponse,
363
- ) => Effect.Effect<OrchestrationV2ProviderFailure | undefined>
367
+ (result: EffectAcpSchema.PromptResponse) => Effect.Effect<AcpPromptOutcomeFailure | undefined>
368
>;
369
readonly requiresSignIn?: (cause: unknown) => boolean;
370
/**
@@ -8050,10 +8054,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8054
context: ActiveAcpTurn,
8055
status: "completed" | "interrupted" | "failed" | "cancelled",
8056
failure?: OrchestrationV2ProviderFailure,
8053
- options?: { readonly childTurnsContinue?: boolean },
8057
+ options?: {
8058
+ readonly childTurnsContinue?: boolean;
8059
+ readonly threadDisposition?: "reusable" | "broken";
8060
+ },
8061
): Effect.fn.Return<void> {
8062
if (context.finalized) return;
8063
const settledStatus = context.interrupted ? "interrupted" : status;
8064
+ const threadDisposition = options?.threadDisposition ?? "reusable";
8065
context.finalizedStatus = settledStatus;
8066
context.finalized = true;
8067
const watchdog = context.inactivityWatchdog;
@@ -8152,7 +8160,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8160
const updatedProviderThread: OrchestrationV2ProviderThread = {
8161
...context.input.providerThread,
8162
providerSessionId: input.providerSessionId,
8155
- status: "active",
8163
+ status: threadDisposition === "broken" ? "error" : "active",
8164
lastRunOrdinal: context.input.runOrdinal,
8165
firstRunOrdinal:
8166
context.input.providerThread.firstRunOrdinal ?? context.input.runOrdinal,
@@ -8196,7 +8204,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8204
retry: context.providerRetry.retry,
8205
retryStartedAt: context.providerRetry.startedAt,
8206
}),
8199
- threadDisposition: "reusable",
8207
+ threadDisposition,
8208
}
8209
: {
8210
type: "turn.terminal",
@@ -8206,7 +8214,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8214
runOrdinal: context.input.runOrdinal,
8215
status: settledStatus,
8216
failure: null,
8209
- threadDisposition: "reusable",
8217
+ threadDisposition,
8218
},
8219
);
8220
const subagentsRequiringCarryover = [...context.subagents.values()].filter(
@@ -8951,7 +8959,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8959
yield* Ref.set(runtimeRestartRequired, true);
8960
}
8961
const failure =
8954
- hiddenFailure ??
8962
+ hiddenFailure?.failure ??
8963
(context.interrupted
8964
? undefined
8965
: stopReasonFailure(result.stopReason, result.error));
@@ -8977,6 +8985,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8985
// background tools and subagents keep reporting to this run.
8986
yield* finalizeTurn(context, "failed", failure, {
8987
childTurnsContinue: hasSurvivingBackgroundWork(context),
8988
+ ...(hiddenFailure === undefined
8989
+ ? {}
8990
+ : { threadDisposition: hiddenFailure.threadDisposition }),
8991
});
8992
return;
8993
}
@@ -9259,6 +9270,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9270
readonly modelSelection?: ModelSelection;
9271
readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
9272
}) {
9273
+ if (threadInput.providerThread.status === "error") {
9274
+ // A broken turn left this native history unusable; the caller recovers in a fresh session.
9275
+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({
9276
+ driver,
9277
+ detail: "The native session history is unusable.",
9278
+ });
9279
+ }
9280
return yield* runtimeTransitionPermit.withPermit(
9281
Effect.gen(function* () {
9282
yield* awaitRuntimeTeardown();