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(pi): bound pending polling and retire stale notifications

zqchris546fd007457d
diff --git a/docs/research/pi-subagent-delegation.md b/docs/research/pi-subagent-delegation.md
index f7c9805c4b..1a8a231e49 100644
--- a/docs/research/pi-subagent-delegation.md
+++ b/docs/research/pi-subagent-delegation.md
@@ -83,6 +83,9 @@ sequenceDiagram
- 待投递意图记在原生 custom entry;结果通过 custom message 持久化。
从当前分支恢复时,已投递/已消费的 run 不再通知。
+- 收集循环只读取 pending run 的状态,不反复扫描历史目录。恢复记录若已属于旧 runtime
+ owner,或宿主明确拒绝状态访问,则回传诊断并结束该记录的自动等待;不暴露旧 owner
+ 的输出、不接管或停止其 child。状态文件暂时不可读但宿主仍确认有效时继续等待。
- 父轮已经 abort/error 时不追加自动继续;结束前等待中定期查询 host gate,
用户停止、关闭或账号边界会撤销本轮通知。原生 Pi 再检查一次等待期间的 abort。
- 新输入优先于收集等待。`agent_settled` 清除未投递意图,防止下一次不相关输入复活旧通知。
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts
index 715a135288..8321c61fcc 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts
@@ -12,14 +12,20 @@ import { CINDY_SUBAGENT_EXTENSION_SOURCE } from '../cindy-subagent-source.js';
const compiled = ts.transpileModule(CINDY_SUBAGENT_EXTENSION_SOURCE + '\nexport { parentContextSnapshot, createResultDelivery };', {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText;
-const extension: any = {};
-new Function('require', 'exports', compiled)(createRequire(import.meta.url), extension);
+const nativeRequire = createRequire(import.meta.url);
+function loadExtension(fsOverrides: Record<string, unknown> = {}) {
+ const loaded: any = {};
+ new Function('require', 'exports', compiled)((name: string) => name === 'node:fs'
+ ? { ...nativeRequire(name), ...fsOverrides } : nativeRequire(name), loaded);
+ return loaded;
+}
+const extension = loadExtension();
const roots: string[] = [];
afterEach(async () => {
vi.unstubAllEnvs();
await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));
});
-async function fixture() {
+async function fixture(fsOverrides: Record<string, unknown> = {}) {
const root = await mkdtemp(path.join(os.tmpdir(), 'pi-delegation-'));
roots.push(root);
vi.stubEnv('CINDY_PI_SUBAGENT_RUN_ROOT', root);
@@ -38,13 +44,19 @@ async function fixture() {
let tool: any;
const pi = { on: (event: string, handler: any) => { hooks[event] = handler; }, appendEntry: vi.fn(),
registerTool: (value: any) => { tool = value; } };
- await extension.default(pi);
+ await loadExtension(fsOverrides).default(pi);
const ctx = { ui: { input: vi.fn(async (_title: string, _payload: string) => JSON.stringify({ ok: true })) },
sessionManager: { getBranch: () => [] }, hasPendingMessages: () => false };
const execute = (params: any, signal = new AbortController().signal) => tool.execute('control-id', params, signal, undefined, ctx);
return { root, runId, dir, status, publish, hooks, pi, ctx, execute };
}
const boundary = { outcome: 'completed', context: { pendingMessages: [] } };
+function restorePending(f: Awaited<ReturnType<typeof fixture>>) {
+ f.hooks.session_start!({}, { sessionManager: { getBranch: () => [{
+ type: 'custom', customType: 'cindy-subagent-delivery',
+ data: { runId: f.runId, state: 'pending', deadlineAt: Date.now() + 86400000 },
+ }] } });
+}
describe('Pi delegation behavior', () => {
it('forks the native projected context, prioritizing the latest correction and compaction summary', () => {
@@ -186,6 +198,90 @@ describe('Pi delegation behavior', () => {
expect(result.entries[0].content).toContain('Runner crashed');
});
+ it('polls only pending runs without listing or reading historical statuses', async () => {
+ const fs = nativeRequire('node:fs');
+ const readStatus = vi.fn(fs.readFileSync);
+ const scanHistory = vi.fn(fs.readdirSync);
+ const f = await fixture({ readFileSync: readStatus, readdirSync: scanHistory });
+ const historicalId = randomUUID();
+ await mkdir(path.join(f.root, historicalId));
+ await writeFile(path.join(f.root, historicalId, 'status.json'), JSON.stringify({
+ ...f.status, runId: historicalId, state: 'completed',
+ }));
+ restorePending(f);
+ // Keep the run active for several poll ticks, then simulate user input.
+ let polls = 0;
+ f.ctx.hasPendingMessages = () => ++polls > 3;
+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();
+ expect(scanHistory).not.toHaveBeenCalled();
+ const files = readStatus.mock.calls.map(args => String(args[0]));
+ expect(files.filter(file => file === path.join(f.dir, 'status.json'))).toHaveLength(3);
+ expect(files.some(file => file.includes(historicalId))).toBe(false);
+ });
+
+ it.each(['running', 'completed'])('settles a restored %s run owned by the previous runtime without exposing its output', async state => {
+ const f = await fixture();
+ f.status.state = state;
+ f.status.runtimeOwnerId = 'previous-runtime';
+ f.status.tasks.forEach(task => { task.status = state; task.output = 'FOREIGN_OUTPUT'; });
+ await f.publish();
+ restorePending(f);
+ const result = await f.hooks.agent_before_settle!(boundary, f.ctx);
+ expect(result.continue).toBe(true);
+ expect(result.entries[0].content).toContain('another runtime owner');
+ expect(result.entries[0].content).not.toContain('FOREIGN_OUTPUT');
+ expect(result.entries[0].details.runIds).toEqual([f.runId]);
+ expect(f.ctx.ui.input.mock.calls.every(([, payload]) => JSON.parse(payload).action === 'delivery')).toBe(true);
+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();
+ f.hooks.session_start!({}, { sessionManager: { getBranch: () => [{
+ type: 'custom', customType: 'cindy-subagent-delivery',
+ data: { runId: f.runId, state: 'pending', deadlineAt: Date.now() + 86400000 },
+ }, ...result.entries] } });
+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();
+ expect(await readdir(f.dir)).toEqual(['status.json']);
+ });
+
+ it('settles a restored missing run when the host rejects status access', async () => {
+ const f = await fixture();
+ await rm(path.join(f.dir, 'status.json'));
+ restorePending(f);
+ f.ctx.ui.input.mockImplementation(async (_title, payload) => JSON.stringify(JSON.parse(payload).action === 'status'
+ ? { ok: false, error: 'PI Subagent runner control failed' } : { ok: true }));
+ const result = await f.hooks.agent_before_settle!(boundary, f.ctx);
+ expect(result.entries[0].content).toContain('host rejected status access');
+ expect(result.entries[0].content).toContain('does not confirm the child stopped');
+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();
+ });
+
+ it('does not deliver legacy output when both the runtime and status lack an owner', async () => {
+ const f = await fixture();
+ vi.stubEnv('CINDY_PI_SUBAGENT_OWNER_ID', undefined);
+ f.status.state = 'completed';
+ f.status.tasks.forEach(task => { task.status = 'completed'; task.output = 'LEGACY_OUTPUT'; });
+ await writeFile(path.join(f.dir, 'status.json'), JSON.stringify({ ...f.status, runtimeOwnerId: undefined }));
+ restorePending(f);
+ const result = await f.hooks.agent_before_settle!(boundary, f.ctx);
+ expect(result.entries[0].content).toContain('another runtime owner');
+ expect(result.entries[0].content).not.toContain('LEGACY_OUTPUT');
+ });
+
+ it('keeps a transiently unreadable status pending when the host still confirms the run', async () => {
+ const f = await fixture();
+ await rm(path.join(f.dir, 'status.json'));
+ restorePending(f);
+ f.ctx.ui.input.mockImplementation(async (_title, payload) => {
+ if (JSON.parse(payload).action === 'status') {
+ f.status.state = 'completed';
+ f.status.tasks.forEach(task => { task.status = 'completed'; task.output = 'RECOVERED_RESULT'; });
+ await f.publish();
+ }
+ return JSON.stringify({ ok: true });
+ });
+ const result = await f.hooks.agent_before_settle!(boundary, f.ctx);
+ expect(result.entries[0].content).toContain('RECOVERED_RESULT');
+ expect(result.entries[0].content).not.toContain('rejected');
+ });
+
it('retains the failure reason alongside intermediate output', async () => {
const f = await fixture();
Object.assign(f.status.tasks[0]!, { status: 'failed', error: 'Provider disconnected' });
diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
index 6c2d768d3f..e3c5e643a1 100644
--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
@@ -512,6 +512,18 @@ function writePrivateJson(file, value) {
try { chmodSync(file, 0o600); } catch (err) { /* best effort on Windows */ }
}
+function readDurableStatus(runId) {
+ const root = process.env[RUN_ROOT_ENV];
+ if (!root || typeof runId !== 'string' || !/^[0-9a-f-]{36}$/i.test(runId)) return null;
+ try {
+ const file = join(root, runId, 'status.json');
+ const stat = statSync(file);
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return null;
+ const status = JSON.parse(readFileSync(file, 'utf8'));
+ return status && status.version === 1 && status.runId === runId ? status : null;
+ } catch (err) { return null; /* transiently unreadable status */ }
+}
+
function durableStatuses() {
const root = process.env[RUN_ROOT_ENV];
const runtimeOwnerId = process.env[OWNER_ID_ENV];
@@ -521,21 +533,10 @@ function durableStatuses() {
const statuses = [];
for (const entry of entries) {
if (!entry.isDirectory() || !/^[0-9a-f-]{36}$/i.test(entry.name)) continue;
- const file = join(root, entry.name, 'status.json');
- try {
- const stat = statSync(file);
- if (!stat.isFile() || stat.size > 2 * 1024 * 1024) continue;
- const status = JSON.parse(readFileSync(file, 'utf8'));
- // Shared userData can contain runs for the same task opened by another
- // Desktop instance. The in-model management actions are a control plane,
- // so legacy or foreign ownership must fail closed just like host controls.
- if (
- status
- && status.version === 1
- && status.runId === entry.name
- && status.runtimeOwnerId === runtimeOwnerId
- ) statuses.push(status);
- } catch (err) { /* unreadable runs fail closed */ }
+ const status = readDurableStatus(entry.name);
+ // Only explicit list/management discovery scans history. Never expose
+ // legacy or foreign-owner results through the model's control plane.
+ if (status && status.runtimeOwnerId === runtimeOwnerId) statuses.push(status);
}
return statuses.sort(function (left, right) { return Number(right.startedAt || 0) - Number(left.startedAt || 0); });
}
@@ -901,7 +902,10 @@ async function requestRunnerControl(ctx, action, runId, options = {}) {
);
}
if (!response || response.ok !== true) {
- throw new Error('subagent: Cindy could not ' + action + ' the durable runner.');
+ throw Object.assign(
+ new Error('subagent: Cindy could not ' + action + ' the durable runner.'),
+ { runnerRejected: !!response && response.ok === false && typeof response.error === 'string' },
+ );
}
return response;
}
@@ -1339,20 +1343,25 @@ function createResultDelivery(pi) {
return;
}
if (typeof ctx.hasPendingMessages === 'function' && ctx.hasPendingMessages()) return;
- const statuses = durableStatuses();
const ready = [];
const runIds = [];
const pollHost = Date.now() >= nextHostPoll;
if (pollHost) nextHostPoll = Date.now() + 1000;
for (const [runId, deadlineAt] of pending) {
- const status = statuses.find(function (entry) { return entry.runId === runId; });
- if (status && isTerminalStatus(status.state)) {
+ // Poll only the pending set: completed history can be arbitrarily
+ // large and must not occupy Pi's event loop on every 250 ms tick.
+ const status = readDurableStatus(runId);
+ if (status && (!process.env[OWNER_ID_ENV] || status.runtimeOwnerId !== process.env[OWNER_ID_ENV])) {
+ ready.push('runId=' + runId + ': automatic result collection is unavailable because the run belongs to another runtime owner. Its output was not read into this conversation; this does not confirm the child stopped.');
+ runIds.push(runId);
+ } else if (status && isTerminalStatus(status.state)) {
ready.push(describeRun(status));
runIds.push(runId);
} else if (pollHost) {
try { await requestRunnerControl(ctx, 'status', runId); } catch (error) {
- if (error && error.runnerExited) {
- ready.push('runId=' + runId + ': ' + error.message);
+ if (error && (error.runnerExited || error.runnerRejected)) {
+ ready.push('runId=' + runId + ': ' + error.message
+ + (error.runnerRejected ? ' Automatic collection ended after the host rejected status access; this does not confirm the child stopped.' : ''));
runIds.push(runId);
continue;
}