Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(permissions): 群任务运行中权限切换与普通任务保持一致 (#6869)
Dashe3f555054071
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex e2879f08fe..0a51b4897a 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -292,9 +292,8 @@ interface TurnState {interactionRouteLease: InteractionRouteLease | null;/*** Host turn lease held for the duration of a per-turn permission policy turn.- * While held, session.setPermissionMode() blocks any switch into a mode the- * agent lists as turnPermissionPolicy-unsupported (e.g. Pi Full Access),- * closing the hot-switch bypass window. Released on every terminal / requeue /+ * Keeps new sends and retirement behind this turn's background continuations;+ * the owner's live permission changes remain immediate. Released on every terminal / requeue /* cleanup path via releaseTurnInteractionRoute. Null when the turn has no policy.*/hostTurnLeaseRelease: (() => void) | null;@@ -1675,10 +1674,8 @@ export function createTurnRunner(if (sessionStates.get(rowId)?.makerSession !== noticeSession) return false;return im.sendText(userId, text, { threadTs: noticeScope });});- // 策略轮持一张 host turn lease:期间 setPermissionMode 切到 agent 声明为- // turnPermissionPolicy-unsupported 的档位(如 Pi Full Access)会被阻塞到本轮- // 终态,堵死"热切到 bypass 让 bridge 直接放行、策略连冒泡机会都没有"的绕过。- // 两个 surface 都需要:channel 与 desktop 的策略同样必须扛住热切。+ // 策略轮保留逻辑占用直到后台续跑和收尾结束;新输入仍须等待,+ // 主人在 Cindy 中切换权限则立即沿用普通任务的运行时切换。if (effectiveTurnPolicy) {item.turn.hostTurnLeaseRelease = state.makerSession.acquireTurnLease();}diff --git a/apps/desktop/src/main/im/telegram/adapter.ts b/apps/desktop/src/main/im/telegram/adapter.tsindex eebeaef56c..bbb85b460c 100644--- a/apps/desktop/src/main/im/telegram/adapter.ts+++ b/apps/desktop/src/main/im/telegram/adapter.ts@@ -210,7 +210,9 @@ export function buildTelegramAdapter(// Full access 是 owner 对这条任务的明确授权。该档下各 Agent 的工具调用不会// 冒泡到 host,逐轮强确认策略无法兑现;owner 触发时取缔策略,避免 provider// 启动前报不支持。非 owner 仍保留策略并 fail-closed,不能借同一群任务的- // Full access 直接驱动工具。其它权限档与群上下文隔离都不受影响。+ // Full access 直接驱动工具。这里仅负责新消息准入;主人对已受理轮次主动切档+ // 按普通任务立即生效(2026-10-23 Dash 裁决),不在这里增加运行中限制。+ // 其它权限档与群上下文隔离都不受影响。// 伙伴自有 bot: 完全访问是主人对这个伙伴的明确授权, 三种 Agent 在该档下都// 无法兑现逐轮策略, 成员触发的轮次同样取缔策略而不是拒跑 —— 要成员动手前// 必须确认, 把伙伴设成 Auto 或 Ask。diff --git a/apps/desktop/src/main/im/telegram/permissionPolicy.ts b/apps/desktop/src/main/im/telegram/permissionPolicy.tsindex db75fe411d..2dd180fa74 100644--- a/apps/desktop/src/main/im/telegram/permissionPolicy.ts+++ b/apps/desktop/src/main/im/telegram/permissionPolicy.ts@@ -12,8 +12,9 @@ import { channelForceConfirmToolCall } from '../shared/channelToolPolicy';* 判定逻辑与个人微信 / 钉钉共用 channelForceConfirmToolCall(嵌套解包覆盖* Claude call_tool、Codex MCP elicitation 与 Pi 桥接 MCP / 二级分派插件)。* maker 不支持某个会话权限档时会拒绝本策略(fail-closed), 不会静默放开。- * 唯一例外是用户显式选择 Full access(bypassPermissions): adapter 会在 dispatch- * 前取缔本策略, 直接按该档执行;群历史 lane 隔离仍独立生效。+ * 新消息准入时,adapter 仅对 owner 轮次或伙伴自有 bot 在 Full access 下取缔策略。+ * 主人运行中主动切档则与普通任务一致,当前已受理轮次立即跟随新权限,包括成员轮次;+ * 来源身份、新消息准入与群历史 lane 隔离仍独立生效。*/export function createTelegramGuestTurnPermissionPolicy(taskId: string, isOwner?: boolean): TurnPermissionPolicy {return {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.tsindex 53af65d30b..9fce93c0e4 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts@@ -53,8 +53,8 @@ function fixture() {const planDeps={...settingDeps,persistSessionFields:planPersist,ipcMain:{handle:(_name:unknown,fn:typeof setPlan)=>{setPlan=fn;}},MAKER_INVOKE:{SET_PLAN_MODE:'plan'}};new Function(...Object.keys(planDeps), planJs)(...Object.values(planDeps));expect(setPlan, 'SET_PLAN_MODE source extraction must register its handler').toBeTypeOf('function');- const setImMode = (mode: PermissionMode) => changeSessionPermissionMode({- sessionId:'task', mode, modes:[{id:mode,displayName:mode}],+ const setImMode = (mode: PermissionMode, confirmedFullAccess = false) => changeSessionPermissionMode({+ sessionId:'task', mode, confirmedFullAccess, modes:[{id:mode,displayName:mode}],readPreviousMode:async()=>history.permissionMode as PermissionMode,getLiveSession:()=>cold?null:live,persist:async next=>{await epoch.client.tx('bots.persistSessionPermission',{mode:next});},@@ -354,28 +354,40 @@ it.each(['queued','runtime','database'])('rejects IM ownership changes during %sexpect(f.epoch.client.tx).toHaveBeenCalledTimes(point==='database'?1:0);});-it('lets a real Session policy lease restore through the send fence while a permission commit waits',async()=>{+// Regression: all permission transitions must have identical runtime/persistence+// results for ordinary and IM-leased tasks through local, remote and IM entry points.+it.each(['local','remote','im'].flatMap(entry=>[false,true].map(groupTurn=>({entry,groupTurn}))))('commits every permission transition immediately ($entry, group turn=$groupTurn)',async({entry,groupTurn})=>{const f=fixture(), transport=vi.fn(async()=>{});+ if(entry==='remote')f.remote();const logger={trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return logger;}};const session=new Session({id:'task',agentKind:'codex',workDir:'/fixture',permissionMode:'ask',turnStallMs:0,handle:{setPermissionMode:transport,setInteractionResolver(){},close:async()=>{}} as never,- capabilities:{permissionModes:[{id:'ask'},{id:'bypassPermissions'}],setPermissionModeMidSession:{supported:true},+ capabilities:{permissionModes:[{id:'ask'},{id:'auto'},{id:'bypassPermissions'}],setPermissionModeMidSession:{supported:true},turnPermissionPolicy:{unsupportedPermissionModes:['bypassPermissions']}} as never,logger});- const releaseLease=session.acquireTurnLease();+ const releaseLease=groupTurn?session.acquireTurnLease():()=>{};f.live.setPermissionMode.mockImplementation(mode=>session.setPermissionMode(mode as PermissionMode));- let started!:()=>void;const entered=new Promise<void>(r=>{started=r;});- f.live.setPermissionMode.mockImplementationOnce(mode=>{started();return session.setPermissionMode(mode as PermissionMode);});- const change=f.setMode('bypassPermissions');try{- await entered;- expect(transport).not.toHaveBeenCalled();- // The continuation's existing send fence and Host-owned restore stay free.- await withSendToSessionLock('task',()=>session.setPermissionModeTracked('ask'));- expect(transport).toHaveBeenCalledExactlyOnceWith('ask');- expect(f.epoch.client.tx).not.toHaveBeenCalled();- }finally{releaseLease();await change;await session.close();}- expect(transport.mock.calls).toEqual([['ask'],['bypassPermissions']]);- expect(f.history.permissionMode).toBe('bypassPermissions');+ f.history.permissionMode='ask';+ const expected:PermissionMode[][]=[];+ // Covers all six directions and a repeated selection without ending the turn.+ for(const mode of ['ask','auto','bypassPermissions','auto','ask','bypassPermissions','ask'] as const){+ const previous=session.permissionModeState;+ const previousMode=previous.mode;+ if(previousMode===null)throw new Error('expected a previously selected permission mode');+ if(entry==='im'){+ if(mode==='bypassPermissions'){+ await expect(f.setImMode(mode)).resolves.toMatchObject({kind:'confirmation-required'});+ expect(transport.mock.calls).toEqual(expected);+ }+ await expect(f.setImMode(mode,true)).resolves.toMatchObject({kind:'changed',mode});+ }else await f.setMode(mode);+ expected.push([mode]);+ expect(transport.mock.calls).toEqual(expected);+ expect(f.history.permissionMode).toBe(mode);+ await expect(withSendToSessionLock('task',()=>session.setPermissionModeIfUnchanged(previous,previousMode))).resolves.toBe(false);+ expect(session.permissionModeState.mode).toBe(mode);+ }+ }finally{releaseLease();await session.close();}});diff --git a/docs/product-rules/im-permission-confirmation.md b/docs/product-rules/im-permission-confirmation.mdindex d6f86641fb..1e42a94aa8 100644--- a/docs/product-rules/im-permission-confirmation.md+++ b/docs/product-rules/im-permission-confirmation.md@@ -24,6 +24,22 @@恢复前取消则各端统一显示取消结果,不提前把 IM 卡片标成允许。普通提问和计划审阅不在本次多处确认范围内。+## 运行中切换权限++2026-10-23,用户要求 IM 群任务与普通任务共用即时权限切换,覆盖所有支持的权限档位。+无论放宽还是收紧,均使用普通任务同一套运行时切换、持久化和失败恢复流程,不等待+群轮次、后台续跑或渠道收尾结束,不增加群任务专属的切换分支。+默认权限、自动审核、完全访问之间任意切换均适用;进入完全访问的确认也沿用普通任务规则。+当前轮次后续工具审批与续跑跟随新档位;收紧时是否中断原生执行同样由对应 Agent 的通用实现决定。+群策略保留来源信息,不能覆盖主人当前选择的完全访问。新消息仍走渠道原有准入策略。+这也适用于已经受理的成员发起轮次:主人运行中主动切档即授权该任务的当前执行,+不因发起人身份再延后或另走切换流程;不会因此把成员标记为主人,也不改变下一条成员消息的准入。++`Session.acquireTurnLease` 只维持任务逻辑占用,保护新输入排队与收尾顺序,不阻塞+`Session.setPermissionMode`。临时权限恢复不得覆盖主人的新选择。+实现与回归见 `packages/maker-core/src/session.ts`、`maker.test.ts` 及三个 Agent 的+权限审批测试;桌面、手机、同账号远控共用同一宿主入口与原有身份校验。+## 来源与边界`IMMessageEvent.interactionSource` 是可选的传输层元数据,提供群/聊天名、话题名、diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex 8e8c55ba55..e2bf7c55ba 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -234,6 +234,12 @@ hook 侧既有的逐轮 `[渠道说明]`,两者措辞不同但都向模型说适用于其它 IM 的共享合同与新增渠道接入见 [IM 权限确认](im-permission-confirmation.md)。两侧的 owner 权限、超时来源、提问与计划审阅差异不因此统一。+2026-10-23,Dash 要求群任务运行中任意权限切换与普通任务即时生效。下表「群轮次权限档」+保留的是**新消息准入**:个人 bot 不能仅凭任务原有的完全访问设置受理成员消息并放行工具。+已受理轮次中主人主动切到完全访问则是对当前任务的明确授权,包括成员发起的轮次,+不会等待轮次结束或继续套用旧策略。该新决定覆盖旧裁决对运行中切档的限制;发起人身份、+群历史隔离及下一条消息准入规则不变,详见 [运行中切换权限](im-permission-confirmation.md#运行中切换权限)。+| 差异 | 官方 | 个人 | 裁决与理由 ||---|---|---|---|| **伙伴自有 bot** | 无:官方入口的伙伴归属需要协议携带执行归属并由服务端核验,尚未接入 | 有:伙伴设置「消息平台」页直接填自己申请的 bot token 与主人 id,或一次性把 设置 → IM 机器人 里已配好的个人 bot 移过来(主人 id 与全响应群随连接带过去,个人 bot 随即清空,不共用;失败时个人 bot 原样恢复);本机 Hermes / OpenClaw 导入能确定唯一主人 id 时也直接建成连接;每条连接一份个人 Telegram 适配器实例;主人私聊进伙伴主任务,群 / 话题 / 外部用户私聊各进一条隐藏的 `role='channel'` 专线;外部用户私聊放行(带非主人标记,命令静默丢;渠道说明写明发言人并点出「不是主人」,不按 speaker 有无误判成群)。不读设置页的人格与行为配置:表情 / 引用档位用默认值,群参与模式(仅 @ / 全响应)按连接各一份存在连接记录里,由伙伴「消息平台」页每条连接下的「群聊」小节设置;全响应消息先经辅助模型判「该不该插话」(见第四节 2k,个人 bot 同款);伙伴「消息平台」页同样可挂企业微信 / 钉钉 / Discord 机器人(各自传输层按连接前缀隔离凭证、不注册设置卡 IPC),本表只管 Telegram;命令菜单去掉 `/project` `/model` `/permission`(渠道里会被拒,单源 `isCompanionManagedCommand`)。专线里别人的消息在任务面板卡头写出发言人与群名(`imSource.origin`),不以主人名义显示。**群轮次权限档与本表「群轮次权限档」行有意不同**:伙伴设置里的权限档是唯一开关,主人触发的轮次不挂逐轮策略,成员 / 外部用户触发的轮次只对破坏性动作强确认(`channelForceConfirmToolCall`,飞书同口径),完全访问下成员轮次同样取缔策略直接执行而不是拒跑(2026-10-16 Chris 裁决,见 `cindy-bots-runtime.md` §2)。设置 → IM 机器人 那份个人 bot 完全沿用本表其余各行 | 2026-10-15 Chris 裁决伙伴自己带 IM bot(见 `cindy-bots-runtime.md` §2);2026-10-17 Chris 允许从个人 bot 一次性移交。这是分期差异不是架构裁决:官方侧接入前登记为缺口,不得只改设置页宣称官方群路由完成 |diff --git a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.tsindex fef302a902..ef490fb3d5 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts@@ -874,7 +874,7 @@ describe('Auto-review wiring: lightweight reviewer controls gray actions', () =>await next.handle.close();});- it.each([false, true])('Auto to Full access retains turn scope without restoring MCP forced prompts (%s)', async (restricted) => {+ it.each([false, true])('Auto to Full access applies the owner choice during review (IM policy=%s)', async (restricted) => {let release!: (decision: { verdict: 'allow' }) => void;const reviewer = vi.fn(() => new Promise<{ verdict: 'allow' }>((resolve) => { release = resolve; }));const { handle, canUseTool, seen } = await startSession('auto', {@@ -889,7 +889,7 @@ describe('Auto-review wiring: lightweight reviewer controls gray actions', () =>await vi.waitFor(() => expect(reviewer).toHaveBeenCalledOnce());await handle.setPermissionMode!('bypassPermissions');release({ verdict: 'allow' });- expect(await pending).toMatchObject({ behavior: restricted ? 'deny' : 'allow' });+ expect(await pending).toMatchObject({ behavior: 'allow' });expect(permissionRequests(seen)).toHaveLength(0);await handle.close();});diff --git a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.tsindex 6cab6157e2..7190fc680c 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts@@ -775,6 +775,17 @@ describe('ClaudeCodeAgent canUseTool honors the host MCP approval policy', () =>expect(permissionRequests(seen)[0]?.suggestions).toBeUndefined();expect(result.behavior).toBe('allow');expect(result.updatedPermissions).toBeUndefined();+ // A live owner permission change supersedes the IM policy on this same turn.+ await handle.setPermissionMode!('bypassPermissions');+ expect((await canUseTool('mcp__cindy_contacts__call_tool', { name: 'contacts_delete' }, {+ toolUseID: 't-policy-full-access',+ })).behavior).toBe('allow');+ expect(permissionRequests(seen)).toHaveLength(1);+ await handle.setPermissionMode!('ask');+ await canUseTool('mcp__cindy_contacts__call_tool', { name: 'contacts_delete' }, {+ toolUseID: 't-policy-restored',+ });+ expect(permissionRequests(seen)).toHaveLength(2);await handle.close();});@@ -998,11 +1009,14 @@ describe('prompt-each-time never turns into a persisted grant', () => {await handle.close();});- it('Full access overrides a pending prompt-each-time MCP approval', async () => {+ it.each([false, true])('Full access overrides a pending MCP approval (IM policy=%s)', async (imPolicy) => {const { handle, canUseTool } = await startSession(() => 'prompt-each-time', {// 决策永不返回:请求挂起,等模式切换来结算。decide: () => undefined,});+ if (imPolicy) await handle.send({ type: 'user', content: 'Merge the contacts.' }, {+ turnPermissionPolicy: { origin: { kind: 'im', channel: 'feishu' }, confirmationSurface: 'channel', forceConfirmToolCall: () => true },+ });const pending = canUseTool('mcp__cindy_contacts__call_tool', { name: 'contacts_merge' }, {toolUseID: 't-pending',@@ -1704,7 +1718,7 @@ describe('remote sessions share the same permission semantics', () => {await handle.close();});- it.each([false, true])('remote Auto to Full access retains turn scope without restoring MCP forced prompts (%s)', async (restricted) => {+ it.each([false, true])('remote Auto to Full access applies the owner choice during review (IM policy=%s)', async (restricted) => {let release!: (decision: { verdict: 'allow' }) => void;const reviewer = vi.fn(() => new Promise<{ verdict: 'allow' }>((resolve) => { release = resolve; }));const { handle, onApprovalRequest, seen } = await startRemoteSession(() => 'prompt-each-time', {@@ -1722,7 +1736,7 @@ describe('remote sessions share the same permission semantics', () => {await vi.waitFor(() => expect(reviewer).toHaveBeenCalledOnce());await handle.setPermissionMode!('bypassPermissions');release({ verdict: 'allow' });- expect(await pending).toMatchObject({ behavior: restricted ? 'deny' : 'allow' });+ expect(await pending).toMatchObject({ behavior: 'allow' });expect(permissionRequests(seen)).toHaveLength(0);await handle.close();});diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 255c8a87e6..939fcb23c6 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -2252,7 +2252,7 @@ export class ClaudeCodeAgent extends BaseAgent {};const forceTurnConfirmation = (toolName: string, input: unknown): boolean => {const policy = activeTurnPermissionPolicy;- if (!policy) return false;+ if (!policy || mutablePermissionMode === 'bypassPermissions') return false;try {return policy.forceConfirmToolCall(toolName, input) === true;} catch (error) {@@ -2280,8 +2280,6 @@ export class ClaudeCodeAgent extends BaseAgent {kind: InteractionRequest['kind'];resolve: (d: InteractionDecision) => void;settled: boolean;- /** 本轮来源/执行范围约束独立于 MCP 的逐次审批偏好。 */- turnPolicyForcePrompt?: boolean;/** Auto 审阅故障降级来的确认:系统收口不能当成用户点了拒绝。 */unavailableHandoff?: boolean;/** 目录授权变化会使这次文件读写审批的根快照失效。 */@@ -2301,7 +2299,7 @@ export class ClaudeCodeAgent extends BaseAgent {*/async function dispatchInteraction(req: InteractionRequest,- opts?: { turnPolicyForcePrompt?: boolean; directorySensitive?: boolean },+ opts?: { directorySensitive?: boolean },): Promise<InteractionDecision> {if (!interactionResolver) {return safeDefaultDecision(req.kind, 'no_resolver_attached');@@ -2312,7 +2310,6 @@ export class ClaudeCodeAgent extends BaseAgent {kind: req.kind,resolve,settled: false,- ...(opts?.turnPolicyForcePrompt ? { turnPolicyForcePrompt: true } : {}),...(opts?.directorySensitive ? { directorySensitive: true } : {}),...(req.kind === 'permission' && isAutoReviewUnavailableMetadata(req.metadata)? { unavailableHandoff: true }@@ -2345,11 +2342,10 @@ export class ClaudeCodeAgent extends BaseAgent {const entries = Array.from(pendingInteractions.entries());for (const [requestId, entry] of entries) {if (entry.settled) continue;- const effectiveResolveAs = resolveAs === 'allow' && entry.turnPolicyForcePrompt ? 'deny' : resolveAs;- const decision = effectiveResolveAs === 'allow' && entry.kind !== 'ask_user_question'+ const decision = resolveAs === 'allow' && entry.kind !== 'ask_user_question'? ({ kind: entry.kind, behavior: 'allow' } as InteractionDecision): safeDefaultDecision(entry.kind, reason);- if (effectiveResolveAs === 'deny' && entry.unavailableHandoff) {+ if (resolveAs === 'deny' && entry.unavailableHandoff) {autoReviewConfirmUndeliveredNotice.notify();}entry.settled = true;@@ -2358,7 +2354,7 @@ export class ClaudeCodeAgent extends BaseAgent {const dismissedPayload: InteractionDismissedEvent = {requestId,reason,- resolvedAs: effectiveResolveAs,+ resolvedAs: resolveAs,};eventQueue.push({ type: 'interaction_dismissed', data: dismissedPayload, source: 'claude-code' });}@@ -2641,9 +2637,6 @@ export class ClaudeCodeAgent extends BaseAgent {return { behavior: 'deny', message: 'The current Plan turn is read-only.' };}if (modeAfterReview === 'bypassPermissions') {- if (turnPolicyForcePrompt) {- return { behavior: 'deny', message: 'Permission mode changed; retry within the authorized turn scope.' };- }return { behavior: 'allow', updatedInput: executionInput };}if (modeAfterReview !== reviewPermissionMode) {@@ -2695,7 +2688,7 @@ export class ClaudeCodeAgent extends BaseAgent {unavailableHandoff? annotatePermissionRequestForUnavailableReview(permissionRequest): permissionRequest,- { turnPolicyForcePrompt, directorySensitive: directorySensitivePermission },+ { directorySensitive: directorySensitivePermission },);notifyIfAutoReviewConfirmUndelivered(unavailableHandoff, decision);if (isPlanToolBlocked(toolName)) {@@ -3904,7 +3897,6 @@ export class ClaudeCodeAgent extends BaseAgent {const REMOTE_APPROVAL_TIMEOUT_MS = 110_000;async function dispatchWithTimeout(req: InteractionRequest,- dispatchOpts?: { turnPolicyForcePrompt?: boolean },): Promise<InteractionDecision> {let timer: NodeJS.Timeout | undefined;try {@@ -3913,7 +3905,7 @@ export class ClaudeCodeAgent extends BaseAgent {dismissSinglePending(req.requestId, 'approval_timeout');reject(new Error('approval timed out'));}, REMOTE_APPROVAL_TIMEOUT_MS);- dispatchInteraction(req, dispatchOpts).then(resolve, reject);+ dispatchInteraction(req).then(resolve, reject);});} finally {if (timer) clearTimeout(timer);@@ -4045,9 +4037,7 @@ export class ClaudeCodeAgent extends BaseAgent {params.input ?? {},);if (mutablePermissionMode === 'bypassPermissions') {- return remoteTurnPolicyForcePrompt- ? { kind: 'permission', behavior: 'deny', reason: 'Permission mode changed; retry within the authorized turn scope.' }- : { kind: 'permission', behavior: 'allow' };+ return { kind: 'permission', behavior: 'allow' };}// 远端会话走同一份 host MCP 策略 —— 否则 SSH 会话里可信 server 又要逐次// 弹窗, prompt-each-time 的"禁止持久化授权"保护也整套缺失。@@ -4082,9 +4072,7 @@ export class ClaudeCodeAgent extends BaseAgent {return { kind: 'permission', behavior: 'deny', reason: 'The current Plan turn is read-only.' };}if (modeAfterReview === 'bypassPermissions') {- return remoteTurnPolicyForcePrompt- ? { kind: 'permission', behavior: 'deny', reason: 'Permission mode changed; retry within the authorized turn scope.' }- : { kind: 'permission', behavior: 'allow' };+ return { kind: 'permission', behavior: 'allow' };}if (modeAfterReview === reviewPermissionMode && autoDecision.verdict === 'allow') {return { kind: 'permission', behavior: 'allow' };@@ -4126,7 +4114,6 @@ export class ClaudeCodeAgent extends BaseAgent {remoteUnavailableHandoff? annotatePermissionRequestForUnavailableReview(remotePermissionRequest): remotePermissionRequest,- { turnPolicyForcePrompt: remoteTurnPolicyForcePrompt },);} catch {if (remoteUnavailableHandoff) autoReviewConfirmUndeliveredNotice.notify();diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 1d7d225d6c..f9f4fb8efa 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -2625,6 +2625,13 @@ describe('CodexAgent permissions', () => {suggestions: undefined,});if (!handle.setPermissionMode) throw new Error('expected setPermissionMode');+ // Owner takeover must apply to subsequent approvals in this same policy turn.+ await handle.setPermissionMode('bypassPermissions');+ await expect(handlers.commandExecutionApproval({+ threadId: 'start-thread-id', turnId: 'turn-wechat-policy', itemId: 'cmd-owner-takeover',+ command: 'rm -rf build', cwd: '/repo',+ })).resolves.toEqual({ decision: 'accept' });+ expect(resolver).toHaveBeenCalledOnce();await handle.setPermissionMode('ask');expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {threadId: 'start-thread-id',@@ -16080,7 +16087,7 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});- it.each([false, true])('Auto to Full access retains turn scope without restoring MCP forced prompts (%s)', async (restricted) => {+ it.each([false, true])('Auto to Full access applies the owner choice during review (IM policy=%s)', async (restricted) => {const gate = deferred<{ verdict: 'allow' }>();const review = vi.fn<AutoReviewDelegate>(() => gate.promise);const agent = new CodexAgent(createDeps({}, { reviewAutoPermissionAction: review, getMcpToolApprovalPolicy: () => 'prompt-each-time' }));@@ -16100,7 +16107,7 @@ describe('CodexAgent MCP thread context hooks', () => {await vi.waitFor(() => expect(review).toHaveBeenCalledOnce());await handle.setPermissionMode!('bypassPermissions');gate.resolve({ verdict: 'allow' });- expect(await pending).toEqual({ action: restricted ? 'decline' : 'accept', content: null, _meta: null });+ expect(await pending).toEqual({ action: 'accept', content: null, _meta: null });expect(resolver).not.toHaveBeenCalled();await handle.close();});@@ -16518,12 +16525,13 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});- it.each(['auto', 'bypassPermissions'] as const)('pending MCP approvals follow a switch to %s', async (mode) => {+ it.each((['auto', 'bypassPermissions'] as const).flatMap(mode => [false, true].map(imPolicy => ({ mode, imPolicy }))))('pending MCP approvals follow a switch to $mode (IM policy=$imPolicy)', async ({ mode, imPolicy }) => {// Full 批准挂起请求;Auto 不能将尚未审阅的旧请求批量批准。const agent = new CodexAgent(createDeps({}, {getMcpToolApprovalPolicy: () => 'prompt-each-time',}));- const host = installFakeHost(agent);+ const host = installFakeHost(agent, method => method === Method.TurnStart+ ? { turn: { id: 'turn-1' } } : undefined);const handle = await agent.startSession({sessionId: 'session-high-risk-mode-switch',@@ -16531,6 +16539,9 @@ describe('CodexAgent MCP thread context hooks', () => {workingDir: '/repo',permissionMode: 'ask',});+ if (imPolicy) await handle.send({ type: 'user', content: 'Merge the contacts.' }, {+ turnPermissionPolicy: { origin: { kind: 'im', channel: 'feishu' }, confirmationSurface: 'channel', forceConfirmToolCall: () => true },+ });const iterator = handle.events()[Symbol.asyncIterator]();const handlers = host.getThreadHandlers();if (!handlers?.mcpServerElicitation) throw new Error('expected mcpServerElicitation handler');@@ -16554,7 +16565,9 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.setPermissionMode(mode);await expect(responsePromise).resolves.toEqual({ action: mode === 'auto' ? 'decline' : 'accept', content: null, _meta: null });- await expect(nextEvent(iterator)).resolves.toMatchObject({+ let dismissed = await nextEvent(iterator);+ while (dismissed.type !== 'interaction_dismissed') dismissed = await nextEvent(iterator);+ expect(dismissed).toMatchObject({type: 'interaction_dismissed',data: {reason: `permission_mode_changed_to_${mode}`,@@ -21422,7 +21435,7 @@ describe('CodexAgent yield continuation', () => {await handle.close();});- it.each([false, true])('inherits the origin policies on yield continuation (text-only=%s)', async (toolsDisabled) => {+ it.each([[false, false], [true, false], [false, true]])('inherits origin policies and current permissions on yield continuation (text-only=%s, Full access=%s)', async (toolsDisabled, fullAccess) => {const agent = new CodexAgent(createDeps({}, { registerCodexTextOnlyPolicy: () => () => {} }));let turnSeq = 0;const host = installFakeHost(agent, (method) => {@@ -21451,6 +21464,7 @@ describe('CodexAgent yield continuation', () => {// The fake notification exercises continuation policy even though a real// text-only tool would have been denied before producing this output.await handle.send({ type: 'user', content: 'run typecheck' }, { turnPermissionPolicy: policy, toolsDisabled });+ if (fullAccess) await handle.setPermissionMode!('bypassPermissions');const resumesBeforeContinuation = host.request.mock.calls.filter(([method]) => method === Method.ThreadResume).length;handlers.itemCompleted({threadId: 'start-thread-id',@@ -21471,7 +21485,10 @@ describe('CodexAgent yield continuation', () => {expect(yieldTurnStartCalls(host)).toHaveLength(1);});const [, continuationParams] = yieldTurnStartCalls(host)[0] as [string, Record<string, unknown>];- expect(continuationParams).toMatchObject({+ expect(continuationParams).toMatchObject(fullAccess ? {+ approvalPolicy: 'never',+ sandboxPolicy: { type: 'dangerFullAccess' },+ } : {approvalPolicy: 'untrusted',sandboxPolicy: { type: 'readOnly' },});diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 46f206a2d3..32f6f24958 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -4898,7 +4898,7 @@ assertRouteCurrent();};const forceTurnConfirmation = (toolName: string, input: unknown): boolean => {const policy = activeTurnPermissionPolicy;- if (!policy) return false;+ if (!policy || mutablePermissionMode === 'bypassPermissions') return false;try {return policy.forceConfirmToolCall(toolName, input) === true;} catch (error) {@@ -6732,7 +6732,7 @@ assertRouteCurrent();// those handlers auto-accept non-forced actions in Auto mode.const turnApprovalConfig: CodexPermissionConfig = reviewMode? { approvalPolicy: 'never', sandbox: 'read-only' }- : activeTurnPermissionPolicy+ : activeTurnPermissionPolicy && mutablePermissionMode !== 'bypassPermissions'? {approvalPolicy: 'untrusted',sandbox: 'read-only',@@ -6749,7 +6749,7 @@ assertRouteCurrent();};if (currentWorkspacePermissionProfile() !== undefined &&- !activeTurnPermissionPolicy+ (!activeTurnPermissionPolicy || mutablePermissionMode === 'bypassPermissions')) {// The profile was selected on thread/start or thread/resume. Repeating// the selector here makes Codex 0.145.0 reload its base config (which@@ -7933,8 +7933,6 @@ assertRouteCurrent();reviewing?: boolean;turnId: string | null;itemId?: string;- /** 本轮来源/执行范围约束独立于 MCP 的逐次审批偏好。 */- turnPolicyForcePrompt?: boolean;/** Auto 审阅故障降级来的确认:系统收口不能当成用户点了拒绝。 */unavailableHandoff?: boolean;onSystemDenied?: (reason: string) => void;@@ -8226,7 +8224,7 @@ assertRouteCurrent();// auto_review 负责;fallback 路由则由 user reviewer 把越界请求发回客户端,// 再由 Cindy reviewer 静默裁决。// MCP 的逐次审批标记不能覆盖用户选择的 Full access。- // 独立的本轮执行范围约束仍由 turn policy 决定。+ // 主人运行中选择 Full access 后,本轮 IM 策略同样跟随当前权限。if (mutablePermissionMode === 'bypassPermissions' &&!turnPolicyForcePrompt@@ -8286,11 +8284,6 @@ assertRouteCurrent();// await 期间经 setPermissionMode 的重赋值,仍视此处为 'auto';运行期确实可能已变。const modeAfterReview = mutablePermissionMode as PermissionMode;if (modeAfterReview === 'bypassPermissions') {- if (turnPolicyForcePrompt) {- denialReason = formatPermissionDenial('system', 'Permission mode changed; retry within the authorized turn scope.');- reportMcpDenial('system');- return 'decline';- }return 'accept';}if (modeAfterReview !== reviewPermissionMode) {@@ -8330,7 +8323,6 @@ assertRouteCurrent();settled: false,turnId,...(opts?.itemId ? { itemId: opts.itemId } : {}),- turnPolicyForcePrompt,...(unavailableHandoff ? { unavailableHandoff: true } : {}),onSystemDenied: (reason) => reportMcpDenial('system', reason, false),};@@ -8396,15 +8388,14 @@ assertRouteCurrent();if (entry.settled || (preserveReviewing && entry.reviewing)) continue;entry.settled = true;pendingApprovals.delete(requestId);- const effectiveResolveAs = resolveAs === 'allow' && entry.turnPolicyForcePrompt ? 'deny' : resolveAs;- if (effectiveResolveAs === 'deny') entry.onSystemDenied?.(reason);- if (effectiveResolveAs === 'deny' && entry.unavailableHandoff && entry.kind !== 'mcpServerElicitation') {+ if (resolveAs === 'deny') entry.onSystemDenied?.(reason);+ if (resolveAs === 'deny' && entry.unavailableHandoff && entry.kind !== 'mcpServerElicitation') {autoReviewConfirmUndeliveredNotice.notify();}- entry.resolve(effectiveResolveAs === 'allow' ? 'accept' : 'decline', reason);+ entry.resolve(resolveAs === 'allow' ? 'accept' : 'decline', reason);eventQueue.push({type: 'interaction_dismissed',- data: { requestId, reason, resolvedAs: effectiveResolveAs },+ data: { requestId, reason, resolvedAs: resolveAs },source: 'codex',});}@@ -13266,7 +13257,11 @@ assertRouteCurrent();}if (sendOpts.turnPermissionPolicy &&- mutablePermissionMode === 'bypassPermissions'+ mutablePermissionMode === 'bypassPermissions' &&+ // Internal continuations belong to the turn the owner just took over.+ // New externally supplied policy turns still undergo normal admission.+ !(sendOpts as CodexInternalSendOptions)[CODEX_INTERNAL_CONTINUATION] &&+ !(sendOpts as CodexInternalSendOptions)[CODEX_INTERACTION_CONTINUATION]) {throw new TurnPermissionPolicyUnsupportedError('codex',diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 97312130ed..f1f11ad585 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -4594,6 +4594,17 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {expect(JSON.stringify(review.mock.calls[0]?.[0])).not.toContain('PRIVATE_FILE_BODY');expect(JSON.parse((review.mock.calls[0]?.[0].action as { description: string }).description).executionEvidence).toMatchObject({ kind: 'file-write', path: input.path, resolvedPath: input.path, resolvedWritableRoots: [cwd] });+ // The same active policy must follow the owner's live choice, then resume+ // normal confirmation when the owner tightens back to Ask.+ await handle.setPermissionMode!('bypassPermissions');+ firePermissionRequest('policy-full-access', 'write', input);+ expect(await waitForResponse('policy-full-access')).toMatchObject({ confirmed: true });+ expect(review).toHaveBeenCalledOnce();+ expect(resolver).not.toHaveBeenCalled();+ await handle.setPermissionMode!('ask');+ firePermissionRequest('policy-ask-restored', 'write', input);+ expect(await waitForResponse('policy-ask-restored')).toMatchObject({ confirmed: true });+ expect(resolver).toHaveBeenCalledOnce();});it('reviews MCP operations when turn policy cannot classify them', async () => {@@ -5179,12 +5190,15 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {* 已经失效的卡。此前 resolver 只挂在卡上、切档不会唤醒它,工具调用会一直卡住(codex P1)。* 与 Claude / Codex 的 dismissAllPending 同口径,并发 interaction_dismissed 让 UI 收卡。*/- it('settles an in-flight permission card when the mode widens to Full access', async () => {+ it.each([false, true])('settles an in-flight permission card when the mode widens to Full access (IM policy=%s)', async (imPolicy) => {const handle = await start('ask', undefined, false, {serverNames: ['cindy_browser'],// prompt(非 prompt-each-time)→ 放宽档位时接受替用户放行。policy: () => 'prompt',});+ if (imPolicy) await handle.send({ type: 'user', content: 'Open the page.' }, {+ turnPermissionPolicy: { origin: { kind: 'im', channel: 'feishu' }, confirmationSurface: 'channel', forceConfirmToolCall: () => true },+ });const events: Array<Record<string, unknown>> = [];void (async () => {for await (const e of handle.events()) {diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 9201abd7f3..85792b2535 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -4713,7 +4713,7 @@ export class PiAgent extends BaseAgent {}const requestId = `pi-subagent:${key}`;const turnPolicyForcePrompt = (() => {- if (!activeTurnPermissionPolicy) return false;+ if (!activeTurnPermissionPolicy || permissionMode === 'bypassPermissions') return false;try {return activeTurnPermissionPolicy.forceConfirmToolCall(toolName, input) === true;} catch (error) {@@ -4751,7 +4751,7 @@ export class PiAgent extends BaseAgent {unregister = registerPendingPrompt(requestId, {// control-plane writes must keep forcePrompt across a Full Access// hot-switch; otherwise dismissAllPendingPrompts would allow them.- forcePrompt: options.forcePrompt || adopted || turnPolicyForcePrompt,+ forcePrompt: options.forcePrompt || adopted,...(options.unavailableHandoff ? { unavailableHandoff: true } : {}),// Durable child: losing the surface parks the question.deferWhenSurfaceLost: true,@@ -4822,7 +4822,7 @@ export class PiAgent extends BaseAgent {if (controlPlaneWrite) return requestUserDecision({ forcePrompt: true });if (adopted && permissionMode !== 'auto') return requestUserDecision({ forcePrompt: true });if (permissionMode === 'bypassPermissions') {- return turnPolicyForcePrompt ? 'system-deny' : 'allow';+ return 'allow';}const mcpTarget = resolveMcpToolTarget(toolName, registeredMcpServerNames);const mcpPolicy = (() => {@@ -4852,7 +4852,7 @@ export class PiAgent extends BaseAgent {const hostAutoApprove = mcpPolicy === 'auto-approve' && !turnPolicyForcePrompt && !adopted;const reviewPermissionMode = permissionMode;if (reviewPermissionMode !== 'auto' && !hostAutoApprove) {- return requestUserDecision({ forcePrompt: turnPolicyForcePrompt || mcpPolicy === 'prompt-each-time' });+ return requestUserDecision({ forcePrompt: mcpPolicy === 'prompt-each-time' });}checkingAutomaticPermission = true;try {@@ -8840,6 +8840,7 @@ export class PiAgent extends BaseAgent {const toolName = payload.args === undefined ? 'cindy_pi_extension' : 'cindy_pi_command';const toolInput = payload.args === undefined ? { action: payload.action, source } : { args: payload.args };const forcePrompt = (() => {+ if (context.permissionMode === 'bypassPermissions') return false;try { return context.turnPermissionPolicy?.forceConfirmToolCall(toolName, toolInput) === true; }catch { return true; }})();@@ -8873,7 +8874,7 @@ export class PiAgent extends BaseAgent {return;}if (autoDecision?.unavailable) context.notifyAutoReviewUnavailable();- const approved = (!forcePrompt && getPermissionCtx().permissionMode === 'bypassPermissions')+ const approved = getPermissionCtx().permissionMode === 'bypassPermissions'|| (!forcePrompt && autoDecision?.verdict === 'allow' && getPermissionCtx().permissionMode === 'auto')|| await new Promise<boolean>((resolve) => {if (!context.resolver) {@@ -8894,7 +8895,7 @@ export class PiAgent extends BaseAgent {resolve(value);};unregister = context.registerPendingPrompt(`${id}:pi-extension-mutation`, {- forcePrompt,+ forcePrompt: false,unavailableHandoff: autoDecision?.unavailable,settle: (resolveAs, reason) => {if (settled) return;@@ -9167,7 +9168,7 @@ export class PiAgent extends BaseAgent {* 代码:同步抛错不能变成放行,按"必须询问" fail-closed(与 CC/Codex 同口径)。*/const turnPolicyForcePrompt = ((): boolean => {- if (!turnPermissionPolicy) return false;+ if (!turnPermissionPolicy || permissionMode === 'bypassPermissions') return false;try {return turnPermissionPolicy.forceConfirmToolCall(toolName, input) === true;} catch (err) {@@ -9270,8 +9271,8 @@ export class PiAgent extends BaseAgent {*/const isFullAccessNow = (): boolean => getPermissionCtx().permissionMode === 'bypassPermissions';/**- * MCP 逐次确认和 AI ask 不覆盖 Full access;来源/本轮范围约束与需要用户输入的- * 交互仍保留。是否允许持久化决定,不等于是否继承会话权限。+ * MCP 逐次确认、AI ask 和 IM 策略不覆盖主人当前选择的 Full access;+ * 需要用户输入或明确确认的控制面操作仍保留。*/const requestUserConfirmation = async (opts?: {@@ -9281,19 +9282,17 @@ export class PiAgent extends BaseAgent {},): Promise<PiPermissionResolution> => {// 发起确认前:已切到 Full access 就不该再弹卡。- // 本轮范围仍由 policy 约束,不能把 MCP 风险标记当成第二份会话权限。if (isFullAccessNow() && opts?.requireExplicitDecision !== true) {- return turnPolicyForcePrompt ? 'system-deny' : 'allow';+ return 'allow';}const outcome = await requestUserDecision({- forcePrompt: turnPolicyForcePrompt || opts?.requireExplicitDecision === true,+ forcePrompt: opts?.requireExplicitDecision === true,...(opts?.unavailableHandoff ? { unavailableHandoff: true } : {}),});// 已有决策(用户明确表态,或切档时代为 settle)→ 以它为准,不再被档位二次翻转。if (outcome.decided) return outcome.resolution;// 拿不到决策:Full access 下按 bypass 语义放行,其余一律 fail-closed。- return turnPolicyForcePrompt- || opts?.requireExplicitDecision === true+ return opts?.requireExplicitDecision === true|| !isFullAccessNow()? outcome.resolution: 'allow';@@ -9303,9 +9302,7 @@ export class PiAgent extends BaseAgent {// 已把普通 bypass 拦在冒泡之前,但档位是热切换的:confirm 冒泡之后用户仍可能切到 Full access。此时// MCP 策略 / 灰区审阅 / 弹窗都不该再改变「全放行」语义,也不该因为没有 resolver 就// 拒掉工具调用(与 auto 分支既有的 modeAfterReview bypass 收口同口径)。- // 本轮策略命中时不吃 Full Access 短路:policy + bypassPermissions 已在 send 预检- // 拒绝、且 policy turn 持 host lease 堵死热切到 bypass,故此处 turnPolicyForcePrompt- // 为真本不可达;仍显式 fail-closed,避免任一上游闸门被绕过就静默放行破坏性调用。+ // IM 任务中主人显式切档与普通任务一致,不再由本轮旧策略阻塞。if (controlPlaneWrite) {sendPermissionResolution(await requestUserConfirmation({forcePrompt: true,@@ -9313,7 +9310,7 @@ export class PiAgent extends BaseAgent {}));return;}- if (isFullAccessNow() && !turnPolicyForcePrompt) {+ if (isFullAccessNow()) {sendPermissionResolution('allow');return;}@@ -9380,7 +9377,7 @@ export class PiAgent extends BaseAgent {// - 仍是 auto → 按本次审查 verdict 收口(下方原逻辑)。const modeAfterReview = getPermissionCtx().permissionMode;if (modeAfterReview === 'bypassPermissions') {- sendPermissionResolution(turnPolicyForcePrompt ? 'system-deny' : 'allow');+ sendPermissionResolution('allow');return;}if (modeAfterReview !== permissionMode) {diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 6763b5cc80..5f9c4ccc57 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -4221,7 +4221,9 @@ describe('Session permission mode leases', () => {expect(handle.send).toHaveBeenCalledOnce();});- it('defers an unsafe external permission switch until a host turn lease is released', async () => {+ // Regression: an IM turn lease must not postpone any owner permission choice.+ // Exercise the public Session API while retaining the lease that fences new sends.+ it.each(['ask', 'auto', 'bypassPermissions'] as const)('applies %s immediately during a host turn lease without admitting another turn', async (mode) => {const handle = createHandle({ id: 'permission-host-lease-thread' });const applied: PermissionMode[] = [];handle.setPermissionMode = vi.fn(async (mode: PermissionMode) => {@@ -4253,64 +4255,24 @@ describe('Session permission mode leases', () => {const releaseLease = session.acquireTurnLease();const temporary = await session.setPermissionModeTracked('ask');- const externalChange = session.setPermissionMode('bypassPermissions');- await Promise.resolve();-- expect(applied).toEqual(['ask']);- expect(session.stablePermissionModeState).toBeNull();+ const externalChange = session.setPermissionMode(mode);+ await expect(externalChange).resolves.toBeUndefined();+ expect(applied).toEqual(['ask', mode]);+ expect(session.stablePermissionModeState).toEqual({ mode, generation: 2 });await expect(session.setPermissionModeIfUnchanged(temporary, 'bypassPermissions'),).resolves.toBe(false);- expect(applied).toEqual(['ask']);+ expect(applied).toEqual(['ask', mode]);const nextTurn = session.send('after leased permission change');+ await Promise.resolve();+ expect(handle.send).not.toHaveBeenCalled();releaseLease();- await expect(externalChange).resolves.toBeUndefined();await expect(nextTurn).resolves.toEqual({ accepted: true });- expect(applied).toEqual(['ask', 'bypassPermissions']);+ expect(applied).toEqual(['ask', mode]);expect(handle.send).toHaveBeenCalledOnce();});- it('allows a safe external permission switch during a host turn lease', async () => {- const handle = createHandle({ id: 'permission-safe-host-lease-thread' });- const applied: PermissionMode[] = [];- handle.setPermissionMode = vi.fn(async (mode: PermissionMode) => {- applied.push(mode);- });- const baseCapabilities = createAgent(async () => handle).capabilities;- const session = new Session({- id: 'permission-safe-host-lease-session',- agentKind: 'codex',- workDir: '/repo',- handle,- capabilities: {- ...baseCapabilities,- permissionModes: [- { id: 'ask', displayName: 'Ask' },- { id: 'auto', displayName: 'Auto' },- { id: 'bypassPermissions', displayName: 'Full access' },- ],- setPermissionModeMidSession: { supported: true },- turnPermissionPolicy: {- supported: { supported: true },- unsupportedPermissionModes: ['bypassPermissions'],- },- },- logger: createLogger(),- permissionMode: 'bypassPermissions',- });-- const releaseLease = session.acquireTurnLease();- const temporary = await session.setPermissionModeTracked('ask');- await expect(session.setPermissionMode('auto')).resolves.toBeUndefined();- await expect(- session.setPermissionModeIfUnchanged(temporary, 'bypassPermissions'),- ).resolves.toBe(false);- releaseLease();-- expect(applied).toEqual(['ask', 'auto']);- expect(session.permissionModeState).toEqual({ mode: 'auto', generation: 2 });- });});describe('Maker invalid-resume persistence bridge', () => {diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 5f6381e2a9..ad6b7ed16f 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -844,8 +844,7 @@ export class Session {return { accepted: false, reason: 'cancelled-before-dispatch' };}}- // A user/API permission change may have been waiting for the lease above.- // Preserve its ordering before admitting the next turn.+ // Preserve user/API permission change ordering before admitting the next turn.while (this.externalPermissionModeChangesInFlight > 0) {if (await this.waitForGateOrAbort(this.externalPermissionModeChangeChain, handleOpts.signal)) {return { accepted: false, reason: 'cancelled-before-dispatch' };@@ -1904,16 +1903,8 @@ export class Session {this.assertPermissionModeSupported(mode);this.externalPermissionModeChangesInFlight += 1;const operation = this.externalPermissionModeChangeChain.catch(() => undefined).then(async () => {- if (this.isTurnPermissionPolicyUnsafe(mode)) {- // Official group turns hold a host lease until background continuations- // and the temporary safe-mode restore have both settled. Do not let an- // external Full access / accept-edits switch weaken that active turn.- // Host-owned temporary switches use setPermissionModeTracked and remain- // able to restore while this operation waits, avoiding a lease deadlock.- while (this.hostTurnLeases.size > 0) {- await Promise.all([...this.hostTurnLeases]);- }- }+ // The owner's live permission choice applies equally to IM and Desktop+ // turns. Host leases fence new sends/retirement, not permission changes.await this.setPermissionModeTracked(mode);});const tracked = operation.finally(() => {@@ -1967,9 +1958,8 @@ export class Session {mode: PermissionMode,): Promise<boolean> {this.assertPermissionModeSupported(mode);- // An external request is newer user intent even when an unsafe target is- // still waiting for a host turn lease. Never restore over it, and never- // wait here: that request may need this restore path to release the lease.+ // An external request is newer user intent, including while its runtime+ // update is still in flight. Never restore over it.if (this.externalPermissionModeChangesInFlight > 0) return false;this.permissionModeChangesInFlight += 1;const operation = this.permissionModeChangeChain.catch(() => undefined).then(async () => {@@ -2014,10 +2004,6 @@ export class Session {}}- private isTurnPermissionPolicyUnsafe(mode: PermissionMode): boolean {- return this.capabilities.turnPermissionPolicy?.unsupportedPermissionModes.includes(mode) === true;- }-async setFastMode(enabled: boolean | 'ultrafast'): Promise<void> {this.ensureActive();if (!this.handle.setFastMode) {