@@ -175,6 +175,7 @@ import { resolveCandidateThinkingLevel, resolveEffectiveAgentRuntime } from "./t
175175import { resolveAgentTimeoutMs } from "./timeout.js" ;
176176import { hasNonzeroUsage } from "./usage.js" ;
177177import { ensureAgentWorkspace } from "./workspace.js" ;
178+ import { acquireWorktreeRunLease , resolveWorktreeIdForPath } from "./worktrees/run-lease.js" ;
178179
179180const log = createSubsystemLogger ( "agents/agent-command" ) ;
180181
@@ -902,61 +903,77 @@ async function prepareAgentCommandExecution(opts: AgentCommandOpts, runtime: Run
902903 if ( opts . thinkingOnce && ! thinkOnce ) {
903904 throw new Error ( `Invalid one-shot thinking level. Use one of: ${ thinkingLevelsHint } .` ) ;
904905 }
905- await ensureAgentWorkspace ( {
906- dir : workspaceDirRaw ,
907- ensureBootstrapFiles : ! agentCfg ?. skipBootstrap ,
908- skipOptionalBootstrapFiles : agentCfg ?. skipOptionalBootstrapFiles ,
906+ // Lease the managed worktree before any workspace-dependent preparation so idle
907+ // GC or a separate remover cannot delete the checkout while it is being set up;
908+ // a session bound to a removed worktree fails closed here. Released on any prepare
909+ // failure below and in the run's outer cleanup.
910+ const resolvedCwd = cwd ? resolveUserPath ( cwd ) : undefined ;
911+ const worktreeId = await resolveWorktreeIdForPath ( {
912+ sessionEntry : sessionEntryRaw ,
913+ candidatePaths : [ resolvedCwd ?? workspaceDir , workspaceDir ] ,
909914 } ) ;
910- const runId = opts . runId ?. trim ( ) || sessionId ;
911- const { getAcpSessionManager } = await loadAcpManagerRuntime ( ) ;
912- const acpManager = getAcpSessionManager ( ) ;
913- const acpResolution = sessionKey
914- ? acpManager . resolveSession ( {
915- cfg,
916- sessionKey,
917- } )
918- : null ;
919- const body =
920- ! isRawModelRun && acpResolution ?. kind === "ready"
921- ? resolveAcpPromptBody ( message , opts . internalEvents )
922- : prependInternalEventContext ( message , opts . internalEvents ) ;
923- const transcriptBody =
924- opts . transcriptMessage ?? resolveInternalEventTranscriptBody ( message , opts . internalEvents ) ;
915+ const runLease = worktreeId ? await acquireWorktreeRunLease ( worktreeId ) : undefined ;
916+ try {
917+ await ensureAgentWorkspace ( {
918+ dir : workspaceDirRaw ,
919+ ensureBootstrapFiles : ! agentCfg ?. skipBootstrap ,
920+ skipOptionalBootstrapFiles : agentCfg ?. skipOptionalBootstrapFiles ,
921+ } ) ;
922+ const runId = opts . runId ?. trim ( ) || sessionId ;
923+ const { getAcpSessionManager } = await loadAcpManagerRuntime ( ) ;
924+ const acpManager = getAcpSessionManager ( ) ;
925+ const acpResolution = sessionKey
926+ ? acpManager . resolveSession ( {
927+ cfg,
928+ sessionKey,
929+ } )
930+ : null ;
931+ const body =
932+ ! isRawModelRun && acpResolution ?. kind === "ready"
933+ ? resolveAcpPromptBody ( message , opts . internalEvents )
934+ : prependInternalEventContext ( message , opts . internalEvents ) ;
935+ const transcriptBody =
936+ opts . transcriptMessage ?? resolveInternalEventTranscriptBody ( message , opts . internalEvents ) ;
925937
926- return {
927- opts : commandOpts ,
928- body,
929- transcriptBody,
930- cfg,
931- configuredThinkingCatalog,
932- normalizedSpawned,
933- agentCfg,
934- thinkOverride,
935- thinkOnce,
936- verboseOverride,
937- timeoutMs,
938- runTimeoutOverrideMs,
939- sessionId,
940- sessionKey,
941- sessionEntry : sessionEntryRaw ,
942- sessionStore,
943- storePath,
944- isNewSession,
945- persistedThinking,
946- persistedVerbose,
947- sessionAgentId,
948- outboundSession,
949- workspaceDir,
950- cwd : cwd ? resolveUserPath ( cwd ) : undefined ,
951- agentDir,
952- pluginsEnabled,
953- manifestMetadataSnapshot,
954- modelManifestContext,
955- runId,
956- isSubagentLane,
957- acpManager,
958- acpResolution,
959- } ;
938+ return {
939+ opts : commandOpts ,
940+ body,
941+ transcriptBody,
942+ cfg,
943+ configuredThinkingCatalog,
944+ normalizedSpawned,
945+ agentCfg,
946+ thinkOverride,
947+ thinkOnce,
948+ verboseOverride,
949+ timeoutMs,
950+ runTimeoutOverrideMs,
951+ sessionId,
952+ sessionKey,
953+ sessionEntry : sessionEntryRaw ,
954+ sessionStore,
955+ storePath,
956+ isNewSession,
957+ persistedThinking,
958+ persistedVerbose,
959+ sessionAgentId,
960+ outboundSession,
961+ workspaceDir,
962+ cwd : resolvedCwd ,
963+ agentDir,
964+ pluginsEnabled,
965+ manifestMetadataSnapshot,
966+ modelManifestContext,
967+ runId,
968+ isSubagentLane,
969+ acpManager,
970+ acpResolution,
971+ runLease,
972+ } ;
973+ } catch ( error ) {
974+ await runLease ?. release ( ) ;
975+ throw error ;
976+ }
960977}
961978
962979async function agentCommandInternal (
@@ -1008,9 +1025,9 @@ async function agentCommandInternal(
10081025 pluginsEnabled,
10091026 manifestMetadataSnapshot,
10101027 modelManifestContext,
1028+ runLease,
10111029 } = prepared ;
10121030 let lifecycleGeneration = opts . lifecycleGeneration ?? captureAgentRunLifecycleGeneration ( runId ) ;
1013- assertAgentRunLifecycleGenerationCurrent ( lifecycleGeneration ) ;
10141031 const effectiveCwd = cwd ? resolveUserPath ( cwd ) : workspaceDir ;
10151032 let sessionEntry = prepared . sessionEntry ;
10161033 const sessionStateActor = classifySessionStateActor ( {
@@ -1026,7 +1043,6 @@ async function agentCommandInternal(
10261043 let trackedRestartRecoveryDeliveryContext = false ;
10271044 let currentRunDeliveryContext : DeliveryContext | undefined ;
10281045 const preparedSessionId = sessionEntry ?. sessionId ;
1029- const sessionStoreRuntime = storePath && sessionKey ? await loadSessionStoreRuntime ( ) : undefined ;
10301046 const internalModelRunTargets =
10311047 initialOpts . modelRun === true && suppressVisibleSessionEffects
10321048 ? new Map < string , AgentRunSessionTarget > ( )
@@ -1043,49 +1059,56 @@ async function agentCommandInternal(
10431059 ) ;
10441060 }
10451061
1046- // Reset marks its mutation before interrupting work. An aborted run must not
1047- // queue behind that mutation or reset would wait on the run holding the queue.
1048- const sessionWorkAdmission = await beginSessionWorkAdmission ( {
1049- scope : storePath ?? `agent:${ sessionAgentId } ` ,
1050- identities : [ sessionKey , sessionId ] ,
1051- signal : opts . abortSignal ,
1052- onInterrupt : ( ) => lifecycleAbortController . abort ( createAgentRunRestartAbortError ( ) ) ,
1053- assertAllowed : ( ) => {
1054- const currentEntry =
1055- sessionStoreRuntime && storePath && sessionKey
1056- ? sessionStoreRuntime . loadSessionEntry ( {
1057- storePath,
1058- sessionKey,
1059- readConsistency : "latest" ,
1060- } )
1061- : sessionEntry ;
1062- if ( ! currentEntry && preparedSessionId ) {
1063- throw new Error ( `Session "${ sessionKey ?? sessionId } " changed while starting work. Retry.` ) ;
1064- }
1065- const matchesIntentionalRollover =
1066- isNewSession && currentEntry ?. sessionId === preparedSessionId ;
1067- if ( currentEntry && currentEntry . sessionId !== sessionId && ! matchesIntentionalRollover ) {
1068- throw new Error ( `Session "${ sessionKey ?? sessionId } " changed while starting work. Retry.` ) ;
1069- }
1070- const archivedSessionError = resolveSessionWorkStartError (
1071- sessionKey ?? sessionId ,
1072- currentEntry ,
1073- ) ;
1074- if ( archivedSessionError ) {
1075- throw new Error ( archivedSessionError ) ;
1076- }
1077- sessionEntry = currentEntry ;
1078- if ( sessionStore && sessionKey ) {
1079- if ( currentEntry ) {
1080- sessionStore [ sessionKey ] = currentEntry ;
1081- } else {
1082- delete sessionStore [ sessionKey ] ;
1083- }
1084- }
1085- } ,
1086- } ) ;
1087-
1062+ let sessionWorkAdmission : Awaited < ReturnType < typeof beginSessionWorkAdmission > > | undefined ;
10881063 try {
1064+ assertAgentRunLifecycleGenerationCurrent ( lifecycleGeneration ) ;
1065+ const sessionStoreRuntime =
1066+ storePath && sessionKey ? await loadSessionStoreRuntime ( ) : undefined ;
1067+ // Reset marks its mutation before interrupting work. An aborted run must not
1068+ // queue behind that mutation or reset would wait on the run holding the queue.
1069+ sessionWorkAdmission = await beginSessionWorkAdmission ( {
1070+ scope : storePath ?? `agent:${ sessionAgentId } ` ,
1071+ identities : [ sessionKey , sessionId ] ,
1072+ signal : opts . abortSignal ,
1073+ onInterrupt : ( ) => lifecycleAbortController . abort ( createAgentRunRestartAbortError ( ) ) ,
1074+ assertAllowed : ( ) => {
1075+ const currentEntry =
1076+ sessionStoreRuntime && storePath && sessionKey
1077+ ? sessionStoreRuntime . loadSessionEntry ( {
1078+ storePath,
1079+ sessionKey,
1080+ readConsistency : "latest" ,
1081+ } )
1082+ : sessionEntry ;
1083+ if ( ! currentEntry && preparedSessionId ) {
1084+ throw new Error (
1085+ `Session "${ sessionKey ?? sessionId } " changed while starting work. Retry.` ,
1086+ ) ;
1087+ }
1088+ const matchesIntentionalRollover =
1089+ isNewSession && currentEntry ?. sessionId === preparedSessionId ;
1090+ if ( currentEntry && currentEntry . sessionId !== sessionId && ! matchesIntentionalRollover ) {
1091+ throw new Error (
1092+ `Session "${ sessionKey ?? sessionId } " changed while starting work. Retry.` ,
1093+ ) ;
1094+ }
1095+ const archivedSessionError = resolveSessionWorkStartError (
1096+ sessionKey ?? sessionId ,
1097+ currentEntry ,
1098+ ) ;
1099+ if ( archivedSessionError ) {
1100+ throw new Error ( archivedSessionError ) ;
1101+ }
1102+ sessionEntry = currentEntry ;
1103+ if ( sessionStore && sessionKey ) {
1104+ if ( currentEntry ) {
1105+ sessionStore [ sessionKey ] = currentEntry ;
1106+ } else {
1107+ delete sessionStore [ sessionKey ] ;
1108+ }
1109+ }
1110+ } ,
1111+ } ) ;
10891112 return await sessionWorkAdmission . run ( async ( ) => {
10901113 if ( opts . deliver === true ) {
10911114 const sendPolicy = resolveSendPolicy ( {
@@ -2821,7 +2844,10 @@ async function agentCommandInternal(
28212844 }
28222845 } ) ;
28232846 } finally {
2824- sessionWorkAdmission . release ( ) ;
2847+ if ( runLease ) {
2848+ await runLease . release ( ) ;
2849+ }
2850+ sessionWorkAdmission ?. release ( ) ;
28252851 if ( internalModelRunTargets ) {
28262852 // Compaction may rotate a private session identity. Remove every owned
28272853 // SQLite row only after delivery; transcript and trajectory rows cascade.
0 commit comments