Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): bound stale config-home sweeps
lizzjin77d0958b8262
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.tsindex 9fef505b41..d74ff0428c 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@@ -2449,6 +2449,76 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {}});+ it('starts a new session while stale config-home cleanup is blocked and finishes the backlog later', async () => {+ const { promises: fs } = await import('node:fs');+ const originalRm = fs.rm.bind(fs);+ const staleHomes = Array.from({ length: 10 }, (_, index) => {+ const staleHome = path.join(agentHome, 'run-tmp', `stale-budget-${index}`);+ mkdirSync(staleHome, { recursive: true });+ writeFileSync(+ path.join(staleHome, '.cindy-owner.json'),+ `${JSON.stringify({+ version: 1,+ ownerPid: 2_147_483_647,+ createdAt: 1,+ directoryName: path.basename(staleHome),+ })}\n`,+ );+ return staleHome;+ });+ const staleHomeKeys = new Set(staleHomes.map((home) => path.resolve(home)));+ let announceRemovalStarted!: () => void;+ const removalStarted = new Promise<void>((resolve) => { announceRemovalStarted = resolve; });+ let releaseRemoval!: () => void;+ const removalGate = new Promise<void>((resolve) => { releaseRemoval = resolve; });+ let removalReleased = false;+ let staleRemovalCount = 0;+ let batchYieldObservedAt: number | undefined;+ const unblockRemoval = (): void => {+ if (removalReleased) return;+ removalReleased = true;+ releaseRemoval();+ };+ const rmSpy = vi.spyOn(fs, 'rm').mockImplementation(async (target, options) => {+ if (staleHomeKeys.has(path.resolve(String(target)))) {+ staleRemovalCount += 1;+ if (staleRemovalCount === 8) {+ setTimeout(() => { batchYieldObservedAt = staleRemovalCount; }, 0);+ }+ announceRemovalStarted();+ await removalGate;+ rmSync(String(target), { recursive: true, force: true });+ return;+ }+ return originalRm(target, options);+ });+ const startPromise = new PiAgent(buildDeps()).startSession({+ sessionId: 'bounded-stale-sweep',+ workingDir: cwd,+ model: 'm',+ });+ let handle: Awaited<typeof startPromise> | undefined;+ try {+ await removalStarted;+ await vi.waitFor(+ () => expect(knobs.spawnedEnvs.some(+ (env) => env.CINDY_PI_SESSION_ID === 'bounded-stale-sweep',+ )).toBe(true),+ { timeout: 500 },+ );+ unblockRemoval();+ handle = await startPromise;+ await waitFor(() => staleHomes.every((home) => !existsSync(home)));+ await vi.waitFor(() => expect(batchYieldObservedAt).toBe(8));+ } finally {+ unblockRemoval();+ handle ??= await startPromise;+ rmSpy.mockRestore();+ await handle.close();+ await Promise.all(staleHomes.map((home) => originalRm(home, { recursive: true, force: true })));+ }+ });+it('reclaims a v2 local config home whose owner pid was recycled', async () => {const runtimeId = 'a'.repeat(32);const recycledHome = path.join(agentHome, 'run-tmp', runtimeId);@@ -2472,7 +2542,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {model: 'm',});try {- expect(existsSync(recycledHome)).toBe(false);+ await waitFor(() => !existsSync(recycledHome));} finally {await handle.close();}@@ -2499,10 +2569,9 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {return ownerHome;});const probeMemos: unknown[] = [];- const ownerProbe = vi- .spyOn(piSubagentRuns, 'isPiHostProcessInstanceAlive')- .mockImplementation(function () {- probeMemos.push(arguments[1]);+ vi.spyOn(piSubagentRuns, 'isPiHostProcessInstanceAliveAsync')+ .mockImplementation(async (identity, memo) => {+ if (identity.pid === ownerPid) probeMemos.push(memo);return true;});@@ -2512,7 +2581,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {model: 'm',});try {- expect(ownerProbe).toHaveBeenCalledTimes(ownerHomes.length);+ await vi.waitFor(() => expect(probeMemos).toHaveLength(ownerHomes.length));// pi-subagent-runs separately locks that one shared memo means one// PowerShell/ps start-time probe per owner pid and sweep.expect(probeMemos[0]).toBeInstanceOf(Map);@@ -2616,8 +2685,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {model: "m",});try {- expect(existsSync(orphanedHome)).toBe(false);- expect(existsSync(deadOwnerHome)).toBe(false);+ await waitFor(() => !existsSync(orphanedHome) && !existsSync(deadOwnerHome));expect(existsSync(path.join(activeHome, "models.json"))).toBe(true);expect(existsSync(liveOwnerHome)).toBe(true);} finally {diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.tsindex 078cf495cc..3696758e0e 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts@@ -19,6 +19,7 @@ import {piSubagentDeletedTombstonePath,writePiSubagentDeletedTombstone,clearPiSubagentDeletedTombstone,+ isPiHostProcessInstanceAliveAsync,isPiSubagentRunStale,piSubagentControlOwnership,piSubagentLaunchFencePath,@@ -993,6 +994,44 @@ describe('PI durable subagent run store', () => {});});+ it('keeps the event loop responsive while probing several host process incarnations', async () => {+ const pids = [410_001, 410_002, 410_003, 410_004, 410_005, 410_006];+ const startTimeSec = 123_456;+ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!;+ const realKill = process.kill.bind(process);+ Object.defineProperty(process, 'platform', { ...originalPlatform, value: 'win32' });+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(+ ((pid: number, signal?: NodeJS.Signals | number) => {+ if (pids.includes(pid) && signal === 0) return true;+ return realKill(pid, signal);+ }) as typeof process.kill,+ );+ childProcess.probeDelayMs = 50;+ childProcess.spawnSync.mockReset();+ childProcess.spawnSync.mockImplementation(() => ({+ status: 0,+ stdout: String(startTimeSec),+ }));+ let settled = 0;+ try {+ const probes = pids.map((pid) => isPiHostProcessInstanceAliveAsync({+ pid,+ startTimeSec,+ }).finally(() => { settled += 1; }));++ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ expect(settled).toBe(0);+ await expect(Promise.all(probes)).resolves.toEqual(pids.map(() => true));+ expect(childProcess.spawnSync).toHaveBeenCalledTimes(pids.length);+ } finally {+ childProcess.probeDelayMs = 0;+ childProcess.spawnSync.mockReset();+ childProcess.spawnSync.mockImplementation(() => ({ status: 0, stdout: '' }));+ killSpy.mockRestore();+ Object.defineProperty(process, 'platform', originalPlatform);+ }+ });+/*** The account boundary escalates to killing the runner because a durable* child holds unrevocable BYOM credentials. "Reclaimed" therefore has to meandiff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 71d5082a00..e2a59fa937 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -100,7 +100,7 @@ import {listPiSubagentRunDiagnostics,listPiSubagentRunDirectoryIds,listPiSubagentRuns,- isPiHostProcessInstanceAlive,+ isPiHostProcessInstanceAliveAsync,piHostProcessStartTimeSec,piSubagentRunRoot,piSubagentApprovalScope,@@ -465,9 +465,14 @@ async function stageManagedRipgrep(configHome: string, sourcePath: string | undeconst LOCAL_CONFIG_HOME_OWNER_FILE = '.cindy-owner.json';const LOCAL_CONFIG_HOME_OWNER_VERSION = 2;const LOCAL_CONFIG_HOME_REMOVE_RETRY_DELAYS_MS = [0, 25, 100] as const;+/** One background turn may inspect only this many directory entries. */+const LOCAL_CONFIG_HOME_SWEEP_ENTRY_BUDGET = 8;+/** Stop a round after the current async operation once this soft budget expires. */+const LOCAL_CONFIG_HOME_SWEEP_TIME_BUDGET_MS = 250;const LOCAL_CONFIG_HOME_RUNTIME_ID_RE = /^[a-f0-9]{32}$/;const SHA256_HEX_RE = /^[a-f0-9]{64}$/;const activeLocalConfigHomes = new Set<string>();+const activeLocalConfigHomeSweeps = new Set<string>();/** Durable proof used only to decide whether a local per-session config home is reclaimable. */interface LocalConfigHomeOwnerV1 {@@ -602,17 +607,17 @@ function isLocalProcessAlive(pid: number): boolean {}}-function localConfigHomeOwnerIsActive(+async function localConfigHomeOwnerIsActive(owner: LocalConfigHomeOwner,configHome: string,startTimeMemo?: ProcessStartTimeMemo,-): boolean {+): Promise<boolean> {if (owner.version === 1) {return owner.ownerPid === process.pid? activeLocalConfigHomes.has(localConfigHomeKey(configHome)): isLocalProcessAlive(owner.ownerPid);}- if (!isPiHostProcessInstanceAlive({+ if (!await isPiHostProcessInstanceAliveAsync({pid: owner.ownerPid,startTimeSec: owner.ownerStartTimeSec,}, startTimeMemo)) return false;@@ -671,39 +676,79 @@ async function sweepStaleLocalConfigHomes(});return;}- // One owner process may have many active session homes. Reuse only the- // expensive start-time sample within this sweep; each check still performs- // a fresh signal-0 liveness probe and deletion still re-reads the marker.- const ownerStartTimeMemo: ProcessStartTimeMemo = new Map();- for (const entry of entries) {- if (!entry.isDirectory()) continue;- const candidate = path.resolve(runTmp, entry.name);- if (path.dirname(candidate) !== runTmp) continue;- const owner = await readLocalConfigHomeOwner(candidate);- // Markerless homes may belong to an older Cindy instance between directory- // creation and Pi spawn. No process snapshot can prove them reclaimable.- if (!owner) continue;- if (localConfigHomeOwnerIsActive(owner, candidate, ownerStartTimeMemo)) continue;-- // Re-read immediately before deletion. A directory whose marker changed or- // whose owner became active is no longer the orphan we proved above.- const currentOwner = await readLocalConfigHomeOwner(candidate);- if (- !currentOwner- || !sameLocalConfigHomeOwner(currentOwner, owner)- ) continue;- if (localConfigHomeOwnerIsActive(currentOwner, candidate, ownerStartTimeMemo)) continue;-- const outcome = await removeLocalConfigHomeWithRetry(candidate);- if (!outcome.removed) {- logger.debug('pi configHome orphan cleanup failed (retried next startSession)', {- configHomeId: entry.name,- message: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),+ let offset = 0;+ while (offset < entries.length) {+ if (offset > 0) {+ // A large backlog is split into separate event-loop turns. This bounds+ // each reclaim round and lets startup, IPC, and rendering work proceed.+ await new Promise<void>((resolve) => {+ const timer = setTimeout(resolve, 0);+ timer.unref();});}+ // Re-probe every owner incarnation in every round. Carrying this memo across+ // the yield could hide a pid that died and was recycled between rounds.+ const ownerStartTimeMemo: ProcessStartTimeMemo = new Map();+ const roundStartedAt = Date.now();+ let inspected = 0;+ while (offset < entries.length && inspected < LOCAL_CONFIG_HOME_SWEEP_ENTRY_BUDGET) {+ if (+ inspected > 0+ && Date.now() - roundStartedAt >= LOCAL_CONFIG_HOME_SWEEP_TIME_BUDGET_MS+ ) break;+ const entry = entries[offset++]!;+ inspected += 1;+ if (!entry.isDirectory()) continue;+ const candidate = path.resolve(runTmp, entry.name);+ if (path.dirname(candidate) !== runTmp) continue;+ const owner = await readLocalConfigHomeOwner(candidate);+ // Markerless homes may belong to an older Cindy instance between directory+ // creation and Pi spawn. No process snapshot can prove them reclaimable.+ if (!owner) continue;+ if (await localConfigHomeOwnerIsActive(owner, candidate, ownerStartTimeMemo)) continue;++ // Re-read immediately before deletion. A directory whose marker changed or+ // whose owner became active is no longer the orphan we proved above.+ const currentOwner = await readLocalConfigHomeOwner(candidate);+ if (+ !currentOwner+ || !sameLocalConfigHomeOwner(currentOwner, owner)+ ) continue;+ if (await localConfigHomeOwnerIsActive(currentOwner, candidate, ownerStartTimeMemo)) continue;++ const outcome = await removeLocalConfigHomeWithRetry(candidate);+ if (!outcome.removed) {+ logger.debug('pi configHome orphan cleanup failed (retried next startSession)', {+ configHomeId: entry.name,+ message: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),+ });+ }+ }}}+/** Coalesce startup-triggered sweeps without putting reclamation on the startup critical path. */+function scheduleStaleLocalConfigHomeSweep(+ agentHome: string,+ logger: ConfigHomeCleanupLogger,+): void {+ const sweepKey = localConfigHomeKey(path.resolve(agentHome, 'run-tmp'));+ if (activeLocalConfigHomeSweeps.has(sweepKey)) return;+ activeLocalConfigHomeSweeps.add(sweepKey);+ const timer = setTimeout(() => {+ void sweepStaleLocalConfigHomes(agentHome, logger)+ .catch((error) => {+ logger.debug('pi configHome orphan scan failed (non-fatal)', {+ message: error instanceof Error ? error.message : String(error),+ });+ })+ .finally(() => {+ activeLocalConfigHomeSweeps.delete(sweepKey);+ });+ }, 0);+ timer.unref();+}+/** cindy Effort → pi thinking level(pi 无 ultra)。思考开关走 setThinkingEnabled / thinkingEnabled。 */function effortToPiThinkingLevel(effort: Effort): string {return effort === 'ultra' ? 'max' : effort;@@ -2308,7 +2353,7 @@ export class PiAgent extends BaseAgent {});}if (!remote) {- await sweepStaleLocalConfigHomes(+ scheduleStaleLocalConfigHomeSweep(agentHome,this.deps.logger,);diff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.tsindex e6045a6a83..5dccf4b2d5 100644--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts@@ -1217,6 +1217,43 @@ function probeProcessStartTimeSec(pid: number, now: number): number | null {}}+/**+ * Reclaim probes must never block Electron Main while Windows starts PowerShell.+ * An unreadable or timed-out probe remains conservative: the owner is treated+ * as alive and the directory is left for a later sweep.+ */+const PROCESS_START_TIME_PROBE_TIMEOUT_MS = 1_000;++async function probeProcessStartTimeSecAsync(pid: number, now: number): Promise<number | null> {+ try {+ if (process.platform === 'win32') {+ const { stdout } = await execFileAsync(+ 'powershell.exe',+ [+ '-NoProfile', '-NonInteractive', '-Command',+ `[int64]((Get-Process -Id ${pid}).StartTime.ToUniversalTime() - [datetime]'1970-01-01').TotalSeconds`,+ ],+ {+ encoding: 'utf8',+ timeout: PROCESS_START_TIME_PROBE_TIMEOUT_MS,+ windowsHide: true,+ },+ );+ const match = (typeof stdout === 'string' ? stdout : '').match(/-?\d+/);+ const seconds = match ? Number(match[0]) : NaN;+ return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds) : null;+ }+ const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'etime='], {+ encoding: 'utf8',+ timeout: PROCESS_START_TIME_PROBE_TIMEOUT_MS,+ });+ const elapsed = parseElapsedSeconds(typeof stdout === 'string' ? stdout : '');+ return elapsed === null ? null : Math.round(now / 1_000 - elapsed);+ } catch {+ return null;+ }+}+/*** Per-sweep memo for the start-time probe, passed down rather than held.*@@ -1239,6 +1276,16 @@ function readProcessStartTimeSec(pid: number, memo?: ProcessStartTimeMemo): numbreturn startTimeSec;}+async function readProcessStartTimeSecAsync(+ pid: number,+ memo?: ProcessStartTimeMemo,+): Promise<number | null> {+ if (memo?.has(pid)) return memo.get(pid) ?? null;+ const startTimeSec = await probeProcessStartTimeSecAsync(pid, Date.now());+ memo?.set(pid, startTimeSec);+ return startTimeSec;+}+/** `ps` rounds to the second and samples after we read the clock. */const OWNER_START_TIME_TOLERANCE_SEC = 5;@@ -1277,6 +1324,20 @@ export function isPiHostProcessInstanceAlive(return isOwnerInstanceAlive(identity, startTimeMemo);}+/** Non-blocking incarnation check for background config-home reclamation. */+export async function isPiHostProcessInstanceAliveAsync(+ identity: PiSubagentOwnerIdentity,+ startTimeMemo?: ProcessStartTimeMemo,+): Promise<boolean> {+ if (isProcessAlive(identity.pid) === false) return false;+ if (identity.startTimeSec === undefined) return true;+ const startTimeSec = identity.pid === process.pid+ ? ownProcessStartTimeSec()+ : await readProcessStartTimeSecAsync(identity.pid, startTimeMemo);+ if (startTimeSec === null) return true;+ return Math.abs(startTimeSec - identity.startTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;+}+function isProcessAlive(pid: number | undefined): boolean | null {if (!Number.isSafeInteger(pid) || (pid ?? 0) <= 0) return null;try {