Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): distinguish consumed follow-ups from steering
xuzini-xzn003113a3c164
diff --git a/packages/maker-core/src/agents/pi/__tests__/cache-compatibility.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/cache-compatibility.integration.test.tsindex be184c2ee7..a803b53a05 100644--- a/packages/maker-core/src/agents/pi/__tests__/cache-compatibility.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cache-compatibility.integration.test.ts@@ -34,6 +34,8 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTT// #7561: actual followUp start has no second agent_start. Exercise the// public send queue and outgoing HTTP, beyond the unit lifecycle fixture.{ api, mode: 'queued', rejection: { error: { message: 'opaque refusal', type: 'invalid_request_error' } } },+ { api, mode: 'steer', rejection: { error: { message: 'opaque refusal', type: 'invalid_request_error' } } },+ { api, mode: 'mixed', rejection: { error: { message: 'opaque refusal', type: 'invalid_request_error' } } },]))('preserves bounded recovery and native caching: $api / $mode', async ({ api, mode, rejection }) => {const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-cache-integration-'));const received: Array<Record<string, unknown>> = [];@@ -47,9 +49,10 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTTexpect(req.headers.authorization).toBe('Bearer fixture-key');let body = ''; for await (const chunk of req) body += chunk;const data = JSON.parse(body); received.push(data);- const held = mode === 'queued' && received.length === 1;+ const held = ['queued', 'steer', 'mixed'].includes(mode) && received.length === 1;if (held) { firstArrived(); await firstReleased; }- if (!held && (persistentFailure || rejectCache && ('prompt_cache_key' in data || 'prompt_cache_retention' in data))) {+ const successfulSteer = mode === 'mixed' && received.length === 2;+ if (!held && !successfulSteer && (persistentFailure || rejectCache && ('prompt_cache_key' in data || 'prompt_cache_retention' in data))) {res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify(rejection)); return;}res.writeHead(200, { 'content-type': 'text/event-stream' });@@ -77,9 +80,10 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTTconst events: AgentEvent[] = [];const finish = (async () => { for await (const event of handle!.events()) { events.push(event); if (event.type === 'done') break; } })();await handle!.send({ type: 'user', content: 'Reply OK' });- if (mode === 'queued' && received.length <= 1) {+ if (['queued', 'steer', 'mixed'].includes(mode) && received.length <= 1) {await firstRequest;- await handle!.send({ type: 'user', content: 'Reply OK to the queued message' });+ if (mode !== 'steer') await handle!.send({ type: 'user', content: 'Reply OK to the queued message' });+ if (mode !== 'queued') await handle!.steer({ type: 'user', content: 'Reply OK to the inserted steer' });releaseFirst();}await finish; return events;@@ -87,11 +91,11 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTTconst agent = new PiAgent(deps);handle = await agent.startSession({ ...opts, sessionId: 'first' });const first = await run();- expect(received).toHaveLength(mode === 'supported' ? 1 : mode === 'queued' ? 3 : 2);+ expect(received).toHaveLength(mode === 'supported' ? 1 : mode === 'queued' ? 3 : mode === 'mixed' ? 4 : 2);expect(received[0]).toHaveProperty('prompt_cache_key');expect(received[0]).toHaveProperty('prompt_cache_retention', '24h');- if (mode !== 'supported') {- const original = mode === 'queued' ? 1 : 0;+ if (mode !== 'supported' && mode !== 'steer') {+ const original = mode === 'queued' ? 1 : mode === 'mixed' ? 2 : 0;expect(received[original]).toHaveProperty('prompt_cache_retention', '24h');const { prompt_cache_key: _key, prompt_cache_retention: _retention, ...without } = received[original];expect(received[original + 1]).toEqual(without);@@ -100,9 +104,10 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTTconst sessions = path.join(root, 'agent', 'sessions');const transcripts = readdirSync(sessions, { recursive: true }).map(name => path.join(sessions, name.toString())).filter(name => name.endsWith('.jsonl'));const entries = transcripts.flatMap(name => readFileSync(name, 'utf8').trim().split('\n').map(line => JSON.parse(line)));- expect(entries.filter(entry => entry.type === 'message' && entry.message?.role === 'user')).toHaveLength(mode === 'queued' ? 2 : 1);- expect(entries.filter(entry => entry.type === 'message' && entry.message?.role === 'assistant')).toHaveLength(mode === 'queued' ? 2 : 1);- if (mode === 'always-fails') {+ const userInputs = mode === 'mixed' ? 3 : ['queued', 'steer'].includes(mode) ? 2 : 1;+ expect(entries.filter(entry => entry.type === 'message' && entry.message?.role === 'user')).toHaveLength(userInputs);+ expect(entries.filter(entry => entry.type === 'message' && entry.message?.role === 'assistant')).toHaveLength(userInputs);+ if (mode === 'always-fails' || mode === 'steer') {expect(first.filter(e => e.type === 'error')).toHaveLength(1);expect(first.find(e => e.type === 'error')?.data).toMatchObject({ piCacheRecoveryHandled: true });expect(existsSync(storeFile)).toBe(false);@@ -119,7 +124,7 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTTexpect(records).toHaveLength(1);expect(records[0].expiresAt - records[0].learnedAt).toBe((mode === 'explicit' ? 7 : 1) * 86400000);expect(readFileSync(storeFile, 'utf8')).not.toContain(endpoint);- if (mode === 'queued') return;+ if (mode === 'queued' || mode === 'mixed') return;await handle.close(); handle = await agent.startSession({ ...opts, sessionId: 'learned' });await run(); expect(received).toHaveLength(3); expect(received[2]).not.toHaveProperty('prompt_cache_key');// The same running Pi must restore real fields when its rule expires.diff --git a/packages/maker-core/src/agents/pi/__tests__/cache-input.test.ts b/packages/maker-core/src/agents/pi/__tests__/cache-input.test.tsnew file mode 100644index 0000000000..a7eba3f331--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/cache-input.test.ts@@ -0,0 +1,79 @@+import { createHash } from 'node:crypto';+import { describe, expect, it } from 'vitest';+import { createPiCacheInputTracker } from '../cache-input.js';++describe('Pi accepted queue provenance', () => {+ function fixture() {+ const digest = (text: string) => createHash('sha256').update(text).digest('hex');+ const tracker = createPiCacheInputTracker(digest);+ const queues = (steering: string[], followUp: string[]) => tracker.observe({ type: 'queue_update', steering, followUp });+ const start = (text: string) => tracker.observe({ type: 'message_start', message: { role: 'user', content: [{ type: 'text', text }], timestamp: 123 } });+ return { tracker, queues, start };+ }++ it('uses accepted expanded queue text, including mixed queue priority and multiple inputs', () => {+ const h = fixture();+ // Raw input events may be transformed/handled; only native accepted+ // queues count. No input counter or unexpanded text is involved.+ h.tracker.observe({ type: 'input', streamingBehavior: 'steer', text: 'handled' });+ h.queues([], ['expanded template', 'second']);+ h.queues(['inserted steer'], ['expanded template', 'second']);+ h.queues([], ['expanded template', 'second']);+ expect(h.start('inserted steer')?.followUp).toBe(false);+ h.queues([], ['second']);+ const first = h.start('expanded template');+ expect(first?.followUp).toBe(true);+ expect(h.tracker.read(first!.key)).toEqual(first);+ expect(h.tracker.read('stale')).toBeUndefined();+ h.queues([], []);+ expect(h.start('second')?.followUp).toBe(true);+ expect(h.start('not queued')?.followUp).toBe(false);+ });++ it('does not mistake clearing/replacement, mismatched messages or tools for consumption', () => {+ const h = fixture();+ h.queues([], ['one', 'two']); h.queues([], []);+ expect(h.start('one')?.followUp).toBe(false);+ h.queues([], ['one']); h.queues([], ['replacement']);+ expect(h.start('one')?.followUp).toBe(false);+ h.queues([], []);+ expect(h.start('different')?.followUp).toBe(false);+ h.queues([], ['one']); h.queues([], []);+ h.tracker.observe({ type: 'agent_start' });+ expect(h.start('one')?.followUp).toBe(false);+ expect(h.tracker.observe({ type: 'message_start', message: { role: 'toolResult' } })).toBeUndefined();+ });++ it('fails closed for identical text across queues, even after it disappears from one queue', () => {+ const h = fixture();+ h.queues(['same'], ['same']);+ h.queues([], ['same']);+ expect(h.start('same')?.followUp).toBe(false);+ h.queues([], []);+ expect(h.start('same')?.followUp).toBe(false);+ h.tracker.observe({ type: 'agent_settled' });+ h.queues([], ['same']); h.queues([], []);+ expect(h.start('same')?.followUp).toBe(true);+ });++ it.each(['agent_settled', 'session_switch', 'session_shutdown'])('discards accepted queues at %s', type => {+ const h = fixture();+ h.queues([], ['old session']);+ h.tracker.observe({ type });+ h.queues([], []);+ expect(h.start('old session')?.followUp).toBe(false);+ h.queues([], ['new input']); h.queues([], []);+ expect(h.start('new input')?.followUp).toBe(true);+ });++ it('does not reuse uncertain or excessive queue state', () => {+ const h = fixture();+ h.tracker.observe({ type: 'queue_update', steering: null, followUp: [] });+ h.queues([], ['one']); h.queues([], []);+ expect(h.start('one')?.followUp).toBe(false);+ h.tracker.observe({ type: 'agent_settled' });+ h.queues([], Array.from({ length: 1025 }, (_, i) => String(i)));+ h.queues([], ['one']); h.queues([], []);+ expect(h.start('one')?.followUp).toBe(false);+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/cache-recovery.test.ts b/packages/maker-core/src/agents/pi/__tests__/cache-recovery.test.tsindex 29f3e51933..eac2d97cb3 100644--- a/packages/maker-core/src/agents/pi/__tests__/cache-recovery.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cache-recovery.test.ts@@ -35,9 +35,14 @@ function fixture() {pi: { on: (name: string, fn: (...args: any[]) => void) => handlers.set(name, fn) },process: { env: { PI_CODING_AGENT_DIR: '/agent', CINDY_PI_CACHE_COMPAT_FILE: '/compat.json' } },// The in-memory filesystem uses POSIX keys on every host, including Windows.- ...fs, path: path.posix, createHash, randomUUID, Buffer, Date: { now: () => now }, homedir: () => '/home/fixture',+ ...fs, path: path.posix, createHash, randomUUID, Buffer, setTimeout, clearTimeout, Date: { now: () => now }, homedir: () => '/home/fixture',});- const startUser = () => handlers.get('message_start')?.({ message: { role: 'user', content: [{ type: 'text', text: 'OK' }] } });+ const startUser = (direct = true, followUp = false) => {+ if (direct) handlers.get('before_agent_start')?.({});+ handlers.get('message_start')?.({ message: { role: 'user', content: [{ type: 'text', text: 'OK' }] } }, {+ mode: 'rpc', ui: { input: async (_title: string, raw: string) => JSON.stringify({ key: JSON.parse(raw).key, followUp }) },+ });+ };const fresh = () => { handlers.get('input')!({ source: 'rpc' }, { isIdle: () => true }); startUser(); };const interrupt = () => handlers.get('input')!({ source: 'rpc', streamingBehavior: 'steer' }, { isIdle: () => false });const sent: any[] = [];@@ -65,7 +70,7 @@ function fixture() {}describe('Pi native cache recovery', () => {- it.each(['openai-completions', 'openai-responses'])('keeps learned payload recovery without taking provider ownership on an older %s registry', api => {+ it.each(['openai-completions', 'openai-responses'])('keeps learned payload recovery without taking provider ownership on an older %s registry', async api => {const h = fixture();const selected = { ...model, api };const rules = [{ ...selected, providerId: 'connection', routeKey }];@@ -80,7 +85,7 @@ describe('Pi native cache recovery', () => {const ctx = { model: selected, modelRegistry: { getProvider: vi.fn() } };const hook = h.handlers.get('before_provider_request')!;const payload = { ...body, service_tier: 'priority' };- expect(hook?.({ payload }, ctx) ?? payload).toEqual({ model: 'wire', messages: body.messages, service_tier: 'priority' });+ expect((await hook?.({ payload }, ctx)) ?? payload).toEqual({ model: 'wire', messages: body.messages, service_tier: 'priority' });expect(ctx.modelRegistry.getProvider).not.toHaveBeenCalled();expect(payload).toHaveProperty('prompt_cache_key', 'cache');// A newly loaded bridge reads the same durable record, not process memory.@@ -89,29 +94,29 @@ describe('Pi native cache recovery', () => {restarted.files.set('/compat.json', h.files.get('/compat.json')!);restarted.fresh();const recovered = restarted.handlers.get('before_provider_request')!;- expect(recovered({ payload }, ctx)).not.toHaveProperty('prompt_cache_key');- expect(recovered({ payload }, { ...ctx, model: { ...selected, baseUrl: selected.baseUrl + '/other' } })).toBeUndefined();- expect(recovered({ payload }, { ...ctx, modelRegistry: { ...ctx.modelRegistry, getRegisteredNativeProvider: vi.fn() } })).toBeUndefined();+ expect(await recovered({ payload }, ctx)).not.toHaveProperty('prompt_cache_key');+ expect(await recovered({ payload }, { ...ctx, model: { ...selected, baseUrl: selected.baseUrl + '/other' } })).toBeUndefined();+ expect(await recovered({ payload }, { ...ctx, modelRegistry: { ...ctx.modelRegistry, getRegisteredNativeProvider: vi.fn() } })).toBeUndefined();restarted.clock(1086400001);// Expiry cannot change a tool continuation in the already-started input.restarted.handlers.get('tool_execution_start')!();- expect(recovered({ payload }, ctx)).not.toHaveProperty('prompt_cache_key');+ expect(await recovered({ payload }, ctx)).not.toHaveProperty('prompt_cache_key');restarted.startUser();- expect(recovered({ payload }, ctx)).toBeUndefined();+ expect(await recovered({ payload }, ctx)).toBeUndefined();expect(restarted.record()).toEqual(record);});- it('preserves normal caching and bounds legacy records in the older registry payload hook', () => {+ it('preserves normal caching and bounds legacy records in the older registry payload hook', async () => {const h = fixture();const ctx = { model, modelRegistry: {} };const hook = () => h.handlers.get('before_provider_request')?.({ payload: body }, ctx);h.fresh();- expect(hook()).toBeUndefined();+ expect(await hook()).toBeUndefined();h.files.set('/compat.json', JSON.stringify({ routes: { [key]: { supportsLongCacheRetention: false } } }));h.clock(1001); h.fresh();- expect(hook()).toEqual({ model: 'wire', messages: body.messages });+ expect(await hook()).toEqual({ model: 'wire', messages: body.messages });h.clock(1000 + 7 * 86400000 + 1); h.fresh();- expect(hook()).toBeUndefined();+ expect(await hook()).toBeUndefined();});it('does one final-payload comparison, learns only after generation, and preserves usage', async () => {@@ -149,7 +154,7 @@ describe('Pi native cache recovery', () => {h.handlers.get('input')!({ source: 'rpc', streamingBehavior: 'followUp' }, { isIdle: () => false });});expect(h.sent).toHaveLength(1); expect(h.record()).toBeUndefined();- h.startUser();+ h.startUser(false, true);await h.request([failure()]);expect(h.sent).toHaveLength(3);expect(h.sent[1]).toHaveProperty('prompt_cache_key');@@ -165,6 +170,78 @@ describe('Pi native cache recovery', () => {expect(h.record()).toMatchObject({ evidence: 'opaque' });});+ it('does not reopen recovery when an actual steer user message is consumed', async () => {+ const h = fixture(); h.fresh();+ h.handlers.get('tool_execution_start')!();+ h.interrupt(); h.startUser(false);+ await h.request([failure(), success]);+ expect(h.sent).toHaveLength(1);+ expect(h.sent[0]).toHaveProperty('prompt_cache_key');+ expect(h.record()).toBeUndefined();+ // A later independently consumed followUp still owns its budget.+ h.startUser(false, true);+ await h.request([failure(), failure(), success]);+ expect(h.sent).toHaveLength(3);+ expect(h.record()).toMatchObject({ evidence: 'opaque' });+ });++ it('keeps the continuing snapshot when steer is consumed across its TTL', async () => {+ const h = fixture();+ const record = { supportsLongCacheRetention: false, learnedAt: 1000000000, expiresAt: 1086400000, evidence: 'opaque' };+ h.files.set('/compat.json', JSON.stringify({ routes: { [key]: record } }));+ h.fresh();+ h.handlers.get('tool_execution_start')!();+ h.clock(1086400001); h.interrupt(); h.startUser(false);+ await h.request([success]);+ expect(h.sent[0]).not.toHaveProperty('prompt_cache_key');+ const hook = h.handlers.get('before_provider_request')!;+ expect(await hook({ payload: body }, { model, modelRegistry: {} })).not.toHaveProperty('prompt_cache_key');+ h.startUser(false, true); await h.request([success]);+ expect(h.sent[1]).toHaveProperty('prompt_cache_key');+ });++ it('does not arm from a stale receipt or a followUp cancelled while its receipt is pending', async () => {+ for (const cancel of [false, true]) {+ const h = fixture(); h.fresh(); h.interrupt();+ h.handlers.get('message_start')!({ message: { role: 'user', content: [] } }, { mode: 'rpc', ui: {+ input: async (_title: string, raw: string) => {+ if (cancel) h.handlers.get('tool_execution_start')!();+ return JSON.stringify({ key: cancel ? JSON.parse(raw).key : 'stale', followUp: true });+ },+ } });+ await h.request([failure(), success]);+ expect(h.sent).toHaveLength(1);+ expect(h.record()).toBeUndefined();+ }+ });++ it.each([true, false].flatMap(direct => [{ direct, mode: 'rpc' }, { direct, mode: undefined }]))(+ 'binds $direct input receipts before message_end replaces the message (mode: $mode)', async ({ direct, mode }) => {+ const h = fixture(); h.fresh(); h.interrupt();+ if (direct) h.handlers.get('before_agent_start')!({});+ const message = { role: 'user', content: [{ type: 'text', text: 'accepted input' }], timestamp: 123 };+ const key = createHash('sha256').update(JSON.stringify(message)).digest('hex');+ const query = vi.fn(async () => JSON.stringify({ key, followUp: !direct }));+ h.handlers.get('message_start')!({ message }, { mode, ui: { input: query } });+ // Pi's message_end replacement mutates the same message object in place.+ Object.assign(message, { content: [{ type: 'text', text: 'extension replacement' }], timestamp: 456 });+ await h.request([failure(), success]);+ expect(query).toHaveBeenCalledWith('cindy:cache-input', JSON.stringify({ key, direct }));+ expect(h.sent).toHaveLength(2);+ expect(h.record()).toMatchObject({ evidence: 'opaque' });+ },+ );++ it('does not ask an interactive runtime to confirm queued provenance', async () => {+ const h = fixture(); h.fresh(); h.interrupt();+ const query = vi.fn();+ h.handlers.get('message_start')!({ message: { role: 'user', content: [] } }, { mode: 'interactive', ui: { input: query } });+ await h.request([failure(), success]);+ expect(query).not.toHaveBeenCalled();+ expect(h.sent).toHaveLength(1);+ expect(h.record()).toBeUndefined();+ });+// PR #7561 P1: freeze learned state across tool calls, including the case// where the TTL passes after input start but before the first provider call.it('freezes learned cache removal until the next real user input', async () => {diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.tsindex 998f6bb219..7733570336 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts@@ -218,6 +218,7 @@ async function makeFixture(options: {outputText?: string;chain?: boolean;approval?: boolean;+ cacheQueries?: boolean;/*** Emit several approval requests from one prompt, the way a turn whose* parallel tool calls each ask before running does. The fake child only@@ -433,6 +434,16 @@ let buffer = '';const expectedApprovals = ${JSON.stringify(approvalIds)};const answeredApprovals = new Set();let allowedApprovals = 0;+${options.cacheQueries ? `let cacheQueryStage = 0;+function cacheQuery(kind) {+ const message = { role: 'user', content: [{ type: 'text', text: kind }], timestamp: 123 };+ const key = require('node:crypto').createHash('sha256').update(JSON.stringify(message)).digest('hex');+ const emit = event => process.stdout.write(JSON.stringify(event) + '\\n');+ emit({ type: 'queue_update', steering: kind === 'steer' ? [kind] : [], followUp: kind === 'followUp' ? [kind] : [] });+ emit({ type: 'queue_update', steering: [], followUp: [] });+ emit({ type: 'message_start', message });+ emit({ type: 'extension_ui_request', id: 'cache-query', method: 'input', title: 'cindy:cache-input', placeholder: JSON.stringify({ key, direct: false }) });+}` : ''}process.stdin.setEncoding('utf8');process.stdin.on('data', (chunk) => {buffer += chunk;@@ -447,6 +458,7 @@ process.stdin.on('data', (chunk) => {if (command.type === 'prompt') {fs.appendFileSync(process.env.CINDY_TEST_PI_PROMPTS, JSON.stringify(command.message) + '\\n');process.stdout.write(JSON.stringify({ type: 'response', command: 'prompt', success: true }) + '\\n');+ ${options.cacheQueries ? `cacheQuery('steer'); continue;` : ''}${approvalIds.length > 0? `for (const id of expectedApprovals) {process.stdout.write(JSON.stringify({ type: 'extension_ui_request', id, method: ${JSON.stringify(approvalMethod)}, title: 'cindy:permission', ${approvalMethod === 'input' ? 'placeholder' : 'message'}: JSON.stringify({ toolName: 'write', input: { path: 'a.txt' } }) }) + '\\n');@@ -457,6 +469,13 @@ process.stdin.on('data', (chunk) => {${fixtureLifecycle}${options.hangOnMessage ? '}' : ''}`}}+ ${options.cacheQueries ? `if (command.type === 'extension_ui_response' && command.id === 'cache-query') {+ const receipt = JSON.parse(command.value);+ if (receipt.followUp !== (cacheQueryStage === 1)) process.exit(14);+ cacheQueryStage++;+ if (cacheQueryStage === 1) cacheQuery('followUp');+ else { ${fixtureLifecycle} }+ }` : ''}if (command.type === 'extension_ui_response' && expectedApprovals.includes(command.id)) {answeredApprovals.add(command.id);if (command.confirmed || command.value === 'allow') allowedApprovals += 1;@@ -1438,6 +1457,22 @@ describe('Cindy durable PI Subagent runner', () => {await waitForClose(fixture.child, fixture.stderr);});+ it('answers cache provenance privately for consumed steer and followUp in the real runner', async () => {+ const fixture = await makeFixture({ cacheQueries: true });+ const completed = await waitFor(async () => {+ const [run] = await listPiSubagentRuns(fixture.root);+ return run?.state === 'completed' ? run : null;+ });+ expect(completed.tasks[0]?.output).toBe('fixture result');+ expect(completed.tasks[0]?.pendingApproval).toBeUndefined();+ const commands = (await readFile(fixture.commandsFile, 'utf8')).trim().split('\n').map(line => JSON.parse(line));+ const replies = commands.filter(command => command.id === 'cache-query');+ expect(replies).toHaveLength(2);+ expect(replies.map(command => JSON.parse(command.value).followUp)).toEqual([false, true]);+ expect(await readFile(path.join(fixture.runDir, 'transcript.jsonl'), 'utf8')).not.toContain('cindy:cache-input');+ await waitForClose(fixture.child, fixture.stderr);+ });+it('forwards a child approval response through runner-owned RPC stdin', async () => {const fixture = await makeFixture({ approval: true });const pending = await waitFor(async () => {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 70ab1437c7..c6f4abbf24 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@@ -1403,10 +1403,27 @@ describe("Pi provider-aware model routing", () => {active = expected;if (mode === 'send') await handle.send({ type: 'user', content: 'try cache' });if (mode !== 'queued') captured.onEvent!({ type: 'agent_start' });- captured.onEvent!({ type: 'message_start', message: { role: 'user', content: [{ type: 'text', text: 'try cache' }] } });+ if (mode === 'queued') {+ captured.onEvent!({ type: 'queue_update', steering: [], followUp: ['try cache'] });+ captured.onEvent!({ type: 'queue_update', steering: [], followUp: [] });+ }+ const message = { role: 'user', content: [{ type: 'text', text: 'try cache' }] };+ captured.onEvent!({ type: 'message_start', message });+ const key = createHash('sha256').update(JSON.stringify(message)).digest('hex');+ captured.onEvent!({ type: 'extension_ui_request', method: 'input', title: 'cindy:cache-input',+ id: 'cache-input', placeholder: JSON.stringify({ key, direct: mode !== 'queued' }) });// Expiry or another session's learning during the request must not// change whether this input actually started with the override.active = !expected;+ // Consumed steer is another user message in the same execution. It+ // must neither refresh the receipt nor treat an auto-retry as input.+ captured.onEvent!({ type: 'queue_update', steering: ['steer'], followUp: [] });+ captured.onEvent!({ type: 'queue_update', steering: [], followUp: [] });+ const steer = { role: 'user', content: [{ type: 'text', text: 'steer' }] };+ captured.onEvent!({ type: 'message_start', message: steer });+ captured.onEvent!({ type: 'extension_ui_request', method: 'input', title: 'cindy:cache-input',+ id: 'cache-steer', placeholder: JSON.stringify({ key: createHash('sha256').update(JSON.stringify(steer)).digest('hex'), direct: false }) });+ captured.onEvent!({ type: 'agent_start' });captured.onEvent!({ type: 'message_start', message: { role: 'toolResult', content: [] } });captured.onEvent!({ type: 'auto_retry_end', success: false,finalError: '400: unsupported parameter: prompt_cache_retention' });diff --git a/packages/maker-core/src/agents/pi/cache-input.ts b/packages/maker-core/src/agents/pi/cache-input.tsnew file mode 100644index 0000000000..0634da8120--- /dev/null+++ b/packages/maker-core/src/agents/pi/cache-input.ts@@ -0,0 +1,60 @@+/** Observe Pi's accepted, expanded queue, never infer delivery from input text.+ * This self-contained function also runs in the generated subagent supervisor. */+export function createPiCacheInputTracker(digest: (text: string) => string) {+ let steering: string[] = [];+ let followUp: string[] = [];+ let removed: { kind: 'steer' | 'followUp'; text: string } | undefined;+ const ambiguous = new Set<string>();+ let overflow = false;+ let last: { key: string; followUp: boolean } | undefined;+ const same = (a: string[], b: string[]) => a.length === b.length && a.every((v, i) => v === b[i]);+ function deletion(before: string[], after: string[]) {+ if (before.length !== after.length + 1) return undefined;+ let i = 0;+ while (i < after.length && before[i] === after[i]) i++;+ return before.slice(i + 1).every((v, j) => v === after[i + j]) ? before[i] : undefined;+ }+ return {+ observe(event: { type: string; [key: string]: unknown }) {+ if (event.type === 'queue_update') {+ removed = undefined;+ if (!Array.isArray(event.steering) || !Array.isArray(event.followUp)+ || event.steering.length + event.followUp.length > 1024+ || [...event.steering, ...event.followUp].some(v => typeof v !== 'string')) {+ overflow = true; steering = []; followUp = []; return;+ }+ const nextSteering = event.steering as string[];+ const nextFollowUp = event.followUp as string[];+ // Pi's public queue bookkeeping matches text, steering first. Identical+ // text in both queues is ambiguous even if it is later cleared.+ for (const text of [...steering, ...nextSteering]) {+ if (followUp.includes(text) || nextFollowUp.includes(text)) {+ if (ambiguous.size >= 1024) overflow = true;+ else ambiguous.add(digest(text));+ }+ }+ const steerText = same(followUp, nextFollowUp) ? deletion(steering, nextSteering) : undefined;+ const followText = same(steering, nextSteering) ? deletion(followUp, nextFollowUp) : undefined;+ if (steerText !== undefined) removed = { kind: 'steer', text: steerText };+ else if (followText !== undefined) removed = { kind: 'followUp', text: followText };+ steering = [...nextSteering]; followUp = [...nextFollowUp];+ } else if (event.type === 'message_start') {+ const message = event.message as { role?: string; content?: unknown } | undefined;+ if (message?.role !== 'user') return;+ const text = typeof message.content === 'string' ? message.content+ : Array.isArray(message.content) ? message.content.filter(v => v?.type === 'text').map(v => v.text).join('') : '';+ last = { key: digest(JSON.stringify(message)), followUp: !overflow && removed?.kind === 'followUp'+ && removed.text === text && !ambiguous.has(digest(text)) };+ removed = undefined;+ return last;+ } else if (['agent_start', 'agent_settled', 'session_switch', 'session_shutdown'].includes(event.type)) {+ removed = undefined;+ if (event.type !== 'agent_start') {+ steering = []; followUp = [];+ ambiguous.clear(); overflow = false; last = undefined;+ }+ }+ },+ read(key: unknown) { return typeof key === 'string' && last?.key === key ? last : undefined; },+ };+}diff --git a/packages/maker-core/src/agents/pi/cache-recovery-source.ts b/packages/maker-core/src/agents/pi/cache-recovery-source.tsindex 979c711eab..09776c69c1 100644--- a/packages/maker-core/src/agents/pi/cache-recovery-source.ts+++ b/packages/maker-core/src/agents/pi/cache-recovery-source.ts@@ -7,6 +7,9 @@ function installCindyCacheRecovery(pi) {const home = process.env.CINDY_PI_CACHE_COMPAT_FILE;const file = home && home.replace(/^\$HOME(?=\/)/, () => homedir());let turn;+ let pendingInput;+ let directInput = false;+ let revision = 0;let sequence = 0;let memory = Object.create(null);let routeRules = new Map();@@ -18,14 +21,15 @@ function installCindyCacheRecovery(pi) {return Array.isArray(value) ? value : [];} catch { return []; }}- function refreshRules() {- routeRules = new Map(rules().flatMap(rule => {+ function readRules() {+ return new Map(rules().flatMap(rule => {if (!rule || typeof rule !== 'object' || typeof rule.providerId !== 'string'|| !/^[a-f0-9]{64}$/.test(rule.routeKey)) return [];return [[JSON.stringify([rule.provider, rule.id, rule.baseUrl, rule.api]),JSON.stringify([rule.providerId, rule.id, rule.routeKey])]];}));}+ function refreshRules() { routeRules = readRules(); }refreshRules();function route(model) {if (!supported(model?.api)) return;@@ -154,33 +158,78 @@ function installCindyCacheRecovery(pi) {}return cacheRejected || /(?:unsupported|not supported|unknown|未知|不支持).{0,80}prompt_cache_(?:key|retention)|prompt_cache_(?:key|retention).{0,80}(?:unsupported|not supported|unknown|未知|不支持)/i.test(body) ? 'explicit' : 'opaque';}+ function invalidate() {+ revision++;+ if (turn) { turn.safe = false; turn.valid = false; }+ }pi.on('input', () => {// Queuing/steering invalidates the old trial immediately. It cannot arm a// budget for the new input until Pi actually starts that user message.- if (turn) { turn.safe = false; turn.valid = false; }+ directInput = false;+ invalidate();});- pi.on('message_start', (event) => {+ pi.on('before_agent_start', () => { directInput = true; });+ pi.on('message_start', (event, ctx) => {if (event.message?.role !== 'user') return;- // Queued follow-ups do not emit agent_start. Tool continuations and native- // retries do not start a user message, so they retain this input's budget.- refreshRules();+ // Pi represents both steer and followUp as user messages. Snapshot now,+ // but decide ownership only after the supervisor sees the public event.+ invalidate();+ const inputRules = readRules();const records = load()?.routes ?? Object.create(null);for (const [key, record] of Object.entries(memory)) {if ((records[key]?.learnedAt ?? 0) < record.learnedAt) records[key] = record;}const startedAt = Date.now();const learned = new Set(Object.keys(records).filter(key => active(records[key], startedAt)));- turn = { sequence: ++sequence, safe: true, valid: true, attempted: false, learned };+ // Pi's later message_end hooks may replace this object in place. Match+ // the supervisor's message_start receipt, not a subsequently edited object.+ const key = createHash('sha256').update(JSON.stringify(event.message)).digest('hex');+ pendingInput = { key, ctx, direct: directInput, revision, learned, inputRules };+ if (directInput) {+ routeRules = inputRules;+ turn = { sequence: ++sequence, safe: true, valid: true, attempted: false, learned };+ }+ directInput = false;});+ async function settleInput() {+ const input = pendingInput;+ if (!input) return;+ if (!input.promise) input.promise = (async () => {+ let followUp = false;+ let timer;+ try {+ // Older RPC ExtensionContext versions do not expose mode.+ if (input.ctx?.mode && input.ctx.mode !== 'rpc') throw new Error('not RPC');+ const key = input.key;+ const raw = await Promise.race([+ input.ctx.ui.input('cindy:cache-input', JSON.stringify({ key, direct: input.direct })),+ new Promise(resolve => { timer = setTimeout(() => resolve(undefined), 5000); }),+ ]);+ if (typeof raw === 'string') {+ const receipt = JSON.parse(raw);+ followUp = receipt?.key === key && receipt.followUp === true;+ }+ } catch { /* Unconfirmed queued provenance must not reopen recovery. */ }+ finally { if (timer) clearTimeout(timer); }+ if (pendingInput !== input || input.revision !== revision || input.ctx?.signal?.aborted) return;+ if (!input.direct && followUp) {+ routeRules = input.inputRules;+ turn = { sequence: ++sequence, safe: true, valid: true, attempted: false, learned: input.learned };+ }+ pendingInput = undefined;+ })();+ await input.promise;+ }for (const name of ['tool_call', 'tool_execution_start', 'model_select', 'session_switch', 'session_shutdown']) {- pi.on(name, () => { if (turn) { turn.safe = false; turn.valid = false; } });+ pi.on(name, invalidate);}- pi.on('before_provider_request', (event, ctx) => {+ pi.on('before_provider_request', async (event, ctx) => {// Older registries cannot safely restore an extension provider's ownership.// Keep their existing host recovery usable without registering a provider;// modern registries leave all payload handling to the final stream wrapper.if (typeof ctx.modelRegistry?.getProvider === 'function'&& typeof ctx.modelRegistry?.getRegisteredNativeProvider === 'function') return;+ await settleInput();const key = route(ctx.model);// Use the same input snapshot as the modern wrapper, including tool rounds// across expiry. Before any input exists, preserve native preparation calls.@@ -192,39 +241,40 @@ function installCindyCacheRecovery(pi) {refreshRules,accepts: model => Boolean(route(model)),wrap(model, options, invoke, provider = model.provider) {- const key = route(model);- if (!key || !turn) return invoke(options);- const owner = turn;- const startedAt = Date.now();- const learned = owner.learned.has(key);- let originalFingerprint;- let originalIdentity;- let hasCache = false;- let skipped = false;- const sameInput = () => turn === owner && owner.valid && owner.safe && !options?.signal?.aborted;- const requestOptions = (trial) => ({ ...options,- onPayload: async (payload, requestModel) => {- const replacement = await options?.onPayload?.(payload, requestModel);- const finalPayload = replacement === undefined ? payload : replacement;- if (!finalPayload || typeof finalPayload !== 'object' || Array.isArray(finalPayload)) return finalPayload;- if (trial) {- if (!sameInput() || fingerprint(finalPayload) !== originalFingerprint- || requestIdentity(requestModel, options) !== originalIdentity) {- skipped = true;- throw new Error('CINDY_CACHE_RETRY_CONTEXT_CHANGED');- }- return withoutCache(finalPayload);- }- hasCache = fields.some(field => Object.hasOwn(finalPayload, field));- if (hasCache && sameInput() && !owner.attempted && requestModel?.id === model.id- && requestModel?.api === model.api && requestModel?.baseUrl === model.baseUrl) {- originalFingerprint = fingerprint(finalPayload);- originalIdentity = requestIdentity(requestModel, options);- }- return learned || owner.trialKey === key ? withoutCache(finalPayload) : finalPayload;- },- });return (async function* () {+ await settleInput();+ const key = route(model);+ if (!key || !turn) { yield* invoke(options); return; }+ const owner = turn;+ const startedAt = Date.now();+ const learned = owner.learned.has(key);+ let originalFingerprint;+ let originalIdentity;+ let hasCache = false;+ let skipped = false;+ const sameInput = () => turn === owner && owner.valid && owner.safe && !options?.signal?.aborted;+ const requestOptions = (trial) => ({ ...options,+ onPayload: async (payload, requestModel) => {+ const replacement = await options?.onPayload?.(payload, requestModel);+ const finalPayload = replacement === undefined ? payload : replacement;+ if (!finalPayload || typeof finalPayload !== 'object' || Array.isArray(finalPayload)) return finalPayload;+ if (trial) {+ if (!sameInput() || fingerprint(finalPayload) !== originalFingerprint+ || requestIdentity(requestModel, options) !== originalIdentity) {+ skipped = true;+ throw new Error('CINDY_CACHE_RETRY_CONTEXT_CHANGED');+ }+ return withoutCache(finalPayload);+ }+ hasCache = fields.some(field => Object.hasOwn(finalPayload, field));+ if (hasCache && sameInput() && !owner.attempted && requestModel?.id === model.id+ && requestModel?.api === model.api && requestModel?.baseUrl === model.baseUrl) {+ originalFingerprint = fingerprint(finalPayload);+ originalIdentity = requestIdentity(requestModel, options);+ }+ return learned || owner.trialKey === key ? withoutCache(finalPayload) : finalPayload;+ },+ });for await (const event of invoke(requestOptions(false))) {if (event.type !== 'error') {// A successful response start rules out retrying an in-stream failure.diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.tsindex 6ab362ef63..00b9874c83 100644--- a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts@@ -22,12 +22,15 @@* `verifyPiSubagentRunnerIdentity` in `pi-subagent-runs.ts`.*/+import { createPiCacheInputTracker } from './cache-input.js';+export const CINDY_SUBAGENT_RUNNER_FILENAME = 'cindy-subagent-runner.cjs';export const CINDY_SUBAGENT_RUNNER_SOURCE = String.raw`'use strict';const { spawn, spawnSync } = require('node:child_process');-const { createHmac, randomUUID } = require('node:crypto');+const { createHash, createHmac, randomUUID } = require('node:crypto');+const createPiCacheInputTracker = ${createPiCacheInputTracker.toString()};const fs = require('node:fs');const path = require('node:path');@@ -869,6 +872,7 @@ function main() {let settled = false;let agentSettled = false;let terminalError = '';+ const cacheInputTracker = createPiCacheInputTracker(text => createHash('sha256').update(text).digest('hex'));function settle(code, signal, spawnError) {if (settled) return;@@ -912,6 +916,14 @@ function main() {safeAppendTranscript(state, { type: 'cindy.subagent.stdout', at: Date.now(), childId: task.childId, line: line });return;}+ cacheInputTracker.observe(event);+ if (event.type === 'extension_ui_request' && event.method === 'input' && event.title === 'cindy:cache-input') {+ let request = {};+ try { request = JSON.parse(typeof event.placeholder === 'string' ? event.placeholder : '{}'); } catch (_) {}+ const receipt = !task.stopRequested && !state.stopRequested ? cacheInputTracker.read(request && request.key) : undefined;+ send(task, { type: 'extension_ui_response', id: event.id, value: JSON.stringify(receipt || {}) });+ return;+ }safeAppendTranscript(state, { type: 'cindy.subagent.child_event', at: Date.now(), childId: task.childId, event: event });if (event.type === 'extension_ui_request') {const pending = {diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex daa7a93247..8546df04b7 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -1,4 +1,5 @@import { getPiExtensionUiCapability } from './extension-ui-capabilities.js';+import { createPiCacheInputTracker } from './cache-input.js';import { createHarnessHookBridge } from '../shared/harness-hooks.js';import { parsePiManagementArgs, parsePiManagementText } from './managed-command.js';import { canonicalSkillPath, snapshotDisabledSkillLaunch, currentDisabledSkillLaunchPaths, extendDisabledSkillLaunchPaths, type DisabledSkillLaunchSnapshot } from '../shared/skill-activation.js';@@ -4211,6 +4212,8 @@ export class PiAgent extends BaseAgent {applied: compat?.supportsLongCacheRetention === false };};let inputCacheCompatibility: PiCacheCompatibility | undefined;+ const cacheInputTracker = createPiCacheInputTracker(text => createHash('sha256').update(text).digest('hex'));+ let pendingCacheCompatibility: { key: string; value: PiCacheCompatibility | undefined } | undefined;ctx.getCacheCompatibility = () => inputCacheCompatibility;let activeEffortSnapshot = initialEffortSnapshot;let mutableEffort: Effort | null = startupEffort ?? null;@@ -5749,11 +5752,18 @@ export class PiAgent extends BaseAgent {transport,logger: this.deps.logger,onEvent: (event: PiRpcEvent) => {- if (event.type === 'agent_start'- || event.type === 'message_start' && (event.message as { role?: string } | undefined)?.role === 'user') {- // Native Execute/Refine starts an agent; queued follow-ups only- // start a user message. Freeze until the next input, not tool round.- inputCacheCompatibility = readCacheCompatibility();+ const cacheInput = cacheInputTracker.observe(event);+ if (cacheInput) pendingCacheCompatibility = { key: cacheInput.key, value: readCacheCompatibility() };+ if (event.type === 'extension_ui_request' && event.method === 'input' && event.title === 'cindy:cache-input') {+ let request: { key?: unknown; direct?: unknown } = {};+ try { request = JSON.parse(typeof event.placeholder === 'string' ? event.placeholder : '{}'); } catch {}+ const receipt = !closed && !proc.isClosed ? cacheInputTracker.read(request?.key) : undefined;+ if (receipt && pendingCacheCompatibility?.key === receipt.key && (request.direct === true || receipt.followUp)) {+ inputCacheCompatibility = pendingCacheCompatibility.value;+ pendingCacheCompatibility = undefined;+ }+ proc.send({ type: 'extension_ui_response', id: event.id, value: JSON.stringify(receipt ?? {}) });+ return;}if (event.type === 'agent_start' && !ctx.pendingHostTurnStartToken) {syncNativePlanMode?.();