Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): reject unrelated field errors and align resumed route rules
xuzini-xzn0dde74713d0a
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 21f4ffa649..de7f3ef60c 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@@ -106,6 +106,34 @@ describe('Pi native cache recovery', () => {expect(h.sent).toHaveLength(1); expect(h.record()).toBeUndefined();});+ it.each([+ 'Validation: Unsupported parameter(s): temperature',+ 'Unknown field: future_vendor_option',+ "Unsupported parameter(s): ['temperature']",+ "Unsupported parameter(s): ['prompt_cache_key', 'temperature']",+ "The parameter 'temperature' is not supported",+ '未知请求字段:temperature',+ '参数 temperature 不支持',+ 'Unsupported parameter: prompt_cache_key; unsupported parameter: temperature',+ ])('does not trial an explicitly rejected other field without structured param: %s', async message => {+ const h = fixture(); h.fresh();+ await h.request([failure('400: ' + JSON.stringify({ error: { type: 'invalid_request_error', param: null, message } })), success]);+ expect(h.sent).toHaveLength(1);+ expect(h.record()).toBeUndefined();+ });++ it.each(['Validation: Unsupported parameter(s): prompt_cache_key',+ 'Unsupported parameter: prompt_cache_retention.',+ "The parameter 'prompt_cache_key' is not supported",+ '未知请求字段:prompt_cache_retention',+ "Unsupported parameter(s): ['prompt_cache_key', 'prompt_cache_retention']",+ ])('still learns explicit cache rejection: %s', async message => {+ const h = fixture(); h.fresh();+ await h.request([failure('400: ' + JSON.stringify({ error: { param: null, message } })), success]);+ expect(h.sent).toHaveLength(2);+ expect(h.record()).toMatchObject({ evidence: 'explicit', expiresAt: 1604800000 });+ });+it.each(['start', 'thinking_delta', 'toolcall_start'])('never retries after %s or a prior tool', async type => {const h = fixture(); h.fresh(); await h.request([[{ type }, failure()]]);expect(h.sent).toHaveLength(1); expect(h.record()).toBeUndefined();diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.tsindex b9c2267050..998f6bb219 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts@@ -925,18 +925,39 @@ describe('Cindy durable PI Subagent runner', () => {const rules = JSON.stringify([{ provider: 'fixture', id: 'wire', routeKey: 'a'.repeat(64) }]);await writeFile(sourceFile, rules);const launchRunner = vi.fn(async () => {});- const id = await resumePiSubagentRun(fixture.root, first.runId, 'continue', { ...resumeLaunch(fixture), launchRunner });+ const id = await resumePiSubagentRun(fixture.root, first.runId, 'continue', { ...resumeLaunch(fixture), runtimeSnapshot: undefined, launchRunner });if (!id) throw new Error('Expected a resumed generation');expect(await readFile(path.join(fixture.root, id, 'pi-home', 'pi-cache-compatibility.json'), 'utf8')).toBe(rules);expect(launchRunner).toHaveBeenCalledOnce();// This unlaunched queued generation would otherwise block the second attempt.await rm(path.join(fixture.root, id), { recursive: true, force: true });await writeFile(sourceFile, 'x'.repeat(256 * 1024 + 1));- await expect(resumePiSubagentRun(fixture.root, first.runId, 'continue', { ...resumeLaunch(fixture), launchRunner }))+ await expect(resumePiSubagentRun(fixture.root, first.runId, 'continue', { ...resumeLaunch(fixture), runtimeSnapshot: undefined, launchRunner })).rejects.toThrow('cache rules escaped');expect(launchRunner).toHaveBeenCalledOnce();});+ it.each([true, false])('keeps resumed cache rules in the current model generation (rules present: %s)', async hasRules => {+ const { fixture, first } = await resumableFixture();+ const rules = (endpoint: string, digest: string) => JSON.stringify([{+ provider: 'fixture', id: 'wire', api: 'openai-completions', providerId: 'connection',+ baseUrl: endpoint, routeKey: digest.repeat(64),+ }]);+ await writeFile(path.join(fixture.root, first.runId, 'pi-home', 'pi-cache-compatibility.json'), rules('https://old.invalid/v1', 'a'));+ const currentRules = Buffer.from(rules('https://current.invalid/v1', 'b'));+ const launch = resumeLaunch(fixture);+ const currentModels = Buffer.from('{"providers":{"fixture":{"baseUrl":"https://current.invalid/v1"}}}');+ const runtimeSnapshot = { ...launch.runtimeSnapshot, modelsJson: currentModels, cacheRulesJson: hasRules ? currentRules : undefined };+ const id = await resumePiSubagentRun(fixture.root, first.runId, 'continue', {+ ...launch, runtimeSnapshot, launchRunner: vi.fn(async () => {}),+ });+ if (!id) throw new Error('Expected a resumed generation');+ await expect(readFile(path.join(fixture.root, id, 'pi-home', 'models.json'))).resolves.toEqual(currentModels);+ const savedRules = readFile(path.join(fixture.root, id, 'pi-home', 'pi-cache-compatibility.json'));+ if (hasRules) await expect(savedRules).resolves.toEqual(currentRules);+ else await expect(savedRules).rejects.toMatchObject({ code: 'ENOENT' });+ });+it('refuses when a live instance already holds the claim', async () => {const { fixture, first } = await resumableFixture();// process.ppid is certainly alive and is not us.diff --git a/packages/maker-core/src/agents/pi/cache-recovery-source.ts b/packages/maker-core/src/agents/pi/cache-recovery-source.tsindex 2eed2547c6..d060014d72 100644--- a/packages/maker-core/src/agents/pi/cache-recovery-source.ts+++ b/packages/maker-core/src/agents/pi/cache-recovery-source.ts@@ -116,6 +116,20 @@ function installCindyCacheRecovery(pi) {data = data.error;}if (/api.?key|unauthori[sz]ed|authentication|permission denied|quota|rate.?limit|model.{0,30}(?:not found|does not exist)|context.{0,25}(?:length|limit)|content.?filter|content.?policy|invalid.{0,15}value|鉴权|认证失败|额度|限流|模型不存在|上下文.{0,8}(?:超|长)|内容审核|参数值/i.test(body)) return;+ // A named rejection is evidence even when a gateway omits structured param.+ // Parse the field relationship, never a list of vendor or parameter names.+ for (const pattern of [+ /(?:unsupported|unknown|unrecognized|unexpected)\s+(?:parameters?|fields?|arguments?|properties|property|options?)(?:\(s\))?[\s:=]*(\[[^\]]+\]|['"\x60]?[a-z_][\w.-]*)/gi,+ /(?:parameter|field|argument|property|option)\s*[:=]?\s*['"\x60]?([a-z_][\w.-]*)['"\x60]?\s+(?:is\s+)?(?:unsupported|unknown|unrecognized|unexpected|not\s+(?:supported|allowed|permitted))/gi,+ /(?:未知|不支持|不接受|无法识别)(?:的)?(?:请求)?(?:参数|字段|属性|选项)[\s::=]*(\[[^\]]+\]|['"\x60]?[a-z_][\w.-]*)/gi,+ /(?:参数|字段|属性|选项)\s*[::=]?\s*['"\x60]?([a-z_][\w.-]*)['"\x60]?\s*(?:不支持|不被支持|未知|无法识别)/gi,+ ]) {+ for (const match of body.matchAll(pattern)) {+ for (const field of match[1].matchAll(/[a-z_][\w.-]*/gi)) {+ if (!fields.includes(field[0].replace(/\.+$/, '').toLowerCase())) return;+ }+ }+ }return /(?: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) => {diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 9ff1675547..c2a6478865 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -5505,10 +5505,11 @@ export class PiAgent extends BaseAgent {const operation = (async () => {await permissionWriteChain;if (closed) throw new Error('PI session is closed');- const [modelsJson, bridgeSource, runnerSource] = await Promise.all([+ const [modelsJson, bridgeSource, runnerSource, cacheRulesJson] = await Promise.all([fs.readFile(path.join(configHome, 'models.json')),fs.readFile(bridgeExtensionPath),fs.readFile(subagentRunnerPath),+ fs.readFile(path.join(configHome, 'pi-cache-compatibility.json')),]);const runId = await resumePiSubagentRun(subagentRunRoot, taskId, message, {launchRunner: (request) => this.launchSubagentRunner(request),@@ -5522,7 +5523,7 @@ export class PiAgent extends BaseAgent {...reviewPathSnapshot,},runnerFallbackFile: subagentRunnerPath,- runtimeSnapshot: { modelsJson, bridgeSource, runnerSource },+ runtimeSnapshot: { modelsJson, bridgeSource, runnerSource, cacheRulesJson },}, childId);if (!runId) throw new Error('No terminal PI Subagent run is available to resume.');await requestPiSubagentRefresh();diff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.tsindex b9bf20dc5f..892eed6e39 100644--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts@@ -2292,6 +2292,7 @@ interface PiSubagentResumeLaunch {modelsJson: Buffer;bridgeSource: Buffer;runnerSource: Buffer;+ cacheRulesJson?: Buffer;};}@@ -2724,18 +2725,25 @@ async function resumeClaimedPiSubagentRun(fs.readFile(selectedRunnerFile),]);JSON.parse(modelsJson.toString('utf8'));- // Optional for older durable snapshots; apply the same artifact boundary as models.json.- let cacheRules: Buffer | undefined;- try {- const sourceCacheRules = path.join(sourceConfigHome, 'pi-cache-compatibility.json');- const [info, canonical] = await Promise.all([fs.lstat(sourceCacheRules), fs.realpath(sourceCacheRules)]);- if (info.isSymbolicLink() || !info.isFile() || info.size > 256 * 1024- || path.dirname(canonical) !== canonicalConfigHome) {- throw new Error('PI Subagent resume cache rules escaped their source run');+ // Rules and models must come from the same generation. An older caller's+ // current snapshot without rules must not inherit a historical route digest.+ let cacheRules = launch.runtimeSnapshot?.cacheRulesJson;+ if (cacheRules && cacheRules.byteLength > 256 * 1024) {+ throw new Error('PI Subagent resume cache rules escaped their source run');+ }+ if (!launch.runtimeSnapshot) {+ try {+ const sourceCacheRules = path.join(sourceConfigHome, 'pi-cache-compatibility.json');+ const [info, canonical] = await Promise.all([fs.lstat(sourceCacheRules), fs.realpath(sourceCacheRules)]);+ if (info.isSymbolicLink() || !info.isFile() || info.size > 256 * 1024+ || path.dirname(canonical) !== canonicalConfigHome) {+ throw new Error('PI Subagent resume cache rules escaped their source run');+ }+ cacheRules = await fs.readFile(sourceCacheRules);+ } catch (error) {+ // Optional for older durable snapshots; preserve their missing-file compatibility.+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;}- cacheRules = await fs.readFile(sourceCacheRules);- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;}const runId = randomUUID();const runDir = path.join(root, runId);