Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(provider-sharing): 支持当前任务内持续允许凭证操作
DavidShen487fa5208cb7
diff --git a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.tsindex e3d7554c4f..22fa9791fb 100644--- a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts@@ -33,7 +33,8 @@ vi.mock('node:child_process', async (importOriginal) => ({}));import { ExecServerRelay } from '../controller/execServerRelay';-import type { ExecutorAction, ExecutorGateDecision } from '../executor/gate';+import { RemoteExecutor } from '../executor/executor';+import { ExecutorGate, type ExecutorAction, type ExecutorGateDecision } from '../executor/gate';import { ExecutorWorkspace } from '../executor/workspace';let root: string;@@ -83,6 +84,32 @@ function setup() {}describe('exec-server relay with confirmation on this computer', () => {+ it('uses an explicit session consent for subsequent Codex credential requests', async () => {+ const workspace = new ExecutorWorkspace({ workingDir: root });+ const gate = new ExecutorGate(workspace, 'full', Date.now, { confirmCredentials: true });+ const confirm = vi.fn(async () => 'session' as const);+ const executor = new RemoteExecutor({ workspace, gate, rgPath: 'unused', confirm });+ const relay = new ExecServerRelay({+ codexPath: 'codex', cwd: root, workspace,+ authorize: (action) => executor.check(action),+ confirm: (action) => executor.confirm(action),+ push: async () => undefined,+ });+ try {+ relay.handle({ t: 'ws', connId: 'credentials', kind: 'open', path: '/ws/exec-server' });+ for (const [id, file] of [[1, '.env'], [2, '.env.production']] as const) {+ relay.handle({+ t: 'ws', connId: 'credentials', kind: 'message',+ data: JSON.stringify({ id, method: 'fs/readFile', params: { path: path.join(root, file) } }),+ });+ }+ await vi.waitFor(() => expect(spawned.lines.map((line) => JSON.parse(line).id)).toEqual([1, 2]));+ expect(confirm).toHaveBeenCalledTimes(1);+ } finally {+ relay.close();+ await executor.close();+ }+ });it('passes ordinary messages straight through', () => {const { send, sentIds, pending } = setup();send({ id: 1, method: 'fs/readFile', params: { path: path.join(root, 'a.txt') } });diff --git a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.tsindex 3ed3c8b333..98f6dd1572 100644--- a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts@@ -3,7 +3,7 @@ import os from 'node:os';import path from 'node:path';import { pathToFileURL } from 'node:url';-import { MAIN_OWNED_SEND_CONTEXT } from '@cindy/maker-core';+import { MAIN_OWNED_SEND_CONTEXT, type InteractionDecision } from '@cindy/maker-core';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import WebSocket from 'ws';@@ -17,6 +17,7 @@ import { EventLog, LineSplitter } from '../eventLog';import { ExecutorGate } from '../executor/gate';import { ExecutorWorkspace } from '../executor/workspace';import { createRunTunnel } from '../host/tunnel';+import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';import { decodeOpenPayload, decodeSendOptions, encodeSendOptions, isSafeProjectFilePath } from '../wire';let root: string;@@ -125,7 +126,7 @@ describe('tunnel', () => {});describe('confirmations raised on this computer', () => {- it('use the Agent confirmation channel and accept only a one-time allow', async () => {+ it('uses the Agent confirmation channel and offers an explicit credential grant for this task', async () => {let next = 0;const controller = createRemoteAgentHandle({client: {} as RemoteAgentRunClient,@@ -153,6 +154,7 @@ describe('confirmations raised on this computer', () => {input: { file_path: env },description: 'goes through the sharer',metadata: { hostOwnedConfirmation: 'shared_provider_credential' },+ suggestions: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL],}]);behavior = 'deny';expect(await controller.confirm(request)).toBe(false);@@ -161,6 +163,42 @@ describe('confirmations raised on this computer', () => {input: { command: 'cat .env' },});});++ it('accepts a session grant only when offered by this computer, and ignores late answers', async () => {+ const controller = createRemoteAgentHandle({+ client: {} as RemoteAgentRunClient,+ started: { id: 'sdk-1', agentKind: 'claude-code', model: 'm', shadowDir: '', methods: [], state: {} },+ workspace: new ExecutorWorkspace({ workingDir: root }),+ recordApproval: () => undefined,+ newId: () => 'req',+ dispose: async () => undefined,+ });+ const request = credentialConfirmation({ kind: 'read', path: path.join(root, '.env') }, 'shared credentials');+ controller.handle.setInteractionResolver(async () => ({+ kind: 'permission', behavior: 'allow', permissionUpdates: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL],+ }));+ expect(await controller.confirm(request)).toBe('session');+ expect(await controller.confirm({ ...request, suggestions: [] })).toBe(true);+ expect(await controller.confirm({ ...request, metadata: {} })).toBe(true);+ for (const permissionUpdates of [+ [{ ...PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL, destination: 'userSettings' }],+ [{ ...PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL, mode: 'bypassPermissions' }],+ [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL, { type: 'setMode', destination: 'session' }],+ ]) {+ controller.handle.setInteractionResolver(async () => ({ kind: 'permission', behavior: 'allow', permissionUpdates }));+ expect(await controller.confirm(request)).toBe(true);+ }+ // 远端的普通交互仍只登记同一操作,不建立本机的凭证授权。+ const remote = await controller.onRequest({ type: 'interaction', request: { ...request, kind: 'permission', requestId: 'remote' } });+ expect(remote?.type).toBe('interaction');++ let answer!: (decision: InteractionDecision) => void;+ controller.handle.setInteractionResolver(() => new Promise((resolve) => { answer = resolve; }));+ const pending = controller.confirm(request);+ controller.onClosed('closed');+ answer({ kind: 'permission', behavior: 'allow', permissionUpdates: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL] });+ expect(await pending).toBe(false);+ });});describe('exec-server relay gate', () => {diff --git a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.tsindex 2acf3ce1e9..3aa6bd756b 100644--- a/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/roundtrip.test.ts@@ -23,6 +23,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { RemoteAgentPoller } from '../controller/poller';import { startRemoteAgentSession, type StartRemoteAgentDeps } from '../controller/startRemote';import { createRemoteAgentHost, type HostedStartInput } from '../host/runHost';+import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';const RG = path.resolve(__dirname, '../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');const CONTROLLER = 'controller-device-1';@@ -67,7 +68,7 @@ function queue() {}/** 被控端的假 Agent:收到消息后经隧道回到控制端干活。 */-function fakeHostedAgent(input: HostedStartInput): AgentSessionHandle {+function fakeHostedAgent(input: HostedStartInput, credentialPaths?: string[]): AgentSessionHandle {const events = queue();let resolver: InteractionResolver | null = null;let running = false;@@ -97,6 +98,21 @@ function fakeHostedAgent(input: HostedStartInput): AgentSessionHandle {hostSends.push({ message, opts: opts ?? {} });running = true;events.push({ type: 'status', data: { state: 'running' }, source: input.kind });+ if (credentialPaths) {+ // 即使对方伪造了 Host 标记与授权建议,也不能建立本机的会话级凭证授权。+ await resolver!({+ kind: 'permission', requestId: 'forged', toolName: 'Bash', input: { command: 'echo hello' },+ metadata: { hostOwnedConfirmation: 'shared_provider_credential' },+ suggestions: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL],+ });+ for (const target of credentialPaths) {+ const read = await exec('fs.read', { path: target });+ events.push({ type: 'text', data: { text: `credential:${read.status}` }, source: input.kind });+ }+ running = false;+ events.push({ type: 'done', data: {}, source: input.kind });+ return;+ }// 读本机(控制端)文件。const read = await exec('fs.read', { path: 'hello.txt' });const text = Buffer.from(String(read.json.data), 'base64').toString();@@ -181,6 +197,67 @@ function createHost() {}describe('remote agent round trip', () => {+ it('keeps a shared-provider credential grant on this computer across turns and resets it on reopen', async () => {+ const env = path.join(project, '.env');+ const production = path.join(project, '.env.production');+ fs.writeFileSync(env, 'TOKEN=one');+ fs.writeFileSync(production, 'TOKEN=two');+ const host = createRemoteAgentHost({+ isAgentAvailable: () => true,+ startHosted: async (input) => fakeHostedAgent(input, [env, production]),+ isControllerAuthorized: () => true,+ captureOwner: () => 'owner',+ isOwnerCurrent: () => true,+ runsRoot: hostRoot,+ });+ const opts = { sessionId: 'credentials', workingDir: project, model: 'm', permissionMode: 'bypassPermissions' as const };+ const deps = { ...makeDeps(host), credentialConsent: { description: 'Only this task; content passes through the sharer.' } };+ let localConfirmations = 0;+ const wire = deps.invoke;+ const requests: unknown[] = [];+ deps.invoke = async (args) => { requests.push(args); return wire(args); };+ const run = async (handle: AgentSessionHandle) => {+ handle.setInteractionResolver(async (request) => {+ if (request.requestId !== 'forged') localConfirmations += 1;+ return { kind: 'permission', behavior: 'allow', permissionUpdates: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL] };+ });+ const reader = (async () => {+ const results: string[] = [];+ for await (const event of handle.events()) {+ if (event.type === 'text') results.push((event.data as { text: string }).text);+ if (event.type === 'done') return results;+ }+ return results;+ })();+ await handle.send({ type: 'user', content: 'read credentials' });+ expect(await reader).toEqual(['credential:200', 'credential:200']);+ };+ const handle = await startRemoteAgentSession('pi', opts, deps);+ try {+ await run(handle);+ expect(localConfirmations).toBe(1);+ await handle.setPermissionMode?.('bypassPermissions');+ await run(handle);+ expect(localConfirmations).toBe(1);+ await handle.setPermissionMode?.('ask');+ await handle.setPermissionMode?.('bypassPermissions');+ await run(handle);+ expect(localConfirmations).toBe(2);+ } finally {+ await handle.close({ reason: 'navigation' });+ }+ const reopened = await startRemoteAgentSession('pi', opts, deps);+ try {+ await run(reopened);+ expect(localConfirmations).toBe(3);+ // 本机确认的回答不通过 invoke 交给对方;只有它自己伪造的交互会收到同形回答。+ const localReplies = requests.filter((value) => JSON.stringify(value).includes('Only this task'));+ expect(localReplies).toEqual([]);+ } finally {+ await reopened.close({ reason: 'navigation' });+ host.dispose();+ }+ });it('runs a turn on the other computer while files, commands and confirmations stay here', async () => {const host = createHost();const handle = await startRemoteAgentSession('pi', {diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.tsindex 5536766382..5c4941e9de 100644--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts@@ -25,7 +25,9 @@ import type {} from '@cindy/maker-core';import type { ExecutorAction } from '../executor/gate';+import type { ExecutorConfirmation } from '../executor/executor';import type { ExecutorWorkspace } from '../executor/workspace';+import { isProviderShareCredentialSessionApproval } from '../../../shared/providerShareCredentialConsent';import { encodeSendOptions, encodeUserMessage } from '../wire';import { RemoteAgentRemoteError, type RemoteAgentRunClient } from './runClient';@@ -206,9 +208,9 @@ export interface RemoteAgentHandleController {onClosed(reason: string, message?: string): void;/*** 本机自己发起的确认(不是 Agent 发来的):走与 Agent 确认同一个确认卡通道,桌面、手机远控与 IM 都能- * 处理。只认这一次「允许」,不接受「总是允许」;交互还没接上或任务已结束时按拒绝处理。+ * 处理。只有本机提供了凭证授权建议的确认卡能返回会话级允许;交互还没接上或任务已结束时按拒绝处理。*/- confirm(request: LocalConfirmation): Promise<boolean>;+ confirm(request: LocalConfirmation): Promise<ExecutorConfirmation>;}export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandleController {@@ -443,7 +445,12 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandasync confirm(request) {if (!resolver || disposed) return false;const decision = await resolver({ ...request, kind: 'permission', requestId: deps.newId() });- return !disposed && decision.kind === 'permission' && decision.behavior === 'allow';+ if (disposed || decision.kind !== 'permission' || decision.behavior !== 'allow') return false;+ // 只能从本机生成的凭证确认卡建立授权;对方的 interaction 回包不经过这里。+ if (request.metadata?.hostOwnedConfirmation === 'shared_provider_credential'+ && isProviderShareCredentialSessionApproval(request.suggestions)+ && isProviderShareCredentialSessionApproval(decision.permissionUpdates)) return 'session';+ return true;},onClosed(reason, message) {// 'superseded':同一任务被重新打开、旧实例让位给新实例,不是错误,静默收起。diff --git a/apps/desktop/src/main/remote-agent/controller/service.ts b/apps/desktop/src/main/remote-agent/controller/service.tsindex 4bc0abb1dc..24ff36a8c0 100644--- a/apps/desktop/src/main/remote-agent/controller/service.ts+++ b/apps/desktop/src/main/remote-agent/controller/service.ts@@ -80,8 +80,10 @@ export interface DeviceAgentServiceDeps {/** 没有提供界面语言的说明时用的英文说明。 */const SHARED_PROVIDER_CREDENTIAL_NOTICE =- "This task uses a provider shared with you, so what the agent reads passes through the sharer's computer. "- + 'This involves a credential file, so it needs your confirmation.';+ "This task uses a shared provider, so what the agent reads passes through the sharer's computer or another computer they arrange. "+ + 'This may involve credentials, so it needs your confirmation. '+ + 'Always allow for this session skips further shared-provider credential confirmations in this task. '+ + 'Reopening the task or changing its permission mode requires confirmation again.';function mcpTargets(extra: PiExtraSpawnConfig | null): Map<string, LocalMcpTarget> {const targets = new Map<string, LocalMcpTarget>();diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.tsindex 18567ad90f..c7bfed7517 100644--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts@@ -18,6 +18,7 @@ import {} from '@cindy/device-link';import type { AgentEvent, AgentSessionHandle, StartSessionOptions } from '@cindy/maker-core';+import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../shared/providerShareCredentialConsent';import { RemoteExecutor, type ExecutorCaptureHooks } from '../executor/executor';import type { PdfTextExtractor } from '../executor/files';import { ExecutorGate, executorGateModeFor, type ExecutorAction } from '../executor/gate';@@ -182,7 +183,11 @@ export function shadowAliases(/** 凭证类操作的确认卡:用与 Agent 自带工具同名的工具显示本机路径或命令。 */export function credentialConfirmation(action: ExecutorAction, description: string): LocalConfirmation {- const base = { description, metadata: { hostOwnedConfirmation: 'shared_provider_credential' } };+ const base = {+ description,+ metadata: { hostOwnedConfirmation: 'shared_provider_credential' },+ suggestions: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL],+ };switch (action.kind) {case 'exec':return { ...base, toolName: 'Bash', input: { command: action.command } };@@ -387,10 +392,12 @@ export async function startRemoteAgentSession(newId: deps.newId,...(deps.groupSwitch?.takeNewRound ? { takeGroupNewRound: deps.groupSwitch.takeNewRound } : {}),onPermissionMode: (mode) => {+ if (permissionMode === mode) return;permissionMode = mode as typeof permissionMode;executor.setGateMode(executorGateModeFor(permissionMode, planMode));},onPlanMode: (enabled) => {+ if (planMode === enabled) return;planMode = enabled;executor.setGateMode(executorGateModeFor(permissionMode, planMode));},diff --git a/apps/desktop/src/main/remote-agent/credentials.ts b/apps/desktop/src/main/remote-agent/credentials.tsindex 52320236aa..95dd6bb825 100644--- a/apps/desktop/src/main/remote-agent/credentials.ts+++ b/apps/desktop/src/main/remote-agent/credentials.ts@@ -2,7 +2,8 @@* 供应商分享的受邀者任务里「凭证类」的判定(控制端)。** 受邀者任务的对话与 Agent 读到的文件内容会经过分享者的电脑。凭证类文件(密钥、.env、云与工具的- * 登录凭证)不论权限档,都要受邀者在本机确认后才发出:启动时不随项目说明同步,任务中读取时弹确认卡+ * 登录凭证)不论权限档,都要受邀者在本机确认后才发出:启动时不随项目说明同步,任务中读取时弹确认卡,+ * 可明确允许当前任务后续的凭证操作;关闭、重新打开任务或切换权限档后恢复确认* (docs/product-rules/provider-sharing.md §9 第 7 条)。** 规则沿用本机任务的凭证规则(isSensitiveCredentialPath),只有一处不同:Claude Code / Codex 配置目录里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 251757ef6a..5ddc7057bc 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@@ -5,7 +5,7 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { handleExecMcpRequest } from '../ccMcp';-import { RemoteExecutor } from '../executor';+import { RemoteExecutor, type ExecutorConfirmation } from '../executor';import { EXECUTOR_APPROVAL_TTL_MS, ExecutorGate, executorGateModeFor, type ExecutorAction } from '../gate';import type { PdfTextExtractor } from '../files';import { findWindowsGitBash, truncateOutput } from '../shell';@@ -580,7 +580,7 @@ describe('findWindowsGitBash', () => {describe('shared provider credentials', () => {function sharedExecutor(mode: ReturnType<typeof executorGateModeFor>,- confirm?: (action: ExecutorAction) => Promise<boolean>,+ confirm?: (action: ExecutorAction) => Promise<ExecutorConfirmation>,) {const workspace = new ExecutorWorkspace({ workingDir: project });const gate = new ExecutorGate(workspace, mode, Date.now, { confirmCredentials: true });@@ -661,6 +661,97 @@ describe('shared provider credentials', () => {expect(asked).toEqual([]);});+ it('remembers an explicit credential grant across different operations only in this task', async () => {+ const confirm = vi.fn(async (): Promise<ExecutorConfirmation> => 'session');+ const { executor, gate } = sharedExecutor('full', confirm);+ const env = path.join(project, '.env');+ const production = path.join(project, '.env.production');+ fs.writeFileSync(env, 'TOKEN=1');+ fs.writeFileSync(production, 'TOKEN=2');+ try {+ expect(text(await executor.callTool('Read', { file_path: env }))).toBe('1\tTOKEN=1');+ expect(text(await executor.callTool('Read', { file_path: production }))).toBe('1\tTOKEN=2');+ expect((await executor.callTool('Write', { file_path: env, content: 'TOKEN=3' })).isError).not.toBe(true);+ expect(fs.readFileSync(env, 'utf8')).toBe('TOKEN=3');+ expect(executor.check({ kind: 'exec', command: 'cat ~/.aws/credentials', cwd: project }).ok).toBe(true);+ expect(confirm).toHaveBeenCalledTimes(1);+ expect(gate.needsCredentialConsent({ kind: 'read', path: production })).toBe(false);+ // 另一任务(即便在相同目录)以及重新打开的任务,都有独立的上限。+ expect(sharedExecutor('full').gate.authorize({ kind: 'read', path: production }).ok).toBe(false);+ await executor.close();+ expect(executor.check({ kind: 'read', path: production }).ok).toBe(false);+ } finally {+ await executor.close();+ }+ });++ it('keeps allow-once commands one-time and revokes the session grant when the permission mode is set', async () => {+ const command: ExecutorAction = { kind: 'exec', command: 'cat .env', cwd: project };+ const confirm = vi.fn(async () => true);+ const { executor, gate } = sharedExecutor('full', confirm);+ expect(await executor.confirm(command)).toBe(true);+ expect(executor.check(command).ok).toBe(true);+ expect(executor.check(command).ok).toBe(false);+ expect(await executor.confirm(command)).toBe(true);+ expect(confirm).toHaveBeenCalledTimes(2);+ expect(executor.check(command).ok).toBe(true);++ gate.allowCredentialsForSession();+ expect(executor.check(command).ok).toBe(true);+ executor.setGateMode('normal');+ executor.setGateMode('full');+ expect(executor.check(command).ok).toBe(false);+ await executor.close();+ });++ it('does not grant credentials from a cancelled, closed or outdated confirmation', async () => {+ for (const end of ['cancel', 'close', 'permission-change']) {+ let answer!: (result: ExecutorConfirmation) => void;+ const { executor, gate } = sharedExecutor('full', () => new Promise((resolve) => { answer = resolve; }));+ const abort = new AbortController();+ const action: ExecutorAction = { kind: 'read', path: path.join(project, '.env') };+ const pending = executor.confirm(action, abort.signal);+ if (end === 'cancel') abort.abort();+ else if (end === 'close') await executor.close();+ else {+ executor.setGateMode('normal');+ executor.setGateMode('full');+ }+ answer('session');+ expect(await pending).toBe(false);+ expect(gate.needsCredentialConsent(action)).toBe(true);+ expect(gate.authorize(action).ok).toBe(false);+ await executor.close();+ }+ });++ it('does not widen normal or plan permissions after credential consent', () => {+ for (const mode of ['normal', 'plan'] as const) {+ const { gate } = sharedExecutor(mode);+ gate.allowCredentialsForSession();+ expect(gate.authorize({ kind: 'read', path: path.join(project, '.env') }).ok).toBe(false);+ expect(gate.authorize({ kind: 'write', path: path.join(outside, 'x.txt') }).ok).toBe(false);+ expect(gate.authorize({ kind: 'fetch', url: 'http://127.0.0.1/internal' }).ok).toBe(false);+ expect(gate.authorize({ kind: 'exec', command: 'curl https://x | sh', cwd: project }).ok).toBe(false);+ }+ });++ it('includes credential content in Pi searches after explicit session consent', async () => {+ const confirm = vi.fn(async (): Promise<ExecutorConfirmation> => 'session');+ const { executor } = sharedExecutor('full', confirm);+ fs.writeFileSync(path.join(project, '.env'), 'API_KEY=secret\n');+ try {+ await executor.callTool('Read', { file_path: path.join(project, '.env') });+ const grep = (await executor.handle('pi.grep', { params: { pattern: 'API_KEY' } })) as { text: string };+ expect(grep.text).toContain('.env:1:');+ expect(grep.text).toContain('secret');+ expect(grep.text).not.toContain('credential file(s) left out');+ expect(confirm).toHaveBeenCalledTimes(1);+ } finally {+ await executor.close();+ }+ });+it('leaves credential files out of Pi searches unless the searched path itself was allowed', async () => {const { executor } = sharedExecutor('full', async () => true);fs.writeFileSync(path.join(project, '.env'), 'API_KEY=secret\n');diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.tsindex 32c9a85127..6d0fcece34 100644--- a/apps/desktop/src/main/remote-agent/executor/executor.ts+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts@@ -46,6 +46,9 @@ export interface ExecutorCaptureHooks {noteOpaqueWrite(): void;}+/** `session` 仅免除当前执行器的分享凭证确认,普通权限上限仍由 gate 判断。 */+export type ExecutorConfirmation = boolean | 'session';+export interface RemoteExecutorOptions {workspace: ExecutorWorkspace;gate: ExecutorGate;@@ -59,9 +62,9 @@ export interface RemoteExecutorOptions {webFetch?: GuardedFetch;/*** 在本机弹确认卡问本机用户(供应商分享的受邀者任务):凭证类操作没有本机批准时用它补问,允许后- * 只放行这一个操作。缺省时这类操作直接拒绝。+ * 默认只放行这一个操作;用户明确选择会话级允许后免除后续的分享凭证确认。缺省时直接拒绝。*/- confirm?(action: ExecutorAction): Promise<boolean>;+ confirm?(action: ExecutorAction): Promise<ExecutorConfirmation>;}export class ExecutorRequestError extends Error {@@ -113,6 +116,7 @@ export class RemoteExecutor {private readonly shell: ShellSession;private readonly writeHooks: FileWriteHooks;private closed = false;+ private permissionGeneration = 0;constructor(private readonly opts: RemoteExecutorOptions) {this.workspace = opts.workspace;@@ -132,6 +136,7 @@ export class RemoteExecutor {/** 本机任务的权限档变化时更新上限档位。 */setGateMode(mode: ExecutorGateMode): void {+ this.permissionGeneration += 1;this.gate.setMode(mode);}@@ -152,9 +157,15 @@ export class RemoteExecutor {*/async confirm(action: ExecutorAction, signal?: AbortSignal): Promise<boolean> {if (this.closed || !this.opts.confirm || !this.gate.needsCredentialConsent(action)) return false;+ const permissionGeneration = this.permissionGeneration;const allowed = await this.opts.confirm(action).catch(() => false);- // 等确认期间任务结束或请求被取消:不再执行。- if (!allowed || this.closed || signal?.aborted) return false;+ // 等确认期间任务结束、请求被取消或权限已切换:不接受旧确认。+ if ((allowed !== true && allowed !== 'session') || this.closed || signal?.aborted+ || permissionGeneration !== this.permissionGeneration) return false;+ if (allowed === 'session') {+ this.gate.allowCredentialsForSession();+ if (this.gate.getMode() === 'full') return true;+ }this.gate.recordApproval(action);return true;}diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.tsindex df8f74d200..53f83ee723 100644--- a/apps/desktop/src/main/remote-agent/executor/gate.ts+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts@@ -14,7 +14,7 @@* 只认本机用户刚批准过的同一地址;批准过的地址抓取时放开内网(域名也可能解析到内网);* - 计划模式:只允许读取、抓取网页和静态可证只读的命令,其余同样要本机用户批准过;* - 供应商分享的受邀者任务:内容会经过分享者的电脑,凭证类的读写与读取凭证的命令即使在全权下- * 也只认本机用户批准过的同一操作(credentials.ts)。+ * 也要本机用户确认;用户可明确允许当前任务后续的凭证操作(credentials.ts)。* 批准记录只在短时间内有效;命令与抓取的批准用一次即失效,路径批准在有效期内覆盖同一路径的读写* (编辑会先读后写)。*/@@ -98,6 +98,7 @@ export interface ExecutorGateOptions {export class ExecutorGate {private mode: ExecutorGateMode;private approvals: Approval[] = [];+ private credentialsAllowedForSession = false;constructor(private readonly workspace: ExecutorWorkspace,@@ -109,9 +110,15 @@ export class ExecutorGate {}setMode(mode: ExecutorGateMode): void {+ this.credentialsAllowedForSession = false;this.mode = mode;}+ /** 本机用户在凭证确认卡上选择了「本任务总是允许」。授权随执行器关闭或权限档变化失效。 */+ allowCredentialsForSession(): void {+ if (this.options.confirmCredentials) this.credentialsAllowedForSession = true;+ }+getMode(): ExecutorGateMode {return this.mode;}@@ -128,7 +135,7 @@ export class ExecutorGate {* 真实目标再判一次)、目录级读取的根本身是凭证目录,或命令读取 / 打出凭证。*/needsCredentialConsent(action: ExecutorAction): boolean {- if (!this.options.confirmCredentials) return false;+ if (!this.options.confirmCredentials || this.credentialsAllowedForSession) return false;if (action.kind === 'fetch') return false;if (action.kind === 'exec') {return isShareCredentialCommand(action.command, this.workspace.allRoots(), { cwd: action.cwd, platform: process.platform });diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsxindex 604c8262e6..a145c18af4 100644--- a/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx@@ -11,6 +11,7 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import type { PendingPermission } from '@/lib/makerChatStore';+import { PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL } from '../../../../shared/providerShareCredentialConsent';// 仓库同款 i18n mock:t 返回 key(带参时拼上参数便于断言)。vi.mock('react-i18next', () => ({@@ -52,6 +53,16 @@ function permission(suggestions?: unknown[]): PendingPermission {}describe('PermissionPrompt 的会话级授权按钮', () => {+ it('供应商分享的凭证确认提供本任务允许,并回传本机提供的授权标记', () => {+ const onRespond = vi.fn();+ render(<PermissionPrompt permission={permission([PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL])} onRespond={onRespond} />);+ fireEvent.click(screen.getByRole('button', { name: /alwaysAllowForSession/ }));+ expect(onRespond).toHaveBeenCalledWith({+ behavior: 'allow',+ updatedPermissions: [PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL],+ decisionClassification: 'user_permanent',+ });+ });it('提交中禁用按钮和快捷键,失败后允许重试', () => {const onRespond = vi.fn();const request = permission([bashRule]);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 82019c9eee..7f46d64b49 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10132,7 +10132,7 @@"saveEdit": "Save Text"},"sharedProviderCredential": {- "description": "This task uses a provider shared with you, so what the Agent reads passes through the sharer's computer. This step involves a credential file (such as a key or .env), so it continues only after you confirm."+ "description": "This task uses a shared provider, so what the Agent reads passes through the sharer’s computer or another computer they arrange. This step may involve credentials (such as keys or .env) and needs your confirmation. “Always allow for this session” skips further shared-provider credential confirmations in this task. Reopening the task or changing its permission mode requires confirmation again."},"mediaDownload": {"title": "Download the generated media?",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 06dfced78d..ed89d7afa3 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10094,7 +10094,7 @@"saveEdit": "テキストを保存"},"sharedProviderCredential": {- "description": "このタスクは共有されたプロバイダーを使っているため、Agent が読み取った内容は共有元のパソコンを経由します。この操作は認証情報のファイル(鍵や .env など)に関わるため、確認してから続行します。"+ "description": "このタスクは共有されたプロバイダーを使うため、Agent が読み取った内容は共有元または共有元が手配したパソコンを経由します。この操作は認証情報(鍵や .env など)に関わる可能性があり、確認が必要です。「このセッションで常に許可」を選ぶと、このタスクで共有に伴う認証情報の確認を繰り返しません。タスクを開き直すか権限モードを変更すると、再度確認します。"},"mediaDownload": {"title": "生成されたメディアをダウンロードしますか?",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 94bd506dd4..8c8b7c0e40 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10094,7 +10094,7 @@"saveEdit": "텍스트 저장"},"sharedProviderCredential": {- "description": "이 작업은 공유받은 제공자를 사용하므로 Agent가 읽은 내용이 공유한 사람의 컴퓨터를 거칩니다. 이 단계는 자격 증명 파일(키, .env 등)과 관련되어 있어 확인한 후에 계속됩니다."+ "description": "이 작업은 공유받은 제공자를 사용하므로 Agent가 읽은 내용은 공유한 사람의 컴퓨터 또는 그 사람이 지정한 컴퓨터를 거칩니다. 이 단계는 자격 증명(키, .env 등)과 관련될 수 있어 확인이 필요합니다. ‘이 세션에서 항상 허용’을 선택하면 이 작업에서 공유에 따른 자격 증명 확인을 반복하지 않습니다. 작업을 다시 열거나 권한 모드를 변경하면 다시 확인합니다."},"mediaDownload": {"title": "생성된 미디어를 다운로드할까요?",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex d87aa77c41..e97669331e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10094,7 +10094,7 @@"saveEdit": "保存文本"},"sharedProviderCredential": {- "description": "这个任务用的是分享来的供应商,Agent 读到的内容会经过分享者的电脑。这一步涉及凭证类文件(如密钥、.env),需要你确认后才继续。"+ "description": "这个任务用的是分享来的供应商,Agent 读到的内容会经过分享者或其安排的电脑。这一步可能涉及凭证(如密钥、.env),需要你确认后才继续。选择「本任务总是允许」后,本任务后续凭证操作不再额外确认;重新打开任务或切换权限档后需再次确认。"},"mediaDownload": {"title": "允许下载生成的媒体?",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 97b22b6400..577151b837 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10094,7 +10094,7 @@"saveEdit": "儲存文字"},"sharedProviderCredential": {- "description": "這個任務用的是分享來的供應商,Agent 讀到的內容會經過分享者的電腦。這一步涉及憑證類檔案(如金鑰、.env),需要你確認後才繼續。"+ "description": "這個任務用的是分享來的供應商,Agent 讀到的內容會經過分享者或其安排的電腦。這一步可能涉及憑證(如金鑰、.env),需要你確認後才繼續。選擇「本任務總是允許」後,本任務後續憑證操作不再額外確認;重新開啟任務或切換權限模式後需再次確認。"},"mediaDownload": {"title": "允許下載產生的媒體?",diff --git a/apps/desktop/src/shared/providerShareCredentialConsent.ts b/apps/desktop/src/shared/providerShareCredentialConsent.tsnew file mode 100644index 0000000000..d503de64b9--- /dev/null+++ b/apps/desktop/src/shared/providerShareCredentialConsent.ts@@ -0,0 +1,15 @@+/** 本机确认卡提供的授权标记;只免除当前任务的供应商分享凭证确认。 */+export const PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL = {+ type: 'providerShareCredentialSessionApproval',+ destination: 'session',+} as const;++/** 只接受完整的单项授权,避免把其他规则或权限档变更当成凭证授权。 */+export function isProviderShareCredentialSessionApproval(updates: unknown): boolean {+ if (!Array.isArray(updates) || updates.length !== 1) return false;+ const update = updates[0];+ return !!update && typeof update === 'object' && !Array.isArray(update)+ && Object.keys(update).length === 2+ && update.type === PROVIDER_SHARE_CREDENTIAL_SESSION_APPROVAL.type+ && update.destination === 'session';+}diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex 64f6b7b112..ea8ac3eee0 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -276,8 +276,11 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):- 凭证类文件(密钥、`.env`、云与工具的登录凭证,规则同本机任务;Claude Code / Codex 配置目录里的Skill、子代理、命令与说明文字不算)不随项目说明与个人配置在启动时同步,链接按真实目标判断;- 任务中读写凭证类文件、执行读取或打出凭证的命令,不论权限档(含完全访问)都要受邀者在本机确认卡上- 允许,只放行这一次,与本机任务读凭证「每次都问」一致;Pi 的搜索结果不含凭证类文件的内容。确认卡与- Agent 的确认走同一通道,手机远控与 IM 也能处理;+ 允许,默认只放行这一次。确认卡同时提供「本任务总是允许」(2026-10-12 用户确认):受邀者明确选择后,+ 当前任务运行期间不再额外确认凭证操作,Pi 的搜索结果也可包含凭证内容;只在本机执行器内存里记住,+ 关闭、重新打开任务或切换权限档后恢复确认,不扩展到其他任务或供应商分享。原权限档的其他限制仍然生效,+ 启动同步仍排除凭证文件。确认卡说明内容会经过分享者或其安排的电脑,以及这项授权的范围与失效时机。+ 确认卡与 Agent 的确认走同一通道,手机远控与 IM 也能处理;- 命令只能按命令文本识别(脚本里读的、编码后再解开的认不出来),是防误发,不是防恶意。同账号远程供应商不受影响:与本机一致,项目与个人配置里的符号链接一律跟随,不额外确认。实现:`apps/desktop/src/main/remote-agent/{credentials.ts,executor/gate.ts,controller/projectFiles.ts}`。