Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: address review — close shutdown and prompt gaps
Chris8351a2521c7d
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.tsindex 40e945a491..137d5ca097 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@@ -1525,6 +1525,58 @@ describe('Pi provider-aware model routing', () => {await handle.close();});+ it.each([+ ['transport close before response', new Error('pi process exited (code=null, signal=null)')],+ ['unknown write result', new Error('write EPIPE')],+ ['malformed response envelope', new Error('pi rpc: response for prompt missing boolean success')],+ ])('marks %s after prompt request starts as an unconfirmed dispatch', async (_label, failure) => {+ 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 failure;+ return { success: true, data: {} };+ };+ const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));+ const handle = await agent.startSession({+ sessionId: `prompt-unknown-${String(_label).replaceAll(' ', '-')}`,+ workingDir: cwd,+ model: 'local-model',+ });++ await expect(handle.send({ type: 'user', content: 'continue the goal' })).rejects.toMatchObject({+ name: 'TurnDispatchUnconfirmedError',+ code: 'TURN_DISPATCH_UNCONFIRMED',+ cause: failure,+ });+ expect(captured.requests.filter((request) => request.type === 'prompt')).toHaveLength(1);+ await handle.close();+ });++ it('keeps an explicit prompt rejection as a confirmed undispatched error', 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') return { success: false, error: 'prompt rejected before acceptance' };+ return { success: true, data: {} };+ };+ const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));+ const handle = await agent.startSession({+ sessionId: 'prompt-explicit-rejection',+ workingDir: cwd,+ model: 'local-model',+ });++ const error = await handle.send({ type: 'user', content: 'continue the goal' })+ .then(() => null, (reason: unknown) => reason);+ expect(error).toEqual(expect.objectContaining({+ message: 'pi prompt rejected: prompt rejected before acceptance',+ }));+ expect((error as { code?: unknown }).code).toBeUndefined();+ 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/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 9938dcc2d4..c942be9c1f 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -2744,6 +2744,8 @@ export class PiAgent extends BaseAgent {const previousTurnPermissionPolicy = activeTurnPermissionPolicy;activeTurnPermissionPolicy = sendOpts?.turnPermissionPolicy ?? null;let providerAccepted = false;+ let promptRequestStarted = false;+ let providerRejected = false;try {if (reviewMode) {await assertReviewMessageContentPaths(@@ -2767,6 +2769,7 @@ export class PiAgent extends BaseAgent {? await readPiUserEntryIds(): null;rejectIfCancelled(sendOpts, 'send');+ promptRequestStarted = true;const resp = await proc.request(command, {timeoutMs: PI_PROMPT_ACCEPTANCE_TIMEOUT_MS,// Prompt acceptance may legitimately span multiple compaction@@ -2776,6 +2779,7 @@ export class PiAgent extends BaseAgent {PI_PROMPT_ACCEPTANCE_PROGRESS_EVENTS.has(event.type),});if (!resp.success) {+ providerRejected = true;throw new Error(`pi prompt rejected: ${resp.error ?? 'unknown'}`);}providerAccepted = true;@@ -2784,16 +2788,14 @@ 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。+ // Before proc.request the turn is known not to have reached Pi. Once+ // request starts, a transport/write/envelope failure cannot prove+ // whether Pi accepted the prompt; only success:false is an explicit+ // rejection. Fence every other unknown result before Goal may resume.+ if (promptRequestStarted && !providerAccepted && !providerRejected) {+ const detail = err instanceof Error ? err.message : String(err);throw new TurnDispatchUnconfirmedError(- `Pi did not confirm prompt acceptance within ${PI_PROMPT_ACCEPTANCE_TIMEOUT_MS}ms`,+ `Pi did not confirm prompt acceptance: ${detail}`,{ cause: err },);}diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 14316c6029..224a5107e5 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -386,6 +386,67 @@ describe('Maker session creation singleflight', () => {expect(close).toHaveBeenCalledTimes(2);});+ it('detaches active sessions before the creation barrier and reclaims late publications', async () => {+ const lifecycleStarted = createDeferred();+ const lifecycleGate = createDeferred();+ const initialClose = vi.fn(async () => undefined);+ const lateClose = vi.fn(async () => undefined);+ const initialHandle = createHandle({ id: 'initial-pi-thread', agentKind: 'pi' });+ initialHandle.close = initialClose;+ const lateHandle = createHandle({ id: 'late-pi-thread', agentKind: 'pi' });+ lateHandle.close = lateClose;+ const startSession = vi.fn(async (opts: CreateSessionOptions) =>+ opts.id === 'session-initial' ? initialHandle : lateHandle,+ );+ const agent = createAgent(startSession, 'pi');+ const dispose = vi.fn(async () => undefined);+ agent.dispose = dispose;+ const maker = new Maker({+ agents: { pi: agent },+ storage: createStorage(),+ logger: createLogger(),+ lifecycleHooks: {+ prepareStartOptions: async (sessionId) => {+ if (sessionId !== 'session-late') return;+ lifecycleStarted.resolve();+ await lifecycleGate.promise;+ },+ },+ });++ await maker.createSession({+ id: 'session-initial',+ agentKind: 'pi',+ workingDir: '/repo',+ model: 'pi-model',+ });+ const creatingLate = maker.createSession({+ id: 'session-late',+ agentKind: 'pi',+ workingDir: '/repo',+ model: 'pi-model',+ });+ await lifecycleStarted.promise;++ const shuttingDown = maker.shutdown();+ await vi.waitFor(() => expect(initialClose).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(dispose).toHaveBeenCalledTimes(1));+ expect(lateClose).not.toHaveBeenCalled();++ lifecycleGate.resolve();+ await creatingLate;+ await shuttingDown;++ expect(initialClose).toHaveBeenCalledTimes(1);+ expect(lateClose).toHaveBeenCalledTimes(1);+ expect(dispose).toHaveBeenCalledTimes(2);+ expect(maker.listActiveSessions()).toEqual([]);++ await maker.shutdown();+ expect(initialClose).toHaveBeenCalledTimes(1);+ expect(lateClose).toHaveBeenCalledTimes(1);+ });+it('disposes an agent again after a lifecycle-blocked startup clears the creation barrier', async () => {const lifecycleStarted = createDeferred();const lifecycleGate = createDeferred();diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex f2aca496c0..9c6444dc2d 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -946,9 +946,30 @@ export class Maker {const agentEntries = Object.entries(this.agents);const errors: Array<{ kind: string; name: string; error: unknown }> = [];- // Queue agent-level process shutdown before waiting for session creation.- // PiAgent.dispose() owns its own startup barrier, so a startup that fails- // after this point can still publish a quarantine entry and be reclaimed.+ // Snapshot current sessions before the creation barrier. Existing local+ // Claude/PI processes must start terminating immediately; a stuck startup+ // must not consume the entire host quit window before their detach begins.+ const initialSessionSnapshot = Array.from(this.activeSessions.values());+ const initialSessionIdentities = new Set(initialSessionSnapshot);+ const queueSessionDetaches = (+ sessions: readonly Session[],+ phase: 'initial' | 'late',+ ): Array<Promise<void>> => {+ for (const session of sessions) {+ if (!this.closeReasons.has(session)) this.closeReasons.set(session, 'requested');+ }+ return sessions.map((session) =>+ Promise.resolve()+ .then(() => session.detach())+ .catch((e) => {+ errors.push({ kind: `session-${phase}`, name: session.id, error: e });+ }),+ );+ };++ // Queue agent-level process shutdown and the initial Session snapshot+ // before waiting for session creation. PiAgent.dispose() owns its startup+ // barrier; Session detach owns already-published local agent processes.const initialAgentDisposes = agentEntries.map(([kind, agent]) =>Promise.resolve().then(() => agent.dispose())@@ -956,10 +977,11 @@ export class Maker {errors.push({ kind: 'agent', name: kind, error: e });}),);+ const initialSessionDetaches = queueSessionDetaches(initialSessionSnapshot, 'initial');// createSession registers its promise before yielding. Blocking new calls// above makes this a stable barrier: after it settles, every handle started- // before shutdown is either active or present in failedHandleCleanups.+ // before shutdown is active, closed, or present in failedHandleCleanups.const creationSnapshot = Array.from(this.pendingSessionCreations);await Promise.allSettled(creationSnapshot);@@ -971,19 +993,14 @@ export class Maker {}),);- // Snapshot only after the creation barrier. Status listeners mutate- // activeSessions during close, so iteration must use a stable array.- const sessSnapshot = Array.from(this.activeSessions.values());+ // Only sessions published while the creation barrier was settling belong+ // to the late pass. Identity filtering avoids detaching an initial Session+ // twice when it remains in activeSessions until its first detach settles.+ const lateSessionSnapshot = Array.from(this.activeSessions.values())+ .filter((session) => !initialSessionIdentities.has(session));+ const lateSessionDetaches = queueSessionDetaches(lateSessionSnapshot, 'late');const failedHandleCleanupSnapshot = Array.from(this.failedHandleCleanups.entries());- // shutdown() calls detach() directly instead of closeSession(), so record- // the explicit cause before any asynchronous close callback can run. This- // prevents app exit from looking like an unexpected provider rebuild and- // accidentally preserving an automatic retry lease.- for (const session of sessSnapshot) {- if (!this.closeReasons.has(session)) this.closeReasons.set(session, 'requested');- }-const failedHandleCloses = failedHandleCleanupSnapshot.map(([sessionId, entry]) =>Promise.resolve().then(() => this.retryFailedHandleCleanup(sessionId, entry))@@ -992,18 +1009,11 @@ export class Maker {}),);- const sessionCloses = sessSnapshot.map((s) =>- Promise.resolve()- .then(() => s.detach())- .catch((e) => {- errors.push({ kind: 'session', name: s.id, error: e });- }),- );-await Promise.allSettled([+ ...initialSessionDetaches,...finalAgentDisposes,...failedHandleCloses,- ...sessionCloses,+ ...lateSessionDetaches,]);if (errors.length > 0) {