Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(claude-code): 非 Claude 主模型会话不再被内置 Explore 改判成 Opus (#3879)
Lizib5034d60fbfc
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.tsindex 532ce558f9..c5c5c38f32 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts@@ -3,9 +3,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';import type { AgentRuntimeConfig } from '../../../interfaces/runtime-config.js';import {+ EXPLORE_INHERIT_CAP_DISABLE_ENV,SENSITIVE_ANTHROPIC_ENV_KEYS,+ applyExploreInheritCapEnv,applySubagentModelEnv,buildClaudeEnv,+ exploreInheritCapEnvNeedsSync,+ shouldDisableExploreInheritCap,} from '../env-builder.js';const MODEL_CONTEXT_WINDOWS_ENV = 'XDT_MAKER_MODEL_CONTEXT_WINDOWS';@@ -35,6 +39,7 @@ describe('buildClaudeEnv', () => {const originalSubagentModel = process.env.CLAUDE_CODE_SUBAGENT_MODEL;const originalMaxContextTokens = process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS;const originalCompactPctOverride = process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE;+ const originalExploreInheritCap = process.env[EXPLORE_INHERIT_CAP_DISABLE_ENV];afterEach(() => {if (originalDisableCron === undefined) {@@ -54,6 +59,7 @@ describe('buildClaudeEnv', () => {restore('CLAUDE_CODE_SUBAGENT_MODEL', originalSubagentModel);restore('CLAUDE_CODE_MAX_CONTEXT_TOKENS', originalMaxContextTokens);restore('CLAUDE_AUTOCOMPACT_PCT_OVERRIDE', originalCompactPctOverride);+ restore(EXPLORE_INHERIT_CAP_DISABLE_ENV, originalExploreInheritCap);});it('disables Claude Code native cron for host-managed sessions', async () => {@@ -350,6 +356,99 @@ describe('buildClaudeEnv', () => {expect(env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE).toBe('80');});+ describe('built-in Explore inherit cap (CC 2.1.198+)', () => {+ // 上游把内置 Explore 的 `model: "inherit"` 按「模型名里有没有 haiku/sonnet/opus」+ // 判定是否超过 opus,超了就**替换**成 opus。经 fp 路由的非 Claude 模型全部误判。+ it('disables the cap for non-Claude session models so Explore inherits the parent', async () => {+ for (const activeModel of ['gpt-5.6-sol[1m]', 'codex/gpt-5.6-sol', 'z-ai/glm-5.2[1m]']) {+ const env = await buildClaudeEnv(createAuthAdapter(), {}, { activeModel });+ expect(env[EXPLORE_INHERIT_CAP_DISABLE_ENV], activeModel).toBe('1');+ }+ });++ it('keeps upstream behaviour for Claude-family session models', async () => {+ // haiku / sonnet / opus:cap 本来就不触发,设了反而是无谓的行为变化。+ // fable:不在那三档里 → cap 会触发,而那是上游有意的成本上限,必须保留。+ for (const activeModel of [+ 'claude-opus-5[1m]',+ 'claude-sonnet-5',+ 'claude-haiku-4-5-20251001',+ 'claude-fable-5-1',+ 'anthropic/claude-fable-5-1',+ ]) {+ const env = await buildClaudeEnv(createAuthAdapter(), {}, { activeModel });+ expect(env[EXPLORE_INHERIT_CAP_DISABLE_ENV], activeModel).toBeUndefined();+ }+ });++ it('does not guess when the spawn model is unknown', async () => {+ const env = await buildClaudeEnv(createAuthAdapter(), {});++ expect(env[EXPLORE_INHERIT_CAP_DISABLE_ENV]).toBeUndefined();+ expect(shouldDisableExploreInheritCap(undefined)).toBe(false);+ expect(shouldDisableExploreInheritCap(' ')).toBe(false);+ });++ it('keeps an explicit override from behaviorFlags or the inherited host env', async () => {+ const flagged = await buildClaudeEnv(+ createAuthAdapter(),+ { behaviorFlags: { [EXPLORE_INHERIT_CAP_DISABLE_ENV]: '0' } },+ { activeModel: 'gpt-5.6-sol[1m]' },+ );+ expect(flagged[EXPLORE_INHERIT_CAP_DISABLE_ENV]).toBe('0');++ process.env[EXPLORE_INHERIT_CAP_DISABLE_ENV] = '0';+ const inherited = await buildClaudeEnv(createAuthAdapter(), {}, {+ activeModel: 'gpt-5.6-sol[1m]',+ });+ expect(inherited[EXPLORE_INHERIT_CAP_DISABLE_ENV]).toBe('0');+ });++ it('applies to the remote spawn env too', async () => {+ // 远端 daemon 跑的是同一个 CC CLI,同一个误判。+ const env = await buildClaudeEnv(createAuthAdapter(), {}, {+ mode: 'remote',+ activeModel: 'gpt-5.6-sol[1m]',+ });++ expect(env[EXPLORE_INHERIT_CAP_DISABLE_ENV]).toBe('1');+ });++ it('replaces a Cindy-managed cap flag when the live model crosses the policy boundary', () => {+ const env: Record<string, string> = {+ [EXPLORE_INHERIT_CAP_DISABLE_ENV]: '1',+ };++ applyExploreInheritCapEnv(env, 'claude-fable-5', 'replace');+ expect(env[EXPLORE_INHERIT_CAP_DISABLE_ENV]).toBeUndefined();++ applyExploreInheritCapEnv(env, 'gpt-5.6-sol[1m]', 'replace');+ expect(env[EXPLORE_INHERIT_CAP_DISABLE_ENV]).toBe('1');+ });++ it('keeps an explicit override in if-undefined mode even when replace would flip it', () => {+ const env: Record<string, string> = {+ [EXPLORE_INHERIT_CAP_DISABLE_ENV]: '0',+ };++ applyExploreInheritCapEnv(env, 'gpt-5.6-sol[1m]', 'if-undefined');+ expect(env[EXPLORE_INHERIT_CAP_DISABLE_ENV]).toBe('0');+ });++ it('treats an explicit override as already in sync so live switches do not rebuild', () => {+ const env: Record<string, string> = {+ [EXPLORE_INHERIT_CAP_DISABLE_ENV]: '0',+ };+ expect(exploreInheritCapEnvNeedsSync(env, 'gpt-5.6-sol[1m]')).toBe(false);+ expect(exploreInheritCapEnvNeedsSync(env, 'claude-fable-5')).toBe(false);+ expect(exploreInheritCapEnvNeedsSync({}, 'gpt-5.6-sol[1m]')).toBe(true);+ expect(exploreInheritCapEnvNeedsSync(+ { [EXPLORE_INHERIT_CAP_DISABLE_ENV]: '1' },+ 'claude-fable-5',+ )).toBe(true);+ });+ });+it('defaults command output to plain text across common CLI color controls', async () => {delete process.env.NO_COLOR;delete process.env.CLICOLOR;diff --git a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.tsindex 673fd2efdc..e73db76c17 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts@@ -358,6 +358,193 @@ describe('ClaudeCodeAgent runtime settings during rewind window', () => {await handle.close();});+ it('rebuilds the local Query env when a live switch crosses the Explore inherit-cap policy', async () => {+ const { handle, firstQuery } = await startRewindableSession({+ model: 'gpt-5.6-sol',+ availableModels: [+ {+ id: 'gpt-5.6-sol',+ displayName: 'GPT 5.6 Sol',+ contextWindow: 256_000,+ efforts: ['high'],+ defaultEffort: 'high',+ },+ {+ id: 'claude-fable-5',+ displayName: 'Claude Fable 5',+ contextWindow: 1_000_000,+ efforts: ['high'],+ defaultEffort: 'high',+ },+ ],+ });+ void (async () => {+ try { for await (const _event of handle.events()) { /* drain */ } } catch { /* ignore */ }+ })();+ firstQuery.stream.emit({ type: 'system', subtype: 'init', session_id: 'sdk-explore-cap' });+ await vi.waitFor(() => {+ expect(handle.id).toBe('sdk-explore-cap');+ });++ const startEnv = sdkMock.query.mock.calls[0]?.[0]?.options?.env as Record<string, string> | undefined;+ expect(startEnv?.CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP).toBe('1');++ await handle.setModel?.('claude-fable-5');+ expect(firstQuery.setModel).toHaveBeenCalledWith('claude-fable-5[1m]');++ const secondQuery = createFakeQuery();+ sdkMock.query.mockReturnValue(secondQuery);+ await handle.send({ type: 'user', content: 'after crossing to fable' });++ expect(sdkMock.query).toHaveBeenCalledTimes(2);+ expect(firstQuery.close).toHaveBeenCalled();+ const rebuildEnv = sdkMock.query.mock.calls[1]?.[0]?.options?.env as Record<string, string> | undefined;+ expect(rebuildEnv?.CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP).toBeUndefined();+ expect(sdkMock.query.mock.calls[1]?.[0]?.options?.forkSession).toBe(true);+ expect(sdkMock.query.mock.calls[1]?.[0]?.options?.resumeSessionAt).toBeUndefined();++ await handle.close();+ });++ it('rebuilds the local Query env when a live switch from Fable to GPT re-enables the cap disable flag', async () => {+ const { handle, firstQuery } = await startRewindableSession({+ model: 'claude-fable-5',+ availableModels: [+ {+ id: 'claude-fable-5',+ displayName: 'Claude Fable 5',+ contextWindow: 1_000_000,+ efforts: ['high'],+ defaultEffort: 'high',+ },+ {+ id: 'gpt-5.6-sol',+ displayName: 'GPT 5.6 Sol',+ contextWindow: 256_000,+ efforts: ['high'],+ defaultEffort: 'high',+ },+ ],+ });+ void (async () => {+ try { for await (const _event of handle.events()) { /* drain */ } } catch { /* ignore */ }+ })();+ firstQuery.stream.emit({ type: 'system', subtype: 'init', session_id: 'sdk-explore-cap-gpt' });+ await vi.waitFor(() => {+ expect(handle.id).toBe('sdk-explore-cap-gpt');+ });++ const startEnv = sdkMock.query.mock.calls[0]?.[0]?.options?.env as Record<string, string> | undefined;+ expect(startEnv?.CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP).toBeUndefined();++ await handle.setModel?.('gpt-5.6-sol');++ const secondQuery = createFakeQuery();+ sdkMock.query.mockReturnValue(secondQuery);+ await handle.send({ type: 'user', content: 'after crossing to gpt' });++ expect(sdkMock.query).toHaveBeenCalledTimes(2);+ const rebuildEnv = sdkMock.query.mock.calls[1]?.[0]?.options?.env as Record<string, string> | undefined;+ expect(rebuildEnv?.CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP).toBe('1');++ await handle.close();+ });++ it('does not rebuild the Query when a live switch stays on the same Explore inherit-cap policy', async () => {+ const { handle, firstQuery } = await startRewindableSession();+ void (async () => {+ try { for await (const _event of handle.events()) { /* drain */ } } catch { /* ignore */ }+ })();+ firstQuery.stream.emit({ type: 'system', subtype: 'init', session_id: 'sdk-explore-cap-same' });+ await vi.waitFor(() => {+ expect(handle.id).toBe('sdk-explore-cap-same');+ });++ await handle.setModel?.('claude-sonnet-5');+ await handle.send({ type: 'user', content: 'same-policy switch' });++ expect(sdkMock.query).toHaveBeenCalledTimes(1);+ expect(firstQuery.setModel).toHaveBeenCalledWith('claude-sonnet-5');++ await handle.close();+ });++ it('rejects a remote live switch that would desync the Explore inherit-cap env', async () => {+ const { handle, firstQuery } = await startRewindableSession({+ remoteHostId: 'remote-1',+ model: 'claude-fable-5',+ availableModels: [+ {+ id: 'claude-fable-5',+ displayName: 'Claude Fable 5',+ contextWindow: 1_000_000,+ efforts: ['high'],+ defaultEffort: 'high',+ },+ {+ id: 'gpt-5.6-sol',+ displayName: 'GPT 5.6 Sol',+ contextWindow: 256_000,+ efforts: ['high'],+ defaultEffort: 'high',+ },+ ],+ });+ void (async () => {+ try { for await (const _event of handle.events()) { /* drain */ } } catch { /* ignore */ }+ })();+ firstQuery.stream.emit({ type: 'system', subtype: 'init', session_id: 'sdk-remote-explore-cap' });+ await vi.waitFor(() => {+ expect(handle.id).toBe('sdk-remote-explore-cap');+ });++ await expect(handle.setModel?.('gpt-5.6-sol')).rejects.toThrow(+ /REMOTE_MODEL_SWITCH_ROUTE_CHANGE/,+ );+ expect(firstQuery.setModel).not.toHaveBeenCalled();+ expect(handle.model).toBe('claude-fable-5');++ await handle.close();+ });++ it('rejects a remote Explore inherit-cap switch even while rewind rebuild is pending', async () => {+ const { handle, firstQuery } = await startRewindableSession({+ remoteHostId: 'remote-1',+ model: 'claude-fable-5',+ availableModels: [+ {+ id: 'claude-fable-5',+ displayName: 'Claude Fable 5',+ contextWindow: 1_000_000,+ efforts: ['high'],+ defaultEffort: 'high',+ },+ {+ id: 'gpt-5.6-sol',+ displayName: 'GPT 5.6 Sol',+ contextWindow: 256_000,+ efforts: ['high'],+ defaultEffort: 'high',+ },+ ],+ });+ void (async () => {+ try { for await (const _event of handle.events()) { /* drain */ } } catch { /* ignore */ }+ })();+ firstQuery.stream.emit({ type: 'system', subtype: 'init', session_id: 'sdk-remote-explore-cap-rewind' });+ await vi.waitFor(() => {+ expect(handle.id).toBe('sdk-remote-explore-cap-rewind');+ });++ await handle.commitRewindFiles?.('user-uuid-1', 'assistant-uuid-1');+ await expect(handle.setModel?.('gpt-5.6-sol')).rejects.toThrow(+ /REMOTE_MODEL_SWITCH_ROUTE_CHANGE/,+ );+ expect(handle.model).toBe('claude-fable-5');++ await handle.close();+ });+it('uses the session provider route when the same model id has different windows', async () => {const configDir = await makeTempDir();process.env.CLAUDE_CONFIG_DIR = configDir;diff --git a/packages/maker-core/src/agents/claude-code/env-builder.ts b/packages/maker-core/src/agents/claude-code/env-builder.tsindex 9fdfbe2e79..3d2b49e75f 100644--- a/packages/maker-core/src/agents/claude-code/env-builder.ts+++ b/packages/maker-core/src/agents/claude-code/env-builder.ts@@ -271,6 +271,119 @@ export function applySubagentModelEnv(else delete env.CLAUDE_CODE_SUBAGENT_MODEL;}+export const EXPLORE_INHERIT_CAP_DISABLE_ENV = 'CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP';++/**+ * CC 判定「主模型是否在 Explore inherit cap 之内」用的家族词(2.1.259 反编译里的 `ven`,+ * cap 值 `Cen = "opus"`,取 `ven.slice(0, indexOf(cap)+1)` = 整个数组)。CC 侧是**子串**+ * 匹配、大小写不敏感,这里照抄它的口径,不要换成前缀或精确匹配。+ */+const EXPLORE_CAP_TIER_WORDS = ['haiku', 'sonnet', 'opus'] as const;++/**+ * cap 只对 Claude 家族才算「限高」。家族里不在上面三档中的成员(Fable)被 cap 收到 Opus+ * 是上游有意的成本上限,必须保留 —— 所以这里额外识别家族标记。+ *+ * 与 `apps/desktop` 的 `ANTHROPIC_WIRE_MODEL_PREFIXES` 刻意不复用:那份在 main 进程,+ * maker-core 反向 import 会破坏依赖方向(见 docs/dev-rules/architecture-invariants.md)。+ * 两处都只是「前缀/子串兜底地板」,新增 Anthropic 家族名时同步加词即可。+ */+const CLAUDE_FAMILY_MARKERS = ['claude', 'fable'] as const;++/**+ * 内置 `Explore` 子代理的 inherit cap 是否该关掉。+ *+ * ## 上游行为(CC 2.1.198 起,CHANGELOG:「now inherits the main session's model (capped+ * at opus) instead of running on haiku」;2.1.259 反编译)+ *+ * 内置 Explore 声明的是 `model: "inherit"`,但派发前先过一层 cap:+ *+ * ```js+ * function FX(agent, mainLoopModel) {+ * if (agent.agentType !== "Explore" || agent.source !== "built-in") return agent.model;+ * if (env.CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP) return "inherit";+ * return r7r(mainLoopModel) ? { inheritCap: "opus" } : "inherit";+ * }+ * function r7r(m) {+ * if (provider() !== "firstParty") return false;+ * return !containsAnyWord(m, ["haiku", "sonnet", "opus"]); // 纯子串匹配+ * }+ * ```+ *+ * 而 `{ inheritCap: "opus" }` 到了 resolver 里会被拆成裸别名 `"opus"`,之后与「用户手写+ * `model: opus`」完全同路 —— **它不是天花板,是直接替换**。+ *+ * ## 为什么要关+ *+ * 「在 cap 之内」是靠**模型名里有没有那三个词**判定的。Cindy 的 fp 路由在 CC 眼里是+ * firstParty,而经它路由的非 Claude 模型(`gpt-5.6-sol[1m]` 等)名字里三个词都没有,于是+ * 被判成「超过 opus」→ 静默改判成 Opus。实测:GPT 会话里 8 次 Explore 派发,3 次没带+ * `model` 参数的全部打到 `claude-opus-5[1m]`,跨了供应商与计费(另 5 次调用时显式写了+ * 模型,per-invocation 参数优先级更高,照旧生效)。+ *+ * 上游的意图对 Claude 家族是成立的(别比 Opus 更贵),对它认不出的模型则是把「未知」+ * 当成了「更贵」。所以只在后者把开关打开,其余场景一律保持上游行为:+ *+ * | 主模型 | 结果 |+ * |---|---|+ * | Opus / Sonnet / Haiku | 不设 —— cap 本来就不触发,行为零变化 |+ * | Fable | 不设 —— 保留上游的成本上限 |+ * | 非 Claude(GPT / 网关模型…) | 设 —— Explore 跟随主模型 |+ *+ * 非 firstParty 路由本来就走不到 cap,那里设了也只是 no-op,不额外分支。+ *+ * ## 已知边界+ *+ * - **依赖一个未公开的 env**。上游哪天移除,这里静默退回现状(不会崩)。单测钉住的只是本+ * 函数的判定表,**钉不住二进制行为** —— 上面那段反编译是 2.1.259+ * (`tools/claude/latest.json` 的 pin)的实测结论,升级 CC 后请回到二进制里重新核对+ * `FX` / `r7r` 与 `ven`/`Cen`,再决定这张表是否还成立。+ * - 本机热切若跨过这张表,由 `applyExploreInheritCapEnv(..., 'replace')` 改字典,下一+ * 次 send 重建 Query 让子进程吃到新 env。远端 daemon 烤死 spawn env,跨表则拒绝切模。+ */+export function shouldDisableExploreInheritCap(activeModel: string | undefined): boolean {+ const model = activeModel?.trim().toLowerCase();+ // 拿不到本次 spawn 的模型时不猜,保持上游行为。+ if (!model) return false;+ if (EXPLORE_CAP_TIER_WORDS.some((word) => model.includes(word))) return false;+ if (CLAUDE_FAMILY_MARKERS.some((word) => model.includes(word))) return false;+ return true;+}++/**+ * 把 Explore inherit-cap 开关写进(或移出) env 字典。+ *+ * - `if-undefined`:spawn 用。behaviorFlags / 用户显式设的值优先,只在键缺失时注入 `'1'`。+ * - `replace`:本机热切跨策略时用。只动 Cindy 注入的 `'1'` / 缺省,不碰显式覆盖(如 `'0'`)。+ */+export function applyExploreInheritCapEnv(+ env: Record<string, string>,+ activeModel: string | undefined,+ mode: 'if-undefined' | 'replace',+): void {+ const disable = shouldDisableExploreInheritCap(activeModel);+ if (mode === 'if-undefined') {+ if (env[EXPLORE_INHERIT_CAP_DISABLE_ENV] === undefined && disable) {+ env[EXPLORE_INHERIT_CAP_DISABLE_ENV] = '1';+ }+ return;+ }+ const current = env[EXPLORE_INHERIT_CAP_DISABLE_ENV];+ if (current !== undefined && current !== '1') return;+ if (disable) env[EXPLORE_INHERIT_CAP_DISABLE_ENV] = '1';+ else delete env[EXPLORE_INHERIT_CAP_DISABLE_ENV];+}++/** Cindy 可改写的 cap 开关是否与目标模型失配。显式覆盖(非 `'1'`)视为用户钉死,不算失配。 */+export function exploreInheritCapEnvNeedsSync(+ env: Record<string, string>,+ activeModel: string | undefined,+): boolean {+ const current = env[EXPLORE_INHERIT_CAP_DISABLE_ENV];+ if (current !== undefined && current !== '1') return false;+ return shouldDisableExploreInheritCap(activeModel) !== (current === '1');+}+/*** 组装最终注入到 sdkQuery options.env 的字典。* 顺序:cleanEnv → behaviorFlags → endpoint → authEnv(鉴权最后,避免被 behaviorFlags 覆盖)@@ -377,6 +490,10 @@ export async function buildClaudeEnv(env.ANTHROPIC_SMALL_FAST_MODEL = options.smallFastModel;}+ // 非 Claude 主模型的会话关掉内置 Explore 的 inherit cap ——+ // 否则 CC 会把它静默改判成 Opus(判据与代价见 shouldDisableExploreInheritCap)。+ applyExploreInheritCapEnv(env, options.activeModel, 'if-undefined');+// 第三道防线: 告诉 CC CLI "provider 路由由 host 接管"。// CC 内部 filterSettingsEnv 看到此标记后,会从所有 settings-sourced env 中剥掉// ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN 等 provider 相关字段,diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex cab3129ed5..b6a27bb904 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -108,9 +108,11 @@ import { formatManagedImageReferences } from '../shared/managed-image-reference.import { pickTurnStartStatus, type OneShotState } from '../shared/turn-start-phrases.js';import { ToolLoopGuard } from '../shared/loop-guard.js';import {+ applyExploreInheritCapEnv,applyOAuthSpawnEntrypointGate,applySubagentModelEnv,buildClaudeEnv,+ exploreInheritCapEnvNeedsSync,REMOTE_ROUTE_OVERRIDE_ENV_KEYS,} from './env-builder.js';import { buildClaudeFlagSettings } from './flag-settings.js';@@ -2522,6 +2524,11 @@ export class ClaudeCodeAgent extends BaseAgent {let autoReviewDirectoryGeneration = 0;let activeQueryDirectoryGeneration = autoReviewDirectoryGeneration;let extraDirsRebuildAttempted = false;+ // 本机热切跨过 Explore inherit-cap 策略后,子进程 env 必须随 Query 重建。+ // 代际与 extraDirs 同款:setModel 只加代,buildQuery 才把当前 Query 标成已吃进+ // 该代。await buildQuery 期间再切一次不会被这次 spawn 误标成已同步。+ let exploreInheritCapEnvGeneration = 0;+ let activeQueryExploreInheritCapGeneration = exploreInheritCapEnvGeneration;// 拷贝进工作目录只允许作 Claude resume 不吃新 additionalDirectories 时的临时缺口。// 默认关闭;启用条件:extraDirsRebuildAttempted 且下一 Query 代际仍落后。落地后// library extraDirs 重建成功即删副本,不得把拷贝写成架构。@@ -3588,6 +3595,7 @@ export class ClaudeCodeAgent extends BaseAgent {activeQueryHasDirectoryGrants = additionalDirectories.length > 0;activeQueryDirectoryGeneration = autoReviewDirectoryGeneration;extraDirsRebuildAttempted = false;+ activeQueryExploreInheritCapGeneration = exploreInheritCapEnvGeneration;const sdkStartPermissionMode = extra?.permissionMode ?? effectiveSdkPermissionMode();sdkInPlanMode = sdkStartPermissionMode === 'plan';const query = sdkQuery({@@ -5515,6 +5523,13 @@ export class ClaudeCodeAgent extends BaseAgent {) {pendingRewindTo = sdkSessionId;extraDirsRebuildAttempted = true;+ } else if (+ activeQueryExploreInheritCapGeneration !== exploreInheritCapEnvGeneration+ && !pendingRewindTo+ && !activeBridgeRewindResumeAt+ && sdkSessionId+ ) {+ pendingRewindTo = sdkSessionId;} else if (extraDirsCopyFallbackEnabled&& extraDirsRebuildAttempted@@ -6484,7 +6499,24 @@ export class ClaudeCodeAgent extends BaseAgent {}const sdkModel = sdkModelFor(newModel);const isControlBlocked = controlRequestsBlocked();- log.debug('setModel', { from: mutableModel, to: newModel, sdk: sdkModel, controlRequestsBlocked: isControlBlocked });+ const liveEnv = opts.remoteHostId ? remoteEnv : env;+ const exploreInheritCapNeedsRebuild = liveEnv+ ? exploreInheritCapEnvNeedsSync(liveEnv, sdkModel)+ : false;+ if (exploreInheritCapNeedsRebuild && opts.remoteHostId) {+ // 与远端路由变化同码:daemon 烤死 spawn env,热切改不了 Explore cap。+ // host 已把 REMOTE_MODEL_SWITCH_ROUTE_CHANGE 映射成「关闭并重建远程任务」。+ throw new Error(+ `[REMOTE_MODEL_SWITCH_ROUTE_CHANGE] switching to "${newModel}" would desync the remote Explore inherit-cap env; close and recreate the remote session to apply it`,+ );+ }+ log.debug('setModel', {+ from: mutableModel,+ to: newModel,+ sdk: sdkModel,+ controlRequestsBlocked: isControlBlocked,+ exploreInheritCapNeedsRebuild,+ });if (!isControlBlocked) {// flag settings 只在 Query 创建时写入。热切若只调 setModel,Claude Code// 仍按启动时的组织白名单校验,后加载的网关模型会报@@ -6552,6 +6584,14 @@ export class ClaudeCodeAgent extends BaseAgent {}// 适用性在 getToolLoopGuard 里按已更新的 mutableModel 逐 scope 判,这里只清状态。resetToolLoopGuards();+ if (exploreInheritCapNeedsRebuild && liveEnv && !opts.remoteHostId) {+ applyExploreInheritCapEnv(liveEnv, sdkModel, 'replace');+ // 子进程 env 在 spawn 时钉死,Query.setModel 改不了。只改字典并加代,+ // 下一轮 send 再走 extraDirs 同款 resume+fork 重建。这里不碰+ // pendingRewindTo:热切若落在 in-flight turn / rewind 接受窗,提前设标记+ // 会让 forward loop 把当前 Query 当成过渡态静音。+ exploreInheritCapEnvGeneration += 1;+ }},async setEffort(newEffort: Effort) {diff --git a/packages/maker-core/src/agents/claude-code/subagent-model-default.ts b/packages/maker-core/src/agents/claude-code/subagent-model-default.tsindex 761e0279db..fbcb4b25a4 100644--- a/packages/maker-core/src/agents/claude-code/subagent-model-default.ts+++ b/packages/maker-core/src/agents/claude-code/subagent-model-default.ts@@ -14,6 +14,26 @@* env 变量是**强制覆盖**,平台没有「最低优先级默认值」这个位置。于是用户手写 agent 里的* `model:` 一旦设过该设置就**静默失效** —— 说的是默认,做的是覆盖。*+ * ## ⚠️ 上面那张表在 cc 2.1.259 上已经不成立(2026-09-03 实测,尚未据此改行为)+ *+ * 反编译 2.1.259 的解析函数,env **从最高降到了最低**:+ *+ * 1. 每次调用传入的 model 参数+ * 2. agent frontmatter 的 model —— 且写 `"inherit"` 会直接短路回主会话模型+ * 3. `CLAUDE_CODE_SUBAGENT_MODEL` ← 只在该 agent **完全没声明** model 时才轮到它+ * 4. 主会话模型+ *+ * 另有 `CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1` 恢复旧的「env 压过一切」。+ *+ * 两个直接后果:+ * - 下面「有人声明 model 就整个会话不设 env」的条件化**已无必要**(env 再也盖不掉+ * frontmatter),但也无害,所以先不动 —— 改它要连带重跑那个判别实验;+ * - 内置 `Explore` 自己声明了 `model: "inherit"`,会在读 env 之前短路,所以这个设置+ * **对它从来不生效**。它另有一层 cap,见 env-builder.ts 的+ * `shouldDisableExploreInheritCap`。+ *+ * 结论保持:要动这段逻辑,先回到当前 pin 的二进制里重新核对解析顺序,别只信这段文字。+ ** ## 做法:条件化地设不设 env** | 会话里的情况 | 做法 | 效果 |