Skip to content

Commit 40a3bd2

Browse files
authored
refactor(agents): unify guarded subagent lifecycle cleanup (#119637)
1 parent 9b2328d commit 40a3bd2

7 files changed

Lines changed: 141 additions & 258 deletions

‎src/agents/subagent-control.ts‎

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -340,17 +340,19 @@ async function killSubagentRun(params: {
340340
targetState?: SubagentKillTargetState;
341341
error?: string;
342342
}> {
343+
const markKilledBestEffort = () =>
344+
markSubagentRunTerminatedBestEffort({
345+
runId: params.entry.runId,
346+
reason: "killed",
347+
suppressTaskDelivery: params.suppressTaskDelivery,
348+
});
343349
const initialTargetState = resolveSubagentKillTargetState(params.entry);
344350
if (initialTargetState) {
345351
if (
346352
params.entry.endedReason === SUBAGENT_ENDED_REASON_KILLED &&
347353
params.entry.suppressAnnounceReason !== "steer-restart"
348354
) {
349-
markSubagentRunTerminatedBestEffort({
350-
runId: params.entry.runId,
351-
reason: "killed",
352-
suppressTaskDelivery: params.suppressTaskDelivery,
353-
});
355+
markKilledBestEffort();
354356
}
355357
return { killed: false, targetState: initialTargetState };
356358
}
@@ -399,11 +401,7 @@ async function killSubagentRun(params: {
399401
params.entry.endedReason === SUBAGENT_ENDED_REASON_KILLED &&
400402
params.entry.suppressAnnounceReason !== "steer-restart"
401403
) {
402-
markSubagentRunTerminatedBestEffort({
403-
runId: params.entry.runId,
404-
reason: "killed",
405-
suppressTaskDelivery: params.suppressTaskDelivery,
406-
});
404+
markKilledBestEffort();
407405
}
408406
return { killed: false, sessionId, targetState: targetStateAfterRuntimeLoad };
409407
}
@@ -535,11 +533,7 @@ async function killSubagentRun(params: {
535533
targetState.task.status === "cancelled" &&
536534
targetState.task.error === SUBAGENT_KILL_TASK_ERROR;
537535
if (killedTarget) {
538-
markSubagentRunTerminatedBestEffort({
539-
runId: params.entry.runId,
540-
reason: "killed",
541-
suppressTaskDelivery: params.suppressTaskDelivery,
542-
});
536+
markKilledBestEffort();
543537
} else {
544538
try {
545539
releaseSubagentRunKillClaim({
@@ -1166,15 +1160,17 @@ export async function steerControlledSubagentRun(params: {
11661160
// chat.abort remains the primary cleanup; exact session deletion is only
11671161
// the fallback when the accepted session row can be resolved.
11681162
}
1169-
if (!isAgentEventLifecycleGenerationCurrent(steerLifecycleGeneration)) {
1170-
await terminateAcceptedCollectorRun({
1163+
const terminateUnownedSteer = () =>
1164+
terminateAcceptedCollectorRun({
11711165
childSessionKey: params.entry.childSessionKey,
11721166
gatewayRunId: runId,
11731167
expectedSessionId: acceptedSessionEntry?.sessionId,
11741168
expectedLifecycleRevision: acceptedSessionEntry?.lifecycleRevision,
11751169
callGateway: subagentControlDeps.callGateway,
11761170
timeoutMs: 10_000,
11771171
});
1172+
if (!isAgentEventLifecycleGenerationCurrent(steerLifecycleGeneration)) {
1173+
await terminateUnownedSteer();
11781174
clearSubagentRunSteerRestart(params.entry.runId, currentEntry);
11791175
return {
11801176
status: "error",
@@ -1197,14 +1193,7 @@ export async function steerControlledSubagentRun(params: {
11971193
task: params.message,
11981194
});
11991195
if (!replaced) {
1200-
await terminateAcceptedCollectorRun({
1201-
childSessionKey: params.entry.childSessionKey,
1202-
gatewayRunId: runId,
1203-
expectedSessionId: acceptedSessionEntry?.sessionId,
1204-
expectedLifecycleRevision: acceptedSessionEntry?.lifecycleRevision,
1205-
callGateway: subagentControlDeps.callGateway,
1206-
timeoutMs: 10_000,
1207-
});
1196+
await terminateUnownedSteer();
12081197
clearSubagentRunSteerRestart(params.entry.runId, currentEntry);
12091198
return {
12101199
status: "error",

‎src/agents/subagent-registry-lifecycle-cleanup.ts‎

Lines changed: 48 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -73,60 +73,75 @@ export function createSubagentRegistryLifecycleCleanup(
7373
entry.endedReason === SUBAGENT_ENDED_REASON_COMPLETE &&
7474
entry.execution.outcome?.status === "ok";
7575

76-
const finalizeResumedAnnounceGiveUp = async (giveUpParams: {
76+
const finalizeAnnounceGiveUp = async (giveUpParams: {
7777
runId: string;
7878
entry: SubagentRunRecord;
7979
reason: "expiry" | "permanent_failure";
80+
cleanup?: "delete" | "keep";
81+
cleanupGeneration?: number;
82+
retryCount?: number;
83+
completedAt?: number;
8084
}) => {
81-
if (shouldSuspendPendingFinalDelivery(giveUpParams.entry)) {
85+
const { runId, entry, reason, cleanup, cleanupGeneration, retryCount, completedAt } =
86+
giveUpParams;
87+
if (shouldSuspendPendingFinalDelivery(entry)) {
8288
suspendPendingFinalDelivery({
83-
runId: giveUpParams.runId,
84-
entry: giveUpParams.entry,
85-
reason: giveUpParams.reason,
86-
error: getDeliveryLastError(giveUpParams.entry),
89+
runId,
90+
entry,
91+
reason,
92+
error: getDeliveryLastError(entry),
8793
});
8894
return;
8995
}
90-
const deliveryError = getDeliveryLastError(giveUpParams.entry) ?? giveUpParams.reason;
91-
clearPendingFinalDelivery(giveUpParams.entry);
92-
const failedDelivery = ensureDeliveryState(giveUpParams.entry);
96+
const deliveryError = getDeliveryLastError(entry) ?? reason;
97+
clearPendingFinalDelivery(entry);
98+
const failedDelivery = ensureDeliveryState(entry);
9399
failedDelivery.status = "failed";
94100
failedDelivery.lastError = deliveryError;
101+
if (retryCount != null) {
102+
failedDelivery.attemptCount = retryCount;
103+
failedDelivery.lastAttemptAt = completedAt ?? Date.now();
104+
}
95105
safeSetSubagentTaskDeliveryStatus({
96-
entry: giveUpParams.entry,
106+
entry,
97107
deliveryStatus: "failed",
98108
deliveryError,
99109
});
100110
safeMarkRequiredCompletionDeliveryBlocked({
101-
entry: giveUpParams.entry,
111+
entry,
102112
reason: deliveryError,
103113
});
104-
giveUpParams.entry.wakeOnDescendantSettle = undefined;
105-
const completion = ensureCompletionState(giveUpParams.entry);
114+
entry.wakeOnDescendantSettle = undefined;
115+
const completion = ensureCompletionState(entry);
106116
completion.fallbackResultText = undefined;
107117
completion.fallbackCapturedAt = undefined;
108-
const shouldDeleteAttachments =
109-
giveUpParams.entry.cleanup === "delete" || !giveUpParams.entry.retainAttachmentsOnKeep;
110-
if (shouldDeleteAttachments) {
111-
await safeRemoveAttachmentsDir(giveUpParams.entry);
118+
if ((cleanup ?? entry.cleanup) === "delete" || !entry.retainAttachmentsOnKeep) {
119+
await safeRemoveAttachmentsDir(entry);
120+
}
121+
if (
122+
cleanupGeneration !== undefined &&
123+
!isCleanupAttemptCurrent(runId, entry, cleanupGeneration)
124+
) {
125+
await retireSupersededCleanupIfNeeded(runId, entry, cleanupGeneration);
126+
return;
112127
}
113-
const completionReason = resolveCleanupCompletionReason(giveUpParams.entry);
114-
logAnnounceGiveUp(giveUpParams.entry, giveUpParams.reason);
128+
const completionReason = resolveCleanupCompletionReason(entry);
129+
logAnnounceGiveUp(entry, reason);
115130
// Retry-limit / expiry give-up should not leave cleanup stuck behind the
116131
// best-effort ended hook. Mark the run cleaned first, then fire the hook.
117132
completeCleanupBookkeeping({
118-
runId: giveUpParams.runId,
119-
entry: giveUpParams.entry,
120-
cleanup: giveUpParams.entry.cleanup,
121-
completedAt: Date.now(),
133+
runId,
134+
entry,
135+
cleanup: cleanup ?? entry.cleanup,
136+
completedAt: completedAt ?? Date.now(),
122137
});
123-
if (!shouldSuppressSubagentRecoverySessionEffects(giveUpParams.entry)) {
138+
if (!shouldSuppressSubagentRecoverySessionEffects(entry)) {
124139
await emitCompletionEndedHookIfNeeded(
125-
giveUpParams.entry,
140+
entry,
126141
completionReason,
127142
() =>
128-
isEndedHookOwnerCurrent(giveUpParams.runId, giveUpParams.entry) &&
129-
!shouldSuppressSubagentRecoverySessionEffects(giveUpParams.entry),
143+
isEndedHookOwnerCurrent(runId, entry) &&
144+
!shouldSuppressSubagentRecoverySessionEffects(entry),
130145
);
131146
}
132147
};
@@ -159,7 +174,7 @@ export function createSubagentRegistryLifecycleCleanup(
159174
entry,
160175
cleanupGeneration: cleanupGenerations.get(entry)!,
161176
run: async () => {
162-
await finalizeResumedAnnounceGiveUp({
177+
await finalizeAnnounceGiveUp({
163178
runId,
164179
entry,
165180
reason: "expiry",
@@ -326,64 +341,15 @@ export function createSubagentRegistryLifecycleCleanup(
326341
}
327342

328343
if (deferredDecision.kind === "give-up") {
329-
if (shouldSuspendPendingFinalDelivery(entry)) {
330-
suspendPendingFinalDelivery({
331-
runId,
332-
entry,
333-
reason: deferredDecision.reason,
334-
error: getDeliveryLastError(entry),
335-
});
336-
return;
337-
}
338-
const deliveryError = getDeliveryLastError(entry) ?? deferredDecision.reason;
339-
clearPendingFinalDelivery(entry);
340-
const failedDelivery = ensureDeliveryState(entry);
341-
failedDelivery.status = "failed";
342-
failedDelivery.lastError = deliveryError;
343-
if (deferredDecision.retryCount != null) {
344-
failedDelivery.attemptCount = deferredDecision.retryCount;
345-
failedDelivery.lastAttemptAt = now;
346-
}
347-
safeSetSubagentTaskDeliveryStatus({
348-
entry,
349-
deliveryStatus: "failed",
350-
deliveryError,
351-
});
352-
safeMarkRequiredCompletionDeliveryBlocked({
353-
entry,
354-
reason: deliveryError,
355-
});
356-
entry.wakeOnDescendantSettle = undefined;
357-
const completion = ensureCompletionState(entry);
358-
completion.fallbackResultText = undefined;
359-
completion.fallbackCapturedAt = undefined;
360-
const shouldDeleteAttachments = cleanup === "delete" || !entry.retainAttachmentsOnKeep;
361-
if (shouldDeleteAttachments) {
362-
await safeRemoveAttachmentsDir(entry);
363-
}
364-
if (!isCleanupAttemptCurrent(runId, entry, cleanupGeneration)) {
365-
await retireSupersededCleanupIfNeeded(runId, entry, cleanupGeneration);
366-
return;
367-
}
368-
const completionReason = resolveCleanupCompletionReason(entry);
369-
logAnnounceGiveUp(entry, deferredDecision.reason);
370-
// Giving up on announce delivery is terminal for cleanup even if the
371-
// best-effort hook is still resolving.
372-
completeCleanupBookkeeping({
344+
await finalizeAnnounceGiveUp({
373345
runId,
374346
entry,
347+
reason: deferredDecision.reason,
375348
cleanup,
349+
cleanupGeneration,
350+
retryCount: deferredDecision.retryCount,
376351
completedAt: now,
377352
});
378-
if (!shouldSuppressSubagentRecoverySessionEffects(entry)) {
379-
await emitCompletionEndedHookIfNeeded(
380-
entry,
381-
completionReason,
382-
() =>
383-
isEndedHookOwnerCurrent(runId, entry) &&
384-
!shouldSuppressSubagentRecoverySessionEffects(entry),
385-
);
386-
}
387353
return;
388354
}
389355

@@ -642,7 +608,7 @@ export function createSubagentRegistryLifecycleCleanup(
642608

643609
return {
644610
completeCleanupBookkeeping,
645-
finalizeResumedAnnounceGiveUp,
611+
finalizeResumedAnnounceGiveUp: finalizeAnnounceGiveUp,
646612
retireRunModeBundleMcpRuntime,
647613
startSubagentAnnounceCleanupFlow,
648614
};

‎src/agents/subagent-registry-restore.ts‎

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
} from "./subagent-registry-helpers.js";
1717
import type { createSubagentRegistryLifecycleController } from "./subagent-registry-lifecycle.js";
1818
import type { SubagentRunRecord } from "./subagent-registry.types.js";
19-
import { isSessionLifecycleChangedGatewayError } from "./subagent-session-cleanup.js";
19+
import { deleteSubagentSessionForCleanup } from "./subagent-session-cleanup.js";
2020
import {
2121
loadSubagentSessionEntry,
2222
type SubagentSessionStoreCache,
@@ -327,27 +327,18 @@ export function createSubagentRegistryRestorer(config: {
327327
if (!ownsCleanup()) {
328328
return false;
329329
}
330-
try {
331-
await deps().callGateway({
332-
method: "sessions.delete",
333-
params: {
334-
key: entry.childSessionKey,
335-
deleteTranscript: true,
336-
expectedSessionId,
337-
expectedLifecycleRevision,
338-
emitLifecycleHooks: false,
339-
},
340-
timeoutMs: 10_000,
341-
});
342-
sessionDeleted = true;
343-
return true;
344-
} catch (cleanupError) {
345-
if (isSessionLifecycleChangedGatewayError(cleanupError)) {
346-
sessionOwnershipChanged = true;
347-
return true;
348-
}
349-
throw cleanupError;
350-
}
330+
const outcome = await deleteSubagentSessionForCleanup({
331+
callGateway: deps().callGateway,
332+
childSessionKey: entry.childSessionKey,
333+
expectedSessionId,
334+
expectedLifecycleRevision,
335+
onError: (cleanupError) => {
336+
throw cleanupError;
337+
},
338+
});
339+
sessionDeleted = outcome === "deleted";
340+
sessionOwnershipChanged = outcome === "changed";
341+
return outcome !== "failed";
351342
},
352343
{
353344
shouldRetry: () => !launchTerminationConfirmed && ownsCleanup(),

‎src/agents/subagent-registry-sweeper.ts‎

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import type {
3131
SubagentRunRecord,
3232
} from "./subagent-registry.types.js";
3333
import { isStaleUnendedSubagentRun } from "./subagent-run-liveness.js";
34-
import { isSessionLifecycleChangedGatewayError } from "./subagent-session-cleanup.js";
34+
import { deleteSubagentSessionForCleanup } from "./subagent-session-cleanup.js";
3535
import {
3636
loadSubagentSessionEntry,
3737
resolveCompletionFromSessionEntry,
@@ -210,25 +210,20 @@ export function createSubagentRegistrySweeper(params: {
210210
childSessionKey: string,
211211
identity: FrozenSessionIdentity,
212212
): Promise<"deleted" | "changed"> {
213-
try {
214-
await params.callGateway({
215-
method: "sessions.delete",
216-
params: {
217-
key: childSessionKey,
218-
deleteTranscript: true,
219-
emitLifecycleHooks: false,
220-
expectedSessionId: identity.sessionId,
221-
expectedLifecycleRevision: identity.lifecycleRevision,
222-
},
223-
timeoutMs: 10_000,
224-
});
225-
return "deleted";
226-
} catch (error) {
227-
if (isSessionLifecycleChangedGatewayError(error)) {
228-
return "changed";
229-
}
230-
throw error;
213+
let failure: unknown;
214+
const outcome = await deleteSubagentSessionForCleanup({
215+
callGateway: params.callGateway,
216+
childSessionKey,
217+
expectedSessionId: identity.sessionId,
218+
expectedLifecycleRevision: identity.lifecycleRevision,
219+
onError: (error) => {
220+
failure = error;
221+
},
222+
});
223+
if (outcome === "failed") {
224+
throw failure;
231225
}
226+
return outcome;
232227
}
233228

234229
const sweptContext = (entry: SubagentRunRecord) => ({

0 commit comments

Comments
 (0)