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): parse rejected field lists and serialize resume snapshots

xuzini-xzn313ab9802fd7
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.ts
index de7f3ef60c..5bbc06c1d7 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
@@ -111,6 +111,9 @@ describe('Pi native cache recovery', () => {
'Unknown field: future_vendor_option',
"Unsupported parameter(s): ['temperature']",
"Unsupported parameter(s): ['prompt_cache_key', 'temperature']",
+ 'Unsupported parameters: prompt_cache_key, temperature',
+ "Unsupported parameter(s): 'prompt_cache_key', 'future_vendor_option'",
+ '未知请求字段:prompt_cache_key,temperature',
"The parameter 'temperature' is not supported",
'未知请求字段:temperature',
'参数 temperature 不支持',
@@ -127,6 +130,11 @@ describe('Pi native cache recovery', () => {
"The parameter 'prompt_cache_key' is not supported",
'未知请求字段:prompt_cache_retention',
"Unsupported parameter(s): ['prompt_cache_key', 'prompt_cache_retention']",
+ 'Unsupported parameters: prompt_cache_key, prompt_cache_retention',
+ "Unsupported parameter(s): 'prompt_cache_key', 'prompt_cache_retention'",
+ 'Unsupported parameter: prompt_cache_key, use prompt_cache_options instead',
+ 'Unsupported parameter: prompt_cache_key, please use a supported option',
+ '未知请求字段:prompt_cache_key,请改用 prompt_cache_options',
])('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]);
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.ts
index b53111e7f2..50aebf4f7c 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
@@ -1,6 +1,7 @@
import ts from "typescript";
import { createHash } from "node:crypto";
import {
+ promises as fs,
mkdirSync,
existsSync,
mkdtempSync,
@@ -19,6 +20,7 @@ vi.setConfig({ testTimeout: 30_000 });
import { CINDY_BRIDGE_EXTENSION_SOURCE } from "../cindy-bridge-source.js";
import { CINDY_SUBAGENT_EXTENSION_SOURCE } from "../cindy-subagent-source.js";
import { piCacheRouteKey } from '../cache-compatibility.js';
+import * as piSubagentRuns from '../pi-subagent-runs.js';
const captured = vi.hoisted(() => ({
args: [] as string[],
@@ -5607,6 +5609,76 @@ describe("Pi provider-aware model routing", () => {
await handle.close();
});
+ it.each(['ok', 'invalid'] as const)('captures a coherent resume snapshot after a concurrent model refresh: %s', async (ack) => {
+ let endpoint = 'http://a.test';
+ const deps = byomDeps(async () => ({ providers: [{
+ id: 'native-a', name: 'Native A', adapterProvider: 'openai',
+ baseUrl: endpoint, api: 'openai-completions',
+ models: [{ id: 'local-model', contextWindow: 200_000 }],
+ }], env: {} }));
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'resume-during-refresh', workingDir: cwd,
+ model: 'local-model', providerId: 'native-a',
+ });
+ const config = captured.env.PI_CODING_AGENT_DIR!;
+ const rulesFile = path.join(config, 'pi-cache-compatibility.json');
+ const modelsFile = path.join(config, 'models.json');
+ const write = fs.writeFile.bind(fs);
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let entered!: () => void;
+ const writingRules = new Promise<void>(resolve => { entered = resolve; });
+ let blocked = false;
+ const writer = vi.spyOn(fs, 'writeFile').mockImplementation(async (file, ...args) => {
+ if (String(file) === rulesFile && !blocked) {
+ blocked = true;
+ entered();
+ await gate;
+ }
+ return write(file, ...args);
+ });
+ const reader = vi.spyOn(fs, 'readFile');
+ const resumeSpy = vi.spyOn(piSubagentRuns, 'resumePiSubagentRun')
+ .mockResolvedValue('123e4567-e89b-42d3-a456-426614174098');
+ let switching: Promise<unknown> | undefined;
+ let resuming: Promise<unknown> | undefined;
+ try {
+ endpoint = 'http://b.test';
+ captured.refreshAckMode = ack;
+ switching = handle.setModel!('local-model', { providerId: 'native-a' })
+ .then(() => undefined, error => error);
+ await writingRules;
+ expect(readFileSync(modelsFile, 'utf8')).toContain('http://b.test');
+ expect(readFileSync(rulesFile, 'utf8')).toContain('http://a.test');
+ reader.mockClear();
+ resuming = handle.resumeBackgroundTask!('terminal-task', 'continue')
+ .then(runId => runId, error => error);
+ // Let the resume reach its read boundary while refresh is held mid-write.
+ await new Promise<void>(resolve => setImmediate(resolve));
+ expect(reader.mock.calls.some(([file]) => String(file) === modelsFile)).toBe(false);
+ expect(resumeSpy).not.toHaveBeenCalled();
+ release();
+ const result = await switching;
+ if (ack === 'invalid') expect(result).toBeInstanceOf(Error);
+ else expect(result).toBeUndefined();
+ expect(await resuming).toBeUndefined();
+ expect(resumeSpy).toHaveBeenCalledOnce();
+ const snapshot = resumeSpy.mock.calls[0][3]!.runtimeSnapshot!;
+ const expected = ack === 'ok' ? 'http://b.test' : 'http://a.test';
+ expect(JSON.parse(snapshot.modelsJson.toString()).providers['native-a'].baseUrl).toBe(expected);
+ expect(JSON.parse(snapshot.cacheRulesJson!.toString())).toContainEqual(expect.objectContaining({
+ provider: 'native-a', baseUrl: expected,
+ }));
+ } finally {
+ release();
+ await Promise.allSettled([switching, resuming]);
+ await handle.close();
+ writer.mockRestore();
+ reader.mockRestore();
+ resumeSpy.mockRestore();
+ }
+ });
+
it.each(['provider', 'model'] as const)('retains only the running credential when its %s disappears during catalog refresh', async (removed) => {
let updated = false;
const running = {
diff --git a/packages/maker-core/src/agents/pi/cache-recovery-source.ts b/packages/maker-core/src/agents/pi/cache-recovery-source.ts
index d060014d72..80af250255 100644
--- a/packages/maker-core/src/agents/pi/cache-recovery-source.ts
+++ b/packages/maker-core/src/agents/pi/cache-recovery-source.ts
@@ -95,6 +95,24 @@ function installCindyCacheRecovery(pi) {
return fingerprint({ api: model?.api, provider: model?.provider, id: model?.id, baseUrl: model?.baseUrl,
modelHeaders: model?.headers, headers: options?.headers, apiKey: options?.apiKey });
}
+ function rejectedFieldList(text) {
+ let rest = text.trimStart().replace(/^\[\s*/, '');
+ const result = [];
+ while (rest) {
+ const match = /^(?:(['"\x60])([a-z_][\w.-]*)\1|([a-z_][\w.-]*))/i.exec(rest);
+ if (!match) break;
+ const tail = rest.slice(match[0].length);
+ // A comma may introduce prose ("use another option instead"). Bare
+ // continuation fields must end at a list/sentence boundary; quoted fields
+ // are explicit. This parses the list without naming vendors or options.
+ if (result.length && !match[1] && !/^\s*(?:[,,;\].!?]|$)/.test(tail)) break;
+ result.push((match[2] ?? match[3]).replace(/\.+$/, '').toLowerCase());
+ const separator = /^\s*[,,]\s*/.exec(tail);
+ if (!separator) break;
+ rest = tail.slice(separator[0].length);
+ }
+ return result;
+ }
function failureKind(message, provider) {
const text = message?.errorMessage;
if (typeof text !== 'string' || text.length > 64 * 1024 || message.stopReason !== 'error'
@@ -118,19 +136,23 @@ function installCindyCacheRecovery(pi) {
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.
+ let cacheRejected = false;
for (const pattern of [
- /(?:unsupported|unknown|unrecognized|unexpected)\s+(?:parameters?|fields?|arguments?|properties|property|options?)(?:\(s\))?[\s:=]*(\[[^\]]+\]|['"\x60]?[a-z_][\w.-]*)/gi,
+ /(?:unsupported|unknown|unrecognized|unexpected)\s+(?:parameters?|fields?|arguments?|properties|property|options?)(?:\(s\))?[\s:=]*/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::=]*/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;
+ const rejected = match[1] ? [match[1].replace(/\.+$/, '').toLowerCase()]
+ : rejectedFieldList(body.slice(match.index + match[0].length));
+ for (const field of rejected) {
+ if (!fields.includes(field)) return;
+ cacheRejected = true;
}
}
}
- 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';
+ 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') {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index c2a6478865..eb6bd628bf 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -5505,12 +5505,18 @@ export class PiAgent extends BaseAgent {
const operation = (async () => {
await permissionWriteChain;
if (closed) throw new Error('PI session is closed');
- 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')),
- ]);
+ // Model refresh writes and rolls back these files in the RPC lane. Read
+ // the snapshot there too, so a child never freezes a mixed generation.
+ // Launch/refresh below stay outside: they may enqueue their own RPC.
+ const [modelsJson, bridgeSource, runnerSource, cacheRulesJson] = await runExclusivePiRpc(() => {
+ if (closed) throw new Error('PI session is closed');
+ return 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),
env: durableSpawnEnv,