@@ -516,7 +516,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
516516 > ( ) ;
517517 const pendingPrompts = new Map < string , PendingPiPrompt > ( ) ;
518518 const sessionApprovals = new Set < string > ( ) ;
519- let lifecycleInFlight = false ;
519+ let lifecycleRequestsInFlight = 0 ;
520520 // Answering a dialog and terminalizing a turn both publish lifecycle
521521 // events. Pi can settle immediately after `extension_ui_response`, so
522522 // serialize the two paths to stop `turn.terminal` from overtaking the
@@ -641,26 +641,29 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
641641 } ;
642642
643643 const lifecycleRequest = ( record : PiRpcRecord ) =>
644- Effect . suspend ( ( ) => {
645- sessionApprovals . clear ( ) ;
646- lifecycleInFlight = true ;
647- return request ( record , PI_SESSION_TIMEOUT_MS ) ;
648- } ) . pipe (
649- // A local timeout does not cancel Pi's lifecycle hook. Retire the
650- // process before fallback can race its eventual switch/new-session.
651- Effect . tapError ( ( error ) =>
652- Effect . logWarning ( "Pi session lifecycle request failed" , {
653- providerSessionId : input . providerSessionId ,
654- operation : record [ "type" ] ,
655- errorTag : error . _tag ,
656- } ) ,
657- ) ,
658- Effect . catchTags ( {
659- PiRpcTimeoutError : ( error ) =>
660- connection . terminate . pipe ( Effect . andThen ( Effect . fail ( error ) ) ) ,
644+ Effect . acquireUseRelease (
645+ Effect . sync ( ( ) => {
646+ sessionApprovals . clear ( ) ;
647+ lifecycleRequestsInFlight ++ ;
661648 } ) ,
662- Effect . onInterrupt ( ( ) => connection . terminate ) ,
663- Effect . ensuring ( Effect . sync ( ( ) => ( lifecycleInFlight = false ) ) ) ,
649+ ( ) =>
650+ request ( record , PI_SESSION_TIMEOUT_MS ) . pipe (
651+ // A local timeout does not cancel Pi's lifecycle hook. Retire the
652+ // process before fallback can race its eventual switch/new-session.
653+ Effect . tapError ( ( error ) =>
654+ Effect . logWarning ( "Pi session lifecycle request failed" , {
655+ providerSessionId : input . providerSessionId ,
656+ operation : record [ "type" ] ,
657+ errorTag : error . _tag ,
658+ } ) ,
659+ ) ,
660+ Effect . catchTags ( {
661+ PiRpcTimeoutError : ( error ) =>
662+ connection . terminate . pipe ( Effect . andThen ( Effect . fail ( error ) ) ) ,
663+ } ) ,
664+ Effect . onInterrupt ( ( ) => connection . terminate ) ,
665+ ) ,
666+ ( ) => Effect . sync ( ( ) => lifecycleRequestsInFlight -- ) ,
664667 ) ;
665668
666669 const tokenUsageFromStats = (
@@ -2763,7 +2766,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
27632766 if (
27642767 pending . method === "confirm" &&
27652768 requestInput . decision === "acceptForSession" &&
2766- ! lifecycleInFlight
2769+ lifecycleRequestsInFlight === 0
27672770 ) {
27682771 sessionApprovals . add ( pending . approvalKey ) ;
27692772 }
0 commit comments