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 21, 13:30 UTC
fix(pi): resume attached sessions without reloading extensions (#21512)
Co-authored-by: Julian Rustig <jruestig@posteo.de>
Julius Marminge committed
Nov 14, 2026 at 16:47 UTC
b732f647f2208bf12083cad325443044c087dd2a
7 files changed
+629
-216
apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/pi_output.ts
+9
-5
@@ -22,8 +22,10 @@ export function assertPiProviderThreadResumeOutput(
22
result: OrchestratorV2ScenarioResult,
23
transcript: ProviderReplayTranscript,
24
) {
25
- const processStarts = transcript.entries.filter(
26
- (entry) => entry.type === "expect_outbound" && field(entry.frame, "type") === "process_start",
25
+ const processStarts = transcript.entries.flatMap((entry) =>
26
+ entry.type === "expect_outbound" && field(entry.frame, "type") === "process_start"
27
+ ? [entry.frame]
28
+ : [],
29
);
30
assert.lengthOf(processStarts, 2, "the idle release must retire the first Pi process");
31
const switches = transcript.entries.flatMap((entry) =>
@@ -31,11 +33,13 @@ export function assertPiProviderThreadResumeOutput(
33
? [entry]
34
: [],
35
);
36
+ const resumedArgs = field(processStarts[1], "args");
37
assert.deepEqual(
35
- switches.map((entry) => [entry.label, field(entry.frame, "sessionPath")]),
36
- [["switch_session@p2", "/pi-sessions/session-1.jsonl"]],
37
- "the respawned process must resume the first session file",
38
+ Array.isArray(resumedArgs) ? resumedArgs.slice(0, 4) : resumedArgs,
39
+ ["--mode", "rpc", "--session", "/pi-sessions/session-1.jsonl"],
40
+ "the respawned process must attach the first session file at startup",
41
);
42
+ assert.lengthOf(switches, 0, "an already attached session must not reload extensions");
43
44
assertBaseProjection({
45
result,
apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/pi_transcript.ndjson
+2
-6
@@ -1,4 +1,4 @@
1
-{"type":"transcript_start","provider":"pi","protocol":"pi.rpc-jsonl","version":"1.0.0","scenario":"provider_thread_resume","metadata":{"generatedBy":"live-pi-recorder","piVersion":"1.0.0","model":"openrouter/deepseek/deepseek-v4-flash","launchArgs":"--provider openrouter --model deepseek/deepseek-v4-flash --no-extensions --no-skills --no-prompt-templates --no-context-files --approve"}}
1
+{"type":"transcript_start","provider":"pi","protocol":"pi.rpc-jsonl","version":"1.0.0","scenario":"provider_thread_resume","metadata":{"generatedBy":"live-pi-recorder","piVersion":"1.0.0","model":"openrouter/deepseek/deepseek-v4-flash","launchArgs":"--provider openrouter --model deepseek/deepseek-v4-flash --no-extensions --no-skills --no-prompt-templates --no-context-files --approve","protocolMigration":"Spawn-time persisted sessions and same-file activation; original recorded model responses retained."}}
2
{"type":"expect_outbound","label":"process_start","frame":{"type":"process_start","args":["--mode","rpc","--provider","openrouter","--model","deepseek/deepseek-v4-flash","--no-extensions","--no-skills","--no-prompt-templates","--no-context-files","--approve","--extension","<any>"]}}
3
{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-0"}}
4
{"type":"emit_inbound","label":"extension_ui_request","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000001","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
@@ -57,12 +57,8 @@
57
{"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-7","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"6f98cdca","parentId":"99029ea8","timestamp":"2026-01-01T00:00:00.342Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"ed824dcd","parentId":"6f98cdca","timestamp":"2026-01-01T00:00:00.346Z","name":"Replay fixture: provider_thread_resume"},{"type":"message","id":"bcd18902","parentId":"ed824dcd","timestamp":"2026-01-01T00:00:00.359Z","message":{"role":"system","content":"","sections":{"preamble":"<system-prompt-section>","tools":"<system-prompt-section>","rules":"<system-prompt-section>","docs":"<system-prompt-section>","cwd":"<system-prompt-section>"},"timestamp":1790898591862,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"47cc13d2","parentId":"bcd18902","timestamp":"2026-01-01T00:00:00.359Z","message":{"role":"user","content":[{"type":"text","text":"Respond with exactly: provider thread resume fixture first turn complete"}],"timestamp":1767225600352}},{"type":"message","id":"c16b838e","parentId":"47cc13d2","timestamp":"2026-01-01T00:00:02.431Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to respond with exactly: \"provider thread resume fixture first turn complete\"\n\nBut first let me understand the context. This seems like a test or verification step. Let me look around the workspace to understand what's happening.\n\nActually, the instruction is clear: \"Respond with exactly: provider thread resume fixture first turn complete\"\n\nLet me just respond with that exact phrase.","thinkingSignature":"<signature>"},{"type":"text","text":"provider thread resume fixture first turn complete"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1792,"output":85,"cacheRead":0,"cacheWrite":0,"reasoning":103,"totalTokens":1877,"cost":{"input":0.00007501312,"output":0.0000071162,"cacheRead":0,"cacheWrite":0,"total":0.00008212932000000001}},"stopReason":"stop","timestamp":1767225600373,"responseId":"gen-1790898592-I4HavmQckm46d2n6xeJC","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"c16b838e"}}}
58
{"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-8"}}
59
{"type":"emit_inbound","label":"response:get_session_stats","frame":{"id":"t3-8","type":"response","command":"get_session_stats","success":true,"data":{"sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","userMessages":1,"assistantMessages":1,"toolCalls":0,"toolResults":0,"totalMessages":3,"tokens":{"input":1792,"output":85,"cacheRead":0,"cacheWrite":0,"total":1877},"cost":0.00008212932000000001,"contextUsage":{"tokens":1877,"contextWindow":1048576,"percent":0.17900466918945312}}}}
60
-{"type":"expect_outbound","label":"process_start@p2","frame":{"type":"process_start","args":["--mode","rpc","--provider","openrouter","--model","deepseek/deepseek-v4-flash","--no-extensions","--no-skills","--no-prompt-templates","--no-context-files","--approve","--extension","<any>"]}}
61
-{"type":"expect_outbound","label":"switch_session@p2","frame":{"type":"switch_session","sessionPath":"/pi-sessions/session-1.jsonl","id":"t3-0"}}
60
+{"type":"expect_outbound","label":"process_start@p2","frame":{"type":"process_start","args":["--mode","rpc","--session","/pi-sessions/session-1.jsonl","--provider","openrouter","--model","deepseek/deepseek-v4-flash","--no-extensions","--no-skills","--no-prompt-templates","--no-context-files","--approve","--extension","<any>"]}}
61
{"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000003","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
63
-{"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000004","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
64
-{"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000005","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
65
-{"type":"emit_inbound","label":"response:switch_session@p2","frame":{"id":"t3-0","type":"response","command":"switch_session","success":true,"data":{"cancelled":false}}}
62
{"type":"expect_outbound","label":"get_state@p2","frame":{"type":"get_state","id":"t3-2"}}
63
{"type":"emit_inbound","label":"response:get_state@p2","frame":{"id":"t3-2","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: provider_thread_resume","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}}
64
{"type":"expect_outbound","label":"get_available_models@p2","frame":{"type":"get_available_models","id":"t3-3"}}
apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/pi_output.ts
+4
-3
@@ -63,9 +63,10 @@ export function assertPiThreadRollbackOutput(
63
const [providerThread] = projection.providerThreads;
64
assert.lengthOf(projection.providerThreads, 1);
65
assert.equal(providerThread?.nativeThreadRef?.nativeId, "/pi-sessions/session-2.jsonl");
66
- assert.deepEqual(
67
- outboundOfType(transcript, "switch_session").map((frame) => field(frame, "sessionPath")),
68
- ["/pi-sessions/session-2.jsonl"],
66
+ assert.lengthOf(
67
+ outboundOfType(transcript, "switch_session"),
68
+ 0,
69
+ "the fork already selected the rollback session file",
70
);
71
72
const finalAnswer = projection.turnItems.findLast((item) => item.type === "assistant_message");
apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/pi_transcript.ndjson
+1
-5
@@ -1,4 +1,4 @@
1
-{"type":"transcript_start","provider":"pi","protocol":"pi.rpc-jsonl","version":"1.0.0","scenario":"thread_rollback","metadata":{"generatedBy":"live-pi-recorder","piVersion":"1.0.0","model":"openrouter/deepseek/deepseek-v4-flash","launchArgs":"--provider openrouter --model deepseek/deepseek-v4-flash --no-extensions --no-skills --no-prompt-templates --no-context-files --approve"}}
1
+{"type":"transcript_start","provider":"pi","protocol":"pi.rpc-jsonl","version":"1.0.0","scenario":"thread_rollback","metadata":{"generatedBy":"live-pi-recorder","piVersion":"1.0.0","model":"openrouter/deepseek/deepseek-v4-flash","launchArgs":"--provider openrouter --model deepseek/deepseek-v4-flash --no-extensions --no-skills --no-prompt-templates --no-context-files --approve","protocolMigration":"Spawn-time persisted sessions and same-file activation; original recorded model responses retained."}}
2
{"type":"expect_outbound","label":"process_start","frame":{"type":"process_start","args":["--mode","rpc","--provider","openrouter","--model","deepseek/deepseek-v4-flash","--no-extensions","--no-skills","--no-prompt-templates","--no-context-files","--approve","--extension","<any>"]}}
3
{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-0"}}
4
{"type":"emit_inbound","label":"extension_ui_request","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000001","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
@@ -87,10 +87,6 @@
87
{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-13","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-2.jsonl","sessionId":"00000000-0000-4000-8000-000000000005","sessionName":"Replay fixture: thread_rollback","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}}
88
{"type":"expect_outbound","label":"get_entries","frame":{"type":"get_entries","id":"t3-14"}}
89
{"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-14","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"648fe89a","parentId":null,"timestamp":"2026-01-01T00:00:00.000Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"thinking_level_change","id":"00c31b78","parentId":"648fe89a","timestamp":"2026-01-01T00:00:00.000Z","thinkingLevel":"high"},{"type":"model_change","id":"cc15a6b4","parentId":"00c31b78","timestamp":"2026-01-01T00:00:00.344Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"2c1dcf96","parentId":"cc15a6b4","timestamp":"2026-01-01T00:00:00.349Z","name":"Replay fixture: thread_rollback"},{"type":"message","id":"aca5528d","parentId":"2c1dcf96","timestamp":"2026-01-01T00:00:00.357Z","message":{"role":"system","content":"","sections":{"preamble":"<system-prompt-section>","tools":"<system-prompt-section>","rules":"<system-prompt-section>","docs":"<system-prompt-section>","cwd":"<system-prompt-section>"},"timestamp":1790898591831,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"70559bb2","parentId":"aca5528d","timestamp":"2026-01-01T00:00:00.357Z","message":{"role":"user","content":[{"type":"text","text":"Respond with exactly: rollback fixture first turn complete"}],"timestamp":1767225600354}},{"type":"message","id":"c906b4e2","parentId":"70559bb2","timestamp":"2026-01-01T00:00:02.034Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user is asking me to respond with exactly: \"rollback fixture first turn complete\"\n\nLet me check if there are any rollback-related fixtures or tests in the workspace first, as this seems like a test instruction.","thinkingSignature":"<signature>"},{"type":"text","text":"rollback fixture first turn complete"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1791,"output":52,"cacheRead":0,"cacheWrite":0,"reasoning":54,"totalTokens":1843,"cost":{"input":0.00007497126,"output":0.00000435344,"cacheRead":0,"cacheWrite":0,"total":0.0000793247}},"stopReason":"stop","timestamp":1767225600369,"responseId":"gen-1790898592-a7T4i6GUUneRyLxy0gtp","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"c906b4e2"}}}
90
-{"type":"expect_outbound","label":"switch_session","frame":{"type":"switch_session","sessionPath":"/pi-sessions/session-2.jsonl","id":"t3-15"}}
91
-{"type":"emit_inbound","label":"extension_ui_request","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000006","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
92
-{"type":"emit_inbound","label":"extension_ui_request","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000007","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
93
-{"type":"emit_inbound","label":"response:switch_session","frame":{"id":"t3-15","type":"response","command":"switch_session","success":true,"data":{"cancelled":false}}}
90
{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-16"}}
91
{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-16","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-2.jsonl","sessionId":"00000000-0000-4000-8000-000000000005","sessionName":"Replay fixture: thread_rollback","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}}
92
{"type":"expect_outbound","label":"get_entries","frame":{"type":"get_entries","id":"t3-17"}}
apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_stop/pi_transcript.ndjson
+2
-10
@@ -1,4 +1,4 @@
1
-{"type":"transcript_start","provider":"pi","protocol":"pi.rpc-jsonl","version":"1.0.0","scenario":"thread_rollback_after_stop","metadata":{"generatedBy":"live-pi-recorder","piVersion":"1.0.0","model":"openrouter/deepseek/deepseek-v4-flash","launchArgs":"--provider openrouter --model deepseek/deepseek-v4-flash --no-extensions --no-skills --no-prompt-templates --no-context-files --approve"}}
1
+{"type":"transcript_start","provider":"pi","protocol":"pi.rpc-jsonl","version":"1.0.0","scenario":"thread_rollback_after_stop","metadata":{"generatedBy":"live-pi-recorder","piVersion":"1.0.0","model":"openrouter/deepseek/deepseek-v4-flash","launchArgs":"--provider openrouter --model deepseek/deepseek-v4-flash --no-extensions --no-skills --no-prompt-templates --no-context-files --approve","protocolMigration":"Spawn-time persisted sessions and same-file activation; original recorded model responses retained."}}
2
{"type":"expect_outbound","label":"process_start","frame":{"type":"process_start","args":["--mode","rpc","--provider","openrouter","--model","deepseek/deepseek-v4-flash","--no-extensions","--no-skills","--no-prompt-templates","--no-context-files","--approve","--extension","<any>"]}}
3
{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-0"}}
4
{"type":"emit_inbound","label":"extension_ui_request","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000001","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
@@ -149,12 +149,8 @@
149
{"type":"emit_inbound","label":"response:abort","frame":{"id":"t3-10","type":"response","command":"abort","success":true}}
150
{"type":"expect_outbound","label":"get_entries","frame":{"type":"get_entries","since":"b184b5a8","id":"t3-11"}}
151
{"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-11","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"message","id":"ee73daae","parentId":"b184b5a8","timestamp":"2026-01-01T00:00:01.971Z","message":{"role":"user","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."}],"timestamp":1767225601969}},{"type":"message","id":"c3915df7","parentId":"ee73daae","timestamp":"2026-01-01T00:00:06.406Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a command that will wait for 30 seconds, and then after it completes, respond with a specific message. But they also say \"Do not answer until it completes\" - but this command will run for 30 seconds and then naturally finish. However, the response they want is \"interrupt fixture should not finish naturally\" which contradicts the fact that it did finish naturally.\n\nWait, let me re-read. They want me to run the command and not answer until it completes. The command is a node script that logs \"interrupt fixture tool started\" and then waits 30 seconds. If I wait for it to complete, it will finish naturally after 30 seconds. But the response they want is \"interrupt fixture should not finish naturally\" - implying that the fixture should have been interrupted before finishing naturally.\n\nThis is a test scenario. Let me just run it and see what happens. Actually, maybe they want me to just run it and respond accordingly. Let me execute the command.\n\nActually, I think this is part of a test where the system might interrupt/kill the process. Let me just run the command with a sufficient timeout.","thinkingSignature":"<signature>"},{"type":"toolCall","id":"call_8ac3cb4177994abdb9aa1c57","name":"bash","arguments":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":35}}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":77,"output":317,"cacheRead":1792,"cacheWrite":0,"reasoning":284,"totalTokens":2186,"cost":{"input":0.00000322322,"output":0.000026539239999999998,"cacheRead":0.000015002623999999998,"cacheWrite":0,"total":0.000044765084}},"stopReason":"toolUse","timestamp":1767225601972,"responseId":"gen-1790898593-E5hfYfRp6aKBI57pUKss","rawStopReason":"tool_calls","thinkingLevel":"high"}},{"type":"message","id":"641f3d3f","parentId":"c3915df7","timestamp":"2026-01-01T00:00:06.463Z","message":{"role":"toolResult","toolCallId":"call_8ac3cb4177994abdb9aa1c57","toolName":"bash","content":[{"type":"text","text":"interrupt fixture tool started\n\n\nCommand aborted"}],"details":{},"isError":true,"timestamp":1767225606463}},{"type":"message","id":"e3ab1495","parentId":"641f3d3f","timestamp":"2026-01-01T00:00:06.465Z","message":{"role":"assistant","content":[],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"error","errorMessage":"This operation was aborted","timestamp":1767225606465,"thinkingLevel":"high"}}],"leafId":"e3ab1495"}}}
152
-{"type":"expect_outbound","label":"process_start@p2","frame":{"type":"process_start","args":["--mode","rpc","--provider","openrouter","--model","deepseek/deepseek-v4-flash","--no-extensions","--no-skills","--no-prompt-templates","--no-context-files","--approve","--extension","<any>"]}}
153
-{"type":"expect_outbound","label":"switch_session@p2","frame":{"type":"switch_session","sessionPath":"/pi-sessions/session-1.jsonl","id":"t3-0"}}
152
+{"type":"expect_outbound","label":"process_start@p2","frame":{"type":"process_start","args":["--mode","rpc","--session","/pi-sessions/session-1.jsonl","--provider","openrouter","--model","deepseek/deepseek-v4-flash","--no-extensions","--no-skills","--no-prompt-templates","--no-context-files","--approve","--extension","<any>"]}}
153
{"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000003","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
155
-{"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000004","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
156
-{"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000005","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
157
-{"type":"emit_inbound","label":"response:switch_session@p2","frame":{"id":"t3-0","type":"response","command":"switch_session","success":true,"data":{"cancelled":false}}}
154
{"type":"expect_outbound","label":"get_state@p2","frame":{"type":"get_state","id":"t3-2"}}
155
{"type":"emit_inbound","label":"response:get_state@p2","frame":{"id":"t3-2","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: thread_rollback_after_stop","autoCompactionEnabled":true,"messageCount":7,"pendingMessageCount":0}}}
156
{"type":"expect_outbound","label":"get_available_models@p2","frame":{"type":"get_available_models","id":"t3-3"}}
@@ -212,10 +208,6 @@
208
{"type":"emit_inbound","label":"response:get_state@p2","frame":{"id":"t3-11","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-2.jsonl","sessionId":"00000000-0000-4000-8000-000000000008","sessionName":"Replay fixture: thread_rollback_after_stop","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}}
209
{"type":"expect_outbound","label":"get_entries@p2","frame":{"type":"get_entries","id":"t3-12"}}
210
{"type":"emit_inbound","label":"response:get_entries@p2","frame":{"id":"t3-12","type":"response","command":"get_entries","success":true,"data":{"entries":[{"type":"model_change","id":"e0846d39","parentId":null,"timestamp":"2026-01-01T00:00:00.000Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"thinking_level_change","id":"10e2239d","parentId":"e0846d39","timestamp":"2026-01-01T00:00:00.000Z","thinkingLevel":"high"},{"type":"model_change","id":"7aecf566","parentId":"10e2239d","timestamp":"2026-01-01T00:00:00.359Z","provider":"openrouter","modelId":"deepseek/deepseek-v4-flash"},{"type":"session_info","id":"5e1135b5","parentId":"7aecf566","timestamp":"2026-01-01T00:00:00.363Z","name":"Replay fixture: thread_rollback_after_stop"},{"type":"message","id":"66a686a0","parentId":"5e1135b5","timestamp":"2026-01-01T00:00:00.371Z","message":{"role":"system","content":"","sections":{"preamble":"<system-prompt-section>","tools":"<system-prompt-section>","rules":"<system-prompt-section>","docs":"<system-prompt-section>","cwd":"<system-prompt-section>"},"timestamp":1790898591965,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}},{"type":"message","id":"0d296cbc","parentId":"66a686a0","timestamp":"2026-01-01T00:00:00.372Z","message":{"role":"user","content":[{"type":"text","text":"Respond with exactly: rollback fixture first turn complete"}],"timestamp":1767225600369}},{"type":"message","id":"b184b5a8","parentId":"0d296cbc","timestamp":"2026-01-01T00:00:01.622Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to respond with exactly \"rollback fixture first turn complete\".","thinkingSignature":"<signature>"},{"type":"text","text":"rollback fixture first turn complete"}],"api":"openai-completions","provider":"openrouter","model":"deepseek/deepseek-v4-flash","usage":{"input":1795,"output":24,"cacheRead":0,"cacheWrite":0,"reasoning":21,"totalTokens":1819,"cost":{"input":0.00007513869999999999,"output":0.00000200928,"cacheRead":0,"cacheWrite":0,"total":0.00007714798}},"stopReason":"stop","timestamp":1767225600386,"responseId":"gen-1790898592-vpyqfefcvhCaD41XnfZc","rawStopReason":"stop","thinkingLevel":"high"}}],"leafId":"b184b5a8"}}}
215
-{"type":"expect_outbound","label":"switch_session@p2","frame":{"type":"switch_session","sessionPath":"/pi-sessions/session-2.jsonl","id":"t3-13"}}
216
-{"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000009","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
217
-{"type":"emit_inbound","label":"extension_ui_request@p2","frame":{"type":"extension_ui_request","id":"00000000-0000-4000-8000-000000000010","method":"notify","message":"t3-code MCP unavailable: T3_MCP_URL or T3_MCP_BEARER_TOKEN is missing.","notifyType":"warning"}}
218
-{"type":"emit_inbound","label":"response:switch_session@p2","frame":{"id":"t3-13","type":"response","command":"switch_session","success":true,"data":{"cancelled":false}}}
211
{"type":"expect_outbound","label":"get_state@p2","frame":{"type":"get_state","id":"t3-14"}}
212
{"type":"emit_inbound","label":"response:get_state@p2","frame":{"id":"t3-14","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-2.jsonl","sessionId":"00000000-0000-4000-8000-000000000008","sessionName":"Replay fixture: thread_rollback_after_stop","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}}
213
{"type":"expect_outbound","label":"get_entries@p2","frame":{"type":"get_entries","id":"t3-15"}}
packages/provider-pi/src/server/adapter.test.ts
+302
-21
@@ -22,6 +22,7 @@ import {
22
import * as Cause from "effect/Cause";
23
import * as DateTime from "effect/DateTime";
24
import * as Deferred from "effect/Deferred";
25
+import * as Duration from "effect/Duration";
26
import * as Effect from "effect/Effect";
27
import * as Exit from "effect/Exit";
28
import * as Fiber from "effect/Fiber";
@@ -33,6 +34,7 @@ import * as Schema from "effect/Schema";
34
import * as Scope from "effect/Scope";
35
import * as Sink from "effect/Sink";
36
import * as Stream from "effect/Stream";
37
+import * as TestClock from "effect/testing/TestClock";
38
import * as ChildProcess from "effect/process/ChildProcess";
39
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
40
@@ -165,9 +167,9 @@ interface FakePi {
167
readonly queueState: (data: Record<string, unknown>) => void;
168
readonly setStreaming: (streaming: boolean) => void;
169
readonly setCompacting: (compacting: boolean) => void;
168
- readonly deferNextState: () => void;
170
+ readonly deferNextState: (started?: Deferred.Deferred<void>) => void;
171
readonly resolveDeferredState: (data: unknown) => Effect.Effect<void>;
170
- readonly failNextState: () => void;
172
+ readonly failNextState: (skip?: number) => void;
173
readonly failNextThinking: () => void;
174
readonly deferNextLifecycle: (
175
type: "switch_session" | "new_session" | "fork" | "prompt" | "abort",
@@ -225,8 +227,9 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
227
const statsQueue: Array<unknown> = [];
228
const allRequests: Array<PiRpcRecord> = [];
229
let deferState = false;
230
+ let deferredStateStarted: Deferred.Deferred<void> | undefined;
231
let deferredStateRequest: PiRpcRecord | undefined;
229
- let failState = false;
232
+ let failStateAfter: number | null = null;
233
let failThinking = false;
234
let vetoSwitch = false;
235
let vetoNewSession = false;
@@ -270,8 +273,8 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
273
};
274
switch (record["type"]) {
275
case "get_state":
273
- if (failState) {
274
- failState = false;
276
+ if (failStateAfter !== null && failStateAfter-- === 0) {
277
+ failStateAfter = null;
278
return { ...base, success: false, error: "state unavailable" };
279
}
280
return {
@@ -371,6 +374,10 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
374
if (record["type"] === "get_state" && deferState) {
375
deferState = false;
376
deferredStateRequest = record;
377
+ if (deferredStateStarted !== undefined) {
378
+ yield* Deferred.succeed(deferredStateStarted, undefined);
379
+ deferredStateStarted = undefined;
380
+ }
381
continue;
382
}
383
if (record["type"] === deferredLifecycle) {
@@ -436,8 +443,9 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
443
takeRequest,
444
queueEntries: (data) => entriesQueue.push(data),
445
queueMessages: (data) => messagesQueue.push(data),
439
- deferNextState: () => {
446
+ deferNextState: (started) => {
447
deferState = true;
448
+ deferredStateStarted = started;
449
},
450
resolveDeferredState: (data) =>
451
Effect.gen(function* () {
@@ -452,8 +460,8 @@ const makeFakePi: Effect.Effect<FakePi> = Effect.gen(function* () {
460
data,
461
});
462
}),
455
- failNextState: () => {
456
- failState = true;
463
+ failNextState: (skip = 0) => {
464
+ failStateAfter = skip;
465
},
466
deferNextLifecycle: (type) => {
467
deferredLifecycle = type;
@@ -531,6 +539,7 @@ const openRuntime = Effect.fnUntraced(function* (
539
providerSessionId = SESSION_ID,
540
forkFake?: FakePi,
541
continuationRequests?: PiAdapterV2Options["continuationRequests"],
542
+ initialNativeThreadId?: string,
543
) {
544
const adapter = yield* makeAdapter(fake, "", forkFake, continuationRequests);
545
const runtime = yield* adapter.openSession({
@@ -538,6 +547,7 @@ const openRuntime = Effect.fnUntraced(function* (
547
providerSessionId,
548
modelSelection: modelSelection(model),
549
runtimePolicy,
550
+ ...(initialNativeThreadId === undefined ? {} : { initialNativeThreadId }),
551
});
552
const emitted = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
553
yield* runtime.events.pipe(
@@ -910,6 +920,7 @@ describe("PiAdapterV2", () => {
920
title: "Continue?",
921
});
922
yield* takeEvent((event) => event.type === "runtime_request.updated");
923
+ fake.queueState({ sessionFile: "/fake/other-session.jsonl" });
924
fake.vetoNextSwitch();
925
const exit = yield* runtime.resumeThread({ providerThread }).pipe(Effect.exit);
926
assert.isTrue(Exit.isFailure(exit));
@@ -937,6 +948,7 @@ describe("PiAdapterV2", () => {
948
statusKey: key,
949
statusText: key === "lint" ? "Lint clean" : "Watching",
950
});
951
+ fake.queueState({ sessionFile: "/fake/other-session.jsonl" });
952
fake.deferNextLifecycle("switch_session");
953
const switching = yield* runtime
954
.resumeThread({ providerThread })
@@ -1532,7 +1544,7 @@ describe("PiAdapterV2", () => {
1544
}).pipe(Effect.scoped, Effect.provide(layerTest)),
1545
);
1546
1535
- it.effect("adopts a completed native wake without sending a synthetic prompt", () =>
1547
+ it.effect("adopts a wake during same-file registration without a prompt", () =>
1548
Effect.gen(function* () {
1549
const fake = yield* makeFakePi;
1550
const offers =
@@ -1552,6 +1564,10 @@ describe("PiAdapterV2", () => {
1564
modelSelection: modelSelection("default"),
1565
runtimePolicy,
1566
});
1567
+ const reading = yield* Deferred.make<void>();
1568
+ fake.deferNextState(reading);
1569
+ const registering = yield* runtime.resumeThread({ providerThread }).pipe(Effect.forkChild);
1570
+ yield* Deferred.await(reading);
1571
yield* fake.emit({ type: "agent_start" });
1572
const offer = yield* Queue.take(offers).pipe(
1573
Effect.raceFirst(
@@ -1567,6 +1583,8 @@ describe("PiAdapterV2", () => {
1583
assert.equal(offer.providerThreadId, providerThread.id);
1584
assert.equal(offer.delivery, "adapter_buffered");
1585
assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1586
+ yield* fake.resolveDeferredState(recordedIdleState(FAKE_SESSION_FILE));
1587
+ yield* Fiber.join(registering);
1588
let dispatchCommitted = false;
1589
yield* offer.dispatchIfCurrent!(
1590
Effect.sync(() => {
@@ -1828,14 +1846,23 @@ describe("PiAdapterV2", () => {
1846
modelSelection: modelSelection("default"),
1847
runtimePolicy,
1848
});
1831
- yield* fake.emit({ type: "agent_start" });
1832
- const offer = yield* Queue.take(offers);
1833
- assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(providerThread));
1849
const otherThread = {
1850
...providerThread,
1851
appThreadId: ThreadId.make("other-thread"),
1852
id: ProviderThreadId.make("other-provider-thread"),
1853
};
1854
+ const reading = yield* Deferred.make<void>();
1855
+ fake.deferNextState(reading);
1856
+ const registering = yield* runtime
1857
+ .resumeThread({ providerThread: otherThread })
1858
+ .pipe(Effect.result, Effect.forkChild);
1859
+ yield* Deferred.await(reading);
1860
+ yield* fake.emit({ type: "agent_start" });
1861
+ const offer = yield* Queue.take(offers);
1862
+ yield* fake.resolveDeferredState(recordedIdleState("/fake/other-session.jsonl"));
1863
+ assert.equal((yield* Fiber.join(registering))._tag, "Failure");
1864
+ assert.isFalse(fake.allRequests().some((request) => request.type === "switch_session"));
1865
+ assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(providerThread));
1866
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(otherThread));
1867
const failure = yield* runtime
1868
.resumeThread({ providerThread: otherThread })
@@ -2091,6 +2118,223 @@ describe("PiAdapterV2", () => {
2118
}).pipe(Effect.scoped, Effect.provide(layerTest)),
2119
);
2120
2121
+ it.effect(
2122
+ "resumes a persisted session at spawn without replacing it or clearing model selection",
2123
+ () =>
2124
+ Effect.gen(function* () {
2125
+ const original = yield* openRuntime(yield* makeFakePi);
2126
+ const persisted = yield* original.runtime.ensureThread({
2127
+ threadId: THREAD_ID,
2128
+ modelSelection: modelSelection("default"),
2129
+ runtimePolicy,
2130
+ });
2131
+ const fake = yield* makeFakePi;
2132
+ const { runtime, takeEvent } = yield* openRuntime(
2133
+ fake,
2134
+ "default",
2135
+ THREAD_ID,
2136
+ SESSION_ID,
2137
+ undefined,
2138
+ undefined,
2139
+ FAKE_SESSION_FILE,
2140
+ );
2141
+ const args = fake.lastSpawn().args;
2142
+ assert.include(args, "--session");
2143
+ assert.equal(args[args.indexOf("--session") + 1], FAKE_SESSION_FILE);
2144
+ assert.notInclude(args, "--no-session");
2145
+ assert.notInclude(args, "--no-extensions");
2146
+ assert.include(args, "--extension");
2147
+
2148
+ // Startup extensions can hold Pi's first reply past the ordinary request deadline.
2149
+ const reading = yield* Deferred.make<void>();
2150
+ fake.deferNextState(reading);
2151
+ const registering = yield* runtime
2152
+ .ensureThread({
2153
+ threadId: THREAD_ID,
2154
+ modelSelection: modelSelection("default"),
2155
+ runtimePolicy,
2156
+ existingProviderThread: persisted,
2157
+ })
2158
+ .pipe(Effect.forkChild);
2159
+ yield* Deferred.await(reading);
2160
+ yield* TestClock.adjust(Duration.millis(16_820));
2161
+ yield* fake.resolveDeferredState({
2162
+ ...recordedIdleState(FAKE_SESSION_FILE.replace("/--workspace--/", "/--workspace--/./")),
2163
+ });
2164
+ const providerThread = yield* Fiber.join(registering);
2165
+ assert.equal(providerThread.id, persisted.id);
2166
+ assert.isFalse(fake.allRequests().some((request) => request.type === "switch_session"));
2167
+ yield* startTurn(runtime, providerThread, "anthropic/claude-sonnet");
2168
+ assert.equal((yield* fake.takeRequest("prompt"))["message"], "Hello pi");
2169
+ yield* fake.emit({ type: "agent_start" });
2170
+ yield* fake.emit({ type: "agent_settled" });
2171
+ yield* takeEvent((event) => event.type === "turn.terminal");
2172
+
2173
+ const resumed = yield* runtime.resumeThread({ providerThread });
2174
+ yield* startTurn(runtime, resumed, "anthropic/claude-sonnet", [], "Continue", undefined, 2);
2175
+ assert.equal((yield* fake.takeRequest("prompt"))["message"], "Continue");
2176
+ assert.isFalse(fake.allRequests().some((request) => request.type === "switch_session"));
2177
+ assert.equal(
2178
+ fake.allRequests().filter((request) => request.type === "set_model").length,
2179
+ 1,
2180
+ );
2181
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
2182
+ );
2183
+
2184
+ it.effect("creates a fresh session when cold resume is bypassed before registration", () =>
2185
+ Effect.gen(function* () {
2186
+ const original = yield* openRuntime(yield* makeFakePi);
2187
+ const persisted = yield* original.runtime.ensureThread({
2188
+ threadId: THREAD_ID,
2189
+ modelSelection: modelSelection("default"),
2190
+ runtimePolicy,
2191
+ });
2192
+ const fake = yield* makeFakePi;
2193
+ const { runtime } = yield* openRuntime(
2194
+ fake,
2195
+ "default",
2196
+ THREAD_ID,
2197
+ SESSION_ID,
2198
+ undefined,
2199
+ undefined,
2200
+ FAKE_SESSION_FILE,
2201
+ );
2202
+ const fresh = yield* runtime.ensureThread({
2203
+ threadId: THREAD_ID,
2204
+ modelSelection: modelSelection("default"),
2205
+ runtimePolicy,
2206
+ existingProviderThread: { ...persisted, nativeThreadRef: null },
2207
+ });
2208
+ assert.equal(fresh.id, persisted.id);
2209
+ assert.notEqual(fresh.nativeThreadRef?.nativeId, persisted.nativeThreadRef?.nativeId);
2210
+ assert.equal(
2211
+ fake.allRequests().filter((request) => request.type === "new_session").length,
2212
+ 1,
2213
+ );
2214
+ assert.isFalse(fake.allRequests().some((request) => request.type === "switch_session"));
2215
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
2216
+ );
2217
+
2218
+ it.effect("reserves registration during its state read and releases it on interruption", () =>
2219
+ Effect.gen(function* () {
2220
+ const fake = yield* makeFakePi;
2221
+ const { runtime, takeEvent } = yield* openRuntime(fake);
2222
+ const providerThread = yield* runtime.ensureThread({
2223
+ threadId: THREAD_ID,
2224
+ modelSelection: modelSelection("default"),
2225
+ runtimePolicy,
2226
+ });
2227
+ yield* startTurn(runtime, providerThread, "anthropic/claude-sonnet");
2228
+ yield* fake.takeRequest("prompt");
2229
+ yield* fake.emit({ type: "agent_start" });
2230
+ yield* fake.emit({ type: "agent_settled" });
2231
+ yield* takeEvent((event) => event.type === "turn.terminal");
2232
+
2233
+ const reading = yield* Deferred.make<void>();
2234
+ fake.deferNextState(reading);
2235
+ const registering = yield* runtime.resumeThread({ providerThread }).pipe(Effect.forkChild);
2236
+ yield* Deferred.await(reading);
2237
+ const overlappingTurn = yield* startTurn(runtime, providerThread).pipe(Effect.result);
2238
+ assert.equal(overlappingTurn._tag, "Failure", "A turn was accepted during registration");
2239
+ const overlappingResume = yield* runtime.resumeThread({ providerThread }).pipe(Effect.result);
2240
+ assert.equal(overlappingResume._tag, "Failure");
2241
+ yield* fake.resolveDeferredState(recordedIdleState(FAKE_SESSION_FILE));
2242
+ const resumed = yield* Fiber.join(registering);
2243
+
2244
+ const interruptedRead = yield* Deferred.make<void>();
2245
+ fake.deferNextState(interruptedRead);
2246
+ const interrupted = yield* runtime
2247
+ .resumeThread({ providerThread: resumed })
2248
+ .pipe(Effect.forkChild);
2249
+ yield* Deferred.await(interruptedRead);
2250
+ yield* Fiber.interrupt(interrupted);
2251
+ yield* fake.resolveDeferredState(recordedIdleState(FAKE_SESSION_FILE));
2252
+ fake.failNextState();
2253
+ const failedRead = yield* runtime
2254
+ .resumeThread({ providerThread: resumed })
2255
+ .pipe(Effect.result);
2256
+ assert.equal(failedRead._tag, "Failure");
2257
+
2258
+ yield* startTurn(runtime, resumed, "anthropic/claude-sonnet", [], "Continue", undefined, 2);
2259
+ assert.equal((yield* fake.takeRequest("prompt"))["message"], "Continue");
2260
+ yield* fake.emit({ type: "agent_start" });
2261
+ yield* fake.emit({ type: "agent_settled" });
2262
+ const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
2263
+ assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed");
2264
+ assert.isFalse(fake.allRequests().some((request) => request.type === "switch_session"));
2265
+ assert.equal(fake.allRequests().filter((request) => request.type === "set_model").length, 1);
2266
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
2267
+ );
2268
+
2269
+ it.effect("respawns without the session when Pi exits on an unusable spawn session", () =>
2270
+ Effect.gen(function* () {
2271
+ const original = yield* openRuntime(yield* makeFakePi);
2272
+ const persisted = yield* original.runtime.ensureThread({
2273
+ threadId: THREAD_ID,
2274
+ modelSelection: modelSelection("default"),
2275
+ runtimePolicy,
2276
+ });
2277
+ // A cleared ref takes the new_session path, which must also run the recovery.
2278
+ for (const providerThread of [persisted, { ...persisted, nativeThreadRef: null }]) {
2279
+ const failed = yield* makeFakePi;
2280
+ const replacement = yield* makeFakePi;
2281
+ // The transport fails stdin and events together; awaiting this orders registration after both.
2282
+ const transportDown = yield* Deferred.make<void>();
2283
+ let spawnCount = 0;
2284
+ const fake = {
2285
+ ...replacement,
2286
+ spawner: ChildProcessSpawner.make((command) => {
2287
+ spawnCount++;
2288
+ if (spawnCount > 1) return replacement.spawner.spawn(command);
2289
+ // Exits at once so the transport is already down before registration runs.
2290
+ return failed.spawner.spawn(command).pipe(
2291
+ Effect.map((child) =>
2292
+ ChildProcessSpawner.makeHandle({
2293
+ ...child,
2294
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
2295
+ stdin: child.stdin.pipe(
2296
+ Sink.ensuring(Deferred.succeed(transportDown, undefined)),
2297
+ ),
2298
+ }),
2299
+ ),
2300
+ );
2301
+ }),
2302
+ };
2303
+ yield* failed.closeStdout;
2304
+ const { runtime, takeEvent } = yield* openRuntime(
2305
+ fake,
2306
+ "default",
2307
+ THREAD_ID,
2308
+ SESSION_ID,
2309
+ undefined,
2310
+ undefined,
2311
+ FAKE_SESSION_FILE,
2312
+ );
2313
+ assert.include(failed.lastSpawn().args, "--session");
2314
+ yield* Deferred.await(transportDown);
2315
+ replacement.queueState({ sessionFile: "/fake/default-session.jsonl" });
2316
+ const resumed = yield* runtime.resumeThread({ providerThread });
2317
+ assert.equal(spawnCount, 2);
2318
+ assert.notInclude(replacement.lastSpawn().args, "--session");
2319
+ assert.include(replacement.lastSpawn().args, "--extension");
2320
+ const switched = replacement.allRequests().find((r) => r.type === "switch_session");
2321
+ if (providerThread.nativeThreadRef === null) {
2322
+ assert.isUndefined(switched);
2323
+ assert.notEqual(resumed.nativeThreadRef?.nativeId, FAKE_SESSION_FILE);
2324
+ } else {
2325
+ assert.equal(switched?.sessionPath, FAKE_SESSION_FILE);
2326
+ assert.equal(resumed.nativeThreadRef?.nativeId, FAKE_SESSION_FILE);
2327
+ }
2328
+ yield* startTurn(runtime, resumed);
2329
+ yield* replacement.takeRequest("prompt");
2330
+ yield* replacement.emit({ type: "agent_start" });
2331
+ yield* replacement.emit({ type: "agent_settled" });
2332
+ const terminal = yield* takeEvent((event) => event.type === "turn.terminal");
2333
+ assert.isTrue(terminal.type === "turn.terminal" && terminal.status === "completed");
2334
+ }
2335
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
2336
+ );
2337
+
2338
it.effect("rejects a resume while a turn is active", () =>
2339
Effect.gen(function* () {
2340
const fake = yield* makeFakePi;
@@ -2144,12 +2388,32 @@ describe("PiAdapterV2", () => {
2388
2389
const otherCwd = yield* sessionAt(`${host.paths.cwd}-original-checkout`);
2390
forkFake.queueState({ sessionFile: forkFile });
2391
+ fake.queueState({ sessionFile: FAKE_SESSION_FILE });
2392
fake.queueState({ sessionFile: forkFile });
2393
const resumed = yield* runtime.resumeThread({ providerThread: otherCwd });
2394
const args = forkFake.lastSpawn().args;
2395
assert.equal(args[args.indexOf("--fork") + 1], otherCwd.nativeThreadRef?.nativeId);
2396
assert.equal(lastSwitch(), forkFile);
2397
assert.equal(resumed.nativeThreadRef?.nativeId, forkFile);
2398
+
2399
+ // A cold start may attach only a session recorded in this cwd; others take the fork above.
2400
+ for (const thread of [sameCwd, otherCwd]) {
2401
+ const coldFake = yield* makeFakePi;
2402
+ yield* openRuntime(
2403
+ coldFake,
2404
+ "default",
2405
+ THREAD_ID,
2406
+ SESSION_ID,
2407
+ undefined,
2408
+ undefined,
2409
+ thread.nativeThreadRef?.nativeId,
2410
+ );
2411
+ const coldArgs = coldFake.lastSpawn().args;
2412
+ assert.equal(
2413
+ coldArgs.includes("--session") ? coldArgs[coldArgs.indexOf("--session") + 1] : undefined,
2414
+ thread === sameCwd ? sameCwd.nativeThreadRef?.nativeId : undefined,
2415
+ );
2416
+ }
2417
}).pipe(Effect.scoped, Effect.provide(layerTest)),
2418
);
2419
@@ -2162,8 +2426,10 @@ describe("PiAdapterV2", () => {
2426
modelSelection: modelSelection("default"),
2427
runtimePolicy,
2428
});
2429
+ fake.queueState({ sessionFile: "/fake/other-session.jsonl" });
2430
fake.vetoNextSwitch();
2166
- yield* runtime.resumeThread({ providerThread }).pipe(Effect.flip);
2431
+ const error = yield* runtime.resumeThread({ providerThread }).pipe(Effect.flip);
2432
+ assert.match(String(error.cause), /cancelled the session switch/);
2433
const replacement = yield* runtime.ensureThread({
2434
threadId: THREAD_ID,
2435
modelSelection: modelSelection("default"),
@@ -2224,6 +2490,7 @@ describe("PiAdapterV2", () => {
2490
modelSelection: modelSelection("default"),
2491
runtimePolicy,
2492
});
2493
+ fake.queueState({ sessionFile: "/fake/other-session.jsonl" });
2494
fake.deferNextLifecycle("switch_session");
2495
const resumed = yield* runtime.resumeThread({ providerThread }).pipe(Effect.forkChild);
2496
yield* fake.takeRequest("switch_session");
@@ -2621,7 +2888,13 @@ describe("PiAdapterV2", () => {
2888
startedAt: null,
2889
completedAt: null,
2890
});
2891
+ yield* startTurn(runtime, source, "anthropic/claude-sonnet");
2892
+ yield* fake.takeRequest("prompt");
2893
+ yield* fake.emit({ type: "agent_start" });
2894
+ yield* fake.emit({ type: "agent_settled" });
2895
+ yield* takeEvent((event) => event.type === "turn.terminal");
2896
forkFake.queueState({ sessionFile: forkFile });
2897
+ fake.queueState({ sessionFile: FAKE_SESSION_FILE });
2898
fake.queueState({ sessionFile: forkFile });
2899
const target = ThreadId.make("fork-target");
2900
const forked = yield* runtime.forkThread({
@@ -2651,7 +2924,18 @@ describe("PiAdapterV2", () => {
2924
fake.allRequests().some((request) => request.type === "fork" || request.type === "clone"),
2925
);
2926
const adopted = { ...forked, id: ProviderThreadId.make("pending-fork-row") };
2654
- yield* startTurn(runtime, adopted, "default", [], "Continue", undefined, 1, target);
2927
+ yield* startTurn(
2928
+ runtime,
2929
+ adopted,
2930
+ "anthropic/claude-sonnet",
2931
+ [],
2932
+ "Continue",
2933
+ undefined,
2934
+ 1,
2935
+ target,
2936
+ );
2937
+ yield* fake.takeRequest("prompt");
2938
+ assert.equal(fake.allRequests().filter((request) => request.type === "set_model").length, 2);
2939
yield* fake.emit({ type: "agent_start" });
2940
yield* fake.emit({ type: "agent_settled" });
2941
const updated = yield* takeEvent(
@@ -3922,14 +4206,11 @@ describe("PiAdapterV2", () => {
4206
"Success",
4207
`rollback on a fresh Pi runtime failed: ${result._tag === "Failure" ? String(result.failure.cause) : ""}`,
4208
);
4209
+ const args = fake.lastSpawn().args;
4210
+ assert.equal(args[args.indexOf("--session") + 1], sessionFile);
4211
const requests = fake.allRequests();
3926
- const switchIndex = requests.findIndex(
3927
- (request) => request.type === "switch_session" && request.sessionPath === sessionFile,
3928
- );
3929
- const forkIndex = requests.findIndex((request) => request.type === "fork");
3930
- assert.isAtLeast(switchIndex, 0, "fresh runtime never switched to the persisted session");
3931
- assert.isAbove(forkIndex, switchIndex, "fork ran before switching to the persisted session");
3932
- assert.equal(requests[forkIndex]?.entryId, "u2");
4212
+ assert.isFalse(requests.some((request) => request.type === "switch_session"));
4213
+ assert.equal(requests.find((request) => request.type === "fork")?.entryId, "u2");
4214
if (result._tag !== "Success") return;
4215
assert.equal(
4216
result.success.providerThread.nativeThreadRef?.nativeId,
packages/provider-pi/src/server/adapter.ts
+309
-166
@@ -30,9 +30,12 @@ import * as Cause from "effect/Cause";
30
import * as DateTime from "effect/DateTime";
31
import * as Deferred from "effect/Deferred";
32
import * as Option from "effect/Option";
33
+import * as Path from "effect/Path";
34
import * as Duration from "effect/Duration";
35
import * as Effect from "effect/Effect";
36
import * as FileSystem from "effect/FileSystem";
37
+import * as Exit from "effect/Exit";
38
+import * as Scope from "effect/Scope";
39
import * as Fiber from "effect/Fiber";
40
import * as Queue from "effect/Queue";
41
import * as Schema from "effect/Schema";
@@ -67,6 +70,7 @@ import {
70
piRecordNumber as recordNumber,
71
piRecordString as recordString,
72
type PiRpcConnection,
73
+ type PiRpcError,
74
type PiRpcRecord,
75
} from "./rpc.ts";
76
import {
@@ -439,6 +443,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
443
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
444
const agentScope = yield* AgentScope;
445
const fileSystem = yield* FileSystem.FileSystem;
446
+ const path = yield* Path.Path;
447
const idAllocator = yield* IdAllocator.IdAllocatorV2;
448
const host = yield* ProviderHost.ProviderHost;
449
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
@@ -486,31 +491,74 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
491
if (!resolvedLaunchArgs.ok) {
492
return yield* protocolError(resolvedLaunchArgs.message);
493
}
489
- const launch = buildPiRpcLaunch({
490
- launchArgs: resolvedLaunchArgs.args,
491
- environment: options.environment,
492
- mcpSession,
493
- extensionPath,
494
- runtimeMode: input.runtimePolicy.runtimeMode,
494
+ // A workspace handoff restarts Pi in a new cwd, but the session header still names the old one.
495
+ const sessionHeaderNamesCwd = Effect.fnUntraced(function* (sessionFile: string) {
496
+ const header = yield* fileSystem.stream(sessionFile).pipe(
497
+ Stream.decodeText(),
498
+ Stream.splitLines,
499
+ Stream.runHead,
500
+ Effect.map(Option.getOrUndefined),
501
+ Effect.orElseSucceed(() => undefined),
502
+ );
503
+ if (header === undefined) return true;
504
+ const sessionCwd = recordString(Option.getOrUndefined(decodeSessionHeader(header)), "cwd");
505
+ if (sessionCwd === undefined || sessionCwd === cwd) return true;
506
+ const realCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
507
+ return sessionCwd === realCwd;
508
});
496
- const scopedLaunch = yield* agentScope.wrap({
497
- command: options.settings.binaryPath || "pi",
498
- args: launch.args,
499
- name: "pi",
500
- threadId: input.threadId,
501
- env: launch.env,
509
+ // Spawning on a session from another cwd would skip the handoff fork in registerThread.
510
+ const initialSessionPath =
511
+ input.initialNativeThreadId !== undefined &&
512
+ (yield* sessionHeaderNamesCwd(input.initialNativeThreadId))
513
+ ? input.initialNativeThreadId
514
+ : undefined;
515
+ const startConnection = Effect.fnUntraced(function* (sessionPath?: string) {
516
+ const connectionScope = yield* Scope.fork(scope, "sequential");
517
+ return yield* Effect.gen(function* () {
518
+ const launch = buildPiRpcLaunch({
519
+ launchArgs: resolvedLaunchArgs.args,
520
+ environment: options.environment,
521
+ mcpSession,
522
+ extensionPath,
523
+ sessionPath,
524
+ runtimeMode: input.runtimePolicy.runtimeMode,
525
+ });
526
+ const scopedLaunch = yield* agentScope.wrap({
527
+ command: options.settings.binaryPath || "pi",
528
+ args: launch.args,
529
+ name: "pi",
530
+ threadId: input.threadId,
531
+ env: launch.env,
532
+ });
533
+ // Finalizers run in reverse order: reap detached work after terminating Pi.
534
+ const scopeUnit = scopedLaunch.unit;
535
+ const stopScope =
536
+ scopeUnit === undefined
537
+ ? Effect.void
538
+ : yield* Effect.cached(agentScope.stop(scopeUnit));
539
+ yield* Effect.addFinalizer(() => stopScope);
540
+ const connection = yield* makePiRpcConnection({
541
+ command: scopedLaunch.command,
542
+ args: scopedLaunch.args,
543
+ cwd,
544
+ env: launch.env,
545
+ });
546
+ // Detached children can keep stdout open after Pi exits.
547
+ if (scopeUnit !== undefined) {
548
+ yield* connection.exited.pipe(
549
+ Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }),
550
+ Effect.forkIn(connectionScope),
551
+ );
552
+ }
553
+ return { connection, scope: connectionScope };
554
+ }).pipe(
555
+ Effect.provideService(Scope.Scope, connectionScope),
556
+ Effect.onExit((exit) =>
557
+ Exit.isFailure(exit) ? Scope.close(connectionScope, exit) : Effect.void,
558
+ ),
559
+ );
560
});
503
- // Finalizers run in reverse order: reap detached work after terminating Pi.
504
- const scopeUnit = scopedLaunch.unit;
505
- const stopScope =
506
- scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit));
507
- yield* Effect.addFinalizer(() => stopScope);
508
- const connection: PiRpcConnection = yield* makePiRpcConnection({
509
- command: scopedLaunch.command,
510
- args: scopedLaunch.args,
511
- cwd,
512
- env: launch.env,
513
- }).pipe(
561
+ let started = yield* startConnection(initialSessionPath).pipe(
562
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
563
Effect.mapError(
564
(cause) =>
@@ -521,13 +569,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
569
}),
570
),
571
);
524
- // Detached children can keep stdout open after Pi exits.
525
- if (scopeUnit !== undefined) {
526
- yield* connection.exited.pipe(
527
- Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }),
528
- Effect.forkIn(scope),
529
- );
530
- }
572
+ let connection: PiRpcConnection = started.connection;
573
+ const initialActivationDone = yield* Deferred.make<void>();
574
+ let initialActivationPending = initialSessionPath !== undefined;
575
+ let initialRequestStarted = false;
576
const now = yield* DateTime.now;
577
let sessionEntity: OrchestrationV2ProviderSession = {
578
id: input.providerSessionId,
@@ -562,8 +607,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
607
// Pi can settle immediately after dialog response; serialize so terminal cannot overtake request resolution.
608
const sessionEventPermit = yield* Semaphore.make(1);
609
let threadState: PiThreadState | null = null;
565
- let registrationAttempted = false;
566
- let lastNativeThreadId: string | null = null;
610
+ let registrationAttempted = initialSessionPath !== undefined;
611
+ let registrationInProgress = false;
612
+ let lastNativeThreadId: string | null = initialSessionPath ?? null;
613
let stopRequested = false;
614
let unsolicitedActivityDetected = false;
615
// Turn failures can leave Pi alive; pump termination retires the runtime.
@@ -779,8 +825,47 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
825
return ordinal;
826
};
827
782
- const request = (record: PiRpcRecord, timeoutMs = PI_REQUEST_TIMEOUT_MS) =>
783
- connection.request(record, timeoutMs);
828
+ const request = Effect.fnUntraced(function* (
829
+ record: PiRpcRecord,
830
+ timeoutMs = PI_REQUEST_TIMEOUT_MS,
831
+ ) {
832
+ if (!initialActivationPending || initialRequestStarted)
833
+ return yield* connection.request(record, timeoutMs);
834
+ initialRequestStarted = true;
835
+ return yield* connection.request(record, timeoutMs).pipe(
836
+ Effect.catchTags({
837
+ PiRpcError: Effect.fn("PiAdapter.recoverSpawnSession")(function* (error: PiRpcError) {
838
+ if (
839
+ closed ||
840
+ stopRequested ||
841
+ unsolicitedActivityDetected ||
842
+ (error.operation !== "read" && error.operation !== "write")
843
+ )
844
+ return yield* error;
845
+ // Pi can exit on an unusable --session before RPC starts.
846
+ // Finish failing its queue before retiring the readers.
847
+ yield* Queue.fail(connection.events, error);
848
+ yield* Scope.close(started.scope, Exit.void);
849
+ yield* sessionEventPermit.withPermits(1)(cancelPendingPrompts(yield* DateTime.now));
850
+ started = yield* startConnection().pipe(
851
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
852
+ );
853
+ connection = started.connection;
854
+ if (closed || stopRequested) {
855
+ yield* connection.terminate;
856
+ return yield* error;
857
+ }
858
+ return yield* connection.request(record, timeoutMs);
859
+ }),
860
+ }),
861
+ Effect.ensuring(
862
+ Effect.gen(function* () {
863
+ initialActivationPending = false;
864
+ yield* Deferred.succeed(initialActivationDone, undefined);
865
+ }),
866
+ ),
867
+ );
868
+ });
869
870
const nonNegativeInteger = (input: unknown, key: string): number | undefined => {
871
const value = recordNumber(input, key);
@@ -2601,7 +2686,19 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2686
2687
yield* Effect.gen(function* () {
2688
while (true) {
2604
- const event = yield* Queue.take(connection.events);
2689
+ const activeConnection = connection;
2690
+ const event = yield* Queue.take(activeConnection.events).pipe(
2691
+ Effect.catchTags({
2692
+ // Untraced: this runs inside the per-event pump loop.
2693
+ PiRpcError: Effect.fnUntraced(function* (error: PiRpcError) {
2694
+ // Let activation replace the failed startup before publishing its transport error.
2695
+ if (initialActivationPending) yield* Deferred.await(initialActivationDone);
2696
+ if (activeConnection !== connection) return undefined;
2697
+ return yield* error;
2698
+ }),
2699
+ }),
2700
+ );
2701
+ if (event === undefined || activeConnection !== connection) continue;
2702
yield* sessionEventPermit.withPermits(1)(
2703
Effect.gen(function* () {
2704
// Tracked here rather than in handleSessionEvent, which also
@@ -2759,147 +2856,186 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2856
).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
2857
});
2858
2762
- // A workspace handoff restarts Pi in a new cwd, but the session header still names the old one.
2859
const sessionFileInCwd = Effect.fnUntraced(function* (
2860
sessionFile: string,
2861
providerThreadCreatedAt: DateTime.Utc,
2862
) {
2767
- const header = yield* fileSystem.stream(sessionFile).pipe(
2768
- Stream.decodeText(),
2769
- Stream.splitLines,
2770
- Stream.runHead,
2771
- Effect.map(Option.getOrUndefined),
2772
- Effect.orElseSucceed(() => undefined),
2773
- );
2774
- if (header === undefined) return sessionFile;
2775
- const sessionCwd = recordString(Option.getOrUndefined(decodeSessionHeader(header)), "cwd");
2776
- if (sessionCwd === undefined || sessionCwd === cwd) return sessionFile;
2777
- const realCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
2778
- if (sessionCwd === realCwd) return sessionFile;
2863
+ if (yield* sessionHeaderNamesCwd(sessionFile)) return sessionFile;
2864
return yield* forkSessionIntoCwd(sessionFile, { type: "nothing" }, providerThreadCreatedAt);
2865
});
2866
2782
- const registerThread = Effect.fnUntraced(function* (
2783
- threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput,
2784
- publish = true,
2785
- ) {
2786
- if (rollbackBarrier !== null)
2787
- return yield* protocolError("Cannot register a Pi thread during rollback");
2788
- if (threadState !== null && threadState.activeTurn !== null) {
2789
- return yield* protocolError("Cannot register a Pi thread while a turn is active");
2790
- }
2791
- if (pendingWake !== null) {
2792
- const state = threadState;
2793
- if (
2794
- state !== null &&
2795
- state === pendingWake.state &&
2796
- state.providerThread.appThreadId === threadInput.threadId &&
2797
- (threadInput.existingProviderThread === undefined ||
2798
- threadInput.existingProviderThread.nativeThreadRef?.nativeId ===
2799
- state.providerThread.nativeThreadRef?.nativeId)
2800
- )
2801
- return state.providerThread;
2802
- return yield* protocolError(
2803
- "Cannot switch Pi threads while native work is awaiting a turn",
2804
- );
2805
- }
2806
- const existing = threadInput.existingProviderThread;
2807
- const resumeId = existing?.nativeThreadRef?.nativeId;
2808
- const needsNewSession = resumeId == null && registrationAttempted;
2809
- registrationAttempted = true;
2810
- if (resumeId != null || needsNewSession) {
2811
- lastNativeThreadId = resumeId ?? lastNativeThreadId;
2812
- // Failed lifecycle operations can still change native sessions; invalidate bindings and defaults.
2813
- threadState = null;
2814
- appliedModel = null;
2815
- appliedThinking = null;
2816
- appliedSessionName = null;
2817
- baselineModel = null;
2818
- baselineThinking = null;
2819
- contextWindow = null;
2820
- const result = yield* lifecycleRequest(
2821
- resumeId != null && existing !== undefined
2822
- ? {
2823
- type: "switch_session",
2824
- sessionPath: yield* sessionFileInCwd(resumeId, existing.createdAt),
2825
- }
2826
- : { type: "new_session" },
2827
- );
2828
- if (recordField(result, "cancelled") === true) {
2829
- return yield* protocolError("A Pi extension cancelled the session switch");
2867
+ const registerThread = Effect.fnUntraced(
2868
+ function* (
2869
+ threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput,
2870
+ publish = true,
2871
+ ) {
2872
+ if (rollbackBarrier !== null)
2873
+ return yield* protocolError("Cannot register a Pi thread during rollback");
2874
+ if (threadState !== null && threadState.activeTurn !== null) {
2875
+ return yield* protocolError("Cannot register a Pi thread while a turn is active");
2876
}
2831
- }
2832
- const stateData = yield* request({ type: "get_state" });
2833
- if (discoveredModels === null) yield* discoverModels();
2834
- contextWindow = rememberModelContextWindow(recordField(stateData, "model"));
2835
- // Capture each baseline before applying selections so our own choices cannot become Pi defaults.
2836
- if (baselineModel === null && appliedModel === null) {
2837
- const stateModel = recordField(stateData, "model");
2838
- const provider = recordString(stateModel, "provider");
2839
- const modelId = recordString(stateModel, "id");
2840
- if (provider !== undefined && modelId !== undefined) {
2841
- baselineModel = { provider, modelId };
2877
+ if (pendingWake !== null) {
2878
+ const state = threadState;
2879
+ if (
2880
+ state !== null &&
2881
+ state === pendingWake.state &&
2882
+ state.providerThread.appThreadId === threadInput.threadId &&
2883
+ (threadInput.existingProviderThread === undefined ||
2884
+ threadInput.existingProviderThread.nativeThreadRef?.nativeId ===
2885
+ state.providerThread.nativeThreadRef?.nativeId)
2886
+ )
2887
+ return state.providerThread;
2888
+ return yield* protocolError(
2889
+ "Cannot switch Pi threads while native work is awaiting a turn",
2890
+ );
2891
}
2843
- }
2844
- if (baselineThinking === null && appliedThinking === null) {
2845
- baselineThinking = recordString(stateData, "thinkingLevel") ?? null;
2846
- appliedThinking = baselineThinking;
2847
- }
2848
- // switch_session accepts a file path, not Pi's display session UUID.
2849
- const nativeId = recordString(stateData, "sessionFile");
2850
- if (nativeId === undefined) {
2851
- return yield* protocolError("get_state returned no persisted sessionFile", stateData);
2852
- }
2853
- if (needsNewSession && nativeId === lastNativeThreadId) {
2854
- return yield* protocolError("Pi did not create a distinct session file");
2855
- }
2856
- lastNativeThreadId = nativeId;
2857
- const createdAt = yield* DateTime.now;
2858
- const providerThread: OrchestrationV2ProviderThread =
2859
- existing !== undefined
2860
- ? {
2861
- ...existing,
2862
- providerSessionId: input.providerSessionId,
2863
- nativeThreadRef: providerRef(nativeId),
2864
- ...(needsNewSession ? { nativeConversationHeadRef: null, contextUsage: null } : {}),
2865
- status: "idle",
2866
- updatedAt: createdAt,
2867
- }
2868
- : {
2869
- id: idAllocator.derive.providerThread({
2892
+ const existing = threadInput.existingProviderThread;
2893
+ const resumeId = existing?.nativeThreadRef?.nativeId;
2894
+ const needsNewSession = resumeId == null && registrationAttempted;
2895
+ registrationAttempted = true;
2896
+ // This probe replaces switch_session as a resume's first request, so it keeps the lifecycle deadline.
2897
+ // It also recovers a failed spawn session before lifecycleRequest offers to its dead queue.
2898
+ let stateData =
2899
+ resumeId != null || initialActivationPending
2900
+ ? yield* request({ type: "get_state" }, PI_SESSION_TIMEOUT_MS)
2901
+ : undefined;
2902
+ const liveSessionFile = recordString(stateData, "sessionFile");
2903
+ // Switching replaces the session and reloads extensions, so keep an already attached file.
2904
+ const alreadyOnResumeFile =
2905
+ resumeId != null &&
2906
+ liveSessionFile !== undefined &&
2907
+ path.resolve(cwd, liveSessionFile) === path.resolve(cwd, resumeId);
2908
+ if (!alreadyOnResumeFile && (resumeId != null || needsNewSession)) {
2909
+ if (pendingWake !== null) {
2910
+ return yield* protocolError(
2911
+ "Cannot switch Pi threads while native work is awaiting a turn",
2912
+ );
2913
+ }
2914
+ lastNativeThreadId = resumeId ?? lastNativeThreadId;
2915
+ // Failed lifecycle operations can still change native sessions; invalidate bindings and defaults.
2916
+ threadState = null;
2917
+ appliedModel = null;
2918
+ appliedThinking = null;
2919
+ appliedSessionName = null;
2920
+ baselineModel = null;
2921
+ baselineThinking = null;
2922
+ contextWindow = null;
2923
+ const result = yield* lifecycleRequest(
2924
+ resumeId != null && existing !== undefined
2925
+ ? {
2926
+ type: "switch_session",
2927
+ sessionPath: yield* sessionFileInCwd(resumeId, existing.createdAt),
2928
+ }
2929
+ : { type: "new_session" },
2930
+ );
2931
+ if (recordField(result, "cancelled") === true) {
2932
+ return yield* protocolError("A Pi extension cancelled the session switch");
2933
+ }
2934
+ stateData = undefined;
2935
+ }
2936
+ stateData ??= yield* request({ type: "get_state" });
2937
+ if (discoveredModels === null) yield* discoverModels();
2938
+ contextWindow = rememberModelContextWindow(recordField(stateData, "model"));
2939
+ // Capture each baseline before applying selections so our own choices cannot become Pi defaults.
2940
+ if (baselineModel === null && appliedModel === null) {
2941
+ const stateModel = recordField(stateData, "model");
2942
+ const provider = recordString(stateModel, "provider");
2943
+ const modelId = recordString(stateModel, "id");
2944
+ if (provider !== undefined && modelId !== undefined) {
2945
+ baselineModel = { provider, modelId };
2946
+ }
2947
+ }
2948
+ if (baselineThinking === null && appliedThinking === null) {
2949
+ baselineThinking = recordString(stateData, "thinkingLevel") ?? null;
2950
+ appliedThinking = baselineThinking;
2951
+ }
2952
+ // switch_session accepts a file path, not Pi's display session UUID.
2953
+ const nativeId = recordString(stateData, "sessionFile");
2954
+ if (nativeId === undefined) {
2955
+ return yield* protocolError("get_state returned no persisted sessionFile", stateData);
2956
+ }
2957
+ if (needsNewSession && nativeId === lastNativeThreadId) {
2958
+ return yield* protocolError("Pi did not create a distinct session file");
2959
+ }
2960
+ lastNativeThreadId = nativeId;
2961
+ const createdAt = yield* DateTime.now;
2962
+ const providerThread: OrchestrationV2ProviderThread =
2963
+ existing !== undefined
2964
+ ? {
2965
+ ...existing,
2966
+ providerSessionId: input.providerSessionId,
2967
+ nativeThreadRef: providerRef(nativeId),
2968
+ ...(needsNewSession
2969
+ ? { nativeConversationHeadRef: null, contextUsage: null }
2970
+ : {}),
2971
+ status: "idle",
2972
+ updatedAt: createdAt,
2973
+ }
2974
+ : {
2975
+ id: idAllocator.derive.providerThread({
2976
+ driver: PI_PROVIDER,
2977
+ nativeThreadId: nativeId,
2978
+ }),
2979
driver: PI_PROVIDER,
2871
- nativeThreadId: nativeId,
2872
- }),
2873
- driver: PI_PROVIDER,
2874
- providerInstanceId: options.instanceId,
2875
- providerSessionId: input.providerSessionId,
2876
- appThreadId: threadInput.threadId,
2877
- ownerNodeId: null,
2878
- nativeThreadRef: providerRef(nativeId),
2879
- nativeConversationHeadRef: null,
2880
- status: "idle",
2881
- firstRunOrdinal: null,
2882
- lastRunOrdinal: null,
2883
- handoffIds: [],
2884
- forkedFrom: null,
2885
- pendingBackgroundTasks: [],
2886
- createdAt,
2887
- updatedAt: createdAt,
2888
- };
2889
- threadState = { providerThread, activeTurn: null };
2890
- const baselineEntries = yield* request({ type: "get_entries" }).pipe(
2891
- Effect.orElseSucceed(() => undefined),
2892
- );
2893
- lastKnownLeaf = recordString(baselineEntries, "leafId") ?? null;
2894
- leafCursorStale = baselineEntries === undefined;
2895
- if (publish)
2896
- yield* emit({
2897
- type: "provider_thread.updated",
2898
- driver: PI_PROVIDER,
2899
- providerThread,
2900
- });
2901
- return providerThread;
2902
- });
2980
+ providerInstanceId: options.instanceId,
2981
+ providerSessionId: input.providerSessionId,
2982
+ appThreadId: threadInput.threadId,
2983
+ ownerNodeId: null,
2984
+ nativeThreadRef: providerRef(nativeId),
2985
+ nativeConversationHeadRef: null,
2986
+ status: "idle",
2987
+ firstRunOrdinal: null,
2988
+ lastRunOrdinal: null,
2989
+ handoffIds: [],
2990
+ forkedFrom: null,
2991
+ pendingBackgroundTasks: [],
2992
+ createdAt,
2993
+ updatedAt: createdAt,
2994
+ };
2995
+ if (
2996
+ threadState !== null &&
2997
+ threadState.providerThread.id === providerThread.id &&
2998
+ threadState.providerThread.appThreadId === threadInput.threadId &&
2999
+ threadState.providerThread.nativeThreadRef?.nativeId === resumeId
3000
+ ) {
3001
+ // A wake arriving during the reads still owns this same-session binding.
3002
+ threadState.providerThread = providerThread;
3003
+ } else {
3004
+ if (pendingWake !== null) {
3005
+ return yield* protocolError(
3006
+ "Cannot switch Pi threads while native work is awaiting a turn",
3007
+ );
3008
+ }
3009
+ threadState = { providerThread, activeTurn: null };
3010
+ }
3011
+ const baselineEntries = yield* request({ type: "get_entries" }).pipe(
3012
+ Effect.orElseSucceed(() => undefined),
3013
+ );
3014
+ lastKnownLeaf = recordString(baselineEntries, "leafId") ?? null;
3015
+ leafCursorStale = baselineEntries === undefined;
3016
+ if (publish)
3017
+ yield* emit({
3018
+ type: "provider_thread.updated",
3019
+ driver: PI_PROVIDER,
3020
+ providerThread,
3021
+ });
3022
+ return providerThread;
3023
+ },
3024
+ (effect) =>
3025
+ Effect.acquireUseRelease(
3026
+ Effect.suspend(() => {
3027
+ if (registrationInProgress)
3028
+ return protocolError("Cannot register a Pi thread during registration");
3029
+ registrationInProgress = true;
3030
+ return Effect.void;
3031
+ }),
3032
+ () => effect,
3033
+ () =>
3034
+ Effect.sync(() => {
3035
+ registrationInProgress = false;
3036
+ }),
3037
+ ),
3038
+ );
3039
3040
const applySelection = Effect.fnUntraced(function* (modelSelection: ModelSelection) {
3041
const thinking = getModelSelectionStringOptionValue(modelSelection, "thinking");
@@ -3066,6 +3202,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3202
}),
3203
startTurn: Effect.fn("PiAdapter.startTurn")(
3204
function* (turnInput) {
3205
+ if (registrationInProgress)
3206
+ return yield* protocolError("Cannot start a Pi turn during registration");
3207
if (rollbackBarrier !== null)
3208
return yield* protocolError("Cannot start a Pi turn during rollback");
3209
const state = threadState;
@@ -3166,6 +3304,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3304
const pendingAck = yield* Effect.gen(function* () {
3305
if (
3306
threadState !== state ||
3307
+ registrationInProgress ||
3308
state.activeTurn !== null ||
3309
closed ||
3310
stopRequested ||
@@ -3510,6 +3649,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3649
),
3650
rollbackThread: Effect.fn("PiAdapter.rollbackThread")(
3651
function* (rollbackInput) {
3652
+ if (registrationInProgress)
3653
+ return yield* protocolError("Cannot roll back a Pi thread during registration");
3654
// A fresh runtime (restart or idle release) must load the persisted session before forking.
3655
// Unpublished: the rollback service persists the returned snapshot.
3656
if (
@@ -3555,6 +3696,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3696
Effect.gen(function* () {
3697
if (
3698
rollbackBarrier !== null ||
3699
+ registrationInProgress ||
3700
threadState !== state ||
3701
state.activeTurn !== null ||
3702
pendingWake !== null ||
@@ -4002,6 +4144,7 @@ function piUiResponse(
4144
export type PiAdapterV2DriverEnv =
4145
| ChildProcessSpawner.ChildProcessSpawner
4146
| FileSystem.FileSystem
4147
+ | Path.Path
4148
| IdAllocator.IdAllocatorV2
4149
| McpProviderSessions.McpProviderSessions
4150
| ProviderHost.ProviderHost;