Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-sharing): 受邀者会话的 Agent 自带工具改为白名单
Lizif24156e5275b
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 7ffc013199..079eb1b4cb 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -645,6 +645,7 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自(旧版分享者回 `CHANNEL_NOT_ALLOWED`,受邀者的模型列表读不到这个分享),订阅与其他 channel 一律拒绝,撤权后迟到的结果改写为 `ACCESS_REVOKED`。受邀者的任务把 `sessions.agent_device_id`记成 `share:<shareId>`(不改 schema),旧版本读到它按连不上的电脑处理。受邀者对端的 `open` 载荷按白名单复核(hooks / env / apiKeyHelper 剥离、越界 `@` 引用与 `!` 命令语法中和、不加载 B 的个人化与托管 Skill),只能恢复自己建立的会话;+ B 上受邀者会话的 Agent 自带工具按白名单开放(产品规则 §9 第 5 条,不改 wire);remote-agent wire 本身不变。新错误码 `REMOTE_AGENT_SHARE_PAUSED` / `REMOTE_AGENT_SHARE_REMOVED` / `REMOTE_AGENT_SHARE_UNAVAILABLE`只在受邀者本机产生(分享者电脑回 `ACCESS_REVOKED`、relay 回 `REMOTE_DISABLED` 时改写成 `UNAVAILABLE`);控制这台电脑的旧版手机没有对应文案,显示通用的发送失败提示。分享出去的 `maker:provider:list` 去掉分享者的账号身份diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex 748adcc0d7..594e9f6bd9 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -228,8 +228,14 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):5. **分享者电脑上不留可利用的本机能力**:Agent 在分享者电脑上运行时,不加载分享者的个人配置、hooks、插件、扩展和本机 MCP(Claude Code 现状已满足,Codex 与 Pi 须补到同等水平),也不执行受邀者随项目带来的 hooks、扩展等可执行配置。- **联网工具不单独处理**(2026-10-07 裁决):WebFetch、联网搜索等与同账号远程供应商的现行逻辑一致,- 由分享者电脑上的 Agent 从分享者的网络发出。+ **Agent 自带工具按白名单开放**(2026-10-10 裁决,取代 2026-10-07「联网工具不单独处理」):Agent+ 程序以分享者的系统用户在分享者电脑上运行,受邀者会话只开放不作用于分享者电脑、分享者电脑上的其他+ 会话和分享者账号的自带工具;文件与命令仍回到受邀者电脑执行。Agent 升级新增的工具不会自动开放,+ 须评估后加入白名单。因此给其他会话发消息、发布到分享者账号(如 Claude 的 Artifact、云端定时任务、+ 设计项目)、在分享者电脑上读文件或跑命令都不可用;WebFetch 会从分享者的网络发出请求、能访问分享者+ 的内网,对受邀者关闭;联网搜索由模型服务方执行,保持可用。同账号远程供应商不受影响。+ 实现:Claude Code 用 SDK `tools` 白名单,Codex 按功能清单关闭白名单之外的功能,Pi 只放行 Cindy+ 扩展注册的工具(`packages/maker-core/src/agents/{shared/device-hosted,codex/device-hosted-guest,pi/cindy-bridge-source}.ts`)。6. **受邀者隐私**:申请前明确告知对话与文件内容会经过并保存在分享者电脑上;分享被删除或受邀者退出后,分享者电脑清理该受邀者的 Agent 会话记录与镜像文件。7. **受邀者自己的权限**:受邀者电脑上的文件与命令操作仍由受邀者自己的任务权限档把关,分享不放宽@@ -257,7 +263,7 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):6. 关闭或删除后,受邀者正在运行的任务立即停止,下一条消息被拒并提示原因与换模型入口。7. 管理页按人、按模型显示用量,订阅类标注估算。8. 受邀者无法通过分享调用分享者电脑上的任何非远程 Agent 能力,随项目带来的 hooks、扩展不会在- 分享者电脑上执行。+ 分享者电脑上执行;Agent 自带工具里作用于分享者电脑、其他会话或分享者账号的都不可用(§9 第 5 条)。9. 中国大陆版与 Global 账号之间能完成同样的申请、审批、使用与撤销;合规开关关闭时跨区链接给出明确提示,同区域分享不受影响。10. Light 与 Dark 两种模式都已实现。diff --git a/docs/provider-sharing-implementation-plan.md b/docs/provider-sharing-implementation-plan.mdindex e770748dd3..cf5c4259e7 100644--- a/docs/provider-sharing-implementation-plan.md+++ b/docs/provider-sharing-implementation-plan.md@@ -137,7 +137,8 @@ P0 拆成两部分。受邀者身份由 `RemoteAgentHostDeps.controllerTrust`| C0-11 | 插件清单与通讯录说明 | Claude 托管会话目前仍把本机的插件清单(ghost roster)和通讯录说明拼进 system prompt。受邀者会话应去掉;这属于 system prompt 拼接改动,按 `maker-core-and-agent-behavior.md` §4 需先经维护者确认 || C0-12 | 真实验证 | 用真实 Claude Code 验证:受邀者项目里的 hooks、`env`、`apiKeyHelper`、`!` 命令、`@` 外部引用、家目录 CLAUDE.md 都不生效(Windows 上 `claudeMdExcludes` 的路径写法需实测) |-WebFetch、WebSearch 等联网工具不单独处理,与同账号远程供应商的现行逻辑一致(2026-10-07 裁决)。+受邀者会话的 Agent 自带工具按白名单开放,WebFetch 对受邀者关闭、WebSearch 保留(2026-10-10 裁决,取代+2026-10-07「联网工具不单独处理」,见产品规则 §9 第 5 条)。## 4. P1 同区域 MVP@@ -285,5 +286,6 @@ WebFetch、WebSearch 等联网工具不单独处理,与同账号远程供应1. 不限分享人数;链接 5 分钟过期、不限次数生成,不做未使用链接管理;申请提交后 24 小时内有效。2. 申请只能在电脑上完成,手机打开链接只提示到电脑上打开。-3. WebFetch、WebSearch 等联网工具与同账号远程供应商一致,不单独处理。+3. ~~WebFetch、WebSearch 等联网工具与同账号远程供应商一致,不单独处理。~~ 2026-10-10 改为:受邀者会话的+ Agent 自带工具按白名单开放,WebFetch 关闭、WebSearch 保留(产品规则 §9 第 5 条)。4. 身份只展示昵称和头像,用 auth-server 签发的身份名片(D7);不展示也不收集邮箱、手机号(含脱敏)、组织、区域;不新增、也不使用任何查看他人资料的能力。diff --git a/packages/maker-core/src/agents/claude-code/__tests__/device-hosted-guest.native.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/device-hosted-guest.native.test.tsnew file mode 100644index 0000000000..d8e4ccee3a--- /dev/null+++ b/packages/maker-core/src/agents/claude-code/__tests__/device-hosted-guest.native.test.ts@@ -0,0 +1,118 @@+/**+ * 真 Claude Code:受邀者(另一个账号)的托管会话只把白名单里的自带工具发给模型。+ * 用假的模型服务抓 Claude Code 实际发出的请求,核对 tools;不带白名单时同一请求里有名单外的+ * 工具(证明这个检查能发现问题)。Claude Code 升级后白名单不再生效时,这里会失败。+ *+ * 显式开启:CINDY_CLAUDE_TEST_BINARY=<claude 可执行文件> vitest run <本文件>。+ */+import { mkdtemp, rm } from 'node:fs/promises';+import { createServer, type Server } from 'node:http';+import { realpathSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { query } from '@anthropic-ai/claude-agent-sdk';+import { describe, expect, it } from 'vitest';++import { DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS, DEVICE_HOSTED_GUEST_CLAUDE_TOOLS } from '../../shared/device-hosted.js';++const binaryPath = process.env.CINDY_CLAUDE_TEST_BINARY;++function sse(events: Array<Record<string, unknown>>): string {+ return events.map((event) => `event: ${String(event.type)}\ndata: ${JSON.stringify(event)}\n\n`).join('');+}++/** 假的模型服务:记录每个带 tools 的请求里的工具名,一律回一句文本结束本轮。 */+async function startFakeModel(): Promise<{ server: Server; url: string; toolNames: string[][] }> {+ const toolNames: string[][] = [];+ const server = createServer((req, res) => {+ let body = '';+ req.on('data', (chunk) => { body += chunk; });+ req.on('end', () => {+ if (req.method !== 'POST' || !req.url?.startsWith('/v1/messages') || req.url.includes('count_tokens')) {+ res.writeHead(404, { 'content-type': 'application/json' }).end('{}');+ return;+ }+ let parsed: { stream?: boolean; tools?: Array<{ name?: string }> } = {};+ try {+ parsed = JSON.parse(body) as typeof parsed;+ } catch { /* 非 JSON 请求按无工具处理 */ }+ if (Array.isArray(parsed.tools)) toolNames.push(parsed.tools.map((tool) => String(tool.name)));+ const message = {+ id: 'msg_1', type: 'message', role: 'assistant', model: 'claude-sonnet-4-5-20250929',+ content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 1 },+ };+ if (parsed.stream === false) {+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({+ ...message, content: [{ type: 'text', text: 'DONE' }], stop_reason: 'end_turn',+ }));+ return;+ }+ res.writeHead(200, { 'content-type': 'text/event-stream' }).end(sse([+ { type: 'message_start', message },+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'DONE' } },+ { type: 'content_block_stop', index: 0 },+ { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } },+ { type: 'message_stop' },+ ]));+ });+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('fake model server has no port');+ return { server, url: `http://127.0.0.1:${address.port}`, toolNames };+}++/** 跑一轮,返回发给模型的工具名(合并所有带 tools 的请求)。 */+async function modelToolNames(tools: string[] | undefined): Promise<string[]> {+ const root = realpathSync.native(await mkdtemp(path.join(tmpdir(), 'cindy-claude-guest-native-')));+ const fake = await startFakeModel();+ try {+ const run = query({+ prompt: 'Reply with DONE.',+ options: {+ pathToClaudeCodeExecutable: binaryPath,+ cwd: root,+ model: 'claude-sonnet-4-5-20250929',+ env: {+ ...process.env,+ CLAUDE_CONFIG_DIR: path.join(root, 'config'),+ ANTHROPIC_API_KEY: 'sk-ant-cindy-native-test',+ ANTHROPIC_BASE_URL: fake.url,+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',+ DISABLE_TELEMETRY: '1',+ },+ settingSources: [],+ strictMcpConfig: true,+ disallowedTools: [...DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS],+ ...(tools ? { tools } : {}),+ maxTurns: 1,+ },+ });+ for await (const message of run) {+ if (message.type === 'result') break;+ }+ run.close();+ return [...new Set(fake.toolNames.flat())];+ } finally {+ await new Promise<void>((resolve) => fake.server.close(() => resolve()));+ await rm(root, { recursive: true, force: true });+ }+}++describe.skipIf(!binaryPath)('Claude Code device-hosted guest with a real binary', () => {+ it('sends only allowlisted built-in tools to the model', async () => {+ const names = await modelToolNames([...DEVICE_HOSTED_GUEST_CLAUDE_TOOLS]);+ expect(names.length).toBeGreaterThan(0);+ const allowed = new Set<string>(DEVICE_HOSTED_GUEST_CLAUDE_TOOLS);+ // 'Task' 是 Agent 的旧名,部分版本在请求里用它。+ allowed.add('Task');+ expect(names.filter((name) => !allowed.has(name) && !name.startsWith('mcp__'))).toEqual([]);+ }, 120_000);++ it('sends tools outside the allowlist when no allowlist is given', async () => {+ const names = await modelToolNames(undefined);+ expect(names).toContain('WebFetch');+ }, 120_000);+});diff --git a/packages/maker-core/src/agents/claude-code/__tests__/device-hosted-guest.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/device-hosted-guest.test.tsindex 57bc2332ae..725611d9d7 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/device-hosted-guest.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/device-hosted-guest.test.ts@@ -19,6 +19,7 @@ import {import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';import type { Logger } from '../../../interfaces/logger.js';import { CONTACTS_RULES_DISABLED } from '../../../contacts/system-prompt.js';+import { DEVICE_HOSTED_GUEST_CLAUDE_TOOLS } from '../../shared/device-hosted.js';const sdkMock = vi.hoisted(() => ({forkSession: vi.fn(),@@ -74,16 +75,47 @@ async function makeTempDir(): Promise<string> {const GHOST_ROSTER = 'HOST GHOST ROSTER';+type CapturedHook = (input: Record<string, unknown>, toolUseId: string | undefined, options: { signal: AbortSignal }) => Promise<{+ hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string };+}>;+interface CapturedOptions {plugins?: Array<{ type: string; path: string }>;systemPrompt?: { append?: string };settings?: {disableAllHooks?: boolean;+ disableClaudeAiConnectors?: boolean;+ disableRemoteControl?: boolean;+ disableSkillShellExecution?: boolean;claudeMdExcludes?: string[];availableModels?: string[];env?: Record<string, string>;};env?: Record<string, string>;+ tools?: unknown;+ disallowedTools?: string[];+ hooks?: { PreToolUse?: Array<{ hooks: CapturedHook[] }> };+}++/** 依次跑 PreToolUse 回调,返回第一个拒绝原因;都放行时返回 null。 */+async function preToolUseDenial(options: CapturedOptions, toolName: string, toolInput: unknown): Promise<string | null> {+ const input = {+ hook_event_name: 'PreToolUse',+ session_id: 'sdk-session',+ transcript_path: '',+ cwd: '',+ tool_name: toolName,+ tool_input: toolInput,+ };+ for (const matcher of options.hooks?.PreToolUse ?? []) {+ for (const hook of matcher.hooks) {+ const result = await hook(input, 'tool-use-1', { signal: new AbortController().signal });+ if (result?.hookSpecificOutput?.permissionDecision === 'deny') {+ return result.hookSpecificOutput.permissionDecisionReason ?? '';+ }+ }+ }+ return null;}const GUEST_PROVIDER: DeviceHostedGuestProvider = {@@ -213,6 +245,24 @@ describe('Claude Code device-hosted guest sessions', () => {expect(options.env?.ANTHROPIC_SMALL_FAST_MODEL).toBe('shared/model-a');});+ it('exposes only the allowlisted built-in tools and turns off account and shell features', async () => {+ const { options } = await startHostedSession(true);+ // 白名单是显式数组:不是 preset,也不是缺省(缺省 = Claude Code 全部自带工具)。+ expect(options.tools).toEqual([...DEVICE_HOSTED_GUEST_CLAUDE_TOOLS]);+ expect(options.tools).not.toContain('WebFetch');+ expect(options.disallowedTools).toContain('Bash');+ expect(options.settings?.disableClaudeAiConnectors).toBe(true);+ expect(options.settings?.disableRemoteControl).toBe(true);+ expect(options.settings?.disableSkillShellExecution).toBe(true);+ });++ it('denies subagent isolation for guests but not ordinary subagents', async () => {+ const { options } = await startHostedSession(true);+ expect(await preToolUseDenial(options, 'Agent', { description: 'd', prompt: 'p', isolation: 'remote' }))+ .toMatch(/isolation/);+ expect(await preToolUseDenial(options, 'Agent', { description: 'd', prompt: 'p' })).toBeNull();+ });+it('refuses a guest session without a provider boundary or on another provider', async () => {await expect(startHostedSession(true, { guestProvider: null })).rejects.toThrow(/REMOTE_AGENT_UNSUPPORTED/);await expect(startHostedSession(true, { providerId: 'other-provider' }))@@ -223,6 +273,11 @@ describe('Claude Code device-hosted guest sessions', () => {const { options } = await startHostedSession(false);expect(options.settings?.disableAllHooks).toBeUndefined();expect(options.settings?.claudeMdExcludes).toBeUndefined();+ expect(options.tools).toBeUndefined();+ expect(options.settings?.disableClaudeAiConnectors).toBeUndefined();+ expect(options.settings?.disableRemoteControl).toBeUndefined();+ expect(options.settings?.disableSkillShellExecution).toBeUndefined();+ expect(await preToolUseDenial(options, 'Agent', { description: 'd', prompt: 'p', isolation: 'worktree' })).toBeNull();expect(options.plugins?.length).toBe(1);expect(options.systemPrompt?.append).toContain(GHOST_ROSTER);expect(options.systemPrompt?.append).toContain(CONTACTS_RULES_DISABLED);diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex f3253cd4c8..a794a2bf2e 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -220,8 +220,10 @@ import {import {DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS,DEVICE_HOSTED_EXEC_MCP_SERVER,+ DEVICE_HOSTED_GUEST_CLAUDE_TOOLS,deviceHostedBuiltinToolName,deviceHostedClaudeNote,+ deviceHostedGuestAgentDenial,deviceHostedGuestClaudeMdExcludes,deviceHostedMcpUrl,deviceHostedSubagentAllows,@@ -2011,6 +2013,18 @@ export class ClaudeCodeAgent extends BaseAgent {if (hosted) {if (input.hook_event_name === 'PreToolUse') {const pre = input as PreToolUseHookInput & { agent_id?: string; agent_type?: string };+ // 受邀者:子代理不能用隔离选项(在本机建 worktree,或用本机用户的 claude.ai 账号开云端任务)。+ const guestDenial = hosted.guest ? deviceHostedGuestAgentDenial(pre.tool_name, pre.tool_input) : null;+ if (guestDenial) {+ return {+ continue: true,+ hookSpecificOutput: {+ hookEventName: 'PreToolUse' as const,+ permissionDecision: 'deny' as const,+ permissionDecisionReason: guestDenial,+ },+ };+ }const builtin = deviceHostedBuiltinToolName(pre.tool_name);// 参数化规则(Bash(git diff:*) 之类)要按本次命令判范围,不能当成整个工具放行。const toolInput = pre.tool_input as Record<string, unknown> | undefined;@@ -2855,6 +2869,11 @@ export class ClaudeCodeAgent extends BaseAgent {// 受邀者(另一个账号)的托管会话:不执行任何设置与插件里的 hooks / 状态栏命令,// 不加载会话目录之外(属于本机用户)的 CLAUDE.md 与规则。settings.disableAllHooks = true;+ // 本机用户 claude.ai 账号里的连接器、Remote Control,以及技能与命令里的内联 shell+ // (会在本机执行)一律关闭。+ settings.disableClaudeAiConnectors = true;+ settings.disableRemoteControl = true;+ settings.disableSkillShellExecution = true;const excludes = deviceHostedGuestClaudeMdExcludes(hosted);if (excludes.length > 0) settings.claudeMdExcludes = [...(settings.claudeMdExcludes ?? []), ...excludes];// 路由令牌请求头在最高优先级的设置层再写一次:会话中途出现的项目设置不能把它改掉。@@ -4381,6 +4400,8 @@ export class ClaudeCodeAgent extends BaseAgent {...(opts.botRuntimeProfile || hosted ? { strictMcpConfig: true } : {}),// 设备托管:自带文件与命令工具只能操作本机,关掉,由 cindy_exec 顶替。...(hosted ? { disallowedTools: [...DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS] } : {}),+ // 受邀者(另一个账号):自带工具只开白名单里的,其余都作用于本机或本机用户的账号。+ ...(hosted?.guest ? { tools: [...DEVICE_HOSTED_GUEST_CLAUDE_TOOLS] } : {}),// 设备托管:个人配置(用户级设置、hooks)属于任务所在电脑,不加载本机用户级设置;// 项目级设置来自同步过来的影子目录(只保留权限规则)。settingSources: reviewMode || !!opts.botRuntimeProfilediff --git a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.tsindex 76132a88f9..6e611024c6 100644--- a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts+++ b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts@@ -1,5 +1,6 @@/**- * 真 Codex app-server:受邀者(另一个账号)的托管会话使用受邀者目录作为 CODEX_HOME。+ * 真 Codex app-server:受邀者(另一个账号)的托管会话使用受邀者目录作为 CODEX_HOME,线程里只开+ * 白名单内的 Codex 功能(按线程向 app-server 查询核对)。* 本机用户 CODEX_HOME 里的全局 AGENTS.md 不进入请求,会话历史只写在受邀者目录里,本机用户的* 历史与凭证文件不被触碰;命令经 exec-server 环境在「任务所在电脑」执行(这里用一个独立的* `codex exec-server` 进程模拟)。同账号托管会话仍使用本机用户的 CODEX_HOME。@@ -18,6 +19,7 @@ import { describe, expect, it } from 'vitest';import type { Logger } from '../../../interfaces/logger.js';import type { DeviceHostedSession } from '../../base-agent.js';+import { CODEX_DEVICE_HOSTED_GUEST_KEPT_FEATURES, listCodexFeatures } from '../device-hosted-guest.js';import { CodexAgent } from '../index.js';const binaryPath = process.env.CINDY_CODEX_TEST_BINARY;@@ -165,6 +167,19 @@ describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server',})();await handle.send({ type: 'user', content: 'hello' }, { throwOnStartFailure: true });await done;+ // 按这个线程向 Codex 查功能状态:受邀者线程里白名单之外的功能都是关着的;同账号线程里有开着的。+ const hosts = (agent as unknown as { hosts: Map<string, { request: (method: string, params: unknown) => Promise<unknown> }> }).hosts;+ const threadHost = [...hosts].find(([key]) => key.startsWith('local-guest:') === guest)?.[1];+ if (!threadHost) throw new Error('expected the session app-server');+ const threadFeatures = await listCodexFeatures((cursor) => threadHost.request(+ 'experimentalFeature/list', { threadId: handle.id, limit: 200, ...(cursor ? { cursor } : {}) },+ ));+ const enabledOutsideAllowlist = threadFeatures+ .filter((feature) => feature.enabled && feature.stage !== 'removed' && !CODEX_DEVICE_HOSTED_GUEST_KEPT_FEATURES.has(feature.name))+ .map((feature) => feature.name);+ if (guest)+ expect(enabledOutsideAllowlist).toEqual([]);+ else expect(enabledOutsideAllowlist.length).toBeGreaterThan(0);await handle.close();expect(bodies.length).toBeGreaterThan(0);diff --git a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.tsindex d9db79ccee..064b140ba7 100644--- a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts+++ b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts@@ -51,8 +51,33 @@ interface Fixture {guestHome?: boolean;/** 受邀者启动时用的来源;默认就是分享的供应商(xd)。 */providerId?: string;+ /** app-server 不给功能清单(旧版本或出错)。 */+ noFeatureList?: boolean;}+/** app-server 的功能清单,分两页返回。 */+const FEATURE_PAGES: Record<string, { data: Array<{ name: string; stage: string; enabled: boolean }>; nextCursor: string | null }> = {+ first: {+ data: [+ { name: 'shell_tool', stage: 'stable', enabled: true },+ { name: 'view_image', stage: 'stable', enabled: true },+ { name: 'image_generation', stage: 'stable', enabled: true },+ { name: 'in_app_local_automation', stage: 'stable', enabled: true },+ { name: 'network_proxy', stage: 'beta', enabled: false },+ ],+ nextCursor: 'page-2',+ },+ 'page-2': {+ data: [+ { name: 'multi_agent', stage: 'stable', enabled: true },+ { name: 'item_ids', stage: 'removed', enabled: true },+ { name: 'web_search_request', stage: 'deprecated', enabled: false },+ { name: 'future_local_tool', stage: 'underDevelopment', enabled: true },+ ],+ nextCursor: null,+ },+};+const SHARED_PROVIDER = { providerId: 'xd', modelIds: ['gpt-5.5'], routeToken: 'route-token' };async function startHosted(fixture: Fixture) {@@ -144,6 +169,9 @@ async function startHosted(fixture: Fixture) {};case Method.EnvironmentAdd:return {};+ case Method.ExperimentalFeatureList:+ if (fixture.noFeatureList) throw new Error('unknown method');+ return FEATURE_PAGES[(params as { cursor?: string }).cursor ?? 'first'];case Method.ThreadStart:return {thread: { id: 'start-thread-id', ...(reportedHome !== codexHome ? { path: path.join(reportedHome, 'sessions', 'rollout.jsonl') } : {}) },@@ -268,6 +296,19 @@ describe('Codex device-hosted guest sessions', () => {// 联网搜索与同账号托管会话一致,不额外关闭。expect(config.web_search).toBeUndefined();expect(config['features.multi_agent']).toBeUndefined();+ // Codex 功能按白名单:名单外的(本机开着的、关着的、Codex 新增的)都写 false;名单内的、已移除的、+ // 关着的旧开关不动。功能清单逐页取完。+ expect(config).toMatchObject({+ 'features.image_generation': false,+ 'features.in_app_local_automation': false,+ 'features.network_proxy': false,+ 'features.future_local_tool': false,+ });+ for (const key of ['features.shell_tool', 'features.view_image', 'features.item_ids', 'features.web_search_request']) {+ expect(config[key]).toBeUndefined();+ }+ expect(fixture.request.mock.calls.filter(([method]) => method === Method.ExperimentalFeatureList)+ .map(([, params]) => (params as { cursor?: string }).cursor)).toEqual([undefined, 'page-2']);// 项目说明经执行环境从受邀者电脑读取,项目根的判定与同账号一致。expect(config.project_root_markers).toBeUndefined();// 本机用户的技能关闭;Codex 自带的与受邀者带来的保留。@@ -311,11 +352,19 @@ describe('Codex device-hosted guest sessions', () => {expect(String(params.developerInstructions)).toContain(GHOST_ROSTER);expect(fixture.getContactsPromptState).toHaveBeenCalled();expect(fixture.getDisabledSkillPaths).toHaveBeenCalled();- // 同账号不检查本机 Skill / MCP 清单(Review 与受邀者才逐项关闭)。+ // 同账号不检查本机 Skill / MCP 清单(Review 与受邀者才逐项关闭),Codex 功能也不按白名单收窄。expect(fixture.request.mock.calls.some(([method]) => method === Method.McpServerStatusList)).toBe(false);+ expect(fixture.request.mock.calls.some(([method]) => method === Method.ExperimentalFeatureList)).toBe(false);+ expect(config['features.image_generation']).toBeUndefined();await handle.close();});+ it('refuses a shared user when Codex cannot list its features', async () => {+ const fixture = await startHosted({ guest: true, noFeatureList: true });+ await expect(fixture.started).rejects.toThrow(/Cannot start Codex for a shared user safely/);+ expect(fixture.request.mock.calls.some(([method]) => method === Method.ThreadStart)).toBe(false);+ });+it('refuses a shared user without its own Codex home', async () => {// 没有受邀者目录就只能用本机用户任务共用的 app-server(带着本机的登录与子代理调配):不启动。const fixture = await startHosted({ guest: true, guestHome: false });diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.tsindex 885bfe09b9..ae58900e6c 100644--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts@@ -1240,6 +1240,7 @@ export const Method = {ConfigRead: 'config/read',/** EXPERIMENTAL. Register a remote exec-server as a named environment. */EnvironmentAdd: 'environment/add',+ ExperimentalFeatureList: 'experimentalFeature/list',ExperimentalFeatureEnablementSet: 'experimentalFeature/enablement/set',MemoryReset: 'memory/reset',// ServerRequest (Phase 2 + permissions):diff --git a/packages/maker-core/src/agents/codex/device-hosted-guest.ts b/packages/maker-core/src/agents/codex/device-hosted-guest.tsindex 47ac1a195b..780254c4d6 100644--- a/packages/maker-core/src/agents/codex/device-hosted-guest.ts+++ b/packages/maker-core/src/agents/codex/device-hosted-guest.ts@@ -6,7 +6,8 @@* 本机技能与 MCP、会读写本机 Codex 记忆的 memories、在本机进程里跑代码或操控本机的工具* (js_repl、code mode 宿主、浏览器、电脑操控)。全局说明与历史由独立的 CODEX_HOME(受邀者目录)隔开;* 项目说明经执行环境从受邀者电脑读取(与同账号一致,不沿本机影子目录向上找)。- * 联网搜索与模型能力保持与同账号托管会话一致。供应商只用分享给受邀者的那一个:不升格为带本机+ * Codex 功能按白名单开放(CODEX_DEVICE_HOSTED_GUEST_KEPT_FEATURES),Codex 升级新增的功能不会自动+ * 开放给受邀者;联网搜索由模型服务方执行,保持可用。供应商只用分享给受邀者的那一个:不升格为带本机* 订阅登录的超集进程,子代理不能指定模型或改道到本机的其它供应商。* 只对受邀者生效,同账号托管会话不变。*/@@ -63,6 +64,69 @@ export const CODEX_DEVICE_HOSTED_GUEST_THREAD_CONFIG: Readonly<Record<string, un'memories.use_memories': false,});+/**+ * 受邀者线程可以保持开启的 Codex 功能(白名单)。其余功能一律在线程配置里写 false:本机默认开着的、+ * 本机或项目配置打开的、Codex 升级新增的都一样。启动时从 app-server 取完整的功能清单+ * (experimentalFeature/list),名单外的逐个关闭,见 codexGuestFeatureOverrides。+ *+ * 留下的:命令、补丁与看图(经执行环境在受邀者电脑上执行),子代理,技能搜索,等待,审批与提问,+ * 目标与 Fast,以及连接、鉴权、上下文压缩本身需要的。生图不在内:它能按本机路径读参考图。+ */+export const CODEX_DEVICE_HOSTED_GUEST_KEPT_FEATURES: ReadonlySet<string> = new Set([+ 'shell_tool', 'unified_exec', 'unified_exec_tty', 'write_stdin_approval', 'view_image',+ 'multi_agent', 'multi_agent_v2', 'skill_search', 'sleep_tool', 'mentions_v2',+ 'guardian_approval', 'guardian_reuse_parent_compaction', 'auth_elicitation', 'tool_call_mcp_elicitation',+ 'goals', 'fast_mode',+ 'secret_auth_storage', 'enable_request_compression', 'system_proxy_fallback', 'unbounded_connection_retries',+ 'content_item_kinds', 'compaction_image_budget',+]);++/** experimentalFeature/list 里的一项(只用到这几个字段)。 */+export interface CodexFeatureState {+ name: string;+ stage: string;+ enabled: boolean;+}++/** 取完整的功能清单(逐页)。清单拿不到或格式不对就抛错:确认不了哪些功能开着,就不启动受邀者会话。 */+export async function listCodexFeatures(+ requestPage: (cursor: string | undefined) => Promise<unknown>,+): Promise<CodexFeatureState[]> {+ const features: CodexFeatureState[] = [];+ let cursor: string | undefined;+ for (let page = 0; page < 50; page += 1) {+ const response = await requestPage(cursor) as { data?: unknown; nextCursor?: unknown } | null | undefined;+ if (!response || !Array.isArray(response.data)) throw new Error('Codex returned no feature list.');+ for (const item of response.data as Array<Record<string, unknown> | null>) {+ if (!item || typeof item.name !== 'string' || typeof item.stage !== 'string' || typeof item.enabled !== 'boolean') {+ throw new Error('Codex returned a feature entry Cindy cannot read.');+ }+ features.push({ name: item.name, stage: item.stage, enabled: item.enabled });+ }+ if (typeof response.nextCursor !== 'string' || response.nextCursor.length === 0) {+ if (features.length === 0) throw new Error('Codex returned an empty feature list.');+ return features;+ }+ cursor = response.nextCursor;+ }+ throw new Error('Codex returned too many feature pages.');+}++/**+ * 受邀者线程的功能关闭项:名单外的功能都写 false(不论现在是否开着,项目配置也打不开)。+ * 已移除的开关不再起作用,跳过;已弃用的开关可能映射到别的配置,只关现在开着的。+ */+export function codexGuestFeatureOverrides(features: readonly CodexFeatureState[]): Record<string, false> {+ const out: Record<string, false> = {};+ for (const feature of features) {+ if (CODEX_DEVICE_HOSTED_GUEST_KEPT_FEATURES.has(feature.name)) continue;+ if (feature.stage === 'removed') continue;+ if (feature.stage === 'deprecated' && !feature.enabled) continue;+ out[`features.${feature.name}`] = false;+ }+ return out;+}+/** Codex 的用户级说明文件(CODEX_HOME 下),与 Codex 的读取顺序一致。 */export const CODEX_USER_INSTRUCTION_FILE_NAMES = ['AGENTS.override.md', 'AGENTS.md'] as const;diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 5de6519956..c62872bb52 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -29,6 +29,8 @@ import {import {assertNoCodexUserInstructions,CODEX_DEVICE_HOSTED_GUEST_THREAD_CONFIG,+ codexGuestFeatureOverrides,+ listCodexFeatures,withoutCodexSpawnModelOverrides,} from './device-hosted-guest.js';import { LIBRARY_READ_ROOT, withLibraryNativeReadContext } from '../shared/library-native-read.js';@@ -5506,6 +5508,8 @@ assertRouteCurrent();// 设备托管:本机 MCP 一律停用,只用任务所在电脑经隧道提供的 Cindy 工具(令牌放在隧道路径里,// 本机 MCP 的 bearer 令牌对隧道无效)。let hostedLocalMcpNames: string[] = [];+ // 受邀者:白名单之外的 Codex 功能在线程配置里逐个关闭(启动时按 app-server 的功能清单生成)。+ let hostedGuestFeatureConfig: Record<string, false> = {};const readHostedMcpConfig = (): Record<string, unknown> => {const out: Record<string, unknown> = {};for (const name of hostedLocalMcpNames) {@@ -6461,9 +6465,9 @@ assertRouteCurrent();'features.remote_plugin': false,}: {}),- // 受邀者:只关闭本机的插件 / hooks / connectors / 记忆,以及在本机执行代码的工具;+ // 受邀者:固定关闭本机的插件 / hooks / connectors / 记忆,再按功能清单关闭白名单之外的 Codex 功能;// 不含 mcp_servers.* 键,经隧道的 MCP(readHostedMcpConfig)保持启用。联网搜索不变。- ...(hostedGuest ? CODEX_DEVICE_HOSTED_GUEST_THREAD_CONFIG : {}),+ ...(hostedGuest ? { ...CODEX_DEVICE_HOSTED_GUEST_THREAD_CONFIG, ...hostedGuestFeatureConfig } : {}),// Review disables only transport-bearing entries discovered above.// Its host omits Cindy's MCP bridge, so a bare memory override would// create an invalid transport even though the entry is disabled.@@ -7046,6 +7050,18 @@ assertRouteCurrent();// 受邀者:确认不了本机 MCP 都已停用就不启动,不能让本机 MCP 留在另一个账号的会话里。if (hostedGuest) throw new Error(`Cannot start Codex for a shared user safely: ${String(error)}`);}+ if (hostedGuest) {+ // 受邀者:Codex 的功能只开白名单里的。清单取不到就不启动。+ try {+ hostedGuestFeatureConfig = codexGuestFeatureOverrides(await listCodexFeatures((cursor) => host.request(+ Method.ExperimentalFeatureList, { limit: 200, ...(cursor ? { cursor } : {}) },+ { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },+ )));+ } catch (error) {+ throw new Error(`Cannot start Codex for a shared user safely: ${String(error)}`);+ }+ assertCurrentHost('experimentalFeature/list');+ }assertCurrentHost('environment/add');await host.request(Method.EnvironmentAdd, {environmentId: hostedEnvironmentId,diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.tsindex 66b402a69b..f17fa1924b 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts@@ -62,6 +62,7 @@ it('keeps text-only policy local and ordinary tools independent of host UI failu).outputText;runInNewContext(compiled, {process: { env: { CINDY_PI_TURN_TOOL_POLICY: 'runtime-token' } },+ guestToolGate: null,currentPermissionState: () => { permissionReads++; return { reviewOnly: false, mode: 'bypassPermissions' }; },pi: { on: (event: string, callback: (event: any, ctx: any) => any) => { handlers.set(event, callback); } },});@@ -103,6 +104,47 @@ it('keeps text-only policy local and ordinary tools independent of host UI failuexpect(await tool({ toolName: 'ask_user_question' }, ctx)).toBeUndefined();});+it('lets a shared user\'s Pi call only tools that Cindy extensions registered', async () => {+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;+ const gateStart = source.indexOf('function createCindyGuestToolGate');+ const gateEnd = source.indexOf('\nconst PERMISSION_TITLE', gateStart);+ const handlerStart = source.indexOf(" pi.on('tool_call'");+ const handlerEnd = source.indexOf('\n });', handlerStart) + '\n });'.length;+ // 子代理扩展的工具名在生成时写进源码。+ expect(source).toContain('createCindyGuestToolGate(piApi, ["subagent"])');+ const handlers = new Map<string, (event: any, ctx: any) => any>();+ const registered: string[] = [];+ const api = {+ on: (event: string, callback: (event: any, ctx: any) => any) => { handlers.set(event, callback); },+ registerTool(tool: { name: string }) { registered.push(tool.name); },+ getActiveTools() { return ['read']; },+ };+ const compiled = ts.transpileModule(+ source.slice(gateStart, gateEnd)+ + '\nconst guestToolGate = createCindyGuestToolGate(api, ["subagent"]);\nconst pi = guestToolGate.pi;'+ + '\npi.registerTool({ name: "read" });\npi.registerTool({ name: "cindy_mcp_call_tool" });\nresult = pi.getActiveTools();\ngate = guestToolGate;\n'+ + source.slice(handlerStart, handlerEnd),+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+ ).outputText;+ const sandbox: Record<string, unknown> = {+ api, result: undefined, gate: undefined, Proxy, Reflect,+ toolsDisabledForTurn: () => false,+ currentPermissionState: () => ({ reviewOnly: false, mode: 'bypassPermissions' }),+ };+ runInNewContext(compiled, sandbox);+ // 注册照常交给 Pi,其余 API 原样转发。+ expect(registered).toEqual(['read', 'cindy_mcp_call_tool']);+ expect(sandbox.result).toEqual(['read']);+ const tool = handlers.get('tool_call')!;+ const ctx = { ui: { confirm: async () => true }, isIdle: () => true };+ for (const toolName of ['powershell', 'codemode', 'tool_search', 'mcp__local__run', 'future_builtin', undefined]) {+ expect(await tool({ toolName, input: {} }, ctx)).toMatchObject({ block: true, reason: expect.stringMatching(/shared provider/) });+ }+ // Cindy 扩展注册的(含经 Pi 原名顶替的 read)与子代理工具放行,交给后面的权限门。+ const gate = sandbox.gate as { blocks: (toolName: unknown) => boolean };+ for (const toolName of ['read', 'cindy_mcp_call_tool', 'subagent']) expect(gate.blocks(toolName)).toBe(false);+});+const canLinkFile = (() => {const root = mkdtempSync(path.join(tmpdir(), 'cindy-bridge-file-link-probe-'));try {@@ -254,7 +296,7 @@ function loadBashPackageHomeHelper(): {};}-function powerShellOverlayEnabled(platform: NodeJS.Platform, factory: unknown): boolean {+function powerShellOverlayEnabled(platform: NodeJS.Platform, factory: unknown, guest = false): boolean {const source = CINDY_BRIDGE_EXTENSION_SOURCE;const start = source.indexOf('const createPowerShellTool =');const end = source.indexOf('// Cindy owns a separate Pi extension store.', start);@@ -264,6 +306,7 @@ function powerShellOverlayEnabled(platform: NodeJS.Platform, factory: unknown):return Boolean(runInNewContext(condition, {createPowerShellTool: factory,process: { platform },+ guestToolGate: guest ? {} : null,}));}@@ -1484,6 +1527,8 @@ describe('cindy-bridge extension source', () => {it('registers the native PowerShell overlay on Windows when Pi exports its factory', () => {expect(powerShellOverlayEnabled('win32', () => undefined)).toBe(true);expect(powerShellOverlayEnabled('win32', undefined)).toBe(false);+ // 受邀者会话不注册:它在本机执行,设备托管没有对应的执行器。+ expect(powerShellOverlayEnabled('win32', () => undefined, true)).toBe(false);});it.each(['darwin', 'linux'] as const)(diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-device-hosted-guest.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-device-hosted-guest.integration.test.tsindex 2e72fd5cb8..61dd9a34d6 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-device-hosted-guest.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-device-hosted-guest.integration.test.ts@@ -134,6 +134,7 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi device-hosted guest context files (rdeviceHosted,});const systems: string[] = [];+ const toolLists: string[][] = [];for (let turn = 0; turn < 2; turn++) {const start = bodies.length;const events: AgentEvent[] = [];@@ -149,7 +150,15 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi device-hosted guest context files (rconst request = bodies.slice(start).find((entry) => entry.url.includes('/messages'));expect(request, JSON.stringify(events)).toBeDefined();systems.push(JSON.stringify(JSON.parse(request!.body).system));+ toolLists.push((JSON.parse(request!.body).tools ?? []).map((tool: { name: string }) => tool.name));}+ // 受邀者:模型只看到 Cindy 扩展注册的工具,Pi 自带而没被替换的(Windows 上默认开着的 powershell)不出现;+ // 工具清单在轮次之间不变。+ if (guest) {+ expect(toolLists[0]).toEqual(expect.arrayContaining(['read', 'bash', 'edit', 'write', 'grep', 'find', 'ls']));+ expect(toolLists[0]).not.toContain('powershell');+ }+ expect(toolLists[1]).toEqual(toolLists[0]);const text = systems[0]!;expect(text).toContain('GUEST_PROJECT_CANARY');expect(text).toContain('GUEST_PERSONAL_CANARY');diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 28b9beecf9..feee1a1a12 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -34,6 +34,7 @@ import {} from "../shared/sensitive-credential-paths.js";import { projectPiPackageCommandDiagnostic, projectPiManagedCommandFailure } from "../base-agent.js";import { shellInputRedirectionParserSource } from "../shared/shell-input-redirections.js";+import { CINDY_SUBAGENT_TOOL_NAME } from "./cindy-subagent-source.js";const SHELL_INPUT_REDIRECTION_PARSER_SOURCE = shellInputRedirectionParserSource();const CREDENTIAL_WORD_BOUNDARY = '\u0001';@@ -79,7 +80,7 @@ import * as piCodingAgent from '@earendil-works/pi-coding-agent';// 设备托管(CINDY_PI_HOSTED):Pi 在本机运行,任务、项目文件与命令在同账号另一台电脑上。// 文件与命令工具改走本机隧道上的执行器;工具与提示里的路径都是那台电脑的真实工作目录。-type CindyHostedConfig = { url: string; token: string; cwd: string; platform: string; shell: string; mirrorRoot: string };+type CindyHostedConfig = { url: string; token: string; cwd: string; platform: string; shell: string; mirrorRoot: string; guest: boolean };const CINDY_HOSTED: CindyHostedConfig | null = (() => {try {const raw = process.env.CINDY_PI_HOSTED;@@ -93,12 +94,36 @@ const CINDY_HOSTED: CindyHostedConfig | null = (() => {platform: typeof value.platform === 'string' ? value.platform : '',shell: typeof value.shell === 'string' ? value.shell : '',mirrorRoot: typeof value.mirrorRoot === 'string' ? value.mirrorRoot : '',+ // 受邀者(供应商分享的另一个账号)的会话。+ guest: value.guest === true,};} catch {return null;}})();+/**+ * 受邀者会话的工具门:只放行 Cindy 扩展注册的工具。Pi 进程以本机用户的身份在本机运行,Pi 自带而+ * Cindy 没有替换的工具(如 powershell、codemode)、Pi 内置 MCP 的工具,以及 Pi 升级新增的工具都会+ * 直接作用于本机,一律拦下。返回的 pi 记下经它注册的工具名,其余 API 原样转发。+ */+function createCindyGuestToolGate(api: any, seed: string[]): { pi: any; blocks: (toolName: unknown) => boolean } {+ const names = new Set<string>(seed);+ const pi = new Proxy(api, {+ get(target: any, prop: string | symbol) {+ const value = Reflect.get(target, prop, target);+ if (prop === 'registerTool' && typeof value === 'function') {+ return (tool: any, ...rest: unknown[]) => {+ if (tool && typeof tool.name === 'string') names.add(tool.name);+ return value.call(target, tool, ...rest);+ };+ }+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ return { pi, blocks: (toolName: unknown) => typeof toolName !== 'string' || !names.has(toolName) };+}+const PERMISSION_TITLE = 'cindy:permission';const TURN_CHANGE_CAPTURE_TITLE = 'cindy:turn-change-capture';const PERMISSION_ALLOW = 'allow';@@ -3864,7 +3889,21 @@ function registerCindyHostedTools(});}-export default async function cindyBridge(pi: any) {+export default async function cindyBridge(piApi: any) {+ // 受邀者:只放行 Cindy 扩展注册的工具(本扩展经下面的 pi 注册的,加上子代理扩展的工具)。+ const guestToolGate = CINDY_HOSTED && CINDY_HOSTED.guest+ ? createCindyGuestToolGate(piApi, [${JSON.stringify(CINDY_SUBAGENT_TOOL_NAME)}])+ : null;+ const pi = guestToolGate ? guestToolGate.pi : piApi;+ if (guestToolGate) {+ // 被拦的工具也不交给模型(例如 Pi 自带的 codemode、tool_search)。+ pi.on('before_agent_start', () => {+ if (typeof pi.getActiveTools !== 'function' || typeof pi.setActiveTools !== 'function') return;+ const active: string[] = pi.getActiveTools();+ const allowed = active.filter((name) => !guestToolGate.blocks(name));+ if (allowed.length !== active.length) pi.setActiveTools(allowed);+ });+ }installTextOnlyTurnPolicy(pi);const nativeProviderAdapters = await registerCindyNativeProviderAdapters(pi);const initialNativeSettings = typeof pi.getSettings === 'function' ? undefined@@ -4059,8 +4098,9 @@ export default async function cindyBridge(pi: any) {// Pi v0.84.3 Windows powershell is the same spawn family as bash. Overlay only// on Windows and when the runtime exports the factory so 0.83.0 sessions keep loading.+ // 受邀者会话不注册:它在本机执行,设备托管没有对应的执行器;Pi 自带的 powershell 由工具门拦下。const createPowerShellTool = (piCodingAgent as { createPowerShellTool?: typeof createBashTool }).createPowerShellTool;- if (process.platform === 'win32' && typeof createPowerShellTool === 'function') {+ if (process.platform === 'win32' && typeof createPowerShellTool === 'function' && !guestToolGate) {const powershellTool = createPowerShellTool(process.cwd(), {exposeSessionEnvironment: false,spawnHook: ({ command, cwd, env }) => ({@@ -4243,6 +4283,9 @@ export default async function cindyBridge(pi: any) {// ── 权限门 ────────────────────────────────────────────────────────────────pi.on('tool_call', async (event: any, ctx: any) => {+ if (guestToolGate && guestToolGate.blocks(event.toolName)) {+ return { block: true, reason: 'This tool is not available in a task that uses a shared provider.' };+ }if (toolsDisabledForTurn()) {return { block: true, reason: 'Tools are disabled for this host-owned text-only turn.' };}diff --git a/packages/maker-core/src/agents/shared/device-hosted.test.ts b/packages/maker-core/src/agents/shared/device-hosted.test.tsindex a109b10de1..e59687a8c5 100644--- a/packages/maker-core/src/agents/shared/device-hosted.test.ts+++ b/packages/maker-core/src/agents/shared/device-hosted.test.ts@@ -6,7 +6,10 @@ import { describe, expect, it } from 'vitest';import type { DeviceHostedSession } from '../base-agent.js';import {+ DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS,+ DEVICE_HOSTED_GUEST_CLAUDE_TOOLS,deviceHostedEnvironmentNote,+ deviceHostedGuestAgentDenial,deviceHostedGuestClaudeMdExcludes,deviceHostedGuestSessionRoot,deviceHostedPiEnvValue,@@ -224,3 +227,33 @@ describe('deviceHostedSubagentAllows', () => {expect(deviceHostedSubagentAllows('Plan', 'Write', rules)).toBe(true);});});++describe('device-hosted guest Claude tools', () => {+ it('never lists tools that act on this computer, its other sessions or its user account', () => {+ const forbidden = [+ ...DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS,+ // 其他会话+ 'ListAgents', 'SendMessage',+ // 本机用户的 claude.ai 账号+ 'Artifact', 'RemoteTrigger', 'DesignSync', 'ClaudeDesign', 'Projects', 'Workflow', 'PushNotification',+ 'ReadNotifications', 'SendFeedback', 'ProposeSkills', 'ProposeGoal',+ // 本机文件、命令与网络+ 'Monitor', 'SendUserFile', 'LSP', 'WebFetch', 'OfferChromeSetup',+ ];+ for (const name of forbidden) expect(DEVICE_HOSTED_GUEST_CLAUDE_TOOLS).not.toContain(name);+ });++ it('keeps subagents, questions, plan mode, tasks, skills and web search', () => {+ for (const name of ['Agent', 'AskUserQuestion', 'EnterPlanMode', 'ExitPlanMode', 'TodoWrite', 'ToolSearch', 'Skill', 'WebSearch']) {+ expect(DEVICE_HOSTED_GUEST_CLAUDE_TOOLS).toContain(name);+ }+ });++ it('refuses subagent isolation and leaves other calls alone', () => {+ expect(deviceHostedGuestAgentDenial('Agent', { prompt: 'x', isolation: 'remote' })).toMatch(/isolation/);+ expect(deviceHostedGuestAgentDenial('Task', { prompt: 'x', isolation: 'worktree' })).toMatch(/isolation/);+ expect(deviceHostedGuestAgentDenial('Agent', { prompt: 'x' })).toBeNull();+ expect(deviceHostedGuestAgentDenial('Agent', undefined)).toBeNull();+ expect(deviceHostedGuestAgentDenial('WebSearch', { isolation: 'remote' })).toBeNull();+ });+});diff --git a/packages/maker-core/src/agents/shared/device-hosted.ts b/packages/maker-core/src/agents/shared/device-hosted.tsindex c6b5216b6c..c85369fe49 100644--- a/packages/maker-core/src/agents/shared/device-hosted.ts+++ b/packages/maker-core/src/agents/shared/device-hosted.ts@@ -108,6 +108,38 @@ export const DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS = ['Glob', 'Grep', 'LS', 'PowerShell', 'EnterWorktree', 'ExitWorktree',] as const;+/**+ * 受邀者(供应商分享的另一个账号)会话可用的 Claude Code 自带工具,经 SDK `tools` 交给+ * Claude Code:名单之外的自带工具在会话里根本不存在,Claude Code 升级新增的工具也不会自动+ * 开放给受邀者。Agent 程序以本机用户的身份在本机运行,其余自带工具都直接作用于本机或本机+ * 用户:其他会话(ListAgents / SendMessage)、本机用户的 claude.ai 账号(Artifact、+ * RemoteTrigger、DesignSync 等)、本机文件与命令(Monitor、SendUserFile 等)、本机网络(WebFetch)。+ * 文件与命令由 cindy_exec 回到受邀者电脑执行(MCP 工具不受 `tools` 限制)。+ */+export const DEVICE_HOSTED_GUEST_CLAUDE_TOOLS = [+ // 子代理。隔离选项另由 deviceHostedGuestAgentDenial 拦下。+ 'Agent',+ // 只作用于会话自身:提问、计划模式、待办与后台任务、延迟加载的工具、技能、结果卡片、定时唤醒。+ 'AskUserQuestion', 'EnterPlanMode', 'ExitPlanMode',+ 'TodoWrite', 'TaskCreate', 'TaskGet', 'TaskList', 'TaskUpdate', 'TaskStop', 'TaskOutput',+ 'ToolSearch', 'Skill', 'ReportFindings', 'ScheduleWakeup', 'CronCreate', 'CronDelete', 'CronList',+ // 只连本会话配置的 MCP 服务,设备托管时都经隧道回到受邀者电脑。+ 'ListMcpResourcesTool', 'ReadMcpResourceTool',+ // 由模型服务方执行,不经本机网络。+ 'WebSearch',+] as const;++/**+ * 受邀者会话里子代理的隔离选项:worktree 在本机建 git worktree,remote 用本机用户的 claude.ai+ * 账号开云端任务,都不允许。返回拒绝原因;其他调用返回 null。+ */+export function deviceHostedGuestAgentDenial(toolName: string, input: unknown): string | null {+ if (toolName !== 'Agent' && toolName !== 'Task') return null;+ const isolation = input && typeof input === 'object' ? (input as { isolation?: unknown }).isolation : undefined;+ if (isolation === undefined || isolation === null) return null;+ return 'Subagent isolation is not available in this task. Start the subagent without the isolation option.';+}+const EXEC_PREFIX = `mcp__${DEVICE_HOSTED_EXEC_MCP_SERVER}__`;/** `mcp__cindy_exec__Bash` → `Bash`;不是顶替工具时返回 null。 */