@devries-cameron20 / t3code Mirror · read-only / commits / 18ac394ee4
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, 05:45 UTC

fix(pi): hold messages until compaction ends (#24388)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 2, 2026 at 18:51 UTC 18ac394ee4a93eea06ff17d053be1ad474de3eff
2 files changed +440 -49
packages/provider-pi/src/server/adapter.test.ts
+340 -26
@@ -161,10 +161,11 @@ interface FakePi {
161 readonly vetoNextSwitch: () => void;
162 readonly queueState: (data: Record<string, unknown>) => void;
163 readonly setStreaming: (streaming: boolean) => void;
164 + readonly setCompacting: (compacting: boolean) => void;
165 readonly deferNextState: () => void;
166 readonly resolveDeferredState: (data: unknown) => Effect.Effect<void>;
167 readonly failNextState: () => void;
167 - readonly deferNextLifecycle: (type: "switch_session" | "new_session" | "fork") => void;
168 + readonly deferNextLifecycle: (type: "switch_session" | "new_session" | "fork" | "abort") => void;
169 readonly deferNextModelSelection: () => void;
170 readonly queueModels: (models: ReadonlyArray<unknown>) => void;
171 readonly vetoNextNewSession: () => void;
@@ -197,6 +198,10 @@ const recordedIdleState = (sessionFile: string) => ({
198 pendingMessageCount: 0,
199 });
200
201 +/** Pi 1.4.0 rejects every prompt while compaction runs, including steers. */
202 +const PI_COMPACTING_PROMPT_ERROR =
203 + "Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.";
204 +
205 const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
206 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
207 const requests = yield* Queue.unbounded<PiRpcRecord>();
@@ -215,6 +220,7 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
220 let sessionGeneration = 0;
221 let models: ReadonlyArray<unknown> = [];
222 let isStreaming: boolean | null = null;
223 + let isCompacting = false;
224 let clearQueue: Parameters<FakePi["setClearQueue"]>[0] = { steering: [], followUp: [] };
225 let stdinBuffer = "";
226
@@ -228,7 +234,10 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
234 });
235
236 const respondTo = (record: PiRpcRecord): PiRpcRecord | null => {
231 - if (typeof record["id"] !== "string" && !(record["type"] === "prompt" && isStreaming !== null))
237 + if (
238 + typeof record["id"] !== "string" &&
239 + !(record["type"] === "prompt" && (isStreaming !== null || isCompacting))
240 + )
241 return null;
242 const base = {
243 type: "response",
@@ -251,6 +260,9 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
260 },
261 };
262 case "prompt":
263 + if (isCompacting) {
264 + return { ...base, success: false, error: PI_COMPACTING_PROMPT_ERROR };
265 + }
266 if (isStreaming && record["streamingBehavior"] === undefined) {
267 return {
268 ...base,
@@ -397,6 +409,9 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
409 setStreaming: (streaming) => {
410 isStreaming = streaming;
411 },
412 + setCompacting: (compacting) => {
413 + isCompacting = compacting;
414 + },
415 queueStats: (data) => statsQueue.push(data),
416 setClearQueue: (result) => {
417 clearQueue = result;
@@ -791,7 +806,7 @@ describe("PiAdapterV2", () => {
806 );
807
808 it.effect.each([false, true])(
794 - "retains native wake ownership after a rejected joining prompt, compaction aborted=%s",
809 + "retains native wake ownership and delivers a joining prompt held through compaction, aborted=%s",
810 (aborted) =>
811 Effect.gen(function* () {
812 const fake = yield* makeFakePi;
@@ -818,9 +833,6 @@ describe("PiAdapterV2", () => {
833 yield* fake.emit({ type: "agent_settled" });
834 yield* fake.emit({ type: "compaction_start", reason: "manual" });
835 yield* startTurn(runtime, providerThread);
821 - yield* fake.takeRequest("prompt");
822 - const rejection = "Cannot submit a prompt while compaction is in progress.";
823 - yield* fake.emit({ type: "response", command: "prompt", success: false, error: rejection });
836 yield* fake.emit({
837 type: "extension_ui_request",
838 id: "native-compaction-dialog",
@@ -836,22 +848,21 @@ describe("PiAdapterV2", () => {
848 decision: "accept",
849 });
850 yield* fake.takeRequest("extension_ui_response");
839 - if (aborted) {
840 - yield* fake.emit({ type: "compaction_end", result: null, aborted: true });
841 - const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
842 - assert.isTrue(
843 - terminal.type === "turn.terminal" &&
844 - terminal.status === "failed" &&
845 - terminal.failure.message === rejection,
846 - );
847 - return;
848 - }
851 + assert.isFalse(fake.allRequests().some((request) => request["type"] === "prompt"));
852 + yield* fake.emit(
853 + aborted
854 + ? { type: "compaction_end", result: null, aborted: true }
855 + : {
856 + type: "compaction_end",
857 + result: { summary: "Native compaction finished" },
858 + willRetry: true,
859 + },
860 + );
861 + const prompt = yield* fake.takeRequest("prompt");
862 + assert.equal(prompt["message"], "Hello pi");
863 fake.queueState({ isStreaming: true });
850 - yield* fake.emit({
851 - type: "compaction_end",
852 - result: { summary: "Native compaction finished" },
853 - willRetry: true,
854 - });
864 + yield* fake.emit({ type: "response", command: "prompt", success: true });
865 + yield* fake.takeRequest("get_state");
866 yield* fake.emit({ type: "agent_start" });
867 yield* fake.emit({ type: "message_start", message: { role: "assistant" } });
868 yield* fake.emit({
@@ -864,13 +875,12 @@ describe("PiAdapterV2", () => {
875 });
876 const message = yield* takeEvent((event) => event.type === "message.updated");
877 assert.isTrue(message.type === "message.updated" && message.message.runId !== null);
867 - yield* fake.takeRequest("get_state");
878 yield* fake.emit({ type: "agent_settled" });
879 const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
870 - assert.isTrue(
871 - terminal.type === "turn.terminal" &&
872 - terminal.status === "failed" &&
873 - terminal.failure.message === rejection,
880 + assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed");
881 + assert.equal(
882 + fake.allRequests().filter((request) => request["type"] === "prompt").length,
883 + 1,
884 );
885 }).pipe(Effect.scoped, Effect.provide(layerTest)),
886 );
@@ -4138,6 +4148,310 @@ describe("PiAdapterV2", () => {
4148 }).pipe(Effect.scoped, Effect.provide(layerTest)),
4149 );
4150
4151 + it.effect("delivers a turn-start prompt sent during detached compaction once it ends", () =>
4152 + Effect.gen(function* () {
4153 + const fake = yield* makeFakePi;
4154 + const { runtime, takeEvent } = yield* openRuntime(fake);
4155 + const providerThread = yield* runtime.ensureThread({
4156 + threadId: THREAD_ID,
4157 + modelSelection: modelSelection("default"),
4158 + runtimePolicy,
4159 + });
4160 + yield* startTurn(runtime, providerThread);
4161 + yield* fake.takeRequest("prompt");
4162 + yield* fake.emit({ type: "agent_start" });
4163 + yield* fake.emit({ type: "agent_settled" });
4164 + yield* fake.takeRequest("get_state");
4165 + const first = yield* takeEvent((event) => event.type === "turn.terminal");
4166 + assert.isTrue(first.type === "turn.terminal" && first.status === "completed");
4167 +
4168 + fake.setCompacting(true);
4169 + yield* fake.emit({ type: "compaction_start", reason: "manual" });
4170 + // The dialog proves the pump observed compaction_start before the prompt.
4171 + yield* fake.emit({
4172 + type: "extension_ui_request",
4173 + id: "detached-compaction-dialog",
4174 + method: "confirm",
4175 + title: "Continue?",
4176 + });
4177 + yield* takeEvent((event) => event.type === "runtime_request.updated");
4178 + yield* startTurn(
4179 + runtime,
4180 + providerThread,
4181 + "default",
4182 + [],
4183 + "Sent during compaction",
4184 + undefined,
4185 + 2,
4186 + );
4187 + // Writes go out in order, so this round trip flushes any prompt sent before it.
4188 + yield* runtime.readThreadSnapshot({ providerThread });
4189 + fake.setCompacting(false);
4190 + const compactionEnded = fake.allRequests().length;
4191 + assert.isFalse(
4192 + fake
4193 + .allRequests()
4194 + .some(
4195 + (request) =>
4196 + request["type"] === "prompt" && request["message"] === "Sent during compaction",
4197 + ),
4198 + );
4199 + yield* fake.emit({
4200 + type: "compaction_end",
4201 + reason: "manual",
4202 + result: { summary: "smaller", tokensBefore: 10_000, estimatedTokensAfter: 2_000 },
4203 + aborted: false,
4204 + willRetry: false,
4205 + });
4206 + const delivered = yield* fake.takeRequest("prompt");
4207 + assert.equal(delivered["message"], "Sent during compaction");
4208 + yield* fake.emit({ type: "agent_start" });
4209 + fake.queueState({ isStreaming: false, isCompacting: false, pendingMessageCount: 0 });
4210 + yield* fake.emit({ type: "agent_settled" });
4211 + const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
4212 + assert.equal(
4213 + fake
4214 + .allRequests()
4215 + .slice(compactionEnded)
4216 + .filter(
4217 + (request) =>
4218 + request["type"] === "prompt" && request["message"] === "Sent during compaction",
4219 + ).length,
4220 + 1,
4221 + );
4222 + assert.isTrue(
4223 + terminal.type === "turn.terminal" && terminal.status === "completed",
4224 + `turn ended ${terminal.type === "turn.terminal" ? terminal.status : terminal.type}`,
4225 + );
4226 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
4227 + );
4228 +
4229 + it.effect.each([
4230 + { error: PI_COMPACTING_PROMPT_ERROR, retried: true },
4231 + { error: "Model unavailable", retried: false },
4232 + ])(
4233 + "retries a prompt Pi rejected because compaction started first, retried=$retried",
4234 + ({ error, retried }) =>
4235 + Effect.gen(function* () {
4236 + const fake = yield* makeFakePi;
4237 + const { runtime, takeEvent } = yield* openRuntime(fake);
4238 + const providerThread = yield* runtime.ensureThread({
4239 + threadId: THREAD_ID,
4240 + modelSelection: modelSelection("default"),
4241 + runtimePolicy,
4242 + });
4243 + yield* startTurn(runtime, providerThread);
4244 + yield* fake.takeRequest("prompt");
4245 + yield* fake.emit({ type: "response", command: "prompt", success: true });
4246 + yield* fake.emit({ type: "agent_start" });
4247 + yield* fake.emit({ type: "agent_settled" });
4248 + yield* fake.takeRequest("get_state");
4249 + yield* takeEvent((event) => event.type === "turn.terminal");
4250 +
4251 + yield* startTurn(runtime, providerThread, "default", [], "Raced compaction", undefined, 2);
4252 + yield* fake.takeRequest("prompt");
4253 + yield* fake.emit({ type: "compaction_start", reason: "manual" });
4254 + yield* fake.emit({
4255 + type: "response",
4256 + command: "prompt",
4257 + success: false,
4258 + error,
4259 + });
4260 + if (!retried) {
4261 + const failed = yield* takeEvent((event) => event.type === "turn.terminal");
4262 + assert.isTrue(
4263 + failed.type === "turn.terminal" &&
4264 + failed.status === "failed" &&
4265 + failed.failure.message === error,
4266 + );
4267 + return;
4268 + }
4269 + const compactionEnded = fake.allRequests().length;
4270 + yield* fake.emit({ type: "compaction_end", result: null, aborted: true });
4271 + const retriedPrompt = yield* fake.takeRequest("prompt");
4272 + assert.equal(retriedPrompt["message"], "Raced compaction");
4273 + yield* fake.emit({ type: "agent_start" });
4274 + yield* fake.emit({ type: "agent_settled" });
4275 + const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
4276 + assert.isTrue(
4277 + terminal.type === "turn.terminal" && terminal.status === "completed",
4278 + `turn ended ${terminal.type === "turn.terminal" ? terminal.status : terminal.type}`,
4279 + );
4280 + assert.equal(
4281 + fake
4282 + .allRequests()
4283 + .slice(compactionEnded)
4284 + .filter((request) => request["type"] === "prompt").length,
4285 + 1,
4286 + );
4287 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
4288 + );
4289 +
4290 + it.effect.each([{ restart: false }, { restart: true }])(
4291 + "restarts Pi when Stop interrupts a prompt held for detached compaction, restart=$restart",
4292 + ({ restart }) =>
4293 + Effect.gen(function* () {
4294 + const fake = yield* makeFakePi;
4295 + const { runtime, takeEvent } = yield* openRuntime(fake);
4296 + const providerThread = yield* runtime.ensureThread({
4297 + threadId: THREAD_ID,
4298 + modelSelection: modelSelection("default"),
4299 + runtimePolicy,
4300 + });
4301 + yield* startTurn(runtime, providerThread);
4302 + yield* fake.takeRequest("prompt");
4303 + yield* fake.emit({ type: "agent_start" });
4304 + yield* fake.emit({ type: "agent_settled" });
4305 + yield* fake.takeRequest("get_state");
4306 + yield* takeEvent((event) => event.type === "turn.terminal");
4307 +
4308 + fake.setCompacting(true);
4309 + yield* fake.emit({ type: "compaction_start", reason: "manual" });
4310 + // The dialog proves the pump observed compaction_start before the prompt.
4311 + yield* fake.emit({
4312 + type: "extension_ui_request",
4313 + id: "held-prompt-dialog",
4314 + method: "confirm",
4315 + title: "Continue?",
4316 + });
4317 + yield* takeEvent((event) => event.type === "runtime_request.updated");
4318 + yield* startTurn(runtime, providerThread, "default", [], "Held prompt", undefined, 2);
4319 + // Writes go out in order, so this round trip flushes any prompt sent before it.
4320 + yield* runtime.readThreadSnapshot({ providerThread });
4321 + assert.isFalse(
4322 + fake
4323 + .allRequests()
4324 + .some(
4325 + (request) => request["type"] === "prompt" && request["message"] === "Held prompt",
4326 + ),
4327 + );
4328 + const running = yield* takeEvent(
4329 + (event) =>
4330 + event.type === "provider_turn.updated" &&
4331 + event.providerTurn.status === "running" &&
4332 + event.providerTurn.ordinal === 2,
4333 + );
4334 + const providerTurnId =
4335 + running.type === "provider_turn.updated" ? running.providerTurn.id : undefined;
4336 + assert.isDefined(providerTurnId);
4337 +
4338 + const interruptedAt = fake.allRequests().length;
4339 + if (restart) {
4340 + fake.deferNextLifecycle("abort");
4341 + const stop = yield* Effect.forkChild(
4342 + runtime.interruptTurn({
4343 + providerThread,
4344 + providerTurnId: providerTurnId!,
4345 + requestRuntimeRestart: true,
4346 + }),
4347 + );
4348 + const abort = yield* fake.takeRequest("abort");
4349 + // The abort ends compaction before Pi exits; the stopped turn's prompt stays held.
4350 + fake.setCompacting(false);
4351 + yield* fake.emit({
4352 + type: "compaction_end",
4353 + reason: "manual",
4354 + result: null,
4355 + aborted: true,
4356 + });
4357 + yield* fake.emit({
4358 + type: "extension_ui_request",
4359 + id: "after-compaction-dialog",
4360 + method: "confirm",
4361 + title: "Continue?",
4362 + });
4363 + yield* takeEvent((event) => event.type === "runtime_request.updated");
4364 + yield* fake.emit({ type: "response", id: abort["id"], command: "abort", success: true });
4365 + yield* Fiber.join(stop);
4366 + } else {
4367 + yield* runtime.interruptTurn({ providerThread, providerTurnId: providerTurnId! });
4368 + assert.isFalse(fake.allRequests().some((request) => request["type"] === "abort"));
4369 + }
4370 + yield* fake.closeStdout;
4371 + const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
4372 + assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "interrupted");
4373 + assert.isFalse(
4374 + fake
4375 + .allRequests()
4376 + .slice(interruptedAt)
4377 + .some((request) => request["type"] === "prompt"),
4378 + );
4379 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
4380 + );
4381 +
4382 + it.effect("delivers a steer sent during in-turn compaction once it ends", () =>
4383 + Effect.gen(function* () {
4384 + const fake = yield* makeFakePi;
4385 + const { runtime, takeEvent } = yield* openRuntime(fake);
4386 + const providerThread = yield* runtime.ensureThread({
4387 + threadId: THREAD_ID,
4388 + modelSelection: modelSelection("default"),
4389 + runtimePolicy,
4390 + });
4391 + yield* startTurn(runtime, providerThread);
4392 + yield* fake.takeRequest("prompt");
4393 + const running = yield* takeEvent(
4394 + (event) =>
4395 + event.type === "provider_turn.updated" && event.providerTurn.status === "running",
4396 + );
4397 + const providerTurnId =
4398 + running.type === "provider_turn.updated" ? running.providerTurn.id : undefined;
4399 + assert.isDefined(providerTurnId);
4400 + yield* fake.emit({ type: "agent_start" });
4401 + fake.queueState({ isStreaming: false, isCompacting: true, pendingMessageCount: 0 });
4402 + yield* fake.emit({ type: "agent_settled" });
4403 + yield* fake.takeRequest("get_state");
4404 + fake.setCompacting(true);
4405 + yield* fake.emit({ type: "compaction_start", reason: "manual" });
4406 + yield* takeEvent(
4407 + (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction",
4408 + );
4409 +
4410 + yield* runtime.steerTurn({
4411 + threadId: THREAD_ID,
4412 + runId: RunId.make("run:thread-pi-test:1"),
4413 + providerThread,
4414 + providerTurnId: providerTurnId!,
4415 + message: {
4416 + messageId: "message:thread-pi-test:steer-during-compaction" as never,
4417 + text: "Steer during compaction",
4418 + attachments: [],
4419 + createdBy: "user",
4420 + creationSource: "web",
4421 + },
4422 + });
4423 + fake.setCompacting(false);
4424 + const compactionEnded = fake.allRequests().length;
4425 + yield* fake.emit({
4426 + type: "compaction_end",
4427 + reason: "manual",
4428 + result: { summary: "smaller", tokensBefore: 10_000, estimatedTokensAfter: 2_000 },
4429 + aborted: false,
4430 + willRetry: false,
4431 + });
4432 + const delivered = yield* fake.takeRequest("prompt");
4433 + assert.equal(delivered["message"], "Steer during compaction");
4434 + yield* fake.emit({ type: "agent_start" });
4435 + fake.queueState({ isStreaming: false, isCompacting: false, pendingMessageCount: 0 });
4436 + yield* fake.emit({ type: "agent_settled" });
4437 + const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
4438 + assert.equal(
4439 + fake
4440 + .allRequests()
4441 + .slice(compactionEnded)
4442 + .filter(
4443 + (request) =>
4444 + request["type"] === "prompt" && request["message"] === "Steer during compaction",
4445 + ).length,
4446 + 1,
4447 + );
4448 + assert.isTrue(
4449 + terminal.type === "turn.terminal" && terminal.status === "completed",
4450 + `turn ended ${terminal.type === "turn.terminal" ? terminal.status : terminal.type}`,
4451 + );
4452 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
4453 + );
4454 +
4455 it.effect("keeps working after a settle probe fails before detached compaction", () =>
4456 Effect.gen(function* () {
4457 const fake = yield* makeFakePi;
packages/provider-pi/src/server/adapter.ts
+100 -23
@@ -398,6 +398,15 @@ function piApprovalRequestKind(title: string): "command" | "file-change" {
398 : "command";
399 }
400
401 +/** Pi 1.4.0 rejects prompts with this when they race a compaction it already started. */
402 +const PI_COMPACTING_PROMPT_REJECTION = "Cannot submit a prompt while compaction is in progress";
403 +
404 +interface PiPromptSend {
405 + readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
406 + readonly kind: "turn_start" | "steer";
407 + readonly record: PiRpcRecord;
408 +}
409 +
410 interface PiThreadState {
411 providerThread: OrchestrationV2ProviderThread;
412 activeTurn: ActivePiTurn | null;
@@ -560,14 +569,30 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
569 const modelContextWindows = new Map<string, number>();
570 let modelsDiscovered = false;
571 // Prompt ACKs lack IDs; retain session send order and ownership so late ACKs cannot affect new turns.
563 - const pendingPromptResponses: Array<{
564 - readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
565 - readonly kind: "turn_start" | "steer";
566 - }> = [];
572 + const pendingPromptResponses: Array<PiPromptSend> = [];
573 const pendingCompactResponses: Array<{
574 readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
575 readonly kind: "turn_start" | "steer";
576 }> = [];
577 + // Pi rejects every prompt while it compacts, including compaction an
578 + // extension starts after the turn settled. Hold prompts until it ends.
579 + let nativeCompacting = false;
580 + const heldPrompts: Array<PiPromptSend> = [];
581 + // Prompts sent before the pump observed compaction_start are rejected
582 + // after it; they precede every prompt held since.
583 + let rejectedHeldCount = 0;
584 +
585 + const sendPrompt = Effect.fnUntraced(function* (prompt: PiPromptSend) {
586 + if (nativeCompacting) {
587 + heldPrompts.push(prompt);
588 + return;
589 + }
590 + yield* connection.send(prompt.record);
591 + pendingPromptResponses.push(prompt);
592 + });
593 + // A just-released prompt has not started its run yet, so a settle probe
594 + // racing it would see Pi idle. Its ack re-arms the probe instead.
595 + let releasedPromptTurnId: OrchestrationV2ProviderTurn["id"] | null = null;
596
597 const compactRpcRecord = (command: PiCompactCommand): PiRpcRecord =>
598 command.customInstructions === undefined
@@ -1835,7 +1860,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1860 if (result === null || result === undefined) {
1861 if (event["aborted"] === true) {
1862 yield* emitCompaction(turn, compaction, "cancelled");
1838 - if (turn.settleWhenIdle || !turn.sawAgentActivity) {
1863 + if (
1864 + (turn.settleWhenIdle || !turn.sawAgentActivity) &&
1865 + releasedPromptTurnId !== turn.providerTurn.id
1866 + ) {
1867 yield* scheduleSettleProbe(turn, turn.settleWhenIdle);
1868 }
1869 return;
@@ -1845,7 +1873,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1873 yield* emitCompaction(turn, compaction, "failed", {
1874 summary: errorMessage.slice(0, 1_000),
1875 });
1848 - if (turn.settleWhenIdle || !turn.sawAgentActivity) {
1876 + if (
1877 + (turn.settleWhenIdle || !turn.sawAgentActivity) &&
1878 + releasedPromptTurnId !== turn.providerTurn.id
1879 + ) {
1880 yield* scheduleSettleProbe(turn, turn.settleWhenIdle);
1881 }
1882 return;
@@ -1862,7 +1893,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1893 ...(beforeTokenCount === undefined ? {} : { beforeTokenCount }),
1894 ...(afterTokenCount === undefined ? {} : { afterTokenCount }),
1895 });
1865 - if (turn.settleWhenIdle || !turn.sawAgentActivity) {
1896 + if (
1897 + (turn.settleWhenIdle || !turn.sawAgentActivity) &&
1898 + releasedPromptTurnId !== turn.providerTurn.id
1899 + ) {
1900 yield* scheduleSettleProbe(turn, turn.settleWhenIdle);
1901 }
1902 return;
@@ -2012,6 +2046,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2046 const pendingPrompt = command === "prompt" ? pendingPromptResponses.shift() : undefined;
2047 const responseTurn =
2048 pendingPrompt?.providerTurnId === turn?.providerTurn.id ? turn : null;
2049 + if (
2050 + event["success"] === false &&
2051 + nativeCompacting &&
2052 + recordString(event, "error")?.startsWith(PI_COMPACTING_PROMPT_REJECTION) === true &&
2053 + pendingPrompt !== undefined &&
2054 + responseTurn !== null
2055 + ) {
2056 + heldPrompts.splice(rejectedHeldCount++, 0, pendingPrompt);
2057 + return;
2058 + }
2059 + // Settlement is not probed while a steer awaits its ack (see
2060 + // compaction_end); once Pi answers, the run it may have started is
2061 + // visible to get_state.
2062 + if (pendingPrompt?.kind === "steer" && responseTurn?.settleWhenIdle === true) {
2063 + yield* scheduleSettleProbe(responseTurn, true);
2064 + }
2065 if (event["success"] === true) {
2066 // Command-only prompts emit no agent_settled; probe idle and re-queue behind preceding native events.
2067 if (
@@ -2123,7 +2173,33 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2173 yield* Effect.gen(function* () {
2174 while (true) {
2175 const event = yield* Queue.take(connection.events);
2126 - yield* sessionEventPermit.withPermits(1)(handleSessionEvent(event));
2176 + yield* sessionEventPermit.withPermits(1)(
2177 + Effect.gen(function* () {
2178 + // Tracked here rather than in handleSessionEvent, which also
2179 + // replays buffered wake events after they were observed.
2180 + if (event["type"] === "compaction_start") nativeCompacting = true;
2181 + if (event["type"] === "compaction_end") {
2182 + nativeCompacting = false;
2183 + // Send before the handler can probe settlement, so Pi sees the
2184 + // prompt first. Prompts whose turn ended or is stopping are dropped.
2185 + rejectedHeldCount = 0;
2186 + for (const held of heldPrompts.splice(0)) {
2187 + const turn = threadState?.activeTurn;
2188 + if (
2189 + turn?.providerTurn.id !== held.providerTurnId ||
2190 + turn.interrupted ||
2191 + stopRequested
2192 + )
2193 + continue;
2194 + yield* sendPrompt(held);
2195 + releasedPromptTurnId = held.providerTurnId;
2196 + }
2197 + }
2198 + yield* handleSessionEvent(event).pipe(
2199 + Effect.ensuring(Effect.sync(() => (releasedPromptTurnId = null))),
2200 + );
2201 + }),
2202 + );
2203 }
2204 }).pipe(
2205 Effect.catchCause((cause) =>
@@ -2558,15 +2634,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2634 kind: "turn_start",
2635 });
2636 } else if (payload !== null) {
2561 - yield* connection.send({
2562 - type: "prompt",
2563 - message: payload.message,
2564 - streamingBehavior: "steer",
2565 - ...(payload.images.length === 0 ? {} : { images: payload.images }),
2566 - });
2567 - pendingPromptResponses.push({
2637 + yield* sendPrompt({
2638 providerTurnId: providerTurn.id,
2639 kind: "turn_start",
2640 + record: {
2641 + type: "prompt",
2642 + message: payload.message,
2643 + streamingBehavior: "steer",
2644 + ...(payload.images.length === 0 ? {} : { images: payload.images }),
2645 + },
2646 });
2647 }
2648 yield* emit({
@@ -2652,15 +2728,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2728 kind: "steer",
2729 });
2730 } else if (payload !== null) {
2655 - yield* connection.send({
2656 - type: "prompt",
2657 - message: payload.message,
2658 - streamingBehavior: "steer",
2659 - ...(payload.images.length === 0 ? {} : { images: payload.images }),
2660 - });
2661 - pendingPromptResponses.push({
2731 + yield* sendPrompt({
2732 providerTurnId: turn.providerTurn.id,
2733 kind: "steer",
2734 + record: {
2735 + type: "prompt",
2736 + message: payload.message,
2737 + streamingBehavior: "steer",
2738 + ...(payload.images.length === 0 ? {} : { images: payload.images }),
2739 + },
2740 });
2741 }
2742 turn.settleProbeGeneration += 1;
@@ -2696,7 +2772,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2772 interruptInput.requestRuntimeRestart === true ||
2773 turn.settleWhenIdle ||
2774 turn.activeCompaction !== null ||
2699 - turn.manualCompactInFlight
2775 + turn.manualCompactInFlight ||
2776 + nativeCompacting
2777 ) {
2778 // Generic abort misses manual compaction; terminate so Stop covers /compact and recovery.
2779 stopRequested = true;