Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): bind cache recovery to actual user inputs
xuzini-xznc04ff38f5a24
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 ab33519d53..be184c2ee7 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@@ -31,16 +31,25 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTT{ api, mode: 'explicit', rejection: { message: '未知请求字段:prompt_cache_retention', type: 'invalid_request_error' } },{ api, mode: 'always-fails', rejection: { message: 'Validation: Unsupported parameter(s): prompt_cache_key', type: 'invalid_request_error' } },{ api, mode: 'supported', rejection: {} },+ // #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' } } },]))('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>> = [];let rejectCache = mode !== 'supported';let persistentFailure = mode === 'always-fails';+ let firstArrived!: () => void;+ const firstRequest = new Promise<void>(resolve => { firstArrived = resolve; });+ let releaseFirst!: () => void;+ const firstReleased = new Promise<void>(resolve => { releaseFirst = resolve; });const gateway = createServer(async (req, res) => {expect(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);- if (persistentFailure || rejectCache && ('prompt_cache_key' in data || 'prompt_cache_retention' in data)) {+ const held = mode === 'queued' && received.length === 1;+ if (held) { firstArrived(); await firstReleased; }+ if (!held && (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' });@@ -67,24 +76,32 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTTconst run = async () => {const 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' }); await finish; return events;+ await handle!.send({ type: 'user', content: 'Reply OK' });+ if (mode === 'queued' && received.length <= 1) {+ await firstRequest;+ await handle!.send({ type: 'user', content: 'Reply OK to the queued message' });+ releaseFirst();+ }+ await finish; return events;};const agent = new PiAgent(deps);handle = await agent.startSession({ ...opts, sessionId: 'first' });const first = await run();- expect(received).toHaveLength(mode === 'supported' ? 1 : 2);+ expect(received).toHaveLength(mode === 'supported' ? 1 : mode === 'queued' ? 3 : 2);expect(received[0]).toHaveProperty('prompt_cache_key');expect(received[0]).toHaveProperty('prompt_cache_retention', '24h');if (mode !== 'supported') {- const { prompt_cache_key: _key, prompt_cache_retention: _retention, ...without } = received[0];- expect(received[1]).toEqual(without);+ const original = mode === 'queued' ? 1 : 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);}expect(first.filter(e => e.type === 'done')).toHaveLength(1);const 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(1);- expect(entries.filter(entry => entry.type === 'message' && entry.message?.role === 'assistant')).toHaveLength(1);+ 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') {expect(first.filter(e => e.type === 'error')).toHaveLength(1);expect(first.find(e => e.type === 'error')?.data).toMatchObject({ piCacheRecoveryHandled: true });@@ -102,6 +119,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;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.@@ -112,6 +130,7 @@ describe.skipIf(!existsSync(binary))('Pi cache recovery over real native RPC/HTThandle = await agent.startSession({ ...opts, sessionId: 'other-route' });await run(); expect(received[4]).toHaveProperty('prompt_cache_retention', '24h');} finally {+ releaseFirst();await handle?.close(); gateway.closeAllConnections();await new Promise<void>(resolve => gateway.close(() => resolve()));rmSync(root, { recursive: true, force: true });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 913672973d..29f3e51933 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@@ -37,7 +37,8 @@ function fixture() {// 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',});- const fresh = () => handlers.get('input')!({ source: 'rpc' }, { isIdle: () => true });+ const startUser = () => handlers.get('message_start')?.({ message: { role: 'user', content: [{ type: 'text', text: 'OK' }] } });+ const fresh = () => { handlers.get('input')!({ source: 'rpc' }, { isIdle: () => true }); startUser(); };const interrupt = () => handlers.get('input')!({ source: 'rpc', streamingBehavior: 'steer' }, { isIdle: () => false });const sent: any[] = [];let invocation = 0;@@ -59,7 +60,7 @@ function fixture() {for await (const event of api.wrap(selectedModel, options, invoke)) output.push(event);return output;};- return { api, handlers, fresh, interrupt, request, files, sent, clock: (value: number) => { now = value; },+ return { api, handlers, fresh, startUser, interrupt, request, files, sent, clock: (value: number) => { now = value; },failWrites: () => { writeFails = true; }, record: () => JSON.parse(files.get('/compat.json') ?? '{"routes":{}}').routes[key] };}@@ -73,8 +74,9 @@ describe('Pi native cache recovery', () => {const record = { supportsLongCacheRetention: false, learnedAt: 1000000000,expiresAt: 1086400000, evidence: 'opaque' };// Another session can learn after the last RPC input. Native continuation- // has no new RPC input event, but must still consume the durable record.+ // has no new RPC input event, but its real user message starts a new input.h.files.set('/compat.json', JSON.stringify({ routes: { [key]: record } }));+ h.startUser();const ctx = { model: selected, modelRegistry: { getProvider: vi.fn() } };const hook = h.handlers.get('before_provider_request')!;const payload = { ...body, service_tier: 'priority' };@@ -91,6 +93,10 @@ describe('Pi native cache recovery', () => {expect(recovered({ payload }, { ...ctx, model: { ...selected, baseUrl: selected.baseUrl + '/other' } })).toBeUndefined();expect(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');+ restarted.startUser();expect(recovered({ payload }, ctx)).toBeUndefined();expect(restarted.record()).toEqual(record);});@@ -135,6 +141,46 @@ describe('Pi native cache recovery', () => {expect(h.sent[3]).toHaveProperty('prompt_cache_key');});+ // PR #7561 P1: input queuing is not execution; Pi emits user message_start+ // (without agent_start) when followUp actually begins. Unit production wrapper.+ it('arms one budget only when a queued user input actually starts', async () => {+ const h = fixture(); h.fresh();+ await h.request([failure()], {}, () => {+ h.handlers.get('input')!({ source: 'rpc', streamingBehavior: 'followUp' }, { isIdle: () => false });+ });+ expect(h.sent).toHaveLength(1); expect(h.record()).toBeUndefined();+ h.startUser();+ await h.request([failure()]);+ expect(h.sent).toHaveLength(3);+ expect(h.sent[1]).toHaveProperty('prompt_cache_key');+ expect(h.sent[2]).not.toHaveProperty('prompt_cache_key');+ for (const role of ['assistant', 'toolResult', 'system']) h.handlers.get('message_start')?.({ message: { role } });+ h.handlers.get('turn_start')?.({});+ await h.request([failure()]);+ expect(h.sent).toHaveLength(4);+ expect(h.sent[3]).not.toHaveProperty('prompt_cache_key');+ expect(h.record()).toBeUndefined();+ h.startUser(); await h.request([failure(), failure(), failure(), failure(), failure(), success]);+ expect(h.sent).toHaveLength(6);+ expect(h.record()).toMatchObject({ evidence: 'opaque' });+ });++ // 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 () => {+ const h = fixture();+ h.files.set('/compat.json', JSON.stringify({ routes: { [key]: { supportsLongCacheRetention: false,+ learnedAt: 1000000000, expiresAt: 1086400000, evidence: 'opaque' } } }));+ h.fresh(); h.clock(1086400001);+ await h.request([success]);+ h.handlers.get('tool_execution_start')!();+ await h.request([success]);+ expect(h.sent).toHaveLength(2);+ for (const payload of h.sent) expect(payload).toEqual({ model: 'wire', messages: body.messages });+ h.startUser(); await h.request([success]);+ expect(h.sent[2]).toEqual(body);+ });+it('treats an unfamiliar gateway error type as opaque without a vendor allowlist', async () => {const h = fixture(); h.fresh();await h.request([failure('400: {"error":{"type":"new_gateway_validation_shape","message":"请求不满足要求"}}'), success]);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 54c3390e71..70ab1437c7 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@@ -1387,7 +1387,7 @@ describe("Pi provider-aware model routing", () => {await handle.close();});- it.each([false, true])('freezes per-input cache learning across expiry and relearning, native continuation: %s', async (native) => {+ it.each(['send', 'native', 'queued'])('freezes per-input cache learning across expiry and relearning: %s', async (mode) => {let active = true;const deps = byomDeps(async () => ({ providers: [{id: 'native-a', name: 'Native A', baseUrl: 'https://cache.example/v1', api: 'openai-completions',@@ -1401,11 +1401,13 @@ describe("Pi provider-aware model routing", () => {try {for (const expected of [true, false, true]) {active = expected;- if (!native) await handle.send({ type: 'user', content: 'try cache' });- captured.onEvent!({ type: 'agent_start' });+ 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' }] } });// Expiry or another session's learning during the request must not// change whether this input actually started with the override.active = !expected;+ captured.onEvent!({ type: 'message_start', message: { role: 'toolResult', content: [] } });captured.onEvent!({ type: 'auto_retry_end', success: false,finalError: '400: unsupported parameter: prompt_cache_retention' });let event;diff --git a/packages/maker-core/src/agents/pi/cache-recovery-source.ts b/packages/maker-core/src/agents/pi/cache-recovery-source.tsindex 9a19ab472c..979c711eab 100644--- a/packages/maker-core/src/agents/pi/cache-recovery-source.ts+++ b/packages/maker-core/src/agents/pi/cache-recovery-source.ts@@ -154,15 +154,23 @@ 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';}- pi.on('input', (event, ctx) => {- if (ctx.isIdle() && !event.streamingBehavior && event.source === 'rpc') {- refreshRules();- 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;- }- turn = { sequence: ++sequence, safe: true, valid: true, attempted: false, records };- } else 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; }+ });+ pi.on('message_start', (event) => {+ 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();+ 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 };});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; } });@@ -174,9 +182,9 @@ function installCindyCacheRecovery(pi) {if (typeof ctx.modelRegistry?.getProvider === 'function'&& typeof ctx.modelRegistry?.getRegisteredNativeProvider === 'function') return;const key = route(ctx.model);- // Native continuation need not emit a new RPC input. Read current learning- // here as well, rather than reuse the previous RPC input's snapshot.- if (!key || !active(load()?.routes[key], Date.now())) return;+ // Use the same input snapshot as the modern wrapper, including tool rounds+ // across expiry. Before any input exists, preserve native preparation calls.+ if (!key || !(turn ? turn.learned.has(key) : active(load()?.routes[key], Date.now()))) return;const payload = event.payload;if (payload && typeof payload === 'object' && !Array.isArray(payload)) return withoutCache(payload);});@@ -188,7 +196,7 @@ function installCindyCacheRecovery(pi) {if (!key || !turn) return invoke(options);const owner = turn;const startedAt = Date.now();- const learned = active(owner.records[key], startedAt);+ const learned = owner.learned.has(key);let originalFingerprint;let originalIdentity;let hasCache = false;@@ -239,7 +247,7 @@ function installCindyCacheRecovery(pi) {if (retried.type === 'done' && turn === owner && owner.valid && !options?.signal?.aborted&& ['stop', 'toolUse'].includes(retried.message?.stopReason)) {const record = remember(key, evidence, startedAt);- if (record) owner.records[key] = record;+ if (record) owner.learned.add(key);}if (retried.type !== 'error') owner.safe = false;yield retried.type === 'error'diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex bdda4b9400..daa7a93247 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -5749,9 +5749,10 @@ export class PiAgent extends BaseAgent {transport,logger: this.deps.logger,onEvent: (event: PiRpcEvent) => {- if (event.type === 'agent_start') {- // Includes native Execute/Refine and queued follow-ups. Freeze the- // active record for this input, even if it expires during the call.+ 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();}if (event.type === 'agent_start' && !ctx.pendingHostTurnStartToken) {