@@ -31,6 +31,7 @@ import * as Option from "effect/Option";
3131import * as Duration from "effect/Duration" ;
3232import * as Effect from "effect/Effect" ;
3333import * as FileSystem from "effect/FileSystem" ;
34+ import * as Path from "effect/Path" ;
3435import * as Fiber from "effect/Fiber" ;
3536import * as Queue from "effect/Queue" ;
3637import * as Schema from "effect/Schema" ;
@@ -427,6 +428,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
427428 const spawner = yield * ChildProcessSpawner . ChildProcessSpawner ;
428429 const agentScope = yield * AgentScope ;
429430 const fileSystem = yield * FileSystem . FileSystem ;
431+ const path = yield * Path . Path ;
430432 const idAllocator = yield * IdAllocator . IdAllocatorV2 ;
431433 const host = yield * ProviderHost . ProviderHost ;
432434 const mcpSessions = yield * McpProviderSessions . McpProviderSessions ;
@@ -439,6 +441,67 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
439441 ...( payload === undefined ? { } : { payload } ) ,
440442 } ) ;
441443
444+ const readForkSession = Effect . fn ( "PiAdapter.readForkSession" ) (
445+ function * ( file : string , targetId ?: string ) {
446+ const contents = yield * fileSystem . readFileString ( file ) ;
447+ if ( targetId !== undefined && ! contents . includes ( targetId ) ) return null ;
448+ const records : Array < unknown > = [ ] ;
449+ for ( const line of contents . split ( "\n" ) ) {
450+ if ( line . trim ( ) . length === 0 ) continue ;
451+ const record = Option . getOrNull ( decodePiSessionLine ( line ) ) ;
452+ if ( record === null ) return null ;
453+ records . push ( record ) ;
454+ }
455+ if ( recordField ( records [ 0 ] , "type" ) !== "session" || recordField ( records [ 0 ] , "version" ) !== 3 )
456+ return null ;
457+ const entries = records . slice ( 1 ) ;
458+ const listing = piSessionListing ( {
459+ entries,
460+ leafId : recordString ( entries . at ( - 1 ) , "id" ) ?? null ,
461+ } ) ;
462+ return listing === null
463+ ? null
464+ : { listing, parentSession : recordString ( records [ 0 ] , "parentSession" ) } ;
465+ } ,
466+ Effect . orElseSucceed ( ( ) => null ) ,
467+ ) ;
468+
469+ const findForkSource = Effect . fn ( "PiAdapter.findForkSource" ) ( function * (
470+ sourceFile : string ,
471+ boundary : PiForkBoundary ,
472+ createdAt : DateTime . Utc ,
473+ ) {
474+ const targetRef = boundary . type === "uncaptured" ? boundary . target ?. nativeTurnRef : undefined ;
475+ if (
476+ boundary . type !== "uncaptured" ||
477+ targetRef ?. strength !== "strong" ||
478+ targetRef . nativeId === null
479+ )
480+ return sourceFile ;
481+ const current = yield * readForkSession ( sourceFile ) ;
482+ if ( current === null || current . listing . entries . has ( targetRef . nativeId ) ) return sourceFile ;
483+ const directory = path . dirname ( sourceFile ) ;
484+ const files = yield * fileSystem . readDirectory ( directory ) . pipe ( Effect . orElseSucceed ( ( ) => [ ] ) ) ;
485+ const matches = new Map < string , string | undefined > ( ) ;
486+ for ( const name of files ) {
487+ const file = path . resolve ( directory , name ) ;
488+ if ( file === path . resolve ( sourceFile ) || ! name . endsWith ( ".jsonl" ) ) continue ;
489+ const session = yield * readForkSession ( file , targetRef . nativeId ) ;
490+ if (
491+ session === null ||
492+ piPreviousSessionForkBoundary ( session . listing , boundary , createdAt ) === undefined
493+ )
494+ continue ;
495+ matches . set (
496+ file ,
497+ session . parentSession === undefined ? undefined : path . resolve ( session . parentSession ) ,
498+ ) ;
499+ }
500+ // Pi fork copies retain entry IDs and point to their source with parentSession.
501+ const roots = [ ...matches ] . filter ( ( [ , parent ] ) => parent === undefined || ! matches . has ( parent ) ) ;
502+ return roots . length === 1 ? roots [ 0 ] ! [ 0 ] : sourceFile ;
503+ } ) ;
504+
442505 return ProviderAdapter . ProviderAdapterV2 . of ( {
443506 instanceId : options . instanceId ,
444507 driver : PI_PROVIDER ,
@@ -3259,6 +3322,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
32593322 target : { type : "provider_turn" , providerTurn : target } ,
32603323 providerThreadTurns : sourceTurns ,
32613324 } ) ;
3325+ const forkSourceFile = yield * findForkSource ( sourceFile , boundary , source . createdAt ) ;
32623326 // CLI --fork uses Pi's own session format and sets the destination cwd. RPC
32633327 // switch_session/clone alone would retain the source cwd.
32643328 const forkLaunch = buildPiRpcLaunch ( {
@@ -3274,7 +3338,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
32743338 Effect . gen ( function * ( ) {
32753339 const forkConnection = yield * makePiRpcConnection ( {
32763340 command : options . settings . binaryPath || "pi" ,
3277- args : [ ...forkLaunch . args , "--fork" , sourceFile ] ,
3341+ args : [ ...forkLaunch . args , "--fork" , forkSourceFile ] ,
32783342 cwd,
32793343 env : forkLaunch . env ,
32803344 } ) ;
@@ -3283,11 +3347,26 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
32833347 Effect . ignore ,
32843348 Effect . forkScoped ,
32853349 ) ;
3350+ let forkBoundary = boundary ;
3351+ if ( forkSourceFile !== sourceFile && boundary . type === "uncaptured" ) {
3352+ const listing = piSessionListing (
3353+ yield * forkConnection . request ( { type : "get_entries" } ) ,
3354+ ) ;
3355+ const recovered =
3356+ listing === null
3357+ ? undefined
3358+ : piPreviousSessionForkBoundary ( listing , boundary , source . createdAt ) ;
3359+ if ( recovered === undefined )
3360+ return yield * protocolError (
3361+ "Pi fork target is no longer recoverable in its previous session" ,
3362+ ) ;
3363+ forkBoundary = recovered ;
3364+ }
32863365 const beforeEntry =
3287- boundary . type === "nothing"
3366+ forkBoundary . type === "nothing"
32883367 ? null
32893368 : yield * piForkEntry (
3290- boundary ,
3369+ forkBoundary ,
32913370 source . createdAt ,
32923371 forkConnection . request ( { type : "get_entries" } ) ,
32933372 ) ;
@@ -3302,7 +3381,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
33023381 }
33033382 const state = yield * forkConnection . request ( { type : "get_state" } ) ;
33043383 const file = recordString ( state , "sessionFile" ) ;
3305- if ( file === undefined || file === sourceFile ) {
3384+ if ( file === undefined || file === sourceFile || file === forkSourceFile ) {
33063385 return yield * protocolError ( "Pi fork did not create a distinct session file" ) ;
33073386 }
33083387 return file ;
@@ -3363,6 +3442,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
33633442
33643443interface PiSessionEntry {
33653444 readonly parentId : string | null ;
3445+ readonly isMessage : boolean ;
33663446 readonly isUserMessage : boolean ;
33673447 /** Pi's `timestamp` as epoch milliseconds; null when missing or unparsable. */
33683448 readonly timestamp : number | null ;
@@ -3373,6 +3453,8 @@ interface PiSessionListing {
33733453 readonly leafId : string | null ;
33743454}
33753455
3456+ const decodePiSessionLine = Schema . decodeUnknownOption ( Schema . fromJsonString ( Schema . Unknown ) ) ;
3457+
33763458function piSessionListing ( data : unknown ) : PiSessionListing | null {
33773459 const leafId = recordField ( data , "leafId" ) ;
33783460 const entries = piSessionEntries ( recordField ( data , "entries" ) ) ;
@@ -3392,6 +3474,8 @@ function piSessionEntries(entries: unknown): ReadonlyMap<string, PiSessionEntry>
33923474 const timestamp = recordString ( entry , "timestamp" ) ;
33933475 byId . set ( id , {
33943476 parentId,
3477+ isMessage :
3478+ recordField ( entry , "type" ) === "message" || recordField ( entry , "type" ) === "custom_message" ,
33953479 isUserMessage :
33963480 recordField ( entry , "type" ) === "message" &&
33973481 recordString ( recordField ( entry , "message" ) , "role" ) === "user" ,
@@ -3516,6 +3600,46 @@ function piUncapturedForkEntry(
35163600 return earliest ;
35173601}
35183602
3603+ function piPreviousSessionForkBoundary (
3604+ listing : PiSessionListing ,
3605+ boundary : Extract < PiForkBoundary , { type : "uncaptured" } > ,
3606+ createdAt : DateTime . Utc ,
3607+ ) : PiForkBoundary | undefined {
3608+ const target = boundary . target ;
3609+ const ref = target ?. nativeTurnRef ;
3610+ if (
3611+ ref ?. strength !== "strong" ||
3612+ ref . nativeId === null ||
3613+ target ?. startedAt == null ||
3614+ target . completedAt === null
3615+ )
3616+ return undefined ;
3617+ const entry = listing . entries . get ( ref . nativeId ) ;
3618+ const end = DateTime . toEpochMillis ( target . completedAt ) ;
3619+ if (
3620+ entry ?. isUserMessage !== true ||
3621+ entry . timestamp === null ||
3622+ entry . timestamp < DateTime . toEpochMillis ( target . startedAt ) ||
3623+ entry . timestamp > end
3624+ )
3625+ return undefined ;
3626+ const walk = walkPiBranch ( listing . entries , listing . leafId , ref . nativeId ) ;
3627+ if ( walk ?. reachedStop !== true ) return undefined ;
3628+ const before = piUncapturedForkEntry ( listing , boundary , createdAt ) ;
3629+ if ( before !== undefined ) return { type : "entry" , entryId : before } ;
3630+ let current = listing . leafId ;
3631+ while ( current !== null && current !== ref . nativeId ) {
3632+ const message = listing . entries . get ( current ) ;
3633+ if (
3634+ message === undefined ||
3635+ ( message . isMessage && ( message . timestamp === null || message . timestamp > end ) )
3636+ )
3637+ return undefined ;
3638+ current = message . parentId ;
3639+ }
3640+ return { type : "nothing" } ;
3641+ }
3642+
35193643function piSubagentOutput ( result : unknown ) : string {
35203644 const stopReason = recordString ( result , "stopReason" ) ;
35213645 const failed =
@@ -3609,6 +3733,7 @@ function piUiResponse(
36093733export type PiAdapterV2DriverEnv =
36103734 | ChildProcessSpawner . ChildProcessSpawner
36113735 | FileSystem . FileSystem
3736+ | Path . Path
36123737 | IdAllocator . IdAllocatorV2
36133738 | McpProviderSessions . McpProviderSessions
36143739 | ProviderHost . ProviderHost ;
0 commit comments