@@ -1216,11 +1216,19 @@ export const layerWithOptions = (
12161216 // Capture runtime identity before yielding; replacements can reuse the session id.
12171217 const probedRuntime = entry . runtime ;
12181218 const hasPendingWork =
1219- probedRuntime . hasPendingBackgroundWork === undefined
1219+ ( probedRuntime . hasPendingBackgroundWork === undefined
12201220 ? false
12211221 : yield * probedRuntime . hasPendingBackgroundWork . pipe (
12221222 Effect . catchCause ( ( ) => Effect . succeed ( false ) ) ,
1223- ) ;
1223+ ) ) ||
1224+ // Closing now would skip the archive of a child whose parent has not taken its result.
1225+ Option . isSome (
1226+ yield * Effect . findFirst ( entry . idleThreadUnloads . keys ( ) , ( threadId ) =>
1227+ delegatedChildArchive ( threadId ) . pipe (
1228+ Effect . map ( ( child ) => child === "awaiting_delivery" ) ,
1229+ ) ,
1230+ ) ,
1231+ ) ;
12241232 if ( hasPendingWork ) {
12251233 const now = yield * Clock . currentTimeMillis ;
12261234 const pinnedSinceMs = entry . pinnedSinceMs ?? now ;
@@ -1255,6 +1263,18 @@ export const layerWithOptions = (
12551263 pinnedForMs : now - pinnedSinceMs ,
12561264 } ) ;
12571265 }
1266+ // Closing skips the threads' own idle unloads, so archive delivered children first.
1267+ yield * Effect . forEach (
1268+ entry . idleThreadUnloads ,
1269+ ( [ threadId , pending ] ) =>
1270+ unloadIdleThread ( {
1271+ providerSessionId : input . providerSessionId ,
1272+ threadId,
1273+ generation : pending . generation ,
1274+ archiveOnly : true ,
1275+ } ) ,
1276+ { discard : true } ,
1277+ ) ;
12581278 // Adapter probes yield; guard busyTurns and idleGeneration atomically when removing the entry.
12591279 yield * releaseEntry ( {
12601280 providerSessionId : input . providerSessionId ,
@@ -1672,11 +1692,44 @@ export const layerWithOptions = (
16721692 } ,
16731693 ) ;
16741694
1695+ // Provider clients list a delegated child as an ordinary conversation, so a
1696+ // finished one is archived once its parent has the result.
1697+ const delegatedChildArchive = Effect . fn ( "ProviderSessionManager.delegatedChildArchive" ) (
1698+ function * ( threadId : ThreadId ) {
1699+ const { thread, runs } = yield * projectionStore . getThreadRecords ( threadId , [ "runs" ] , {
1700+ runStatuses : [ ] ,
1701+ includeLatestRun : true ,
1702+ } ) ;
1703+ // Follow-up tasks name their run; the initial task is the node the child forked from.
1704+ const taskId =
1705+ runs . at ( - 1 ) ?. delegatedTaskId ??
1706+ ( thread . forkedFrom ?. type === "node" ? thread . forkedFrom . nodeId : undefined ) ;
1707+ const parentThreadId = thread . lineage . parentThreadId ;
1708+ if ( parentThreadId === null || taskId === undefined ) return undefined ;
1709+ const task = ( yield * projectionStore . getThreadRecords ( parentThreadId , [ "subagents" ] , {
1710+ subagentIds : [ taskId ] ,
1711+ } ) ) . subagents [ 0 ] ;
1712+ if (
1713+ task ?. origin !== "app_owned" ||
1714+ task . childThreadId !== threadId ||
1715+ task . status !== "completed"
1716+ ) {
1717+ return undefined ;
1718+ }
1719+ const delivery = task . completionDelivery ?. state ;
1720+ if ( delivery === "pending" || delivery === "claimed" ) return "awaiting_delivery" ;
1721+ return delivery === "delivered" || delivery === "acknowledged" ? "ready" : undefined ;
1722+ } ,
1723+ ( effect ) => effect . pipe ( Effect . orElseSucceed ( ( ) => undefined ) ) ,
1724+ ) ;
1725+
16751726 const unloadIdleThread = Effect . fn ( "ProviderSessionManager.unloadIdleThread" ) (
16761727 function * ( input : {
16771728 readonly providerSessionId : ProviderSessionId ;
16781729 readonly threadId : ThreadId ;
16791730 readonly generation : number ;
1731+ /** Session release unloads only the threads it would archive, and never waits. */
1732+ readonly archiveOnly ?: boolean ;
16801733 } ) : Effect . fn . Return < void > {
16811734 const outcome = yield * threadAttachment . withLock (
16821735 threadAttachmentKey ( input ) ,
@@ -1703,6 +1756,11 @@ export const layerWithOptions = (
17031756 . hasPendingBackgroundWorkForThread ( pending . providerThread )
17041757 . pipe ( Effect . catchCause ( ( ) => Effect . succeed ( false ) ) ) ;
17051758 if ( hasPendingWork ) return "deferred" as const ;
1759+ const child = yield * delegatedChildArchive ( input . threadId ) ;
1760+ // Unloading now would miss the archive once the parent takes the result.
1761+ if ( child === "awaiting_delivery" ) return "deferred" as const ;
1762+ const archive = child === "ready" ;
1763+ if ( input . archiveOnly === true && ! archive ) return "skipped" as const ;
17061764 const unloading = yield * Ref . modify ( sessions , ( current ) => {
17071765 const latest = current . get ( key ) ;
17081766 if (
@@ -1726,8 +1784,23 @@ export const layerWithOptions = (
17261784 return [ true , updated ] as const ;
17271785 } ) ;
17281786 if ( ! unloading ) return "skipped" as const ;
1729- yield * unloadThread ( { providerThread : pending . providerThread } ) . pipe (
1730- Effect . timeout ( UNLOAD_THREAD_TIMEOUT_MS ) ,
1787+ const unload = ( archiveThread : boolean ) =>
1788+ unloadThread ( {
1789+ providerThread : pending . providerThread ,
1790+ archive : archiveThread ,
1791+ } ) . pipe ( Effect . timeout ( UNLOAD_THREAD_TIMEOUT_MS ) ) ;
1792+ yield * unload ( archive ) . pipe (
1793+ // A failed or timed-out archive may have left the thread loaded.
1794+ Effect . catch ( ( cause ) =>
1795+ archive
1796+ ? Effect . logWarning ( "orchestration-v2.driver-session.idle-archive-failed" , {
1797+ providerSessionId : input . providerSessionId ,
1798+ threadId : input . threadId ,
1799+ providerThreadId : pending . providerThread . id ,
1800+ cause,
1801+ } ) . pipe ( Effect . andThen ( unload ( false ) ) )
1802+ : Effect . fail ( cause ) ,
1803+ ) ,
17311804 Effect . tap ( ( ) =>
17321805 Ref . update ( sessions , ( current ) => {
17331806 const latest = current . get ( key ) ;
@@ -1750,7 +1823,7 @@ export const layerWithOptions = (
17501823 } ) ,
17511824 ) ;
17521825 // Wait outside the lock so the next attach is not blocked.
1753- if ( outcome === "deferred" ) {
1826+ if ( outcome === "deferred" && input . archiveOnly !== true ) {
17541827 yield * Effect . sleep ( Duration . millis ( idleTimeoutMs ) ) ;
17551828 return yield * unloadIdleThread ( input ) ;
17561829 }
0 commit comments