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(plugins): 完全访问下自动批准文件交接 (#1417)

Dash647dd11be0c0
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/attachmentGrant.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/attachmentGrant.test.ts
index ef07d5264c..d9932f936c 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/attachmentGrant.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/attachmentGrant.test.ts
@@ -1,6 +1,6 @@
/**
* attachmentGrant.test.ts — 用户图片过户单测(纯 DI,无 Electron)。
- * 覆盖:happy path 记账链路(blob 入账 + ghost-grant 引用 + 指纹返回)、
+ * 覆盖:happy path 记账链路(blob 入账 + 人工/工具交接引用 + 指纹返回)、
* 地址解析失败整批拒且零副作用、张数上限、空批直通、落库中途失败报错。
*/
@@ -88,7 +88,7 @@ describe('grantAttachmentsToGhost', () => {
expect((r as { message: string }).message).toContain('disk full');
});
- it('解析层给出 originKind(异步解析,总仓 blob 账本闸)→ 过户行按真实出生记账', async () => {
+ it('工具出生附件使用独立 ghost-tool-grant,避免旧版误当人工永久授权', async () => {
const { deps, addRef } = makeDeps({
// 异步 resolveImageUrl(接线层查账后附带出生);会话内生成图 = tool。
resolveImageUrl: async () => ({
@@ -99,7 +99,9 @@ describe('grantAttachmentsToGhost', () => {
});
const r = await grantAttachmentsToGhost(deps, { ghostId: 'g', urls: ['cindy-media://blobs/x.jpg'] });
expect(r.ok).toBe(true);
- expect(addRef).toHaveBeenCalledWith(expect.objectContaining({ originKind: 'tool' }));
+ expect(addRef).toHaveBeenCalledWith(
+ expect.objectContaining({ refKind: 'ghost-tool-grant', originKind: 'tool' }),
+ );
});
it('账本闸策略拒(GrantPolicyError)→ 整批拒零副作用,拒绝理由原样透出不落格式教学文案', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/dirDeposit.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/dirDeposit.test.ts
index c50f912b7c..ef1e51b6ba 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/dirDeposit.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/dirDeposit.test.ts
@@ -8,7 +8,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { collectDirFiles, DirDepositVault } from '../dirDeposit';
import { GHOST_DIR_DEPOSIT_TTL_MS } from '../../../shared/ghost';
@@ -168,7 +168,14 @@ describe('DirDepositVault userGranted 旁路(workdir 外确认卡通过后)', ()
await fs.promises.writeFile(path.join(outside, 'a.txt'), 'hello');
const vault = new DirDepositVault();
expect(vault.deposit({ ghostId: 'g1', dirAbs: outside, workdirAbs: workdir }).ok).toBe(false);
- const r = vault.deposit({ ghostId: 'g1', dirAbs: outside, workdirAbs: workdir, userGranted: true });
+ const expectedRealPath = await fs.promises.realpath(outside);
+ const r = vault.deposit({
+ ghostId: 'g1',
+ dirAbs: expectedRealPath,
+ workdirAbs: workdir,
+ userGranted: true,
+ expectedRealPath,
+ });
expect(r.ok).toBe(true);
if (r.ok) {
const taken = vault.take('g1', r.receipt.token);
@@ -202,4 +209,111 @@ describe('DirDepositVault userGranted 旁路(workdir 外确认卡通过后)', ()
});
expect(r.ok).toBe(false);
});
+
+ it('授权后的 canonical 路径被换成 symlink 时拒绝出票', async () => {
+ const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-approved-dir-'));
+ try {
+ const approved = path.join(root, 'approved');
+ const replacement = path.join(root, 'replacement');
+ await fs.promises.mkdir(approved);
+ await fs.promises.mkdir(replacement);
+ await fs.promises.writeFile(path.join(approved, 'approved.txt'), 'approved');
+ await fs.promises.writeFile(path.join(replacement, 'replacement.txt'), 'replacement');
+ const expectedRealPath = await fs.promises.realpath(approved);
+ const replacementRealPath = await fs.promises.realpath(replacement);
+ const moved = path.join(path.dirname(expectedRealPath), 'approved-moved');
+ await fs.promises.rename(expectedRealPath, moved);
+ try {
+ await fs.promises.symlink(
+ replacementRealPath,
+ expectedRealPath,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+
+ const result = new DirDepositVault().deposit({
+ ghostId: 'g1',
+ dirAbs: expectedRealPath,
+ workdirAbs: workdir,
+ userGranted: true,
+ expectedRealPath,
+ });
+
+ expect(result).toEqual({ ok: false, message: '路径在授权后发生变化,请重新确认' });
+ } finally {
+ await fs.promises.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('出票后、take 前根目录被换成外部 symlink:取票成功但实际 read 拒绝', async () => {
+ const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-dir-ticket-swap-'));
+ try {
+ const approved = path.join(root, 'approved');
+ const outside = path.join(root, 'outside');
+ await fs.promises.mkdir(approved);
+ await fs.promises.mkdir(outside);
+ await fs.promises.writeFile(path.join(approved, 'file.txt'), 'approved');
+ await fs.promises.writeFile(path.join(outside, 'file.txt'), 'outside');
+ const vault = new DirDepositVault();
+ const deposited = vault.deposit({
+ ghostId: 'g1',
+ dirAbs: approved,
+ workdirAbs: workdir,
+ userGranted: true,
+ });
+ if (!deposited.ok) throw new Error('deposit failed');
+
+ await fs.promises.rename(approved, `${approved}-moved`);
+ try {
+ await fs.promises.symlink(
+ outside,
+ approved,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+
+ const taken = vault.take('g1', deposited.receipt.token);
+ expect(taken).not.toBeNull();
+ await expect(taken!.files[0].read()).rejects.toThrow(/出票后发生变化/);
+ } finally {
+ await fs.promises.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('take 后单个文件被换成外部 symlink:read 仍拒绝', async () => {
+ const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-dir-file-swap-'));
+ try {
+ const approved = path.join(root, 'approved');
+ const outside = path.join(root, 'outside.txt');
+ await fs.promises.mkdir(approved);
+ const target = path.join(approved, 'file.txt');
+ await fs.promises.writeFile(target, 'approved');
+ await fs.promises.writeFile(outside, 'outside');
+ const vault = new DirDepositVault();
+ const deposited = vault.deposit({
+ ghostId: 'g1',
+ dirAbs: approved,
+ workdirAbs: workdir,
+ userGranted: true,
+ });
+ if (!deposited.ok) throw new Error('deposit failed');
+ const taken = vault.take('g1', deposited.receipt.token);
+ expect(taken).not.toBeNull();
+
+ await fs.promises.rename(target, `${target}.moved`);
+ try {
+ await fs.promises.symlink(outside, target, 'file');
+ } catch {
+ return;
+ }
+
+ await expect(taken!.files[0].read()).rejects.toThrow();
+ } finally {
+ await fs.promises.rm(root, { recursive: true, force: true });
+ }
+ });
});
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 c55b25eca6..c68d4e4499 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -641,6 +641,9 @@ describe('FORGE_GUIDE', () => {
'CONFIRM_DENIED',
'uploadDir',
'dir_deposit',
+ // 目录/保存交接的权限档契约:本地 Full Access 自动,其余/远程确认。
+ '本地 Full Access 会话则自动过户、不弹卡',
+ '远程会话仍由用户确认',
// fs 槽(2026-07-14):三档代写(私有目录/工作目录/save 票据)。
'fs-request',
"root: 'data'",
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/saveDeposit.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/saveDeposit.test.ts
index a75b382eda..b6027bfca4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/saveDeposit.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/saveDeposit.test.ts
@@ -5,7 +5,7 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SaveDepositVault, sanitizeSaveFileName } from '../dirDeposit.js';
import { GHOST_SAVE_DEPOSIT_MAX_USES, GHOST_SAVE_DEPOSIT_TTL_MS } from '../../../shared/ghost.js';
@@ -82,6 +82,176 @@ describe('SaveDepositVault', () => {
expect(await vault.write('g1', '00000000-0000-4000-8000-000000000000', 'a.txt', new Uint8Array([1]))).toBeNull();
});
+ it('写入前完整性校验失败会清掉本次创建的空文件,重试仍可使用原文件名', async () => {
+ const vault = new SaveDepositVault();
+ const deposited = vault.deposit({ ghostId: 'g1', dirAbs: saveDir, workdirAbs: workdir });
+ if (!deposited.ok) throw new Error('deposit failed');
+
+ const originalStatSync = fs.statSync.bind(fs);
+ const statSpy = vi.spyOn(fs, 'statSync').mockImplementationOnce((filePath) => {
+ const stat = originalStatSync(filePath);
+ return Object.assign(Object.create(Object.getPrototypeOf(stat)), stat, {
+ ino: stat.ino + 1,
+ }) as fs.Stats;
+ });
+ try {
+ await expect(
+ vault.write('g1', deposited.receipt.token, 'integrity.txt', new Uint8Array([1, 2, 3])),
+ ).resolves.toBeNull();
+ } finally {
+ statSpy.mockRestore();
+ }
+
+ const target = path.join(saveDir, 'integrity.txt');
+ expect(fs.existsSync(target)).toBe(false);
+ await expect(
+ vault.write('g1', deposited.receipt.token, 'integrity.txt', new Uint8Array([4])),
+ ).resolves.toEqual({ fileName: 'integrity.txt' });
+ expect(fs.readFileSync(target)).toEqual(Buffer.from([4]));
+ });
+
+ it('部分写入失败会清掉残留字节,重试不会被迫改名', async () => {
+ const vault = new SaveDepositVault();
+ const deposited = vault.deposit({ ghostId: 'g1', dirAbs: saveDir, workdirAbs: workdir });
+ if (!deposited.ok) throw new Error('deposit failed');
+
+ const target = path.join(saveDir, 'partial.bin');
+ const originalOpen = fs.promises.open.bind(fs.promises);
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementationOnce(async (...args) => {
+ const handle = await originalOpen(...args);
+ const originalWriteFile = handle.writeFile.bind(handle);
+ return {
+ stat: handle.stat.bind(handle),
+ writeFile: async (data: Uint8Array) => {
+ await originalWriteFile(data.subarray(0, 1));
+ throw new Error('simulated EIO');
+ },
+ truncate: handle.truncate.bind(handle),
+ close: handle.close.bind(handle),
+ } as unknown as fs.promises.FileHandle;
+ });
+ try {
+ await expect(
+ vault.write('g1', deposited.receipt.token, 'partial.bin', new Uint8Array([1, 2, 3])),
+ ).resolves.toBeNull();
+ } finally {
+ openSpy.mockRestore();
+ }
+
+ expect(fs.existsSync(target)).toBe(false);
+ await expect(
+ vault.write('g1', deposited.receipt.token, 'partial.bin', new Uint8Array([4, 5])),
+ ).resolves.toEqual({ fileName: 'partial.bin' });
+ expect(fs.readFileSync(target)).toEqual(Buffer.from([4, 5]));
+ });
+
+ it('写入失败期间目标被替换时不误删替代文件', async () => {
+ if (process.platform === 'win32') return;
+
+ const vault = new SaveDepositVault();
+ const deposited = vault.deposit({ ghostId: 'g1', dirAbs: saveDir, workdirAbs: workdir });
+ if (!deposited.ok) throw new Error('deposit failed');
+
+ const target = path.join(saveDir, 'replacement.bin');
+ const moved = `${target}.moved`;
+ const originalOpen = fs.promises.open.bind(fs.promises);
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementationOnce(async (...args) => {
+ const handle = await originalOpen(...args);
+ const originalWriteFile = handle.writeFile.bind(handle);
+ return {
+ stat: handle.stat.bind(handle),
+ writeFile: async (data: Uint8Array) => {
+ await originalWriteFile(data.subarray(0, 1));
+ await fs.promises.rename(target, moved);
+ await fs.promises.writeFile(target, Buffer.from('replacement'));
+ throw new Error('simulated EIO');
+ },
+ truncate: handle.truncate.bind(handle),
+ close: handle.close.bind(handle),
+ } as unknown as fs.promises.FileHandle;
+ });
+ try {
+ await expect(
+ vault.write('g1', deposited.receipt.token, 'replacement.bin', new Uint8Array([1, 2, 3])),
+ ).resolves.toBeNull();
+ } finally {
+ openSpy.mockRestore();
+ }
+
+ expect(fs.readFileSync(target, 'utf8')).toBe('replacement');
+ expect(fs.existsSync(moved)).toBe(true);
+ expect(fs.readFileSync(moved)).toHaveLength(0);
+ });
+
+ it('写入完成后目标被移出批准目录时拒绝并清空原 inode', async () => {
+ if (process.platform === 'win32') return;
+
+ const vault = new SaveDepositVault();
+ const deposited = vault.deposit({ ghostId: 'g1', dirAbs: saveDir, workdirAbs: workdir });
+ if (!deposited.ok) throw new Error('deposit failed');
+
+ const target = path.join(saveDir, 'post-write-move.bin');
+ const moved = `${target}.moved`;
+ const originalOpen = fs.promises.open.bind(fs.promises);
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementationOnce(async (...args) => {
+ const handle = await originalOpen(...args);
+ const originalWriteFile = handle.writeFile.bind(handle);
+ return {
+ stat: handle.stat.bind(handle),
+ writeFile: async (data: Uint8Array) => {
+ await originalWriteFile(data);
+ await fs.promises.rename(target, moved);
+ },
+ truncate: handle.truncate.bind(handle),
+ close: handle.close.bind(handle),
+ } as unknown as fs.promises.FileHandle;
+ });
+ try {
+ await expect(
+ vault.write('g1', deposited.receipt.token, 'post-write-move.bin', new Uint8Array([1, 2, 3])),
+ ).resolves.toBeNull();
+ } finally {
+ openSpy.mockRestore();
+ }
+
+ expect(fs.existsSync(target)).toBe(false);
+ expect(fs.readFileSync(moved)).toHaveLength(0);
+ });
+
+ it('close 失败按统一 null 语义返回并清理已创建文件', async () => {
+ const vault = new SaveDepositVault();
+ const deposited = vault.deposit({ ghostId: 'g1', dirAbs: saveDir, workdirAbs: workdir });
+ if (!deposited.ok) throw new Error('deposit failed');
+
+ const target = path.join(saveDir, 'close-failure.bin');
+ const originalOpen = fs.promises.open.bind(fs.promises);
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementationOnce(async (...args) => {
+ const handle = await originalOpen(...args);
+ const originalWriteFile = handle.writeFile.bind(handle);
+ const originalClose = handle.close.bind(handle);
+ let closeCalls = 0;
+ return {
+ stat: handle.stat.bind(handle),
+ writeFile: (data: Uint8Array) => originalWriteFile(data),
+ truncate: handle.truncate.bind(handle),
+ close: async () => {
+ closeCalls += 1;
+ if (closeCalls === 1) throw new Error('simulated close failure');
+ await originalClose();
+ },
+ } as unknown as fs.promises.FileHandle;
+ });
+ try {
+ await expect(
+ vault.write('g1', deposited.receipt.token, 'close-failure.bin', new Uint8Array([1, 2, 3])),
+ ).resolves.toBeNull();
+ } finally {
+ openSpy.mockRestore();
+ }
+
+ expect(fs.existsSync(target)).toBe(false);
+ });
+
it('TTL 过期 / 次数写满自动作废', async () => {
let now = 1_000_000;
const vault = new SaveDepositVault(() => now);
@@ -105,7 +275,14 @@ describe('SaveDepositVault userGranted 旁路(workdir 外确认卡通过后)', (
try {
const vault = new SaveDepositVault();
expect(vault.deposit({ ghostId: 'g1', dirAbs: outside, workdirAbs: workdir }).ok).toBe(false);
- const r = vault.deposit({ ghostId: 'g1', dirAbs: outside, workdirAbs: workdir, userGranted: true });
+ const expectedRealPath = await fs.promises.realpath(outside);
+ const r = vault.deposit({
+ ghostId: 'g1',
+ dirAbs: expectedRealPath,
+ workdirAbs: workdir,
+ userGranted: true,
+ expectedRealPath,
+ });
expect(r.ok).toBe(true);
if (r.ok) {
const written = await vault.write('g1', r.receipt.token, 'a.txt', new TextEncoder().encode('hi'));
@@ -122,4 +299,75 @@ describe('SaveDepositVault userGranted 旁路(workdir 外确认卡通过后)', (
expect(vault.deposit({ ghostId: 'g1', dirAbs: saveDir, workdirAbs: null }).ok).toBe(false);
expect(vault.deposit({ ghostId: 'g1', dirAbs: saveDir, workdirAbs: null, userGranted: true }).ok).toBe(true);
});
+
+ it('授权后的 canonical 路径被换成 symlink 时拒绝出票', async () => {
+ const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'save-approved-dir-'));
+ try {
+ const approved = path.join(root, 'approved');
+ const replacement = path.join(root, 'replacement');
+ await fs.promises.mkdir(approved);
+ await fs.promises.mkdir(replacement);
+ const expectedRealPath = await fs.promises.realpath(approved);
+ const replacementRealPath = await fs.promises.realpath(replacement);
+ const moved = path.join(path.dirname(expectedRealPath), 'approved-moved');
+ await fs.promises.rename(expectedRealPath, moved);
+ try {
+ await fs.promises.symlink(
+ replacementRealPath,
+ expectedRealPath,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+
+ const result = new SaveDepositVault().deposit({
+ ghostId: 'g1',
+ dirAbs: expectedRealPath,
+ workdirAbs: workdir,
+ userGranted: true,
+ expectedRealPath,
+ });
+
+ expect(result).toEqual({ ok: false, message: '路径在授权后发生变化,请重新确认' });
+ } finally {
+ await fs.promises.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('出票后目标根被换成外部 symlink:write 拒绝且不在外部落盘', async () => {
+ const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'save-ticket-swap-'));
+ try {
+ const approved = path.join(root, 'approved');
+ const outside = path.join(root, 'outside');
+ await fs.promises.mkdir(approved);
+ await fs.promises.mkdir(outside);
+ const vault = new SaveDepositVault();
+ const deposited = vault.deposit({
+ ghostId: 'g1',
+ dirAbs: approved,
+ workdirAbs: workdir,
+ userGranted: true,
+ });
+ if (!deposited.ok) throw new Error('deposit failed');
+
+ await fs.promises.rename(approved, `${approved}-moved`);
+ try {
+ await fs.promises.symlink(
+ outside,
+ approved,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+
+ await expect(
+ vault.write('g1', deposited.receipt.token, 'escaped.txt', new TextEncoder().encode('no')),
+ ).resolves.toBeNull();
+ await expect(fs.promises.stat(path.join(outside, 'escaped.txt'))).rejects.toThrow();
+ } finally {
+ await fs.promises.rm(root, { recursive: true, force: true });
+ }
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/attachmentGrant.ts b/apps/desktop/src/main/cindy-brain/attachmentGrant.ts
index 0f28e4f9b5..f10112e61b 100644
--- a/apps/desktop/src/main/cindy-brain/attachmentGrant.ts
+++ b/apps/desktop/src/main/cindy-brain/attachmentGrant.ts
@@ -4,8 +4,8 @@
* 归属铁律不动:意识永远只能读自己名下的账。用户想让意识处理**自己的图**,
* 走"显式引渡":AI 调 ghost_call 时把当前会话里用户图片的 xdt-image:// 地址
* 放进顶层 attachments → 本模块逐张解析、读字节、落媒体总仓(blob)、给目标
- * 意识记一条 ghost-grant 引用(授权按张、永久,与画廊同生命周期,回收随
- * 引用计数)→ 返回指纹数组。调用方把指纹注入 args.attachments 交给意识——
+ * 意识记一条可读引用(人工交接 = ghost-grant;Host 工具代办 =
+ * ghost-tool-grant)→ 返回指纹数组。调用方把指纹注入 args.attachments 交给意识——
* 意识拿到的仍只是字符串,摸不到路径与字节(平台结构保证不破)。
*
* 语义:用户把图和请求一起发出 = 对这批图的授权意图明确,不再弹框。
@@ -48,7 +48,7 @@ export interface AttachmentGrantDeps {
/** 加引用行(真身 ledger.addRef;出生按解析层给出的真实来源记账)。 */
addRef(params: {
hash: string;
- refKind: 'ghost-grant';
+ refKind: 'ghost-grant' | 'ghost-tool-grant';
refId: string;
originKind: 'user' | 'tool';
label?: string;
@@ -126,11 +126,14 @@ export async function grantAttachmentsToGhost(
bytes: written.bytes,
isCache: false,
});
+ const originKind = r.originKind ?? 'user';
await deps.addRef({
hash: written.hash,
- refKind: 'ghost-grant',
+ // refKind 本身就是回退兼容边界:旧客户端只把 ghost-grant 当成人工
+ // 永久授权,因而工具自动交接必须落到它不认识的独立类型。
+ refKind: originKind === 'user' ? 'ghost-grant' : 'ghost-tool-grant',
refId: ghostId,
- originKind: r.originKind ?? 'user',
+ originKind,
});
hashes.push(written.hash);
} catch (err) {
diff --git a/apps/desktop/src/main/cindy-brain/dirDeposit.ts b/apps/desktop/src/main/cindy-brain/dirDeposit.ts
index c71e6d7fb7..fca0b639ef 100644
--- a/apps/desktop/src/main/cindy-brain/dirDeposit.ts
+++ b/apps/desktop/src/main/cindy-brain/dirDeposit.ts
@@ -14,9 +14,9 @@
* networkSlot 凭返回的 read() 逐文件读盘代组 multipart 出网。
*
* 安全论证:dir 只能来自主 agent 的 ghost_call 调用(用户信任域、权限模式
- * 管辖),且被钳制在会话 workdir 内——workdir 内容本就是主 agent 可读可发网
- * 的范围,本通道不扩大攻击面;意识自造 token 无效(票据按 ghostId 绑定、
- * 主机侧随机发放)。
+ * 管辖)。默认钳制在会话 workdir 内;workdir 外仅接受 Host 已完成的人工确认
+ * 或实时 Full Access 裁决,并用 canonical 路径快照复核。意识自造 token 无效
+ * (票据按 ghostId 绑定、主机侧随机发放)。
*
* 纯 Node(fs/path/crypto),零 Electron(规则 14):单测直接驱动。
* 收集逻辑源自 @cindy/mcps xd-service/collect.ts(该包随 MCP 退役删除,
@@ -140,13 +140,64 @@ export function isPathInsideDir(parentAbs: string, childAbs: string): boolean {
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
}
+/** 两个 realpath 快照是否指向同一规范路径(Windows 大小写不敏感)。 */
+function sameRealPath(a: string, b: string): boolean {
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
+}
+
interface VaultEntry {
ghostId: string;
+ /** 出票时目录/单文件根的 canonical 真身;消费时重新核对,防换链。 */
+ rootRealPath: string;
files: CollectedDirFile[];
totalBytes: number;
expiresAt: number;
}
+/**
+ * 读取票据文件前后的路径复核。最终分量用 O_NOFOLLOW 打开,随后用句柄
+ * identity 对照当前路径,避免出票后把文件或祖先目录换成外部 symlink。
+ */
+async function readDepositedFile(
+ rootRealPath: string,
+ file: CollectedDirFile,
+): Promise<Uint8Array> {
+ const rootBefore = fs.realpathSync.native(rootRealPath);
+ const fileBefore = fs.realpathSync.native(file.absPath);
+ if (
+ !sameRealPath(rootBefore, rootRealPath) ||
+ !isPathInsideDir(rootRealPath, fileBefore)
+ ) {
+ throw new Error('目录过户路径在出票后发生变化');
+ }
+
+ const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0);
+ const handle = await fs.promises.open(file.absPath, flags);
+ try {
+ const openedStat = await handle.stat();
+ if (!openedStat.isFile()) throw new Error('目录过户目标不再是文件');
+
+ // open 之后再复核一次:若祖先目录在 realpath 与 open 之间被换链,
+ // 当前路径真身或 inode/dev identity 会与已打开句柄不一致,拒绝读字节。
+ const rootAfter = fs.realpathSync.native(rootRealPath);
+ const fileAfter = fs.realpathSync.native(file.absPath);
+ const pathStat = fs.statSync(file.absPath);
+ if (
+ !sameRealPath(rootAfter, rootRealPath) ||
+ !isPathInsideDir(rootRealPath, fileAfter) ||
+ pathStat.dev !== openedStat.dev ||
+ pathStat.ino !== openedStat.ino
+ ) {
+ throw new Error('目录过户路径在出票后发生变化');
+ }
+
+ const bytes = await handle.readFile();
+ return new Uint8Array(bytes);
+ } finally {
+ await handle.close();
+ }
+}
+
/**
* 过户票据库:deposit 发票,take 验票取货(单次消费 + TTL + ghostId 绑定)。
* 进程内内存态——票据本就是"一次调用链内"的短命凭据,不落盘。
@@ -158,17 +209,19 @@ export class DirDepositVault {
/**
* 过户一个目录。workdirAbs 是当前会话工作目录(钳制边界);userGranted=true
- * 表示用户已在确认卡上对**这个路径**点了允许(GhostGrantConfirmBridge),
- * 跳过 workdir 钳制(存在性/类型校验照常)——除接线层的确认流外,任何
- * 调用方不得传 true。缺 workdir 语境且未获用户确认时直接拒绝。
+ * 是历史字段名,表示 Host 已通过人工确认或实时 Full Access 对**这个路径**
+ * 完成可信裁决,因而可跳过 workdir 钳制(存在性/类型校验照常)——除接线层
+ * 的授权流外,任何调用方不得传 true。expectedRealPath 是裁决时的 canonical
+ * 快照;提供时出票前必须复核一致。缺 workdir 语境且未获可信裁决时直接拒绝。
*/
deposit(params: {
ghostId: string;
dirAbs: string;
workdirAbs: string | null;
userGranted?: boolean;
+ expectedRealPath?: string;
}): { ok: true; receipt: DirDepositReceipt } | { ok: false; message: string } {
- const { ghostId, dirAbs, workdirAbs, userGranted } = params;
+ const { ghostId, dirAbs, workdirAbs, userGranted, expectedRealPath } = params;
if (!path.isAbsolute(dirAbs)) {
return { ok: false, message: `dir 必须是绝对路径,得到:${dirAbs}` };
}
@@ -185,6 +238,9 @@ export class DirDepositVault {
} catch {
return { ok: false, message: `目录不存在:${dirAbs}` };
}
+ if (expectedRealPath && !sameRealPath(realDir, expectedRealPath)) {
+ return { ok: false, message: '路径在授权后发生变化,请重新确认' };
+ }
// workdir 真身单独解:解不开(远程路径 / 已删)按「不在 workdir 内」处理,
// 未获用户确认时拒,而不是误报"目录不存在"。
let realWorkdir: string | null = null;
@@ -227,6 +283,7 @@ export class DirDepositVault {
const token = randomUUID();
this.entries.set(token, {
ghostId,
+ rootRealPath: realDir,
files: collected.files,
totalBytes: collected.totalBytes,
expiresAt: this.now() + GHOST_DIR_DEPOSIT_TTL_MS,
@@ -257,7 +314,7 @@ export class DirDepositVault {
files: entry.files.map((f) => ({
relPath: f.relPath,
size: f.size,
- read: () => fs.promises.readFile(f.absPath).then((b) => new Uint8Array(b)),
+ read: () => readDepositedFile(entry.rootRealPath, f),
})),
};
}
@@ -326,15 +383,140 @@ export function sanitizeSaveFileName(raw: string | undefined): string {
return cleaned;
}
-/** 防覆盖去重:已存在时在扩展名前插 " (n)"。 */
-function dedupeFileName(dirAbs: string, fileName: string): string {
- let candidate = fileName;
+/** 防覆盖去重候选:第 n 个重名在扩展名前插 " (n)"。 */
+function dedupeFileName(fileName: string, n: number): string {
+ if (n === 0) return fileName;
const ext = path.extname(fileName);
const stem = fileName.slice(0, fileName.length - ext.length);
- for (let n = 1; fs.existsSync(path.join(dirAbs, candidate)); n++) {
- candidate = `${stem} (${n})${ext}`;
+ return `${stem} (${n})${ext}`;
+}
+
+/**
+ * 在 canonical 根下原子创建一个不覆盖的文件。先用 O_EXCL/O_NOFOLLOW
+ * 钉住句柄,再核对根路径、目标真身与句柄 identity,最后才写入字节。
+ */
+async function writeNewSaveFile(
+ dirRealPath: string,
+ fileName: string,
+ bytes: Uint8Array,
+): Promise<string | null> {
+ const flags =
+ fs.constants.O_WRONLY |
+ fs.constants.O_CREAT |
+ fs.constants.O_EXCL |
+ (fs.constants.O_NOFOLLOW ?? 0);
+
+ for (let n = 0; n < 10_000; n++) {
+ let currentRoot: string;
+ try {
+ currentRoot = fs.realpathSync.native(dirRealPath);
+ } catch {
+ return null;
+ }
+ if (!sameRealPath(currentRoot, dirRealPath)) return null;
+
+ const candidate = dedupeFileName(fileName, n);
+ const target = path.join(dirRealPath, candidate);
+ let handle: fs.promises.FileHandle;
+ try {
+ handle = await fs.promises.open(target, flags, 0o666);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') continue;
+ return null;
+ }
+
+ let openedStat: fs.Stats | null = null;
+ let result: string | null = null;
+ let closeFailed = false;
+ try {
+ openedStat = await handle.stat();
+ const rootAfter = fs.realpathSync.native(dirRealPath);
+ const targetAfter = fs.realpathSync.native(target);
+ const pathStat = fs.statSync(target);
+ if (
+ !openedStat.isFile() ||
+ !sameRealPath(rootAfter, dirRealPath) ||
+ !sameRealPath(path.dirname(targetAfter), dirRealPath) ||
+ pathStat.dev !== openedStat.dev ||
+ pathStat.ino !== openedStat.ino
+ ) {
+ return null;
+ }
+ await handle.writeFile(bytes);
+
+ // 写入本身也可能触发另一个进程的 rename / replace;提交成功前再
+ // 复核 canonical 根、目标父目录与句柄 identity,避免把已移出批准
+ // 目录的 inode 当成成功交接。
+ const writtenStat = await handle.stat();
+ const rootAfterWrite = fs.realpathSync.native(dirRealPath);
+ const targetAfterWrite = fs.realpathSync.native(target);
+ const pathStatAfterWrite = fs.statSync(target);
+ if (
+ !writtenStat.isFile() ||
+ !sameRealPath(rootAfterWrite, dirRealPath) ||
+ !sameRealPath(path.dirname(targetAfterWrite), dirRealPath) ||
+ writtenStat.dev !== openedStat.dev ||
+ writtenStat.ino !== openedStat.ino ||
+ pathStatAfterWrite.dev !== writtenStat.dev ||
+ pathStatAfterWrite.ino !== writtenStat.ino
+ ) {
+ return null;
+ }
+ result = candidate;
+ } catch {
+ // result 保持 null;失败路径在 finally 中尽力清理。
+ } finally {
+ // 校验或写入失败时,先通过仍持有的句柄清空可能已经写入的字节。
+ // 这样即使路径随后被替换,也不会把半成品字节留在原 inode 上。
+ if (result !== null) {
+ // 保留成功路径原有的 close 语义;close 失败仍视为写盘失败。
+ try {
+ await handle.close();
+ } catch {
+ closeFailed = true;
+ result = null;
+ }
+ }
+
+ if (result === null) {
+ if (openedStat?.isFile()) {
+ try {
+ await handle.truncate(0);
+ } catch {
+ // 清理失败不能覆盖原始失败结果。
+ }
+ }
+
+ // Windows 下先关闭句柄再 unlink;失败路径的 close 只做 best effort,
+ // 不能把原始 null 结果升级成异常。
+ try {
+ await handle.close();
+ } catch {
+ // 清理失败不能覆盖原始失败结果。
+ }
+
+ // 仅当路径仍指向本次 O_EXCL 打开的同一 dev/ino 时删除,避免目标在
+ // 校验窗口内被替换成 symlink/其它文件后误删替代目标。
+ if (openedStat?.isFile()) {
+ try {
+ const currentStat = await fs.promises.lstat(target);
+ if (
+ currentStat.dev === openedStat.dev &&
+ currentStat.ino === openedStat.ino
+ ) {
+ await fs.promises.unlink(target);
+ }
+ } catch {
+ // 清理失败不能覆盖原始失败结果。
+ }
+ }
+ }
+ }
+ if (closeFailed) return null;
+ if (result !== null) return result;
+ return null;
}
- return candidate;
+ return null;
}
/**
@@ -345,14 +527,15 @@ export class SaveDepositVault {
private readonly entries = new Map<string, SaveVaultEntry>();
constructor(private readonly now: () => number = Date.now) {}
- /** 过户一个可写目录(钳制与 userGranted 旁路口径与 DirDepositVault.deposit 完全一致)。 */
+ /** 过户一个可写目录(钳制、授权快照与 DirDepositVault.deposit 完全一致)。 */
deposit(params: {
ghostId: string;
dirAbs: string;
workdirAbs: string | null;
userGranted?: boolean;
+ expectedRealPath?: string;
}): { ok: true; receipt: SaveDepositReceipt } | { ok: false; message: string } {
- const { ghostId, dirAbs, workdirAbs, userGranted } = params;
+ const { ghostId, dirAbs, workdirAbs, userGranted, expectedRealPath } = params;
if (!path.isAbsolute(dirAbs)) {
return { ok: false, message: `save_dir 必须是绝对路径,得到:${dirAbs}` };
}
@@ -365,6 +548,9 @@ export class SaveDepositVault {
} catch {
return { ok: false, message: `目录不存在:${dirAbs}(落盘目录需要预先存在)` };
}
+ if (expectedRealPath && !sameRealPath(realDir, expectedRealPath)) {
+ return { ok: false, message: '路径在授权后发生变化,请重新确认' };
+ }
let realWorkdir: string | null = null;
if (workdirAbs) {
try {
@@ -416,14 +602,14 @@ export class SaveDepositVault {
return null;
}
if (entry.usesLeft <= 0 || bytes.byteLength > entry.bytesLeft) return null;
- const finalName = dedupeFileName(entry.dirAbs, sanitizeSaveFileName(fileName));
- try {
- // 异步写:上限 256MB,同步写会把 main event loop 卡住数百 ms 到秒级
- //(遇杀软实时扫描更糟),期间全部 IPC / 窗口交互冻结(规则 15)。
- await fs.promises.writeFile(path.join(entry.dirAbs, finalName), bytes);
- } catch {
- return null;
- }
+ // 异步写:上限 256MB,同步写会把 main event loop 卡住数百 ms 到秒级
+ //(遇杀软实时扫描更糟),期间全部 IPC / 窗口交互冻结(规则 15)。
+ const finalName = await writeNewSaveFile(
+ entry.dirAbs,
+ sanitizeSaveFileName(fileName),
+ bytes,
+ );
+ if (!finalName) return null;
entry.usesLeft -= 1;
entry.bytesLeft -= bytes.byteLength;
if (entry.usesLeft <= 0 || entry.bytesLeft <= 0) this.entries.delete(token);
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index d2be86e98b..e90dab713a 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -2052,8 +2052,8 @@ const r = await cindy.fetch({
**目录上传(uploadDir,目录过户票据)**:要把用户的一个本地目录整体传给你的
服务(静态站点部署等),流程是"主 agent 过户 → 你凭票上传"——主 agent 调
ghost_call 时把目录**绝对路径**放在顶层 \`dir\` 参数(会话工作目录内直接放行,
-工作目录外主机会弹确认卡、用户点允许才过户;自动排除 node_modules/.git/.env
-等),主机收集文件后把一次性限时票据注入你的
+工作目录外若主 agent 是本地 Full Access 会话则自动过户、不弹卡;其它权限档及
+远程会话仍由用户确认;自动排除 node_modules/.git/.env 等),主机收集文件后把一次性限时票据注入你的
\`args.dir_deposit\`(含 token / file_count / total_bytes / rel_paths 相对路径清单);
你在工具描述里写清"目录经 ghost_call 顶层 dir 交付",然后:
@@ -2081,7 +2081,7 @@ preset 判定等纯逻辑);伪造/过期/别人的票据统一"票据无效"。
(邮件附件、云盘文档等任意类型)存到用户本地时,流程同样是"主 agent 过户 →
你凭票下载"——主 agent 调 ghost_call 时把**目标目录绝对路径**放在顶层
\`save_dir\` 参数(目录必须已存在;会话工作目录内直接放行,工作目录外主机会
-弹确认卡、用户点允许才过户),主机把限时
+在本地 Full Access 下自动过户、不弹卡;其它权限档及远程会话仍弹确认卡),主机把限时
票据注入你的 \`args.save_deposit\`(含 token / dir_name 目录名);你在工具
描述里写清"下载目录经 ghost_call 顶层 save_dir 交付",然后:
diff --git a/apps/desktop/src/main/cindy-brain/fsSlot.ts b/apps/desktop/src/main/cindy-brain/fsSlot.ts
index 0999fc9d5d..ba5595839b 100644
--- a/apps/desktop/src/main/cindy-brain/fsSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/fsSlot.ts
@@ -26,9 +26,9 @@
*
* 权限对齐哲学:意识写 workdir 的"吵闹程度"必须和主 agent 自己 Edit 文件
* 完全一致——agent 免批的模式意识也免批,agent 逐条批的模式意识也逐条批。
- * claude / codex 共用 sessions.permission_mode 这一列(codex 的 approval/
- * sandbox 由它映射派生,见 maker-core mapPermissionToCodex),所以一张映射
- * 表覆盖两种 agent(规则 9:映射写死在代码,不靠 prompt 判断)。
+ * claude / codex / pi 共用 sessions.permission_mode 这一列(codex 的 approval/
+ * sandbox 由它映射派生,pi bridge 每次 tool_call 现读自己的运行时权限文件),
+ * 所以一张映射表覆盖三种 agent(规则 9:映射写死在代码,不靠 prompt 判断)。
*
* 依赖注入(规则 14):fs 之外的能力(意识清单/票据库/session 快照/确认桥)
* 全部经 deps,单测拿 tmpdir 直测零 Electron。
diff --git a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
index 546427ba04..2eb63864e9 100644
--- a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
@@ -1,11 +1,12 @@
/**
* GhostGrantConfirmBridge —— ghost_call 过户 workdir 外文件的「用户确认」桥。
*
- * 背景:意识触碰用户文件的通道(attachments / dir / save_dir)原本把可达面
- * 钳制在「进过聊天流的图」与「会话 workdir 内」;两层策略升级后(2026-07-14
- * 与 Lizi 定案):workdir 内自动放行,workdir 外改为**弹确认卡**——把「拖图
- * 进聊天」这个授权动作换成「点一下允许」,决定权在用户的点击上,被注入的
- * 模型只能发起请求、点不了按钮。
+ * 背景:意识触碰用户文件的通道(attachments / dir / save_dir)把可达面钳制在
+ * 「进过聊天流的图」与「会话 workdir 内」;普通权限档遇到 workdir 外路径时
+ * 由本桥**弹确认卡**——把「拖图进聊天」这个授权动作换成「点一下允许」,
+ * 决定权在用户的点击上,被注入的模型只能发起请求、点不了按钮。
+ * 当前本地活跃会话为 Full Access 时,mcp-integrations/ghost.ts 会在进入本桥前
+ * 按实时 Session 状态自动放行;workspace / fs_write 等其它 lane 不受该旁路影响。
*
* 实现完全对齐 IssueConfirmBridge 的成熟模式:main 侧发起,broadcast 一个
* kind='ghost_grant_confirm' 的 interaction 到 renderer(复用
diff --git a/apps/desktop/src/main/cindy-brain/refImageBudget.ts b/apps/desktop/src/main/cindy-brain/refImageBudget.ts
index f411fa5046..b08e13a92b 100644
--- a/apps/desktop/src/main/cindy-brain/refImageBudget.ts
+++ b/apps/desktop/src/main/cindy-brain/refImageBudget.ts
@@ -4,7 +4,8 @@
* 为什么需要:`reference_image` 把张数上限放到 9 之后,单次 edit_video 最坏
* 能拖进 9 张源图,而单张并不小 —— 源图取自 ledger.ghostCanRead 放行的账目,
* 除寄存(单张 50MB)还包括 ghost-gallery(network as:'media' 落仓,硬顶
- * GHOST_FETCH_MEDIA_MAX_BYTES = 256MB)与 ghost-grant。主机侧要把每张读成
+ * GHOST_FETCH_MEDIA_MAX_BYTES = 256MB)与 ghost-grant / ghost-tool-grant。
+ * 主机侧要把每张读成
* base64 data URI 交给上游,这条链上会同时存在:
* 原始 Buffer(1×)+ base64 字符串(4/3×)+ JSON.stringify 后的请求体(再 4/3×)
* 峰值约聚合量的 3.7 倍 —— 几百 MB 的输入足以把 main 进程打到 OOM 或长时间停顿。
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
index 3be7b051b1..0804850d66 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
@@ -93,6 +93,98 @@ describe('addRef / removeRefs(引用增删)', () => {
db.delete(schema.mediaBlobs).run();
expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
});
+
+ it('hasRef 可按 originKind 区分人工授权与工具自动授权', async () => {
+ await seedBlob(HASH_A);
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'ghost-grant', refId: 'art', originKind: 'tool' },
+ db,
+ );
+
+ await expect(
+ ledger.hasRef({ hash: HASH_A, refKind: 'ghost-grant', refId: 'art' }, db),
+ ).resolves.toBe(true);
+ await expect(
+ ledger.hasRef({
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'user',
+ }, db),
+ ).resolves.toBe(false);
+ await expect(
+ ledger.hasRef({
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'tool',
+ }, db),
+ ).resolves.toBe(true);
+
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'ghost-grant', refId: 'art', originKind: 'user' },
+ db,
+ );
+ await expect(
+ ledger.hasRef({
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'user',
+ }, db),
+ ).resolves.toBe(true);
+ });
+
+ it('hasGhostToolGrant 兼容旧 ghost-grant/tool,但不把 user provenance 当工具交接', async () => {
+ await seedBlob(HASH_A);
+ await expect(
+ ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db),
+ ).resolves.toBe(false);
+
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'ghost-grant', refId: 'art', originKind: 'user' },
+ db,
+ );
+ await expect(
+ ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db),
+ ).resolves.toBe(false);
+
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'ghost-grant', refId: 'art', originKind: 'tool' },
+ db,
+ );
+ await expect(
+ ledger.hasGhostToolGrant({ hash: HASH_A, ghostId: 'art' }, db),
+ ).resolves.toBe(true);
+
+ await seedBlob(HASH_B);
+ await ledger.addRef(
+ { hash: HASH_B, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' },
+ db,
+ );
+ await expect(
+ ledger.hasGhostToolGrant({ hash: HASH_B, ghostId: 'art' }, db),
+ ).resolves.toBe(true);
+ });
+
+ it('新版工具交接可取件,但旧版 ghost-grant shortcut 看不到它(回退 fail closed)', async () => {
+ await seedBlob(HASH_A);
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' },
+ db,
+ );
+
+ // 新版运行时仍能把本次交接的指纹交给插件实际使用。
+ await expect(ledger.ghostCanRead(HASH_A, 'art', db)).resolves.toBe(true);
+ // 模拟旧客户端不带 provenance 的永久授权 shortcut:它只查
+ // refKind='ghost-grant',因此不会把新版自动交接误当成人工批准。
+ await expect(
+ ledger.hasRef({ hash: HASH_A, refKind: 'ghost-grant', refId: 'art' }, db),
+ ).resolves.toBe(false);
+ await expect(
+ ledger.hasRef({ hash: HASH_A, refKind: 'ghost-tool-grant', refId: 'art' }, db),
+ ).resolves.toBe(true);
+ });
});
describe('removeRefsExceptHash(替换型引用清理:个人头像换图)', () => {
@@ -210,6 +302,24 @@ describe('ghostCanRead(供图归属校验)', () => {
await expect(ledger.ghostCanRead(HASH_A, 'other-ghost', db)).resolves.toBe(false);
});
+ it('Host 工具代办交接(ghost-tool-grant)→ 放行本意识,但不是人工授权', async () => {
+ await seedBlob(HASH_A);
+ await ledger.addRef(
+ { hash: HASH_A, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' },
+ db,
+ );
+ await expect(ledger.ghostCanRead(HASH_A, 'art', db)).resolves.toBe(true);
+ await expect(ledger.ghostCanRead(HASH_A, 'other-ghost', db)).resolves.toBe(false);
+ await expect(
+ ledger.hasRef({
+ hash: HASH_A,
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'user',
+ }, db),
+ ).resolves.toBe(false);
+ });
+
it('本意识寄存(ghost-deposit)→ 放行本意识,别的意识仍拒(#784)', async () => {
await seedBlob(HASH_A);
await ledger.addRef(
diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.ts
index 432d0798ce..4ad0073559 100644
--- a/apps/desktop/src/main/cindy-media/ledger.ts
+++ b/apps/desktop/src/main/cindy-media/ledger.ts
@@ -34,8 +34,13 @@ function defaultDb(): LedgerDb {
/**
* 引用方类型(多态引用,详见 schema.ts mediaRefs 注释)。
* 'ghost-grant':用户显式引渡给某意识的图(随 ghost_call attachments
- * 过户 / 拖进面板)——授权按张、永久,refId = 意识 id;与画廊 ref 一样计入
- * 归属校验(ghostCanRead)与"不被回收"。
+ * 人工确认 / 拖进面板)——授权按张、永久,refId = 意识 id;与画廊 ref 一样
+ * 计入归属校验(ghostCanRead)与"不被回收"。
+ * 'ghost-tool-grant':Host 按工具权限代办的媒体交接(workdir 内直通、Full
+ * Access 自动交接、工具出生的聊天附件等),refId = 意识 id。它同样让意识
+ * 能按指纹取件,但**绝不**表示用户点过永久授权。刻意使用独立 refKind 而不是
+ * 只靠 originKind 区分:旧客户端的授权 shortcut 只认识 ghost-grant,回退后
+ * 会 fail closed,不会把新版自动交接误当成人工永久授权。
* 'ghost-deposit':意识经 cindy 槽 deposit_media 寄存的媒体(用户在插件面板里
* 粘贴/拖入的图等,makecindy/cindy#784),refId = 意识 id。与 gallery / grant
* 一样计入归属校验与"不被回收",但**刻意独立成一类**,原因有三:
@@ -60,6 +65,7 @@ export type MediaRefKind =
| 'im-inbox'
| 'ghost-gallery'
| 'ghost-grant'
+ | 'ghost-tool-grant'
| 'ghost-deposit'
| 'import'
| 'integration-cache'
@@ -179,7 +185,41 @@ export async function getIntegrationCacheHash(
/** 某指纹在某引用方名下是否已有引用(commit 幂等去重用,避免重发消息刷重复行)。 */
export async function hasRef(
- params: { hash: string; refKind: MediaRefKind; refId: string },
+ params: {
+ hash: string;
+ refKind: MediaRefKind;
+ refId: string;
+ /** Optional provenance filter; omit to preserve the historical any-origin query. */
+ originKind?: MediaOriginKind;
+ },
+ db: LedgerDb = defaultDb(),
+): Promise<boolean> {
+ const predicates = [
+ eq(mediaRefs.hash, params.hash),
+ eq(mediaRefs.refKind, params.refKind),
+ eq(mediaRefs.refId, params.refId),
+ ];
+ if (params.originKind !== undefined) {
+ predicates.push(eq(mediaRefs.originKind, params.originKind));
+ }
+ const rows = await db
+ .select({ one: sql`1` })
+ .from(mediaRefs)
+ .where(and(...predicates))
+ .limit(1)
+ .all();
+ return rows.length > 0;
+}
+
+/**
+ * 某意识是否已有 Host 工具代办的附件交接记录。
+ *
+ * 新版使用独立的 ghost-tool-grant/tool;旧版曾把同一语义写成
+ * ghost-grant/tool。两者都只能作为工具 provenance 使用,不能被当成
+ * ghost-grant/user 的人工永久授权。集中兼容旧行,避免各调用点漏判或扩权。
+ */
+export async function hasGhostToolGrant(
+ params: { hash: string; ghostId: string },
db: LedgerDb = defaultDb(),
): Promise<boolean> {
const rows = await db
@@ -188,8 +228,12 @@ export async function hasRef(
.where(
and(
eq(mediaRefs.hash, params.hash),
- eq(mediaRefs.refKind, params.refKind),
- eq(mediaRefs.refId, params.refId),
+ eq(mediaRefs.refId, params.ghostId),
+ eq(mediaRefs.originKind, 'tool'),
+ or(
+ eq(mediaRefs.refKind, 'ghost-tool-grant'),
+ eq(mediaRefs.refKind, 'ghost-grant'),
+ ),
),
)
.limit(1)
@@ -202,8 +246,9 @@ export async function hasRef(
* - session-attachment / import:refId 就是会话 id,直接删;
* - message:refId 是消息 id,按出生会话(originSessionId)连坐删——
* 会话没了,它名下消息的引用自然一起走;
- * - **绝不**碰 ghost-gallery / ghost-grant / ghost-deposit:画廊/引渡/寄存
- * 是跨会话的持久引用,"删会话作品不陪葬"正是靠这几类 ref 存活
+ * - **绝不**碰 ghost-gallery / ghost-grant / ghost-tool-grant /
+ * ghost-deposit:画廊/引渡/工具交接/寄存是跨会话的持久引用,
+ * "删会话作品不陪葬"正是靠这几类 ref 存活
* (寄存物同理:画布上的图不该因为删了某个会话就变得不能改)。
* 引用删完后引用归零的 blob 交回收器,本函数不动字节仓。
*/
@@ -262,7 +307,8 @@ export async function removeRefs(
/**
* 意识面板供图归属校验:该指纹「出生自本意识」「挂在本意识画廊」「用户
- * 显式引渡给本意识(ghost-grant)」或「本意识寄存的(ghost-deposit)」才放行。
+ * 显式引渡给本意识(ghost-grant)」「Host 代办交接给本意识
+ * (ghost-tool-grant)」或「本意识寄存的(ghost-deposit)」才放行。
* 查无此账 = 拒(不区分"不存在"与"不属于你",不给探测空间)。
*
* 寄存计入本校验正是 #784 要买的东西:用户粘进面板的图寄存后与生成图同权,
@@ -284,6 +330,7 @@ export async function ghostCanRead(
and(eq(mediaRefs.originKind, 'ghost'), eq(mediaRefs.originId, ghostId)),
and(eq(mediaRefs.refKind, 'ghost-gallery'), eq(mediaRefs.refId, ghostId)),
and(eq(mediaRefs.refKind, 'ghost-grant'), eq(mediaRefs.refId, ghostId)),
+ and(eq(mediaRefs.refKind, 'ghost-tool-grant'), eq(mediaRefs.refId, ghostId)),
and(eq(mediaRefs.refKind, 'ghost-deposit'), eq(mediaRefs.refId, ghostId)),
),
),
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 14858e3a7f..aa3ff33c4d 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -454,8 +454,8 @@ export async function getSessionRowSnapshot(id: string): Promise<{
/**
* 按 session id 查 fs 槽(意识写文件)守门要看的会话快照:workdir 位置、
- * permission 模式(claude / codex 共用这一列,codex 的 approval/sandbox 由
- * 它映射派生)、plan 开关、远程工作区标记。失败 swallow 返 null(调用方按
+ * permission 模式(claude / codex / pi 共用这一列,codex 的 approval/sandbox
+ * 由它映射派生)、plan 开关、远程工作区标记。失败 swallow 返 null(调用方按
* 「会话不存在」拒绝写入,不抛)。
*/
export async function getSessionFsSnapshot(id: string): Promise<{
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index fcbd272a66..9067c02be4 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -1411,8 +1411,8 @@ export const mediaBlobs = sqliteTable('media_blobs', {
* refKind/refId 是多态引用(消息 id / 会话 id / 意识 id),不设 FK——
* 删除会话/卸载意识时由对应业务代码删自己名下的 ref(回收器对账兜底)。
* origin* 记出生:意识面板供图的归属校验即查「该指纹是否有 origin 为本意识
- * 的行,或 ghost-gallery / ghost-grant / ghost-deposit ref」(ghostCanRead,
- * 见 main/cindy-media/ledger.ts)。
+ * 的行,或 ghost-gallery / ghost-grant / ghost-tool-grant / ghost-deposit ref」
+ * (ghostCanRead,见 main/cindy-media/ledger.ts)。
*
* refKind 是无约束的 text 列:新增引用类型只改 ledger.ts 的联合类型,
* 不需要 migration。
@@ -1424,7 +1424,7 @@ export const mediaRefs = sqliteTable(
hash: text('hash')
.notNull()
.references((): AnySQLiteColumn => mediaBlobs.hash, { onDelete: 'cascade' }),
- /** 'message' | 'session-attachment' | 'ghost-gallery' | 'ghost-deposit' | 'import'…(联合类型见 ledger.ts)。 */
+ /** 'message' | 'session-attachment' | 'ghost-gallery' | 'ghost-tool-grant' | 'ghost-deposit' | 'import'…(联合类型见 ledger.ts)。 */
refKind: text('ref_kind').notNull(),
/** 引用方 id:消息 clientId / 会话 id / 意识 id。 */
refId: text('ref_id').notNull(),
diff --git a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
index 6bb69fa28e..3e4c3423cc 100644
--- a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
@@ -1,7 +1,7 @@
/**
* cc-remote-mcp 的 buildCcRemoteHttpMcpServers:
* bridge 不可用时降级为空;server 名单按白名单过滤;session ctx 注册进 bridge
- * 并以 ?session= query + persistent token 下发;cleanup 注销 ctx;同 session
+ * 并以 ?session=&instance= query + persistent token 下发;cleanup 注销 ctx;同 session
* 重建直接覆盖注册不累积。
*/
@@ -13,9 +13,19 @@ import type { CodexHttpBridge } from '../../mcp-integrations/codexHttpBridge.js'
import { buildCcRemoteHttpMcpServers } from '../cc-remote-mcp.js';
function fakeBridge() {
- const registered = new Map<string, { sessionId: string; agentKind: string; vendorOptions: unknown }>();
+ const registered = new Map<string, {
+ sessionId: string;
+ sessionInstanceId?: string;
+ agentKind: string;
+ vendorOptions: unknown;
+ }>();
const bridge = {
- registerSessionCtx: vi.fn((sessionId: string, ctx: { sessionId: string; agentKind: string; vendorOptions: unknown }) => {
+ registerSessionCtx: vi.fn((sessionId: string, ctx: {
+ sessionId: string;
+ sessionInstanceId?: string;
+ agentKind: string;
+ vendorOptions: unknown;
+ }) => {
registered.set(sessionId, ctx);
}),
unregisterSessionCtx: vi.fn((sessionId: string, expectedCtx?: unknown) => {
@@ -183,10 +193,15 @@ describe('buildCcRemoteHttpMcpServers', () => {
expect(needsFreshStart).toBe(true);
});
- it('injects only whitelisted servers with the persistent token and ?session= routing', async () => {
+ it('injects only whitelisted servers with persistent token and instance-bound routing', async () => {
const { bridge, registered } = fakeBridge();
const { servers } = await buildCcRemoteHttpMcpServers(
- { host: HOST, sessionId: 's1', workingDir: '/remote/repo' },
+ {
+ host: HOST,
+ sessionId: 's1',
+ sessionInstanceId: 'instance-1',
+ workingDir: '/remote/repo',
+ },
{
ensureBridgeStarted: async () => ({
port: 38080,
@@ -202,12 +217,13 @@ describe('buildCcRemoteHttpMcpServers', () => {
expect(Object.keys(servers).sort()).toEqual(['cindy_orca', 'orca_worker_bridge']);
expect(servers.cindy_orca).toEqual({
type: 'http',
- url: 'http://127.0.0.1:47921/mcp/cindy_orca?session=s1',
+ url: 'http://127.0.0.1:47921/mcp/cindy_orca?session=s1&instance=instance-1',
headers: { Authorization: 'Bearer persistent-test-token' },
});
// ctx 以 sessionId 为 key 注册,带 agentKind / vendorOptions。
expect(registered.get('s1')).toMatchObject({
sessionId: 's1',
+ sessionInstanceId: 'instance-1',
agentKind: 'claude-code',
vendorOptions: { orcaRole: 'lead', orcaLeadSessionId: 's1' },
});
@@ -424,4 +440,40 @@ describe('buildCcRemoteHttpMcpServers', () => {
// 被判 drift 重建。
expect(withMemory.fingerprint).not.toBe(withoutMemory.fingerprint);
});
+
+ it('changes the generation fingerprint when the Session instance changes', async () => {
+ const { bridge } = fakeBridge();
+ const deps = {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca'],
+ bridge,
+ }),
+ ensureForward: vi.fn(async () => 47921),
+ getBridgeToken: async () => 'persistent-test-token',
+ synthesizeVendorOptions: async () => ({}),
+ };
+ const first = await buildCcRemoteHttpMcpServers(
+ {
+ host: HOST,
+ sessionId: 'same-business-session',
+ sessionInstanceId: 'instance-old',
+ workingDir: '/remote/repo',
+ },
+ deps,
+ );
+ const replacement = await buildCcRemoteHttpMcpServers(
+ {
+ host: HOST,
+ sessionId: 'same-business-session',
+ sessionInstanceId: 'instance-new',
+ workingDir: '/remote/repo',
+ },
+ deps,
+ );
+
+ expect(first.fingerprint).toBeDefined();
+ expect(replacement.fingerprint).toBeDefined();
+ expect(first.fingerprint).not.toBe(replacement.fingerprint);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
index f2b3f4c2fe..0964731386 100644
--- a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
+++ b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
@@ -4,7 +4,8 @@
* 与 codex 远端的路径差异:cc 的 MCP 配置是 per-query SDK 参数
* (startParams.mcpServers, 经 cc-mgr 透传到 daemon 端 SDK),没有常驻
* daemon 的 config.toml / env 问题。但身份通道与 codex 对齐:持久 bearer
- * token (safeStorage, 跨 app 重启稳定) 鉴权 + URL query `?session=<id>`
+ * token (safeStorage, 跨 app 重启稳定) 鉴权 + URL query
+ * `?session=<id>&instance=<opaque>`
* 路由 session ctx。持久 token 解决 detach/reattach 与 app 重启后旧 query
* 重建时的 token 失效问题;ctx 注册表是内存态,query 重建时重新注册,
* query close 时注销。
@@ -23,6 +24,7 @@ import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';
import {
computeRemoteMcpFingerprint,
selectRemoteInjectableServerNames,
+ withMcpRouteIdentity,
} from '../mcp-integrations/codexHttpBridge.js';
import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';
import { getSessionOrcaRole, getWorkerLink } from '../localDb/orcaTeamStore.js';
@@ -102,6 +104,8 @@ export async function buildCcRemoteHttpMcpServers(
args: {
host: RemoteHost;
sessionId: string;
+ /** 当前 Maker Session 实例代号;作为 opaque bridge route identity 下发。 */
+ sessionInstanceId?: string;
workingDir: string;
/** session 自己的 vendorOptions (maker-core startSession 透传); 优先于 DB 合成。 */
vendorOptions?: Record<string, unknown>;
@@ -172,6 +176,7 @@ export async function buildCcRemoteHttpMcpServers(
const ctx = {
agentKind: 'claude-code' as const,
sessionId: args.sessionId,
+ ...(args.sessionInstanceId ? { sessionInstanceId: args.sessionInstanceId } : {}),
workingDir: args.workingDir,
// remote ctx: scope key 语义见 maker-core buildMemoryScopeKey。
remoteHostId: args.host.id,
@@ -186,7 +191,10 @@ export async function buildCcRemoteHttpMcpServers(
name,
{
type: 'http' as const,
- url: `http://127.0.0.1:${remotePort}/mcp/${name}?session=${encodeURIComponent(args.sessionId)}`,
+ url: withMcpRouteIdentity(`http://127.0.0.1:${remotePort}/mcp/${name}`, {
+ sessionId: args.sessionId,
+ sessionInstanceId: args.sessionInstanceId,
+ }),
headers: { Authorization: `Bearer ${bridgeToken}` },
},
]),
@@ -199,6 +207,7 @@ export async function buildCcRemoteHttpMcpServers(
bridgeInstanceId: started.bridge.instanceId,
remotePort,
serverNames: names,
+ sessionInstanceId: args.sessionInstanceId,
}),
};
} catch (err) {
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 0f6078682b..59a58c416b 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -602,6 +602,20 @@ export function getMaker(): Maker {
lspPool: getLspPool(),
pluginRegistry,
invokeRemote: remoteInvoke,
+ // 只读活跃 Session 的运行时真相。权限切换是 runtime-first、DB-second,
+ // 因此插件过户自动放行不得回退 sessions.permission_mode;会话不再 active
+ // 时同样 fail closed。闭包在 MCP tool-call 时执行,此时 _maker 已装配完成。
+ getLiveSessionGrantState: (sessionId: string, sessionInstanceId: string) => {
+ if (!sessionInstanceId) return null;
+ const session = _maker?.getSession(sessionId);
+ if (!session || session.instanceId !== sessionInstanceId) return null;
+ const permission = session.stablePermissionModeState;
+ if (!permission) return null;
+ return {
+ permissionMode: permission.mode,
+ remoteHostId: session.remoteHostId,
+ };
+ },
};
const orcaTeamStoreAdapter = createDesktopOrcaTeamStoreAdapter({
getWorkerLink,
@@ -781,7 +795,7 @@ export function getMaker(): Maker {
// RemoteQuery 实现 SDK Query interface 的子集 (ClaudeCodeAgent 实际只调
// for-await / interrupt / setModel / setPermissionMode / applyFlagSettings),
// factory 返回时直接 `as unknown as Query` cast 即可。
- remoteCcQueryFactory: async ({ remoteHostId, sessionId, startParams, vendorOptions, onApprovalRequest, onOAuthRefresh, makerMemoryEnabled }) => {
+ remoteCcQueryFactory: async ({ remoteHostId, sessionId, sessionInstanceId, startParams, vendorOptions, onApprovalRequest, onOAuthRefresh, makerMemoryEnabled }) => {
const host = getRemoteSshPool().get(remoteHostId);
if (host?.getStatus() !== 'ready') {
throw new Error(`remote ssh host not ready: ${remoteHostId}`);
@@ -810,6 +824,7 @@ export function getMaker(): Maker {
{
host,
sessionId,
+ sessionInstanceId,
workingDir: typeof startParams.cwd === 'string' ? startParams.cwd : '',
vendorOptions,
// per-session Maker Memory 开关 (maker-core 归一后透传)。
@@ -1028,6 +1043,9 @@ export function getMaker(): Maker {
}
let mcpExtraArgs: string[] = [];
let mcpExtraEnv: Record<string, string> = {};
+ let buildSessionMcpConfig:
+ | ((sessionInstanceId: string) => Record<string, unknown>)
+ | undefined;
try {
const cfg = await getCodexExtraSpawnConfig({
mcpProviders: providers,
@@ -1035,6 +1053,7 @@ export function getMaker(): Maker {
});
mcpExtraArgs = cfg.extraArgs;
mcpExtraEnv = cfg.extraEnv;
+ buildSessionMcpConfig = cfg.buildSessionMcpConfig;
// 本次 spawn 配置实际应用的通讯录可用性快照 —— 从返回的 cfg 本体推导,
// 不另读 settings: getCodexExtraSpawnConfig 是模块级缓存, 失效失败后
// 命中缓存返回的还是 pre-toggle 配置, 此时 live 设置读数会谎报新状态
@@ -1107,6 +1126,7 @@ export function getMaker(): Maker {
...buildCodexProxySpawnArgs(endpoint, authInjection),
],
extraEnv: mcpExtraEnv,
+ ...(buildSessionMcpConfig ? { buildSessionMcpConfig } : {}),
codexProxyActive: ready,
// oauth spawn 才定义 OpenAI 身份 provider(spawn args 同源);maker-core 只对
// 「订阅直连路由」的 thread 用它开 OpenAI 远端压缩,其余 thread 保持本地压缩。
@@ -1115,7 +1135,7 @@ export function getMaker(): Maker {
: {}),
};
},
- registerCodexMcpThreadContext: ({ threadId, sessionId, workingDir, remoteHostId, vendorOptions }) => {
+ registerCodexMcpThreadContext: ({ threadId, sessionId, sessionInstanceId, workingDir, remoteHostId, vendorOptions }) => {
// Codex shares one app-server across sessions. Freeze the effective
// ordinary-tool policy at thread creation so later Settings changes do
// not mutate a runtime that is already running.
@@ -1123,6 +1143,7 @@ export function getMaker(): Maker {
registerCodexMcpThreadContext(threadId, {
agentKind: 'codex',
sessionId,
+ ...(sessionInstanceId ? { sessionInstanceId } : {}),
workingDir,
// remote thread ctx: scope key 语义见 buildMemoryScopeKey。
...(remoteHostId ? { remoteHostId } : {}),
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
index c343078cfe..8f61f87a6f 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
@@ -106,22 +106,39 @@ describe('codexEnvironment', () => {
expect(firstUrl.origin).toBe(secondUrl.origin);
expect(firstUrl.pathname).toBe('/mcp/cindy_test');
expect(secondUrl.pathname).toBe('/mcp/cindy_test');
+
+ expect(first.buildSessionMcpConfig).toBeTypeOf('function');
+ const boundConfig = first.buildSessionMcpConfig!('instance-1');
+ const boundUrl = new URL(boundConfig['mcp_servers.cindy_test.url'] as string);
+ expect(boundUrl.origin).toBe(firstUrl.origin);
+ expect(boundUrl.pathname).toBe('/mcp/cindy_test');
+ expect(boundUrl.searchParams.get('instance')).toBe('instance-1');
+ expect(boundUrl.searchParams.has('session')).toBe(false);
+
+ const replacementUrl = new URL(
+ first.buildSessionMcpConfig!('instance-2')['mcp_servers.cindy_test.url'] as string,
+ );
+ expect(replacementUrl.searchParams.get('instance')).toBe('instance-2');
+ expect(replacementUrl.toString()).not.toBe(boundUrl.toString());
});
- it('preserves a thread disabled-tool policy across context re-registration', async () => {
+ it('freezes policy within one session instance but replaces it on thread rebinding', async () => {
const cfg = await getCodexExtraSpawnConfig({
mcpProviders: [testProvider()],
logger: noopLogger(),
});
const register = vi.spyOn(cfg.bridge!, 'registerThreadContext');
+ const unregister = vi.spyOn(cfg.bridge!, 'unregisterThreadContext');
registerCodexMcpThreadContext('thread-1', {
agentKind: 'codex',
+ sessionInstanceId: 'instance-old',
workingDir: '/project',
vendorOptions: { [CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: ['cindy-ssh'] },
});
registerCodexMcpThreadContext('thread-1', {
agentKind: 'codex',
+ sessionInstanceId: 'instance-old',
workingDir: '/project',
vendorOptions: { [CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: [] },
});
@@ -134,7 +151,27 @@ describe('codexEnvironment', () => {
}),
}),
);
- unregisterCodexMcpThreadContext('thread-1');
+
+ registerCodexMcpThreadContext('thread-1', {
+ agentKind: 'codex',
+ sessionInstanceId: 'instance-new',
+ workingDir: '/project',
+ vendorOptions: { [CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: [] },
+ });
+ expect(register).toHaveBeenLastCalledWith(
+ 'thread-1',
+ expect.objectContaining({
+ sessionInstanceId: 'instance-new',
+ vendorOptions: expect.objectContaining({
+ [CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: [],
+ }),
+ }),
+ );
+
+ unregisterCodexMcpThreadContext('thread-1', 'instance-old');
+ expect(unregister).not.toHaveBeenCalled();
+ unregisterCodexMcpThreadContext('thread-1', 'instance-new');
+ expect(unregister).toHaveBeenCalledWith('thread-1', 'instance-new');
});
it('Slack 在 bridge 启动后完成绑定时,清缓存会按最新 provider gate 重建', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
index b6c35623a8..7dbba5fb5a 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
@@ -8,6 +8,7 @@ import {
selectRemoteInjectableServerNames,
startCodexHttpBridge,
type CodexHttpBridge,
+ withMcpRouteIdentity,
} from '../codexHttpBridge.js';
import { CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY } from '../codexBuiltinToolPolicy.js';
@@ -41,6 +42,19 @@ function createTestServer(): McpServer {
],
}),
);
+ server.tool(
+ 'current_instance',
+ 'Return the active lizi MCP session context instance id.',
+ {},
+ async () => ({
+ content: [
+ {
+ type: 'text' as const,
+ text: getLiziMcpSessionContext()?.sessionInstanceId ?? 'no-instance',
+ },
+ ],
+ }),
+ );
return server;
}
@@ -111,6 +125,25 @@ describe('remote injection shared pure functions (R4 P3)', () => {
expect(computeRemoteMcpFingerprint({ ...base, token: 'tok2', serverNames: ['cindy_orca', 'cindy_memory'] })).not.toBe(fp);
expect(computeRemoteMcpFingerprint({ ...base, bridgeInstanceId: 'b2', serverNames: ['cindy_orca', 'cindy_memory'] })).not.toBe(fp);
expect(computeRemoteMcpFingerprint({ ...base, remotePort: 47922, serverNames: ['cindy_orca', 'cindy_memory'] })).not.toBe(fp);
+ expect(computeRemoteMcpFingerprint({
+ ...base,
+ serverNames: ['cindy_orca', 'cindy_memory'],
+ sessionInstanceId: 'instance-1',
+ })).not.toBe(computeRemoteMcpFingerprint({
+ ...base,
+ serverNames: ['cindy_orca', 'cindy_memory'],
+ sessionInstanceId: 'instance-2',
+ }));
+ });
+
+ it('withMcpRouteIdentity preserves the base route and encodes opaque identity', () => {
+ const result = new URL(withMcpRouteIdentity('http://127.0.0.1:47921/mcp/cindy_orca', {
+ sessionId: 'session / 1',
+ sessionInstanceId: 'instance?1',
+ }));
+ expect(result.pathname).toBe('/mcp/cindy_orca');
+ expect(result.searchParams.get('session')).toBe('session / 1');
+ expect(result.searchParams.get('instance')).toBe('instance?1');
});
});
@@ -245,6 +278,92 @@ describe('codexHttpBridge', () => {
});
});
+ it('binds local Codex tool calls to the registered Session instance', async () => {
+ bridge = await startCodexHttpBridge({
+ serverFactories: { cindy_test: createTestServer },
+ logger: noopLogger(),
+ });
+ bridge.registerThreadContext('thread-instance', {
+ agentKind: 'codex',
+ sessionId: 'session-instance',
+ sessionInstanceId: 'instance-current',
+ workingDir: '/repo',
+ vendorOptions: {},
+ });
+
+ const headers = {
+ authorization: `Bearer ${bridge.token}`,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const activeUrl = withMcpRouteIdentity(bridge.url('cindy_test'), {
+ sessionInstanceId: 'instance-current',
+ });
+ const initResp = await fetch(activeUrl, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '1.0.0' },
+ },
+ }),
+ });
+ expect(initResp.status).toBe(200);
+ const mcpSessionId = initResp.headers.get('mcp-session-id');
+ expect(mcpSessionId).toBeTruthy();
+ await initResp.text();
+
+ const call = (url: string, id: number, name: string) =>
+ fetch(url, {
+ method: 'POST',
+ headers: { ...headers, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id,
+ method: 'tools/call',
+ params: {
+ name,
+ arguments: {},
+ _meta: { threadId: 'thread-instance' },
+ },
+ }),
+ });
+
+ const active = await call(activeUrl, 2, 'current_instance');
+ expect(active.status).toBe(200);
+ expect(await readRpcResponse(active)).toMatchObject({
+ result: { content: [{ type: 'text', text: 'instance-current' }] },
+ });
+
+ const stale = await call(
+ withMcpRouteIdentity(bridge.url('cindy_test'), {
+ sessionInstanceId: 'instance-stale',
+ }),
+ 3,
+ 'current_instance',
+ );
+ expect(stale.status).toBe(401);
+ await stale.text();
+
+ // An old unbound URL keeps ordinary session-aware tools compatible, but
+ // deliberately removes the capability needed for Full Access auto-grants.
+ const legacySession = await call(bridge.url('cindy_test'), 4, 'current_session');
+ expect(legacySession.status).toBe(200);
+ expect(await readRpcResponse(legacySession)).toMatchObject({
+ result: { content: [{ type: 'text', text: 'session-instance' }] },
+ });
+ const legacyInstance = await call(bridge.url('cindy_test'), 5, 'current_instance');
+ expect(legacyInstance.status).toBe(200);
+ expect(await readRpcResponse(legacyInstance)).toMatchObject({
+ result: { content: [{ type: 'text', text: 'no-instance' }] },
+ });
+ });
+
it('keeps the thread context when a batch sibling omits the thread id', async () => {
// Regression: a JSON-RPC batch carrying a notification (no
// params._meta.threadId) alongside a well-attributed tools/call used to
@@ -619,7 +738,7 @@ describe('codexHttpBridge', () => {
}
});
- it('resolves identity from ?session= query without _meta.threadId (remote cc)', async () => {
+ it('keeps legacy ?session= routing compatible without exposing the Session instance', async () => {
bridge = await startCodexHttpBridge({
// remote cc 走 persistent token, 仅限协同白名单 — 用白名单内的
// cindy_orca 模拟真实 cc 流量 (scope 收窄后 cindy_test 会被 403)。
@@ -630,6 +749,7 @@ describe('codexHttpBridge', () => {
bridge.registerSessionCtx('cc-session-1', {
agentKind: 'claude-code',
sessionId: 'cc-session-1',
+ sessionInstanceId: 'cc-instance-1',
workingDir: '/remote/repo',
vendorOptions: {},
});
@@ -677,17 +797,94 @@ describe('codexHttpBridge', () => {
result: { content: [{ type: 'text', text: 'cc-session-1' }] },
});
+ const instanceResp = await fetch(sessionUrl, {
+ method: 'POST',
+ headers: { ...headers, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 3,
+ method: 'tools/call',
+ params: { name: 'current_instance', arguments: {} },
+ }),
+ });
+ expect(instanceResp.status).toBe(200);
+ expect(await readRpcResponse(instanceResp)).toMatchObject({
+ result: { content: [{ type: 'text', text: 'no-instance' }] },
+ });
+
// 注销后 ?session= 未命中立刻 401 (fail-closed)。
bridge.unregisterSessionCtx('cc-session-1');
const after = await fetch(sessionUrl, {
method: 'POST',
headers,
- body: initBody(3),
+ body: initBody(4),
});
expect(after.status).toBe(401);
await after.text();
});
+ it('requires remote Claude and Pi routes to match both session and instance', async () => {
+ bridge = await startCodexHttpBridge({
+ serverFactories: { cindy_orca: createTestServer },
+ additionalBearerTokens: () => ['remote-persistent-token'],
+ logger: noopLogger(),
+ });
+ bridge.registerSessionCtx('remote-session', {
+ agentKind: 'pi',
+ sessionId: 'remote-session',
+ sessionInstanceId: 'remote-instance-current',
+ workingDir: '/repo',
+ vendorOptions: {},
+ });
+
+ const headers = {
+ authorization: 'Bearer remote-persistent-token',
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const initBody = JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '1.0.0' },
+ },
+ });
+ const activeUrl = withMcpRouteIdentity(bridge.url('cindy_orca'), {
+ sessionId: 'remote-session',
+ sessionInstanceId: 'remote-instance-current',
+ });
+ const activeInit = await fetch(activeUrl, { method: 'POST', headers, body: initBody });
+ expect(activeInit.status).toBe(200);
+ const mcpSessionId = activeInit.headers.get('mcp-session-id');
+ await activeInit.text();
+
+ const activeCall = await fetch(activeUrl, {
+ method: 'POST',
+ headers: { ...headers, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/call',
+ params: { name: 'current_instance', arguments: {} },
+ }),
+ });
+ expect(activeCall.status).toBe(200);
+ expect(await readRpcResponse(activeCall)).toMatchObject({
+ result: { content: [{ type: 'text', text: 'remote-instance-current' }] },
+ });
+
+ const staleUrl = withMcpRouteIdentity(bridge.url('cindy_orca'), {
+ sessionId: 'remote-session',
+ sessionInstanceId: 'remote-instance-stale',
+ });
+ const stale = await fetch(staleUrl, { method: 'POST', headers, body: initBody });
+ expect(stale.status).toBe(401);
+ await stale.text();
+ });
+
it('rejects an unregistered ?session= query while leaving token-only requests untouched', async () => {
bridge = await startCodexHttpBridge({
serverFactories: { cindy_test: createTestServer },
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexMcpThreadContextStore.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexMcpThreadContextStore.test.ts
index 54df0a4e89..63e0081d61 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexMcpThreadContextStore.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexMcpThreadContextStore.test.ts
@@ -36,6 +36,20 @@ describe('createCodexMcpThreadContextStore', () => {
expect(store.getContextForThreadId('thread-1')).toBeUndefined();
});
+ it('ignores a stale unregister after the same thread id is rebound to a new session instance', () => {
+ const store = createCodexMcpThreadContextStore();
+ const oldContext = { ...ctx('session-1'), sessionInstanceId: 'instance-old' };
+ const newContext = { ...ctx('session-1'), sessionInstanceId: 'instance-new' };
+
+ store.registerThreadContext('thread-1', oldContext);
+ store.registerThreadContext('thread-1', newContext);
+ store.unregisterThreadContext('thread-1', 'instance-old');
+
+ expect(store.getContextForThreadId('thread-1')).toBe(newContext);
+ store.unregisterThreadContext('thread-1', 'instance-new');
+ expect(store.getContextForThreadId('thread-1')).toBeUndefined();
+ });
+
it('preserves the vendorOptions object reference', () => {
const store = createCodexMcpThreadContextStore();
const vendorOptions = { orcaRole: 'lead' };
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 8f8ddc6a4c..b850bae5e4 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -1,5 +1,5 @@
/**
- * ghostWorkdirGate.test.ts — 目录级禁用的**生效链路**测试(规则 14)。
+ * ghostWorkdirGate.test.ts — ghost_call 的 workdir / 过户授权生效链路测试(规则 14)。
*
* 用真实 ghostWorkdirPrefs(electron userData mock 到 os.tmpdir 临时目录,
* 规则 23:测试路径不落仓库工作区)+ mock 掉 ghost.ts 的重依赖,覆盖:
@@ -8,9 +8,12 @@
* 2. getRosterItems / listAwakeGhosts 按会话 workdir 过滤被禁用的意识;
* 3. callGhostTool 兜底拒绝(GHOST_DISABLED_IN_WORKDIR),派发器零触碰;
* 未禁用的意识照常派发。
+ * 4. Claude Code / Codex / Pi 的 Full Access 对 attachments / dir / save_dir
+ * 自动过户,降档恢复确认;缺会话、查询失败、远程会话 fail closed。
*/
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -21,8 +24,48 @@ import type {
const tmpUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'ghost-workdir-gate-'));
const prefsFile = () => path.join(tmpUserData, 'ghost-workdir-prefs.json');
+const outsideDir = path.join(tmpUserData, 'outside');
const logWarnMock = vi.fn();
+const logInfoMock = vi.fn();
const grantAttachmentsMock = vi.fn();
+const confirmRequestMock = vi.fn(async () => ({ confirmed: true, allowDirs: false }));
+const classifyLocalAttachmentPathMock = vi.fn();
+const resolveGhostAttachmentUrlMock = vi.fn();
+type TestLedgerRef = {
+ hash: string;
+ refKind: string;
+ refId: string;
+ originKind?: 'user' | 'tool';
+};
+const ledgerRefs: TestLedgerRef[] = [];
+const ledgerHasRefMock = vi.fn(async (params: TestLedgerRef) =>
+ ledgerRefs.some(
+ (ref) =>
+ ref.hash === params.hash &&
+ ref.refKind === params.refKind &&
+ ref.refId === params.refId &&
+ (params.originKind === undefined || ref.originKind === params.originKind),
+ ),
+);
+const ledgerHasGhostToolGrantMock = vi.fn(
+ async (params: { hash: string; ghostId: string }) =>
+ ledgerRefs.some(
+ (ref) =>
+ ref.hash === params.hash &&
+ ref.refId === params.ghostId &&
+ ref.originKind === 'tool' &&
+ (ref.refKind === 'ghost-tool-grant' || ref.refKind === 'ghost-grant'),
+ ),
+);
+const ledgerAddRefMock = vi.fn(async (params: TestLedgerRef) => {
+ ledgerRefs.push({ ...params });
+ return `ref-${ledgerRefs.length}`;
+});
+const dirDepositMock = vi.fn(() => ({ ok: true, receipt: { token: 'dir-ticket' } }));
+const saveDepositMock = vi.fn(() => ({ ok: true, receipt: { token: 'save-ticket' } }));
+const liveGrantStateMock = vi.fn();
+const alsSessionContextMock = vi.fn();
+const resolvedAttachmentOrigins: Array<'user' | 'tool' | undefined> = [];
vi.mock('electron', () => ({ app: { getPath: () => tmpUserData } }));
vi.mock('../../appSessionState.js', () => ({
@@ -32,24 +75,30 @@ vi.mock('../../maker-host/logger-adapter.js', () => ({
desktopMakerLogger: { child: () => ({ info: () => {}, warn: () => {}, error: () => {} }) },
}));
vi.mock('../../logger.js', () => ({
- createLogger: () => ({ info: () => {}, warn: logWarnMock, error: () => {}, debug: () => {} }),
+ createLogger: () => ({ info: logInfoMock, warn: logWarnMock, error: () => {}, debug: () => {} }),
}));
-// ALS 语境:恒缺省 → resolveSessionContext 走建线闭包 ctx(claude 路径同款)。
-vi.mock('@cindy/mcps', () => ({ getLiziMcpSessionContext: () => undefined }));
+// Claude 走建线闭包 ctx;Codex / Pi 用此 mock 模拟 HTTP bridge 的 ALS 恢复。
+vi.mock('@cindy/mcps', () => ({ getLiziMcpSessionContext: () => alsSessionContextMock() }));
const WORKDIR = '/proj/alpha';
const listMock = vi.fn<() => unknown[]>(() => []);
const dispatchMock = vi.fn(async () => ({ ok: true as const, result: 'done' }));
-const setupAssessmentMock = vi.fn((_ghostId: string) => ({
- state: 'ready' as const,
- revision: 0,
- groups: [],
-}));
+const setupAssessmentMock = vi.fn((_ghostId: string) => {
+ void _ghostId;
+ return {
+ state: 'ready' as const,
+ revision: 0,
+ groups: [],
+ };
+});
const ensureReadyMock = vi.fn(
- async (_request: GhostSetupEnsureRequest): Promise<GhostSetupEnsureResult> => ({
- ok: true as const,
- assessment: { state: 'ready' as const, revision: 0, groups: [] },
- }),
+ async (_request: GhostSetupEnsureRequest): Promise<GhostSetupEnsureResult> => {
+ void _request;
+ return {
+ ok: true as const,
+ assessment: { state: 'ready' as const, revision: 0, groups: [] },
+ };
+ },
);
const sessionSnapshotMock = vi.fn(async () => ({
workingDir: WORKDIR,
@@ -77,23 +126,33 @@ vi.mock('../../cindy-brain/attachmentGrant.js', () => ({
MAX_GRANT_ONLY_ATTACHMENTS: 32,
}));
vi.mock('../../cindy-brain/dirDeposit.js', () => ({
- collectDirFiles: vi.fn(),
- getDirDepositVault: vi.fn(),
- getSaveDepositVault: vi.fn(),
+ collectDirFiles: () => ({ ok: true, files: [], totalBytes: 0 }),
+ getDirDepositVault: () => ({ deposit: dirDepositMock }),
+ getSaveDepositVault: () => ({ deposit: saveDepositMock }),
isPathInsideDir: () => false,
}));
-vi.mock('../../cindy-brain/ghostGrantConfirmBridge.js', () => ({ getGhostGrantConfirmBridge: vi.fn() }));
-vi.mock('../../cindy-brain/ghostLocalPathGrant.js', () => ({ classifyLocalAttachmentPath: vi.fn() }));
+vi.mock('../../cindy-brain/ghostGrantConfirmBridge.js', () => ({
+ getGhostGrantConfirmBridge: () => ({ request: confirmRequestMock }),
+}));
+vi.mock('../../cindy-brain/ghostLocalPathGrant.js', () => ({
+ classifyLocalAttachmentPath: classifyLocalAttachmentPathMock,
+}));
vi.mock('../../cindy-brain/cardService.js', () => ({ withCardToken: (r: unknown) => r }));
vi.mock('../../cindy-brain/forge.js', () => ({ FORGE_GUIDE: 'guide', packGhostDir: vi.fn() }));
vi.mock('../../cindy-brain/openFileInstall.js', () => ({ handleIncomingCindyFile: vi.fn() }));
vi.mock('../../localDb/ipc/sessions.js', () => ({
getSessionFsSnapshot: sessionSnapshotMock,
}));
-vi.mock('../../cindy-media/blobStore.js', () => ({}));
-vi.mock('../../cindy-media/ledger.js', () => ({}));
+vi.mock('../../cindy-media/blobStore.js', () => ({ mimeForExt: () => 'image/png' }));
+vi.mock('../../cindy-media/ledger.js', () => ({
+ hasRef: ledgerHasRefMock,
+ hasGhostToolGrant: ledgerHasGhostToolGrantMock,
+ addRef: ledgerAddRefMock,
+}));
vi.mock('../../cindy-media/attachmentGrantGate.js', () => ({ chatAttachmentOrigin: vi.fn() }));
-vi.mock('../ghostAttachmentResolve.js', () => ({ resolveGhostAttachmentUrl: vi.fn() }));
+vi.mock('../ghostAttachmentResolve.js', () => ({
+ resolveGhostAttachmentUrl: resolveGhostAttachmentUrlMock,
+}));
const { getCindyGhostsMcpDeps } = await import('../ghost');
const { setGhostDisabledForWorkdir, listDisabledGhostIdsForWorkdir, isGhostDisabledForWorkdir } =
@@ -113,14 +172,26 @@ function chipGhost(id: string, slots: string[] = ['tool']): unknown {
};
}
-function makeDeps() {
+type TestAgentKind = 'claude-code' | 'codex' | 'pi';
+
+function makeDeps(
+ agentKind: TestAgentKind = 'claude-code',
+ sessionId: string | null = 's1',
+ sessionInstanceId: string | null = sessionId ? `${sessionId}-instance` : null,
+) {
const ctx = {
- agentKind: 'claude-code',
+ agentKind,
workingDir: WORKDIR,
vendorOptions: {},
- sessionId: 's1',
+ ...(sessionId ? { sessionId } : {}),
+ ...(sessionInstanceId ? { sessionInstanceId } : {}),
} as unknown as LiziMcpSessionContext;
- return getCindyGhostsMcpDeps(ctx);
+ // Claude 的 in-process server 闭包 session ctx;Codex/Pi 的共享 HTTP bridge
+ // 在 tool-call 时从 ALS 恢复真实 ctx。
+ alsSessionContextMock.mockReturnValue(agentKind === 'claude-code' ? undefined : ctx);
+ return getCindyGhostsMcpDeps(agentKind === 'claude-code' ? ctx : undefined, {
+ getLiveSessionGrantState: liveGrantStateMock,
+ });
}
function clearAllPrefs(): void {
@@ -131,6 +202,7 @@ function clearAllPrefs(): void {
}
beforeEach(() => {
+ fs.mkdirSync(outsideDir, { recursive: true });
listMock.mockReset();
listMock.mockReturnValue([chipGhost('art'), chipGhost('other')]);
dispatchMock.mockClear();
@@ -142,7 +214,91 @@ beforeEach(() => {
assessment: { state: 'ready', revision: 0, groups: [] },
});
grantAttachmentsMock.mockReset();
+ grantAttachmentsMock.mockImplementation(
+ async (
+ deps: {
+ resolveImageUrl: (url: string) => Promise<{
+ absPath: string;
+ originKind?: 'user' | 'tool';
+ buffer?: Uint8Array;
+ }>;
+ addRef: (params: TestLedgerRef) => Promise<string>;
+ },
+ params: { urls: string[]; ghostId: string; maxCount?: number },
+ ) => {
+ if (params.urls.length > (params.maxCount ?? 4)) {
+ return { ok: false, message: `附件过多(单次上限 ${params.maxCount ?? 4} 张)` };
+ }
+ const hashes: string[] = [];
+ for (const url of params.urls) {
+ const resolved = await deps.resolveImageUrl(url);
+ resolvedAttachmentOrigins.push(resolved.originKind);
+ const buffer = resolved.buffer ?? (await fs.promises.readFile(resolved.absPath));
+ const hash = createHash('sha256').update(buffer).digest('hex');
+ const originKind = resolved.originKind ?? 'user';
+ await deps.addRef({
+ hash,
+ refKind: originKind === 'user' ? 'ghost-grant' : 'ghost-tool-grant',
+ refId: params.ghostId,
+ originKind,
+ });
+ hashes.push(hash);
+ }
+ return { ok: true, hashes };
+ },
+ );
+ resolvedAttachmentOrigins.length = 0;
+ confirmRequestMock.mockReset();
+ confirmRequestMock.mockResolvedValue({ confirmed: true, allowDirs: false });
+ classifyLocalAttachmentPathMock.mockReset();
+ classifyLocalAttachmentPathMock.mockImplementation((url: string) => {
+ const stat = fs.statSync(url);
+ return {
+ kind: 'outside-workdir',
+ absPath: url,
+ mimeType: 'image/png',
+ size: stat.size,
+ name: path.basename(url),
+ };
+ });
+ resolveGhostAttachmentUrlMock.mockReset();
+ resolveGhostAttachmentUrlMock.mockImplementation(() => {
+ throw new Error('not a managed media URL');
+ });
+ ledgerHasRefMock.mockReset();
+ ledgerHasRefMock.mockImplementation(async (params: TestLedgerRef) =>
+ ledgerRefs.some(
+ (ref) =>
+ ref.hash === params.hash &&
+ ref.refKind === params.refKind &&
+ ref.refId === params.refId &&
+ (params.originKind === undefined || ref.originKind === params.originKind),
+ ),
+ );
+ ledgerHasGhostToolGrantMock.mockReset();
+ ledgerHasGhostToolGrantMock.mockImplementation(
+ async (params: { hash: string; ghostId: string }) =>
+ ledgerRefs.some(
+ (ref) =>
+ ref.hash === params.hash &&
+ ref.refId === params.ghostId &&
+ ref.originKind === 'tool' &&
+ (ref.refKind === 'ghost-tool-grant' || ref.refKind === 'ghost-grant'),
+ ),
+ );
+ ledgerAddRefMock.mockReset();
+ ledgerAddRefMock.mockImplementation(async (params: TestLedgerRef) => {
+ ledgerRefs.push({ ...params });
+ return `ref-${ledgerRefs.length}`;
+ });
+ ledgerRefs.length = 0;
+ dirDepositMock.mockClear();
+ saveDepositMock.mockClear();
+ liveGrantStateMock.mockReset();
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'auto', remoteHostId: null });
+ alsSessionContextMock.mockReset();
logWarnMock.mockClear();
+ logInfoMock.mockClear();
sessionSnapshotMock.mockReset();
sessionSnapshotMock.mockResolvedValue({
workingDir: WORKDIR,
@@ -282,6 +438,70 @@ describe('ghost_call 兜底拒绝', () => {
expect(grantAttachmentsMock).not.toHaveBeenCalled();
expect(dispatchMock).not.toHaveBeenCalled();
});
+
+ it('grant_only 在 Full Access 下自动交接,降档后恢复确认并保留 provenance', async () => {
+ const file = path.join(outsideDir, 'grant-only-full-access.png');
+ fs.writeFileSync(file, 'grant-only-bytes');
+ let permissionMode = 'bypassPermissions';
+ liveGrantStateMock.mockImplementation(() => ({ permissionMode, remoteHostId: null }));
+ const deps = makeDeps('codex', 'grant-only-full-access');
+
+ const fullAccessResult = await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'ignored-tool',
+ args: {},
+ attachments: [file],
+ grantOnly: true,
+ });
+
+ expect(fullAccessResult).toMatchObject({
+ ok: true,
+ result: expect.objectContaining({ granted_count: 1 }),
+ });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(dispatchMock).not.toHaveBeenCalled();
+ expect(resolvedAttachmentOrigins).toEqual(['tool']);
+ expect(ledgerRefs).toEqual([
+ expect.objectContaining({
+ refKind: 'ghost-tool-grant',
+ refId: 'art',
+ originKind: 'tool',
+ }),
+ ]);
+
+ permissionMode = 'ask';
+ const downgradedResult = await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'ignored-tool',
+ args: {},
+ attachments: [file],
+ grantOnly: true,
+ });
+
+ expect(downgradedResult).toMatchObject({
+ ok: true,
+ result: expect.objectContaining({ granted_count: 1 }),
+ });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(ledgerRefs.map((ref) => [ref.refKind, ref.originKind])).toEqual([
+ ['ghost-tool-grant', 'tool'],
+ ['ghost-grant', 'user'],
+ ]);
+
+ await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'ignored-tool',
+ args: {},
+ attachments: [file],
+ grantOnly: true,
+ });
+
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(ledgerRefs.map((ref) => [ref.refKind, ref.originKind])).toEqual([
+ ['ghost-tool-grant', 'tool'],
+ ['ghost-grant', 'user'],
+ ]);
+ });
});
describe('session-context 宿主铸造', () => {
@@ -322,3 +542,765 @@ describe('session-context 宿主铸造', () => {
);
});
});
+
+describe('Full Access 插件文件交接', () => {
+ it.each<TestAgentKind>(['claude-code', 'codex', 'pi'])(
+ '%s 的 bypassPermissions 对 workdir 外 dir 自动放行',
+ async (agentKind) => {
+ const dir = path.join(outsideDir, `dir-${agentKind}`);
+ fs.mkdirSync(dir, { recursive: true });
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ });
+
+ const result = await makeDeps(agentKind).callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ dir,
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(liveGrantStateMock).toHaveBeenCalledWith('s1', 's1-instance');
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ const approvedRealPath = fs.realpathSync.native(dir);
+ expect(dirDepositMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ ghostId: 'art',
+ dirAbs: approvedRealPath,
+ userGranted: true,
+ expectedRealPath: approvedRealPath,
+ }),
+ );
+ expect(logInfoMock).toHaveBeenCalledWith(
+ 'ghost grant: Full Access auto-approved outside-workdir handoff',
+ expect.objectContaining({
+ ghostId: 'art',
+ lane: 'dir',
+ count: 1,
+ grantSource: 'full-access',
+ }),
+ );
+ },
+ );
+
+ it('attachments 的 Full Access 自动授权不升级为人工永久授权,降档后恢复确认', async () => {
+ const file = path.join(outsideDir, 'full-access.png');
+ fs.writeFileSync(file, 'png-bytes');
+ let permissionMode = 'bypassPermissions';
+ liveGrantStateMock.mockImplementation(() => ({ permissionMode, remoteHostId: null }));
+ const deps = makeDeps('claude-code', 'attachment-full');
+
+ const result = await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [file],
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(resolvedAttachmentOrigins).toEqual(['tool']);
+ expect(ledgerRefs).toEqual([
+ expect.objectContaining({
+ refKind: 'ghost-tool-grant',
+ refId: 'art',
+ originKind: 'tool',
+ }),
+ ]);
+ expect(logInfoMock).toHaveBeenCalledWith(
+ 'ghost grant: Full Access auto-approved outside-workdir handoff',
+ expect.objectContaining({ lane: 'attachments', grantSource: 'full-access' }),
+ );
+ expect(logInfoMock).not.toHaveBeenCalledWith(
+ 'ghost grant confirm: user approved outside-workdir attachments',
+ expect.anything(),
+ );
+
+ permissionMode = 'ask';
+ await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [file],
+ });
+
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(ledgerHasRefMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ refKind: 'ghost-grant',
+ refId: 'art',
+ originKind: 'user',
+ }),
+ );
+ expect(ledgerRefs.map((ref) => [ref.refKind, ref.originKind])).toEqual([
+ ['ghost-tool-grant', 'tool'],
+ ['ghost-grant', 'user'],
+ ]);
+
+ await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [file],
+ });
+
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(ledgerRefs.map((ref) => [ref.refKind, ref.originKind])).toEqual([
+ ['ghost-tool-grant', 'tool'],
+ ['ghost-grant', 'user'],
+ ]);
+ });
+
+ it('同一 Full Access attachment 重复交接只保留一条工具授权引用', async () => {
+ const file = path.join(outsideDir, 'full-access-repeat.png');
+ fs.writeFileSync(file, 'repeat-bytes');
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ });
+ const deps = makeDeps('pi', 'attachment-repeat');
+
+ await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [file],
+ });
+ await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [file],
+ });
+
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(ledgerRefs).toEqual([
+ expect.objectContaining({
+ refKind: 'ghost-tool-grant',
+ refId: 'art',
+ originKind: 'tool',
+ }),
+ ]);
+ expect(ledgerAddRefMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('总仓 blob 可复用既有人工 ghost-grant provenance,不再询问', async () => {
+ const file = path.join(outsideDir, 'managed-user.png');
+ const bytes = Buffer.from('managed-user');
+ fs.writeFileSync(file, bytes);
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ ledgerRefs.push({ hash, refKind: 'ghost-grant', refId: 'art', originKind: 'user' });
+ resolveGhostAttachmentUrlMock.mockReturnValue({
+ absPath: file,
+ mimeType: 'image/png',
+ blobHash: hash,
+ });
+
+ const result = await makeDeps('codex', 'managed-user').callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [`xdt-media://blob/${hash}`],
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(resolvedAttachmentOrigins).toEqual(['user']);
+ expect(ledgerRefs).toEqual([
+ { hash, refKind: 'ghost-grant', refId: 'art', originKind: 'user' },
+ ]);
+ expect(ledgerAddRefMock).not.toHaveBeenCalled();
+ });
+
+ it('总仓 blob 的工具 provenance 只在当前 Full Access 下复用,降档后回到用户确认', async () => {
+ const file = path.join(outsideDir, 'managed-tool.png');
+ const bytes = Buffer.from('managed-tool');
+ fs.writeFileSync(file, bytes);
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ ledgerRefs.push({ hash, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' });
+ resolveGhostAttachmentUrlMock.mockReturnValue({
+ absPath: file,
+ mimeType: 'image/png',
+ blobHash: hash,
+ });
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null });
+ const deps = makeDeps('codex', 'managed-tool');
+ const blobUrl = `xdt-media://blob/${hash}`;
+
+ const fullAccessResult = await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [blobUrl],
+ });
+
+ expect(fullAccessResult).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(resolvedAttachmentOrigins).toEqual(['tool']);
+ expect(ledgerRefs).toEqual([
+ { hash, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' },
+ ]);
+
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'ask', remoteHostId: null });
+ const downgradedResult = await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [blobUrl],
+ });
+
+ expect(downgradedResult).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(confirmRequestMock).toHaveBeenCalledWith(
+ 'managed-tool',
+ expect.objectContaining({
+ lane: 'attachments',
+ items: [expect.objectContaining({ name: 'managed-tool.png' })],
+ }),
+ );
+ expect(resolvedAttachmentOrigins).toEqual(['tool', 'user']);
+ expect(ledgerRefs).toEqual([
+ { hash, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' },
+ { hash, refKind: 'ghost-grant', refId: 'art', originKind: 'user' },
+ ]);
+
+ await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [blobUrl],
+ });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('旧版 ghost-grant/tool 在 Full Access 下兼容交接,降档后仍只走用户确认', async () => {
+ const file = path.join(outsideDir, 'legacy-managed-tool.png');
+ const bytes = Buffer.from('legacy-managed-tool');
+ fs.writeFileSync(file, bytes);
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ ledgerRefs.push({ hash, refKind: 'ghost-grant', refId: 'art', originKind: 'tool' });
+ resolveGhostAttachmentUrlMock.mockReturnValue({
+ absPath: file,
+ mimeType: 'image/png',
+ blobHash: hash,
+ });
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null });
+ const deps = makeDeps('pi', 'legacy-managed-tool');
+ const blobUrl = `xdt-media://blob/${hash}`;
+
+ const fullAccessResult = await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [blobUrl],
+ });
+
+ expect(fullAccessResult).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(resolvedAttachmentOrigins).toEqual(['tool']);
+ expect(ledgerRefs).toEqual(
+ expect.arrayContaining([
+ { hash, refKind: 'ghost-grant', refId: 'art', originKind: 'tool' },
+ { hash, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' },
+ ]),
+ );
+ expect(ledgerRefs).not.toContainEqual({ hash, refKind: 'ghost-grant', refId: 'art', originKind: 'user' });
+
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'auto', remoteHostId: null });
+ const downgradedResult = await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [blobUrl],
+ });
+
+ expect(downgradedResult).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(resolvedAttachmentOrigins).toEqual(['tool', 'user']);
+ expect(ledgerRefs).toContainEqual({ hash, refKind: 'ghost-grant', refId: 'art', originKind: 'user' });
+
+ await deps.callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [blobUrl],
+ });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('grant_only 对多个既有工具 provenance 在降档下只弹一张确认卡', async () => {
+ const entries = ['batch-a', 'batch-b'].map((label) => {
+ const file = path.join(outsideDir, `${label}.png`);
+ const bytes = Buffer.from(label);
+ fs.writeFileSync(file, bytes);
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ return { file, hash, url: `xdt-media://blob/${hash}` };
+ });
+ const byUrl = new Map(
+ entries.map((entry) => [
+ entry.url,
+ { absPath: entry.file, mimeType: 'image/png', blobHash: entry.hash },
+ ]),
+ );
+ for (const entry of entries) {
+ ledgerRefs.push({
+ hash: entry.hash,
+ refKind: 'ghost-tool-grant',
+ refId: 'art',
+ originKind: 'tool',
+ });
+ }
+ resolveGhostAttachmentUrlMock.mockImplementation((url: string) => {
+ const resolved = byUrl.get(url);
+ if (!resolved) throw new Error('not a managed media URL');
+ return resolved;
+ });
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'ask', remoteHostId: null });
+
+ const result = await makeDeps('pi', 'managed-tool-batch').callGhostTool({
+ ghostId: 'art',
+ tool: 'ignored-tool',
+ args: {},
+ attachments: entries.map((entry) => entry.url),
+ grantOnly: true,
+ });
+
+ expect(result).toMatchObject({
+ ok: true,
+ result: expect.objectContaining({ granted_count: 2 }),
+ });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(confirmRequestMock).toHaveBeenCalledWith(
+ 'managed-tool-batch',
+ expect.objectContaining({
+ lane: 'attachments',
+ items: [
+ expect.objectContaining({ name: 'batch-a.png' }),
+ expect.objectContaining({ name: 'batch-b.png' }),
+ ],
+ }),
+ );
+ expect(resolvedAttachmentOrigins).toEqual(['user', 'user']);
+ expect(ledgerRefs).toHaveLength(4);
+ expect(ledgerRefs.filter((ref) => ref.refKind === 'ghost-grant')).toHaveLength(2);
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
+ it('managed 工具 provenance 在批量预读前受总字节上限保护', async () => {
+ const file = path.join(outsideDir, 'managed-too-large.png');
+ fs.writeFileSync(file, 'sparse-placeholder');
+ const descriptor = fs.openSync(file, 'r+');
+ try {
+ fs.ftruncateSync(descriptor, 1024 * 1024 * 1024 + 1);
+ } finally {
+ fs.closeSync(descriptor);
+ }
+ const hash = createHash('sha256').update('sparse-placeholder').digest('hex');
+ ledgerRefs.push({ hash, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' });
+ resolveGhostAttachmentUrlMock.mockReturnValue({
+ absPath: file,
+ mimeType: 'image/png',
+ blobHash: hash,
+ });
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null });
+
+ const result = await makeDeps('codex', 'managed-too-large').callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [`xdt-media://blob/${hash}`],
+ });
+
+ expect(result).toMatchObject({
+ ok: false,
+ errorCode: 'ATTACHMENT_INVALID',
+ message: expect.stringContaining('总体积过大'),
+ });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(grantAttachmentsMock).not.toHaveBeenCalled();
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
+ it('超出附件张数上限时不触发 managed provenance 预读或确认', async () => {
+ const entries = Array.from({ length: 5 }, (_, index) => {
+ const file = path.join(outsideDir, `over-limit-${index}.png`);
+ const bytes = Buffer.from(`over-limit-${index}`);
+ fs.writeFileSync(file, bytes);
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ return { file, hash, url: `xdt-media://blob/${hash}` };
+ });
+ const byUrl = new Map(
+ entries.map((entry) => [
+ entry.url,
+ { absPath: entry.file, mimeType: 'image/png', blobHash: entry.hash },
+ ]),
+ );
+ for (const entry of entries) {
+ ledgerRefs.push({
+ hash: entry.hash,
+ refKind: 'ghost-tool-grant',
+ refId: 'art',
+ originKind: 'tool',
+ });
+ }
+ resolveGhostAttachmentUrlMock.mockImplementation((url: string) => {
+ const resolved = byUrl.get(url);
+ if (!resolved) throw new Error('not a managed media URL');
+ return resolved;
+ });
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'ask', remoteHostId: null });
+
+ const result = await makeDeps('pi', 'managed-tool-over-limit').callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: entries.map((entry) => entry.url),
+ });
+
+ expect(result).toMatchObject({
+ ok: false,
+ errorCode: 'ATTACHMENT_INVALID',
+ message: expect.stringContaining('附件过多'),
+ });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(grantAttachmentsMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ maxCount: 4 }),
+ );
+ expect(resolvedAttachmentOrigins).toEqual([]);
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ {
+ name: '远程 Full Access',
+ configure: () =>
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: 'remote-1',
+ }),
+ sessionInstanceId: 'remote-instance',
+ },
+ {
+ name: 'live session 缺失',
+ configure: () => liveGrantStateMock.mockReturnValue(null),
+ sessionInstanceId: 'missing-instance',
+ },
+ {
+ name: 'live permission 查询失败',
+ configure: () =>
+ liveGrantStateMock.mockImplementation(() => {
+ throw new Error('runtime registry unavailable');
+ }),
+ sessionInstanceId: 'failed-instance',
+ },
+ {
+ name: 'instance 缺失',
+ configure: () =>
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ }),
+ sessionInstanceId: null,
+ },
+ ] as const)(
+ '$name 下工具 provenance fail closed 到用户确认',
+ async ({ configure, sessionInstanceId }) => {
+ const file = path.join(outsideDir, 'managed-tool-fail-closed.png');
+ const bytes = Buffer.from('managed-tool-fail-closed');
+ fs.writeFileSync(file, bytes);
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ ledgerRefs.push({ hash, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' });
+ resolveGhostAttachmentUrlMock.mockReturnValue({
+ absPath: file,
+ mimeType: 'image/png',
+ blobHash: hash,
+ });
+ configure();
+
+ const result = await makeDeps(
+ 'pi',
+ 'managed-tool-fail-closed',
+ sessionInstanceId,
+ ).callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ attachments: [`xdt-media://blob/${hash}`],
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(resolvedAttachmentOrigins).toEqual(['user']);
+ expect(ledgerRefs).toEqual([
+ { hash, refKind: 'ghost-tool-grant', refId: 'art', originKind: 'tool' },
+ { hash, refKind: 'ghost-grant', refId: 'art', originKind: 'user' },
+ ]);
+ },
+ );
+
+ it('save_dir 在 Full Access 下不弹卡并继续签发票据', async () => {
+ const dir = path.join(outsideDir, 'save-full-access');
+ fs.mkdirSync(dir, { recursive: true });
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ });
+
+ const result = await makeDeps('pi', 'save-full').callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ saveDir: dir,
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ const approvedRealPath = fs.realpathSync.native(dir);
+ expect(saveDepositMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ ghostId: 'art',
+ dirAbs: approvedRealPath,
+ userGranted: true,
+ expectedRealPath: approvedRealPath,
+ }),
+ );
+ expect(logInfoMock).toHaveBeenCalledWith(
+ 'ghost grant: Full Access auto-approved outside-workdir handoff',
+ expect.objectContaining({ lane: 'save_dir', grantSource: 'full-access' }),
+ );
+ });
+
+ it('save_dir 从 Full Access 热切回 ask 后立即恢复确认', async () => {
+ const dir = path.join(outsideDir, 'save-hot-switch');
+ fs.mkdirSync(dir, { recursive: true });
+ let permissionMode = 'bypassPermissions';
+ liveGrantStateMock.mockImplementation(() => ({ permissionMode, remoteHostId: null }));
+ const deps = makeDeps('pi', 'save-hot-switch-session');
+
+ await deps.callGhostTool({ ghostId: 'art', tool: 'run', args: {}, saveDir: dir });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+
+ permissionMode = 'ask';
+ await deps.callGhostTool({ ghostId: 'art', tool: 'run', args: {}, saveDir: dir });
+
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(confirmRequestMock).toHaveBeenCalledWith(
+ 'save-hot-switch-session',
+ expect.objectContaining({ ghostId: 'art', lane: 'save_dir' }),
+ );
+ });
+
+ it('从 Full Access 热切回 ask 后,同一路径立即恢复确认', async () => {
+ const dir = path.join(outsideDir, 'hot-switch');
+ fs.mkdirSync(dir, { recursive: true });
+ let permissionMode = 'bypassPermissions';
+ liveGrantStateMock.mockImplementation(() => ({ permissionMode, remoteHostId: null }));
+ const deps = makeDeps('codex', 'hot-switch-session');
+
+ await deps.callGhostTool({ ghostId: 'art', tool: 'run', args: {}, dir });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+
+ permissionMode = 'ask';
+ await deps.callGhostTool({ ghostId: 'art', tool: 'run', args: {}, dir });
+
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ expect(confirmRequestMock).toHaveBeenCalledWith(
+ 'hot-switch-session',
+ expect.objectContaining({ ghostId: 'art', lane: 'dir' }),
+ );
+ });
+
+ it('同 business sessionId 的旧 MCP context 不能借用新 Session 实例权限', async () => {
+ const dir = path.join(outsideDir, 'same-id-replacement');
+ fs.mkdirSync(dir, { recursive: true });
+ liveGrantStateMock.mockImplementation((_sessionId, sessionInstanceId) =>
+ sessionInstanceId === 'new-instance'
+ ? { permissionMode: 'bypassPermissions', remoteHostId: null }
+ : null,
+ );
+
+ const result = await makeDeps('codex', 'same-business-id', 'old-instance').callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ dir,
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(liveGrantStateMock).toHaveBeenCalledWith('same-business-id', 'old-instance');
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('缺 session instance id 时不能借 Full Access 自动扩权', async () => {
+ const dir = path.join(outsideDir, 'missing-instance-id');
+ fs.mkdirSync(dir, { recursive: true });
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ });
+
+ const result = await makeDeps('claude-code', 'legacy-session', null).callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ dir,
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(liveGrantStateMock).not.toHaveBeenCalled();
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('dir 授权后原始 symlink 改指,也只给已裁决的 canonical 路径出票', async () => {
+ const approved = path.join(outsideDir, 'dir-approved');
+ const replacement = path.join(outsideDir, 'dir-replacement');
+ const alias = path.join(outsideDir, 'dir-alias');
+ fs.mkdirSync(approved, { recursive: true });
+ fs.mkdirSync(replacement, { recursive: true });
+ try {
+ fs.symlinkSync(approved, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return;
+ }
+ const approvedRealPath = fs.realpathSync.native(alias);
+ liveGrantStateMock.mockImplementation(() => {
+ fs.rmSync(alias, { force: true });
+ fs.symlinkSync(replacement, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ return { permissionMode: 'bypassPermissions', remoteHostId: null };
+ });
+
+ const result = await makeDeps('pi', 'dir-toctou').callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ dir: alias,
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(dirDepositMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ dirAbs: approvedRealPath,
+ expectedRealPath: approvedRealPath,
+ userGranted: true,
+ }),
+ );
+ });
+
+ it('save_dir 授权后原始 symlink 改指,也只给已裁决的 canonical 路径出票', async () => {
+ const approved = path.join(outsideDir, 'save-approved');
+ const replacement = path.join(outsideDir, 'save-replacement');
+ const alias = path.join(outsideDir, 'save-alias');
+ fs.mkdirSync(approved, { recursive: true });
+ fs.mkdirSync(replacement, { recursive: true });
+ try {
+ fs.symlinkSync(approved, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return;
+ }
+ const approvedRealPath = fs.realpathSync.native(alias);
+ liveGrantStateMock.mockImplementation(() => {
+ fs.rmSync(alias, { force: true });
+ fs.symlinkSync(replacement, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ return { permissionMode: 'bypassPermissions', remoteHostId: null };
+ });
+
+ const result = await makeDeps('claude-code', 'save-toctou').callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ saveDir: alias,
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(saveDepositMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ dirAbs: approvedRealPath,
+ expectedRealPath: approvedRealPath,
+ userGranted: true,
+ }),
+ );
+ });
+
+ it.each(['ask', 'default', 'acceptEdits', 'plan', 'auto'] as const)(
+ '%s 不自动批准 workdir 外过户',
+ async (permissionMode) => {
+ const sessionId = `mode-${permissionMode}`;
+ const dir = path.join(outsideDir, sessionId);
+ fs.mkdirSync(dir, { recursive: true });
+ liveGrantStateMock.mockReturnValue({ permissionMode, remoteHostId: null });
+
+ const result = await makeDeps('claude-code', sessionId).callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ dir,
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it.each([
+ {
+ name: 'live session 缺失',
+ sessionId: 'missing-live',
+ configure: () => liveGrantStateMock.mockReturnValue(null),
+ },
+ {
+ name: 'live permission 查询失败',
+ sessionId: 'lookup-failed',
+ configure: () =>
+ liveGrantStateMock.mockImplementation(() => {
+ throw new Error('runtime registry unavailable');
+ }),
+ },
+ {
+ name: '远程 Full Access 会话',
+ sessionId: 'remote-full',
+ configure: () =>
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: 'remote-1',
+ }),
+ },
+ ])('$name fail closed 到原确认路径', async ({ sessionId, configure }) => {
+ const dir = path.join(outsideDir, sessionId);
+ fs.mkdirSync(dir, { recursive: true });
+ configure();
+
+ const result = await makeDeps('pi', sessionId).callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ dir,
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('没有 sessionId 时不能借 Full Access 自动扩权', async () => {
+ const dir = path.join(outsideDir, 'anonymous');
+ fs.mkdirSync(dir, { recursive: true });
+ liveGrantStateMock.mockReturnValue({
+ permissionMode: 'bypassPermissions',
+ remoteHostId: null,
+ });
+
+ const result = await makeDeps('claude-code', null).callGhostTool({
+ ghostId: 'art',
+ tool: 'run',
+ args: {},
+ dir,
+ });
+
+ expect(result).toMatchObject({ ok: false, errorCode: 'DIR_INVALID' });
+ expect(liveGrantStateMock).not.toHaveBeenCalled();
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
index e7d479fc63..402b873bfc 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts
@@ -45,6 +45,12 @@ function createTestServer(name: string): McpServer {
server.tool('current_session', 'Return the active lizi MCP session id.', {}, async () => ({
content: [{ type: 'text' as const, text: getLiziMcpSessionContext()?.sessionId ?? 'no-session' }],
}));
+ server.tool('current_instance', 'Return the active runtime session instance id.', {}, async () => ({
+ content: [{
+ type: 'text' as const,
+ text: getLiziMcpSessionContext()?.sessionInstanceId ?? 'no-instance',
+ }],
+ }));
return server;
}
@@ -86,17 +92,19 @@ describe('piEnvironment per-session identity', () => {
await shutdownPiEnvironment();
});
- it('registers a pi session ctx and routes it through ?session= so tools see the sessionId', async () => {
+ it('registers a pi session ctx and routes it through session + instance identity', async () => {
const config = await getPiExtraSpawnConfig([makeProvider()], noopLogger(), {
sessionId: 'pi-lead-1',
+ sessionInstanceId: 'pi-instance-1',
workingDir: '/repo',
vendorOptions: {},
});
expect(config?.mcpBridge).toBeTruthy();
const server = config!.mcpBridge!.servers[0]!;
const token = config!.mcpBridge!.token;
- // URL 必须带上本会话的 ?session= 路由。
- expect(server.url).toContain('?session=pi-lead-1');
+ const routeUrl = new URL(server.url);
+ expect(routeUrl.searchParams.get('session')).toBe('pi-lead-1');
+ expect(routeUrl.searchParams.get('instance')).toBe('pi-instance-1');
const headers = {
authorization: `Bearer ${token}`,
@@ -125,14 +133,81 @@ describe('piEnvironment per-session identity', () => {
result: { content: [{ type: 'text', text: 'pi-lead-1' }] },
});
+ const instanceResp = await fetch(server.url, {
+ method: 'POST',
+ headers: { ...headers, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 3,
+ method: 'tools/call',
+ params: { name: 'current_instance', arguments: {} },
+ }),
+ });
+ expect(instanceResp.status).toBe(200);
+ expect(await readRpcText(instanceResp)).toMatchObject({
+ result: { content: [{ type: 'text', text: 'pi-instance-1' }] },
+ });
+
// close 语义:注销后 ?session=pi-lead-1 未命中 → 401 fail-closed。
expect(config!.disposeSessionCtx).toBeTypeOf('function');
config!.disposeSessionCtx!();
- const after = await fetch(server.url, { method: 'POST', headers, body: INIT_BODY(3) });
+ const after = await fetch(server.url, { method: 'POST', headers, body: INIT_BODY(4) });
expect(after.status).toBe(401);
await after.text();
});
+ it('rejects a stale pi instance route after the same business session is rebound', async () => {
+ const oldConfig = await getPiExtraSpawnConfig([makeProvider()], noopLogger(), {
+ sessionId: 'pi-rebound',
+ sessionInstanceId: 'pi-instance-old',
+ workingDir: '/repo',
+ vendorOptions: {},
+ });
+ const newConfig = await getPiExtraSpawnConfig([makeProvider()], noopLogger(), {
+ sessionId: 'pi-rebound',
+ sessionInstanceId: 'pi-instance-new',
+ workingDir: '/repo',
+ vendorOptions: {},
+ });
+ const oldServer = oldConfig!.mcpBridge!.servers[0]!;
+ const newServer = newConfig!.mcpBridge!.servers[0]!;
+ const headers = {
+ authorization: `Bearer ${newConfig!.mcpBridge!.token}`,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+
+ expect(new URL(oldServer.url).searchParams.get('instance')).toBe('pi-instance-old');
+ expect(new URL(newServer.url).searchParams.get('instance')).toBe('pi-instance-new');
+
+ const stale = await fetch(oldServer.url, {
+ method: 'POST',
+ headers,
+ body: INIT_BODY(11),
+ });
+ expect(stale.status).toBe(401);
+ await stale.text();
+
+ const active = await fetch(newServer.url, {
+ method: 'POST',
+ headers,
+ body: INIT_BODY(12),
+ });
+ expect(active.status).toBe(200);
+ await active.text();
+
+ // 旧进程迟到 close 只释放自己的 lease,不得注销新实例的 ctx。
+ oldConfig!.disposeSessionCtx!();
+ const afterOldClose = await fetch(newServer.url, {
+ method: 'POST',
+ headers,
+ body: INIT_BODY(13),
+ });
+ expect(afterOldClose.status).toBe(200);
+ await afterOldClose.text();
+ newConfig!.disposeSessionCtx!();
+ });
+
it('omits ?session= and registers nothing for an anonymous session (no sessionId)', async () => {
// 非内置 provider(无 plugin 策略)→ 匿名会话不触发 per-call gate,仍能验证 ctx 流通:
// 无 ctx 绑定 → 工具拿到 'no-session'(控制类工具会据此回落 LEAD_NOT_SUPPORTED)。
diff --git a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
index 7ee00b1f1f..fe39a10fba 100644
--- a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
@@ -15,6 +15,7 @@ import { CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY } from './codexBuiltinToolPolicy.
import {
startCodexHttpBridge,
type CodexHttpBridge,
+ withMcpRouteIdentity,
} from './codexHttpBridge.js';
import { getRemoteMcpBridgeToken } from './remoteMcpBridgeToken.js';
@@ -42,6 +43,8 @@ export interface CodexExtraSpawnConfig {
bridge: CodexHttpBridge | null;
/** bridge 上实际挂出的 server 名 (远端注入 config.toml 时按此渲染 mcp_servers 段)。 */
bridgeServerNames: string[];
+ /** 为本地 app-server 的具体 thread 绑定 Session instance 的 URL overrides。 */
+ buildSessionMcpConfig?: (sessionInstanceId: string) => Record<string, unknown>;
}
export interface GetCodexExtraSpawnConfigOptions {
@@ -52,7 +55,10 @@ export interface GetCodexExtraSpawnConfigOptions {
let cached: Promise<CodexExtraSpawnConfig> | null = null;
let activeBridge: CodexHttpBridge | null = null;
let activeBridgeServerNames: string[] | null = null;
-const disabledPluginIdsByThread = new Map<string, unknown>();
+const disabledPluginPolicyByThread = new Map<
+ string,
+ { sessionInstanceId?: string; policy: unknown }
+>();
/**
* 懒启动 + 缓存。多个 codex session 并发首次调用共享同一个 in-flight Promise,
@@ -143,21 +149,37 @@ export function registerCodexMcpThreadContext(
ctx: LiziMcpSessionContext,
): void {
const requestedPolicy = ctx.vendorOptions?.[CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY];
- if (!disabledPluginIdsByThread.has(threadId)) {
- disabledPluginIdsByThread.set(threadId, requestedPolicy);
+ const frozen = disabledPluginPolicyByThread.get(threadId);
+ if (!frozen || frozen.sessionInstanceId !== ctx.sessionInstanceId) {
+ disabledPluginPolicyByThread.set(threadId, {
+ ...(ctx.sessionInstanceId ? { sessionInstanceId: ctx.sessionInstanceId } : {}),
+ policy: requestedPolicy,
+ });
}
+ const effectivePolicy = disabledPluginPolicyByThread.get(threadId)?.policy;
activeBridge?.registerThreadContext(threadId, {
...ctx,
vendorOptions: {
...ctx.vendorOptions,
- [CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: disabledPluginIdsByThread.get(threadId),
+ [CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: effectivePolicy,
},
});
}
-export function unregisterCodexMcpThreadContext(threadId: string): void {
- disabledPluginIdsByThread.delete(threadId);
- activeBridge?.unregisterThreadContext(threadId);
+export function unregisterCodexMcpThreadContext(
+ threadId: string,
+ expectedSessionInstanceId?: string,
+): void {
+ const frozen = disabledPluginPolicyByThread.get(threadId);
+ if (
+ expectedSessionInstanceId !== undefined &&
+ frozen !== undefined &&
+ frozen.sessionInstanceId !== expectedSessionInstanceId
+ ) {
+ return;
+ }
+ disabledPluginPolicyByThread.delete(threadId);
+ activeBridge?.unregisterThreadContext(threadId, expectedSessionInstanceId);
}
async function doStart(
@@ -190,6 +212,9 @@ async function doStart(
...(active.remoteHostId ? { remoteHostId: active.remoteHostId } : {}),
vendorOptions: active.vendorOptions,
sessionId: active.sessionId,
+ ...(active.sessionInstanceId
+ ? { sessionInstanceId: active.sessionInstanceId }
+ : {}),
getSessionContext: ctx.getSessionContext,
};
},
@@ -336,5 +361,16 @@ async function doStart(
},
bridge,
bridgeServerNames,
+ ...(bridge
+ ? {
+ buildSessionMcpConfig: (sessionInstanceId: string) =>
+ Object.fromEntries(
+ bridgeServerNames.map((name) => [
+ `mcp_servers.${name}.url`,
+ withMcpRouteIdentity(bridge.url(name), { sessionInstanceId }),
+ ]),
+ ),
+ }
+ : {}),
};
}
diff --git a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
index 24696506f9..82fe6cbdbd 100644
--- a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
@@ -88,15 +88,33 @@ export function computeRemoteMcpFingerprint(opts: {
bridgeInstanceId: string;
remotePort: number;
serverNames: readonly string[];
+ /** Remote Claude query identity; omitted for the shared remote Codex daemon. */
+ sessionInstanceId?: string;
}): string {
+ const instancePart = opts.sessionInstanceId
+ ? `|session-instance:${opts.sessionInstanceId}`
+ : '';
return createHash('sha256')
.update(
- `${opts.token}|${opts.bridgeInstanceId}|${opts.remotePort}|${[...opts.serverNames].sort().join(',')}`,
+ `${opts.token}|${opts.bridgeInstanceId}|${opts.remotePort}|${[...opts.serverNames].sort().join(',')}${instancePart}`,
'utf8',
)
.digest('hex')
.slice(0, 12);
}
+
+/** Append the opaque host-owned identity used to route one harness MCP client. */
+export function withMcpRouteIdentity(
+ rawUrl: string,
+ identity: { sessionId?: string; sessionInstanceId?: string },
+): string {
+ const url = new URL(rawUrl);
+ if (identity.sessionId) url.searchParams.set('session', identity.sessionId);
+ if (identity.sessionInstanceId) {
+ url.searchParams.set('instance', identity.sessionInstanceId);
+ }
+ return url.toString();
+}
/**
* init request body 上限 (1MB)。codex MCP init payload 实际 < 1KB,
* 1MB 给极端情况留余量。超限直接 413 拒绝 — 防巨大 body 在 JSON.parse
@@ -118,7 +136,7 @@ export interface CodexHttpBridge {
/** 拼出 codex 端 config 用的 URL,例如 http://127.0.0.1:54321/mcp/lizi_feishu */
url(serverName: string): string;
registerThreadContext(threadId: string, ctx: LiziMcpSessionContext): void;
- unregisterThreadContext(threadId: string): void;
+ unregisterThreadContext(threadId: string, expectedSessionInstanceId?: string): void;
/**
* sessionId → session ctx 直绑通道 (远端 Claude Code 用)。
* cc 远端经 SSH remote-forward 直连本 bridge,但其 MCP 请求的 _meta 里没有
@@ -221,10 +239,11 @@ export async function startCodexHttpBridge(
// 路由参数,未命中说明 query 已注销或id 系伪造,不能按无 ctx 放行。
// 不带 ?session= 的 (本地 codex 子进程) 走请求体 threadId 路由。
const sessionQuery = url.searchParams.get('session');
+ const instanceQuery = url.searchParams.get('instance');
let sessionTokenCtx: LiziMcpSessionContext | undefined;
if (sessionQuery !== null) {
- sessionTokenCtx = sessionCtxById.get(sessionQuery);
- if (!sessionTokenCtx) {
+ const registeredCtx = sessionCtxById.get(sessionQuery);
+ if (!registeredCtx) {
res.statusCode = 401;
res.end();
// 不落完整 url:query 里的明文 sessionId 无诊断价值,只记路径与
@@ -235,6 +254,24 @@ export async function startCodexHttpBridge(
});
return;
}
+ if (
+ instanceQuery !== null &&
+ registeredCtx.sessionInstanceId !== instanceQuery
+ ) {
+ res.statusCode = 401;
+ res.end();
+ log.warn('rejected request with mismatched session instance query', {
+ path: url.pathname,
+ session: prefixId(sessionQuery),
+ });
+ return;
+ }
+ // Legacy URLs keep ordinary session-aware tools working, but the
+ // permission-sensitive Full Access shortcut must not accept a context
+ // whose concrete Session instance was never carried by the request.
+ sessionTokenCtx = instanceQuery === null
+ ? withoutSessionInstanceId(registeredCtx)
+ : registeredCtx;
}
if (!url.pathname.startsWith(MCP_PATH_PREFIX)) {
res.statusCode = 404;
@@ -275,6 +312,7 @@ export async function startCodexHttpBridge(
threadContextStore,
pluginId: opts.pluginIdByServerName?.[serverName],
sessionTokenCtx,
+ threadInstanceQuery: sessionQuery === null ? instanceQuery : null,
});
} catch (err) {
log.error('request handler threw', {
@@ -439,6 +477,8 @@ interface DispatchOpts {
pluginId?: string;
/** per-session token 命中时解析出的 ctx;存在即优先于 _meta.threadId 路由。 */
sessionTokenCtx?: LiziMcpSessionContext;
+ /** Local Codex per-thread URL identity. null means an unbound legacy URL. */
+ threadInstanceQuery: string | null;
}
interface SessionTransport {
@@ -456,7 +496,18 @@ interface SessionTransport {
* 重新 init MCP server 的开销)。
*/
async function dispatchToTransport(opts: DispatchOpts): Promise<void> {
- const { req, res, createMcpServer, transports, serverName, log, threadContextStore, pluginId, sessionTokenCtx } = opts;
+ const {
+ req,
+ res,
+ createMcpServer,
+ transports,
+ serverName,
+ log,
+ threadContextStore,
+ pluginId,
+ sessionTokenCtx,
+ threadInstanceQuery,
+ } = opts;
const sessionIdHeader = req.headers['mcp-session-id'];
const sessionId = typeof sessionIdHeader === 'string' ? sessionIdHeader : undefined;
@@ -486,7 +537,10 @@ async function dispatchToTransport(opts: DispatchOpts): Promise<void> {
}
if (!activeContext) {
const threadId = extractCodexThreadId(parsedBody);
- activeContext = threadContextStore.getContextForThreadId(threadId);
+ activeContext = contextForThreadRoute(
+ threadContextStore.getContextForThreadId(threadId),
+ threadInstanceQuery,
+ );
let decision: 'no_thread_id' | 'thread_unregistered' | 'ctx_resolved';
if (!threadId) {
decision = 'no_thread_id';
@@ -504,10 +558,29 @@ async function dispatchToTransport(opts: DispatchOpts): Promise<void> {
});
}
}
+ if (
+ !sessionTokenCtx &&
+ threadInstanceQuery !== null &&
+ hasUnverifiedInstanceBoundToolCall(parsedBody, threadContextStore, threadInstanceQuery)
+ ) {
+ res.statusCode = 401;
+ res.end('Session instance mismatch');
+ log.warn('rejected Codex MCP tool call with stale session instance route', {
+ serverName,
+ mcpSessionId: prefixId(sessionId),
+ });
+ return;
+ }
// per-session token (远端 cc) 命中时身份来自 URL token,tools/call 的
// policy 边界同样要用这份 ctx,不能回落到 threadId 路由后判 missing。
const blockedToolCall = pluginId
- ? findBlockedToolCall(parsedBody, threadContextStore, pluginId, sessionTokenCtx)
+ ? findBlockedToolCall(
+ parsedBody,
+ threadContextStore,
+ pluginId,
+ sessionTokenCtx,
+ threadInstanceQuery,
+ )
: undefined;
if (blockedToolCall && pluginId) {
log.info('blocked Codex built-in tool call', {
@@ -624,6 +697,7 @@ function findBlockedToolCall(
threadContextStore: ReturnType<typeof createCodexMcpThreadContextStore>,
pluginId: string,
sessionTokenCtx?: LiziMcpSessionContext,
+ threadInstanceQuery: string | null = null,
): BlockedToolCall | undefined {
const messages = Array.isArray(body) ? body : [body];
// ?session= 路由时 threadId 不参与任何判定 (强优先, 见下), ambiguity
@@ -641,7 +715,10 @@ function findBlockedToolCall(
// 一个已注册 threadId 就能绕过本 session 冻结的 built-in plugin
// disabled policy (执行态身份同样是 sessionTokenCtx 强优先)。
const threadId = extractCodexThreadIdFromMessage(message);
- const context = sessionTokenCtx ?? threadContextStore.getContextForThreadId(threadId);
+ const context = sessionTokenCtx ?? contextForThreadRoute(
+ threadContextStore.getContextForThreadId(threadId),
+ threadInstanceQuery,
+ );
// Ordinary built-in providers are initialized globally, so the bridge is
// their only deterministic per-thread policy boundary. A malformed or
// stale client must not bypass that boundary by omitting an id or naming
@@ -657,6 +734,44 @@ function findBlockedToolCall(
return undefined;
}
+/**
+ * Resolve a Codex thread only when its registered Session instance matches the
+ * per-thread MCP URL. An unbound legacy URL retains the ordinary context after
+ * removing the instance capability, so Full Access remains fail closed.
+ */
+function contextForThreadRoute(
+ context: LiziMcpSessionContext | undefined,
+ instanceQuery: string | null,
+): LiziMcpSessionContext | undefined {
+ if (!context) return undefined;
+ if (instanceQuery === null) return withoutSessionInstanceId(context);
+ return context.sessionInstanceId === instanceQuery ? context : undefined;
+}
+
+function hasUnverifiedInstanceBoundToolCall(
+ body: unknown,
+ threadContextStore: ReturnType<typeof createCodexMcpThreadContextStore>,
+ instanceQuery: string,
+): boolean {
+ const messages = Array.isArray(body) ? body : [body];
+ for (const message of messages) {
+ if (!isToolCallMessage(message)) continue;
+ const threadId = extractCodexThreadIdFromMessage(message);
+ const context = threadContextStore.getContextForThreadId(threadId);
+ if (!threadId || context?.sessionInstanceId !== instanceQuery) return true;
+ }
+ return false;
+}
+
+function withoutSessionInstanceId(
+ context: LiziMcpSessionContext,
+): LiziMcpSessionContext {
+ if (!context.sessionInstanceId) return context;
+ const { sessionInstanceId: _sessionInstanceId, ...legacyContext } = context;
+ void _sessionInstanceId;
+ return legacyContext;
+}
+
function writeBlockedToolCallResponse(
res: http.ServerResponse,
body: unknown,
diff --git a/apps/desktop/src/main/mcp-integrations/codexMcpThreadContextStore.ts b/apps/desktop/src/main/mcp-integrations/codexMcpThreadContextStore.ts
index 7d0227b03f..351e245932 100644
--- a/apps/desktop/src/main/mcp-integrations/codexMcpThreadContextStore.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexMcpThreadContextStore.ts
@@ -2,7 +2,7 @@ import type { LiziMcpSessionContext } from '@cindy/mcps';
export interface CodexMcpThreadContextStore {
registerThreadContext(threadId: string, ctx: LiziMcpSessionContext): void;
- unregisterThreadContext(threadId: string): void;
+ unregisterThreadContext(threadId: string, expectedSessionInstanceId?: string): void;
getContextForThreadId(threadId: string | undefined): LiziMcpSessionContext | undefined;
registeredThreadCount(): number;
}
@@ -15,7 +15,13 @@ export function createCodexMcpThreadContextStore(): CodexMcpThreadContextStore {
contextsByThread.set(threadId, ctx);
},
- unregisterThreadContext(threadId) {
+ unregisterThreadContext(threadId, expectedSessionInstanceId) {
+ if (
+ expectedSessionInstanceId !== undefined &&
+ contextsByThread.get(threadId)?.sessionInstanceId !== expectedSessionInstanceId
+ ) {
+ return;
+ }
contextsByThread.delete(threadId);
},
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index e4ec837b23..1c3201feb9 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -26,6 +26,7 @@ import type {
CindyGhostInfo,
CindyGhostsMcpDeps,
} from 'cindy-tools';
+import type { PermissionMode } from '@cindy/maker-core';
import { getLiziMcpSessionContext, type LiziMcpSessionContext } from '@cindy/mcps';
import {
@@ -75,12 +76,32 @@ import { createLogger } from '../logger.js';
const log = createLogger('mcp/cindy');
/* ────────────────────────────────────────────────────────────────────────
- * workdir 外过户确认(2026-07-14 与 Lizi 定案的两层策略):
+ * workdir 外过户确认:
* - 过户对象在会话 workdir 内 → 自动放行(与目录过户同信任等级);
- * - workdir 外(含无 workdir 语境)→ 弹确认卡,用户点允许才继续。
- * 决定权在用户的点击上——被注入的模型只能发起请求,点不了按钮。
+ * - 本地活跃会话当前为 Full Access(bypassPermissions) → Host 自动放行;
+ * - 其余 workdir 外场景(含无会话/远程会话)→ 弹确认卡,用户点允许才继续。
+ * Full Access 只替代本处文件/目录交接确认,不扩大插件 manifest slot、网络、
+ * 凭证、Setup、安装/更新等其它授权边界。
* ──────────────────────────────────────────────────────────────────────── */
+export interface GhostGrantLiveSessionState {
+ permissionMode: PermissionMode | null;
+ remoteHostId: string | null;
+}
+
+export interface CindyGhostsHostDeps {
+ /**
+ * 现读活跃 Maker Session 的运行时状态。不得回退 DB:权限热切换先作用于
+ * runtime、后持久化,DB 在合法窗口内会滞后;缺失/异常必须 fail closed。
+ */
+ getLiveSessionGrantState?: (
+ sessionId: string,
+ sessionInstanceId: string,
+ ) => GhostGrantLiveSessionState | null;
+}
+
+type GhostGrantApprovalSource = 'user' | 'full-access';
+
/** 确认卡内嵌图片预览的文件体积上限(只是预览阈值,不是过户限制——超阈值
* 照样可过户,卡片上退化为文件名 + 路径 + 大小)。 */
const GRANT_PREVIEW_MAX_BYTES = 4 * 1024 * 1024;
@@ -92,6 +113,10 @@ const GRANT_PREVIEW_MAX_ITEMS = 8;
* 持有(最长 10 分钟),不设闸的话 32 张大视频能把 main 进程打到 OOM。 */
const GRANT_BATCH_MAX_TOTAL_BYTES = 1024 * 1024 * 1024;
+function grantBatchTooLargeMessage(): string {
+ return `本批附件总体积过大(超过 ${Math.floor(GRANT_BATCH_MAX_TOTAL_BYTES / (1024 * 1024))}MB),请拆成多批过户`;
+}
+
/** 已读入的文件字节 → dataURL 缩略预览(确认卡展示真实字节;非图/超阈值缺省)。 */
function buildGrantPreviewDataUrl(buffer: Uint8Array, mimeType: string): string | undefined {
if (!mimeType.startsWith('image/') || buffer.byteLength > GRANT_PREVIEW_MAX_BYTES)
@@ -171,9 +196,38 @@ function isInsideSessionWorkdir(targetAbs: string, workdirAbs: string | null): b
async function requestGrantConfirm(params: {
ghostId: string;
sessionId: string | null;
+ sessionInstanceId: string | null;
lane: GhostGrantLane;
items: GhostGrantFileItem[];
-}): Promise<{ ok: true; allowDirs?: boolean } | { ok: false; message: string }> {
+ getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
+}): Promise<
+ | { ok: true; approvalSource: GhostGrantApprovalSource; allowDirs?: boolean }
+ | { ok: false; message: string }
+> {
+ if (params.sessionId && params.sessionInstanceId && params.getLiveSessionGrantState) {
+ try {
+ const live = params.getLiveSessionGrantState(params.sessionId, params.sessionInstanceId);
+ // 远程会话的 workingDir 是另一台机器上的路径。即使档位为 Full Access,
+ // 也不能据此静默读取本机同名/任意路径;保留原确认边界。
+ if (live?.permissionMode === 'bypassPermissions' && !live.remoteHostId) {
+ log.info('ghost grant: Full Access auto-approved outside-workdir handoff', {
+ ghostId: params.ghostId,
+ lane: params.lane,
+ count: params.items.length,
+ grantSource: 'full-access',
+ });
+ return { ok: true, approvalSource: 'full-access' };
+ }
+ } catch (error) {
+ // 自动扩权查询必须 fail closed:运行时状态读不到就继续走原确认路径,
+ // 绝不回退可能滞后的 DB permission_mode。
+ log.warn('ghost grant: live permission lookup failed; falling back to confirmation', {
+ ghostId: params.ghostId,
+ lane: params.lane,
+ errorType: error instanceof Error ? error.name : typeof error,
+ });
+ }
+ }
const bridge = getGhostGrantConfirmBridge();
if (!bridge) {
return {
@@ -195,7 +249,9 @@ async function requestGrantConfirm(params: {
lane: params.lane,
items: params.items,
});
- if (decision.confirmed) return { ok: true, allowDirs: decision.allowDirs };
+ if (decision.confirmed) {
+ return { ok: true, approvalSource: 'user', allowDirs: decision.allowDirs };
+ }
return {
ok: false,
message:
@@ -216,6 +272,8 @@ async function prepareLocalPathAttachments(params: {
ghostId: string;
workdirAbs: string | null;
sessionId: string | null;
+ sessionInstanceId: string | null;
+ getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
/** 张数上限(普通调用 MAX_GRANT_ATTACHMENTS;grant_only 批量预授权放宽)。 */
maxCount: number;
}): Promise<
@@ -265,12 +323,14 @@ async function prepareLocalPathAttachments(params: {
if (totalBytes > GRANT_BATCH_MAX_TOTAL_BYTES) {
return {
ok: false,
- message: `本批附件总体积过大(超过 ${Math.floor(GRANT_BATCH_MAX_TOTAL_BYTES / (1024 * 1024))}MB),请拆成多批过户`,
+ message: grantBatchTooLargeMessage(),
};
}
- // 授权记忆(按张、永久):先算内容指纹查账本,该意识名下已有 ghost-grant
- // 授权行的直接放行——同一张图允许过一次,后续调用不再重复弹卡。指纹
- // 算法与 blobStore.writeBlob 同(sha256 hex),读到的字节顺便喂预览。
+ // 人工授权记忆(按张、永久):先算内容指纹查账本,该意识名下已有 user
+ // provenance 的 ghost-grant 授权行才直接放行。Full Access 自动交接写入
+ // 独立 ghost-tool-grant + tool provenance,热切回 ask/auto 后必须恢复确认。
+ // 指纹算法与
+ // blobStore.writeBlob 同(sha256 hex),读到的字节顺便喂预览。
const needConfirm: Array<{
url: string;
absPath: string;
@@ -289,7 +349,12 @@ async function prepareLocalPathAttachments(params: {
const hash = createHash('sha256').update(buffer).digest('hex');
// 两级记忆:内容指纹永久授权(账本)→ 目录级会话授权(确认卡勾选)。
const granted =
- (await ledger.hasRef({ hash, refKind: 'ghost-grant', refId: params.ghostId })) ||
+ (await ledger.hasRef({
+ hash,
+ refKind: 'ghost-grant',
+ refId: params.ghostId,
+ originKind: 'user',
+ })) ||
(params.sessionId !== null &&
dirGrantMemory.has(
dirGrantMemoryKey(
@@ -334,23 +399,26 @@ async function prepareLocalPathAttachments(params: {
const confirm = await requestGrantConfirm({
ghostId: params.ghostId,
sessionId: params.sessionId,
+ sessionInstanceId: params.sessionInstanceId,
lane: 'attachments',
items,
+ getLiveSessionGrantState: params.getLiveSessionGrantState,
});
if (!confirm.ok) return confirm;
for (const o of needConfirm) {
- // 用户点了允许 = 显式授权,出生记 user(与拖图进聊天同语义);带 T1
- // 字节落仓——确认卡预览的字节就是过户的字节,中途换文件无效。
+ // 人工确认记 user;Full Access 自动交接记 tool,不能伪装成用户点击。
+ // 两者都带 T1 字节落仓——确认/授权判定时读到的字节就是实际过户
+ // 的字节,中途换文件无效。
resolved.set(o.url, {
absPath: o.absPath,
mimeType: o.mimeType,
- originKind: 'user',
+ originKind: confirm.approvalSource === 'user' ? 'user' : 'tool',
buffer: o.buffer,
});
}
// 「允许该目录」勾选:把每张图的精确父目录记入会话级记忆,后续同目录
// 媒体文件对该意识本会话免弹(跨调用批量任务只需点一次)。
- if (confirm.allowDirs && params.sessionId) {
+ if (confirm.approvalSource === 'user' && confirm.allowDirs && params.sessionId) {
for (const o of needConfirm) {
dirGrantMemory.add(
dirGrantMemoryKey(
@@ -362,27 +430,37 @@ async function prepareLocalPathAttachments(params: {
);
}
}
- log.info('ghost grant confirm: user approved outside-workdir attachments', {
- ghostId: params.ghostId,
- count: needConfirm.length,
- });
+ if (confirm.approvalSource === 'user') {
+ log.info('ghost grant confirm: user approved outside-workdir attachments', {
+ ghostId: params.ghostId,
+ count: needConfirm.length,
+ grantSource: 'user-confirmation',
+ });
+ }
}
}
return { ok: true, resolved };
}
/**
- * dir / save_dir 的 workdir 外确认:目标真实存在且在 workdir 外时弹卡,
- * 允许 → userGranted=true 交给票据库旁路钳制;目标不存在/类型不对时不弹
- * (直接交给 deposit 报标准错,别让用户为一个必失败的请求点允许)。
+ * dir / save_dir 的 workdir 外授权:目标真实存在且在 workdir 外时,人工确认
+ * 或本地活跃 Full Access 可令历史字段 userGranted=true,交给票据库旁路钳制;
+ * 目标不存在/类型不对时不弹卡(直接交给 deposit 报标准错,别让用户为一个
+ * 必失败的请求点允许)。
*/
async function confirmDepositOutsideWorkdir(params: {
ghostId: string;
sessionId: string | null;
+ sessionInstanceId: string | null;
lane: 'dir' | 'save_dir';
dirAbs: string;
workdirAbs: string | null;
-}): Promise<{ ok: true; userGranted: boolean } | { ok: false; message: string }> {
+ getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
+}): Promise<
+ | { ok: true; userGranted: false }
+ | { ok: true; userGranted: true; approvedRealPath: string }
+ | { ok: false; message: string }
+> {
if (!path.isAbsolute(params.dirAbs)) return { ok: true, userGranted: false };
let real: string;
let stat: fs.Stats;
@@ -399,7 +477,7 @@ async function confirmDepositOutsideWorkdir(params: {
params.sessionId &&
dirGrantMemory.has(dirGrantMemoryKey(params.sessionId, params.ghostId, params.lane, real))
) {
- return { ok: true, userGranted: true };
+ return { ok: true, userGranted: true, approvedRealPath: real };
}
let item: GhostGrantFileItem;
@@ -428,18 +506,180 @@ async function confirmDepositOutsideWorkdir(params: {
const confirm = await requestGrantConfirm({
ghostId: params.ghostId,
sessionId: params.sessionId,
+ sessionInstanceId: params.sessionInstanceId,
lane: params.lane,
items: [item],
+ getLiveSessionGrantState: params.getLiveSessionGrantState,
});
if (!confirm.ok) return confirm;
- if (params.sessionId) {
+ // Full Access 是每次在实时档位上自动裁决,不伪造「用户确认过」的目录
+ // 记忆。这样热切回 ask/auto 后,同一路径的新过户会立刻恢复询问。
+ if (confirm.approvalSource === 'user' && params.sessionId) {
dirGrantMemory.add(dirGrantMemoryKey(params.sessionId, params.ghostId, params.lane, real));
}
- log.info('ghost grant confirm: user approved outside-workdir deposit', {
+ if (confirm.approvalSource === 'user') {
+ log.info('ghost grant confirm: user approved outside-workdir deposit', {
+ ghostId: params.ghostId,
+ lane: params.lane,
+ grantSource: 'user-confirmation',
+ });
+ }
+ return { ok: true, userGranted: true, approvedRealPath: real };
+}
+
+type ManagedToolGrantCandidate = {
+ hash: string;
+ absPath: string;
+ mimeType: string;
+ buffer: Uint8Array;
+ urls: string[];
+};
+
+/**
+ * 总仓 blob 的工具交接必须先整批完成权限裁决,再交给 attachmentGrant
+ * 的两阶段解析/落仓。这样 grant_only 仍只弹一张确认卡,同时把确认前
+ * 读到的同一批字节限制在统一的内存上限内。
+ */
+async function prepareManagedToolGrantSources(params: {
+ urls: string[];
+ ghostId: string;
+ localResolved: Map<string, ResolvedGrantSource>;
+ maxCount: number;
+ sessionId: string | null;
+ sessionInstanceId: string | null;
+ getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
+}): Promise<
+ { ok: true; resolved: Map<string, ResolvedGrantSource> } | { ok: false; message: string }
+> {
+ // Preserve attachmentGrant's standard count error and, importantly, do not
+ // read or confirm an over-limit batch before that error is produced.
+ if (params.urls.length > params.maxCount) return { ok: true, resolved: new Map() };
+
+ const candidates = new Map<string, ManagedToolGrantCandidate>();
+ let totalBytes = 0;
+ for (const source of params.localResolved.values()) {
+ if (source.buffer) totalBytes += source.buffer.byteLength;
+ }
+
+ for (const url of params.urls) {
+ if (params.localResolved.has(url)) continue;
+ let resolved: { absPath: string; mimeType: string; blobHash?: string };
+ try {
+ resolved = resolveGhostAttachmentUrl(url);
+ } catch {
+ continue;
+ }
+ if (!resolved.blobHash) continue;
+
+ let origin: 'user' | 'tool' | null;
+ let userGranted: boolean;
+ let toolGranted: boolean;
+ try {
+ origin = await chatAttachmentOrigin(resolved.blobHash);
+ if (origin) continue;
+ userGranted = await ledger.hasRef({
+ hash: resolved.blobHash,
+ refKind: 'ghost-grant',
+ refId: params.ghostId,
+ originKind: 'user',
+ });
+ if (userGranted) continue;
+ toolGranted = await ledger.hasGhostToolGrant({
+ hash: resolved.blobHash,
+ ghostId: params.ghostId,
+ });
+ } catch {
+ return { ok: false, message: '附件授权状态读取失败,请重试' };
+ }
+ if (!toolGranted) continue;
+
+ let candidate = candidates.get(resolved.blobHash);
+ if (!candidate) {
+ let stat: fs.Stats;
+ try {
+ stat = await fs.promises.stat(resolved.absPath);
+ } catch {
+ return {
+ ok: false,
+ message: `附件读取失败:${path.basename(resolved.absPath)}(文件不可读或已被移动)`,
+ };
+ }
+ if (!stat.isFile()) {
+ return {
+ ok: false,
+ message: `附件读取失败:${path.basename(resolved.absPath)}(文件不可读或已被移动)`,
+ };
+ }
+ if (totalBytes + stat.size > GRANT_BATCH_MAX_TOTAL_BYTES) {
+ return { ok: false, message: grantBatchTooLargeMessage() };
+ }
+ let buffer: Uint8Array;
+ try {
+ buffer = await fs.promises.readFile(resolved.absPath);
+ } catch {
+ return {
+ ok: false,
+ message: `附件读取失败:${path.basename(resolved.absPath)}(文件不可读或已被移动)`,
+ };
+ }
+ if (totalBytes + buffer.byteLength > GRANT_BATCH_MAX_TOTAL_BYTES) {
+ return { ok: false, message: grantBatchTooLargeMessage() };
+ }
+ totalBytes += buffer.byteLength;
+ candidate = {
+ hash: resolved.blobHash,
+ absPath: resolved.absPath,
+ mimeType: resolved.mimeType,
+ buffer,
+ urls: [],
+ };
+ candidates.set(resolved.blobHash, candidate);
+ }
+ candidate.urls.push(url);
+ }
+
+ if (candidates.size === 0) return { ok: true, resolved: new Map() };
+
+ let previewCount = 0;
+ const items: GhostGrantFileItem[] = [];
+ for (const candidate of candidates.values()) {
+ const canPreview =
+ candidate.mimeType.startsWith('image/') && previewCount < GRANT_PREVIEW_MAX_ITEMS;
+ const previewDataUrl = canPreview
+ ? buildGrantPreviewDataUrl(candidate.buffer, candidate.mimeType)
+ : undefined;
+ if (previewDataUrl) previewCount += 1;
+ items.push({
+ name: path.basename(candidate.absPath),
+ absPath: candidate.absPath,
+ size: candidate.buffer.byteLength,
+ mimeType: candidate.mimeType,
+ ...(previewDataUrl ? { previewDataUrl } : {}),
+ });
+ }
+
+ const confirm = await requestGrantConfirm({
ghostId: params.ghostId,
- lane: params.lane,
+ sessionId: params.sessionId,
+ sessionInstanceId: params.sessionInstanceId,
+ lane: 'attachments',
+ items,
+ getLiveSessionGrantState: params.getLiveSessionGrantState,
});
- return { ok: true, userGranted: true };
+ if (!confirm.ok) return confirm;
+
+ const originKind = confirm.approvalSource === 'user' ? 'user' : 'tool';
+ const resolved = new Map<string, ResolvedGrantSource>();
+ for (const candidate of candidates.values()) {
+ const source: ResolvedGrantSource = {
+ absPath: candidate.absPath,
+ mimeType: candidate.mimeType,
+ originKind,
+ buffer: candidate.buffer,
+ };
+ for (const url of candidate.urls) resolved.set(url, source);
+ }
+ return { ok: true, resolved };
}
/**
@@ -453,6 +693,8 @@ async function grantAttachmentUrls(params: {
urls: string[];
workdirAbs: string | null;
sessionId: string | null;
+ sessionInstanceId: string | null;
+ getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
maxCount: number;
}): Promise<{ ok: true; hashes: string[] } | { ok: false; message: string }> {
const { ghostId } = params;
@@ -461,9 +703,21 @@ async function grantAttachmentUrls(params: {
ghostId,
workdirAbs: params.workdirAbs,
sessionId: params.sessionId,
+ sessionInstanceId: params.sessionInstanceId,
+ getLiveSessionGrantState: params.getLiveSessionGrantState,
maxCount: params.maxCount,
});
if (!localGrant.ok) return localGrant;
+ const managedToolGrant = await prepareManagedToolGrantSources({
+ urls: params.urls,
+ ghostId,
+ localResolved: localGrant.resolved,
+ maxCount: params.maxCount,
+ sessionId: params.sessionId,
+ sessionInstanceId: params.sessionInstanceId,
+ getLiveSessionGrantState: params.getLiveSessionGrantState,
+ });
+ if (!managedToolGrant.ok) return managedToolGrant;
return grantAttachmentsToGhost(
{
// 宽容解析:模型可能只有本地路径、缩图副本路径、或把 xdt-image
@@ -474,21 +728,36 @@ async function grantAttachmentUrls(params: {
resolveImageUrl: async (url) => {
const local = localGrant.resolved.get(url);
if (local) return local;
+ const managed = managedToolGrant.resolved.get(url);
+ if (managed) return managed;
const r = resolveGhostAttachmentUrl(url);
if (!r.blobHash) return r;
const origin = await chatAttachmentOrigin(r.blobHash);
if (!origin) {
- // 授权记忆:该内容此前已过户给本意识(ghost-grant 行在账)时,
- // 模型拿总仓地址再引用直接放行——workdir 外确认流落仓后,
- // 模型手里的地址就是总仓形态,不放行会逼它绕回原路径。
- const granted = await ledger.hasRef({
+ // 交接记忆:该内容此前已过户给本意识时,模型拿总仓地址再引用
+ // 直接放行——workdir 外确认流落仓后,模型手里的地址就是总仓
+ // 形态,不放行会逼它绕回原路径。人工确认与 Host 工具代办必须
+ // 保留各自 provenance:后者仍是 ghost-tool-grant,绝不升级成人工
+ // 永久授权;这里只复用它本来就已经赋予插件的取件能力。
+ const userGranted = await ledger.hasRef({
hash: r.blobHash,
refKind: 'ghost-grant',
refId: ghostId,
+ originKind: 'user',
});
- if (granted) {
+ if (userGranted) {
return { absPath: r.absPath, mimeType: r.mimeType, originKind: 'user' };
}
+ const toolGranted = await ledger.hasGhostToolGrant({
+ hash: r.blobHash,
+ ghostId,
+ });
+ if (toolGranted) {
+ // The batch preflight above must have covered every tool grant.
+ // If the ledger changes during the async resolve phase, fail
+ // closed instead of silently opening a one-item confirmation path.
+ throw new GrantPolicyError('附件授权状态已变化,请重试');
+ }
// 策略拒绝标记:message 原样透给模型(落格式教学文案会误导自纠)。
throw new GrantPolicyError('该图片不是聊天里出现过的附件,不可过户');
}
@@ -497,10 +766,15 @@ async function grantAttachmentUrls(params: {
readFile: (absPath) => fs.promises.readFile(absPath),
writeBlob: (p) => blobStore.writeBlob(p),
recordBlob: (p) => ledger.recordBlob(p),
- // 幂等化:同 (指纹, 意识) 已有授权行就不再插新行——授权语义是
- // "存在即永久",重复过户同一张图不该让账本膨胀。
+ // 顺序调用幂等化:同 (指纹,意识,引用类型,来源) 已有交接行就不再插入。
+ // 并发 check-then-insert 仍可能产生重复账行,但不会改变归属或扩权语义。
addRef: async (p) => {
- const exists = await ledger.hasRef({ hash: p.hash, refKind: p.refKind, refId: p.refId });
+ const exists = await ledger.hasRef({
+ hash: p.hash,
+ refKind: p.refKind,
+ refId: p.refId,
+ originKind: p.originKind,
+ });
return exists ? '' : ledger.addRef(p);
},
log,
@@ -518,7 +792,10 @@ async function grantAttachmentUrls(params: {
* AsyncLocalStorage(getLiziMcpSessionContext)恢复——因此运行时取语境一律
* "ALS 优先、闭包兜底"(见 resolveSessionContext)。
*/
-export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): CindyGhostsMcpDeps {
+export function getCindyGhostsMcpDeps(
+ sessionCtx?: LiziMcpSessionContext,
+ hostDeps: CindyGhostsHostDeps = {},
+): CindyGhostsMcpDeps {
const resolveSessionContext = (): LiziMcpSessionContext | undefined =>
getLiziMcpSessionContext() ?? sessionCtx;
return {
@@ -619,13 +896,14 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
message: '该插件需要 Cindy 账号,未登录状态不可用;不要重试,改用本地可用方式。',
};
}
- // 用户图片过户:attachments 里的地址逐张落媒体总仓 + 记
- // ghost-grant 引用(显式引渡 = 授权,按张、永久),指纹注入
+ // 用户图片过户:attachments 里的地址逐张落媒体总仓 + 记可读引用
+ // (人工确认 = ghost-grant;Host 工具代办 = ghost-tool-grant),指纹注入
// args.attachments 交给意识。任何一张失败整批拒(ATTACHMENT_INVALID),
// 不做半成品授权。全链路见 grantAttachmentUrls。
let mergedArgs = args;
const sessionContext = resolveSessionContext();
const sessionIdForConfirm = sessionContext?.sessionId ?? null;
+ const sessionInstanceIdForGrant = sessionContext?.sessionInstanceId ?? null;
const sessionWorkdir = sessionContext?.workingDir ?? null;
// 目录级禁用兜底(防御线):花名册/ghost_list 已过滤,正常路径走不到
// 这里——只有"会话开着时中途被禁"(快照已含自述)或模型凭上文记忆
@@ -693,10 +971,18 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
.list()
.find((g) => g.manifest.id === ghostId);
if (!refreshed || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
}
if (!refreshed.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
}
if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
return {
@@ -709,13 +995,21 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
!grantOnly &&
!(refreshed.manifest.tools ?? []).some((candidate) => candidate.name === tool)
) {
- return { ok: false, errorCode: 'TOOL_NOT_FOUND', message: toolNotFoundMessage(ghostId, tool, refreshed.manifest.tools) };
+ return {
+ ok: false,
+ errorCode: 'TOOL_NOT_FOUND',
+ message: toolNotFoundMessage(ghostId, tool, refreshed.manifest.tools),
+ };
}
let finalAssessment;
try {
finalAssessment = getGhostSetupAssessment(ghostId);
} catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
}
if (finalAssessment.state !== 'ready') {
return {
@@ -734,27 +1028,50 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
.list()
.find((g) => g.manifest.id === ghostId);
if (!grantTarget || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
}
if (!grantTarget.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
}
if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR', message: t('newChat.pluginSetup.targetDisabledInWorkdir') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
}
try {
const grantOnlyAssessment = getGhostSetupAssessment(ghostId);
if (grantOnlyAssessment.state !== 'ready') {
- return { ok: false, errorCode: 'SETUP_REQUIRED', message: t('newChat.pluginSetup.setupIncomplete'), setup: grantOnlyAssessment };
+ return {
+ ok: false,
+ errorCode: 'SETUP_REQUIRED',
+ message: t('newChat.pluginSetup.setupIncomplete'),
+ setup: grantOnlyAssessment,
+ };
}
} catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
}
const grant = await grantAttachmentUrls({
ghostId,
urls: attachments!,
workdirAbs: sessionWorkdir,
sessionId: sessionIdForConfirm,
+ sessionInstanceId: sessionInstanceIdForGrant,
+ getLiveSessionGrantState: hostDeps.getLiveSessionGrantState,
maxCount: MAX_GRANT_ONLY_ATTACHMENTS,
});
if (!grant.ok) {
@@ -766,21 +1083,42 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
.list()
.find((g) => g.manifest.id === ghostId);
if (!postGrant || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
}
if (!postGrant.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
}
if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR', message: t('newChat.pluginSetup.targetDisabledInWorkdir') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
}
try {
const postGrantAssessment = getGhostSetupAssessment(ghostId);
if (postGrantAssessment.state !== 'ready') {
- return { ok: false, errorCode: 'SETUP_REQUIRED', message: t('newChat.pluginSetup.setupChangedDuringResume'), setup: postGrantAssessment };
+ return {
+ ok: false,
+ errorCode: 'SETUP_REQUIRED',
+ message: t('newChat.pluginSetup.setupChangedDuringResume'),
+ setup: postGrantAssessment,
+ };
}
} catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
}
log.info('ghost grant-only: batch pre-granted', { ghostId, count: grant.hashes.length });
return {
@@ -790,7 +1128,7 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
granted_count: grant.hashes.length,
attachments: grant.hashes,
guidance:
- '整批文件已过户并获授权;继续逐次调用目标工具,引用原路径或这些指纹都不会再弹确认卡。不要向用户复述指纹列表。',
+ '整批文件已过户并获授权;在当前权限档位下继续逐次调用目标工具,可引用原路径或这些指纹。若热切回需要确认的权限档位,后续重新交接可能再次弹出确认卡。不要向用户复述指纹列表。',
},
};
}
@@ -800,6 +1138,8 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
urls: attachments,
workdirAbs: sessionWorkdir,
sessionId: sessionIdForConfirm,
+ sessionInstanceId: sessionInstanceIdForGrant,
+ getLiveSessionGrantState: hostDeps.getLiveSessionGrantState,
maxCount: MAX_GRANT_ATTACHMENTS,
});
if (!grant.ok) {
@@ -815,18 +1155,21 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
const dirConfirm = await confirmDepositOutsideWorkdir({
ghostId,
sessionId: sessionIdForConfirm,
+ sessionInstanceId: sessionInstanceIdForGrant,
lane: 'dir',
dirAbs: dir,
workdirAbs: sessionWorkdir,
+ getLiveSessionGrantState: hostDeps.getLiveSessionGrantState,
});
if (!dirConfirm.ok) {
return { ok: false, errorCode: 'DIR_INVALID', message: dirConfirm.message };
}
const deposited = getDirDepositVault().deposit({
ghostId,
- dirAbs: dir,
+ dirAbs: dirConfirm.userGranted ? dirConfirm.approvedRealPath : dir,
workdirAbs: sessionWorkdir,
userGranted: dirConfirm.userGranted,
+ ...(dirConfirm.userGranted ? { expectedRealPath: dirConfirm.approvedRealPath } : {}),
});
if (!deposited.ok) {
return { ok: false, errorCode: 'DIR_INVALID', message: deposited.message };
@@ -840,18 +1183,21 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
const saveConfirm = await confirmDepositOutsideWorkdir({
ghostId,
sessionId: sessionIdForConfirm,
+ sessionInstanceId: sessionInstanceIdForGrant,
lane: 'save_dir',
dirAbs: saveDir,
workdirAbs: sessionWorkdir,
+ getLiveSessionGrantState: hostDeps.getLiveSessionGrantState,
});
if (!saveConfirm.ok) {
return { ok: false, errorCode: 'DIR_INVALID', message: saveConfirm.message };
}
const saveDeposited = getSaveDepositVault().deposit({
ghostId,
- dirAbs: saveDir,
+ dirAbs: saveConfirm.userGranted ? saveConfirm.approvedRealPath : saveDir,
workdirAbs: sessionWorkdir,
userGranted: saveConfirm.userGranted,
+ ...(saveConfirm.userGranted ? { expectedRealPath: saveConfirm.approvedRealPath } : {}),
});
if (!saveDeposited.ok) {
return { ok: false, errorCode: 'DIR_INVALID', message: saveDeposited.message };
@@ -863,6 +1209,7 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
// "主机铸造、不可伪造";未声明槽的插件连剥除后的空位都不给。
if ('session_context' in mergedArgs) {
const { session_context: _dropped, ...rest } = mergedArgs;
+ void _dropped;
mergedArgs = rest;
}
// Pre-dispatch revalidation: attachment grants and dir tickets may have
@@ -872,10 +1219,18 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
.list()
.find((g) => g.manifest.id === ghostId);
if (!preDispatch || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
}
if (!preDispatch.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
}
if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
return {
@@ -885,7 +1240,11 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
};
}
if (!(preDispatch.manifest.tools ?? []).some((c) => c.name === tool)) {
- return { ok: false, errorCode: 'TOOL_NOT_FOUND', message: toolNotFoundMessage(ghostId, tool, preDispatch.manifest.tools) };
+ return {
+ ok: false,
+ errorCode: 'TOOL_NOT_FOUND',
+ message: toolNotFoundMessage(ghostId, tool, preDispatch.manifest.tools),
+ };
}
try {
const preDispatchAssessment = getGhostSetupAssessment(ghostId);
@@ -898,7 +1257,11 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
};
}
} catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
}
// Session-context slot: use the revalidated manifest to decide injection.
// Re-read manifest after the async buildGhostSessionContext to guard against
@@ -913,26 +1276,53 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
}
}
// Full revalidation after session-context await (DB query may take time)
- const postCtx = getGhostManager().list().find((g) => g.manifest.id === ghostId);
+ const postCtx = getGhostManager()
+ .list()
+ .find((g) => g.manifest.id === ghostId);
if (!postCtx || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
}
if (!postCtx.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
}
if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR', message: t('newChat.pluginSetup.targetDisabledInWorkdir') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
}
if (!(postCtx.manifest.tools ?? []).some((c) => c.name === tool)) {
- return { ok: false, errorCode: 'TOOL_NOT_FOUND', message: toolNotFoundMessage(ghostId, tool, postCtx.manifest.tools) };
+ return {
+ ok: false,
+ errorCode: 'TOOL_NOT_FOUND',
+ message: toolNotFoundMessage(ghostId, tool, postCtx.manifest.tools),
+ };
}
try {
const postCtxAssessment = getGhostSetupAssessment(ghostId);
if (postCtxAssessment.state !== 'ready') {
- return { ok: false, errorCode: 'SETUP_REQUIRED', message: t('newChat.pluginSetup.setupChangedDuringResume'), setup: postCtxAssessment };
+ return {
+ ok: false,
+ errorCode: 'SETUP_REQUIRED',
+ message: t('newChat.pluginSetup.setupChangedDuringResume'),
+ setup: postCtxAssessment,
+ };
}
} catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
}
// ── 卡槽③:callId 在这里预铸并登记给卡片服务 ────────────────────
// 时序契约:register(供片窗开)→ dispatch(意识拿到同一 callId,执行
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 826d5c685d..685030ba6a 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -9,7 +9,7 @@ import {
import type { OrcaMcpDeps } from '@cindy/mcps';
import { createCindyGhostsMcpServer } from 'cindy-tools';
import type { MakerMemoryManager } from '@cindy/maker-core';
-import { getCindyGhostsMcpDeps } from './ghost.js';
+import { getCindyGhostsMcpDeps, type GhostGrantLiveSessionState } from './ghost.js';
import { getAndroidMcpDeps } from './android.js';
import { getBrowserMcpDeps } from './browser.js';
import { getComputerMcpDeps } from './computer.js';
@@ -54,6 +54,11 @@ export interface DesktopMcpProvidersDeps {
pluginRegistry: PluginRegistry;
/** Device-link transport stays host-injected so provider tests do not load Electron runtime services. */
invokeRemote: ChatHistoryReaderDeps['invokeRemote'];
+ /** 插件文件交接只认活跃 Session 的实时权限;缺失时由 ghost.ts fail closed。 */
+ getLiveSessionGrantState?: (
+ sessionId: string,
+ sessionInstanceId: string,
+ ) => GhostGrantLiveSessionState | null;
}
export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcpProvider[] {
@@ -427,7 +432,11 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
toClaudeSdkConfig: (ctx) => ({
type: 'sdk',
name: 'cindy',
- instance: createCindyGhostsMcpServer(getCindyGhostsMcpDeps(ctx)),
+ instance: createCindyGhostsMcpServer(
+ getCindyGhostsMcpDeps(ctx, {
+ getLiveSessionGrantState: deps.getLiveSessionGrantState,
+ }),
+ ),
}),
});
diff --git a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts b/apps/desktop/src/main/mcp-integrations/piEnvironment.ts
index b10e4a2e5e..973e3063b2 100644
--- a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts
+++ b/apps/desktop/src/main/mcp-integrations/piEnvironment.ts
@@ -9,7 +9,7 @@
* session 身份(orca / 会话身份类工具能绑定当前 pi 会话):
* - bridge 是懒启动单例(所有 pi 会话共享 HTTP server + server 工厂)。
* - 带 sessionId 的会话:在 bridge 上 registerSessionCtx + 给该会话的 server URL
- * 打 `?session=<id>` 路由 —— 与远端 Claude Code 的身份通道同机制。工具 handler
+ * 打 `?session=<id>&instance=<opaque>` 路由 —— 与远端 Claude Code 的身份通道同机制。工具 handler
* 经 getLiziMcpSessionContext() 拿到 {agentKind:'pi', sessionId, ...},
* start_team/create_worker 据此绑定 Lead(否则回落 LEAD_NOT_SUPPORTED)。
* - 匿名会话(无 sessionId):不注册、URL 不带 query,走无 ctx 兜底(行为同改动前)。
@@ -36,7 +36,11 @@ import { getLiziMcpSessionContext, type LiziMcpSessionContext } from '@cindy/mcp
import type { Logger as MakerLogger } from '@cindy/maker-core';
-import { startCodexHttpBridge, type CodexHttpBridge } from './codexHttpBridge.js';
+import {
+ startCodexHttpBridge,
+ type CodexHttpBridge,
+ withMcpRouteIdentity,
+} from './codexHttpBridge.js';
import { CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY } from './codexBuiltinToolPolicy.js';
import { pluginIdForKnownProviderName } from '../maker-host/plugins/builtin-plugins.js';
// 直接取 plugins 模块的 registry 单例,不经 maker-host/index.ts —— 后者 import pi-host,
@@ -125,6 +129,9 @@ export async function getPiExtraSpawnConfig(
const liziCtx: LiziMcpSessionContext = {
agentKind: 'pi',
sessionId,
+ ...(sessionCtx?.sessionInstanceId
+ ? { sessionInstanceId: sessionCtx.sessionInstanceId }
+ : {}),
workingDir: sessionCtx?.workingDir ?? '',
vendorOptions: {
...sessionCtx?.vendorOptions,
@@ -143,7 +150,10 @@ export async function getPiExtraSpawnConfig(
try {
const servers = serverNames.map((name) => ({
name,
- url: `${bridge.url(name)}?session=${encodeURIComponent(sessionId)}`,
+ url: withMcpRouteIdentity(bridge.url(name), {
+ sessionId,
+ sessionInstanceId: sessionCtx?.sessionInstanceId,
+ }),
}));
return {
mcpBridge: { token: bridge.token, servers },
@@ -199,8 +209,7 @@ async function ensureBridge(providers: McpProvider[], logger: MakerLogger): Prom
for (;;) {
if (!startPromise) {
const epoch = environmentEpoch;
- let pending!: Promise<StartedPiBridge | null>;
- pending = doStart(providers, logger.child('pi-environment'))
+ const pending = doStart(providers, logger.child('pi-environment'))
.then((raw) => {
if (!raw) return null;
const started: StartedPiBridge = {
@@ -257,6 +266,9 @@ async function doStart(
workingDir: active.workingDir,
vendorOptions: active.vendorOptions,
sessionId: active.sessionId,
+ ...(active.sessionInstanceId
+ ? { sessionInstanceId: active.sessionInstanceId }
+ : {}),
getSessionContext: ctx.getSessionContext,
};
},
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index c166829543..ff8613f161 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -31,6 +31,13 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
真正的强隔离需要 OS 级手段(macOS `sandbox-exec`、Linux 只读 bind mount / seccomp),
**本阶段未接入**。选择 Full access 即接受上述风险;需要硬边界时用 ask/auto 档,或等 OS
沙箱落地。改动权限相关代码时不要再堆「看起来能拦」的正则并当成安全边界。
+ 与 Claude Code/Codex 一致,Pi 会话的 Full Access 也会让插件 `ghost_call` 的
+ `attachments`/`dir`/`save_dir` 在 Host 侧免去额外过户确认;实现必须现读活跃 Session
+ 的稳定状态并同时匹配其 runtime instance identity;权限切换或关闭在途、远程/缺会话/
+ 实例不匹配/查询失败均 fail closed,且不得扩到 workspace、Setup、安装/更新、OAuth、
+ Secret/凭证等其它授权面。instance 仅作为 opaque query 写入 Host 生成的 Pi MCP URL;桥接
+ 注册表不匹配时返回 401。旧 URL 缺 instance 时可兼容普通会话工具,但必须向工具隐藏
+ instance,使 Full Access 自动交接保持 fail closed。
- **MCP 桥**:`piEnvironment.ts` 把 in-process MCP providers 暴露成 localhost streamable-HTTP,
bridge 用极简 client `tools/list` + `registerTool` 成 `mcp__<server>__<tool>`。
- **plan 模式**:挂 pi 自带 plan-mode 扩展,`/plan` toggle 驱动;Cindy 维护镜像态并在 resume
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 049af2996b..5b36c36b66 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -104,6 +104,25 @@
- 附件、媒体、目录和保存路径通过归属校验后的 grant/deposit/ledger 交接,**禁止把
宿主绝对路径或不必要的字节暴露给沙箱**。媒体字节须走
[`media-storage-and-protocols.md`](media-storage-and-protocols.md) 的统一入库。
+ `ghost_call` 的 `attachments`/`dir`/`save_dir` 在目标位于 workdir 外时,普通权限档
+ 仍沿用现有确认与授权记忆策略;仅当 Host 能现读到**本地活跃会话**的运行时权限恰为
+ `bypassPermissions`(Full Access)时自动批准。该判定不得读取启动期 MCP context 快照,
+ 也不得回退可能滞后的 DB `permission_mode`。business `sessionId` 不足以证明仍是同一内存
+ Session,必须同时匹配由 Maker 铸造、调用方不可覆盖的 instance identity;权限切换在途、
+ close/detach 已开始、会话缺失、实例不匹配、查询失败、远程会话均 fail closed。
+ 对 Codex、Pi 与远端 Claude Code 这类进程外 harness,instance 只作为 opaque MCP route
+ identity 写入 Host 生成的 loopback URL;桥接层必须将 URL identity 与注册表中的当前实例
+ 严格比对,不匹配直接 401。兼容旧客户端时,缺 instance 的 URL 可继续获得普通会话上下文,
+ 但必须剥除 instance 能力,使 Full Access 自动交接继续 fail closed。
+ 自动批准须在日志标明来源为 Full Access,不得伪装为用户点击,也不得写入人工目录授权
+ 记忆。附件自动交接必须写独立 `ghost-tool-grant`,不得写 `ghost-grant`;这是回退兼容
+ 边界——旧客户端只认识后者,降级时必须 fail closed,不能把新版自动交接误读成人工永久
+ 授权。热切回其它档位后新请求必须恢复确认。此旁路**不适用于** workspace 创建、插件
+ Setup/安装/更新、OAuth、Secret/凭证或其它确认边界。
+ `dir`/`save_dir` 批准的是裁决时解析到的 canonical realpath 快照;出票必须使用该规范路径
+ 并在票据库内重新解析核对,路径映射已变化时拒绝并要求重新确认。出票后真正读/写时仍须
+ 再次核对根与目标真身;保存文件必须排他创建且不跟随最终 symlink,不能让短命票据留下消费期
+ TOCTOU。附件继续使用裁决前已读入的字节,不得在批准后重新跟随原始路径。
- 面板供片与注入的主题 token 只用 `ghostPanelTheme.ts` 白名单内的值,不扩大暴露面。
## 5. 存量插件兼容:升级必须无感(红线)
diff --git a/docs/plugin-setup-runtime.md b/docs/plugin-setup-runtime.md
index bb5b21dd22..7a50184ae2 100644
--- a/docs/plugin-setup-runtime.md
+++ b/docs/plugin-setup-runtime.md
@@ -362,7 +362,12 @@ Main → Renderer:
禁止在 setup ready 前产生授权记忆、目录票据、沙箱副作用或插件调用。已经进入 dispatch 的调用不因后续配置变化自动重试。
-`grant_only` 只建立附件用户授权,不执行插件工具,并保持忽略 `tool` 的调用语义;但它同样必须先通过 Host-authoritative setup gate,禁止未配置插件提前获得持久授权。旧插件页 `GhostSetupStatus` 投影可保留兼容行为;真正的运行时 gate 遇到缺失声明或无法解析的 requirement 时不得 fail-open。
+`grant_only` 只建立附件交接,不执行插件工具,并保持忽略 `tool` 的调用语义。非
+Full Access 下,用户确认会建立人工 `ghost-grant`;本地 Full Access 下则只建立
+`ghost-tool-grant` 取件引用,不弹卡,也不形成降档后仍生效的人工永久授权。两种路径都必须
+先通过 Host-authoritative setup gate,禁止未配置插件提前获得任何媒体引用。旧插件页
+`GhostSetupStatus` 投影可保留兼容行为;真正的运行时 gate 遇到缺失声明或无法解析的
+requirement 时不得 fail-open。
### 5.2 Coordinator
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index 2fb6b07bad..66e4845c17 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -1130,6 +1130,11 @@ describe("formatGhostRoster(花名册快照:语义召回数据源)", () => {
expect(callDesc).not.toContain("id: art");
// ghost_call 仍保留自身基线描述(去重不等于把描述删空)。
expect(callDesc).toContain("调用某个插件(Ghost)提供的工具。");
+ // 权限契约必须进入模型可见描述:本地 Full Access 自动交接,远程/降档
+ // 仍 fail closed,且自动交接不伪装成人工永久授权。
+ expect(callDesc).toContain("Full Access(bypassPermissions)");
+ expect(callDesc).toContain("远程会话仍向用户弹确认卡");
+ expect(callDesc).toContain("不写人工永久授权");
});
});
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index 96de3b3465..1c083f9608 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -52,12 +52,14 @@ const D_GHOST_CALL = [
"顶层 dir(不是塞进 args):主机会收集文件并以",
"一次性票据注入 args.dir_deposit,插件凭票上传——这是插件触碰用户目录的唯一通道。",
"过户钳制(attachments / dir / save_dir 通用):路径在当前会话工作目录内直接放行;",
- "工作目录外会向用户弹确认卡,用户点允许才继续——被拒绝/超时会返回对应错误,",
- "此时不要重试,转告用户即可。已允许过的不重复弹卡:同一文件(按内容指纹)对",
- "同一插件永久生效,同一目录在本会话内生效。",
- "批量预授权:计划连续多次调用同一插件、每次用一个工作目录外文件时(如逐张图生成视频),",
- "**必须**先发一次 grant_only:true + attachments 列出整批文件(≤32 张,tool 随便填会被忽略)",
- "——用户只需在一张卡上批一次;跳过预授权会让用户被迫一张张点允许。",
+ "工作目录外若是本地 Full Access(bypassPermissions)会话则自动过户、不弹卡;其它权限档及",
+ "远程会话仍向用户弹确认卡,被拒绝/超时后不要重试,转告用户即可。Full Access 自动交接",
+ "不写人工永久授权,热切回其它权限档后会恢复确认;用户已明确允许的同一文件(按内容指纹)",
+ "对同一插件永久生效,同一目录在本会话内生效。",
+ "批量预授权:非 Full Access 下计划连续多次调用同一插件、每次用一个工作目录外文件时",
+ "(如逐张图生成视频),**必须**先发一次 grant_only:true + attachments 列出整批文件",
+ "(≤32 张,tool 随便填会被忽略)——用户只需在一张卡上批一次。Full Access 下普通调用本就",
+ "自动过户;grant_only 只做提前交接,不会建立降档后仍生效的人工授权。",
"结构化错误:GHOST_NOT_FOUND(未安装或已卸载)/ GHOST_ASLEEP(未启用,可提示用户到主界面侧边栏「插件」中启用)/",
"GHOST_DISABLED_IN_WORKDIR(用户在当前工作目录停用了该插件——不要重试,改用其它方式完成)/",
"TOOL_NOT_FOUND(常见是把二级分派操作名当成了顶层 tool,按上文 call_tool 形态改写后重试)/ GHOST_CRASHED /",
@@ -758,26 +760,26 @@ export function createCindyGhostsMcpServer(
.boolean()
.optional()
.describe(
- "可选:true = 本次调用只做 attachments 批量预授权、不执行工具(tool/args/dir/save_dir 全部被忽略)。计划连续多次调用同一插件使用多个工作目录外文件时必须先走一次,attachments 上限放宽到 32 张;用户在一张确认卡上批完,后续调用不再弹卡。",
+ "可选:true = 本次调用只做 attachments 批量交接、不执行工具(tool/args/dir/save_dir 全部被忽略)。非 Full Access 下计划连续使用多个工作目录外文件时必须先走一次,attachments 上限放宽到 32 张,让用户在一张确认卡上批完。Full Access 下不弹卡,且该自动交接不会建立降档后仍生效的人工永久授权。",
),
attachments: z
.array(z.string())
.max(32)
.optional()
.describe(
- "可选,普通调用 ≤4 张(grant_only 预授权 ≤32 张):要交给插件的图片/媒体文件。地址原样透传即可,四种写法都认:xdt-image://<会话ID>/<文件名>、cindy-media://blobs/<指纹>.<后缀>、消息里给出的本机绝对路径(主机会归一化并验归属),或本机媒体文件(图/视频/音频)的绝对路径——工作目录内直接放行,工作目录外主机会弹确认卡由用户决定。不要自己拼地址。主机过户给该插件后以指纹注入 args.attachments。仅在用户明确要拿自己的文件给插件处理时使用;非媒体类型文件改用顶层 dir。",
+ "可选,普通调用 ≤4 张(grant_only 批量交接 ≤32 张):要交给插件的图片/媒体文件。地址原样透传即可,四种写法都认:xdt-image://<会话ID>/<文件名>、cindy-media://blobs/<指纹>.<后缀>、消息里给出的本机绝对路径(主机会归一化并验归属),或本机媒体文件(图/视频/音频)的绝对路径——工作目录内直接放行;工作目录外在本地 Full Access 下自动过户,其它权限档及远程会话弹确认卡。不要自己拼地址。主机过户给该插件后以指纹注入 args.attachments。仅在用户明确要拿自己的文件给插件处理时使用;非媒体类型文件改用顶层 dir。",
),
dir: z
.string()
.optional()
.describe(
- "可选:要交给插件上传的本地目录或单个文件的绝对路径(如站点部署的构建产物目录、要传的附件文件)。位于当前会话工作目录内直接放行,工作目录外主机会弹确认卡由用户决定;主机收集文件(自动排除 node_modules/.git/.env 等)并以一次性票据注入 args.dir_deposit,插件凭票上传,摸不到路径与字节。仅当目标工具的说明要求交付目录/文件时使用。",
+ "可选:要交给插件上传的本地目录或单个文件的绝对路径(如站点部署的构建产物目录、要传的附件文件)。位于当前会话工作目录内直接放行;工作目录外在本地 Full Access 下自动过户,其它权限档及远程会话弹确认卡。主机收集文件(自动排除 node_modules/.git/.env 等)并以一次性票据注入 args.dir_deposit,插件凭票上传,摸不到路径与字节。仅当目标工具的说明要求交付目录/文件时使用。",
),
save_dir: z
.string()
.optional()
.describe(
- "可选:让插件把下载的文件存进的本地目录绝对路径(如附件下载目标目录)。必须是已存在的目录;位于当前会话工作目录内直接放行,工作目录外主机会弹确认卡由用户决定。主机发限时票据注入 args.save_deposit = { token, dir_name },插件凭票让主机把下载字节直接写进该目录(文件名主机消毒、不覆盖已有文件),插件摸不到绝对路径与字节。仅当目标工具的说明要求提供落盘目录时使用。",
+ "可选:让插件把下载的文件存进的本地目录绝对路径(如附件下载目标目录)。必须是已存在的目录;位于当前会话工作目录内直接放行;工作目录外在本地 Full Access 下自动过户,其它权限档及远程会话弹确认卡。主机发限时票据注入 args.save_deposit = { token, dir_name },插件凭票让主机把下载字节直接写进该目录(文件名主机消毒、不覆盖已有文件),插件摸不到绝对路径与字节。仅当目标工具的说明要求提供落盘目录时使用。",
),
setup_plan: ghostSetupPlanInputSchema
.optional()
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index 8af395fe89..7c84ad5c0d 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -212,22 +212,25 @@ export interface CindyGhostsMcpDeps {
/**
* 用户图片过户(可选):会话里用户图片的地址(xdt-image:// /
* cindy-media://blobs/ / 本机绝对路径,主机归一化并验归属)。
- * host 把每张图落媒体总仓、给目标意识记 ghost-grant 引用(显式引渡 =
- * 授权,按张、永久),再以指纹数组注入 args.attachments 交给意识——
+ * host 把每张图落媒体总仓、给目标意识记可读引用(人工确认的引渡才形成
+ * 按张永久授权;工作目录/Full Access 等 Host 代办交接不冒充用户授权),
+ * 再以指纹数组注入 args.attachments 交给意识——
* 意识拿到的仍只是字符串指纹,摸不到路径与字节。
*/
attachments?: string[];
/**
- * 批量预授权(可选):true 时本次调用**只做 attachments 过户、不派发
+ * 批量交接(可选):true 时本次调用**只做 attachments 过户、不派发
* 工具**(tool/args 被忽略)。用途:agent 计划连续多次调用同一意识、
- * 每次用一个 workdir 外文件时,先把整批文件一次性过户——用户只见一张
- * 列出全部文件的确认卡,批一次;之后逐次调用命中授权记忆不再弹卡。
+ * 每次用一个 workdir 外文件时,先把整批文件一次性过户——非 Full Access
+ * 下用户只见一张列出全部文件的确认卡;Full Access 下自动交接、不弹卡,
+ * 且不会形成降档后仍生效的人工永久授权。
* 普通调用 attachments 上限 4 张,grant_only 放宽(上限由 host 定)。
*/
grantOnly?: boolean;
/**
* 目录过户(可选):要整体交给意识上传的本地目录**绝对路径**(部署
- * 构建产物等场景)。host 验证(必须位于当前会话 workdir 内)、收集
+ * 构建产物等场景)。host 验证路径;workdir 内直接放行,workdir 外仅
+ * 本地 Full Access 自动过户,其它权限档及远程会话须用户确认。随后收集
* 文件并预检限额、发一次性限时票据,以 args.dir_deposit =
* { token, file_count, total_bytes, rel_paths } 注入交给意识——意识拿到
* 的只有票据与相对路径清单,摸不到绝对路径与文件字节;上传时经
@@ -236,8 +239,9 @@ export interface CindyGhostsMcpDeps {
dir?: string;
/**
* 下行落盘过户(可选):让意识把下载的文件存进的本地目录**绝对路径**
- * (附件下载等场景)。host 验证(必须是当前会话 workdir 内的已存在
- * 目录)、发限时票据,以 args.save_deposit = { token, dir_name } 注入
+ * (附件下载等场景)。host 验证为已存在目录;workdir 内直接放行,
+ * workdir 外仅本地 Full Access 自动过户,其它权限档及远程会话须用户
+ * 确认。随后发限时票据,以 args.save_deposit = { token, dir_name } 注入
* 交给意识——意识经 fetch-request 的 as:'file' + saveTo 报 token,主机
* 把响应字节直接写进该目录(文件名消毒去重,不覆盖);意识全程摸不到
* 绝对路径与文件字节。
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 8fae5c4f61..8f833f0820 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -745,6 +745,13 @@ export interface LiziMcpSessionContext {
* ctx 时,标准范式是工具直接返业务错误码 (如 LEAD_NOT_SUPPORTED) 而不是抛异常。
*/
sessionId?: string;
+ /**
+ * 当前内存 Session 实例的唯一代号。business sessionId 在重建后可能复用,
+ * 权限读取方用本字段阻断旧 MCP 请求借用新实例权限。宿主可将它作为
+ * opaque route identity 放进 harness 的本地 MCP URL;不得把它暴露成
+ * 模型或插件可控的工具参数。
+ */
+ sessionInstanceId?: string;
}
export interface CodexHttpMcpConfig {
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 1951ac01d5..0186ae5ffc 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -82,6 +82,8 @@ export interface AgentCapabilityAdditions {
export interface CodexMcpThreadContextArgs {
threadId: string;
sessionId: string;
+ /** 当前 Maker Session 实例代号;同 business session 重建后必须变化。 */
+ sessionInstanceId?: string;
workingDir: string;
/**
* SSH remote 会话的 host id。cindy_memory 的 store 定位键要靠它区分
@@ -182,6 +184,8 @@ export interface PiNativeProvidersResult {
*/
export interface PiExtraSpawnConfigContext {
sessionId?: string;
+ /** 当前 Maker Session 实例代号;用于阻断旧 bridge 请求借用新实例权限。 */
+ sessionInstanceId?: string;
workingDir: string;
vendorOptions?: Record<string, unknown>;
}
@@ -189,6 +193,13 @@ export interface PiExtraSpawnConfigContext {
export interface CodexExtraSpawnConfig {
extraArgs: string[];
extraEnv: Record<string, string>;
+ /**
+ * Build per-thread config overrides that bind host-owned HTTP MCP URLs to one
+ * in-memory Session instance. The app-server process is shared, so the spawn
+ * config only supplies the unbound base URL; thread/start|resume must add the
+ * opaque route identity for the concrete Session using this callback.
+ */
+ buildSessionMcpConfig?: (sessionInstanceId: string) => Record<string, unknown>;
codexProxyActive?: boolean;
/**
* spawn args 中定义的「OpenAI 身份」provider id(name 逐字为 "OpenAI",
@@ -416,7 +427,10 @@ export interface AgentDeps {
* behavior; implementations should be in-memory and best-effort.
*/
registerCodexMcpThreadContext?: (args: CodexMcpThreadContextArgs) => void;
- unregisterCodexMcpThreadContext?: (threadId: string) => void;
+ unregisterCodexMcpThreadContext?: (
+ threadId: string,
+ expectedSessionInstanceId?: string,
+ ) => void;
/**
* Codex 专用:为远端机器构造一个 codex app-server transport。
@@ -627,6 +641,8 @@ export interface AgentDeps {
remoteCcQueryFactory?: (opts: {
remoteHostId: string;
sessionId: string;
+ /** 当前 Maker Session 实例代号;只在宿主 MCP 身份上下文中流转。 */
+ sessionInstanceId?: string;
/**
* 给 cc-mgr daemon 起 SDK Query 时用的全部 options
* (cwd / model / env / mcpServers / systemPrompt / additionalDirectories /
@@ -791,6 +807,13 @@ export interface StartSessionOptions {
* (如 LEAD_NOT_SUPPORTED) 让 LLM 知道当前调用无法绑定到具体 session。
*/
sessionId?: string;
+ /**
+ * Maker 为本次内存 Session 实例铸造的唯一代号。业务 sessionId 可在重建后
+ * 复用;MCP 权限读取必须同时匹配本代号。Maker 会覆盖外部同名输入。宿主可
+ * 将它作为 opaque route identity 放进 harness 的本地 MCP URL,但不得把它
+ * 暴露成模型或插件可控的工具参数。
+ */
+ sessionInstanceId?: string;
workingDir: string;
/**
* Product workspace classification. `dialogue` sessions may still receive an
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
index 0d06f8f205..58ab91efe9 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
@@ -29,7 +29,10 @@ import type { CapabilityRoutingPolicy } from '../../../types/capability-routing.
import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';
import type { InteractionDecision, InteractionRequest } from '../../../types/events.js';
import type { Logger } from '../../../interfaces/logger.js';
-import type { McpProvider } from '../../../interfaces/mcp-provider.js';
+import type {
+ McpProvider,
+ McpProviderContext,
+} from '../../../interfaces/mcp-provider.js';
const sdkMock = vi.hoisted(() => ({
forkSession: vi.fn(),
@@ -757,6 +760,40 @@ describe('prompt-each-time never turns into a persisted grant', () => {
});
describe('a custom server cannot take over a builtin name', () => {
+ it('passes the runtime session instance id into Claude MCP provider context', async () => {
+ const configDir = await makeTempDir();
+ process.env.CLAUDE_CONFIG_DIR = configDir;
+ const workingDir = await makeTempDir();
+ sdkMock.query.mockReturnValue(createFakeQuery());
+ let capturedContext: McpProviderContext | undefined;
+ const deps = createDeps();
+ deps.mcpProviders = [
+ {
+ name: 'cindy_probe',
+ toClaudeSdkConfig: (context) => {
+ capturedContext = context;
+ return { type: 'stdio', command: 'true' };
+ },
+ },
+ ];
+
+ const handle = await new ClaudeCodeAgent(deps).startSession({
+ sessionId: 'session-instance-context',
+ sessionInstanceId: 'instance-claude-context',
+ model: 'claude-opus-4-6',
+ workingDir,
+ permissionMode: 'default',
+ });
+
+ expect(capturedContext).toMatchObject({
+ agentKind: 'claude-code',
+ sessionId: 'session-instance-context',
+ sessionInstanceId: 'instance-claude-context',
+ workingDir,
+ });
+ await handle.close();
+ });
+
it('keeps the first registration when two providers share a name', async () => {
const configs: Array<{ name: string; marker: string }> = [];
const contexts: McpToolApprovalContext[] = [];
@@ -866,12 +903,21 @@ describe('remote sessions share the same permission semantics', () => {
toClaudeSdkConfig: () => ({ type: 'http', url: `https://x/${name}` }),
})) as McpProvider[];
let remoteStartParams: Record<string, unknown> | undefined;
+ let remoteIdentity: { sessionId: string; sessionInstanceId?: string } | undefined;
deps.remoteCcQueryFactory = (async (args: {
+ sessionId: string;
+ sessionInstanceId?: string;
onApprovalRequest: (raw: unknown) => Promise<{ behavior?: string }>;
startParams: Record<string, unknown>;
}) => {
onApprovalRequest = args.onApprovalRequest;
remoteStartParams = args.startParams;
+ remoteIdentity = {
+ sessionId: args.sessionId,
+ ...(args.sessionInstanceId
+ ? { sessionInstanceId: args.sessionInstanceId }
+ : {}),
+ };
return createFakeQuery(
options?.initMcpServerNames,
options?.failedInitMcpServerNames,
@@ -881,6 +927,7 @@ describe('remote sessions share the same permission semantics', () => {
const agent = new ClaudeCodeAgent(deps);
const handle = await agent.startSession({
sessionId: 'session-remote-mcp-policy',
+ sessionInstanceId: 'instance-remote-mcp-policy',
model: 'claude-opus-4-6',
workingDir,
remoteHostId: 'remote-1',
@@ -894,9 +941,19 @@ describe('remote sessions share the same permission semantics', () => {
});
}
if (!onApprovalRequest) throw new Error('expected remote onApprovalRequest');
- return { handle, onApprovalRequest, seen, remoteStartParams };
+ return { handle, onApprovalRequest, seen, remoteStartParams, remoteIdentity };
}
+ it('passes the runtime session instance id into the remote Claude factory', async () => {
+ const { handle, remoteIdentity } = await startRemoteSession(() => 'auto-approve');
+
+ expect(remoteIdentity).toEqual({
+ sessionId: 'session-remote-mcp-policy',
+ sessionInstanceId: 'instance-remote-mcp-policy',
+ });
+ await handle.close();
+ });
+
it('auto-approves trusted MCP tools without prompting', async () => {
const { handle, onApprovalRequest, seen } = await startRemoteSession(() => 'auto-approve', {
attachResolver: () => ({ kind: 'permission', behavior: 'allow' }),
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 6575a10568..bf80f2cb81 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -1184,6 +1184,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// 到对应 session 的业务函数。host 直接调 startSession 而没透 sessionId
// 时此处为 undefined, 工具按"无 session 绑定"语义处理。
sessionId: opts.sessionId,
+ ...(opts.sessionInstanceId ? { sessionInstanceId: opts.sessionInstanceId } : {}),
getSessionContext: () => context,
};
// null-prototype: server 名来自用户可控的自定义 MCP id, 而 id 正则允许下划线,
@@ -2350,6 +2351,7 @@ export class ClaudeCodeAgent extends BaseAgent {
const remoteQuery = await this.deps.remoteCcQueryFactory({
remoteHostId: opts.remoteHostId,
sessionId: opts.sessionId,
+ ...(opts.sessionInstanceId ? { sessionInstanceId: opts.sessionInstanceId } : {}),
startParams,
// 协同身份以 session 自己的 vendorOptions 为准 (worker 首次创建时
// DB 标记尚未写入, host 现场查库会拿到空角色)。见 base-agent.ts
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 9036263852..31379bccfb 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -234,6 +234,8 @@ export interface AppServerHostOptions {
* oauth-bearer spawn 存在)。thread/start|resume 据此对订阅直连会话开远端压缩。
*/
remoteCompactionProviderId?: string;
+ /** Per-thread host-owned MCP URL overrides keyed by the Session instance. */
+ buildSessionMcpConfig?: (sessionInstanceId: string) => Record<string, unknown>;
}
interface BufferedNotification {
@@ -285,6 +287,16 @@ export class AppServerHost {
return this.opts.remoteCompactionProviderId ?? null;
}
+ /**
+ * Return the host-owned MCP URL overrides for one concrete Session instance.
+ * Anonymous/legacy callers keep the spawn-level unbound URLs, which preserves
+ * ordinary MCP compatibility while permission-sensitive tools fail closed.
+ */
+ getSessionMcpConfig(sessionInstanceId?: string): Record<string, unknown> {
+ if (!sessionInstanceId || !this.opts.buildSessionMcpConfig) return {};
+ return this.opts.buildSessionMcpConfig(sessionInstanceId);
+ }
+
getConnectionId(): string {
return this.connectionId;
}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 3fc563091d..c395ac3e7f 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -319,6 +319,7 @@ function installFakeHost(
remoteCompactionProviderId?: string;
userAgent?: string;
codexHome?: string;
+ buildSessionMcpConfig?: (sessionInstanceId?: string) => Record<string, unknown>;
} = {},
) {
const ensureStarted = vi.fn(async () => ({
@@ -366,6 +367,9 @@ function installFakeHost(
const unsubscribeThread = vi.fn(async () => {});
const isCodexProxyActive = vi.fn(() => opts.codexProxyActive === true);
const getRemoteCompactionProviderId = vi.fn(() => opts.remoteCompactionProviderId ?? null);
+ const getSessionMcpConfig = vi.fn((sessionInstanceId?: string) =>
+ opts.buildSessionMcpConfig?.(sessionInstanceId) ?? {},
+ );
const host = {
ensureStarted,
// startSession 的 initialize 直调走限时变体 (codex R13 P1): fake 里
@@ -376,6 +380,7 @@ function installFakeHost(
unsubscribeThread,
isCodexProxyActive,
getRemoteCompactionProviderId,
+ getSessionMcpConfig,
getConnectionId: () => 'test-connection',
getThreadHandlers: () => threadHandlers,
};
@@ -5167,6 +5172,7 @@ describe('CodexAgent MCP thread context hooks', () => {
const handle = await agent.startSession({
sessionId: 'session-codex-mcp-context',
+ sessionInstanceId: 'instance-codex-mcp-context',
model: 'gpt-5.4',
workingDir: '/repo',
vendorOptions: { orcaRole: 'lead' },
@@ -5176,13 +5182,60 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(registerCodexMcpThreadContext).toHaveBeenCalledWith({
threadId: 'start-thread-id',
sessionId: 'session-codex-mcp-context',
+ sessionInstanceId: 'instance-codex-mcp-context',
workingDir: '/repo',
vendorOptions: { orcaRole: 'lead' },
});
await handle.close();
expect(unregisterCodexMcpThreadContext).toHaveBeenCalledTimes(1);
- expect(unregisterCodexMcpThreadContext).toHaveBeenCalledWith('start-thread-id');
+ expect(unregisterCodexMcpThreadContext).toHaveBeenCalledWith(
+ 'start-thread-id',
+ 'instance-codex-mcp-context',
+ );
+ });
+
+ it('applies instance-bound MCP URLs to both thread/start and thread/resume', async () => {
+ const buildConfig = (sessionInstanceId?: string) => ({
+ 'mcp_servers.cindy_ghosts.url': `http://127.0.0.1:47100/mcp/cindy_ghosts?instance=${sessionInstanceId}`,
+ });
+
+ const startAgent = new CodexAgent(createDeps());
+ const startHost = installFakeHost(startAgent, undefined, {
+ buildSessionMcpConfig: buildConfig,
+ });
+ const startHandle = await startAgent.startSession({
+ sessionId: 'session-instance-start',
+ sessionInstanceId: 'instance-start',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const startParams = startHost.request.mock.calls.find(
+ ([method]) => method === Method.ThreadStart,
+ )?.[1] as { config?: Record<string, unknown> };
+ expect(startHost.getSessionMcpConfig).toHaveBeenCalledWith('instance-start');
+ expect(startParams.config).toMatchObject(buildConfig('instance-start'));
+
+ const resumeAgent = new CodexAgent(createDeps());
+ const resumeHost = installFakeHost(resumeAgent, undefined, {
+ buildSessionMcpConfig: buildConfig,
+ });
+ const resumeHandle = await resumeAgent.startSession({
+ sessionId: 'session-instance-resume',
+ sessionInstanceId: 'instance-resume',
+ resumeSessionId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const resumeParams = resumeHost.request.mock.calls.find(
+ ([method]) => method === Method.ThreadResume,
+ )?.[1] as { config?: Record<string, unknown> };
+ expect(resumeHost.getSessionMcpConfig).toHaveBeenCalledWith('instance-resume');
+ expect(resumeParams.config).toMatchObject(buildConfig('instance-resume'));
+ expect(resumeParams.config).not.toEqual(startParams.config);
+
+ await startHandle.close();
+ await resumeHandle.close();
});
it('unsubscribes the app-server thread when closing a local session without stopping the shared host', async () => {
@@ -5209,7 +5262,7 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(transport!.closed).toBe(false);
});
- it('finishes closing when the app-server stays connected without answering thread/unsubscribe', async () => {
+ it('retires the shared app-server when thread/unsubscribe stays unanswered', async () => {
vi.useFakeTimers();
try {
MockCodexTransport.dropThreadUnsubscribe = true;
@@ -5225,12 +5278,61 @@ describe('CodexAgent MCP thread context hooks', () => {
await vi.advanceTimersByTimeAsync(5_000);
await expect(closePromise).resolves.toBeUndefined();
- expect(createdTransports[0]?.closed).toBe(false);
+ // A timed-out thread/unsubscribe means the daemon may still keep the
+ // thread loaded. Retiring the shared host prevents a later Cindy task
+ // from resuming that loaded thread with a stale MCP identity/config.
+ expect(createdTransports[0]?.closed).toBe(true);
} finally {
vi.useRealTimers();
}
});
+ it('retires the captured host and rejects an unused-thread replacement when release fails', async () => {
+ const agent = new CodexAgent(createDeps());
+ let threadStartSeq = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.ThreadStart) {
+ return {
+ thread: { id: `replacement-thread-${++threadStartSeq}` },
+ model: 'gpt-5.4',
+ modelProvider: 'openai',
+ cwd: '/repo',
+ };
+ }
+ return undefined;
+ });
+ const retireHostKey = vi
+ .spyOn(
+ agent as unknown as { retireHostKey: (...args: unknown[]) => Promise<void> },
+ 'retireHostKey',
+ )
+ .mockResolvedValue(undefined);
+ const handle = await agent.startSession({
+ sessionId: 'session-unused-replacement-release-failure',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const initialSubscription = host.subscribeThread.mock.results[0]?.value;
+ const release = initialSubscription?.release;
+ if (!release) throw new Error('expected initial subscription');
+ release.mockRejectedValueOnce(new Error('thread/unsubscribe failed'));
+
+ await handle.setExtraDirs?.(['/shared-before-first-turn']);
+ await expect(
+ handle.send(
+ { type: 'user', content: 'use the reference on the first turn' },
+ { throwOnStartFailure: true },
+ ),
+ ).rejects.toThrow(/session expired|reference profile replacement cleanup/i);
+
+ expect(retireHostKey).toHaveBeenCalledWith(
+ 'local',
+ 'unused profile replacement release',
+ expect.objectContaining({ failIfActive: false }),
+ );
+ expect(host.subscribeThread).toHaveBeenCalledTimes(1);
+ });
+
describe('websocket body recovery auto-retry', () => {
const ENCRYPTED_ERROR =
'Encrypted content could not be decrypted or parsed. code=invalid_encrypted_content';
@@ -12080,6 +12182,9 @@ describe('CodexAgent.forkSdkSession', () => {
threadId: 'fork-thread-id',
numTurns: 2,
});
+ expect(host.unsubscribeThread).toHaveBeenNthCalledWith(1, 'fork-thread-id');
+ expect(host.unsubscribeThread).toHaveBeenNthCalledWith(2, 'rollback-thread-id');
+ expect(host.unsubscribeThread).not.toHaveBeenCalledWith('source-thread-id');
expect(result.newSdkSessionId).toBe('rollback-thread-id');
expect(result.uuidMap.size).toBe(0);
});
@@ -12100,10 +12205,60 @@ describe('CodexAgent.forkSdkSession', () => {
threadId: 'source-thread-id',
persistExtendedHistory: true,
});
+ expect(host.unsubscribeThread).toHaveBeenCalledTimes(1);
+ expect(host.unsubscribeThread).toHaveBeenCalledWith('fork-thread-id');
+ expect(host.unsubscribeThread).not.toHaveBeenCalledWith('source-thread-id');
expect(result.newSdkSessionId).toBe('fork-thread-id');
expect(result.uuidMap.size).toBe(0);
});
+ it('unloads the forked child when rollback fails', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.ThreadRollback) throw new Error('rollback failed');
+ return undefined;
+ });
+
+ await expect(agent.forkSdkSession({
+ sourceSdkSessionId: 'source-thread-id',
+ upToMessageId: undefined,
+ tailTurnsToDrop: 1,
+ })).rejects.toThrow('rollback failed');
+
+ expect(host.unsubscribeThread).toHaveBeenCalledTimes(1);
+ expect(host.unsubscribeThread).toHaveBeenCalledWith('fork-thread-id');
+ expect(host.unsubscribeThread).not.toHaveBeenCalledWith('source-thread-id');
+ });
+
+ it('retires the captured host and rejects when a forked child cannot be unloaded', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ host.unsubscribeThread.mockRejectedValueOnce(new Error('unsubscribe failed'));
+ const retireHostKey = vi
+ .spyOn(
+ agent as unknown as { retireHostKey: (...args: unknown[]) => Promise<void> },
+ 'retireHostKey',
+ )
+ .mockResolvedValue(undefined);
+
+ await expect(agent.forkSdkSession({
+ sourceSdkSessionId: 'source-thread-id',
+ upToMessageId: undefined,
+ tailTurnsToDrop: 0,
+ })).rejects.toThrow('unsubscribe failed');
+
+ expect(retireHostKey).toHaveBeenCalledWith(
+ 'local',
+ 'Codex fork child fork-thread-id could not be unloaded safely',
+ expect.objectContaining({
+ failIfActive: false,
+ logPrefix: 'codex fork child cleanup',
+ expectedGeneration: 0,
+ }),
+ );
+ expect(host.unsubscribeThread).not.toHaveBeenCalledWith('source-thread-id');
+ });
+
it('forks from a temporary rollout copy without unsafe payload lines', async () => {
const agent = new CodexAgent(createDeps());
let copied = '';
@@ -12259,6 +12414,45 @@ describe('CodexAgent rewind', () => {
await handle.close();
});
+ it('retires the captured host and terminates the handle when rollback subscription release fails', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const retireHostKey = vi
+ .spyOn(
+ agent as unknown as { retireHostKey: (...args: unknown[]) => Promise<void> },
+ 'retireHostKey',
+ )
+ .mockResolvedValue(undefined);
+ const handle = await agent.startSession({
+ sessionId: 'session-rewind-release-failure',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const commitRewindFiles = handle.commitRewindFiles;
+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');
+ const initialSubscription = host.subscribeThread.mock.results[0]?.value;
+ const release = initialSubscription?.release;
+ if (!release) throw new Error('expected initial subscription');
+ release.mockRejectedValueOnce(new Error('thread/unsubscribe failed'));
+
+ await expect(
+ commitRewindFiles('', '', { tailTurnsToDrop: 1 }),
+ ).rejects.toThrow(/session expired|thread\/rollback subscription cleanup/i);
+
+ expect(retireHostKey).toHaveBeenCalledWith(
+ 'local',
+ 'thread/rollback subscription release',
+ expect.objectContaining({ failIfActive: false }),
+ );
+ expect(host.subscribeThread).toHaveBeenCalledTimes(1);
+ await expect(
+ handle.send(
+ { type: 'user', content: 'must stay closed after cleanup failure' },
+ { throwOnStartFailure: true },
+ ),
+ ).rejects.toThrow(/closed/i);
+ });
+
it('discards the replacement thread when close races with rollback cleanup', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent);
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index d33c5a01df..06ada00b06 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -31,6 +31,7 @@ import {
TurnPermissionPolicyUnsupportedError,
type AgentSessionHandle,
type AgentDeps,
+ type CodexExtraSpawnConfig,
type StartSessionOptions,
type OneShotOptions,
type RefreshLocalModelsOptions,
@@ -1954,6 +1955,7 @@ export class CodexAgent extends BaseAgent {
let extraArgs: string[] = [];
let codexProxyActive = false;
let remoteCompactionProviderId: string | undefined;
+ let buildSessionMcpConfig: CodexExtraSpawnConfig['buildSessionMcpConfig'];
for (;;) {
const upgradedToSuperset = spawnCredentialMode !== credentialMode;
onSpawnCredentialModeResolved?.(spawnCredentialMode);
@@ -1974,6 +1976,7 @@ export class CodexAgent extends BaseAgent {
extraArgs = [];
codexProxyActive = false;
remoteCompactionProviderId = undefined;
+ buildSessionMcpConfig = undefined;
if (this.deps.prepareCodexExtraSpawnConfig) {
try {
const cfg = await this.deps.prepareCodexExtraSpawnConfig(
@@ -1987,6 +1990,7 @@ export class CodexAgent extends BaseAgent {
assertCurrentGeneration('spawn config');
Object.assign(env, cfg.extraEnv);
extraArgs = cfg.extraArgs;
+ buildSessionMcpConfig = cfg.buildSessionMcpConfig;
codexProxyActive = cfg.codexProxyActive === true && !remoteHostId;
// OpenAI 身份 provider 依赖 loopback proxy 路由订阅直连;proxy 不可用
// (退化直连网关)时不得下发,否则远端压缩请求会打到不支持它的上游。
@@ -2062,6 +2066,7 @@ export class CodexAgent extends BaseAgent {
clientInfo: { name: 'cindy', version: '0.0.0' },
codexProxyActive,
remoteCompactionProviderId,
+ buildSessionMcpConfig,
// app-server 对失败 RPC 返回 cloudRequirements + Auth/relogin 结构化错误时,当前 host
// 持有的 token 已不可用。stderr 与工具输出只做诊断,绝不驱动鉴权状态。保留 host 只会
// 持续撞鉴权失败; auth.invalidate 会触发 logout + 通知 UI 重登。延后到 microtask
@@ -3012,6 +3017,7 @@ export class CodexAgent extends BaseAgent {
register({
threadId,
sessionId: sid,
+ ...(opts.sessionInstanceId ? { sessionInstanceId: opts.sessionInstanceId } : {}),
workingDir: opts.workingDir,
// remote thread ctx: scope key 语义见 buildMemoryScopeKey。
...(opts.remoteHostId ? { remoteHostId: opts.remoteHostId } : {}),
@@ -3033,7 +3039,8 @@ export class CodexAgent extends BaseAgent {
try {
const unregister = this.deps.unregisterCodexMcpThreadContext;
if (!unregister) return;
- unregister(threadId);
+ if (opts.sessionInstanceId) unregister(threadId, opts.sessionInstanceId);
+ else unregister(threadId);
log.debug('codex MCP thread context unregistered', {
threadId: prefixId(threadId),
});
@@ -3053,6 +3060,86 @@ export class CodexAgent extends BaseAgent {
}
descendantMcpThreadIds.clear();
};
+ const terminateHandleAfterThreadCleanupFailure = (reason: string): void => {
+ if (closed) return;
+ closed = true;
+ resetUpstreamIdleForTurnEnd();
+ unregisterCodexMcpContext(threadId);
+ unregisterDescendantCodexMcpContexts();
+ abandonBufferedTurns(reason);
+ abandonPendingCapabilitySteers();
+ try { dismissAllPending(reason, 'deny'); } catch (e) { log.warn('dismissAllPending threw', { error: String(e) }); }
+ try { dismissAllPendingUserInput(reason); } catch (e) { log.warn('dismissAllPendingUserInput threw', { error: String(e) }); }
+ try { clearAllPendingUserInputInteractions(); } catch (e) { log.warn('clear pending user input threw', { error: String(e) }); }
+ try { stopActiveRolloutPlanFallback(); } catch (e) { log.warn('stop rollout plan fallback threw', { error: String(e) }); }
+ try { discardOverloadRetry(reason); } catch (e) { log.warn('cancel overload retry threw', { error: String(e) }); }
+ subscription = null;
+ try { eventQueue.end(); } catch (e) { log.warn('eventQueue.end threw', { error: String(e) }); }
+ };
+ const retireCapturedHostAfterThreadCleanupFailure = async (
+ reason: string,
+ ): Promise<void> => {
+ if (!isCurrentHost()) {
+ log.warn('thread cleanup failed after host replacement; skipping stale retire', {
+ threadId,
+ hostKey: currentHostKey,
+ reason,
+ });
+ return;
+ }
+ await this.retireHostKey(currentHostKey, reason, {
+ failIfActive: false,
+ logPrefix: 'codex thread cleanup',
+ ...(capturedHostWasRegistered ? { expectedHost: host } : {}),
+ expectedGeneration: hostGeneration,
+ });
+ };
+ const runThreadCleanupOrRetire = async (params: {
+ cleanupThreadId: string;
+ reason: string;
+ cleanup: () => Promise<void>;
+ }): Promise<boolean> => {
+ try {
+ await params.cleanup();
+ return true;
+ } catch (error) {
+ log.warn('Codex thread cleanup failed; retiring captured app-server', {
+ threadId: params.cleanupThreadId,
+ reason: params.reason,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ try {
+ await retireCapturedHostAfterThreadCleanupFailure(params.reason);
+ } catch (retireError) {
+ log.warn('Codex host retire after thread cleanup failure threw', {
+ threadId: params.cleanupThreadId,
+ reason: params.reason,
+ error: retireError instanceof Error ? retireError.message : String(retireError),
+ });
+ }
+ terminateHandleAfterThreadCleanupFailure(params.reason);
+ return false;
+ }
+ };
+ const releaseCurrentThreadSubscription = async (reason: string): Promise<boolean> => {
+ const currentSubscription = subscription;
+ if (!currentSubscription) return true;
+ const released = await runThreadCleanupOrRetire({
+ cleanupThreadId: threadId,
+ reason,
+ cleanup: () => currentSubscription.release(),
+ });
+ if (subscription === currentSubscription) subscription = null;
+ return released;
+ };
+ const unsubscribeDetachedThread = async (
+ detachedThreadId: string,
+ reason: string,
+ ): Promise<boolean> => runThreadCleanupOrRetire({
+ cleanupThreadId: detachedThreadId,
+ reason,
+ cleanup: () => host.unsubscribeThread(detachedThreadId),
+ });
function currentApprovalConfig(): CodexPermissionConfig {
return mapPermissionToCodex(
mutablePermissionMode,
@@ -3082,6 +3169,7 @@ export class CodexAgent extends BaseAgent {
const config = {
...capabilityRoutingConfig,
...(readonlyReferenceDirsSupported ? readonlyReferencesConfig : {}),
+ ...host.getSessionMcpConfig(opts.sessionInstanceId),
};
const shared = {
approvalPolicy,
@@ -3607,7 +3695,11 @@ export class CodexAgent extends BaseAgent {
onLateResolve: async (lateResp) => {
const lateThreadId = lateResp.thread.id;
if (lateThreadId === previousThreadId) return;
- await host.unsubscribeThread(lateThreadId);
+ const cleaned = await unsubscribeDetachedThread(
+ lateThreadId,
+ 'late unused profile replacement cleanup',
+ );
+ if (!cleaned) return;
log.debug('discarded late unused profile replacement', {
previousThreadId,
threadId: lateThreadId,
@@ -3617,14 +3709,10 @@ export class CodexAgent extends BaseAgent {
assertCurrentHost('read-only reference profile replacement');
const nextThreadId = resp.thread.id;
if (closed) {
- try {
- await host.unsubscribeThread(nextThreadId);
- } catch (e) {
- log.warn('unused profile replacement cleanup threw after close', {
- error: String(e),
- threadId: nextThreadId,
- });
- }
+ await unsubscribeDetachedThread(
+ nextThreadId,
+ 'unused profile replacement cleanup after close',
+ );
throw new Error('Codex session closed during read-only reference profile replacement');
}
if (
@@ -3634,24 +3722,18 @@ export class CodexAgent extends BaseAgent {
mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;
}
if (nextThreadId !== previousThreadId) {
- try {
- await subscription?.release();
- } catch (e) {
- log.warn('unused profile replacement release threw', {
- error: String(e),
- threadId: previousThreadId,
- });
+ const released = await releaseCurrentThreadSubscription(
+ 'unused profile replacement release',
+ );
+ if (!released) {
+ throw staleHostError('read-only reference profile replacement cleanup');
}
unregisterCodexMcpContext(previousThreadId);
if (closed) {
- try {
- await host.unsubscribeThread(nextThreadId);
- } catch (e) {
- log.warn('unused profile replacement cleanup threw after concurrent close', {
- error: String(e),
- threadId: nextThreadId,
- });
- }
+ await unsubscribeDetachedThread(
+ nextThreadId,
+ 'unused profile replacement cleanup after concurrent close',
+ );
throw new Error('Codex session closed during read-only reference profile replacement');
}
threadId = nextThreadId;
@@ -4306,6 +4388,8 @@ export class CodexAgent extends BaseAgent {
await this.retireHostKey(currentHostKey, reason, {
failIfActive: false,
logPrefix: 'codex upstream-idle watchdog',
+ ...(capturedHostWasRegistered ? { expectedHost: host } : {}),
+ expectedGeneration: hostGeneration,
});
};
/** turn 结束 / 中断时收表并清工具项(终态可能先于 item completed 到达)。 */
@@ -8158,7 +8242,7 @@ export class CodexAgent extends BaseAgent {
// thread 发 turn/start(assertCurrentHost 会抛,但那是在无人接收的
// setTimeout 回调里,白留一次失败与一条误导日志)。
try { discardOverloadRetry('session_closed'); } catch (e) { log.warn('cancel overload retry threw', { error: String(e) }); }
- try { await subscription?.release(); } catch (e) { log.warn('release threw', { error: String(e) }); }
+ await releaseCurrentThreadSubscription('session close subscription release');
try { eventQueue.end(); } catch (e) { log.warn('eventQueue.end threw', { error: String(e) }); }
},
@@ -8358,21 +8442,16 @@ export class CodexAgent extends BaseAgent {
const previousThreadId = threadId;
const nextThreadId = rollbackResp.thread.id || previousThreadId;
if (nextThreadId !== previousThreadId) {
- try {
- await subscription?.release();
- } catch {
- // no-op: stale subscription cleanup should not fail a successful rollback.
+ const released = await releaseCurrentThreadSubscription('thread/rollback subscription release');
+ if (!released) {
+ throw staleHostError('thread/rollback subscription cleanup');
}
unregisterCodexMcpContext(previousThreadId);
if (closed) {
- try {
- await host.unsubscribeThread(nextThreadId);
- } catch (e) {
- log.warn('thread/unsubscribe replacement after close threw', {
- error: String(e),
- threadId: nextThreadId,
- });
- }
+ await unsubscribeDetachedThread(
+ nextThreadId,
+ 'thread/rollback replacement cleanup after close',
+ );
log.info('commitRewindFiles discarded replacement after concurrent close', {
previousThreadId,
nextThreadId,
@@ -8505,6 +8584,46 @@ export class CodexAgent extends BaseAgent {
const log = this.deps.logger.child('codex/fork');
const tailTurnsToDrop = normalizeTailTurnsToDrop(opts.tailTurnsToDrop);
let stripCopyPath: string | undefined;
+ let utilityHostKey: string | undefined;
+ let utilityHost: AppServerHost | undefined;
+ let utilityHostGeneration: number | undefined;
+ let utilityHostWasRegistered = false;
+ const createdThreadIds = new Set<string>();
+ const cleanupCreatedThreads = async (): Promise<void> => {
+ if (!utilityHost || !utilityHostKey || createdThreadIds.size === 0) return;
+ for (const threadId of createdThreadIds) {
+ try {
+ // Codex 0.145 keeps a forked child loaded in the shared app-server.
+ // Unload it before the new Cindy Session resumes with its own MCP
+ // instance URL; otherwise thread/resume.config is ignored and the
+ // child remains bound to the utility host's spawn-level URL.
+ await utilityHost.unsubscribeThread(threadId);
+ } catch (error) {
+ const reason = `Codex fork child ${threadId} could not be unloaded safely`;
+ log.warn('fork child cleanup failed; retiring shared app-server', {
+ threadId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ try {
+ await this.retireHostKey(utilityHostKey, reason, {
+ failIfActive: false,
+ logPrefix: 'codex fork child cleanup',
+ ...(utilityHostWasRegistered ? { expectedHost: utilityHost } : {}),
+ ...(utilityHostGeneration !== undefined
+ ? { expectedGeneration: utilityHostGeneration }
+ : {}),
+ });
+ } catch (retireError) {
+ log.warn('fork child cleanup host retire threw', {
+ threadId,
+ error: retireError instanceof Error ? retireError.message : String(retireError),
+ });
+ }
+ throw error;
+ }
+ }
+ createdThreadIds.clear();
+ };
log.info('forkSdkSession ▶', {
sourceSdkSessionId: opts.sourceSdkSessionId,
upToMessageId: opts.upToMessageId,
@@ -8513,7 +8632,12 @@ export class CodexAgent extends BaseAgent {
note: 'Codex 精确 fork: thread/fork 后按需 thread/rollback 新 thread 尾部 turn',
});
try {
- const { host } = await this.getUtilityHost();
+ const utility = await this.getUtilityHost();
+ utilityHostKey = utility.key;
+ utilityHost = utility.host;
+ utilityHostGeneration = this.hostGenerations.get(utility.key) ?? 0;
+ utilityHostWasRegistered = this.hosts.get(utility.key) === utility.host;
+ const { host } = utility;
await host.ensureStarted();
// Imported Codex threads may still live under another CODEX_HOME. Resume
// already asks the desktop host to link/adopt their state and rollout;
@@ -8538,6 +8662,7 @@ export class CodexAgent extends BaseAgent {
};
const resp = await host.request<ThreadForkResponse>(Method.ThreadFork, params);
let newSdkSessionId = resp.thread.id;
+ createdThreadIds.add(newSdkSessionId);
if (tailTurnsToDrop > 0) {
const rollbackParams: ThreadRollbackParams = {
threadId: newSdkSessionId,
@@ -8547,18 +8672,24 @@ export class CodexAgent extends BaseAgent {
Method.ThreadRollback,
rollbackParams,
);
- newSdkSessionId = rollbackResp.thread.id || newSdkSessionId;
+ const rollbackThreadId = rollbackResp.thread.id || newSdkSessionId;
+ createdThreadIds.add(rollbackThreadId);
+ newSdkSessionId = rollbackThreadId;
}
log.info('forkSdkSession ◀', { newSdkSessionId, tailTurnsToDrop });
return { newSdkSessionId, uuidMap: new Map() };
} finally {
- if (stripCopyPath) {
- await fs.rm(path.dirname(stripCopyPath), { recursive: true, force: true }).catch((err) => {
- log.warn('strip encrypted rollout temp cleanup failed', {
- path: stripCopyPath,
- err: err instanceof Error ? err.message : String(err),
+ try {
+ await cleanupCreatedThreads();
+ } finally {
+ if (stripCopyPath) {
+ await fs.rm(path.dirname(stripCopyPath), { recursive: true, force: true }).catch((err) => {
+ log.warn('strip encrypted rollout temp cleanup failed', {
+ path: stripCopyPath,
+ err: err instanceof Error ? err.message : String(err),
+ });
});
- });
+ }
}
}
}
@@ -8665,11 +8796,36 @@ export class CodexAgent extends BaseAgent {
private async retireHostKey(
key: string,
reason: string,
- opts: { failIfActive: boolean; logPrefix: string },
+ opts: {
+ failIfActive: boolean;
+ logPrefix: string;
+ /** Optional identity fence for delayed cleanup from an older handle. */
+ expectedHost?: AppServerHost;
+ expectedGeneration?: number;
+ },
): Promise<void> {
+ let expectedGeneration = opts.expectedGeneration;
+ const matchesExpectedHost = (): boolean => {
+ if (opts.expectedHost && this.hosts.get(key) !== opts.expectedHost) return false;
+ if (
+ expectedGeneration !== undefined &&
+ (this.hostGenerations.get(key) ?? 0) !== expectedGeneration
+ ) {
+ return false;
+ }
+ return true;
+ };
+ if (!matchesExpectedHost()) {
+ this.deps.logger.warn(`${opts.logPrefix}: stale host cleanup skipped`, {
+ key,
+ reason,
+ });
+ return;
+ }
const inflight = this.hostPromises.get(key);
if (inflight) {
- this.bumpHostGeneration(key);
+ const bumpedGeneration = this.bumpHostGeneration(key);
+ if (expectedGeneration !== undefined) expectedGeneration = bumpedGeneration;
this.hostPromises.delete(key);
try {
await Promise.race([
@@ -8683,6 +8839,15 @@ export class CodexAgent extends BaseAgent {
message: (e as Error).message,
});
}
+ // The in-flight entry may have been replaced while we waited for it.
+ // Never let an old handle's delayed cleanup delete the newer host.
+ if (!matchesExpectedHost()) {
+ this.deps.logger.warn(`${opts.logPrefix}: stale host cleanup skipped after await`, {
+ key,
+ reason,
+ });
+ return;
+ }
}
const host = this.hosts.get(key);
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 25ae0d39bf..14072d0db3 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -69,6 +69,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
let cwd = '';
let disposed = 0;
let proxyDisposed = 0;
+ let preparedMcpContext: unknown;
beforeEach(() => {
knobs.ctorThrows = false;
@@ -78,6 +79,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
knobs.spawnedEnvs = [];
disposed = 0;
proxyDisposed = 0;
+ preparedMcpContext = undefined;
agentHome = mkdtempSync(path.join(tmpdir(), 'pi-cleanup-home-'));
cwd = mkdtempSync(path.join(tmpdir(), 'pi-cleanup-cwd-'));
});
@@ -107,14 +109,22 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
resolvePiAgentHome: () => agentHome,
registerPiProxySession: () => () => { proxyDisposed++; },
// 注册身份并回传 disposeSessionCtx 探针(servers 空,无需真桥)。
- preparePiExtraSpawnConfig: async () => ({
- mcpBridge: { token: 'itest', servers: [] },
- disposeSessionCtx: () => { disposed++; },
- }),
+ preparePiExtraSpawnConfig: async (_providers, context) => {
+ preparedMcpContext = context;
+ return {
+ mcpBridge: { token: 'itest', servers: [] },
+ disposeSessionCtx: () => { disposed++; },
+ };
+ },
};
}
- const opts = () => ({ sessionId: 's1', workingDir: cwd, model: 'm' });
+ const opts = () => ({
+ sessionId: 's1',
+ sessionInstanceId: 'pi-instance-1',
+ workingDir: cwd,
+ model: 'm',
+ });
it('disposes ctx (and does not close a nonexistent proc) when the process constructor throws synchronously', async () => {
knobs.ctorThrows = true;
@@ -137,6 +147,11 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
it('does not dispose ctx on the success path (dispose is deferred to close())', async () => {
const agent = new PiAgent(buildDeps());
const handle = await agent.startSession(opts());
+ expect(preparedMcpContext).toMatchObject({
+ sessionId: 's1',
+ sessionInstanceId: 'pi-instance-1',
+ workingDir: cwd,
+ });
expect(disposed).toBe(0);
expect(proxyDisposed).toBe(0);
await handle.close();
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index dc79a4d3f2..2dec58877c 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -694,6 +694,7 @@ export class PiAgent extends BaseAgent {
try {
const extra = await this.deps.preparePiExtraSpawnConfig(this.deps.mcpProviders ?? [], {
sessionId: opts.sessionId,
+ ...(opts.sessionInstanceId ? { sessionInstanceId: opts.sessionInstanceId } : {}),
workingDir: opts.workingDir,
vendorOptions: opts.vendorOptions,
});
diff --git a/packages/maker-core/src/interfaces/mcp-provider.ts b/packages/maker-core/src/interfaces/mcp-provider.ts
index f20a9c9478..95b513bc42 100644
--- a/packages/maker-core/src/interfaces/mcp-provider.ts
+++ b/packages/maker-core/src/interfaces/mcp-provider.ts
@@ -15,6 +15,13 @@ export interface McpProviderContext {
* 无法绑定到单个 session"。
*/
sessionId?: string;
+ /**
+ * Maker 为本次内存 Session 实例铸造的唯一代号。business sessionId 可在
+ * close/rebuild 后复用;权限相关 MCP 不得只凭 sessionId 借用新实例状态。
+ * 宿主可把它作为 opaque route identity 放进 harness 的本地 MCP URL,
+ * 但不得下发成模型或插件可控的工具参数。
+ */
+ sessionInstanceId?: string;
/**
* 返回当前 tool-call 绑定的真实 session ctx。
*
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 63ac63592d..441cfcef61 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -123,7 +123,48 @@ function createHandle(args: {
};
}
+function createDeferred<T = void>(): {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+} {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
describe('Maker session creation singleflight', () => {
+ it('binds each rebuilt business session to a fresh runtime instance id', async () => {
+ const seenInstanceIds: string[] = [];
+ const startSession = vi.fn(async (opts: CreateSessionOptions) => {
+ seenInstanceIds.push(opts.sessionInstanceId ?? '');
+ return createHandle({ id: `thread-${seenInstanceIds.length}` });
+ });
+ const maker = new Maker({
+ agents: { codex: createAgent(startSession) },
+ storage: createStorage(),
+ logger: createLogger(),
+ });
+ const options: CreateSessionOptions = {
+ id: 'session-rebuilt',
+ sessionInstanceId: 'caller-must-not-control-this',
+ agentKind: 'codex',
+ workingDir: '/repo',
+ model: 'gpt-5.4',
+ };
+
+ const first = await maker.createSession(options);
+ expect(first.instanceId).toBe(seenInstanceIds[0]);
+ expect(first.instanceId).not.toBe('caller-must-not-control-this');
+
+ await maker.closeSession(options.id!);
+ const second = await maker.createSession(options);
+
+ expect(second.instanceId).toBe(seenInstanceIds[1]);
+ expect(second.instanceId).not.toBe(first.instanceId);
+ });
+
it('shares one startup when the same business session is restored concurrently', async () => {
let resolveStart!: (handle: AgentSessionHandle) => void;
const startPending = new Promise<AgentSessionHandle>((resolve) => {
@@ -187,6 +228,198 @@ describe('Maker session creation singleflight', () => {
await expect(maker.createSession({ ...options })).resolves.toBeInstanceOf(Session);
expect(startSession).toHaveBeenCalledTimes(2);
});
+
+ it('rejects a second business task using the same live Codex thread until close completes', async () => {
+ const threadId = '11111111-1111-1111-1111-111111111111';
+ const closeGate = createDeferred();
+ const firstHandle = createHandle({ id: threadId });
+ firstHandle.close = vi.fn(() => closeGate.promise);
+ const secondHandle = createHandle({ id: threadId });
+ const startSession = vi.fn()
+ .mockResolvedValueOnce(firstHandle)
+ .mockResolvedValueOnce(secondHandle);
+ const maker = new Maker({
+ agents: { codex: createAgent(startSession) },
+ storage: createStorage(),
+ logger: createLogger(),
+ });
+ const options = (id: string): CreateSessionOptions => ({
+ id,
+ agentKind: 'codex',
+ workingDir: '/repo',
+ model: 'gpt-5.4',
+ resumeSessionId: threadId,
+ });
+
+ await maker.createSession(options('session-a'));
+ await expect(maker.createSession(options('session-b'))).rejects.toThrow(
+ /already active in another Cindy task/i,
+ );
+ expect(startSession).toHaveBeenCalledTimes(1);
+
+ const closing = maker.closeSession('session-a');
+ await vi.waitFor(() => expect(firstHandle.close).toHaveBeenCalledTimes(1));
+ await expect(maker.createSession(options('session-b'))).rejects.toThrow(
+ /already active in another Cindy task/i,
+ );
+ expect(startSession).toHaveBeenCalledTimes(1);
+
+ closeGate.resolve();
+ await closing;
+ const replacement = await maker.createSession(options('session-b'));
+ expect(replacement.sdkSessionId).toBe(threadId);
+ expect(startSession).toHaveBeenCalledTimes(2);
+ await replacement.close();
+ });
+
+ it('scopes Codex thread claims by remote target and permits different threads', async () => {
+ const sharedThread = '22222222-2222-2222-2222-222222222222';
+ const otherThread = '33333333-3333-3333-3333-333333333333';
+ const startSession = vi.fn(async (opts: CreateSessionOptions) =>
+ createHandle({ id: opts.resumeSessionId! }),
+ );
+ const maker = new Maker({
+ agents: { codex: createAgent(startSession) },
+ storage: createStorage(),
+ logger: createLogger(),
+ });
+ const base = {
+ agentKind: 'codex' as const,
+ workingDir: '/repo',
+ model: 'gpt-5.4',
+ };
+
+ const local = await maker.createSession({
+ ...base,
+ id: 'session-local',
+ resumeSessionId: sharedThread,
+ });
+ const remote = await maker.createSession({
+ ...base,
+ id: 'session-remote',
+ remoteHostId: 'remote-1',
+ resumeSessionId: sharedThread,
+ });
+ const other = await maker.createSession({
+ ...base,
+ id: 'session-other-thread',
+ resumeSessionId: otherThread,
+ });
+
+ expect(startSession).toHaveBeenCalledTimes(3);
+ await Promise.all([local.close(), remote.close(), other.close()]);
+ });
+
+ it('releases a provisional Codex thread claim when startup fails', async () => {
+ const threadId = '44444444-4444-4444-4444-444444444444';
+ const startSession = vi.fn()
+ .mockRejectedValueOnce(new Error('resume failed'))
+ .mockResolvedValueOnce(createHandle({ id: threadId }));
+ const maker = new Maker({
+ agents: { codex: createAgent(startSession) },
+ storage: createStorage(),
+ logger: createLogger(),
+ });
+ const options = (id: string): CreateSessionOptions => ({
+ id,
+ agentKind: 'codex',
+ workingDir: '/repo',
+ model: 'gpt-5.4',
+ resumeSessionId: threadId,
+ });
+
+ await expect(maker.createSession(options('session-failed'))).rejects.toThrow('resume failed');
+ const recovered = await maker.createSession(options('session-recovered'));
+
+ expect(startSession).toHaveBeenCalledTimes(2);
+ await recovered.close();
+ });
+
+ it('moves the Codex thread claim when the live handle reports a replacement id', async () => {
+ const firstThread = '55555555-5555-5555-5555-555555555555';
+ const nextThread = '66666666-6666-6666-6666-666666666666';
+ const firstEvents = createAsyncQueue<AgentEvent>();
+ const firstHandle = createHandle({ id: firstThread });
+ firstHandle.events = () => firstEvents;
+ const startSession = vi.fn(async (opts: CreateSessionOptions) =>
+ opts.id === 'session-a'
+ ? firstHandle
+ : createHandle({ id: opts.resumeSessionId! }),
+ );
+ const maker = new Maker({
+ agents: { codex: createAgent(startSession) },
+ storage: createStorage(),
+ logger: createLogger(),
+ });
+ const base = {
+ agentKind: 'codex' as const,
+ workingDir: '/repo',
+ model: 'gpt-5.4',
+ };
+ const first = await maker.createSession({
+ ...base,
+ id: 'session-a',
+ resumeSessionId: firstThread,
+ });
+ const moved = new Promise<void>((resolve) => {
+ const unsubscribe = first.onEvent((event) => {
+ if (event.type !== 'session_id' || event.data !== nextThread) return;
+ unsubscribe();
+ resolve();
+ });
+ });
+
+ firstEvents.push({ type: 'session_id', data: nextThread, source: 'codex' });
+ await moved;
+
+ const oldThreadReuse = await maker.createSession({
+ ...base,
+ id: 'session-old-thread-reuse',
+ resumeSessionId: firstThread,
+ });
+ await expect(maker.createSession({
+ ...base,
+ id: 'session-next-thread-conflict',
+ resumeSessionId: nextThread,
+ })).rejects.toThrow(/already active in another Cindy task/i);
+
+ await Promise.all([first.close(), oldThreadReuse.close()]);
+ });
+
+ it('closes the Codex handle and releases its claim when session storage fails', async () => {
+ const threadId = '77777777-7777-7777-7777-777777777777';
+ const storage = createStorage();
+ const create = storage.create.bind(storage);
+ storage.create = vi.fn()
+ .mockRejectedValueOnce(new Error('storage unavailable'))
+ .mockImplementation(create);
+ const failedHandle = createHandle({ id: threadId });
+ failedHandle.close = vi.fn(async () => {});
+ const startSession = vi.fn()
+ .mockResolvedValueOnce(failedHandle)
+ .mockResolvedValueOnce(createHandle({ id: threadId }));
+ const maker = new Maker({
+ agents: { codex: createAgent(startSession) },
+ storage,
+ logger: createLogger(),
+ });
+ const options = (id: string): CreateSessionOptions => ({
+ id,
+ agentKind: 'codex',
+ workingDir: '/repo',
+ model: 'gpt-5.4',
+ resumeSessionId: threadId,
+ });
+
+ await expect(maker.createSession(options('session-storage-failed'))).rejects.toThrow(
+ 'storage unavailable',
+ );
+ expect(failedHandle.close).toHaveBeenCalledTimes(1);
+
+ const recovered = await maker.createSession(options('session-storage-recovered'));
+ expect(startSession).toHaveBeenCalledTimes(2);
+ await recovered.close();
+ });
});
describe('Maker session close events', () => {
@@ -1426,12 +1659,14 @@ describe('Session permission mode leases', () => {
});
const permissionChange = session.setPermissionModeTracked('ask');
+ expect(session.stablePermissionModeState).toBeNull();
const nextTurn = session.send('after permission restore');
await vi.waitFor(() => expect(handle.setPermissionMode).toHaveBeenCalledOnce());
expect(handle.send).not.toHaveBeenCalled();
releasePermission();
await expect(permissionChange).resolves.toMatchObject({ mode: 'ask' });
+ expect(session.stablePermissionModeState).toEqual({ mode: 'ask', generation: 1 });
await expect(nextTurn).resolves.toEqual({ accepted: true });
expect(handle.send).toHaveBeenCalledOnce();
});
@@ -1472,6 +1707,7 @@ describe('Session permission mode leases', () => {
await Promise.resolve();
expect(applied).toEqual(['ask']);
+ expect(session.stablePermissionModeState).toBeNull();
await expect(
session.setPermissionModeIfUnchanged(temporary, 'bypassPermissions'),
).resolves.toBe(false);
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index d0ac804f31..e61a06f7ca 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -33,6 +33,7 @@ import type {
} from './types/customizations.js';
import { Session, generateSessionId } from './session.js';
import type {
+ AgentSessionHandle,
BaseAgent,
StartSessionOptions,
OneShotOptions,
@@ -147,6 +148,30 @@ function capabilitiesForSession(
};
}
+function isClaimableCodexThreadId(id: string | undefined): id is string {
+ return (
+ typeof id === 'string' &&
+ id.length > 0 &&
+ !id.startsWith('<') &&
+ /^[0-9a-fA-F-]+$/.test(id)
+ );
+}
+
+function codexThreadClaimKey(remoteHostId: string | undefined, threadId: string): string {
+ return JSON.stringify([remoteHostId ?? null, threadId]);
+}
+
+interface CodexThreadClaimOwner {
+ token: symbol;
+ sessionId: string;
+ sessionInstanceId: string;
+}
+
+interface CodexThreadClaimLease {
+ moveTo(threadId: string): void;
+ release(): void;
+}
+
export class Maker {
protected readonly agents: Partial<Record<AgentKind, BaseAgent>>;
protected readonly storage: SessionStorage;
@@ -163,6 +188,13 @@ export class Maker {
string,
{ promise: Promise<Session> }
>();
+ /**
+ * Codex 0.145 会忽略已加载 thread 的 thread/resume.config。不同 Cindy task
+ * 若同时复用同一 native thread,后启动者会继续使用前一 Session 的 MCP URL,
+ * 使实例绑定失配并破坏通知路由。按 target(local / remote host)+thread 独占;
+ * claim 由启动前持有到 Session 真正 close,禁止覆盖或抢占。
+ */
+ private readonly activeCodexThreadClaims = new Map<string, CodexThreadClaimOwner>();
/**
* 同一 business session 的 vendor id 写入必须串行。invalid-resume CAS 只有排在
* 已在途的 session_id update 之后执行,才能保证旧写入不会在清空后反向覆盖。
@@ -191,6 +223,59 @@ export class Maker {
});
}
+ private claimCodexThread(params: {
+ sessionId: string;
+ sessionInstanceId: string;
+ remoteHostId?: string;
+ threadId: string;
+ }): CodexThreadClaimLease {
+ const owner: CodexThreadClaimOwner = {
+ token: Symbol('codex-thread-claim'),
+ sessionId: params.sessionId,
+ sessionInstanceId: params.sessionInstanceId,
+ };
+ let currentKey: string | null = null;
+ let released = false;
+
+ const moveTo = (threadId: string): void => {
+ if (released) throw new Error('Codex thread claim was already released');
+ const nextKey = codexThreadClaimKey(params.remoteHostId, threadId);
+ if (nextKey === currentKey) return;
+ const existing = this.activeCodexThreadClaims.get(nextKey);
+ if (existing && existing.token !== owner.token) {
+ throw new Error(
+ `Codex thread ${threadId} is already active in another Cindy task. Close that task and try again.`,
+ );
+ }
+ this.activeCodexThreadClaims.set(nextKey, owner);
+ const previousKey = currentKey;
+ currentKey = nextKey;
+ if (
+ previousKey &&
+ previousKey !== nextKey &&
+ this.activeCodexThreadClaims.get(previousKey)?.token === owner.token
+ ) {
+ this.activeCodexThreadClaims.delete(previousKey);
+ }
+ };
+
+ moveTo(params.threadId);
+ return {
+ moveTo,
+ release: () => {
+ if (released) return;
+ released = true;
+ if (
+ currentKey &&
+ this.activeCodexThreadClaims.get(currentKey)?.token === owner.token
+ ) {
+ this.activeCodexThreadClaims.delete(currentKey);
+ }
+ currentKey = null;
+ },
+ };
+ }
+
/**
* 创建一个新会话。
*
@@ -283,21 +368,65 @@ export class Maker {
// provider ctx 时塞到 ctx.sessionId 上 (claude-code/index.ts buildMcpServers)。
// MCP server 工厂据此闭包绑定 "我属于哪个 session", 控制类工具 (如
// start_team / create_worker) 需要它把回调路由到对应 session 的业务函数。
- const handle = await agent.startSession({
- ...startOpts,
- sessionId: id,
- // 强制由 Maker 注入持久化 CAS,不能信任外部 CreateSessionOptions 自带回调。
- // Claude adapter 只在精确识别 invalid-resume 时调用;Codex 不消费该字段。
- // 对所有 claude-code 会话装配(不止 resume):全新会话也可能在首个 turn 崩溃前
- // 就把 SDK 回填、已落库的 sdk_session_id 变成幽灵 id(见 claude-code/index.ts
- // 的 fresh-session self-reference 恢复),需要同一把 CAS 才能把它清掉,否则下一次
- // send 会 resume 同一个不存在的会话反复失败。
- onInvalidResumeSession:
- opts.agentKind === 'claude-code'
- ? (expectedSdkSessionId) =>
- this.invalidateAndClearSdkSessionId(id, expectedSdkSessionId)
- : undefined,
- });
+ // business id 在 close/rebuild 后会复用;另铸一个只活在本次内存实例里的
+ // 代号,让迟到的旧 MCP 请求不能借用新 Session 的权限状态。
+ const sessionInstanceId = generateSessionId();
+ let codexThreadClaim =
+ opts.agentKind === 'codex' && isClaimableCodexThreadId(startOpts.resumeSessionId)
+ ? this.claimCodexThread({
+ sessionId: id,
+ sessionInstanceId,
+ remoteHostId: startOpts.remoteHostId,
+ threadId: startOpts.resumeSessionId,
+ })
+ : null;
+ let handle: AgentSessionHandle;
+ try {
+ handle = await agent.startSession({
+ ...startOpts,
+ sessionId: id,
+ sessionInstanceId,
+ // 强制由 Maker 注入持久化 CAS,不能信任外部 CreateSessionOptions 自带回调。
+ // Claude adapter 只在精确识别 invalid-resume 时调用;Codex 不消费该字段。
+ // 对所有 claude-code 会话装配(不止 resume):全新会话也可能在首个 turn 崩溃前
+ // 就把 SDK 回填、已落库的 sdk_session_id 变成幽灵 id(见 claude-code/index.ts
+ // 的 fresh-session self-reference 恢复),需要同一把 CAS 才能把它清掉,否则下一次
+ // send 会 resume 同一个不存在的会话反复失败。
+ onInvalidResumeSession:
+ opts.agentKind === 'claude-code'
+ ? (expectedSdkSessionId) =>
+ this.invalidateAndClearSdkSessionId(id, expectedSdkSessionId)
+ : undefined,
+ });
+ } catch (error) {
+ codexThreadClaim?.release();
+ throw error;
+ }
+ if (opts.agentKind === 'codex' && isClaimableCodexThreadId(handle.id)) {
+ try {
+ if (codexThreadClaim) {
+ codexThreadClaim.moveTo(handle.id);
+ } else {
+ codexThreadClaim = this.claimCodexThread({
+ sessionId: id,
+ sessionInstanceId,
+ remoteHostId: startOpts.remoteHostId,
+ threadId: handle.id,
+ });
+ }
+ } catch (error) {
+ try {
+ await handle.close();
+ } catch (closeError) {
+ this.logger.warn('failed to close Codex handle after thread claim conflict', {
+ sessionId: id,
+ error: String(closeError),
+ });
+ }
+ codexThreadClaim?.release();
+ throw error;
+ }
+ }
this.logger.debug('createSession ↑ agent.startSession returned', {
localSessionId: id,
sdkSessionId: handle.id,
@@ -306,28 +435,43 @@ export class Maker {
// 落地元数据 —— storage 已有同 id 的 row 时跳过 insert, 走 update 把 sdkSessionId 写回
let meta: SessionMeta;
- const existingRow = opts.id ? await this.storage.get(opts.id) : null;
- if (existingRow) {
- meta = handle.id !== '<pending>' && existingRow.sdkSessionId !== handle.id
- ? await this.storage.update(id, { sdkSessionId: handle.id })
- : existingRow;
- } else {
- meta = await this.storage.create({
- id,
- agentKind: opts.agentKind,
- workDir: opts.workingDir,
- title: opts.title ?? DEFAULT_DRAFT_SESSION_TITLE,
- model: opts.model,
- workspaceKind: opts.workspaceKind,
- effort: opts.effort,
- permissionMode: opts.permissionMode,
- fastMode: opts.fastMode,
- parentSessionId: opts.parentSessionId,
- // remoteHostId: 远端 session 把目标机器持久化, 之后 resume / list 都能识别。
- // 本地 session 留 undefined (sqlite 落空), 跟历史行为兼容。
- remoteHostId: opts.remoteHostId,
- sdkSessionId: handle.id !== '<pending>' ? handle.id : undefined,
- });
+ try {
+ const existingRow = opts.id ? await this.storage.get(opts.id) : null;
+ if (existingRow) {
+ meta = handle.id !== '<pending>' && existingRow.sdkSessionId !== handle.id
+ ? await this.storage.update(id, { sdkSessionId: handle.id })
+ : existingRow;
+ } else {
+ meta = await this.storage.create({
+ id,
+ agentKind: opts.agentKind,
+ workDir: opts.workingDir,
+ title: opts.title ?? DEFAULT_DRAFT_SESSION_TITLE,
+ model: opts.model,
+ workspaceKind: opts.workspaceKind,
+ effort: opts.effort,
+ permissionMode: opts.permissionMode,
+ fastMode: opts.fastMode,
+ parentSessionId: opts.parentSessionId,
+ // remoteHostId: 远端 session 把目标机器持久化, 之后 resume / list 都能识别。
+ // 本地 session 留 undefined (sqlite 落空), 跟历史行为兼容。
+ remoteHostId: opts.remoteHostId,
+ sdkSessionId: handle.id !== '<pending>' ? handle.id : undefined,
+ });
+ }
+ } catch (error) {
+ if (codexThreadClaim) {
+ try {
+ await handle.close();
+ } catch (closeError) {
+ this.logger.warn('failed to close Codex handle after session storage failure', {
+ sessionId: id,
+ error: String(closeError),
+ });
+ }
+ codexThreadClaim.release();
+ }
+ throw error;
}
const delivery = handle.codexProductPromptDelivery;
@@ -355,6 +499,7 @@ export class Maker {
const session = new Session({
id: meta.id,
+ sessionInstanceId,
agentKind: meta.agentKind,
workDir: meta.workDir,
handle,
@@ -369,6 +514,28 @@ export class Maker {
// 当 SDK 回填 sdkSessionId 时持久化
session.onEvent((evt) => {
if (evt.type === 'session_id' && typeof evt.data === 'string' && evt.data) {
+ if (opts.agentKind === 'codex' && isClaimableCodexThreadId(evt.data)) {
+ try {
+ if (codexThreadClaim) {
+ codexThreadClaim.moveTo(evt.data);
+ } else {
+ codexThreadClaim = this.claimCodexThread({
+ sessionId: id,
+ sessionInstanceId,
+ remoteHostId: startOpts.remoteHostId,
+ threadId: evt.data,
+ });
+ }
+ } catch (error) {
+ this.logger.error('Codex thread claim move failed; closing conflicting session', {
+ sessionId: id,
+ sdkSessionId: evt.data,
+ error: String(error),
+ });
+ void session.close();
+ return;
+ }
+ }
void this.persistSdkSessionId(meta.id, evt.data).catch((e) => {
this.logger.warn('failed to persist sdkSessionId', { error: String(e) });
});
@@ -377,6 +544,7 @@ export class Maker {
session.onStatusChange((status) => {
if (status === 'closed') {
+ codexThreadClaim?.release();
// 不再持久化运行态: 'closed' 是 SDK 子进程的瞬态, 重启即灭, 无意义存盘。
this.activeSessions.delete(meta.id);
this.emit({
diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.ts
index beb4444162..ce1c0c8daf 100644
--- a/packages/maker-core/src/session.close.test.ts
+++ b/packages/maker-core/src/session.close.test.ts
@@ -37,6 +37,12 @@ describe('Session close lifecycle', () => {
handle,
capabilities: {} as never,
logger: createLogger() as never,
+ permissionMode: 'bypassPermissions',
+ });
+
+ expect(session.stablePermissionModeState).toEqual({
+ mode: 'bypassPermissions',
+ generation: 0,
});
const firstClose = session.close();
@@ -45,6 +51,7 @@ describe('Session close lifecycle', () => {
expect(secondClose).toBe(firstClose);
expect(close).toHaveBeenCalledTimes(1);
expect(session.getStatus()).not.toBe('closed');
+ expect(session.stablePermissionModeState).toBeNull();
transportClose.resolve();
await Promise.all([firstClose, secondClose]);
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 188d98b486..a05957fcbd 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -122,6 +122,8 @@ function parseTurnStallMs(raw: string | undefined): number {
export interface SessionOptions {
id: string;
+ /** 与 Agent MCP context 同源的本次内存实例代号;省略时由 Session 自铸。 */
+ sessionInstanceId?: string;
agentKind: AgentKind;
workDir: string;
handle: AgentSessionHandle;
@@ -269,6 +271,8 @@ type SendReservation = {
export class Session {
readonly id: string;
+ /** business id 可复用;instanceId 精确标识本次内存 Session incarnation。 */
+ readonly instanceId: string;
readonly agentKind: AgentKind;
readonly workDir: string;
readonly capabilities: Capabilities;
@@ -294,6 +298,8 @@ export class Session {
* 同时请求关闭;所有调用方都必须等到 transport / 子进程真正释放后才能继续回收 worktree。
*/
private closePromise: Promise<void> | null = null;
+ /** close/detach 一进入同步入口就置位,早于底层 handle 的异步关闭完成。 */
+ private terminationStarted = false;
private eventLoopStarted = false;
private sendReservation: SendReservation | null = null;
/**
@@ -330,6 +336,7 @@ export class Session {
constructor(opts: SessionOptions) {
this.id = opts.id;
+ this.instanceId = opts.sessionInstanceId ?? generateSessionId();
this.agentKind = opts.agentKind;
this.workDir = opts.workDir;
this.handle = opts.handle;
@@ -580,6 +587,7 @@ export class Session {
if (this.closePromise) return this.closePromise;
if (this.status === 'closed') return Promise.resolve();
+ this.terminationStarted = true;
this.closePromise = this.performClose();
return this.closePromise;
}
@@ -593,6 +601,7 @@ export class Session {
if (this.status !== 'active' || this.closePromise || this.isTurnRunning()) {
return Promise.resolve(false);
}
+ this.terminationStarted = true;
this.closePromise = this.performClose();
return this.closePromise.then(() => true);
}
@@ -614,6 +623,7 @@ export class Session {
async detach(): Promise<void> {
if (this.status === 'closed') return;
+ this.terminationStarted = true;
try {
if (this.handle.detach) {
await this.handle.detach();
@@ -680,6 +690,22 @@ export class Session {
return { ...this.permissionModeStateValue };
}
+ /**
+ * 只在本 Session 仍活跃、未开始关闭、且没有权限切换在途时返回稳定快照。
+ * 权限边界读取方必须用本 getter,不能直接用 permissionModeState:底层切换
+ * 完成前旧 mode 仍会保留,而收紧操作一开始就应 fail closed。
+ */
+ get stablePermissionModeState(): PermissionModeState | null {
+ if (this.status !== 'active' || this.terminationStarted) return null;
+ if (
+ this.permissionModeChangesInFlight > 0 ||
+ this.externalPermissionModeChangesInFlight > 0
+ ) {
+ return null;
+ }
+ return this.permissionModeState;
+ }
+
/**
* Keep this Session logically occupied beyond the provider's own turn flag.
* The caller must release the returned lease on every terminal path.