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): 去掉静默拒路径并修好 RPC leftover 与 subagent rg (#4518)

Chris Zhang618cc8d25e15
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 0c55e93b79..e4e0fd31ca 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -12,6 +12,7 @@ import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
+import { resolveCanonicalSessionPath } from '@cindy/mcps';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
GHOST_MANIFEST_SUMMARY_MAX_CHARS,
@@ -116,6 +117,15 @@ function packGhostDir(
return packGhostDirRaw(dir, { sessionWorkdir: workDir, ...options });
}
+async function hostAuthorizedOutside(dir: string, isCurrent: () => boolean = () => true) {
+ const authorizedDir = await resolveCanonicalSessionPath(path.parse(path.resolve(dir)).root, dir);
+ return {
+ allowOutsideWorkdir: true as const,
+ authorizedDir,
+ isCurrent,
+ };
+}
+
async function expectSameExistingRealPath(actual: string, expected: string): Promise<void> {
const normalize = (value: string) => (process.platform === 'win32' ? value.toLowerCase() : value);
const [actualReal, expectedReal] = await Promise.all([
@@ -370,6 +380,89 @@ describe('packGhostDir', () => {
}
});
+ it('packs a host-authorized source outside the session workdir', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': 'export default {}',
+ });
+ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-granted-'));
+ try {
+ const outsideDir = path.join(outsideRoot, 'src');
+ await fs.promises.cp(dir, outsideDir, { recursive: true });
+ const packed = await packGhostDirRaw(outsideDir, {
+ sessionWorkdir: workDir,
+ ...(await hostAuthorizedOutside(outsideDir)),
+ });
+ expect(packed).toMatchObject({ ok: true });
+ if (!packed.ok) return;
+ await expect(fs.promises.access(path.join(outsideDir, 'demo-1.0.0.cindy'))).resolves.toBeUndefined();
+
+ await expect(packGhostDirRaw(outsideDir, {
+ sessionWorkdir: workDir,
+ allowOutsideWorkdir: true,
+ })).resolves.toMatchObject({ ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR' });
+ await expect(packGhostDirRaw(outsideDir, {
+ sessionWorkdir: workDir,
+ allowOutsideWorkdir: true,
+ authorizedDir: path.join(outsideRoot, 'other-src'),
+ isCurrent: () => true,
+ })).resolves.toMatchObject({ ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR' });
+ } finally {
+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });
+ }
+ });
+
+ it('still rejects Host-managed roots after outside-workdir authorization', async () => {
+ const managedRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-managed-'));
+ try {
+ const installedDir = path.join(managedRoot, 'demo');
+ await fs.promises.mkdir(installedDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(installedDir, 'ghost.json'),
+ JSON.stringify(GOOD_MANIFEST),
+ );
+ await fs.promises.writeFile(path.join(installedDir, 'main.js'), '// installed');
+ await expect(
+ packGhostDirRaw(installedDir, {
+ sessionWorkdir: workDir,
+ forbiddenRootDirs: [managedRoot],
+ ...(await hostAuthorizedOutside(installedDir)),
+ }),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
+ });
+ } finally {
+ await fs.promises.rm(managedRoot, { recursive: true, force: true });
+ }
+ });
+
+ it('does not write a package after the outside grant expires', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': 'export default {}',
+ });
+ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-stale-grant-'));
+ try {
+ const outsideDir = path.join(outsideRoot, 'src');
+ await fs.promises.cp(dir, outsideDir, { recursive: true });
+ await expect(packGhostDirRaw(outsideDir, {
+ sessionWorkdir: workDir,
+ ...(await hostAuthorizedOutside(outsideDir, () => false)),
+ })).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(fs.existsSync(path.join(outsideDir, 'demo-1.0.0.cindy'))).toBe(false);
+
+ let remaining = 1;
+ await expect(packGhostDirRaw(outsideDir, {
+ sessionWorkdir: workDir,
+ ...(await hostAuthorizedOutside(outsideDir, () => remaining-- > 0)),
+ })).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(fs.existsSync(path.join(outsideDir, 'demo-1.0.0.cindy'))).toBe(false);
+ } finally {
+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });
+ }
+ });
+
it('rejects Host-managed roots, descendants, case aliases, and junction aliases', async () => {
const managedRoot = path.join(workDir, 'managed');
const installedDir = path.join(managedRoot, 'demo');
@@ -1493,6 +1586,91 @@ describe('scaffoldGhostDir', () => {
await fs.promises.rm(outside, { recursive: true, force: true });
}
});
+
+ it('scaffolds outside the session workdir only after host authorization', async () => {
+ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-scaffold-out-'));
+ const dir = path.join(outsideRoot, 'plugin');
+ try {
+ await expect(
+ scaffoldGhostDir(
+ { dir, template: 'plain', id: 'out-plugin', name: 'Out plugin' },
+ { sessionWorkdir: workDir },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
+ expect(fs.existsSync(dir)).toBe(false);
+
+ const authorizedDir = path.join(await fs.promises.realpath(outsideRoot), 'plugin');
+ await expect(
+ scaffoldGhostDir(
+ { dir, template: 'plain', id: 'out-plugin', name: 'Out plugin' },
+ { sessionWorkdir: workDir, allowOutsideWorkdir: true },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
+ expect(fs.existsSync(dir)).toBe(false);
+
+ await expect(
+ scaffoldGhostDir(
+ { dir, template: 'plain', id: 'out-plugin', name: 'Out plugin' },
+ { sessionWorkdir: workDir, ...(await hostAuthorizedOutside(authorizedDir)) },
+ ),
+ ).resolves.toMatchObject({ ok: true, dir: authorizedDir });
+ expect(fs.existsSync(path.join(authorizedDir, 'ghost.json'))).toBe(true);
+
+ const swapped = path.join(outsideRoot, 'swapped');
+ await expect(
+ scaffoldGhostDir(
+ { dir: swapped, template: 'plain', id: 'swap-plugin', name: 'Swap plugin' },
+ { sessionWorkdir: workDir, allowOutsideWorkdir: true, authorizedDir, isCurrent: () => true },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
+ expect(fs.existsSync(swapped)).toBe(false);
+
+ const staleDir = path.join(outsideRoot, 'stale-plugin');
+ const writeScaffold = vi.fn(testScaffoldWriter);
+ await expect(
+ scaffoldGhostDirRaw(
+ {
+ dir: staleDir,
+ template: 'plain',
+ id: 'stale-plugin',
+ name: 'Stale plugin',
+ minCindyVersion: '1.2.3',
+ },
+ {
+ sessionWorkdir: workDir,
+ ...(await hostAuthorizedOutside(staleDir, () => false)),
+ writeScaffold,
+ },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(writeScaffold).not.toHaveBeenCalled();
+ expect(fs.existsSync(staleDir)).toBe(false);
+
+ const expiredAfterIdentity = path.join(outsideRoot, 'expired-after-identity');
+ const lateWriter = vi.fn(testScaffoldWriter);
+ let remaining = 1;
+ await expect(
+ scaffoldGhostDirRaw(
+ {
+ dir: expiredAfterIdentity,
+ template: 'plain',
+ id: 'expired-after-identity',
+ name: 'Expired after identity',
+ minCindyVersion: '1.2.3',
+ },
+ {
+ sessionWorkdir: workDir,
+ ...(await hostAuthorizedOutside(expiredAfterIdentity, () => remaining-- > 0)),
+ writeScaffold: lateWriter,
+ },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(lateWriter).not.toHaveBeenCalled();
+ expect(fs.existsSync(expiredAfterIdentity)).toBe(false);
+ } finally {
+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });
+ }
+ });
});
describe('FORGE_GUIDE', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index cedd16f7ba..e8e426201d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -188,6 +188,8 @@ describe('market Ghost session boundary', () => {
// 只有确认旧进程退出,才切断旧市场的自动更新路由;等待失败时保留原路由,
// 也不会尝试恢复第二份 resident 进程。
expect(detachIndex).toBeGreaterThan(stopAndWaitIndex);
+ expect(helperBody.indexOf('if (isCurrent?.() === false)')).toBeGreaterThan(-1);
+ expect(helperBody.indexOf('if (isCurrent?.() === false)')).toBeLessThan(stopAndWaitIndex);
expect(oauthLockIndex).toBeGreaterThan(detachIndex);
expect(managerUpdateIndex).toBeGreaterThan(oauthLockIndex);
expect(helperBody).toContain('marketLedger.restoreInstallation(');
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index a1c55c0fe6..8a5d58880f 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -176,7 +176,8 @@ export type ForgePackResult =
| 'INTERNAL'
// Forge 打包出口的会话 workdir 门 + 受管根禁区(C-4 + #7)。
| 'SOURCE_OUTSIDE_WORKDIR'
- | 'SOURCE_IS_INSTALLED_PLUGIN';
+ | 'SOURCE_IS_INSTALLED_PLUGIN'
+ | 'PERMISSION_DENIED';
message: string;
};
@@ -199,7 +200,7 @@ export type ForgeScaffoldResult =
}
| {
ok: false;
- errorCode: 'INVALID_INPUT' | 'TARGET_EXISTS' | 'INTERNAL';
+ errorCode: 'INVALID_INPUT' | 'TARGET_EXISTS' | 'PERMISSION_DENIED' | 'INTERNAL';
message: string;
};
@@ -228,12 +229,29 @@ export interface ForgeScaffoldWriteRequest {
}
export type ForgeScaffoldWriteResult =
- { ok: true } | { ok: false; errorCode: 'TARGET_EXISTS' | 'INTERNAL'; message: string };
+ { ok: true } | { ok: false; errorCode: 'TARGET_EXISTS' | 'INTERNAL' | 'PERMISSION_DENIED'; message: string };
export type ForgeScaffoldWriter = (
request: ForgeScaffoldWriteRequest,
) => Promise<ForgeScaffoldWriteResult>;
+const FORGE_OUTSIDE_GRANT_STALE_MESSAGE =
+ 'Task or Plan permissions changed; retry with the current scope.';
+
+type ForgeOutsideGrantOptions = {
+ allowOutsideWorkdir?: boolean;
+ authorizedDir?: string;
+ isCurrent?: () => boolean;
+};
+
+function staleOutsideForgeGrant(
+ options?: ForgeOutsideGrantOptions,
+): { ok: false; errorCode: 'PERMISSION_DENIED'; message: string } | null {
+ if (!options?.allowOutsideWorkdir || !options.authorizedDir) return null;
+ if (options.isCurrent?.() === true) return null;
+ return { ok: false, errorCode: 'PERMISSION_DENIED', message: FORGE_OUTSIDE_GRANT_STALE_MESSAGE };
+}
+
/** 生成插件清单;先走正式校验,再允许任何文件落盘。 */
function scaffoldManifest(input: ForgeScaffoldInput): Record<string, unknown> {
const common = {
@@ -558,6 +576,9 @@ export async function scaffoldGhostDir(
sessionWorkdir?: string | null;
forbiddenRootDirs?: readonly string[];
writeScaffold?: ForgeScaffoldWriter;
+ allowOutsideWorkdir?: boolean;
+ authorizedDir?: string;
+ isCurrent?: () => boolean;
},
): Promise<ForgeScaffoldResult> {
const template = input.template;
@@ -592,6 +613,8 @@ export async function scaffoldGhostDir(
message: '会话工作目录不存在,无法确定骨架输出位置',
};
}
+ const staleGrant = staleOutsideForgeGrant(options);
+ if (staleGrant) return staleGrant;
let realTarget: string;
try {
realTarget = await resolveThroughExistingAncestor(resolved);
@@ -602,8 +625,18 @@ export async function scaffoldGhostDir(
message: err instanceof Error ? err.message : String(err),
};
}
- if (!realTarget.startsWith(`${realWorkdir}${path.sep}`) && realTarget !== realWorkdir) {
- return { ok: false, errorCode: 'INVALID_INPUT', message: 'dir 必须在当前会话工作目录内' };
+ if (
+ !realTarget.startsWith(`${realWorkdir}${path.sep}`)
+ && realTarget !== realWorkdir
+ ) {
+ if (
+ !options?.allowOutsideWorkdir
+ || !options.authorizedDir
+ || !isPathInsideDir(options.authorizedDir, realTarget)
+ || !isPathInsideDir(realTarget, options.authorizedDir)
+ ) {
+ return { ok: false, errorCode: 'INVALID_INPUT', message: 'dir 必须在当前会话工作目录内' };
+ }
}
for (const forbiddenRoot of options?.forbiddenRootDirs ?? []) {
let resolvedForbiddenRoot: string;
@@ -631,7 +664,9 @@ export async function scaffoldGhostDir(
};
}
}
- const targetDir = path.resolve(input.dir);
+ const targetDir = options?.allowOutsideWorkdir && options.authorizedDir
+ ? path.resolve(options.authorizedDir)
+ : path.resolve(input.dir);
const files = scaffoldFiles(input);
const manifestRaw = files[GHOST_MANIFEST_FILE];
if (typeof manifestRaw !== 'string') {
@@ -676,15 +711,21 @@ export async function scaffoldGhostDir(
return {
ok: false,
errorCode: 'INVALID_INPUT',
- message: 'dir 的父目录必须是工作目录内已存在的普通目录',
+ message: options?.allowOutsideWorkdir
+ ? 'dir 的父目录必须是已存在的普通目录'
+ : 'dir 的父目录必须是工作目录内已存在的普通目录',
};
}
parentRealPath = await realpathNative(parentDir);
- if ((await pathHasLinkSegment(parentDir)) || !isPathInsideDir(realWorkdir, parentRealPath)) {
+ const parentHasLinkAncestor = await pathHasLinkSegment(parentDir);
+ const parentOutsideWorkdir = !isPathInsideDir(realWorkdir, parentRealPath);
+ if (parentHasLinkAncestor || (parentOutsideWorkdir && !options?.allowOutsideWorkdir)) {
return {
ok: false,
errorCode: 'INVALID_INPUT',
- message: 'dir 的父目录必须是工作目录内已存在且没有链接祖先的普通目录',
+ message: parentHasLinkAncestor
+ ? 'dir 的父目录必须是没有链接祖先的普通目录'
+ : 'dir 的父目录必须是工作目录内已存在且没有链接祖先的普通目录',
};
}
} catch (err) {
@@ -692,7 +733,9 @@ export async function scaffoldGhostDir(
return {
ok: false,
errorCode: 'INVALID_INPUT',
- message: 'dir 的父目录必须先创建,并且必须位于当前工作目录内',
+ message: options?.allowOutsideWorkdir
+ ? 'dir 的父目录必须先创建'
+ : 'dir 的父目录必须先创建,并且必须位于当前工作目录内',
};
}
return {
@@ -710,6 +753,8 @@ export async function scaffoldGhostDir(
message: 'Forge scaffold stable-directory capability is unavailable',
};
}
+ const staleBeforeWrite = staleOutsideForgeGrant(options);
+ if (staleBeforeWrite) return staleBeforeWrite;
const writeResult = await options.writeScaffold({
parentDir,
targetName: path.basename(targetDir),
@@ -1309,11 +1354,26 @@ export async function packGhostDir(
sessionWorkdir?: string | null;
forbiddenRootDirs?: readonly string[];
iconPng?: Buffer;
+ /**
+ * Host already authorized this source via the session permission path
+ * (Full Access / auto-review / user confirm). Forbidden managed roots
+ * still apply. `authorizedDir` is the granted canonical identity and is
+ * required whenever `allowOutsideWorkdir` is true.
+ */
+ allowOutsideWorkdir?: boolean;
+ authorizedDir?: string;
+ /**
+ * Host grant generation captured at authorize time. Required whenever
+ * `allowOutsideWorkdir` is used with `authorizedDir`; rechecked after the
+ * long pack and immediately before the `.cindy` write.
+ */
+ isCurrent?: () => boolean;
},
): Promise<ForgePackResult> {
- // Forge 打包出口专属安全门(C-4 + #7):source 必须在会话 workdir 内、且不得是受管根
- //(已装插件 / 批准状态根 / seed 根,双向判定)。算出的 realSourceDir 作为
- // buildGhostPackage 的 expectedRealDir 上游锚点——正是它要求"由上游校验后传入"的那份。
+ // Forge 打包出口专属安全门(C-4 + #7):source 默认必须在会话 workdir 内;Host 已按
+ // 当前会话权限放行后可带 allowOutsideWorkdir。受管根(已装插件 / 批准状态根 /
+ // seed 根)始终双向拒绝。算出的 realSourceDir 作为 buildGhostPackage 的
+ // expectedRealDir 上游锚点——正是它要求"由上游校验后传入"的那份。
const workdir = options?.sessionWorkdir;
if (!workdir) {
return {
@@ -1332,6 +1392,8 @@ export async function packGhostDir(
message: 'The current session workdir does not exist',
};
}
+ const staleGrant = staleOutsideForgeGrant(options);
+ if (staleGrant) return staleGrant;
let realSourceDir: string;
try {
realSourceDir = await realpathNative(dir);
@@ -1339,11 +1401,18 @@ export async function packGhostDir(
return { ok: false, errorCode: 'DIR_NOT_FOUND', message: `目录不存在:${dir}` };
}
if (!isPathInsideDir(realWorkdir, realSourceDir)) {
- return {
- ok: false,
- errorCode: 'SOURCE_OUTSIDE_WORKDIR',
- message: 'Forge source must be inside the current session workdir',
- };
+ if (
+ !options?.allowOutsideWorkdir
+ || !options.authorizedDir
+ || !isPathInsideDir(options.authorizedDir, realSourceDir)
+ || !isPathInsideDir(realSourceDir, options.authorizedDir)
+ ) {
+ return {
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ message: 'Forge source must be inside the current session workdir',
+ };
+ }
}
for (const forbiddenRoot of options?.forbiddenRootDirs ?? []) {
const resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);
@@ -1380,6 +1449,8 @@ export async function packGhostDir(
realSourceDir,
`${built.manifest.id}-${built.manifest.version}.cindy`,
);
+ const staleBeforeWrite = staleOutsideForgeGrant(options);
+ if (staleBeforeWrite) return staleBeforeWrite;
try {
await fs.promises.writeFile(cindyPath, built.buf);
} catch (err) {
@@ -1550,8 +1621,9 @@ Cindy 会默认把自身版本写进这份具体插件的 \`minCindyVersion\`;
配置和结果呈现,生成请求由当前 Agent 调用 Core media 工具(§2、§4.0.4)。
问完后把选择复述成一份简短设计小结(要解决的问题/目标用户/交互流程/所选形态/
-权限边界/验收标准),并顺带说明源码会放在工作目录的哪个文件夹——位置不需要用户选
-(骨架只能建在会话工作目录内,装入后归主机统一管理),让用户知情即可。用户确认
+权限边界/验收标准),并顺带说明源码会放在工作目录的哪个文件夹——工作目录内直接建;
+工作目录外(例如相邻 worktree)走当前会话权限,不因目录边界悄悄失败。位置不需要用户选
+(装入后归主机统一管理),让用户知情即可。用户确认
小结后再动手。**修改现有意识同样适用**:先读现有 ghost.json 与源码,列出改动会
影响哪些已选形态,再让用户确认。
@@ -4513,19 +4585,21 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件
### 7.2 打包、安装与验证
-1. 新插件先调 \`ghost_forge_scaffold\` 生成骨架,或把已有源码放在用户工作目录下的
- 一个文件夹里(如 \`my-ghost/\`);脚手架目标必须是新目录,绝不覆盖已有文件,
- 其父目录必须是工作目录内已存在的普通目录;也不能落在已安装插件目录或 Host 状态目录内(会被拒,理由同下一条);
- **Forge 源码必须是当前会话工作目录里的独立作者目录**。已安装插件目录以及
- Host 管理的状态目录都不是源码区,禁止直接修改、打包或用路径别名绕过;若要继续
- 开发已有插件,先把源码复制/迁出到工作目录中的新目录,再从该副本制作;
+1. 新插件先调 \`ghost_forge_scaffold\` 生成骨架,或指向已有源码目录(如 \`my-ghost/\`);
+ 脚手架目标必须是新目录,绝不覆盖已有文件,其父目录必须已存在且是普通目录;
+ 也不能落在已安装插件目录或 Host 状态目录内(会被拒,理由同下一条);
+ **Forge 源码必须是独立作者目录,不能是已安装插件或 Host 状态目录**。
+ 会话工作目录内直接建/打包;工作目录外(例如相邻 worktree)走当前会话权限:
+ 本地 Full Access 自动放行,Auto 交审阅,Ask 向用户确认,远程或无法核验的会话仍拒绝。
+ 已安装插件目录以及 Host 管理的状态目录都不是源码区,禁止直接修改、打包或用路径别名绕过;
+ 若要继续开发已有插件,先把源码复制/迁出到独立作者目录,再从该副本制作;
2. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——只做校验和打包,不安装或更新插件;
产物落在源码目录里(\`<id>-<version>.cindy\`,同版本覆盖,下次打包自动跳过);
macOS / Linux 源文件的普通 Unix 权限会原样进入包(特殊位会剥除),所以随包本机
可执行程序必须在打包前就设好执行位(例如 \`chmod 755 path/to/program\`),不要靠
文件扩展名或 \`bin/\` 目录让宿主猜测;
若返回 \`SOURCE_IS_INSTALLED_PLUGIN\`,不要重试或换大小写、软链接、junction 绕过,
- 按上一步迁出源码后再打包;也可能返回 \`SOURCE_OUTSIDE_WORKDIR\`(源码不在会话工作目录内);
+ 按上一步迁出源码后再打包;未获会话权限时也可能返回 \`SOURCE_OUTSIDE_WORKDIR\`;
3. 用户明确要求当前 Agent 安装或更新这份源码时,调用
\`ghost_forge_install({ dir: '<绝对路径>' })\`。它会重新校验并打包当前源码,再把这次
产生的确切包直接安装;首次安装会启用,同 id 已安装时原位更新并保留启用状态、配置、
diff --git a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
index 0ac817cfd7..bd49706a44 100644
--- a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
@@ -6,7 +6,7 @@
* 由本桥**弹确认卡**——把「拖图进聊天」这个授权动作换成「点一下允许」,
* 决定权在用户的点击上,被注入的模型只能发起请求、点不了按钮。
* 当前本地活跃会话为 Full Access 时,mcp-integrations/ghost.ts 会在进入本桥前
- * 按实时 Session 状态自动放行;workspace / fs_write 等其它 lane 不受该旁路影响。
+ * 按实时 Session 状态自动放行;workspace / fs_write / forge_source 同样走本桥。
*
* 实现完全对齐 IssueConfirmBridge 的成熟模式:main 侧发起,broadcast 一个
* kind='ghost_grant_confirm' 的 interaction 到 renderer(复用
@@ -29,7 +29,10 @@ import { createDesktopOnlyConfirmationRequestId } from './desktopOnlyConfirmatio
* fs_write = fs 槽写 workdir 文件(会话 permission 为逐条确认档时,
* 意识每次写入前弹卡;同目录本会话批一次,记忆在 fsSlot);workspace =
* workspace 槽在会话 workdir 外的目录下创建/复用会话入口(2026-07-25,
- * 不过户字节,只授权"以此目录为工作区建会话")。
+ * 不过户字节,只授权"以此目录为工作区建会话");
+ * forge_source = Forge 打包/骨架/安装的源码目录在会话 workdir 外(会写入
+ * .cindy 产物、骨架文件,或接着安装启用插件,不是过户票据);
+ * outside_workdir = 文档/电脑等内置工具读写会话 workdir 外的路径。
*/
export type GhostGrantLane =
| 'attachments'
@@ -37,7 +40,9 @@ export type GhostGrantLane =
| 'save_dir'
| 'reveal_path'
| 'fs_write'
- | 'workspace';
+ | 'workspace'
+ | 'forge_source'
+ | 'outside_workdir';
/** 确认卡上逐条展示的过户对象(路径/大小让用户看清自己在授权什么)。 */
export interface GhostGrantFileItem {
@@ -61,6 +66,10 @@ export interface GhostGrantConfirmPayload {
ghostName: string;
lane: GhostGrantLane;
items: GhostGrantFileItem[];
+ /** 发起这次确认的工具名,确认卡用来写清具体副作用。 */
+ sourceTool?: string;
+ /** 这次授权对应的读写方向。 */
+ operation?: 'read' | 'write';
}
export type GhostGrantConfirmDecision =
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index a778908881..51e28512aa 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -5778,7 +5778,11 @@ async function updateLocalGhostPackageLocked(
expectedPackageSha256: string,
expectedInstalledApproval: string,
installOrigin?: 'agent-forge',
+ isCurrent?: () => boolean,
): Promise<InstalledGhost> {
+ if (isCurrent?.() === false) {
+ throwIpcError('PRECONDITION_FAILED', '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。');
+ }
const runtime = getGhostRuntime();
const marketLedger = getPluginMarketLedger().bind(
ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),
@@ -5899,7 +5903,7 @@ async function updateLocalGhostPackageLocked(
*/
export async function installOrUpdateLocalGhostPackageFromForge(
cindyFilePath: string,
- expected: { ghostId: string; packageSha256: string },
+ expected: { ghostId: string; packageSha256: string; isCurrent?: () => boolean },
): Promise<{ ghost: InstalledGhost; action: 'installed' | 'updated' }> {
const manager = getGhostManager();
const inspected = await manager.inspect(cindyFilePath);
@@ -5933,8 +5937,14 @@ export async function installOrUpdateLocalGhostPackageFromForge(
throwIpcError('MUTATION_CANCELLED', '用户取消了企业身份插件安装');
}
}
+ if (expected.isCurrent?.() === false) {
+ throwIpcError('PRECONDITION_FAILED', '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。');
+ }
return withGhostInstallLock(inspected.manifest.id, async () => {
+ if (expected.isCurrent?.() === false) {
+ throwIpcError('PRECONDITION_FAILED', '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。');
+ }
const installed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);
if (!installed) {
return {
@@ -5962,6 +5972,7 @@ export async function installOrUpdateLocalGhostPackageFromForge(
expected.packageSha256,
ghostInstallApprovalToken(installed.approval),
installOrigin,
+ expected.isCurrent,
),
action: 'updated',
};
diff --git a/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts b/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts
index db0178c74e..138af4abaf 100644
--- a/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts
+++ b/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts
@@ -15,5 +15,12 @@ describe('docs output writer packaging', () => {
expect(forge).toContain("entry: 'src/main/doc-tools/docsOutputWriterUtilityProcess.ts'");
expect(controller).toContain("path.join(__dirname, 'docsOutputWriterUtilityProcess.js')");
expect(controller).toContain('cwd: rootDir');
+ expect(controller).toContain('authorizedOutsideWorkdir');
+ expect(controller).toContain('assertDocsOutputGrantCurrent');
+ expect(controller).toContain('await fs.mkdir(lexicalParent, { recursive: true })');
+ expect(controller).toContain('grantedParent.isSymbolicLink()');
+ expect(controller.indexOf('assertDocsOutputGrantCurrent(input)')).toBeLessThan(
+ controller.lastIndexOf("child.postMessage({ type: 'write', request })"),
+ );
});
});
diff --git a/apps/desktop/src/main/doc-tools/docsOutputWriter.ts b/apps/desktop/src/main/doc-tools/docsOutputWriter.ts
index beff2fc610..cc5b7970c3 100644
--- a/apps/desktop/src/main/doc-tools/docsOutputWriter.ts
+++ b/apps/desktop/src/main/doc-tools/docsOutputWriter.ts
@@ -4,7 +4,10 @@ import path from 'node:path';
// eslint-disable-next-line no-restricted-imports -- final writes need a one-shot cwd-bound process, not a database worker.
import { utilityProcess } from 'electron';
-import { DocsPathError, type WriteDocsOutputFn } from '@cindy/mcps';
+import {
+ DocsPathError,
+ type WriteDocsOutputFn,
+} from '@cindy/mcps';
import {
relativeOutputParentPath,
@@ -94,18 +97,47 @@ function throwResultError(
throw new Error(result.message);
}
+function assertDocsOutputGrantCurrent(input: { isCurrent?: () => boolean }): void {
+ if (input.isCurrent?.() === false) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ '任务权限已变化,这次越界路径授权已失效。',
+ '请用当前任务权限重试。',
+ );
+ }
+}
+
export const writeDocsOutput: WriteDocsOutputFn = async (input) => {
+ assertDocsOutputGrantCurrent(input);
const parentDir = path.dirname(input.path);
- const realRoot = await fs.realpath(input.root);
const lexicalParent = path.resolve(parentDir);
const parentRelativePath = relativeOutputParentPath(input.root, lexicalParent);
if (parentRelativePath === null) {
- throw new DocsPathError(
- 'PATH_NOT_ALLOWED',
- `输出目录不在任务工作目录内: ${lexicalParent}`,
- '请改用任务工作目录内的输出路径。',
- );
+ if (!input.authorizedOutsideWorkdir) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `输出目录不在任务工作目录内: ${lexicalParent}`,
+ '请改用任务工作目录内的输出路径。',
+ );
+ }
+ await fs.mkdir(lexicalParent, { recursive: true });
+ const grantedParent = await fs.lstat(lexicalParent, { bigint: true });
+ if (!grantedParent.isDirectory() || grantedParent.isSymbolicLink()) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `授权后的输出目录不再是普通目录: ${lexicalParent}`,
+ '请改用任务工作目录内的输出路径,或确认外部目录在授权后没有被替换。',
+ );
+ }
+ const realParent = await fs.realpath(lexicalParent);
+ return writeDocsOutput({
+ ...input,
+ path: path.join(realParent, path.basename(input.path)),
+ root: realParent,
+ authorizedOutsideWorkdir: false,
+ });
}
+ const realRoot = await fs.realpath(input.root);
const rootStat = await fs.lstat(realRoot, { bigint: true });
if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
throw new DocsPathError(
@@ -185,7 +217,14 @@ export const writeDocsOutput: WriteDocsOutputFn = async (input) => {
(message as { type?: unknown }).type === 'ready'
) {
ready = true;
- child.postMessage({ type: 'write', request });
+ void (async () => {
+ try {
+ assertDocsOutputGrantCurrent(input);
+ child.postMessage({ type: 'write', request });
+ } catch (error) {
+ finish(error);
+ }
+ })();
return;
}
const result = parseResult(message);
diff --git a/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts b/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts
index 88c3c6cb81..0a3d400a70 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts
@@ -310,10 +310,8 @@ describe('killRemotePiManagerSession sessionId validation (sync rejection)', ()
});
// ---------------------------------------------------------------------------
-// 轮 40-w5 HIGH:SSH stdout 分帧缓冲的 OOM 守卫 —— 远端输出无换行字节流超过
-// 16MB(与本地 attachJsonlReader 对齐的硬上限)时必须关闭 transport, 而不是
-// 让主进程内存随远端字节流无界增长。用直连模式 + fake ExecStreamHandle 驱动
-// onStdoutBytes, 不依赖真实 SSH。
+// SSH stdout 分帧缓冲的 OOM 守卫 —— 远端输出无换行字节流超过 16MB 时丢掉当前
+// 行并resync, 不关 transport。合法 get_entries 带图历史可以超过该上限。
// ---------------------------------------------------------------------------
function fakeLogger() {
const logger = {
@@ -342,7 +340,7 @@ describe('SSH stdout buffer overflow guard', () => {
return { handlers, handle };
}
- it('closes the transport when remote streams >16MB without a newline', async () => {
+ it('resyncs after an oversized unterminated line instead of closing the transport', async () => {
const execStream = vi.fn();
const host = { id: 'test-host', execStream } as unknown as RemoteHost;
const { handlers, handle } = fakeChannel();
@@ -356,20 +354,24 @@ describe('SSH stdout buffer overflow guard', () => {
env: {},
logger: fakeLogger() as never,
});
+ const lines: string[] = [];
+ const oversized: unknown[] = [];
+ transport.onLine((line) => lines.push(line));
+ transport.onOversizedFrame?.(() => oversized.push(true));
const closed: PiTransportCloseInfo[] = [];
transport.onClose((info) => closed.push(info));
// 等 async IIFE 完成 channel 建立并注册 handlers。
await vi.waitFor(() => expect(handlers.onStdoutBytes).toBeDefined());
- // 单块无换行字节流超过 16MB 上限。
handlers.onStdoutBytes!(Buffer.alloc(16 * 1024 * 1024 + 1, 0x61));
+ handlers.onStdoutBytes!(Buffer.from('residual-base64-fragment\n{"ok":1}\n'));
- await vi.waitFor(() => expect(closed.length).toBe(1));
- expect(closed[0].reason).toMatch(/buffer overflow/);
- expect(handle.kill).toHaveBeenCalled(); // fireClose 关闭 channel
- // transport 已关闭:后续写入必须 reject。
- await expect(transport.writeLine('{"type":"request"}')).rejects.toThrow(/closed/);
+ expect(closed).toHaveLength(0);
+ expect(handle.kill).not.toHaveBeenCalled();
+ expect(oversized).toHaveLength(1);
+ expect(lines).toEqual(['{"ok":1}']);
+ await expect(transport.writeLine('{"type":"request"}')).resolves.toBeUndefined();
});
it('does not trip the guard on legitimately large line-framed output', async () => {
diff --git a/apps/desktop/src/main/maker-host/pi-remote-transport.ts b/apps/desktop/src/main/maker-host/pi-remote-transport.ts
index 942de6c0a6..fc3b781baf 100644
--- a/apps/desktop/src/main/maker-host/pi-remote-transport.ts
+++ b/apps/desktop/src/main/maker-host/pi-remote-transport.ts
@@ -36,6 +36,7 @@ import type {
PiTransportCloseInfo,
PiLineHandler,
PiCloseHandler,
+ PiOversizedFrameHandler,
PiRemoteFileOps,
} from '@cindy/maker-core';
@@ -84,8 +85,8 @@ export function redactCredentialText(text: string): string {
`${pre}${quote}[REDACTED]${sep}[REDACTED]`);
return out;
}
-// 轮 40-w1 HIGH:SSH stdout JSONL 缓冲上限 —— 与本地 attachJsonlReader 的
-// MAX_JSONL_BUFFER_CHARS(16MB)对齐, 防远端异常输出无换行流导致 OOM。
+// SSH stdout JSONL 缓冲上限 —— 与本地 attachJsonlReader 的
+// MAX_JSONL_BUFFER_CHARS(16MB)对齐。超限resync 到下一行,不关 transport。
const SSH_JSONL_MAX_BUFFER_CHARS = 16 * 1024 * 1024;
// 轮 40-w4 MEDIUM-1:写队列(pendingWrites)硬上限 —— SSH channel 建立阶段
// (execStream 挂住/极慢)时每次 writeLine 都会 push 闭包, 无上限会无界增长
@@ -521,15 +522,17 @@ function createSshPiChannelTransport(
let envWritten = false;
const lineHandlers = new Set<PiLineHandler>();
+ const oversizedHandlers = new Set<PiOversizedFrameHandler>();
const closeHandlers = new Set<PiCloseHandler>();
const stderrHandlers = new Set<(line: string) => void>();
const pendingWrites: Array<{ line: string; resolve: () => void; reject: (err: Error) => void }> = [];
/** stdout 行切分缓冲(ssh channel 文本块可能跨行/半行)。 */
let stdoutBuffer = '';
+ let skippingOversizedLine = false;
// 轮 8 发现 5:ExecStreamHandle.onStdout 用 chunk.toString('utf8') 逐块解码,
// 跨 chunk 的多字节 UTF-8 字符会被切成 U+FFFD。改用 onStdoutBytes +
// StringDecoder(与 attachJsonlReader 同款), 保证 JSONL 帧内中文/emoji 不损坏。
- const stdoutDecoder = new StringDecoder('utf8');
+ let stdoutDecoder = new StringDecoder('utf8');
/** stdout 尾部 flush(幂等):channel 关闭/主动 close 前把 stdoutBuffer 里
* 残留的未换行尾帧(pi 崩溃前输出半行 / 最后一行无 \n)吐给 lineHandlers,
@@ -542,7 +545,7 @@ function createSshPiChannelTransport(
flushedTail = true;
const tail = stdoutBuffer + stdoutDecoder.end();
stdoutBuffer = '';
- if (tail.trim().length > 0) {
+ if (!skippingOversizedLine && tail.trim().length > 0 && tail.length <= SSH_JSONL_MAX_BUFFER_CHARS) {
fireLine(tail.endsWith('\r') ? tail.slice(0, -1) : tail);
}
};
@@ -567,6 +570,12 @@ function createSshPiChannelTransport(
for (const handler of lineHandlers) handler(line);
};
+ const fireOversizedFrame = (): void => {
+ for (const handler of oversizedHandlers) {
+ try { handler(); } catch { /* handler should not throw */ }
+ }
+ };
+
const fireStderr = (line: string): void => {
for (const handler of stderrHandlers) handler(line);
};
@@ -705,21 +714,43 @@ function createSshPiChannelTransport(
if (closed) return;
if (handshakeTimer) { clearTimeout(handshakeTimer); handshakeTimer = null; }
stdoutBuffer += stdoutDecoder.write(chunk);
- // 轮 40-w1 HIGH:SSH stdout 缓冲无 OOM 上限(本地 attachJsonlReader 有
- // 16MB guard, 双实现契约不一致)。远端路径更不可信 —— 超限丢弃缓冲并
- // 关闭(继续解析已无意义, 且防 OOM)。
- if (stdoutBuffer.length > SSH_JSONL_MAX_BUFFER_CHARS) {
- logger.warn('pi ssh stdout buffer exceeded limit — closing transport', {
- hostId: opts.remoteHost.id,
- bytes: stdoutBuffer.length,
- });
- stdoutBuffer = '';
- fireClose({ code: null, signal: null, reason: 'pi ssh stdout buffer overflow (no newline in stream)' });
- return;
- }
+ // 与本地 attachJsonlReader 对齐:超限丢掉当前行并resync 到下一个 \n。
+ // 合法 get_entries 带图历史可以超过 16MB;关 transport 会把整段会话打死。
while (true) {
+ if (skippingOversizedLine) {
+ const newlineIndex = stdoutBuffer.indexOf('\n');
+ if (newlineIndex === -1) {
+ stdoutBuffer = '';
+ stdoutDecoder = new StringDecoder('utf8');
+ break;
+ }
+ stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
+ skippingOversizedLine = false;
+ continue;
+ }
const newlineIndex = stdoutBuffer.indexOf('\n');
- if (newlineIndex === -1) break;
+ if (newlineIndex === -1) {
+ if (stdoutBuffer.length > SSH_JSONL_MAX_BUFFER_CHARS) {
+ logger.warn('pi ssh stdout buffer exceeded limit — discarding until next newline', {
+ hostId: opts.remoteHost.id,
+ bytes: stdoutBuffer.length,
+ });
+ skippingOversizedLine = true;
+ fireOversizedFrame();
+ stdoutBuffer = '';
+ stdoutDecoder = new StringDecoder('utf8');
+ }
+ break;
+ }
+ if (newlineIndex > SSH_JSONL_MAX_BUFFER_CHARS) {
+ logger.warn('pi ssh stdout discarded oversized JSONL frame', {
+ hostId: opts.remoteHost.id,
+ bytes: newlineIndex,
+ });
+ fireOversizedFrame();
+ stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
+ continue;
+ }
let line = stdoutBuffer.slice(0, newlineIndex);
stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
if (line.endsWith('\r')) line = line.slice(0, -1);
@@ -836,6 +867,11 @@ function createSshPiChannelTransport(
return () => { closeHandlers.delete(handler); };
},
+ onOversizedFrame(handler: PiOversizedFrameHandler): () => void {
+ oversizedHandlers.add(handler);
+ return () => { oversizedHandlers.delete(handler); };
+ },
+
async close(reason = 'pi ssh transport close()'): Promise<void> {
if (closed) return;
fireClose({ code: null, signal: null, reason });
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
index 32564ce992..b9d19ddf2d 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
@@ -32,6 +32,7 @@ vi.mock('../../maker-ipc/register.js', () => ({
}));
vi.mock('@cindy/mcps', () => ({
+ setSessionPathAuthorizer: vi.fn(),
createLiziMcpProviders: vi.fn((config: Record<string, unknown>) => {
mockState.capturedProvidersConfig = config;
return [
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer-contract.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer-contract.test.ts
index 2c5aab28ad..ab2a8845b4 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer-contract.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer-contract.test.ts
@@ -49,9 +49,29 @@ describe('installed Computer Use contract', () => {
});
it('rejects unavailable tools and incompatible arguments before dispatch', () => {
expect(() => adaptComputerDriverArgs('missing', {}, schemas)).toThrow('does not advertise');
- expect(() => adaptComputerDriverArgs('click', { pid: 1, unsupported: true }, schemas)).toThrow(
- 'does not accept unsupported',
- );
+ const olderClick = new Map([['click', {
+ properties: { pid: {}, window_id: {}, element_index: {}, snapshot_id: {} },
+ additionalProperties: false,
+ }]]);
+ expect(adaptComputerDriverArgs('click', {
+ pid: 1,
+ window_id: 2,
+ element_index: 3,
+ snapshot_id: 's01234567',
+ delivery_mode: 'background',
+ }, olderClick)).toEqual({
+ pid: 1,
+ window_id: 2,
+ element_index: 3,
+ snapshot_id: 's01234567',
+ });
+ expect(() => adaptComputerDriverArgs('click', {
+ pid: 1,
+ window_id: 2,
+ element_index: 3,
+ snapshot_id: 's01234567',
+ unsupported: true,
+ }, olderClick)).toThrow('does not accept unsupported');
expect(() =>
adaptComputerDriverArgs('verify_state', { pid: 1, window_id: 2 }, schemas),
).toThrow('requires expect');
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index 398f0aa26a..1b0171acb8 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -12,7 +12,7 @@
* 自动过户,降档恢复确认;缺会话、查询失败、远程会话 fail closed。
*/
-import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
@@ -134,7 +134,9 @@ vi.mock('../../logger.js', () => ({
createLogger: () => ({ info: logInfoMock, warn: logWarnMock, error: () => {}, debug: () => {} }),
}));
// Claude 走建线闭包 ctx;Codex / Pi 用此 mock 模拟 HTTP bridge 的 ALS 恢复。
-vi.mock('@cindy/mcps', () => ({ getLiziMcpSessionContext: () => alsSessionContextMock() }));
+vi.mock('@cindy/mcps', () => ({
+ getLiziMcpSessionContext: () => alsSessionContextMock(),
+}));
const isAuthorizationSessionMock = vi.fn(async () => false);
vi.mock('../../maker-ipc/botAuthorizationHost.js', () => ({ isBotAuthorizationSession: isAuthorizationSessionMock }));
@@ -250,7 +252,7 @@ vi.mock('../ghostAttachmentResolve.js', () => ({
resolveGhostAttachmentUrl: resolveGhostAttachmentUrlMock,
}));
-const { getCindyGhostsMcpDeps, getGhostRosterPrompt } = await import('../ghost');
+const { authorizeDesktopSessionPath, getCindyGhostsMcpDeps, getGhostRosterPrompt } = await import('../ghost');
const { createCindyGhostsMcpServer } = await import('cindy-tools');
const { setGhostDisabledForWorkdir, listDisabledGhostIdsForWorkdir, isGhostDisabledForWorkdir } =
await import('../../cindy-brain/ghostWorkdirPrefs');
@@ -750,6 +752,390 @@ describe('Forge session workdir gate', () => {
});
});
+describe('Forge workdir-out permission path', () => {
+ let localWorkdir: string;
+ let outsideRoot: string;
+ let sourceDir: string;
+
+ beforeEach(() => {
+ localWorkdir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-forge-grant-wd-'));
+ outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-forge-grant-src-'));
+ sourceDir = path.join(outsideRoot, 'plugin-src');
+ fs.mkdirSync(sourceDir);
+ sessionSnapshotMock.mockResolvedValue({
+ workingDir: localWorkdir,
+ permissionMode: 'auto',
+ planModeEnabled: false,
+ remoteHostId: null,
+ });
+ });
+
+ afterEach(() => {
+ fs.rmSync(localWorkdir, { recursive: true, force: true });
+ fs.rmSync(outsideRoot, { recursive: true, force: true });
+ });
+
+ function packedOk() {
+ return {
+ ok: true as const,
+ buf: Buffer.from('packed'),
+ cindyPath: path.join(sourceDir, 'demo-1.0.0.cindy'),
+ manifest: { id: 'demo', name: 'Demo', version: '1.0.0' },
+ };
+ }
+
+ it('Full Access packs an outside source without a confirm card', async () => {
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ isCurrent: () => true,
+ });
+ packGhostDirMock.mockResolvedValueOnce(packedOk());
+ const result = await makeDeps('pi', 'forge-bypass').forgePack({ dir: sourceDir });
+ expect(result).toMatchObject({ ok: true });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(packGhostDirMock).toHaveBeenCalledWith(
+ sourceDir,
+ expect.objectContaining({
+ sessionWorkdir: localWorkdir,
+ allowOutsideWorkdir: true,
+ authorizedDir: fs.realpathSync.native(sourceDir),
+ }),
+ );
+ expect(packGhostDirMock.mock.calls[0]?.[1]?.isCurrent?.()).toBe(true);
+ expect(packGhostDirMock.mock.calls[0]?.[1]?.authorizedAncestors).toBeUndefined();
+ });
+
+ it('Auto-review allow packs an outside source', async () => {
+ const reviewAction = vi.fn(async (_action: { description?: string }) => ({ verdict: 'allow' as const }));
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'auto',
+ remoteHostId: null,
+ reviewAction,
+ isCurrent: () => true,
+ });
+ packGhostDirMock.mockResolvedValueOnce(packedOk());
+ const result = await makeDeps('pi', 'forge-auto').forgePack({ dir: sourceDir });
+ expect(result).toMatchObject({ ok: true });
+ expect(reviewAction).toHaveBeenCalledOnce();
+ const action = reviewAction.mock.calls[0]?.[0];
+ expect(action?.description).toContain('plugin_file_handoff');
+ expect(action?.description).toContain('forge_source');
+ expect(action?.description).toContain('ghost_forge_pack');
+ expect(action?.description).toContain('write');
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(packGhostDirMock).toHaveBeenCalledWith(
+ sourceDir,
+ expect.objectContaining({
+ allowOutsideWorkdir: true,
+ authorizedDir: fs.realpathSync.native(sourceDir),
+ }),
+ );
+ });
+
+ it('Auto-review block returns PERMISSION_DENIED without packing', async () => {
+ const reviewAction = vi.fn(async () => ({
+ verdict: 'block' as const,
+ reason: 'Stay in the session workdir',
+ }));
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'auto',
+ remoteHostId: null,
+ reviewAction,
+ isCurrent: () => true,
+ });
+ const result = await makeDeps('pi', 'forge-auto-block').forgePack({ dir: sourceDir });
+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(packGhostDirMock).not.toHaveBeenCalled();
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ });
+
+ it('Ask shows a forge_source confirm card then packs', async () => {
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'ask',
+ remoteHostId: null,
+ isCurrent: () => true,
+ });
+ packGhostDirMock.mockResolvedValueOnce(packedOk());
+ const result = await makeDeps('pi', 'forge-ask').forgePack({ dir: sourceDir });
+ expect(result).toMatchObject({ ok: true });
+ expect(confirmRequestMock).toHaveBeenCalledWith(
+ 'forge-ask',
+ expect.objectContaining({
+ ghostId: 'cindy-forge',
+ ghostName: 'Forge',
+ lane: 'forge_source',
+ sourceTool: 'ghost_forge_pack',
+ operation: 'write',
+ }),
+ );
+ expect(packGhostDirMock).toHaveBeenCalledWith(
+ sourceDir,
+ expect.objectContaining({
+ allowOutsideWorkdir: true,
+ authorizedDir: fs.realpathSync.native(sourceDir),
+ }),
+ );
+ });
+
+ it('Ask deny does not pack', async () => {
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'ask',
+ remoteHostId: null,
+ isCurrent: () => true,
+ });
+ confirmRequestMock.mockResolvedValueOnce({ confirmed: false, allowDirs: false });
+ const result = await makeDeps('pi', 'forge-ask-deny').forgePack({ dir: sourceDir });
+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(packGhostDirMock).not.toHaveBeenCalled();
+ });
+
+ it('Full Access scaffolds an outside directory without a confirm card', async () => {
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ isCurrent: () => true,
+ });
+ const dir = path.join(outsideRoot, 'new-plugin');
+ await expect(
+ makeDeps('pi', 'forge-scaffold-bypass').forgeScaffold({
+ dir,
+ template: 'plain',
+ id: 'new-plugin',
+ name: 'New plugin',
+ }),
+ ).resolves.toMatchObject({ ok: true });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(scaffoldGhostDirMock).toHaveBeenCalledWith(
+ expect.objectContaining({ minCindyVersion: '2.3.4' }),
+ expect.objectContaining({
+ sessionWorkdir: localWorkdir,
+ allowOutsideWorkdir: true,
+ authorizedDir: path.join(fs.realpathSync.native(outsideRoot), 'new-plugin'),
+ }),
+ );
+ });
+
+ it('rejects an outside source after the live grant expires', async () => {
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ isCurrent: () => false,
+ });
+ const result = await makeDeps('pi', 'forge-expired').forgePack({ dir: sourceDir });
+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(packGhostDirMock).not.toHaveBeenCalled();
+ });
+
+ it('denies an outside pack when the session instance is missing or dead', async () => {
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ isCurrent: () => true,
+ });
+ await expect(
+ makeDeps('pi', 'forge-no-instance', null).forgePack({ dir: sourceDir }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(packGhostDirMock).not.toHaveBeenCalled();
+
+ liveGrantStateMock.mockReturnValue(null);
+ await expect(
+ makeDeps('pi', 'forge-dead-instance').forgePack({ dir: sourceDir }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(packGhostDirMock).not.toHaveBeenCalled();
+ });
+
+ it('does not install after pack if the live grant expires', async () => {
+ let current = true;
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ isCurrent: () => current,
+ });
+ packGhostDirMock.mockImplementation(async () => {
+ current = false;
+ return packedOk();
+ });
+ const result = await makeDeps('pi', 'forge-install-stale').forgeInstall({ dir: sourceDir });
+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(forgeInstallPackageMock).not.toHaveBeenCalled();
+ });
+
+ it('passes the live grant into the Forge install transaction', async () => {
+ const isCurrent = () => true;
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ isCurrent,
+ });
+ packGhostDirMock.mockResolvedValueOnce(packedOk());
+ await expect(
+ makeDeps('pi', 'forge-install-current').forgeInstall({ dir: sourceDir }),
+ ).resolves.toMatchObject({ ok: true });
+ expect(forgeInstallPackageMock).toHaveBeenCalledWith(
+ packedOk().cindyPath,
+ expect.objectContaining({
+ ghostId: 'demo',
+ isCurrent,
+ }),
+ );
+ });
+
+ it('does not stage a publish pack after the live grant expires', async () => {
+ let current = true;
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ isCurrent: () => current,
+ });
+ packGhostDirMock.mockImplementation(async () => {
+ current = false;
+ return packedOk();
+ });
+ const result = await makeDeps('pi', 'forge-publish-stale').forgePack({
+ dir: sourceDir,
+ intent: 'publish',
+ });
+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(completeForgePackStagingMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('session path authorization for docs/computer', () => {
+ const outsidePath = path.join(outsideDir, 'report.docx');
+
+ it('Full Access allows a local outside path without a confirm card', async () => {
+ const isCurrent = () => true;
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ isCurrent,
+ });
+ await expect(authorizeDesktopSessionPath({
+ sessionId: 's1',
+ sessionInstanceId: 's1-instance',
+ workingDir: WORKDIR,
+ path: outsidePath,
+ toolName: 'cindy-docs',
+ operation: 'write',
+ }, liveGrantStateMock)).resolves.toEqual({ allowed: true, isCurrent });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ });
+
+ it('Auto review can allow or block an outside path', async () => {
+ const isCurrent = () => true;
+ const reviewAction = vi.fn(async (_action: { description?: string }): Promise<{ verdict: 'allow' | 'block'; reason?: string }> => ({
+ verdict: 'allow',
+ }));
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'auto',
+ remoteHostId: null,
+ reviewAction,
+ isCurrent,
+ });
+ await expect(authorizeDesktopSessionPath({
+ sessionId: 's1',
+ sessionInstanceId: 's1-instance',
+ workingDir: WORKDIR,
+ path: outsidePath,
+ toolName: 'cindy-docs',
+ operation: 'write',
+ }, liveGrantStateMock)).resolves.toEqual({ allowed: true, isCurrent });
+ expect(reviewAction).toHaveBeenCalledOnce();
+ const reviewed = reviewAction.mock.calls[0]?.[0];
+ expect(reviewed?.description).toContain('cindy-docs');
+ expect(reviewed?.description).toContain('"operation":"write"');
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+
+ reviewAction.mockResolvedValueOnce({ verdict: 'block', reason: 'not this path' });
+ await expect(authorizeDesktopSessionPath({
+ sessionId: 's1',
+ sessionInstanceId: 's1-instance',
+ workingDir: WORKDIR,
+ path: outsidePath,
+ toolName: 'cindy-computer:get_window_state',
+ operation: 'write',
+ }, liveGrantStateMock)).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('Ask shows a confirm card and remote sessions stay closed', async () => {
+ const isCurrent = () => true;
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'ask',
+ remoteHostId: null,
+ isCurrent,
+ });
+ await expect(authorizeDesktopSessionPath({
+ sessionId: 's1',
+ sessionInstanceId: 's1-instance',
+ workingDir: WORKDIR,
+ path: outsidePath,
+ toolName: 'cindy-docs',
+ operation: 'write',
+ }, liveGrantStateMock)).resolves.toEqual({ allowed: true, isCurrent });
+ expect(confirmRequestMock).toHaveBeenCalledOnce();
+ expect(confirmRequestMock).toHaveBeenCalledWith(
+ 's1',
+ expect.objectContaining({
+ lane: 'outside_workdir',
+ sourceTool: 'cindy-docs',
+ operation: 'write',
+ }),
+ );
+
+ await expect(authorizeDesktopSessionPath({
+ sessionId: 's1',
+ sessionInstanceId: 's1-instance',
+ workingDir: WORKDIR,
+ remoteHostId: 'ssh-1',
+ path: outsidePath,
+ toolName: 'cindy-docs',
+ operation: 'write',
+ }, liveGrantStateMock)).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('denies outside paths when the session instance is missing or dead', async () => {
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ });
+ await expect(authorizeDesktopSessionPath({
+ sessionId: 's1',
+ workingDir: WORKDIR,
+ path: outsidePath,
+ toolName: 'cindy-docs',
+ operation: 'write',
+ }, liveGrantStateMock)).resolves.toMatchObject({ allowed: false });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+
+ liveGrantStateMock.mockReturnValue(null);
+ await expect(authorizeDesktopSessionPath({
+ sessionId: 's1',
+ sessionInstanceId: 'dead-instance',
+ workingDir: WORKDIR,
+ path: outsidePath,
+ toolName: 'cindy-computer:get_window_state',
+ operation: 'write',
+ }, liveGrantStateMock)).resolves.toMatchObject({ allowed: false });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+
+ liveGrantStateMock.mockImplementation(() => {
+ throw new Error('runtime registry unavailable');
+ });
+ await expect(authorizeDesktopSessionPath({
+ sessionId: 's1',
+ sessionInstanceId: 's1-instance',
+ workingDir: WORKDIR,
+ path: outsidePath,
+ toolName: 'cindy-docs',
+ operation: 'write',
+ }, liveGrantStateMock)).resolves.toMatchObject({ allowed: false });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ });
+});
+
afterAll(() => {
fs.rmSync(tmpUserData, { recursive: true, force: true });
});
diff --git a/apps/desktop/src/main/mcp-integrations/computer-contract.ts b/apps/desktop/src/main/mcp-integrations/computer-contract.ts
index 16f4306eed..17751d3c34 100644
--- a/apps/desktop/src/main/mcp-integrations/computer-contract.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer-contract.ts
@@ -9,6 +9,9 @@ export class ComputerContractError extends Error {
readonly code = 'COMPUTER_DRIVER_INCOMPATIBLE';
}
+/** Fields Cindy may advertise after an older installed driver froze its schema. */
+const DRIVER_COMPAT_OPTIONAL_FIELDS = new Set(['delivery_mode']);
+
export function adaptComputerDriverArgs(
name: string,
input: Record<string, unknown>,
@@ -45,6 +48,12 @@ export function adaptComputerDriverArgs(
for (const key of Object.keys(args)) {
if (args[key] === undefined) delete args[key];
else if (schema.additionalProperties === false && !(key in props)) {
+ // Only strip fields Cindy added after older drivers froze their schema.
+ // Unknown keys still fail closed so a misspelled target cannot dispatch.
+ if (DRIVER_COMPAT_OPTIONAL_FIELDS.has(key)) {
+ delete args[key];
+ continue;
+ }
throw new ComputerContractError(
`Installed driver ${name} does not accept ${key}; no action was dispatched.`,
);
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index b6afa0d9c1..75399c5828 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -38,7 +38,12 @@ import type {
CindyGhostsMcpDeps,
} from 'cindy-tools';
import { toolAutoReviewAction, type PermissionMode, type ReviewableAction, type AutoReviewDecision } from '@cindy/maker-core';
-import { getLiziMcpSessionContext, type LiziMcpSessionContext } from '@cindy/mcps';
+import {
+ getLiziMcpSessionContext,
+ type LiziMcpSessionContext,
+ type SessionPathAuthorization,
+ type SessionPathAuthorizationRequest,
+} from '@cindy/mcps';
import {
GRANT_AUTHORIZATION_CHANGED_MESSAGE,
@@ -126,11 +131,235 @@ const convertForgeIconToPng = createForgeIconConverter({
fork: forkForgeIconConversionHost,
});
+const CINDY_FORGE_GRANT_ID = 'cindy-forge';
+const CINDY_SESSION_FS_GRANT_ID = 'cindy-session-fs';
+
+/** realpath 对尚未创建的 scaffold 目标会失败,改走已存在的最深祖先。 */
+function classifyForgeSourceRelativeToWorkdir(
+ source: string,
+ workdir: string,
+): 'inside' | 'outside' | 'unknown' {
+ try {
+ const realWorkdir = fs.realpathSync.native(path.resolve(workdir));
+ let cursor = path.resolve(source);
+ const { root } = path.parse(cursor);
+ while (true) {
+ try {
+ const realSource = fs.realpathSync.native(cursor);
+ return isPathInsideDir(realWorkdir, realSource) ? 'inside' : 'outside';
+ } catch {
+ if (cursor === root) return 'unknown';
+ const parent = path.dirname(cursor);
+ if (parent === cursor) return 'unknown';
+ cursor = parent;
+ }
+ }
+ } catch {
+ return 'unknown';
+ }
+}
+
+function resolveCanonicalForgeDir(source: string): string {
+ let cursor = path.resolve(source);
+ const tail: string[] = [];
+ const { root } = path.parse(cursor);
+ while (true) {
+ try {
+ const real = fs.realpathSync.native(cursor);
+ return path.join(real, ...tail);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return path.resolve(source);
+ if (cursor === root) return path.resolve(source);
+ const parent = path.dirname(cursor);
+ if (parent === cursor) return path.resolve(source);
+ tail.unshift(path.basename(cursor));
+ cursor = parent;
+ }
+ }
+}
+
+type ForgeOutsideAccess =
+ | { ok: true; allowOutsideWorkdir: false }
+ | {
+ ok: true;
+ allowOutsideWorkdir: true;
+ authorizedDir: string;
+ isCurrent?: () => boolean;
+ }
+ | { ok: false; errorCode: 'PERMISSION_DENIED'; message: string };
+
+function forgeOutsidePackFlags(access: Extract<ForgeOutsideAccess, { ok: true }>): {
+ allowOutsideWorkdir?: boolean;
+ authorizedDir?: string;
+ isCurrent?: () => boolean;
+} {
+ return access.allowOutsideWorkdir
+ ? {
+ allowOutsideWorkdir: true,
+ authorizedDir: access.authorizedDir,
+ ...(access.isCurrent ? { isCurrent: access.isCurrent } : {}),
+ }
+ : {};
+}
+
+function requireLiveSessionInstance(
+ sessionId: string | undefined,
+ sessionInstanceId: string | undefined,
+ getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'],
+): { ok: true; sessionId: string; sessionInstanceId: string } | { ok: false; message: string } {
+ if (!sessionId || !sessionInstanceId || !getLiveSessionGrantState) {
+ return {
+ ok: false,
+ message: '当前调用无法确认任务实例,不能读写工作目录外的路径。请在本机已打开的任务里重试。',
+ };
+ }
+ try {
+ if (!getLiveSessionGrantState(sessionId, sessionInstanceId)) {
+ return {
+ ok: false,
+ message: '当前任务实例已失效,不能读写工作目录外的路径。请用当前任务重试。',
+ };
+ }
+ } catch {
+ return {
+ ok: false,
+ message: '当前任务权限状态读不到,不能读写工作目录外的路径。请用当前任务重试。',
+ };
+ }
+ return { ok: true, sessionId, sessionInstanceId };
+}
+
+async function authorizeForgeOutsideWorkdir(params: {
+ dir: string;
+ sessionWorkdir: string;
+ sessionContext: LiziMcpSessionContext | undefined;
+ toolName: 'ghost_forge_scaffold' | 'ghost_forge_pack' | 'ghost_forge_install';
+ operation: 'read' | 'write';
+ getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
+}): Promise<ForgeOutsideAccess> {
+ const location = classifyForgeSourceRelativeToWorkdir(params.dir, params.sessionWorkdir);
+ if (location !== 'outside') return { ok: true, allowOutsideWorkdir: false };
+ const live = requireLiveSessionInstance(
+ params.sessionContext?.sessionId,
+ params.sessionContext?.sessionInstanceId,
+ params.getLiveSessionGrantState,
+ );
+ if (!live.ok) {
+ return { ok: false, errorCode: 'PERMISSION_DENIED', message: live.message };
+ }
+ const authorizedDir = resolveCanonicalForgeDir(params.dir);
+ let size = 0;
+ let isDirectory = true;
+ try {
+ const stat = fs.statSync(authorizedDir);
+ isDirectory = stat.isDirectory() || stat.isSymbolicLink();
+ size = stat.size;
+ } catch {
+ /* pack/scaffold still report DIR_NOT_FOUND */
+ }
+ const granted = await requestGrantConfirm({
+ ghostId: CINDY_FORGE_GRANT_ID,
+ sessionId: live.sessionId,
+ sessionInstanceId: live.sessionInstanceId,
+ lane: 'forge_source',
+ items: [{
+ name: path.basename(authorizedDir) || authorizedDir,
+ absPath: authorizedDir,
+ size,
+ isDirectory,
+ }],
+ toolName: params.toolName,
+ operation: params.operation,
+ getLiveSessionGrantState: params.getLiveSessionGrantState,
+ });
+ if (!granted.ok) {
+ return { ok: false, errorCode: 'PERMISSION_DENIED', message: granted.message };
+ }
+ if (!granted.isCurrent) {
+ return {
+ ok: false,
+ errorCode: 'PERMISSION_DENIED',
+ message: '当前任务实例已失效,不能读写工作目录外的路径。请用当前任务重试。',
+ };
+ }
+ if (granted.isCurrent() === false) {
+ return { ok: false, errorCode: 'PERMISSION_DENIED', message: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
+ }
+ return {
+ ok: true,
+ allowOutsideWorkdir: true,
+ authorizedDir,
+ isCurrent: granted.isCurrent,
+ };
+}
+
+function assertForgeGrantCurrent(access: Extract<ForgeOutsideAccess, { ok: true }>): ForgeOutsideAccess {
+ if (access.allowOutsideWorkdir && access.isCurrent?.() !== true) {
+ return { ok: false, errorCode: 'PERMISSION_DENIED', message: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
+ }
+ return access;
+}
+
+function denyOutsideSessionPath(reason: string): SessionPathAuthorization {
+ return { allowed: false, reason };
+}
+
+export async function authorizeDesktopSessionPath(
+ request: SessionPathAuthorizationRequest,
+ getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'],
+): Promise<SessionPathAuthorization> {
+ if (request.remoteHostId) {
+ return {
+ allowed: false,
+ reason: '远程会话不能授权控制端本机路径。请改用当前任务工作目录内的路径,或在本机会话中重试。',
+ };
+ }
+ const live = requireLiveSessionInstance(request.sessionId, request.sessionInstanceId, getLiveSessionGrantState);
+ if (!live.ok) return denyOutsideSessionPath(live.message);
+ let size = 0;
+ let isDirectory = false;
+ try {
+ const stat = fs.statSync(request.path);
+ isDirectory = stat.isDirectory();
+ size = stat.size;
+ } catch {
+ /* write targets may not exist yet */
+ }
+ const granted = await requestGrantConfirm({
+ ghostId: CINDY_SESSION_FS_GRANT_ID,
+ sessionId: live.sessionId,
+ sessionInstanceId: live.sessionInstanceId,
+ lane: 'outside_workdir',
+ items: [{
+ name: path.basename(request.path) || request.path,
+ absPath: request.path,
+ size,
+ isDirectory,
+ }],
+ toolName: request.toolName,
+ operation: request.operation,
+ getLiveSessionGrantState,
+ });
+ if (!granted.ok) return denyOutsideSessionPath(granted.message);
+ if (!granted.isCurrent) {
+ return denyOutsideSessionPath('当前任务实例已失效,不能读写工作目录外的路径。请用当前任务重试。');
+ }
+ if (granted.isCurrent() === false) {
+ return { allowed: false, reason: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
+ }
+ return { allowed: true, isCurrent: granted.isCurrent };
+}
+
/** pack 与显式 install 共用同一套可选 AI 图标叠加,避免二次打包丢失图标。 */
async function packForgeSource(
dir: string,
sessionWorkdir: string,
iconSource?: string,
+ packFlags: {
+ allowOutsideWorkdir?: boolean;
+ authorizedDir?: string;
+ isCurrent?: () => boolean;
+ } = {},
) {
let iconPng: Buffer | undefined;
let iconNote = '';
@@ -154,9 +383,22 @@ async function packForgeSource(
});
}
}
+ if (packFlags.allowOutsideWorkdir && packFlags.authorizedDir && packFlags.isCurrent?.() !== true) {
+ return {
+ ok: false as const,
+ result: { ok: false as const, errorCode: 'PERMISSION_DENIED' as const, message: GRANT_AUTHORIZATION_CHANGED_MESSAGE },
+ };
+ }
const packOptions = {
sessionWorkdir,
forbiddenRootDirs: ghostForgeForbiddenRootDirs(),
+ ...(packFlags.allowOutsideWorkdir
+ ? {
+ allowOutsideWorkdir: true,
+ authorizedDir: packFlags.authorizedDir,
+ ...(packFlags.isCurrent ? { isCurrent: packFlags.isCurrent } : {}),
+ }
+ : {}),
};
let packed = await packGhostDir(dir, iconPng ? { ...packOptions, iconPng } : packOptions);
// icon overlay 的任何失败都不是打包门槛:用原源码再打一次。若原源码
@@ -175,12 +417,14 @@ async function packForgeSource(
}
/* ────────────────────────────────────────────────────────────────────────
- * workdir 外过户确认:
- * - 过户对象在会话 workdir 内 → 自动放行(与目录过户同信任等级);
+ * workdir 外过户 / Forge 源码确认:
+ * - 对象在会话 workdir 内 → 自动放行;
* - 本地活跃会话当前为 Full Access(bypassPermissions) → Host 自动放行;
- * - 其余 workdir 外场景(含无会话/远程会话)→ 弹确认卡,用户点允许才继续。
- * Full Access 只替代本处文件/目录交接确认,不扩大插件 manifest slot、网络、
- * 凭证、Setup、安装/更新等其它授权边界。
+ * - Auto → 当前会话统一审阅器(allow 继续 / block 返回原因 / ask 才弹卡);
+ * - 其余(Ask、无会话、远程、查询失败)→ 弹确认卡,用户点允许才继续。
+ * 禁止在 Host 已按当前档位放行后再因目录边界悄悄硬断。
+ * Full Access 只替代本处确认,不扩大插件 manifest slot、网络、
+ * 凭证、Setup、安装/更新等其它授权边界。Forge 受管根仍硬拒。
* ──────────────────────────────────────────────────────────────────────── */
export interface GhostGrantLiveSessionState {
@@ -365,6 +609,8 @@ async function getForgeSessionFsGate(
/** 意识显示名(确认卡标题用;查不到回落 id)。 */
function ghostDisplayName(ghostId: string): string {
+ if (ghostId === CINDY_FORGE_GRANT_ID) return 'Forge';
+ if (ghostId === CINDY_SESSION_FS_GRANT_ID) return 'Cindy';
const g = getGhostManager()
.list()
.find((x) => x.manifest.id === ghostId);
@@ -391,6 +637,8 @@ async function requestGrantConfirm(params: {
sessionInstanceId: string | null;
lane: GhostGrantLane;
items: GhostGrantFileItem[];
+ toolName?: string;
+ operation?: 'read' | 'write';
getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
}): Promise<
| { ok: true; approvalSource: GhostGrantApprovalSource; allowDirs?: boolean; isCurrent?: () => boolean }
@@ -419,6 +667,8 @@ async function requestGrantConfirm(params: {
const decision = await live.reviewAction(toolAutoReviewAction('plugin_file_handoff', {
ghostId: params.ghostId,
lane: params.lane,
+ ...(params.toolName ? { sourceTool: params.toolName } : {}),
+ ...(params.operation ? { operation: params.operation } : {}),
files: params.items.map(({ absPath, size, mimeType, isDirectory }) => ({ absPath, size, mimeType, isDirectory })),
}, live.remoteHostId ? 'These are files on the controller, NOT the remote task filesystem.' : undefined));
if (expired()) return denied;
@@ -459,6 +709,8 @@ async function requestGrantConfirm(params: {
ghostName: ghostDisplayName(params.ghostId),
lane: params.lane,
items: params.items,
+ ...(params.toolName ? { sourceTool: params.toolName } : {}),
+ ...(params.operation ? { operation: params.operation } : {}),
});
if (expired()) return denied;
if (decision.confirmed) {
@@ -2049,10 +2301,22 @@ export function getCindyGhostsMcpDeps(
'当前是未发布或预发布 Cindy 构建,请明确填写 minCindyVersion(插件实际依赖的首个 Cindy 正式版本)',
};
}
+ const access = await authorizeForgeOutsideWorkdir({
+ dir: request.dir,
+ sessionWorkdir: gate.workingDir,
+ sessionContext: resolveSessionContext(),
+ toolName: 'ghost_forge_scaffold',
+ operation: 'write',
+ getLiveSessionGrantState: hostDeps.getLiveSessionGrantState,
+ });
+ if (!access.ok) return access;
+ const currentAccess = assertForgeGrantCurrent(access);
+ if (!currentAccess.ok) return currentAccess;
const result = await scaffoldGhostDir({ ...request, minCindyVersion }, {
sessionWorkdir: gate.workingDir,
forbiddenRootDirs: ghostForgeForbiddenRootDirs(),
writeScaffold: writeForgeScaffoldWithStableParent,
+ ...forgeOutsidePackFlags(currentAccess),
});
if (result.ok) {
log.info('ghost forge scaffold created', {
@@ -2066,10 +2330,24 @@ export function getCindyGhostsMcpDeps(
},
async forgePack({ dir, iconSource, intent }): Promise<CindyForgePackResult> {
return withForgeOwnerLease(async () => {
- const gate = await getForgeSessionFsGate(resolveSessionContext());
+ const sessionContext = resolveSessionContext();
+ const gate = await getForgeSessionFsGate(sessionContext);
if (!gate.ok) return gate;
- const attempt = await packForgeSource(dir, gate.workingDir, iconSource);
+ const access = await authorizeForgeOutsideWorkdir({
+ dir,
+ sessionWorkdir: gate.workingDir,
+ sessionContext,
+ toolName: 'ghost_forge_pack',
+ operation: 'write',
+ getLiveSessionGrantState: hostDeps.getLiveSessionGrantState,
+ });
+ if (!access.ok) return access;
+ const currentAccess = assertForgeGrantCurrent(access);
+ if (!currentAccess.ok) return currentAccess;
+ const attempt = await packForgeSource(dir, gate.workingDir, iconSource, forgeOutsidePackFlags(currentAccess));
if (!attempt.ok) return attempt.result;
+ const stillGranted = assertForgeGrantCurrent(currentAccess);
+ if (!stillGranted.ok) return stillGranted;
const { packed, iconNote } = attempt;
if (intent === 'publish') {
const alreadyInstalled = getGhostManager()
@@ -2115,10 +2393,24 @@ export function getCindyGhostsMcpDeps(
},
async forgeInstall({ dir, iconSource }): Promise<CindyForgeInstallResult> {
return withForgeOwnerLease(async () => {
- const gate = await getForgeSessionFsGate(resolveSessionContext());
+ const sessionContext = resolveSessionContext();
+ const gate = await getForgeSessionFsGate(sessionContext);
if (!gate.ok) return gate;
- const attempt = await packForgeSource(dir, gate.workingDir, iconSource);
+ const access = await authorizeForgeOutsideWorkdir({
+ dir,
+ sessionWorkdir: gate.workingDir,
+ sessionContext,
+ toolName: 'ghost_forge_install',
+ operation: 'write',
+ getLiveSessionGrantState: hostDeps.getLiveSessionGrantState,
+ });
+ if (!access.ok) return access;
+ const currentAccess = assertForgeGrantCurrent(access);
+ if (!currentAccess.ok) return currentAccess;
+ const attempt = await packForgeSource(dir, gate.workingDir, iconSource, forgeOutsidePackFlags(currentAccess));
if (!attempt.ok) return attempt.result;
+ const stillGranted = assertForgeGrantCurrent(currentAccess);
+ if (!stillGranted.ok) return stillGranted;
const { packed, iconNote } = attempt;
try {
const installed = await installOrUpdateLocalGhostPackageFromForge(
@@ -2126,6 +2418,9 @@ export function getCindyGhostsMcpDeps(
{
ghostId: packed.manifest.id,
packageSha256: createHash('sha256').update(packed.buf).digest('hex'),
+ ...(stillGranted.allowOutsideWorkdir && stillGranted.isCurrent
+ ? { isCurrent: stillGranted.isCurrent }
+ : {}),
},
);
log.info('ghost forge install completed', {
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index c4922a08e4..4719996bab 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -8,6 +8,7 @@ import { and, eq } from 'drizzle-orm';
import {
createLiziMcpProviders,
resolveLiziMcpSessionContext,
+ setSessionPathAuthorizer,
type IOSSimulatorMcpAccessDecision,
type LiziMcpProvider,
type LiziMcpSessionContext,
@@ -18,6 +19,7 @@ import type { OrcaMcpDeps } from '@cindy/mcps';
import { createCindyGhostsMcpServer } from 'cindy-tools';
import type { MakerMemoryManager } from '@cindy/maker-core';
import {
+ authorizeDesktopSessionPath,
getCindyGhostsMcpDeps,
type GhostGrantLiveSessionState,
type CindyGhostsHostDeps,
@@ -115,6 +117,9 @@ export interface DesktopMcpProvidersDeps {
}
export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcpProvider[] {
+ setSessionPathAuthorizer((request) =>
+ authorizeDesktopSessionPath(request, deps.getLiveSessionGrantState),
+ );
const { pluginRegistry } = deps;
let redactSshText: ((snapshot: SshHostSnapshotLike, text: string) => string) | undefined;
const loadRemoteSsh = async () => {
diff --git a/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx b/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx
index 53a3e85724..5968977b84 100644
--- a/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx
@@ -72,7 +72,21 @@ export function GhostGrantConfirmCard({ pending, onRespond }: GhostGrantConfirmC
? 'ghostGrant.confirm.descriptionFsWrite'
: pending.lane === 'workspace'
? 'ghostGrant.confirm.descriptionWorkspace'
- : 'ghostGrant.confirm.descriptionSaveDir';
+ : pending.lane === 'forge_source'
+ ? pending.sourceTool === 'ghost_forge_install'
+ ? 'ghostGrant.confirm.descriptionForgeInstall'
+ : pending.sourceTool === 'ghost_forge_scaffold'
+ ? 'ghostGrant.confirm.descriptionForgeScaffold'
+ : pending.sourceTool === 'ghost_forge_pack'
+ ? 'ghostGrant.confirm.descriptionForgePack'
+ : 'ghostGrant.confirm.descriptionForgeSource'
+ : pending.lane === 'outside_workdir'
+ ? pending.operation === 'read'
+ ? 'ghostGrant.confirm.descriptionOutsideRead'
+ : pending.operation === 'write'
+ ? 'ghostGrant.confirm.descriptionOutsideWrite'
+ : 'ghostGrant.confirm.descriptionOutsideWorkdir'
+ : 'ghostGrant.confirm.descriptionSaveDir';
return (
<div
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6ac049852e..a8eca0c801 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11014,6 +11014,13 @@
"descriptionRevealPath": "The path is returned to the current Agent only after you allow it and will enter the conversation record; paired devices may sync that record. This does not grant any plugin access to the file.",
"descriptionFsWrite": "This plugin requests to write the files below into the current session's working directory. If you allow, further writes to the same directory in this session won't ask again.",
"descriptionWorkspace": "This folder is outside this session's working directory. If you allow, Cindy creates an empty session for it in the sidebar (an existing session is reused) without reading any files inside.",
+ "descriptionForgeSource": "The directory below is outside this session's working directory. If you allow, Forge will pack or scaffold the plugin there (it writes a .cindy artifact or skeleton files).",
+ "descriptionForgeScaffold": "The directory below is outside this session's working directory. If you allow, Forge will create plugin source files there.",
+ "descriptionForgePack": "The directory below is outside this session's working directory. If you allow, Forge will pack the plugin there and write a .cindy artifact.",
+ "descriptionForgeInstall": "The directory below is outside this session's working directory. If you allow, Forge will pack this plugin and install and enable it on this computer.",
+ "descriptionOutsideWorkdir": "The path below is outside this session's working directory. If you allow, the current tool can read or write there.",
+ "descriptionOutsideRead": "The path below is outside this session's working directory. If you allow, the current tool can read there.",
+ "descriptionOutsideWrite": "The path below is outside this session's working directory. If you allow, the current tool can write there.",
"dirMeta": "{{count}} files · {{size}}",
"directory": "Directory",
"allowDirs": "Also allow their folders (media files in the same folders won't ask again this session)",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d3bd823ee9..8759c65c78 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -10998,6 +10998,13 @@
"descriptionRevealPath": "このパスは許可後にのみ現在の Agent へ返され、会話履歴に入ります。ペアリング済みデバイスにも同期される場合があります。この操作によってプラグインへファイルの読み取り権限が付与されることはありません。",
"descriptionFsWrite": "このプラグインは現在のセッションの作業ディレクトリに以下のファイルを書き込もうとしています。許可すると、このセッション中は同じディレクトリへの書き込みは再確認されません。",
"descriptionWorkspace": "このフォルダは現在のセッションの作業ディレクトリの外にあります。許可すると、Cindy がこのフォルダを作業ディレクトリとする空のセッションをサイドバーに作成します(既にセッションがある場合は再利用)。中のファイルは読み取りません。",
+ "descriptionForgeSource": "以下のディレクトリは現在のセッションの作業ディレクトリの外にあります。許可すると、Forge がそこでプラグインをパックまたは雛形生成します(.cindy 成果物または雛形ファイルを書き込みます)。",
+ "descriptionForgeScaffold": "以下のディレクトリは現在のセッションの作業ディレクトリの外にあります。許可すると、Forge がそこにプラグインの雛形を生成します。",
+ "descriptionForgePack": "以下のディレクトリは現在のセッションの作業ディレクトリの外にあります。許可すると、Forge がそこでプラグインをパックし、.cindy 成果物を書き込みます。",
+ "descriptionForgeInstall": "以下のディレクトリは現在のセッションの作業ディレクトリの外にあります。許可すると、Forge がこのプラグインをパックし、このコンピュータにインストールして有効化します。",
+ "descriptionOutsideWorkdir": "以下のパスは現在のセッションの作業ディレクトリの外にあります。許可すると、現在のツールがそこを読み書きできます。",
+ "descriptionOutsideRead": "以下のパスは現在のセッションの作業ディレクトリの外にあります。許可すると、現在のツールがそこを読み取れます。",
+ "descriptionOutsideWrite": "以下のパスは現在のセッションの作業ディレクトリの外にあります。許可すると、現在のツールがそこに書き込めます。",
"dirMeta": "{{count}} 個のファイル · {{size}}",
"directory": "ディレクトリ",
"allowDirs": "これらのファイルのフォルダーも許可(このセッション中、同じフォルダーのメディアファイルは再確認しません)",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 7d168782f0..8ebfc65c80 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -10998,6 +10998,13 @@
"descriptionRevealPath": "이 경로는 허용한 뒤에만 현재 Agent로 반환되며 대화 기록에 남습니다. 페어링된 기기에도 해당 기록이 동기화될 수 있습니다. 이 작업은 플러그인에 파일 읽기 권한을 부여하지 않습니다.",
"descriptionFsWrite": "이 플러그인이 현재 세션의 작업 디렉터리에 아래 파일을 쓰려고 합니다. 허용하면 이 세션 동안 같은 디렉터리에 대한 이후 쓰기는 다시 묻지 않습니다.",
"descriptionWorkspace": "이 폴더는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 Cindy가 이 폴더를 작업 디렉터리로 하는 빈 세션을 사이드바에 만듭니다(이미 세션이 있으면 재사용). 폴더 안의 파일은 읽지 않습니다.",
+ "descriptionForgeSource": "아래 디렉터리는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 Forge가 해당 디렉터리에서 플러그인을 패키징하거나 스캐폴드합니다(.cindy 산출물 또는 스켈레톤 파일을 씁니다).",
+ "descriptionForgeScaffold": "아래 디렉터리는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 Forge가 해당 디렉터리에 플러그인 소스 스켈레톤을 만듭니다.",
+ "descriptionForgePack": "아래 디렉터리는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 Forge가 해당 디렉터리에서 플러그인을 패키징하고 .cindy 산출물을 씁니다.",
+ "descriptionForgeInstall": "아래 디렉터리는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 Forge가 이 플러그인을 패키징한 뒤 이 컴퓨터에 설치하고 활성화합니다.",
+ "descriptionOutsideWorkdir": "아래 경로는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 현재 도구가 해당 위치를 읽거나 쓸 수 있습니다.",
+ "descriptionOutsideRead": "아래 경로는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 현재 도구가 해당 위치를 읽을 수 있습니다.",
+ "descriptionOutsideWrite": "아래 경로는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 현재 도구가 해당 위치에 쓸 수 있습니다.",
"dirMeta": "파일 {{count}}개 · {{size}}",
"directory": "디렉터리",
"allowDirs": "이 파일들의 폴더도 허용(이 세션에서 같은 폴더의 미디어 파일은 다시 묻지 않습니다)",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 8667db9042..40f3a00009 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -10994,6 +10994,13 @@
"descriptionRevealPath": "该路径只会在你允许后返回给当前 Agent,并进入对话记录;配对设备可能同步到这条记录。此操作不授予插件读取文件的权限。",
"descriptionFsWrite": "该插件请求在当前任务的工作目录写入以下文件。允许后,本任务内它写同一目录不再询问。",
"descriptionWorkspace": "该文件夹在当前任务的工作目录之外。允许后,Cindy 会以它为工作目录在侧边栏创建一个空任务(已有任务时直接复用),不会读取其中的文件。",
+ "descriptionForgeSource": "以下目录在当前任务的工作目录之外。允许后,Forge 会在该目录打包或生成插件源码(会写入 .cindy 产物或骨架文件)。",
+ "descriptionForgeScaffold": "以下目录在当前任务的工作目录之外。允许后,Forge 会在该目录生成插件源码骨架。",
+ "descriptionForgePack": "以下目录在当前任务的工作目录之外。允许后,Forge 会在该目录打包插件并写入 .cindy 产物。",
+ "descriptionForgeInstall": "以下目录在当前任务的工作目录之外。允许后,Forge 会打包该目录的插件,并安装、启用到本机。",
+ "descriptionOutsideWorkdir": "以下路径在当前任务的工作目录之外。允许后,当前工具可以读取或写入该位置。",
+ "descriptionOutsideRead": "以下路径在当前任务的工作目录之外。允许后,当前工具可以读取该位置。",
+ "descriptionOutsideWrite": "以下路径在当前任务的工作目录之外。允许后,当前工具可以写入该位置。",
"dirMeta": "{{count}} 个文件 · {{size}}",
"directory": "目录",
"allowDirs": "同时允许这些文件所在目录(本任务内同目录媒体文件不再询问)",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 8e117ecd77..bd3b870d91 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -10994,6 +10994,13 @@
"descriptionRevealPath": "該路徑只會在你允許後回傳給目前 Agent,並進入對話記錄;配對裝置可能同步該記錄。此操作不授予插件讀取檔案的權限。",
"descriptionFsWrite": "該插件請求在當前任務的工作目錄寫入以下檔案。允許後,本任務內它寫同一目錄不再詢問。",
"descriptionWorkspace": "該資料夾在當前任務的工作目錄之外。允許後,Cindy 會以它為工作目錄在側邊欄建立一個空任務(已有任務時直接複用),不會讀取其中的檔案。",
+ "descriptionForgeSource": "以下目錄在當前任務的工作目錄之外。允許後,Forge 會在該目錄打包或產生插件源碼(會寫入 .cindy 產物或骨架檔案)。",
+ "descriptionForgeScaffold": "以下目錄在當前任務的工作目錄之外。允許後,Forge 會在該目錄產生插件源碼骨架。",
+ "descriptionForgePack": "以下目錄在當前任務的工作目錄之外。允許後,Forge 會在該目錄打包插件並寫入 .cindy 產物。",
+ "descriptionForgeInstall": "以下目錄在當前任務的工作目錄之外。允許後,Forge 會打包該目錄的插件,並安裝、啟用到本機。",
+ "descriptionOutsideWorkdir": "以下路徑在當前任務的工作目錄之外。允許後,目前工具可以讀取或寫入該位置。",
+ "descriptionOutsideRead": "以下路徑在當前任務的工作目錄之外。允許後,目前工具可以讀取該位置。",
+ "descriptionOutsideWrite": "以下路徑在當前任務的工作目錄之外。允許後,目前工具可以寫入該位置。",
"dirMeta": "{{count}} 個檔案 · {{size}}",
"directory": "目錄",
"allowDirs": "同時允許這些檔案所在目錄(本任務內同目錄媒體檔案不再詢問)",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 7d53713ff2..201370cb0a 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -850,9 +850,13 @@ export interface PendingGhostGrantConfirm {
* 往目录里存文件;reveal_path = 允许当前 Agent 获得单个媒体仓本机路径;
* fs_write = 意识申请写工作目录文件(会话 permission 为
* 逐条确认档时逐次弹,同目录本会话批一次);workspace = 意识申请以该目录
- * 为工作区在侧边栏创建/复用会话入口(不过户字节)。
+ * 为工作区在侧边栏创建/复用会话入口(不过户字节);
+ * forge_source = Forge 打包/骨架/安装的源码目录在工作目录外;
+ * outside_workdir = 文档/电脑等内置工具读写工作目录外的路径。
*/
- lane: 'attachments' | 'dir' | 'save_dir' | 'reveal_path' | 'fs_write' | 'workspace';
+ lane: 'attachments' | 'dir' | 'save_dir' | 'reveal_path' | 'fs_write' | 'workspace' | 'forge_source' | 'outside_workdir';
+ sourceTool?: string;
+ operation?: 'read' | 'write';
items: Array<{
name: string;
absPath: string;
@@ -15465,7 +15469,9 @@ function parseGhostGrantConfirmRequest(request: {
lane !== 'save_dir' &&
lane !== 'reveal_path' &&
lane !== 'fs_write' &&
- lane !== 'workspace'
+ lane !== 'workspace' &&
+ lane !== 'forge_source' &&
+ lane !== 'outside_workdir'
)
return null;
if (typeof request.ghostId !== 'string' || typeof request.ghostName !== 'string') return null;
@@ -15497,6 +15503,10 @@ function parseGhostGrantConfirmRequest(request: {
ghostId: request.ghostId,
ghostName: request.ghostName,
lane,
+ ...(typeof request.sourceTool === 'string' ? { sourceTool: request.sourceTool } : {}),
+ ...(request.operation === 'read' || request.operation === 'write'
+ ? { operation: request.operation }
+ : {}),
items,
};
}
diff --git a/docs/dev-rules/pi-full-access-native-parity.md b/docs/dev-rules/pi-full-access-native-parity.md
index 40236370c8..dfaeeb82e9 100644
--- a/docs/dev-rules/pi-full-access-native-parity.md
+++ b/docs/dev-rules/pi-full-access-native-parity.md
@@ -20,15 +20,15 @@ Cindy Pi 的 **Full access(`bypassPermissions`)必须与同版本原生 Pi
- 不拦已装 Pi 扩展的工具调用(完全访问下)
- 不改 context-mode 自己的命令沙箱 PATH
- 不改 MCP 网关、斜杠转义、项目 `--no-approve`
-- 不放开 Extra Dirs 结构化写入
-- 不放开对 Cindy 运行目录(`models.json` / 权限档)的模型写入
+- 不把 Ask / Auto 的 Extra Dirs 写改成静默硬拦
+- 不把 Cindy 运行目录(`models.json` / 权限档)的模型写入改成静默硬拦或 Full Access 自动放行
## 允许保留的机械隔离
仅这两条,且不得拿它们扩大阻断面:
-1. 模型不得写 agent home(Cindy 控制面)
-2. Extra Dirs 的结构化写工具保持只读
+1. 模型写 agent home(Cindy 控制面)必须强制用户确认,不得静默拒绝或 Full Access 自动放行
+2. Extra Dirs 的结构化写跟随会话权限:Full Access 放行,Auto 审阅,Ask 确认
需要真隔离时用 Ask / Auto,或等 OS 沙箱;不要在 Full access 上堆正则。
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 0b605b0734..f102d099c7 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -25,15 +25,22 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
**不得**用凭证路径 / `/proc/*/environ` 文本硬拦拒绝原生允许的读、搜、bash。Ask/Auto
仍把这类调用升级为审批;Full access 选择即接受父进程环境里的代理 token / 网关 key /
BYOM key / 外部 MCP header **可能被读取**。允许保留的机械隔离仅限 Cindy 自身运行所必需:
- 模型不得写 agent home(`models.json` / 权限档),Extra Dirs 的结构化写工具保持只读。
+ 模型写 agent home(`models.json` / 权限档 / subagent 快照)必须强制用户确认,即使
+ Full Access 也不得静默放行或静默拒绝。Extra Dirs 的结构化写跟随会话权限:本地
+ Full Access 放行,Auto 交审阅,Ask 确认,禁止再在 bridge 里悄悄硬断。
bash 写入 Extra Dirs 仍非 OS 强制。真正的强隔离需要 OS 级手段(macOS `sandbox-exec`、
Linux 只读 bind mount / seccomp),**本阶段未接入**。需要硬边界时用 ask/auto 档,或等 OS
沙箱落地。改动权限相关代码时不要再堆「看起来能拦」的正则并当成安全边界。
与 Claude Code/Codex 一致,Pi 会话的 Full Access 也会让插件 `ghost_call` 的
- `attachments`/`dir`/`save_dir` 在 Host 侧免去额外过户确认;实现必须现读活跃 Session
+ `attachments`/`dir`/`save_dir`,以及 Forge 在工作目录外的 scaffold/pack/install
+ 在 Host 侧免去额外确认;实现必须现读活跃 Session
的稳定状态并同时匹配其 runtime instance identity;权限切换或关闭在途、远程/缺会话/
实例不匹配/查询失败均 fail closed。工作区草稿、工作目录写入和媒体路径揭示等操作审批
- 同样沿用会话权限;MCP 逐次审批标记不得覆盖 Full Access。Setup、OAuth、Secret 的信息
+ 同样沿用会话权限;MCP 逐次审批标记不得覆盖 Full Access。Host 已按当前档位放行后,
+ 不得再因「不在会话工作目录内」悄悄硬断,把 Agent 晾在空转里。 cindy-docs 与电脑截图 /
+ 录制路径同样走这条会话权限,不得在工具层再静默 PATH_NOT_ALLOWED。 授权卡片与后续
+ I/O 绑定已解析的规范路径,工作目录里的 symlink 不能把越界目标藏成相对路径。电脑
+ 驱动契约只丢掉 Cindy 后加的兼容字段(目前是 `delivery_mode`),其它未知参数仍拒。Setup、OAuth、Secret 的信息
输入与安装/更新策略保持原边界。instance 仅作为 opaque query 写入 Host 生成的 Pi MCP URL;桥接
注册表不匹配时返回 401。旧 URL 缺 instance 时可兼容普通会话工具,但必须向工具隐藏
instance,使 Full Access 自动交接保持 fail closed。
@@ -58,7 +65,8 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
正文。取消只中止本次 HTTP 等待,不承诺撤销服务端已执行的动作。网络错误只附白名单错误码,
仅 JSON-RPC `-32602` 明确参数错误附 schema,工具业务错误保留原反馈。
- **plan 模式**:挂 pi 自带 plan-mode 扩展,`/plan` toggle 驱动;Cindy 维护镜像态并在 resume
- 时从 `get_entries` 校正。
+ 时从本机 session JSONL 校正(只打开启动时 `--session-dir` 真身内的普通文件,
+ 并有字节/时间预算,超限回退 RPC);远端仍走 `get_entries`。
## 2. 配置面:Cindy 显式设置 vs 放任 pi 默认
diff --git a/docs/dev-rules/pi-remaining-work.md b/docs/dev-rules/pi-remaining-work.md
index 6c51cf63e3..82553c7e19 100644
--- a/docs/dev-rules/pi-remaining-work.md
+++ b/docs/dev-rules/pi-remaining-work.md
@@ -10,7 +10,7 @@
- Pi pin 升至 v0.83.0;Mac Intel/Apple Silicon、Linux x64/arm64、Windows x64/arm64
六平台资产有官方 digest pin,Forge 按目标平台 provision 完整目录并打包。
-- 文件附件、Extra Dirs(结构化写工具只读保护)、minimal thinking、纯 BYOM 无 Cindy 登录已开放。
+- 文件附件、Extra Dirs(结构化写跟随会话权限)、minimal thinking、纯 BYOM 无 Cindy 登录已开放。
- 精确 rewind 由 Pi `fork(entryId)` 裁剪对话,文件恢复复用 Cindy Git savepoint;与原会话树共用入口。
- Pi Auto Memory 控制面已开放,自动/手动 compaction summary 写 searchable digest;reset 复用
Maker Memory manager。
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index ccec82e38c..1f1f3c75fe 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -164,9 +164,11 @@
真正越出沙箱的技能继续使用 receipt 绑定的字节指纹与 Host 状态根快照。不要把审计字段误写成
全量运行时内容校验,也不要因取消能力确认弹窗而删除现有完整性守门。
- **Forge 的源码区与 Host 受管根互斥。** `ghost_forge_scaffold` / `ghost_forge_pack` /
- `ghost_forge_install` 的目标
- 必须是当前会话工作目录里的独立作者目录;命中安装根或状态根一律拒绝,并按 realpath
- 挡住大小写折叠与软链/junction 别名。`ghost_forge_pack` 只负责校验与打包;只有用户明确
+ `ghost_forge_install` 的目标必须是独立作者目录,不得是安装根或状态根;按 realpath
+ 挡住大小写折叠与软链/junction 别名。会话工作目录内直接放行;工作目录外走与
+ `ghost_call` 过户相同的会话权限路径(本地 Full Access 自动放行,Auto 交当前会话
+ AI 审阅,Ask 弹确认卡,远程/缺会话/查询失败 fail closed),禁止在 Host 已放行
+ 后再因目录边界悄悄硬断。`ghost_forge_pack` 只负责校验与打包;只有用户明确
要求后调用独立的 `ghost_forge_install` 才安装或更新,不因 scaffold/pack 成功而隐式安装。
- `skill` 是唯一**越出沙箱**的能力:技能指令由主 Agent 以用户全部权限执行、全局
生效、不随 workdir 级停用隐藏。其安全边界是**声明一致性**(manifest 里的
@@ -296,14 +298,20 @@
close/detach 已开始、会话缺失、实例不匹配、查询失败、远程会话均 fail closed。
对 Codex、Pi 与远端 Claude Code 这类进程外 harness,instance 只作为 opaque MCP route
identity 写入 Host 生成的 loopback URL;桥接层必须将 URL identity 与注册表中的当前实例
- 严格比对,不匹配直接 401。兼容旧客户端时,缺 instance 的 URL 可继续获得普通会话上下文,
+ 严格比对,不匹配直接 401。 兼容旧客户端时,缺 instance 的 URL 可继续获得普通会话上下文,
但必须剥除 instance 能力,使 Full Access 自动交接继续 fail closed。
+ 越界文件系统副作用(cindy-docs / 电脑工具的 `outside_workdir`,以及 Forge 的
+ `forge_source`)在缺少 instance、live grant 读不到或实例已失效时直接拒绝,
+ 不得退回仅凭用户确认的放行;附件过户仍可确认。
自动批准须区分 Full Access 与 AI 审阅来源,不得伪装为用户点击,也不得写入人工目录授权
记忆。附件自动交接必须写独立 `ghost-tool-grant`,不得写 `ghost-grant`;这是回退兼容
边界——旧客户端只认识后者,降级时必须 fail closed,不能把新版自动交接误读成人工永久
授权。切回 Ask 后新请求恢复确认。在途插件操作统一沿用当前会话的操作审批:包括工作区
- 草稿创建、工作目录写入和媒体路径揭示,Full Access 不额外审批,Auto 进入现有统一审阅器,
- Ask 沿用原确认流程。MCP 的 `prompt-each-time` 仅限制授权记忆,不得覆盖 Full Access,
+ 草稿创建、工作目录写入、媒体路径揭示,Forge 在工作目录外的打包/骨架,以及
+ cindy-docs / 电脑工具读写工作目录外路径,
+ Full Access 不额外审批,Auto 进入现有统一审阅器,
+ Ask 沿用原确认流程。越界路径的确认与执行绑定裁决时解析到的规范路径,
+ 工作目录里的 symlink 不能把真实目标藏成相对路径。MCP 的 `prompt-each-time` 仅限制授权记忆,不得覆盖 Full Access,
也不得跳过 Auto 审阅。审批期间实例、权限或调用归属失效时,旧 allow 不可执行。
Plan 与操作审批档位正交:Host 副作用须先检查实时 Plan 状态,未知或切换中拒绝;
Plan 切换代次也参与审批后和落盘前复核,不能以数据库镜像或切回原状态恢复旧授权。
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index 24feec871d..b07f65eff6 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -128,6 +128,8 @@ const D_GHOST_FORGE_SCAFFOLD = [
"template 可选:plain(普通沙箱工具)、agent-action(卡片点击后让 Agent 继续/分叉/新建)、",
"node-json-rpc(普通随包 Node 服务)、node-mcp(随包 stdio MCP)。Node 模板只写零依赖示例",
"源码,不会执行 npm install / npx / postinstall。生成后按需求修改,再调用 ghost_forge_pack。",
+ "会话工作目录内直接生成;工作目录外(例如相邻 worktree)走当前会话权限:",
+ "本地 Full Access 自动放行,Auto 交审阅,Ask 向用户确认。不要因为目录在工作目录外就改换目录或空转重试。",
].join("\n");
const D_GHOST_FORGE_PACK = [
@@ -135,7 +137,9 @@ const D_GHOST_FORGE_PACK = [
"缺省只打包并返回产物路径;intent=publish 时额外返回一次性 publishToken。",
"intent=publish 仅企业组织成员可用;个人账号仍可使用缺省的纯打包模式。",
"dir 传源码目录的绝对路径(目录里须有 ghost.json;打包自动跳过 .git / node_modules /",
- "隐藏文件 / *.cindy)。仅当用户明确选择 AI 生成图标时,可把图片工具结果的",
+ "隐藏文件 / *.cindy)。会话工作目录内直接打包;工作目录外走当前会话权限",
+ "(本地 Full Access 自动放行,Auto 交审阅,Ask 向用户确认),不要因此改换目录或空转重试。",
+ "仅当用户明确选择 AI 生成图标时,可把图片工具结果的",
"xdt_image_url 取单张地址;若只有 xdt_image_urls 则取数组第一项,再把得到的 cindy-media:// 地址传给 icon_source;主机会 best-effort 嵌入,失败保留默认图标继续打包。",
"失败返回结构化错误(MANIFEST_INVALID 等,message 带具体原因),",
"按 message 修正源码后重新打包即可。成功只表示 cindyPath 对应的产物已经生成;",
@@ -146,7 +150,7 @@ const D_GHOST_FORGE_INSTALL = [
"把当前源码目录重新校验、打包,并立即安装到 Cindy;同 id 已安装时原位更新。",
"只有用户明确要求安装或更新当前插件时才调用。不要因为 scaffold 或 pack 成功就自动调用。",
"首次安装后直接启用;更新保留原有启用状态、配置、数据与面板位置,同版本也可覆盖。",
- "dir 传当前会话工作目录内的插件源码目录绝对路径。成功返回本次真实执行的是 installed 还是 updated;",
+ "dir 传插件源码目录绝对路径(工作目录外走与 pack 相同的会话权限)。成功返回本次真实执行的是 installed 还是 updated;",
"仅当用户明确选择 AI 生成图标时,可像 ghost_forge_pack 一样传 icon_source。",
"失败返回打包校验或 Host 安装事务的结构化错误。ghost_forge_pack 始终只打包,不受本工具影响。",
].join("\n");
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index de605479fa..7988172265 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -224,7 +224,8 @@ export type CindyGhostCallResult =
/** ghost_forge_pack 的结构化失败分类(host 侧产生,原样透传给 agent)。 */
export type CindyForgePackErrorCode =
| 'DIR_NOT_FOUND' // 目录不存在或不是目录
- | 'SOURCE_OUTSIDE_WORKDIR' // 源目录不在当前会话工作目录内
+ | 'SOURCE_OUTSIDE_WORKDIR' // 源目录在工作目录外且未获当前会话权限,或会话工作目录缺失
+ | 'PERMISSION_DENIED' // 工作目录外源码未获 Full Access / Auto 审阅 / 用户确认
| 'WORKDIR_NOT_LOCAL' // 当前会话工作目录在远端或无法证明为本地
| 'WORKDIR_READ_ONLY' // 当前会话禁止写入
| 'SOURCE_IS_INSTALLED_PLUGIN' // 源目录命中 Host 管理的已安装插件或批准状态根
@@ -321,7 +322,7 @@ export type CindyForgeScaffoldResult =
}
| {
ok: false;
- errorCode: 'INVALID_INPUT' | 'TARGET_EXISTS' | 'WORKDIR_NOT_LOCAL' | 'WORKDIR_READ_ONLY' | 'INTERNAL';
+ errorCode: 'INVALID_INPUT' | 'TARGET_EXISTS' | 'WORKDIR_NOT_LOCAL' | 'WORKDIR_READ_ONLY' | 'PERMISSION_DENIED' | 'INTERNAL';
message: string;
};
diff --git a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts
index cb0a51d099..8f1a7ee7a3 100644
--- a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts
@@ -27,6 +27,7 @@ import JSZip from 'jszip';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createCindyDocsMcpServer } from '../cindy_docsMcpServer.js';
+import { setSessionPathAuthorizer } from '../session-path-auth.js';
import {
DOCX_MAX_MARKDOWN_BYTES,
DOCX_MAX_SUBTITLE_BYTES,
@@ -65,7 +66,7 @@ it('preserves the authoritative root including trailing whitespace', async () =>
await fs.mkdir(root);
await fs.mkdir(root.trim());
const output = await prepareOutputPath(resolveSessionRoot(sessionCtx({ workingDir: root })), 'result.txt', false);
- await fs.writeFile(output, 'exact');
+ await fs.writeFile(output.abs, 'exact');
expect(await fs.readFile(path.join(root, 'result.txt'), 'utf8')).toBe('exact');
await expect(fs.stat(path.join(root.trim(), 'result.txt'))).rejects.toMatchObject({ code: 'ENOENT' });
});
@@ -76,6 +77,7 @@ beforeEach(async () => {
});
afterEach(async () => {
+ setSessionPathAuthorizer(undefined);
vi.restoreAllMocks();
while (created.length > 0) {
const dir = created.pop()!;
@@ -1215,6 +1217,78 @@ describe('路径边界与覆盖语义', () => {
await expect(fs.stat(path.join(outside, 'escaped.docx'))).rejects.toThrow();
});
+ it('Host 授权后可以把文档写到工作目录外', async () => {
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-granted-'));
+ created.push(outside);
+ const outPath = path.join(await fs.realpath(outside), 'granted.docx');
+ setSessionPathAuthorizer(async (request) => {
+ expect(request.path).toBe(outPath);
+ expect(request.operation).toBe('write');
+ expect(request.toolName).toBe('make_docx');
+ return { allowed: true, isCurrent: () => true };
+ });
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# granted',
+ outPath,
+ });
+ expect(result.ok).toBe(true);
+ await expect(fs.stat(outPath)).resolves.toMatchObject({ size: expect.any(Number) });
+ });
+
+ it('Host 授权经工作目录链接时写入真实目标', async () => {
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-link-granted-'));
+ created.push(outside);
+ await fs.symlink(
+ outside,
+ path.join(workdir, 'link'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ const canonical = path.join(await fs.realpath(outside), 'escaped.docx');
+ setSessionPathAuthorizer(async (request) => {
+ expect(request.path).toBe(canonical);
+ return { allowed: true, isCurrent: () => true };
+ });
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# escaped',
+ outPath: 'link/escaped.docx',
+ });
+ expect(result.ok).toBe(true);
+ await expect(fs.stat(canonical)).resolves.toMatchObject({ size: expect.any(Number) });
+ });
+
+ it('Host 拒绝后工作目录外的文档写入仍失败', async () => {
+ const outside = path.join(os.tmpdir(), 'cindy-docs-denied.docx');
+ setSessionPathAuthorizer(async () => ({ allowed: false, reason: '审阅拒绝了这次越界写入。' }));
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# denied',
+ outPath: outside,
+ });
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ expect((result.data as Record<string, string>).hint).toContain('审阅拒绝');
+ await expect(fs.stat(outside)).rejects.toThrow();
+ });
+
+ it('授权后权限失效则不再落盘', async () => {
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-stale-grant-'));
+ created.push(outside);
+ const outPath = path.join(await fs.realpath(outside), 'stale.docx');
+ const isCurrent = vi.fn()
+ .mockReturnValueOnce(true)
+ .mockReturnValue(false);
+ setSessionPathAuthorizer(async () => ({ allowed: true, isCurrent }));
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# stale',
+ outPath,
+ });
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ expect((result.data as Record<string, string>).hint).toContain('当前任务权限');
+ await expect(fs.stat(outPath)).rejects.toThrow();
+ });
+
it('同名文件默认不覆盖,overwrite:true 才覆盖', async () => {
const client = await connect();
const first = await callTool(client, 'make_docx', {
@@ -1242,6 +1316,46 @@ describe('路径边界与覆盖语义', () => {
expect(await unzip(forced.path as string, 'word/document.xml')).toContain('第二版');
});
+ it('打开外部输入前授权代次失效则拒绝读取', async () => {
+ const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-stale-open-'));
+ created.push(outsideDir);
+ const granted = path.join(await fs.realpath(outsideDir), 'granted.txt');
+ await fs.writeFile(granted, 'granted-bytes');
+ await expect(readInputFileWithinLimit(
+ workdir,
+ granted,
+ 1024,
+ (bytes) => new DocsPathError('FILE_TOO_LARGE', String(bytes), 'too large'),
+ { allowOutsideRoot: true, isCurrent: () => false },
+ )).rejects.toMatchObject({ code: 'PATH_NOT_ALLOWED' });
+ });
+
+ it('获批的外部输入被换成符号链接后不再跟读', async () => {
+ const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-granted-read-'));
+ created.push(outsideDir);
+ const granted = path.join(await fs.realpath(outsideDir), 'granted.txt');
+ const other = path.join(await fs.realpath(outsideDir), 'other.txt');
+ await fs.writeFile(granted, 'granted-bytes');
+ await fs.writeFile(other, 'other-bytes');
+ await expect(readInputFileWithinLimit(
+ workdir,
+ granted,
+ 1024,
+ (bytes) => new DocsPathError('FILE_TOO_LARGE', String(bytes), 'too large'),
+ { allowOutsideRoot: true },
+ )).resolves.toEqual(Buffer.from('granted-bytes'));
+
+ await fs.rm(granted);
+ await fs.symlink(other, granted);
+ await expect(readInputFileWithinLimit(
+ workdir,
+ granted,
+ 1024,
+ (bytes) => new DocsPathError('FILE_TOO_LARGE', String(bytes), 'too large'),
+ { allowOutsideRoot: true },
+ )).rejects.toMatchObject({ code: 'PATH_NOT_ALLOWED' });
+ });
+
it('输入读取只接受与边界校验相同的已打开文件身份', async () => {
const inside = path.join(workdir, 'inside.txt');
const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-outside-'));
diff --git a/packages/lizi-mcps/src/__tests__/sessionPathAuth.test.ts b/packages/lizi-mcps/src/__tests__/sessionPathAuth.test.ts
new file mode 100644
index 0000000000..f8d061b6ba
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/sessionPathAuth.test.ts
@@ -0,0 +1,71 @@
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ authorizeSessionPathOutsideWorkdir,
+ resolveAbsoluteSessionPath,
+ resolveCanonicalSessionPath,
+ setSessionPathAuthorizer,
+} from '../session-path-auth.js';
+
+afterEach(() => {
+ setSessionPathAuthorizer(undefined);
+});
+
+describe('session path authorization', () => {
+ it('resolves relative paths against the session root', () => {
+ expect(resolveAbsoluteSessionPath('/repo', 'docs/a.pdf')).toBe(path.resolve('/repo', 'docs/a.pdf'));
+ expect(resolveAbsoluteSessionPath('/repo', '/tmp/out.pdf')).toBe(path.resolve('/tmp/out.pdf'));
+ });
+
+ it('binds a workdir symlink to the real outside target', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-session-path-wd-'));
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-session-path-out-'));
+ try {
+ await fs.symlink(
+ outside,
+ path.join(root, 'link'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ await expect(resolveCanonicalSessionPath(root, 'link/report.docx')).resolves.toBe(
+ path.join(await fs.realpath(outside), 'report.docx'),
+ );
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.rm(outside, { recursive: true, force: true });
+ }
+ });
+
+ it('fails closed for remote sessions and when no host authorizer is registered', async () => {
+ await expect(authorizeSessionPathOutsideWorkdir({
+ workingDir: '/repo',
+ remoteHostId: 'ssh-1',
+ path: '/tmp/out.pdf',
+ toolName: 'cindy-docs',
+ operation: 'write',
+ })).resolves.toMatchObject({ allowed: false });
+
+ await expect(authorizeSessionPathOutsideWorkdir({
+ workingDir: '/repo',
+ path: '/tmp/out.pdf',
+ toolName: 'cindy-docs',
+ operation: 'write',
+ })).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('delegates local decisions to the host authorizer', async () => {
+ setSessionPathAuthorizer(async (request) => {
+ expect(request.path).toBe(path.resolve('/tmp/out.pdf'));
+ return { allowed: true };
+ });
+ await expect(authorizeSessionPathOutsideWorkdir({
+ workingDir: '/repo',
+ path: path.resolve('/tmp/out.pdf'),
+ toolName: 'cindy-docs',
+ operation: 'write',
+ })).resolves.toEqual({ allowed: true });
+ });
+});
diff --git a/packages/lizi-mcps/src/cindy-docs/_paths.ts b/packages/lizi-mcps/src/cindy-docs/_paths.ts
index 76fe5fa81b..e7ab7779c6 100644
--- a/packages/lizi-mcps/src/cindy-docs/_paths.ts
+++ b/packages/lizi-mcps/src/cindy-docs/_paths.ts
@@ -5,7 +5,8 @@
* 才是权威**(resolveLiziMcpSessionContext:Claude 走闭包、Codex/Pi 走
* AsyncLocalStorage;解析不出归属时它会把 workingDir 抹成空串)。所有
* 模型给的路径先经 resolvePathInsideRoot 做「.. 穿越 + symlink 逃逸 + 绝对路径
- * 越界」三重钳制,再决定能不能写。
+ * 越界」三重钳制;越界后交给 Host 会话权限(bypass 放行 / auto 审阅 / ask 确认),
+ * 不再悄悄失败。
*
* 为什么写类工具默认不覆盖:文档产出常常是用户手里唯一的一份(改了三轮的报告),
* 模型重跑一次就静默盖掉是不可接受的。覆盖必须由模型显式 overwrite:true 表态。
@@ -14,9 +15,57 @@
import { constants as fsConstants, promises as fs, type BigIntStats } from 'node:fs';
import path from 'node:path';
-import { resolveLiziMcpSessionContext } from '../session-context.js';
+import { resolveLiziMcpSessionContext, getLiziMcpSessionContext } from '../session-context.js';
+import {
+ authorizeSessionPathOutsideWorkdir,
+ resolveCanonicalSessionPath,
+} from '../session-path-auth.js';
import { PathBoundaryError, resolvePathInsideRoot } from '../shared/assertInsidePath.js';
-import type { DocsMcpSessionCtx } from './types.js';
+import type { DocsMcpSessionCtx, WriteDocsOutputFn } from './types.js';
+
+export type PreparedDocsPath = {
+ abs: string;
+ authorizedOutsideWorkdir: boolean;
+ isCurrent?: () => boolean;
+};
+
+export function assertDocsGrantCurrent(isCurrent?: () => boolean): void {
+ if (isCurrent?.() === false) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ '任务权限已变化,这次越界路径授权已失效。',
+ '请用当前任务权限重试。',
+ );
+ }
+}
+
+export function docsReadOptions(prepared: PreparedDocsPath): {
+ allowOutsideRoot?: boolean;
+ isCurrent?: () => boolean;
+} {
+ return {
+ allowOutsideRoot: prepared.authorizedOutsideWorkdir,
+ ...(prepared.isCurrent ? { isCurrent: prepared.isCurrent } : {}),
+ };
+}
+
+export async function commitDocsOutput(
+ writeDocsOutput: WriteDocsOutputFn,
+ root: string,
+ prepared: PreparedDocsPath,
+ data: Uint8Array,
+ overwrite: boolean,
+): Promise<void> {
+ assertDocsGrantCurrent(prepared.isCurrent);
+ await writeDocsOutput({
+ root,
+ path: prepared.abs,
+ data,
+ overwrite,
+ authorizedOutsideWorkdir: prepared.authorizedOutsideWorkdir,
+ ...(prepared.isCurrent ? { isCurrent: prepared.isCurrent } : {}),
+ });
+}
/** 工具层可识别的路径类失败。code 直接进 payload 的 errorCode。 */
export class DocsPathError extends Error {
@@ -67,32 +116,70 @@ export function resolveSessionRoot(sessionCtx: DocsMcpSessionCtx): string {
}
/** 把 PathBoundaryError 统一翻成工具层的 PATH_NOT_ALLOWED。 */
-function toPathError(err: unknown, inputPath: string): never {
+function toPathError(err: unknown, inputPath: string, hint?: string): never {
if (err instanceof PathBoundaryError) {
throw new DocsPathError(
'PATH_NOT_ALLOWED',
err.message,
- `路径 "${inputPath}" 不在本任务的工作目录内。请改用工作目录内的相对路径(例如 documents/report.pdf)。`,
+ hint
+ ?? `路径 "${inputPath}" 不在本任务的工作目录内。请改用工作目录内的相对路径(例如 documents/report.pdf)。`,
);
}
throw err;
}
+async function resolveDocsPath(
+ root: string,
+ inputPath: string,
+ operation: 'read' | 'write',
+ sessionCtx?: DocsMcpSessionCtx,
+ toolName = 'cindy-docs',
+): Promise<PreparedDocsPath> {
+ try {
+ return {
+ abs: await resolvePathInsideRoot(root, inputPath),
+ authorizedOutsideWorkdir: false,
+ };
+ } catch (err) {
+ if (!(err instanceof PathBoundaryError)) throw err;
+ const ctx = sessionCtx
+ ? resolveLiziMcpSessionContext(sessionCtx)
+ : getLiziMcpSessionContext();
+ const abs = await resolveCanonicalSessionPath(root, inputPath);
+ const auth = await authorizeSessionPathOutsideWorkdir({
+ sessionId: ctx?.sessionId,
+ sessionInstanceId: ctx?.sessionInstanceId,
+ workingDir: root,
+ remoteHostId: ctx?.remoteHostId,
+ path: abs,
+ toolName,
+ operation,
+ });
+ if (!auth.allowed) toPathError(err, inputPath, auth.reason);
+ if (auth.isCurrent?.() === false) {
+ toPathError(err, inputPath, '任务权限已变化,这次越界路径授权已失效。请用当前任务权限重试。');
+ }
+ return {
+ abs,
+ authorizedOutsideWorkdir: true,
+ ...(auth.isCurrent ? { isCurrent: auth.isCurrent } : {}),
+ };
+ }
+}
+
/**
- * 校验并准备一个输出路径:边界钳制 → 覆盖判定。
- * 返回可直接写入的绝对路径。
+ * 校验并准备一个输出路径:边界钳制 → 会话权限 → 覆盖判定。
+ * 工作目录外的路径在 Host 授权后放行,不再悄悄失败。
*/
export async function prepareOutputPath(
root: string,
outPath: string,
overwrite: boolean,
-): Promise<string> {
- let abs: string;
- try {
- abs = await resolvePathInsideRoot(root, outPath);
- } catch (err) {
- toPathError(err, outPath);
- }
+ sessionCtx?: DocsMcpSessionCtx,
+ toolName = 'cindy-docs',
+): Promise<PreparedDocsPath> {
+ const prepared = await resolveDocsPath(root, outPath, 'write', sessionCtx, toolName);
+ const abs = prepared.abs;
let exists = true;
try {
@@ -108,7 +195,7 @@ export async function prepareOutputPath(
);
}
- return abs;
+ return prepared;
}
/** 生成器只允许与实际字节格式一致的后缀,避免产出“内容是 Word、名字却是 PDF”的文件。 */
@@ -124,17 +211,20 @@ export function assertOutputExtension(outPath: string, expectedExtension: string
}
/** 校验一个读取路径:边界钳制 + 必须是普通文件。 */
-export async function prepareInputPath(root: string, inPath: string): Promise<string> {
- let abs: string;
- try {
- abs = await resolvePathInsideRoot(root, inPath);
- } catch (err) {
- toPathError(err, inPath);
- }
+export async function prepareInputPath(
+ root: string,
+ inPath: string,
+ sessionCtx?: DocsMcpSessionCtx,
+ toolName = 'cindy-docs',
+): Promise<PreparedDocsPath> {
+ const prepared = await resolveDocsPath(root, inPath, 'read', sessionCtx, toolName);
+ const abs = prepared.abs;
let isFile = false;
try {
- const st = await fs.stat(abs);
- isFile = st.isFile();
+ const st = prepared.authorizedOutsideWorkdir
+ ? await fs.lstat(abs)
+ : await fs.stat(abs);
+ isFile = st.isFile() && !st.isSymbolicLink();
} catch {
isFile = false;
}
@@ -145,7 +235,7 @@ export async function prepareInputPath(root: string, inPath: string): Promise<st
`找不到文件 "${inPath}"。先确认它在本任务的工作目录里,并检查文件名与扩展名。`,
);
}
- return abs;
+ return prepared;
}
/**
@@ -210,14 +300,25 @@ export async function readInputFileWithinLimit(
abs: string,
maxBytes: number,
tooLarge: (bytes: number) => DocsPathError,
+ options?: { allowOutsideRoot?: boolean; isCurrent?: () => boolean },
): Promise<Buffer> {
+ assertDocsGrantCurrent(options?.isCurrent);
// 校验与读取绑定到同一个已打开文件身份,封住路径检查后父目录被换成根外
// symlink 的窗口;身份不可用的网络盘 fail closed,不拿 0 === 0 放行。
let canonicalPath: string;
let realRoot: string;
try {
- [canonicalPath, realRoot] = await Promise.all([fs.realpath(abs), fs.realpath(root)]);
- if (!isInsideRealRoot(realRoot, canonicalPath)) throw changedInputPath(abs);
+ if (options?.allowOutsideRoot) {
+ const listed = await fs.lstat(abs, { bigint: true });
+ if (!listed.isFile() || listed.isSymbolicLink()) throw changedInputPath(abs);
+ canonicalPath = abs;
+ realRoot = abs;
+ } else {
+ [canonicalPath, realRoot] = await Promise.all([fs.realpath(abs), fs.realpath(root)]);
+ if (!isInsideRealRoot(realRoot, canonicalPath)) {
+ throw changedInputPath(abs);
+ }
+ }
} catch (err) {
if (err instanceof DocsPathError) throw err;
if (err instanceof PathBoundaryError) toPathError(err, abs);
@@ -233,7 +334,9 @@ export async function readInputFileWithinLimit(
if (!stat.isFile() || !sameFileIdentity(expectedStat, stat)) {
throw changedInputPath(canonicalPath);
}
- await verifyOpenedInputStillInsideRoot(realRoot, canonicalPath, stat);
+ if (!options?.allowOutsideRoot) {
+ await verifyOpenedInputStillInsideRoot(realRoot, canonicalPath, stat);
+ }
if (stat.size > BigInt(maxBytes)) throw tooLarge(Number(stat.size));
const size = Number(stat.size);
@@ -252,7 +355,9 @@ export async function readInputFileWithinLimit(
if (offset !== data.length || !sameFileVersion(stat, after)) {
throw changedInputPath(canonicalPath);
}
- await verifyOpenedInputStillInsideRoot(realRoot, canonicalPath, after);
+ if (!options?.allowOutsideRoot) {
+ await verifyOpenedInputStillInsideRoot(realRoot, canonicalPath, after);
+ }
return data;
} finally {
await handle.close();
@@ -266,9 +371,10 @@ export function describeOutput(
bytes: number,
): { path: string; relativePath: string; bytes: number } {
const rel = path.relative(path.resolve(root), abs);
+ const outside = rel.startsWith('..') || path.isAbsolute(rel);
return {
path: abs,
- relativePath: rel.length > 0 ? rel : path.basename(abs),
+ relativePath: outside ? abs : (rel.length > 0 ? rel : path.basename(abs)),
bytes,
};
}
diff --git a/packages/lizi-mcps/src/cindy-docs/index.ts b/packages/lizi-mcps/src/cindy-docs/index.ts
index 66ec6c7d0f..ab9dd734dd 100644
--- a/packages/lizi-mcps/src/cindy-docs/index.ts
+++ b/packages/lizi-mcps/src/cindy-docs/index.ts
@@ -42,11 +42,15 @@ export {
} from './csv.js';
export {
DocsPathError,
+ assertDocsGrantCurrent,
+ commitDocsOutput,
describeOutput,
+ docsReadOptions,
prepareInputPath,
prepareOutputPath,
readInputFileWithinLimit,
resolveSessionRoot,
+ type PreparedDocsPath,
} from './_paths.js';
export { okPayload, errorPayload, type DocsPayloadResult } from './_payload.js';
diff --git a/packages/lizi-mcps/src/cindy-docs/inspect_pdf.ts b/packages/lizi-mcps/src/cindy-docs/inspect_pdf.ts
index 1f009b7c81..bc9f202f73 100644
--- a/packages/lizi-mcps/src/cindy-docs/inspect_pdf.ts
+++ b/packages/lizi-mcps/src/cindy-docs/inspect_pdf.ts
@@ -21,6 +21,7 @@ import { z } from 'zod';
import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
import {
+ docsReadOptions,
DocsPathError,
prepareInputPath,
readInputFileWithinLimit,
@@ -148,7 +149,8 @@ export function registerInspectPdfTool(
}
const carriedVerdict = previousVerdict ?? 'incomplete';
const root = resolveSessionRoot(sessionCtx);
- const abs = await prepareInputPath(root, inputPath);
+ const prepared = await prepareInputPath(root, inputPath, sessionCtx, 'inspect_pdf');
+ const abs = prepared.abs;
if (path.extname(abs).toLowerCase() !== '.pdf') {
return errorPayload(
'UNSUPPORTED_FORMAT',
@@ -167,6 +169,7 @@ export function registerInspectPdfTool(
`PDF 过大: ${bytes} 字节`,
`PDF 有 ${(bytes / 1024 / 1024).toFixed(1)} MB,超出检查上限(64 MB)。请先压缩或拆分 PDF。`,
),
+ docsReadOptions(prepared),
);
if (data.byteLength === 0) {
return errorPayload(
diff --git a/packages/lizi-mcps/src/cindy-docs/make_docx.ts b/packages/lizi-mcps/src/cindy-docs/make_docx.ts
index d216f91b48..0fb6dbe64e 100644
--- a/packages/lizi-mcps/src/cindy-docs/make_docx.ts
+++ b/packages/lizi-mcps/src/cindy-docs/make_docx.ts
@@ -10,6 +10,7 @@ import { z } from 'zod';
import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
import {
assertOutputExtension,
+ commitDocsOutput,
describeOutput,
DocsPathError,
prepareOutputPath,
@@ -92,7 +93,8 @@ export function registerMakeDocxTool(
try {
const root = resolveSessionRoot(sessionCtx);
assertOutputExtension(outPath, '.docx');
- const abs = await prepareOutputPath(root, outPath, overwrite);
+ const prepared = await prepareOutputPath(root, outPath, overwrite, sessionCtx, 'make_docx');
+ const abs = prepared.abs;
const trimmedTitle = title?.trim() ?? '';
const useCover = trimmedTitle.length > 0 && (cover ?? true);
const buffer = await markdownToDocxBuffer(markdown, {
@@ -101,7 +103,7 @@ export function registerMakeDocxTool(
...(trimmedTitle.length > 0 ? { title: trimmedTitle } : {}),
...(subtitle ? { subtitle } : {}),
});
- await writeDocsOutput({ root, path: abs, data: buffer, overwrite });
+ await commitDocsOutput(writeDocsOutput, root, prepared, buffer, overwrite);
return okPayload({
...describeOutput(root, abs, buffer.byteLength),
format: 'docx',
diff --git a/packages/lizi-mcps/src/cindy-docs/make_pptx.ts b/packages/lizi-mcps/src/cindy-docs/make_pptx.ts
index c2a5d830a9..13b7c3832b 100644
--- a/packages/lizi-mcps/src/cindy-docs/make_pptx.ts
+++ b/packages/lizi-mcps/src/cindy-docs/make_pptx.ts
@@ -17,7 +17,9 @@ import { z } from 'zod';
import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
import {
assertOutputExtension,
+ commitDocsOutput,
describeOutput,
+ docsReadOptions,
DocsPathError,
prepareInputPath,
prepareOutputPath,
@@ -485,7 +487,8 @@ export function registerMakePptxTool(
try {
const root = resolveSessionRoot(sessionCtx);
assertOutputExtension(outPath, '.pptx');
- const abs = await prepareOutputPath(root, outPath, overwrite);
+ const prepared = await prepareOutputPath(root, outPath, overwrite, sessionCtx, 'make_pptx');
+ const abs = prepared.abs;
const palette = resolveDocsTheme(theme as DocsThemeName);
// 图片先全部过边界闸和字节上限、再转成内存 data URI。后续 pptxgenjs 不再
@@ -495,7 +498,8 @@ export function registerMakePptxTool(
let totalImageBytes = 0;
for (const [index, slide] of slides.entries()) {
if (!slide.imagePath) continue;
- const imageAbs = await prepareInputPath(root, slide.imagePath);
+ const imagePrepared = await prepareInputPath(root, slide.imagePath, sessionCtx, 'make_pptx');
+ const imageAbs = imagePrepared.abs;
// pptxgenjs 只按扩展名决定内嵌的 content-type,喂个 .webp 进去会生成一个
// PowerPoint 打不开的坏包 —— 那正是「看着成功、其实交了坏文件」,必须先拦。
if (!isSupportedPptxImage(imageAbs)) {
@@ -517,6 +521,7 @@ export function registerMakePptxTool(
`第 ${index + 1} 页的图片过大: ${size} 字节`,
`图片 "${slide.imagePath}" 有 ${(size / 1024 / 1024).toFixed(1)} MB,超过单张图片上限(12 MB)。请先压缩或缩小图片。`,
),
+ docsReadOptions(imagePrepared),
);
const mime = detectPptxImageMime(bytes);
if (!mime || !(await validateDecodablePptxImage(bytes))) {
@@ -843,7 +848,7 @@ export function registerMakePptxTool(
const buffer = (await pptx.write({
outputType: 'nodebuffer',
})) as Buffer;
- await writeDocsOutput({ root, path: abs, data: buffer, overwrite });
+ await commitDocsOutput(writeDocsOutput, root, prepared, buffer, overwrite);
return okPayload({
...describeOutput(root, abs, buffer.byteLength),
format: 'pptx',
diff --git a/packages/lizi-mcps/src/cindy-docs/make_xlsx.ts b/packages/lizi-mcps/src/cindy-docs/make_xlsx.ts
index cf8ef8d055..160aefd470 100644
--- a/packages/lizi-mcps/src/cindy-docs/make_xlsx.ts
+++ b/packages/lizi-mcps/src/cindy-docs/make_xlsx.ts
@@ -11,6 +11,7 @@ import { z } from 'zod';
import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
import {
assertOutputExtension,
+ commitDocsOutput,
describeOutput,
DocsPathError,
prepareOutputPath,
@@ -341,7 +342,8 @@ export function registerMakeXlsxTool(
assertXlsxAggregateBounds(sheets);
const root = resolveSessionRoot(sessionCtx);
assertOutputExtension(outPath, '.xlsx');
- const abs = await prepareOutputPath(root, outPath, overwrite);
+ const prepared = await prepareOutputPath(root, outPath, overwrite, sessionCtx, 'make_xlsx');
+ const abs = prepared.abs;
const palette = resolveDocsTheme((theme ?? DEFAULT_DOCS_THEME) as DocsThemeName);
const workbook = new ExcelJS.Workbook();
@@ -454,12 +456,13 @@ export function registerMakeXlsxTool(
}
const arrayBuffer = await workbook.xlsx.writeBuffer();
- await writeDocsOutput({
+ await commitDocsOutput(
+ writeDocsOutput,
root,
- path: abs,
- data: Buffer.from(arrayBuffer as ArrayBuffer),
+ prepared,
+ Buffer.from(arrayBuffer as ArrayBuffer),
overwrite,
- });
+ );
return okPayload({
...describeOutput(root, abs, arrayBuffer.byteLength),
format: 'xlsx',
diff --git a/packages/lizi-mcps/src/cindy-docs/read_sheet.ts b/packages/lizi-mcps/src/cindy-docs/read_sheet.ts
index 8f0e191f84..096666162a 100644
--- a/packages/lizi-mcps/src/cindy-docs/read_sheet.ts
+++ b/packages/lizi-mcps/src/cindy-docs/read_sheet.ts
@@ -17,6 +17,7 @@ import { z } from 'zod';
import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
import {
DocsPathError,
+ docsReadOptions,
prepareInputPath,
readInputFileWithinLimit,
resolveSessionRoot,
@@ -55,7 +56,7 @@ const DESCRIPTION = [
'csv / tsv 支持 UTF-8,以及带 BOM 的 UTF-16LE / UTF-16BE 导出文件。',
'xlsx 会先检查文件大小与 ZIP 解压比,再在受限 worker 中解析(15 秒超时);超限会返回 FILE_TOO_LARGE/READ_TIMEOUT。',
'',
- '【读不到时】文件不在工作目录内会返回 PATH_NOT_ALLOWED,不存在返回 NOT_A_FILE。',
+ '【读不到时】未获授权的工作目录外路径返回 PATH_NOT_ALLOWED,不存在返回 NOT_A_FILE。',
'.xls(老二进制格式)不支持,先让用户另存为 .xlsx。',
].join('\n');
@@ -323,8 +324,15 @@ async function readXlsx(
maxRows: number,
startColumn: number,
maxColumns: number,
+ readOptions?: ReturnType<typeof docsReadOptions>,
): Promise<SheetRead> {
- const archive = await readInputFileWithinLimit(root, absPath, MAX_XLSX_BYTES, xlsxTooLarge);
+ const archive = await readInputFileWithinLimit(
+ root,
+ absPath,
+ MAX_XLSX_BYTES,
+ xlsxTooLarge,
+ readOptions,
+ );
return readXlsxInWorker(archive, sheetSelector, startRow, maxRows, startColumn, maxColumns);
}
@@ -336,6 +344,7 @@ async function readTextTable(
maxRows: number,
startColumn: number,
maxColumns: number,
+ readOptions?: ReturnType<typeof docsReadOptions>,
): Promise<SheetRead> {
const bytes = await readInputFileWithinLimit(
root,
@@ -347,6 +356,7 @@ async function readTextTable(
`文本表格过大: ${size} 字节`,
`这个文件有 ${(size / 1024 / 1024).toFixed(1)} MB,超出单次读取上限(32 MB)。请先让用户拆分文件,或改用命令行工具处理。`,
),
+ readOptions,
);
const text = decodeUnicodeText(bytes, '文本表格');
const parsed = parseDelimitedWindow(text, {
@@ -415,14 +425,21 @@ export function registerReadSheetTool(
handler: async ({ path: inputPath, sheet, startRow, maxRows, startColumn, maxColumns }) => {
try {
const root = resolveSessionRoot(sessionCtx);
- const abs = await prepareInputPath(root, inputPath);
+ const prepared = await prepareInputPath(root, inputPath, sessionCtx, 'read_sheet');
+ const abs = prepared.abs;
const ext = path.extname(abs).toLowerCase();
let result: SheetRead;
if (ext === '.xlsx' || ext === '.xlsm') {
- result = await readXlsx(root, abs, sheet, startRow, maxRows, startColumn, maxColumns);
+ result = await readXlsx(
+ root, abs, sheet, startRow, maxRows, startColumn, maxColumns,
+ docsReadOptions(prepared),
+ );
} else if (ext === '.csv' || ext === '.tsv' || ext === '.tab' || ext === '.txt') {
- result = await readTextTable(root, abs, ext, startRow, maxRows, startColumn, maxColumns);
+ result = await readTextTable(
+ root, abs, ext, startRow, maxRows, startColumn, maxColumns,
+ docsReadOptions(prepared),
+ );
} else if (ext === '.xls') {
return errorPayload(
'UNSUPPORTED_FORMAT',
diff --git a/packages/lizi-mcps/src/cindy-docs/render_pdf.ts b/packages/lizi-mcps/src/cindy-docs/render_pdf.ts
index 8a68ddec25..2a5dcb9680 100644
--- a/packages/lizi-mcps/src/cindy-docs/render_pdf.ts
+++ b/packages/lizi-mcps/src/cindy-docs/render_pdf.ts
@@ -19,7 +19,9 @@ import { z } from 'zod';
import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
import {
assertOutputExtension,
+ commitDocsOutput,
describeOutput,
+ docsReadOptions,
DocsPathError,
prepareInputPath,
prepareOutputPath,
@@ -78,6 +80,7 @@ const LOCAL_RESOURCE_MIME_TYPES: Record<string, string> = {
interface ResourceSnapshotContext {
root: string;
+ sessionCtx?: DocsMcpSessionCtx;
totalBytes: number;
resourceReferences: number;
cache: Map<string, string>;
@@ -804,7 +807,8 @@ async function snapshotLocalResource(
const lexicalCacheKey = `${path.resolve(absPath)}\0${mimeOverride ?? ''}`;
const lexicalCached = context.lexicalCache.get(lexicalCacheKey);
if (lexicalCached) return `${lexicalCached}${fragment}`;
- const preparedPath = await prepareInputPath(context.root, absPath);
+ const prepared = await prepareInputPath(context.root, absPath, context.sessionCtx, 'render_pdf');
+ const preparedPath = prepared.abs;
const cacheKey = `${path.resolve(preparedPath)}\0${mimeOverride ?? ''}`;
const cached = context.cache.get(cacheKey);
if (cached) return `${cached}${fragment}`;
@@ -823,6 +827,7 @@ async function snapshotLocalResource(
`本地资源过大: ${preparedPath}`,
`这份本地资源有 ${(size / 1024 / 1024).toFixed(1)} MB,超过单个资源上限(8 MB)。请压缩或改成更小的 data URI。`,
),
+ docsReadOptions(prepared),
);
const afterDirectory = await captureDirectorySnapshot(resourceDirectory);
if (!sameDirectorySnapshot(beforeDirectory, afterDirectory)) {
@@ -865,9 +870,11 @@ async function inlineLocalResources(
html: string,
expectedSourceDirectory?: DirectorySnapshot,
initialDirectorySnapshots?: Map<string, DirectorySnapshot>,
+ sessionCtx?: DocsMcpSessionCtx,
): Promise<string> {
const context: ResourceSnapshotContext = {
root,
+ sessionCtx,
totalBytes: 0,
resourceReferences: 0,
cache: new Map(),
@@ -1067,8 +1074,10 @@ export function registerRenderPdfTool(
try {
const root = resolveSessionRoot(sessionCtx);
assertOutputExtension(outPath, '.pdf');
- const abs = await prepareOutputPath(root, outPath, overwrite);
- const sourcePath = hasPath ? await prepareInputPath(root, htmlPath!) : undefined;
+ const prepared = await prepareOutputPath(root, outPath, overwrite, sessionCtx, 'render_pdf');
+ const abs = prepared.abs;
+ const sourcePrepared = hasPath ? await prepareInputPath(root, htmlPath!, sessionCtx, 'render_pdf') : undefined;
+ const sourcePath = sourcePrepared?.abs;
const sourceDirectory = sourcePath
? await captureDirectorySnapshot(path.dirname(sourcePath))
: undefined;
@@ -1083,6 +1092,7 @@ export function registerRenderPdfTool(
// the resource base between the HTML snapshot and inlining.
const sourceSnapshotPath = sourcePath
? await (async () => {
+ if (sourcePrepared?.authorizedOutsideWorkdir) return sourcePath;
const [realRoot, realSource] = await Promise.all([
fs.realpath(root),
fs.realpath(sourcePath),
@@ -1109,6 +1119,7 @@ export function registerRenderPdfTool(
`HTML 过大: ${bytes} 字节`,
`这份 HTML 有 ${(bytes / 1024 / 1024).toFixed(1)} MB,超出 PDF 渲染上限(16 MB)。请压缩内联图片/字体或拆分文档后重试。`,
),
+ sourcePrepared ? docsReadOptions(sourcePrepared) : undefined,
)
: undefined;
const sourceHtml = sourceBytes ? decodeUnicodeText(sourceBytes, 'HTML') : html!;
@@ -1128,6 +1139,7 @@ export function registerRenderPdfTool(
sourceHtml,
sourceDirectory,
initialDirectorySnapshots,
+ sessionCtx,
);
const palette = resolveDocsTheme((theme ?? DEFAULT_DOCS_THEME) as DocsThemeName);
const wrapped = applyReportTemplate(snapshotHtml, palette, template);
@@ -1173,7 +1185,7 @@ export function registerRenderPdfTool(
{},
);
}
- await writeDocsOutput({ root, path: abs, data: buffer, overwrite });
+ await commitDocsOutput(writeDocsOutput, root, prepared, buffer, overwrite);
const described = describeOutput(root, abs, buffer.byteLength);
const warnings: string[] = [];
diff --git a/packages/lizi-mcps/src/cindy-docs/types.ts b/packages/lizi-mcps/src/cindy-docs/types.ts
index 71527ed551..8238867e53 100644
--- a/packages/lizi-mcps/src/cindy-docs/types.ts
+++ b/packages/lizi-mcps/src/cindy-docs/types.ts
@@ -74,6 +74,10 @@ export type WriteDocsOutputFn = (input: {
path: string;
data: Uint8Array;
overwrite: boolean;
+ /** Host already authorized a path outside the session workingDir. */
+ authorizedOutsideWorkdir?: boolean;
+ /** Recheck immediately before the final write; stale grants must not commit. */
+ isCurrent?: () => boolean;
}) => Promise<void>;
/** 单页结构快照。宽高单位是 PDF point(1/72 英寸)。 */
diff --git a/packages/lizi-mcps/src/cindy_docsMcpServer.ts b/packages/lizi-mcps/src/cindy_docsMcpServer.ts
index 69a2292fa7..22d23565ba 100644
--- a/packages/lizi-mcps/src/cindy_docsMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_docsMcpServer.ts
@@ -53,8 +53,9 @@ import type { LiziMcpLogger } from './types.js';
*/
const D_COMMON_TAIL =
' 全部能力零系统依赖,不需要用户预先装 LibreOffice / Office 或任何外部程序。' +
- '所有输入输出路径必须在当前任务的工作目录内(建议放 documents/,文件名用「日期-主题」)。' +
- '错误码:`PATH_NOT_ALLOWED` 路径越界;`FILE_EXISTS` 目标已存在(确认覆盖再加 overwrite:true);' +
+ '输入输出路径默认落在当前任务的工作目录内(建议放 documents/,文件名用「日期-主题」)。' +
+ '工作目录外的路径会按当前任务权限放行、审阅或请用户确认,不会悄悄失败。' +
+ '错误码:`PATH_NOT_ALLOWED` 路径越界或未获授权;`FILE_EXISTS` 目标已存在(确认覆盖再加 overwrite:true);' +
'`ATOMIC_PUBLISH_UNSUPPORTED` 当前输出位置无法安全地原子防覆盖发布;' +
'`NOT_A_FILE` 输入找不到;`NO_SESSION_CONTEXT` 本次调用没绑定工作目录。';
diff --git a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
index fe19224842..24813c8078 100644
--- a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
+++ b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
@@ -3,12 +3,18 @@ import fsSync from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { setSessionPathAuthorizer } from '../session-path-auth.js';
+import * as sessionPathAuth from '../session-path-auth.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { createComputerMcpServer } from './server.js';
import type { ComputerMcpDeps } from '../types.js';
+afterEach(() => {
+ setSessionPathAuthorizer(undefined);
+});
+
const canLinkFile = (() => {
const root = fsSync.mkdtempSync(path.join(os.tmpdir(), 'computer-file-link-probe-'));
try {
@@ -951,10 +957,403 @@ describe('createComputerMcpServer', () => {
expect(payload.ok).toBe(false);
expect(payload.errorCode).toBe('PATH_NOT_ALLOWED');
expect(payload.data.message).toContain('省略 screenshot_out_file');
- expect(payload.data.message).toContain('workingDir 内');
+ expect(payload.data.message).toContain('工作目录');
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('dispatches an outside screenshot path after host authorization', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const outside = path.join(await fs.realpath(path.resolve(root, '..')), 'granted.png');
+ setSessionPathAuthorizer(async (request) => {
+ expect(request.path).toBe(outside);
+ expect(request.toolName).toBe('cindy-computer:get_window_state');
+ return { allowed: true };
+ });
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: root,
+ sessionId: 'screenshot-granted',
+ }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'get_window_state',
+ args: {
+ pid: 123,
+ window_id: 7,
+ capture_mode: 'vision',
+ screenshot_out_file: outside,
+ },
+ },
+ })) as { ok: boolean };
+
+ expect(payload.ok).toBe(true);
+ expect(deps.callTool).toHaveBeenCalledWith(
+ 'get_window_state',
+ expect.objectContaining({ screenshot_out_file: outside }),
+ expect.anything(),
+ );
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('does not dispatch an authorized screenshot after the live grant expires', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const outside = path.join(await fs.realpath(path.resolve(root, '..')), 'stale.png');
+ let remaining = 1;
+ setSessionPathAuthorizer(async () => ({
+ allowed: true,
+ isCurrent: () => remaining-- > 0,
+ }));
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: root,
+ sessionId: 'screenshot-stale',
+ }),
+ });
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'get_window_state',
+ args: {
+ pid: 123,
+ window_id: 7,
+ capture_mode: 'vision',
+ screenshot_out_file: outside,
+ },
+ },
+ })) as { ok: boolean; errorCode?: string };
+
+ expect(payload.ok).toBe(false);
+ expect(payload.errorCode).toBe('PATH_NOT_ALLOWED');
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('does not dispatch after the live grant expires during path rebind', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const outside = path.join(await fs.realpath(path.resolve(root, '..')), 'rebind-stale.png');
+ let current = true;
+ setSessionPathAuthorizer(async () => ({
+ allowed: true,
+ isCurrent: () => current,
+ }));
+ const originalBound = sessionPathAuth.authorizedSessionPathStillBound;
+ const bindSpy = vi.spyOn(sessionPathAuth, 'authorizedSessionPathStillBound').mockImplementation(
+ async (workingDir, authorized) => {
+ current = false;
+ return originalBound(workingDir, authorized);
+ },
+ );
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: root,
+ sessionId: 'screenshot-rebind-stale',
+ }),
+ });
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'get_window_state',
+ args: {
+ pid: 123,
+ window_id: 7,
+ capture_mode: 'vision',
+ screenshot_out_file: outside,
+ },
+ },
+ })) as { ok: boolean; errorCode?: string };
+
+ expect(payload.ok).toBe(false);
+ expect(payload.errorCode).toBe('PATH_NOT_ALLOWED');
+ expect(deps.callTool).not.toHaveBeenCalled();
+ bindSpy.mockRestore();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('does not dispatch an authorized screenshot after the parent is swapped to a symlink', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const grantedParent = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-shot-grant-')));
+ const evilParent = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-shot-evil-')));
+ const granted = path.join(grantedParent, 'out.png');
+ await fs.writeFile(path.join(evilParent, 'out.png'), 'evil');
+ setSessionPathAuthorizer(async () => {
+ await fs.rm(grantedParent, { recursive: true, force: true });
+ await fs.symlink(
+ evilParent,
+ grantedParent,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ return { allowed: true };
+ });
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: root,
+ sessionId: 'screenshot-swapped',
+ }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'get_window_state',
+ args: {
+ pid: 123,
+ window_id: 7,
+ capture_mode: 'vision',
+ screenshot_out_file: granted,
+ },
+ },
+ })) as { ok: boolean; errorCode?: string };
+
+ expect(payload.ok).toBe(false);
+ expect(payload.errorCode).toBe('PATH_NOT_ALLOWED');
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.rm(evilParent, { recursive: true, force: true });
+ await fs.rm(grantedParent, { recursive: true, force: true });
+ });
+
+ it('authorizes a workdir symlink screenshot path as the real target', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const outsideDir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-link-')));
+ await fs.symlink(
+ outsideDir,
+ path.join(root, 'link'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ const canonical = path.join(outsideDir, 'granted.png');
+ setSessionPathAuthorizer(async (request) => {
+ expect(request.path).toBe(canonical);
+ return { allowed: true };
+ });
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: root,
+ sessionId: 'screenshot-link-granted',
+ }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'get_window_state',
+ args: {
+ pid: 123,
+ window_id: 7,
+ capture_mode: 'vision',
+ screenshot_out_file: path.join(root, 'link', 'granted.png'),
+ },
+ },
+ })) as { ok: boolean };
+
+ expect(payload.ok).toBe(true);
+ expect(deps.callTool).toHaveBeenCalledWith(
+ 'get_window_state',
+ expect.objectContaining({ screenshot_out_file: canonical }),
+ expect.anything(),
+ );
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.rm(outsideDir, { recursive: true, force: true });
+ });
+
+ it('replays an outside trajectory after host authorization', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const outside = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-replay-out-')));
+ const directory = await writeTrajectory(outside, [
+ { tool: 'click', arguments: { pid: 123, window_id: 7, x: 10, y: 20 } },
+ ]);
+ setSessionPathAuthorizer(async (request) => {
+ expect(request.path).toBe(directory);
+ expect(request.operation).toBe('read');
+ expect(request.toolName).toBe('cindy-computer:replay_trajectory');
+ return { allowed: true };
+ });
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: directory, delay_ms: 0, stop_on_error: false },
+ },
+ })) as { ok: boolean; data: { attempted: number; succeeded: number } };
+
+ expect(payload).toMatchObject({ ok: true, data: { attempted: 1, succeeded: 1 } });
+ expect(deps.callTool).toHaveBeenCalledWith(
+ 'click',
+ { pid: 123, window_id: 7, x: 10, y: 20 },
+ expect.anything(),
+ );
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.rm(outside, { recursive: true, force: true });
+ });
+
+ it('authorizes a recorded outside screenshot path once before replay dispatch', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const outside = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-replay-shot-')));
+ const screenshot = path.join(outside, 'frame.png');
+ const directory = await writeTrajectory(root, [
+ {
+ tool: 'get_window_state',
+ arguments: {
+ pid: 123,
+ window_id: 7,
+ capture_mode: 'vision',
+ screenshot_out_file: screenshot,
+ },
+ },
+ ]);
+ const authorizer = vi.fn(async (request: { path: string; toolName?: string }) => {
+ expect(request.path).toBe(screenshot);
+ expect(request.toolName).toBe('cindy-computer:get_window_state');
+ return { allowed: true, isCurrent: () => true };
+ });
+ setSessionPathAuthorizer(authorizer);
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: directory, delay_ms: 0, stop_on_error: false },
+ },
+ })) as { ok: boolean; data: { attempted: number; succeeded: number } };
+
+ expect(payload).toMatchObject({ ok: true, data: { attempted: 1, succeeded: 1 } });
+ expect(authorizer).toHaveBeenCalledOnce();
+ expect(deps.callTool).toHaveBeenCalledWith(
+ 'get_window_state',
+ expect.objectContaining({ screenshot_out_file: screenshot }),
+ expect.anything(),
+ );
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.rm(outside, { recursive: true, force: true });
+ });
+
+ it('does not replay an outside trajectory after the live grant expires', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const outside = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-replay-stale-')));
+ const directory = await writeTrajectory(outside, [
+ { tool: 'click', arguments: { pid: 123, window_id: 7, x: 10, y: 20 } },
+ ]);
+ let remaining = 1;
+ setSessionPathAuthorizer(async () => ({
+ allowed: true,
+ isCurrent: () => remaining-- > 0,
+ }));
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: directory, delay_ms: 0, stop_on_error: false },
+ },
+ })) as { ok: boolean; errorCode?: string };
+
+ expect(payload.ok).toBe(false);
+ expect(payload.errorCode).toBe('PATH_NOT_ALLOWED');
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.rm(outside, { recursive: true, force: true });
+ });
+
+ it('does not follow a granted replay directory after it is replaced by a symlink', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const grantedParent = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-replay-grant-')));
+ const evilParent = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-replay-evil-')));
+ const grantedDir = await writeTrajectory(grantedParent, [
+ { tool: 'click', arguments: { pid: 1, window_id: 1, x: 1, y: 1 } },
+ ]);
+ await writeTrajectory(evilParent, [
+ { tool: 'click', arguments: { pid: 999, window_id: 999, x: 9, y: 9 } },
+ ]);
+ setSessionPathAuthorizer(async () => {
+ await fs.rm(grantedDir, { recursive: true, force: true });
+ await fs.symlink(
+ path.join(evilParent, 'rec'),
+ grantedDir,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ return { allowed: true };
+ });
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: grantedDir, delay_ms: 0, stop_on_error: false },
+ },
+ })) as { ok: boolean };
+
+ expect(payload.ok).toBe(false);
expect(deps.callTool).not.toHaveBeenCalled();
await h.cleanup();
await fs.rm(root, { recursive: true, force: true });
+ await fs.rm(grantedParent, { recursive: true, force: true });
+ await fs.rm(evilParent, { recursive: true, force: true });
});
it('suggests omitting screenshot_out_file when the session has no workingDir', async () => {
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.ts
index 083974bfc2..b98d6ae833 100644
--- a/packages/lizi-mcps/src/computer/server.ts
+++ b/packages/lizi-mcps/src/computer/server.ts
@@ -4,6 +4,11 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { jsonObjectArg } from '../json-object-arg.js';
import { resolvePathInsideRoot, PathBoundaryError } from '../shared/assertInsidePath.js';
+import {
+ authorizeSessionPathOutsideWorkdir,
+ authorizedSessionPathStillBound,
+ resolveCanonicalSessionPath,
+} from '../session-path-auth.js';
import type {
ComputerMcpCallContext,
ComputerMcpDeps,
@@ -108,10 +113,12 @@ interface ReplayTrajectoryAction {
turn: string;
tool: ComputerMcpToolName;
args: Record<string, unknown>;
+ authorizedOutsidePaths: Map<string, AuthorizedOutsidePath>;
}
interface ComputerDispatchOptions {
pathWorkingDirOverride?: string;
+ preAuthorizedOutsidePaths?: Map<string, AuthorizedOutsidePath>;
}
type ComputerMcpTextResult = ReturnType<typeof textResult>;
@@ -273,6 +280,113 @@ function readSessionId(options: ComputerMcpServerOptions): string | undefined {
return readCallContext(options)?.sessionId;
}
+function isInsideDir(parent: string, child: string): boolean {
+ if (parent === child) return true;
+ const rel = path.relative(parent, child);
+ return rel.length > 0 && !rel.startsWith('..') && !path.isAbsolute(rel);
+}
+
+type AuthorizedOutsidePath = {
+ path: string;
+ isCurrent?: () => boolean;
+};
+
+function authorizedDirPath(
+ authorizedOutsidePaths: Map<string, AuthorizedOutsidePath>,
+ key = 'dir',
+): string | undefined {
+ return authorizedOutsidePaths.get(key)?.path;
+}
+
+function outsideGrantExpired(grant?: AuthorizedOutsidePath): boolean {
+ return grant?.isCurrent?.() === false;
+}
+
+function staleOutsideGrantResult(tool: string, arg: string) {
+ return textResult(
+ {
+ ok: false,
+ errorCode: 'PATH_NOT_ALLOWED',
+ data: {
+ tool,
+ arg,
+ message: '任务权限已变化,这次越界路径授权已失效。请用当前任务权限重试。',
+ },
+ },
+ true,
+ );
+}
+
+function reboundOutsideGrantResult(tool: string, arg: string) {
+ return textResult(
+ {
+ ok: false,
+ errorCode: 'PATH_NOT_ALLOWED',
+ data: {
+ tool,
+ arg,
+ message: '已授权路径在回放前发生变化,已停止读取。请用当前任务权限重试。',
+ },
+ },
+ true,
+ );
+}
+
+function staleAuthorizedOutsideGrant(
+ authorizedOutsidePaths: Map<string, AuthorizedOutsidePath>,
+ tool: string,
+): ComputerMcpTextResult | null {
+ for (const [key, authorized] of authorizedOutsidePaths) {
+ if (outsideGrantExpired(authorized)) return staleOutsideGrantResult(tool, key);
+ }
+ return null;
+}
+
+async function replayDirGrantStillBound(
+ workingDir: string,
+ authorizedOutsidePaths: Map<string, AuthorizedOutsidePath>,
+): Promise<ComputerMcpTextResult | null> {
+ const dirGrant = authorizedOutsidePaths.get('dir');
+ if (!dirGrant) return null;
+ if (outsideGrantExpired(dirGrant)) return staleOutsideGrantResult('replay_trajectory', 'dir');
+ if (!await authorizedPathStillBound(workingDir, dirGrant)) {
+ return reboundOutsideGrantResult('replay_trajectory', 'dir');
+ }
+ if (outsideGrantExpired(dirGrant)) return staleOutsideGrantResult('replay_trajectory', 'dir');
+ return null;
+}
+
+async function authorizedPathStillBound(
+ workingDir: string,
+ authorized: AuthorizedOutsidePath,
+): Promise<boolean> {
+ return authorizedSessionPathStillBound(workingDir, authorized.path);
+}
+
+async function resolveReplayBoundPath(
+ workingRoot: string,
+ inputPath: string,
+ authorizedRoot?: string,
+): Promise<string> {
+ if (!authorizedRoot) return resolvePathInsideRoot(workingRoot, inputPath);
+ const resolved = path.isAbsolute(inputPath)
+ ? path.resolve(inputPath)
+ : path.resolve(workingRoot, inputPath);
+ let real: string;
+ try {
+ real = await fs.realpath(resolved);
+ } catch {
+ if (!isInsideDir(authorizedRoot, resolved)) {
+ throw new PathBoundaryError(`路径越界: "${inputPath}" 不在已授权回放目录内`);
+ }
+ return resolved;
+ }
+ if (!isInsideDir(authorizedRoot, real)) {
+ throw new PathBoundaryError(`路径越界: "${inputPath}" 不在已授权回放目录内`);
+ }
+ return resolved;
+}
+
export function createComputerMcpServer(
deps: ComputerMcpDeps,
options: ComputerMcpServerOptions = {},
@@ -345,16 +459,19 @@ export function createComputerMcpServer(
// Resolve every local path before a guard reads it. In particular,
// trajectory inspection must never follow a model-supplied path outside
- // the current task working directory.
+ // the current task working directory. Keep the grant map on this call so
+ // concurrent Codex HTTP dispatches cannot steal each other's authorized root.
+ const authorizedOutsidePaths = new Map(dispatchOptions?.preAuthorizedOutsidePaths);
const pathGuardError = await guardPathArgs(
name as ComputerMcpToolName,
parsedData,
dispatchOptions?.pathWorkingDirOverride,
+ authorizedOutsidePaths,
);
if (pathGuardError) return pathGuardError;
if (name === 'replay_trajectory') {
- return replayTrajectoryWithGuards(parsedData, signal);
+ return replayTrajectoryWithGuards(parsedData, signal, authorizedOutsidePaths);
}
// 快照代际护栏:element_index 指向"某次 get_window_state 的第几项",观察和
@@ -375,6 +492,31 @@ export function createComputerMcpServer(
}
if (signal?.aborted) return replayCancelledResult();
+ const workingDir = dispatchOptions?.pathWorkingDirOverride
+ ?? options.getSessionContext?.().workingDir
+ ?? '';
+ for (const [key, authorized] of authorizedOutsidePaths) {
+ if (outsideGrantExpired(authorized)) {
+ return staleOutsideGrantResult(name, key);
+ }
+ if (!workingDir || !await authorizedPathStillBound(workingDir, authorized)) {
+ return textResult(
+ {
+ ok: false,
+ errorCode: 'PATH_NOT_ALLOWED',
+ data: {
+ tool: name,
+ arg: key,
+ message: '已授权路径在派发前发生变化,已停止写入。请用当前任务权限重试。',
+ },
+ },
+ true,
+ );
+ }
+ }
+ const staleAfterBind = staleAuthorizedOutsideGrant(authorizedOutsidePaths, name);
+ if (staleAfterBind) return staleAfterBind;
+
const parsedArgs = withSessionArg(
name as ComputerMcpToolName,
parsedData,
@@ -528,7 +670,8 @@ export function createComputerMcpServer(
async function prepareReplayTrajectory(
parsedData: Record<string, unknown>,
- signal?: AbortSignal,
+ signal: AbortSignal | undefined,
+ authorizedOutsidePaths: Map<string, AuthorizedOutsidePath>,
): Promise<ReplayTrajectoryPreparation> {
const directory = parsedData.dir;
const workingDir = options.getSessionContext?.().workingDir ?? '';
@@ -550,7 +693,16 @@ export function createComputerMcpServer(
// a legitimate symlinked workspace (including macOS /var -> /private/var)
// is not rejected by a lexical alias mismatch.
trajectoryRoot = await fs.realpath(directory);
- await resolvePathInsideRoot(workingRoot, trajectoryRoot);
+ const authorizedRoot = authorizedDirPath(authorizedOutsidePaths);
+ if (authorizedRoot) {
+ const rebound = await replayDirGrantStillBound(workingDir, authorizedOutsidePaths);
+ if (rebound) return { error: rebound };
+ if (!isInsideDir(authorizedRoot, trajectoryRoot)) {
+ throw new PathBoundaryError('回放目录不再匹配已授权路径');
+ }
+ } else {
+ await resolvePathInsideRoot(workingRoot, trajectoryRoot);
+ }
let entryCount = 0;
const trajectoryDirectory = await fs.opendir(trajectoryRoot);
@@ -593,9 +745,12 @@ export function createComputerMcpServer(
for (const turn of candidates) {
try {
if (signal?.aborted) return { error: replayCancelledResult() };
- const turnPath = await resolvePathInsideRoot(
+ const rebound = await replayDirGrantStillBound(workingDir, authorizedOutsidePaths);
+ if (rebound) return { error: rebound };
+ const turnPath = await resolveReplayBoundPath(
workingRoot,
path.join(trajectoryRoot, turn),
+ authorizedDirPath(authorizedOutsidePaths),
);
if (!(await fs.lstat(turnPath)).isDirectory()) {
return {
@@ -606,9 +761,10 @@ export function createComputerMcpServer(
};
}
- const actionPath = await resolvePathInsideRoot(
+ const actionPath = await resolveReplayBoundPath(
workingRoot,
path.join(turnPath, 'action.json'),
+ authorizedDirPath(authorizedOutsidePaths),
);
if ((await fs.lstat(actionPath)).isSymbolicLink()) {
return {
@@ -619,7 +775,11 @@ export function createComputerMcpServer(
};
}
const canonicalActionPath = await fs.realpath(actionPath);
- await resolvePathInsideRoot(workingRoot, canonicalActionPath);
+ await resolveReplayBoundPath(
+ workingRoot,
+ canonicalActionPath,
+ authorizedDirPath(authorizedOutsidePaths),
+ );
const actionFile = await fs.open(actionPath, REPLAY_READ_FLAGS);
let actionText: string;
try {
@@ -633,7 +793,11 @@ export function createComputerMcpServer(
};
}
const currentCanonicalPath = await fs.realpath(actionPath);
- await resolvePathInsideRoot(workingRoot, currentCanonicalPath);
+ await resolveReplayBoundPath(
+ workingRoot,
+ currentCanonicalPath,
+ authorizedDirPath(authorizedOutsidePaths),
+ );
const currentStat = await fs.stat(currentCanonicalPath);
if (currentStat.dev !== stat.dev || currentStat.ino !== stat.ino) {
return {
@@ -715,9 +879,10 @@ export function createComputerMcpServer(
};
}
const args = parsed.data as Record<string, unknown>;
- const nestedPathError = await guardPathArgs(toolName, args, workingRoot);
+ const nestedGrants = new Map<string, AuthorizedOutsidePath>();
+ const nestedPathError = await guardPathArgs(toolName, args, workingRoot, nestedGrants);
if (nestedPathError) return { error: nestedPathError };
- actions.push({ turn, tool: toolName, args });
+ actions.push({ turn, tool: toolName, args, authorizedOutsidePaths: nestedGrants });
} catch (error) {
if (signal?.aborted) return { error: replayCancelledResult() };
deps.logger?.warn('failed to validate Computer Use trajectory action', {
@@ -802,9 +967,10 @@ export function createComputerMcpServer(
async function replayTrajectoryWithGuards(
parsedData: Record<string, unknown>,
- signal?: AbortSignal,
+ signal: AbortSignal | undefined,
+ authorizedOutsidePaths: Map<string, AuthorizedOutsidePath>,
) {
- const prepared = await prepareReplayTrajectory(parsedData, signal);
+ const prepared = await prepareReplayTrajectory(parsedData, signal, authorizedOutsidePaths);
if ('error' in prepared) return prepared.error;
const startedAt = Date.now();
@@ -822,6 +988,11 @@ export function createComputerMcpServer(
for (const [index, action] of prepared.actions.entries()) {
if (signal?.aborted) return replayCancelledResult();
+ const rebound = await replayDirGrantStillBound(
+ options.getSessionContext?.().workingDir ?? '',
+ authorizedOutsidePaths,
+ );
+ if (rebound) return rebound;
if (Date.now() - startedAt >= MAX_REPLAY_WALL_CLOCK_MS) {
return replayBudgetExceededResult();
}
@@ -834,6 +1005,7 @@ export function createComputerMcpServer(
// root. Reuse it so a symlink spelling of the session workingDir does
// not make those immutable absolute paths look lexically out of scope.
pathWorkingDirOverride: prepared.workingRoot,
+ preAuthorizedOutsidePaths: action.authorizedOutsidePaths,
});
if (signal?.aborted) return replayCancelledResult();
const payload = JSON.parse(result.content[0].text) as { outcome?: { status?: string }; data?: { outcome_unknown?: boolean } };
@@ -895,7 +1067,8 @@ export function createComputerMcpServer(
async function guardPathArgs(
name: ComputerMcpToolName,
parsedData: Record<string, unknown>,
- workingDirOverride?: string,
+ workingDirOverride: string | undefined,
+ authorizedOutsidePaths: Map<string, AuthorizedOutsidePath>,
) {
const argNames = COMPUTER_PATH_ARGS[name];
if (!argNames) return null;
@@ -923,6 +1096,35 @@ export function createComputerMcpServer(
parsedData[key] = await resolvePathInsideRoot(workingDir, value);
} catch (e) {
if (e instanceof PathBoundaryError) {
+ const sessionContext = options.getSessionContext?.();
+ const abs = await resolveCanonicalSessionPath(workingDir, value);
+ const existing = authorizedOutsidePaths.get(key);
+ if (
+ existing
+ && existing.path === abs
+ && existing.isCurrent?.() !== false
+ && await authorizedPathStillBound(workingDir, existing)
+ ) {
+ parsedData[key] = abs;
+ continue;
+ }
+ const auth = await authorizeSessionPathOutsideWorkdir({
+ sessionId: sessionContext?.sessionId,
+ sessionInstanceId: sessionContext?.sessionInstanceId,
+ workingDir,
+ remoteHostId: sessionContext?.remoteHostId,
+ path: abs,
+ toolName: `cindy-computer:${name}`,
+ operation: name === 'replay_trajectory' ? 'read' : 'write',
+ });
+ if (auth.allowed) {
+ parsedData[key] = abs;
+ authorizedOutsidePaths.set(key, {
+ path: abs,
+ ...(auth.isCurrent ? { isCurrent: auth.isCurrent } : {}),
+ });
+ continue;
+ }
return textResult(
{
ok: false,
@@ -931,8 +1133,8 @@ export function createComputerMcpServer(
tool: name,
arg: key,
message: key === 'screenshot_out_file'
- ? `${e.message} 请省略 screenshot_out_file 由 driver 使用默认路径,或将其改为当前 workingDir 内的路径。`
- : e.message,
+ ? `${auth.reason} 也可省略 screenshot_out_file 由 driver 使用默认路径。`
+ : auth.reason,
},
},
true,
diff --git a/packages/lizi-mcps/src/index.ts b/packages/lizi-mcps/src/index.ts
index 707c09f707..0c55df4dd1 100644
--- a/packages/lizi-mcps/src/index.ts
+++ b/packages/lizi-mcps/src/index.ts
@@ -39,6 +39,7 @@ export * from './cindy-docs/index.js';
export * from './orca/index.js';
export * from './session-context.js';
+export * from './session-path-auth.js';
export * from './lsp/index.js';
diff --git a/packages/lizi-mcps/src/session-path-auth.ts b/packages/lizi-mcps/src/session-path-auth.ts
new file mode 100644
index 0000000000..7b1e6d4b09
--- /dev/null
+++ b/packages/lizi-mcps/src/session-path-auth.ts
@@ -0,0 +1,106 @@
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+/**
+ * Host-owned authorization for a local filesystem path that resolved outside
+ * the current session workingDir. Cindy Desktop registers this once; other
+ * hosts may leave it unset, in which case the path stays fail-closed.
+ */
+export type SessionPathAuthorizationRequest = {
+ sessionId?: string;
+ sessionInstanceId?: string;
+ workingDir: string;
+ remoteHostId?: string;
+ path: string;
+ toolName: string;
+ operation: 'read' | 'write';
+};
+
+export type SessionPathAuthorization =
+ | { allowed: true; isCurrent?: () => boolean }
+ | { allowed: false; reason: string };
+
+export type SessionPathAuthorizer = (
+ request: SessionPathAuthorizationRequest,
+) => Promise<SessionPathAuthorization>;
+
+let authorizer: SessionPathAuthorizer | undefined;
+
+export function setSessionPathAuthorizer(next?: SessionPathAuthorizer): void {
+ authorizer = next;
+}
+
+export function getSessionPathAuthorizer(): SessionPathAuthorizer | undefined {
+ return authorizer;
+}
+
+export function resolveAbsoluteSessionPath(root: string, inputPath: string): string {
+ const rootAbs = path.resolve(root);
+ return path.isAbsolute(inputPath) ? path.resolve(inputPath) : path.resolve(rootAbs, inputPath);
+}
+
+/**
+ * Identity shown on the Host grant card and used for later I/O. Follows
+ * existing ancestors so a workdir symlink cannot hide an outside target.
+ */
+export async function resolveCanonicalSessionPath(root: string, inputPath: string): Promise<string> {
+ const lexical = resolveAbsoluteSessionPath(root, inputPath);
+ const tail: string[] = [];
+ let cursor = lexical;
+ for (;;) {
+ try {
+ const real = await fs.realpath(cursor);
+ return tail.length === 0 ? real : path.join(real, ...tail);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return lexical;
+ const parent = path.dirname(cursor);
+ if (parent === cursor) return lexical;
+ tail.unshift(path.basename(cursor));
+ cursor = parent;
+ }
+ }
+}
+
+/**
+ * Re-resolve the granted path and reject any symlink in the remaining
+ * ancestor chain. Missing leaf/parent is allowed so write targets can be
+ * bound before they exist.
+ */
+export async function authorizedSessionPathStillBound(
+ workingDir: string,
+ authorized: string,
+): Promise<boolean> {
+ if (await resolveCanonicalSessionPath(workingDir, authorized) !== authorized) return false;
+ let cursor = path.resolve(authorized);
+ const { root } = path.parse(cursor);
+ for (;;) {
+ try {
+ if ((await fs.lstat(cursor)).isSymbolicLink()) return false;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return false;
+ }
+ if (cursor === root) return true;
+ const parent = path.dirname(cursor);
+ if (parent === cursor) return true;
+ cursor = parent;
+ }
+}
+
+export async function authorizeSessionPathOutsideWorkdir(
+ request: SessionPathAuthorizationRequest,
+): Promise<SessionPathAuthorization> {
+ if (request.remoteHostId) {
+ return {
+ allowed: false,
+ reason: '远程会话不能授权控制端本机路径。请改用当前任务工作目录内的路径,或在本机会话中重试。',
+ };
+ }
+ const fn = authorizer;
+ if (!fn) {
+ return {
+ allowed: false,
+ reason: `路径 "${request.path}" 不在本任务的工作目录内。请改用工作目录内的相对路径。`,
+ };
+ }
+ return fn(request);
+}
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index 2badcd3d16..9b2a27ead7 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -621,7 +621,9 @@ describe('cindy-bridge extension source', () => {
expect(CINDY_BRIDGE_EXTENSION_SOURCE).not.toContain(
"if (credentialRead && permission.mode === 'bypassPermissions')",
);
- expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("if (permission.mode === 'bypassPermissions') return;");
+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain(
+ "if (permission.mode === 'bypassPermissions' && !controlPlaneWrite) return;",
+ );
expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('await ctx.ui.input(');
} finally {
rmSync(tempRoot, { recursive: true, force: true });
@@ -1720,21 +1722,18 @@ describe('cindy-bridge extension source', () => {
"if (event.toolName === 'cindy_pi_extension' || event.toolName === 'cindy_pi_command') return;",
);
expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain(
- "if (permission.mode === 'bypassPermissions') return;",
+ "if (permission.mode === 'bypassPermissions' && !controlPlaneWrite) return;",
);
});
- it('hard-blocks writes only in read-only reference roots, not external writable roots', () => {
+ it('bubbles Extra Dirs writes and forces confirmation for agent-home writes', () => {
const source = CINDY_BRIDGE_EXTENSION_SOURCE;
- const readOnlyGate = source.indexOf('permission.readOnlyRoots.some((root) =>');
- const credentialGate = source.indexOf('const environRead = isCindyShellTool(event.toolName)', readOnlyGate);
- expect(readOnlyGate).toBeGreaterThan(-1);
- expect(credentialGate).toBeGreaterThan(readOnlyGate);
- expect(source.slice(readOnlyGate, credentialGate)).not.toContain('permission.writableRoots');
+ expect(source).not.toContain('Cindy extra reference directories are read-only.');
+ expect(source).not.toContain('Cindy agent runtime directory is read-only.');
expect(source).not.toContain('Cindy blocks reading credential or key paths, even with Full access.');
expect(source).not.toContain('Cindy blocks reading process environment (/proc/*/environ), even with Full access.');
- expect(source).toContain('const writeInsideAnyGrantedRoot = (roots: readonly string[])');
- expect(source).toContain('&& !writeInsideWritableRoot');
+ expect(source).toContain('const controlPlaneWrite = Boolean(');
+ expect(source).toContain('...(controlPlaneWrite ? { controlPlaneWrite: true } : {})');
expect(source).toContain('resolvedWritePath: writeTargetResolved');
expect(source).toContain(
'resolvedWritableRoots: resolveWritableRootsForHost(permission.writableRoots)',
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
index a312896219..2c1b2f6d06 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
@@ -147,6 +147,7 @@ describe('cindy-subagent extension source', () => {
expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(
"copyFileSync(join(configHome, 'internal-extensions', 'cindy-bridge.ts'), bridgeExtension)",
);
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('copyManagedRipgrep(configHome, childConfigHome)');
expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('childConfigHome: childConfigHome');
});
@@ -610,4 +611,13 @@ describe('cindy-subagent extension source', () => {
expect(writeBack).toBeGreaterThan(-1);
expect(spawnCall).toBeGreaterThan(writeBack);
});
+
+ it('points durable children at a private staged ripgrep, not the parent configHome', () => {
+ const src = CINDY_SUBAGENT_RUNNER_SOURCE;
+ expect(src).toContain("childEnv.CINDY_PI_MANAGED_RG_PATH = childRg");
+ const writeBack = src.indexOf('childEnv.CINDY_PI_MANAGED_RG_PATH = childRg');
+ const spawnCall = src.indexOf('spawn(config.binary, childArgs');
+ expect(writeBack).toBeGreaterThan(-1);
+ expect(spawnCall).toBeGreaterThan(writeBack);
+ });
});
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 c14a538275..4e805ec21b 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
@@ -462,6 +462,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
resolvedCredentialPaths?: unknown;
resolvedWritePath?: unknown;
resolvedWritableRoots?: unknown;
+ controlPlaneWrite?: unknown;
},
): void {
const writeEvidence = toolName === 'write' || toolName === 'edit'
@@ -3590,6 +3591,70 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
rmSync(replacementWritableDir, { recursive: true, force: true });
});
+ it('forces an explicit decision for agent-home writes even under Full Access', async () => {
+ const review = vi.fn(async () => ({ verdict: 'allow' as const }));
+ const handle = await start('bypassPermissions', review);
+ const resolver = vi.fn(async (): Promise<{ kind: 'permission'; behavior: 'allow' | 'deny' }> => ({
+ kind: 'permission',
+ behavior: 'allow',
+ }));
+ handle.setInteractionResolver?.(resolver as never);
+
+ firePermissionRequest(
+ 'control-plane-bypass',
+ 'write',
+ { path: path.join(cwd, 'models.json') },
+ { controlPlaneWrite: true },
+ );
+ expect(await waitForResponse('control-plane-bypass')).toMatchObject({ confirmed: true });
+ expect(resolver).toHaveBeenCalledOnce();
+ expect(review).not.toHaveBeenCalled();
+
+ resolver.mockResolvedValueOnce({ kind: 'permission', behavior: 'deny' });
+ firePermissionRequest(
+ 'control-plane-deny',
+ 'write',
+ { path: path.join(cwd, 'models.json') },
+ { controlPlaneWrite: true },
+ );
+ expect(await waitForResponse('control-plane-deny')).toMatchObject({ confirmed: false });
+ await handle.close();
+ });
+
+ it('does not settle a pending agent-home write when switching to Full Access', async () => {
+ const handle = await start('ask');
+ handle.setInteractionResolver?.(async () => await new Promise(() => {}));
+ firePermissionRequest(
+ 'control-plane-pending',
+ 'write',
+ { path: path.join(cwd, 'models.json') },
+ { controlPlaneWrite: true },
+ );
+ await flush();
+ expect(captured.sent.find((m) => m.id === 'control-plane-pending')).toBeUndefined();
+ await handle.setPermissionMode?.('bypassPermissions');
+ expect(await waitForResponse('control-plane-pending')).toMatchObject({ confirmed: false });
+ await handle.close();
+ });
+
+ it('does not let Auto-review silently allow agent-home writes', async () => {
+ const review = vi.fn(async () => ({ verdict: 'allow' as const }));
+ const handle = await start('auto', review);
+ const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'allow' as const }));
+ handle.setInteractionResolver?.(resolver as never);
+
+ firePermissionRequest(
+ 'control-plane-auto',
+ 'write',
+ { path: path.join(cwd, 'models.json') },
+ { controlPlaneWrite: true },
+ );
+ expect(await waitForResponse('control-plane-auto')).toMatchObject({ confirmed: true });
+ expect(resolver).toHaveBeenCalledOnce();
+ expect(review).not.toHaveBeenCalled();
+ await handle.close();
+ });
+
it('reviews evidence for remote Pi destructive paths instead of using controller realpath', async () => {
const localSafeTarget = path.join(cwd, 'controller-safe-target');
const remoteLink = path.join(cwd, 'remote-link');
diff --git a/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts b/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts
index 2a0e5f0192..11dc74ad56 100644
--- a/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/rpc-client.test.ts
@@ -9,17 +9,19 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ PI_RPC_OVERSIZED_FRAME_ERROR,
PiRpcProcess,
PiRpcRequestTimeoutError,
type PiRpcSpawnOptions,
} from '../rpc-client.js';
-import type { PiTransport, PiLineHandler, PiCloseHandler } from '../transport.js';
+import type { PiTransport, PiLineHandler, PiCloseHandler, PiOversizedFrameHandler } from '../transport.js';
// ── Fake transport:捕获 writeLine,手动触发 onLine/onClose ─────────────
function makeFakeTransport() {
const written: Array<{ line: string; resolve: () => void; reject: (e: Error) => void }> = [];
let lineHandler: PiLineHandler | undefined;
let closeHandler: PiCloseHandler | undefined;
+ let oversizedHandler: PiOversizedFrameHandler | undefined;
const transport = {
writeLine: vi.fn((line: string) => {
return new Promise<void>((resolve, reject) => {
@@ -28,16 +30,18 @@ function makeFakeTransport() {
}),
onLine: vi.fn((h: PiLineHandler) => { lineHandler = h; return () => { lineHandler = undefined; }; }),
onClose: vi.fn((h: PiCloseHandler) => { closeHandler = h; return () => { closeHandler = undefined; }; }),
+ onOversizedFrame: vi.fn((h: PiOversizedFrameHandler) => { oversizedHandler = h; return () => { oversizedHandler = undefined; }; }),
onStderr: vi.fn(() => () => undefined),
close: vi.fn(async () => { closeHandler?.({ code: 0, signal: null, reason: 'test close' }); }),
isClosed: vi.fn(() => false),
get pid() { return 1234; },
} satisfies PiTransport;
const emitLine = (line: string) => lineHandler?.(line);
+ const emitOversized = () => oversizedHandler?.();
const drain = () => {
for (const w of written.splice(0)) w.resolve();
};
- return { transport, emitLine, drain, written };
+ return { transport, emitLine, emitOversized, drain, written };
}
function makeProc(overrides: Partial<PiRpcSpawnOptions> = {}) {
@@ -239,4 +243,33 @@ describe('PiRpcProcess close semantics (bridge-disconnect vs explicit close)', (
expect(killRemoteSession).toHaveBeenCalledTimes(2);
});
+
+ it('fails a pending get_entries immediately when the transport drops an oversized frame', async () => {
+ const { transport, emitOversized, drain } = makeFakeTransport();
+ const { proc } = makeProc({ transport });
+ const pending = proc.request({ type: 'get_entries' });
+ drain();
+ emitOversized();
+ await expect(pending).resolves.toMatchObject({
+ success: false,
+ command: 'get_entries',
+ error: PI_RPC_OVERSIZED_FRAME_ERROR,
+ });
+ });
+
+ it('does not fail a lone pending steer when an oversized event frame is dropped', async () => {
+ const { transport, emitLine, emitOversized, drain } = makeFakeTransport();
+ const { proc } = makeProc({ transport });
+ const pending = proc.request({ type: 'steer', message: 'keep going' });
+ drain();
+ emitOversized();
+ const sentFrame = JSON.parse(transport.writeLine.mock.calls[0][0] as string) as { id: string };
+ emitLine(JSON.stringify({
+ type: 'response', id: sentFrame.id, command: 'steer', success: true,
+ }));
+ await expect(pending).resolves.toMatchObject({
+ success: true,
+ command: 'steer',
+ });
+ });
});
diff --git a/packages/maker-core/src/agents/pi/__tests__/session-jsonl-scan.test.ts b/packages/maker-core/src/agents/pi/__tests__/session-jsonl-scan.test.ts
new file mode 100644
index 0000000000..d08ba4bccc
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/session-jsonl-scan.test.ts
@@ -0,0 +1,43 @@
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { scanPiSessionJsonl } from '../session-jsonl-scan.js';
+
+const dirs: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
+});
+
+async function sessionFile(lines: string[]): Promise<string> {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'pi-session-scan-'));
+ dirs.push(dir);
+ const file = path.join(dir, 'session.jsonl');
+ await writeFile(file, `${lines.join('\n')}\n`);
+ return file;
+}
+
+describe('scanPiSessionJsonl', () => {
+ it('collects user entry ids and the last plan-mode flag without loading image payloads', async () => {
+ const hugeImage = `{"type":"message","id":"img1","parentId":"root","message":{"role":"user","content":[{"type":"image","data":"${'A'.repeat(8000)}"}]}}`;
+ const file = await sessionFile([
+ '{"type":"session","version":3,"id":"s1"}',
+ '{"type":"message","id":"u1","parentId":null,"message":{"role":"user","content":[{"type":"text","text":"hi"}]}}',
+ hugeImage,
+ '{"type":"custom","id":"p1","customType":"plan-mode","data":{"enabled":true}}',
+ '{"type":"message","id":"a1","parentId":"u1","message":{"role":"assistant","content":[{"type":"text","text":"ok"}]}}',
+ '{"type":"custom","id":"p2","customType":"plan-mode","data":{"enabled":false}}',
+ ]);
+
+ const scan = await scanPiSessionJsonl(file);
+ expect(scan).not.toBeNull();
+ expect([...scan!.userEntryIds].sort()).toEqual(['img1', 'u1']);
+ expect(scan!.lastPlanModeEnabled).toBe(false);
+ });
+
+ it('returns null when the session file is missing', async () => {
+ await expect(scanPiSessionJsonl(path.join(os.tmpdir(), 'missing-pi-session.jsonl'))).resolves.toBeNull();
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/__tests__/transport.test.ts b/packages/maker-core/src/agents/pi/__tests__/transport.test.ts
index d3102c9540..fcf7fdbc82 100644
--- a/packages/maker-core/src/agents/pi/__tests__/transport.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/transport.test.ts
@@ -4,7 +4,7 @@
* 覆盖:
* - createPiStdioTransport:spawn 参数、onClose 单次、close() 幂等竞态
* (轮 21 H-1)、SIGTERM→SIGKILL 升级、writeLine 关闭后拒绝、stderr 缓冲
- * - attachJsonlReader:跨 chunk UTF-8、尾部 flush、OOM 守卫(轮 21 H-3)、
+ * - attachJsonlReader:跨 chunk UTF-8、尾部 flush、OOM 守卫后resync 到下一行、
* CRLF strip、error 事件不崩(轮 21 M-1)
*/
@@ -333,16 +333,29 @@ describe('attachJsonlReader', () => {
expect(lines).toEqual(['{"a":1}']);
});
- it('discards buffer over OOM guard (round 21 H-3)', () => {
+ it('discards an oversized unterminated line through its newline, then resumes (round 21 H-3)', () => {
const stream = makeStream();
const lines: string[] = [];
+ const oversized = vi.fn();
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- attachJsonlReader(stream, (l) => lines.push(l));
- // 超 16MB 无换行的流
+ attachJsonlReader(stream, (l) => lines.push(l), oversized);
+ // 超 16MB 无换行的流仍是同一行,不能把后续残余当新帧。
const big = 'a'.repeat(16 * 1024 * 1024 + 100);
stream.emit('data', big);
- // 缓冲被丢弃, 后续合法行不受影响
- stream.emit('data', '{"ok":1}\n');
+ stream.emit('data', 'residual-base64-fragment\n{"ok":1}\n');
+ expect(lines).toEqual(['{"ok":1}']);
+ expect(oversized).toHaveBeenCalledOnce();
+ expect(warnSpy).toHaveBeenCalled();
+ warnSpy.mockRestore();
+ });
+
+ it('does not emit leftover bytes of an oversized complete line as JSON', () => {
+ const stream = makeStream();
+ const lines: string[] = [];
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ attachJsonlReader(stream, (l) => lines.push(l));
+ const oversized = `${'a'.repeat(16 * 1024 * 1024 + 50)}\n{"ok":1}\n`;
+ stream.emit('data', oversized);
expect(lines).toEqual(['{"ok":1}']);
expect(warnSpy).toHaveBeenCalled();
warnSpy.mockRestore();
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 359ef816be..49bfb21fdb 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -3921,15 +3921,15 @@ export default async function cindyBridge(pi: any) {
// Best-effort capture; the permission boundary below remains authoritative.
}
}
- // Extra Dirs 的结构化写工具永远禁止,即使 Full access 也不能把“只读引用”静默
- // 升级成写目录。bash 仍由 Cindy 审批/模型指令约束(Pi 暂无 OS sandbox API)。
+ // Extra Dirs 的结构化写不再在 bridge 里静默硬拦:Full Access 与原生 Pi 一样放行,
+ // Auto 交 Host 审阅,Ask 弹确认。bash 仍由 Cindy 审批/模型指令约束(Pi 暂无 OS
+ // sandbox API)。
const targetPath = typeof event.input?.path === 'string' ? event.input.path : '';
// agent 运行时目录(configHome:models.json/权限档/subagent 快照/bridge 扩展)
// 是控制面:模型改写 models.json 的 baseUrl/apiKey 可把后续请求全部 MITM 到
- // 攻击者 endpoint, 会话内容随之外泄(R5 安全审计 H-4)。host 侧写入不经此门
- // (直连远端 fs / 本地 fs, 不走 pi 工具);模型的结构化写一律硬拦,含 Full access
- // —— 与 permission file 同等级防护(CINDY_PI_PERMISSION_FILE 已在 SECRET_ENV_NAMES
- // 剥离, models.json 走这条统一路径拦截)。
+ // 攻击者 endpoint。Host 侧写入不经此门;模型的结构化写不再静默硬拦,而是冒泡
+ // 并强制用户确认(含 Full Access)。CINDY_PI_PERMISSION_FILE 已在 SECRET_ENV_NAMES
+ // 剥离,models.json 走这条统一确认路径。
const agentHomeDir = process.env.PI_CODING_AGENT_DIR;
const subagentRunDir = process.env[SUBAGENT_RUN_DIR_ENV];
// 轮 40-w4-t12 HIGH-2 + 轮 40-w4-t13 HIGH:写目标 symlink 绕过 —— isInsideRoot
@@ -3956,39 +3956,11 @@ export default async function cindyBridge(pi: any) {
isInsideRoot(targetPath, subagentRunDir)
|| (writeTargetResolved !== null && isInsideRoot(writeTargetResolved, subagentRunDir))
);
- const writeInsideAnyGrantedRoot = (roots: readonly string[]) => targetPath
- && roots.some((root) => {
- let resolvedRoot: string | null = null;
- try {
- resolvedRoot = realpathSync(root);
- } catch {
- resolvedRoot = null;
- }
- return (
- isInsideRoot(targetPath, root)
- && writeTargetResolved !== null
- && resolvedRoot !== null
- && isInsideRoot(writeTargetResolved, resolvedRoot)
- );
- });
- const writeInsideWritableRoot = writeInsideAnyGrantedRoot(permission.writableRoots);
- if (
+ const controlPlaneWrite = Boolean(
targetPath
&& FILE_WRITE_BUILTINS.has(event.toolName)
&& (writeInsideAgentHome || writeInsideSubagentRun)
- ) {
- return { block: true, reason: 'Cindy agent runtime directory is read-only.' };
- }
- if (
- targetPath
- && FILE_WRITE_BUILTINS.has(event.toolName)
- && !writeInsideWritableRoot
- && permission.readOnlyRoots.some((root) =>
- isInsideRoot(targetPath, root)
- || (writeTargetResolved !== null && isInsideRoot(writeTargetResolved, root)))
- ) {
- return { block: true, reason: 'Cindy extra reference directories are read-only.' };
- }
+ );
// 凭证/密钥路径的内置只读工具与 bash 输入重定向都必须携带 canonical
// 证据,供 Ask/Auto 升级审批。Full access 不在这里硬拦 — 原生 Pi 没有这道门,
// 文本拦截也不是安全边界(可被变形绕过)。
@@ -4024,7 +3996,7 @@ export default async function cindyBridge(pi: any) {
// runtime capability and applies the current general permission policy before it
// issues a one-shot store grant. Let it reach that boundary in every mode.
if (event.toolName === 'cindy_pi_extension' || event.toolName === 'cindy_pi_command') return;
- if (permission.mode === 'bypassPermissions') return;
+ if (permission.mode === 'bypassPermissions' && !controlPlaneWrite) return;
// MCP discovery/one-tool schema inspection only returns metadata already
// supplied by connected servers. It is the read-only half of the gateway
// and never executes a capability, so Ask/Auto should not interrupt the user.
@@ -4073,6 +4045,7 @@ export default async function cindyBridge(pi: any) {
? {
resolvedWritePath: writeTargetResolved,
resolvedWritableRoots: resolveWritableRootsForHost(permission.writableRoots),
+ ...(controlPlaneWrite ? { controlPlaneWrite: true } : {}),
}
: {}),
}),
diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts
index 529e6fc465..3c6e29fe67 100644
--- a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts
@@ -757,6 +757,10 @@ function main() {
CINDY_PI_PERMISSION_FILE: config.permissionFile,
PI_CODING_AGENT_DIR: config.childConfigHome,
});
+ const childRg = path.join(config.childConfigHome, 'bin', process.platform === 'win32' ? 'rg.exe' : 'rg');
+ try {
+ if (fs.statSync(childRg).isFile()) childEnv.CINDY_PI_MANAGED_RG_PATH = childRg;
+ } catch (_) { /* parent may not have staged ripgrep */ }
let routeProxySessionToken = '';
try {
routeProxySessionToken = deriveRouteProxySessionToken(task);
diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
index 21089cca5b..f5bececf24 100644
--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
@@ -404,6 +404,22 @@ function readPermissionSnapshot() {
}
}
+function copyManagedRipgrep(parentHome, childHome) {
+ const name = process.platform === 'win32' ? 'rg.exe' : 'rg';
+ const source = join(parentHome, 'bin', name);
+ try {
+ if (!statSync(source).isFile()) return;
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return;
+ throw error;
+ }
+ const destDir = join(childHome, 'bin');
+ mkdirSync(destDir, { recursive: true, mode: 0o700 });
+ const dest = join(destDir, name);
+ copyFileSync(source, dest);
+ try { chmodSync(dest, 0o755); } catch (err) { /* best effort on Windows */ }
+}
+
function toolsFor(agent, permission) {
if (agent !== 'worker') return PROFILES[agent].tools;
// Ask/Auto are enforced by cindy-bridge inside the child. Its RPC UI request
@@ -898,6 +914,9 @@ async function launchDurableRun(binary, tasks, runtime, taskId, mode, context, d
try { chmodSync(permissionFile, 0o600); } catch (err) { /* best effort on Windows */ }
mkdirSync(childConfigHome, { recursive: true, mode: 0o700 });
copyFileSync(join(configHome, 'models.json'), join(childConfigHome, 'models.json'));
+ // Parent configHome is ephemeral. Durable children outlive it, so Pi native
+ // grep (PI_CODING_AGENT_DIR/bin) and the Cindy find override need a private copy.
+ copyManagedRipgrep(configHome, childConfigHome);
// Inherit the parent's frozen rules, not the possibly edited native user
// home. Child config outlives the parent when a durable run is detached.
for (const name of ${JSON.stringify(PI_GLOBAL_CONTEXT_FILE_NAMES)}) {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 34926974c1..24adb15aae 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -30,6 +30,7 @@ import { constants as fsConstants, promises as fs } from 'node:fs';
import { createHash, createHmac, randomBytes } from 'node:crypto';
import { piSupportedEfforts } from '@cindy/model-providers/pi-thinking-levels';
import { readPiGlobalContext } from './global-context.js';
+import { scanPiSessionJsonl } from './session-jsonl-scan.js';
/**
* 轮 40-w4-t5 CRITICAL:远端 agentHome 是 POSIX 路径($HOME/... 或展开后的
@@ -4276,6 +4277,7 @@ export class PiAgent extends BaseAgent {
let input: Record<string, unknown> = {};
let resolvedWritePath: string | null | undefined;
let resolvedWritableRoots: string[] | null | undefined;
+ let controlPlaneWrite = false;
const approvalPayload = approval.method === 'input'
? approval.placeholder
: approval.message;
@@ -4286,6 +4288,7 @@ export class PiAgent extends BaseAgent {
input?: unknown;
resolvedWritePath?: unknown;
resolvedWritableRoots?: unknown;
+ controlPlaneWrite?: unknown;
};
if (typeof payload.toolName === 'string' && payload.toolName) toolName = payload.toolName;
if (payload.input && typeof payload.input === 'object' && !Array.isArray(payload.input)) {
@@ -4306,6 +4309,7 @@ export class PiAgent extends BaseAgent {
? payload.resolvedWritableRoots as string[]
: null;
}
+ controlPlaneWrite = payload.controlPlaneWrite === true;
} catch {
/* malformed permission payload remains a generic, deny-by-default prompt */
}
@@ -4334,7 +4338,12 @@ export class PiAgent extends BaseAgent {
const requestUserDecision = async (
options: { forcePrompt: boolean; unavailableHandoff?: boolean },
): Promise<PiPermissionResolution | null> => {
- if (permissionMode === 'bypassPermissions' && !adopted && !turnPolicyForcePrompt) return 'allow';
+ if (
+ permissionMode === 'bypassPermissions'
+ && !adopted
+ && !turnPolicyForcePrompt
+ && !options.forcePrompt
+ ) return 'allow';
// Session wires the resolver immediately after handle creation. Keep a
// very fast Ask/gray request pending until that wiring exists instead
// of turning startup ordering into a denial. The runner timeout remains
@@ -4350,7 +4359,9 @@ export class PiAgent extends BaseAgent {
resolve(resolution);
};
unregister = registerPendingPrompt(requestId, {
- forcePrompt: adopted || turnPolicyForcePrompt,
+ // control-plane writes must keep forcePrompt across a Full Access
+ // hot-switch; otherwise dismissAllPendingPrompts would allow them.
+ forcePrompt: options.forcePrompt || adopted || turnPolicyForcePrompt,
...(options.unavailableHandoff ? { unavailableHandoff: true } : {}),
// Durable child: losing the surface parks the question.
deferWhenSurfaceLost: true,
@@ -4417,6 +4428,7 @@ export class PiAgent extends BaseAgent {
const resolveConfirmation = async (): Promise<PiPermissionResolution | null> => {
// Review resumed child evidence against current user authorization.
// Other modes retain the independent confirmation for adopted work.
+ if (controlPlaneWrite) return requestUserDecision({ forcePrompt: true });
if (adopted && permissionMode !== 'auto') return requestUserDecision({ forcePrompt: true });
if (permissionMode === 'bypassPermissions') {
return turnPolicyForcePrompt ? 'system-deny' : 'allow';
@@ -5365,7 +5377,39 @@ export class PiAgent extends BaseAgent {
throw err;
}
- const readPersistedPlanMode = async (): Promise<boolean | null> => {
+ let localSessionScanCache:
+ | { file: string; mtimeMs: number; size: number; scan: NonNullable<Awaited<ReturnType<typeof scanPiSessionJsonl>>> }
+ | null = null;
+
+ const readLocalSessionScan = async () => {
+ // 远端 sessionFile 不在本机;带图长任务的 get_entries 会撑破 16 Mi 字符 JSONL 帧。
+ if (remote || typeof sdkSessionId !== 'string' || !path.isAbsolute(sdkSessionId)) return null;
+ try {
+ const stat = await fs.stat(sdkSessionId);
+ if (
+ localSessionScanCache
+ && localSessionScanCache.file === sdkSessionId
+ && localSessionScanCache.mtimeMs === stat.mtimeMs
+ && localSessionScanCache.size === stat.size
+ ) {
+ return localSessionScanCache.scan;
+ }
+ const scan = await scanPiSessionJsonl(sdkSessionId);
+ if (scan) {
+ localSessionScanCache = {
+ file: sdkSessionId,
+ mtimeMs: stat.mtimeMs,
+ size: stat.size,
+ scan,
+ };
+ }
+ return scan;
+ } catch {
+ return null;
+ }
+ };
+
+ const readPersistedPlanModeFromEntries = async (): Promise<boolean | null> => {
const entriesResp = await proc.request({ type: 'get_entries' });
if (!entriesResp.success) return null;
const entries =
@@ -5387,24 +5431,36 @@ export class PiAgent extends BaseAgent {
return false;
};
+ const readPersistedPlanMode = async (): Promise<boolean | null> => {
+ const local = await readLocalSessionScan();
+ if (local) return local.lastPlanModeEnabled ?? false;
+ return readPersistedPlanModeFromEntries();
+ };
+
+ const readPiUserEntryIdsFromEntries = async (): Promise<Set<string> | null> => {
+ const response = await proc.request({ type: 'get_entries' });
+ if (!response.success) return null;
+ const data = typeof response.data === 'object' && response.data !== null ? (response.data as Record<string, unknown>) : null;
+ // malformed success 不能当“空历史”,否则下一次正常读取会把任意既有 user entry
+ // 误判成刚发送的消息并串错附件。
+ if (!Array.isArray(data?.entries)) return null;
+ const entries = data.entries;
+ const ids = new Set<string>();
+ for (const raw of entries) {
+ if (typeof raw !== 'object' || raw === null) continue;
+ const entry = raw as Record<string, unknown>;
+ if (entry.type !== 'message' || typeof entry.id !== 'string' || entry.id.length === 0) continue;
+ const message = typeof entry.message === 'object' && entry.message !== null ? (entry.message as Record<string, unknown>) : null;
+ if (message?.role === 'user') ids.add(entry.id);
+ }
+ return ids;
+ };
+
const readPiUserEntryIds = async (): Promise<Set<string> | null> => {
try {
- const response = await proc.request({ type: 'get_entries' });
- if (!response.success) return null;
- const data = typeof response.data === 'object' && response.data !== null ? (response.data as Record<string, unknown>) : null;
- // malformed success 不能当“空历史”,否则下一次正常读取会把任意既有 user entry
- // 误判成刚发送的消息并串错附件。
- if (!Array.isArray(data?.entries)) return null;
- const entries = data.entries;
- const ids = new Set<string>();
- for (const raw of entries) {
- if (typeof raw !== 'object' || raw === null) continue;
- const entry = raw as Record<string, unknown>;
- if (entry.type !== 'message' || typeof entry.id !== 'string' || entry.id.length === 0) continue;
- const message = typeof entry.message === 'object' && entry.message !== null ? (entry.message as Record<string, unknown>) : null;
- if (message?.role === 'user') ids.add(entry.id);
- }
- return ids;
+ const local = await readLocalSessionScan();
+ if (local) return local.userEntryIds;
+ return await readPiUserEntryIdsFromEntries();
} catch (error) {
this.deps.logger.warn('pi user-entry snapshot failed (attachment link unavailable)', {
message: error instanceof Error ? error.message : String(error),
@@ -5416,7 +5472,7 @@ export class PiAgent extends BaseAgent {
const reportAcceptedPiUserEntry = async (before: Set<string> | null, callback: SendOptions['onTranscriptUserEntry']): Promise<void> => {
if (!before || !callback) return;
// prompt RPC 在 Pi 的 preflight acceptance 点返回,entry 紧接着才 append。短轮询
- // get_entries,按“此前不存在的 user entry”取稳定 id;捕获失败只影响附件分支恢复,
+ // session JSONL / get_entries,按“此前不存在的 user entry”取稳定 id;捕获失败只影响附件分支恢复,
// 不能把已被 Pi 接受的发送伪报成失败。
for (let attempt = 0; attempt < 25; attempt += 1) {
const current = await readPiUserEntryIds();
@@ -5762,13 +5818,13 @@ export class PiAgent extends BaseAgent {
// plan 镜像与 pi 持久态对齐(resume 关键):pi 的 plan-mode 扩展在 session_start 会从
// session entry 自恢复 planModeEnabled,但不发 notify。若镜像固定为 false 而 pi 实为 true,
- // 由于 /plan 是 toggle + setPlanMode 幂等短路,会导致方向反转或关不掉。故从 get_entries
- // 读最后一条 plan-mode custom entry 的 enabled 校正镜像(get_entries 已验证暴露该 entry)。
+ // 由于 /plan 是 toggle + setPlanMode 幂等短路,会导致方向反转或关不掉。故从本机 session
+ // JSONL(远端仍走 get_entries)读活动分支上最后一条 plan-mode custom entry 的 enabled 校正镜像。
if (planModeExtAvailable) {
try {
planModeActive = await readPersistedPlanMode();
if (planModeActive === null) {
- this.deps.logger.warn('pi plan-mode state sync: get_entries failed or returned an invalid state; plan mirror remains unknown');
+ this.deps.logger.warn('pi plan-mode state sync: persisted session scan failed; plan mirror remains unknown');
}
} catch (err) {
planModeActive = null;
@@ -8071,6 +8127,7 @@ export class PiAgent extends BaseAgent {
let resolvedCredentialPaths: string[] | null | undefined;
let resolvedWritePath: string | null | undefined;
let resolvedWritableRoots: string[] | null | undefined;
+ let controlPlaneWrite = false;
try {
const rawPayload = method === 'input' ? event.placeholder : event.message;
const payload = JSON.parse(typeof rawPayload === 'string' ? rawPayload : '{}') as {
@@ -8079,6 +8136,7 @@ export class PiAgent extends BaseAgent {
resolvedCredentialPaths?: unknown;
resolvedWritePath?: unknown;
resolvedWritableRoots?: unknown;
+ controlPlaneWrite?: unknown;
};
if (typeof payload.toolName === 'string' && payload.toolName.length > 0) toolName = payload.toolName;
if (payload.input && typeof payload.input === 'object') input = payload.input as Record<string, unknown>;
@@ -8104,6 +8162,7 @@ export class PiAgent extends BaseAgent {
? payload.resolvedWritableRoots as string[]
: null;
}
+ controlPlaneWrite = payload.controlPlaneWrite === true;
} catch {
/* keep defaults */
}
@@ -8305,6 +8364,13 @@ export class PiAgent extends BaseAgent {
// 本轮策略命中时不吃 Full Access 短路:policy + bypassPermissions 已在 send 预检
// 拒绝、且 policy turn 持 host lease 堵死热切到 bypass,故此处 turnPolicyForcePrompt
// 为真本不可达;仍显式 fail-closed,避免任一上游闸门被绕过就静默放行破坏性调用。
+ if (controlPlaneWrite) {
+ sendPermissionResolution(await requestUserConfirmation({
+ forcePrompt: true,
+ requireExplicitDecision: true,
+ }));
+ return;
+ }
if (isFullAccessNow() && !turnPolicyForcePrompt) {
sendPermissionResolution('allow');
return;
diff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
index 5e3f88e94b..c6c204101c 100644
--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
@@ -1,6 +1,7 @@
import { execFile, spawnSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import {
+ constants as fsConstants,
createReadStream,
lstatSync,
readFileSync,
@@ -115,6 +116,31 @@ export async function clearPiSubagentDeletedTombstone(
}
}
+async function copyStagedRipgrep(
+ fromConfigHome: string,
+ toConfigHome: string,
+ fallbackSourcePath?: string,
+): Promise<void> {
+ const basename = process.platform === 'win32' ? 'rg.exe' : 'rg';
+ const candidates = [path.join(fromConfigHome, 'bin', basename)];
+ if (fallbackSourcePath && path.isAbsolute(fallbackSourcePath)) candidates.push(fallbackSourcePath);
+ for (const source of candidates) {
+ try {
+ const sourceStat = await fs.stat(source);
+ if (!sourceStat.isFile()) continue;
+ const destDir = path.join(toConfigHome, 'bin');
+ const dest = path.join(destDir, basename);
+ await fs.mkdir(destDir, { recursive: true, mode: 0o700 });
+ await fs.copyFile(source, dest, fsConstants.COPYFILE_FICLONE);
+ if (process.platform !== 'win32') await fs.chmod(dest, 0o755);
+ return;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ throw error;
+ }
+ }
+}
+
export type PiSubagentRunState = 'queued' | 'running' | 'completed' | 'failed' | 'stopped';
export interface PiSubagentTaskStatus {
@@ -2644,6 +2670,13 @@ async function resumeClaimedPiSubagentRun(
}
await fs.mkdir(childConfigHome, { recursive: true, mode: 0o700 });
await fs.writeFile(path.join(childConfigHome, 'models.json'), modelsJson, { mode: 0o600, flag: 'wx' });
+ await copyStagedRipgrep(
+ sourceConfigHome,
+ childConfigHome,
+ typeof launch.env.CINDY_PI_MANAGED_RG_PATH === 'string'
+ ? launch.env.CINDY_PI_MANAGED_RG_PATH
+ : undefined,
+ );
await fs.writeFile(bridgeExtension, bridgeSource, { mode: 0o600, flag: 'wx' });
await writeAtomicJson(permissionFile, launch.permissionSnapshot);
await fs.writeFile(runnerFile, runnerSource, { mode: 0o600, flag: 'wx' });
diff --git a/packages/maker-core/src/agents/pi/rpc-client.ts b/packages/maker-core/src/agents/pi/rpc-client.ts
index 3e55558ca8..51e509aabe 100644
--- a/packages/maker-core/src/agents/pi/rpc-client.ts
+++ b/packages/maker-core/src/agents/pi/rpc-client.ts
@@ -19,7 +19,7 @@ import type { PiTransport } from './transport.js';
export { attachJsonlReader } from './transport.js';
export { createPiStdioTransport } from './transport.js';
-export type { PiTransport, PiTransportCloseInfo, PiLineHandler, PiCloseHandler } from './transport.js';
+export type { PiTransport, PiTransportCloseInfo, PiLineHandler, PiCloseHandler, PiOversizedFrameHandler } from './transport.js';
/** pi RPC 响应帧。 */
export interface PiRpcResponse {
@@ -37,6 +37,9 @@ export interface PiRpcEvent {
[key: string]: unknown;
}
+export const PI_RPC_OVERSIZED_FRAME_ERROR =
+ 'RPC response exceeded 16 MiB and was discarded.';
+
export class PiRpcRequestTimeoutError extends Error {
readonly code = 'PI_RPC_TIMEOUT';
@@ -142,6 +145,7 @@ export class PiRpcProcess {
this.failAllPending(new Error(`pi process exited (code=${info.code}, signal=${info.signal})`));
opts.onExit({ code: info.code, signal: info.signal });
});
+ this.transport.onOversizedFrame?.(() => this.failOversizedPending());
}
get pid(): number | undefined {
@@ -378,6 +382,27 @@ export class PiRpcProcess {
}
}
+ private failOversizedPending(): void {
+ // 超限通知不带帧 type / 响应 id。事件帧(如 message_end)也可能超限;
+ // 只能结束能确定归属的 get_entries,不能把唯一 pending 的 steer/abort 猜成受害者。
+ const victims = [...this.pending.entries()].filter(([, entry]) => entry.commandType === 'get_entries');
+ if (victims.length === 0) {
+ this.logger.warn('pi rpc: discarded oversized JSONL frame with no matching pending get_entries');
+ return;
+ }
+ for (const [id, entry] of victims) {
+ clearTimeout(entry.timer);
+ this.pending.delete(id);
+ entry.resolve({
+ type: 'response',
+ id,
+ command: entry.commandType,
+ success: false,
+ error: PI_RPC_OVERSIZED_FRAME_ERROR,
+ });
+ }
+ }
+
private failAllPending(err: Error): void {
for (const [, entry] of this.pending) {
clearTimeout(entry.timer);
diff --git a/packages/maker-core/src/agents/pi/session-jsonl-scan.ts b/packages/maker-core/src/agents/pi/session-jsonl-scan.ts
new file mode 100644
index 0000000000..3ad43b5a3d
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/session-jsonl-scan.ts
@@ -0,0 +1,134 @@
+import { createReadStream } from 'node:fs';
+import { StringDecoder } from 'node:string_decoder';
+
+const ENTRY_PREFIX_CHARS = 4096;
+
+export interface PiSessionJsonlScan {
+ userEntryIds: Set<string>;
+ lastPlanModeEnabled: boolean | null;
+}
+
+function recordOf(value: unknown): Record<string, unknown> | null {
+ return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null;
+}
+
+function firstQuoted(field: string, prefix: string): string | undefined {
+ const match = new RegExp(`"${field}"\\s*:\\s*"([^"]*)"`).exec(prefix);
+ return match?.[1];
+}
+
+function extractEntryMeta(line: string): {
+ type?: string;
+ id?: string;
+ role?: string;
+ customType?: string;
+ planEnabled?: boolean;
+} {
+ const prefix = line.length > ENTRY_PREFIX_CHARS ? line.slice(0, ENTRY_PREFIX_CHARS) : line;
+ if (line.length <= 64 * 1024) {
+ try {
+ const entry = recordOf(JSON.parse(line));
+ if (!entry) return {};
+ const message = recordOf(entry.message);
+ const data = recordOf(entry.data);
+ return {
+ type: typeof entry.type === 'string' ? entry.type : undefined,
+ id: typeof entry.id === 'string' ? entry.id : undefined,
+ role: typeof message?.role === 'string' ? message.role : undefined,
+ customType: typeof entry.customType === 'string' ? entry.customType : undefined,
+ planEnabled: typeof data?.enabled === 'boolean' ? data.enabled : undefined,
+ };
+ } catch {
+ /* fall through to prefix scan for truncated / huge lines */
+ }
+ }
+ return {
+ type: firstQuoted('type', prefix),
+ id: firstQuoted('id', prefix),
+ role: firstQuoted('role', prefix),
+ customType: firstQuoted('customType', prefix),
+ };
+}
+
+function applyEntry(scan: PiSessionJsonlScan, line: string): void {
+ const trimmed = line.endsWith('\r') ? line.slice(0, -1) : line;
+ if (trimmed.length === 0) return;
+ const meta = extractEntryMeta(trimmed);
+ if (meta.type === 'message' && meta.role === 'user' && meta.id) {
+ scan.userEntryIds.add(meta.id);
+ }
+ if (meta.customType === 'plan-mode' && typeof meta.planEnabled === 'boolean') {
+ scan.lastPlanModeEnabled = meta.planEnabled;
+ }
+}
+
+/**
+ * 只扫 session JSONL 的元数据:user entry id 与最后一条 plan-mode。
+ * 不经过 Pi RPC,也不把整段带图历史装进 16 Mi 字符的 JSONL 响应帧。
+ */
+export async function scanPiSessionJsonl(sessionFile: string): Promise<PiSessionJsonlScan | null> {
+ return new Promise((resolve) => {
+ const scan: PiSessionJsonlScan = {
+ userEntryIds: new Set<string>(),
+ lastPlanModeEnabled: null,
+ };
+ const stream = createReadStream(sessionFile);
+ const decoder = new StringDecoder('utf8');
+ let buffer = '';
+ let prefix = '';
+ let skippingRestOfLine = false;
+ let settled = false;
+
+ const finish = (result: PiSessionJsonlScan | null): void => {
+ if (settled) return;
+ settled = true;
+ resolve(result);
+ };
+
+ const consumePrefixLine = (): void => {
+ if (prefix.length === 0) return;
+ applyEntry(scan, prefix);
+ prefix = '';
+ };
+
+ const emitCompleteLines = (): void => {
+ while (true) {
+ if (skippingRestOfLine) {
+ const newlineIndex = buffer.indexOf('\n');
+ if (newlineIndex === -1) {
+ buffer = '';
+ return;
+ }
+ buffer = buffer.slice(newlineIndex + 1);
+ skippingRestOfLine = false;
+ consumePrefixLine();
+ continue;
+ }
+ const newlineIndex = buffer.indexOf('\n');
+ if (newlineIndex === -1) {
+ if (buffer.length > ENTRY_PREFIX_CHARS) {
+ prefix = buffer.slice(0, ENTRY_PREFIX_CHARS);
+ buffer = '';
+ skippingRestOfLine = true;
+ }
+ return;
+ }
+ applyEntry(scan, buffer.slice(0, newlineIndex));
+ buffer = buffer.slice(newlineIndex + 1);
+ }
+ };
+
+ stream.on('data', (chunk: Buffer | string) => {
+ buffer += typeof chunk === 'string' ? chunk : decoder.write(chunk);
+ emitCompleteLines();
+ });
+ stream.on('error', () => finish(null));
+ stream.on('end', () => {
+ buffer += decoder.end();
+ emitCompleteLines();
+ if (!skippingRestOfLine && buffer.length > 0) applyEntry(scan, buffer);
+ else consumePrefixLine();
+ finish(scan);
+ });
+ });
+}
diff --git a/packages/maker-core/src/agents/pi/transport.ts b/packages/maker-core/src/agents/pi/transport.ts
index 128e691d4d..fbd939eed5 100644
--- a/packages/maker-core/src/agents/pi/transport.ts
+++ b/packages/maker-core/src/agents/pi/transport.ts
@@ -40,6 +40,7 @@ export interface PiTransportCloseInfo {
export type PiLineHandler = (line: string) => void;
export type PiCloseHandler = (info: PiTransportCloseInfo) => void;
+export type PiOversizedFrameHandler = () => void;
/**
* 双向 transport。一个实例只服务一个 PiRpcProcess (1:1)。
@@ -57,6 +58,12 @@ export interface PiTransport {
/** 注册关闭回调。触发后此 transport 不再可用, writeLine 一律 reject。 */
onClose(handler: PiCloseHandler): () => void;
+ /**
+ * (可选) 丢掉超限 JSONL 帧时通知协议层。合法 get_entries 带图历史可以超过
+ * 16 MiB;transport 必须保持存活,但对应 pending RPC 不能再空等超时。
+ */
+ onOversizedFrame?(handler: PiOversizedFrameHandler): () => void;
+
/** 主动关闭。幂等; resolve 后内部资源已释放。 */
close(reason?: string): Promise<void>;
@@ -132,6 +139,7 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
}
const lineHandlers = new Set<PiLineHandler>();
+ const oversizedHandlers = new Set<PiOversizedFrameHandler>();
const closeHandlers = new Set<PiCloseHandler>();
const stderrHandlers = new Set<(line: string) => void>();
const stderrBuffer: string[] = [];
@@ -174,6 +182,9 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
attachJsonlReader(child.stdout, (line) => {
if (closed) return;
for (const handler of lineHandlers) handler(line);
+ }, () => {
+ if (closed) return;
+ for (const handler of oversizedHandlers) handler();
});
attachJsonlReader(child.stderr, (line) => {
if (line.trim().length === 0) return;
@@ -304,6 +315,11 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
return () => { closeHandlers.delete(handler); };
},
+ onOversizedFrame(handler: PiOversizedFrameHandler): () => void {
+ oversizedHandlers.add(handler);
+ return () => { oversizedHandlers.delete(handler); };
+ },
+
close(reason = 'pi transport close()'): Promise<void> {
if (closed) return Promise.resolve();
if (closeAttempt) return closeAttempt;
@@ -345,45 +361,83 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo
* (pi docs/rpc.md 明确警告 Node readline 不合规。)
*
* 轮 21 H-3:缓冲无界增长防护 —— 损坏/恶意 pi 进程持续输出无 \n 的字节流时
- * buffer 无限累积会 OOM 整个进程。超过上限丢弃缓冲并告警(单条 JSONL 帧
- * 远超任何合法负载;pi 协议帧都是小 JSON)。
+ * buffer 无限累积会 OOM 整个进程。超过上限必须丢掉**当前这一行**并告警。
+ *
+ * 合法 `get_entries` 在带图长任务里可以超过 16 Mi 字符。超限不能把行边界重置成
+ * “从此开始是新帧”:那会把同一行的残余 base64 当下一行 JSON。正确做法是继续丢到
+ * 下一个 `\n`,再恢复分帧。
*/
-const MAX_JSONL_BUFFER_CHARS = 16 * 1024 * 1024;
+export const MAX_JSONL_BUFFER_CHARS = 16 * 1024 * 1024;
export function attachJsonlReader(
stream: NodeJS.ReadableStream,
onLine: (line: string) => void,
+ onOversizedFrame?: () => void,
): void {
let decoder = new StringDecoder('utf8');
let buffer = '';
+ let skippingOversizedLine = false;
- stream.on('data', (chunk: Buffer | string) => {
- buffer += typeof chunk === 'string' ? chunk : decoder.write(chunk);
- // OOM 守卫:超限丢弃缓冲(与 pi-manager 的 NDJSONDecoder 同策略)。
+ const resetDecoder = (): void => {
// 轮 40-w4-t9 HIGH:丢弃时**必须重建 StringDecoder** —— 否则被丢帧末尾
- // 残留的半个多字节字符会留在 decoder 内, 污染后续合法帧(JSONL 内容
- // 损坏或解析失败)。
- if (buffer.length > MAX_JSONL_BUFFER_CHARS) {
- console.warn(
- `[pi] JSONL line buffer exceeded ${MAX_JSONL_BUFFER_CHARS} chars without newline — discarding (corrupt stream?)`,
- );
+ // 残留的半个多字节字符会留在 decoder 内, 污染后续合法帧。
+ decoder = new StringDecoder('utf8');
+ };
+
+ const dropThroughNewline = (): boolean => {
+ const newlineIndex = buffer.indexOf('\n');
+ if (newlineIndex === -1) {
buffer = '';
- decoder = new StringDecoder('utf8');
- return;
+ resetDecoder();
+ return false;
}
+ buffer = buffer.slice(newlineIndex + 1);
+ skippingOversizedLine = false;
+ return true;
+ };
+
+ const emitCompleteLines = (): void => {
while (true) {
+ if (skippingOversizedLine) {
+ if (!dropThroughNewline()) return;
+ continue;
+ }
const newlineIndex = buffer.indexOf('\n');
- if (newlineIndex === -1) break;
+ if (newlineIndex === -1) {
+ if (buffer.length > MAX_JSONL_BUFFER_CHARS) {
+ console.warn(
+ `[pi] JSONL line buffer exceeded ${MAX_JSONL_BUFFER_CHARS} chars without newline — discarding until next newline`,
+ );
+ skippingOversizedLine = true;
+ onOversizedFrame?.();
+ dropThroughNewline();
+ }
+ return;
+ }
+ if (newlineIndex > MAX_JSONL_BUFFER_CHARS) {
+ console.warn(
+ `[pi] JSONL line exceeded ${MAX_JSONL_BUFFER_CHARS} chars — discarding oversized frame`,
+ );
+ onOversizedFrame?.();
+ buffer = buffer.slice(newlineIndex + 1);
+ continue;
+ }
let line = buffer.slice(0, newlineIndex);
buffer = buffer.slice(newlineIndex + 1);
if (line.endsWith('\r')) line = line.slice(0, -1);
onLine(line);
}
+ };
+
+ stream.on('data', (chunk: Buffer | string) => {
+ buffer += typeof chunk === 'string' ? chunk : decoder.write(chunk);
+ emitCompleteLines();
});
stream.on('end', () => {
buffer += decoder.end();
- if (buffer.length > 0) {
+ emitCompleteLines();
+ if (!skippingOversizedLine && buffer.length > 0 && buffer.length <= MAX_JSONL_BUFFER_CHARS) {
onLine(buffer.endsWith('\r') ? buffer.slice(0, -1) : buffer);
}
});
diff --git a/packages/maker-core/src/index.ts b/packages/maker-core/src/index.ts
index 367bae7737..fef40c0ff7 100644
--- a/packages/maker-core/src/index.ts
+++ b/packages/maker-core/src/index.ts
@@ -47,6 +47,7 @@ export type {
PiTransportCloseInfo,
PiLineHandler,
PiCloseHandler,
+ PiOversizedFrameHandler,
} from './agents/pi/transport.js';
// pi 远端 agentHome 文件操作原语(host 经 SSH 实现)。
export type { PiRemoteFileOps } from './agents/base-agent.js';