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): 受邀者的 WebFetch 改在受邀者电脑上抓取
Lizifd3b9dd35489
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 4c02c926d3..6c0fc33603 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -121,6 +121,7 @@ import { getProviderGroupGuestSwitch } from '../provider-group/guestSwitch.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';import { remoteBackgroundInvoke, remoteInvoke } from '../device-link/index.js';import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';+import { parseProviderShareAgentDeviceId } from '../device-link/providerShareGuest.js';import { createHistoryRemoteDeps } from '../mcp-integrations/historyDevices.js';import { WorktreePool } from '../worktree/index.js';import { getReadyBinaryPath, getCachedBinaryStatus } from '../agent-binaries/index.js';@@ -140,7 +141,7 @@ import {writeCodexHistoryHasProductPrompt,} from './session-storage.js';import { desktopMakerLogger } from './logger-adapter.js';-import { outboundFetch } from './outbound-fetch.js';+import { guardedOutboundFetch, outboundFetch } from './outbound-fetch.js';import { readCustomProviderKey } from '../secrets/providerSecretStore.js';import { createVisionBridge } from '../vision-bridge/vision-bridge.js';import {@@ -2718,6 +2719,9 @@ export function getMaker(): Maker {isGroupAssigned: (sessionId) => readProviderGroupBinding(sessionId) !== null,// 分享来的供应商被分享者建成了组:那台出问题时对方发来「需要换一台」,本机交接后带回凭证(§6.1)。groupSwitch: getProviderGroupGuestSwitch(),+ // 供应商分享的受邀者任务:WebFetch 用本机网络抓取(系统代理、单跳、内网要本机批准)。+ isSharedProviderDevice: (deviceId) => parseProviderShareAgentDeviceId(deviceId) !== null,+ webFetch: guardedOutboundFetch,logger: desktopMakerLogger,}),makerMemory: makerMemoryManager,diff --git a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.tsindex e18df08227..e21da6e8a0 100644--- a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts@@ -140,6 +140,10 @@ describe('exec-server relay gate', () => {expect(approvalActionsFor({kind: 'permission', requestId: 'r', toolName: 'Edit', input: { file_path: 'src/a.ts' },}, workspace)).toEqual([{ kind: 'write', path: path.join(root, 'src/a.ts') }]);+ // 受邀者任务里本机提供的 WebFetch:登记批准过的地址。+ expect(approvalActionsFor({+ kind: 'permission', requestId: 'r', toolName: 'mcp__cindy_exec__WebFetch', input: { url: ' http://10.0.0.5/wiki ', prompt: 'x' },+ }, workspace)).toEqual([{ kind: 'fetch', url: 'http://10.0.0.5/wiki' }]);expect(approvalActionsFor({ kind: 'ask_user_question', requestId: 'r', questions: [] }, workspace)).toEqual([]);});});@@ -233,6 +237,8 @@ describe('event mapping and project files', () => {it('shows the built-in tool names for Claude Code tools that run on this computer', () => {expect(mapClaudeHostedEvent({ type: 'tool_use', data: { toolName: 'mcp__cindy_exec__Bash', input: {} } }).data).toEqual({ toolName: 'Bash', input: {} });+ expect(mapClaudeHostedEvent({ type: 'tool_use', data: { toolName: 'mcp__cindy_exec__WebFetch', input: { url: 'https://a.b' } } }).data)+ .toEqual({ toolName: 'WebFetch', input: { url: 'https://a.b' } });expect(mapClaudeHostedEvent({ type: 'tool_use', data: { toolName: 'mcp__cindy_memory__x' } }).data).toEqual({ toolName: 'mcp__cindy_memory__x' });});diff --git a/apps/desktop/src/main/remote-agent/controller/eventMap.ts b/apps/desktop/src/main/remote-agent/controller/eventMap.tsindex f4452e75a6..076ec1931b 100644--- a/apps/desktop/src/main/remote-agent/controller/eventMap.ts+++ b/apps/desktop/src/main/remote-agent/controller/eventMap.ts@@ -3,11 +3,12 @@** Claude Code 的自带文件与命令工具在对方电脑上由 Cindy 工具(`mcp__cindy_exec__Bash` 等)顶替,* 本机界面、记录与统计看到的仍是自带工具名(Bash / Read / Edit …),和本机任务一样渲染。+ * 供应商分享的受邀者任务里 WebFetch 也由本机提供,同样改回自带工具名。*/import type { AgentEvent, AgentKind } from '@cindy/maker-core';const EXEC_PREFIX = 'mcp__cindy_exec__';-const EXEC_TOOLS = new Set(['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit']);+const EXEC_TOOLS = new Set(['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit', 'WebFetch']);export function builtinToolName(name: unknown): string | null {if (typeof name !== 'string' || !name.startsWith(EXEC_PREFIX)) return null;diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.tsindex 73b3d870f1..254c9e8a00 100644--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts@@ -163,6 +163,10 @@ export function approvalActionsFor(// 路径不合法时不登记。}}+ // 受邀者任务里本机提供的 WebFetch:登记批准过的地址。+ if (name === 'webfetch' && typeof input.url === 'string' && input.url.trim()) {+ actions.push({ kind: 'fetch', url: input.url.trim() });+ }return actions;}diff --git a/apps/desktop/src/main/remote-agent/controller/service.ts b/apps/desktop/src/main/remote-agent/controller/service.tsindex 85c683ff44..a06702c53c 100644--- a/apps/desktop/src/main/remote-agent/controller/service.ts+++ b/apps/desktop/src/main/remote-agent/controller/service.ts@@ -26,6 +26,7 @@ import { resolveMemoryScopeKey } from '@cindy/maker-core';import type { ExecutorCaptureHooks } from '../executor/executor';import type { PdfTextExtractor } from '../executor/files';+import type { GuardedFetch } from '../executor/webFetch';import { remoteAgentEventMapper } from './eventMap';import {collectAncestorInstructionFiles,@@ -67,6 +68,10 @@ export interface DeviceAgentServiceDeps {/** 用户亲自接手后的这次发送开始新的一轮(取走即用掉)。 */takeNewRound?(sessionId: string): boolean;};+ /** 任务的「Agent 所在电脑」是不是分享来的供应商(受邀者任务)。 */+ isSharedProviderDevice?(deviceId: string): boolean;+ /** 受邀者任务在本机抓取网页的出站通道(WebFetch)。 */+ webFetch?: GuardedFetch;logger: Logger;}@@ -153,6 +158,8 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {const sessionId = opts.sessionId;const groupSwitch = sessionId && deps.groupSwitch ? deps.groupSwitch : null;const switchToken = groupSwitch && sessionId ? groupSwitch.takeForOpen(sessionId) : undefined;+ // 受邀者任务:Agent 自带的 WebFetch 在分享者电脑上已关闭,改由本机抓取。同账号任务不提供。+ const webFetch = deps.webFetch && deps.isSharedProviderDevice?.(input.deviceId) ? deps.webFetch : undefined;return startRemoteAgentSession(input.agentKind, opts, {invoke: poller.invoke,poller,@@ -168,6 +175,7 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {},}: {}),+ ...(webFetch ? { webFetch } : {}),prepareMcp: async ({ kind, opts: startOpts, vendorOptions }): Promise<PreparedRemoteMcp> => {const extra = await deps.prepareMcpBridge(deps.mcpProviders(), deps.logger, {agentKind: kind,diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.tsindex 91f08f70d2..a5ff4bbb7b 100644--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts@@ -21,6 +21,7 @@ import type { AgentEvent, AgentSessionHandle, StartSessionOptions } from '@cindyimport { RemoteExecutor, type ExecutorCaptureHooks } from '../executor/executor';import type { PdfTextExtractor } from '../executor/files';import { ExecutorGate, executorGateModeFor } from '../executor/gate';+import type { GuardedFetch } from '../executor/webFetch';import { ExecutorWorkspace } from '../executor/workspace';import type {RemoteAgentOpenPayload,@@ -70,6 +71,11 @@ export interface StartRemoteAgentDeps {isGitRepo(workingDir: string): Promise<boolean>;/** Read 读 PDF 时取文字(Claude Code)。 */extractPdfText?: PdfTextExtractor;+ /**+ * 在本机抓取网页的出站通道:给 Claude Code 提供 WebFetch(供应商分享的受邀者任务,自带的+ * WebFetch 在对方电脑上已关闭)。缺省时不提供。+ */+ webFetch?: GuardedFetch;/** 改写来自对方的事件(如工具名)。 */mapEvent?: (kind: RemoteAgentKind) => ((event: AgentEvent) => AgentEvent) | undefined;/** 本机 Codex 程序(给对方的 Codex 提供 exec-server 执行环境);缺省时不提供。 */@@ -181,6 +187,8 @@ export async function startRemoteAgentSession(rgPath: deps.rgPath,capture: deps.capture?.({ kind, opts }),...(deps.extractPdfText ? { extractPdfText: deps.extractPdfText } : {}),+ // 只有 Claude Code 经 cindy_exec 使用这组工具。+ ...(kind === 'claude-code' && deps.webFetch ? { webFetch: deps.webFetch } : {}),});let permissionMode = opts.permissionMode;let planMode = opts.planMode === true;diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.tsindex e39f42cccf..3d377bbbe6 100644--- a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts@@ -9,6 +9,7 @@ import { RemoteExecutor } from '../executor';import { EXECUTOR_APPROVAL_TTL_MS, ExecutorGate, executorGateModeFor } from '../gate';import type { PdfTextExtractor } from '../files';import { findWindowsGitBash, truncateOutput } from '../shell';+import type { GuardedFetch } from '../webFetch';import { ExecutorWorkspace } from '../workspace';const RG = path.resolve(__dirname, '../../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');@@ -22,7 +23,7 @@ let opaque: number;function makeExecutor(mode: ReturnType<typeof executorGateModeFor> = 'normal',- extra: { aliases?: Array<{ from: string; to: string }>; now?: () => number; extractPdfText?: PdfTextExtractor } = {},+ extra: { aliases?: Array<{ from: string; to: string }>; now?: () => number; extractPdfText?: PdfTextExtractor; webFetch?: GuardedFetch } = {},) {const workspace = new ExecutorWorkspace({ workingDir: project, aliases: extra.aliases });const gate = new ExecutorGate(workspace, mode, extra.now);@@ -32,6 +33,7 @@ function makeExecutor(rgPath: RG,tempDir: path.join(root, 'tmp'),...(extra.extractPdfText ? { extractPdfText: extra.extractPdfText } : {}),+ ...(extra.webFetch ? { webFetch: extra.webFetch } : {}),capture: {beforeWrite: async (p) => {captured.push(p);@@ -189,6 +191,31 @@ describe('permission ceiling', () => {expect(executorGateModeFor('auto')).toBe('normal');expect(executorGateModeFor('plan')).toBe('plan');});++ it('lets public pages through and holds local, private and metadata addresses until confirmed on this computer', () => {+ const workspace = new ExecutorWorkspace({ workingDir: project });+ const gate = new ExecutorGate(workspace, 'normal');+ expect(gate.authorize({ kind: 'fetch', url: 'https://example.com/docs' })).toEqual({ ok: true });+ for (const url of ['http://169.254.169.254/latest/meta-data/', 'http://localhost:3000/', 'http://10.0.0.5/wiki', 'http://127.1/']) {+ expect(gate.authorize({ kind: 'fetch', url }).ok).toBe(false);+ }+ gate.recordApproval({ kind: 'fetch', url: 'http://10.0.0.5/wiki' });+ // 批准只覆盖这一个地址,用一次即失效。+ expect(gate.authorize({ kind: 'fetch', url: 'http://10.0.0.5/wiki' })).toEqual({ ok: true, elevated: true });+ expect(gate.authorize({ kind: 'fetch', url: 'http://10.0.0.5/wiki' }).ok).toBe(false);+ gate.recordApproval({ kind: 'fetch', url: 'http://10.0.0.5/wiki' });+ expect(gate.authorize({ kind: 'fetch', url: 'http://10.0.0.5/other' }).ok).toBe(false);+ // 公网样式的域名也可能解析到内网:本机用户批准过这个地址时同样放开内网,用一次即失效。+ gate.recordApproval({ kind: 'fetch', url: 'https://wiki.corp.example/page' });+ expect(gate.authorize({ kind: 'fetch', url: 'https://wiki.corp.example/page' })).toEqual({ ok: true, elevated: true });+ expect(gate.authorize({ kind: 'fetch', url: 'https://wiki.corp.example/page' })).toEqual({ ok: true });+ // 只读的网络请求:计划模式也可以抓公网页面。+ const plan = new ExecutorGate(workspace, executorGateModeFor('default', true));+ expect(plan.authorize({ kind: 'fetch', url: 'https://example.com' }).ok).toBe(true);+ expect(plan.authorize({ kind: 'fetch', url: 'http://localhost/' }).ok).toBe(false);+ const full = new ExecutorGate(workspace, executorGateModeFor('bypassPermissions'));+ expect(full.authorize({ kind: 'fetch', url: 'http://localhost/' })).toEqual({ ok: true, elevated: true });+ });});describe('Claude Code style file tools', () => {@@ -489,6 +516,44 @@ describe('cindy_exec MCP endpoint', () => {expect((await post({ jsonrpc: '2.0', id: 4, method: 'nope' })).json.error.code).toBe(-32601);expect((await handleExecMcpRequest(executor, 'GET', undefined)).status).toBe(405);expect((await handleExecMcpRequest(executor, 'POST', Buffer.from('{bad'))).status).toBe(400);+ // 没有启用 WebFetch 时(同账号任务)既不列出也不能调用。+ const fetchCall = await post({ jsonrpc: '2.0', id: 5, method: 'tools/call', params: { name: 'WebFetch', arguments: { url: 'https://example.com' } } });+ expect(fetchCall.json.result).toMatchObject({ isError: true, content: [{ text: 'Unknown tool: WebFetch' }] });+ });++ it('offers WebFetch when enabled and fetches private addresses only after the user confirms', async () => {+ const calls: Array<{ url: string; allowPrivateNetwork?: boolean; allowHttp?: boolean }> = [];+ const webFetch: GuardedFetch = async (url, _init, _before, approval) => {+ calls.push({ url, allowPrivateNetwork: approval?.allowPrivateNetwork, allowHttp: approval?.allowHttp });+ return {+ response: new Response('<html><head><title>Wiki</title></head><body><p>Hello</p></body></html>', {+ headers: { 'content-type': 'text/html; charset=utf-8' },+ }),+ release: async () => {},+ };+ };+ const { executor, gate } = makeExecutor('normal', { webFetch });+ expect(executor.toolDefinitions().map((tool) => tool.name))+ .toEqual(['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit', 'WebFetch']);++ const page = await executor.callTool('WebFetch', { url: 'http://example.com/a', prompt: 'greeting' });+ expect(page.isError).toBeUndefined();+ expect(text(page)).toContain('Title: Wiki');+ expect(text(page)).toContain('Hello');+ expect(calls.at(-1)).toEqual({ url: 'https://example.com/a', allowPrivateNetwork: false, allowHttp: false });++ const denied = await executor.callTool('WebFetch', { url: 'http://10.0.0.5/wiki' });+ expect(denied.isError).toBe(true);+ expect(text(denied)).toContain('needs the user\'s confirmation');+ expect(calls).toHaveLength(1);+ gate.recordApproval({ kind: 'fetch', url: 'http://10.0.0.5/wiki' });+ expect((await executor.callTool('WebFetch', { url: 'http://10.0.0.5/wiki' })).isError).toBeUndefined();+ expect(calls.at(-1)).toEqual({ url: 'http://10.0.0.5/wiki', allowPrivateNetwork: true, allowHttp: true });++ for (const url of ['file:///etc/passwd', 'not a url', 'https://user:[email protected]/']) {+ expect((await executor.callTool('WebFetch', { url })).isError).toBe(true);+ }+ expect(calls).toHaveLength(2);});});diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/webFetch.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/webFetch.test.tsnew file mode 100644index 0000000000..5aa50658bb--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/webFetch.test.ts@@ -0,0 +1,117 @@+import { SsrFBlockedError } from '@cindy/browser-control-runtime/ssrf-runtime';+import { describe, expect, it } from 'vitest';++import { fetchWebPage, htmlToText, WEB_FETCH_PAGE_CHARS, type GuardedFetch } from '../webFetch';++function text(result: { content: Array<{ type: string; text?: string }> }): string {+ return result.content.map((item) => item.text ?? '').join('');+}++/** 按地址回应的假出站通道,记录每一跳。 */+function fakeFetch(routes: Record<string, () => Response>): { fetch: GuardedFetch; hops: string[]; released: number } {+ const state = { hops: [] as string[], released: 0 };+ const fetch: GuardedFetch = async (url) => {+ state.hops.push(url);+ const route = routes[url];+ if (!route) throw new Error(`unexpected ${url}`);+ return { response: route(), release: async () => { state.released += 1; } };+ };+ return { fetch, get hops() { return state.hops; }, get released() { return state.released; } };+}++const html = (body: string, headers: Record<string, string> = {}) => () => new Response(body, {+ headers: { 'content-type': 'text/html; charset=utf-8', ...headers },+});++describe('htmlToText', () => {+ it('keeps headings, links, lists and code blocks and drops scripts, styles and markup', () => {+ const { title, text: out } = htmlToText([+ '<html><head><title>Guide & Notes</title><style>p{color:red}</style></head><body>',+ '<script>alert(1)</script><!-- note -->',+ '<h1>Install</h1><p>Run the\n installer from <a href="/download?a=1&b=2">the site</a>.</p>',+ '<ul><li>One</li><li>Two <b></li></ul>',+ '<pre><code>npm install\n cindy</code></pre>',+ '<p>Bad <a href="javascript:alert(1)">link</a> and <a href="#top">anchor</a>; café ☺ Über & </p>',+ '<p>Unclosed <a href="https://x.example/">tail',+ '</body></html>',+ ].join(''), new URL('https://docs.example.com/guide/'));+ expect(title).toBe('Guide & Notes');+ expect(out).toContain('# Install');+ expect(out).toContain('Run the installer from [the site](https://docs.example.com/download?a=1&b=2).');+ expect(out).toContain('- One\n- Two <b>');+ expect(out).toContain('```\nnpm install\n cindy\n```');+ expect(out).toContain('Bad link and anchor; café ☺ Über &');+ expect(out).toContain('Unclosed tail');+ expect(out).not.toMatch(/alert|color:red|note|x\.example|[\u0001-\u0004]/);+ });+});++describe('fetchWebPage', () => {+ it('upgrades http, follows redirects on the same site and returns the page text', async () => {+ const fake = fakeFetch({+ 'https://example.com/a': () => new Response(null, { status: 301, headers: { location: 'https://www.example.com/b' } }),+ 'https://www.example.com/b': html('<title>B</title><p>Body text</p>'),+ });+ const result = await fetchWebPage(fake.fetch, { url: new URL('http://example.com/a'), startIndex: 0, allowPrivateNetwork: false });+ expect(result.isError).toBeUndefined();+ expect(text(result)).toBe('URL: https://www.example.com/b\nTitle: B\n\nBody text');+ expect(fake.hops).toEqual(['https://example.com/a', 'https://www.example.com/b']);+ expect(fake.released).toBe(2);+ });++ it('hands redirects to another host back to the agent instead of following them', async () => {+ const fake = fakeFetch({+ 'https://example.com/go': () => new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/latest/' } }),+ });+ const result = await fetchWebPage(fake.fetch, { url: new URL('https://example.com/go'), startIndex: 0, allowPrivateNetwork: false });+ expect(result.isError).toBeUndefined();+ expect(text(result)).toContain('redirected to a different host: http://169.254.169.254/latest/');+ expect(fake.hops).toEqual(['https://example.com/go']);+ });++ it('keeps http and the private network only for an approved address', async () => {+ const approvals: unknown[] = [];+ const fetch: GuardedFetch = async (url, _init, _before, approval) => {+ approvals.push({ url, ...approval });+ return { response: new Response('plain', { headers: { 'content-type': 'text/plain' } }), release: async () => {} };+ };+ await fetchWebPage(fetch, { url: new URL('http://10.0.0.5/wiki'), startIndex: 0, allowPrivateNetwork: true });+ expect(approvals).toEqual([{ url: 'http://10.0.0.5/wiki', targetUrl: 'http://10.0.0.5/wiki', allowHttp: true, allowPrivateNetwork: true }]);+ });++ it('explains private-network blocks, HTTP errors, loops and non-text content', async () => {+ const blocked: GuardedFetch = async () => {+ throw new SsrFBlockedError('Blocked: resolves to private/internal/special-use IP address');+ };+ const privateResult = await fetchWebPage(blocked, { url: new URL('https://intranet.example/'), startIndex: 0, allowPrivateNetwork: false });+ expect(privateResult.isError).toBe(true);+ expect(text(privateResult)).toContain('private network');++ const fake = fakeFetch({+ 'https://example.com/404': () => new Response('nope', { status: 404, statusText: 'Not Found' }),+ 'https://example.com/loop': () => new Response(null, { status: 302, headers: { location: '/loop' } }),+ 'https://example.com/logo.png': () => new Response(new Uint8Array([137, 80, 78, 71]), { headers: { 'content-type': 'image/png' } }),+ });+ const notFound = await fetchWebPage(fake.fetch, { url: new URL('https://example.com/404'), startIndex: 0, allowPrivateNetwork: false });+ expect(text(notFound)).toBe('https://example.com/404 returned HTTP 404 Not Found.');+ const loop = await fetchWebPage(fake.fetch, { url: new URL('https://example.com/loop'), startIndex: 0, allowPrivateNetwork: false });+ expect(text(loop)).toContain('loop');+ const image = await fetchWebPage(fake.fetch, { url: new URL('https://example.com/logo.png'), startIndex: 0, allowPrivateNetwork: false });+ expect(image.isError).toBe(true);+ expect(text(image)).toContain('image/png, not a text page');+ });++ it('returns long pages in parts and decodes the declared charset', async () => {+ const long = 'x'.repeat(WEB_FETCH_PAGE_CHARS + 10);+ const fake = fakeFetch({+ 'https://example.com/long': () => new Response(long, { headers: { 'content-type': 'text/plain' } }),+ 'https://example.com/latin': () => new Response(new Uint8Array([0x63, 0x61, 0x66, 0xe9]), { headers: { 'content-type': 'text/plain; charset=iso-8859-1' } }),+ });+ const first = await fetchWebPage(fake.fetch, { url: new URL('https://example.com/long'), startIndex: 0, allowPrivateNetwork: false });+ expect(text(first)).toContain(`Characters 0–${WEB_FETCH_PAGE_CHARS} of ${WEB_FETCH_PAGE_CHARS + 10}. Call WebFetch again with start_index=${WEB_FETCH_PAGE_CHARS}`);+ const rest = await fetchWebPage(fake.fetch, { url: new URL('https://example.com/long'), startIndex: WEB_FETCH_PAGE_CHARS, allowPrivateNetwork: false });+ expect(text(rest).endsWith('\n\nxxxxxxxxxx')).toBe(true);+ const latin = await fetchWebPage(fake.fetch, { url: new URL('https://example.com/latin'), startIndex: 0, allowPrivateNetwork: false });+ expect(text(latin)).toBe('URL: https://example.com/latin\n\ncafé');+ });+});diff --git a/apps/desktop/src/main/remote-agent/executor/ccMcp.ts b/apps/desktop/src/main/remote-agent/executor/ccMcp.tsindex 7c26aef8da..cfbeeb7d82 100644--- a/apps/desktop/src/main/remote-agent/executor/ccMcp.ts+++ b/apps/desktop/src/main/remote-agent/executor/ccMcp.ts@@ -2,7 +2,7 @@* `cindy_exec` MCP 服务(控制端):把执行器的 Claude Code 风格工具以 MCP(Streamable HTTP,* 无状态、请求-响应)提供给另一台电脑上的 Claude Code。请求经设备互联隧道到达这里。*/-import { executorCcToolDefinitions, type RemoteExecutor } from './executor';+import type { RemoteExecutor } from './executor';export const CINDY_EXEC_MCP_SERVER = 'cindy_exec';const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];@@ -66,7 +66,7 @@ async function handleOne(jsonrpc: '2.0',id: request.id,result: {- tools: executorCcToolDefinitions().map((tool) => ({+ tools: executor.toolDefinitions().map((tool) => ({name: tool.name,description: tool.description,inputSchema: tool.inputSchema,diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.tsindex c1cd496ad9..4eb81fda4c 100644--- a/apps/desktop/src/main/remote-agent/executor/executor.ts+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts@@ -4,7 +4,8 @@* Agent 所在电脑发来的每个文件 / 命令请求都在这里先过权限上限,再在本机执行:* - `handle(op, body)`:原始操作(Pi 的工具后端);* - `callTool(name, args)`:Claude Code 风格的 Bash / BashOutput / KillShell / Read / Write / Edit /- * NotebookEdit(Claude Code 的自带文件与命令工具关掉后由它顶替)。+ * NotebookEdit(Claude Code 的自带文件与命令工具关掉后由它顶替);供应商分享的受邀者任务另有+ * WebFetch(自带的 WebFetch 对受邀者关闭,改在本机抓取)。* 写文件前通知「每轮改动对比」抓取改前内容;命令执行后登记一次无法预知范围的改动。*/import path from 'node:path';@@ -33,6 +34,7 @@ import {import type { ExecutorAction, ExecutorGate, ExecutorGateDecision, ExecutorGateMode } from './gate';import { piGrep, type PiGrepInput } from './search';import { resolveExecutorShell, runOnce, ShellSession } from './shell';+import { fetchWebPage, WEB_FETCH_PAGE_CHARS, type GuardedFetch } from './webFetch';import { ExecutorPathError, type ExecutorWorkspace } from './workspace';/** Pi bash 的超时(秒)上限,与 Pi 侧 Cindy 桥的上限一致。 */@@ -52,6 +54,8 @@ export interface RemoteExecutorOptions {tempDir?: string;/** Read 读 PDF 时取文字;缺省时 PDF 不能用 Read 读取。 */extractPdfText?: PdfTextExtractor;+ /** 提供 WebFetch(在本机抓取网页)所用的出站通道;缺省时不提供这个工具。 */+ webFetch?: GuardedFetch;}export class ExecutorRequestError extends Error {@@ -91,8 +95,8 @@ function optionalString(body: Record<string, unknown>, key: string): string | unreturn value;}-/** Claude Code 风格工具名(与自带工具同名,模型和界面看到的都是这些名字)。 */-export const EXECUTOR_CC_TOOL_NAMES = ['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit'] as const;+/** Claude Code 风格工具名(与自带工具同名,模型和界面看到的都是这些名字)。WebFetch 只在启用时提供。 */+export const EXECUTOR_CC_TOOL_NAMES = ['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit', 'WebFetch'] as const;export type ExecutorCcToolName = (typeof EXECUTOR_CC_TOOL_NAMES)[number];export class RemoteExecutor {@@ -142,6 +146,11 @@ export class RemoteExecutor {await this.shell.close();}+ /** 给 Claude Code 的工具定义(cindy_exec 的 tools/list)。 */+ toolDefinitions(): ReturnType<typeof executorCcToolDefinitions> {+ return executorCcToolDefinitions(process.platform, { webFetch: this.opts.webFetch !== undefined });+ }+private ensureOpen(): void {if (this.closed) throw new ExecutorRequestError('CLOSED', 'The task has ended on the computer where it runs.');}@@ -323,6 +332,9 @@ export class RemoteExecutor {edit_mode: editMode,}, this.readState, this.writeHooks));}+ case 'WebFetch':+ if (!this.opts.webFetch) return textResult(`Unknown tool: ${name}`, true);+ return this.mapToolResult(await this.webFetch(this.opts.webFetch, args, signal));default:return textResult(`Unknown tool: ${name}`, true);}@@ -349,6 +361,23 @@ export class RemoteExecutor {};}+ private async webFetch(fetchImpl: GuardedFetch, args: Record<string, unknown>, signal?: AbortSignal): Promise<ToolResult> {+ const raw = str(args, 'url').trim();+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ return textResult(`Not a valid URL: ${raw}`, true);+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return textResult('Only http and https URLs can be fetched.', true);+ if (url.username || url.password) return textResult('URLs with a user name or password cannot be fetched.', true);+ const startIndex = Math.max(0, Math.floor(optionalNumber(args, 'start_index') ?? 0));+ // 按 Agent 给的原样地址核对:本机用户在确认卡上批准的就是这个地址。+ const decision = this.gate.authorize({ kind: 'fetch', url: raw });+ if (!decision.ok) throw new ExecutorDenied(decision.reason ?? 'Not allowed.');+ return fetchWebPage(fetchImpl, { url, startIndex, allowPrivateNetwork: decision.elevated === true, signal });+ }+private async bash(args: Record<string, unknown>, signal?: AbortSignal): Promise<ToolResult> {const rawCommand = args.command;if (typeof rawCommand !== 'string' || !rawCommand.trim()) return textResult('command is required.', true);@@ -374,7 +403,10 @@ class ExecutorDenied extends Error {}/** 给 Claude Code 的工具定义(参数名与自带工具一致;说明是 Cindy 自己写的)。 */-export function executorCcToolDefinitions(platform: NodeJS.Platform = process.platform): Array<{+export function executorCcToolDefinitions(+ platform: NodeJS.Platform = process.platform,+ options: { webFetch?: boolean } = {},+): Array<{name: ExecutorCcToolName;description: string;inputSchema: Record<string, unknown>;@@ -383,6 +415,26 @@ export function executorCcToolDefinitions(platform: NodeJS.Platform = process.plconst shellNote = platform === 'win32'? 'Commands run in Git Bash when available, otherwise cmd.exe.': `Commands run with ${path.basename(process.env.SHELL || 'bash')}.`;+ const webFetch = options.webFetch ? [{+ name: 'WebFetch' as const,+ description: [+ "Fetch a web page using the network of the user's computer and return its text.",+ 'HTML is converted to plain text with headings, links, lists and code blocks kept; other text types are returned as they are. Images, PDFs and other files are not returned.',+ 'HTTP URLs are upgraded to HTTPS. A redirect to another host is not followed: the result gives the new URL, so call WebFetch again with it.',+ `Long pages come in parts of ${WEB_FETCH_PAGE_CHARS} characters; pass start_index to read further.`,+ "Addresses on the user's computer or a private network need the user's confirmation.",+ ].join(' '),+ inputSchema: {+ type: 'object',+ properties: {+ url: { type: 'string', description: 'The URL to fetch' },+ prompt: { type: 'string', description: 'What you are looking for on the page, shown to the user. The page text is returned for you to read.' },+ start_index: { type: 'integer', minimum: 0, description: 'Character position to start from when reading a long page (default 0)' },+ },+ required: ['url'],+ additionalProperties: false,+ },+ }] : [];return [{name: 'Bash',@@ -498,5 +550,6 @@ export function executorCcToolDefinitions(platform: NodeJS.Platform = process.pladditionalProperties: false,},},+ ...webFetch,];}diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.tsindex 9dfeca3919..9c337f0ab7 100644--- a/apps/desktop/src/main/remote-agent/executor/gate.ts+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts@@ -10,13 +10,15 @@* - 可写根外的写与工作区外的递归读:本机任务同样必问(auto-review 对区外写返回 prompt),* 执行器只认本机用户批准过的同一操作 —— 反向请求按本机策略与规范批准重建,发起方那台* 电脑不可信时也不能绕过本机用户的目录授权;- * - 计划模式:只允许读取和静态可证只读的命令,其余同样要本机用户批准过。- * 批准记录只在短时间内有效;命令批准用一次即失效,路径批准在有效期内覆盖同一路径的读写+ * - 抓取网页:本机地址、内网与云 metadata 这类地址(与本机任务里 WebFetch / curl 同一判定)+ * 只认本机用户刚批准过的同一地址;批准过的地址抓取时放开内网(域名也可能解析到内网);+ * - 计划模式:只允许读取、抓取网页和静态可证只读的命令,其余同样要本机用户批准过。+ * 批准记录只在短时间内有效;命令与抓取的批准用一次即失效,路径批准在有效期内覆盖同一路径的读写* (编辑会先读后写)。*/import path from 'node:path';-import { classifyShellCommand } from '@cindy/maker-core';+import { classifyShellCommand, reviewAction } from '@cindy/maker-core';import type { ExecutorWorkspace } from './workspace';@@ -29,12 +31,15 @@ export type ExecutorGateMode = 'full' | 'plan' | 'normal';export type ExecutorAction =| { kind: 'read'; path: string; scope?: 'tree' }| { kind: 'write'; path: string }- | { kind: 'exec'; command: string; cwd: string };+ | { kind: 'exec'; command: string; cwd: string }+ | { kind: 'fetch'; url: string };export interface ExecutorGateDecision {ok: boolean;/** 拒绝时给 Agent 看的原因。 */reason?: string;+ /** 放行来自全权或本机用户的批准,而不只是普通上限之内(抓取网页据此决定能否访问内网)。 */+ elevated?: boolean;}/** 批准记录的有效期:覆盖「确认后到真正执行」之间的间隔,过期须重新确认。 */@@ -42,7 +47,7 @@ export const EXECUTOR_APPROVAL_TTL_MS = 2 * 60_000;const MAX_APPROVALS = 256;interface Approval {- kind: 'path' | 'exec';+ kind: 'path' | 'exec' | 'fetch';key: string;expiresAt: number;}@@ -63,6 +68,25 @@ function execKey(command: string, cwd: string): string {return `${path.resolve(cwd)}\\0${command}`;}+function fetchKey(url: string): string {+ try {+ return new URL(url).href;+ } catch {+ return url;+ }+}++function approvalOf(action: ExecutorAction): { kind: Approval['kind']; key: string } {+ switch (action.kind) {+ case 'exec':+ return { kind: 'exec', key: execKey(action.command, action.cwd) };+ case 'fetch':+ return { kind: 'fetch', key: fetchKey(action.url) };+ default:+ return { kind: 'path', key: pathKey(action.path) };+ }+}+export class ExecutorGate {private mode: ExecutorGateMode;private approvals: Approval[] = [];@@ -86,25 +110,32 @@ export class ExecutorGate {/** 本机用户在确认卡上允许了一个操作后调用。 */recordApproval(action: ExecutorAction): void {this.prune();- this.approvals.push(action.kind === 'exec'- ? { kind: 'exec', key: execKey(action.command, action.cwd), expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS }- : { kind: 'path', key: pathKey(action.path), expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS });+ this.approvals.push({ ...approvalOf(action), expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS });if (this.approvals.length > MAX_APPROVALS) this.approvals.splice(0, this.approvals.length - MAX_APPROVALS);}authorize(action: ExecutorAction): ExecutorGateDecision {- if (this.mode === 'full') return { ok: true };+ if (this.mode === 'full') return { ok: true, elevated: true };+ // 抓取网页:本机用户批准过这个地址就放开内网。公网样式的域名也可能解析到内网(公司内网域名),+ // 只看地址文本判定为不必问,但抓取时会按 DNS 结果被拦下。+ if (action.kind === 'fetch' && this.consume(action)) return { ok: true, elevated: true };if (!this.requiresApproval(action)) return { ok: true };- if (this.consume(action)) return { ok: true };+ if (this.consume(action)) return { ok: true, elevated: true };return {ok: false,reason: action.kind === 'exec'? 'This command needs the user\'s confirmation on the computer where the task runs, and it was not confirmed.'- : `Access to ${action.path} needs the user's confirmation on the computer where the task runs, and it was not confirmed.`,+ : action.kind === 'fetch'+ ? `Fetching ${action.url} needs the user's confirmation on the computer where the task runs, and it was not confirmed.`+ : `Access to ${action.path} needs the user's confirmation on the computer where the task runs, and it was not confirmed.`,};}private requiresApproval(action: ExecutorAction): boolean {+ if (action.kind === 'fetch') {+ // 只读的网络请求,计划模式也可以;本机、内网与 metadata 地址按本机任务的同一判定必问。+ return reviewAction({ kind: 'network', target: action.url }, this.workspace.allRoots()) === 'prompt-each-time';+ }if (action.kind === 'exec') {const verdict = classifyShellCommand(action.command, this.workspace.allRoots(), {cwd: action.cwd,@@ -127,11 +158,10 @@ export class ExecutorGate {private consume(action: ExecutorAction): boolean {this.prune();- const kind = action.kind === 'exec' ? 'exec' : 'path';- const key = action.kind === 'exec' ? execKey(action.command, action.cwd) : pathKey(action.path);+ const { kind, key } = approvalOf(action);const index = this.approvals.findIndex((approval) => approval.kind === kind && approval.key === key);if (index < 0) return false;- if (kind === 'exec') this.approvals.splice(index, 1);+ if (kind !== 'path') this.approvals.splice(index, 1);return true;}diff --git a/apps/desktop/src/main/remote-agent/executor/webFetch.ts b/apps/desktop/src/main/remote-agent/executor/webFetch.tsnew file mode 100644index 0000000000..ab60ac5177--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/webFetch.ts@@ -0,0 +1,345 @@+/**+ * 远程 Agent 执行器的 WebFetch(控制端)。+ *+ * 供应商分享的受邀者任务里,Claude Code 自带的 WebFetch 会从分享者的网络发出请求、能访问分享者+ * 的内网,已对受邀者关闭;这里改在本机(受邀者电脑)用本机网络抓取:+ * - 经 Desktop 的出站通道(系统代理),不带 Cindy 的 Cookie 与登录态;按 DNS 解析结果拦下内网+ * 地址,只有本机用户批准过(或任务是全权)时才放行;+ * - 只发一跳:同一网站内的跳转最多跟 5 次,跳到其它网站时把新地址交还给 Agent,由它重新调用+ * (重新过权限上限与本机确认);+ * - 只返回文本:HTML 转成纯文本(保留标题、链接、列表、代码块),其它文本类原样返回;长页面分段读取。+ */+import { SsrFBlockedError } from '@cindy/browser-control-runtime/ssrf-runtime';++import { textResult, type ToolResult } from './files';++/** Desktop 出站通道(maker-host/outbound-fetch 的 guardedOutboundFetch)。 */+export type GuardedFetch = (+ url: string,+ init: RequestInit,+ beforeDispatch: () => void | Promise<void>,+ approval?: { targetUrl: string; allowHttp?: boolean; allowPrivateNetwork?: boolean },+) => Promise<{ response: Response; release: () => Promise<void> }>;++const TIMEOUT_MS = 30_000;+const MAX_REDIRECTS = 5;+/** 读取的响应体上限;超出部分丢弃并在结果里注明。 */+const MAX_BODY_BYTES = 2 * 1024 * 1024;+/** 每次返回的字符数,更长的页面用 start_index 分段读。 */+export const WEB_FETCH_PAGE_CHARS = 40_000;+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);++export interface WebFetchRequest {+ url: URL;+ startIndex: number;+ /** 本机用户批准过这个地址(或全权):内网地址与 http 可用。 */+ allowPrivateNetwork: boolean;+ signal?: AbortSignal;+}++/** 同一网站:主机名去掉开头的 www. 后相同(端口也要相同)。 */+function sameSite(a: URL, b: URL): boolean {+ const host = (url: URL) => url.hostname.replace(/^www\./i, '').toLowerCase();+ return host(a) === host(b) && a.port === b.port;+}++/** 未经批准的地址一律用 https(与 Claude Code 自带 WebFetch 一致)。 */+function upgraded(url: URL, allowHttp: boolean): URL {+ if (allowHttp || url.protocol !== 'http:') return url;+ const next = new URL(url.href);+ next.protocol = 'https:';+ return next;+}++async function readBody(response: Response): Promise<{ bytes: Buffer; cut: boolean }> {+ const reader = response.body?.getReader();+ if (!reader) return { bytes: Buffer.alloc(0), cut: false };+ const chunks: Buffer[] = [];+ let size = 0;+ let cut = false;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ const room = MAX_BODY_BYTES - size;+ if (value.byteLength > room) {+ chunks.push(Buffer.from(value.subarray(0, room)));+ size += room;+ cut = true;+ break;+ }+ chunks.push(Buffer.from(value));+ size += value.byteLength;+ }+ } finally {+ reader.releaseLock();+ }+ return { bytes: Buffer.concat(chunks, size), cut };+}++function mediaType(contentType: string | null): { type: string; charset: string | null } {+ if (!contentType) return { type: '', charset: null };+ const [type, ...params] = contentType.split(';');+ const charset = params+ .map((param) => /^\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(param)?.[1] ?? null)+ .find((value) => value !== null) ?? null;+ return { type: type.trim().toLowerCase(), charset };+}++function isTextType(type: string): boolean {+ return type.startsWith('text/')+ || /^application\/(?:json|xml|javascript|ecmascript|x-javascript|x-sh|x-yaml|yaml|toml|x-www-form-urlencoded)$/.test(type)+ || /\+(?:json|xml)$/.test(type);+}++function decode(bytes: Buffer, charset: string | null): string {+ try {+ return new TextDecoder(charset ?? 'utf-8').decode(bytes);+ } catch {+ return new TextDecoder('utf-8').decode(bytes);+ }+}++/** HTML 没在响应头里写编码时,从开头的 <meta> 里找。 */+function htmlCharset(bytes: Buffer): string | null {+ const head = bytes.subarray(0, 4096).toString('latin1');+ return /<meta[^>]+charset\s*=\s*["']?([\w-]+)/i.exec(head)?.[1] ?? null;+}++// ─── HTML → 文本 ───────────────────────────────────────────────++const NAMED_ENTITIES: Record<string, string> = {+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', ensp: ' ', emsp: ' ', thinsp: ' ',+ copy: '©', reg: '®', trade: '™', hellip: '…', mdash: '—', ndash: '–', minus: '−',+ lsquo: '‘', rsquo: '’', sbquo: '‚', ldquo: '“', rdquo: '”', bdquo: '„', laquo: '«', raquo: '»',+ bull: '•', middot: '·', times: '×', divide: '÷', plusmn: '±', deg: '°', micro: 'µ', para: '¶',+ sect: '§', euro: '€', pound: '£', yen: '¥', cent: '¢', larr: '←', rarr: '→', uarr: '↑', darr: '↓',+ harr: '↔', le: '≤', ge: '≥', ne: '≠', asymp: '≈', infin: '∞', frac12: '½', frac14: '¼', frac34: '¾',+ szlig: 'ß', oslash: 'ø', Oslash: 'Ø', aelig: 'æ', AElig: 'Æ', eth: 'ð', ETH: 'Ð', thorn: 'þ', THORN: 'Þ',+};++/** 带重音的拉丁字母(é Ü ç …):字母加组合附加符号。 */+const ACCENT_MARKS: Record<string, string> = {+ acute: '\u0301', grave: '\u0300', circ: '\u0302', uml: '\u0308', tilde: '\u0303', ring: '\u030a', cedil: '\u0327',+};++function namedEntity(name: string): string | undefined {+ const known = NAMED_ENTITIES[name];+ if (known !== undefined) return known;+ const accented = /^([A-Za-z])(acute|grave|circ|uml|tilde|ring|cedil)$/.exec(name);+ if (accented) return (accented[1] + ACCENT_MARKS[accented[2]]).normalize('NFC');+ // & < 之类的大写写法。+ return /^(?:AMP|LT|GT|QUOT)$/.test(name) ? NAMED_ENTITIES[name.toLowerCase()] : undefined;+}++function decodeEntities(text: string): string {+ return text.replace(/&(#\d{1,7}|#x[0-9a-f]{1,6}|[a-z][a-z0-9]{1,31});/gi, (whole, body: string) => {+ if (body[0] === '#') {+ const code = body[1] === 'x' || body[1] === 'X' ? Number.parseInt(body.slice(2), 16) : Number.parseInt(body.slice(1), 10);+ // 控制字符(换行、制表除外)与非法码点不还原。+ if (!Number.isFinite(code) || code > 0x10ffff || (code < 0x20 && code !== 0x0a && code !== 0x09)) return '';+ return String.fromCodePoint(code);+ }+ return namedEntity(body) ?? whole;+ });+}++function attribute(tag: string, name: string): string | null {+ const match = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag);+ return match ? decodeEntities(match[1] ?? match[2] ?? match[3] ?? '') : null;+}++function stripTags(html: string): string {+ return decodeEntities(html.replace(/<[^>]*>/g, ''));+}++// 链接与代码块用控制字符做占位,逐段线性处理,避免对未闭合标签的回溯。+const LINK_OPEN = '\u0001';+const LINK_HREF_END = '\u0002';+const LINK_CLOSE = '\u0003';+const PRE_MARK = '\u0004';++const BLOCK_TAGS = 'p|div|section|article|header|footer|nav|main|aside|table|thead|tbody|tfoot|tr|ul|ol|dl|dt|dd|blockquote|figure|figcaption|form|fieldset|details|summary|address|center';++/** HTML 转成纯文本:标题写成 #,列表写成 -,链接写成 [文字](地址),<pre> 写成代码块。 */+export function htmlToText(html: string, baseUrl?: URL): { title: string | null; text: string } {+ let source = html+ .replace(/<!--[\s\S]*?-->/g, ' ')+ .replace(/<(script|style|noscript|template|svg|iframe|object|canvas|math)\b[\s\S]*?<\/\1\s*>/gi, ' ');+ const titleMatch = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(source);+ const title = titleMatch ? stripTags(titleMatch[1]).replace(/\s+/g, ' ').trim() || null : null;+ // 标题单独返回;没有 <head> 的页面里 <title> 也不进正文。+ source = source+ .replace(/<head\b[\s\S]*?<\/head\s*>/gi, ' ')+ .replace(/<title\b[^>]*>[\s\S]*?<\/title\s*>/gi, ' ');++ // 代码块先取出(保留原样的换行与缩进),占位放进独立的一行。+ const blocks: string[] = [];+ source = source.replace(/<pre\b[^>]*>([\s\S]*?)<\/pre\s*>/gi, (_whole, inner: string) => {+ blocks.push(stripTags(inner.replace(/<br\s*\/?>/gi, '\n')).replace(/^\n+|\s+$/g, ''));+ return `<div>${PRE_MARK}${blocks.length - 1}${PRE_MARK}</div>`;+ });++ source = source+ .replace(/\s+/g, ' ')+ .replace(/<a\b[^>]*>/gi, (tag) => {+ const href = attribute(tag, 'href');+ if (!href || /^\s*(?:javascript|data|vbscript):/i.test(href) || href.startsWith('#')) return LINK_OPEN + LINK_HREF_END;+ let resolved = href.trim();+ try {+ resolved = new URL(resolved, baseUrl).href;+ } catch {+ // 无法解析时保留原样。+ }+ return `${LINK_OPEN}${resolved.replace(/[\u0001-\u0004]/g, '')}${LINK_HREF_END}`;+ })+ .replace(/<\/a\s*>/gi, LINK_CLOSE)+ .replace(/<h([1-6])\b[^>]*>/gi, (_tag, level: string) => `\n\n${'#'.repeat(Number(level))} `)+ .replace(/<\/h[1-6]\s*>/gi, '\n\n')+ .replace(/<li\b[^>]*>/gi, '\n- ')+ .replace(/<br\s*\/?>/gi, '\n')+ .replace(/<hr\b[^>]*>/gi, '\n\n---\n\n')+ .replace(/<\/(?:td|th)\s*>/gi, ' | ')+ .replace(new RegExp(`</?(?:${BLOCK_TAGS})\\b[^>]*>`, 'gi'), '\n')+ .replace(/<img\b[^>]*>/gi, (tag) => {+ const alt = attribute(tag, 'alt')?.trim();+ return alt ? ` [image: ${alt}] ` : ' ';+ });+ let text = stripTags(source)+ .replace(new RegExp(`${LINK_OPEN}([^${LINK_HREF_END}]*)${LINK_HREF_END}([^${LINK_OPEN}${LINK_CLOSE}]*)${LINK_CLOSE}`, 'g'),+ (_whole, href: string, label: string) => {+ const shown = label.trim();+ if (!href) return label;+ return shown ? `[${shown}](${href})` : href;+ })+ // 没有闭合的链接:丢掉地址,只留文字。+ .replace(new RegExp(`${LINK_OPEN}[^${LINK_HREF_END}]*${LINK_HREF_END}`, 'g'), '')+ .replace(/[\u0001-\u0003]/g, '');+ text = text+ .split('\n')+ .map((line) => line.replace(/[ \t]+/g, ' ').trim())+ .join('\n')+ .replace(/\n{3,}/g, '\n\n')+ .trim()+ .replace(new RegExp(`${PRE_MARK}(\\d+)${PRE_MARK}`, 'g'), (_whole, index: string) => `\`\`\`\n${blocks[Number(index)] ?? ''}\n\`\`\``);+ return { title, text };+}++// ─── 抓取 ──────────────────────────────────────────────────────++function pageOf(text: string, startIndex: number): { body: string; note: string } {+ const total = text.length;+ if (startIndex >= total && total > 0) {+ return { body: '', note: `start_index ${startIndex} is past the end of the page (${total} characters).` };+ }+ const end = Math.min(total, startIndex + WEB_FETCH_PAGE_CHARS);+ const body = text.slice(startIndex, end);+ if (startIndex === 0 && end === total) return { body, note: '' };+ const more = end < total ? ` Call WebFetch again with start_index=${end} to read more.` : '';+ return { body, note: `Characters ${startIndex}–${end} of ${total}.${more}` };+}++/** 抓取一个网页并返回文本。网络与内容问题以错误结果返回,不抛出。 */+export async function fetchWebPage(fetchImpl: GuardedFetch, request: WebFetchRequest): Promise<ToolResult> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);+ timer.unref?.();+ const signal = request.signal ? AbortSignal.any([controller.signal, request.signal]) : controller.signal;+ const allowHttp = request.allowPrivateNetwork;+ const original = request.url;+ let current = upgraded(original, allowHttp);+ const visited = new Set<string>();+ try {+ for (let hop = 0; ; hop += 1) {+ visited.add(current.href);+ const { response, release } = await fetchImpl(+ current.href,+ {+ method: 'GET',+ redirect: 'manual',+ credentials: 'omit',+ signal,+ headers: {+ accept: 'text/html,application/xhtml+xml,text/plain;q=0.9,application/json;q=0.8,*/*;q=0.5',+ 'user-agent': 'Mozilla/5.0 (compatible; Cindy WebFetch)',+ },+ },+ () => signal.throwIfAborted(),+ { targetUrl: current.href, allowHttp, allowPrivateNetwork: request.allowPrivateNetwork },+ );+ try {+ if (REDIRECT_STATUSES.has(response.status)) {+ const location = response.headers.get('location');+ if (!location) return textResult(`${current.href} returned HTTP ${response.status} without a redirect address.`, true);+ let next: URL;+ try {+ next = new URL(location, current);+ } catch {+ return textResult(`${current.href} redirected to an invalid address: ${location}`, true);+ }+ if (next.protocol !== 'http:' && next.protocol !== 'https:') {+ return textResult(`${current.href} redirected to an unsupported address: ${next.href}`, true);+ }+ if (!sameSite(current, next) || next.username || next.password) {+ return textResult([+ `The URL redirected to a different host: ${next.href}`,+ 'It was not followed. Call WebFetch again with this URL if you want its content.',+ ].join('\n'));+ }+ next = upgraded(next, allowHttp);+ if (visited.has(next.href)) return textResult(`${original.href} redirects in a loop.`, true);+ if (hop + 1 > MAX_REDIRECTS) return textResult(`${original.href} redirected more than ${MAX_REDIRECTS} times.`, true);+ current = next;+ continue;+ }+ if (!response.ok) {+ return textResult(`${current.href} returned HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}.`, true);+ }+ const { type, charset } = mediaType(response.headers.get('content-type'));+ const isHtml = type === 'text/html' || type === 'application/xhtml+xml';+ if (type && !isHtml && !isTextType(type)) {+ return textResult(`${current.href} is ${type}, not a text page. WebFetch returns text only; download it with a command if you need the file.`, true);+ }+ const { bytes, cut } = await readBody(response);+ const sniffedHtml = !type && /^\s*(?:<!doctype html|<html|<head|<body)/i.test(bytes.subarray(0, 512).toString('latin1'));+ let title: string | null = null;+ let text: string;+ if (isHtml || sniffedHtml) {+ const converted = htmlToText(decode(bytes, charset ?? htmlCharset(bytes)), current);+ title = converted.title;+ text = converted.text;+ } else {+ text = decode(bytes, charset);+ }+ const page = pageOf(text, request.startIndex);+ const header = [+ `URL: ${current.href}`,+ ...(title ? [`Title: ${title}`] : []),+ ...(cut ? [`Only the first ${MAX_BODY_BYTES / (1024 * 1024)} MB of the response was read.`] : []),+ ...(page.note ? [page.note] : []),+ ];+ return textResult(`${header.join('\n')}\n\n${page.body || '(The page has no text.)'}`);+ } finally {+ try {+ await response.body?.cancel().catch(() => undefined);+ } finally {+ await release();+ }+ }+ }+ } catch (error) {+ if (error instanceof SsrFBlockedError) {+ return textResult([+ `${current.href} is on the local or a private network.`,+ "Fetching it needs the user's confirmation on the computer where the task runs.",+ ].join(' '), true);+ }+ if (controller.signal.aborted && !request.signal?.aborted) {+ return textResult(`Fetching ${current.href} timed out after ${TIMEOUT_MS / 1000} seconds.`, true);+ }+ if (request.signal?.aborted) return textResult('The fetch was cancelled.', true);+ return textResult(`Could not fetch ${current.href}: ${(error as Error)?.message ?? String(error)}`, true);+ } finally {+ clearTimeout(timer);+ }+}diff --git a/apps/desktop/src/renderer/features/provider-share/ProviderShareApproveDialog.tsx b/apps/desktop/src/renderer/features/provider-share/ProviderShareApproveDialog.tsxindex 396dc466e2..fff1207fab 100644--- a/apps/desktop/src/renderer/features/provider-share/ProviderShareApproveDialog.tsx+++ b/apps/desktop/src/renderer/features/provider-share/ProviderShareApproveDialog.tsx@@ -6,6 +6,7 @@ import { useState } from 'react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';+import { useProviders } from '@/hooks/useProviders';import { toast } from '@/lib/toast';import { extractIpcError, mapIpcErrorToI18nKey } from '@/utils/ipcError';@@ -15,7 +16,7 @@ import {ProviderShareDialogTitle,ProviderSharePairingCode,} from './ProviderShareDialog';-import type { ProviderSharePendingRequest } from './providerShareFormat';+import { sharesClaudeLoginEmail, type ProviderSharePendingRequest } from './providerShareFormat';import { removeProviderSharePendingRequest } from './providerShareStore';import { ShareAvatar } from './ShareAvatar';import { useShareTimeFormat } from './useShareTimeFormat';@@ -34,6 +35,8 @@ export function ProviderShareApproveDialog({const { request, share } = item;const name = request.displayName;const provider = share.providerLabel;+ const { providers } = useProviders();+ const claudeEmail = sharesClaudeLoginEmail(providers.find((view) => view.id === share.providerId));const decide = async (action: 'approve' | 'reject') => {if (busy) return;@@ -91,6 +94,7 @@ export function ProviderShareApproveDialog({</div><div className="mt-3.5 flex flex-col gap-1 rounded-lg bg-[var(--surface)] px-3 py-2.5 text-12 leading-[1.5] text-[var(--text-secondary)]"><p>{t('providerShare.approve.callout', { name, provider })}</p>+ {claudeEmail ? <p>{t('providerShare.approve.calloutClaudeEmail', { name })}</p> : null}<p>{t('providerShare.approve.calloutUnknown')}</p></div><ProviderShareDialogFooter>diff --git a/apps/desktop/src/renderer/features/provider-share/__tests__/providerShareFormat.test.ts b/apps/desktop/src/renderer/features/provider-share/__tests__/providerShareFormat.test.tsindex e735219256..6b9fabf10f 100644--- a/apps/desktop/src/renderer/features/provider-share/__tests__/providerShareFormat.test.ts+++ b/apps/desktop/src/renderer/features/provider-share/__tests__/providerShareFormat.test.ts@@ -15,6 +15,7 @@ import {providerShareJoinErrorKind,shareAvatarInitial,shareLinkRemainingMs,+ sharesClaudeLoginEmail,summarizeShareUsage,} from '../providerShareFormat';import { PROVIDER_SHARE_MANAGE_PARAM, providerShareManagePath } from '../providerShareNavigation';@@ -177,3 +178,14 @@ describe('providerShareFormat', () => {expect(url.searchParams.get(PROVIDER_SHARE_MANAGE_PARAM)).toBe('custom:my provider');});});++describe('sharesClaudeLoginEmail', () => {+ it('is true only for Claude subscription logins, whose email Claude Code hands to the model', () => {+ expect(sharesClaudeLoginEmail({ id: 'anthropic', source: 'builtin', auth: { method: 'oauth' } })).toBe(true);+ expect(sharesClaudeLoginEmail({ id: 'claude-work', source: 'user', auth: { method: 'oauth', native: 'claude' } })).toBe(true);+ expect(sharesClaudeLoginEmail({ id: 'openai', source: 'builtin', auth: { method: 'oauth', native: 'codex' } })).toBe(false);+ expect(sharesClaudeLoginEmail({ id: 'anthropic-key', source: 'user', auth: { method: 'apiKey' } })).toBe(false);+ expect(sharesClaudeLoginEmail({ id: 'anthropic', source: 'organization', auth: { method: 'apiKey' } })).toBe(false);+ expect(sharesClaudeLoginEmail(undefined)).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/features/provider-share/providerShareFormat.ts b/apps/desktop/src/renderer/features/provider-share/providerShareFormat.tsindex d432ff3a7e..3a9b55b461 100644--- a/apps/desktop/src/renderer/features/provider-share/providerShareFormat.ts+++ b/apps/desktop/src/renderer/features/provider-share/providerShareFormat.ts@@ -3,6 +3,7 @@* 不读 window、不碰 i18n,便于单测。*/import type { ProviderShareReceived, ProviderShareRequestItem } from '@cindy/device-link';+import type { ProviderView } from '@cindy/model-providers';import { formatCompactTokens, formatTurnCostMoney } from '@/lib/usageFormat';@@ -28,6 +29,15 @@ export function providerShareGate(input: {return input.invocationEnabled ? 'on' : 'invocation-off';}+/**+ * 分享的是 Claude 订阅登录:Claude Code 会把登录账号的邮箱交给模型,受邀者的 Agent 能看到。+ * 挡不住(只有改掉整条连接方式的开关),审批时告诉分享者(2026-10-10 用户裁决)。+ */+export function sharesClaudeLoginEmail(provider: Pick<ProviderView, 'id' | 'source' | 'auth'> | undefined): boolean {+ if (!provider || provider.auth.method !== 'oauth') return false;+ return provider.auth.native === 'claude' || (provider.source === 'builtin' && provider.id === 'anthropic');+}+/** 任务记录里「Agent 在某个分享者的电脑上」的设备 id(与 main 的 providerShareAgentDeviceId 同构)。 */export function providerShareAgentDeviceId(shareId: string): string {return `${PROVIDER_SHARE_AGENT_DEVICE_PREFIX}${shareId}`;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 8e133cdbb5..98f02d4e12 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -292,6 +292,7 @@"requestedAt": "Requested {{time}} with your share link","pairingHint": "Before approving, you can ask them over the channel you sent the link through: “What pairing code do you see?” Approve if it matches.","callout": "Once approved, {{name}} can use {{provider}} models in their own sessions. The Agent runs on this computer and usage counts toward your {{provider}}. You can pause or remove access anytime in “Share {{provider}}”.",+ "calloutClaudeEmail": "While {{name}} uses it, the Agent can see the email address you sign in to Claude with.","calloutUnknown": "If you don’t recognize this person, decline; the link stops working once declined.","approve": "Approve Sharing","reject": "Decline Request",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 9ee64b4fc2..95dae92816 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -290,6 +290,7 @@"requestedAt": "共有リンクから申請: {{time}}","pairingHint": "承認する前に、リンクを送ったのと同じ方法で「表示されているペアリングコードは?」と相手に確認できます。一致したら承認してください。","callout": "承認すると、{{name}} は自分のセッションで {{provider}} のモデルを使えます。Agent はこのパソコンで実行され、使用量はあなたの {{provider}} に計上されます。「{{provider}} を共有」からいつでも停止または削除できます。",+ "calloutClaudeEmail": "{{name}} が使用している間、Agent はあなたが Claude へのログインに使っているメールアドレスを確認できます。","calloutUnknown": "申請者に心当たりがない場合は拒否してください。拒否するとこのリンクは無効になります。","approve": "共有を承認","reject": "申請を拒否",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 8e20602e04..06bb72deb6 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -290,6 +290,7 @@"requestedAt": "{{time}} 공유 링크로 요청함","pairingHint": "승인하기 전에 링크를 보낸 곳에서 “보이는 페어링 코드가 뭐예요?”라고 물어볼 수 있습니다. 일치하면 승인하세요.","callout": "승인하면 {{name}}님이 자신의 세션에서 {{provider}} 모델을 사용할 수 있습니다. Agent는 이 컴퓨터에서 실행되고 사용량은 내 {{provider}}에 계산됩니다. ‘{{provider}} 공유’에서 언제든지 일시 중지하거나 삭제할 수 있습니다.",+ "calloutClaudeEmail": "{{name}}님이 사용하는 동안 Agent가 Claude 로그인에 쓰는 내 이메일 주소를 볼 수 있습니다.","calloutUnknown": "요청한 사람을 모른다면 거절하세요. 거절하면 이 링크는 더 이상 사용할 수 없습니다.","approve": "공유 승인","reject": "요청 거절",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 36b0e287ff..bb3101b939 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -290,6 +290,7 @@"requestedAt": "{{time}}通过你的分享链接申请","pairingHint": "同意前可以通过发链接的渠道问对方一句:「你看到的配对码是多少?」一致再同意。","callout": "同意后,{{name}} 可以在自己的任务里使用 {{provider}} 的模型。Agent 在这台电脑上运行,用量计入你的 {{provider}}。你可以随时在「分享 {{provider}}」里关闭或删除。",+ "calloutClaudeEmail": "{{name}} 使用时,Agent 能看到你登录 Claude 用的邮箱。","calloutUnknown": "如果你不认识申请人,请拒绝;拒绝后这条链接作废。","approve": "同意分享","reject": "拒绝申请",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 090ff3f8d0..93afcf865e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -290,6 +290,7 @@"requestedAt": "{{time}}透過你的分享連結申請","pairingHint": "同意前可以透過傳連結的管道問對方一句:「你看到的配對碼是多少?」一致再同意。","callout": "同意後,{{name}} 可以在自己的任務裡使用 {{provider}} 的模型。Agent 在這臺電腦上執行,用量計入你的 {{provider}}。你可以隨時在「分享 {{provider}}」裡關閉或刪除。",+ "calloutClaudeEmail": "{{name}} 使用時,Agent 能看到你登入 Claude 用的電子郵件地址。","calloutUnknown": "如果你不認識申請人,請拒絕;拒絕後這條連結作廢。","approve": "同意分享","reject": "拒絕申請",diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex b2d1cdd5ae..8d6307e5e8 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -649,7 +649,9 @@ 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);+ B 上受邀者会话的 Agent 自带工具按白名单开放(产品规则 §9 第 5 条,不改 wire);受邀者电脑上的 `cindy_exec` 在任务的+ Agent 位置是 `share:` 时为 Claude Code 追加 `WebFetch`(在受邀者电脑抓取,tools/list 追加项):旧版受邀者不列,受邀者就没有+ WebFetch;旧版分享者上它与自带 WebFetch 并存。两种组合都不报错,也不改 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 c836c9bdf6..9fe52b1779 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -83,6 +83,8 @@提交后受邀者看到本次申请的**配对码**(见 §6.1),等待分享者同意。4. **分享者审批**:分享者在供应商所在的电脑上收到弹窗(应用在后台时同时发系统通知),展示申请人的昵称和头像(见 §6)、申请的供应商与同一个配对码,选择「同意分享」或「拒绝」。+ 分享的是 Claude 订阅登录时,弹窗另写一句:受邀者使用时,Agent 能看到分享者登录 Claude 用的邮箱+ (Claude Code 自己会把它交给模型,Cindy 目前挡不住;2026-10-10 裁决先告知分享者)。5. **建立**:同意后分享立即生效,受邀者收到通知,模型列表里出现该供应商。### 4.2 链接与申请的状态@@ -234,10 +236,13 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):程序以分享者的系统用户在分享者电脑上运行,受邀者会话只开放不作用于分享者电脑、分享者电脑上的其他会话和分享者账号的自带工具;文件与命令仍回到受邀者电脑执行。Agent 升级新增的工具不会自动开放,须评估后加入白名单。因此给其他会话发消息、发布到分享者账号(如 Claude 的 Artifact、云端定时任务、- 设计项目)、在分享者电脑上读文件或跑命令都不可用;WebFetch 会从分享者的网络发出请求、能访问分享者- 的内网,对受邀者关闭;联网搜索由模型服务方执行,保持可用。同账号远程供应商不受影响。+ 设计项目)、在分享者电脑上读文件或跑命令都不可用;自带的 WebFetch 会从分享者的网络发出请求、能访问+ 分享者的内网,对受邀者关闭,Claude Code 的 WebFetch 改由受邀者电脑提供、用受邀者的网络抓取(同日补充;+ 受邀者电脑上的 Cindy 较旧时没有):本机、内网与云 metadata 地址须受邀者在确认卡上批准,跳到其他网站+ 时交回 Agent 重新调用;联网搜索由模型服务方执行,保持可用。同账号远程供应商不受影响。实现:Claude Code 用 SDK `tools` 白名单,Codex 按功能清单关闭白名单之外的功能,Pi 只放行 Cindy- 扩展注册的工具(`packages/maker-core/src/agents/{shared/device-hosted,codex/device-hosted-guest,pi/cindy-bridge-source}.ts`)。+ 扩展注册的工具(`packages/maker-core/src/agents/{shared/device-hosted,codex/device-hosted-guest,pi/cindy-bridge-source}.ts`);+ 受邀者电脑上的 WebFetch 见 `apps/desktop/src/main/remote-agent/executor/webFetch.ts`。6. **受邀者隐私**:申请前明确告知对话与文件内容会经过分享者的电脑,并保存在实际运行任务的那台电脑上(有供应商组时可能是分享者安排的其他电脑);分享被删除或受邀者退出后,分享者电脑清理该受邀者的 Agent会话记录与镜像文件,并请接过它任务的组内电脑清理([供应商组](provider-groups.md) §4)。diff --git a/docs/provider-sharing-implementation-plan.md b/docs/provider-sharing-implementation-plan.mdindex cf5c4259e7..44761dd1bc 100644--- a/docs/provider-sharing-implementation-plan.md+++ b/docs/provider-sharing-implementation-plan.md@@ -138,7 +138,9 @@ P0 拆成两部分。受邀者身份由 `RemoteAgentHostDeps.controllerTrust`| C0-12 | 真实验证 | 用真实 Claude Code 验证:受邀者项目里的 hooks、`env`、`apiKeyHelper`、`!` 命令、`@` 外部引用、家目录 CLAUDE.md 都不生效(Windows 上 `claudeMdExcludes` 的路径写法需实测) |受邀者会话的 Agent 自带工具按白名单开放,WebFetch 对受邀者关闭、WebSearch 保留(2026-10-10 裁决,取代-2026-10-07「联网工具不单独处理」,见产品规则 §9 第 5 条)。+2026-10-07「联网工具不单独处理」,见产品规则 §9 第 5 条)。同日补充:Claude Code 受邀者的 WebFetch 改由受邀者电脑的+执行器提供、用受邀者的网络抓取(`apps/desktop/src/main/remote-agent/executor/webFetch.ts`);分享 Claude 订阅登录时,+审批弹窗告知分享者「受邀者的 Agent 能看到你登录 Claude 用的邮箱」。## 4. P1 同区域 MVPdiff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.tsindex 15b4b531ee..b22ff320ab 100644--- a/packages/maker-core/src/agents/index.ts+++ b/packages/maker-core/src/agents/index.ts@@ -122,7 +122,7 @@ export {export { toolAutoReviewAction } from './shared/auto-review-decision.js';export { AUTO_REVIEW_CONTINUATION_POLICY } from './shared/continuation-policy.js';export type { ReviewableAction } from './shared/auto-review.js';-export { classifyShellCommand } from './shared/auto-review.js';+export { classifyShellCommand, reviewAction } from './shared/auto-review.js';export type {ToolLoopReviewDecision,ToolLoopReviewer,diff --git a/packages/maker-core/src/agents/shared/device-hosted.test.ts b/packages/maker-core/src/agents/shared/device-hosted.test.tsindex e59687a8c5..c65bdee3b2 100644--- a/packages/maker-core/src/agents/shared/device-hosted.test.ts+++ b/packages/maker-core/src/agents/shared/device-hosted.test.ts@@ -8,6 +8,8 @@ import type { DeviceHostedSession } from '../base-agent.js';import {DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS,DEVICE_HOSTED_GUEST_CLAUDE_TOOLS,+ deviceHostedBuiltinToolName,+ deviceHostedClaudeNote,deviceHostedEnvironmentNote,deviceHostedGuestAgentDenial,deviceHostedGuestClaudeMdExcludes,@@ -256,4 +258,13 @@ describe('device-hosted guest Claude tools', () => {expect(deviceHostedGuestAgentDenial('Agent', undefined)).toBeNull();expect(deviceHostedGuestAgentDenial('WebSearch', { isolation: 'remote' })).toBeNull();});++ it('judges the WebFetch that runs on the guest computer like the built-in one, without promising it to the model', () => {+ expect(deviceHostedBuiltinToolName('mcp__cindy_exec__WebFetch')).toBe('WebFetch');+ expect(deviceHostedBuiltinToolName('mcp__cindy_exec__Bash')).toBe('Bash');+ expect(deviceHostedBuiltinToolName('mcp__cindy_exec__Monitor')).toBeNull();+ expect(deviceHostedBuiltinToolName('mcp__other__WebFetch')).toBeNull();+ // 受邀者电脑上的 Cindy 较旧时没有这个工具,说明里不提。+ expect(deviceHostedClaudeNote(hosted({ guest: true }), '/local')).not.toContain('WebFetch');+ });});diff --git a/packages/maker-core/src/agents/shared/device-hosted.ts b/packages/maker-core/src/agents/shared/device-hosted.tsindex c85369fe49..b05fef83c0 100644--- a/packages/maker-core/src/agents/shared/device-hosted.ts+++ b/packages/maker-core/src/agents/shared/device-hosted.ts@@ -102,6 +102,11 @@ export function deviceHostedPiMcpBridge(hosted: DeviceHostedSession): NonNullablexport const DEVICE_HOSTED_EXEC_MCP_SERVER = 'cindy_exec';/** 顶替的工具名(与自带工具同名)。 */export const DEVICE_HOSTED_EXEC_TOOL_NAMES = ['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'NotebookEdit'] as const;+/**+ * 只在受邀者会话里由任务所在电脑提供的顶替工具:自带的 WebFetch 对受邀者关闭,改在受邀者电脑上+ * 抓取。受邀者电脑上的 Cindy 较旧时不提供,所以不写进给模型的说明,只用于权限按自带工具判定。+ */+export const DEVICE_HOSTED_GUEST_EXEC_TOOL_NAMES = ['WebFetch'] as const;/** 设备托管时关掉的 Claude Code 自带工具:它们只能操作本机,项目不在这里。 */export const DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS = ['Bash', 'BashOutput', 'KillShell', 'Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit',@@ -114,7 +119,7 @@ export const DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS = [* 开放给受邀者。Agent 程序以本机用户的身份在本机运行,其余自带工具都直接作用于本机或本机* 用户:其他会话(ListAgents / SendMessage)、本机用户的 claude.ai 账号(Artifact、* RemoteTrigger、DesignSync 等)、本机文件与命令(Monitor、SendUserFile 等)、本机网络(WebFetch)。- * 文件与命令由 cindy_exec 回到受邀者电脑执行(MCP 工具不受 `tools` 限制)。+ * 文件、命令与 WebFetch 由 cindy_exec 回到受邀者电脑执行(MCP 工具不受 `tools` 限制)。*/export const DEVICE_HOSTED_GUEST_CLAUDE_TOOLS = [// 子代理。隔离选项另由 deviceHostedGuestAgentDenial 拦下。@@ -146,7 +151,10 @@ const EXEC_PREFIX = `mcp__${DEVICE_HOSTED_EXEC_MCP_SERVER}__`;export function deviceHostedBuiltinToolName(toolName: string): string | null {if (!toolName.startsWith(EXEC_PREFIX)) return null;const name = toolName.slice(EXEC_PREFIX.length);- return (DEVICE_HOSTED_EXEC_TOOL_NAMES as readonly string[]).includes(name) ? name : null;+ return (DEVICE_HOSTED_EXEC_TOOL_NAMES as readonly string[]).includes(name)+ || (DEVICE_HOSTED_GUEST_EXEC_TOOL_NAMES as readonly string[]).includes(name)+ ? name+ : null;}/** `Bash` → `mcp__cindy_exec__Bash`。 */