A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(acp): harden resident session lifecycle (#1494)
Seth Kartend98d0762c0de
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 2c348b4fba..82246c2a51 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,9 @@## [Unreleased]+- Added correlated ACP terminal-quiescence metadata, resident session settlement, and fail-closed daemon input fencing; prevented recovery state from persisting runtime credentials or model configuration.+- Fixed explicit RLM child deletion leaving hidden unsettled work after runtime teardown, including reporting cleanup failures and notifying the parent when deletion completes.+## [0.7.4] - 2026-08-19- Fixed model searches ranking stronger matches ahead of weaker signed-in matches while preferring signed-in providers for equivalent results ([#539](https://github.com/PrimeIntellect-ai/prime-agent/pull/539) by [@eliebak](https://github.com/eliebak)).diff --git a/packages/coding-agent/src/cli/daemon-ps.ts b/packages/coding-agent/src/cli/daemon-ps.tsindex ea1d16de53..518329622d 100644--- a/packages/coding-agent/src/cli/daemon-ps.ts+++ b/packages/coding-agent/src/cli/daemon-ps.ts@@ -1021,7 +1021,7 @@ function isTrackedWorkerDescriptor(value: unknown): value is DaemonWorkerDescrip}const descriptor = value as Partial<DaemonWorkerDescriptor>;return (- descriptor.version === 1 &&+ (descriptor.version === 1 || descriptor.version === 2) &&typeof descriptor.supervisorSocketPath === "string" &&typeof descriptor.workerId === "string" &&Number.isInteger(descriptor.pid) &&diff --git a/packages/coding-agent/src/core/agent-session-config.ts b/packages/coding-agent/src/core/agent-session-config.tsindex 40ed3a1702..f855f4c075 100644--- a/packages/coding-agent/src/core/agent-session-config.ts+++ b/packages/coding-agent/src/core/agent-session-config.ts@@ -45,6 +45,21 @@ export interface AgentSessionRuntimeConfig {initialGoal?: { objective: string; tokenBudget?: number };}+export type DurableAgentSessionRuntimeConfig = Pick<+ AgentSessionRuntimeConfig,+ "cwd" | "agentDir" | "sessionDir" | "telemetryDisabled"+>;++/** Only non-secret host settings needed to locate and govern durable daemon state. */+export function durableAgentSessionRuntimeConfig(config: AgentSessionRuntimeConfig): DurableAgentSessionRuntimeConfig {+ return {+ ...(typeof config.cwd === "string" ? { cwd: config.cwd } : {}),+ ...(typeof config.agentDir === "string" ? { agentDir: config.agentDir } : {}),+ ...(typeof config.sessionDir === "string" ? { sessionDir: config.sessionDir } : {}),+ ...(config.telemetryDisabled === true ? { telemetryDisabled: true as const } : {}),+ };+}+export function mergeAgentSessionRuntimeConfig(base: AgentSessionRuntimeConfig,override?: AgentSessionRuntimeConfig,diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex e50cc72768..f3d7408ecd 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -172,6 +172,8 @@ import {HEARTBEAT_PROMPT_PREVIEW_LABEL,IPYTHON_STATE_RESTORED_CUSTOM_TYPE,isSessionSlashCommandMessage,+ RLM_CHILD_FAILURE_CUSTOM_TYPE,+ RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,} from "./messages.js";import type { ModelRegistry } from "./model-registry.js";import { throwIfPromptAdmissionCancelled } from "./prompt-admission.js";@@ -857,13 +859,33 @@ interface RlmChildRun {prompt: string;sessionName: string;sessionDir: string;+ model: Model<Api>;status: RlmChildAgentStatus;error?: string;abort: () => void;publication: AgentMessageDeferred;+ /** Resolves after terminal result publication and detached-run cleanup finish. */+ settlement: AgentMessageDeferred;+ /** Child session, once its runtime exists. Used to cancel nested child runs. */session?: AgentSession;settled: boolean;+ /** Do not inject a late terminal notice after the parent session is aborted. */+ suppressTerminalNotice?: boolean;+ /** Excluded from future strong barriers after an authoritative cancellation cut. */+ abandonedForQuiescence?: boolean;+ /** Selector snapshot for an admitted explicit delete. */detachedDeletion?: RlmSubagentRegistryEntry;+ /** Shared physical runtime cleanup owned by the explicit-delete path. */+ deletionCleanup?: Promise<void>;+ deletionCleanupObserver?: Promise<boolean>;+ /** Resolves when a deletion may release its selector reservation. */+ deletionReservation: AgentMessageDeferred;+ deletionCleanupFailed?: boolean;+ deletionRunFinished?: boolean;+ deletionNotice?: Promise<void>;+ deletionNeedsCompletionNotice?: boolean;+ completeDeletion?: () => Promise<void>;+ reportDeletionCleanupFailure?: (error: unknown) => Promise<void>;emitUpdate?: () => void;unsubscribe?: () => void;}@@ -1012,8 +1034,11 @@ export class AgentSession {private _sessionInputArrivalEpoch = 0;// Persists abort/restart suspension after the initiating call returns.private _sessionInputPumpSuspended = false;+ private _sessionInputSuspendedForUpdateRestart = false;// Branch mutation pause leases can overlap and must all release before dispatch resumes.private readonly _queuedWorkPauses = new Set<symbol>();+ private readonly _sessionInputAdmissionPauses = new Set<symbol>();+ private readonly _durableRlmTerminalNoticeActionIds = new Set<string>();private _sessionActionCommitTail: Promise<void> = Promise.resolve();private _sessionActionCommitOwner: symbol | undefined;private _pendingSessionActionFenceWaiters = 0;@@ -1110,6 +1135,9 @@ export class AgentSession {private _parentReplyCount = 0;private _subagentRuntimeHost?: SubagentRuntimeHost;private _activeRlmChildRuns = new Map<string, RlmChildRun>();+ private _unsettledRlmChildRuns = new Set<RlmChildRun>();+ private _abandonedRlmQuiescenceChildIds = new Set<string>();+ private _rlmQuiescenceWaitAborts = new Set<AbortController>();private _pendingRlmSubagentSessionNames = new Set<string>();// Inline mode keeps finished child sessions so the inspector can still read them;// the daemon does the same by leaving the child session resident in its registry.@@ -1149,6 +1177,7 @@ export class AgentSession {private _turnIntervalAutoRefinePending = false;private _postCompactionContinuationScheduled = false;private _postCompactionContinuationTimer: ReturnType<typeof setTimeout> | undefined;+ private _postCompactionContinuationSettlement: AgentMessageDeferred | undefined;private _postCompactionContinuationMessages: AgentMessage[] = [];private _scheduledPostCompactionContinuationMessages: AgentMessage[] = [];private _queuedAutonomousThresholdContinuations = new WeakMap<AssistantMessage, AgentMessage>();@@ -3850,9 +3879,22 @@ export class AgentSession {private async _disposeAsyncOnce(): Promise<void> {// Flush kernels/traces for both still-running and retained children; the sync// dispose() below only tears them down synchronously.- for (const run of this._activeRlmChildRuns.values()) {- if (run.session) {- await run.session.disposeAsync().catch(() => undefined);+ for (const run of [...this._activeRlmChildRuns.values()]) {+ const childSession = run.session;+ if (!childSession) continue;+ if (run.detachedDeletion) {+ run.suppressTerminalNotice = true;+ if (run.deletionCleanupObserver) {+ await run.deletionCleanupObserver.catch(() => false);+ } else if (run.deletionCleanup) {+ await run.deletionCleanup.catch(() => childSession.disposeAsync().catch(() => undefined));+ } else {+ // Cleanup already failed and was exposed for retry before disposal.+ await childSession.disposeAsync().catch(() => undefined);+ }+ if (!run.settled) await this._finishRlmRunDeletion(run);+ } else {+ await childSession.disposeAsync().catch(() => undefined);}}for (const unsubscribe of this._rlmChildUnsubscribes.values()) {@@ -3899,6 +3941,8 @@ export class AgentSession {return;}this._disposed = true;+ for (const run of this._unsettledRlmChildRuns) run.suppressTerminalNotice = true;+ for (const controller of this._rlmQuiescenceWaitAborts) controller.abort();this._sessionActionCommitDisposeAbortController.abort();try {// Invalidate scheduled timers and abort any in-flight review so a late@@ -4357,6 +4401,7 @@ export class AgentSession {options?.customMessage && isAgentSessionMessage(options.customMessage) ? options.customMessage : undefined;await this._prompt(text, {...options,+ resumeIfIdle: false,expandPromptTemplates: false,skipInputHandlers: true,skipPrePromptWork: true,@@ -4398,12 +4443,142 @@ export class AgentSession {});}+ private _isRlmTerminalNotice(message: CustomMessage): boolean {+ return (+ message.customType === RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE ||+ message.customType === RLM_CHILD_FAILURE_CUSTOM_TYPE+ );+ }++ private _assertRlmTerminalNotice(message: CustomMessage): void {+ if (!this._isRlmTerminalNotice(message)) {+ throw new Error("Deferred terminal admission only accepts RLM child terminal notices.");+ }+ }++ private _isRlmTerminalNoticeAction(action: QueuedSessionAction): boolean {+ if (action.payload.kind !== "turn") return false;+ const message = primaryDeliveryRecord(action).message;+ return message.role === "custom" && this._isRlmTerminalNotice(message);+ }++ private _hasDeferredRlmTerminalNotices(): boolean {+ return this._pendingNextTurnMessages.some((message) => this._isRlmTerminalNotice(message));+ }++ private _enqueueRlmTerminalNoticeAction(message: CustomMessage): void {+ this._assertRlmTerminalNotice(message);+ const action = this._createPreparedTurnAction("followUp", message.content as string, undefined, {+ message,+ suppressAutonomousContinuation: true,+ resumeIfIdle: false,+ source: "internal",+ executionPolicy: this._turnExecutionPolicy("injected"),+ queueVisible: false,+ });+ this._durableRlmTerminalNoticeActionIds.add(action.id);+ try {+ const result = this._admitSessionInput(action, { wake: false });+ if (!result.accepted) throw new Error("RLM child terminal notice was not admitted.");+ } catch (error) {+ this._durableRlmTerminalNoticeActionIds.delete(action.id);+ throw error;+ }+ }++ private _flushDeferredRlmTerminalNotices(): void {+ if (+ this._sessionInputAdmissionPauses.size > 0 ||+ this._sessionInputPumpSuspended ||+ this._queuedWorkPauses.size > 0 ||+ this._disposed ||+ this._disposing+ ) {+ return;+ }+ while (true) {+ const index = this._pendingNextTurnMessages.findIndex((message) => this._isRlmTerminalNotice(message));+ if (index < 0) break;+ const message = this._pendingNextTurnMessages[index];+ try {+ this._enqueueRlmTerminalNoticeAction(message);+ } catch {+ return;+ }+ this._pendingNextTurnMessages.splice(index, 1);+ }+ this._scheduleSessionInputPump();+ }++ private async _acquireRlmTerminalNoticeRetentionFence(): Promise<{ owner: symbol; release(): void } | undefined> {+ const disposeSignal = this._sessionActionCommitDisposeAbortController.signal;+ while (!this._disposed && !this._disposing && !disposeSignal.aborted) {+ if (this._queuedWorkPauses.size > 0) {+ let wake = () => {};+ const pauseReleased = new Promise<void>((resolve) => {+ wake = resolve;+ this._sessionInputCheckpointWaiters.add(resolve);+ });+ try {+ await waitForPromiseOrAbort(pauseReleased, disposeSignal, "Terminal notice retention cancelled");+ } catch {+ return undefined;+ } finally {+ this._sessionInputCheckpointWaiters.delete(wake);+ }+ continue;+ }+ let fence: { owner: symbol; release(): void };+ try {+ fence = await this._acquireSessionActionCommitFence(disposeSignal);+ } catch {+ return undefined;+ }+ if (this._queuedWorkPauses.size === 0 && !this._disposed && !this._disposing) return fence;+ fence.release();+ }+ return undefined;+ }++ private async _deferRlmTerminalNotice(message: CustomMessage): Promise<void> {+ this._assertRlmTerminalNotice(message);+ const fence = await this._acquireRlmTerminalNoticeRetentionFence();+ if (!fence) return;+ try {+ if (this._disposed || this._disposing) return;+ this._pendingNextTurnMessages.push(cloneCustomMessage(message));+ this._flushDeferredRlmTerminalNotices();+ } finally {+ fence.release();+ }+ }++ private _demoteRlmTerminalNoticeActions(): void {+ const actions = this._actionStore+ .clearableActions()+ .filter((action) => this._durableRlmTerminalNoticeActionIds.has(action.id));+ if (actions.length === 0) return;+ for (const action of actions) {+ if (!this._isRlmTerminalNoticeAction(action)) continue;+ const message = primaryDeliveryRecord(action).message;+ if (message.role === "custom") this._pendingNextTurnMessages.push(cloneCustomMessage(message));+ }+ const ids = new Set(actions.map((action) => action.id));+ this._cancelSessionActions(+ (action) => ids.has(action.id),+ new Error("RLM child terminal notice deferred across session input suspension."),+ actions,+ );+ for (const id of ids) this._durableRlmTerminalNoticeActionIds.delete(id);+ }+private async _promptInjectedMessage(text: string,message: CustomMessage,options?: InternalPromptOptions & { executionPolicy?: TurnExecutionPolicy },): Promise<void> {- if (!this.isStreaming && options?.resumeIfIdle) this._sessionInputPumpSuspended = false;+ if (!this.isStreaming && options?.resumeIfIdle) this._resumeSessionInputAdmission();+ const admissionEpoch = this._sessionInputPumpEpoch;const admissionFence = await this._acquireDirectTurnAdmissionFence(options?.signal).catch((error: unknown) => {throwIfPromptAdmissionCancelled(options?.signal);throw error;@@ -4411,6 +4586,9 @@ export class AgentSession {const reportPreflight = oncePreflight(options?.preflightResult);try {throwIfPromptAdmissionCancelled(options?.signal);+ if (admissionEpoch !== this._sessionInputPumpEpoch) {+ throw new Error("Injected session input was invalidated before admission");+ }options?.admissionCommitted?.();const queueForStreaming = this.isStreaming;const queueForBusy = options?.queueIfBusy === true && this._isBusyForSessionInput("preflight");@@ -4471,10 +4649,12 @@ export class AgentSession {}private async _prompt(text: string, options?: InternalPromptOptions): Promise<void> {+ const resumeSuspendedInput = options?.resumeIfIdle !== false;if (!this.isStreaming) {- this._sessionInputPumpSuspended = false;+ if (resumeSuspendedInput) this._resumeSessionInputAdmission();this._assertSessionActionAdmissionAvailable();}+ const admissionEpoch = this._sessionInputPumpEpoch;const commitFence = this.isStreaming? undefined: await this._acquireDirectTurnAdmissionFence(options?.signal).catch((error: unknown) => {@@ -4485,6 +4665,9 @@ export class AgentSession {const run = async () => {try {throwIfPromptAdmissionCancelled(options?.signal);+ if (!resumeSuspendedInput && admissionEpoch !== this._sessionInputPumpEpoch) {+ throw new Error("Session input was invalidated before admission");+ }options?.admissionCommitted?.();const isInternalPrompt = options?.internalPrompt === true;const expandPromptTemplates = isInternalPrompt ? false : (options?.expandPromptTemplates ?? true);@@ -4862,7 +5045,16 @@ export class AgentSession {...(recovered.suppressAutonomousContinuation ? { suppressAutonomousContinuation: true } : {}),};});- for (const action of actions) this._admitSessionInput(action, { restore: true });+ for (const action of actions) {+ const durableTerminalNotice = this._isRlmTerminalNoticeAction(action);+ if (durableTerminalNotice) this._durableRlmTerminalNoticeActionIds.add(action.id);+ try {+ this._admitSessionInput(action, { restore: true });+ } catch (error) {+ if (durableTerminalNotice) this._durableRlmTerminalNoticeActionIds.delete(action.id);+ throw error;+ }+ }return actions.length;}@@ -5160,7 +5352,10 @@ export class AgentSession {if (this._disposed || this._disposing) {throw new Error("Cannot admit a session action because the session is disposing or disposed.");}- if (this.unfinishedActionCount > 0 && this._sessionInputPumpSuspended) {+ if (this._sessionInputAdmissionPauses.size > 0) {+ throw new Error("Cannot admit a session action while session input admission is paused.");+ }+ if (this._sessionInputPumpSuspended) {throw new Error("Cannot admit a session action while queued session input is suspended.");}}@@ -5181,6 +5376,9 @@ export class AgentSession {if (this._disposed || this._disposing) {throw new Error("Cannot admit a session action because the session is disposing or disposed.");}+ if (this._sessionInputAdmissionPauses.size > 0) {+ throw new Error("Cannot admit a session action while session input admission is paused.");+ }const coalescedOwner = options.restore ? undefined : this._coalescedFollowUpOwner(action);if (coalescedOwner) {if (action.agentMessageId !== coalescedOwner.agentMessageId) {@@ -5214,7 +5412,9 @@ export class AgentSession {action.payload.kind === "session_command" ||action.wake === "immediate")) {- if (action.payload.kind === "turn" && action.wake === "immediate") this._sessionInputPumpSuspended = false;+ if (action.payload.kind === "turn" && action.wake === "immediate") {+ this._resumeSessionInputAdmission();+ }this._scheduleSessionInputPump();}return { accepted: true, disposition, ticket: controller.ticket };@@ -5436,6 +5636,7 @@ export class AgentSession {action.lifecycle.state === "failed" ||action.lifecycle.state === "cancelled")) {+ this._durableRlmTerminalNoticeActionIds.delete(action.id);this._actionStore.releaseTerminal(action);}}@@ -5810,6 +6011,7 @@ export class AgentSession {});}} else if (options?.triggerTurn) {+ if (!this._sessionInputSuspendedForUpdateRestart) this._resumeSessionInputAdmission();const admissionFence = await this._acquireDirectTurnAdmissionFence();try {const normalized = normalizeMessageContent(message.content);@@ -6064,6 +6266,7 @@ export class AgentSession {this.isBashRunning ||this._refineInFlight !== undefined ||this._branchSummaryOperation !== undefined ||+ this._postCompactionContinuationSettlement !== undefined ||this.unfinishedActionCount > 0);}@@ -6263,6 +6466,25 @@ export class AgentSession {}}+ acquireSessionInputPause(): { release(): void } {+ const token = Symbol("session-input-admission-pause");+ this._sessionInputAdmissionPauses.add(token);+ this._sessionInputPumpRequested = false;+ this._sessionInputPumpEpoch++;+ let released = false;+ return {+ release: () => {+ if (released) return;+ released = true;+ this._sessionInputAdmissionPauses.delete(token);+ this._sessionInputPumpEpoch++;+ this._notifySessionInputCheckpointChange();+ this._flushDeferredRlmTerminalNotices();+ this._scheduleSessionInputPump();+ },+ };+ }+acquireQueuedWorkPause(): { release(): void } {const token = Symbol("queued-work-pause");this._queuedWorkPauses.add(token);@@ -6275,6 +6497,7 @@ export class AgentSession {released = true;this._queuedWorkPauses.delete(token);this._notifySessionInputCheckpointChange();+ this._flushDeferredRlmTerminalNotices();this._scheduleSessionInputPump();},};@@ -6361,10 +6584,18 @@ export class AgentSession {};}- /** Resume the scheduler after requestAbort/abortForUpdateRestart suspended it; owned pause leases are unaffected. */- resumeQueuedWork(): boolean {+ private _resumeSessionInputAdmission(): void {+ if (!this._sessionInputPumpSuspended) return;this._sessionInputPumpSuspended = false;+ this._sessionInputSuspendedForUpdateRestart = false;+ this._sessionInputPumpEpoch++;this._notifySessionInputCheckpointChange();+ this._flushDeferredRlmTerminalNotices();+ }++ /** Resume the scheduler after requestAbort/abortForUpdateRestart suspended it; owned pause leases are unaffected. */+ resumeQueuedWork(): boolean {+ this._resumeSessionInputAdmission();this._scheduleSessionInputPump();return this._hasSelectableSessionInput();}@@ -6403,6 +6634,16 @@ export class AgentSession {}}+ /** Wait for normal idle and any continuation already owned by compaction. */+ async waitForHeadlessIdle(): Promise<void> {+ while (true) {+ await this.waitForIdle();+ const postCompactionContinuation = this._postCompactionContinuationSettlement?.promise;+ if (!postCompactionContinuation) return;+ await postCompactionContinuation;+ }+ }+getPendingNextTurnMessageSnapshots(): readonly CustomMessage[] {const messages = this._pendingNextTurnMessages.map((message) => cloneCustomMessage(message));for (const action of this._actionStore.unfinishedActions()) {@@ -6429,6 +6670,7 @@ export class AgentSession {restorePendingNextTurnMessages(messages: readonly CustomMessage[]): void {this._pendingNextTurnMessages.push(...messages.map((message) => cloneCustomMessage(message)));+ this._flushDeferredRlmTerminalNotices();}removeQueuedFollowUp(queueKey: string): boolean {@@ -6449,11 +6691,20 @@ export class AgentSession {}requestAbort(): void {+ for (const run of [...this._unsettledRlmChildRuns]) {+ if (run.status === "cancelled") this._abandonRlmRunForQuiescence(run);+ }+ for (const controller of this._rlmQuiescenceWaitAborts) controller.abort();this._sessionInputPumpRequested = false;this._sessionInputPumpEpoch++;this._sessionInputPumpSuspended = true;+ this._sessionInputSuspendedForUpdateRestart = false;+ this._demoteRlmTerminalNoticeActions();this._cancelSessionActions(- (action) => action.payload.kind === "turn" && !action.payload.queueVisible,+ (action) =>+ action.payload.kind === "turn" &&+ !action.payload.queueVisible &&+ !this._durableRlmTerminalNoticeActionIds.has(action.id),new Error("Prompt aborted before delivery."),);this._cancelPostCompactionContinue();@@ -6492,8 +6743,10 @@ export class AgentSession {this._sessionInputPumpRequested = false;this._sessionInputPumpEpoch++;this._sessionInputPumpSuspended = true;+ this._sessionInputSuspendedForUpdateRestart = true;this._cancelPostCompactionContinue();this.abortRetry();+ for (const controller of this._rlmQuiescenceWaitAborts) controller.abort();this._cancelActiveRlmChildRuns("Parent session aborted for update restart");this._goalAbortInProgress = this._goalState.status === "active";this.agent.abort();@@ -7059,6 +7312,13 @@ export class AgentSession {return this._rlmDepth === 0 && this._localHarnessStateDir() !== undefined;}+ private _settlePostCompactionContinue(): void {+ if (this._postCompactionContinuationScheduled || this._postCompactionContinuationTimer) return;+ const settlement = this._postCompactionContinuationSettlement;+ this._postCompactionContinuationSettlement = undefined;+ settlement?.resolve();+ }+private _cancelPostCompactionContinue(): void {if (this._postCompactionContinuationTimer) {clearTimeout(this._postCompactionContinuationTimer);@@ -7066,6 +7326,7 @@ export class AgentSession {}this._postCompactionContinuationScheduled = false;this._scheduledPostCompactionContinuationMessages = [];+ this._settlePostCompactionContinue();}private _discardPendingAutoRefine(options: { cancelPostCompactionContinue?: boolean } = {}): void {@@ -7162,11 +7423,14 @@ export class AgentSession {if (this._postCompactionContinuationScheduled) {return;}+ this._postCompactionContinuationSettlement ??= createAgentMessageDeferred();this._postCompactionContinuationScheduled = true;this._scheduledPostCompactionContinuationMessages = [...this._postCompactionContinuationMessages];this._postCompactionContinuationTimer = setTimeout(() => {this._postCompactionContinuationTimer = undefined;- void this._runScheduledPostCompactionContinue();+ void this._runScheduledPostCompactionContinue()+ .catch(() => undefined)+ .finally(() => this._settlePostCompactionContinue());}, 100);}@@ -8893,6 +9157,14 @@ export class AgentSession {return { session: child };}+ private _abandonRlmRunForQuiescence(run: RlmChildRun): void {+ run.suppressTerminalNotice = true;+ run.abandonedForQuiescence = true;+ this._abandonedRlmQuiescenceChildIds.add(run.id);+ this._unsettledRlmChildRuns.delete(run);+ run.settlement.resolve();+ }+private _cancelActiveRlmChildRuns(reason: string): void {for (const run of this._activeRlmChildRuns.values()) {this._cancelRlmChildRun(run, reason);@@ -8904,6 +9176,7 @@ export class AgentSession {return false;}run.status = "cancelled";+ if (this._sessionInputPumpSuspended) this._abandonRlmRunForQuiescence(run);run.error = reason;run.publication.reject(new Error(reason));run.abort();@@ -9161,8 +9434,19 @@ export class AgentSession {try {return await deletion;} finally {- if (this._deletingRlmChildren.get(subagent.rlm_child_id)?.promise === deletion) {- this._deletingRlmChildren.delete(subagent.rlm_child_id);+ const clearReservation = () => {+ if (this._deletingRlmChildren.get(subagent.rlm_child_id)?.promise === deletion) {+ this._deletingRlmChildren.delete(subagent.rlm_child_id);+ }+ };+ const run = this._activeRlmChildRuns.get(subagent.rlm_child_id);+ if (run?.detachedDeletion) {+ // Keep every selector reserved until the run settles, or until a failed+ // cleanup is exposed for an explicit retry. Repeated deletes before that+ // boundary return the same accepted result.+ void run.deletionReservation.promise.then(clearReservation, clearReservation);+ } else {+ clearReservation();}}}@@ -9174,12 +9458,92 @@ export class AgentSession {return session?.disposeAsync() ?? Promise.resolve();}+ private _ensureRlmRunDeletionCleanup(run: RlmChildRun, session: AgentSession): Promise<void> {+ if (run.deletionCleanup) return run.deletionCleanup;+ const cleanup = Promise.resolve().then(() => this._deleteRlmSubagentSession(run.id, session));+ run.deletionCleanup = cleanup;+ // Deletion admission is intentionally nonblocking. The detached run owner+ // joins this exact promise before settlement and records any failure.+ void cleanup.catch(() => undefined);+ return cleanup;+ }++ private async _recordRlmRunDeletionCleanupFailure(+ run: RlmChildRun,+ subagent: RlmSubagentRegistryEntry,+ session: AgentSession,+ error: unknown,+ ): Promise<void> {+ if (this._disposed || this._disposing) {+ run.suppressTerminalNotice = true;+ await session.disposeAsync().catch(() => undefined);+ if (!run.settled) await this._finishRlmRunDeletion(run);+ return;+ }+ run.deletionCleanup = undefined;+ run.deletionCleanupObserver = undefined;+ run.deletionCleanupFailed = true;+ run.session = session;+ this._rlmChildCleanupFailures.set(run.id, subagent);+ // Make retry admission available before waking the parent model with the+ // retry-required notice.+ run.deletionReservation.resolve();+ await Promise.resolve();+ await run.reportDeletionCleanupFailure?.(error);+ }++ private async _finishRlmRunDeletion(run: RlmChildRun): Promise<void> {+ await run.completeDeletion?.();+ if (this._activeRlmChildRuns.get(run.id) === run) {+ this._removeRlmSubagentTracking(run.id, run);+ }+ run.settled = true;+ run.settlement.resolve();+ run.deletionReservation.resolve();+ this._unsettledRlmChildRuns.delete(run);+ }++ private _observeRlmRunDeletionCleanup(+ run: RlmChildRun,+ subagent: RlmSubagentRegistryEntry,+ session: AgentSession,+ cleanup: Promise<void>,+ ): Promise<boolean> {+ if (run.deletionCleanupObserver) return run.deletionCleanupObserver;+ const observer = cleanup.then(+ () => true,+ async (error) => {+ await this._recordRlmRunDeletionCleanupFailure(run, subagent, session, error);+ return false;+ },+ );+ run.deletionCleanupObserver = observer;+ void observer.catch(() => undefined);+ return observer;+ }++ private _continueFinishedRlmRunDeletion(+ run: RlmChildRun,+ subagent: RlmSubagentRegistryEntry,+ session: AgentSession,+ ): void {+ const cleanup = this._ensureRlmRunDeletionCleanup(run, session);+ const observer = this._observeRlmRunDeletionCleanup(run, subagent, session, cleanup);+ if (!run.deletionRunFinished) return;+ void observer+ .then(async (cleanupSucceeded) => {+ if (cleanupSucceeded) await this._finishRlmRunDeletion(run);+ })+ .catch(() => undefined);+ }+private _removeRlmSubagentTracking(childId: string, run?: RlmChildRun): void {run?.unsubscribe?.();this._rlmChildUnsubscribes.get(childId)?.();this._rlmChildUnsubscribes.delete(childId);this._rlmChildSessions.delete(childId);this._rlmChildCleanupFailures.delete(childId);+ this._abandonedRlmQuiescenceChildIds.delete(childId);if (!run || this._activeRlmChildRuns.get(childId) === run) {this._activeRlmChildRuns.delete(childId);}@@ -9210,7 +9574,20 @@ export class AgentSession {const childId = subagent.rlm_child_id;const run = this._activeRlmChildRuns.get(childId);if (run) {- if (!this._cancelRlmChildRun(run, "Deleted by parent orchestrator")) {+ if (run.deletionCleanupFailed) {+ // Reset retry coordination only after selector preflight reaches the+ // resolved child. A failed preflight must leave the prior retry boundary+ // intact so a later call can acquire it.+ run.deletionCleanupFailed = false;+ run.deletionReservation = createAgentMessageDeferred();+ }+ // The detached task remains the sole lifecycle owner. Mark deletion before+ // cancellation so its catch/finally path cannot race a normal release or+ // terminal notice against the physical delete.+ run.detachedDeletion = subagent;+ if (this._cancelRlmChildRun(run, "Deleted by parent orchestrator")) {+ run.deletionNeedsCompletionNotice = true;+ } else {this._emitRlmSubagentRemoval(subagent);}const liveSession = run.session;@@ -9219,33 +9596,16 @@ export class AgentSession {this._removeRlmSubagentTracking(childId, run);return { subagent };}- if (liveSession) {- try {- await this._deleteRlmSubagentSession(childId, liveSession);- } catch (error) {- if (this._disposed || this._disposing) {- this._removeRlmSubagentTracking(childId, run);- void liveSession.disposeAsync().catch(() => undefined);- throw error;- }- this._rlmChildSessions.set(childId, liveSession);- this._rlmChildCleanupFailures.set(childId, subagent);- if (run.unsubscribe) this._rlmChildUnsubscribes.set(childId, run.unsubscribe);- this._activeRlmChildRuns.delete(childId);- run.abort = noopRlmChildAbort;- run.unsubscribe = undefined;- run.session = undefined;- throw error;- }- this._deletedRlmChildIds.add(childId);- this._removeRlmSubagentTracking(childId, run);- return { subagent };+ if (liveSession && run.settled) {+ run.deletionRunFinished = true;+ run.settlement = createAgentMessageDeferred();+ run.settled = false;+ this._unsettledRlmChildRuns.add(run);}+ if (liveSession) this._continueFinishedRlmRunDeletion(run, subagent, liveSession);- // Startup can be blocked in a host before it has a session to close. Admit- // deletion immediately, but retain the cancelled run as a hidden tombstone- // until startup settles so selectors cannot be reused underneath it.- run.detachedDeletion = subagent;+ // Return once deletion is accepted. The run stays hidden but unsettled until+ // abort-insensitive model/tool work unwinds and the shared cleanup finishes.this._deletedRlmChildIds.add(childId);return { subagent };}@@ -9309,6 +9669,54 @@ export class AgentSession {return unsubscribe;}+ /** Live recursive child roster from lifecycle state, including nested work under retained parents. */+ getRlmChildSnapshots(): RlmChildAgentSnapshot[] {+ const snapshots: RlmChildAgentSnapshot[] = [];+ const recorded = new Set<string>();+ const traversed = new Set<string>();+ for (const run of this._activeRlmChildRuns.values()) {+ const hidden =+ run.detachedDeletion || this._deletingRlmChildren.has(run.id) || this._deletedRlmChildIds.has(run.id);+ const child = run.session;+ if (!hidden) {+ const model = child?.model ?? run.model;+ snapshots.push({+ id: run.id,+ parentId: this._rlmParentNodeId,+ sessionName: child?.sessionName ?? run.sessionName,+ model: `${model.provider}/${model.id}`,+ label: rlmChildLabel(run.prompt),+ status: run.status,+ sessionDir: run.sessionDir,+ });+ recorded.add(run.id);+ }+ if (child) {+ traversed.add(run.id);+ snapshots.push(...child.getRlmChildSnapshots());+ }+ }+ for (const [childId, child] of this._rlmChildSessions) {+ if (recorded.has(childId) || traversed.has(childId)) continue;+ const hidden = this._deletingRlmChildren.has(childId) || this._deletedRlmChildIds.has(childId);+ if (!hidden) {+ snapshots.push({+ id: childId,+ parentId: this._rlmParentNodeId,+ sessionName: child.sessionName,+ model: child.model ? `${child.model.provider}/${child.model.id}` : undefined,+ label: child.sessionName ?? "child agent",+ // A failed delete retains the session solely for cleanup retry. Preserve+ // its cancellation truth in snapshots rather than reviving it as done.+ status: this._rlmChildCleanupFailures.has(childId) ? "cancelled" : "done",+ sessionDir: child._rlmSessionDir ?? child.sessionManager.getSessionDir(),+ });+ }+ snapshots.push(...child.getRlmChildSnapshots());+ }+ return snapshots;+ }+/** True when any direct or nested subagent is still running or queued. */hasRunningRlmChildren(): boolean {for (const run of this._activeRlmChildRuns.values()) {@@ -9328,6 +9736,78 @@ export class AgentSession {return false;}+ private _rlmChildSessionSnapshot(): AgentSession[] {+ const sessions = new Set<AgentSession>();+ for (const [childId, session] of this._rlmChildSessions) {+ if (!this._abandonedRlmQuiescenceChildIds.has(childId)) sessions.add(session);+ }+ for (const run of this._activeRlmChildRuns.values()) {+ if (run.session && !run.abandonedForQuiescence) sessions.add(run.session);+ }+ return [...sessions];+ }++ private _hasUnsettledRlmQuiescenceWork(): boolean {+ if (this._hasDeferredRlmTerminalNotices()) return true;+ if ([...this._unsettledRlmChildRuns].some((run) => !run.settled)) return true;+ return this._rlmChildSessionSnapshot().some(+ (child) => child.isSessionActive || child._hasUnsettledRlmQuiescenceWork(),+ );+ }++ /**+ * Wait for every admitted descendant run to publish its terminal parent+ * message and for the resulting parent turns to drain. Re-snapshotting after+ * each drain includes descendants spawned while earlier results were consumed.+ */+ async waitForRlmQuiescence(externalSignal?: AbortSignal): Promise<void> {+ const cancellation = new AbortController();+ const cancelFromParent = () => cancellation.abort();+ if (externalSignal?.aborted) cancellation.abort();+ else externalSignal?.addEventListener("abort", cancelFromParent, { once: true });+ this._rlmQuiescenceWaitAborts.add(cancellation);+ let rejectCancelled = (_error: Error) => {};+ const cancelled = new Promise<never>((_resolve, reject) => {+ rejectCancelled = reject;+ });+ const onCancelled = () => rejectCancelled(new Error("RLM quiescence wait cancelled"));+ cancellation.signal.addEventListener("abort", onCancelled, { once: true });+ if (cancellation.signal.aborted) onCancelled();+ const wait = <T>(operation: Promise<T>): Promise<T> => Promise.race([operation, cancelled]);+ try {+ while (true) {+ await wait(this.waitForHeadlessIdle());+ // Strong RLM quiescence also owns session-level work (bash, refine,+ // branch mutation, and manual compaction) that interactive waitForIdle+ // intentionally ignores. Yield a macrotask while such work is active so+ // recursive parent/child barriers cannot form a microtask busy-loop.+ if (this.isSessionActive || this._hasDeferredRlmTerminalNotices()) {+ await wait(new Promise<void>((resolve) => setTimeout(resolve, 0)));+ continue;+ }+ const unsettledRuns = [...this._unsettledRlmChildRuns].filter((run) => !run.settled);+ const childSessions = this._rlmChildSessionSnapshot();+ if (unsettledRuns.length === 0 && !this._hasUnsettledRlmQuiescenceWork()) return;+ await wait(+ Promise.all([+ ...unsettledRuns.map((run) => run.settlement.promise),+ ...childSessions.map((child) => child.waitForRlmQuiescence(cancellation.signal)),+ ]),+ );+ // Always loop through the self-active/deferred checks again. Work may+ // start at the child-settlement boundary.+ }+ } finally {+ // A local descendant error must cancel sibling recursive waits owned by+ // this barrier before their propagation listeners are removed.+ cancellation.abort();+ externalSignal?.removeEventListener("abort", cancelFromParent);+ cancellation.signal.removeEventListener("abort", onCancelled);+ this._rlmQuiescenceWaitAborts.delete(cancellation);+ }+ }++ // Inline (non-daemon) mode only; daemon clients attach to the child session directly.getRlmChildSession(childId: string): AgentSession | undefined {const direct = this._activeRlmChildRuns.get(childId)?.session ?? this._rlmChildSessions.get(childId);if (direct) {@@ -9348,9 +9828,20 @@ export class AgentSession {return undefined;}+ /**+ * Cancel a single RLM child run by id, searching nested child sessions.+ *+ * @returns true when a live run was cancelled or its unsettled terminal notice+ * was suppressed; false when the id is unknown or the run already settled.+ */cancelRlmChildRun(childId: string, reason = "Cancelled by user"): boolean {const run = this._activeRlmChildRuns.get(childId);if (run) {+ if (run.status !== "running" && run.status !== "queued" && !run.settled) {+ if (this._sessionInputPumpSuspended) this._abandonRlmRunForQuiescence(run);+ else run.suppressTerminalNotice = true;+ return true;+ }return this._cancelRlmChildRun(run, reason);}for (const candidate of this._activeRlmChildRuns.values()) {@@ -9507,15 +9998,19 @@ export class AgentSession {prompt,sessionName,sessionDir: childSessionDir,+ model: modelSelection.model,status: "queued",settled: false,abort: noopRlmChildAbort,publication: createAgentMessageDeferred(),+ settlement: createAgentMessageDeferred(),+ deletionReservation: createAgentMessageDeferred(),};const throwIfCancelled = () => {if (run.status === "cancelled") throw new Error(run.error ?? "RLM child cancelled");};this._activeRlmChildRuns.set(run.id, run);+ this._unsettledRlmChildRuns.add(run);const emitChildUpdate = () => {const childModel = childSession?.model ?? modelSelection.model;this._emit({@@ -9548,6 +10043,9 @@ export class AgentSession {run.session = child;run.abort = () => void child.abort();run.publication.resolve();+ // Cancellation may have been admitted while runtime construction was+ // blocked and run.abort was still a no-op.+ if (run.status === "cancelled") run.abort();};const subagentOptions: CreateRlmSubagentRuntimeOptions = {...this._createRlmSubagentRuntimeOptions({@@ -9563,24 +10061,38 @@ export class AgentSession {};const deliverTerminalMessageToParent = async (message: CustomMessage): Promise<void> => {- const childController = childSession?._agentMessageController;- if (childController) {- try {- await childController.sendAgentMessage({- target: this.sessionId,- message: message.content as string,- });- return;- } catch {- // An unattributed notice beats silence, so fall through to the injected path.- }- }- await this._promptInjectedMessage(message.content as string, message, {- streamingBehavior: "followUp",- queueIfBusy: true,- returnAfterAccepted: true,- suppressAutonomousContinuation: true,- }).catch(() => undefined);+ // Synthesized lifecycle notices always use the parent's private durable+ // path. Explicit child replies continue through agent_message separately.+ await this._deferRlmTerminalNotice(message);+ };++ run.completeDeletion = () => {+ if (!run.deletionNeedsCompletionNotice || run.suppressTerminalNotice || this._disposed || this._disposing) {+ return Promise.resolve();+ }+ if (run.deletionNotice) return run.deletionNotice;+ const notice = deliverTerminalMessageToParent(+ createRlmChildTerminalNoticeMessage({+ kind: "cancelled",+ childId: run.id,+ sessionName,+ reason: run.error ?? "Deleted by parent orchestrator",+ }),+ );+ run.deletionNotice = notice;+ return notice;+ };++ run.reportDeletionCleanupFailure = (error) => {+ if (run.suppressTerminalNotice || this._disposed || this._disposing) return Promise.resolve();+ const cleanupError = error instanceof Error ? error.message : String(error);+ return deliverTerminalMessageToParent(+ createRlmChildFailureMessage({+ childId: run.id,+ sessionName,+ error: `Deletion cleanup failed; retry rlm.delete_subagent("${run.id}") before completion: ${cleanupError}`,+ }),+ );};// Runtime startup and the task run are deliberately detached. The public@@ -9686,12 +10198,17 @@ export class AgentSession {source: "extension",customMessage: spawnMessage,});+ await child.waitForRlmQuiescence();if (run.error) throw new Error(run.error);run.status = "done";durationMs = Date.now() - startedAt;activity = undefined;emitChildUpdate();- if (!run.detachedDeletion && child._parentReplyCount === parentReplyCountBeforeRun) {+ if (+ !run.detachedDeletion &&+ !run.suppressTerminalNotice &&+ child._parentReplyCount === parentReplyCountBeforeRun+ ) {const lastAssistantText = child.getLastAssistantText();await deliverTerminalMessageToParent(createRlmChildTerminalNoticeMessage({@@ -9702,7 +10219,7 @@ export class AgentSession {}),);}- if (!this.registerRlmChildSession(run.id, child)) {+ if (!this.registerRlmChildSession(run.id, child) && !run.detachedDeletion) {if (childRuntime && this._subagentRuntimeHost?.releaseRlmSubagentRuntime) {await this._subagentRuntimeHost.releaseRlmSubagentRuntime(childRuntime, subagentOptions, "error")@@ -9721,7 +10238,7 @@ export class AgentSession {durationMs = Date.now() - startedAt;activity = undefined;emitChildUpdate();- if (!run.detachedDeletion) {+ if (!run.detachedDeletion && !run.suppressTerminalNotice) {if (run.status === "error") {await deliverTerminalMessageToParent(createRlmChildFailureMessage({@@ -9771,32 +10288,42 @@ export class AgentSession {}}} finally {- if (run.detachedDeletion && childRuntime) {- try {- await this._deleteRlmSubagentSession(run.id, childRuntime.session);- } catch {- if (!this._disposed && !this._disposing) {- this._rlmChildSessions.set(run.id, childRuntime.session);- this._rlmChildCleanupFailures.set(run.id, run.detachedDeletion);+ if (run.detachedDeletion) {+ run.deletionRunFinished = true;+ if (!run.settled) {+ let cleanupSucceeded = !run.deletionCleanupFailed;+ if (childRuntime && cleanupSucceeded) {+ const cleanup =+ run.deletionCleanup ?? this._ensureRlmRunDeletionCleanup(run, childRuntime.session);+ cleanupSucceeded = await this._observeRlmRunDeletionCleanup(+ run,+ run.detachedDeletion,+ childRuntime.session,+ cleanup,+ );}+ if (cleanupSucceeded) await this._finishRlmRunDeletion(run);}- }- if (this._activeRlmChildRuns.get(run.id) === run) {- if (this._rlmChildSessions.has(run.id)) {- this._activeRlmChildRuns.delete(run.id);- if (run.unsubscribe) this._rlmChildUnsubscribes.set(run.id, run.unsubscribe);- run.abort = noopRlmChildAbort;- run.unsubscribe = undefined;- run.session = undefined;- } else if (run.status !== "error" || run.detachedDeletion) {- this._removeRlmSubagentTracking(run.id, run);- } else {- run.unsubscribe?.();- run.abort = noopRlmChildAbort;- run.unsubscribe = undefined;+ } else {+ if (this._activeRlmChildRuns.get(run.id) === run) {+ if (this._rlmChildSessions.has(run.id)) {+ this._activeRlmChildRuns.delete(run.id);+ if (run.unsubscribe) this._rlmChildUnsubscribes.set(run.id, run.unsubscribe);+ run.abort = noopRlmChildAbort;+ run.unsubscribe = undefined;+ run.session = undefined;+ } else if (run.status !== "error") {+ this._removeRlmSubagentTracking(run.id, run);+ } else {+ run.unsubscribe?.();+ run.abort = noopRlmChildAbort;+ run.unsubscribe = undefined;+ }}+ run.settled = true;+ run.settlement.resolve();+ this._unsettledRlmChildRuns.delete(run);}- run.settled = true;}})().catch(() => undefined);diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.tsindex 5468fcf417..385fde6831 100644--- a/packages/coding-agent/src/main.ts+++ b/packages/coding-agent/src/main.ts@@ -194,6 +194,10 @@ function toPrintOutputMode(appMode: AppMode): Exclude<Mode, "rpc" | "acp" | "daereturn appMode === "json" ? "json" : "text";}+export function isClientOwnedDaemonSession(appMode: AppMode, noSession?: boolean): boolean {+ return appMode !== "acp" || noSession === true;+}+// `prime-agent agents` opens the agents view directly.export function parseAgentsViewCommand(args: string[]): { explicitAgentsView: boolean; args: string[] } {if (args[0] === "agents") {@@ -965,6 +969,7 @@ async function createDaemonClientConnection(options: {closeClientOnDispose: true,sendClientEnv: true,ownedSession: options.clientOwned,+ ownedSessionRecoveryConfig: options.clientOwned ? options.config : undefined,supportsExtensionUi: options.supportsExtensionUi,recoverDaemon: () => ensureInteractiveDaemonRunning(options.socketPath),telemetryDisabled: options.config.telemetryDisabled,@@ -982,7 +987,7 @@ async function createDaemonClientConnection(options: {await listActiveDaemonSessionSummaries(client),options.sessionPath,);- if (activeSummary) {+ if (activeSummary && activeSummary.workerState !== "failed") {return await attach(activeSummary);}}@@ -1001,7 +1006,7 @@ async function createDaemonClientConnection(options: {noSession: options.noSession,env: collectDaemonClientEnv(),lifecycle: options.clientOwned ? "client_owned" : "resident",- launchEnv: options.clientOwned ? collectDaemonLaunchEnv() : undefined,+ launchEnv: collectDaemonLaunchEnv(),});if (!response.success) {throw deserializeDaemonError(response);@@ -1537,7 +1542,7 @@ export async function main(args: string[], options?: MainOptions) {config: defaultSessionConfig,sessionPath: parsed.noSession ? undefined : sessionManager.getSessionFile(),continueRecent: parsed.continue,- clientOwned: true,+ clientOwned: isClientOwnedDaemonSession(appMode, parsed.noSession),noSession: parsed.noSession,supportsExtensionUi: appMode === "rpc",}));diff --git a/packages/coding-agent/src/modes/acp/acp-meta.ts b/packages/coding-agent/src/modes/acp/acp-meta.tsindex fbe1ff211c..1918616da2 100644--- a/packages/coding-agent/src/modes/acp/acp-meta.ts+++ b/packages/coding-agent/src/modes/acp/acp-meta.ts@@ -59,6 +59,13 @@ export interface PrimeAgentRefinementMeta {error?: string;}+export interface PrimeAgentQuiescenceMeta {+ /** Subagents that have not reached a terminal state at the observation point. */+ outstandingSubagents: number;+ /** Autonomous continuation slots still available at the observation point. */+ remainingAutonomousContinuations: number;+}+export interface PrimeAgentAgentMessageMeta {toolCallId: string;target?: string;@@ -72,7 +79,35 @@ export interface PrimeAgentCwdMeta {actual: string;}+/**+ * Producer-side ordering and causality for ACP updates.+ *+ * `promptTurnId` is allocated when ACP accepts a prompt, never inferred from+ * whichever prompt happens to be running when an update is delivered. `0`+ * means a session-scoped event with no prompt origin (for example a heartbeat+ * change before the first prompt). `eventSequence` is connection-wide and+ * strictly increases for every update Prime Agent publishes.+ */+export type PrimeAgentEventPhase = "event" | "responseBoundary" | "terminalQuiescence";++/** The outcome carried by a correlated response boundary and terminal envelope. */+export type PrimeAgentResponseOutcome = "result" | "error";+export interface PrimeAgentSessionMeta {+ /** Monotonically increasing ACP prompt turn which caused this update. */+ promptTurnId?: number;+ /** Strictly increasing producer sequence, across all ACP updates. */+ eventSequence?: number;+ /** Whether this is ordinary work, the prompt response boundary, or final quiescence. */+ phase?: PrimeAgentEventPhase;+ /**+ * The boundary/terminal outcome. This deliberately has only `result` and+ * `error`: ACP's transport stop reasons (including `end_turn`) are never a+ * causal completion signal.+ */+ outcome?: PrimeAgentResponseOutcome;+ /** Whether an accepted response boundary promises a later terminal-quiescence envelope. */+ terminalQuiescenceExpected?: boolean;/** Present when a client-requested cwd differs from the agent's real cwd. */cwd?: PrimeAgentCwdMeta;/** Set when the session's heartbeat or cron schedule changed. */@@ -86,6 +121,8 @@ export interface PrimeAgentSessionMeta {compaction?: { tokensBefore?: number; summary?: string };subagents?: PrimeAgentSubagentMeta[];autonomous?: PrimeAgentAutonomousMeta;+ /** Observed subagent and autonomous-continuation counts at completion. */+ quiescence?: PrimeAgentQuiescenceMeta;ipython?: PrimeAgentIpythonMeta;}diff --git a/packages/coding-agent/src/modes/acp/acp-mode.ts b/packages/coding-agent/src/modes/acp/acp-mode.tsindex 4228c5ed8e..3c1b768203 100644--- a/packages/coding-agent/src/modes/acp/acp-mode.ts+++ b/packages/coding-agent/src/modes/acp/acp-mode.ts@@ -10,10 +10,15 @@ import type { AgentSessionRuntime } from "../../core/agent-session-runtime.js";import type { AgentAutonomousStatus } from "../../core/autonomous.js";import { takeOverStdout, writeRawStdout } from "../../core/output-guard.js";import { InProcessAgentConnection } from "../agent-connection/in-process-agent-connection.js";-import type { AgentConnection } from "../agent-connection/types.js";+import type {+ AgentConnection,+ AgentConnectionRlmChildAgentSnapshot,+ AgentConnectionSessionEvent,+ AgentConnectionSessionInputPause,+} from "../agent-connection/types.js";import { latestAutonomousGateAttempt } from "../headless-completion.js";import { type AcpEventMappingState, acpUpdatesForSessionEvent } from "./acp-events.js";-import { primeAgentMeta } from "./acp-meta.js";+import { PRIME_AGENT_META_NAMESPACE, type PrimeAgentAutonomousMeta, primeAgentMeta } from "./acp-meta.js";import { type AcpStopReason, acpStopReason } from "./acp-stop-reason.js";/**@@ -51,6 +56,17 @@ function canonicalCwd(path: string): string {return normalizeWindowsDriveLetter(canonical);}+function isJsonRpcResponse(message: unknown, requestId: unknown): boolean {+ if (typeof message !== "object" || message === null) return false;+ const record = message as Record<string, unknown>;+ return (+ record.jsonrpc === "2.0" &&+ record.id === requestId &&+ !Object.hasOwn(record, "method") &&+ Object.hasOwn(record, "result") !== Object.hasOwn(record, "error")+ );+}+function sameCwd(left: string, right: string): boolean {const canonicalLeft = canonicalCwd(left);const canonicalRight = canonicalCwd(right);@@ -83,10 +99,217 @@ export interface AcpModeOptions {ownStdout?: boolean;}+interface AcpPendingTerminal {+ promptTurnId: number;+ boundary: TurnBoundary;+ outcome: "result" | "error";+ abort: AbortController;+ failure?: string;+ task?: Promise<void>;+}++interface AcpInputPauseRelease {+ promise: Promise<void>;+ resolve(): void;+ reject(error: unknown): void;+}+interface AcpSessionEntry {id: string;abort: AbortController | undefined;+ cancelling: boolean;+ cancelTask: Promise<void> | undefined;+ stopFailure: string | undefined;+ inputPause: AgentConnectionSessionInputPause | undefined;+ inputPauseKey: string | undefined;+ inputPauseRelease: AcpInputPauseRelease | undefined;+ pendingTerminal: AcpPendingTerminal | undefined;+ promptTask: Promise<void> | undefined;+ resolvePromptTask: (() => void) | undefined;unsubscribe: (() => void) | undefined;+ producer: AcpUpdateProducer;+}++/**+ * The sole producer of ACP session updates for one ACP session.+ *+ * ACP notifications are asynchronous, so assigning an id at each call site is+ * insufficient: detached calls can be observed out of order. This producer+ * serializes publication and stamps the *delivered* order. Its phase/outcome+ * fields are application metadata, deliberately independent of ACP stop+ * reasons such as `end_turn`.+ */+class AcpUpdateProducer {+ private eventSequence = 0;+ private nextPromptTurnId = 0;+ private activePromptTurnId = 0;+ private tail: Promise<void> = Promise.resolve();+ private readonly childOriginTurnIds = new Map<string, number>();+ private readonly terminalChildOriginTurns = new Set<number>();+ private readonly responseCommittedTurns = new Set<number>();+ private readonly terminalLifecycleTurns = new Set<number>();+ private readonly finishedPromptTurns = new Set<number>();+ private readonly admissionReady: Promise<void>;+ private releaseAdmission!: () => void;+ private admissionOpen = false;+ private admissionClosed = false;++ constructor(+ private readonly sessionId: string,+ private readonly client: { notify(method: unknown, params: unknown): Promise<unknown> },+ ) {+ // Subscribe before the initial snapshot, but do not let that subscription+ // publish a session-bound update before session/new has replied.+ this.admissionReady = new Promise<void>((resolve) => {+ this.releaseAdmission = resolve;+ });+ }++ commitSessionNewResponse(): void {+ if (this.admissionClosed) return;+ this.admissionOpen = true;+ this.releaseAdmission();+ }++ failSessionNewAdmission(): void {+ if (this.admissionOpen || this.admissionClosed) return;+ this.admissionClosed = true;+ this.releaseAdmission();+ }++ beginPrompt(): number {+ this.activePromptTurnId = ++this.nextPromptTurnId;+ return this.activePromptTurnId;+ }++ private cleanupTurn(turnId: number): void {+ this.responseCommittedTurns.delete(turnId);+ if (![...this.childOriginTurnIds.values()].some((originTurnId) => originTurnId === turnId)) {+ this.terminalChildOriginTurns.delete(turnId);+ }+ }++ beginTerminalLifecycle(turnId: number): void {+ this.terminalLifecycleTurns.add(turnId);+ }++ finishPrompt(turnId: number): void {+ if (this.activePromptTurnId === turnId) this.activePromptTurnId = 0;+ if (this.terminalLifecycleTurns.has(turnId)) {+ this.finishedPromptTurns.add(turnId);+ return;+ }+ this.cleanupTurn(turnId);+ }++ finishTerminalLifecycle(turnId: number): void {+ this.terminalLifecycleTurns.delete(turnId);+ if (this.finishedPromptTurns.delete(turnId)) this.cleanupTurn(turnId);+ }++ /**+ * Cut a scoreable terminal boundary before it is queued. A subscription+ * callback after this point is connection-scoped, never appended to a turn+ * that an evaluator may treat as terminal.+ */+ commitResponse(turnId: number): void {+ this.responseCommittedTurns.add(turnId);+ }++ isResponseCommitted(turnId: number): boolean {+ return this.responseCommittedTurns.has(turnId);+ }++ sealTerminal(turnId: number): void {+ this.commitResponse(turnId);+ if ([...this.childOriginTurnIds.values()].some((originTurnId) => originTurnId === turnId)) {+ this.terminalChildOriginTurns.add(turnId);+ }+ if (this.activePromptTurnId === turnId) this.activePromptTurnId = 0;+ }++ turnForEvent(event: AgentConnectionSessionEvent): number {+ if (event.type === "rlm_child_update") {+ const known = this.childOriginTurnIds.get(event.child.id);+ const originTurnId = known ?? this.activePromptTurnId;+ const turnId = this.terminalChildOriginTurns.has(originTurnId) ? 0 : originTurnId;+ const childFinished = ["done", "error", "cancelled"].includes(event.child.status);+ if (childFinished) {+ this.childOriginTurnIds.delete(event.child.id);+ if (![...this.childOriginTurnIds.values()].some((origin) => origin === originTurnId)) {+ this.terminalChildOriginTurns.delete(originTurnId);+ }+ } else if (known === undefined) {+ // Remember its initial origin, including connection scope, so a later+ // child update cannot be relabelled by a subsequent prompt.+ this.childOriginTurnIds.set(event.child.id, originTurnId);+ }+ return turnId;+ }+ return this.activePromptTurnId;+ }++ async publish(+ update: Record<string, unknown>,+ turnId: number,+ phase: "event" | "responseBoundary" | "terminalQuiescence",+ outcome?: "result" | "error",+ ): Promise<boolean> {+ // Admission is synchronous through the tail assignment below: close either+ // rejects this call here or drains the update after it joins the queue.+ if (this.admissionClosed) return false;+ const eventSequence = ++this.eventSequence;+ const priorMeta = (update._meta && typeof update._meta === "object" ? update._meta : {}) as Record<+ string,+ unknown+ >;+ const priorPrimeMeta =+ priorMeta[PRIME_AGENT_META_NAMESPACE] && typeof priorMeta[PRIME_AGENT_META_NAMESPACE] === "object"+ ? (priorMeta[PRIME_AGENT_META_NAMESPACE] as Record<string, unknown>)+ : {};+ const correlatedUpdate = {+ ...update,+ _meta: {+ ...priorMeta,+ [PRIME_AGENT_META_NAMESPACE]: {+ ...priorPrimeMeta,+ promptTurnId: turnId,+ eventSequence,+ phase,+ ...(outcome ? { outcome } : {}),+ },+ },+ };+ // Keep the chain alive after a failed notification, while preserving+ // the order of every later notification and allowing callers to await its drain.+ let published = false;+ this.tail = this.tail.then(async () => {+ try {+ await this.admissionReady;+ if (!this.admissionOpen) return;+ await this.client.notify(acp.methods.client.session.update, {+ sessionId: this.sessionId,+ update: correlatedUpdate,+ });+ published = true;+ } catch {+ // Drop only this update; a rejected queue tail would strand later updates.+ }+ });+ await this.tail;+ return published;+ }++ drain(): Promise<void> {+ return this.tail;+ }++ async close(): Promise<void> {+ this.admissionClosed = true;+ this.releaseAdmission();+ await this.tail;+ this.admissionOpen = false;+ }}/**@@ -124,18 +347,32 @@ function promptContent(blocks: readonly unknown[]): { text: string; images: Imagreturn { text: texts.join("\n"), images };}-function autonomousMeta(status: AgentAutonomousStatus | undefined): Record<string, unknown> | undefined {+function autonomousMeta(status: AgentAutonomousStatus | undefined): PrimeAgentAutonomousMeta | undefined {if (!status?.enabled) return undefined;- return primeAgentMeta({- autonomous: {- enabled: status.enabled,- continuationsUsed: status.continuationsUsed,- turnsUsed: status.turnsUsed,- tokensUsed: status.tokensUsed,- gateAttempt: latestAutonomousGateAttempt(status) || undefined,- gateFailure: status.lastGateFailure?.exitText,- },- });+ return {+ enabled: status.enabled,+ continuationsUsed: status.continuationsUsed,+ turnsUsed: status.turnsUsed,+ tokensUsed: status.tokensUsed,+ gateAttempt: latestAutonomousGateAttempt(status) || undefined,+ gateFailure: status.lastGateFailure?.exitText,+ };+}++function outstandingSubagentCount(children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined): number {+ return (children ?? []).filter((child) => child.status === "queued" || child.status === "running").length;+}++function quiescenceMeta(+ status: AgentAutonomousStatus,+ children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined,+): { outstandingSubagents: number; remainingAutonomousContinuations: number } {+ return {+ outstandingSubagents: outstandingSubagentCount(children),+ remainingAutonomousContinuations: status.enabled+ ? Math.max(0, status.limits.maxContinuations - status.continuationsUsed)+ : 0,+ };}/**@@ -235,10 +472,174 @@ export async function runAcpModeWithConnection(// session keeps every event unambiguously attributable; a second session/new// is refused rather than silently sharing conversation state, cwd, and queues.let session: AcpSessionEntry | undefined;+ let closedInputPause: AgentConnectionSessionInputPause | undefined;+ let closedInputPauseKey: string | undefined;+ let sessionNewInFlight = false;+ let sessionCloseInFlight = false;+ let sessionCloseTask: Promise<void> | undefined;let bound = false;- const stream =+ const baseStream =options.stream ?? acp.ndJsonStream(rawStdoutSink(), Readable.toWeb(process.stdin) as ReadableStream<Uint8Array>);+ // ACP's public request handler only returns a response; it has no response+ // commit callback. Observe the outgoing response at the supplied stream+ // boundary instead. The SDK serializes every write, so opening the producer+ // after this write resolves puts buffered notifications strictly behind it.+ let pendingSessionNewResponse:+ | {+ requestId: unknown;+ producer: AcpUpdateProducer;+ entry: AcpSessionEntry;+ inputPause: AgentConnectionSessionInputPause | undefined;+ }+ | undefined;+ const failPendingSessionNewResponse = (): void => {+ const admission = pendingSessionNewResponse;+ pendingSessionNewResponse = undefined;+ admission?.producer.failSessionNewAdmission();+ admission?.entry.inputPauseRelease?.reject(new Error("ACP session/new response was not delivered"));+ };+ type AcpStreamMessage = typeof baseStream.writable extends WritableStream<infer TMessage> ? TMessage : never;+ const stream: typeof baseStream = {+ readable: baseStream.readable,+ writable: new WritableStream<AcpStreamMessage>({+ async write(message) {+ let writer: WritableStreamDefaultWriter<AcpStreamMessage> | undefined;+ try {+ writer = baseStream.writable.getWriter();+ await writer.write(message);+ } catch (error) {+ failPendingSessionNewResponse();+ throw error;+ } finally {+ writer?.releaseLock();+ }+ if (pendingSessionNewResponse && isJsonRpcResponse(message, pendingSessionNewResponse.requestId)) {+ const admission = pendingSessionNewResponse;+ pendingSessionNewResponse = undefined;+ if (admission.inputPause) {+ try {+ await admission.inputPause.release();+ if (admission.entry.inputPause === admission.inputPause) {+ admission.entry.inputPause = undefined;+ admission.entry.inputPauseKey = undefined;+ }+ if (closedInputPause === admission.inputPause) {+ closedInputPause = undefined;+ closedInputPauseKey = undefined;+ }+ admission.entry.inputPauseRelease?.resolve();+ admission.entry.inputPauseRelease = undefined;+ } catch (error) {+ admission.entry.stopFailure = error instanceof Error ? error.message : String(error);+ admission.entry.inputPauseRelease?.reject(error);+ }+ }+ admission.producer.commitSessionNewResponse();+ }+ },+ async close() {+ let writer: WritableStreamDefaultWriter<AcpStreamMessage> | undefined;+ try {+ writer = baseStream.writable.getWriter();+ await writer.close();+ } catch (error) {+ failPendingSessionNewResponse();+ throw error;+ } finally {+ writer?.releaseLock();+ }+ failPendingSessionNewResponse();+ },+ async abort(reason) {+ let writer: WritableStreamDefaultWriter<AcpStreamMessage> | undefined;+ try {+ writer = baseStream.writable.getWriter();+ await writer.abort(reason);+ } catch (error) {+ failPendingSessionNewResponse();+ throw error;+ } finally {+ writer?.releaseLock();+ }+ failPendingSessionNewResponse();+ },+ }),+ };++ const cancelOutstandingRlmChildren = async (): Promise<void> => {+ const children = await connection.getRlmChildSnapshots();+ const cancellations = await Promise.allSettled(children.map((child) => connection.cancelRlmChild(child.id)));+ const failed = cancellations.find((result) => result.status === "rejected");+ if (failed?.status === "rejected") throw failed.reason;+ };+ const abortConnectionWork = async (): Promise<void> => {+ await connection.abortAndClearQueue();+ };+ const acquireStopInputPause = async (entry: AcpSessionEntry): Promise<AgentConnectionSessionInputPause> => {+ if (entry.inputPauseRelease) {+ await entry.inputPauseRelease.promise.catch(() => undefined);+ entry.inputPauseRelease = undefined;+ }+ const leaseKey = entry.inputPauseKey ?? randomUUID();+ entry.inputPauseKey = leaseKey;+ const pause = await connection.acquireSessionInputPause(leaseKey);+ entry.inputPause = pause;+ return pause;+ };++ const stopSessionWork = async (pending?: AcpPendingTerminal, promptTask?: Promise<void>): Promise<void> => {+ await abortConnectionWork();+ await connection.waitForIdle();+ await cancelOutstandingRlmChildren();+ await pending?.task;+ await promptTask;+ };++ const finalizePendingTerminal = (entry: AcpSessionEntry, pending: AcpPendingTerminal): void => {+ pending.task = (async () => {+ while (true) {+ const status = await connection.waitForHeadlessCompletion({ waitForRlmQuiescence: true });+ if (pending.abort.signal.aborted || session !== entry || entry.pendingTerminal !== pending) return;+ const finalFailure = await turnFailure(connection, pending.boundary);+ if (pending.abort.signal.aborted || session !== entry || entry.pendingTerminal !== pending) return;+ const liveChildren = await connection.getRlmChildSnapshots();+ if (pending.abort.signal.aborted || session !== entry || entry.pendingTerminal !== pending) return;+ const terminalQuiescence = quiescenceMeta(status, liveChildren);+ if (terminalQuiescence.outstandingSubagents !== 0) continue;++ entry.producer.sealTerminal(pending.promptTurnId);+ const autonomous = autonomousMeta(status);+ const publication = entry.producer.publish(+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({ ...(autonomous ? { autonomous } : {}), quiescence: terminalQuiescence }),+ },+ pending.promptTurnId,+ "terminalQuiescence",+ finalFailure ? "error" : pending.outcome,+ );+ // publish() admits the terminal update synchronously before its first await.+ // Release the next prompt only after that ordering cut, not after the client+ // has already observed the notification.+ if (entry.pendingTerminal === pending) entry.pendingTerminal = undefined;+ if (entry.abort === pending.abort) entry.abort = undefined;+ if (!(await publication)) return;+ await entry.producer.drain();+ return;+ }+ })()+ .catch((error: unknown) => {+ if (pending.abort.signal.aborted || entry.pendingTerminal !== pending) return;+ pending.failure = error instanceof Error ? error.message : String(error);+ })+ .finally(() => {+ entry.producer.finishTerminalLifecycle(pending.promptTurnId);+ if (!pending.abort.signal.aborted) return;+ if (entry.pendingTerminal === pending) entry.pendingTerminal = undefined;+ if (entry.abort === pending.abort) entry.abort = undefined;+ });+ };const handle = acp.agent({ name: "prime-agent" })@@ -257,116 +658,261 @@ export async function runAcpModeWithConnection(_meta: primeAgentMeta({}),})).onRequest("session/new", async (ctx: any) => {- if (!bound) {- // Only latch after a successful bind: a rejected bind must not leave- // extensions permanently unavailable for the rest of the process.- await options.bindHeadlessExtensions?.();- bound = true;- }- if (session) {+ // Reserve the single-session slot before the first await. Otherwise two+ // concurrent requests can both pass the empty-slot check while cwd or+ // snapshot reads are in flight, then overwrite each other's session.+ if (session || sessionNewInFlight || sessionCloseInFlight) {throw new Error("prime-agent ACP mode hosts one session per connection; " +"start another prime-agent process for a second session",);}- // prime-agent's cwd is fixed at startup by the session it was launched- // with, so a client-supplied cwd cannot be adopted after the fact.- // Report the real cwd back in `_meta` rather than failing the request or- // letting the client assume a directory the agent is not using.- const requestedCwd = (ctx.params as { cwd?: unknown } | undefined)?.cwd;- let cwdMismatch: { requested: string; actual: string } | undefined;- if (typeof requestedCwd === "string" && requestedCwd.length > 0) {- const actual = await connection- .getState()- .then((state) => state.cwd)- .catch(() => undefined);- if (actual && !sameCwd(requestedCwd, actual)) {- cwdMismatch = { requested: requestedCwd, actual };+ sessionNewInFlight = true;+ try {+ if (!bound) {+ // Only latch after a successful bind: a rejected bind must not leave+ // extensions permanently unavailable for the rest of the process.+ await options.bindHeadlessExtensions?.();+ bound = true;}- }- const sessionId = randomUUID();- const entry: AcpSessionEntry = { id: sessionId, abort: undefined, unsubscribe: undefined };- // Subscribe for the session lifetime, not per prompt turn: prime-agent- // subagents are fire-and-forget and keep reporting after the spawning turn- // ends, so a turn-scoped subscription would drop their updates. One- // mapping state per session keeps streaming bash output correlated with- // the run that produced it.- const mappingState: AcpEventMappingState = {};- const unsubscribe = connection.subscribe((event) => {- const notify = (update: Record<string, unknown>) =>- void ctx.client.notify(acp.methods.client.session.update, { sessionId, update }).catch(() => undefined);- // Heartbeats and cron schedules are connection-level rather than- // session events, but they drive the long-running work an ACP client- // most needs to observe.- if (event.type === "heartbeats_changed") {- notify({ sessionUpdate: "session_info_update", _meta: primeAgentMeta({ heartbeatsChanged: true }) });- return;+ // prime-agent's cwd is fixed at startup by the session it was launched+ // with, so a client-supplied cwd cannot be adopted after the fact.+ // Report the real cwd back in `_meta` rather than failing the request or+ // letting the client assume a directory the agent is not using.+ const requestedCwd = (ctx.params as { cwd?: unknown } | undefined)?.cwd;+ let cwdMismatch: { requested: string; actual: string } | undefined;+ if (typeof requestedCwd === "string" && requestedCwd.length > 0) {+ const actual = await connection+ .getState()+ .then((state) => state.cwd)+ .catch(() => undefined);+ if (actual && !sameCwd(requestedCwd, actual)) {+ cwdMismatch = { requested: requestedCwd, actual };+ }}- if (event.type !== "session_event") return;- for (const update of acpUpdatesForSessionEvent(event.event, mappingState)) {- notify(update);+ const sessionId = randomUUID();+ // Install the listener before fetching the snapshot. Child updates can arrive+ // while the snapshot request is in flight; the connection remains the+ // authoritative source used when quiescence is emitted below.+ const producer = new AcpUpdateProducer(sessionId, ctx.client);+ let inputPauseRelease: AcpInputPauseRelease | undefined;+ if (closedInputPause) {+ let resolve!: () => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<void>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ void promise.catch(() => undefined);+ inputPauseRelease = { promise, resolve, reject };}- });- // Claim the single-session slot only once the subscription exists, so a- // failed subscribe cannot leave the slot occupied and unusable.- entry.unsubscribe = unsubscribe;- session = entry;- return {- sessionId,- ...(cwdMismatch ? { _meta: primeAgentMeta({ cwd: cwdMismatch }) } : {}),- };+ const entry: AcpSessionEntry = {+ id: sessionId,+ abort: undefined,+ cancelling: false,+ cancelTask: undefined,+ stopFailure: undefined,+ inputPause: closedInputPause,+ inputPauseKey: closedInputPauseKey,+ inputPauseRelease,+ pendingTerminal: undefined,+ promptTask: undefined,+ resolvePromptTask: undefined,+ unsubscribe: undefined,+ producer,+ };+ // Subscribe for the session lifetime, not per prompt turn: prime-agent+ // subagents are fire-and-forget and keep reporting after the spawning turn+ // ends, so a turn-scoped subscription would drop their updates. One+ // mapping state per session keeps streaming bash output correlated with+ // the run that produced it.+ const mappingState: AcpEventMappingState = {};+ const observedChildren = new Map<string, unknown>();+ const unsubscribe = connection.subscribe((event) => {+ // Heartbeats are connection-scoped, including if one races a prompt.+ // They therefore intentionally use origin turn 0.+ if (event.type === "heartbeats_changed") {+ void producer.publish(+ { sessionUpdate: "session_info_update", _meta: primeAgentMeta({ heartbeatsChanged: true }) },+ 0,+ "event",+ );+ return;+ }+ if (event.type !== "session_event") return;+ if (event.event.type === "rlm_child_update") {+ observedChildren.set(event.event.child.id, event.event.child);+ }+ const turnId = producer.turnForEvent(event.event);+ for (const update of acpUpdatesForSessionEvent(event.event, mappingState)) {+ void producer.publish(update, turnId, "event");+ }+ });+ try {+ // Reconcile after subscribing so updates cannot be lost while the snapshot+ // request is in flight. Do not turn a failed read into an empty roster.+ const initialSnapshot = await connection.getInitialSnapshot();+ for (const child of initialSnapshot.children ?? []) {+ if (observedChildren.has(child.id)) continue;+ observedChildren.set(child.id, child);+ const event = { type: "rlm_child_update", child } as const;+ const turnId = producer.turnForEvent(event);+ for (const update of acpUpdatesForSessionEvent(event, mappingState)) {+ void producer.publish(update, turnId, "event");+ }+ }+ } catch (error) {+ producer.failSessionNewAdmission();+ unsubscribe();+ throw error;+ }+ // Claim the single-session slot only once the subscription and snapshot are+ // ready, so a failed setup cannot leave it occupied and unusable.+ entry.unsubscribe = unsubscribe;+ session = entry;+ const response = {+ sessionId,+ ...(cwdMismatch ? { _meta: primeAgentMeta({ cwd: cwdMismatch }) } : {}),+ };+ // The stream wrapper commits this gate after this exact response has+ // written. Buffered subscription updates retain producer order.+ pendingSessionNewResponse = {+ requestId: ctx.requestId,+ producer: entry.producer,+ entry,+ inputPause: closedInputPause,+ };+ return response;+ } finally {+ sessionNewInFlight = false;+ }}).onRequest("session/prompt", async (ctx: any) => {const params = ctx.params as { sessionId: string; prompt: readonly unknown[] };const entry = session?.id === params.sessionId ? session : undefined;if (!entry) throw new Error(`Unknown ACP session: ${params.sessionId}`);-- // ACP allows one turn at a time per session. Refuse a concurrent prompt- // rather than overwriting the running turn's controller, which would make- // the live turn uncancellable and let the loser's cleanup clear it.- if (entry.abort) {- throw new Error("A prompt turn is already running for this ACP session");+ if (sessionCloseInFlight) throw new Error(`ACP session is closing: ${params.sessionId}`);+ if (entry.cancelling) throw new Error(`ACP session is cancelling: ${params.sessionId}`);+ await entry.inputPauseRelease?.promise;+ // A prompt response precedes its correlated terminal update. Serialize the+ // next turn behind that lifecycle so it cannot overwrite terminal ownership.+ await entry.pendingTerminal?.task;+ if (session !== entry) throw new Error(`Unknown ACP session: ${params.sessionId}`);+ if (sessionCloseInFlight) throw new Error(`ACP session is closing: ${params.sessionId}`);+ if (entry.cancelling) throw new Error(`ACP session is cancelling: ${params.sessionId}`);+ if (entry.stopFailure) throw new Error(`ACP session stop failed: ${entry.stopFailure}`);+ if (entry.pendingTerminal?.failure) {+ throw new Error(`ACP lifecycle reconciliation failed: ${entry.pendingTerminal.failure}`);}+ if (entry.abort) throw new Error("A prompt turn is already running for this ACP session");+const abort = new AbortController();entry.abort = abort;-+ let resolvePromptTask!: () => void;+ const promptTask = new Promise<void>((resolve) => {+ resolvePromptTask = resolve;+ });+ entry.promptTask = promptTask;+ entry.resolvePromptTask = resolvePromptTask;+ // Allocate the causal turn before the first await, not when an update is+ // delivered. This prevents late producer events becoming the next turn.+ const promptTurnId = entry.producer.beginPrompt();+ let responseBoundaryEmitted = false;try {const { text, images } = promptContent(params.prompt);- // Only this turn's messages may decide its outcome, and compaction can- // rebuild the transcript mid-turn, so record the pre-turn messages- // themselves rather than how many there were.const priorMessages = turnBoundary(await connection.getMessages());+ if (abort.signal.aborted) {+ await entry.producer.drain();+ return { stopReason: "cancelled" satisfies AcpStopReason };+ }await connection.promptAndWait(text, images.length > 0 ? { images } : undefined);- // Autonomous gates continue inside this same prompt turn: the turn is- // only over once the gate loop settles.+ if (abort.signal.aborted) {+ await entry.producer.drain();+ return { stopReason: "cancelled" satisfies AcpStopReason };+ }const status = await connection.waitForHeadlessCompletion();- const meta = autonomousMeta(status);- if (meta) {- await ctx.client- .notify(acp.methods.client.session.update, {- sessionId: params.sessionId,- update: { sessionUpdate: "session_info_update", _meta: meta },- })- .catch(() => undefined);+ if (abort.signal.aborted) {+ await entry.producer.drain();+ return { stopReason: "cancelled" satisfies AcpStopReason };}- // A turn that failed (provider error, auth, no usable model) must not be- // reported as a clean end_turn. Print mode surfaces- // `stopReason: "error"` with its errorMessage; ACP previously dropped- // that and answered end_turn with no updates at all, which reads to a- // client as a successful but empty turn.const failure = await turnFailure(connection, priorMessages);- if (failure && !abort.signal.aborted) {- throw new Error(`prime-agent turn failed: ${failure}`);+ if (abort.signal.aborted) {+ await entry.producer.drain();+ return { stopReason: "cancelled" satisfies AcpStopReason };+ }+ const autonomous = autonomousMeta(status);+ const liveChildren = await connection.getRlmChildSnapshots();+ if (abort.signal.aborted) {+ await entry.producer.drain();+ return { stopReason: "cancelled" satisfies AcpStopReason };+ }+ const outcome = failure ? "error" : "result";+ const observedQuiescence = quiescenceMeta(status, liveChildren);+ // The roster is telemetry at the response cut, not proof of terminality:+ // a child can publish a terminal status before its result reaches the parent.+ // Every turn therefore finalizes through the strong settlement barrier.+ entry.producer.commitResponse(promptTurnId);+ responseBoundaryEmitted = await entry.producer.publish(+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({ terminalQuiescenceExpected: true }),+ },+ promptTurnId,+ "responseBoundary",+ outcome,+ );+ if (!responseBoundaryEmitted) throw new Error("Failed to publish ACP response boundary");+ const completionUpdateEmitted = await entry.producer.publish(+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({ ...(autonomous ? { autonomous } : {}), quiescence: observedQuiescence }),+ },+ promptTurnId,+ "event",+ );+ if (!completionUpdateEmitted) throw new Error("Failed to publish ACP completion update");+ await entry.producer.drain();+ if (!abort.signal.aborted) {+ entry.producer.beginTerminalLifecycle(promptTurnId);+ const pending: AcpPendingTerminal = { promptTurnId, boundary: priorMessages, outcome, abort };+ entry.pendingTerminal = pending;+ finalizePendingTerminal(entry, pending);}- return { stopReason: acpStopReason({ cancelled: abort.signal.aborted, autonomous: status }) };+ if (failure) throw new Error(`prime-agent turn failed: ${failure}`);+ return {+ stopReason: acpStopReason({+ cancelled: abort.signal.aborted && !entry.producer.isResponseCommitted(promptTurnId),+ autonomous: status,+ }),+ };} catch (error) {- // Cancellation is a normal ACP prompt outcome, not a JSON-RPC error.- if (abort.signal.aborted) return { stopReason: "cancelled" satisfies AcpStopReason };+ if (abort.signal.aborted && !entry.producer.isResponseCommitted(promptTurnId)) {+ await entry.producer.drain();+ return { stopReason: "cancelled" satisfies AcpStopReason };+ }+ // Failed prompt/snapshot admission gets one correlated error boundary;+ // it never gets an invented terminal-quiescence update.+ if (!responseBoundaryEmitted) {+ await entry.producer.publish(+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({ terminalQuiescenceExpected: false }),+ },+ promptTurnId,+ "responseBoundary",+ "error",+ );+ }+ await entry.producer.drain();throw error;} finally {- // Only clear our own controller: a later turn must not be cleared by- // an earlier one unwinding.- if (entry.abort === abort) entry.abort = undefined;+ entry.producer.finishPrompt(promptTurnId);+ if (entry.promptTask === promptTask) {+ entry.promptTask = undefined;+ entry.resolvePromptTask = undefined;+ resolvePromptTask();+ }+ if (entry.abort === abort && entry.pendingTerminal?.abort !== abort) entry.abort = undefined;}}).onRequest("session/close", async (ctx: any) => {@@ -377,23 +923,94 @@ export async function runAcpModeWithConnection(// Stop real work, not just local bookkeeping: aborting only the local// controller leaves the agent running with nobody listening, so closing// must abort the connection the same way session/cancel does.+ if (sessionCloseInFlight) throw new Error(`ACP session is already closing: ${params.sessionId}`);+ sessionCloseInFlight = true;+ let finishClose!: () => void;+ sessionCloseTask = new Promise<void>((resolve) => {+ finishClose = resolve;+ });const closing = session;- session = undefined;- closing.unsubscribe?.();- if (closing.abort) {- closing.abort.abort();- await connection.abort().catch(() => undefined);+ try {+ await closing.cancelTask?.catch(() => undefined);+ closing.cancelling = true;+ closing.abort?.abort();+ const pending = closing.pendingTerminal;+ const promptTask = closing.promptTask;+ try {+ const inputPause = await acquireStopInputPause(closing);+ const inputPauseKey = closing.inputPauseKey;+ if (!inputPauseKey) throw new Error("Missing ACP close input-pause key");+ await stopSessionWork(pending, promptTask);+ closing.unsubscribe?.();+ // Keep the backing session fenced until a replacement ACP session is admitted.+ await closing.producer.close();+ closedInputPause = inputPause;+ closedInputPauseKey = inputPauseKey;+ if (closing.inputPause === inputPause) {+ closing.inputPause = undefined;+ closing.inputPauseKey = undefined;+ }+ closing.stopFailure = undefined;+ } catch (error) {+ closing.stopFailure = error instanceof Error ? error.message : String(error);+ throw error;+ }+ if (session === closing) session = undefined;+ return {};+ } finally {+ if (session === closing) closing.cancelling = false;+ finishClose();+ sessionCloseTask = undefined;+ sessionCloseInFlight = false;}- return {};}).onNotification("session/cancel", async (ctx: any) => {const params = ctx.params as { sessionId: string };+ while (sessionCloseInFlight) await sessionCloseTask;// Only cancel the addressed session: aborting unconditionally would kill// whichever turn happens to be running, and leave the real turn's// AbortController unmarked so it reports a wrong stop reason.- if (session?.id !== params.sessionId || !session.abort) return;- session.abort.abort();- await connection.abort().catch(() => undefined);+ if (session?.id !== params.sessionId) return;+ const cancelling = session;+ if (cancelling.cancelling) {+ await cancelling.cancelTask;+ return;+ }+ const abort = cancelling.abort;+ if (!abort && !cancelling.stopFailure && !cancelling.inputPauseRelease) return;+ const pending = abort && cancelling.pendingTerminal?.abort === abort ? cancelling.pendingTerminal : undefined;+ const promptTask = cancelling.promptTask;+ cancelling.cancelling = true;+ const cancelTask = (async () => {+ abort?.abort();+ try {+ const inputPause = await acquireStopInputPause(cancelling);+ await stopSessionWork(pending, promptTask);+ await inputPause.release();+ if (cancelling.inputPause === inputPause) {+ cancelling.inputPause = undefined;+ cancelling.inputPauseKey = undefined;+ }+ if (closedInputPause === inputPause) {+ closedInputPause = undefined;+ closedInputPauseKey = undefined;+ }+ cancelling.inputPauseRelease = undefined;+ cancelling.stopFailure = undefined;+ if (pending && cancelling.pendingTerminal === pending) cancelling.pendingTerminal = undefined;+ if (abort && cancelling.abort === abort) cancelling.abort = undefined;+ } catch (error) {+ cancelling.stopFailure = error instanceof Error ? error.message : String(error);+ throw error;+ }+ })();+ cancelling.cancelTask = cancelTask;+ try {+ await cancelTask;+ } finally {+ if (cancelling.cancelTask === cancelTask) cancelling.cancelTask = undefined;+ cancelling.cancelling = false;+ }}).connect(stream);@@ -403,7 +1020,11 @@ export async function runAcpModeWithConnection(await handle.closed.catch(() => undefined);session?.abort?.abort();session?.unsubscribe?.();+ await session?.inputPause?.release().catch(() => undefined);session = undefined;+ await closedInputPause?.release().catch(() => undefined);+ closedInputPause = undefined;+ closedInputPauseKey = undefined;await connection.dispose().catch(() => undefined);// Only the real stdio entrypoint owns the process; a caller-supplied transport// (tests, embedding) must never have its host exited from under it.diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.tsindex 016a053279..e9d9c8354f 100644--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts@@ -4,6 +4,7 @@ import type { ImageContent, ServiceTier, Transport } from "@earendil-works/pi-aiimport { appendRotatingLog, getAgentLogPath, getDaemonLogPath } from "../../config.js";import type { AgentSessionMessageReceipt, AgentSessionMessageSafetyStatus } from "../../core/agent-messages.js";import type { AgentSessionEvent } from "../../core/agent-session.js";+import type { AgentSessionRuntimeConfig } from "../../core/agent-session-config.js";import type { AgentAutonomousStatus } from "../../core/autonomous.js";import type { BashResult } from "../../core/bash-executor.js";import type { CompactionResult } from "../../core/compaction/index.js";@@ -51,6 +52,7 @@ import type {AgentConnectionExecuteBashOptions,AgentConnectionExtensionUiResponse,AgentConnectionForkOptions,+ AgentConnectionHeadlessCompletionOptions,AgentConnectionHeartbeat,AgentConnectionModel,AgentConnectionModelCatalog,@@ -65,11 +67,13 @@ import type {AgentConnectionQueueMode,AgentConnectionQueueState,AgentConnectionResourceSnapshot,+ AgentConnectionRlmChildAgentSnapshot,AgentConnectionSavedSessionInfo,AgentConnectionSavedSessionScope,AgentConnectionScopedModel,AgentConnectionSessionContext,AgentConnectionSessionHeader,+ AgentConnectionSessionInputPause,AgentConnectionSessionListCallbacks,AgentConnectionSessionTreeFlatNode,AgentConnectionSessionTreeNode,@@ -170,6 +174,8 @@ export interface DaemonAgentConnectionOptions {supportsExtensionUi?: boolean;/** Dispose the connection by stopping its hidden worker instead of detaching. */ownedSession?: boolean;+ /** Fresh runtime context used only if the owned worker must be relaunched. */+ ownedSessionRecoveryConfig?: AgentSessionRuntimeConfig;/** Require the target worker to have been created with telemetry disabled. */telemetryDisabled?: true;}@@ -210,10 +216,13 @@ export class DaemonAgentConnection implements AgentConnection {private readonly unsubscribeDaemonMessages: () => void;private readonly unsubscribeDaemonClose: () => void;private readonly clientId = `daemon-agent-connection:${randomUUID()}`;+ private readonly sessionInputPauses = new Map<string, Promise<AgentConnectionSessionInputPause>>();+ private sessionInputPauseGeneration = 0;private ownedSessionPromotionTail = Promise.resolve();private lastEventCursor: DaemonEventCursor | undefined;private readonly retiredEventGenerations = new Set<string>();private lastEventSequence: number | undefined;+ private childRosterSequence: number | undefined;private latestSnapshot: AgentConnectionSnapshot | undefined;private latestSnapshotIsFresh = false;private attachedSessionId: string | undefined;@@ -256,10 +265,21 @@ export class DaemonAgentConnection implements AgentConnection {});this.captureDaemonLogPath();this.unsubscribeDaemonClose = this.client.onClose((error) => {+ const invalidatedInputPause = this.sessionInputPauses.size > 0;+ this.sessionInputPauses.clear();+ this.sessionInputPauseGeneration++;this.rejectSnapshotAssemblies(error);if (this.disposed || this.terminalCloseEmitted) {return;}+ if (invalidatedInputPause) {+ this.terminalCloseEmitted = true;+ void this.emit({+ type: "closed",+ error: "Daemon connection closed while session input was paused; the fence was invalidated.",+ });+ return;+ }const closeReason = getDaemonSocketCloseReason(error);if (closeReason === "shutdown") {this.terminalCloseEmitted = true;@@ -312,6 +332,11 @@ export class DaemonAgentConnection implements AgentConnection {],env: this.options.sendClientEnv ? collectDaemonClientEnv() : undefined,launchEnv: this.options.ownedSession ? collectDaemonLaunchEnv() : undefined,+ ...(this.options.ownedSession &&+ this.options.ownedSessionRecoveryConfig &&+ this.client.supportsServerCapability("owned_session_recovery_context")+ ? { recoveryConfig: this.options.ownedSessionRecoveryConfig }+ : {}),telemetryDisabled: this.options.telemetryDisabled,resumeCursor:this.lastEventCursor === undefined@@ -339,6 +364,7 @@ export class DaemonAgentConnection implements AgentConnection {? await this.waitForSnapshot(result.snapshotStream.id): result.snapshot;this.latestSnapshot = mapDaemonSessionSnapshot(snapshot, result.replay);+ if (Array.isArray(snapshot.children)) this.childRosterSequence = snapshot.lastEventSequence;if (this.lastEventSequence !== undefined) {this.latestSnapshot.lastEventSequence = this.lastEventSequence;}@@ -396,10 +422,6 @@ export class DaemonAgentConnection implements AgentConnection {activeSessionId: this.activeSessionId,}),]);- // Children only travel in the attach snapshot; a session event arriving- // before the first read marks the cache stale, but the attach-time child- // roster is still the best seed available (live rlm_child_update events- // overwrite each entry anyway).const children = this.latestSnapshot?.children;const streamingMessage = this.latestSnapshot?.streamingMessage;this.latestSnapshot = {@@ -422,6 +444,27 @@ export class DaemonAgentConnection implements AgentConnection {return this.latestSnapshot;}+ async getRlmChildSnapshots(): Promise<AgentConnectionRlmChildAgentSnapshot[]> {+ if (!this.client.supportsServerCapability("authoritative_child_roster")) {+ throw new DaemonCapabilityUnavailableError("get_rlm_children", "authoritative_child_roster");+ }+ const data = await this.requestData<{+ children: AgentConnectionRlmChildAgentSnapshot[];+ eventSequence: number;+ }>({ type: "get_rlm_children", activeSessionId: this.activeSessionId });+ if (!Array.isArray(data.children) || !Number.isInteger(data.eventSequence)) {+ throw new Error("Daemon returned an invalid child roster");+ }+ if ((this.childRosterSequence ?? -1) > data.eventSequence) {+ return this.latestSnapshot?.children ?? data.children;+ }+ this.childRosterSequence = data.eventSequence;+ if (this.latestSnapshot) {+ this.latestSnapshot = { ...this.latestSnapshot, children: data.children };+ }+ return data.children;+ }+async getMessages(): Promise<AgentMessage[]> {if (this.latestSnapshotIsFresh && this.latestSnapshot) {return this.latestSnapshot.messages;@@ -570,6 +613,60 @@ export class DaemonAgentConnection implements AgentConnection {}}+ async acquireSessionInputPause(leaseKey: string): Promise<AgentConnectionSessionInputPause> {+ if (this.terminalCloseEmitted) throw new Error("Daemon connection is closed; cannot acquire an input pause.");+ const activeSessionId = this.activeSessionId;+ const generation = this.sessionInputPauseGeneration;+ const acquisitionKey = JSON.stringify([activeSessionId, leaseKey]);+ const existing = this.sessionInputPauses.get(acquisitionKey);+ if (existing) return existing;+ const acquisition = (async (): Promise<AgentConnectionSessionInputPause> => {+ const { pauseId } = await this.requestData<{ pauseId: string }>({+ type: "acquire_session_input_pause",+ activeSessionId,+ leaseKey,+ });+ if (generation !== this.sessionInputPauseGeneration || this.terminalCloseEmitted) {+ try {+ await this.requestData({+ type: "release_session_input_pause",+ activeSessionId,+ pauseId,+ });+ } catch {+ this.client.close();+ }+ throw new Error("Session input pause acquisition was invalidated by a daemon reconnect.");+ }+ let released = false;+ return {+ release: async () => {+ if (released) return;+ if (generation !== this.sessionInputPauseGeneration) {+ throw new Error("Session input pause was invalidated by a daemon reconnect.");+ }+ await this.requestData({+ type: "release_session_input_pause",+ activeSessionId,+ pauseId,+ });+ released = true;+ if (this.sessionInputPauses.get(acquisitionKey) === acquisition) {+ this.sessionInputPauses.delete(acquisitionKey);+ }+ },+ };+ })();+ this.sessionInputPauses.set(acquisitionKey, acquisition);+ try {+ return await acquisition;+ } catch (error) {+ if (this.sessionInputPauses.get(acquisitionKey) === acquisition)+ this.sessionInputPauses.delete(acquisitionKey);+ throw error;+ }+ }+async listCronJobs(options: { includeInactive?: boolean } = {}): Promise<AgentCronJob[]> {const data = await this.requestData<{ jobs: AgentCronJob[] }>({type: "cron_list",@@ -928,11 +1025,17 @@ export class DaemonAgentConnection implements AgentConnection {);}- async waitForHeadlessCompletion(): Promise<AgentAutonomousStatus> {+ async waitForHeadlessCompletion(options?: AgentConnectionHeadlessCompletionOptions): Promise<AgentAutonomousStatus> {+ if (options?.waitForRlmQuiescence && !this.client.supportsServerCapability("rlm_quiescence_barrier")) {+ throw new Error(+ "the daemon is running an older build without RLM quiescence barriers; restart the daemon and try again",+ );+ }return this.requestData<AgentAutonomousStatus>({type: "wait_for_headless_completion",activeSessionId: this.activeSessionId,+ ...(options?.waitForRlmQuiescence ? { waitForRlmQuiescence: true } : {}),},DAEMON_LONG_RUNNING_REQUEST_TIMEOUT_MS,);@@ -1488,6 +1591,10 @@ export class DaemonAgentConnection implements AgentConnection {if (message.event.type !== "refine_complete" && message.event.type !== "refine_failed") {this.observeStreamingMessage(message.event);}+ if (message.event.type === "rlm_child_update") {+ this.childRosterSequence = maxEventSequence(this.childRosterSequence, getDaemonMessageSequence(message));+ this.observeRlmChildUpdate(message.event.child);+ }this.latestSnapshotIsFresh = false;await this.emit({ type: "session_event", event: message.event });return;@@ -1512,6 +1619,9 @@ export class DaemonAgentConnection implements AgentConnection {this.attachedSessionId = message.snapshot.state.sessionId;this.attachedSessionFile = message.snapshot.state.sessionFile;this.latestSnapshot = mapDaemonSessionSnapshot(message.snapshot);+ if (Array.isArray(message.snapshot.children)) {+ this.childRosterSequence = message.snapshot.lastEventSequence;+ }if (this.lastEventSequence !== undefined) {this.latestSnapshot.lastEventSequence = this.lastEventSequence;}@@ -1540,6 +1650,7 @@ export class DaemonAgentConnection implements AgentConnection {latestSnapshot.lastEventCursor = this.lastEventCursor;}this.latestSnapshot = latestSnapshot;+ this.childRosterSequence = undefined;this.latestSnapshotIsFresh = true;await this.emit({ type: "session_replaced", state: message.state, messages: message.messages });return;@@ -1829,6 +1940,7 @@ export class DaemonAgentConnection implements AgentConnection {this.attachedSessionId = snapshot.state.sessionId;this.attachedSessionFile = snapshot.state.sessionFile;this.latestSnapshot = mapDaemonSessionSnapshot(snapshot, replay);+ this.childRosterSequence = Array.isArray(snapshot.children) ? snapshot.lastEventSequence : undefined;this.latestSnapshotIsFresh = true;}@@ -1914,6 +2026,19 @@ export class DaemonAgentConnection implements AgentConnection {}}+ private observeRlmChildUpdate(child: AgentConnectionRlmChildAgentSnapshot): void {+ if (!this.latestSnapshot) return;+ const children = this.latestSnapshot.children ?? [];+ const index = children.findIndex((candidate) => candidate.id === child.id);+ const updatedChildren = [...children];+ if (index === -1) {+ updatedChildren.push(child);+ } else {+ updatedChildren[index] = child;+ }+ this.latestSnapshot = { ...this.latestSnapshot, children: updatedChildren };+ }+private observeStreamingMessage(event: AgentSessionEvent): void {if (!this.latestSnapshot) {return;diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.tsindex e8257b3fb1..e30b71e5a1 100644--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts@@ -35,6 +35,7 @@ import type {AgentConnectionExecuteBashOptions,AgentConnectionExtensionUiResponse,AgentConnectionForkOptions,+ AgentConnectionHeadlessCompletionOptions,AgentConnectionHeartbeat,AgentConnectionModel,AgentConnectionModelCatalog,@@ -49,11 +50,13 @@ import type {AgentConnectionQueueMode,AgentConnectionQueueState,AgentConnectionResourceSnapshot,+ AgentConnectionRlmChildAgentSnapshot,AgentConnectionSavedSessionInfo,AgentConnectionSavedSessionScope,AgentConnectionScopedModel,AgentConnectionSessionContext,AgentConnectionSessionHeader,+ AgentConnectionSessionInputPause,AgentConnectionSessionListCallbacks,AgentConnectionSessionTreeNode,AgentConnectionSessionWatcher,@@ -75,6 +78,7 @@ export class InProcessAgentConnection implements AgentConnection {private readonly listeners = new Set<AgentConnectionEventListener>();private readonly beforeSessionInvalidateListeners = new Set<AgentConnectionBeforeSessionInvalidateListener>();private readonly sideQuestionRuns = new Map<string, SideQuestionRun>();+ private readonly sessionInputPauses = new Map<string, AgentConnectionSessionInputPause>();private headlessExtensionOptions: InProcessHeadlessExtensionOptions | undefined;private unsubscribeSessionEvents: (() => void) | undefined;@@ -128,6 +132,10 @@ export class InProcessAgentConnection implements AgentConnection {return createAgentConnectionSnapshot(this.runtimeHost);}+ async getRlmChildSnapshots(): Promise<AgentConnectionRlmChildAgentSnapshot[]> {+ return this.session.getRlmChildSnapshots();+ }+async getMessages(): Promise<AgentMessage[]> {return this.session.state.messages;}@@ -210,6 +218,23 @@ export class InProcessAgentConnection implements AgentConnection {return queue;}+ async acquireSessionInputPause(leaseKey: string): Promise<AgentConnectionSessionInputPause> {+ const existing = this.sessionInputPauses.get(leaseKey);+ if (existing) return existing;+ const pause = this.session.acquireSessionInputPause();+ let released = false;+ const lease: AgentConnectionSessionInputPause = {+ release: async () => {+ if (released) return;+ pause.release();+ released = true;+ if (this.sessionInputPauses.get(leaseKey) === lease) this.sessionInputPauses.delete(leaseKey);+ },+ };+ this.sessionInputPauses.set(leaseKey, lease);+ return lease;+ }+async listCronJobs(_options: { includeInactive?: boolean } = {}): Promise<AgentCronJob[]> {return [];}@@ -391,8 +416,8 @@ export class InProcessAgentConnection implements AgentConnection {await this.session.waitForIdle();}- async waitForHeadlessCompletion(): Promise<AgentAutonomousStatus> {- return waitForHeadlessCompletion(this.session);+ async waitForHeadlessCompletion(options?: AgentConnectionHeadlessCompletionOptions): Promise<AgentAutonomousStatus> {+ return waitForHeadlessCompletion(this.session, options);}async executeBash(command: string, options?: AgentConnectionExecuteBashOptions): Promise<void> {@@ -587,6 +612,8 @@ export class InProcessAgentConnection implements AgentConnection {async dispose(): Promise<void> {this.abortAllSideQuestions();+ await Promise.allSettled([...this.sessionInputPauses.values()].map((pause) => pause.release()));+ this.sessionInputPauses.clear();this.unsubscribeSessionEvents?.();this.unsubscribeSessionEvents = undefined;if (typeof this.runtimeHost.setBeforeSessionInvalidate === "function") {diff --git a/packages/coding-agent/src/modes/agent-connection/snapshot.ts b/packages/coding-agent/src/modes/agent-connection/snapshot.tsindex d772c76d26..3b08cc4cda 100644--- a/packages/coding-agent/src/modes/agent-connection/snapshot.ts+++ b/packages/coding-agent/src/modes/agent-connection/snapshot.ts@@ -74,6 +74,7 @@ export function createAgentConnectionSnapshot(tree: sessionManager.getTree(),leafId: sessionManager.getLeafId(),},+ children: session.getRlmChildSnapshots(),};}diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.tsindex a5e8ea699c..33797100c3 100644--- a/packages/coding-agent/src/modes/agent-connection/types.ts+++ b/packages/coding-agent/src/modes/agent-connection/types.ts@@ -624,12 +624,22 @@ export type AgentConnectionEvent =export type AgentConnectionEventListener = (event: AgentConnectionEvent) => void | Promise<void>;export type AgentConnectionBeforeSessionInvalidateListener = () => void;+export interface AgentConnectionHeadlessCompletionOptions {+ /** Wait for descendant terminal publication and the parent turns it triggers. */+ waitForRlmQuiescence?: boolean;+}++export interface AgentConnectionSessionInputPause {+ release(): Promise<void>;+}+export interface AgentConnection {subscribe(listener: AgentConnectionEventListener): () => void;onBeforeSessionInvalidate(listener: AgentConnectionBeforeSessionInvalidateListener): () => void;getState(): Promise<AgentConnectionState>;getInitialSnapshot(): Promise<AgentConnectionSnapshot>;+ getRlmChildSnapshots(): Promise<AgentConnectionRlmChildAgentSnapshot[]>;getMessages(): Promise<AgentMessage[]>;getSessionHeader(): Promise<AgentConnectionSessionHeader | undefined>;getCommands(): Promise<AgentConnectionSlashCommand[]>;@@ -653,6 +663,7 @@ export interface AgentConnection {): Promise<AgentConnectionQueuedMessageMutationStatus>;clearQueue(): Promise<AgentConnectionQueueState>;abortAndClearQueue(): Promise<AgentConnectionQueueState>;+ acquireSessionInputPause(leaseKey: string): Promise<AgentConnectionSessionInputPause>;listCronJobs(options?: { includeInactive?: boolean }): Promise<AgentCronJob[]>;listHeartbeats(): Promise<AgentConnectionHeartbeat[]>;manageHeartbeat(@@ -690,7 +701,7 @@ export interface AgentConnection {abort(): Promise<void>;cancelRlmChild(childId: string): Promise<boolean>;waitForIdle(): Promise<void>;- waitForHeadlessCompletion(): Promise<AgentAutonomousStatus>;+ waitForHeadlessCompletion(options?: AgentConnectionHeadlessCompletionOptions): Promise<AgentAutonomousStatus>;/*** Run a user-initiated bash command (! / !! prefix). Resolution timing isdiff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 05a7632a25..9e84c54a52 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -276,6 +276,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["get_state","get_connection_state","get_messages",+ "get_rlm_children","get_session_stats","get_context_tree","get_commands",@@ -286,6 +287,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["mutate_queued_message","clear_queue","abort_and_clear_queue",+ "acquire_session_input_pause",+ "release_session_input_pause","cron_list","heartbeats_list","heartbeat_manage",@@ -453,6 +456,10 @@ export class AgentDaemon {private server?: Server;private shuttingDown = false;private readonly updateRestartQueuePauses = new Map<string, { release(): void }>();+ private readonly sessionInputPauses = new Map<+ string,+ { activeSessionId: string; owner: DaemonSocketClient; leaseKey: string; pause: { release(): void } }+ >();private readonly mutationDrain = new MutationDrainLatch();private updateRestart?: {id: symbol;@@ -3338,6 +3345,11 @@ export class AgentDaemon {socket.off("close", cleanup);socket.off("error", cleanup);this.clearClientCatchupRetry(client);+ for (const [pauseId, entry] of this.sessionInputPauses) {+ if (entry.owner !== client) continue;+ entry.pause.release();+ this.sessionInputPauses.delete(pauseId);+ }this.detachClient(client);client.detachInput();this.clients.delete(client);@@ -3941,8 +3953,18 @@ export class AgentDaemon {case "detach": {if (command.activeSessionId) {const state = this.getSessionState(command.activeSessionId);+ for (const [pauseId, entry] of this.sessionInputPauses) {+ if (entry.owner !== client || entry.activeSessionId !== command.activeSessionId) continue;+ entry.pause.release();+ this.sessionInputPauses.delete(pauseId);+ }this.detachClientFromSession(client, state);} else {+ for (const [pauseId, entry] of this.sessionInputPauses) {+ if (entry.owner !== client) continue;+ entry.pause.release();+ this.sessionInputPauses.delete(pauseId);+ }this.detachClient(client);}return success(command.id, "detach");@@ -4386,6 +4408,38 @@ export class AgentDaemon {});}+ case "acquire_session_input_pause": {+ const existing = [...this.sessionInputPauses].find(+ ([, entry]) =>+ entry.owner === client &&+ entry.activeSessionId === command.activeSessionId &&+ entry.leaseKey === command.leaseKey,+ );+ if (existing) {+ return success(command.id, "acquire_session_input_pause", { pauseId: existing[0] });+ }+ const state = this.getSessionState(command.activeSessionId);+ const pauseId = randomUUID();+ this.sessionInputPauses.set(pauseId, {+ activeSessionId: command.activeSessionId,+ owner: client,+ leaseKey: command.leaseKey,+ pause: state.runtime.session.acquireSessionInputPause(),+ });+ return success(command.id, "acquire_session_input_pause", { pauseId });+ }++ case "release_session_input_pause": {+ const entry = this.sessionInputPauses.get(command.pauseId);+ if (!entry) return success(command.id, "release_session_input_pause");+ if (entry.owner !== client || entry.activeSessionId !== command.activeSessionId) {+ throw new Error(`Session input pause is owned by another client: ${command.pauseId}`);+ }+ this.sessionInputPauses.delete(command.pauseId);+ entry.pause.release();+ return success(command.id, "release_session_input_pause");+ }+case "wait_for_idle": {const state = this.getSessionState(command.activeSessionId);await state.runtime.session.waitForIdle();@@ -4397,7 +4451,9 @@ export class AgentDaemon {return success(command.id,"wait_for_headless_completion",- await waitForHeadlessCompletion(state.runtime.session),+ await waitForHeadlessCompletion(state.runtime.session, {+ waitForRlmQuiescence: command.waitForRlmQuiescence,+ }),);}@@ -4425,6 +4481,14 @@ export class AgentDaemon {});}+ case "get_rlm_children": {+ const state = this.getSessionState(command.activeSessionId);+ return success(command.id, "get_rlm_children", {+ children: state.runtime.session.getRlmChildSnapshots(),+ eventSequence: state.lastEventSequence,+ });+ }+case "get_session_stats": {const state = this.getSessionState(command.activeSessionId);const stats: SessionStats = state.runtime.session.getSessionStats();@@ -4932,7 +4996,7 @@ export class AgentDaemon {sequence: state.lastEventSequence,},...(parent ? { parent } : {}),- ...(children.length > 0 ? { children } : {}),+ children,};}diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex b26eb1bdc2..e0f815392c 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -60,8 +60,10 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;// Revision 14 carries the client's monotonic telemetry opt-out on attach and reattach.// Revision 15 adds the mutate_queued_message command and queue_message_mutation capability.// Revision 16 adds the "stopping" workerState and stops reporting disconnected workers as "ready".-export const DAEMON_SCHEMA_REVISION = 16;-export const DAEMON_SCHEMA_ID = "protocol-7-schema-16-1bcb9e7f1a49";+// Revision 17 gates authoritative child rosters and transient owned-session recovery context.+// Revision 18 adds the opt-in RLM quiescence barrier to headless completion.+export const DAEMON_SCHEMA_REVISION = 19;+export const DAEMON_SCHEMA_ID = "protocol-7-schema-19-29b4f87f83e7";export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;export type DaemonProtocolVersion = number;@@ -100,7 +102,11 @@ export type DaemonServerCapability =| "transient_bash"| "session_input_admission"| "prompt_admission_cancellation"- | "queue_message_mutation";+ | "queue_message_mutation"+ | "authoritative_child_roster"+ | "owned_session_recovery_context"+ | "rlm_quiescence_barrier"+ | "session_input_pause";export type DaemonReplayStatus = "complete" | "partial" | "unavailable";@@ -139,6 +145,10 @@ export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability"session_input_admission","prompt_admission_cancellation","queue_message_mutation",+ "authoritative_child_roster",+ "owned_session_recovery_context",+ "rlm_quiescence_barrier",+ "session_input_pause",];export interface DaemonRuntimeIdentity {@@ -158,6 +168,8 @@ export interface DaemonAttachClientMetadata {resumeCursor?: DaemonResumeCursor;/** Opt-out-only policy. A telemetry-enabled worker must reject this attach. */telemetryDisabled?: true;+ /** Fresh owner-supplied runtime context for recovering a client-owned worker. Never persisted. */+ recoveryConfig?: AgentSessionRuntimeConfig;}/**@@ -501,11 +513,17 @@ export type DaemonCommand =| { id?: string; type: "cancel_rlm_child"; activeSessionId: string; childId: string }| { id?: string; type: "delete_rlm_subagent"; activeSessionId: string; childId: string }| { id?: string; type: "wait_for_idle"; activeSessionId: string }- | { id?: string; type: "wait_for_headless_completion"; activeSessionId: string }+ | {+ id?: string;+ type: "wait_for_headless_completion";+ activeSessionId: string;+ waitForRlmQuiescence?: boolean;+ }| { id?: string; type: "get_session_header"; activeSessionId: string }| { id?: string; type: "get_state"; activeSessionId: string }| { id?: string; type: "get_connection_state"; activeSessionId: string }| { id?: string; type: "get_messages"; activeSessionId: string }+ | { id?: string; type: "get_rlm_children"; activeSessionId: string }| { id?: string; type: "get_session_stats"; activeSessionId: string }| { id?: string; type: "get_context_tree"; activeSessionId: string }| { id?: string; type: "get_commands"; activeSessionId: string }@@ -524,6 +542,8 @@ export type DaemonCommand =}| { id?: string; type: "clear_queue"; activeSessionId: string }| { id?: string; type: "abort_and_clear_queue"; activeSessionId: string }+ | { id?: string; type: "acquire_session_input_pause"; activeSessionId: string; leaseKey: string }+ | { id?: string; type: "release_session_input_pause"; activeSessionId: string; pauseId: string }| { id?: string; type: "cron_list"; activeSessionId?: string; includeInactive?: boolean }| { id?: string; type: "heartbeats_list"; activeSessionId?: string }| {@@ -649,6 +669,26 @@ const DELETE_RLM_SUBAGENT_COMMAND = {} as const;const FLAT_SESSION_TREE_COMMAND = { minProtocol: 7 } as const;const TELEMETRY_POLICY_COMMAND = { minProtocol: 7, minSchemaRevision: 14 } as const;+const AUTHORITATIVE_CHILD_ROSTER_COMMAND = {+ minProtocol: 7,+ minSchemaRevision: 17,+ capability: "authoritative_child_roster",+} as const;+const OWNED_SESSION_RECOVERY_CONTEXT = {+ minProtocol: 7,+ minSchemaRevision: 17,+ capability: "owned_session_recovery_context",+} as const;+const RLM_QUIESCENCE_BARRIER_COMMAND = {+ minProtocol: 7,+ minSchemaRevision: 18,+ capability: "rlm_quiescence_barrier",+} as const;+const SESSION_INPUT_PAUSE_COMMAND = {+ minProtocol: 7,+ minSchemaRevision: 19,+ capability: "session_input_pause",+} as const;export const DAEMON_COMMAND_COMPATIBILITY = {ack_result: LEGACY_DAEMON_COMMAND,@@ -689,6 +729,7 @@ export const DAEMON_COMMAND_COMPATIBILITY = {get_state: LEGACY_DAEMON_COMMAND,get_connection_state: LEGACY_DAEMON_COMMAND,get_messages: LEGACY_DAEMON_COMMAND,+ get_rlm_children: AUTHORITATIVE_CHILD_ROSTER_COMMAND,get_session_stats: LEGACY_DAEMON_COMMAND,get_context_tree: LEGACY_DAEMON_COMMAND,get_commands: LEGACY_DAEMON_COMMAND,@@ -699,6 +740,8 @@ export const DAEMON_COMMAND_COMPATIBILITY = {mutate_queued_message: { minProtocol: 7, minSchemaRevision: 15, capability: "queue_message_mutation" },clear_queue: LEGACY_DAEMON_COMMAND,abort_and_clear_queue: LEGACY_DAEMON_COMMAND,+ acquire_session_input_pause: SESSION_INPUT_PAUSE_COMMAND,+ release_session_input_pause: SESSION_INPUT_PAUSE_COMMAND,cron_list: LEGACY_DAEMON_COMMAND,heartbeats_list: { minProtocol: 7, capability: "heartbeat_catalog" },heartbeat_manage: { minProtocol: 7, capability: "heartbeat_management" },@@ -752,17 +795,21 @@ export const DAEMON_COMMAND_COMPATIBILITY = {} as const satisfies Record<DaemonCommandName, DaemonCommandCompatibility>;export function getDaemonCommandCompatibilities(command: DaemonCommand): readonly DaemonCommandCompatibility[] {- const compatibility = DAEMON_COMMAND_COMPATIBILITY[command.type];+ const requirements: DaemonCommandCompatibility[] = [];+ if ((command.type === "attach" || command.type === "reattach") && command.recoveryConfig !== undefined) {+ requirements.push(OWNED_SESSION_RECOVERY_CONTEXT);+ }const carriesTelemetryPolicy =((command.type === "attach" || command.type === "reattach") && command.telemetryDisabled !== undefined) ||(command.type === "create" && command.config?.telemetryDisabled !== undefined);- if (carriesTelemetryPolicy) {- return [TELEMETRY_POLICY_COMMAND, compatibility];- }+ if (carriesTelemetryPolicy) requirements.push(TELEMETRY_POLICY_COMMAND);if ((command.type === "prompt" || command.type === "prompt_and_wait") && command.admissionId !== undefined) {- return [PROMPT_ADMISSION_CANCELLATION_COMMAND, compatibility];+ requirements.push(PROMPT_ADMISSION_CANCELLATION_COMMAND);+ }+ if (command.type === "wait_for_headless_completion" && command.waitForRlmQuiescence === true) {+ requirements.push(RLM_QUIESCENCE_BARRIER_COMMAND);}- return [compatibility];+ return [...requirements, DAEMON_COMMAND_COMPATIBILITY[command.type]];}export type DaemonResponse =@@ -1040,6 +1087,7 @@ const READ_ONLY_DAEMON_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set(["get_state","get_connection_state","get_messages",+ "get_rlm_children","get_session_stats","get_context_tree","get_commands",diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 6d1853e1a7..5fa5f14376 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -22,7 +22,12 @@ import {formatAgentSessionNameUnavailable,sessionNameReservationKey,} from "../../core/agent-messages.js";-import { type AgentSessionRuntimeConfig, mergeAgentSessionRuntimeConfig } from "../../core/agent-session-config.js";+import {+ type AgentSessionRuntimeConfig,+ type DurableAgentSessionRuntimeConfig,+ durableAgentSessionRuntimeConfig,+ mergeAgentSessionRuntimeConfig,+} from "../../core/agent-session-config.js";import {type AgentCronJob,AgentCronJobStore,@@ -116,6 +121,8 @@ import {type DaemonWorkerDescriptor,type DaemonWorkerFrameHeader,type DaemonWorkerLifecycle,+ durableDaemonCreateCommand,+ durableDaemonWorkerDescriptor,SESSION_LEASE_OWNER_ID_ENV,SESSION_LEASES_ENABLED_ENV,} from "./daemon-worker-protocol.js";@@ -131,6 +138,7 @@ type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;const structuredLog = getLogger("coding-agent.daemon-supervisor");const WORKER_CONNECT_TIMEOUT_MS = 30_000;const WORKER_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000;+const INPUT_PAUSE_CLEANUP_TIMEOUT_MS = 5_000;const UPDATE_RESTART_MUTATION_DRAIN_TIMEOUT_MS = 80_000;const UPDATE_RESTART_WORKER_REQUEST_TIMEOUT_MS = 90_000;// The whole pre-commit prepare (drain + worker fencing) must finish inside the@@ -195,6 +203,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["get_state","get_connection_state","get_messages",+ "get_rlm_children","get_session_stats","get_context_tree","get_commands",@@ -205,6 +214,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["mutate_queued_message","clear_queue","abort_and_clear_queue",+ "acquire_session_input_pause",+ "release_session_input_pause","cron_list","heartbeats_list","heartbeat_manage",@@ -272,6 +283,7 @@ interface ResidentWorker {intentionalStop: boolean;stopRevision: number;launchEnv?: Record<string, string>;+ transientCreateCommand?: DaemonCreateCommand;stopFinalization?: Promise<void>;ownerCleanupTimer?: ReturnType<typeof setTimeout>;promotedOwnerClientId?: string;@@ -305,7 +317,7 @@ interface DaemonSupervisorOptions {interface PersistedSupervisorConfig {version: 1;socketPath: string;- defaultSessionConfig: AgentSessionRuntimeConfig;+ defaultSessionConfig: DurableAgentSessionRuntimeConfig;}interface WorkerMatch {@@ -331,6 +343,16 @@ interface SupervisorPromptAdmission {workerActiveSessionId?: string;}+interface SupervisorSessionInputPause {+ owner: DaemonSocketClient;+ worker: ResidentWorker;+ activeSessionId: string;+ requestedActiveSessionId: string;+ leaseKey: string;+ pauseId: string;+ releaseTask?: Promise<DaemonResponse>;+}+function throwIfAdmissionCancelled(admission: SupervisorPromptAdmission | undefined): void {if (admission?.status === "cancelled") throw new PromptAdmissionCancelledError();}@@ -425,7 +447,7 @@ function isDaemonWorkerDescriptor(value: unknown, socketPath: string): value is}const descriptor = value as Partial<DaemonWorkerDescriptor>;return (- descriptor.version === 1 &&+ (descriptor.version === 1 || descriptor.version === 2) &&typeof descriptor.supervisorSocketPath === "string" &&normalizeSocketPath(descriptor.supervisorSocketPath) === socketPath &&typeof descriptor.workerId === "string" &&@@ -598,12 +620,16 @@ export class DaemonSupervisor {private updateRestartPhase?: "draining" | "fencing" | "prepared";private readonly mutationDrain = new MutationDrainLatch();private readonly clients = new Set<DaemonSocketClient>();+ private readonly connectionIds = new WeakMap<DaemonSocketClient, string>();+ private readonly sessionInputPauseEpochs = new WeakMap<DaemonSocketClient, number>();+ private readonly detachingInputPauseSessions = new WeakMap<DaemonSocketClient, Set<string>>();private readonly protocolClientIds = new WeakMap<DaemonSocketClient, string>();private readonly workers = new Map<string, ResidentWorker>();private workerStopCounts?: Map<ResidentWorker, number>;private readonly openingWorkers = new Map<string, Promise<ResidentWorker>>();/** Public admission ids are scoped to the socket that registered them. */private readonly promptAdmissions = new Map<DaemonSocketClient, Map<string, SupervisorPromptAdmission>>();+ private readonly sessionInputPauses = new Map<string, SupervisorSessionInputPause>();private readonly signalCleanupHandlers: Array<() => void> = [];private readonly descriptorDir: string;private readonly generation = randomUUID();@@ -637,7 +663,10 @@ export class DaemonSupervisor {}this.descriptorDir = options.descriptorDir ?? defaultWorkerDescriptorDir(agentDir, socketPath);this.supervisorConfigPath = join(this.descriptorDir, SUPERVISOR_CONFIG_FILE_NAME);- this.defaultSessionConfig = this.loadPersistedSupervisorConfig() ?? options.defaultSessionConfig;+ this.defaultSessionConfig = mergeAgentSessionRuntimeConfig(+ options.defaultSessionConfig,+ this.loadPersistedSupervisorConfig(),+ );this.snapshotCacheRoot = join(this.descriptorDir, "snapshot-cache", this.generation);this.catalog = new DaemonCatalogClient((message) => this.log(message));this.settingsManager = SettingsManager.create(process.cwd(), this.defaultSessionConfig.agentDir ?? agentDir);@@ -940,17 +969,20 @@ export class DaemonSupervisor {descriptor.lifecycle = "recovering";descriptor.recoveryJournalPath ??= join(this.descriptorDir, `${descriptor.workerId}.recovery.jsonl`);descriptor.orphanProcessJournalPath ??= join(this.descriptorDir, `${descriptor.workerId}.orphans.jsonl`);- this.workers.set(descriptor.workerId, {- descriptor,+ const durableDescriptor = durableDaemonWorkerDescriptor(descriptor);+ const worker: ResidentWorker = {+ descriptor: durableDescriptor,descriptorPath: path,summaries: new Map(),snapshotCache: new Map(),transcriptCaches: new Map(),snapshotGenerations: new Map(),snapshotLoads: new Map(),- intentionalStop: descriptor.stopRequestedAt !== undefined,+ intentionalStop: durableDescriptor.stopRequestedAt !== undefined,stopRevision: 0,- });+ };+ this.persistWorker(worker);+ this.workers.set(durableDescriptor.workerId, worker);} catch (error) {this.log(`Ignoring invalid worker descriptor ${path}: ${String(error)}`);}@@ -972,7 +1004,7 @@ export class DaemonSupervisor {) {return undefined;}- return parsed.defaultSessionConfig;+ return durableAgentSessionRuntimeConfig(parsed.defaultSessionConfig);} catch {return undefined;}@@ -982,7 +1014,7 @@ export class DaemonSupervisor {const persisted: PersistedSupervisorConfig = {version: 1,socketPath: this.socketPath,- defaultSessionConfig: this.defaultSessionConfig,+ defaultSessionConfig: durableAgentSessionRuntimeConfig(this.defaultSessionConfig),};const tempPath = `${this.supervisorConfigPath}.${process.pid}.tmp`;writeFileSync(tempPath, `${JSON.stringify(persisted, null, 2)}\n`, { mode: 0o600 });@@ -998,8 +1030,9 @@ export class DaemonSupervisor {private persistWorker(worker: ResidentWorker): void {worker.descriptor.updatedAt = new Date().toISOString();+ const persisted = durableDaemonWorkerDescriptor(worker.descriptor);const tempPath = `${worker.descriptorPath}.${process.pid}.tmp`;- writeFileSync(tempPath, `${JSON.stringify(worker.descriptor, null, 2)}\n`, { mode: 0o600 });+ writeFileSync(tempPath, `${JSON.stringify(persisted, null, 2)}\n`, { mode: 0o600 });chmodSync(tempPath, 0o600);renameSync(tempPath, worker.descriptorPath);}@@ -1029,6 +1062,9 @@ export class DaemonSupervisor {supportsExtensionUi: false,capabilities: new Set(DAEMON_DEFAULT_CLIENT_CAPABILITIES),};+ this.connectionIds.set(client, client.id);+ this.sessionInputPauseEpochs.set(client, 0);+ this.detachingInputPauseSessions.set(client, new Set());this.clients.add(client);void this.ready.then(() => {@@ -1062,6 +1098,11 @@ export class DaemonSupervisor {}cleaned = true;client.detachInput();+ this.sessionInputPauseEpochs.set(client, (this.sessionInputPauseEpochs.get(client) ?? 0) + 1);+ const ownerClientId = this.protocolClientId(client);+ void this.releaseClientSessionInputPauses(client, undefined, true).catch((error: unknown) =>+ this.log(`Failed to release input pauses for disconnected client ${ownerClientId}: ${String(error)}`),+ );this.clients.delete(client);this.cancelWaitingPromptAdmissionsForClient(client);for (const activeSessionId of [...client.attachedActiveSessionIds]) {@@ -1096,6 +1137,72 @@ export class DaemonSupervisor {return this.protocolClientIds.get(client) ?? client.id;}+ private async releaseClientSessionInputPauses(+ owner: DaemonSocketClient,+ activeSessionId?: string,+ forceCleanupOnFailure = false,+ ): Promise<void> {+ const entries = [...this.sessionInputPauses.values()].filter(+ (entry) =>+ entry.owner === owner &&+ (activeSessionId === undefined ||+ entry.activeSessionId === activeSessionId ||+ entry.requestedActiveSessionId === activeSessionId),+ );+ await Promise.all(+ entries.map(async (entry) => {+ if (this.workers.get(entry.worker.descriptor.workerId) !== entry.worker || !entry.worker.client) {+ if (this.sessionInputPauses.get(entry.pauseId) === entry) this.sessionInputPauses.delete(entry.pauseId);+ return;+ }+ try {+ const response = await this.forwardToWorker(+ entry.worker,+ {+ id: randomUUID(),+ type: "release_session_input_pause",+ activeSessionId: entry.activeSessionId,+ pauseId: entry.pauseId,+ },+ INPUT_PAUSE_CLEANUP_TIMEOUT_MS,+ );+ if (!response.success) throw new Error(response.error);+ if (this.sessionInputPauses.get(entry.pauseId) === entry) this.sessionInputPauses.delete(entry.pauseId);+ } catch (error) {+ if (forceCleanupOnFailure) {+ const workerClient = entry.worker.client;+ if (workerClient) {+ workerClient.close();+ await this.handleWorkerClose(+ entry.worker,+ workerClient,+ error instanceof Error ? error : new Error(String(error)),+ );+ } else {+ this.invalidateWorkerSessionInputPauses(+ entry.worker,+ "Session worker became unavailable while releasing an input pause",+ );+ }+ }+ throw error;+ }+ }),+ );+ }++ private invalidateWorkerSessionInputPauses(worker: ResidentWorker, reason: string): void {+ const owners = new Set<DaemonSocketClient>();+ for (const [pauseId, entry] of this.sessionInputPauses) {+ if (entry.worker !== worker) continue;+ this.sessionInputPauses.delete(pauseId);+ owners.add(entry.owner);+ }+ for (const owner of owners) {+ owner.socket.destroy(new Error(reason));+ }+ }+private scheduleOwnedWorkerCleanupForClient(clientId: string): void {if ([...this.clients].some((client) => this.protocolClientId(client) === clientId)) {return;@@ -1488,6 +1595,10 @@ export class DaemonSupervisor {const target = await this.findWorkerForClient(client, command.targetActiveSessionId);const targetActiveSessionId = target.summary.activeSessionId ?? target.summary.id;if (targetActiveSessionId === command.activeSessionId) {+ const detachingSessions = this.detachingInputPauseSessions?.get(client);+ detachingSessions?.delete(command.activeSessionId);+ detachingSessions?.delete(command.targetActiveSessionId);+ detachingSessions?.delete(targetActiveSessionId);return success(command.id, command.type, { cancelled: false });}const targetWasAttached = client.attachedActiveSessionIds.has(targetActiveSessionId);@@ -1500,6 +1611,10 @@ export class DaemonSupervisor {type: "attach",activeSessionId: targetActiveSessionId,});+ const detachingSessions = this.detachingInputPauseSessions?.get(client);+ detachingSessions?.delete(command.activeSessionId);+ detachingSessions?.delete(command.targetActiveSessionId);+ detachingSessions?.delete(targetActiveSessionId);if (client.capabilities.has("chunked_snapshot")) {const transcript =attached.transcript ?? this.getOrCreateTranscriptCache(attached.worker, attached.result);@@ -1535,9 +1650,105 @@ export class DaemonSupervisor {throw error;}}- case "detach":+ case "acquire_session_input_pause": {+ const detachingSessions = this.detachingInputPauseSessions.get(client);+ if (detachingSessions?.has(command.activeSessionId)) {+ throw new Error(`Session is detaching: ${command.activeSessionId}`);+ }+ const match = await this.findWorkerForClient(client, command.activeSessionId);+ const activeSessionId = match.summary.activeSessionId ?? match.summary.id;+ if (detachingSessions?.has(command.activeSessionId) || detachingSessions?.has(activeSessionId)) {+ throw new Error(`Session is detaching: ${command.activeSessionId}`);+ }+ const ownerClientId = this.protocolClientId(client);+ const connectionId = this.connectionIds.get(client);+ if (!connectionId) throw new Error("Daemon client connection identity is unavailable");+ const acquisitionEpoch = this.sessionInputPauseEpochs.get(client) ?? 0;+ const existing = [...this.sessionInputPauses.values()].find(+ (entry) =>+ entry.owner === client &&+ entry.worker === match.worker &&+ entry.activeSessionId === activeSessionId &&+ entry.leaseKey === command.leaseKey &&+ !entry.releaseTask,+ );+ if (existing) {+ return success(command.id, command.type, { pauseId: existing.pauseId });+ }+ const response = await this.forwardToWorker(match.worker, {+ ...command,+ activeSessionId,+ leaseKey: JSON.stringify([connectionId, ownerClientId, command.leaseKey]),+ });+ if (!response.success) return response;+ const pauseId = (response.data as { pauseId?: unknown } | undefined)?.pauseId;+ if (typeof pauseId !== "string") throw new Error("Worker returned an invalid session input pause id");+ if (!this.clients.has(client) || (this.sessionInputPauseEpochs.get(client) ?? 0) !== acquisitionEpoch) {+ try {+ const release = await this.forwardToWorker(match.worker, {+ id: randomUUID(),+ type: "release_session_input_pause",+ activeSessionId,+ pauseId,+ });+ if (!release.success) throw new Error(release.error);+ } catch (error) {+ match.worker.client?.close();+ throw error;+ }+ throw new Error("Session input pause acquisition was invalidated before completion");+ }+ this.sessionInputPauses.set(pauseId, {+ owner: client,+ worker: match.worker,+ activeSessionId,+ requestedActiveSessionId: command.activeSessionId,+ leaseKey: command.leaseKey,+ pauseId,+ });+ return response;+ }+ case "release_session_input_pause": {+ const entry = this.sessionInputPauses.get(command.pauseId);+ if (!entry) return success(command.id, command.type);+ if (entry.owner !== client) {+ throw new Error(`Session input pause is owned by another client: ${command.pauseId}`);+ }+ if (+ command.activeSessionId !== entry.activeSessionId &&+ command.activeSessionId !== entry.requestedActiveSessionId+ ) {+ throw new Error(`Session input pause belongs to another session: ${command.pauseId}`);+ }+ const releaseTask =+ entry.releaseTask ??+ this.forwardToWorker(entry.worker, {+ ...command,+ activeSessionId: entry.activeSessionId,+ });+ entry.releaseTask = releaseTask;+ try {+ const response = await releaseTask;+ if (response.success && this.sessionInputPauses.get(command.pauseId) === entry) {+ this.sessionInputPauses.delete(command.pauseId);+ }+ return response;+ } finally {+ if (this.sessionInputPauses.get(command.pauseId) === entry && entry.releaseTask === releaseTask) {+ entry.releaseTask = undefined;+ }+ }+ }+ case "detach": {+ const detachingSessions = this.detachingInputPauseSessions.get(client) ?? new Set<string>();+ this.detachingInputPauseSessions.set(client, detachingSessions);+ if (command.activeSessionId) detachingSessions.add(command.activeSessionId);+ else for (const activeSessionId of client.attachedActiveSessionIds) detachingSessions.add(activeSessionId);+ this.sessionInputPauseEpochs.set(client, (this.sessionInputPauseEpochs.get(client) ?? 0) + 1);this.detachClient(client, command.activeSessionId);+ await this.releaseClientSessionInputPauses(client, command.activeSessionId, true);return success(command.id, "detach");+ }case "complete_owned_session": {const match = await this.findWorkerForClient(client, command.activeSessionId);if (match.worker.descriptor.ownerClientId !== this.protocolClientId(client)) {@@ -1820,7 +2031,7 @@ export class DaemonSupervisor {sessionPath = await this.catalog.resolve(command.targetActiveSessionId,cwd,- source?.worker.descriptor.createCommand.config?.sessionDir ?? this.defaultSessionConfig.sessionDir,+ source?.worker.descriptor.sessionDir ?? this.defaultSessionConfig.sessionDir,);} catch (catalogError) {// Preserve selector ambiguity so a2a senders can distinguish it from@@ -2030,7 +2241,10 @@ export class DaemonSupervisor {const ownerClientId = command.lifecycle === "client_owned" ? clientId : undefined;if (command.sessionPath) {const activeMatches = this.matchWorkers(command.sessionPath);- if (activeMatches.length === 1 && !(await this.reclaimStaleWorkerRegistration(activeMatches[0]!.worker))) {+ if (+ activeMatches.length === 1 &&+ !(await this.reclaimStaleWorkerRegistration(activeMatches[0]!.worker, command.launchEnv !== undefined))+ ) {return this.reuseWorkerForCreate(activeMatches[0]!.worker, ownerClientId, command.sessionPath);}if (activeMatches.length > 1) {@@ -2042,8 +2256,8 @@ export class DaemonSupervisor {: await this.catalog.resolve(command.sessionPath, config.cwd ?? process.cwd(), config.sessionDir);createCommand = { ...createCommand, sessionPath };const existing = this.findWorkerBySessionFile(sessionPath);- if (existing && !(await this.reclaimStaleWorkerRegistration(existing.worker))) {- return this.reuseWorkerForCreate(existing.worker, ownerClientId, sessionPath);+ if (existing && !(await this.reclaimStaleWorkerRegistration(existing, command.launchEnv !== undefined))) {+ return this.reuseWorkerForCreate(existing, ownerClientId, sessionPath);}}const key = createCommand.sessionPath@@ -2085,6 +2299,11 @@ export class DaemonSupervisor {ownerClientId: string | undefined,sessionPath: string,): ResidentWorker {+ if (worker.descriptor.lifecycle === "failed") {+ throw new Error(+ `Session "${sessionPath}" is registered to a failed worker that could not be safely reclaimed`,+ );+ }if (worker.descriptor.ownerClientId === ownerClientId) {return worker;}@@ -2098,12 +2317,30 @@ export class DaemonSupervisor {* saved transcript forever, so complete the interrupted stop and let the* caller launch a fresh worker for the saved session.*/- private async reclaimStaleWorkerRegistration(worker: ResidentWorker): Promise<boolean> {+ private async reclaimStaleWorkerRegistration(worker: ResidentWorker, freshCreate = false): Promise<boolean> {if (worker.client !== undefined || worker.recovery !== undefined) {return false;}if (worker.descriptor.stopRequestedAt === undefined) {- return false;+ if (worker.descriptor.lifecycle !== "failed" || worker.descriptor.ownerClientId) {+ return false;+ }+ const identity = this.processIdentity(worker.descriptor.pid, worker.descriptor.processStartId);+ if (identity === "current") {+ if (!freshCreate || !worker.descriptor.processStartId) return false;+ await this.stopWorker(worker, true, true);+ return true;+ }+ if (identity !== "gone" && identity !== "replaced") {+ return false;+ }+ worker.intentionalStop = true;+ await this.recoverUncertainWorkerOperations(worker, false);+ this.invalidateWorkerSessionInputPauses(worker, "Session worker stopped while input was paused");+ this.workers.delete(worker.descriptor.workerId);+ this.deleteWorkerDescriptor(worker);+ await this.syncAgentPeers().catch(() => undefined);+ return true;}// Fail fast before waiting on anything: only a confirmed-dead process is// reclaimable. A live, unknown, or still-stopping worker is left alone@@ -2153,6 +2390,7 @@ export class DaemonSupervisor {worker.ownerCleanupTimer = undefined;}worker.launchEnv = undefined;+ worker.transientCreateCommand = undefined;await this.syncAgentPeers().catch((error) => this.log(`Could not synchronize agent peers: ${String(error)}`));}@@ -2166,8 +2404,7 @@ export class DaemonSupervisor {throw new Error(`Session worker ${existing.descriptor.workerId} recovery was cancelled`);}const recoveryStopRevision = existing?.stopRevision;- const launchEnv =- ownerClientId || existing?.descriptor.ownerClientId ? (command.launchEnv ?? existing?.launchEnv) : undefined;+ const launchEnv = command.launchEnv ?? existing?.launchEnv;const createCommand: DaemonCreateCommand = {...withoutSupervisorCreateFields(command),config: mergeAgentSessionRuntimeConfig(this.defaultSessionConfig, command.config),@@ -2236,7 +2473,7 @@ export class DaemonSupervisor {await this.assertRecoveryAllowed();const descriptor: DaemonWorkerDescriptor = {- version: 1,+ version: 2,workerId,pid: childPid,...(childProcessStartId ? { processStartId: childProcessStartId } : {}),@@ -2247,10 +2484,12 @@ export class DaemonSupervisor {authenticationToken: token,rootActiveSessionId,ownerClientId: existing?.descriptor.ownerClientId ?? ownerClientId,+ sessionDir: createCommand.config?.sessionDir,+ telemetryDisabled: createCommand.config?.telemetryDisabled,createdAt: existing?.descriptor.createdAt ?? now,updatedAt: now,lifecycle: "starting",- createCommand: { ...createCommand, id: undefined },+ createCommand: durableDaemonCreateCommand(createCommand),consecutiveFailures: existing?.descriptor.consecutiveFailures ?? 0,};worker = existing ?? {@@ -2264,10 +2503,12 @@ export class DaemonSupervisor {intentionalStop: false,stopRevision: 0,launchEnv,+ transientCreateCommand: ownerClientId ? createCommand : undefined,};await this.assertRecoveryAllowed();worker.descriptor = descriptor;worker.launchEnv = launchEnv;+ worker.transientCreateCommand = descriptor.ownerClientId ? createCommand : undefined;descriptorAssigned = true;this.persistWorker(worker);worker.intentionalStop = false;@@ -2328,6 +2569,10 @@ export class DaemonSupervisor {worker.descriptor.consecutiveFailures = 0;worker.descriptor.lastError = undefined;this.persistWorker(worker);+ if (!worker.descriptor.ownerClientId) {+ worker.launchEnv = undefined;+ worker.transientCreateCommand = undefined;+ }await this.syncAgentPeers().catch((error) => this.log(`Could not synchronize agent peers: ${String(error)}`));this.broadcastHeartbeatsChanged();return worker;@@ -2509,6 +2754,7 @@ export class DaemonSupervisor {return;}worker.client = undefined;+ this.invalidateWorkerSessionInputPauses(worker, "Session worker disconnected while input was paused");const interrupted = new Map<string, Set<string>>();for (const [activeSessionId, generations] of worker.snapshotGenerations ?? []) {for (const generation of generations.values()) {@@ -2860,13 +3106,22 @@ export class DaemonSupervisor {`Cannot safely replace live session worker ${worker.descriptor.workerId} without a verified process identity`,);}+ const recoveryCommand = worker.descriptor.ownerClientId ? worker.transientCreateCommand : undefined;+ if (!recoveryCommand || !worker.launchEnv) {+ await this.recoverUncertainWorkerOperations(worker, false);+ worker.descriptor.lifecycle = "failed";+ worker.descriptor.lastError = "Waiting for a client with fresh runtime context";+ this.persistWorker(worker);+ await this.syncAgentPeers().catch(() => undefined);+ return;+ }const safeToKillWorkerProcess =processAlive && processIdentityMatches && worker.descriptor.processStartId !== undefined;await this.recoverUncertainWorkerOperations(worker, safeToKillWorkerProcess);if (this.isWorkerRecoveryCancelled(worker)) {return;}- await this.launchWorker(worker.descriptor.createCommand, worker);+ await this.launchWorker(recoveryCommand, worker, worker.descriptor.ownerClientId);return;} catch (error) {if (isSupervisorRecoveryCancelled(error) || this.isWorkerRecoveryCancelled(worker)) {@@ -3014,15 +3269,11 @@ export class DaemonSupervisor {}worker.descriptor.rootSessionId = root.sessionId;worker.descriptor.sessionFile = root.sessionFile;- worker.descriptor.createCommand = {- ...worker.descriptor.createCommand,+ worker.descriptor.createCommand = durableDaemonCreateCommand({+ type: "create",sessionPath: root.sessionFile,- continueRecent: false,- config: {- ...worker.descriptor.createCommand.config,- cwd: root.cwd,- },- };+ noSession: worker.descriptor.createCommand.noSession,+ });this.persistWorker(worker);}}@@ -3371,16 +3622,29 @@ export class DaemonSupervisor {});}- private findWorkerBySessionFile(sessionFile: string): WorkerMatch | undefined {+ private findWorkerBySessionFile(sessionFile: string): ResidentWorker | undefined {const target = canonicalSessionPath(sessionFile);+ const matches = new Set<ResidentWorker>();for (const worker of this.workers.values()) {- for (const summary of worker.summaries.values()) {- if (summary.sessionFile && canonicalSessionPath(summary.sessionFile) === target) {- return { worker, summary };- }+ const summaryMatches = [...worker.summaries.values()].some(+ (summary) => summary.sessionFile && canonicalSessionPath(summary.sessionFile) === target,+ );+ const descriptorPath = worker.descriptor.sessionFile+ ? canonicalSessionPath(worker.descriptor.sessionFile)+ : undefined;+ const configuredPath = worker.descriptor.createCommand.sessionPath+ ? canonicalSessionPath(worker.descriptor.createCommand.sessionPath)+ : undefined;+ if (!summaryMatches && descriptorPath !== target && configuredPath !== target) continue;+ if (descriptorPath && configuredPath && descriptorPath !== configuredPath) {+ throw new Error(`Conflicting resident session paths for worker ${worker.descriptor.workerId}`);}+ matches.add(worker);+ }+ if (matches.size > 1) {+ throw new Error(`Ambiguous resident session path "${sessionFile}"`);}- return undefined;+ return matches.values().next().value;}private async forwardToWorker(@@ -3417,6 +3681,18 @@ export class DaemonSupervisor {this.assertTelemetryAttachAllowed(ownedWorker, command.telemetryDisabled);ownedWorker.launchEnv = command.launchEnv ?? ownedWorker.launchEnv;if (!ownedWorker.client || ownedWorker.descriptor.lifecycle !== "ready") {+ if (command.recoveryConfig) {+ ownedWorker.transientCreateCommand = {+ ...ownedWorker.descriptor.createCommand,+ config: {+ ...command.recoveryConfig,+ ...(ownedWorker.descriptor.telemetryDisabled === true ? { telemetryDisabled: true } : {}),+ },+ env: command.env,+ launchEnv: command.launchEnv,+ lifecycle: "client_owned",+ };+ }if (!ownedWorker.launchEnv) {throw new Error("Client-owned session recovery requires the owning client environment");}@@ -3567,6 +3843,9 @@ export class DaemonSupervisor {});}void this.syncWorkerExtensionUi(activeSessionId);+ const detachingSessions = this.detachingInputPauseSessions?.get(client);+ detachingSessions?.delete(command.activeSessionId);+ detachingSessions?.delete(activeSessionId);return { result: publicResult, worker: match.worker, transcript, releaseTranscript };} catch (error) {releaseTranscript?.();@@ -3578,7 +3857,7 @@ export class DaemonSupervisor {}private assertTelemetryAttachAllowed(worker: ResidentWorker, telemetryDisabled: true | undefined): void {- if (telemetryDisabled && worker.descriptor.createCommand.config?.telemetryDisabled !== true) {+ if (telemetryDisabled && worker.descriptor.telemetryDisabled !== true) {throw new Error("Cannot attach to this active agent while telemetry is disabled for the current invocation. Stop the agent and retry so it can restart without telemetry.",);@@ -4298,6 +4577,7 @@ export class DaemonSupervisor {// tuple assertions complete. A synchronous root shutdown event can arrive// before its request resolves, so leave both intact while it is active.if ((this.workerStopCounts?.get(worker) ?? 0) === 0) {+ this.invalidateWorkerSessionInputPauses(worker, "Session worker stopped while input was paused");this.workers.delete(worker.descriptor.workerId);this.deleteWorkerDescriptor(worker);void this.syncAgentPeers().catch(() => undefined);@@ -4859,6 +5139,7 @@ export class DaemonSupervisor {await this.finalizeArchivedWorkerStop(worker);assertStopStillApplies();}+ this.invalidateWorkerSessionInputPauses(worker, "Session worker stopped while input was paused");this.workers.delete(worker.descriptor.workerId);if (removeDescriptor) {this.deleteWorkerDescriptor(worker);diff --git a/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.tsindex 51dea75bd2..31762531e0 100644--- a/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts@@ -38,6 +38,20 @@ export type DaemonWorkerFrameHeader =export type DaemonCreateCommand = Extract<DaemonCommand, { type: "create" }>;+export interface DurableDaemonCreateCommand {+ type: "create";+ sessionPath?: string;+ noSession?: boolean;+}++export function durableDaemonCreateCommand(command: DaemonCreateCommand): DurableDaemonCreateCommand {+ return {+ type: "create",+ ...(command.sessionPath !== undefined ? { sessionPath: command.sessionPath } : {}),+ ...(command.noSession !== undefined ? { noSession: command.noSession } : {}),+ };+}+export type DaemonWorkerCommand =| {id?: string;@@ -84,7 +98,7 @@ export type DaemonWorkerCommandBody = DaemonWorkerCommand extends infer TCommand: never;export interface DaemonWorkerDescriptor {- version: 1;+ version: 1 | 2;workerId: string;pid: number;processStartId?: string;@@ -98,10 +112,12 @@ export interface DaemonWorkerDescriptor {ownerClientId?: string;rootSessionId?: string;sessionFile?: string;+ sessionDir?: string;+ telemetryDisabled?: true;createdAt: string;updatedAt: string;lifecycle: DaemonWorkerLifecycle;- createCommand: DaemonCreateCommand;+ createCommand: DurableDaemonCreateCommand;consecutiveFailures: number;/** Durable intent written before root termination so replacement supervisors never recover it. */stopRequestedAt?: string;@@ -111,6 +127,48 @@ export interface DaemonWorkerDescriptor {lastError?: string;}+export function durableDaemonWorkerDescriptor(descriptor: DaemonWorkerDescriptor): DaemonWorkerDescriptor {+ const versionOneCreateCommand = descriptor.createCommand as unknown as { config?: unknown };+ const versionOneConfig =+ descriptor.version === 1 &&+ typeof versionOneCreateCommand.config === "object" &&+ versionOneCreateCommand.config !== null+ ? (versionOneCreateCommand.config as Record<string, unknown>)+ : undefined;+ const sessionDir =+ descriptor.sessionDir ??+ (typeof versionOneConfig?.sessionDir === "string" ? versionOneConfig.sessionDir : undefined);+ const telemetryDisabled = descriptor.telemetryDisabled === true || versionOneConfig?.telemetryDisabled === true;+ return {+ version: 2,+ workerId: descriptor.workerId,+ pid: descriptor.pid,+ ...(descriptor.processStartId !== undefined ? { processStartId: descriptor.processStartId } : {}),+ socketPath: descriptor.socketPath,+ recoveryJournalPath: descriptor.recoveryJournalPath,+ ...(descriptor.orphanProcessJournalPath !== undefined+ ? { orphanProcessJournalPath: descriptor.orphanProcessJournalPath }+ : {}),+ supervisorSocketPath: descriptor.supervisorSocketPath,+ authenticationToken: descriptor.authenticationToken,+ rootActiveSessionId: descriptor.rootActiveSessionId,+ ...(descriptor.ownerClientId !== undefined ? { ownerClientId: descriptor.ownerClientId } : {}),+ ...(descriptor.rootSessionId !== undefined ? { rootSessionId: descriptor.rootSessionId } : {}),+ ...(descriptor.sessionFile !== undefined ? { sessionFile: descriptor.sessionFile } : {}),+ ...(sessionDir !== undefined ? { sessionDir } : {}),+ ...(telemetryDisabled ? { telemetryDisabled: true as const } : {}),+ createdAt: descriptor.createdAt,+ updatedAt: descriptor.updatedAt,+ lifecycle: descriptor.lifecycle,+ createCommand: durableDaemonCreateCommand(descriptor.createCommand),+ consecutiveFailures: descriptor.consecutiveFailures,+ ...(descriptor.stopRequestedAt !== undefined ? { stopRequestedAt: descriptor.stopRequestedAt } : {}),+ ...(descriptor.archiveOnStop !== undefined ? { archiveOnStop: descriptor.archiveOnStop } : {}),+ ...(descriptor.lastFailureAt !== undefined ? { lastFailureAt: descriptor.lastFailureAt } : {}),+ ...(descriptor.lifecycle === "failed" ? { lastError: "Waiting for a client with fresh runtime context" } : {}),+ };+}+export function isDaemonWorkerProcess(environment: NodeJS.ProcessEnv = process.env): boolean {return environment[DAEMON_WORKER_ROLE_ENV] === "1";}diff --git a/packages/coding-agent/src/modes/headless-completion.ts b/packages/coding-agent/src/modes/headless-completion.tsindex b3d51d03f5..94ffe2c578 100644--- a/packages/coding-agent/src/modes/headless-completion.ts+++ b/packages/coding-agent/src/modes/headless-completion.ts@@ -71,11 +71,20 @@ function autonomousProgressKey(status: AgentAutonomousStatus): string {].join(":");}-export async function waitForHeadlessCompletion(session: AgentSession): Promise<AgentAutonomousStatus> {+export interface HeadlessCompletionOptions {+ /** Include descendant settlement and the parent turns caused by their results. */+ waitForRlmQuiescence?: boolean;+}++export async function waitForHeadlessCompletion(+ session: AgentSession,+ options: HeadlessCompletionOptions = {},+): Promise<AgentAutonomousStatus> {let lastPromptedProgressKey: string | undefined;let repeatedProgressPrompts = 0;while (true) {- await session.waitForIdle();+ if (options.waitForRlmQuiescence) await session.waitForRlmQuiescence();+ else await session.waitForHeadlessIdle();const status = session.getAutonomousStatus();if (!shouldContinueAutonomousGates(status) || !status.lastGateFailure) {return status;@@ -111,6 +120,7 @@ export async function waitForHeadlessCompletion(session: AgentSession): Promise<if (shouldContinueAutonomousGates(postErrorStatus) && postErrorStatus.lastGateFailure) {continue;}+ if (options.waitForRlmQuiescence) continue;return postErrorStatus;}}diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.tsindex 7ff21e88c4..256da26b47 100644--- a/packages/coding-agent/test/agent-connection-daemon.test.ts+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts@@ -9,6 +9,7 @@ import {} from "../src/modes/agent-connection/daemon-agent-connection.js";import type {AgentConnectionEvent,+ AgentConnectionRlmChildAgentSnapshot,AgentConnectionSavedSessionInfo,AgentConnectionState,} from "../src/modes/agent-connection/types.js";@@ -46,8 +47,12 @@ class FakeDaemonClient {attachFailures = 0;connectionStateGate: Promise<void> | undefined;connectionStateFactory: ((activeSessionId: string) => AgentConnectionState) | undefined;+ rlmChildren: AgentConnectionRlmChildAgentSnapshot[] = [];+ rlmChildrenEventSequence = 12;+ rlmChildrenGate: Promise<void> | undefined;abortBashUnknownCommand = false;abortAndClearQueueUnknownCommand = false;+ inputPauseAcquireGate: Promise<void> | undefined;cronAddGate: Promise<void> | undefined;promptGate: Promise<void> | undefined;promptError: Error | undefined;@@ -148,6 +153,14 @@ class FakeDaemonClient {success: true,data: { messages: [{ role: "user", content: "current prompt", timestamp: 4 }] },};+ case "get_rlm_children":+ await this.rlmChildrenGate;+ return {+ type: "response",+ command: command.type,+ success: true,+ data: { children: this.rlmChildren, eventSequence: this.rlmChildrenEventSequence },+ };case "get_resource_snapshot":return {type: "response",@@ -269,6 +282,16 @@ class FakeDaemonClient {success: true,data: { steering: ["aborted"], followUp: ["cleared"] },};+ case "acquire_session_input_pause":+ if (this.inputPauseAcquireGate) await this.inputPauseAcquireGate;+ return {+ type: "response",+ command: command.type,+ success: true,+ data: { pauseId: "pause-1" },+ };+ case "release_session_input_pause":+ return { type: "response", command: command.type, success: true };case "heartbeats_list":return this.serverCapabilities.has("heartbeat_catalog")? { type: "response", command: command.type, success: true, data: { heartbeats: [] } }@@ -348,6 +371,19 @@ class FakeDaemonClient {},};}+ case "wait_for_headless_completion":+ return {+ type: "response",+ command: command.type,+ success: true,+ data: {+ enabled: false,+ continuationsUsed: 0,+ turnsUsed: 0,+ tokensUsed: 0,+ limits: { maxContinuations: 0 },+ },+ };case "wait_for_idle":case "set_scoped_models":case "rename_saved_session":@@ -600,6 +636,7 @@ interface CreateAttachResultOptions {omitSessionContext?: boolean;sessionTree?: DaemonAttachResult["snapshot"]["sessionTree"];parent?: DaemonAttachResult["snapshot"]["parent"];+ children?: DaemonAttachResult["snapshot"]["children"];replay?: DaemonAttachResult["replay"];}@@ -654,6 +691,7 @@ function createAttachResult(lastEventSequence,lastEventCursor,...(options.parent ? { parent: options.parent } : {}),+ ...(options.children ? { children: options.children } : {}),},replay: options.replay ?? {status: "complete",@@ -676,6 +714,27 @@ function createAttachResult(};}+function emitRlmChildUpdate(+ client: FakeDaemonClient,+ activeSessionId: string,+ sequence: number,+ child: AgentConnectionRlmChildAgentSnapshot,+): void {+ client.emitMessage({+ type: "session_event",+ activeSessionId,+ event: { type: "rlm_child_update", child },+ meta: {+ id: `${activeSessionId}:${sequence}`,+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId,+ sequence,+ cursor: { generation: `generation-${activeSessionId}`, sequence },+ emittedAt: "2026-01-01T00:00:00.000Z",+ },+ });+}+function emitSequencedQueueUpdate(client: FakeDaemonClient, activeSessionId: string, sequence: number): void {client.emitMessage({type: "session_event",@@ -711,6 +770,22 @@ describe("DaemonAgentConnection", () => {});});+ it.each([true, false])("capability-gates owned-session recovery context: %s", async (supported) => {+ const fakeClient = new FakeDaemonClient();+ if (supported) fakeClient.serverCapabilities.add("owned_session_recovery_context");+ const recoveryConfig = { cwd: "/tmp/fresh-owner" };+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-owned", {+ ownedSession: true,+ ownedSessionRecoveryConfig: recoveryConfig,+ });++ await connection.attach();++ const request = fakeClient.requests[0];+ if (supported) expect(request).toMatchObject({ recoveryConfig });+ else expect(request).not.toHaveProperty("recoveryConfig");+ });+it("forwards queueIfBusy for prompt admission", async () => {const fakeClient = new FakeDaemonClient();const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");@@ -2139,6 +2214,58 @@ describe("DaemonAgentConnection", () => {});});+ it.each([true, false])("capability-gates authoritative child-roster reads: %s", async (supported) => {+ const fakeClient = new FakeDaemonClient();+ if (supported) fakeClient.serverCapabilities.add("authoritative_child_roster");+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ await connection.attach();++ const children = connection.getRlmChildSnapshots();+ if (supported) await expect(children).resolves.toEqual([]);+ else await expect(children).rejects.toThrow("authoritative_child_roster");+ });++ it("preserves a newer live child update over an in-flight roster read", async () => {+ const fakeClient = new FakeDaemonClient();+ fakeClient.serverCapabilities.add("authoritative_child_roster");+ let releaseRoster!: () => void;+ fakeClient.rlmChildrenGate = new Promise<void>((resolve) => {+ releaseRoster = resolve;+ });+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ await connection.attach();++ const children = connection.getRlmChildSnapshots();+ emitRlmChildUpdate(fakeClient, "active-1", 13, {+ id: "child-live",+ label: "live child",+ status: "running",+ sessionDir: "/tmp/child-live",+ });+ releaseRoster();++ await expect(children).resolves.toEqual([expect.objectContaining({ id: "child-live", status: "running" })]);+ });++ it("keeps the live child roster after an empty attach snapshot", async () => {+ const fakeClient = new FakeDaemonClient();+ fakeClient.attachResultFactory = (command) =>+ createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12, { children: [] });+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");++ await connection.attach();+ emitRlmChildUpdate(fakeClient, "active-1", 13, {+ id: "child-live",+ label: "live child",+ status: "running",+ sessionDir: "/tmp/child-live",+ });++ await expect(connection.getInitialSnapshot()).resolves.toMatchObject({+ children: [expect.objectContaining({ id: "child-live", status: "running" })],+ });+ });+it("refreshes initial snapshots after live events make the cached snapshot stale", async () => {const fakeClient = new FakeDaemonClient();fakeClient.attachResultFactory = (command) =>@@ -2224,12 +2351,21 @@ describe("DaemonAgentConnection", () => {it("sends queue commands through the daemon protocol", async () => {const fakeClient = new FakeDaemonClient();+ fakeClient.serverCapabilities.add("session_input_pause");const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");await connection.attach();await expect(connection.getQueue()).resolves.toEqual({ steering: ["steer"], followUp: ["follow"] });await expect(connection.clearQueue()).resolves.toEqual({ steering: ["cleared"], followUp: [] });await expect(connection.abortAndClearQueue()).resolves.toEqual({ steering: ["aborted"], followUp: ["cleared"] });+ const [inputPause, inputPauseAlias] = await Promise.all([+ connection.acquireSessionInputPause("lease-1"),+ connection.acquireSessionInputPause("lease-1"),+ ]);+ expect(inputPauseAlias).toBe(inputPause);+ (connection as unknown as { activeSessionId: string }).activeSessionId = "active-2";+ await inputPause.release();+ (connection as unknown as { activeSessionId: string }).activeSessionId = "active-1";await connection.waitForIdle();const model = getModel("anthropic", "claude-sonnet-4-5");if (!model) {@@ -2242,14 +2378,26 @@ describe("DaemonAgentConnection", () => {"get_queue","clear_queue","abort_and_clear_queue",+ "acquire_session_input_pause",+ "release_session_input_pause","wait_for_idle","set_scoped_models",]);expect(fakeClient.requests[1]).toMatchObject({ type: "get_queue", activeSessionId: "active-1" });expect(fakeClient.requests[2]).toMatchObject({ type: "clear_queue", activeSessionId: "active-1" });expect(fakeClient.requests[3]).toMatchObject({ type: "abort_and_clear_queue", activeSessionId: "active-1" });- expect(fakeClient.requests[4]).toMatchObject({ type: "wait_for_idle", activeSessionId: "active-1" });+ expect(fakeClient.requests[4]).toMatchObject({+ type: "acquire_session_input_pause",+ activeSessionId: "active-1",+ leaseKey: "lease-1",+ });expect(fakeClient.requests[5]).toMatchObject({+ type: "release_session_input_pause",+ activeSessionId: "active-1",+ pauseId: "pause-1",+ });+ expect(fakeClient.requests[6]).toMatchObject({ type: "wait_for_idle", activeSessionId: "active-1" });+ expect(fakeClient.requests[7]).toMatchObject({type: "set_scoped_models",activeSessionId: "active-1",scopedModels: [{ model, thinkingLevel: "high" }],@@ -2261,6 +2409,79 @@ describe("DaemonAgentConnection", () => {);});+ it("fails closed when a daemon disconnect invalidates an input pause", async () => {+ const fakeClient = new FakeDaemonClient();+ fakeClient.serverCapabilities.add("session_input_pause");+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ await connection.attach();+ const events: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ events.push(event);+ });++ const pause = await connection.acquireSessionInputPause("lease-1");+ fakeClient.disconnectForReconnect("shutdown");++ await expect(pause.release()).rejects.toThrow("invalidated by a daemon reconnect");+ await expect(connection.acquireSessionInputPause("lease-1")).rejects.toThrow("connection is closed");+ expect(events).toContainEqual(+ expect.objectContaining({+ type: "closed",+ error: expect.stringContaining("fence was invalidated"),+ }),+ );+ });++ it("releases an input pause whose acquisition resolves after disconnect", async () => {+ const fakeClient = new FakeDaemonClient();+ fakeClient.serverCapabilities.add("session_input_pause");+ let releaseAcquire!: () => void;+ fakeClient.inputPauseAcquireGate = new Promise<void>((resolve) => {+ releaseAcquire = resolve;+ });+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ await connection.attach();++ const acquisition = connection.acquireSessionInputPause("lease-1");+ await vi.waitFor(() =>+ expect(fakeClient.requests.some((request) => request.type === "acquire_session_input_pause")).toBe(true),+ );+ fakeClient.disconnectForReconnect("shutdown");+ releaseAcquire();++ await expect(acquisition).rejects.toThrow("acquisition was invalidated by a daemon reconnect");+ expect(fakeClient.requests.filter((request) => request.type === "release_session_input_pause")).toHaveLength(1);+ });++ it("capability-gates the strong RLM completion barrier", async () => {+ const oldDaemonClient = new FakeDaemonClient();+ const oldConnection = new DaemonAgentConnection(asDaemonClient(oldDaemonClient), "active-old");+ await oldConnection.attach();+ await oldConnection.waitForHeadlessCompletion();+ expect(oldDaemonClient.requests.at(-1)).toEqual({+ type: "wait_for_headless_completion",+ activeSessionId: "active-old",+ });+ await expect(oldConnection.waitForHeadlessCompletion({ waitForRlmQuiescence: true })).rejects.toThrow(+ "without RLM quiescence barriers",+ );+ expect(oldDaemonClient.requests.map((request) => request.type)).toEqual([+ "attach",+ "wait_for_headless_completion",+ ]);++ const newDaemonClient = new FakeDaemonClient();+ newDaemonClient.serverCapabilities.add("rlm_quiescence_barrier");+ const newConnection = new DaemonAgentConnection(asDaemonClient(newDaemonClient), "active-new");+ await newConnection.attach();+ await newConnection.waitForHeadlessCompletion({ waitForRlmQuiescence: true });+ expect(newDaemonClient.requests.at(-1)).toMatchObject({+ type: "wait_for_headless_completion",+ activeSessionId: "active-new",+ waitForRlmQuiescence: true,+ });+ });+it("cancels rlm child runs through the daemon protocol", async () => {const fakeClient = new FakeDaemonClient();const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");diff --git a/packages/coding-agent/test/agent-connection-in-process.test.ts b/packages/coding-agent/test/agent-connection-in-process.test.tsindex be9054a098..beb868cb0c 100644--- a/packages/coding-agent/test/agent-connection-in-process.test.ts+++ b/packages/coding-agent/test/agent-connection-in-process.test.ts@@ -108,6 +108,7 @@ function createFakeSession(id: string, messages: AgentMessage[]): FakeSessionCongetActiveToolNames: () => ["ipython"],getContextUsage: () => undefined,cancelRlmChildRun: (childId: string) => childId === "child-1",+ getRlmChildSnapshots: () => [],getToolDefinition: (toolName: string) => ({name: toolName,label: toolName,diff --git a/packages/coding-agent/test/agent-session-config.test.ts b/packages/coding-agent/test/agent-session-config.test.tsindex 272fe5a342..b0273acffd 100644--- a/packages/coding-agent/test/agent-session-config.test.ts+++ b/packages/coding-agent/test/agent-session-config.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "vitest";-import { type AgentSessionRuntimeConfig, mergeAgentSessionRuntimeConfig } from "../src/core/agent-session-config.js";+import {+ type AgentSessionRuntimeConfig,+ durableAgentSessionRuntimeConfig,+ mergeAgentSessionRuntimeConfig,+} from "../src/core/agent-session-config.js";describe("mergeAgentSessionRuntimeConfig", () => {it("applies session overrides without mutating default config", () => {@@ -168,4 +172,33 @@ describe("mergeAgentSessionRuntimeConfig", () => {expect(mergeAgentSessionRuntimeConfig({}, { telemetryDisabled: true }).telemetryDisabled).toBe(true);expect(mergeAgentSessionRuntimeConfig({}, {}).telemetryDisabled).toBeUndefined();});++ it("persists only typed daemon host settings", () => {+ const durable = durableAgentSessionRuntimeConfig({+ cwd: "/repo",+ agentDir: "/agent",+ sessionDir: "/sessions",+ telemetryDisabled: true,+ provider: "intercept",+ model: "openai/example",+ apiKey: "secret-api-key",+ extensionFlagValues: { providerSecretKey: "secret-extension-key" },+ initialGoal: { objective: "transient" },+ });++ expect(durable).toEqual({+ cwd: "/repo",+ agentDir: "/agent",+ sessionDir: "/sessions",+ telemetryDisabled: true,+ });+ expect(+ durableAgentSessionRuntimeConfig({+ cwd: 1,+ agentDir: "/agent",+ sessionDir: false,+ telemetryDisabled: "yes",+ } as unknown as AgentSessionRuntimeConfig),+ ).toEqual({ agentDir: "/agent" });+ });});diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex 05e24a2ea8..63afdc6169 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -35,6 +35,7 @@ import { SessionManager } from "../src/core/session-manager.js";import { SettingsManager, type SettingsStorage } from "../src/core/settings-manager.js";import type { Skill } from "../src/core/skills.js";import { createSyntheticSourceInfo } from "../src/core/source-info.js";+import type { BashOperations } from "../src/core/tools/bash.js";import { type ActiveSessionState, resolveActiveSessionState } from "../src/modes/daemon/active-session-state.js";import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";import { createTestExtensionsResult, createTestResourceLoader } from "./utilities.js";@@ -110,17 +111,25 @@ interface CapturedCommReply {interface InspectableRlmRun {id: string;+ prompt?: string;+ sessionName?: string;sessionDir: string;+ model?: typeof model;abort: () => void;status: string;settled: boolean;error?: string;+ abandonedForQuiescence?: boolean;+ publication?: { promise: Promise<void>; resolve(): void; reject(error: Error): void };+ settlement?: { promise: Promise<void>; resolve(): void; reject(error: Error): void };detachedDeletion?: Awaited<ReturnType<AgentSession["listRlmSubagents"]>>["subagents"][number];session?: AgentSession;}interface InspectableRlmSession {+ _disposing: boolean;_activeRlmChildRuns: Map<string, InspectableRlmRun>;+ _unsettledRlmChildRuns: Set<InspectableRlmRun>;_deletingRlmChildren: Map<string,{@@ -131,6 +140,8 @@ interface InspectableRlmSession {_rlmChildCleanupFailures: Map<string, Awaited<ReturnType<AgentSession["listRlmSubagents"]>>["subagents"][number]>;_rlmChildSessions: Map<string, AgentSession>;_rlmChildUnsubscribes: Map<string, () => void>;+ _deletedRlmChildIds: Set<string>;+ _rlmQuiescenceWaitAborts: Set<AbortController>;_createKernelHostHandlers(): HostRequestHandlers;_reapDeletedRlmSubagentRuntimesAfterCompaction(): Promise<void>;}@@ -231,6 +242,20 @@ function findLastMessage(return undefined;}+function deferred<T = void>(): {+ promise: Promise<T>;+ resolve: (value: T | PromiseLike<T>) => void;+ reject: (reason?: unknown) => void;+} {+ let resolve!: (value: T | PromiseLike<T>) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, resolve, reject };+}+describe("AgentSession rlm recursion", () => {let tempDir: string;let session: AgentSession | undefined;@@ -314,6 +339,27 @@ describe("AgentSession rlm recursion", () => {return session;}+ function createAbortInsensitiveChild(): {+ child: AgentSession;+ completion: ReturnType<typeof deferred<void>>;+ hasStarted: () => boolean;+ } {+ const completion = deferred<void>();+ let started = false;+ const child = createSession({+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ started = true;+ void completion.promise.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("child stopped") });+ });+ return stream;+ },+ });+ vi.spyOn(child, "abort").mockResolvedValue();+ return { child, completion, hasStarted: () => started };+ }+it("propagates skipped-running deletion outcomes through the host handler", async () => {const subagent = {rlm_child_id: "running-child",@@ -650,6 +696,97 @@ describe("AgentSession rlm recursion", () => {});});+ it("keeps live nested children visible when their direct parent is hidden by deletion", () => {+ const root = createSession();+ const rootInternals = root as unknown as InspectableRlmSession;+ const hiddenParents = [+ { id: "deleted-parent", hiding: "deleted" as const },+ { id: "deleting-parent", hiding: "deleting" as const },+ { id: "detached-parent", hiding: "detached" as const },+ ];+ const parentInternalsToClear: InspectableRlmSession[] = [];++ for (const [index, { id, hiding }] of hiddenParents.entries()) {+ const parent = createSession({ rlmSessionDir: join(tempDir, id) });+ const parentInternals = parent as unknown as InspectableRlmSession;+ parentInternalsToClear.push(parentInternals);+ const nestedId = `${id}-live-grandchild`;+ parentInternals._activeRlmChildRuns.set(nestedId, {+ id: nestedId,+ prompt: "still working",+ sessionName: nestedId,+ sessionDir: join(tempDir, nestedId),+ model,+ abort: () => {},+ status: index === 1 ? "queued" : "running",+ settled: false,+ });++ if (hiding === "detached") {+ rootInternals._activeRlmChildRuns.set(id, {+ id,+ prompt: "hidden parent",+ sessionName: id,+ sessionDir: join(tempDir, id),+ model,+ abort: () => {},+ status: "cancelled",+ settled: false,+ detachedDeletion: {+ rlm_child_id: id,+ active_session_id: null,+ session_id: null,+ session_name: id,+ session_dir: join(tempDir, id),+ status: "running",+ },+ session: parent,+ });+ // The same child can be visible in both lifecycle registries while+ // deletion settles; it must be traversed exactly once and remain hidden.+ rootInternals._rlmChildSessions.set(id, parent);+ } else {+ rootInternals._rlmChildSessions.set(id, parent);+ if (hiding === "deleted") {+ rootInternals._deletedRlmChildIds.add(id);+ } else {+ rootInternals._deletingRlmChildren.set(id, {+ subagent: {+ rlm_child_id: id,+ active_session_id: null,+ session_id: null,+ session_name: id,+ session_dir: join(tempDir, id),+ status: "completed",+ },+ promise: Promise.resolve({+ subagent: {+ rlm_child_id: id,+ active_session_id: null,+ session_id: null,+ session_name: id,+ session_dir: join(tempDir, id),+ status: "completed",+ },+ }),+ });+ }+ }+ }++ const snapshots = root.getRlmChildSnapshots();+ expect(snapshots.map((snapshot) => snapshot.id).sort()).toEqual(+ hiddenParents.map(({ id }) => `${id}-live-grandchild`).sort(),+ );+ expect(snapshots.map((snapshot) => snapshot.status).sort()).toEqual(["queued", "running", "running"]);+ // These are deliberately minimal lifecycle records; remove them before+ // fixture teardown asks real runs to settle.+ rootInternals._activeRlmChildRuns.clear();+ rootInternals._rlmChildSessions.clear();+ for (const parentInternals of parentInternalsToClear) parentInternals._activeRlmChildRuns.clear();+ root.dispose();+ });+it("makes an orchestrator-chosen name override a custom runtime's preexisting name", async () => {const hostedChild = createSession();hostedChild.setSessionName("factory-assigned-name");@@ -819,11 +956,7 @@ describe("AgentSession rlm recursion", () => {);});- it("delivers an id-addressed send while a completed child's terminal injection is pending", async () => {- let releaseTerminalInjection: () => void = () => {};- const terminalInjectionGate = new Promise<void>((resolve) => {- releaseTerminalInjection = resolve;- });+ it("delivers an id-addressed send after a completed child durably admits its terminal notice", async () => {const child = createSession({ rlmSessionDir: join(tempDir, "completed-child") });const sendAgentMessage = vi.fn(async (input: { target: string; message: string }) => ({id: "agentmsg-completed-child",@@ -854,13 +987,9 @@ describe("AgentSession rlm recursion", () => {deleteRlmSubagentRuntime: async (_id, session) => session?.disposeAsync(),},});- const promptInjectedMessage = vi.fn(async () => terminalInjectionGate);- (root as unknown as { _promptInjectedMessage: typeof promptInjectedMessage })._promptInjectedMessage =- promptInjectedMessage;const spawned = await root.runRlmChild("completed task", { name: "completed-worker" });+ await waitFor(() => root.getRlmChildSession(spawned.rlm_child_id) === child);const internals = root as unknown as InspectableRlmSession;- await waitFor(() => internals._activeRlmChildRuns.get(spawned.rlm_child_id)?.status === "done");- await waitFor(() => promptInjectedMessage.mock.calls.length === 1);const send = internals._createKernelHostHandlers()["agent_message.send"];if (!send) throw new Error("Missing agent_message.send host handler");@@ -870,9 +999,6 @@ describe("AgentSession rlm recursion", () => {expect(sendAgentMessage).toHaveBeenCalledWith(expect.objectContaining({ target: child.sessionId, message: "follow-up" }),);-- releaseTerminalInjection();- await waitFor(() => !internals._activeRlmChildRuns.has(spawned.rlm_child_id));});it("propagates pending child startup failure to an immediate roled send", async () => {@@ -1241,6 +1367,25 @@ describe("AgentSession rlm recursion", () => {});});+ it("suppresses a done child's unsettled fallback notice at the cancellation cut", async () => {+ const root = createSession();+ let suppressed = false;+ root.subscribe((event) => {+ if (event.type === "rlm_child_update" && event.child.status === "done") {+ suppressed = root.cancelRlmChildRun(event.child.id);+ }+ });++ await root.runRlmChild("silent child at cancellation cut", { name: "suppressed-worker" });+ await root.waitForRlmQuiescence();+ expect(suppressed).toBe(true);+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);+ });+it("does not inject a terminal notice when a parent follow-up resets reply state after a reply", async () => {const child = createSession({depth: 1,@@ -1294,7 +1439,7 @@ describe("AgentSession rlm recursion", () => {).toHaveLength(0);});- it("keeps detached deletion silent when child startup later settles", async () => {+ it("notifies after detached startup deletion cleanup settles", async () => {let releaseRuntimeCreation: () => void = () => {};const runtimeCreationGate = new Promise<void>((resolve) => {releaseRuntimeCreation = resolve;@@ -1321,7 +1466,11 @@ describe("AgentSession rlm recursion", () => {root.messages.filter((message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",),- ).toHaveLength(0);+ ).toEqual([+ expect.objectContaining({+ details: expect.objectContaining({ kind: "cancelled", reason: "Deleted by parent orchestrator" }),+ }),+ ]);});it("fully deletes a settled startup failure and frees its session name", async () => {@@ -1370,6 +1519,486 @@ describe("AgentSession rlm recursion", () => {});});+ it("strong quiescence yields to a real gated child bash while interactive idle remains resolved", async () => {+ const child = createSession({ rlmSessionDir: join(tempDir, "bash-active-child") });+ const bashStarted = deferred<void>();+ const bashCompletion = deferred<void>();+ const operations: BashOperations = {+ exec: async () => {+ bashStarted.resolve();+ await bashCompletion.promise;+ return { exitCode: 0 };+ },+ };+ const bash = child.executeBash("gated", undefined, { operations });+ await bashStarted.promise;++ await expect(child.waitForIdle()).resolves.toBeUndefined();+ const root = createSession();+ expect(root.registerRlmChildSession("bash-active-child", child)).toBe(true);+ const originalHeadlessIdle = child.waitForHeadlessIdle.bind(child);+ let headlessIdleCalls = 0;+ vi.spyOn(child, "waitForHeadlessIdle").mockImplementation(async () => {+ if (++headlessIdleCalls > 100) throw new Error("RLM quiescence spun without yielding a macrotask");+ await originalHeadlessIdle();+ });++ const quiescence = root.waitForRlmQuiescence();+ const firstBoundary = await Promise.race([+ quiescence.then(+ () => "resolved" as const,+ () => "rejected" as const,+ ),+ sleep(20).then(() => "timer" as const),+ ]);+ expect(firstBoundary).toBe("timer");++ bashCompletion.resolve();+ await bash;+ await expect(quiescence).resolves.toBeUndefined();+ expect(headlessIdleCalls).toBeLessThan(100);+ });++ it("rechecks parent self-activity after a child quiescence boundary", async () => {+ const child = createSession({ rlmSessionDir: join(tempDir, "boundary-active-child") });+ const childBashStarted = deferred<void>();+ const childBashCompletion = deferred<void>();+ const childBash = child.executeBash("child-boundary-gate", undefined, {+ operations: {+ exec: async () => {+ childBashStarted.resolve();+ await childBashCompletion.promise;+ return { exitCode: 0 };+ },+ },+ });+ await childBashStarted.promise;+ const parentBashStarted = deferred<void>();+ const parentBashCompletion = deferred<void>();+ const root = createSession();+ expect(root.registerRlmChildSession("boundary-active-child", child)).toBe(true);+ const originalChildQuiescence = child.waitForRlmQuiescence.bind(child);+ const childWaitStarted = deferred<void>();+ let parentBash: Promise<unknown> | undefined;+ vi.spyOn(child, "waitForRlmQuiescence").mockImplementation(async (signal) => {+ childWaitStarted.resolve();+ await originalChildQuiescence(signal);+ parentBash = root.executeBash("parent-boundary-gate", undefined, {+ operations: {+ exec: async () => {+ parentBashStarted.resolve();+ await parentBashCompletion.promise;+ return { exitCode: 0 };+ },+ },+ });+ });++ const quiescence = root.waitForRlmQuiescence();+ await childWaitStarted.promise;+ childBashCompletion.resolve();+ await childBash;+ const parentBoundaryStarted = await Promise.race([+ parentBashStarted.promise.then(() => true),+ sleep(200).then(() => false),+ ]);+ expect(parentBoundaryStarted).toBe(true);+ const boundary = await Promise.race([+ quiescence.then(() => "quiesced" as const),+ sleep(20).then(() => "active" as const),+ ]);+ expect(boundary).toBe("active");++ parentBashCompletion.resolve();+ await parentBash;+ const finalBoundary = await Promise.race([+ quiescence.then(() => "quiesced" as const),+ sleep(200).then(() => "blocked" as const),+ ]);+ expect(finalBoundary).toBe("quiesced");+ });++ it("propagates root quiescence cancellation into a child self-active waiter", async () => {+ const child = createSession({ rlmSessionDir: join(tempDir, "cancelled-bash-active-child") });+ const bashStarted = deferred<void>();+ const bashCompletion = deferred<void>();+ const operations: BashOperations = {+ exec: async () => {+ bashStarted.resolve();+ await bashCompletion.promise;+ return { exitCode: 0 };+ },+ };+ const bash = child.executeBash("cancelled-gate", undefined, { operations });+ await bashStarted.promise;+ const root = createSession();+ expect(root.registerRlmChildSession("cancelled-bash-active-child", child)).toBe(true);++ const quiescence = root.waitForRlmQuiescence();+ await vi.waitFor(() => expect((child as unknown as InspectableRlmSession)._rlmQuiescenceWaitAborts.size).toBe(1));+ root.requestAbort();+ await expect(quiescence).rejects.toThrow("RLM quiescence wait cancelled");+ expect(child.isBashRunning).toBe(true);+ expect((child as unknown as InspectableRlmSession)._rlmQuiescenceWaitAborts.size).toBe(0);++ bashCompletion.resolve();+ await bash;+ });++ it("cancels sibling recursive waiters when one child quiescence wait fails", async () => {+ const childAStarted = deferred<void>();+ const childACompletion = deferred<void>();+ const childA = createSession({ rlmSessionDir: join(tempDir, "failing-wait-child") });+ const childABash = childA.executeBash("child-a-gate", undefined, {+ operations: {+ exec: async () => {+ childAStarted.resolve();+ await childACompletion.promise;+ return { exitCode: 0 };+ },+ },+ });+ const childBStarted = deferred<void>();+ const childBCompletion = deferred<void>();+ const childB = createSession({ rlmSessionDir: join(tempDir, "sibling-wait-child") });+ const childBBash = childB.executeBash("child-b-gate", undefined, {+ operations: {+ exec: async () => {+ childBStarted.resolve();+ await childBCompletion.promise;+ return { exitCode: 0 };+ },+ },+ });+ await Promise.all([childAStarted.promise, childBStarted.promise]);+ const root = createSession();+ expect(root.registerRlmChildSession("failing-wait-child", childA)).toBe(true);+ expect(root.registerRlmChildSession("sibling-wait-child", childB)).toBe(true);++ const quiescence = root.waitForRlmQuiescence();+ await vi.waitFor(() => {+ expect((childA as unknown as InspectableRlmSession)._rlmQuiescenceWaitAborts.size).toBe(1);+ expect((childB as unknown as InspectableRlmSession)._rlmQuiescenceWaitAborts.size).toBe(1);+ });+ childA.requestAbort();+ await expect(quiescence).rejects.toThrow("RLM quiescence wait cancelled");+ await vi.waitFor(() =>+ expect((childB as unknown as InspectableRlmSession)._rlmQuiescenceWaitAborts.size).toBe(0),+ );+ expect(childB.isBashRunning).toBe(true);++ childACompletion.resolve();+ childBCompletion.resolve();+ await Promise.all([childABash, childBBash]);+ });++ it("durably defers a child terminal notice across ACP-style input pause and scheduler suspension", async () => {+ const childStarted = deferred<void>();+ const childCompletion = deferred<void>();+ const synthesizedAgentMessageSend = vi.fn(async () => ({+ id: "unexpected-synthesized-send",+ source: "agent_message" as const,+ target: { activeSessionId: "parent-active", sessionId: "parent-session" },+ message: "unexpected",+ deliveryStatus: "delivered" as const,+ }));+ const child = createSession({+ rlmSessionDir: join(tempDir, "paused-terminal-child"),+ agentMessageController: {+ listAgents: () => ({ agents: [] }),+ roster: () => ({ current: { name: "child", id: "child", depth: 1 }, entries: [] }),+ sendAgentMessage: synthesizedAgentMessageSend,+ },+ streamFn: (_model, context) => {+ const stream = createAssistantMessageEventStream();+ childStarted.resolve();+ void childCompletion.promise.then(() => {+ stream.push({+ type: "done",+ reason: "stop",+ message: assistantMessage(`child answer: ${userText(context)}`),+ });+ });+ return stream;+ },+ });+ let parentNoticeTurns = 0;+ const root = createSession({+ streamFn: () => {+ parentNoticeTurns++;+ return streamAnswer("parent processed terminal notice");+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: child }),+ deleteRlmSubagentRuntime: async () => {},+ },+ });++ await root.runRlmChild("finish during ACP close", { name: "paused-terminal-worker" });+ await childStarted.promise;+ const inputPause = root.acquireSessionInputPause();+ root.requestAbort();+ await expect(root.prompt("external prompt", { resumeIfIdle: false })).rejects.toThrow(+ "session input admission is paused",+ );++ childCompletion.resolve();+ const internals = root as unknown as InspectableRlmSession;+ const deferredNotices = () =>+ root+ .getPendingNextTurnMessageSnapshots()+ .filter((message) => message.customType === "rlm_child_terminal_notice");+ await vi.waitFor(() => expect(deferredNotices()).toHaveLength(1));+ expect(synthesizedAgentMessageSend).not.toHaveBeenCalled();+ const restartSnapshot = root.getPendingNextTurnMessageSnapshots();+ await vi.waitFor(() => expect(internals._unsettledRlmChildRuns.size).toBe(0));+ expect(root.unfinishedActionCount).toBe(0);+ const closeIdleBoundary = await Promise.race([+ root.waitForIdle().then(() => "idle" as const),+ sleep(50).then(() => "blocked" as const),+ ]);+ expect(closeIdleBoundary).toBe("idle");+ const quiescence = root.waitForRlmQuiescence();+ const strongBoundary = await Promise.race([+ quiescence.then(() => "quiesced" as const),+ sleep(20).then(() => "paused" as const),+ ]);+ expect(strongBoundary).toBe("paused");+ expect(root.clearQueue()).toEqual({ steering: [], followUp: [] });+ expect(deferredNotices()).toHaveLength(1);++ root.resumeQueuedWork();+ await expect(root.waitForIdle()).resolves.toBeUndefined();+ expect(parentNoticeTurns).toBe(0);+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);++ inputPause.release();+ await expect(quiescence).resolves.toBeUndefined();+ expect(parentNoticeTurns).toBe(1);+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(1);++ let restoredNoticeTurns = 0;+ const restored = createSession({+ streamFn: () => {+ restoredNoticeTurns++;+ return streamAnswer("restored parent processed terminal notice");+ },+ });+ restored.restorePendingNextTurnMessages(restartSnapshot);+ await restored.waitForRlmQuiescence();+ expect(restoredNoticeTurns).toBe(1);+ expect(+ restored.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(1);+ root.dispose();+ });++ it("demotes a pre-admitted terminal action when ACP close suspends before delivery", async () => {+ const childStarted = deferred<void>();+ const childCompletion = deferred<void>();+ const child = createSession({+ rlmSessionDir: join(tempDir, "pre-admitted-terminal-child"),+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ childStarted.resolve();+ void childCompletion.promise.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("child finished") });+ });+ return stream;+ },+ });+ let parentNoticeTurns = 0;+ const root = createSession({+ streamFn: () => {+ parentNoticeTurns++;+ return streamAnswer("parent processed pre-admitted terminal notice");+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: child }),+ deleteRlmSubagentRuntime: async () => {},+ },+ });++ await root.runRlmChild("finish before ACP close cut", { name: "pre-admitted-terminal-worker" });+ await childStarted.promise;+ const dispatchGate = vi+ .spyOn(root as unknown as { _scheduleSessionInputPump(): void }, "_scheduleSessionInputPump")+ .mockImplementation(() => {});+ childCompletion.resolve();+ await vi.waitFor(() => expect(root.unfinishedActionCount).toBe(1));+ expect(+ root+ .getPendingNextTurnMessageSnapshots()+ .filter((message) => message.customType === "rlm_child_terminal_notice"),+ ).toHaveLength(0);++ const inputPause = root.acquireSessionInputPause();+ root.requestAbort();+ await vi.waitFor(() => expect(root.unfinishedActionCount).toBe(0));+ expect(+ root+ .getPendingNextTurnMessageSnapshots()+ .filter((message) => message.customType === "rlm_child_terminal_notice"),+ ).toHaveLength(1);+ dispatchGate.mockRestore();+ await expect(root.waitForIdle()).resolves.toBeUndefined();+ expect(root.clearQueue()).toEqual({ steering: [], followUp: [] });++ root.resumeQueuedWork();+ inputPause.release();+ await root.waitForRlmQuiescence();+ expect(parentNoticeTurns).toBe(1);+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(1);+ });++ it("linearizes terminal retention after an update checkpoint snapshot", async () => {+ const childStarted = deferred<void>();+ const childCompletion = deferred<void>();+ const child = createSession({+ rlmSessionDir: join(tempDir, "update-checkpoint-terminal-child"),+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ childStarted.resolve();+ void childCompletion.promise.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("child finished for update") });+ });+ return stream;+ },+ });+ let parentNoticeTurns = 0;+ const root = createSession({+ streamFn: () => {+ parentNoticeTurns++;+ return streamAnswer("parent processed update terminal notice");+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: child }),+ deleteRlmSubagentRuntime: async () => {},+ },+ });++ const spawned = await root.runRlmChild("finish at update snapshot", { name: "update-terminal-worker" });+ await childStarted.promise;+ const updatePause = root.acquireQueuedWorkPause();+ childCompletion.resolve();+ const internals = root as unknown as InspectableRlmSession;+ await vi.waitFor(() => expect(internals._activeRlmChildRuns.get(spawned.rlm_child_id)?.status).toBe("done"));+ await root.waitForSessionInputCheckpoint();+ const pendingSnapshot = root.getPendingNextTurnMessageSnapshots();+ const actionSnapshot = root.getSessionActionRecoverySnapshot();+ expect(pendingSnapshot.filter((message) => message.customType === "rlm_child_terminal_notice")).toHaveLength(0);+ expect(+ actionSnapshot.actions.filter(+ (action) =>+ action.payload.kind === "turn" &&+ action.payload.customMessage?.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);+ expect(internals._unsettledRlmChildRuns.size).toBe(1);+ expect(internals._activeRlmChildRuns.get(spawned.rlm_child_id)?.settled).toBe(false);++ updatePause.release();+ await root.waitForRlmQuiescence();+ expect(parentNoticeTurns).toBe(1);+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(1);+ });++ it("keeps settled error deletion in quiescence through cleanup retry", async () => {+ const child = createSession({ rlmSessionDir: join(tempDir, "settled-error-child") });+ vi.spyOn(child, "promptAndWait").mockRejectedValue(new Error("child prompt failed"));+ const firstCleanup = deferred<void>();+ const retryCleanup = deferred<void>();+ let cleanupAttempts = 0;+ const deleteRlmSubagentRuntime = vi.fn(async (_id: string, session?: AgentSession) => {+ const cleanup = ++cleanupAttempts === 1 ? firstCleanup.promise : retryCleanup.promise;+ await cleanup;+ await session?.disposeAsync();+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: child }),+ releaseRlmSubagentRuntime: async () => {},+ deleteRlmSubagentRuntime,+ },+ });++ const spawned = await root.runRlmChild("fail after startup", { name: "settled-error-worker" });+ const internals = root as unknown as InspectableRlmSession;+ await vi.waitFor(() => expect(internals._activeRlmChildRuns.get(spawned.rlm_child_id)?.settled).toBe(true));+ const run = internals._activeRlmChildRuns.get(spawned.rlm_child_id);+ if (!run) throw new Error("Missing settled error run");+ expect(run.status).toBe("error");+ expect(run.session).toBe(child);+ expect(internals._rlmChildSessions.has(spawned.rlm_child_id)).toBe(false);+ expect(internals._unsettledRlmChildRuns.has(run)).toBe(false);++ await expect(root.deleteRlmSubagent("settled-error-worker")).resolves.toMatchObject({+ subagent: { rlm_child_id: spawned.rlm_child_id },+ });+ await expect(root.deleteRlmSubagent(spawned.rlm_child_id)).resolves.toMatchObject({+ subagent: { rlm_child_id: spawned.rlm_child_id },+ });+ expect(deleteRlmSubagentRuntime).toHaveBeenCalledOnce();+ expect(run.settled).toBe(false);+ expect(internals._unsettledRlmChildRuns.has(run)).toBe(true);+ let quiesced = false;+ const quiescence = root.waitForRlmQuiescence().then(() => {+ quiesced = true;+ });+ await sleep(20);+ expect(quiesced).toBe(false);++ firstCleanup.reject(new Error("first cleanup failed"));+ await waitFor(() => internals._rlmChildCleanupFailures.has(spawned.rlm_child_id));+ await sleep(20);+ expect(quiesced).toBe(false);+ expect(internals._activeRlmChildRuns.has(spawned.rlm_child_id)).toBe(true);+ expect(internals._unsettledRlmChildRuns.has(run)).toBe(true);+ await expect(root.runRlmChild("replacement before retry", { name: "settled-error-worker" })).rejects.toThrow(+ "an agent of that name already exists at depth 1 under this parent",+ );++ await expect(root.deleteRlmSubagent("settled-error-worker")).resolves.toMatchObject({+ subagent: { rlm_child_id: spawned.rlm_child_id },+ });+ await expect(root.deleteRlmSubagent(spawned.rlm_child_id)).resolves.toMatchObject({+ subagent: { rlm_child_id: spawned.rlm_child_id },+ });+ expect(deleteRlmSubagentRuntime).toHaveBeenCalledTimes(2);+ await sleep(20);+ expect(quiesced).toBe(false);++ retryCleanup.resolve();+ await quiescence;+ expect(internals._activeRlmChildRuns.has(spawned.rlm_child_id)).toBe(false);+ expect(internals._unsettledRlmChildRuns.has(run)).toBe(false);+ expect(internals._deletingRlmChildren.has(spawned.rlm_child_id)).toBe(false);+ expect(deleteRlmSubagentRuntime).toHaveBeenCalledTimes(2);+ await expect(+ root.runRlmChild("replacement after cleanup", { name: "settled-error-worker" }),+ ).resolves.toMatchObject({+ name: "settled-error-worker",+ });+ });+it("notifies the runtime host when the initial child task completes", async () => {const child = createSession({ rlmSessionDir: join(tempDir, "host-completion-child") });const completeRlmSubagentRuntime = vi.fn(() => true);@@ -2293,12 +2922,105 @@ describe("AgentSession rlm recursion", () => {expect(promptAndWait).not.toHaveBeenCalled();});- it("does not cancel active rlm children when only the parent turn is interrupted", async () => {- let releaseChild: () => void = () => {};- const release = new Promise<void>((resolve) => {- releaseChild = resolve;+ it("cancels strong quiescence before abandoning children for an update restart", async () => {+ const deferred = () => {+ let resolve!: () => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<void>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ promise.catch(() => undefined);+ return { promise, resolve, reject };+ };+ const child = createSession({ rlmSessionDir: join(tempDir, "update-restart-parent") });+ const childInternals = child as unknown as InspectableRlmSession;+ childInternals._activeRlmChildRuns.set("live-grandchild", {+ id: "live-grandchild",+ prompt: "still working",+ sessionName: "live-grandchild",+ sessionDir: join(tempDir, "live-grandchild"),+ model,+ abort: () => {},+ status: "running",+ settled: false,});- let childStarted = false;+ const root = createSession();+ const rootInternals = root as unknown as InspectableRlmSession;+ const run: InspectableRlmRun = {+ id: "update-restart-parent",+ prompt: "parent work",+ sessionName: "update-restart-parent",+ sessionDir: join(tempDir, "update-restart-parent"),+ model,+ abort: () => {},+ status: "running",+ settled: false,+ publication: deferred(),+ settlement: deferred(),+ session: child,+ };+ rootInternals._activeRlmChildRuns.set(run.id, run);+ rootInternals._unsettledRlmChildRuns.add(run);++ const quiescence = root.waitForRlmQuiescence();+ await Promise.resolve();+ root.abortForUpdateRestart();++ await expect(quiescence).rejects.toThrow("RLM quiescence wait cancelled");+ expect(run.abandonedForQuiescence).toBe(true);+ expect(root.getRlmChildSnapshots()).toEqual(+ expect.arrayContaining([expect.objectContaining({ id: "live-grandchild", status: "running" })]),+ );++ rootInternals._activeRlmChildRuns.clear();+ rootInternals._unsettledRlmChildRuns.clear();+ childInternals._activeRlmChildRuns.clear();+ root.dispose();+ child.dispose();+ });++ it("does not carry an abandoned queued child into the next strong quiescence lifecycle", async () => {+ let releaseStartup: () => void = () => {};+ const startupGate = new Promise<void>((resolve) => {+ releaseStartup = resolve;+ });+ const child = createSession({ rlmSessionDir: join(tempDir, "abandoned-queued-child") });+ const promptAndWait = vi.spyOn(child, "promptAndWait");+ const root = createSession({+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ stream.push({ type: "done", reason: "stop", message: assistantMessage("next lifecycle done") });+ return stream;+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ await startupGate;+ return { session: child };+ },+ deleteRlmSubagentRuntime: async () => {},+ },+ });++ const spawned = await root.runRlmChild("blocked startup");+ root.requestAbort();+ expect(root.cancelRlmChildRun(spawned.rlm_child_id)).toBe(true);+ await expect(root.waitForRlmQuiescence()).resolves.toBeUndefined();+ root.resumeQueuedWork();+ await root.prompt("next lifecycle");+ await expect(root.waitForRlmQuiescence()).resolves.toBeUndefined();++ releaseStartup();+ await waitFor(() => !(root as unknown as InspectableRlmSession)._activeRlmChildRuns.has(spawned.rlm_child_id));+ expect(promptAndWait).not.toHaveBeenCalled();+ });++ it("does not cancel active rlm children when only the parent turn is interrupted", async () => {+ let releaseChild: () => void = () => {};+ const release = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ let childStarted = false;const root = createSession({streamFn: (_model, context) => {const text = userText(context);@@ -2493,64 +3215,423 @@ describe("AgentSession rlm recursion", () => {expect(root.getRlmChildSession(spawned.rlm_child_id)).toBeUndefined();});- it("does not let completion retention resurrect a child being deleted", async () => {- const root = createSession();- const spawned = await root.runRlmChild("fast child", { name: "fast-worker" });- await waitFor(() => root.getRlmChildSession(spawned.rlm_child_id) !== undefined);- await expect(root.deleteRlmSubagent("fast-worker")).resolves.toMatchObject({+ it("aborts an active child tool and settles only after shared runtime cleanup", async () => {+ let toolStarted = false;+ let toolAborted = false;+ const tool = {+ name: "blocking_tool",+ description: "Block until cancellation",+ label: "blocking tool",+ parameters: Type.Object({}),+ execute: async (_toolCallId: string, _params: Record<string, never>, signal: AbortSignal) => {+ toolStarted = true;+ await new Promise<never>((_resolve, reject) => {+ const rejectAborted = () => {+ toolAborted = true;+ reject(new Error("tool aborted"));+ };+ if (signal.aborted) rejectAborted();+ else signal.addEventListener("abort", rejectAborted, { once: true });+ });+ throw new Error("unreachable");+ },+ };+ const hostedChild = createSession({+ customTools: [tool],+ streamFn: (_model, context) => {+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ const hasToolResult = context.messages.some((message) => message.role === "toolResult");+ stream.push({+ type: "done",+ reason: hasToolResult ? "stop" : "toolUse",+ message: hasToolResult+ ? assistantMessage("unexpected completion")+ : {+ ...assistantMessage(""),+ content: [{ type: "toolCall" as const, id: "blocking-1", name: tool.name, arguments: {} }],+ stopReason: "toolUse" as const,+ },+ });+ });+ return stream;+ },+ });+ let releaseCleanup: () => void = () => {};+ const cleanupGate = new Promise<void>((resolve) => {+ releaseCleanup = resolve;+ });+ let cleanupStarted = false;+ const deleteRuntime = vi.fn(async () => {+ cleanupStarted = true;+ await cleanupGate;+ await hostedChild.disposeAsync();+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: deleteRuntime,+ },+ });++ const spawned = await root.runRlmChild("use the blocking tool", { name: "tool-worker" });+ await waitFor(() => toolStarted);+ const firstDeletion = root.deleteRlmSubagent("tool-worker");+ const repeatedDeletion = root.deleteRlmSubagent(spawned.rlm_child_id);+ await expect(firstDeletion).resolves.toMatchObject({ subagent: { rlm_child_id: spawned.rlm_child_id } });+ await expect(repeatedDeletion).resolves.toMatchObject({ subagent: { rlm_child_id: spawned.rlm_child_id } });+ await waitFor(() => toolAborted && cleanupStarted);+ expect(deleteRuntime).toHaveBeenCalledOnce();++ let quiesced = false;+ const quiescence = root.waitForRlmQuiescence().then(() => {+ quiesced = true;+ });+ await sleep(20);+ expect(quiesced).toBe(false);+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);++ releaseCleanup();+ await quiescence;+ expect(deleteRuntime).toHaveBeenCalledOnce();+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toEqual([+ expect.objectContaining({+ details: expect.objectContaining({ kind: "cancelled", reason: "Deleted by parent orchestrator" }),+ }),+ ]);+ });++ it("admits a private durable deletion notice only after runtime cleanup", async () => {+ let releaseChild: () => void = () => {};+ const childGate = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ let childStarted = false;+ let cleanupSucceeded = false;+ const sendAgentMessage = vi.fn(async () => {+ expect(cleanupSucceeded).toBe(true);+ return {+ id: "agentmsg-deletion-complete",+ source: "agent_message" as const,+ target: { activeSessionId: "parent-active", sessionId: "parent-session" },+ message: "deleted",+ deliveryStatus: "delivered" as const,+ };+ });+ const hostedChild = createSession({+ agentMessageController: {+ listAgents: () => ({+ current: { activeSessionId: "child-active", sessionId: "child-session" },+ agents: [],+ }),+ sendAgentMessage,+ },+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ childStarted = true;+ void childGate.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("child stopped") });+ });+ return stream;+ },+ });+ vi.spyOn(hostedChild, "abort").mockResolvedValue();+ let releaseCleanup: () => void = () => {};+ const cleanupGate = new Promise<void>((resolve) => {+ releaseCleanup = resolve;+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: () => cleanupGate,+ },+ });++ const spawned = await root.runRlmChild("controller ordering", { name: "controller-worker" });+ await waitFor(() => childStarted);+ await root.deleteRlmSubagent(spawned.rlm_child_id);+ releaseChild();+ await sleep(20);+ expect(sendAgentMessage).not.toHaveBeenCalled();+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);++ cleanupSucceeded = true;+ releaseCleanup();+ await root.waitForRlmQuiescence();+ expect(sendAgentMessage).not.toHaveBeenCalled();+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toEqual([+ expect.objectContaining({+ content: expect.stringContaining("was cancelled: Deleted by parent orchestrator"),+ }),+ ]);+ });++ it("preserves failed cleanup retry across transient preflight failure before abort-insensitive unwind", async () => {+ const { child: hostedChild, completion: childCompletion, hasStarted } = createAbortInsensitiveChild();+ const retryCleanup = deferred<void>();+ let cleanupAttempts = 0;+ let failNextDeletePreflight = false;+ const root = createSession({+ agentMessageController: {+ listAgents: async () => {+ if (failNextDeletePreflight) {+ failNextDeletePreflight = false;+ throw new Error("delete preflight failed");+ }+ return {+ current: { activeSessionId: "parent-active", sessionId: "parent-session" },+ agents: [],+ };+ },+ sendAgentMessage: async () => {+ throw new Error("unexpected direct send");+ },+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: () => {+ if (++cleanupAttempts === 1) throw new Error("cleanup failed synchronously");+ return retryCleanup.promise;+ },+ },+ });++ const spawned = await root.runRlmChild("abort-insensitive cleanup retry", { name: "retry-worker" });+ await waitFor(hasStarted);+ await expect(root.deleteRlmSubagent(spawned.rlm_child_id)).resolves.toMatchObject({subagent: { rlm_child_id: spawned.rlm_child_id },});- expect(await root.listRlmSubagents()).toEqual({ subagents: [] });- await Promise.resolve();- expect(root.getRlmChildSession(spawned.rlm_child_id)).toBeUndefined();+ const internals = root as unknown as InspectableRlmSession;+ await waitFor(() => internals._rlmChildCleanupFailures.size === 1);+ const failureContent = await vi.waitFor(() => {+ const notice = root.messages.find(+ (message) => message.role === "custom" && message.customType === "rlm_child_failure",+ );+ if (!notice || notice.role !== "custom") throw new Error("Missing cleanup failure notice");+ return notice.content;+ });+ expect(failureContent).toEqual(expect.stringContaining("Deletion cleanup failed"));+ expect(failureContent).toEqual(expect.stringMatching(/retry/i));++ failNextDeletePreflight = true;+ await expect(root.deleteRlmSubagent("retry-worker")).rejects.toThrow("delete preflight failed");+ expect(cleanupAttempts).toBe(1);++ await expect(root.deleteRlmSubagent("retry-worker")).resolves.toMatchObject({+ subagent: { rlm_child_id: spawned.rlm_child_id },+ });+ expect(cleanupAttempts).toBe(2);+ let quiesced = false;+ const quiescence = root.waitForRlmQuiescence().then(() => {+ quiesced = true;+ });+ retryCleanup.resolve();+ await sleep(20);+ expect(quiesced).toBe(false);++ childCompletion.resolve();+ await quiescence;+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(1);+ expect(internals._rlmChildCleanupFailures.size).toBe(0);+ await expect(root.runRlmChild("replacement", { name: "retry-worker" })).resolves.toMatchObject({+ name: "retry-worker",+ });+ });++ it("settles a pre-existing deletion cleanup failure during parent disposal", async () => {+ const { child: hostedChild, completion: childCompletion, hasStarted } = createAbortInsensitiveChild();+ const disposeHostedChild = vi.spyOn(hostedChild, "disposeAsync");+ const deleteRuntime = vi.fn(() => Promise.reject(new Error("cleanup failed before dispose")));+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: deleteRuntime,+ },+ });++ const spawned = await root.runRlmChild("pre-failed cleanup disposal", { name: "pre-failed-worker" });+ await waitFor(hasStarted);+ await root.deleteRlmSubagent(spawned.rlm_child_id);+ const internals = root as unknown as InspectableRlmSession;+ const run = internals._activeRlmChildRuns.get(spawned.rlm_child_id);+ if (!run) throw new Error("Missing deleting run");+ await waitFor(() => internals._rlmChildCleanupFailures.size === 1);++ await root.disposeAsync();+ expect(deleteRuntime).toHaveBeenCalledOnce();+ expect(disposeHostedChild).toHaveBeenCalled();+ expect(internals._activeRlmChildRuns.has(spawned.rlm_child_id)).toBe(false);+ expect(internals._unsettledRlmChildRuns.has(run)).toBe(false);+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);+ childCompletion.resolve();+ });++ it("settles disposal after cleanup succeeds without waiting for abort-insensitive task unwind", async () => {+ const { child: hostedChild, completion: childCompletion, hasStarted } = createAbortInsensitiveChild();+ const cleanup = deferred<void>();+ const deleteRuntime = vi.fn(() => cleanup.promise);+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: deleteRuntime,+ },+ });++ const spawned = await root.runRlmChild("successful cleanup disposal", { name: "dispose-success-worker" });+ await waitFor(hasStarted);+ await root.deleteRlmSubagent(spawned.rlm_child_id);+ const internals = root as unknown as InspectableRlmSession;+ const run = internals._activeRlmChildRuns.get(spawned.rlm_child_id);+ if (!run) throw new Error("Missing deleting run");++ const disposal = root.disposeAsync();+ await waitFor(() => internals._disposing);+ cleanup.resolve();+ await disposal;+ expect(deleteRuntime).toHaveBeenCalledOnce();+ expect(internals._activeRlmChildRuns.has(spawned.rlm_child_id)).toBe(false);+ expect(internals._unsettledRlmChildRuns.has(run)).toBe(false);+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);+ childCompletion.resolve();+ });++ it("settles and suppresses notices when deletion cleanup fails during parent disposal", async () => {+ const { child: hostedChild, completion: childCompletion, hasStarted } = createAbortInsensitiveChild();+ const disposeHostedChild = vi.spyOn(hostedChild, "disposeAsync");+ const cleanup = deferred<void>();+ const deleteRuntime = vi.fn(() => cleanup.promise);+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: deleteRuntime,+ },+ });++ const spawned = await root.runRlmChild("dispose during failed cleanup", { name: "dispose-worker" });+ await waitFor(hasStarted);+ await root.deleteRlmSubagent(spawned.rlm_child_id);+ const internals = root as unknown as InspectableRlmSession;+ const run = internals._activeRlmChildRuns.get(spawned.rlm_child_id);+ if (!run) throw new Error("Missing deleting run");++ const disposal = root.disposeAsync();+ await waitFor(() => internals._disposing);+ cleanup.reject(new Error("cleanup failed during dispose"));+ childCompletion.resolve();+ await disposal;+ expect(deleteRuntime).toHaveBeenCalledOnce();+ expect(disposeHostedChild).toHaveBeenCalled();+ expect(internals._activeRlmChildRuns.has(spawned.rlm_child_id)).toBe(false);+ expect(internals._unsettledRlmChildRuns.has(run)).toBe(false);+ expect(+ root.messages.filter(+ (message) =>+ message.role === "custom" &&+ (message.customType === "rlm_child_failure" || message.customType === "rlm_child_terminal_notice"),+ ),+ ).toHaveLength(0);});- it("reconciles failed-delete tracking when the detached retry succeeds", async () => {+ it("keeps deleted live runs in the RLM quiescence barrier until settlement", async () => {let releaseChild: () => void = () => {};const release = new Promise<void>((resolve) => {releaseChild = resolve;});let childStarted = false;- let deleteAttempts = 0;const hostedChild = createSession({- rlmSessionDir: join(tempDir, "detached-retry-child"),- streamFn: (_model, context) => {+ rlmSessionDir: join(tempDir, "deleted-live-child"),+ streamFn: () => {const stream = createAssistantMessageEventStream();childStarted = true;void release.then(() => {- stream.push({- type: "done",- reason: "stop",- message: assistantMessage(`child answer: ${userText(context)}`),- });+ stream.push({ type: "done", reason: "stop", message: assistantMessage("child stopped") });});return stream;},});+ vi.spyOn(hostedChild, "abort").mockResolvedValue();const root = createSession({+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ stream.push({ type: "done", reason: "stop", message: assistantMessage("parent acknowledged") });+ return stream;+ },subagentRuntimeHost: {createRlmSubagentRuntime: async () => ({ session: hostedChild }),- deleteRlmSubagentRuntime: async (_id, session) => {- if (++deleteAttempts === 1) throw new Error("first close failed");- await session?.disposeAsync();- },+ deleteRlmSubagentRuntime: async () => {},},});- await root.runRlmChild("slow retry shard", { name: "retry-worker" });+ const spawned = await root.runRlmChild("slow child", { name: "deleted-live-worker" });await waitFor(() => childStarted);- await expect(root.deleteRlmSubagent("retry-worker")).rejects.toThrow("first close failed");- const internals = root as unknown as InspectableRlmSession;- expect(internals._rlmChildCleanupFailures.size).toBe(1);+ let quiesced = false;+ const quiescence = root.waitForRlmQuiescence().then(() => {+ quiesced = true;+ });+ await root.deleteRlmSubagent(spawned.rlm_child_id);+ await sleep(20);+ expect(quiesced).toBe(false);+releaseChild();+ await quiescence;+ expect(quiesced).toBe(true);+ });- await waitFor(() => deleteAttempts === 2);- await waitFor(() => internals._rlmChildCleanupFailures.size === 0);- expect(internals._rlmChildSessions.size).toBe(0);- expect(internals._rlmChildUnsubscribes.size).toBe(0);- await expect(root.runRlmChild("replacement", { name: "retry-worker" })).resolves.toMatchObject({- name: "retry-worker",+ it("does not add a cancellation notice when deletion races a durably admitted completion notice", async () => {+ const root = createSession();+ const dispatchGate = vi+ .spyOn(root as unknown as { _scheduleSessionInputPump(): void }, "_scheduleSessionInputPump")+ .mockImplementation(() => {});+ const spawned = await root.runRlmChild("fast child", { name: "fast-worker" });+ const internals = root as unknown as InspectableRlmSession;+ await waitFor(+ () =>+ root.getRlmChildSession(spawned.rlm_child_id) !== undefined &&+ !internals._activeRlmChildRuns.has(spawned.rlm_child_id),+ );+ expect(root.unfinishedActionCount).toBe(1);++ await expect(root.deleteRlmSubagent("fast-worker")).resolves.toMatchObject({+ subagent: { rlm_child_id: spawned.rlm_child_id },});+ dispatchGate.mockRestore();+ await root.waitForRlmQuiescence();+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(root.getRlmChildSession(spawned.rlm_child_id)).toBeUndefined();+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toEqual([expect.objectContaining({ details: expect.objectContaining({ kind: "completed_without_reply" }) })]);+ expect(internals._activeRlmChildRuns.has(spawned.rlm_child_id)).toBe(false);});it("keeps failed closure retryable without hanging or late resurrection", async () => {@@ -2597,11 +3678,7 @@ describe("AgentSession rlm recursion", () => {expect(internals._rlmChildCleanupFailures.size).toBe(0);});- it("reserves an errored startup name while its detached failure injection settles", async () => {- let releaseFailureInjection: () => void = () => {};- const failureInjectionGate = new Promise<void>((resolve) => {- releaseFailureInjection = resolve;- });+ it("keeps an errored startup deletable after its failure notice is durably admitted", async () => {const root = createSession({subagentRuntimeHost: {createRlmSubagentRuntime: async () => {@@ -2610,24 +3687,19 @@ describe("AgentSession rlm recursion", () => {deleteRlmSubagentRuntime: async () => undefined,},});- const promptInjectedMessage = vi.fn(async () => failureInjectionGate);- (root as unknown as { _promptInjectedMessage: typeof promptInjectedMessage })._promptInjectedMessage =- promptInjectedMessage;await root.runRlmChild("failing startup", { name: "failed-worker" });- await waitFor(() => promptInjectedMessage.mock.calls.length === 1);+ await vi.waitFor(async () => {+ expect((await root.listRlmSubagents()).subagents[0]).toMatchObject({+ session_name: "failed-worker",+ status: "error",+ });+ });const failed = (await root.listRlmSubagents()).subagents[0];- expect(failed).toMatchObject({ session_name: "failed-worker", status: "error" });await expect(root.deleteRlmSubagent("failed-worker")).resolves.toEqual({ subagent: failed });const internals = root as unknown as InspectableRlmSession;- expect(internals._activeRlmChildRuns.size).toBe(1);+ expect(internals._activeRlmChildRuns.size).toBe(0);expect(await root.listRlmSubagents()).toEqual({ subagents: [] });- await expect(root.runRlmChild("replacement", { name: "failed-worker" })).rejects.toThrow(- "an agent of that name already exists at depth 1 under this parent",- );-- releaseFailureInjection();- await waitFor(() => !internals._activeRlmChildRuns.has(failed?.rlm_child_id ?? ""));await expect(root.runRlmChild("replacement", { name: "failed-worker" })).resolves.toMatchObject({name: "failed-worker",});@@ -2749,12 +3821,13 @@ describe("AgentSession rlm recursion", () => {expect(disposeHostedChild).not.toHaveBeenCalled();await root.deleteRlmSubagent("starting-worker");+ await root.waitForRlmQuiescence();expect(deleteRuntime).toHaveBeenCalledTimes(2);expect(disposeHostedChild).toHaveBeenCalledOnce();expect(internals._rlmChildCleanupFailures.size).toBe(0);});- it("deletes a running direct child by name and waits for runtime cleanup", async () => {+ it("accepts deletion of a running direct child without waiting for task unwind", async () => {let releaseChild: () => void = () => {};const release = new Promise<void>((resolve) => {releaseChild = resolve;@@ -2778,13 +3851,9 @@ describe("AgentSession rlm recursion", () => {if (!running) {throw new Error("Missing running child registry entry");}- const deletion = root.deleteRlmSubagent("slow-worker");- const duplicateDeletion = root.deleteRlmSubagent(running.rlm_child_id);+ await expect(root.deleteRlmSubagent("slow-worker")).resolves.toEqual({ subagent: running });expect(await root.listRlmSubagents()).toEqual({ subagents: [] });- await expect(deletion).resolves.toEqual({ subagent: running });- await expect(duplicateDeletion).resolves.toEqual({ subagent: running });releaseChild();- expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});it("deletes an inactive nested RLM child through the root session", async () => {@@ -2870,6 +3939,8 @@ describe("AgentSession rlm recursion", () => {void nestedRelease.then(() => {stream.push({ type: "done", reason: "stop", message: assistantMessage(`child answer: ${text}`) });});+ } else {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("cancellation acknowledged") });}return stream;},diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.tsindex d7eb8acf4a..809d0c50fa 100644--- a/packages/coding-agent/test/daemon-protocol.test.ts+++ b/packages/coding-agent/test/daemon-protocol.test.ts@@ -21,8 +21,59 @@ import {isDaemonMutatingCommand,salvageDaemonCommandId,} from "../src/modes/daemon/daemon-protocol.js";+import {+ type DaemonWorkerDescriptor,+ durableDaemonWorkerDescriptor,+} from "../src/modes/daemon/daemon-worker-protocol.js";describe("daemon protocol helpers", () => {+ it("serializes worker descriptors as identity-only version 2 state", () => {+ const descriptor = {+ version: 1,+ workerId: "worker",+ pid: 123,+ processStartId: "process-start",+ socketPath: "/tmp/worker.sock",+ recoveryJournalPath: "/state/recovery.jsonl",+ orphanProcessJournalPath: "/state/orphans.jsonl",+ supervisorSocketPath: "/tmp/supervisor.sock",+ authenticationToken: "local-worker-token",+ rootActiveSessionId: "active",+ sessionFile: "/sessions/root.jsonl",+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ lifecycle: "ready",+ createCommand: {+ type: "create",+ sessionPath: "/sessions/root.jsonl",+ config: {+ sessionDir: "/legacy/sessions",+ telemetryDisabled: true,+ apiKey: "secret-api-key",+ extensionFlagValues: { providerSecretKey: "secret-extension" },+ },+ env: { PROVIDER_TOKEN: "secret-client-env" },+ launchEnv: { PROVIDER_TOKEN: "secret-launch-env" },+ runtimeMetadata: { parentActiveSessionId: "secret-runtime" },+ },+ launchEnv: { PROVIDER_TOKEN: "secret-top-level-env" },+ consecutiveFailures: 0,+ lastError: "secret-error",+ } as unknown as DaemonWorkerDescriptor;++ const durable = durableDaemonWorkerDescriptor(descriptor);++ expect(durable.version).toBe(2);+ expect(durable.createCommand).toEqual({ type: "create", sessionPath: "/sessions/root.jsonl" });+ expect(durable).toMatchObject({+ workerId: "worker",+ sessionFile: "/sessions/root.jsonl",+ sessionDir: "/legacy/sessions",+ telemetryDisabled: true,+ });+ expect(JSON.stringify(durable)).not.toContain("secret-");+ });+it("keeps the advertised schema identity synchronized with wire type shapes", () => {const source = readFileSync(resolve(__dirname, "../src/modes/daemon/daemon-protocol.ts"), "utf8");const commandSource = source.slice(@@ -121,6 +172,59 @@ describe("daemon protocol helpers", () => {).toEqual([{ minProtocol: 7, minSchemaRevision: 14 }, { minProtocol: 7 }]);});+ it("capability-gates authoritative rosters and transient owned-session recovery context", () => {+ expect(DAEMON_COMMAND_COMPATIBILITY.get_rlm_children).toEqual({+ minProtocol: 7,+ minSchemaRevision: 17,+ capability: "authoritative_child_roster",+ });+ expect(+ getDaemonCommandCompatibilities({+ type: "attach",+ activeSessionId: "active-1",+ recoveryConfig: { cwd: "/tmp/fresh-owner" },+ }),+ ).toEqual([+ { minProtocol: 7, minSchemaRevision: 17, capability: "owned_session_recovery_context" },+ { minProtocol: 7 },+ ]);+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toEqual(+ expect.arrayContaining([+ "authoritative_child_roster",+ "owned_session_recovery_context",+ "rlm_quiescence_barrier",+ ]),+ );+ });++ it("gates the opt-in RLM quiescence wire field", () => {+ expect(+ getDaemonCommandCompatibilities({+ type: "wait_for_headless_completion",+ activeSessionId: "active-1",+ waitForRlmQuiescence: true,+ }),+ ).toEqual([{ minProtocol: 7, minSchemaRevision: 18, capability: "rlm_quiescence_barrier" }, { minProtocol: 7 }]);+ expect(+ getDaemonCommandCompatibilities({+ type: "wait_for_headless_completion",+ activeSessionId: "active-1",+ }),+ ).toEqual([{ minProtocol: 7 }]);+ });++ it("capability- and schema-gates session input pause leases", () => {+ expect(DAEMON_COMMAND_COMPATIBILITY.acquire_session_input_pause).toEqual({+ minProtocol: 7,+ minSchemaRevision: 19,+ capability: "session_input_pause",+ });+ expect(DAEMON_COMMAND_COMPATIBILITY.release_session_input_pause).toEqual(+ DAEMON_COMMAND_COMPATIBILITY.acquire_session_input_pause,+ );+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("session_input_pause");+ });+it("version- and capability-gates prompt admission cancellation", () => {expect(DAEMON_COMMAND_COMPATIBILITY.cancel_prompt_admission).toEqual({minProtocol: 7,diff --git a/packages/coding-agent/test/daemon-supervisor-admission.test.ts b/packages/coding-agent/test/daemon-supervisor-admission.test.tsindex 770910275b..842681c490 100644--- a/packages/coding-agent/test/daemon-supervisor-admission.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-admission.test.ts@@ -75,8 +75,12 @@ function createHarness(},workers: new Map(),clients: new Set(),+ connectionIds: new WeakMap(),+ sessionInputPauseEpochs: new WeakMap(),+ detachingInputPauseSessions: new WeakMap(),protocolClientIds: new WeakMap(),promptAdmissions: new Map(),+ sessionInputPauses: new Map(),mutationDrain: new MutationDrainLatch(),commandJournal: options.commandJournal ?? {lookup: vi.fn(() => undefined),diff --git a/packages/coding-agent/test/daemon-supervisor-eviction.test.ts b/packages/coding-agent/test/daemon-supervisor-eviction.test.tsindex 6b2542444f..6611372dda 100644--- a/packages/coding-agent/test/daemon-supervisor-eviction.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-eviction.test.ts@@ -309,7 +309,7 @@ describe("daemon supervisor whole-tree eviction", () => {const supervisor = makeSupervisor();const sourceSummary = makeSummary("source-active", now, { sessionId: "source-session" });const source = makeWorker("source", [sourceSummary]);- source.descriptor.createCommand.config = { sessionDir: "/tmp/custom-sessions" };+ Object.assign(source.descriptor, { sessionDir: "/tmp/custom-sessions" });source.summaries = new Map([["source-active", sourceSummary]]);const targetSummary = makeSummary("target-active", now, {sessionId: "target-session",diff --git a/packages/coding-agent/test/daemon-supervisor-input-pause.test.ts b/packages/coding-agent/test/daemon-supervisor-input-pause.test.tsnew file mode 100644index 0000000000..3e7c45466b--- /dev/null+++ b/packages/coding-agent/test/daemon-supervisor-input-pause.test.ts@@ -0,0 +1,335 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { DaemonCommand, DaemonResponse } from "../src/modes/daemon/daemon-protocol.js";+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";++type ClientFixture = {+ id: string;+ socket: { destroy: ReturnType<typeof vi.fn> };+ attachedActiveSessionIds: Set<string>;+ capabilities: Set<string>;+};++type WorkerFixture = {+ descriptor: { workerId: string };+ client?: { close: ReturnType<typeof vi.fn> };+};++type PauseEntry = { owner: ClientFixture; worker: WorkerFixture; pauseId: string };++type SupervisorInternals = {+ clients: Set<ClientFixture>;+ workers: Map<string, WorkerFixture>;+ connectionIds: WeakMap<ClientFixture, string>;+ protocolClientIds: WeakMap<ClientFixture, string>;+ sessionInputPauseEpochs: WeakMap<ClientFixture, number>;+ detachingInputPauseSessions: WeakMap<ClientFixture, Set<string>>;+ sessionInputPauses: Map<string, PauseEntry>;+ findWorkerForClient: ReturnType<typeof vi.fn>;+ forwardToWorker: ReturnType<typeof vi.fn>;+ attachClient: ReturnType<typeof vi.fn>;+ reserveSnapshotStream: ReturnType<typeof vi.fn>;+ write: ReturnType<typeof vi.fn>;+ detachClient: ReturnType<typeof vi.fn>;+ handleCommand(client: ClientFixture, command: DaemonCommand): Promise<DaemonResponse | undefined>;+ invalidateWorkerSessionInputPauses(worker: WorkerFixture, reason: string): void;+ handleWorkerClose(worker: WorkerFixture, client: { close: ReturnType<typeof vi.fn> }, error: Error): Promise<void>;+};++const tempDirs: string[] = [];++afterEach(() => {+ for (const directory of tempDirs.splice(0)) rmSync(directory, { recursive: true, force: true });+});++function createHarness() {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-input-pause-"));+ tempDirs.push(directory);+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorInternals;+ const worker: WorkerFixture = { descriptor: { workerId: "worker-1" }, client: { close: vi.fn() } };+ supervisor.workers.set(worker.descriptor.workerId, worker);+ supervisor.findWorkerForClient = vi.fn(async () => ({+ worker,+ summary: { id: "active-1", activeSessionId: "active-1" },+ }));+ let pauseSequence = 0;+ supervisor.forwardToWorker = vi.fn(async (_worker: WorkerFixture, command: DaemonCommand) => {+ if (command.type === "acquire_session_input_pause") {+ pauseSequence++;+ return {+ type: "response",+ command: command.type,+ success: true,+ data: { pauseId: `pause-${pauseSequence}` },+ } satisfies DaemonResponse;+ }+ return { type: "response", command: command.type, success: true } satisfies DaemonResponse;+ });+ supervisor.attachClient = vi.fn(async () => ({ worker, result: { activeSessionId: "active-1" } }));+ supervisor.reserveSnapshotStream = vi.fn(() => vi.fn());+ supervisor.write = vi.fn();+ supervisor.detachClient = vi.fn((client: ClientFixture, activeSessionId?: string) => {+ if (activeSessionId) client.attachedActiveSessionIds.delete(activeSessionId);+ else client.attachedActiveSessionIds.clear();+ });+ supervisor.handleWorkerClose = vi.fn(async (closedWorker: WorkerFixture, workerClient, error: Error) => {+ if (closedWorker.client !== workerClient) return;+ closedWorker.client = undefined;+ supervisor.invalidateWorkerSessionInputPauses(closedWorker, error.message);+ });+ return { supervisor, worker };+}++function addClient(supervisor: SupervisorInternals, socketId: string, protocolId: string): ClientFixture {+ const client = {+ id: protocolId,+ socket: { destroy: vi.fn() },+ attachedActiveSessionIds: new Set(["active-1"]),+ capabilities: new Set<string>(),+ };+ supervisor.clients.add(client);+ supervisor.connectionIds.set(client, socketId);+ supervisor.protocolClientIds.set(client, protocolId);+ supervisor.sessionInputPauseEpochs.set(client, 0);+ supervisor.detachingInputPauseSessions.set(client, new Set());+ return client;+}++function acquireCommand(id: string): DaemonCommand {+ return { id, type: "acquire_session_input_pause", activeSessionId: "active-1", leaseKey: "shared-key" };+}++describe("daemon supervisor session input pause ownership", () => {+ it("keeps identical public lease keys independent across client sockets", async () => {+ const { supervisor } = createHarness();+ const first = addClient(supervisor, "socket-a", "protocol-a");+ const second = addClient(supervisor, "socket-b", "protocol-b");++ const firstResponse = await supervisor.handleCommand(first, acquireCommand("acquire-a"));+ const secondResponse = await supervisor.handleCommand(second, acquireCommand("acquire-b"));+ expect(firstResponse).toMatchObject({ success: true, data: { pauseId: "pause-1" } });+ expect(secondResponse).toMatchObject({ success: true, data: { pauseId: "pause-2" } });+ expect(+ supervisor.forwardToWorker.mock.calls+ .map((call) => call[1] as DaemonCommand)+ .filter((command) => command.type === "acquire_session_input_pause")+ .map((command) => command.leaseKey),+ ).toEqual([+ JSON.stringify(["socket-a", "protocol-a", "shared-key"]),+ JSON.stringify(["socket-b", "protocol-b", "shared-key"]),+ ]);++ await supervisor.handleCommand(first, {+ id: "release-a",+ type: "release_session_input_pause",+ activeSessionId: "active-1",+ pauseId: "pause-1",+ });+ expect(supervisor.sessionInputPauses.has("pause-1")).toBe(false);+ expect(supervisor.sessionInputPauses.has("pause-2")).toBe(true);+ });++ it("clears stable and live detach selectors after reattach", async () => {+ const { supervisor } = createHarness();+ const client = addClient(supervisor, "socket-a", "protocol-a");+ const detachingSessions = supervisor.detachingInputPauseSessions.get(client)!;+ detachingSessions.add("stable-id");++ await supervisor.handleCommand(client, {+ id: "reattach",+ type: "reattach",+ activeSessionId: "old-active",+ targetActiveSessionId: "stable-id",+ });++ expect(detachingSessions.has("stable-id")).toBe(false);+ await expect(+ supervisor.handleCommand(client, {+ id: "acquire",+ type: "acquire_session_input_pause",+ activeSessionId: "stable-id",+ leaseKey: "shared-key",+ }),+ ).resolves.toMatchObject({ success: true, data: { pauseId: "pause-1" } });+ });++ it("reacquires a fresh worker pause while the prior pause is releasing", async () => {+ const { supervisor } = createHarness();+ const client = addClient(supervisor, "socket-a", "protocol-a");+ await supervisor.handleCommand(client, acquireCommand("acquire-1"));+ let finishRelease!: () => void;+ const releaseGate = new Promise<void>((resolve) => {+ finishRelease = resolve;+ });+ supervisor.forwardToWorker.mockImplementationOnce(async (_worker: WorkerFixture, command: DaemonCommand) => {+ await releaseGate;+ return { type: "response", command: command.type, success: true } satisfies DaemonResponse;+ });++ const release = supervisor.handleCommand(client, {+ id: "release-1",+ type: "release_session_input_pause",+ activeSessionId: "active-1",+ pauseId: "pause-1",+ });+ const reacquired = await supervisor.handleCommand(client, acquireCommand("acquire-2"));+ expect(reacquired).toMatchObject({ success: true, data: { pauseId: "pause-2" } });++ finishRelease();+ await release;+ expect(supervisor.sessionInputPauses.has("pause-1")).toBe(false);+ expect(supervisor.sessionInputPauses.has("pause-2")).toBe(true);+ });++ it("deduplicates retries and releases the client lease on detach", async () => {+ const { supervisor } = createHarness();+ const client = addClient(supervisor, "socket-a", "protocol-a");++ const first = await supervisor.handleCommand(client, acquireCommand("acquire-1"));+ const retry = await supervisor.handleCommand(client, acquireCommand("acquire-2"));+ expect(first).toMatchObject({ success: true, data: { pauseId: "pause-1" } });+ expect(retry).toMatchObject({ success: true, data: { pauseId: "pause-1" } });+ expect(+ supervisor.forwardToWorker.mock.calls.filter(+ (call) => (call[1] as DaemonCommand).type === "acquire_session_input_pause",+ ),+ ).toHaveLength(1);++ await supervisor.handleCommand(client, { id: "detach", type: "detach", activeSessionId: "active-1" });+ expect(supervisor.sessionInputPauses.size).toBe(0);+ expect(supervisor.detachClient).toHaveBeenCalledWith(client, "active-1");+ const releaseCalls = supervisor.forwardToWorker.mock.calls.filter(+ (call) => (call[1] as DaemonCommand).type === "release_session_input_pause",+ );+ expect(releaseCalls).toHaveLength(1);+ expect(releaseCalls[0]?.[2]).toBe(5_000);+ });++ it("blocks new acquisitions before detach waits for cleanup", async () => {+ const { supervisor } = createHarness();+ const client = addClient(supervisor, "socket-a", "protocol-a");+ await supervisor.handleCommand(client, acquireCommand("acquire"));+ let releaseCleanup!: () => void;+ const cleanupGate = new Promise<void>((resolve) => {+ releaseCleanup = resolve;+ });+ supervisor.forwardToWorker.mockImplementationOnce(async (_worker: WorkerFixture, command: DaemonCommand) => {+ await cleanupGate;+ return { type: "response", command: command.type, success: true } as DaemonResponse;+ });++ const detach = supervisor.handleCommand(client, {+ id: "detach",+ type: "detach",+ activeSessionId: "active-1",+ });+ await vi.waitFor(() => expect(supervisor.detachClient).toHaveBeenCalledWith(client, "active-1"));+ await expect(supervisor.handleCommand(client, acquireCommand("late-acquire"))).rejects.toThrow(+ "Session is detaching",+ );+ releaseCleanup();+ await expect(detach).resolves.toMatchObject({ success: true });+ expect(supervisor.sessionInputPauses.size).toBe(0);+ });++ it("fails closed for every owner when detach cannot release the worker pause", async () => {+ const { supervisor, worker } = createHarness();+ const client = addClient(supervisor, "socket-a", "protocol-a");+ const other = addClient(supervisor, "socket-b", "protocol-b");+ await supervisor.handleCommand(client, acquireCommand("acquire-a"));+ await supervisor.handleCommand(other, acquireCommand("acquire-b"));+ supervisor.forwardToWorker.mockRejectedValueOnce(new Error("worker unavailable"));++ await expect(+ supervisor.handleCommand(client, { id: "detach", type: "detach", activeSessionId: "active-1" }),+ ).rejects.toThrow("worker unavailable");+ expect(supervisor.sessionInputPauses.size).toBe(0);+ expect(supervisor.handleWorkerClose).toHaveBeenCalledTimes(1);+ expect(worker.client).toBeUndefined();+ expect(client.socket.destroy).toHaveBeenCalled();+ expect(other.socket.destroy).toHaveBeenCalled();+ });++ it("releases all client pauses when detach omits a session id", async () => {+ const { supervisor } = createHarness();+ const client = addClient(supervisor, "socket-a", "protocol-a");+ await supervisor.handleCommand(client, acquireCommand("acquire"));++ await supervisor.handleCommand(client, { id: "detach-all", type: "detach" });++ expect(supervisor.sessionInputPauses.size).toBe(0);+ expect(client.attachedActiveSessionIds.size).toBe(0);+ expect(supervisor.detachClient).toHaveBeenCalledWith(client, undefined);+ });++ it("rejects release from a different public client", async () => {+ const { supervisor } = createHarness();+ const owner = addClient(supervisor, "socket-a", "protocol-a");+ const other = addClient(supervisor, "socket-b", "protocol-b");+ await supervisor.handleCommand(owner, acquireCommand("acquire"));++ await expect(+ supervisor.handleCommand(other, {+ id: "release",+ type: "release_session_input_pause",+ activeSessionId: "active-1",+ pauseId: "pause-1",+ }),+ ).rejects.toThrow("owned by another client");+ });++ it("invalidates every public owner when the worker connection closes", async () => {+ const { supervisor, worker } = createHarness();+ const first = addClient(supervisor, "socket-a", "protocol-a");+ const second = addClient(supervisor, "socket-b", "protocol-b");+ await supervisor.handleCommand(first, acquireCommand("acquire-a"));+ await supervisor.handleCommand(second, acquireCommand("acquire-b"));++ supervisor.invalidateWorkerSessionInputPauses(worker, "worker pause invalidated");++ expect(supervisor.sessionInputPauses.size).toBe(0);+ expect(first.socket.destroy).toHaveBeenCalledWith(+ expect.objectContaining({ message: "worker pause invalidated" }),+ );+ expect(second.socket.destroy).toHaveBeenCalledWith(+ expect.objectContaining({ message: "worker pause invalidated" }),+ );+ });++ it("releases an acquire that completes after its socket is invalidated", async () => {+ const { supervisor } = createHarness();+ const client = addClient(supervisor, "socket-a", "protocol-a");+ let releaseAcquire!: () => void;+ const gate = new Promise<void>((resolve) => {+ releaseAcquire = resolve;+ });+ const forward = supervisor.forwardToWorker;+ forward.mockImplementationOnce(async (_worker: WorkerFixture, command: DaemonCommand) => {+ await gate;+ return {+ type: "response",+ command: command.type,+ success: true,+ data: { pauseId: "pause-late" },+ } as DaemonResponse;+ });++ const acquisition = supervisor.handleCommand(client, acquireCommand("acquire"));+ await vi.waitFor(() => expect(forward).toHaveBeenCalledTimes(1));+ supervisor.sessionInputPauseEpochs.set(client, 1);+ supervisor.clients.delete(client);+ releaseAcquire();++ await expect(acquisition).rejects.toThrow("invalidated before completion");+ expect(forward.mock.calls.map((call) => (call[1] as DaemonCommand).type)).toEqual([+ "acquire_session_input_pause",+ "release_session_input_pause",+ ]);+ expect(supervisor.sessionInputPauses.size).toBe(0);+ });+});diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.tsindex bb09ca9347..6310feeffb 100644--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts@@ -220,6 +220,7 @@ function createExistingLaunchWorker(root: string, descriptorDir: string) {function createSupervisorSnapshotState() {return {clients: new Set<object>(),+ sessionInputPauses: new Map(),pendingReplacementSnapshots: new WeakMap<object, Map<string, unknown>>(),};}@@ -1566,7 +1567,7 @@ describe("daemon worker supervisor monitoring", () => {expect(worker.recovery).toBeUndefined();});- it("relaunches a worker instead of reconnecting to a reused pid", async () => {+ it("fails closed after pid reuse without fresh runtime context", async () => {vi.useFakeTimers();type RecoveryWorker = {descriptor: {@@ -1574,7 +1575,10 @@ describe("daemon worker supervisor monitoring", () => {pid: number;processStartId: string;rootActiveSessionId: string;- createCommand: { type: "create" };+ ownerClientId?: string;+ lifecycle?: string;+ consecutiveFailures: number;+ lastError?: string;};intentionalStop: boolean;stopRevision: number;@@ -1586,6 +1590,8 @@ describe("daemon worker supervisor monitoring", () => {connectWorker: ReturnType<typeof vi.fn>;recoverUncertainWorkerOperations: ReturnType<typeof vi.fn>;launchWorker: ReturnType<typeof vi.fn>;+ persistWorker: ReturnType<typeof vi.fn>;+ syncAgentPeers: ReturnType<typeof vi.fn>;assertRecoveryAllowed: ReturnType<typeof vi.fn>;recoverWorker(worker: RecoveryWorker): Promise<void>;};@@ -1595,7 +1601,7 @@ describe("daemon worker supervisor monitoring", () => {pid: process.pid,processStartId: "different-process-start",rootActiveSessionId: "active-1",- createCommand: { type: "create" },+ consecutiveFailures: 0,},intentionalStop: false,stopRevision: 0,@@ -1606,6 +1612,8 @@ describe("daemon worker supervisor monitoring", () => {connectWorker: vi.fn(),recoverUncertainWorkerOperations: vi.fn(async () => {}),launchWorker: vi.fn(async () => worker),+ persistWorker: vi.fn(),+ syncAgentPeers: vi.fn(async () => {}),assertRecoveryAllowed: vi.fn(async () => {}),}) as RecoveryHarness;@@ -1615,7 +1623,103 @@ describe("daemon worker supervisor monitoring", () => {expect(supervisor.connectWorker).not.toHaveBeenCalled();expect(supervisor.recoverUncertainWorkerOperations).toHaveBeenCalledWith(worker, false);- expect(supervisor.launchWorker).toHaveBeenCalledWith(worker.descriptor.createCommand, worker);+ expect(supervisor.launchWorker).not.toHaveBeenCalled();+ expect(worker.descriptor.lifecycle).toBe("failed");+ expect(supervisor.persistWorker).toHaveBeenCalledWith(worker);+ });++ it("rejects create reuse when a failed worker cannot be safely reclaimed", () => {+ const worker = {+ descriptor: {+ workerId: "failed-unreclaimed",+ rootActiveSessionId: "active-failed",+ lifecycle: "failed",+ },+ };+ const supervisor = Object.create(DaemonSupervisor.prototype) as {+ reuseWorkerForCreate(target: typeof worker, ownerClientId: undefined, sessionPath: string): typeof worker;+ };++ expect(() => supervisor.reuseWorkerForCreate(worker, undefined, "/tmp/failed.jsonl")).toThrow(/failed worker/);+ });++ it("ignores conflicting paths on workers unrelated to a session lookup", () => {+ const unrelated = {+ descriptor: {+ workerId: "unrelated",+ sessionFile: "/tmp/unrelated-a.jsonl",+ createCommand: { type: "create" as const, sessionPath: "/tmp/unrelated-b.jsonl" },+ },+ summaries: new Map(),+ };+ const target = {+ descriptor: {+ workerId: "target",+ sessionFile: "/tmp/target.jsonl",+ createCommand: { type: "create" as const, sessionPath: "/tmp/target.jsonl" },+ },+ summaries: new Map(),+ };+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers: new Map([+ [unrelated.descriptor.workerId, unrelated],+ [target.descriptor.workerId, target],+ ]),+ }) as {+ findWorkerBySessionFile(sessionFile: string): typeof target | undefined;+ };++ expect(supervisor.findWorkerBySessionFile("/tmp/target.jsonl")).toBe(target);+ });++ it("reclaims a dead failed resident so a fresh create can reopen its session", async () => {+ const worker = {+ descriptor: { workerId: "failed-resident", pid: 42, lifecycle: "failed" as const },+ intentionalStop: false,+ };+ const workers = new Map([[worker.descriptor.workerId, worker]]);+ const recoverUncertainWorkerOperations = vi.fn(async () => {});+ const deleteWorkerDescriptor = vi.fn();+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers,+ sessionInputPauses: new Map(),+ processIdentity: vi.fn(() => "gone"),+ recoverUncertainWorkerOperations,+ deleteWorkerDescriptor,+ syncAgentPeers: vi.fn(async () => {}),+ }) as {+ reclaimStaleWorkerRegistration(target: typeof worker): Promise<boolean>;+ };++ await expect(supervisor.reclaimStaleWorkerRegistration(worker)).resolves.toBe(true);+ expect(recoverUncertainWorkerOperations).toHaveBeenCalledWith(worker, false);+ expect(deleteWorkerDescriptor).toHaveBeenCalledWith(worker);+ expect(workers.has(worker.descriptor.workerId)).toBe(false);+ });++ it("stops only an identity-verified failed resident when a fresh create arrives", async () => {+ const worker = {+ descriptor: {+ workerId: "failed-live-resident",+ pid: 42,+ processStartId: "verified-start",+ lifecycle: "failed" as const,+ },+ intentionalStop: false,+ };+ const stopWorker = vi.fn(async () => {});+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers: new Map([[worker.descriptor.workerId, worker]]),+ processIdentity: vi.fn(() => "current"),+ stopWorker,+ }) as {+ reclaimStaleWorkerRegistration(target: typeof worker, freshCreate?: boolean): Promise<boolean>;+ };++ await expect(supervisor.reclaimStaleWorkerRegistration(worker)).resolves.toBe(false);+ expect(stopWorker).not.toHaveBeenCalled();+ await expect(supervisor.reclaimStaleWorkerRegistration(worker, true)).resolves.toBe(true);+ expect(stopWorker).toHaveBeenCalledWith(worker, true, true);});it("does not relaunch a live worker whose process identity is unknown", async () => {@@ -2912,6 +3016,120 @@ describe("daemon worker supervisor monitoring", () => {}});+ it("merges persisted host settings into fresh runtime defaults", () => {+ const root = mkdtempSync(join(tmpdir(), "prime-supervisor-config-merge-"));+ const descriptorDir = join(root, "workers");+ const socketPath = join(root, "supervisor.sock");+ const agentDir = join(root, "agent");+ mkdirSync(descriptorDir, { recursive: true });+ writeFileSync(+ join(descriptorDir, "supervisor-config"),+ JSON.stringify({+ version: 1,+ socketPath: `${root}//supervisor.sock`,+ defaultSessionConfig: { agentDir, cwd: "/persisted/cwd", telemetryDisabled: true },+ }),+ );++ try {+ const supervisor = new DaemonSupervisor(socketPath, {+ descriptorDir,+ defaultSessionConfig: {+ agentDir,+ cwd: "/fresh/cwd",+ provider: "fresh-provider",+ model: "fresh-model",+ apiKey: "fresh-key",+ },+ });+ const config = (supervisor as unknown as { defaultSessionConfig: Record<string, unknown> })+ .defaultSessionConfig;++ expect(config).toMatchObject({+ agentDir,+ cwd: "/persisted/cwd",+ telemetryDisabled: true,+ provider: "fresh-provider",+ model: "fresh-model",+ apiKey: "fresh-key",+ });+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("migrates v1 descriptors by lifting only safe host policy fields", () => {+ const descriptorDir = mkdtempSync(join(tmpdir(), "prime-supervisor-v1-migration-"));+ const descriptorPath = join(descriptorDir, "worker-v1.json");+ try {+ writeFileSync(+ descriptorPath,+ `${JSON.stringify({+ version: 1,+ workerId: "worker-v1",+ pid: 42,+ socketPath: "/tmp/worker-v1.sock",+ recoveryJournalPath: join(descriptorDir, "worker-v1.recovery.jsonl"),+ supervisorSocketPath: "/tmp/supervisor.sock",+ authenticationToken: "local-token",+ rootActiveSessionId: "active-v1",+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ lifecycle: "ready",+ createCommand: {+ type: "create",+ config: {+ sessionDir: "/safe/sessions",+ telemetryDisabled: true,+ apiKey: "secret-api-key",+ extensionFlagValues: { providerSecretKey: "secret-provider-key" },+ },+ launchEnv: { PROVIDER_TOKEN: "secret-env" },+ },+ launchEnv: { PROVIDER_TOKEN: "secret-top-level-env" },+ consecutiveFailures: 0,+ })}\n`,+ );+ const workers = new Map<string, { descriptor: Record<string, unknown> }>();+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ descriptorDir,+ socketPath: "/tmp/supervisor.sock",+ workers,+ log: vi.fn(),+ }) as {+ loadWorkerDescriptors(): void;+ persistWorker(target: unknown): void;+ };++ supervisor.loadWorkerDescriptors();++ const migrated = JSON.parse(readFileSync(descriptorPath, "utf8"));+ expect(migrated).toMatchObject({+ version: 2,+ sessionDir: "/safe/sessions",+ telemetryDisabled: true,+ createCommand: { type: "create" },+ });+ expect(JSON.stringify(migrated)).not.toContain("secret-");+ const runtimeWorker = workers.get("worker-v1");+ expect(runtimeWorker?.descriptor).toMatchObject({+ sessionDir: "/safe/sessions",+ telemetryDisabled: true,+ });+ if (!runtimeWorker) throw new Error("missing migrated worker");+ runtimeWorker.descriptor.lifecycle = "failed";+ runtimeWorker.descriptor.lastError = "secret-runtime-diagnostic";+ supervisor.persistWorker(runtimeWorker);+ expect(runtimeWorker.descriptor.lastError).toBe("secret-runtime-diagnostic");+ expect(JSON.parse(readFileSync(descriptorPath, "utf8"))).toMatchObject({+ lastError: "Waiting for a client with fresh runtime context",+ });+ expect(readFileSync(descriptorPath, "utf8")).not.toContain("secret-runtime-diagnostic");+ } finally {+ rmSync(descriptorDir, { recursive: true, force: true });+ }+ });+it("adopts persisted worker descriptors recorded with a non-canonical supervisor socket path", () => {if (process.platform === "win32") {return;@@ -2922,7 +3140,7 @@ describe("daemon worker supervisor monitoring", () => {writeFileSync(join(descriptorDir, "worker-1.json"),`${JSON.stringify({- version: 1,+ version: 2,workerId: "worker-1",pid: 999_999,socketPath: join(descriptorDir, "worker-1.sock"),@@ -2932,7 +3150,14 @@ describe("daemon worker supervisor monitoring", () => {createdAt: now,updatedAt: now,lifecycle: "running",- createCommand: { type: "create", config: { cwd: descriptorDir, agentDir: descriptorDir } },+ sessionDir: "/safe/sessions",+ telemetryDisabled: true,+ createCommand: {+ type: "create",+ config: { cwd: descriptorDir, agentDir: descriptorDir, apiKey: "secret-api-key" },+ launchEnv: { PROVIDER_TOKEN: "secret-command-env" },+ },+ launchEnv: { PROVIDER_TOKEN: "secret-worker-env" },consecutiveFailures: 0,})}\n`,);@@ -2950,9 +3175,21 @@ describe("daemon worker supervisor monitoring", () => {expect(supervisor.workers.size).toBe(1);const loaded = supervisor.workers.get("worker-1") as {- descriptor: { supervisorSocketPath: string };+ descriptor: Record<string, unknown>;};- expect(loaded.descriptor.supervisorSocketPath).toBe("/tmp/supervisor.sock");+ expect(loaded.descriptor).toMatchObject({+ version: 2,+ supervisorSocketPath: "/tmp/supervisor.sock",+ sessionDir: "/safe/sessions",+ telemetryDisabled: true,+ });+ expect(JSON.stringify(loaded.descriptor)).not.toContain("secret-");+ const persisted = readFileSync(join(descriptorDir, "worker-1.json"), "utf8");+ expect(persisted).not.toContain("secret-");+ expect(JSON.parse(persisted)).toMatchObject({+ version: 2,+ supervisorSocketPath: "/tmp/supervisor.sock",+ });} finally {rmSync(descriptorDir, { recursive: true, force: true });}@@ -3054,6 +3291,73 @@ describe("daemon worker supervisor monitoring", () => {expect(seed).toHaveBeenCalledWith(activeSessionId, streamingMessage);});+ it("reconstructs a client-owned recovery command from fresh attach context", async () => {+ const activeSessionId = "active-owned-recovery";+ const worker = {+ descriptor: {+ workerId: "worker-owned-recovery",+ ownerClientId: "client-1",+ rootActiveSessionId: activeSessionId,+ lifecycle: "failed",+ consecutiveFailures: 1,+ telemetryDisabled: true,+ createCommand: { type: "create" as const, sessionPath: "/tmp/session.jsonl" },+ },+ summaries: new Map(),+ intentionalStop: false,+ stopRevision: 0,+ launchEnv: undefined as Record<string, string> | undefined,+ transientCreateCommand: undefined as Record<string, unknown> | undefined,+ };+ const client = {+ id: "client-1",+ capabilities: new Set<string>(),+ supportsExtensionUi: false,+ attachedActiveSessionIds: new Set<string>(),+ };+ const recoverWorker = vi.fn(async () => {+ throw new Error("stop after reconstruction");+ });+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ workers: new Map([[worker.descriptor.workerId, worker]]),+ clients: new Set([client]),+ protocolClientIds: new WeakMap(),+ persistWorker: vi.fn(),+ recoverWorker,+ }) as {+ attachClient(+ attachClient: typeof client,+ command: {+ type: "attach";+ activeSessionId: string;+ recoveryConfig: { cwd: string };+ launchEnv: Record<string, string>;+ env: Record<string, string>;+ },+ ): Promise<unknown>;+ };++ await expect(+ supervisor.attachClient(client, {+ type: "attach",+ activeSessionId,+ recoveryConfig: { cwd: "/tmp/fresh-owner" },+ launchEnv: { OWNER_SECRET: "fresh" },+ env: { HERDR_PANE_ID: "pane-1" },+ }),+ ).rejects.toThrow("stop after reconstruction");+ expect(worker.transientCreateCommand).toEqual({+ type: "create",+ sessionPath: "/tmp/session.jsonl",+ config: { cwd: "/tmp/fresh-owner", telemetryDisabled: true },+ env: { HERDR_PANE_ID: "pane-1" },+ launchEnv: { OWNER_SECRET: "fresh" },+ lifecycle: "client_owned",+ });+ expect(worker.launchEnv).toEqual({ OWNER_SECRET: "fresh" });+ expect(recoverWorker).toHaveBeenCalledWith(worker);+ });+it("rejects an opted-out attach to a telemetry-enabled worker", async () => {const activeSessionId = "active-telemetry-enabled";const summary = {diff --git a/packages/coding-agent/test/daemon-supervisor-process.test.ts b/packages/coding-agent/test/daemon-supervisor-process.test.tsindex bd56749f3c..5d973738df 100644--- a/packages/coding-agent/test/daemon-supervisor-process.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts@@ -768,9 +768,9 @@ describe("daemon supervisor resident workers", () => {const replacementClient = await connectEventually(socketPath);const listed = await replacementClient.request({ type: "list" });expect(listed.success).toBe(true);- expect(readSupervisorConfig(agentDir)).toMatchObject({- defaultSessionConfig: { sessionDir, noTools: true },- });+ const persistedConfig = readSupervisorConfig(agentDir);+ expect(persistedConfig).toMatchObject({ defaultSessionConfig: { sessionDir } });+ expect(persistedConfig.defaultSessionConfig).not.toHaveProperty("noTools");await replacementClient.request({ type: "shutdown" });replacementClient.close();await waitForSocketGone(socketPath);@@ -1457,30 +1457,48 @@ describe("daemon supervisor resident workers", () => {workerPids.delete(pid);}- let recovered: SessionSummary | undefined;+ let failed: SessionSummary | undefined;const recoveryDeadline = Date.now() + 20_000;while (Date.now() < recoveryDeadline) {const response = await client.request({ type: "list" });if (response.success) {- recovered = requireSessionList(response.data).find(+ failed = requireSessionList(response.data).find((summary) =>(summary.activeSessionId ?? summary.id) === (createdSummary.activeSessionId ?? createdSummary.id),);- if (recovered?.workerState === "ready" && recovered.workerPid !== createdSummary.workerPid) {- break;- }+ if (failed?.workerState === "failed") break;}await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));}- expect(recovered).toMatchObject({ workerState: "ready", activeSessionId: createdSummary.activeSessionId });- if (!recovered?.workerPid) {- throw new Error("Recovered worker did not expose its pid");- }+ expect(failed).toMatchObject({ workerState: "failed", activeSessionId: createdSummary.activeSessionId });+ await connection.dispose();++ const reopened = await client.request({+ type: "create",+ sessionPath: sessionFile,+ continueRecent: false,+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },+ launchEnv: { PRIME_AGENT_TEST_FRESH_CONTEXT: "1" },+ });+ if (!reopened.success) throw new Error(reopened.error);+ const recovered = requireSummary(reopened.data);+ if (!recovered.workerPid) throw new Error("Recovered worker did not expose its pid");workerPids.add(recovered.workerPid);- expect(readFileSync(sessionFile, "utf8")).toContain("prime-agent.worker_recovery");- await expect(connection.getState()).resolves.toMatchObject({ sessionId: createdSummary.sessionId });+ const recoveredConnection = await DaemonAgentConnection.attach(+ client,+ recovered.activeSessionId ?? recovered.id,+ { recoverDaemon: async () => {} },+ );+ const recoveredSnapshot = await recoveredConnection.getInitialSnapshot();+ expect(recoveredSnapshot.messages).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ role: "user" }),+ expect.objectContaining({ role: "assistant" }),+ ]),+ );+ await expect(recoveredConnection.getState()).resolves.toMatchObject({ sessionId: createdSummary.sessionId });- await connection.dispose();+ await recoveredConnection.dispose();await client.request({ type: "shutdown" });client.close();await waitForSocketGone(socketPath);diff --git a/packages/coding-agent/test/main-interactive-routing.test.ts b/packages/coding-agent/test/main-interactive-routing.test.tsindex 5393a358b3..727662662f 100644--- a/packages/coding-agent/test/main-interactive-routing.test.ts+++ b/packages/coding-agent/test/main-interactive-routing.test.ts@@ -11,6 +11,7 @@ import {findActiveDaemonSessionSummaryForInteractiveStartup,findActiveDaemonSessionSummaryForSessionFile,type InteractiveDaemonStartupDecision,+ isClientOwnedDaemonSession,parseAgentsViewCommand,resolveRuntimeSessionOptions,shouldEnsureDaemonBeforeActiveSessionLookup,@@ -26,6 +27,15 @@ import {import type { SessionSummary } from "../src/modes/index.js";describe("interactive startup routing", () => {+ test.each([+ ["acp", false, false],+ ["acp", true, true],+ ["rpc", false, true],+ ["print", false, true],+ ] as const)("classifies %s noSession=%s ownership", (appMode, noSession, expected) => {+ expect(isClientOwnedDaemonSession(appMode, noSession)).toBe(expected);+ });+test.each(["interactive", "print", "json", "rpc"] as const)("uses the daemon runtime for the %s client",(appMode) => {diff --git a/packages/coding-agent/test/print-mode.test.ts b/packages/coding-agent/test/print-mode.test.tsindex 100a03be8d..d1a6b702ef 100644--- a/packages/coding-agent/test/print-mode.test.ts+++ b/packages/coding-agent/test/print-mode.test.ts@@ -31,6 +31,7 @@ type FakeSession = {sessionManager: { getHeader: () => object | undefined };agent: { waitForIdle: ReturnType<typeof vi.fn<() => Promise<void>>> };waitForIdle: ReturnType<typeof vi.fn<() => Promise<void>>>;+ waitForHeadlessIdle: ReturnType<typeof vi.fn<() => Promise<void>>>;state: { messages: AgentMessage[] };messages: AgentMessage[];extensionRunner: FakeExtensionRunner;@@ -96,11 +97,13 @@ function createRuntimeHost(};const state = { messages: Array.isArray(assistantMessage) ? assistantMessage : [assistantMessage] };+ const waitForIdle = vi.fn(async () => {});const session: FakeSession = {sessionManager: { getHeader: () => undefined },agent: { waitForIdle: vi.fn(async () => {}) },- waitForIdle: vi.fn(async () => {}),+ waitForIdle,+ waitForHeadlessIdle: waitForIdle,state,messages: state.messages,extensionRunner,diff --git a/packages/coding-agent/test/suite/acp-features.test.ts b/packages/coding-agent/test/suite/acp-features.test.tsindex 7b51917cf4..5e92bc424d 100644--- a/packages/coding-agent/test/suite/acp-features.test.ts+++ b/packages/coding-agent/test/suite/acp-features.test.ts@@ -477,12 +477,13 @@ describe("ACP mode preserves prime-agent features", () => {expect(beforeClose).toBeGreaterThan(0);await fixture.agent.request("session/close", { sessionId: fixture.sessionId });+ const afterClose = fixture.updates.length;+ expect(afterClose).toBeGreaterThanOrEqual(beforeClose);- // After close the subscription is released, so further agent activity must- // not reach the client.- await harness.session.prompt("post-close activity");- await new Promise((resolve) => setTimeout(resolve, 50));- expect(fixture.updates.length).toBe(beforeClose);+ // After close the subscription is released and the backing session remains+ // admission-fenced until its replacement is established.+ await expect(harness.session.prompt("post-close activity")).rejects.toThrow("session input admission is paused");+ expect(fixture.updates.length).toBe(afterClose);// Closing frees the single-session slot, so a new session is accepted.const next = await fixture.agent.request("session/new", { cwd: harness.tempDir, mcpServers: [] });diff --git a/packages/coding-agent/test/suite/acp-mode.test.ts b/packages/coding-agent/test/suite/acp-mode.test.tsindex 61b1c6252c..c62520cbeb 100644--- a/packages/coding-agent/test/suite/acp-mode.test.ts+++ b/packages/coding-agent/test/suite/acp-mode.test.ts@@ -1,6 +1,6 @@import * as acp from "@agentclientprotocol/sdk";import { fauxAssistantMessage } from "@earendil-works/pi-ai";-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import type { AgentSessionRuntime } from "../../src/core/agent-session-runtime.js";import { PRIME_AGENT_META_NAMESPACE } from "../../src/modes/acp/acp-meta.js";import { runAcpModeWithConnection } from "../../src/modes/acp/index.js";@@ -29,16 +29,132 @@ interface ClientHarness {close: () => void;}-function connectAcpClient(connection: any): ClientHarness {+interface ClientHarnessOptions {+ beforeAcpUpdatePublish?: (update: Record<string, unknown>) => void | Promise<void>;+}++function fakeAcpConnection(+ options: {+ initialSnapshot?: () => Promise<any>;+ finalSnapshot?: () => Promise<any>;+ onPromptAndWait?: () => void | Promise<void>;+ onWaitForHeadlessCompletion?: (options?: { waitForRlmQuiescence?: boolean }) => void | Promise<void>;+ headlessStatus?: Record<string, unknown>;+ onFinalSnapshot?: () => void | Promise<void>;+ onUnsubscribe?: () => void;+ onAbort?: () => void | Promise<void>;+ onAcquireSessionInputPause?: () => void | Promise<void>;+ onReleaseSessionInputPause?: () => void | Promise<void>;+ onCancelRlmChild?: (childId: string) => void | Promise<void>;+ } = {},+): any {+ let listener: ((event: any) => void) | undefined;+ const messages: any[] = [];+ const inputPauses = new Map<string, { release(): Promise<void> }>();+ const snapshot = { state: { cwd: process.cwd() }, messages, children: [] };+ return {+ subscribe(callback: (event: any) => void) {+ listener = callback;+ return () => {+ listener = undefined;+ options.onUnsubscribe?.();+ };+ },+ getState: async () => snapshot.state,+ getMessages: async () => messages,+ getInitialSnapshot: async () => {+ if (options.initialSnapshot) {+ const result = await options.initialSnapshot();+ options.initialSnapshot = undefined;+ return result;+ }+ if (options.finalSnapshot) return options.finalSnapshot();+ return snapshot;+ },+ getRlmChildSnapshots: async () => {+ await options.onFinalSnapshot?.();+ return options.finalSnapshot ? ((await options.finalSnapshot()).children ?? []) : snapshot.children;+ },+ promptAndWait: async () => {+ await options.onPromptAndWait?.();+ },+ dispose: async () => {},+ abort: async () => {+ await options.onAbort?.();+ },+ abortAndClearQueue: async () => {+ await options.onAbort?.();+ return { followUpMessages: [], pendingMessages: [] };+ },+ acquireSessionInputPause: async (leaseKey: string) => {+ const existing = inputPauses.get(leaseKey);+ if (existing) return existing;+ await options.onAcquireSessionInputPause?.();+ const pause = {+ release: async () => {+ await options.onReleaseSessionInputPause?.();+ if (inputPauses.get(leaseKey) === pause) inputPauses.delete(leaseKey);+ },+ };+ inputPauses.set(leaseKey, pause);+ return pause;+ },+ waitForIdle: async () => {},+ cancelRlmChild: async (childId: string) => {+ await options.onCancelRlmChild?.(childId);+ return true;+ },+ waitForHeadlessCompletion: async (completionOptions?: { waitForRlmQuiescence?: boolean }) => {+ await options.onWaitForHeadlessCompletion?.(completionOptions);+ return {+ enabled: false,+ continuationsUsed: 0,+ turnsUsed: 0,+ tokensUsed: 0,+ limits: { maxContinuations: 0 },+ ...options.headlessStatus,+ };+ },+ emitChild(child: any) {+ listener?.({ type: "session_event", event: { type: "rlm_child_update", child } });+ },+ emitHeartbeat() {+ listener?.({ type: "heartbeats_changed" });+ },+ messages,+ };+}++function acpUpdatePhase(update: Record<string, unknown>): unknown {+ const metadata = update._meta as Record<string, unknown> | undefined;+ const primeMetadata = metadata?.[PRIME_AGENT_META_NAMESPACE] as Record<string, unknown> | undefined;+ return primeMetadata?.phase;+}++function connectAcpClient(connection: any, options: ClientHarnessOptions = {}): ClientHarness {// Two web streams crossed over: agent's stdout is the client's stdin.const toAgent = new TransformStream<Uint8Array, Uint8Array>();const toClient = new TransformStream<Uint8Array, Uint8Array>();+ const originalNotify = acp.AgentContext.prototype.notify;+ const publishSpy = options.beforeAcpUpdatePublish+ ? vi.spyOn(acp.AgentContext.prototype, "notify").mockImplementation(async function (+ this: acp.AgentContext,+ method: string,+ params?: unknown,+ ) {+ if (method === acp.methods.client.session.update) {+ const update = (params as { update: Record<string, unknown> }).update;+ await options.beforeAcpUpdatePublish?.(update);+ }+ return originalNotify.call(this, method, params);+ })+ : undefined;const agentStream = acp.ndJsonStream(toClient.writable, toAgent.readable);const clientStream = acp.ndJsonStream(toAgent.writable, toClient.readable);const updates: any[] = [];- void runAcpModeWithConnection(connection, { stream: agentStream } as any);+ void runAcpModeWithConnection(connection, { stream: agentStream });const handle = acp.client({ name: "test-client" })@@ -48,7 +164,14 @@ function connectAcpClient(connection: any): ClientHarness {.connect(clientStream);// connect() yields a handle whose `agent` proxy is the outbound call surface.- return { client: handle.agent, updates, close: () => handle.close() };+ return {+ client: handle.agent,+ updates,+ close: () => {+ publishSpy?.mockRestore();+ handle.close();+ },+ };}describe("ACP mode end to end", () => {@@ -84,4 +207,839 @@ describe("ACP mode end to end", () => {harness.cleanup();}, 30_000);++ it("emits score-safe quiescence metadata with outstanding work and budget", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("done")]);+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));+ const { client, updates } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: harness.tempDir, mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "finish" }],+ });+ await vi.waitFor(() =>+ expect(+ updates.some(+ (update) => update.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.phase === "terminalQuiescence",+ ),+ ).toBe(true),+ );+ const correlated = updates+ .map((update) => update.update?._meta?.[PRIME_AGENT_META_NAMESPACE])+ .filter((meta) => meta?.promptTurnId === 1);+ expect(correlated.map((meta) => meta.eventSequence)).toEqual(+ [...correlated.map((meta) => meta.eventSequence)].sort((a, b) => a - b),+ );+ expect(new Set(correlated.map((meta) => meta.eventSequence)).size).toBe(correlated.length);+ expect(correlated.filter((meta) => meta.phase === "responseBoundary")).toEqual([+ expect.objectContaining({ outcome: "result", terminalQuiescenceExpected: true }),+ ]);+ const terminalIndex = correlated.findIndex((meta) => meta.phase === "terminalQuiescence");+ expect(terminalIndex).toBeGreaterThan(correlated.findIndex((meta) => meta.phase === "responseBoundary"));+ expect(correlated[terminalIndex].quiescence).toEqual({+ outstandingSubagents: 0,+ remainingAutonomousContinuations: 0,+ });+ harness.cleanup();+ }, 30_000);++ it("treats unused autonomous capacity as terminal lifecycle telemetry", async () => {+ const connection = fakeAcpConnection({+ headlessStatus: {+ enabled: true,+ continuationsUsed: 1,+ gateAttempts: {},+ limits: { maxContinuations: 3 },+ },+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "finish" }],+ });+ await vi.waitFor(() =>+ expect(+ updates.some((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.phase === "terminalQuiescence"),+ ).toBe(true),+ );+ const meta = updates.map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]).filter(Boolean);+ expect(meta.filter((item) => item.phase === "responseBoundary")).toHaveLength(1);+ expect(meta.filter((item) => item.phase === "terminalQuiescence")).toEqual([+ expect.objectContaining({+ quiescence: { outstandingSubagents: 0, remainingAutonomousContinuations: 2 },+ }),+ ]);+ close();+ });++ it("reports a descendant-driven parent failure in the terminal outcome", async () => {+ const connection = fakeAcpConnection({+ onWaitForHeadlessCompletion: (options) => {+ if (!options?.waitForRlmQuiescence) return;+ connection.messages.push({+ role: "assistant",+ content: [],+ stopReason: "error",+ errorMessage: "child continuation failed",+ timestamp: Date.now(),+ });+ },+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "delegate" }],+ });+ await vi.waitFor(() =>+ expect(+ updates+ .map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE])+ .find((meta) => meta?.phase === "terminalQuiescence"),+ ).toMatchObject({ promptTurnId: 1, outcome: "error" }),+ );+ close();+ });++ it("finalizes a child-backed turn only after the strong RLM barrier", async () => {+ const child = { id: "child-1", label: "child", status: "running", sessionDir: "/tmp/child" };+ let releaseBarrier!: () => void;+ const barrier = new Promise<void>((resolve) => {+ releaseBarrier = resolve;+ });+ let roster = [{ ...child, status: "done" }];+ let promptCalls = 0;+ let connection: any;+ connection = fakeAcpConnection({+ initialSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: [] }),+ finalSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: roster }),+ onPromptAndWait: () => {+ promptCalls++;+ if (promptCalls === 1) connection.emitChild(child);+ },+ onWaitForHeadlessCompletion: async (options) => {+ if (options?.waitForRlmQuiescence) await barrier;+ },+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "delegate" }],+ });++ let metadata = updates.map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]).filter(Boolean);+ expect(metadata.filter((item) => item.phase === "terminalQuiescence")).toHaveLength(0);+ const nextPrompt = client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "wait for the child" }],+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(promptCalls).toBe(1);++ roster = [{ ...child, status: "done" }];+ connection.emitChild(roster[0]);+ releaseBarrier();+ await vi.waitFor(() => {+ metadata = updates.map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]).filter(Boolean);+ expect(metadata.filter((item) => item.phase === "terminalQuiescence" && item.promptTurnId === 1)).toEqual([+ expect.objectContaining({+ promptTurnId: 1,+ outcome: "result",+ quiescence: { outstandingSubagents: 0, remainingAutonomousContinuations: 0 },+ }),+ ]);+ });+ const sequences = metadata.map((item) => item.eventSequence);+ expect(sequences).toEqual([...sequences].sort((left, right) => left - right));+ await nextPrompt;+ expect(promptCalls).toBe(2);+ close();+ });++ it("coalesces duplicate cancellation notifications under one stop owner", async () => {+ let releaseAbort!: () => void;+ const abortGate = new Promise<void>((resolve) => {+ releaseAbort = resolve;+ });+ let releaseBarrier!: () => void;+ const barrier = new Promise<void>((resolve) => {+ releaseBarrier = resolve;+ });+ let abortCalls = 0;+ let abortEntered!: () => void;+ const abortStarted = new Promise<void>((resolve) => {+ abortEntered = resolve;+ });+ const connection = fakeAcpConnection({+ onWaitForHeadlessCompletion: async (options) => {+ if (options?.waitForRlmQuiescence) await barrier;+ },+ onAbort: async () => {+ abortCalls++;+ abortEntered();+ await abortGate;+ releaseBarrier();+ },+ });+ const { client, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "cancel twice" }],+ });+ await client.notify("session/cancel", { sessionId: session.sessionId });+ await abortStarted;+ await client.notify("session/cancel", { sessionId: session.sessionId });+ await Promise.resolve();+ expect(abortCalls).toBe(1);+ releaseAbort();+ await vi.waitFor(async () => {+ await expect(+ client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "after duplicate cancel" }],+ }),+ ).resolves.toBeDefined();+ });+ close();+ });++ it("cancels deferred child work before reopening prompt admission", async () => {+ const child = { id: "child-cancel", label: "child", status: "running", sessionDir: "/tmp/child" };+ let releaseBarrier!: () => void;+ const barrier = new Promise<void>((resolve) => {+ releaseBarrier = resolve;+ });+ let abortObserved!: () => void;+ const aborted = new Promise<void>((resolve) => {+ abortObserved = resolve;+ });+ let roster = [child];+ let connection: any;+ connection = fakeAcpConnection({+ initialSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: [] }),+ finalSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: roster }),+ onPromptAndWait: () => connection.emitChild(child),+ onWaitForHeadlessCompletion: async (options) => {+ if (options?.waitForRlmQuiescence) await barrier;+ },+ onCancelRlmChild: () => {+ roster = [{ ...child, status: "cancelled" }];+ connection.emitChild(roster[0]);+ releaseBarrier();+ },+ onAbort: () => abortObserved(),+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "delegate" }],+ });+ await client.notify("session/cancel", { sessionId: session.sessionId });+ await aborted;++ const firstTurnTerminal = updates+ .map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE])+ .filter((meta) => meta?.promptTurnId === 1 && meta.phase === "terminalQuiescence");+ expect(firstTurnTerminal).toHaveLength(0);+ await vi.waitFor(async () => {+ await expect(+ client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "after cancellation" }],+ }),+ ).resolves.toBeDefined();+ });+ close();+ });++ it("closes a pending child lifecycle without publishing a false terminal", async () => {+ const child = { id: "child-close", label: "child", status: "running", sessionDir: "/tmp/child" };+ let releaseBarrier!: () => void;+ const barrier = new Promise<void>((resolve) => {+ releaseBarrier = resolve;+ });+ let connection: any;+ connection = fakeAcpConnection({+ initialSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: [] }),+ finalSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: [child] }),+ onPromptAndWait: () => connection.emitChild(child),+ onWaitForHeadlessCompletion: async (options) => {+ if (options?.waitForRlmQuiescence) await barrier;+ },+ onCancelRlmChild: () => releaseBarrier(),+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "delegate" }],+ });+ await client.request("session/close", { sessionId: session.sessionId });+ await Promise.resolve();++ const terminal = updates+ .map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE])+ .filter((meta) => meta?.phase === "terminalQuiescence");+ expect(terminal).toHaveLength(0);+ close();+ });++ it("releases the subscription when the initial roster snapshot fails", async () => {+ let unsubscribeCount = 0;+ const connection = fakeAcpConnection({+ initialSnapshot: async () => {+ throw new Error("snapshot unavailable");+ },+ onUnsubscribe: () => {+ unsubscribeCount += 1;+ },+ });+ const { client, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ await expect(client.request("session/new", { cwd: process.cwd(), mcpServers: [] })).rejects.toThrow();+ expect(unsubscribeCount).toBe(1);+ close();+ });++ it("keeps a live child update newer than the in-flight initial snapshot", async () => {+ let emitChild: (child: any) => void = () => {};+ let releaseSnapshot!: () => void;+ let snapshotEventEmitted!: () => void;+ const snapshotReleased = new Promise<void>((resolve) => {+ releaseSnapshot = resolve;+ });+ const snapshotEvent = new Promise<void>((resolve) => {+ snapshotEventEmitted = resolve;+ });+ const connection = fakeAcpConnection({+ initialSnapshot: async () => {+ emitChild({ id: "during-snapshot", label: "during snapshot", status: "done", sessionDir: "/tmp/child" });+ snapshotEventEmitted();+ await snapshotReleased;+ return {+ state: { cwd: process.cwd() },+ messages: [],+ children: [+ { id: "during-snapshot", label: "during snapshot", status: "running", sessionDir: "/tmp/child" },+ ],+ };+ },+ });+ const originalSubscribe = connection.subscribe.bind(connection);+ connection.subscribe = (listener: (event: any) => void) => {+ emitChild = (child) => listener({ type: "session_event", event: { type: "rlm_child_update", child } });+ return originalSubscribe(listener);+ };+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const pending = client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await snapshotEvent;+ expect(updates).toHaveLength(0);+ releaseSnapshot();+ const session = await pending;+ await vi.waitFor(() => expect(updates).toHaveLength(1));+ expect(updates[0]).toMatchObject({+ sessionId: session.sessionId,+ update: {+ _meta: {+ [PRIME_AGENT_META_NAMESPACE]: {+ eventSequence: 1,+ promptTurnId: 0,+ subagents: [expect.objectContaining({ id: "during-snapshot", status: "done" })],+ },+ },+ },+ });+ close();+ });++ it("publishes and seeds the authoritative initial child roster at turn zero", async () => {+ const child = { id: "resident-child", label: "resident child", status: "running", sessionDir: "/tmp/child" };+ let connection: any;+ connection = fakeAcpConnection({+ initialSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: [child] }),+ onPromptAndWait: () => connection.emitChild({ ...child, status: "done" }),+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "continue" }],+ });+ const childMeta = updates+ .map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE])+ .filter((meta) => meta?.subagents);+ expect(childMeta.map((meta) => meta.promptTurnId)).toEqual([0, 0]);+ close();+ });++ it("propagates a failed roster read at quiescence emission", async () => {+ const connection = fakeAcpConnection({+ initialSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: [] }),+ finalSnapshot: async () => {+ throw new Error("roster unavailable");+ },+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await expect(+ client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "finish" }],+ }),+ ).rejects.toThrow();+ const metadata = updates.map((u) => u.update?._meta?.[PRIME_AGENT_META_NAMESPACE]).filter(Boolean);+ expect(metadata).toContainEqual(+ expect.objectContaining({+ promptTurnId: 1,+ phase: "responseBoundary",+ outcome: "error",+ terminalQuiescenceExpected: false,+ }),+ );+ expect(metadata.find((meta) => meta.phase === "terminalQuiescence")).toBeUndefined();+ close();+ });++ it("keeps global sequences and causal turn ids across sequential prompts", async () => {+ const connection = fakeAcpConnection();+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "first" }],+ });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "second" }],+ });+ await vi.waitFor(() =>+ expect(+ updates.filter((u) => u.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.phase === "terminalQuiescence"),+ ).toHaveLength(2),+ );+ const metadata = updates.map((u) => u.update?._meta?.[PRIME_AGENT_META_NAMESPACE]).filter(Boolean);+ const sequences = metadata.map((meta) => meta.eventSequence);+ expect(sequences).toEqual([...sequences].sort((a, b) => a - b));+ expect(metadata.filter((meta) => meta.phase === "responseBoundary").map((meta) => meta.promptTurnId)).toEqual([+ 1, 2,+ ]);+ expect(metadata.filter((meta) => meta.phase === "terminalQuiescence").map((meta) => meta.promptTurnId)).toEqual([+ 1, 2,+ ]);+ close();+ });++ it("moves a retained child update after terminal to safe turn zero", async () => {+ const child = { id: "child-1", label: "child", status: "running", sessionDir: "/tmp/child" };+ let connection: any;+ connection = fakeAcpConnection({+ onPromptAndWait: () => connection.emitChild(child),+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "first" }],+ });+ await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "second" }],+ });+ connection.emitChild({ ...child, status: "done" });+ await vi.waitFor(() =>+ expect(+ updates.some(+ (u) =>+ u.update?.sessionUpdate === "session_info_update" &&+ u.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.subagents,+ ),+ ).toBe(true),+ );+ const childUpdates = updates+ .map((u) => u.update?._meta?.[PRIME_AGENT_META_NAMESPACE])+ .filter((meta) => meta?.subagents);+ expect(childUpdates.map((meta) => meta.promptTurnId)).toEqual([1, 0]);+ expect(childUpdates.map((meta) => meta.phase)).toEqual(["event", "event"]);+ close();+ });++ it("holds the backing input fence from close until replacement session admission", async () => {+ let acquired = 0;+ let released = 0;+ const connection = fakeAcpConnection({+ onAcquireSessionInputPause: () => {+ acquired++;+ },+ onReleaseSessionInputPause: () => {+ released++;+ },+ });+ const { client, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const first = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await client.request("session/close", { sessionId: first.sessionId });+ expect({ acquired, released }).toEqual({ acquired: 1, released: 0 });++ await expect(client.request("session/new", { cwd: process.cwd(), mcpServers: [] })).resolves.toBeDefined();+ expect({ acquired, released }).toEqual({ acquired: 1, released: 1 });+ close();+ });++ it("retries the same input fence when replacement admission cannot release it", async () => {+ let acquired = 0;+ let releaseAttempts = 0;+ const connection = fakeAcpConnection({+ onAcquireSessionInputPause: () => {+ acquired++;+ },+ onReleaseSessionInputPause: () => {+ releaseAttempts++;+ if (releaseAttempts === 1) throw new Error("release response lost");+ },+ });+ const { client, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });++ await expect(client.request("session/close", { sessionId: session.sessionId })).resolves.toEqual({});+ const replacement = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ await expect(+ client.request("session/prompt", {+ sessionId: replacement.sessionId,+ prompt: [{ type: "text", text: "still fenced" }],+ }),+ ).rejects.toThrow();+ await client.notify("session/cancel", { sessionId: replacement.sessionId });+ await vi.waitFor(async () => {+ await expect(+ client.request("session/prompt", {+ sessionId: replacement.sessionId,+ prompt: [{ type: "text", text: "released on retry" }],+ }),+ ).resolves.toBeDefined();+ });+ expect({ acquired, releaseAttempts }).toEqual({ acquired: 1, releaseAttempts: 2 });+ close();+ });++ it("keeps failed close state fenced and recoverable through cancellation", async () => {+ let abortAttempts = 0;+ let unsubscribeAttempts = 0;+ const connection = fakeAcpConnection({+ onAbort: () => {+ abortAttempts++;+ if (abortAttempts === 1) throw new Error("transient stop failure");+ },+ onUnsubscribe: () => {+ unsubscribeAttempts++;+ },+ });+ const { client, updates, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });++ await expect(client.request("session/close", { sessionId: session.sessionId })).rejects.toThrow();+ expect(unsubscribeAttempts).toBe(0);+ await expect(+ client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "must remain closed to prompts" }],+ }),+ ).rejects.toThrow();++ await client.notify("session/cancel", { sessionId: session.sessionId });+ await vi.waitFor(() => expect(abortAttempts).toBe(2));+ const updatesBeforeHeartbeat = updates.length;+ connection.emitHeartbeat();+ await vi.waitFor(() => expect(updates.length).toBeGreaterThan(updatesBeforeHeartbeat));+ await expect(+ client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "admitted after successful reconciliation" }],+ }),+ ).resolves.toBeDefined();++ await expect(client.request("session/close", { sessionId: session.sessionId })).resolves.toEqual({});+ expect(abortAttempts).toBe(3);+ expect(unsubscribeAttempts).toBe(1);+ close();+ });++ it("reconciles cancellation that arrives during a failed close", async () => {+ let abortAttempts = 0;+ let firstAbortStarted!: () => void;+ let releaseFirstAbort!: () => void;+ const firstAbortEntered = new Promise<void>((resolve) => {+ firstAbortStarted = resolve;+ });+ const firstAbortGate = new Promise<void>((resolve) => {+ releaseFirstAbort = resolve;+ });+ const connection = fakeAcpConnection({+ onAbort: async () => {+ abortAttempts++;+ if (abortAttempts !== 1) return;+ firstAbortStarted();+ await firstAbortGate;+ throw new Error("transient stop failure");+ },+ });+ const { client, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });++ const closing = client.request("session/close", { sessionId: session.sessionId });+ await firstAbortEntered;+ await client.notify("session/cancel", { sessionId: session.sessionId });+ releaseFirstAbort();+ await expect(closing).rejects.toThrow();+ await vi.waitFor(() => expect(abortAttempts).toBe(2));+ await expect(+ client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "admitted after queued cancellation" }],+ }),+ ).resolves.toBeDefined();+ await expect(client.request("session/close", { sessionId: session.sessionId })).resolves.toEqual({});+ close();+ });++ it("settles queued updates before close resolves without a post-close notification", async () => {+ let entered!: () => void;+ let release!: () => void;+ const enteredPublish = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const releasePublish = new Promise<void>((resolve) => {+ release = resolve;+ });+ const connection = fakeAcpConnection();+ const { client, updates, close } = connectAcpClient(connection, {+ beforeAcpUpdatePublish: async () => {+ entered();+ await releasePublish;+ },+ });+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ connection.emitHeartbeat();+ await enteredPublish;+ connection.emitHeartbeat();+ const closing = client.request("session/close", { sessionId: session.sessionId });+ await Promise.resolve();+ let closed = false;+ void closing.then(() => {+ closed = true;+ });+ await Promise.resolve();+ expect(closed).toBe(false);+ await expect(+ client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "must not start while closing" }],+ }),+ ).rejects.toThrow();+ release();+ await closing;+ expect(updates).toHaveLength(2);+ await Promise.resolve();+ expect(updates).toHaveLength(2);+ close();+ });++ it("keeps the session slot reserved until close finishes aborting", async () => {+ let promptStarted!: () => void;+ let releasePrompt!: () => void;+ let abortStarted!: () => void;+ let releaseAbort!: () => void;+ const promptStart = new Promise<void>((resolve) => {+ promptStarted = resolve;+ });+ const promptRelease = new Promise<void>((resolve) => {+ releasePrompt = resolve;+ });+ const abortStart = new Promise<void>((resolve) => {+ abortStarted = resolve;+ });+ const abortRelease = new Promise<void>((resolve) => {+ releaseAbort = resolve;+ });+ const connection = fakeAcpConnection({+ onPromptAndWait: async () => {+ promptStarted();+ await promptRelease;+ },+ onAbort: async () => {+ abortStarted();+ await abortRelease;+ },+ });+ const { client, close } = connectAcpClient(connection);+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ const prompt = client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "wait" }],+ });+ await promptStart;+ const closing = client.request("session/close", { sessionId: session.sessionId });+ await abortStart;+ await expect(client.request("session/new", { cwd: process.cwd(), mcpServers: [] })).rejects.toThrow();+ releaseAbort();+ releasePrompt();+ await expect(prompt).resolves.toMatchObject({ stopReason: "cancelled" });+ await expect(closing).resolves.toEqual({});+ close();+ });++ it("drains queued updates before returning cancellation at the final snapshot cut", async () => {+ let enteredUpdate!: () => void;+ let releaseUpdate!: () => void;+ let enteredSnapshot!: () => void;+ let releaseSnapshot!: () => void;+ const updateStarted = new Promise<void>((resolve) => {+ enteredUpdate = resolve;+ });+ const updateRelease = new Promise<void>((resolve) => {+ releaseUpdate = resolve;+ });+ const snapshotStarted = new Promise<void>((resolve) => {+ enteredSnapshot = resolve;+ });+ const snapshotRelease = new Promise<void>((resolve) => {+ releaseSnapshot = resolve;+ });+ const connection = fakeAcpConnection({+ initialSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: [] }),+ finalSnapshot: async () => ({ state: { cwd: process.cwd() }, messages: [], children: [] }),+ onFinalSnapshot: async () => {+ enteredSnapshot();+ await snapshotRelease;+ },+ });+ const { client, updates, close } = connectAcpClient(connection, {+ beforeAcpUpdatePublish: async () => {+ enteredUpdate();+ await updateRelease;+ },+ });+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ connection.emitHeartbeat();+ await updateStarted;+ const pending = client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "cancel after final snapshot" }],+ });+ await snapshotStarted;+ await client.notify("session/cancel", { sessionId: session.sessionId });+ releaseSnapshot();+ await Promise.resolve();+ let settled = false;+ void pending.then(() => {+ settled = true;+ });+ await Promise.resolve();+ expect(settled).toBe(false);+ releaseUpdate();+ await expect(pending).resolves.toMatchObject({ stopReason: "cancelled" });+ expect(updates).toHaveLength(1);+ close();+ });++ it("does not relabel a nonterminal completion when cancellation races its boundary", async () => {+ let entered!: () => void;+ let release!: () => void;+ const enteredBoundary = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const releaseBoundary = new Promise<void>((resolve) => {+ release = resolve;+ });+ const connection = fakeAcpConnection({+ finalSnapshot: async () => ({+ state: { cwd: process.cwd() },+ messages: [],+ children: [{ id: "live-child", label: "live", status: "running", sessionDir: "/tmp/child" }],+ }),+ });+ const { client, updates, close } = connectAcpClient(connection, {+ beforeAcpUpdatePublish: async (update) => {+ if (acpUpdatePhase(update) === "responseBoundary") {+ entered();+ await releaseBoundary;+ }+ },+ });+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ const pending = client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "gate nonterminal boundary" }],+ });+ await enteredBoundary;+ await client.notify("session/cancel", { sessionId: session.sessionId });+ release();+ await expect(pending).resolves.not.toMatchObject({ stopReason: "cancelled" });+ const meta = updates.map((item) => item.update?._meta?.[PRIME_AGENT_META_NAMESPACE]).filter(Boolean);+ expect(meta).toContainEqual(expect.objectContaining({ phase: "responseBoundary", outcome: "result" }));+ expect(meta).toContainEqual(+ expect.objectContaining({ phase: "event", quiescence: expect.objectContaining({ outstandingSubagents: 1 }) }),+ );+ close();+ });++ it("does not invent terminal quiescence after cancellation crosses the response boundary", async () => {+ let entered!: () => void;+ let release!: () => void;+ const enteredBoundary = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const releaseBoundary = new Promise<void>((resolve) => {+ release = resolve;+ });+ const connection = fakeAcpConnection();+ const { client, updates, close } = connectAcpClient(connection, {+ beforeAcpUpdatePublish: async (update) => {+ if (acpUpdatePhase(update) === "responseBoundary") {+ entered();+ await releaseBoundary;+ }+ },+ });+ await client.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await client.request("session/new", { cwd: process.cwd(), mcpServers: [] });+ const pending = client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "gate boundary" }],+ });+ await enteredBoundary;+ await client.notify("session/cancel", { sessionId: session.sessionId });+ release();+ const result = await pending;+ expect(result.stopReason).not.toBe("cancelled");+ const meta = updates.map((u) => u.update?._meta?.[PRIME_AGENT_META_NAMESPACE]).filter(Boolean);+ expect(meta.filter((item) => item.phase === "responseBoundary")).toEqual([+ expect.objectContaining({ outcome: "result" }),+ ]);+ expect(meta.filter((item) => item.phase === "terminalQuiescence")).toEqual([]);+ close();+ });});diff --git a/packages/coding-agent/test/suite/agent-session-compaction-continuation.test.ts b/packages/coding-agent/test/suite/agent-session-compaction-continuation.test.tsindex 232ed8b643..259baeb15f 100644--- a/packages/coding-agent/test/suite/agent-session-compaction-continuation.test.ts+++ b/packages/coding-agent/test/suite/agent-session-compaction-continuation.test.ts@@ -196,6 +196,49 @@ describe("compaction continuation", () => {expect(harness.getPendingResponseCount()).toBe(0);});+ it("headless idle includes a successful post-compaction continuation", async () => {+ const bigTool = {+ name: "big",+ label: "big",+ description: "returns big text",+ parameters: Type.Object({}),+ execute: async () => ({+ content: [{ type: "text" as const, text: "x".repeat(40_000) }],+ details: {},+ }),+ };+ const harness = await createHarness({+ tools: [bigTool],+ settings: { compaction: { enabled: true, reserveTokens: 500, keepRecentTokens: 1 } },+ models: [{ id: "faux-1", contextWindow: 6_000 }],+ persistSession: true,+ extensionFactories: [+ (pi) => {+ pi.on("session_before_compact", async (event) => ({+ compaction: {+ summary: "auto compacted",+ firstKeptEntryId: event.preparation.firstKeptEntryId,+ tokensBefore: event.preparation.tokensBefore,+ details: {},+ },+ }));+ },+ ],+ });+ harnesses.push(harness);+ harness.setResponses([+ fauxAssistantMessage(fauxToolCall("big", {}), { stopReason: "toolUse" }),+ fauxAssistantMessage("final answer after successful compaction"),+ ]);++ await harness.session.prompt("run the tool then summarize");+ await harness.session.waitForHeadlessIdle();++ expect(harness.eventsOfType("compaction_end").find((event) => event.result)?.result).toBeDefined();+ expect(harness.getPendingResponseCount()).toBe(0);+ expect(harness.session.getLastAssistantText()).toBe("final answer after successful compaction");+ });+// BUG B (end-to-end): unlike the tests above, the threshold compaction here SUCCEEDS.it("e2e: an active goal keeps continuing after a successful threshold compaction", async () => {const sessionRef: { current?: AgentSession } = {};diff --git a/packages/coding-agent/test/suite/agent-session-queue.test.ts b/packages/coding-agent/test/suite/agent-session-queue.test.tsindex e61b5fec13..5719667b35 100644--- a/packages/coding-agent/test/suite/agent-session-queue.test.ts+++ b/packages/coding-agent/test/suite/agent-session-queue.test.ts@@ -2644,6 +2644,91 @@ describe("AgentSession queue characterization", () => {expect(getUserTexts(harness)).toEqual(["queued before abort", "wake after abort"]);});+ it("resumes an explicit custom trigger after an ordinary abort", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ harness.setResponses([fauxAssistantMessage("trigger resumed")]);+ harness.session.requestAbort();++ await harness.session.sendCustomMessage(+ { customType: "trigger", content: "resume after abort", display: false },+ { triggerTurn: true },+ );+ await harness.session.waitForIdle();+ expect(+ harness.session.messages.filter((message) => message.role === "custom").map((message) => message.content),+ ).toContain("resume after abort");+ });++ it("rejects all new session actions while an input admission pause is held", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ const pause = harness.session.acquireSessionInputPause();+ await expect(harness.session.prompt("blocked prompt")).rejects.toThrow("input admission is paused");+ await expect(harness.session.followUp("blocked follow-up")).rejects.toThrow("input admission is paused");++ pause.release();+ harness.setResponses([fauxAssistantMessage("resumed")]);+ await harness.session.prompt("allowed prompt");+ await harness.session.waitForIdle();+ expect(getUserTexts(harness)).toEqual(["allowed prompt"]);+ });++ it("reschedules previously queued input when an admission pause releases", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ harness.setResponses([fauxAssistantMessage("queued input resumed")]);+ const internals = harness.session as unknown as {+ _sessionInputPumpRequested: boolean;+ _scheduleSessionInputPump(): void;+ };+ const schedule = vi.spyOn(internals, "_scheduleSessionInputPump").mockImplementation(() => {});+ await harness.session.followUp("queued before pause");+ expect(harness.session.getFollowUpMessages()).toEqual(["queued before pause"]);+ schedule.mockRestore();++ // Model a pump that was requested before the pause invalidated its epoch.+ internals._sessionInputPumpRequested = true;+ const pause = harness.session.acquireSessionInputPause();+ expect(internals._sessionInputPumpRequested).toBe(false);+ pause.release();+ await harness.session.waitForIdle();+ expect(getUserTexts(harness)).toEqual(["queued before pause"]);+ });++ it("does not admit a late agent message across an abort and explicit resume", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ harness.setResponses([fauxAssistantMessage("user turn done")]);+ harness.session.requestAbort();+ const lateAgentMessage = harness.session.acceptAgentMessagePrompt(+ agentPromptText("agentmsg_after_abort", "late child result"),+ );+ const lateRejection = expect(lateAgentMessage).rejects.toThrow("queued session input is suspended");+ await new Promise<void>((resolve) => setTimeout(resolve, 0));++ await harness.session.prompt("explicit user resume");+ await lateRejection;+ await harness.session.waitForIdle();+ expect(getUserTexts(harness)).toEqual(["explicit user resume"]);+ });++ it("invalidates late agent-message admission when queued work is resumed", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ harness.session.requestAbort();+ const lateAgentMessage = harness.session.acceptAgentMessagePrompt(+ agentPromptText("agentmsg_resume_queue", "late child result"),+ );+ const lateRejection = expect(lateAgentMessage).rejects.toThrow("queued session input is suspended");+ await new Promise<void>((resolve) => setTimeout(resolve, 0));++ harness.session.resumeQueuedWork();+ await lateRejection;+ await harness.session.waitForIdle();+ expect(getUserTexts(harness)).toEqual([]);+ });+it("waitForIdle resolves when the queue is cleared while the pump is suspended", async () => {const harness = await createHarness();harnesses.push(harness);diff --git a/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts b/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.tsindex 6889e82776..19ab4a7f43 100644--- a/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts+++ b/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts@@ -750,7 +750,7 @@ function delay(ms: number): Promise<void> {}describe("ENG-4603 worker recovery convergence", () => {- it("allows only the current generation to replace a crashed resident worker", async () => {+ it("waits for fresh client context before replacing a crashed resident worker", async () => {if (process.platform === "win32") return;const paths = await createPaths();const predecessor = spawnSupervisor(paths);@@ -759,9 +759,8 @@ describe("ENG-4603 worker recovery convergence", () => {await waitForType(predecessor, "ready", 60_000);const predecessorClient = await connectEventually(paths.socketPath);const summary = await createResidentSession(predecessorClient, paths.agentDir);- const activeSessionId = summary.activeSessionId ?? summary.id;const originalWorkerPid = summary.workerPid;- if (!originalWorkerPid) throw new Error("Resident worker did not expose its pid");+ if (!originalWorkerPid || !summary.sessionFile) throw new Error("Resident worker did not expose its identity");const originalWorkerStartId = getProcessStartId(originalWorkerPid);const originalWorkerIdentity = registerFixtureProcess(originalWorkerPid, originalWorkerStartId, "worker")!;@@ -775,9 +774,50 @@ describe("ENG-4603 worker recovery convergence", () => {await waitForExactProcessExit(originalWorkerPid, originalWorkerStartId);const successorClient = await connectEventually(paths.socketPath);+ let failed: DaemonWorkerDescriptor | undefined;+ const failedDeadline = Date.now() + 30_000;+ while (Date.now() < failedDeadline) {+ const candidate = readWorkerDescriptor(paths.descriptorDir);+ if (candidate.pid === originalWorkerPid && candidate.lifecycle === "failed") {+ failed = candidate;+ break;+ }+ await delay(25);+ }+ if (!failed) throw new Error("Successor did not retain the failed resident");+ await delay(750);+ expect(readWorkerDescriptor(paths.descriptorDir)).toMatchObject({+ pid: originalWorkerPid,+ lifecycle: "failed",+ });++ const recovered = await successorClient.request(+ {+ type: "create",+ sessionPath: summary.sessionFile,+ continueRecent: false,+ config: {+ agentDir: paths.agentDir,+ apiKey: "faux-key",+ cwd: paths.agentDir,+ extensions: [fauxExtensionPath],+ model: "faux",+ noContextFiles: true,+ noExtensions: false,+ noSkills: true,+ noTools: true,+ provider: "faux",+ },+ launchEnv: { PRIME_AGENT_TEST_FRESH_CONTEXT: "1" },+ },+ 60_000,+ );+ if (!recovered.success) throw new Error(recovered.error);+ const recoveredSummary = requireSummary(recovered.data);+let replacement: DaemonWorkerDescriptor | undefined;- const deadline = Date.now() + 30_000;- while (Date.now() < deadline) {+ const replacementDeadline = Date.now() + 30_000;+ while (Date.now() < replacementDeadline) {const candidate = readWorkerDescriptor(paths.descriptorDir);if (candidate.pid !== originalWorkerPid && candidate.lifecycle === "ready") {replacement = candidate;@@ -785,20 +825,16 @@ describe("ENG-4603 worker recovery convergence", () => {}await delay(25);}- if (!replacement) throw new Error("Current supervisor did not publish a replacement worker");+ if (!replacement) throw new Error("Fresh client context did not replace the failed worker");expect(getProcessStartId(replacement.pid)).toBe(replacement.processStartId);- await delay(750);expect(exactProcessIsAlive(replacement.pid, replacement.processStartId)).toBe(true);expect(readdirSync(paths.descriptorDir).filter((name) => name.endsWith(".json"))).toHaveLength(1);- const listed = await successorClient.request({ type: "list" });- if (!listed.success) throw new Error(listed.error);- const sessions = (listed.data as { sessions: unknown[] }).sessions;- expect(sessions).toHaveLength(1);- expect(requireSummary(sessions[0]).workerPid).toBe(replacement.pid);- const connection = await DaemonAgentConnection.attach(successorClient, activeSessionId, {- recoverDaemon: async () => {},- });+ const connection = await DaemonAgentConnection.attach(+ successorClient,+ recoveredSummary.activeSessionId ?? recoveredSummary.id,+ { recoverDaemon: async () => {} },+ );await connection.getInitialSnapshot();await connection.prompt("after recovery");await connection.waitForIdle();@@ -815,7 +851,7 @@ describe("ENG-4603 worker recovery convergence", () => {await waitForExit(successor);await waitForExactProcessExit(replacement.pid, replacement.processStartId);await terminateTrackedFixtureProcess(predecessor);- }, 120_000);+ }, 150_000);it("rejects stale commands at worker receipt and before public journal insertion", async () => {if (process.platform === "win32") return;diff --git a/packages/coding-agent/test/suite/regressions/617-subagent-terminal-agent-message.test.ts b/packages/coding-agent/test/suite/regressions/617-subagent-terminal-agent-message.test.tsindex 4b8336d975..7f04a5169f 100644--- a/packages/coding-agent/test/suite/regressions/617-subagent-terminal-agent-message.test.ts+++ b/packages/coding-agent/test/suite/regressions/617-subagent-terminal-agent-message.test.ts@@ -1,21 +1,18 @@import { fauxAssistantMessage } from "@earendil-works/pi-ai";-import { afterEach, describe, expect, it } from "vitest";-import {- AGENT_MESSAGE_CUSTOM_TYPE,- type AgentSessionMessage,- createAgentSessionMessage,-} from "../../../src/core/agent-messages.js";-import { createHarness, type Harness } from "../harness.js";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { CustomMessage } from "../../../src/core/messages.js";+import { waitForHeadlessCompletion } from "../../../src/modes/headless-completion.js";+import { createHarness, getAssistantTexts, type Harness } from "../harness.js";-function terminalMessage(messages: readonly unknown[]): AgentSessionMessage | undefined {- return messages.find(- (message): message is AgentSessionMessage =>+function terminalNotices(messages: readonly unknown[]): CustomMessage[] {+ return messages.filter(+ (message): message is CustomMessage =>typeof message === "object" &&message !== null &&"role" in message &&"customType" in message &&(message as { role?: unknown }).role === "custom" &&- (message as { customType?: unknown }).customType === AGENT_MESSAGE_CUSTOM_TYPE,+ (message as { customType?: unknown }).customType === "rlm_child_terminal_notice",);}@@ -30,37 +27,15 @@ describe("#617 subagent terminal agent messages", () => {parent = undefined;});- it("delivers a child completion without a reply as an attributed agent message", async () => {+ it("delivers a child completion without a reply through the private typed notice path", async () => {const childSessionName = "terminal-worker";+ const sendAgentMessage = vi.fn(async () => {+ throw new Error("synthesized terminal notices must not use agent_message");+ });child = await createHarness({agentMessageController: {listAgents: () => ({ agents: [] }),- sendAgentMessage: async (input) => {- expect(input).toMatchObject({- target: parent!.session.sessionId,- message: expect.stringContaining("completed without sending a reply"),- });- const message = createAgentSessionMessage({- id: "agentmsg-terminal-completion",- source: "agent_message",- message: input.message,- from: {- activeSessionId: "child-active",- sessionId: child!.session.sessionId,- sessionName: childSessionName,- },- fromRelationship: "child",- target: { activeSessionId: "parent-active", sessionId: parent!.session.sessionId },- });- await parent!.session.acceptAgentMessagePrompt(message.content, { customMessage: message });- return {- id: message.details.id,- source: "agent_message",- target: { activeSessionId: "parent-active", sessionId: parent!.session.sessionId },- message: input.message,- deliveryStatus: "delivered",- };- },+ sendAgentMessage,},});parent = await createHarness({@@ -75,51 +50,58 @@ describe("#617 subagent terminal agent messages", () => {const spawned = await parent.session.runRlmChild("finish without replying", { name: childSessionName });- await expect- .poll(() => terminalMessage(parent!.session.messages))- .toMatchObject({- customType: AGENT_MESSAGE_CUSTOM_TYPE,- details: {- id: "agentmsg-terminal-completion",- fromRelationship: "child",- from: { sessionId: child.session.sessionId, sessionName: childSessionName },- },- content: expect.stringContaining(`[from child:${childSessionName}]`),- });- expect(parent.session.messages).not.toContainEqual(- expect.objectContaining({ customType: "rlm_child_terminal_notice" }),- );- expect(terminalMessage(parent.session.messages)?.content).toContain(spawned.rlm_child_id);+ await expect.poll(() => terminalNotices(parent!.session.messages)).toHaveLength(1);+ expect(sendAgentMessage).not.toHaveBeenCalled();+ expect(terminalNotices(parent.session.messages)[0]).toMatchObject({+ customType: "rlm_child_terminal_notice",+ details: {+ kind: "completed_without_reply",+ childId: spawned.rlm_child_id,+ sessionName: childSessionName,+ },+ content: expect.stringContaining(+ `RLM child ${childSessionName} (${spawned.rlm_child_id}) completed without sending a reply`,+ ),+ });});- it("falls back to an injected notice when the agent message cannot be delivered", async () => {- // A controller that always rejects: the parent must still learn the child- // finished. Losing the notice entirely is worse than losing attribution.++ it("waits for the parent to consume a child terminal notice", async () => {+ const childSessionName = "headless-worker";+ const sendAgentMessage = vi.fn(async () => {+ throw new Error("synthesized terminal notices must not use agent_message");+ });child = await createHarness({agentMessageController: {listAgents: () => ({ agents: [] }),- sendAgentMessage: async () => {- throw new Error("delivery unavailable");- },+ sendAgentMessage,},});parent = await createHarness({+ serializedRefine: true,+ rlmDepth: 0,+ rlmMaxDepth: 1,subagentRuntimeHost: {createRlmSubagentRuntime: async () => ({ session: child!.session }),deleteRlmSubagentRuntime: async () => {},- } as never,+ },});- child.setResponses([fauxAssistantMessage("done, no reply to parent")]);- parent.setResponses([fauxAssistantMessage("parent ack")]);+ child.setResponses([fauxAssistantMessage("child completed")]);+ parent.setResponses([fauxAssistantMessage("parent consumed the child result")]);- await parent.session.runRlmChild("do the work");- await new Promise((resolve) => setTimeout(resolve, 200));+ const spawned = await parent.session.runRlmChild("finish without replying", { name: childSessionName });+ await waitForHeadlessCompletion(parent.session, { waitForRlmQuiescence: true });- // The notice arrives some way: either the agent message or the injected- // fallback, but never silently dropped.- const sawNotice = parent.session.messages.some((message) => {- const content = (message as { content?: unknown }).content;- return typeof content === "string" && content.includes("completed without sending a reply");- });- expect(sawNotice || terminalMessage(parent.session.messages) !== undefined).toBe(true);- }, 60_000);+ expect(sendAgentMessage).not.toHaveBeenCalled();+ expect(terminalNotices(parent.session.messages)).toEqual([+ expect.objectContaining({+ details: expect.objectContaining({+ kind: "completed_without_reply",+ childId: spawned.rlm_child_id,+ sessionName: childSessionName,+ }),+ }),+ ]);+ expect(getAssistantTexts(parent)).toEqual(["parent consumed the child result"]);+ expect(parent.session.hasRunningRlmChildren()).toBe(false);+ });});