Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): share recovery inventory across parent roots
Chris23d006b9d2b8
diff --git a/docs/research/pi-subagent-delegation.md b/docs/research/pi-subagent-delegation.mdindex 61a35de6f0..77964a1563 100644--- a/docs/research/pi-subagent-delegation.md+++ b/docs/research/pi-subagent-delegation.md@@ -26,7 +26,8 @@ parentSessionId、runDir 和全部 child/session/agent 身份,并确认所有命令行;若进程在两次查询之间消失或命令行不可读,必须再由 OS 独立确认该 PID 已退出。仍存活但不可读或存活查询失败都不放行,不把其他账号的受保护系统进程混入当前账号证明。仅排除本次启动的 `tasklist` 查询进程自身 PID,避免它正常退出后使清单永久不完整。-查询是只读核验,不向清单里的 PID 发信号。同一次扫描复用清单,下次扫描重新读取。+查询是只读核验,不向清单里的 PID 发信号。先读取本轮所有 parent-session root 的候选回执,+再共享一次清单查询,避免历史 root 逐个查询耗尽总回收预算;下次扫描或升级终止阶段重新读取。续跑使用新 run UUID;复用 native session ID 的活跃子进程仍保守视为未结束。可读的运行态不被结果附件覆盖。缺少、损坏、超限、链接文件、身份不符或不完整的回执仍保持未知并阻止账号交接,不能仅凭宿主退出、文件陈旧或 stop 无回执放行。恢复只读取证据,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 d2a8329401..4149db1dfd 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@@ -1451,6 +1451,34 @@ describe('PI durable subagent run store', () => {: commands.map((command, i) => `${100 + i} ${command}`).join('\n');}+ // #6733: global account/exit sweeps share one deadline across parents.+ // Three complete receipts and a 4s OS probe must fit an 8s budget; the+ // former per-root query exhausted it. Advance a clock, never really wait.+ it.each([false, true])('shares the global recovery budget while last-root child alive is %s', async activeLast => {+ usePlatform('win32');+ const { agentHome, config, result } = await terminalReceiptHome(async () => {});+ for (const parent of ['session-2', 'session-3']) {+ const dir = path.join(piSubagentRunRoot(agentHome, parent), runId);+ await mkdir(dir, { recursive: true });+ const tasks = [{ ...config.tasks[0]!, sessionId: `native-${parent}` }];+ await writeFile(path.join(dir, 'config.json'), JSON.stringify({ ...config, parentSessionId: parent, runDir: dir, tasks }));+ await writeFile(path.join(dir, 'result.json'), JSON.stringify({ ...result, tasks: tasks.map(task => ({ ...task, status: 'completed' })) }));+ }+ let now = Date.now();+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now);+ childProcess.spawnSync.mockClear();+ childProcess.spawnSync.mockImplementation(() => {+ now += 4_000;+ return { status: 0, stdout: inventory([activeLast ? 'pi --session-id native-session-3' : 'node unrelated.js']) };+ });+ try {+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0, { killUnresponsiveRunners: true, killBudgetMs: 8_000 }))+ .resolves.toBe(!activeLast);+ // A fresh inventory is required for escalation, but never per root.+ expect(childProcess.spawnSync).toHaveBeenCalledTimes(activeLast ? 2 : 1);+ } finally { clock.mockRestore(); }+ });+it.each(['runner', 'orphan child'])('keeps a terminal receipt in scope while its %s is alive', async kind => {const { agentHome, dir, config } = await terminalReceiptHome(async () => {});const command = kind === 'runner'diff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.tsindex 41002b9c43..e29541f483 100644--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts@@ -3020,12 +3020,17 @@ const DEFAULT_KILL_BUDGET_MS = 8_000;* signalling child pids read off disk, which the runner header forbids because* of pid reuse.*/-async function sweepableRunsUnderRoot(+interface SweepableRun {+ runId: string;+ status: PiSubagentRunStatus | undefined;+ terminalIdentities?: string[];+}++async function collectSweepableRunsUnderRoot(root: string,scope: PiSubagentSweepScope,- recoveryDeadline: number,startTimeMemo?: ProcessStartTimeMemo,-): Promise<Array<{ runId: string; status: PiSubagentRunStatus | undefined }>> {+): Promise<SweepableRun[]> {const runIds = await listRunDirectoryIds(root);const [listedStatuses, diagnostics] = await Promise.all([listPiSubagentRuns(root),@@ -3035,15 +3040,10 @@ async function sweepableRunsUnderRoot(const staleRunIds = new Set(diagnostics.filter((diagnostic) => diagnostic.kind === 'stale').map((diagnostic) => diagnostic.runId),);- const sweepable: Array<{ runId: string; status: PiSubagentRunStatus | undefined }> = [];- const recoveryCandidates = new Map<string, string[]>();+ const sweepable: SweepableRun[] = [];for (const runId of runIds) {const status = statuses.get(runId);if ((status && isPiSubagentTerminal(status.state)) || staleRunIds.has(runId)) continue;- if (!status) {- const identities = await terminalResultProcessIdentities(root, runId);- if (identities) recoveryCandidates.set(runId, identities);- }if (scope.runtimeOwnerId !== undefined&& status?.runtimeOwnerId !== undefined@@ -3052,18 +3052,33 @@ async function sweepableRunsUnderRoot(continue;}if (scope.hostPid !== undefined && !isSweepableByHost(status, scope.hostPid, startTimeMemo)) continue;- sweepable.push({ runId, status });+ const terminalIdentities = !status ? await terminalResultProcessIdentities(root, runId) : null;+ sweepable.push({ runId, status, ...(terminalIdentities ? { terminalIdentities } : {}) });}- if (recoveryCandidates.size === 0) return sweepable;- // Read all candidate receipts BEFORE the inventory. Caching an earlier- // inventory while reading later receipts could miss a late runner launch.- // This one bounded, read-only probe is shared only within the current pass.+ return sweepable;+}++async function sweepableRunsUnderRoots(+ roots: readonly string[],+ scope: PiSubagentSweepScope,+ recoveryDeadline: number,+ startTimeMemo?: ProcessStartTimeMemo,+): Promise<Map<string, SweepableRun[]>> {+ const byRoot = new Map<string, SweepableRun[]>();+ for (const root of roots) {+ byRoot.set(root, await collectSweepableRunsUnderRoot(root, scope, startTimeMemo));+ }+ if (![...byRoot.values()].some(runs => runs.some(run => run.terminalIdentities))) return byRoot;+ // Read every root's receipts BEFORE the inventory: an earlier cached query+ // could miss a later launch. One query per pass also keeps historical roots+ // from each consuming another slice of the shared recovery deadline.const processes = await readRecoveryProcessInventory(recoveryDeadline);- if (!processes) return sweepable;- return sweepable.filter(({ runId }) => {- const identities = recoveryCandidates.get(runId);- return !identities || processes.some(command => identities.some(id => command.includes(id)));- });+ if (!processes) return byRoot;+ for (const [root, runs] of byRoot) {+ byRoot.set(root, runs.filter(({ terminalIdentities }) => !terminalIdentities+ || processes.some(command => terminalIdentities.some(id => command.includes(id)))));+ }+ return byRoot;}/**@@ -3243,8 +3258,8 @@ async function stopPiSubagentRunsUnderRoots(// meaningfully be recycled, and across passes we must see it if it was.const startTimeMemo: ProcessStartTimeMemo = new Map();let activeCount = 0;- for (const root of roots) {- for (const { runId } of await sweepableRunsUnderRoot(root, scope, recoveryDeadline, startTimeMemo)) {+ for (const [root, runs] of await sweepableRunsUnderRoots(roots, scope, recoveryDeadline, startTimeMemo)) {+ for (const { runId } of runs) {activeCount += 1;const key = `${root}:${runId}`;if (requested.has(key)) continue;@@ -3264,10 +3279,9 @@ async function stopPiSubagentRunsUnderRoots(if (!scope.killUnresponsiveRunners) return false;const killDeadline = Math.min(recoveryDeadline, Date.now() + (scope.killBudgetMs ?? DEFAULT_KILL_BUDGET_MS));let killedAll = true;- for (const root of roots) {- // Re-derived, so a run whose directory vanished in the meantime is gone- // from the set and counts as reclaimed.- const work = await sweepableRunsUnderRoot(root, scope, killDeadline, startTimeMemo);+ // Re-read every root and take a fresh inventory for the escalation pass.+ // A run whose directory vanished is gone from the set and reclaimed.+ for (const work of (await sweepableRunsUnderRoots(roots, scope, killDeadline, startTimeMemo)).values()) {// In parallel: each reclaim is mostly waiting on its own process probe,// and serialising them multiplied the worst case by the number of// runners — enough to overrun a quit budget with only a few of them.