The best way to control Claude Code, Codex and more from any computer or phone
fix(pi): settle prompts consumed by input handlers (#28798)
Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Sérgio Rebelo committed
Nov 12, 2026 at 23:00 UTC
f255158370ebd7509f92903589ad0abd6ebe40ec
3 files changed
+675
-142
apps/server/src/orchestration-v2/Adapters/PiAdapterV2.testkit.ts
+5
-2
@@ -113,7 +113,7 @@ function replayValueMatches(expected: unknown, actual: unknown): boolean {
113
return Object.is(expected, actual);
114
}
115
116
-const ADAPTER_REQUEST_ID = /^t3-\d+$/u;
116
+const ADAPTER_REQUEST_ID = /^t3-(?:prompt-)?\d+$/u;
117
118
function adapterRequestId(frame: unknown): string | undefined {
119
const id = isRecord(frame) ? frame.id : undefined;
@@ -123,7 +123,10 @@ function adapterRequestId(frame: unknown): string | undefined {
123
/** Rebind adapter request ids without pinning counters; provider ids that responses must echo stay exact. */
124
function withRequestId(expected: unknown, actual: unknown): unknown {
125
const actualId = adapterRequestId(actual);
126
- return isRecord(expected) && adapterRequestId(expected) !== undefined && actualId !== undefined
126
+ return isRecord(expected) &&
127
+ actualId !== undefined &&
128
+ (adapterRequestId(expected) !== undefined ||
129
+ (expected.type === "prompt" && expected.id === undefined))
130
? { ...expected, id: actualId }
131
: expected;
132
}
packages/provider-pi/src/server/adapter.test.ts
+494
-41
@@ -30,6 +30,7 @@ import * as Layer from "effect/Layer";
30
import * as Logger from "effect/Logger";
31
import * as Queue from "effect/Queue";
32
import * as Schema from "effect/Schema";
33
+import * as Scope from "effect/Scope";
34
import * as Sink from "effect/Sink";
35
import * as Stream from "effect/Stream";
36
import * as ChildProcess from "effect/process/ChildProcess";
@@ -67,6 +68,7 @@ const decodeUserInputQuestions = Schema.decodeUnknownSync(
68
Schema.Array(OrchestrationV2UserInputQuestion),
69
);
70
71
+const isProviderProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError);
72
const decodeJsonLine = Schema.decodeSync(Schema.fromJsonString(Schema.Unknown));
73
const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
74
@@ -167,7 +169,9 @@ interface FakePi {
169
readonly resolveDeferredState: (data: unknown) => Effect.Effect<void>;
170
readonly failNextState: () => void;
171
readonly failNextThinking: () => void;
170
- readonly deferNextLifecycle: (type: "switch_session" | "new_session" | "fork" | "abort") => void;
172
+ readonly deferNextLifecycle: (
173
+ type: "switch_session" | "new_session" | "fork" | "prompt" | "abort",
174
+ ) => void;
175
readonly deferNextModelSelection: () => void;
176
readonly queueModels: (models: ReadonlyArray<unknown>) => void;
177
readonly vetoNextNewSession: () => void;
@@ -823,6 +827,7 @@ describe("PiAdapterV2", () => {
827
statusText: "Watching 3 files",
828
});
829
const command = failure === "failed compact" ? "compact" : "prompt";
830
+ if (failure === "rejected prompt") fake.deferNextLifecycle("prompt");
831
yield* startTurn(
832
runtime,
833
providerThread,
@@ -1307,6 +1312,7 @@ describe("PiAdapterV2", () => {
1312
yield* Queue.take(offers);
1313
yield* fake.emit({ type: "agent_settled" });
1314
yield* fake.emit({ type: "compaction_start", reason: "manual" });
1315
+ fake.deferNextLifecycle("prompt");
1316
yield* startTurn(runtime, providerThread);
1317
yield* fake.emit({
1318
type: "extension_ui_request",
@@ -1645,6 +1651,7 @@ describe("PiAdapterV2", () => {
1651
event.type === "provider_session.updated" && event.providerSession.status === "ready",
1652
);
1653
}
1654
+ fake.deferNextLifecycle("prompt");
1655
yield* startTurn(runtime, providerThread);
1656
const prompt = yield* fake.takeRequest("prompt");
1657
assert.equal(prompt["message"], "Hello pi");
@@ -1718,6 +1725,7 @@ describe("PiAdapterV2", () => {
1725
});
1726
yield* fake.emit({ type: "agent_start" });
1727
yield* Queue.take(offers);
1728
+ fake.deferNextLifecycle("prompt");
1729
yield* startTurn(runtime, providerThread);
1730
yield* fake.takeRequest("prompt");
1731
yield* fake.emit({ type: "agent_settled", aborted });
@@ -1773,6 +1781,7 @@ describe("PiAdapterV2", () => {
1781
(event) =>
1782
event.type === "provider_session.updated" && event.providerSession.status === "ready",
1783
);
1784
+ fake.deferNextLifecycle("prompt");
1785
yield* startTurn(runtime, providerThread, "default", [], "/hello");
1786
yield* fake.takeRequest("prompt");
1787
if (resumes) yield* fake.emit({ type: "agent_start" });
@@ -3772,7 +3781,83 @@ describe("PiAdapterV2", () => {
3781
}).pipe(Effect.scoped, Effect.provide(layerTest)),
3782
);
3783
3775
- it.effect("settles a command-only prompt from its deferred ack and idle probe", () =>
3784
+ it.effect.each([
3785
+ { first: "initial", accepted: true },
3786
+ { first: "steer", accepted: true },
3787
+ { first: "steer", accepted: false },
3788
+ ])(
3789
+ "waits for consumed input acknowledgments, first=$first accepted=$accepted",
3790
+ ({ first, accepted }) =>
3791
+ Effect.gen(function* () {
3792
+ const fake = yield* makeFakePi;
3793
+ const { runtime, takeEvent } = yield* openRuntime(fake);
3794
+ const providerThread = yield* runtime.ensureThread({
3795
+ threadId: THREAD_ID,
3796
+ modelSelection: modelSelection("default"),
3797
+ runtimePolicy,
3798
+ });
3799
+ fake.deferNextLifecycle("prompt");
3800
+ yield* startTurn(runtime, providerThread);
3801
+ const initial = yield* fake.takeRequest("prompt");
3802
+ fake.deferNextLifecycle("prompt");
3803
+ const running = yield* takeEvent((event) => event.type === "provider_turn.updated");
3804
+ assert.isTrue(running.type === "provider_turn.updated");
3805
+ if (running.type !== "provider_turn.updated") return;
3806
+ yield* runtime.steerTurn({
3807
+ threadId: THREAD_ID,
3808
+ runId: RunId.make("run:thread-pi-test:1"),
3809
+ providerThread,
3810
+ providerTurnId: running.providerTurn.id,
3811
+ message: {
3812
+ messageId: "message:handled-steer-first" as never,
3813
+ text: "Consumed steer",
3814
+ attachments: [],
3815
+ createdBy: "user",
3816
+ creationSource: "web",
3817
+ },
3818
+ });
3819
+ const steer = yield* fake.takeRequest("prompt");
3820
+ const stateRequests = fake
3821
+ .allRequests()
3822
+ .filter((request) => request["type"] === "get_state").length;
3823
+ yield* fake.emit({
3824
+ type: "response",
3825
+ id: (first === "steer" ? steer : initial)["id"],
3826
+ command: "prompt",
3827
+ success: accepted,
3828
+ data: { disposition: "handled" },
3829
+ error: accepted ? undefined : "Input refused",
3830
+ });
3831
+ yield* fake.emit({
3832
+ type: "extension_ui_request",
3833
+ method: "notify",
3834
+ message: "Steer acknowledged",
3835
+ });
3836
+ yield* takeEvent(
3837
+ (event) => event.type === "turn_item.updated" && event.turnItem.type === "system_notice",
3838
+ );
3839
+ assert.equal(runtime.providerSession.status, "running");
3840
+ assert.equal(
3841
+ fake.allRequests().filter((request) => request["type"] === "get_state").length,
3842
+ stateRequests,
3843
+ );
3844
+ yield* fake.emit({
3845
+ type: "response",
3846
+ id: (first === "steer" ? initial : steer)["id"],
3847
+ command: "prompt",
3848
+ success: true,
3849
+ data: { disposition: "handled" },
3850
+ });
3851
+ const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
3852
+ assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed");
3853
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
3854
+ );
3855
+
3856
+ it.effect.each([
3857
+ { text: "/command-only", data: undefined, compacts: false },
3858
+ { text: "Plain handled input", data: { disposition: "handled" }, compacts: false },
3859
+ { text: "Handled input after compaction", data: { disposition: "handled" }, compacts: true },
3860
+ ])("settles consumed input after its ack: $text", ({ text, data, compacts }) =>
3861
Effect.gen(function* () {
3862
const fake = yield* makeFakePi;
3863
const { runtime, takeEvent } = yield* openRuntime(fake);
@@ -3781,8 +3866,27 @@ describe("PiAdapterV2", () => {
3866
modelSelection: modelSelection("default"),
3867
runtimePolicy,
3868
});
3784
- yield* startTurn(runtime, providerThread, "default", [], "/command-only");
3869
+ if (compacts) yield* fake.takeRequest("get_state");
3870
+ fake.deferNextLifecycle("prompt");
3871
+ yield* startTurn(runtime, providerThread, "default", [], text);
3872
yield* fake.takeRequest("prompt");
3873
+ if (compacts) {
3874
+ yield* fake.emit({ type: "compaction_start", reason: "manual" });
3875
+ yield* fake.emit({
3876
+ type: "compaction_end",
3877
+ reason: "manual",
3878
+ result: { summary: "Smaller context", tokensBefore: 1000, estimatedTokensAfter: 100 },
3879
+ aborted: false,
3880
+ willRetry: false,
3881
+ });
3882
+ yield* takeEvent(
3883
+ (event) =>
3884
+ event.type === "turn_item.updated" &&
3885
+ event.turnItem.type === "compaction" &&
3886
+ event.turnItem.status === "completed",
3887
+ );
3888
+ yield* fake.takeRequest("get_state");
3889
+ }
3890
yield* fake.emit({
3891
type: "extension_ui_request",
3892
id: "ui-cmd",
@@ -3790,7 +3894,6 @@ describe("PiAdapterV2", () => {
3894
message: "Command finished\nwith details",
3895
notifyType: "info",
3896
});
3793
- yield* fake.emit({ type: "response", command: "prompt", success: true });
3897
const notice = yield* takeEvent(
3898
(event) =>
3899
(event.type === "turn_item.updated" && event.turnItem.type === "system_notice") ||
@@ -3802,6 +3905,8 @@ describe("PiAdapterV2", () => {
3905
notice.turnItem.status === "completed" &&
3906
notice.turnItem.message === "Command finished\nwith details",
3907
);
3908
+ assert.equal(runtime.providerSession.status, "running");
3909
+ yield* fake.emit({ type: "response", command: "prompt", success: true, data });
3910
const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
3911
assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed");
3912
}).pipe(Effect.scoped, Effect.provide(layerTest)),
@@ -4403,37 +4508,300 @@ describe("PiAdapterV2", () => {
4508
}).pipe(Effect.scoped, Effect.provide(layerTest)),
4509
);
4510
4406
- it.effect("keeps a settled turn's late prompt rejection off the next turn", () =>
4407
- Effect.gen(function* () {
4408
- const fake = yield* makeFakePi;
4409
- const { runtime, takeEvent } = yield* openRuntime(fake);
4410
- const providerThread = yield* runtime.ensureThread({
4411
- threadId: THREAD_ID,
4412
- modelSelection: modelSelection("default"),
4413
- runtimePolicy,
4414
- });
4415
- yield* startTurn(runtime, providerThread, "default", [], "/my-command");
4416
- yield* fake.takeRequest("prompt");
4417
- yield* fake.emit({ type: "agent_start" });
4418
- yield* fake.emit({ type: "agent_settled" });
4419
- const firstTerminal = yield* takeEvent((event) => event.type === "turn.terminal");
4420
- assert.isTrue(firstTerminal.type === "turn.terminal" && firstTerminal.status === "completed");
4511
+ it.effect.each(["settled", "outer-id", "outer-idless", "install-id", "install-idless"])(
4512
+ "waits for a settled turn's late prompt ACK before accepting the next turn: %s",
4513
+ (boundary) =>
4514
+ Effect.gen(function* () {
4515
+ const fake = yield* makeFakePi;
4516
+ const { runtime, takeEvent } = yield* openRuntime(fake);
4517
+ const providerThread = yield* runtime.ensureThread({
4518
+ threadId: THREAD_ID,
4519
+ modelSelection: modelSelection("default"),
4520
+ runtimePolicy,
4521
+ });
4522
+ const interrupted = boundary !== "settled";
4523
+ const atInstall = boundary.startsWith("install-");
4524
+ // Suspend the next start before another turn acquires and releases ownership.
4525
+ if (atInstall) fake.deferNextModelSelection();
4526
+ let next = atInstall
4527
+ ? yield* startTurn(
4528
+ runtime,
4529
+ providerThread,
4530
+ "default",
4531
+ [],
4532
+ "Second turn",
4533
+ modelSelection("xai/grok-4.6"),
4534
+ 2,
4535
+ ).pipe(Effect.result, Effect.forkScoped)
4536
+ : null;
4537
+ const modelRequest = atInstall ? yield* fake.takeRequest("set_model") : null;
4538
+ if (interrupted) fake.deferNextLifecycle("prompt");
4539
+ yield* startTurn(runtime, providerThread, "default", [], "/my-command");
4540
+ const firstPrompt = yield* fake.takeRequest("prompt");
4541
+ const running = yield* takeEvent((event) => event.type === "provider_turn.updated");
4542
+ assert.isTrue(running.type === "provider_turn.updated");
4543
+ if (running.type !== "provider_turn.updated") return;
4544
+ if (interrupted) {
4545
+ const active = yield* startTurn(runtime, providerThread).pipe(Effect.result);
4546
+ assert.isTrue(
4547
+ active._tag === "Failure" &&
4548
+ isProviderProtocolError(active.failure.cause) &&
4549
+ active.failure.cause.reason === "previous_turn_active",
4550
+ );
4551
+ fake.deferNextLifecycle("prompt");
4552
+ yield* runtime.steerTurn({
4553
+ providerThread,
4554
+ providerTurnId: running.providerTurn.id,
4555
+ threadId: THREAD_ID,
4556
+ runId: RunId.make("run:thread-pi-test:1"),
4557
+ message: {
4558
+ messageId: "message:old-steer" as never,
4559
+ text: "Old steer",
4560
+ attachments: [],
4561
+ createdBy: "user",
4562
+ creationSource: "web",
4563
+ },
4564
+ });
4565
+ yield* fake.takeRequest("prompt");
4566
+ yield* fake.emit({
4567
+ type: "extension_ui_request",
4568
+ id: "old-dialog",
4569
+ method: "confirm",
4570
+ title: "Old dialog",
4571
+ });
4572
+ yield* takeEvent(
4573
+ (event) =>
4574
+ event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
4575
+ );
4576
+ yield* runtime.interruptTurn({ providerThread, providerTurnId: running.providerTurn.id });
4577
+ } else {
4578
+ yield* fake.emit({ type: "agent_start" });
4579
+ }
4580
+ yield* fake.emit({ type: "agent_settled" });
4581
+ const firstTerminal = yield* takeEvent((event) => event.type === "turn.terminal");
4582
+ assert.isTrue(
4583
+ firstTerminal.type === "turn.terminal" &&
4584
+ firstTerminal.status === (interrupted ? "interrupted" : "completed"),
4585
+ );
4586
4422
- yield* startTurn(runtime, providerThread, "default", [], "Second turn", undefined, 2);
4423
- yield* fake.takeRequest("prompt");
4424
- yield* fake.emit({
4425
- type: "response",
4426
- command: "prompt",
4427
- success: false,
4428
- error: "late command rejection",
4429
- });
4430
- yield* fake.emit({ type: "agent_start" });
4431
- yield* fake.emit({ type: "agent_settled" });
4432
- const secondTerminal = yield* takeEvent((event) => event.type === "turn.terminal");
4433
- assert.isTrue(
4434
- secondTerminal.type === "turn.terminal" && secondTerminal.status === "completed",
4435
- );
4436
- }).pipe(Effect.scoped, Effect.provide(layerTest)),
4587
+ fake.deferNextLifecycle("prompt");
4588
+ if (next === null) {
4589
+ next = yield* startTurn(
4590
+ runtime,
4591
+ providerThread,
4592
+ "default",
4593
+ [],
4594
+ "Second turn",
4595
+ undefined,
4596
+ 2,
4597
+ ).pipe(Effect.result, Effect.forkScoped({ startImmediately: true }));
4598
+ }
4599
+ if (modelRequest !== null) {
4600
+ yield* fake.emit({
4601
+ type: "response",
4602
+ id: modelRequest["id"],
4603
+ command: "set_model",
4604
+ success: true,
4605
+ data: { provider: "xai", id: "grok-4.6" },
4606
+ });
4607
+ }
4608
+ if (interrupted) {
4609
+ yield* fake.emit({
4610
+ type: "extension_ui_request",
4611
+ id: "old-ack-barrier",
4612
+ method: "confirm",
4613
+ title: "Old input acknowledged",
4614
+ });
4615
+ const barrier = yield* takeEvent((event) => event.type === "runtime_request.updated");
4616
+ assert.isTrue(barrier.type === "runtime_request.updated");
4617
+ if (barrier.type !== "runtime_request.updated") return;
4618
+ yield* runtime.respondToRuntimeRequest({
4619
+ requestId: barrier.runtimeRequest.id,
4620
+ decision: "decline",
4621
+ });
4622
+ yield* fake.takeRequest("extension_ui_response");
4623
+ assert.isUndefined(next.pollUnsafe());
4624
+ assert.lengthOf(
4625
+ fake.allRequests().filter((request) => request["type"] === "prompt"),
4626
+ 2,
4627
+ );
4628
+ yield* fake.emit({
4629
+ type: "response",
4630
+ command: "prompt",
4631
+ success: false,
4632
+ ...(boundary.endsWith("idless") ? {} : { id: firstPrompt["id"] }),
4633
+ error: "late command rejection",
4634
+ });
4635
+ // Duplicate and unknown IDs cannot consume the remaining old steer.
4636
+ for (const id of [firstPrompt["id"], "unknown-prompt"]) {
4637
+ yield* fake.emit({ type: "response", id, command: "prompt", success: true });
4638
+ }
4639
+ yield* fake.emit({
4640
+ type: "extension_ui_request",
4641
+ id: "partial-ack-barrier",
4642
+ method: "confirm",
4643
+ title: "Partial ACK",
4644
+ });
4645
+ const partial = yield* takeEvent(
4646
+ (event) =>
4647
+ event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
4648
+ );
4649
+ assert.isTrue(partial.type === "runtime_request.updated");
4650
+ assert.isUndefined(next.pollUnsafe());
4651
+ assert.lengthOf(
4652
+ fake.allRequests().filter((request) => request["type"] === "prompt"),
4653
+ 2,
4654
+ );
4655
+ yield* fake.emit({ type: "response", command: "prompt", success: true });
4656
+ }
4657
+ assert.equal((yield* Fiber.join(next))._tag, "Success");
4658
+ yield* fake.takeRequest("prompt");
4659
+ yield* fake.emit({
4660
+ type: "response",
4661
+ id: firstPrompt["id"],
4662
+ command: "prompt",
4663
+ success: false,
4664
+ error: "late command rejection",
4665
+ });
4666
+ yield* fake.emit({ type: "response", command: "prompt", success: true });
4667
+ yield* fake.emit({ type: "agent_start" });
4668
+ yield* fake.emit({ type: "agent_settled" });
4669
+ const secondTerminal = yield* takeEvent((event) => event.type === "turn.terminal");
4670
+ assert.isTrue(
4671
+ secondTerminal.type === "turn.terminal" && secondTerminal.status === "completed",
4672
+ );
4673
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
4674
+ );
4675
+
4676
+ it.effect.each([
4677
+ { boundary: "outer", end: "session" },
4678
+ { boundary: "outer", end: "transport" },
4679
+ { boundary: "outer", end: "caller" },
4680
+ { boundary: "install", end: "session" },
4681
+ { boundary: "install", end: "transport" },
4682
+ { boundary: "install", end: "caller" },
4683
+ ])(
4684
+ "settles an ACK-blocked start on $end cancellation at $boundary admission",
4685
+ ({ boundary, end }) =>
4686
+ Effect.gen(function* () {
4687
+ const fake = yield* makeFakePi;
4688
+ const runtimeScope = yield* Scope.make();
4689
+ yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void));
4690
+ const { runtime, takeEvent } = yield* openRuntime(fake).pipe(Scope.provide(runtimeScope));
4691
+ const providerThread = yield* runtime.ensureThread({
4692
+ threadId: THREAD_ID,
4693
+ modelSelection: modelSelection("default"),
4694
+ runtimePolicy,
4695
+ });
4696
+ if (boundary === "install") fake.deferNextModelSelection();
4697
+ let next =
4698
+ boundary === "install"
4699
+ ? yield* startTurn(
4700
+ runtime,
4701
+ providerThread,
4702
+ "default",
4703
+ [],
4704
+ "Second turn",
4705
+ modelSelection("xai/grok-4.6"),
4706
+ 2,
4707
+ ).pipe(Effect.result, Effect.forkScoped({ startImmediately: true }))
4708
+ : null;
4709
+ const modelRequest = next === null ? null : yield* fake.takeRequest("set_model");
4710
+ fake.deferNextLifecycle("prompt");
4711
+ yield* startTurn(runtime, providerThread);
4712
+ const oldPrompt = yield* fake.takeRequest("prompt");
4713
+ const running = yield* takeEvent((event) => event.type === "provider_turn.updated");
4714
+ assert.isTrue(running.type === "provider_turn.updated");
4715
+ if (running.type !== "provider_turn.updated") return;
4716
+ yield* runtime.interruptTurn({ providerThread, providerTurnId: running.providerTurn.id });
4717
+ yield* fake.emit({ type: "agent_settled" });
4718
+ yield* takeEvent((event) => event.type === "turn.terminal");
4719
+ if (next === null) {
4720
+ next = yield* startTurn(
4721
+ runtime,
4722
+ providerThread,
4723
+ "default",
4724
+ [],
4725
+ "Second turn",
4726
+ undefined,
4727
+ 2,
4728
+ ).pipe(Effect.result, Effect.forkScoped({ startImmediately: true }));
4729
+ }
4730
+ if (modelRequest !== null) {
4731
+ yield* fake.emit({
4732
+ type: "response",
4733
+ id: modelRequest["id"],
4734
+ command: "set_model",
4735
+ success: true,
4736
+ data: { provider: "xai", id: "grok-4.6" },
4737
+ });
4738
+ }
4739
+ yield* fake.emit({
4740
+ type: "extension_ui_request",
4741
+ id: "lifecycle-barrier",
4742
+ method: "confirm",
4743
+ title: "Pending ACK",
4744
+ });
4745
+ const dialog = yield* takeEvent(
4746
+ (event) =>
4747
+ event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
4748
+ );
4749
+ assert.isTrue(dialog.type === "runtime_request.updated");
4750
+ assert.isUndefined(next.pollUnsafe());
4751
+ assert.lengthOf(
4752
+ fake.allRequests().filter((request) => request["type"] === "prompt"),
4753
+ 1,
4754
+ );
4755
+ if (end === "caller") {
4756
+ yield* Fiber.interrupt(next);
4757
+ assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(next)));
4758
+ const replacement = yield* startTurn(
4759
+ runtime,
4760
+ providerThread,
4761
+ "default",
4762
+ [],
4763
+ "Replacement",
4764
+ undefined,
4765
+ 3,
4766
+ ).pipe(Effect.result, Effect.forkScoped({ startImmediately: true }));
4767
+ assert.isUndefined(replacement.pollUnsafe());
4768
+ assert.lengthOf(
4769
+ fake.allRequests().filter((request) => request["type"] === "prompt"),
4770
+ 1,
4771
+ );
4772
+ yield* fake.emit({
4773
+ type: "response",
4774
+ id: oldPrompt["id"],
4775
+ command: "prompt",
4776
+ success: true,
4777
+ });
4778
+ assert.equal((yield* Fiber.join(replacement))._tag, "Success");
4779
+ yield* fake.takeRequest("prompt");
4780
+ yield* fake.emit({ type: "agent_start" });
4781
+ yield* fake.emit({ type: "agent_settled" });
4782
+ const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
4783
+ assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed");
4784
+ } else {
4785
+ if (end === "session") yield* Scope.close(runtimeScope, Exit.void);
4786
+ else yield* fake.closeStdout;
4787
+ const failed = yield* Fiber.join(next);
4788
+ assert.isTrue(failed._tag === "Failure" && isProviderProtocolError(failed.failure.cause));
4789
+ yield* fake.emit({
4790
+ type: "response",
4791
+ id: oldPrompt["id"],
4792
+ command: "prompt",
4793
+ success: true,
4794
+ });
4795
+ assert.equal(
4796
+ (yield* startTurn(runtime, providerThread).pipe(Effect.result))._tag,
4797
+ "Failure",
4798
+ );
4799
+ assert.lengthOf(
4800
+ fake.allRequests().filter((request) => request["type"] === "prompt"),
4801
+ 1,
4802
+ );
4803
+ }
4804
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
4805
);
4806
4807
it.effect("shows compaction progress and completes the same activity row", () =>
@@ -5064,6 +5432,7 @@ describe("PiAdapterV2", () => {
5432
yield* fake.takeRequest("get_state");
5433
yield* takeEvent((event) => event.type === "turn.terminal");
5434
5435
+ fake.deferNextLifecycle("prompt");
5436
yield* startTurn(runtime, providerThread, "default", [], "Raced compaction", undefined, 2);
5437
yield* fake.takeRequest("prompt");
5438
yield* fake.emit({ type: "compaction_start", reason: "manual" });
@@ -5402,7 +5771,18 @@ describe("PiAdapterV2", () => {
5771
}).pipe(Effect.scoped, Effect.provide(layerTest)),
5772
);
5773
5405
- it.effect("ignores an idle snapshot made stale by a steer", () =>
5774
+ it.effect.each([
5775
+ { handled: false, steer: "starts" },
5776
+ { handled: true, steer: "starts" },
5777
+ { handled: true, steer: "handled" },
5778
+ { handled: true, steer: "rejected" },
5779
+ { handled: true, steer: "compact-accepted" },
5780
+ { handled: true, steer: "compact-rejected" },
5781
+ { handled: false, steer: "compact-accepted" },
5782
+ { handled: false, steer: "compact-rejected" },
5783
+ { handled: true, steer: "compact-queued-accepted" },
5784
+ { handled: true, steer: "compact-queued-rejected" },
5785
+ ])("ignores stale idle probes, handled=$handled steer=$steer", ({ handled, steer }) =>
5786
Effect.gen(function* () {
5787
const fake = yield* makeFakePi;
5788
const { runtime, takeEvent } = yield* openRuntime(fake);
@@ -5411,6 +5791,7 @@ describe("PiAdapterV2", () => {
5791
modelSelection: modelSelection("default"),
5792
runtimePolicy,
5793
});
5794
+ if (handled) fake.deferNextLifecycle("prompt");
5795
yield* startTurn(runtime, providerThread);
5796
yield* fake.takeRequest("prompt");
5797
const running = yield* takeEvent(
@@ -5421,30 +5802,95 @@ describe("PiAdapterV2", () => {
5802
const providerTurnId =
5803
running.type === "provider_turn.updated" ? running.providerTurn.id : undefined;
5804
assert.isDefined(providerTurnId);
5424
- yield* fake.emit({ type: "agent_start" });
5805
+ if (!handled) yield* fake.emit({ type: "agent_start" });
5806
5807
fake.deferNextState();
5427
- yield* fake.emit({ type: "agent_settled" });
5808
+ yield* fake.emit(
5809
+ handled
5810
+ ? {
5811
+ type: "response",
5812
+ command: "prompt",
5813
+ success: true,
5814
+ data: { disposition: "handled" },
5815
+ }
5816
+ : { type: "agent_settled" },
5817
+ );
5818
yield* fake.takeRequest("get_state");
5429
- yield* runtime.steerTurn({
5819
+ const compact = steer.startsWith("compact-");
5820
+ fake.deferNextLifecycle("prompt");
5821
+ const steerInput = {
5822
threadId: THREAD_ID,
5823
runId: RunId.make("run:thread-pi-test:1"),
5824
providerThread,
5825
providerTurnId: providerTurnId!,
5826
message: {
5827
messageId: "message:thread-pi-test:late-steer" as never,
5436
- text: "Continue after settlement",
5828
+ text: compact ? "/compact" : "Continue after settlement",
5829
attachments: [],
5830
createdBy: "user",
5831
creationSource: "web",
5832
},
5441
- });
5442
- yield* fake.takeRequest("prompt");
5833
+ } satisfies ProviderAdapter.ProviderAdapterV2SteerInput;
5834
+ yield* runtime.steerTurn(steerInput);
5835
+ const steeredPrompt = yield* fake.takeRequest(compact ? "compact" : "prompt");
5836
yield* fake.resolveDeferredState({
5837
isStreaming: false,
5838
isCompacting: false,
5839
pendingMessageCount: 0,
5840
});
5841
+ if (compact) {
5842
+ if (steer.startsWith("compact-queued-")) {
5843
+ yield* runtime.steerTurn(steerInput);
5844
+ yield* fake.takeRequest("compact");
5845
+ // Put a current probe before a notice in the pump, independent of fork scheduling.
5846
+ for (const acknowledged of [false, true]) {
5847
+ if (acknowledged) {
5848
+ yield* fake.emit({ type: "response", command: "compact", success: true });
5849
+ yield* fake.takeRequest("get_state");
5850
+ }
5851
+ yield* fake.emit({
5852
+ type: "t3.settle_probe",
5853
+ providerTurnId,
5854
+ settleProbeGeneration: 2,
5855
+ data: { isStreaming: false, isCompacting: false, pendingMessageCount: 0 },
5856
+ });
5857
+ yield* fake.emit({
5858
+ type: "extension_ui_request",
5859
+ method: "notify",
5860
+ message: "Compact acknowledgment still pending",
5861
+ });
5862
+ const barrier = yield* takeEvent(
5863
+ (event) =>
5864
+ event.type === "turn.terminal" ||
5865
+ (event.type === "turn_item.updated" && event.turnItem.type === "system_notice"),
5866
+ );
5867
+ assert.equal(barrier.type, "turn_item.updated");
5868
+ assert.equal(runtime.providerSession.status, "running");
5869
+ }
5870
+ }
5871
+ yield* fake.emit({
5872
+ type: "response",
5873
+ command: "compact",
5874
+ success: !steer.endsWith("rejected"),
5875
+ error: "Compact refused",
5876
+ });
5877
+ const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
5878
+ assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed");
5879
+ return;
5880
+ }
5881
+ if (steer !== "starts") {
5882
+ yield* fake.emit({
5883
+ type: "response",
5884
+ id: steeredPrompt["id"],
5885
+ command: "prompt",
5886
+ success: steer === "handled",
5887
+ data: { disposition: "handled" },
5888
+ error: steer === "rejected" ? "Input refused" : undefined,
5889
+ });
5890
+ const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
5891
+ assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed");
5892
+ return;
5893
+ }
5894
5895
yield* fake.emit({ type: "agent_start" });
5896
yield* fake.emit({ type: "message_start", message: { role: "assistant" } });
@@ -5472,6 +5918,13 @@ describe("PiAdapterV2", () => {
5918
assistantItem.turnItem.text === "Recovered",
5919
);
5920
5921
+ yield* fake.emit({
5922
+ type: "response",
5923
+ id: steeredPrompt["id"],
5924
+ command: "prompt",
5925
+ success: true,
5926
+ data: { disposition: "started" },
5927
+ });
5928
fake.queueState({ isStreaming: false, isCompacting: false, pendingMessageCount: 0 });
5929
yield* fake.emit({ type: "agent_settled" });
5930
yield* fake.takeRequest("get_state");
packages/provider-pi/src/server/adapter.ts
+176
-99
@@ -363,7 +363,7 @@ interface ActivePiTurn {
363
nativeAborted: boolean;
364
sawAgentActivity: boolean;
365
adoptedWake: boolean;
366
- readonly promptMayBeCommandOnly: boolean;
366
+ promptMayBeCommandOnly: boolean;
367
latestCompactionAfterTokens: number | null;
368
lastLiveUsedTokens: number | null;
369
settleProbeGeneration: number;
@@ -563,12 +563,21 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
563
void,
564
ProviderAdapter.ProviderAdapterProtocolError
565
> | null = null;
566
+ let pendingPromptResponsesDrained: Deferred.Deferred<
567
+ void,
568
+ ProviderAdapter.ProviderAdapterProtocolError
569
+ > | null = null;
570
let closed = false;
571
yield* Effect.addFinalizer(() =>
572
Effect.gen(function* () {
573
closed = true;
574
sessionEntity = { ...sessionEntity, extensionStatuses: [] };
575
pendingWake = null;
576
+ if (pendingPromptResponsesDrained !== null)
577
+ yield* Deferred.fail(
578
+ pendingPromptResponsesDrained,
579
+ protocolError("Pi session closed while awaiting prompt acknowledgment"),
580
+ );
581
if (extensionStatusReset !== null)
582
yield* Deferred.fail(
583
extensionStatusReset.ready,
@@ -597,8 +606,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
606
let contextWindow: number | null = null;
607
const modelContextWindows = new Map<string, number>();
608
let discoveredModels: ReadonlyArray<unknown> | null = null;
600
- // Prompt ACKs lack IDs; retain session send order and ownership so late ACKs cannot affect new turns.
601
- const pendingPromptResponses: Array<PiPromptSend> = [];
609
+ let nextPromptId = 0;
610
+ const pendingPromptResponses: Array<PiPromptSend & { readonly id: string }> = [];
611
const pendingCompactResponses: Array<{
612
readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
613
readonly kind: "turn_start" | "steer";
@@ -616,8 +625,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
625
heldPrompts.push(prompt);
626
return;
627
}
619
- yield* connection.send(prompt.record);
620
- pendingPromptResponses.push(prompt);
628
+ const id = `t3-prompt-${nextPromptId++}`;
629
+ yield* connection.send({ ...prompt.record, id });
630
+ pendingPromptResponsesDrained ??= yield* Deferred.make<
631
+ void,
632
+ ProviderAdapter.ProviderAdapterProtocolError
633
+ >();
634
+ pendingPromptResponses.push({ ...prompt, id });
635
});
636
// A just-released prompt has not started its run yet, so a settle probe
637
// racing it would see Pi idle. Its ack re-arms the probe instead.
@@ -2215,12 +2229,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2229
if (compactTurn !== null) compactTurn.manualCompactInFlight = false;
2230
if (event["success"] === true) {
2231
if (
2218
- pendingCompact?.kind === "turn_start" &&
2232
compactTurn !== null &&
2220
- compactTurn.promptMayBeCommandOnly &&
2221
- !compactTurn.sawAgentActivity
2233
+ (compactTurn.settleWhenIdle ||
2234
+ (compactTurn.promptMayBeCommandOnly && !compactTurn.sawAgentActivity))
2235
) {
2223
- yield* scheduleSettleProbe(compactTurn);
2236
+ yield* scheduleSettleProbe(compactTurn, compactTurn.settleWhenIdle);
2237
}
2238
return;
2239
}
@@ -2231,6 +2244,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2244
yield* Effect.logWarning("Pi rejected a compact steer.", {
2245
errorLength: recordString(event, "error")?.length,
2246
});
2247
+ if (
2248
+ compactTurn.settleWhenIdle ||
2249
+ (compactTurn.promptMayBeCommandOnly && !compactTurn.sawAgentActivity)
2250
+ ) {
2251
+ yield* scheduleSettleProbe(compactTurn, compactTurn.settleWhenIdle);
2252
+ }
2253
return;
2254
}
2255
if (!compactTurn.sawCompaction) {
@@ -2246,9 +2265,23 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2265
}
2266
return;
2267
}
2249
- // Only id-less prompts own ACK slots; a late reply to an id-bearing request must not take one.
2250
- if (command === "prompt" && typeof event["id"] === "string") return;
2251
- const pendingPrompt = command === "prompt" ? pendingPromptResponses.shift() : undefined;
2268
+ const responseId = recordString(event, "id");
2269
+ const promptIndex =
2270
+ command !== "prompt"
2271
+ ? -1
2272
+ : responseId === undefined
2273
+ ? 0
2274
+ : pendingPromptResponses.findIndex((pending) => pending.id === responseId);
2275
+ const pendingPrompt =
2276
+ promptIndex < 0 ? undefined : pendingPromptResponses.splice(promptIndex, 1)[0];
2277
+ if (
2278
+ pendingPrompt !== undefined &&
2279
+ pendingPromptResponses.length === 0 &&
2280
+ pendingPromptResponsesDrained !== null
2281
+ ) {
2282
+ yield* Deferred.succeed(pendingPromptResponsesDrained, undefined);
2283
+ pendingPromptResponsesDrained = null;
2284
+ }
2285
const responseTurn =
2286
pendingPrompt?.providerTurnId === turn?.providerTurn.id ? turn : null;
2287
if (
@@ -2261,12 +2294,21 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2294
heldPrompts.splice(rejectedHeldCount++, 0, pendingPrompt);
2295
return;
2296
}
2264
- // Settlement is not probed while a steer awaits its ack (see
2265
- // compaction_end); once Pi answers, the run it may have started is
2266
- // visible to get_state.
2267
- if (pendingPrompt?.kind === "steer" && responseTurn?.settleWhenIdle === true) {
2268
- yield* scheduleSettleProbe(responseTurn, true);
2297
+ if (
2298
+ event["success"] === true &&
2299
+ pendingPrompt?.kind === "turn_start" &&
2300
+ responseTurn !== null &&
2301
+ recordString(event["data"], "disposition") === "handled"
2302
+ ) {
2303
+ responseTurn.promptMayBeCommandOnly = true;
2304
}
2305
+ const consumedInputIsIdleCandidate =
2306
+ responseTurn !== null &&
2307
+ (responseTurn.settleWhenIdle ||
2308
+ (responseTurn.promptMayBeCommandOnly && !responseTurn.sawAgentActivity)) &&
2309
+ !pendingPromptResponses.some(
2310
+ (pending) => pending.providerTurnId === responseTurn.providerTurn.id,
2311
+ );
2312
if (event["success"] === true) {
2313
if (
2314
pendingPrompt?.messageId !== undefined &&
@@ -2276,15 +2318,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2318
responseTurn.unreadSteers.push(pendingPrompt.messageId);
2319
yield* emitSteerStatus(responseTurn, pendingPrompt.messageId, "pending");
2320
}
2279
- // Command-only prompts emit no agent_settled; probe idle and re-queue behind preceding native events.
2321
+ // Consumed input may emit no agent_settled; probe idle behind preceding native events.
2322
if (
2281
- pendingPrompt?.kind === "turn_start" &&
2323
responseTurn !== null &&
2283
- ((responseTurn.promptMayBeCommandOnly && !responseTurn.sawAgentActivity) ||
2284
- (responseTurn.adoptedWake &&
2324
+ (consumedInputIsIdleCandidate ||
2325
+ (pendingPrompt?.kind === "turn_start" &&
2326
+ responseTurn.adoptedWake &&
2327
(responseTurn.settleWhenIdle || responseTurn.promptMayBeCommandOnly)))
2328
) {
2287
- yield* scheduleSettleProbe(responseTurn, responseTurn.adoptedWake);
2329
+ yield* scheduleSettleProbe(
2330
+ responseTurn,
2331
+ responseTurn.adoptedWake || responseTurn.settleWhenIdle,
2332
+ );
2333
}
2334
return;
2335
}
@@ -2294,6 +2339,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2339
yield* Effect.logWarning("Pi rejected a steer message.", {
2340
errorLength: recordString(event, "error")?.length,
2341
});
2342
+ if (consumedInputIsIdleCandidate && responseTurn !== null)
2343
+ yield* scheduleSettleProbe(responseTurn, responseTurn.settleWhenIdle);
2344
return;
2345
}
2346
const failedTurn =
@@ -2352,6 +2399,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2399
) {
2400
return;
2401
}
2402
+ if (
2403
+ turn.manualCompactInFlight ||
2404
+ pendingCompactResponses.some(
2405
+ (pending) => pending.providerTurnId === turn.providerTurn.id,
2406
+ ) ||
2407
+ pendingPromptResponses.some(
2408
+ (pending) => pending.providerTurnId === turn.providerTurn.id,
2409
+ )
2410
+ ) {
2411
+ turn.settleWhenIdle = true;
2412
+ return;
2413
+ }
2414
if (probeFailed) {
2415
if (!settleAfterAgentActivity) {
2416
if (state !== null) yield* finalizeTurn(state);
@@ -2420,6 +2479,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2479
Effect.gen(function* () {
2480
runtimeRetired = true;
2481
const state = threadState;
2482
+ closed = true;
2483
+ if (pendingPromptResponsesDrained !== null)
2484
+ yield* Deferred.fail(
2485
+ pendingPromptResponsesDrained,
2486
+ protocolError("Pi transport closed while awaiting prompt acknowledgment"),
2487
+ );
2488
if (extensionStatusReset !== null)
2489
yield* Deferred.fail(
2490
extensionStatusReset.ready,
@@ -2771,12 +2836,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2836
if (state === null) {
2837
return yield* protocolError("Pi session has no registered thread");
2838
}
2774
- if (state.activeTurn !== null) {
2775
- return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2776
- driver: PI_PROVIDER,
2777
- detail: `Pi provider thread ${turnInput.providerThread.id} already has an active turn`,
2778
- reason: "previous_turn_active",
2779
- });
2839
+ while (true) {
2840
+ if (state.activeTurn !== null) {
2841
+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2842
+ driver: PI_PROVIDER,
2843
+ detail: `Pi provider thread ${turnInput.providerThread.id} already has an active turn`,
2844
+ reason: "previous_turn_active",
2845
+ });
2846
+ }
2847
+ if (closed || stopRequested)
2848
+ return yield* protocolError("Cannot start a Pi turn after session closure");
2849
+ if (pendingPromptResponsesDrained === null) break;
2850
+ yield* Deferred.await(pendingPromptResponsesDrained);
2851
}
2852
if (
2853
state.providerThread.nativeThreadRef?.nativeId !==
@@ -2854,83 +2925,89 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2925
unreadSteers: [],
2926
};
2927
// Lock only install/send/start events; correlated setup must leave the pump free for dialogs.
2857
- yield* Effect.gen(function* () {
2858
- if (
2859
- threadState !== state ||
2860
- state.activeTurn !== null ||
2861
- closed ||
2862
- stopRequested ||
2863
- rollbackBarrier !== null ||
2864
- state.providerThread.nativeThreadRef?.nativeId !==
2865
- turnInput.providerThread.nativeThreadRef?.nativeId
2866
- ) {
2867
- return yield* protocolError("Pi turn ownership changed before it could start");
2868
- }
2869
- const wake = pendingWake?.state === state ? pendingWake : null;
2870
- if (wake !== null && wake.state.providerThread.appThreadId !== turnInput.threadId) {
2871
- return yield* protocolError("Pi native wake belongs to a different app thread");
2872
- }
2873
- pendingWake = null;
2874
- state.providerThread = turnInput.providerThread;
2875
- state.activeTurn = activeTurn;
2876
- activeTurn.adoptedWake = wake !== null && !continuation;
2877
- if (compactCommand !== null) {
2878
- yield* connection.send(compactRpcRecord(compactCommand));
2879
- pendingCompactResponses.push({
2880
- providerTurnId: providerTurn.id,
2881
- kind: "turn_start",
2928
+ while (true) {
2929
+ const pendingAck = yield* Effect.gen(function* () {
2930
+ if (
2931
+ threadState !== state ||
2932
+ state.activeTurn !== null ||
2933
+ closed ||
2934
+ stopRequested ||
2935
+ rollbackBarrier !== null ||
2936
+ state.providerThread.nativeThreadRef?.nativeId !==
2937
+ turnInput.providerThread.nativeThreadRef?.nativeId
2938
+ ) {
2939
+ return yield* protocolError("Pi turn ownership changed before it could start");
2940
+ }
2941
+ if (pendingPromptResponsesDrained !== null) return pendingPromptResponsesDrained;
2942
+ const wake = pendingWake?.state === state ? pendingWake : null;
2943
+ if (wake !== null && wake.state.providerThread.appThreadId !== turnInput.threadId) {
2944
+ return yield* protocolError("Pi native wake belongs to a different app thread");
2945
+ }
2946
+ pendingWake = null;
2947
+ state.providerThread = turnInput.providerThread;
2948
+ state.activeTurn = activeTurn;
2949
+ activeTurn.adoptedWake = wake !== null && !continuation;
2950
+ if (compactCommand !== null) {
2951
+ yield* connection.send(compactRpcRecord(compactCommand));
2952
+ pendingCompactResponses.push({
2953
+ providerTurnId: providerTurn.id,
2954
+ kind: "turn_start",
2955
+ });
2956
+ } else if (payload !== null) {
2957
+ yield* sendPrompt({
2958
+ providerTurnId: providerTurn.id,
2959
+ kind: "turn_start",
2960
+ record: {
2961
+ type: "prompt",
2962
+ message: payload.message,
2963
+ streamingBehavior: "steer",
2964
+ ...(payload.images.length === 0 ? {} : { images: payload.images }),
2965
+ },
2966
+ });
2967
+ }
2968
+ yield* emit({
2969
+ type: "provider_turn.updated",
2970
+ driver: PI_PROVIDER,
2971
+ threadId: turnInput.threadId,
2972
+ providerTurn,
2973
});
2883
- } else if (payload !== null) {
2884
- yield* sendPrompt({
2885
- providerTurnId: providerTurn.id,
2886
- kind: "turn_start",
2887
- record: {
2888
- type: "prompt",
2889
- message: payload.message,
2890
- streamingBehavior: "steer",
2891
- ...(payload.images.length === 0 ? {} : { images: payload.images }),
2892
- },
2974
+ yield* updateProviderThread(state, {
2975
+ status: "active",
2976
+ firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
2977
+ lastRunOrdinal: turnInput.runOrdinal,
2978
});
2894
- }
2895
- yield* emit({
2896
- type: "provider_turn.updated",
2897
- driver: PI_PROVIDER,
2898
- threadId: turnInput.threadId,
2899
- providerTurn,
2900
- });
2901
- yield* updateProviderThread(state, {
2902
- status: "active",
2903
- firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
2904
- lastRunOrdinal: turnInput.runOrdinal,
2905
- });
2906
- yield* updateProviderSession("running", null);
2907
- if (wake !== null) {
2908
- for (const event of wake.events) {
2909
- if (!continuation && event["type"] === "agent_settled") {
2910
- activeTurn.nativeAborted = event["aborted"] === true;
2911
- activeTurn.settleWhenIdle = true;
2912
- continue;
2979
+ yield* updateProviderSession("running", null);
2980
+ if (wake !== null) {
2981
+ for (const event of wake.events) {
2982
+ if (!continuation && event["type"] === "agent_settled") {
2983
+ activeTurn.nativeAborted = event["aborted"] === true;
2984
+ activeTurn.settleWhenIdle = true;
2985
+ continue;
2986
+ }
2987
+ yield* handleSessionEvent(event);
2988
}
2914
- yield* handleSessionEvent(event);
2989
+ } else if (continuation) {
2990
+ yield* finalizeTurn(state);
2991
}
2916
- } else if (continuation) {
2917
- yield* finalizeTurn(state);
2918
- }
2919
- if (outOfTurnExtensionErrors.length > 0) {
2920
- yield* Queue.offer(connection.events, { type: "t3.flush_extension_errors" });
2921
- }
2922
- }).pipe(
2923
- sessionEventPermit.withPermits(1),
2924
- Effect.tapError(() =>
2925
- Effect.sync(() => {
2926
- if (state.activeTurn === activeTurn) state.activeTurn = null;
2927
- }),
2928
- ),
2929
- );
2992
+ if (outOfTurnExtensionErrors.length > 0) {
2993
+ yield* Queue.offer(connection.events, { type: "t3.flush_extension_errors" });
2994
+ }
2995
+ return null;
2996
+ }).pipe(
2997
+ sessionEventPermit.withPermits(1),
2998
+ Effect.tapError(() =>
2999
+ Effect.sync(() => {
3000
+ if (state.activeTurn === activeTurn) state.activeTurn = null;
3001
+ }),
3002
+ ),
3003
+ );
3004
+ if (pendingAck === null) break;
3005
+ // The native event pump needs the permit to consume the actual ACK.
3006
+ yield* Deferred.await(pendingAck);
3007
+ }
3008
// Pi acks `prompt` only after slash-command expansion completes,
3009
// and extension commands may block on user dialogs indefinitely.
2932
- // Rejections therefore return later as id-less response records
2933
- // handled by the event pump.
3010
+ // Correlated responses therefore return later through the event pump.
3011
},
3012
(effect, turnInput) =>
3013
effect.pipe(