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(core): release startup leases after confirmed Pi exit

DavidShenf87d248b6762
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index b2b162e7e4..daf2db22f1 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1468,6 +1468,17 @@ export class AgentNotAuthenticatedError extends Error {
}
}
+/**
+ * An adapter failed before returning a handle and has confirmed its process stopped.
+ * Maker unwraps the cause after releasing only this startup's host resources.
+ */
+export class AgentStartupStoppedError extends Error {
+ constructor(cause: unknown) {
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
+ this.name = 'AgentStartupStoppedError';
+ }
+}
+
/** An adapter failed before returning a handle, but its process has not confirmed exit. */
export class AgentStartupCleanupPendingError extends Error {
readonly whenStopped: Promise<void>;
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 544c60c95e..6bcfe58c39 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
@@ -121,7 +121,7 @@ import { Session } from '../../../session.js';
import * as piSubagentRuns from '../pi-subagent-runs.js';
import type { PiSubagentRunStatus } from '../pi-subagent-runs.js';
import { piProjectKey } from '../project-trust.js';
-import { AgentStartupCleanupPendingError, type AgentDeps } from '../../base-agent.js';
+import { AgentStartupCleanupPendingError, AgentStartupStoppedError, type AgentDeps } from '../../base-agent.js';
import type { Logger } from '../../../interfaces/logger.js';
import type { PiProjectTrustInputSnapshot } from '../../../types/pi-project-trust.js';
@@ -343,10 +343,24 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(knobs.closeCount).toBe(0); // 构造失败没有 proc 可关
});
- it('disposes ctx and closes the proc when a startup RPC rejects before handoff', async () => {
+ it('reports confirmed startup cleanup only after the proc closes, preserving the RPC error', async () => {
knobs.getStateRejects = true;
+ let confirmStopped!: () => void;
+ knobs.closeGate = new Promise<void>((resolve) => { confirmStopped = resolve; });
const agent = new PiAgent(buildDeps());
- await expect(agent.startSession(opts())).rejects.toThrow(/get_state rejected/);
+ const rejected = vi.fn();
+ const startup = agent.startSession(opts()).catch((error: unknown) => {
+ rejected(error);
+ return error;
+ });
+ await vi.waitFor(() => expect(knobs.closeCount).toBe(1));
+ expect(rejected).not.toHaveBeenCalled();
+ confirmStopped();
+ const failure = await startup;
+ expect(failure).toBeInstanceOf(AgentStartupStoppedError);
+ if (!(failure instanceof AgentStartupStoppedError)) throw new Error('missing exit evidence');
+ expect(failure.message).toBe('get_state rejected (mock)');
+ expect(failure.cause).toEqual(new Error('get_state rejected (mock)'));
expect(disposed).toBe(1);
expect(proxyDisposed).toBe(2);
expect(knobs.closeCount).toBe(1); // 已 spawn → 必须关掉,避免僵尸持有 ?session= 路由
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index fd6bc130e1..d96fd1cfe6 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -57,6 +57,7 @@ function validateSdkSessionId(value: string): string {
import {
AgentNotAuthenticatedError,
AgentStartupCleanupPendingError,
+ AgentStartupStoppedError,
BaseAgent,
MAIN_OWNED_SEND_CONTEXT,
PiManagedPackageMutationCancelledError,
@@ -5166,7 +5167,8 @@ export class PiAgent extends BaseAgent {
cleanupRuntimeFiles();
}
if (cleanupPending) throw cleanupPending;
- throw err;
+ // Only a successful close proves exit; do not infer it from the startup error.
+ throw new AgentStartupStoppedError(err);
}
const launchSubagentRunner = (request: PiSubagentRunnerLaunchRequest): Promise<void> =>
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 5e043da916..124d8e0fdd 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -15,6 +15,7 @@ import { Session } from './session.js';
import { createAsyncQueue } from './agents/shared/async-queue.js';
import {
AgentStartupCleanupPendingError,
+ AgentStartupStoppedError,
TurnPermissionPolicyUnsupportedError,
type AgentSessionHandle,
type BaseAgent,
@@ -1574,10 +1575,41 @@ describe('Maker start-option lifecycle hooks', () => {
expect(onStartCleanupSucceeded).not.toHaveBeenCalled();
});
- it('preserves runtime protection for an ordinary adapter failure without exit evidence', async () => {
+ it.each([new TypeError('startup RPC failed'), 'non-Error startup failure'])(
+ 'releases only the confirmed-stopped startup and preserves its original error: %s', async (startupError) => {
+ const otherStartup = {} as CreateSessionOptions;
+ const leased = new Set<CreateSessionOptions>([otherStartup]);
+ const onStartFailed = vi.fn(({ options, runtimeMayBeAlive }: SessionStartFailureContext) => {
+ if (!runtimeMayBeAlive) leased.delete(options);
+ });
+ const onStartCleanupSucceeded = vi.fn();
+ const maker = new Maker({
+ agents: { pi: createAgent(vi.fn().mockRejectedValue(new AgentStartupStoppedError(startupError)), 'pi') },
+ storage: createStorage(), logger: createLogger(),
+ lifecycleHooks: {
+ prepareStartOptions: (_id, options) => { leased.add(options); },
+ onStartFailed, onStartCleanupSucceeded,
+ },
+ });
+ await expect(maker.createSession({
+ id: 'confirmed-exit', agentKind: 'pi', workingDir: '/repo', model: 'pi-model',
+ })).rejects.toBe(startupError);
+ expect(onStartFailed).toHaveBeenCalledOnce();
+ expect(onStartFailed).toHaveBeenCalledWith(expect.objectContaining({
+ stage: 'agent-start', error: startupError, runtimeMayBeAlive: false,
+ }));
+ expect(leased).toEqual(new Set([otherStartup]));
+ expect(onStartCleanupSucceeded).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ new Error('ordinary startup failure'),
+ Object.assign(new Error('ordinary startup failure'), { name: 'AgentStartupStoppedError' }),
+ ])('preserves runtime protection for an adapter failure without exit evidence: %s', async (error) => {
const onStartFailed = vi.fn();
const onStartCleanupSucceeded = vi.fn();
- const startSession = vi.fn().mockRejectedValue(new Error('ordinary startup failure'));
+ const startSession = vi.fn().mockRejectedValue(error);
const maker = new Maker({
agents: { codex: createAgent(startSession) }, storage: createStorage(), logger: createLogger(),
lifecycleHooks: { onStartFailed, onStartCleanupSucceeded },
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 44512b9941..7cd508654d 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -38,7 +38,7 @@ import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilitie
import { piExplicitSkillRuntimePath } from './agents/pi/skill-runtime-provenance.js';
import { fingerprintPiProjectSkillEntrypoint } from './agents/pi/project-resource-assembly.js';
import { Session, generateSessionId } from './session.js';
-import { AgentStartupCleanupPendingError } from './agents/base-agent.js';
+import { AgentStartupCleanupPendingError, AgentStartupStoppedError } from './agents/base-agent.js';
import type {
AgentSessionHandle,
AgentSessionTeardownOptions,
@@ -716,7 +716,9 @@ export class Maker {
codexThreadClaim?.release();
// A generic adapter error does not prove its process stopped. Preserve
// host guards; only pre-adapter failure or explicit exit evidence releases them.
- await notifyStartFailed('agent-start', error, agentStartAttempted);
+ const runtimeStopped = error instanceof AgentStartupStoppedError;
+ const startupError = runtimeStopped ? error.cause : error;
+ await notifyStartFailed('agent-start', startupError, agentStartAttempted && !runtimeStopped);
if (error instanceof AgentStartupCleanupPendingError) {
// The adapter still owns this unpublished process. Its eventual close
// must release only this startup's resources, even after a rebuild.
@@ -726,7 +728,7 @@ export class Maker {
});
});
}
- throw error;
+ throw startupError;
}
if (opts.agentKind === 'codex' && isClaimableCodexThreadId(handle.id)) {
try {