Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): retain older registry recovery across cache expiry
xuzini-xzn008a2a515fe4
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-native-compat-overrides-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-native-compat-overrides-store.test.tsindex d389d2560a..cd06fda68a 100644--- a/apps/desktop/src/main/maker-host/__tests__/pi-native-compat-overrides-store.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/pi-native-compat-overrides-store.test.ts@@ -13,6 +13,19 @@ const fix = { supportsLongCacheRetention: false };afterAll(() => fs.rmSync(root.path, { recursive: true, force: true }));beforeEach(() => { fs.rmSync(file, { force: true }); });describe('learned cache compatibility', () => {+ it('expires untimed legacy learning from stable file time and preserves its deadline across writes', async () => {+ const writtenAt = Date.now() - 86400000;+ const key = JSON.stringify(['a', 'model', a]);+ fs.writeFileSync(file, JSON.stringify({ routes: { [key]: fix } }));+ fs.utimesSync(file, writtenAt / 1000, writtenAt / 1000);+ const learnedAt = fs.statSync(file).mtimeMs;+ expect(read('a', 'model', a)).toEqual(fix);+ await record('b', 'other', fix, b);+ const migrated = JSON.parse(fs.readFileSync(file, 'utf8')).routes[key];+ expect(migrated).toMatchObject({ evidence: 'explicit', learnedAt, expiresAt: learnedAt + 7 * 86400000 });+ const clock = vi.spyOn(Date, 'now').mockReturnValue(learnedAt + 7 * 86400000 + 1);+ try { expect(read('a', 'model', a)).toBeUndefined(); } finally { clock.mockRestore(); }+ });it('persists only the permitted fix and isolates connection, wire model and route', async () => {expect(await record('a', 'model', { ...fix, supportsStore: true }, a)).toBe(true);expect(read('a', 'model', a)).toEqual(fix);diff --git a/apps/desktop/src/main/maker-host/pi-native-compat-overrides-store.ts b/apps/desktop/src/main/maker-host/pi-native-compat-overrides-store.tsindex 648047b305..ae7fce30ec 100644--- a/apps/desktop/src/main/maker-host/pi-native-compat-overrides-store.ts+++ b/apps/desktop/src/main/maker-host/pi-native-compat-overrides-store.ts@@ -3,6 +3,7 @@* Unreadable files are preserved; a failed write never authorizes replay.*/import { app } from 'electron';+import { statSync } from 'node:fs';import path from 'node:path';import { desktopMakerLogger } from './logger-adapter.js';import { createOverrideSettingsFile } from './override-settings-file.js';@@ -11,6 +12,7 @@ type CacheOverride = { supportsLongCacheRetention: false; learnedAt?: number; exinterface PiNativeCompatOverrides { routes: Record<string, CacheOverride> }const log = desktopMakerLogger.child('pi-native-compat-overrides-store');const DEFAULTS: PiNativeCompatOverrides = { routes: {} };+const filePath = () => path.join(app.getPath('userData'), 'pi-native-compat-overrides.json');function identity(providerId: string, modelId: string, routeKey?: string): string | undefined {if (!routeKey || !/^[a-f0-9]{64}$/.test(routeKey)) return undefined;if (![providerId, modelId].every((v) => typeof v === 'string' && v.length > 0 && v.length <= 512 && !/[\u0000-\u001f\u007f]/.test(v))) return undefined;@@ -33,15 +35,23 @@ function normalize(raw: unknown): PiNativeCompatOverrides {&& record.expiresAt! <= record.learnedAt! + (record.evidence === 'opaque' ? 1 : 7) * 86400000&& (record.evidence === 'explicit' || record.evidence === 'opaque');if (!timed && (record.learnedAt !== undefined || record.expiresAt !== undefined || record.evidence !== undefined)) continue;- routes[key] = { supportsLongCacheRetention: false,- ...(timed ? { learnedAt: record.learnedAt, expiresAt: record.expiresAt, evidence: record.evidence } : {}) };+ if (timed) {+ routes[key] = { supportsLongCacheRetention: false, learnedAt: record.learnedAt,+ expiresAt: record.expiresAt, evidence: record.evidence };+ } else {+ // Match the native bridge's stable grace for untimed legacy learning.+ // Preserve that deadline when an unrelated route is later written.+ const learnedAt = statSync(filePath()).mtimeMs;+ routes[key] = { supportsLongCacheRetention: false, learnedAt,+ expiresAt: learnedAt + 7 * 86400000, evidence: 'explicit' };+ }}} catch { /* Invalid identities are not executable configuration. */ }}return { routes };}const store = createOverrideSettingsFile<PiNativeCompatOverrides>({- filePath: () => path.join(app.getPath('userData'), 'pi-native-compat-overrides.json'),+ filePath,defaults: DEFAULTS, normalize, log, label: 'pi native compat overrides',maxBytes: 256 * 1024, preserveUnreadableFile: true,logLoadedValue: false, logReadErrorDetails: false,@@ -51,7 +61,7 @@ export function readPiNativeCompatOverride(providerId: string, modelId: string,if (!key) return undefined;store.invalidateIfChanged();const record = store.read().routes[key];- return record && (record.expiresAt === undefined || (record.expiresAt > Date.now() && record.learnedAt! <= Date.now()))+ return record && record.expiresAt! > Date.now() && record.learnedAt! <= Date.now()? { supportsLongCacheRetention: false } : undefined;}export async function recordPiNativeCompatOverride(providerId: string, modelId: string,@@ -59,8 +69,10 @@ export async function recordPiNativeCompatOverride(providerId: string, modelId:const key = identity(providerId, modelId, routeKey);if (!key || compat.supportsLongCacheRetention !== false) return false;try {+ const learnedAt = Date.now();await store.updateAtomic((current) => ({ routes: {- ...current.value.routes, [key]: { supportsLongCacheRetention: false },+ ...current.value.routes, [key]: { supportsLongCacheRetention: false, learnedAt,+ expiresAt: learnedAt + 7 * 86400000, evidence: 'explicit' },} }));return readPiNativeCompatOverride(providerId, modelId, routeKey)?.supportsLongCacheRetention === false;} catch {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 5bbc06c1d7..913672973d 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@@ -17,7 +17,7 @@ const success = { type: 'done', message: { stopReason: 'stop', content: [{ type:function fixture() {let now = 1000000000;const files = new Map<string, string>();- const handlers = new Map<string, (...args: any[]) => void>();+ const handlers = new Map<string, (...args: any[]) => any>();const rules = [{ ...model, providerId: 'connection', routeKey }];files.set('/agent/pi-cache-compatibility.json', JSON.stringify(rules));let writeFails = false;@@ -34,7 +34,8 @@ function fixture() {const api = runInNewContext(PI_CACHE_RECOVERY_SOURCE + '\ninstallCindyCacheRecovery(pi)', {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' } },- ...fs, path, createHash, randomUUID, Buffer, Date: { now: () => now }, homedir: () => '/home/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 interrupt = () => handlers.get('input')!({ source: 'rpc', streamingBehavior: 'steer' }, { isIdle: () => false });@@ -63,6 +64,50 @@ 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 => {+ const h = fixture();+ const selected = { ...model, api };+ const rules = [{ ...selected, providerId: 'connection', routeKey }];+ h.files.set('/agent/pi-cache-compatibility.json', JSON.stringify(rules));+ h.fresh();+ 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.+ h.files.set('/compat.json', JSON.stringify({ routes: { [key]: record } }));+ 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(ctx.modelRegistry.getProvider).not.toHaveBeenCalled();+ expect(payload).toHaveProperty('prompt_cache_key', 'cache');+ // A newly loaded bridge reads the same durable record, not process memory.+ const restarted = fixture();+ restarted.files.set('/agent/pi-cache-compatibility.json', JSON.stringify(rules));+ 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();+ restarted.clock(1086400001);+ expect(recovered({ payload }, ctx)).toBeUndefined();+ expect(restarted.record()).toEqual(record);+ });++ it('preserves normal caching and bounds legacy records in the older registry payload hook', () => {+ const h = fixture();+ const ctx = { model, modelRegistry: {} };+ const hook = () => h.handlers.get('before_provider_request')?.({ payload: body }, ctx);+ h.fresh();+ expect(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 });+ h.clock(1000 + 7 * 86400000 + 1); h.fresh();+ expect(hook()).toBeUndefined();+ });+it('does one final-payload comparison, learns only after generation, and preserves usage', async () => {const h = fixture(); h.fresh();const hook = vi.fn((payload: any) => ({ ...payload, third_party: 'preserved', service_tier: 'priority' }));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 50aebf4f7c..54c3390e71 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,6 +1387,37 @@ 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) => {+ let active = true;+ const deps = byomDeps(async () => ({ providers: [{+ id: 'native-a', name: 'Native A', baseUrl: 'https://cache.example/v1', api: 'openai-completions',+ models: [{ id: 'local-model' }],+ }], env: {} }));+ deps.resolvePiNativeCompatOverride = () => active ? { supportsLongCacheRetention: false } : undefined;+ const handle = await new PiAgent(deps).startSession({+ sessionId: 'cache-expiry-receipt', workingDir: cwd, model: 'local-model', providerId: 'native-a',+ });+ const events = handle.events()[Symbol.asyncIterator]();+ 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' });+ // 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: 'auto_retry_end', success: false,+ finalError: '400: unsupported parameter: prompt_cache_retention' });+ let event;+ do { event = await events.next(); } while (!event.done && event.value.type !== 'error');+ expect(event.value?.data).toMatchObject({ piCacheCompatibility: { applied: expected,+ providerId: 'native-a', wireModelId: 'local-model',+ routeKey: piCacheRouteKey('https://cache.example/v1', 'openai-completions') } });+ captured.onEvent!({ type: 'agent_end', messages: [] });+ }+ } finally { await handle.close(); }+ });+it("routes a persisted BYOM id through its namespaced PI runtime provider", async () => {const authProviderIds: Array<string | null | undefined> = [];const deps: AgentDeps = {diff --git a/packages/maker-core/src/agents/pi/cache-recovery-source.ts b/packages/maker-core/src/agents/pi/cache-recovery-source.tsindex 80af250255..9a19ab472c 100644--- a/packages/maker-core/src/agents/pi/cache-recovery-source.ts+++ b/packages/maker-core/src/agents/pi/cache-recovery-source.ts@@ -167,6 +167,19 @@ function installCindyCacheRecovery(pi) {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('before_provider_request', (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;+ 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;+ const payload = event.payload;+ if (payload && typeof payload === 'object' && !Array.isArray(payload)) return withoutCache(payload);+ });return {refreshRules,accepts: model => Boolean(route(model)),diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex eb6bd628bf..bdda4b9400 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -4202,10 +4202,16 @@ export class PiAgent extends BaseAgent {// null/订阅来源会归一到 cindy,setModel 未显式传来源时也必须跟随本次解析结果。let mutablePiProviderId = initialProvider;let mutableProviderId: string | null | undefined = opts.providerId ?? authProviderId;- ctx.getCacheCompatibility = () => {+ const readCacheCompatibility = () => {const route = appliedCacheRoutes.get(JSON.stringify([mutablePiProviderId, mutableWireModel]));- return route ? { ...route, modelId: mutableModel ?? route.modelId } : undefined;+ if (!route) return undefined;+ const compat = remote ? undefined : this.deps.resolvePiNativeCompatOverride?.(+ route.providerId, route.wireModelId, route.routeKey);+ return { ...route, modelId: mutableModel ?? route.modelId,+ applied: compat?.supportsLongCacheRetention === false };};+ let inputCacheCompatibility: PiCacheCompatibility | undefined;+ ctx.getCacheCompatibility = () => inputCacheCompatibility;let activeEffortSnapshot = initialEffortSnapshot;let mutableEffort: Effort | null = startupEffort ?? null;// 用户明确关掉思考(setThinkingEnabled(false) / 切模显式 thinkingEnabled:false /@@ -5743,6 +5749,11 @@ 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.+ inputCacheCompatibility = readCacheCompatibility();+ }if (event.type === 'agent_start' && !ctx.pendingHostTurnStartToken) {syncNativePlanMode?.();}@@ -7676,7 +7687,7 @@ export class PiAgent extends BaseAgent {if (sendOpts) handle.validateSendOptions?.(sendOpts);const expectedCompat = sendOpts?.[PI_CACHE_RECOVERY_EXPECTATION];if (expectedCompat) {- const applied = ctx.getCacheCompatibility?.();+ const applied = readCacheCompatibility();if (!sendOpts?.retryTranscriptUserEntryId || !applied?.applied || applied.routeKey !== expectedCompat.routeKey|| applied.providerId !== expectedCompat.providerId || applied.wireModelId !== expectedCompat.wireModelId) {throw new TurnDispatchRejectedError('Pi cache compatibility was not applied to the expected route');