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: 3 codex P1 — env-file 关停清理、远端权限 hash、远端附件内联

yanb29cbdc16bbf
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 6f20314f10..1c8255d066 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
@@ -1261,4 +1261,111 @@ describe('Pi provider-aware model routing', () => {
// 未走到 spawn(transport 从未创建)。
expect(captured.args).toEqual([]);
});
+
+ it('hashes the remote permission snapshot into spawn env so a later Full-access attach restarts', async () => {
+ const remoteStub: import('../transport.js').PiTransport = {
+ writeLine: async () => {},
+ onLine: () => () => {},
+ onStderr: () => () => {},
+ onClose: () => () => {},
+ close: async () => {},
+ pid: 4321,
+ isClosed: () => false,
+ remoteBinaryPath: '/remote/pi',
+ killRemoteSession: async () => {},
+ };
+ const capturedRemoteEnvs: Array<Record<string, string | undefined>> = [];
+ const remoteFileOps = {
+ mkdirp: async () => {},
+ writeFile: async () => {},
+ stat: async () => ({ isFile: true }),
+ rm: async () => {},
+ listDir: async () => [],
+ };
+ const startRemote = async (permissionMode: 'ask' | 'bypassPermissions') => {
+ const base = byomDeps(async () => ({ providers: [], env: {} }));
+ const agent = new PiAgent({
+ ...base,
+ runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
+ resolveRemotePiBinaryPath: async () => '/remote/pi',
+ getRemotePiTransport: async (_hostId, opts) => {
+ capturedRemoteEnvs.push({ ...(opts.env ?? {}) });
+ return remoteStub;
+ },
+ getRemotePiFileOps: () => remoteFileOps,
+ });
+ const handle = await agent.startSession({
+ sessionId: 'remote-perm-hash',
+ workingDir: cwd,
+ model: 'local-model',
+ permissionMode,
+ remoteHostId: 'remote-host',
+ });
+ await handle.close();
+ };
+
+ await startRemote('ask');
+ await startRemote('bypassPermissions');
+ expect(capturedRemoteEnvs).toHaveLength(2);
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_HASH).toMatch(/^[0-9a-f]{16}$/);
+ expect(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH).toMatch(/^[0-9a-f]{16}$/);
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_HASH)
+ .not.toBe(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH);
+ expect(capturedRemoteEnvs[0]!.CINDY_PI_PERMISSION_FILE)
+ .toBe(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_FILE);
+ });
+
+ it('inlines remote text attachments and rejects local path mentions before dispatch', async () => {
+ const remoteStub: import('../transport.js').PiTransport = {
+ writeLine: async () => {},
+ onLine: () => () => {},
+ onStderr: () => () => {},
+ onClose: () => () => {},
+ close: async () => {},
+ pid: 4321,
+ isClosed: () => false,
+ remoteBinaryPath: '/remote/pi',
+ killRemoteSession: async () => {},
+ };
+ const attachment = path.join(cwd, 'notes.txt');
+ writeFileSync(attachment, 'remote-inline-body');
+ const base = byomDeps(async () => ({ providers: [], env: {} }));
+ const agent = new PiAgent({
+ ...base,
+ runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
+ resolveRemotePiBinaryPath: async () => '/remote/pi',
+ getRemotePiTransport: async () => remoteStub,
+ getRemotePiFileOps: () => ({
+ mkdirp: async () => {},
+ writeFile: async () => {},
+ stat: async () => ({ isFile: true }),
+ rm: async () => {},
+ listDir: async () => [],
+ }),
+ });
+ const handle = await agent.startSession({
+ sessionId: 'remote-attach',
+ workingDir: cwd,
+ model: 'local-model',
+ remoteHostId: 'remote-host',
+ });
+
+ captured.requests.length = 0;
+ await handle.send({
+ type: 'user',
+ content: [
+ { type: 'text', text: 'please read this' },
+ { type: 'file', path: attachment },
+ ],
+ });
+ const prompt = captured.requests.find((r) => r.type === 'prompt');
+ expect(String(prompt?.message)).toContain('remote-inline-body');
+ expect(String(prompt?.message)).not.toContain(attachment);
+
+ await expect(handle.send({
+ type: 'user',
+ content: [{ type: 'mention', name: 'local-dir', path: cwd, kind: 'dir' }],
+ })).rejects.toThrow(/cannot use local path mentions/);
+ await handle.close();
+ });
});
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index f9ee03922e..883c4570f7 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -152,6 +152,10 @@ const PI_SECRET_ENV_NAMES_ENV = 'CINDY_PI_SECRET_ENV_NAMES';
const PI_MANAGED_RG_PATH_ENV = 'CINDY_PI_MANAGED_RG_PATH';
/** 轮 42 P1:models.json 内容指纹(远端 daemon 启动身份的一部分, 值无凭证)。 */
const PI_MODELS_JSON_HASH_ENV = 'CINDY_PI_MODELS_JSON_HASH';
+/** 远端权限/Extra Dir 快照指纹 —— 档位变则 envHash 变, daemon 重启而非覆盖热读文件。 */
+const PI_PERMISSION_HASH_ENV = 'CINDY_PI_PERMISSION_HASH';
+/** 远端附件内联上限:超过则 fail-before-dispatch, 不静默截断。 */
+const REMOTE_PI_ATTACHMENT_MAX_BYTES = 256 * 1024;
/**
* baseUrl 是否指向本机 loopback(远端会话不可达)。与 host 侧 isLoopbackUrl 同口径:
@@ -375,10 +379,14 @@ interface PiPromptImage {
}
/** UserMessage → pi prompt 文本 + images。mention/file 以路径文本引用。 */
-async function buildPiPrompt(message: UserMessage): Promise<{ text: string; images: PiPromptImage[] }> {
+async function buildPiPrompt(
+ message: UserMessage,
+ opts?: { remote?: boolean },
+): Promise<{ text: string; images: PiPromptImage[] }> {
if (typeof message.content === 'string') {
return { text: message.content, images: [] };
}
+ const remote = Boolean(opts?.remote);
const textParts: string[] = [];
const images: PiPromptImage[] = [];
for (const block of message.content as UserContentBlock[]) {
@@ -387,9 +395,42 @@ async function buildPiPrompt(message: UserMessage): Promise<{ text: string; imag
textParts.push(block.text);
break;
case 'mention':
+ // 远端 Pi 读不到本机路径; mention 只是引用提示, 不内联目录/文件内容。
+ if (remote) {
+ throw new Error(
+ `pi: remote sessions cannot use local path mentions (${block.path}) — the remote Pi process cannot read desktop paths`,
+ );
+ }
textParts.push(`\`${block.path}\``);
break;
case 'file':
+ if (remote) {
+ // 远端 Pi 读不到本机路径。内联文本内容;二进制/超大文件 fail-before-dispatch,
+ // 避免 turn 被接受但附件静默丢失,或远端同路径文件被误读。
+ let data: Buffer;
+ try {
+ data = await fs.readFile(block.path);
+ } catch (err) {
+ throw new Error(
+ `pi: failed to read file attachment ${block.path}: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (data.length > REMOTE_PI_ATTACHMENT_MAX_BYTES) {
+ throw new Error(
+ `pi: remote file attachment ${block.path} is ${data.length} bytes (limit ${REMOTE_PI_ATTACHMENT_MAX_BYTES}) — upload to the remote host or send a smaller file`,
+ );
+ }
+ const name = path.basename(block.path);
+ if (data.includes(0)) {
+ throw new Error(
+ `pi: remote sessions cannot inline binary file attachments (${name}) — upload the file to the remote host first`,
+ );
+ }
+ textParts.push(
+ `Attached file \`${name}\` (inlined from desktop; remote Pi cannot read the original path):\n\`\`\`\n${data.toString('utf8')}\n\`\`\``,
+ );
+ break;
+ }
textParts.push(`Attached file (read-only reference): \`${block.path}\``);
break;
case 'image': {
@@ -1139,8 +1180,9 @@ export class PiAgent extends BaseAgent {
// 代价是文件按 startSession 而非 sessionId 唯一 → 必须显式回收,见 cleanupRuntimeFiles。
// 轮 42 P1:远端会话用稳定派生(同 session 重连复用路径 → env 稳定 →
// envHash 稳定 → attach 保活); 本地保持 nonce 隔离(多实例并发启动)。
- // 远端多实例并发同 session 的覆盖竞态由 daemon envHash 串行化保证
- // (kill 先于 spawn)。
+ // 远端同路径热读文件的覆盖:权限/Extra Dir 快照 hash 进 spawn env
+ // (CINDY_PI_PERMISSION_HASH) —— 档位变则 envHash 变, daemon 先 kill 再 spawn,
+ // 不让另一实例把 Full Access 写进仍在跑的 Pi。
const runtimeInstanceId = remote
? stableSessionPathSegment(sid)
: randomBytes(8).toString('hex');
@@ -1767,7 +1809,13 @@ export class PiAgent extends BaseAgent {
// 轮 42 P1:models.json 内容 hash 进 spawn env —— 远端 daemon 的 envHash
// 覆盖它, 配置变更(models.json 改写)时条件 restart 判定生效, 不误 attach。
// 仅远端注入(本地无 envHash 机制); 值本身无凭证(只是内容指纹)。
- if (remote) spawnEnv[PI_MODELS_JSON_HASH_ENV] = modelsJsonHash;
+ if (remote) {
+ spawnEnv[PI_MODELS_JSON_HASH_ENV] = modelsJsonHash;
+ spawnEnv[PI_PERMISSION_HASH_ENV] = createHash('sha256')
+ .update(JSON.stringify(requestedPermissionSnapshot))
+ .digest('hex')
+ .slice(0, 16);
+ }
mergeLoopbackNoProxy(spawnEnv);
const { transport } = await this.createTransport(
{ args, cwd: opts.workingDir, env: spawnEnv, sessionId: opts.sessionId },
@@ -2395,7 +2443,7 @@ export class PiAgent extends BaseAgent {
reviewReadGrants,
);
}
- const { text, images } = await buildPiPrompt(message);
+ const { text, images } = await buildPiPrompt(message, { remote });
rejectIfCancelled(sendOpts, 'send');
assertImageInputSupported(images);
setAutoReviewIntent(message.content);
@@ -2434,7 +2482,7 @@ export class PiAgent extends BaseAgent {
reviewReadGrants,
);
}
- const { text, images } = await buildPiPrompt(message);
+ const { text, images } = await buildPiPrompt(message, { remote });
rejectIfCancelled(sendOpts, 'steer');
assertImageInputSupported(images);
setAutoReviewIntent(message.content);
diff --git a/packages/maker-pi-manager/src/__tests__/session-registry.test.ts b/packages/maker-pi-manager/src/__tests__/session-registry.test.ts
index 0808b6fef7..64f66c12ae 100644
--- a/packages/maker-pi-manager/src/__tests__/session-registry.test.ts
+++ b/packages/maker-pi-manager/src/__tests__/session-registry.test.ts
@@ -984,6 +984,27 @@ describe('shuttingDown', () => {
expect(mockSpawn).not.toHaveBeenCalled();
expect(registry.list()).toHaveLength(0);
});
+
+ it('awaits env-file removal when shutdown races after the credential file is written', async () => {
+ const { registry, tmpDir } = await createRegistry();
+ cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+
+ const envFile = path.join(tmpDir, 'envs', 'env-race-shutdown');
+ const origRename = fsPromises.rename.bind(fsPromises);
+ const renameSpy = vi.spyOn(fsPromises, 'rename').mockImplementation(async (src, dest, ...rest) => {
+ const result = await origRename(src, dest, ...rest);
+ if (String(dest) === envFile) registry.beginShutdown();
+ return result;
+ });
+
+ await expect(
+ registry.ensure('race-shutdown', 'cmd', { CINDY_PI_API_KEY: 'gateway-secret' }, 'h1', false),
+ ).rejects.toThrow(/pi-manager is shutting down/);
+
+ expect(fs.existsSync(envFile)).toBe(false);
+ expect(mockSpawn).not.toHaveBeenCalled();
+ renameSpy.mockRestore();
+ });
});
// ── 7. sessionId / env 校验 ──────────────────────────────
diff --git a/packages/maker-pi-manager/src/session-registry.ts b/packages/maker-pi-manager/src/session-registry.ts
index 2d73ccce51..9240f00715 100644
--- a/packages/maker-pi-manager/src/session-registry.ts
+++ b/packages/maker-pi-manager/src/session-registry.ts
@@ -437,8 +437,10 @@ export class PiSessionRegistry {
}
// 关停守卫提前(spawn 前, 不创建再销毁 —— 自审轮 6 L-3)。
+ // 必须 await 删凭证文件:shutdownAll 只等 pending spawn promise,
+ // fire-and-forget rm 会在 daemon process.exit 前残留 env-<id>(含 gateway/BYOM key)。
if (this.shuttingDown) {
- void fsPromises.rm(envFile, { force: true }).catch(() => {});
+ await fsPromises.rm(envFile, { force: true }).catch(() => {});
throw makeServerError('INTERNAL', 'pi-manager is shutting down');
}