@@ -2,6 +2,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
22import { AgentScope } from "@t3tools/shared/AgentScope" ;
33import { getModelSelectionStringOptionValue } from "@t3tools/shared/model" ;
44import { readToolOutputImage } from "@t3tools/shared/toolOutput" ;
5+ import * as NodeUtil from "node:util" ;
56import * as Predicate from "effect/Predicate" ;
67import {
78 defaultInstanceIdForDriver ,
@@ -90,13 +91,14 @@ const PI_SESSION_TIMEOUT_MS = 60_000;
9091const PI_UNSOLICITED_ACTIVITY_ERROR =
9192 "Pi started agent work outside an active T3 turn. The session was stopped to prevent invisible tool execution." ;
9293const SETTLE_PROBE_MAX_ATTEMPTS = 3 ;
94+ const SETTLE_PROBE_RETRY_DELAY = Duration . millis ( 100 ) ;
9395/**
9496 * Pi has no native signal for extension work that outlives a turn. Extensions
95- * hold a status under this key, or `<key>:<job>`, until the work ends, so the
96- * idle release keeps the process (and the work) alive.
97+ * hold a status under this key, or `<key>:<job>`, until the work ends. Each one
98+ * is a pending background task, so the idle release keeps the process (and the
99+ * work) alive and Stop can end it.
97100 */
98101const PI_BACKGROUND_WORK_STATUS_KEY = "t3:background" ;
99- const SETTLE_PROBE_RETRY_DELAY = Duration . millis ( 100 ) ;
100102
101103const PiProviderCapabilitiesV2 = {
102104 runtimePolicy : { enforcement : "client-boundary" } ,
@@ -545,7 +547,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
545547 let stopRequested = false ;
546548 let unsolicitedActivityDetected = false ;
547549 let pendingWake : PiWake | null = null ;
548- const backgroundWorkStatusKeys = new Set < string > ( ) ;
550+ // Status key to its text, which becomes the task description.
551+ const backgroundWork = new Map < string , string > ( ) ;
552+ // The thread whose roster lists backgroundWork, kept past lifecycle
553+ // failures that clear threadState so its roster can still be emptied.
554+ let backgroundWorkState : PiThreadState | null = null ;
549555 let rollbackBarrier : Deferred . Deferred <
550556 void ,
551557 ProviderAdapter . ProviderAdapterProtocolError
@@ -555,6 +561,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
555561 Effect . gen ( function * ( ) {
556562 closed = true ;
557563 pendingWake = null ;
564+ backgroundWork . clear ( ) ;
558565 if ( rollbackBarrier !== null )
559566 yield * Deferred . fail (
560567 rollbackBarrier ,
@@ -660,8 +667,27 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
660667 return null ;
661668 } ;
662669
663- const lifecycleRequest = ( record : PiRpcRecord ) =>
664- request ( record , PI_SESSION_TIMEOUT_MS ) . pipe (
670+ const pendingBackgroundTasks = ( ) =>
671+ Array . from ( backgroundWork , ( [ taskId , description ] ) => ( {
672+ taskId,
673+ kind : "background_task" as const ,
674+ description,
675+ } ) ) ;
676+
677+ const syncBackgroundWork = ( state : PiThreadState ) => {
678+ backgroundWorkState = state ;
679+ return updateProviderThread ( state , { pendingBackgroundTasks : pendingBackgroundTasks ( ) } ) ;
680+ } ;
681+
682+ const lifecycleRequest = Effect . fnUntraced ( function * ( record : PiRpcRecord ) {
683+ // Pi invalidates the outgoing session's extension context, so its jobs
684+ // can no longer clear their statuses. Pi's own TUI drops them here too.
685+ const outgoingWork = new Map ( backgroundWork ) ;
686+ const outgoingState = backgroundWorkState ;
687+ backgroundWork . clear ( ) ;
688+ if ( outgoingState !== null && outgoingWork . size > 0 )
689+ yield * syncBackgroundWork ( outgoingState ) ;
690+ const result = yield * request ( record , PI_SESSION_TIMEOUT_MS ) . pipe (
665691 // A local timeout does not cancel Pi's lifecycle hook. Retire the
666692 // process before fallback can race its eventual switch/new-session.
667693 Effect . tapError ( ( error ) =>
@@ -677,6 +703,14 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
677703 } ) ,
678704 Effect . onInterrupt ( ( ) => connection . terminate ) ,
679705 ) ;
706+ if ( recordField ( result , "cancelled" ) === true && outgoingWork . size > 0 ) {
707+ for ( const [ key , description ] of outgoingWork ) {
708+ if ( ! backgroundWork . has ( key ) ) backgroundWork . set ( key , description ) ;
709+ }
710+ if ( outgoingState !== null ) yield * syncBackgroundWork ( outgoingState ) ;
711+ }
712+ return result ;
713+ } ) ;
680714
681715 const tokenUsageFromStats = (
682716 stats : unknown ,
@@ -1249,11 +1283,16 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
12491283 ) {
12501284 return ;
12511285 }
1252- if ( ( recordString ( event , "statusText" ) ?? "" ) . length > 0 ) {
1253- backgroundWorkStatusKeys . add ( statusKey ) ;
1254- } else {
1255- backgroundWorkStatusKeys . delete ( statusKey ) ;
1286+ const description = NodeUtil . stripVTControlCharacters (
1287+ recordString ( event , "statusText" ) ?? "" ,
1288+ ) . trim ( ) ;
1289+ if ( description . length > 0 ) {
1290+ if ( backgroundWork . get ( statusKey ) === description ) return ;
1291+ backgroundWork . set ( statusKey , description ) ;
1292+ } else if ( ! backgroundWork . delete ( statusKey ) ) {
1293+ return ;
12561294 }
1295+ if ( threadState !== null ) yield * syncBackgroundWork ( threadState ) ;
12571296 return ;
12581297 }
12591298 if ( method === "notify" ) {
@@ -2269,6 +2308,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
22692308 providerSessionId : input . providerSessionId ,
22702309 nativeThreadRef : providerRef ( nativeId ) ,
22712310 ...( needsNewSession ? { nativeConversationHeadRef : null , contextUsage : null } : { } ) ,
2311+ pendingBackgroundTasks : pendingBackgroundTasks ( ) ,
22722312 status : "idle" ,
22732313 updatedAt : createdAt ,
22742314 }
@@ -2289,11 +2329,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
22892329 lastRunOrdinal : null ,
22902330 handoffIds : [ ] ,
22912331 forkedFrom : null ,
2292- pendingBackgroundTasks : [ ] ,
2332+ pendingBackgroundTasks : pendingBackgroundTasks ( ) ,
22932333 createdAt,
22942334 updatedAt : createdAt ,
22952335 } ;
22962336 threadState = { providerThread, activeTurn : null } ;
2337+ backgroundWorkState = threadState ;
22972338 const baselineEntries = yield * request ( { type : "get_entries" } ) . pipe (
22982339 Effect . orElseSucceed ( ( ) => undefined ) ,
22992340 ) ;
@@ -2397,12 +2438,15 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
23972438 } ,
23982439 events : Stream . fromQueue ( events ) ,
23992440 hasPendingBackgroundWork : Effect . sync (
2400- ( ) => pendingWake !== null || backgroundWorkStatusKeys . size > 0 ,
2441+ ( ) => pendingWake !== null || backgroundWork . size > 0 ,
24012442 ) ,
24022443 hasPendingBackgroundWorkForThread : ( providerThread ) =>
24032444 Effect . sync (
2404- ( ) => pendingWake !== null && pendingWake . state . providerThread . id === providerThread . id ,
2445+ ( ) =>
2446+ ( pendingWake !== null && pendingWake . state . providerThread . id === providerThread . id ) ||
2447+ ( backgroundWork . size > 0 && threadState ?. providerThread . id === providerThread . id ) ,
24052448 ) ,
2449+ backgroundTasksEndWithProcess : true ,
24062450 getModelContextWindow : ( selection ) => {
24072451 if ( selection . instanceId !== options . instanceId ) return undefined ;
24082452 const slug =
@@ -2706,6 +2750,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
27062750 if ( turn === null && interruptInput . requestRuntimeRestart === true ) {
27072751 if ( pendingWake !== null )
27082752 yield * sessionEventPermit . withPermits ( 1 ) ( stopPendingWake ( pendingWake ) ) ;
2753+ else if ( backgroundWork . size > 0 ) {
2754+ stopRequested = true ;
2755+ backgroundWork . clear ( ) ;
2756+ yield * connection . terminate ;
2757+ }
27092758 return ;
27102759 }
27112760 if ( turn === null || turn . providerTurn . id !== interruptInput . providerTurnId ) {
0 commit comments