Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(goal): harden PI goal dispatch lifecycle

Chris360133ed9fcf
diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
index 3f1bf99d0b..4f0d93f6c1 100644
--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, beforeEach, vi } from 'vitest';
+import { TurnDispatchUnconfirmedError } from '@cindy/maker-core';
import type { AgentEvent, SessionSendResult } from '@cindy/maker-core';
import {
@@ -401,6 +402,75 @@ describe('GoalController', () => {
});
// ── setGoal / updateGoal ──
+ it('blocks an unconfirmed dispatch without retrying duplicate Goal work', async () => {
+ const local = makeController();
+ vi.spyOn(local.session, 'send').mockImplementation(async (
+ _message: Parameters<FakeSession['send']>[0],
+ opts: Parameters<FakeSession['send']>[1],
+ ) => {
+ opts?.onDispatching?.();
+ throw new TurnDispatchUnconfirmedError('Pi prompt acceptance timed out');
+ });
+
+ await local.controller.setGoal({ sessionId: 's1', objective: 'finish the work' });
+
+ expect(local.session.send).toHaveBeenCalledTimes(1);
+ expect(await local.storage.get('s1')).toMatchObject({
+ status: 'blocked',
+ turnsUsed: 0,
+ lastReason: expect.stringContaining('Pi prompt acceptance timed out'),
+ });
+ });
+
+ it('blocks a new Goal when its dormant agent session cannot be restored', async () => {
+ const local = makeController();
+ local.setHydratable(false);
+
+ await local.controller.setGoal({
+ sessionId: 's1',
+ objective: 'finish the work',
+ agentKind: 'pi',
+ });
+
+ expect(local.session.sends).toHaveLength(0);
+ expect(await local.storage.get('s1')).toMatchObject({
+ status: 'blocked',
+ turnsUsed: 0,
+ lastReason: expect.stringContaining('unable to restore the agent session'),
+ });
+ });
+
+ it('blocks and rejects a Goal edit when its session cannot be restored', async () => {
+ const local = makeController();
+ await local.storage.set(seededGoal({ status: 'active', objective: 'old objective' }));
+ local.setHydratable(false);
+
+ await expect(local.controller.setGoal({
+ sessionId: 's1',
+ objective: 'new objective',
+ })).rejects.toThrow('unable to restore the agent session for Goal');
+
+ expect(await local.storage.get('s1')).toMatchObject({
+ status: 'blocked',
+ objective: 'old objective',
+ lastReason: expect.stringContaining('unable to restore the agent session'),
+ });
+ expect(local.session.sends).toHaveLength(0);
+ });
+
+ it('surfaces a non-retryable first-turn send failure as blocked instead of active at zero turns', async () => {
+ const local = makeController();
+ vi.spyOn(local.session, 'send').mockRejectedValue(new Error('provider authentication failed'));
+
+ await local.controller.setGoal({ sessionId: 's1', objective: 'finish the work' });
+
+ expect(await local.storage.get('s1')).toMatchObject({
+ status: 'blocked',
+ turnsUsed: 0,
+ lastReason: expect.stringContaining('provider authentication failed'),
+ });
+ });
+
it('setGoal creates a new goal directly with default limits and fires the first turn', async () => {
await h.controller.setGoal({ sessionId: 's1', objective: 'ship the feature' });
const st = await h.storage.get('s1');
@@ -1389,6 +1459,8 @@ describe('GoalController', () => {
});
await startGoal(local);
expect(liveSession.sends).toHaveLength(1);
+ (local.controller as unknown as { goalTurnsInFlight: Set<string> })
+ .goalTurnsInFlight.delete('s1');
const firePromise = (
local.controller as unknown as { fireTurn(sessionId: string): Promise<void> }
@@ -1424,6 +1496,8 @@ describe('GoalController', () => {
});
await startGoal(local);
expect(ensureCalls).toBe(2);
+ (local.controller as unknown as { goalTurnsInFlight: Set<string> })
+ .goalTurnsInFlight.delete('s1');
const firePromise = (
local.controller as unknown as { fireTurn(sessionId: string): Promise<void> }
@@ -1503,8 +1577,10 @@ describe('GoalController', () => {
const internals = local.controller as unknown as {
fireTurn(sessionId: string): Promise<void>;
firing: Map<string, object>;
+ goalTurnsInFlight: Set<string>;
goalDispatchAbortControllers: Map<string, { owner: object; controller: AbortController }>;
};
+ internals.goalTurnsInFlight.delete('s1');
const oldFire = internals.fireTurn('s1');
await vi.waitFor(() => expect(acquireCalls).toBe(2));
@@ -1548,6 +1624,7 @@ describe('GoalController', () => {
fireTurn(sessionId: string): Promise<void>;
goalTurnsInFlight: Set<string>;
};
+ internals.goalTurnsInFlight.delete('s1');
const oldFire = internals.fireTurn('s1');
await vi.waitFor(() => expect(sendCalls).toBe(2));
@@ -2045,14 +2122,17 @@ describe('GoalController', () => {
expect(h.session.sends).toHaveLength(sendsBeforeResume);
});
- it('keeps a manual Resume paused when the session cannot hydrate, then allows retry', async () => {
+ it('blocks a manual Resume when the session cannot hydrate, then allows retry', async () => {
await startGoal(h);
await h.controller.pauseGoal('s1');
const sendsBeforeResume = h.session.sends.length;
h.setHydratable(false);
- await h.controller.resumeGoal('s1');
- expect((await h.storage.get('s1'))?.status).toBe('paused');
+ await expect(h.controller.resumeGoal('s1')).rejects.toThrow(
+ 'unable to restore the agent session for Goal',
+ );
+ expect((await h.storage.get('s1'))?.status).toBe('blocked');
+ expect((await h.storage.get('s1'))?.lastReason).toContain('unable to restore the agent session');
expect(h.session.sends).toHaveLength(sendsBeforeResume);
h.setHydratable(true);
@@ -2108,6 +2188,20 @@ describe('GoalController', () => {
expect(h.session.sends.at(-1)?.content).toContain('keep going');
});
+ it('blocks a dormant active goal when opening cannot restore its session', async () => {
+ const local = makeController();
+ local.setHydratable(false);
+ await local.storage.set(seededGoal({ status: 'active', objective: 'cannot restore' }));
+
+ await local.controller.resumeOnOpen('s1');
+
+ expect(await local.storage.get('s1')).toMatchObject({
+ status: 'blocked',
+ lastReason: expect.stringContaining('unable to restore the agent session'),
+ });
+ expect(local.session.sends).toHaveLength(0);
+ });
+
it('does not let a stale startup active snapshot overwrite a concurrent Stop', async () => {
const active = seededGoal({ status: 'active', objective: 'stay stopped' });
await h.storage.set(active);
@@ -2181,14 +2275,14 @@ describe('GoalController', () => {
expect(h2.session.sends.length).toBe(n);
});
- it('maybeContinueActiveGoal fires only when an active goal is attached and idle', async () => {
+ it('maybeContinueActiveGoal does not overlap an accepted Goal turn before provider running state arrives', async () => {
await h.controller.maybeContinueActiveGoal('s1'); // 无 goal → no-op
expect(h.session.sends).toHaveLength(0);
await startGoal(h);
const before = h.session.sends.length;
await h.controller.maybeContinueActiveGoal('s1');
await tick();
- expect(h.session.sends.length).toBe(before + 1);
+ expect(h.session.sends.length).toBe(before);
await h.controller.pauseGoal('s1');
const afterPause = h.session.sends.length;
await h.controller.maybeContinueActiveGoal('s1');
diff --git a/apps/desktop/src/main/goal-host/__tests__/sessionRestore.test.ts b/apps/desktop/src/main/goal-host/__tests__/sessionRestore.test.ts
index 905ab47f48..e8ac3d6131 100644
--- a/apps/desktop/src/main/goal-host/__tests__/sessionRestore.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/sessionRestore.test.ts
@@ -73,6 +73,26 @@ describe('Goal dormant session restore', () => {
expect(deps.wireSession).toHaveBeenCalledOnce();
});
+ it('rebuilds an error Session instead of returning the poisoned live object', async () => {
+ const poisoned = {
+ ...fakeSession(),
+ getStatus: vi.fn().mockReturnValue('error'),
+ } as unknown as Session;
+ const replacement = fakeSession();
+ const deps = baseDeps({
+ maker: {
+ getSession: vi.fn().mockReturnValue(poisoned),
+ getSessionMeta: vi.fn().mockResolvedValue(META),
+ createSession: vi.fn().mockResolvedValue(replacement),
+ },
+ });
+
+ await expect(restoreSessionForGoal('session-1', deps)).resolves.toBe(replacement);
+
+ expect(deps.maker.createSession).toHaveBeenCalledOnce();
+ expect(deps.wireSession).toHaveBeenCalledWith(replacement);
+ });
+
it('preserves a persisted null provider route when restoring a Pi session', async () => {
const deps = baseDeps({
maker: {
diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts
index 3ba74ba40c..1477d0373a 100644
--- a/apps/desktop/src/main/goal-host/controller.ts
+++ b/apps/desktop/src/main/goal-host/controller.ts
@@ -454,7 +454,15 @@ export class GoalController {
if (this.turns.get(sessionId) !== entryBoundary) return null;
if (!session) {
this.deps.logger.warn('[goal] setGoal edit: no live session', { sessionId });
- return null;
+ const failureBoundary = entryBoundary ?? freshTurn();
+ if (!entryBoundary) this.turns.set(sessionId, failureBoundary);
+ await this.blockDispatchFailure(
+ sessionId,
+ failureBoundary,
+ 'turn dispatch failed: unable to restore the agent session',
+ () => this.turns.get(sessionId) === failureBoundary,
+ );
+ throw new Error('unable to restore the agent session for Goal');
}
const sessionWasBusy = this.isBusy(sessionId);
if (sessionWasBusy) {
@@ -513,7 +521,7 @@ export class GoalController {
if (this.turns.get(sessionId) === activeBoundary) {
await this.fireTurn(sessionId);
}
- return updated;
+ return (await this.deps.storage.get(sessionId)) ?? updated;
} catch (error) {
if (this.turns.get(sessionId) === editBoundary) this.turns.delete(sessionId);
throw error;
@@ -570,7 +578,7 @@ export class GoalController {
if (this.turns.get(sessionId) === activeBoundary) {
await this.fireTurn(sessionId);
}
- return state;
+ return (await this.deps.storage.get(sessionId)) ?? state;
} catch (error) {
if (this.turns.get(sessionId) === createBoundary) this.turns.delete(sessionId);
throw error;
@@ -1013,11 +1021,19 @@ export class GoalController {
}
if (this.turns.get(sessionId) !== lookupBoundary) return;
if (!ensured) {
- if (!opts?.auto) {
- this.cancelDeferredManualResume(sessionId, { restoreUsageResume: true });
+ if (opts?.auto) {
+ if (this.turns.get(sessionId) === lookupBoundary) this.turns.delete(sessionId);
+ return;
}
- if (this.turns.get(sessionId) === lookupBoundary) this.turns.delete(sessionId);
- return;
+ this.completeDeferredManualResume(sessionId);
+ this.cancelUsageResume(sessionId);
+ await this.blockDispatchFailure(
+ sessionId,
+ lookupBoundary,
+ 'turn dispatch failed: unable to restore the agent session',
+ () => this.turns.get(sessionId) === lookupBoundary,
+ );
+ throw new Error('unable to restore the agent session for Goal');
}
if (!opts?.auto && this.isBusy(sessionId)) {
this.deferManualResumeUntilIdle(sessionId, lookupBoundary, state);
@@ -1135,7 +1151,8 @@ export class GoalController {
* resume-on-open(#review):重启后未活会话的 active 目标是 **dormant** —— resumeActiveGoals
* 不会硬 spawn,留着 status=active 但无 listener/timer。用户**打开该会话**时(renderer
* useGoalStatus 拉状态)调用此方法把它接着续上:active ∧ 当前未挂 listener(dormant)→
- * ensureSession 活化 + 挂 listener + 空闲则续一轮。否则(已在管 / 非 active / 活化失败)no-op。
+ * ensureSession 活化 + 挂 listener + 空闲则续一轮。已在管 / 非 active 时 no-op;
+ * 活化失败则转 blocked 并给出可见原因,不能继续显示成正在推进。
* 这样重开会话能让 active 目标自己跑下去,而不是卡死等用户重发 /goal。
*/
async resumeOnOpen(sessionId: string): Promise<void> {
@@ -1172,11 +1189,16 @@ export class GoalController {
}
} finally {
releaseAgentSwitchLock();
- if (!session && this.turns.get(sessionId) === lifecycleBoundary) {
- this.turns.delete(sessionId);
- }
}
- if (!session) return; // 活化失败(如 device-link 远程不可用)→ 留 dormant,下次打开再试
+ if (!session) {
+ await this.blockDispatchFailure(
+ sessionId,
+ lifecycleBoundary,
+ 'turn dispatch failed: unable to restore the agent session',
+ () => this.turns.get(sessionId) === lifecycleBoundary,
+ );
+ return;
+ }
if (this.turns.get(sessionId) !== lifecycleBoundary) return;
this.emit(state);
if (!this.isBusy(sessionId)) {
@@ -1364,6 +1386,9 @@ export class GoalController {
private isBusy(sessionId: string): boolean {
if (this.firing.has(sessionId)) return true;
+ // PI may acknowledge prompt acceptance before agent_start flips the
+ // provider running flag. Goal ownership bridges that acceptance gap.
+ if (this.goalTurnsInFlight.has(sessionId)) return true;
if (this.deps.isSessionInTurn(sessionId)) return true;
const session = this.deps.getSession(sessionId);
return session ? session.isTurnRunning() : false;
@@ -1666,6 +1691,32 @@ export class GoalController {
}
}
+ private async blockDispatchFailure(
+ sessionId: string,
+ boundary: TurnAccumulator,
+ lastReason: string,
+ isCurrent: () => boolean,
+ ): Promise<void> {
+ try {
+ const blocked = await this.trackPersistence(
+ boundary,
+ this.deps.storage.update(sessionId, {
+ status: 'blocked',
+ lastReason,
+ updatedAt: this.now(),
+ }),
+ );
+ if (!isCurrent()) return;
+ if (blocked) this.emit(blocked);
+ } catch (persistError) {
+ this.deps.logger.error('[goal] failed to persist dispatch failure', {
+ sessionId,
+ error: String(persistError),
+ });
+ }
+ if (isCurrent()) this.stopSession(sessionId);
+ }
+
private scheduleContinuation(sessionId: string): void {
const existing = this.timers.get(sessionId);
if (existing) clearTimeout(existing);
@@ -1931,7 +1982,12 @@ export class GoalController {
sessionId,
kind,
});
- if (isCurrentLifecycle()) this.stopSession(sessionId);
+ await this.blockDispatchFailure(
+ sessionId,
+ lifecycleBoundary,
+ 'turn dispatch failed: unable to restore the agent session',
+ isCurrentLifecycle,
+ );
return;
}
// deferred switch 可能刚把 live session 换成目标引擎的新对象;本会话若有 goal
@@ -2004,6 +2060,7 @@ export class GoalController {
if (!isCurrentDispatch()) return;
this.goalTurnsInFlight.delete(sessionId);
this.deps.logger.warn('[goal] send not accepted', { sessionId, kind, reason: result.reason });
+ this.scheduleContinuation(sessionId);
} else {
if (!isCurrentDispatch()) {
baselineStarted = false;
@@ -2018,11 +2075,28 @@ export class GoalController {
this.deps.onUndispatchedUserTurn?.(sessionId);
baselineStarted = false;
}
- if (dispatchBoundary ? isCurrentDispatch() : isCurrentLifecycle()) {
+ const failureBoundary = dispatchBoundary ?? lifecycleBoundary;
+ const isCurrentFailure = (): boolean =>
+ dispatchBoundary ? isCurrentDispatch() : isCurrentLifecycle();
+ if (isCurrentFailure()) {
this.goalTurnsInFlight.delete(sessionId);
}
- // SESSION_RUNNING:会话已有 turn 在跑(用户抢发等);该 turn 的 done 会再触发裁决。
this.deps.logger.warn('[goal] fireTurn send failed', { sessionId, kind, error: String(e) });
+ if (!isCurrentFailure()) return;
+
+ if ((e as { code?: unknown } | null)?.code === 'SESSION_RUNNING') {
+ // dispatch 前的窄 race;现有 turn 的终态会暂停 Goal,空闲检查则负责稍后重试。
+ this.scheduleContinuation(sessionId);
+ return;
+ }
+
+ const errorMessage = e instanceof Error ? e.message : String(e);
+ await this.blockDispatchFailure(
+ sessionId,
+ failureBoundary,
+ `turn dispatch failed: ${errorMessage}`,
+ isCurrentFailure,
+ );
} finally {
releaseAgentSwitchLock();
if (this.goalDispatchAbortControllers.get(sessionId)?.owner === firingOwner) {
diff --git a/apps/desktop/src/main/goal-host/sessionRestore.ts b/apps/desktop/src/main/goal-host/sessionRestore.ts
index a8d5915e9d..0647dd0635 100644
--- a/apps/desktop/src/main/goal-host/sessionRestore.ts
+++ b/apps/desktop/src/main/goal-host/sessionRestore.ts
@@ -39,7 +39,10 @@ export async function restoreSessionForGoal(
deps: RestoreGoalSessionDeps,
): Promise<SessionLike | undefined> {
const live = deps.maker.getSession(sessionId);
- if (live) return live;
+ // A failed close leaves the Session in Maker's live map with status=error.
+ // Do not hand that poisoned object back to Goal: Maker.createSession owns the
+ // retry-close-then-rebuild boundary for this exact state.
+ if (live && live.getStatus?.() !== 'error') return live;
const meta = await deps.maker.getSessionMeta(sessionId).catch(() => null);
if (!meta) {
diff --git a/apps/desktop/src/main/goal-host/types.ts b/apps/desktop/src/main/goal-host/types.ts
index 4f86a72bfa..8605b6d3c5 100644
--- a/apps/desktop/src/main/goal-host/types.ts
+++ b/apps/desktop/src/main/goal-host/types.ts
@@ -10,6 +10,7 @@ import type {
AgentKind,
SendOrigin,
SessionSendResult,
+ SessionStatus,
UserMessage,
} from '@cindy/maker-core';
@@ -150,6 +151,7 @@ export interface SessionLike {
},
): Promise<SessionSendResult>;
onEvent(listener: (event: AgentEvent) => void): () => void;
+ getStatus?(): SessionStatus;
isTurnRunning(): boolean;
abort(): Promise<void>;
}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 2a01174dc2..aa602e1cfd 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1171,6 +1171,22 @@ export class AgentNotAuthenticatedError extends Error {
}
}
+/**
+ * The adapter dispatched a turn request but could not determine whether the
+ * provider accepted it. The Session wrapper must fence the ambiguous handle
+ * before surfacing this error. Fencing prevents further execution but does not
+ * roll back completed side effects, so orchestrators must not blindly replay
+ * the same turn.
+ */
+export class TurnDispatchUnconfirmedError extends Error {
+ readonly code = 'TURN_DISPATCH_UNCONFIRMED';
+
+ constructor(msg: string, options?: ErrorOptions) {
+ super(msg, options);
+ this.name = 'TurnDispatchUnconfirmedError';
+ }
+}
+
export interface StartSessionOptions {
/**
* Business 层 session id (host 调用 maker.createSession 时传的 opts.id, 由
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index cad11202f9..40e945a491 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -7,6 +7,10 @@ const captured = vi.hoisted(() => ({
args: [] as string[],
env: {} as Record<string, string | undefined>,
requests: [] as Array<Record<string, unknown>>,
+ requestOptions: [] as Array<{
+ timeoutMs?: number;
+ refreshTimeoutOnEvent?: (event: { type: string }) => boolean;
+ } | undefined>,
closes: 0,
requestHandler: undefined as undefined | ((command: Record<string, unknown>) => Promise<{ success: boolean; data?: unknown; error?: string }>),
}));
@@ -34,23 +38,44 @@ vi.mock('../transport.js', () => ({
attachJsonlReader: () => {},
}));
-vi.mock('../rpc-client.js', () => ({
- PiRpcProcess: class {
- isClosed = false;
- async request(command: Record<string, unknown>) {
- captured.requests.push(command);
- if (captured.requestHandler) return captured.requestHandler(command);
- if (command.type === 'get_state') {
- return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
- }
- return { success: true, data: {} };
+vi.mock('../rpc-client.js', () => {
+ class PiRpcRequestTimeoutError extends Error {
+ readonly code = 'PI_RPC_TIMEOUT';
+ constructor(
+ readonly commandType: string,
+ readonly timeoutMs: number,
+ ) {
+ super(`pi rpc timeout after ${timeoutMs}ms: ${commandType}`);
+ this.name = 'PiRpcRequestTimeoutError';
}
- send(): void {}
- async close(): Promise<void> { this.isClosed = true; captured.closes += 1; }
- },
-}));
+ }
+ return {
+ PiRpcRequestTimeoutError,
+ PiRpcProcess: class {
+ isClosed = false;
+ async request(
+ command: Record<string, unknown>,
+ options?: {
+ timeoutMs?: number;
+ refreshTimeoutOnEvent?: (event: { type: string }) => boolean;
+ },
+ ) {
+ captured.requests.push(command);
+ captured.requestOptions.push(options);
+ if (captured.requestHandler) return captured.requestHandler(command);
+ if (command.type === 'get_state') {
+ return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ }
+ return { success: true, data: {} };
+ }
+ send(): void {}
+ async close(): Promise<void> { this.isClosed = true; captured.closes += 1; }
+ },
+ };
+});
import { PiAgent } from '../index.js';
+import { PiRpcRequestTimeoutError } from '../rpc-client.js';
import type { AgentDeps } from '../../base-agent.js';
import type { ModelDescriptor } from '../../../types/capabilities.js';
import type { Logger } from '../../../interfaces/logger.js';
@@ -78,6 +103,7 @@ describe('Pi provider-aware model routing', () => {
beforeEach(() => {
captured.args = [];
captured.requests = [];
+ captured.requestOptions = [];
captured.closes = 0;
captured.requestHandler = undefined;
agentHome = mkdtempSync(path.join(tmpdir(), 'pi-provider-home-'));
@@ -1455,6 +1481,50 @@ describe('Pi provider-aware model routing', () => {
await handle.close();
});
+ it('waits through Pi preflight compaction when accepting a prompt', async () => {
+ const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ const handle = await agent.startSession({
+ sessionId: 'prompt-acceptance-budget',
+ workingDir: cwd,
+ model: 'local-model',
+ });
+
+ await handle.send({ type: 'user', content: 'continue the goal' });
+
+ const promptIndex = captured.requests.findIndex((request) => request.type === 'prompt');
+ expect(promptIndex).toBeGreaterThanOrEqual(0);
+ expect(captured.requestOptions[promptIndex]).toMatchObject({ timeoutMs: 600_000 });
+ const refresh = captured.requestOptions[promptIndex]?.refreshTimeoutOnEvent;
+ expect(refresh?.({ type: 'compaction_start' })).toBe(true);
+ expect(refresh?.({ type: 'summarization_retry_scheduled' })).toBe(true);
+ expect(refresh?.({ type: 'agent_start' })).toBe(false);
+ await handle.close();
+ });
+
+ it('marks a true prompt acceptance timeout as an unconfirmed dispatch', async () => {
+ captured.requestHandler = async (command) => {
+ if (command.type === 'get_state') {
+ return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200_000 } } };
+ }
+ if (command.type === 'prompt') {
+ throw new PiRpcRequestTimeoutError('prompt', 600_000);
+ }
+ return { success: true, data: {} };
+ };
+ const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
+ const handle = await agent.startSession({
+ sessionId: 'prompt-acceptance-timeout',
+ workingDir: cwd,
+ model: 'local-model',
+ });
+
+ await expect(handle.send({ type: 'user', content: 'continue the goal' })).rejects.toMatchObject({
+ name: 'TurnDispatchUnconfirmedError',
+ code: 'TURN_DISPATCH_UNCONFIRMED',
+ });
+ await handle.close();
+ });
+
it('keeps a leading /skill: command at the prompt start even when Extra Dirs are configured', async () => {
const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
const handle = await agent.startSession({
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 63ea1f6218..29dc06ea6b 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -21,6 +21,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const knobs = vi.hoisted(() => ({
ctorThrows: false,
getStateRejects: false,
+ closeRejects: false,
closeCount: 0,
onExit: null as null | ((info: { code: number | null; signal: string | null }) => void),
onEvent: null as null | ((event: unknown) => void),
@@ -77,6 +78,7 @@ vi.mock('../rpc-client.js', () => ({
send(): void {}
async close(): Promise<void> {
knobs.closeCount++;
+ if (knobs.closeRejects) throw new Error('close unconfirmed (mock)');
this.isClosed = true;
}
get pid(): number { return 1234; }
@@ -104,6 +106,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
beforeEach(() => {
knobs.ctorThrows = false;
knobs.getStateRejects = false;
+ knobs.closeRejects = false;
knobs.closeCount = 0;
knobs.onExit = null;
knobs.onEvent = null;
@@ -246,6 +249,24 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(knobs.closeCount).toBe(1); // 已 spawn → 必须关掉,避免僵尸持有 ?session= 路由
});
+ it('quarantines a failed startup process until cleanup is confirmed', async () => {
+ knobs.getStateRejects = true;
+ knobs.closeRejects = true;
+ const agent = new PiAgent(buildDeps());
+
+ await expect(agent.startSession(opts())).rejects.toThrow(/cleanup remains unconfirmed/);
+ expect(knobs.spawnedEnvs).toHaveLength(1);
+ // Same business id cannot spawn while the old proc still fails cleanup.
+ await expect(agent.startSession(opts())).rejects.toThrow(/close unconfirmed/);
+ expect(knobs.spawnedEnvs).toHaveLength(1);
+
+ knobs.closeRejects = false;
+ knobs.getStateRejects = false;
+ const handle = await agent.startSession(opts());
+ expect(knobs.spawnedEnvs).toHaveLength(2);
+ await handle.close();
+ });
+
it('does not dispose ctx on the success path (dispose is deferred to close())', async () => {
const agent = new PiAgent(buildDeps());
const handle = await agent.startSession(opts());
diff --git a/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts b/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts
index 8d28a5bef4..61713fda24 100644
--- a/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts
@@ -8,7 +8,11 @@
import { describe, expect, it, vi } from 'vitest';
-import { PiRpcProcess, type PiRpcSpawnOptions } from '../rpc-client.js';
+import {
+ PiRpcProcess,
+ PiRpcRequestTimeoutError,
+ type PiRpcSpawnOptions,
+} from '../rpc-client.js';
import type { PiTransport, PiLineHandler, PiCloseHandler } from '../transport.js';
// ── Fake transport:捕获 writeLine,手动触发 onLine/onClose ─────────────
@@ -114,6 +118,57 @@ describe('PiRpcProcess response envelope validation', () => {
expect(resp.error).toBe('session load failed');
});
+ it('reports request timeouts with a stable command-aware error', async () => {
+ vi.useFakeTimers();
+ try {
+ const { transport } = makeFakeTransport();
+ const { proc } = makeProc({ transport });
+
+ const pending = proc.request({ type: 'prompt' }, { timeoutMs: 75_000 });
+ const rejected = expect(pending).rejects.toEqual(expect.objectContaining({
+ name: 'PiRpcRequestTimeoutError',
+ code: 'PI_RPC_TIMEOUT',
+ commandType: 'prompt',
+ timeoutMs: 75_000,
+ } satisfies Partial<PiRpcRequestTimeoutError>));
+ await vi.advanceTimersByTimeAsync(75_000);
+
+ await rejected;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('refreshes a request idle timeout on matching progress events', async () => {
+ vi.useFakeTimers();
+ try {
+ const { transport, emitLine, written } = makeFakeTransport();
+ const { proc } = makeProc({ transport });
+ const pending = proc.request(
+ { type: 'prompt' },
+ {
+ timeoutMs: 100,
+ refreshTimeoutOnEvent: (event) => event.type === 'compaction_start',
+ },
+ );
+ const sentFrame = JSON.parse(written[0]!.line) as { id: string };
+
+ await vi.advanceTimersByTimeAsync(90);
+ emitLine(JSON.stringify({ type: 'compaction_start', reason: 'threshold' }));
+ await vi.advanceTimersByTimeAsync(90);
+ emitLine(JSON.stringify({
+ type: 'response',
+ id: sentFrame.id,
+ command: 'prompt',
+ success: true,
+ }));
+
+ await expect(pending).resolves.toMatchObject({ success: true });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('unmatched response (late/wrong id) is dropped with a warn, not resolved', async () => {
const { transport, emitLine } = makeFakeTransport();
const { proc, logger } = makeProc({ transport });
@@ -136,7 +191,7 @@ describe('PiRpcProcess close semantics (bridge-disconnect vs explicit close)', (
// 轮 42 P2(codex-connector):bridge 断链(onClose 置 closed)后, 用户显式
// close() 仍必须执行 killRemoteSession —— 它走独立 SSH RPC 可送达 daemon;
// 复用 closed 做 close() 守卫会让显式关闭直接 return, 远端 pi 带凭证跑到
- // idle 回收。closeCalled 单独跟踪「用户已显式关闭」。
+ // idle 回收。成功 close 的共享 Promise 跟踪「已经明确关闭」。
const killRemoteSession = vi.fn(async () => {});
const { transport } = makeFakeTransport();
const { proc } = makeProc({ transport });
@@ -155,4 +210,19 @@ describe('PiRpcProcess close semantics (bridge-disconnect vs explicit close)', (
await proc.close();
expect(killRemoteSession).toHaveBeenCalledTimes(1);
});
+
+ it('retries remote termination after a failed close instead of reporting false success', async () => {
+ const killRemoteSession = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('relay offline'))
+ .mockResolvedValueOnce(undefined);
+ const { transport } = makeFakeTransport();
+ const { proc } = makeProc({ transport });
+ (transport as unknown as { killRemoteSession: unknown }).killRemoteSession = killRemoteSession;
+
+ await expect(proc.close()).rejects.toThrow(/remote daemon session may still be running/);
+ await expect(proc.close()).resolves.toBeUndefined();
+
+ expect(killRemoteSession).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/packages/maker-core/src/agents/pi/__tests__/transport.test.ts b/packages/maker-core/src/agents/pi/__tests__/transport.test.ts
index 9a7283eec8..cc8e71383c 100644
--- a/packages/maker-core/src/agents/pi/__tests__/transport.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/transport.test.ts
@@ -108,7 +108,7 @@ describe('createPiStdioTransport', () => {
}
});
- it('close() resolves even if child never confirms exit after SIGKILL (round 40-w4-t3 HIGH — no hang)', async () => {
+ it('rejects without hanging when SIGKILL exit cannot be confirmed', async () => {
vi.useFakeTimers();
try {
const { transport, child } = makeTransport();
@@ -118,15 +118,22 @@ describe('createPiStdioTransport', () => {
transport.onClose(onClose);
const closePromise = transport.close();
+ const rejected = expect(closePromise).rejects.toThrow(/did not confirm exit after SIGKILL/);
// SIGTERM 宽限期(3s)→ SIGKILL
await vi.advanceTimersByTimeAsync(3_000);
expect(child.kill).toHaveBeenCalledWith('SIGKILL');
- // SIGKILL 确认窗口(5s)超时 → close() 必须 resolve(不再永久挂住)
+ // SIGKILL 确认窗口(5s)超时 → close() 必须收口但不能谎报成功。
await vi.advanceTimersByTimeAsync(5_000);
- await closePromise;
- // 主动 close 语义:onClose 收到通知
- expect(onClose).toHaveBeenCalledTimes(1);
+ await rejected;
+ expect(onClose).not.toHaveBeenCalled();
expect(transport.isClosed()).toBe(true);
+
+ // 未看到真实 exit 前,重复 close 继续 fail closed。
+ await expect(transport.close()).rejects.toThrow(/did not confirm exit after SIGKILL/);
+ // 若进程随后终于退出,确认状态解除,后续幂等 close 才可成功。
+ child.emit('close', null, 'SIGKILL');
+ expect(onClose).toHaveBeenCalledTimes(1);
+ await expect(transport.close()).resolves.toBeUndefined();
} finally {
vi.useRealTimers();
}
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 65d8e98e6e..93c03fa022 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -56,6 +56,7 @@ function validateSdkSessionId(value: string): string {
import {
AgentNotAuthenticatedError,
BaseAgent,
+ TurnDispatchUnconfirmedError,
TurnPermissionPolicyUnsupportedError,
type AgentDeps,
type AgentSessionHandle,
@@ -190,6 +191,15 @@ function isLoopbackOnlyBaseUrl(baseUrl: string): boolean {
const PI_IMAGE_INPUT_UNSUPPORTED_CODE = 'PI_IMAGE_INPUT_UNSUPPORTED';
/** 手动压缩 = 一次完整 LLM 摘要调用(大上下文 + 网关排队),远超默认 30s RPC 超时。 */
const PI_COMPACT_TIMEOUT_MS = 600_000;
+/** prompt 接受前可能自动压缩,同样必须覆盖一次完整摘要调用。 */
+const PI_PROMPT_ACCEPTANCE_TIMEOUT_MS = PI_COMPACT_TIMEOUT_MS;
+const PI_PROMPT_ACCEPTANCE_PROGRESS_EVENTS = new Set([
+ 'compaction_start',
+ 'compaction_end',
+ 'summarization_retry_scheduled',
+ 'summarization_retry_attempt_start',
+ 'summarization_retry_finished',
+]);
/** 分支摘要同样可能触发一次完整 LLM 调用。 */
const PI_BRANCH_NAVIGATION_TIMEOUT_MS = 600_000;
@@ -499,15 +509,41 @@ function piExtraDirsPrompt(dirs: readonly string[]): string {
].join('\n');
}
+interface FailedPiStartupCleanup {
+ proc: PiRpcProcess;
+ promise: Promise<void> | null;
+ cleanupLocal?: () => void;
+}
+
export class PiAgent extends BaseAgent {
readonly kind: AgentKind = 'pi';
readonly capabilities: Capabilities;
+ private readonly failedStartupCleanups = new Map<string, FailedPiStartupCleanup>();
constructor(deps: AgentDeps) {
super(deps);
this.capabilities = this.buildCapabilities(PiAgent.baseCapabilities());
}
+ private async retryFailedStartupCleanup(sessionId: string): Promise<void> {
+ const entry = this.failedStartupCleanups.get(sessionId);
+ if (!entry) return;
+ const cleanup = entry.promise ?? entry.proc.close();
+ entry.promise = cleanup;
+ try {
+ await cleanup;
+ } catch (error) {
+ if (this.failedStartupCleanups.get(sessionId) === entry && entry.promise === cleanup) {
+ entry.promise = null;
+ }
+ throw error;
+ }
+ if (this.failedStartupCleanups.get(sessionId) === entry) {
+ this.failedStartupCleanups.delete(sessionId);
+ entry.cleanupLocal?.();
+ }
+ }
+
private static baseCapabilities(): Capabilities {
return {
switchModel: { supported: true },
@@ -860,6 +896,10 @@ export class PiAgent extends BaseAgent {
}
async startSession(opts: StartSessionOptions): Promise<AgentSessionHandle> {
+ const startupCleanupKey = opts.sessionId ?? '<anonymous>';
+ // A previous pre-publication Pi process for this business session must be
+ // confirmed dead before another spawn can begin.
+ await this.retryFailedStartupCleanup(startupCleanupKey);
// 轮 22 LOW-6:空串 remoteHostId 规范化 —— Boolean('') 是 false 会让会话
// 被判定本地但后续仍把 '' 传给 resolvePiNativeProviders 等, 行为分裂。
if (opts.remoteHostId === '') opts.remoteHostId = undefined;
@@ -2357,17 +2397,36 @@ export class PiAgent extends BaseAgent {
} catch {
/* best-effort:注销失败不掩盖原始启动错误 */
}
- // 轮 42 P1(codex-connector fresh evidence):startup 失败路径的 proc.close()
- // 被 .catch 吞掉 —— 远端 daemon 会话 killRemoteSession 失败时, pi 子进程
- // 可能仍带着凭证 env 在跑, 这里再删 configHome/permission/subagent 会让
- // 存活 pi 丢 bridge/permission 状态。与 onExit/close() 同口径: 远端会话
- // 失败不清理 runtime 文件, 残留交给 daemon idle 回收 / 下次 startSession
- // 的清陈旧目录兜底(轮 40-w4-t4); 本地 stdio close 后进程必死, 保持清理。
- await proc.close().catch(() => {});
- if (!remote) {
+ // startup 失败时必须确认 proc 已关闭。关闭失败的 proc 进入 session-keyed
+ // quarantine;后续同 session startSession 会先重试 cleanup,绝不直接 spawn。
+ // 远端失败时不清 runtime 文件;本地也只有确认进程结束后才清,避免存活
+ // 进程丢 bridge/permission 状态。
+ let closeError: unknown = null;
+ try {
+ await proc.close();
+ } catch (error) {
+ closeError = error;
+ this.failedStartupCleanups.set(startupCleanupKey, {
+ proc,
+ promise: null,
+ ...(!remote
+ ? { cleanupLocal: () => {
+ cleanupConfigHome();
+ cleanupRuntimeFiles();
+ } }
+ : {}),
+ });
+ }
+ if (!remote && !closeError) {
cleanupConfigHome();
cleanupRuntimeFiles();
}
+ if (closeError) {
+ throw new Error(
+ `pi startup failed and process cleanup remains unconfirmed: ${closeError instanceof Error ? closeError.message : String(closeError)}`,
+ { cause: err },
+ );
+ }
throw err;
}
@@ -2669,7 +2728,14 @@ export class PiAgent extends BaseAgent {
? await readPiUserEntryIds()
: null;
rejectIfCancelled(sendOpts, 'send');
- const resp = await proc.request(command);
+ const resp = await proc.request(command, {
+ timeoutMs: PI_PROMPT_ACCEPTANCE_TIMEOUT_MS,
+ // Prompt acceptance may legitimately span multiple compaction
+ // retries. Bound each silent interval, not the whole progressing
+ // preflight, so a healthy long compaction is not killed at 10m.
+ refreshTimeoutOnEvent: (event) =>
+ PI_PROMPT_ACCEPTANCE_PROGRESS_EVENTS.has(event.type),
+ });
if (!resp.success) {
throw new Error(`pi prompt rejected: ${resp.error ?? 'unknown'}`);
}
@@ -2679,6 +2745,19 @@ export class PiAgent extends BaseAgent {
// 只在 Provider 尚未接受本轮时回滚。接受后的 transcript 回调失败不代表
// turn 没启动;此时恢复旧 policy 会让正在运行的新 turn 用错安全边界。
if (!providerAccepted) activeTurnPermissionPolicy = previousTurnPermissionPolicy;
+ const rpcError = err as { code?: unknown; commandType?: unknown } | null;
+ if (
+ rpcError?.code === 'PI_RPC_TIMEOUT'
+ && rpcError.commandType === 'prompt'
+ ) {
+ // 接受等待超时后,原 prompt 仍可能在 preflight 压缩结束时迟到执行。
+ // 上抛稳定错误,让 Session 先占住关闭门再杀 transport;Goal 随后
+ // 明确阻塞并要求人工确认,绝不盲目重放可能已有副作用的 turn。
+ throw new TurnDispatchUnconfirmedError(
+ `Pi did not confirm prompt acceptance within ${PI_PROMPT_ACCEPTANCE_TIMEOUT_MS}ms`,
+ { cause: err },
+ );
+ }
throw err;
}
},
diff --git a/packages/maker-core/src/agents/pi/rpc-client.ts b/packages/maker-core/src/agents/pi/rpc-client.ts
index c838304eee..f1e2033abd 100644
--- a/packages/maker-core/src/agents/pi/rpc-client.ts
+++ b/packages/maker-core/src/agents/pi/rpc-client.ts
@@ -37,6 +37,18 @@ export interface PiRpcEvent {
[key: string]: unknown;
}
+export class PiRpcRequestTimeoutError extends Error {
+ readonly code = 'PI_RPC_TIMEOUT';
+
+ constructor(
+ public readonly commandType: string,
+ public readonly timeoutMs: number,
+ ) {
+ super(`pi rpc timeout after ${timeoutMs}ms: ${commandType}`);
+ this.name = 'PiRpcRequestTimeoutError';
+ }
+}
+
export interface PiRpcSpawnOptions {
/** 已建立的字节流 transport(本地 stdio 或远端 ssh channel)。 */
transport: PiTransport;
@@ -80,18 +92,18 @@ export class PiRpcProcess {
resolve: (resp: PiRpcResponse) => void;
reject: (err: Error) => void;
timer: NodeJS.Timeout;
+ timeoutMs: number;
+ refreshTimeoutOnEvent?: (event: PiRpcEvent) => boolean;
/** 发送命令的 type —— 响应 envelope 校验用(轮 40-w4-t4 CRITICAL)。 */
commandType: string;
}>();
private closed = false;
/**
- * 轮 42 P2(codex-connector):close() 的幂等守卫单独跟踪 —— 与 closed(进程/通道
- * 已死)分离。bridge 断链时 onClose 置 closed, 但**用户显式 close 仍未发生过**:
- * 复用 closed 做 close() 守卫会让显式关闭直接 return, 跳过 killRemoteSession
- * (它走独立 SSH RPC, 断链后仍能送达 daemon), 远端 pi 带凭证跑到 idle 回收。
- * closeCalled 只在用户(或上层)显式 close 后置位, 保证 kill 一定执行一次。
+ * In-flight/successful close is shared. A failed close clears the gate so a
+ * later call can retry remote termination instead of reporting a false
+ * idempotent success while the old daemon session may still be alive.
*/
- private closeCalled = false;
+ private closePromise: Promise<void> | null = null;
private readonly logger: Logger;
constructor(private readonly opts: PiRpcSpawnOptions) {
@@ -124,7 +136,13 @@ export class PiRpcProcess {
/** 发送命令并等待同 id 响应。success:false 时同样 resolve(由调用方看 success/error)。 */
async request(
command: Record<string, unknown>,
- { timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS }: { timeoutMs?: number } = {},
+ {
+ timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
+ refreshTimeoutOnEvent,
+ }: {
+ timeoutMs?: number;
+ refreshTimeoutOnEvent?: (event: PiRpcEvent) => boolean;
+ } = {},
): Promise<PiRpcResponse> {
if (this.isClosed) throw new Error('pi process already exited');
const id = `c${this.nextRequestId++}`;
@@ -133,12 +151,15 @@ export class PiRpcProcess {
return new Promise<PiRpcResponse>((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(id);
- reject(new Error(`pi rpc timeout after ${timeoutMs}ms: ${String(command.type)}`));
+ const commandType = typeof command.type === 'string' ? command.type : '';
+ reject(new PiRpcRequestTimeoutError(commandType, timeoutMs));
}, timeoutMs);
this.pending.set(id, {
resolve,
reject,
timer,
+ timeoutMs,
+ refreshTimeoutOnEvent,
commandType: typeof command.type === 'string' ? command.type : '',
});
this.transport.writeLine(payload).catch((err) => {
@@ -164,40 +185,46 @@ export class PiRpcProcess {
});
}
- /** 优雅关闭:交给 transport(SIGTERM → 宽限期 → SIGKILL,或关 ssh channel)。幂等。 */
- async close(): Promise<void> {
- // 轮 21 H-2 幂等竞态:closeCalled 必须在任何 await 前置位 —— 否则并发 close()
- // 都通过守卫、killRemoteSession RPC 发两次(daemon 模式)+ transport.close
- // 跑两次。置位后 killRemoteSession/close 的失败不再影响幂等语义。
- // 轮 42 P2:守卫用 closeCalled 而非 closed —— onClose(bridge 断链)已置 closed
- // 时, 用户显式 close 仍必须执行 killRemoteSession(独立 SSH RPC 可送达 daemon)。
- if (this.closeCalled) return;
- this.closeCalled = true;
+ /** 优雅关闭:交给 transport(SIGTERM → 宽限期 → SIGKILL,或关 ssh channel)。 */
+ close(): Promise<void> {
+ if (this.closePromise) return this.closePromise;
+ const attempt = this.performClose();
+ this.closePromise = attempt;
+ void attempt.catch(() => {
+ if (this.closePromise === attempt) this.closePromise = null;
+ });
+ return attempt;
+ }
+
+ private async performClose(): Promise<void> {
this.closed = true;
// daemon 模式:用户主动关会话 → 先杀远端 daemon 持有的 pi(对齐 CC/Codex daemon
// 生命周期),再关 transport。顺序关键:先杀 pi 再关 channel,PiAgent 的 onExit
// cleanup(configHome/perm)才发生在 pi 已死后 —— 否则 kill 失败而 cleanup 已删
// configHome,daemon pi 继续跑会用已删文件(R2 生命周期 B3)。
- // 轮 40-w4-t10 HIGH(修复的修复):kill 失败(SSH 断/daemon 不可达)时**仍必须
- // 关 transport** —— 旧实现直接 throw 会跳过 transport.close, 把可恢复的关闭
- // 失败变成永久半开(channel/daemon 继续存活, 重试因 closed 置位 no-op)。
- // kill 失败只决定是否上浮错误, 不阻断底层收口。
+ // kill 失败时仍关 transport,但必须 reject;失败 gate 会被 close() 清掉,
+ // 后续可经独立 SSH RPC 真正重试 kill,不能第二次 close 伪成功。
let killError: unknown = null;
try {
await this.transport.killRemoteSession?.();
} catch (err) {
- // 轮 40-w4-t7 HIGH:kill 失败时 pi 可能继续跑, 残留持凭证的远端 session。
- // fail-closed:上浮错误, 让上层明确知道关闭未完成(daemon idle timeout 兜底)。
killError = new Error(
`pi killRemoteSession failed: ${err instanceof Error ? err.message : String(err)} — remote daemon session may still be running`,
);
}
+ let transportError: unknown = null;
try {
await this.transport.close();
- } catch {
- // transport.close 自身幂等且不抛;防御未来实现变更(自审轮 6 L-1 语义保留)。
+ } catch (err) {
+ transportError = err;
+ }
+ if (transportError) {
+ this.failAllPending(
+ transportError instanceof Error ? transportError : new Error(String(transportError)),
+ );
}
if (killError) throw killError;
+ if (transportError) throw transportError;
}
private handleStdoutLine(line: string): void {
@@ -264,7 +291,17 @@ export class PiRpcProcess {
return;
}
- this.opts.onEvent(obj as PiRpcEvent);
+ const event = obj as PiRpcEvent;
+ for (const [id, entry] of this.pending) {
+ if (!entry.refreshTimeoutOnEvent?.(event)) continue;
+ clearTimeout(entry.timer);
+ entry.timer = setTimeout(() => {
+ if (this.pending.get(id) !== entry) return;
+ this.pending.delete(id);
+ entry.reject(new PiRpcRequestTimeoutError(entry.commandType, entry.timeoutMs));
+ }, entry.timeoutMs);
+ }
+ this.opts.onEvent(event);
}
private failAllPending(err: Error): void {
diff --git a/packages/maker-core/src/agents/pi/transport.ts b/packages/maker-core/src/agents/pi/transport.ts
index 354d058145..cc90d7da2e 100644
--- a/packages/maker-core/src/agents/pi/transport.ts
+++ b/packages/maker-core/src/agents/pi/transport.ts
@@ -116,6 +116,8 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
// 轮 40-w1 MEDIUM-2:close() 进行中标志 —— 防并发 close 双 SIGTERM(轮 21
// 幂等), 与 closed(已通知)分离, 保主动 close 仍触发 onClose。
let closing = false;
+ /** SIGKILL 后未确认退出时,后续 close 继续失败,直到 child 真正发出 close。 */
+ let closeFailure: Error | null = null;
let disposeProcessRegistration: (() => void) | undefined;
if (child.pid != null && child.pid > 0) {
try {
@@ -183,6 +185,7 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
fireClose({ code: null, signal: null, reason: `pi process error: ${err.message}` });
});
child.on('close', (code, signal) => {
+ closeFailure = null;
fireClose({ code, signal, reason: `pi process exited (code=${code}, signal=${signal})` });
});
@@ -216,6 +219,7 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
},
async close(reason = 'pi transport close()'): Promise<void> {
+ if (closeFailure) throw closeFailure;
// 轮 21 H-1 幂等竞态:closed 必须在任何 await 前置位 —— 否则两个并发
// close() 都通过守卫、各发一次 SIGTERM + 各设一个 SIGKILL timer。
// 轮 40-w1 MEDIUM-2:前置 closed 会吞掉子进程 close 事件的 fireClose,
@@ -226,9 +230,8 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
// 优雅关闭:SIGTERM → 宽限期 → SIGKILL → 确认退出。幂等。
// 轮 40-w4-t3 HIGH:旧实现 SIGKILL 后无确认超时 —— D-state/平台异常下
// close 事件不来, await close() 永久挂住, 上层取消流程无法收口。这里
- // 对齐 session-registry 的 waitForExit 语义:超时后仍 resolve(保 close()
- // 的 Promise<void> 契约, PiRpcProcess.close 不 catch —— reject 会冒泡成
- // 未处理错误), 残留子进程由进程管理器兜底, 日志告警可查。
+ // 对齐 session-registry 的 waitForExit 语义:确认窗口到点就结束等待,但
+ // reject 明确表示“未确认终止”,让 Session 保持 error 并阻止新 handle 并存。
let survived = false;
await new Promise<void>((resolve) => {
let done = false;
@@ -244,10 +247,10 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
const onClose = (): void => finish();
const killTimer = setTimeout(() => {
try { child.kill('SIGKILL'); } catch { /* already gone */ }
- // SIGKILL 后再给确认窗口;超时仍 resolve(尽力而为, 不挂死)。
+ // SIGKILL 后再给确认窗口;超时结束等待,随后以稳定错误 reject。
confirmTimer = setTimeout(() => {
survived = true;
- logger.error('pi process did not confirm exit after SIGKILL — transport close resolves anyway', {
+ logger.error('pi process did not confirm exit after SIGKILL', {
pid: child.pid,
});
finish();
@@ -264,13 +267,19 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
});
// 子进程 close 事件若已 fireClose 则 closed=true(通知已发);否则这里补
// 发一次(主动 close 语义:onClose 必须收到终止通知)。
- // 轮 40-w4-t14 HIGH:未确认退出的 survived 状态经 close 通知暴露给上层
- // (reason 带标记), 调用方/进程管理器可据此走更强回收路径, 不再当作
- // 已正常关闭。
+ // 未确认退出只 reject,不能发 onClose(它的语义是进程已终止,PiAgent
+ // 收到后会清 runtime 文件)。child 以后真的 close 时再由全局 listener 通知。
+ const terminationError = survived
+ ? new Error('pi process did not confirm exit after SIGKILL')
+ : null;
+ if (terminationError) {
+ closeFailure = terminationError;
+ throw terminationError;
+ }
fireClose({
code: null,
signal: null,
- reason: survived ? `pi process survived SIGKILL — close() resolved without confirmed exit` : reason,
+ reason,
});
},
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 9cbbd5d8a9..0d2cb43a54 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -275,6 +275,45 @@ describe('Maker session creation singleflight', () => {
void origCreate;
});
+ it('blocks a replacement spawn until an unpublished handle is confirmed closed', async () => {
+ let cleanupCanSucceed = false;
+ const firstClose = vi.fn(async () => {
+ if (!cleanupCanSucceed) throw new Error('termination unconfirmed');
+ });
+ const firstHandle = createHandle({ id: 'pi-orphan', agentKind: 'pi' });
+ firstHandle.close = firstClose;
+ const replacementHandle = createHandle({ id: 'pi-replacement', agentKind: 'pi' });
+ const startSession = vi.fn()
+ .mockResolvedValueOnce(firstHandle)
+ .mockResolvedValueOnce(replacementHandle);
+ const storage = createStorage();
+ const originalCreate = storage.create;
+ storage.create = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('db lock'))
+ .mockImplementation((input) => originalCreate.call(storage, input));
+ const maker = new Maker({
+ agents: { pi: createAgent(startSession, 'pi') },
+ storage,
+ logger: createLogger(),
+ });
+ const options: CreateSessionOptions = {
+ id: 'session-storage-cleanup-fail',
+ agentKind: 'pi',
+ workingDir: '/repo',
+ model: 'pi-model',
+ };
+
+ await expect(maker.createSession(options)).rejects.toThrow('db lock');
+ await expect(maker.createSession(options)).rejects.toThrow('termination unconfirmed');
+ expect(startSession).toHaveBeenCalledTimes(1);
+
+ cleanupCanSucceed = true;
+ await expect(maker.createSession(options)).resolves.toBeInstanceOf(Session);
+ expect(firstClose).toHaveBeenCalledTimes(3);
+ expect(startSession).toHaveBeenCalledTimes(2);
+ });
+
it('rejects a second business task using the same live Codex thread until close completes', async () => {
const threadId = '11111111-1111-1111-1111-111111111111';
const closeGate = createDeferred();
@@ -2189,7 +2228,9 @@ describe('Session turn send guard', () => {
releaseEnd();
await closed;
- await expect(sendPromise).resolves.toEqual({ accepted: false, reason: 'cancelled-before-dispatch' });
+ await expect(sendPromise).rejects.toMatchObject({
+ code: 'TURN_DISPATCH_UNCONFIRMED',
+ });
expect(terminalErrors).toContainEqual(expect.objectContaining({
type: 'error',
data: expect.objectContaining({
@@ -2277,7 +2318,9 @@ describe('Session turn send guard', () => {
});
});
- await session.send('first');
+ await expect(session.send('first')).rejects.toMatchObject({
+ code: 'TURN_DISPATCH_UNCONFIRMED',
+ });
await statusChanged;
await session.abort();
@@ -2402,7 +2445,9 @@ describe('Session turn send guard', () => {
const sendPromise = session.send('first');
await closed;
releaseSend();
- await sendPromise;
+ await expect(sendPromise).rejects.toMatchObject({
+ code: 'TURN_DISPATCH_UNCONFIRMED',
+ });
expect(terminalReasons).toEqual(['original_terminal']);
});
@@ -2492,7 +2537,9 @@ describe('Session turn send guard', () => {
releaseCrash();
await closed;
- await expect(secondSend).resolves.toEqual({ accepted: false, reason: 'cancelled-before-dispatch' });
+ await expect(secondSend).rejects.toMatchObject({
+ code: 'TURN_DISPATCH_UNCONFIRMED',
+ });
expect(terminalReasons).toEqual(['prior_terminal', 'session_event_loop_crashed']);
});
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index f4d76826ad..6ae0b149dc 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -306,6 +306,12 @@ interface CodexThreadClaimLease {
release(): void;
}
+interface FailedHandleCleanup {
+ handle: AgentSessionHandle;
+ promise: Promise<void> | null;
+ onCleaned?: () => void;
+}
+
export class Maker {
protected readonly agents: Partial<Record<AgentKind, BaseAgent>>;
protected readonly storage: SessionStorage;
@@ -322,6 +328,11 @@ export class Maker {
string,
{ promise: Promise<Session> }
>();
+ /**
+ * startSession 已返回、但 Session 尚未发布时 cleanup 失败的 handle。后续同 id
+ * create 必须先把它确认关闭,不能丢失所有权后再 spawn 一个并存进程。
+ */
+ private readonly failedHandleCleanups = new Map<string, FailedHandleCleanup>();
/**
* Codex 0.145 会忽略已加载 thread 的 thread/resume.config。不同 Cindy task
* 若同时复用同一 native thread,后启动者会继续使用前一 Session 的 MCP URL,
@@ -413,6 +424,25 @@ export class Maker {
};
}
+ private async retryFailedHandleCleanup(sessionId: string): Promise<void> {
+ const entry = this.failedHandleCleanups.get(sessionId);
+ if (!entry) return;
+ const cleanup = entry.promise ?? entry.handle.close();
+ entry.promise = cleanup;
+ try {
+ await cleanup;
+ } catch (error) {
+ if (this.failedHandleCleanups.get(sessionId) === entry && entry.promise === cleanup) {
+ entry.promise = null;
+ }
+ throw error;
+ }
+ if (this.failedHandleCleanups.get(sessionId) === entry) {
+ this.failedHandleCleanups.delete(sessionId);
+ entry.onCleaned?.();
+ }
+ }
+
/**
* 创建一个新会话。
*
@@ -425,6 +455,12 @@ export class Maker {
return this.createSessionOnce(opts);
}
+ // Any handle that failed cleanup before publication still owns this
+ // business id. Confirm its shutdown before checking/starting live state.
+ if (this.failedHandleCleanups.has(opts.id)) {
+ await this.retryFailedHandleCleanup(opts.id);
+ }
+
// 进程内已经活着或正在启动的 session, 直接复用 (避免 spawn 第二个 SDK)。
// close() 失败的 Session 不能继续收消息,但也不能立刻从 activeSessions
// 摘掉并与可能仍存活的底层 transport 并存。先重试同一个 close;只有真实
@@ -609,15 +645,24 @@ export class Maker {
// 写失败时, 已启动的 agent handle(PI 远端 daemon session / CC / Codex)必须
// close, 否则 PI 无 codexThreadClaim 时 handle 不关, 远端 pi-manager session/
// MCP bridge 残留成「用户看不到、Maker 管不到」的半创建状态。
+ let cleanupFailed = false;
try {
await handle.close();
} catch (closeError) {
+ cleanupFailed = true;
+ this.failedHandleCleanups.set(id, {
+ handle,
+ promise: null,
+ ...(codexThreadClaim
+ ? { onCleaned: () => codexThreadClaim?.release() }
+ : {}),
+ });
this.logger.warn('failed to close agent handle after session storage failure', {
sessionId: id,
error: String(closeError),
});
}
- if (codexThreadClaim) {
+ if (!cleanupFailed && codexThreadClaim) {
codexThreadClaim.release();
}
throw error;
diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.ts
index ae5dd430c2..82c483a63c 100644
--- a/packages/maker-core/src/session.close.test.ts
+++ b/packages/maker-core/src/session.close.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it, vi } from 'vitest';
import { Session } from './session.js';
-import type { AgentSessionHandle } from './agents/base-agent.js';
+import {
+ TurnDispatchUnconfirmedError,
+ type AgentSessionHandle,
+} from './agents/base-agent.js';
function createLogger() {
const logger = {
@@ -20,6 +23,96 @@ function createDeferred(): { promise: Promise<void>; resolve: () => void } {
}
describe('Session close lifecycle', () => {
+ it('closes an ambiguous transport before surfacing an unconfirmed dispatch', async () => {
+ const eventLoop = createDeferred();
+ const abortController = new AbortController();
+ const close = vi.fn(async () => {
+ eventLoop.resolve();
+ // Give the event iterator a chance to publish its queued terminal event
+ // while Session.close() is still awaiting the handle.
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ const handle = {
+ id: 'thread-unconfirmed',
+ agentKind: 'pi',
+ model: 'gpt-5.4',
+ async send() {
+ abortController.abort();
+ throw new TurnDispatchUnconfirmedError('prompt acceptance timed out');
+ },
+ async *events() {
+ await eventLoop.promise;
+ yield {
+ type: 'error',
+ data: { message: 'late close error', isTerminal: true },
+ source: 'pi',
+ } as never;
+ },
+ close,
+ setInteractionResolver() {},
+ } as unknown as AgentSessionHandle;
+ const session = new Session({
+ id: 'session-unconfirmed',
+ agentKind: 'pi',
+ workDir: '/repo',
+ handle,
+ capabilities: {} as never,
+ logger: createLogger() as never,
+ });
+ const events: unknown[] = [];
+ session.onEvent((event) => events.push(event));
+
+ await expect(session.send('continue the goal', {
+ signal: abortController.signal,
+ })).rejects.toMatchObject({
+ code: 'TURN_DISPATCH_UNCONFIRMED',
+ });
+
+ expect(close).toHaveBeenCalledTimes(1);
+ expect(session.getStatus()).toBe('closed');
+ expect(events).toEqual([]);
+ });
+
+ it('keeps a provider-accepted send accepted when cancellation races with its response', async () => {
+ const sendStarted = createDeferred();
+ const providerAccepted = createDeferred();
+ const eventLoop = createDeferred();
+ const abortController = new AbortController();
+ const session = new Session({
+ id: 'session-accepted-cancel-race',
+ agentKind: 'pi',
+ workDir: '/repo',
+ handle: {
+ id: 'thread-accepted-cancel-race',
+ agentKind: 'pi',
+ model: 'gpt-5.4',
+ async send() {
+ sendStarted.resolve();
+ await providerAccepted.promise;
+ },
+ async *events() {
+ await eventLoop.promise;
+ yield* [];
+ },
+ async close() {
+ eventLoop.resolve();
+ },
+ setInteractionResolver() {},
+ } as unknown as AgentSessionHandle,
+ capabilities: {} as never,
+ logger: createLogger() as never,
+ });
+
+ const sending = session.send('continue the goal', { signal: abortController.signal });
+ await sendStarted.promise;
+ abortController.abort();
+ providerAccepted.resolve();
+
+ await expect(sending).resolves.toEqual({ accepted: true });
+ await session.close();
+ });
+
it('serializes concurrent close calls onto the same transport shutdown', async () => {
const transportClose = createDeferred();
const close = vi.fn(() => transportClose.promise);
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 76dcdfd1c7..3a64f5c681 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -50,6 +50,7 @@ import type {
SendOptions,
TurnContinuationState,
} from './agents/base-agent.js';
+import { TurnDispatchUnconfirmedError } from './agents/base-agent.js';
import type { Logger } from './interfaces/logger.js';
export type SessionStatus = 'active' | 'aborting' | 'closed' | 'error';
@@ -571,14 +572,23 @@ export class Session {
signal: reservation.abortController.signal,
});
} catch (e) {
+ // Cancellation cannot downgrade an explicitly ambiguous provider result
+ // into "cancelled before dispatch"; that would skip the mandatory
+ // transport fence and could leave accepted work running invisibly.
+ if (e instanceof TurnDispatchUnconfirmedError) throw e;
if (reservation.cancelled) {
return { accepted: false, reason: 'cancelled-before-dispatch' };
}
throw e;
}
- if (reservation.cancelled) {
- return { accepted: false, reason: 'cancelled-before-dispatch' };
+ if (reservation.cancelled && (this.terminationStarted || this.closePromise)) {
+ throw new TurnDispatchUnconfirmedError(
+ `Session ${this.id} terminated before provider acceptance could be reconciled`,
+ );
}
+ // A resolved handle.send is the provider-acceptance boundary. A signal
+ // racing after that point may request abort, but cannot rewrite history
+ // and report the turn as undispatched.
turnDispatched = true;
// turn 真正开始跑 → 起 stall 看门狗。后续每个事件都会重置它,done / 终态
// error 会清掉它(见 armTurnStallWatchdog)。
@@ -588,6 +598,18 @@ export class Session {
if (this.sendReservation === reservation) {
this.sendReservation = null;
}
+ if (e instanceof TurnDispatchUnconfirmedError) {
+ // Reserve Session shutdown before closing the handle. This suppresses
+ // a synthetic terminal event from transport teardown and fences any
+ // late provider activity before the orchestrator reports blocked.
+ if (originInstalled && !turnDispatched) {
+ this.currentTurnOrigin = previousTurnOrigin;
+ this.currentTurnAttemptToken = previousTurnAttemptToken;
+ this.turnGeneration = previousTurnGeneration;
+ originInstalled = false;
+ }
+ await this.close();
+ }
throw e;
} finally {
cleanupExternalAbort();
@@ -1688,8 +1710,9 @@ export class Session {
// clear that fence. The fence itself prevents any later generation entering.
observedGeneration = this.turnGeneration;
}
+ if (this.terminationStarted) continue;
// origin 打标与终态清理都收在 fanOutEvent 里(看门狗合成的事件共用同一语义,
- // 见那里的注释)。
+ // 见那里的注释)。关闭门一旦占住,旧 handle 的迟到事件不得再改写业务状态。
this.fanOutEvent(event, observedGeneration);
}
} catch (e) {