@@ -1145,6 +1145,17 @@ interface RlmChildRun {
11451145 unsubscribe?: () => void;
11461146}
11471147
1148+ class RlmChildDeletionCancellation extends Error {
1149+ constructor(
1150+ readonly owner: AgentSession,
1151+ readonly child: AgentSession,
1152+ readonly cleanup: Promise<unknown>,
1153+ readonly settlement?: Promise<void>,
1154+ ) {
1155+ super("RLM quiescence wait cancelled");
1156+ }
1157+ }
1158+
11481159interface RlmChildUsageSource {
11491160 sessionId: string;
11501161 sessionFile?: string;
@@ -13506,6 +13517,15 @@ export class AgentSession {
1350613517 });
1350713518 }
1350813519
13520+ private _cancelChildQuiescenceForDeletion(
13521+ child: AgentSession,
13522+ cleanup: Promise<unknown>,
13523+ settlement?: Promise<void>,
13524+ ): void {
13525+ const cancellation = new RlmChildDeletionCancellation(this, child, cleanup, settlement);
13526+ for (const controller of child._rlmQuiescenceWaitAborts) controller.abort(cancellation);
13527+ }
13528+
1350913529 private async _deleteResolvedRlmSubagent(subagent: RlmSubagentRegistryEntry): Promise<RlmDeleteSubagentResult> {
1351013530 const childId = subagent.rlm_child_id;
1351113531 const run = this._activeRlmChildRuns.get(childId);
@@ -13521,23 +13541,27 @@ export class AgentSession {
1352113541 // cancellation so its catch/finally path cannot race a normal release or
1352213542 // terminal notice against the physical delete.
1352313543 run.detachedDeletion = subagent;
13544+ const liveSession = run.session;
13545+ if (liveSession && run.settled) {
13546+ run.deletionRunFinished = true;
13547+ run.settlement = createAgentMessageDeferred();
13548+ run.settled = false;
13549+ this._unsettledRlmChildRuns.add(run);
13550+ }
13551+ if (liveSession) {
13552+ const cleanup = this._ensureRlmRunDeletionCleanup(run, liveSession);
13553+ this._cancelChildQuiescenceForDeletion(liveSession, cleanup, run.settlement.promise);
13554+ }
1352413555 if (this._cancelRlmChildRun(run, "Deleted by parent orchestrator")) {
1352513556 run.deletionNeedsCompletionNotice = true;
1352613557 } else {
1352713558 this._emitRlmSubagentRemoval(subagent);
1352813559 }
13529- const liveSession = run.session;
1353013560 if (run.status === "error" && !liveSession && run.settled) {
1353113561 this._deletedRlmChildIds.add(childId);
1353213562 this._removeRlmSubagentTracking(childId, run);
1353313563 return { subagent };
1353413564 }
13535- if (liveSession && run.settled) {
13536- run.deletionRunFinished = true;
13537- run.settlement = createAgentMessageDeferred();
13538- run.settled = false;
13539- this._unsettledRlmChildRuns.add(run);
13540- }
1354113565 if (liveSession) this._continueFinishedRlmRunDeletion(run, subagent, liveSession);
1354213566
1354313567 // Return once deletion is accepted. The run stays hidden but unsettled until
@@ -13548,6 +13572,8 @@ export class AgentSession {
1354813572
1354913573 this._emitRlmSubagentRemoval(subagent);
1355013574 const retained = this._rlmChildSessions.get(childId)?.session;
13575+ const deletion = this._deletingRlmChildren.get(childId);
13576+ if (retained && deletion) this._cancelChildQuiescenceForDeletion(retained, deletion.promise);
1355113577 try {
1355213578 await this._deleteRlmSubagentSession(childId, retained);
1355313579 } catch (error) {
@@ -13920,13 +13946,14 @@ export class AgentSession {
1392013946 return [...sessions];
1392113947 }
1392213948
13923- private _hasUnsettledRlmQuiescenceWork(): boolean {
13949+ private _hasUnsettledRlmQuiescenceWork(waitForOwnedChildDeletion = false): boolean {
13950+ if (waitForOwnedChildDeletion && this._deletingRlmChildren.size > 0) return true;
1392413951 if (this.requests.hasPending || this._pendingIpythonExecutions.size > 0 || this._childUsageWrites.size > 0)
1392513952 return true;
1392613953 if (this._hasDeferredRlmTerminalNotices()) return true;
1392713954 if ([...this._unsettledRlmChildRuns].some((run) => !run.settled)) return true;
1392813955 return this._rlmChildSessionSnapshot().some(
13929- (child) => child.isSessionActive || child._hasUnsettledRlmQuiescenceWork(),
13956+ (child) => child.isSessionActive || child._hasUnsettledRlmQuiescenceWork(waitForOwnedChildDeletion ),
1393013957 );
1393113958 }
1393213959
@@ -13935,7 +13962,10 @@ export class AgentSession {
1393513962 * message and for the resulting parent turns to drain. Re-snapshotting after
1393613963 * each drain includes descendants spawned while earlier results were consumed.
1393713964 */
13938- async waitForRlmQuiescence(externalSignal?: AbortSignal): Promise<void> {
13965+ async waitForRlmQuiescence(
13966+ externalSignal?: AbortSignal,
13967+ options: { waitForOwnedChildDeletion?: boolean } = {},
13968+ ): Promise<void> {
1393913969 const cancellation = new AbortController();
1394013970 const cancelFromParent = () => cancellation.abort();
1394113971 if (externalSignal?.aborted) cancellation.abort();
@@ -13945,31 +13975,59 @@ export class AgentSession {
1394513975 const cancelled = new Promise<never>((_resolve, reject) => {
1394613976 rejectCancelled = reject;
1394713977 });
13948- const onCancelled = () => rejectCancelled(new Error("RLM quiescence wait cancelled"));
13978+ const cancellationError = () =>
13979+ cancellation.signal.reason instanceof RlmChildDeletionCancellation
13980+ ? cancellation.signal.reason
13981+ : new Error("RLM quiescence wait cancelled");
13982+ const onCancelled = () => rejectCancelled(cancellationError());
1394913983 cancellation.signal.addEventListener("abort", onCancelled, { once: true });
1395013984 if (cancellation.signal.aborted) onCancelled();
1395113985 const wait = <T>(operation: Promise<T>): Promise<T> => Promise.race([operation, cancelled]);
1395213986 try {
1395313987 while (true) {
1395413988 await wait(this.waitForHeadlessIdle());
13989+ if (cancellation.signal.aborted) throw cancellationError();
1395513990 // Strong RLM quiescence also owns work that interactive waitForIdle ignores.
1395613991 if (this.isSessionActive || this._hasDeferredRlmTerminalNotices()) {
1395713992 await wait(this._waitForSessionActivityChange(cancellation.signal));
1395813993 continue;
1395913994 }
1396013995 const unsettledRuns = [...this._unsettledRlmChildRuns].filter((run) => !run.settled);
1396113996 const childSessions = this._rlmChildSessionSnapshot();
13962- if (unsettledRuns.length === 0 && !this._hasUnsettledRlmQuiescenceWork()) return;
13997+ const deletions = options.waitForOwnedChildDeletion
13998+ ? [...this._deletingRlmChildren.values()].map((deletion) => deletion.promise)
13999+ : [];
14000+ if (unsettledRuns.length === 0 && !this._hasUnsettledRlmQuiescenceWork(options.waitForOwnedChildDeletion))
14001+ return;
1396314002 await wait(
1396414003 Promise.all([
1396514004 ...unsettledRuns.map((run) => run.settlement.promise),
1396614005 ...this._childUsageWrites,
13967- ...childSessions.map((child) => child.waitForRlmQuiescence(cancellation.signal)),
14006+ ...deletions,
14007+ ...childSessions.map(async (child) => {
14008+ try {
14009+ await child.waitForRlmQuiescence(cancellation.signal, options);
14010+ } catch (error) {
14011+ if (
14012+ !options.waitForOwnedChildDeletion ||
14013+ !(error instanceof RlmChildDeletionCancellation) ||
14014+ error.owner !== this ||
14015+ error.child !== child
14016+ ) {
14017+ throw error;
14018+ }
14019+ // Only an admitted owned deletion may replace a cancelled child wait.
14020+ await wait(Promise.all([error.cleanup, error.settlement]));
14021+ }
14022+ }),
1396814023 ]),
1396914024 );
1397014025 // Always loop through the self-active/deferred checks again. Work may
1397114026 // start at the child-settlement boundary.
1397214027 }
14028+ } catch (error) {
14029+ if (cancellation.signal.aborted) throw cancellationError();
14030+ throw error;
1397314031 } finally {
1397414032 // A local descendant error must cancel sibling recursive waits owned by
1397514033 // this barrier before their propagation listeners are removed.
@@ -14356,7 +14414,7 @@ export class AgentSession {
1435614414 throwIfCancelled();
1435714415 if (terminal?.stopReason === "error")
1435814416 throw new Error(terminal.errorMessage || "RLM child inference failed");
14359- await child.waitForRlmQuiescence();
14417+ await child.waitForRlmQuiescence(undefined, { waitForOwnedChildDeletion: true } );
1436014418 await usageSettlement;
1436114419 throwIfCancelled();
1436214420 if (run.error) throw new Error(run.error);
0 commit comments