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 接通离线 grep/find/ls 工具 (#1718)

Chris Zhang35af604b5d20
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 63b0a6965a..2aeca31020 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -44,6 +44,7 @@ import { createLogger } from '../logger.js';
import { readMemorySettings } from './memory-settings-store.js';
import { registerPiProxySession } from './pi-proxy-session-auth.js';
import { getDesktopMcpToolApprovalPolicy } from './mcp-tool-approval-policy.js';
+import { getRipgrepBinaryPath } from './runtime-configs.js';
const log = createLogger('pi-host');
@@ -153,9 +154,13 @@ export function composePiSystemPrompt(hostPrompt: string, agentPrompt: string):
}
function buildDesktopPiRuntimeConfig(): AgentRuntimeConfig {
+ const ripgrepPath = getRipgrepBinaryPath();
const config: AgentRuntimeConfig = {
// 保留 host 共用身份段,再追加 Pi 专属行为段;maker-core 会整体追加到 Pi 原生 prompt。
systemPrompt: composePiSystemPrompt(hostSystemPrompt, piSystemPrompt),
+ // Pi 的 grep 以及 Cindy 覆盖的 find 都固定复用随 Desktop 校验、打包的 rg。
+ // 下发绝对路径而非 PATH,避免 Windows 从不受信工作目录优先命中同名 rg.exe。
+ managedExecutablePaths: { ripgrep: ripgrepPath },
userDataPath: app.getPath('userData'),
};
// 网关 endpoint 随 model-access 凭据同步就绪,用 getter 惰性读(与 claude remoteEndpoint 同理)。
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
new file mode 100644
index 0000000000..1caddfb145
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
+
+describe('cindy-bridge extension source', () => {
+ it('overrides find with the managed ripgrep backend instead of runtime fd download', () => {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+
+ for (const tool of ['createBashTool', 'createFindTool', 'createGrepTool', 'createLsTool']) {
+ expect(source).toContain(tool + ',');
+ }
+ expect(source).toContain("const args = ['--files', '--hidden', '--no-require-git']");
+ expect(source).toContain("if (pattern.includes('/')) {");
+ expect(source).toContain('path.basename(relative)');
+ expect(source).toContain("effectivePattern = '**/' + pattern");
+ expect(source).toContain('path.resolve(cwd, relative)');
+ expect(source).toContain('path.matchesGlob(candidate, effectivePattern)');
+ expect(source).not.toContain("'--glob', pattern");
+ expect(source).toContain('glob: rgGlob');
+ expect(source).toContain('const grepTool = createGrepTool(process.cwd())');
+ expect(source).toContain('spawn(managedRipgrepPath(), args, {');
+ expect(source).not.toContain("spawn('rg'");
+ expect(source).toContain("const MANAGED_RG_PATH_ENV = 'CINDY_PI_MANAGED_RG_PATH'");
+ expect(source).toContain('const lsTool = createLsTool(process.cwd())');
+ expect(source).not.toContain("spawn('fd'");
+ });
+
+ it('keeps generated extension source free of template literals', () => {
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).not.toContain('`');
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).not.toContain('${');
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index c13bb8062d..663b38e9c5 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -10,7 +10,15 @@
*/
import { createServer, type Server } from 'node:http';
-import { mkdtempSync, existsSync, rmSync, writeFileSync, mkdirSync, symlinkSync } from 'node:fs';
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -30,6 +38,13 @@ const PI_BINARY = path.join(
`${process.platform}-${process.arch}`,
process.platform === 'win32' ? 'pi.exe' : 'pi',
);
+const RIPGREP_DIR = path.join(
+ REPO_ROOT,
+ 'apps',
+ 'ripgrep-bin',
+ `${process.platform}-${process.arch}`,
+);
+const RIPGREP_BINARY = path.join(RIPGREP_DIR, process.platform === 'win32' ? 'rg.exe' : 'rg');
const PREVIOUS_PI_BINARY = path.join(
REPO_ROOT,
'tools',
@@ -329,7 +344,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
logout: async () => {},
getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'test-key-123' }),
},
- runtimeConfig: { endpoint },
+ runtimeConfig: { endpoint, managedExecutablePaths: { ripgrep: RIPGREP_BINARY } },
binaryPath: PI_BINARY,
logger: noopLogger,
capabilityAdditions: {
@@ -1141,6 +1156,92 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
}
}
+ it(
+ 'offline grep uses the host-managed ripgrep instead of falling back to bash',
+ { timeout: 60_000 },
+ async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-managed-grep-'));
+ writeFileSync(path.join(workingDir, 'tool-target.ts'), 'needle-line\n');
+ const rogueRg = path.join(workingDir, process.platform === 'win32' ? 'rg.exe' : 'rg');
+ writeFileSync(rogueRg, process.platform === 'win32' ? 'not-an-executable' : '#!/bin/sh\nexit 42\n');
+ if (process.platform !== 'win32') chmodSync(rogueRg, 0o755);
+ try {
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('grep', { pattern: 'needle-line', path: '.', literal: true }),
+ anthropicStreamBody('grep turn finished'),
+ );
+ const reqBefore = seenRequests.length;
+ await runPermissionTurn({
+ sessionId: 'pi-managed-grep',
+ workingDir,
+ permissionMode: 'bypassPermissions',
+ resolverBehavior: 'deny',
+ });
+ const followUp = seenRequests.slice(reqBefore).map((request) => request.body);
+ expect(followUp.some((body) => body.includes('tool-target.ts:1: needle-line'))).toBe(true);
+ } finally {
+ rmSync(workingDir, { recursive: true, force: true });
+ scriptedResponses.length = 0;
+ }
+ },
+ );
+
+ it(
+ 'offline find uses the Cindy ripgrep override without fd',
+ { timeout: 60_000 },
+ async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-managed-find-'));
+ writeFileSync(path.join(workingDir, 'find-me.ts'), 'export {};\n');
+ writeFileSync(path.join(workingDir, 'skip-me.txt'), 'skip\n');
+ mkdirSync(path.join(workingDir, 'nested'));
+ writeFileSync(path.join(workingDir, 'nested', 'find-nested.ts'), 'export {};\n');
+ mkdirSync(path.join(workingDir, 'packages', 'foo', 'src'), { recursive: true });
+ writeFileSync(
+ path.join(workingDir, 'packages', 'foo', 'src', 'find-path.spec.ts'),
+ 'export {};\n',
+ );
+ writeFileSync(path.join(workingDir, '.gitignore'), 'ignored-by-git.ts\n');
+ writeFileSync(path.join(workingDir, 'ignored-by-git.ts'), 'secret\n');
+ try {
+ scriptedResponses.length = 0;
+ scriptedResponses.push(
+ anthropicToolUseBody('find', { pattern: '*.ts', path: '.' }),
+ anthropicStreamBody('find turn finished'),
+ );
+ const reqBefore = seenRequests.length;
+ await runPermissionTurn({
+ sessionId: 'pi-managed-find',
+ workingDir,
+ permissionMode: 'bypassPermissions',
+ resolverBehavior: 'deny',
+ });
+ const followUp = seenRequests.slice(reqBefore).map((request) => request.body);
+ expect(followUp.some((body) => body.includes('find-me.ts'))).toBe(true);
+ expect(followUp.some((body) => body.includes('find-nested.ts'))).toBe(true);
+ expect(followUp.some((body) => body.includes('skip-me.txt'))).toBe(false);
+ expect(followUp.some((body) => body.includes('ignored-by-git.ts'))).toBe(false);
+
+ scriptedResponses.push(
+ anthropicToolUseBody('find', { pattern: 'src/**/*.spec.ts', path: '.' }),
+ anthropicStreamBody('path find turn finished'),
+ );
+ const pathReqBefore = seenRequests.length;
+ await runPermissionTurn({
+ sessionId: 'pi-managed-find-full-path',
+ workingDir,
+ permissionMode: 'bypassPermissions',
+ resolverBehavior: 'deny',
+ });
+ const pathFollowUp = seenRequests.slice(pathReqBefore).map((request) => request.body);
+ expect(pathFollowUp.some((body) => body.includes('find-path.spec.ts'))).toBe(true);
+ } finally {
+ rmSync(workingDir, { recursive: true, force: true });
+ scriptedResponses.length = 0;
+ }
+ },
+ );
+
it(
'auto mode: safe bash executes end-to-end without prompting (real bridge intercept)',
{ timeout: 60_000 },
@@ -1190,7 +1291,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
command: [
'for n in CINDY_PI_API_KEY CINDY_PI_SESSION_ID CINDY_PI_SESSION_TOKEN',
'CINDY_PI_MCP_BRIDGE CINDY_PI_KEY_LOCALBYOM CINDY_PI_REMOTE_MCP_SECRET_0',
- 'CINDY_PI_SECRET_ENV_NAMES',
+ 'CINDY_PI_SECRET_ENV_NAMES CINDY_PI_MANAGED_RG_PATH',
'CINDY_PI_PERMISSION_FILE PI_CODING_AGENT_DIR PI_SESSION_ID PI_SESSION_FILE; do',
' if [ -n "$(printenv "$n")" ]; then printf "PI_ENV_LEAK:%s\\n" "$n"; fi;',
'done; printf "PI_ENV_CLEAN\\n"',
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
index be095fdbe6..fa294c2e22 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
@@ -1,8 +1,8 @@
/**
* pi auto 档 dispatcher + spawn 配置回归 —— mock PiRpcProcess(不 spawn 真 pi),
* 捕获构造参数与 send() 帧,验证:
- * 1. spawn args:改用 --append-system-prompt(保留 pi 默认 prompt),不再 --system-prompt;
- * 2. spawn env:PI_OFFLINE=1(嵌入式不做启动期联网)、PI_CACHE_RETENTION=long、
+ * 1. spawn args:保留 pi 默认 prompt,不用 --tools 筛掉动态 MCP/subagent;
+ * 2. spawn env:PI_OFFLINE=1(嵌入式不做启动期联网)、受管工具绝对路径、PI_CACHE_RETENTION=long、
* NO_PROXY 含 loopback 且吞并小写 no_proxy;
* 3. auto 档:区内写静默 confirmed:true;灰区交当前模型 reviewer,仅 reviewer 明确
* ask / 本地红线才弹 resolver;reviewer 缺失时 fail-closed deny;
@@ -86,6 +86,7 @@ const flush = () => new Promise((r) => setTimeout(r, 0));
describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
let agentHome = '';
let cwd = '';
+ let managedRipgrepPath = '';
let savedNoProxy: string | undefined;
let savedNoProxyLower: string | undefined;
@@ -103,6 +104,13 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
captured.closed = false;
agentHome = mkdtempSync(path.join(tmpdir(), 'pi-dispatch-home-'));
cwd = mkdtempSync(path.join(tmpdir(), 'pi-dispatch-cwd-'));
+ managedRipgrepPath = path.join(
+ agentHome,
+ 'managed-tools',
+ process.platform === 'win32' ? 'rg.exe' : 'rg',
+ );
+ mkdirSync(path.dirname(managedRipgrepPath), { recursive: true });
+ writeFileSync(managedRipgrepPath, 'fake managed ripgrep');
savedNoProxy = process.env.NO_PROXY;
savedNoProxyLower = process.env.no_proxy;
});
@@ -147,7 +155,11 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
logout: async () => {},
getAuthEnv: async () => ({}),
},
- runtimeConfig: { endpoint: 'http://127.0.0.1:9', systemPrompt: 'You are Cindy.' },
+ runtimeConfig: {
+ endpoint: 'http://127.0.0.1:9',
+ systemPrompt: 'You are Cindy.',
+ managedExecutablePaths: { ripgrep: managedRipgrepPath },
+ },
binaryPath: path.join(agentHome, 'pi'),
logger: noopLogger,
capabilityAdditions: {
@@ -219,7 +231,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
});
}
- it('spawns with --append-system-prompt (default pi prompt preserved) and offline/no-proxy env', async () => {
+ it('spawns with a private managed rg path, default prompt and no restrictive tool allowlist', async () => {
if (process.platform === 'win32') {
// Windows 的环境变量键不区分大小写,无法同时构造“仅有小写键”的进程环境。
process.env.NO_PROXY = 'corp.internal';
@@ -232,8 +244,17 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
const idx = captured.args.indexOf('--append-system-prompt');
expect(idx).toBeGreaterThan(-1);
expect(captured.args[idx + 1]).toBe('You are Cindy.');
+ expect(captured.args).not.toContain('--tools');
expect(captured.env.PI_OFFLINE).toBe('1');
expect(captured.env.PI_CACHE_RETENTION).toBe('long');
+ const privateRgPath = captured.env.CINDY_PI_MANAGED_RG_PATH;
+ expect(privateRgPath).toBe(path.join(
+ captured.env.PI_CODING_AGENT_DIR!,
+ 'bin',
+ process.platform === 'win32' ? 'rg.exe' : 'rg',
+ ));
+ expect(path.isAbsolute(privateRgPath!)).toBe(true);
+ expect(readFileSync(privateRgPath!, 'utf8')).toBe('fake managed ripgrep');
expect(captured.proxyRegistration).toEqual({
sessionId: 's1',
token: captured.env.CINDY_PI_SESSION_TOKEN,
@@ -244,6 +265,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
'CINDY_PI_API_KEY',
'CINDY_PI_SESSION_ID',
'CINDY_PI_SESSION_TOKEN',
+ 'CINDY_PI_MANAGED_RG_PATH',
// 子代理路由快照是**控制面**:一次获批的 bash 拿到路径就能改写 provider/model,
// 让后续每次委派打到攻击者选定的 endpoint。与 permission file 同类,必须从
// bash/模型工具的 spawn 边界剥离(review)。
@@ -257,6 +279,26 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
expect(captured.env.no_proxy).toBeUndefined();
});
+ it('does not inherit an unmanaged ripgrep path from the host process env', async () => {
+ const previous = process.env.CINDY_PI_MANAGED_RG_PATH;
+ process.env.CINDY_PI_MANAGED_RG_PATH = path.join(cwd, 'rogue-rg');
+ let handle: AgentSessionHandle | undefined;
+ try {
+ const deps = buildDeps();
+ delete deps.runtimeConfig.managedExecutablePaths;
+ handle = await new PiAgent(deps).startSession({
+ sessionId: 'unmanaged-rg',
+ workingDir: cwd,
+ model: 'm',
+ });
+ expect(captured.env.CINDY_PI_MANAGED_RG_PATH).toBeUndefined();
+ } finally {
+ await handle?.close();
+ if (previous === undefined) delete process.env.CINDY_PI_MANAGED_RG_PATH;
+ else process.env.CINDY_PI_MANAGED_RG_PATH = previous;
+ }
+ });
+
it('refuses the model switch when the subagent routing snapshot cannot be persisted', async () => {
// 顺序不能反:快照必须先落盘、再切 pi 侧模型。
@@ -485,7 +527,10 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
const { readFileSync } = await import('node:fs');
const configHome = captured.env.PI_CODING_AGENT_DIR as string;
const bridge = readFileSync(path.join(configHome, 'extensions', 'cindy-bridge.ts'), 'utf8');
- expect(bridge).toContain("import { createBashTool } from '@earendil-works/pi-coding-agent'");
+ expect(bridge).toContain('createBashTool,');
+ expect(bridge).toContain('createFindTool,');
+ expect(bridge).toContain('createGrepTool,');
+ expect(bridge).toContain('createLsTool,');
expect(bridge).toContain('env: withoutPiSecrets(env)');
expect(bridge).toContain('exposeSessionEnvironment: false');
expect(bridge).toContain("'CINDY_PI_PERMISSION_FILE'");
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index f3b53a6ca1..38f1c17dba 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -31,12 +31,21 @@ export const CINDY_BRIDGE_EXTENSION_SOURCE = String.raw`/**
* cindy-bridge (generated by Cindy — do not edit; overwritten on session start)
*/
import { readFileSync, realpathSync } from 'node:fs';
+import { stat } from 'node:fs/promises';
+import { spawn } from 'node:child_process';
+import { createInterface } from 'node:readline';
import path from 'node:path';
-import { createBashTool } from '@earendil-works/pi-coding-agent';
+import {
+ createBashTool,
+ createFindTool,
+ createGrepTool,
+ createLsTool,
+} from '@earendil-works/pi-coding-agent';
const PERMISSION_TITLE = 'cindy:permission';
const READONLY_BUILTINS = new Set(['read', 'grep', 'find', 'ls']);
const FILE_WRITE_BUILTINS = new Set(['edit', 'write']);
+const MANAGED_RG_PATH_ENV = 'CINDY_PI_MANAGED_RG_PATH';
// Pi 的模型鉴权、localhost proxy 与 MCP bearer 需要留在父进程 env 供 runtime
// 按请求解析,但绝不能继承进 LLM 可调用的 bash 子进程。名单由 host 按本次会话
@@ -45,6 +54,7 @@ const FILE_WRITE_BUILTINS = new Set(['edit', 'write']);
const SECRET_ENV_NAMES = new Set<string>([
'CINDY_PI_SECRET_ENV_NAMES',
'CINDY_PI_PERMISSION_FILE',
+ MANAGED_RG_PATH_ENV,
'PI_CODING_AGENT_DIR',
]);
try {
@@ -64,6 +74,14 @@ function withoutPiSecrets(env: Record<string, string | undefined>): Record<strin
return clean;
}
+function managedRipgrepPath(): string {
+ const configured = process.env[MANAGED_RG_PATH_ENV];
+ if (!configured || !path.isAbsolute(configured)) {
+ throw new Error('Cindy managed ripgrep is unavailable');
+ }
+ return configured;
+}
+
// 凭证/密钥路径特征由 maker-core 的单一来源生成。bridge 自包含、运行时不能 import,
// 但不再维护第二份手写名单,避免新增凭证目录时 Pi 静默漏拦。
const CREDENTIAL_PATH_PATTERNS = ${JSON.stringify(SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS)}
@@ -452,7 +470,114 @@ async function connectServer(pi: any, server: McpServerRef, token: string): Prom
return tools.length;
}
+// Pi 内置 find 依赖 fd;PI_OFFLINE=1 时缺失后不会下载。Cindy 已随 Desktop 校验并
+// 提供 rg,因此把固定参数的 rg --files 适配成 Pi 原生 find operations。参数直接传
+// spawn、不经 shell;文件模式在 JS 里过滤,因为 rg 的 positive glob 会覆盖 .gitignore。
+function rgGlob(
+ pattern: string,
+ cwd: string,
+ options: { ignore: string[]; limit: number },
+): Promise<string[]> {
+ return new Promise((resolve, reject) => {
+ const limit = Number.isFinite(options.limit) ? Math.max(1, Math.floor(options.limit)) : 1000;
+ const args = ['--files', '--hidden', '--no-require-git'];
+ for (const ignored of options.ignore) args.push('--glob', '!' + ignored);
+
+ const child = spawn(managedRipgrepPath(), args, {
+ cwd,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const lines: string[] = [];
+ let stderr = '';
+ let stoppedAtLimit = false;
+ let settled = false;
+ const settle = (fn: () => void) => {
+ if (settled) return;
+ settled = true;
+ fn();
+ };
+ const reader = createInterface({ input: child.stdout });
+ reader.on('line', (line) => {
+ if (!line || lines.length >= limit) return;
+ const relative = line.replace(/\r$/, '');
+ // 完整镜像 Pi 上游 fd 规则:无 slash 时匹配 basename;有 slash 时启用
+ // full-path,且相对 pattern 自动加 **/,让 src/** 同时命中 monorepo 子包。
+ let candidate = path.basename(relative);
+ let effectivePattern = pattern;
+ if (pattern.includes('/')) {
+ candidate = path.resolve(cwd, relative).split(path.sep).join('/');
+ if (!pattern.startsWith('/') && !pattern.startsWith('**/') && pattern !== '**') {
+ effectivePattern = '**/' + pattern;
+ }
+ }
+ // path.matchesGlob 默认不让 * 匹配点开头的段;rg glob 会匹配。保留原路径先匹配
+ // 显式点模式,再用等长占位符补齐 --hidden 下的普通通配语义。
+ const visibleCandidate = candidate.replace(/(^|[\\/])\./g, '$1_');
+ if (!path.matchesGlob(candidate, effectivePattern)
+ && !path.matchesGlob(visibleCandidate, effectivePattern)) return;
+ lines.push(path.join(cwd, relative));
+ if (lines.length >= limit && !child.killed) {
+ stoppedAtLimit = true;
+ child.kill();
+ }
+ });
+ child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
+ child.on('error', (error) => {
+ reader.close();
+ settle(() => reject(new Error('Failed to run Cindy ripgrep: ' + error.message)));
+ });
+ child.on('close', (code) => {
+ reader.close();
+ if (!stoppedAtLimit && code !== 0 && code !== 1) {
+ const message = stderr.trim() || 'ripgrep exited with code ' + String(code);
+ settle(() => reject(new Error(message)));
+ return;
+ }
+ settle(() => resolve(lines));
+ });
+ });
+}
+
export default async function cindyBridge(pi: any) {
+ // 主 Pi 不传 --tools:那个白名单也会筛掉动态 MCP 与 subagent。改由 bridge 注册
+ // 专用只读工具;子代理仍用自己的 read,grep,find,ls 白名单收紧能力面。
+ const grepTool = createGrepTool(process.cwd());
+ pi.registerTool({
+ ...grepTool,
+ execute: async (id: string, params: unknown, signal: AbortSignal, onUpdate: unknown) => {
+ // Fail closed before Pi upstream ensureTool can fall back to cwd/PATH lookup.
+ managedRipgrepPath();
+ return grepTool.execute(id, params as any, signal, onUpdate as any);
+ },
+ });
+
+ // 覆盖内置 find:保留 Pi 原生 schema、渲染、截断和权限工具名,只替换文件枚举后端。
+ const findTool = createFindTool(process.cwd(), {
+ operations: {
+ exists: async (candidate: string) => {
+ try {
+ await stat(candidate);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ glob: rgGlob,
+ },
+ });
+ pi.registerTool({
+ ...findTool,
+ execute: async (id: string, params: unknown, signal: AbortSignal, onUpdate: unknown) =>
+ findTool.execute(id, params as any, signal, onUpdate as any),
+ });
+
+ const lsTool = createLsTool(process.cwd());
+ pi.registerTool({
+ ...lsTool,
+ execute: async (id: string, params: unknown, signal: AbortSignal, onUpdate: unknown) =>
+ lsTool.execute(id, params as any, signal, onUpdate as any),
+ });
+
// 覆盖内置 bash:保持 Pi 原生执行/截断/取消语义,只在 spawn 边界剥离 Cindy
// 私密变量。模型仍可正常发请求,但它执行的任意命令拿不到 proxy/MCP/BYOM 凭证。
const bashTool = createBashTool(process.cwd(), {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index c473480370..8dd2d9e152 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -103,6 +103,7 @@ const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';
const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';
const PI_MCP_BRIDGE_ENV = 'CINDY_PI_MCP_BRIDGE';
const PI_SECRET_ENV_NAMES_ENV = 'CINDY_PI_SECRET_ENV_NAMES';
+const PI_MANAGED_RG_PATH_ENV = 'CINDY_PI_MANAGED_RG_PATH';
const PI_IMAGE_INPUT_UNSUPPORTED_CODE = 'PI_IMAGE_INPUT_UNSUPPORTED';
/** 手动压缩 = 一次完整 LLM 摘要调用(大上下文 + 网关排队),远超默认 30s RPC 超时。 */
const PI_COMPACT_TIMEOUT_MS = 600_000;
@@ -178,6 +179,34 @@ function mergeLoopbackNoProxy(env: NodeJS.ProcessEnv): void {
delete env.no_proxy;
}
+/**
+ * 把 host 已校验的 rg 复制到本会话私有 bin。
+ *
+ * Pi 上游 grep 会先从 PI_CODING_AGENT_DIR/bin 解析工具并返回该绝对路径;find bridge
+ * 也直接 spawn 同一路径。不能只改 PATH:Windows executable lookup 会先看 cwd,仓库里的
+ * rg.exe 便可劫持自动放行的只读工具并继承 Pi 父进程凭证。
+ */
+async function stageManagedRipgrep(
+ configHome: string,
+ sourcePath: string | undefined,
+): Promise<string | undefined> {
+ if (!sourcePath) return undefined;
+ if (!path.isAbsolute(sourcePath)) {
+ throw new Error('pi: managed ripgrep path must be absolute');
+ }
+ const sourceStat = await fs.stat(sourcePath);
+ if (!sourceStat.isFile()) {
+ throw new Error('pi: managed ripgrep path must point to a file');
+ }
+
+ const binDir = path.join(configHome, 'bin');
+ const targetPath = path.join(binDir, process.platform === 'win32' ? 'rg.exe' : 'rg');
+ await fs.mkdir(binDir, { recursive: true });
+ await fs.copyFile(sourcePath, targetPath);
+ if (process.platform !== 'win32') await fs.chmod(targetPath, 0o755);
+ return targetPath;
+}
+
/** cindy Effort → pi thinking level(pi 无 ultra;cindy 无 off)。 */
function effortToPiThinkingLevel(effort: Effort): string {
return effort === 'ultra' ? 'max' : effort;
@@ -1102,6 +1131,10 @@ export class PiAgent extends BaseAgent {
if (firstError) throw firstError;
};
try {
+ const managedRipgrepPath = await stageManagedRipgrep(
+ configHome,
+ this.deps.runtimeConfig.managedExecutablePaths?.ripgrep,
+ );
if (opts.sessionId && this.deps.registerPiProxySession) {
const disposer = this.deps.registerPiProxySession(opts.sessionId, proxySessionToken);
if (typeof disposer === 'function') disposeProxySession = disposer;
@@ -1123,6 +1156,8 @@ export class PiAgent extends BaseAgent {
// 只从 bash/模型工具的 spawn 边界剥离;子代理自己的 spawn 不走 bridge 的 bash 钩子,
// 扩展照旧现读快照,能力不受影响。
CINDY_SUBAGENT_ENV.runtimeFile,
+ // 受管工具路径同属控制面:不得让获批 bash 改写/替换后影响后续自动放行的 grep/find。
+ ...(managedRipgrepPath ? [PI_MANAGED_RG_PATH_ENV] : []),
]));
const spawnEnv: NodeJS.ProcessEnv = {
...process.env,
@@ -1154,6 +1189,12 @@ export class PiAgent extends BaseAgent {
? { [PI_MCP_BRIDGE_ENV]: JSON.stringify(mcpBridge) }
: {}),
};
+ // 不继承宿主进程里碰巧存在的同名变量;Windows 环境键大小写不敏感,必须先清掉
+ // 所有 casing 再写入 host 校验并 stage 后的唯一绝对路径。
+ for (const key of Object.keys(spawnEnv)) {
+ if (key.toLowerCase() === PI_MANAGED_RG_PATH_ENV.toLowerCase()) delete spawnEnv[key];
+ }
+ if (managedRipgrepPath) spawnEnv[PI_MANAGED_RG_PATH_ENV] = managedRipgrepPath;
mergeLoopbackNoProxy(spawnEnv);
proc = new PiRpcProcess({
binaryPath: this.deps.binaryPath,
diff --git a/packages/maker-core/src/interfaces/runtime-config.ts b/packages/maker-core/src/interfaces/runtime-config.ts
index 1e9d9fbffd..d116e45a52 100644
--- a/packages/maker-core/src/interfaces/runtime-config.ts
+++ b/packages/maker-core/src/interfaces/runtime-config.ts
@@ -100,14 +100,23 @@ export interface AgentRuntimeConfig {
autoCompactThresholdPct?: number;
/**
- * Host-managed executable directories to prepend to the agent subprocess PATH.
+ * Host-managed executable directories to prepend to agent subprocess PATH.
*
- * Used for bundled tools that should win over user/system installations, e.g.
- * desktop-packaged ripgrep. Agent implementations decide which subprocesses
- * consume it; paths should already be absolute and host-validated.
+ * Only agents whose executable lookup is safe for PATH-based discovery should consume this.
+ * PI intentionally does not: Windows may resolve an executable from cwd before PATH.
*/
pathPrepends?: string[];
+ /**
+ * Host-validated executable paths that an agent may stage into its private runtime.
+ *
+ * These are explicit paths rather than PATH entries: read-only tools can otherwise
+ * execute a same-named program from an untrusted working directory on Windows.
+ */
+ managedExecutablePaths?: Readonly<{
+ ripgrep?: string;
+ }>;
+
/**
* 宿主产品级 system prompt 注入(host 层)。
* 与 engine 内置 (agents/{vendor}/system-prompt-append.ts) 和 per-call 外部