Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): settle owned continuations and report deferred retirement failures
zqchris4585a81c1920
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.tsindex 52918a168f..1b05caefc9 100644--- a/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts@@ -73,12 +73,12 @@ describe('Pi package runtime invalidation', () => {listActiveSessions: () => [caller.instance, idle.instance],getSessionMeta: vi.fn(async (id: string) => ({ id, agentKind: 'pi' as const, workDir: '/repo',model: 'm', title: id, createdAt: 1, updatedAt: 1 })),- closeSessionIfCurrent: async (instance) => {+ closeSessionIfCurrent: async (instance, _reason, opts) => {if (instance === idle.instance) {await closing.promise;if (fails) throw new Error('idle process exit unconfirmed');}- return instance.closeAfterCurrentTurn();+ return instance.closeAfterCurrentTurn(opts);},};await caller.instance.send('update');@@ -136,7 +136,7 @@ describe('Pi package runtime invalidation', () => {getSessionMeta: vi.fn(async (id: string) => ({ id, agentKind: 'pi' as const, workDir: '/repo',model: 'm', title: id, createdAt: 1, updatedAt: 1 })),closeSessionIfCurrent: async (instance, _reason, opts) => opts?.afterCurrentTurn- ? instance.closeAfterCurrentTurn() : (await instance.close(), 'closed'),+ ? instance.closeAfterCurrentTurn(opts) : (await instance.close(), 'closed'),};await caller.instance.send('update and continue');await sibling.instance.send('build');@@ -157,6 +157,37 @@ describe('Pi package runtime invalidation', () => {expect(sibling.handle.send).toHaveBeenCalledOnce();});+ it('delivers a deferred sibling failure after the caller has closed, without replay', async () => {+ const caller = live('caller');+ const sibling = live('sibling');+ sibling.close.mockRejectedValueOnce(new Error('exit unconfirmed'));+ const maker: InvalidationMaker = {+ advanceLocalPiPackageRuntimeGeneration: vi.fn(),+ listActiveSessions: () => [caller.instance, sibling.instance],+ getSessionMeta: vi.fn(async (id: string) => ({ id, agentKind: 'pi' as const, workDir: '/repo',+ model: 'm', title: id, createdAt: 1, updatedAt: 1 })),+ closeSessionIfCurrent: async (instance, _reason, opts) => instance.closeAfterCurrentTurn(opts),+ };+ await caller.instance.send('update');+ await sibling.instance.send('build');+ const snapshot = await captureLocalPiPackageRuntimeInvalidationSnapshot(maker);+ expect(await settleLocalPiPackageRuntimeSnapshot(maker, snapshot, undefined, undefined,+ () => ({ type: 'text', source: 'pi', data: { isFinal: true, text: 'partial: restart-cindy-to-refresh-packages' } }))).toEqual({ runtimeConvergence: 'deferred' });+ caller.finish('update completed');+ await vi.waitFor(() => expect(caller.instance.getStatus()).toBe('closed'));+ sibling.finish('build saved');+ await vi.waitFor(() => expect(sibling.instance.getStatus()).toBe('error'));+ expect(sibling.seen.map(event => event.type)).toEqual(['text', 'done', 'text']);+ expect(sibling.seen[1].data).toMatchObject({ status: 'completed', result: 'build saved' });+ expect(sibling.seen[2].data).toMatchObject({ text: expect.stringContaining('restart-cindy-to-refresh-packages') });+ expect(sibling.seen[2].data).toMatchObject({ isFinal: true, text: expect.stringContaining('partial') });+ expect(caller.seen.map(event => event.type)).toEqual(['text', 'done']);+ expect(caller.handle.send).toHaveBeenCalledOnce();+ expect(sibling.handle.send).toHaveBeenCalledOnce();+ await sibling.instance.close();+ expect(sibling.close).toHaveBeenCalledTimes(2);+ });+it('replaces local ordinary Pi runtimes only', async () => {const sessions = [session('local-pi', 'pi'),diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 25b8c6ab25..e5451497ae 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -2045,7 +2045,7 @@ export function getMaker(): Maker {pendingPiPackageRuntimeSnapshots.push(snapshot);}},- onPiManagedPackageMutationSettled: async (callerSessionId, publishOutcome) => {+ onPiManagedPackageMutationSettled: async (callerSessionId, publishOutcome, createRetirementFailureEvent) => {const partial = () => publishOutcome({runtimeConvergence: 'partial',recoveryAction: 'restart-cindy-to-refresh-packages',@@ -2058,7 +2058,7 @@ export function getMaker(): Maker {}// The receipt has been sent, not necessarily consumed by Pi. Keep the// caller and busy siblings alive until their owned turn settles.- await settleLocalPiPackageRuntimeSnapshot(maker, snapshot, callerSessionId, publishOutcome);+ await settleLocalPiPackageRuntimeSnapshot(maker, snapshot, callerSessionId, publishOutcome, createRetirementFailureEvent);},getGhostRosterPrompt,// 仅为命中视觉桥目标的 Pi 模型注册 Layer C 工具。diff --git a/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts b/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.tsindex 88d437943b..0b33d68a11 100644--- a/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts+++ b/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts@@ -69,7 +69,7 @@ export async function captureLocalPiPackageRuntimeInvalidationSnapshot(export async function invalidateLocalPiPackageRuntimeSnapshot(maker: InvalidationMaker,snapshot: PiPackageRuntimeInvalidationSnapshot,- opts?: { afterCurrentTurn?: boolean },+ opts?: { afterCurrentTurn?: boolean; failureEvent?: () => AgentEvent },): Promise<PiPackageRuntimeInvalidationResult> {const eligible = snapshot.entries.filter((entry) => entry.eligible);const requestedSessionIds = eligible.map(({ session }) => session.id);@@ -102,11 +102,14 @@ export async function settleLocalPiPackageRuntimeSnapshot(snapshot: PiPackageRuntimeInvalidationSnapshot,callerSessionId?: string,publishOutcome?: (outcome: PiManagedPackageRuntimeConvergence) => AgentEvent,+ createRetirementFailureEvent?: () => AgentEvent,): Promise<PiManagedPackageRuntimeConvergence> {const caller = snapshot.entries.find(({ session }) => session.id === callerSessionId)?.session;const release = publishOutcome ? caller?.acquireTurnLease() : undefined;try {- const result = await invalidateLocalPiPackageRuntimeSnapshot(maker, snapshot, { afterCurrentTurn: true });+ const result = await invalidateLocalPiPackageRuntimeSnapshot(maker, snapshot, {+ afterCurrentTurn: true, failureEvent: createRetirementFailureEvent,+ });const outcome: PiManagedPackageRuntimeConvergence = result.failedSessionIds.length > 0|| (callerSessionId && !snapshot.entries.some(({ session, eligible }) => eligible && session.id === callerSessionId))? { runtimeConvergence: 'partial', recoveryAction: 'restart-cindy-to-refresh-packages' }diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.tsindex cf2a2feefd..f67ec157d6 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -381,6 +381,20 @@ function ordered(...names: string[]) {}describe('production Session event pipeline', () => {+ it('persists and broadcasts a retirement recovery receipt after a successful product terminal', async () => {+ const h = harness();+ h.emit(event('done', { status: 'completed', result: 'saved' }, { source: 'pi' }));+ const data = { isFinal: true, text: 'partial: restart-cindy-to-refresh-packages' };+ effects.fn('onAssistantTextEvent').mockClear();+ effects.fn('broadcast').mockClear();+ h.emit(event('text', data, { source: 'pi' }));+ expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledWith('task', data, null);+ expect(effects.fn('broadcast')).toHaveBeenCalled();+ expect(h.activity.isSessionInTurn('task')).toBe(false);+ expect(h.handle.send).not.toHaveBeenCalled();+ await h.dispose();+ });+it('keeps continuation segments running, then seals the final product boundary', async () => {const h = harness();vi.setSystemTime(1000);@@ -789,6 +803,36 @@ describe('provider turn observer on real Session.send', () => {);await h.dispose();});+ it.each(['local', 'remote', 'unowned'] as const)('holds idle closure only for a scheduled Host continuation: %s', async (owner) => {+ const terminal = deferred(), closed = deferred(), deps = observerDeps();+ const log = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return this; } };+ const handle = {+ id: 'provider', agentKind: 'pi', model: 'test-model',+ send: vi.fn(async () => {}), close: vi.fn(async () => { closed.resolve(); }),+ isTurnRunning: () => false, setInteractionResolver() {},+ async *events() {+ await terminal.promise;+ yield { type: 'done', source: 'pi', data: { status: 'completed', silentStop: true } } as AgentEvent;+ await closed.promise;+ },+ } as unknown as AgentSessionHandle;+ const session = new Session({ id: 'task', agentKind: 'pi', workDir: '/unused', handle,+ capabilities: {} as never, logger: log, turnStallMs: 0 });+ if (owner === 'remote') Object.defineProperty(session, 'remoteHostId', { value: 'ssh-host' });+ const dispose = owner === 'unowned' ? () => {} : installSessionTurnObserver(deps, session);+ const seen: AgentEvent[] = [];+ session.onEvent(event => seen.push(event));+ await session.send('work');+ terminal.resolve();+ await vi.waitFor(() => expect(seen.some(event => event.type === 'done')).toBe(true));+ expect(deps.silentStopTurnLeaseGate.schedule).toHaveBeenCalledTimes(owner === 'local' ? 1 : 0);+ expect(await session.closeIfIdle()).toBe(owner !== 'local');+ dispose();+ if (owner === 'local') expect(await session.closeIfIdle()).toBe(true);+ expect(handle.close).toHaveBeenCalledOnce();+ expect(handle.send).toHaveBeenCalledOnce();+ });+it('leaves remote provider admission and leases to the remote host', async () => {const h = harness(),deps = observerDeps();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.tsindex c774b243b0..9befebfda3 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts@@ -338,6 +338,10 @@ describe('shared-process session turn lease', () => {const runtime = new Session({ id: 'source-1', agentKind: 'pi', workDir: '/repo', handle,capabilities: {} as never, logger, turnStallMs: 0 });const seen: AgentEvent[] = [];+ runtime.setTurnLifecycleObserver({+ beforeProviderStart() {}, onUndispatched() {},+ onTerminal({ turnGeneration }) { runtime.claimHostTurnContinuation(turnGeneration); },+ });runtime.onEvent(event => seen.push(event));await runtime.send('work');const generation = runtime.getTurnGeneration();diff --git a/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts b/apps/desktop/src/main/maker-ipc/sessionTurnObserver.tsindex 8e9909847f..d4c1e7e4a5 100644--- a/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts+++ b/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts@@ -71,6 +71,7 @@ export function installSessionTurnObserver(deps: InstallSessionTurnObserverDeps,// the bounded auto-resume decision runs. Its exact lease is either// replaced by the next provider generation or released by settle.const scheduled = deps.silentStopTurnLeaseGate.schedule(session.id, event, turnLeaseId);+ if (scheduled) session.claimHostTurnContinuation(turnGeneration);if (!scheduled) {deps.log.debug('ignored duplicate silent-stop terminal for the current turn', {sessionId: session.id,diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 8895c8d5ab..0e97facbf7 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -233,7 +233,10 @@ Full access 读/搜/bash 与原生对齐的需求正本见 [`pi-full-access-nati调用者的现有 Host lease 必须覆盖兄弟关闭结果汇总及准确收敛回执的 Session 分发;不能把回执入队当作已分发。交付等待有界,显式关闭仍可结束旧实例。Host 已放弃续跑时,即使 turn lease 记账失败,也应按原实例与 generation 释放退役等待;- 记账失败仍不得据此派发后续工作或重放副作用。+ 记账失败仍不得据此派发后续工作或重放副作用。只有 Host 实际登记续跑的 generation+ 才能阻止空闲关闭;远端/无 observer 接管的 silent-stop 不得凭终态自行占有续跑门。+ 延迟退役的实际关闭若失败,应在该实例的监听器清理前补发 `partial` 与+ `restart-cindy-to-refresh-packages` 恢复回执;不改判此前成功结果,不自动重放工作。- 设置页明确要求停用/移除的即时失效路径仍可关闭运行时;Session 必须在清除监听器和当前 turn 归属前给未结算工作发明确失败。用户 Stop 则保持取消,不触发重放。- provider idle、进程退出、事件流结束都不是成功证明。Session 用已有 turn generation/diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex efc1ce29b8..42a450c3f5 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -661,10 +661,13 @@ export interface AgentDeps {* Native package success remains authoritative; deferred is not a failure.* publishOutcome returns the exact queued event so the Host can retain its* caller lease until Session dispatches that receipt (not a persistence ACK).+ * The event factory supplies a fresh complete receipt for eventual retirement+ * failure, without writing into the possibly closed caller queue.*/onPiManagedPackageMutationSettled?: (callerSessionId: string | undefined,publishOutcome: (outcome: PiManagedPackageRuntimeConvergence) => AgentEvent,+ createRetirementFailureEvent: () => AgentEvent,) => Promise<void>;/**diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 3d3e0e7e72..02d63e9b63 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -708,7 +708,12 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {if (outcome === 'native-failure') throw new PiManagedPackageMutationFailedError(true, 'native-command-failed');return { changed: true, affectedPackage: { source: 'self', enabled: true } };});- deps.onPiManagedPackageMutationSettled = vi.fn(async (_id, publish) => {+ deps.onPiManagedPackageMutationSettled = vi.fn(async (_id, publish, createFailureEvent) => {+ const failure = createFailureEvent();+ expect(failure).not.toBe(createFailureEvent());+ expect(failure).toMatchObject({ type: 'text', source: 'pi', data: {+ isFinal: true, text: expect.stringContaining('restart-cindy-to-refresh-packages'),+ } });const result = await session.closeAfterCurrentTurn();convergenceReceipt = publish({ runtimeConvergence: result === 'deferred' ? 'deferred' : 'complete' });});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.tsindex bfa41e1144..e37769a752 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts@@ -1,4 +1,5 @@-import { mkdtempSync, rmSync } from 'node:fs';+import { mkdtempSync } from 'node:fs';+import { rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -95,9 +96,11 @@ describe('Pi long tool lifecycle through real stdio RPC', () => {// Only terminate the descendant created and reported by this fixture.if (descendantPid) {try { process.kill(descendantPid, 'SIGKILL'); } catch { /* already exited */ }+ // kill() requests termination; Windows may still hold the fixture cwd.+ await vi.waitFor(() => expect(() => process.kill(descendantPid!, 0)).toThrow(), { timeout: 5_000 });}await session?.close();- if (root) rmSync(root, { recursive: true, force: true });+ if (root) await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });session = undefined;descendantPid = undefined;fixture.transport = null;diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 5dc0bb5ab7..38b9ffcd32 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -656,7 +656,14 @@ async function notifyPiManagedPackageMutationSettled(return;}try {- await callback(callerSessionId, publishOutcome);+ await callback(callerSessionId, publishOutcome, () => ({+ type: 'text', source: 'pi', data: {+ text: piManagedPackageRuntimeConvergenceReceipt({+ runtimeConvergence: 'partial', recoveryAction: 'restart-cindy-to-refresh-packages',+ }),+ isFinal: true,+ },+ }));} catch {// Native success remains authoritative. Expose only a stable recovery// outcome; raw host/session errors stay out of logs and receipts.diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex 4ce37bf212..14269f0c91 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -22,7 +22,7 @@ import { clearTimeout as clearNodeTimeout, setTimeout as setNodeTimeout } from 'import type { AgentKind } from './types/common.js';import type { Capabilities } from './types/capabilities.js';-import type { ForkSdkSessionOptions, ForkSdkSessionResult } from './types/events.js';+import type { AgentEvent, ForkSdkSessionOptions, ForkSdkSessionResult } from './types/events.js';import type {ScanAtResourcesOptions,ScanAtResourcesResult,@@ -1160,13 +1160,13 @@ export class Maker {async closeSessionIfCurrent(session: Session,reason: Exclude<MakerSessionCloseReason, 'unexpected'> = 'requested',- opts?: { afterCurrentTurn?: boolean },+ opts?: { afterCurrentTurn?: boolean; failureEvent?: () => AgentEvent },): Promise<'closed' | 'deferred' | void> {if (this.activeSessions.get(session.id) !== session) return;// First closer owns the cause. A later concurrent close must not relabel// a user-requested close as an internal replacement (or vice versa).if (!this.closeReasons.has(session)) this.closeReasons.set(session, reason);- if (opts?.afterCurrentTurn) return session.closeAfterCurrentTurn();+ if (opts?.afterCurrentTurn) return session.closeAfterCurrentTurn(opts);await session.close();return 'closed';// status listener 会自动清理 activeSessions 并 emitdiff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.tsindex d79e3a5417..8ee5afc8f4 100644--- a/packages/maker-core/src/session.close.test.ts+++ b/packages/maker-core/src/session.close.test.ts@@ -26,7 +26,7 @@ function createDeferred(): { promise: Promise<void>; resolve: () => void } {}describe('Session close lifecycle', () => {- function liveTurn() {+ function liveTurn(hostContinuation = true) {const queue = createAsyncQueue<AgentEvent>();let running = false;const handle = {@@ -41,10 +41,48 @@ describe('Session close lifecycle', () => {const session = new Session({ id: 'pi-task', agentKind: 'pi', workDir: '/repo',handle, capabilities: {} as never, logger: createLogger(), turnStallMs: 0 });const seen: AgentEvent[] = [];+ if (hostContinuation) session.setTurnLifecycleObserver({+ beforeProviderStart() {}, onUndispatched() {},+ onTerminal({ turnGeneration, event, isCurrentGeneration }) {+ if (isCurrentGeneration && event.type === 'done' && (event.data as { silentStop?: boolean }).silentStop) {+ session.claimHostTurnContinuation(turnGeneration);+ }+ },+ });session.onEvent((event) => seen.push(event));return { session, handle, queue, seen, idle: () => { running = false; } };}+ it('recycles unclaimed silent-stop terminals instead of inventing a Host owner', async () => {+ const { session, handle, queue, seen, idle } = liveTurn(false);+ await session.send('work');+ idle();+ queue.push({ type: 'done', source: 'pi', data: { status: 'completed', silentStop: true } });+ await vi.waitFor(() => expect(seen).toHaveLength(1));+ expect(await session.closeIfIdle()).toBe(true);+ expect(handle.close).toHaveBeenCalledOnce();+ expect(handle.send).toHaveBeenCalledOnce();+ });++ it('publishes deferred retirement failure before listeners are cleared, retaining successful work', async () => {+ const { session, handle, queue, seen, idle } = liveTurn();+ const close = vi.mocked(handle.close);+ close.mockRejectedValueOnce(new Error('process exit unconfirmed'));+ const recovery: AgentEvent = { type: 'text', source: 'pi', data: { text: 'partial: restart-cindy-to-refresh-packages' } };+ await session.send('work');+ await session.closeAfterCurrentTurn({ failureEvent: () => recovery });+ idle();+ queue.push({ type: 'done', source: 'pi', data: { status: 'completed', result: 'saved result' } });+ await vi.waitFor(() => expect(session.getStatus()).toBe('error'));+ expect(seen.map(event => event.type)).toEqual(['done', 'text']);+ expect(seen[0]?.data).toMatchObject({ status: 'completed', result: 'saved result' });+ expect(seen[1]).toBe(recovery);+ expect(handle.send).toHaveBeenCalledOnce();+ await session.close();+ expect(session.getStatus()).toBe('closed');+ expect(close).toHaveBeenCalledTimes(2);+ });+it('keeps a failed tool caller alive until its reply and product terminal are consumed', async () => {const { session, handle, queue, seen, idle } = liveTurn();await session.send('update and report', { turnAttemptToken: 7 });diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 2167c472df..0d638b1cce 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -1318,19 +1318,30 @@ export class Session {}/** Retire this runtime at its product terminal boundary, without replaying work. */- async closeAfterCurrentTurn(): Promise<'closed' | 'deferred'> {+ async closeAfterCurrentTurn(opts?: { failureEvent?: () => AgentEvent }): Promise<'closed' | 'deferred'> {this.retirementRequested = true;if (this.hasUnsettledTurn() || this.sendReservation !== null|| this.hostTurnLeases.size > 0- || this.retirementContinuationGeneration === this.turnGeneration) return 'deferred';+ || this.retirementContinuationGeneration === this.turnGeneration) {+ this.retirementFailureEvent ??= opts?.failureEvent;+ return 'deferred';+ }await this.close();return 'closed';}private retirementRequested = false;private retirementContinuationGeneration: number | null = null;+ private retirementFailureEvent: (() => AgentEvent) | undefined;++ /** The Host has actually scheduled bounded continuation for this terminal. */+ claimHostTurnContinuation(generation: number): void {+ if (this.terminationStarted || generation !== this.turnGeneration+ || this.terminalEventObservedGeneration !== generation) return;+ this.retirementContinuationGeneration = generation;+ }- /** The existing Host guard has declined/exhausted continuation for this turn. */+ /** The Host declined/exhausted continuation or released its observer ownership. */settleHostTurnContinuation(generation: number): void {if (generation !== this.turnGeneration || this.retirementContinuationGeneration !== generation) return;this.retirementContinuationGeneration = null;@@ -1377,6 +1388,17 @@ export class Session {this.cancelSendReservation(this.sendReservation);await this.handle.close(teardown);closeSucceeded = true;+ } catch (error) {+ const failureEvent = this.retirementFailureEvent;+ this.retirementFailureEvent = undefined;+ if (failureEvent) {+ // The provider queue is already fenced. Dispatch the Host's recovery+ // receipt before clearing listeners, without changing a successful turn.+ try { this.fanOutEvent(failureEvent()); } catch (notificationError) {+ this.logger.warn('runtime retirement recovery receipt failed', { error: String(notificationError) });+ }+ }+ throw error;} finally {this.sendReservation = null;this.unacceptedSendGeneration = null;@@ -1998,6 +2020,7 @@ export class Session {}setTurnLifecycleObserver(observer: SessionTurnLifecycleObserver | null): void {+ if (this.turnLifecycleObserver !== observer) this.settleHostTurnContinuation(this.turnGeneration);this.turnLifecycleObserver = observer;}@@ -2523,7 +2546,7 @@ export class Session {this.rememberReservationWindowPriorTerminal(event, listenerEvent);}if (isCurrentGeneration && isTerminal && !isBackgroundEvent && !lateErrorAfterDoneSnapshot && !reservationWindowLeftover) {- this.retirementContinuationGeneration = this.isSilentStopDoneEvent(event) ? this.turnGeneration : null;+ if (!this.isSilentStopDoneEvent(event)) this.retirementContinuationGeneration = null;this.clearTurnControl(resolvedGeneration);}const isLeftoverProductTerminal =@@ -2583,9 +2606,9 @@ export class Session {this.currentTurnAttemptToken = null;// 终态之后不再计 stall 额度。this.clearTurnStallWatchdog();- // A silent-stop done hands continuation to the existing bounded Host- // guard. Do not destroy the executor before that guard can continue it.- if (!this.isSilentStopDoneEvent(event)) this.finishRetirementIfSettled();+ // Only an actual Host claim keeps the executor available for bounded+ // silent-stop continuation; an unowned terminal can retire normally.+ this.finishRetirementIfSettled();} else if (isCurrentGeneration) {this.armTurnStallWatchdog();}