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(maker-core): pi settings.json 覆写保留用户 shellPath 等自配置键(#3643) (#3743)

fico-hub5997c497ed04
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
index e265eec8f5..189ed4381b 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-native-auto-compact.test.ts
@@ -3,7 +3,7 @@
* events and only latches deterministic failures for the next-send rollover.
*/
-import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -383,6 +383,62 @@ describe("PiAgent native auto-compaction ownership", () => {
await handle.close();
});
+ it("applies stable-root user shellPath to a brand-new session (#3643 cross-start)", async () => {
+ // 用户在稳定根(pi-agent-home/settings.json)配置逃生门;本地 configHome 是
+ // 每会话随机目录,新会话必须能从稳定根拿到配置。
+ writeFileSync(
+ path.join(agentHome, "settings.json"),
+ JSON.stringify({ shellPath: "C:/cygwin64/bin/bash.exe" }, null, 2),
+ );
+ const handle = await start();
+ const files: string[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const next = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(next);
+ else if (entry.name === "settings.json") files.push(next);
+ }
+ };
+ walk(path.join(agentHome, "run-tmp"));
+ expect(files.length).toBeGreaterThan(0);
+ const written = JSON.parse(readFileSync(files[files.length - 1]!, "utf8")) as {
+ shellPath?: string;
+ transport?: string;
+ };
+ expect(written.shellPath).toBe("C:/cygwin64/bin/bash.exe");
+ expect(written.transport).toBe("sse");
+ await handle.close();
+ });
+
+ it("preserves user shellPath across settings.json rewrites (#3643)", async () => {
+ const handle = await start();
+ const files: string[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const next = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(next);
+ else if (entry.name === "settings.json") files.push(next);
+ }
+ };
+ walk(agentHome);
+ expect(files.length).toBeGreaterThan(0);
+ const settingsPath = files[files.length - 1]!;
+ // 用户在会话间隙按 pi docs/windows.md 配置 shell 逃生门。
+ const current = JSON.parse(readFileSync(settingsPath, "utf8")) as Record<string, unknown>;
+ writeFileSync(
+ settingsPath,
+ JSON.stringify({ ...current, shellPath: "C:/cygwin64/bin/bash.exe" }, null, 2),
+ );
+ await handle.setModel!("n");
+ const rewritten = JSON.parse(readFileSync(settingsPath, "utf8")) as {
+ shellPath?: string;
+ compaction?: { reserveTokens?: number };
+ };
+ expect(rewritten.shellPath).toBe("C:/cygwin64/bin/bash.exe");
+ expect(rewritten.compaction?.reserveTokens).toBe(25_000);
+ await handle.close();
+ });
+
it("terminates the session when compaction settings reload fails after a window change", async () => {
const handle = await start();
knobs.switchSessionSuccess = false;
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-settings-passthrough.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-settings-passthrough.test.ts
new file mode 100644
index 0000000000..7d88b9b0cf
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-settings-passthrough.test.ts
@@ -0,0 +1,72 @@
+/**
+ * #3643:Cindy 每次 startSession 覆写隔离 agentHome 的 settings.json。pi 官方文档
+ * 的用户自配置键(shellPath / shellCommandPrefix / npmCommand)是 Windows bash
+ * spawn 故障的第一顺位自救手段,覆写时必须按白名单保留;Cindy 自有键始终以新
+ * 生成内容为准。
+ */
+import { describe, expect, it } from 'vitest';
+
+import { buildPiSettingsJsonContent, mergePiUserSettingsPassthrough } from '../index.js';
+
+describe('mergePiUserSettingsPassthrough (#3643)', () => {
+ const built = buildPiSettingsJsonContent(128_000, 75);
+
+ it('preserves user shellPath and shellCommandPrefix across the rewrite', () => {
+ const existing = JSON.stringify({
+ shellPath: 'C:/Program Files/Git/bin/bash.exe',
+ shellCommandPrefix: 'shopt -s expand_aliases',
+ transport: 'websocket',
+ });
+ const merged = JSON.parse(mergePiUserSettingsPassthrough(built, existing));
+ expect(merged.shellPath).toBe('C:/Program Files/Git/bin/bash.exe');
+ expect(merged.shellCommandPrefix).toBe('shopt -s expand_aliases');
+ // Cindy 自有键不被旧文件覆盖:transport 恒为新生成的 sse。
+ expect(merged.transport).toBe('sse');
+ expect(merged.retry).toEqual(JSON.parse(built).retry);
+ });
+
+ it('preserves npmCommand only when it is a non-empty string array', () => {
+ const good = JSON.stringify({ npmCommand: ['mise', 'exec', 'node@20', '--', 'npm'] });
+ expect(JSON.parse(mergePiUserSettingsPassthrough(built, good)).npmCommand).toEqual([
+ 'mise',
+ 'exec',
+ 'node@20',
+ '--',
+ 'npm',
+ ]);
+ const badType = JSON.stringify({ npmCommand: 'npm' });
+ expect(JSON.parse(mergePiUserSettingsPassthrough(built, badType)).npmCommand).toBeUndefined();
+ const badItems = JSON.stringify({ npmCommand: ['npm', 42] });
+ expect(JSON.parse(mergePiUserSettingsPassthrough(built, badItems)).npmCommand).toBeUndefined();
+ });
+
+ it('rejects blank or non-string shellPath and non-whitelisted keys', () => {
+ const existing = JSON.stringify({
+ shellPath: ' ',
+ defaultTools: ['read', 'powershell'],
+ compaction: { reserveTokens: 1 },
+ });
+ const merged = JSON.parse(mergePiUserSettingsPassthrough(built, existing));
+ expect(merged.shellPath).toBeUndefined();
+ // 白名单之外的键(defaultTools 会与 bridge 工具面冲突)不透传。
+ expect(merged.defaultTools).toBeUndefined();
+ // Cindy 自有 compaction 以新生成内容为准。
+ expect(merged.compaction).toEqual(JSON.parse(built).compaction);
+ });
+
+ it('later sources win: the stable-root user file overrides the per-session file', () => {
+ const session = JSON.stringify({ shellPath: 'C:/old/session/bash.exe', npmCommand: ['npm'] });
+ const stable = JSON.stringify({ shellPath: 'C:/cygwin64/bin/bash.exe' });
+ const merged = JSON.parse(mergePiUserSettingsPassthrough(built, session, stable));
+ expect(merged.shellPath).toBe('C:/cygwin64/bin/bash.exe');
+ // 稳定根没写的键仍从会话文件保留。
+ expect(merged.npmCommand).toEqual(['npm']);
+ });
+
+ it('falls back to the built content when the existing file is missing or corrupt', () => {
+ expect(mergePiUserSettingsPassthrough(built, null)).toBe(built);
+ expect(mergePiUserSettingsPassthrough(built, '')).toBe(built);
+ expect(mergePiUserSettingsPassthrough(built, '{not json')).toBe(built);
+ expect(mergePiUserSettingsPassthrough(built, '[1,2]')).toBe(built);
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 608ff860af..4a6e404dcb 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -1158,6 +1158,61 @@ interface FailedPiStartupCleanup {
cleanupLocal?: () => void;
}
+/**
+ * pi 官方文档的用户自配置键(Windows shell 逃生门与 npm 包装命令):Cindy 每次
+ * startSession 都覆写隔离 agentHome 的 settings.json,若把这些键一并抹掉,用户在
+ * Cindy Pi 里就失去了原生 pi 文档提供的自救手段 —— #3643:bash spawn 失败时
+ * `shellPath` 是 pi Windows shell 解析的第一顺位来源,原生 pi 用户改 settings.json
+ * 即可恢复,Cindy Pi 用户此前无路可走(pi-harness「上游非退化」红线)。
+ * Cindy 自有键(transport/retry/compaction/packages)始终以新生成内容为准。
+ */
+const PI_USER_SETTINGS_PASSTHROUGH_KEYS = ['shellPath', 'shellCommandPrefix', 'npmCommand'] as const;
+
+function collectPiUserSettingsPassthrough(content: string | null): Record<string, unknown> {
+ if (content === null || content.trim().length === 0) return {};
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(content);
+ } catch {
+ return {};
+ }
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return {};
+ const existing = parsed as Record<string, unknown>;
+ const preserved: Record<string, unknown> = {};
+ for (const key of PI_USER_SETTINGS_PASSTHROUGH_KEYS) {
+ const value = existing[key];
+ if (key === 'npmCommand') {
+ if (
+ Array.isArray(value) &&
+ value.length > 0 &&
+ value.every((item) => typeof item === 'string')
+ ) {
+ preserved[key] = value;
+ }
+ continue;
+ }
+ if (typeof value === 'string' && value.trim().length > 0) preserved[key] = value;
+ }
+ return preserved;
+}
+
+/** 多来源合并,靠后的来源同键覆盖靠前的(稳定根用户文件应排最后)。 */
+export function mergePiUserSettingsPassthrough(
+ builtContent: string,
+ ...existingContents: Array<string | null>
+): string {
+ const preserved: Record<string, unknown> = {};
+ for (const content of existingContents) {
+ Object.assign(preserved, collectPiUserSettingsPassthrough(content));
+ }
+ if (Object.keys(preserved).length === 0) return builtContent;
+ const built = JSON.parse(builtContent) as Record<string, unknown>;
+ for (const [key, value] of Object.entries(preserved)) {
+ if (!(key in built)) built[key] = value;
+ }
+ return JSON.stringify(built, null, 2) + '\n';
+}
+
export function buildPiSettingsJsonContent(
contextWindow: number,
piCompactionPct?: number,
@@ -1552,6 +1607,49 @@ export class PiAgent extends BaseAgent {
);
}
+ /**
+ * 生成 settings.json 内容,本地会话在覆写前保留用户自配置白名单键(#3643)。
+ * 两个来源,稳定根优先:
+ * 1. 会话 configHome 的既有 settings.json(同会话内 setModel 等覆写不丢配置);
+ * 2. 稳定 agentHome 根(pi-agent-home/settings.json)——本地 configHome 是
+ * 每会话随机目录(run-tmp/<hex>),只读会话文件会让「重启后新会话」拿不到
+ * 用户配置;稳定根文件才是跨启动生效的逃生门(对齐原生 pi 的
+ * ~/.pi/agent/settings.json 位置语义,Cindy 自身从不写它)。
+ * 远端 fileOps 无 readFile,保持原覆写行为(远端 configHome 全托管,且本机
+ * shell 路径对远端主机无意义)。
+ */
+ private async buildSettingsJsonPreservingUserKeys(
+ settingsJsonPath: string,
+ opts: {
+ fileOps?: PiRemoteFileOps;
+ contextWindow?: number;
+ piCompactionPct?: number;
+ packages?: readonly PiNativePackageEntry[];
+ },
+ ): Promise<string> {
+ const built = this.buildCurrentPiSettingsJson(
+ opts.contextWindow,
+ opts.piCompactionPct,
+ opts.packages,
+ );
+ if (opts.fileOps) return built;
+ const readOrNull = async (file: string): Promise<string | null> => {
+ try {
+ return await fs.readFile(file, 'utf8');
+ } catch {
+ return null;
+ }
+ };
+ const stableUserSettingsPath = joinRemotePosixPath(this.resolveAgentHome(), 'settings.json');
+ const [sessionContent, stableContent] = await Promise.all([
+ readOrNull(settingsJsonPath),
+ stableUserSettingsPath === settingsJsonPath
+ ? Promise.resolve(null)
+ : readOrNull(stableUserSettingsPath),
+ ]);
+ return mergePiUserSettingsPassthrough(built, sessionContent, stableContent);
+ }
+
private async writePiRuntimeSettings(
agentHome: string,
opts: {
@@ -1562,10 +1660,9 @@ export class PiAgent extends BaseAgent {
} = {},
): Promise<void> {
const settingsJsonPath = joinRemotePosixPath(agentHome, 'settings.json');
- const settingsJsonContent = this.buildCurrentPiSettingsJson(
- opts.contextWindow,
- opts.piCompactionPct,
- opts.packages,
+ const settingsJsonContent = await this.buildSettingsJsonPreservingUserKeys(
+ settingsJsonPath,
+ opts,
);
if (opts.fileOps) {
await opts.fileOps.writeFile(settingsJsonPath, settingsJsonContent);
@@ -1774,10 +1871,9 @@ export class PiAgent extends BaseAgent {
// isolated embedded runtime. Other PI providers ignore this transport knob.
// Agent-level retries stay with Pi (provider maxRetries stays 0 — Pi docs:
// SDK retries can swallow quota errors before the agent sees them).
- const settingsJsonContent = this.buildCurrentPiSettingsJson(
- opts.contextWindow,
- opts.piCompactionPct,
- opts.packages,
+ const settingsJsonContent = await this.buildSettingsJsonPreservingUserKeys(
+ settingsJsonPath,
+ opts,
);
// 远端 launch identity 必须覆盖进程启动才读的快照。只 hash models.json 时,
// retry/transport/compaction 改写会落到旧 configHome,daemon 纯 attach。