Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 跟进换模型建议只在换得有用且装得下时给出 (#6458)
Chris Zhang8eccf422a8e0
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/followUpRoute.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/followUpRoute.test.tsnew file mode 100644index 0000000000..b36959d6e3--- /dev/null+++ b/apps/desktop/src/main/bot-autonomy/__tests__/followUpRoute.test.ts@@ -0,0 +1,109 @@+/**+ * 测试价值+ * - 生产入口与可观察结果:suggestFollowUpRoute 给出的换模型建议(get_task_digest 的 suggested_route),+ * 伙伴跟进时照它用 set_session_runtime 代主人换模型;deriveFollowUpUsage 是交给它的可信上下文用量+ * (taskDigestHost 读运行时与库值后经它推导)。+ * - Bug/规则依据:2026-10-19 用户反馈「伙伴把会话的模型切了,上下文直接满了」——任务因工具循环中断,+ * 伙伴照建议把主人用 1M 模型跑的任务换到自己链首的 272K 模型。换模型救不了工具循环;主人自己选的模型+ * 不在伙伴链里时建议退回链首;换过去用量超过提醒线也照样建议。+ * - 现有覆盖缺口:nextBotModelRoute 的测试只覆盖伙伴自己任务的候选链降级,不涉及跟进别人任务时的失败类型、+ * 链外路线与上下文余量;运行时 / 库值的用量推导此前没有任何测试驱动(PR review 指出,三轮修复里各改错过一次)。+ * - 最小失败输入:工具循环出错;只带 SDK invalid_request 或 Codex badRequest 的出错;链外的当前路线(含同模型异供应商);+ * 220K 用量从 1M 换到 272K;没有可信用量时缩窗;用量上限下的正常降级。+ * - tier:unit(纯函数,无数据库与 Electron)。+ */+import { describe, expect, it } from 'vitest';++import { deriveFollowUpUsage, suggestFollowUpRoute, type FollowUpRouteInput } from '../followUpRoute.js';++const OPUS = { harness: 'claude', model: 'claude-opus-5-5', providerId: 'anthropic' } as const;+const SOL = { harness: 'codex', model: 'gpt-6.1-sol', providerId: 'openai' } as const;+const GEMINI = { harness: 'pi', model: 'gemini-3-pro', providerId: 'google' } as const;+const WINDOWS: Record<string, number> = { 'claude-opus-5-5': 1_000_000, 'gpt-6.1-sol': 272_000, 'gemini-3-pro': 1_000_000 };++function input(overrides: Partial<FollowUpRouteInput> = {}): FollowUpRouteInput {+ return {+ chain: [OPUS, SOL, GEMINI],+ current: OPUS,+ failure: { phase: 'usage-limit', error: '已达用量上限', errorReason: null },+ visitedRoutes: [],+ sameHarnessOnly: false,+ contextTokens: 40_000,+ currentContextWindow: 1_000_000,+ windowOf: (route) => WINDOWS[route.model] ?? null,+ ...overrides,+ };+}++describe('follow-up route suggestion', () => {+ it('suggests the next companion route when the task hit a usage limit with room to spare', () => {+ expect(suggestFollowUpRoute(input())).toMatchObject(SOL);+ });++ it('gives no suggestion for failures a different model cannot fix', () => {+ const errored = (error: string, errorReason: string | null) =>+ suggestFollowUpRoute(input({ failure: { phase: 'errored', error, errorReason } }));+ expect(errored('任务因重复工具调用形成循环而中断', 'tool_use_loop_detected')).toBeNull();+ expect(errored('prompt is too long', 'context-overflow')).toBeNull();+ // 没有可判断的错误:不猜。+ expect(errored('', null)).toBeNull();+ // 摘要投影没有 reason、只有运行时记下的 SDK 结构化字段:请求本身无效 / 输出超限。+ const withSdk = (sdkError: string, errorStatus?: number) => suggestFollowUpRoute(input({+ failure: { phase: 'errored', error: 'API Error', errorReason: null, sdkError, errorStatus },+ }));+ expect(withSdk('invalid_request', 400)).toBeNull();+ expect(withSdk('max_output_tokens')).toBeNull();+ // Codex 只带结构化 tag(如 badRequest),消息里没有可匹配的文字。+ expect(suggestFollowUpRoute(input({+ failure: { phase: 'errored', error: 'turn failed', errorReason: null, codexErrorInfo: 'badRequest' },+ }))).toBeNull();+ // 那台账号的问题:换得过去。+ expect(errored('authentication_failed: OAuth token has expired', null)).toMatchObject(SOL);+ });++ it('leaves a task whose model the owner chose alone instead of jumping to the companion primary route', () => {+ const ownerChoice = { harness: 'claude', model: 'claude-fable-5-1', providerId: 'anthropic' } as const;+ expect(suggestFollowUpRoute(input({ current: ownerChoice }))).toBeNull();+ // 同一模型、明确不同的供应商也是主人自己的选择。+ expect(suggestFollowUpRoute(input({ current: { ...OPUS, providerId: 'xd' } }))).toBeNull();+ });++ it('skips a smaller window the current context would crowd, and keeps a larger one', () => {+ // 220K 进 272K 是 81%,过提醒线:跳过 Sol,落到同样 1M 的下一条。+ expect(suggestFollowUpRoute(input({ contextTokens: 220_000 }))).toMatchObject(GEMINI);+ expect(suggestFollowUpRoute(input({ contextTokens: 220_000, chain: [OPUS, SOL] }))).toBeNull();+ // 没有可信用量(会话已关、库里的值可能低报):不缩窗,只留同样大或更大的窗口。+ expect(suggestFollowUpRoute(input({ contextTokens: null }))).toMatchObject(GEMINI);+ // 窗口变大不受当前用量影响。+ expect(suggestFollowUpRoute(input({+ chain: [SOL, OPUS],+ current: SOL,+ currentContextWindow: 272_000,+ contextTokens: 240_000,+ }))).toMatchObject(OPUS);+ });+});++describe('follow-up usage derivation', () => {+ const reading = (contextTokens: number, contextWindow = 1_000_000) => ({ contextTokens, contextWindow });++ it.each([+ // [情形, live, closed, 库值, 期望用量]+ ['新 runtime 的占位 0 不盖掉上一段关闭时的读数', reading(0), reading(220_000), 0, 220_000],+ ['占位 0 被固化进关闭缓存、库里也是 0:未知', reading(0), reading(0), 0, null],+ ['库值低报时运行时读数为准', reading(40_000), null, 220_000, 220_000],+ ['运行时读数更大时取运行时', reading(220_000), null, 40_000, 220_000],+ ['没有运行时读数:库值不能单独证明缩窗安全', null, null, 220_000, null],+ ['什么读数都没有:未知', null, null, null, null],+ ] as const)('%s', (_case, live, closed, dbContextTokens, expected) => {+ expect(deriveFollowUpUsage({ live, closed, dbContextTokens }).contextTokens).toBe(expected);+ });++ it('prefers the current runtime window and falls back to the closed one', () => {+ expect(deriveFollowUpUsage({ live: reading(0, 0), closed: reading(1, 272_000), dbContextTokens: null }).contextWindow)+ .toBe(272_000);+ expect(deriveFollowUpUsage({ live: reading(0, 1_000_000), closed: reading(1, 272_000), dbContextTokens: null })+ .contextWindow).toBe(1_000_000);+ expect(deriveFollowUpUsage({ live: null, closed: null, dbContextTokens: 5 }).contextWindow).toBeNull();+ });+});diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.tsindex 6aa3e7f184..b470cd603d 100644--- a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts+++ b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts@@ -10,7 +10,7 @@* 被当成做完;同一条挂起交互在重启后得到新的事件 id;远程 list-active 连续失败;远程任务两次轮询之间从权限请求* A 换到 B,仍显示 A;本机任务在同一相位里从请求 A 换到 B(权限或回答),沿用 A 的等待时刻;读任务元数据失败一次后,* 这批任务被丢掉,之后再无活动就永远不进表;启动兜底读失败一次后再不重试;启动时归属读失败,上一轮被打断的任务按空归属判给总调度、工作台把空表当成「没事」;伙伴刚开的任务在上次归属读取- * 几秒内出现,被当成「没人开」落到总调度。+ * 几秒内出现,被当成「没人开」落到总调度;出错只留横幅文案、丢了工具循环等稳定原因。* - tier:unit(全部 IO 经注入的内存 fake,时间由 now() 推进,无真实等待)。*/import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';@@ -166,6 +166,20 @@ describe('TaskWatch local observation', () => {expect(h.watch.finished().map((f) => f.sessionId)).toEqual(['user']);});+ // 依据:伙伴跟进要分清工具循环(换模型没用)与供应商失败;只有横幅文案时分不清,会把循环的任务也换模型。+ // 最小失败输入:带 errorReason 的出错投影;旧被控端只给 toolLoop 详情、不给 errorReason。+ it('keeps the stable reason behind an error so follow-up can tell a tool loop apart', async () => {+ const h = harness({ metas: [meta('looped'), meta('legacy-loop'), meta('plain')] });+ await h.watch.start();+ h.watch.applyInputProjection({ sessionId: 'looped', error: '重复工具调用', errorReason: 'tool_use_loop_detected' });+ h.watch.applyInputProjection({ sessionId: 'legacy-loop', error: '重复工具调用', toolLoop: { toolName: 'Bash', count: 5 } });+ h.watch.applyInputProjection({ sessionId: 'plain', error: 'server error' });+ await h.watch.settled();+ expect(h.watch.get('looped')).toMatchObject({ phase: 'errored', errorReason: 'tool_use_loop_detected' });+ expect(h.watch.get('legacy-loop')).toMatchObject({ phase: 'errored', errorReason: 'tool_use_loop_detected' });+ expect(h.watch.get('plain')).toMatchObject({ phase: 'errored', errorReason: null });+ });+it('gives the same pending interaction the same event id after a restart', async () => {const waitingSnapshot = activity('t', 'needs-interaction', { interactionKind: 'ask_user_question', lastActivityAtMs: 7_000 });const ids: string[] = [];diff --git a/apps/desktop/src/main/bot-autonomy/followUpRoute.ts b/apps/desktop/src/main/bot-autonomy/followUpRoute.tsnew file mode 100644index 0000000000..de11887d04--- /dev/null+++ b/apps/desktop/src/main/bot-autonomy/followUpRoute.ts@@ -0,0 +1,99 @@+/**+ * 伙伴跟进时「换哪个模型」的建议(get_task_digest 的 suggested_route)。+ *+ * 伙伴照建议用 set_session_runtime 代主人换模型,没有用户确认,也不会先交接重建上下文,+ * 所以只在换过去确实有用、且换过去装得下时给建议;其余情况不给,由伙伴提醒主人。+ * 规则见 docs/product-rules/cindy-bots-runtime.md §6.3。+ */+import type { TaskDigestFailure } from '../mcp-integrations/taskDigest.js';+import { decideProviderGroupFailure } from '../provider-group/failurePolicy.js';+import {+ botModelRouteIndex,+ nextBotModelRoute,+ normalizeBotModelChain,+ type BotModelRoute,+} from '../../shared/botModelChain.js';+import { agentSwitchKeepsContextHeadroom } from '../../shared/modelSwitchAssessment.js';++export interface FollowUpRouteInput {+ /** 调用方伙伴的有效候选链。 */+ chain: unknown;+ current: Pick<BotModelRoute, 'harness' | 'model' | 'providerId'>;+ /** 出错的那次失败;sdkError / errorStatus / codexErrorInfo 来自运行时记下的本轮终态(摘要投影里没有)。 */+ failure: TaskDigestFailure & { sdkError?: string; errorStatus?: number; codexErrorInfo?: string };+ /** 这件任务已经试过的路线(runtime key)。 */+ visitedRoutes: readonly string[];+ /** SSH 远端任务不能跨 harness 切换(与候选链自动恢复同一口径)。 */+ sameHarnessOnly: boolean;+ /** 任务当前上下文用量(tokens);没有可信读数为 null(此时不推荐更小窗口)。 */+ contextTokens: number | null;+ /** 任务当前路线的上下文窗口;未知为 null。 */+ currentContextWindow: number | null;+ /** 候选路线核实过的上下文窗口;未知为 null。 */+ windowOf(route: BotModelRoute): number | null;+}++export function suggestFollowUpRoute(input: FollowUpRouteInput): BotModelRoute | null {+ // 换模型救不了的失败(工具循环、上下文超限、请求本身无效、内容被拒等)不给建议,+ // 与供应商组「换到哪台都一样就不换」同一判定;没有可判断的错误时也不猜。+ if (input.failure.phase === 'errored') {+ const decision = decideProviderGroupFailure(+ {+ message: input.failure.error ?? '',+ ...(input.failure.errorReason ? { reason: input.failure.errorReason } : {}),+ ...(input.failure.sdkError ? { sdkError: input.failure.sdkError } : {}),+ ...(typeof input.failure.errorStatus === 'number' ? { errorStatus: input.failure.errorStatus } : {}),+ ...(input.failure.codexErrorInfo ? { codexErrorInfo: input.failure.codexErrorInfo } : {}),+ },+ 'run',+ );+ if (decision.action === 'stay') return null;+ }+ const chain = normalizeBotModelChain(input.chain);+ // 任务当前路线不在伙伴候选链里(主人自己选的模型):伙伴的链不是这件任务的备选,不建议换。+ // 同一模型换了明确不同的供应商也算链外(候选链自动恢复用的宽松匹配在这里不适用)。+ const index = botModelRouteIndex(chain, input.current);+ if (index < 0) return null;+ const matched = chain[index]!.providerId;+ if (matched && input.current.providerId && matched !== input.current.providerId) return null;+ return nextBotModelRoute(+ chain,+ input.current,+ input.visitedRoutes,+ (candidate) =>+ (!input.sameHarnessOnly || candidate.harness === input.current.harness)+ // 换过去就挤满的小窗口路线不推荐。+ && agentSwitchKeepsContextHeadroom({+ contextTokens: input.contextTokens,+ currentContextWindow: input.currentContextWindow,+ targetContextWindow: input.windowOf(candidate),+ }),+ );+}++type UsageReading = { contextTokens: number; contextWindow: number } | null | undefined;++const positive = (value: unknown): number | null =>+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;++/**+ * 跟进建议用的可信上下文用量。+ * - live:当前 runtime 的读数;刚 attach、usage 回流前是占位 0。+ * - closed:上一段 runtime 关闭那一刻固化的读数(关闭时也可能把占位 0 固化进去)。+ * - dbContextTokens:库里的用量,只在一轮正常收尾时落库,中断 / 崩溃后可能低报。+ *+ * 运行时读数(live 与 closed 取大)为 0 或缺失时一律按未知(contextTokens: null),+ * 建议层因此不推荐更小窗口;库值只作运行时读数的下限,不能单独证明缩窗安全。+ * 高估只会让更小窗口的候选落空,不会误缩窗。+ */+export function deriveFollowUpUsage(input: {+ live: UsageReading;+ closed: UsageReading;+ dbContextTokens: number | null | undefined;+}): { contextTokens: number | null; contextWindow: number | null } {+ const runtimeTokens = Math.max(positive(input.live?.contextTokens) ?? 0, positive(input.closed?.contextTokens) ?? 0);+ return {+ contextTokens: runtimeTokens > 0 ? Math.max(runtimeTokens, positive(input.dbContextTokens) ?? 0) : null,+ contextWindow: positive(input.live?.contextWindow) ?? positive(input.closed?.contextWindow),+ };+}diff --git a/apps/desktop/src/main/bot-autonomy/hub.ts b/apps/desktop/src/main/bot-autonomy/hub.tsindex 1bda58708c..282e9c2480 100644--- a/apps/desktop/src/main/bot-autonomy/hub.ts+++ b/apps/desktop/src/main/bot-autonomy/hub.ts@@ -23,7 +23,7 @@ import { throwIpcError } from '../utils/ipcValidate.js';import { resolveSchedulerBotId } from './follower.js';import { readBotDirectory } from './hostData.js';import type { BotAutonomyRuntime, GlanceOptions } from './runtime.js';-import { errorCode } from './taskWatch.js';+import { errorCode, type BotAutonomyInputProjection } from './taskWatch.js';const log = createLogger('bot-autonomy');@@ -61,7 +61,7 @@ export function scopeIsCurrent(scope: string): boolean {export function noteBotAutonomyInputProjection(projection: unknown): void {const runtime = current?.runtime;if (!runtime || !projection || typeof projection !== 'object') return;- runtime.watch.applyInputProjection(projection as { sessionId: string; error?: string | null; usageLimitWait?: unknown });+ runtime.watch.applyInputProjection(projection as BotAutonomyInputProjection);}function emptyGlance(botId: string): BotGlance {diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.tsindex b75c7100c3..4dd8339e3f 100644--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts@@ -119,9 +119,26 @@ export interface TaskWatchDeps {onChange(): void;}+/** 输入协调器投影里跟进需要的字段(其余字段不读)。 */+export interface BotAutonomyInputProjection {+ sessionId: string;+ error?: string | null;+ errorReason?: string | null;+ toolLoop?: unknown;+ usageLimitWait?: unknown;+}++/** 工具循环的投影带 toolLoop 详情;旧被控端可能只给 toolLoop、不给 errorReason。 */+function inputProjectionErrorReason(projection: BotAutonomyInputProjection): string | null {+ if (typeof projection.errorReason === 'string' && projection.errorReason) return projection.errorReason;+ return projection.toolLoop ? 'tool_use_loop_detected' : null;+}+interface LocalFacts {activity: SessionActivitySnapshot | null;inputError: string | null;+ /** 出错横幅背后的稳定原因(输入协调器投影的 errorReason / 工具循环),没有就是 null。 */+ inputErrorReason: string | null;usageLimitWait: boolean;}@@ -241,15 +258,20 @@ export class TaskWatch {this.queue(sessionId);}- applyInputProjection(projection: { sessionId: string; error?: string | null; usageLimitWait?: unknown }): void {+ applyInputProjection(projection: BotAutonomyInputProjection): void {if (this.stopped || typeof projection?.sessionId !== 'string') return;const facts = this.factsFor(projection.sessionId);const inputError = typeof projection.error === 'string' && projection.error ? projection.error : null;+ const inputErrorReason = inputError ? inputProjectionErrorReason(projection) : null;const usageLimitWait = !!projection.usageLimitWait;- if (facts.inputError === inputError && facts.usageLimitWait === usageLimitWait) return;+ if (+ facts.inputError === inputError+ && facts.inputErrorReason === inputErrorReason+ && facts.usageLimitWait === usageLimitWait+ ) return;// 没有任何活动、也没有出错 / 等待的会话不进表(投影会为每个会话广播)。if (!this.local.has(projection.sessionId) && !inputError && !usageLimitWait) return;- this.local.set(projection.sessionId, { ...facts, inputError, usageLimitWait });+ this.local.set(projection.sessionId, { ...facts, inputError, inputErrorReason, usageLimitWait });this.queue(projection.sessionId);}@@ -265,7 +287,7 @@ export class TaskWatch {}private factsFor(sessionId: string): LocalFacts {- return this.local.get(sessionId) ?? { activity: null, inputError: null, usageLimitWait: false };+ return this.local.get(sessionId) ?? { activity: null, inputError: null, inputErrorReason: null, usageLimitWait: false };}private queue(sessionId: string): void {@@ -408,6 +430,7 @@ export class TaskWatch {pendingInteractionId,toolInFlight: phase === 'running' && this.deps.isToolCallInFlight(sessionId),error: phase === 'errored' && facts.inputError ? truncateSummary(facts.inputError) : null,+ errorReason: phase === 'errored' ? facts.inputErrorReason : null,creatorBotId,canonicalOfBotId,followerBotId: null,@@ -830,6 +853,7 @@ function sameRow(a: WatchedSession | null, b: WatchedSession): boolean {&& (a.pendingRequestId ?? null) === (b.pendingRequestId ?? null)&& (a.pendingInteractionId ?? null) === (b.pendingInteractionId ?? null)&& a.error === b.error+ && (a.errorReason ?? null) === (b.errorReason ?? null)&& a.followerBotId === b.followerBotId&& a.online === b.online;}diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/taskDigest.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/taskDigest.test.tsindex 37013fa625..f89b9d8d71 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/taskDigest.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/taskDigest.test.ts@@ -2,7 +2,8 @@* 测试价值* - 生产入口与可观察结果:createTaskDigestReader 交给 get_task_digest 的摘要(本机 / 另一台电脑 / 不存在)。* - 规则依据:摘要优先用观察层状态行(与工作台、事件同一口径),缺行时保守推断;子项失败不拖垮整份;- * 跨电脑不给换模型建议(set_session_runtime 只支持本机);离线电脑明确报 REMOTE_UNAVAILABLE。+ * 跨电脑不给换模型建议(set_session_runtime 只支持本机);只有出错 / 用量上限才要换模型建议,并带上这次失败;+ * 离线电脑明确报 REMOTE_UNAVAILABLE。* - 现有覆盖缺口:新模块。* - 最小失败输入:有 / 无观察层状态行的本机任务;PR 读取抛错;离线电脑;已删除任务;状态行带 / 不带* toolInFlight(不知道时摘要里不出现 tool_in_flight,伙伴不能把「没有字段」当成「没有工具在跑」)。@@ -64,11 +65,30 @@ describe('task digest assembly', () => {session_id: 'local-1', device: null, title: '修登录', phase: 'waiting-permission', elapsed_minutes: 9, idle_minutes: 9,last_user_ask: '修登录', last_assistant_line: '要删旧表吗?', pending_question: null, error: null,current_route: route, runtime_generation: 4,- suggested_route: { ...route, harness: 'claude-code', model: 'claude-opus-5-5' },+ // 等权限不是换模型能解决的:不给建议。+ suggested_route: null,pr_status: null, queued_count: 2, follower_bot_id: null, creator_bot_id: null,},});- expect(deps.local.suggestRoute).toHaveBeenCalledWith({ callerSessionId: 'bot-main', targetSessionId: 'local-1', current: route });+ expect(deps.local.suggestRoute).not.toHaveBeenCalled();+ });++ // 依据:换模型建议要按这次失败的原因判断(工具循环换了也没用),摘要须把观察层记下的错误交过去。+ it('asks for a route suggestion only for an errored or usage-limited task, passing the failure along', async () => {+ const row = {+ sessionId: 'local-1', deviceId: null, deviceName: null, online: true, title: '修登录', workingDir: null,+ phase: 'errored', phaseSince: NOW - 5 * 60_000, lastActivityAt: NOW - 5 * 60_000, startedAt: null,+ pendingQuestion: null, error: '重复工具调用', errorReason: 'tool_use_loop_detected',+ creatorBotId: null, followerBotId: 'bot', source: 'user',+ } satisfies WatchedSession;+ const { read, deps } = setup({ 'local-1': row });+ expect(await read({ sessionId: 'local-1', callerSessionId: 'bot-main' })).toMatchObject({+ ok: true, digest: { phase: 'errored', suggested_route: { model: 'claude-opus-5-5' } },+ });+ expect(deps.local.suggestRoute).toHaveBeenCalledWith({+ callerSessionId: 'bot-main', targetSessionId: 'local-1', current: route,+ failure: { phase: 'errored', error: '重复工具调用', errorReason: 'tool_use_loop_detected' },+ });});it('prefers the watcher row for phase, question, error and who follows', async () => {diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 72ab105802..5c7748f60e 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -272,6 +272,30 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// git-context 牵连 Electron 窗口广播,按需加载,不让工具装配一引用就把它带进来。readSessionPrStatuses: async (sessionId) =>(await import('../git-context/ipc.js')).readSessionPrStatuses(sessionId),+ readRuntimeFacts: async (sessionId) => {+ const [{ getMakerIfReady }, { getSessionLastLiveUsage }] = await Promise.all([+ import('../maker-host/index.js'),+ import('../maker-ipc/sessionLastLiveUsage.js'),+ ]);+ const session = getMakerIfReady()?.getSession(sessionId);+ // 原样交出两份运行时读数,可信用量由 deriveFollowUpUsage 统一推导。+ const pick = (usage: { contextTokens: number; contextWindow: number } | null | undefined) =>+ usage ? { contextTokens: usage.contextTokens, contextWindow: usage.contextWindow } : null;+ const live = pick(session?.getUsageSnapshot());+ const closed = pick(getSessionLastLiveUsage(sessionId));+ const terminal = session?.getObservedCurrentTurnTerminal();+ return {+ live,+ closed,+ terminalError: terminal?.kind === 'error'+ ? {+ ...(terminal.sdkError ? { sdkError: terminal.sdkError } : {}),+ ...(terminal.codexErrorInfo ? { codexErrorInfo: terminal.codexErrorInfo } : {}),+ ...(typeof terminal.errorStatus === 'number' ? { errorStatus: terminal.errorStatus } : {}),+ }+ : null,+ };+ },}));const authorizeTaskToolCall = createTaskToolCallAuthorizer({diff --git a/apps/desktop/src/main/mcp-integrations/taskDigest.ts b/apps/desktop/src/main/mcp-integrations/taskDigest.tsindex 3d040309ec..a491f703b1 100644--- a/apps/desktop/src/main/mcp-integrations/taskDigest.ts+++ b/apps/desktop/src/main/mcp-integrations/taskDigest.ts@@ -33,6 +33,13 @@ export interface TaskDigestExchange {lastAssistantLine: string | null;}+/** 要换模型的那次失败:相位与观察层记下的错误(摘要文案 + 稳定原因)。 */+export interface TaskDigestFailure {+ phase: 'errored' | 'usage-limit';+ error: string | null;+ errorReason: string | null;+}+export interface TaskDigestDeps {now(): number;/** 观察层状态行;本机裸 id,另一台电脑 deviceId::sessionId。 */@@ -43,8 +50,17 @@ export interface TaskDigestDeps {readLastExchange(sessionId: string): Promise<TaskDigestExchange>;queuedCount(sessionId: string): Promise<number | null>;prStatus(sessionId: string): Promise<string | null>;- /** 调用方伙伴候选链里下一条可用路线(跳过当前与已试过的);非伙伴调用方返回 null。 */- suggestRoute(params: { callerSessionId?: string; targetSessionId: string; current: TaskDigestRoute }): Promise<TaskDigestRoute | null>;+ /**+ * 出错 / 撞上用量上限时,调用方伙伴候选链里下一条可用路线(跳过当前与已试过的)。+ * 换模型解决不了这次失败、任务当前路线不在候选链里、或换过去装不下当前上下文时返回 null;+ * 非伙伴调用方返回 null。+ */+ suggestRoute(params: {+ callerSessionId?: string;+ targetSessionId: string;+ current: TaskDigestRoute;+ failure: TaskDigestFailure;+ }): Promise<TaskDigestRoute | null>;};remote?: {deviceName(deviceId: string): Promise<string | null>;@@ -165,8 +181,15 @@ export function createTaskDigestReader(deps: TaskDigestDeps) {settle(() => deps.local.queuedCount(key), null),]);const current = activity?.route ?? facts.route;- const suggestedRoute = current- ? await settle(() => deps.local.suggestRoute({ callerSessionId: args.callerSessionId, targetSessionId: key, current }), null)+ const phase = watched?.phase ?? fallbackDigestPhase(activity);+ // 换模型只用来救出错和用量上限(跟进规则也只在这两种相位用它);其余相位不给建议。+ const suggestedRoute = current && (phase === 'errored' || phase === 'usage-limit')+ ? await settle(() => deps.local.suggestRoute({+ callerSessionId: args.callerSessionId,+ targetSessionId: key,+ current,+ failure: { phase, error: watched?.error ?? null, errorReason: watched?.errorReason ?? null },+ }), null): null;return {ok: true,diff --git a/apps/desktop/src/main/mcp-integrations/taskDigestHost.ts b/apps/desktop/src/main/mcp-integrations/taskDigestHost.tsindex 044e7359cc..4b8a40ac18 100644--- a/apps/desktop/src/main/mcp-integrations/taskDigestHost.ts+++ b/apps/desktop/src/main/mcp-integrations/taskDigestHost.ts@@ -6,15 +6,20 @@import { and, eq, isNull } from 'drizzle-orm';import type { InvokeResultPayload } from '@cindy/device-link';import type { HistoryDevice, TaskDigestRoute } from '@cindy/mcps';+import type { AgentKind } from '@cindy/model-providers';+import { deriveFollowUpUsage, suggestFollowUpRoute } from '../bot-autonomy/followUpRoute.js';import { parseActiveSessionList } from '../bot-autonomy/phase.js';import { getDbClient } from '../localDb/client/current.js';import { botProfileVersions, botSessionLinks, sessions } from '../localDb/schema.js';+import { getActiveCatalog } from '../maker-host/active-catalog.js';import { readEffectiveBotModelChain } from '../maker-host/bot-model-chain-settings-store.js';+import { resolveConfiguredContextWindow } from '../maker-host/model-context-settings.js';+import { lookupVerifiedContextWindow } from '../maker-ipc/contextOverflowRollover.js';import { getSessionRuntimeControlSnapshot } from '../maker-ipc/sessionRuntimeControl.js';import { readWatchedSession } from '../maker-ipc/botWorkbenchAutonomyBridge.js';import { lastExchange, readSessionLastExchange } from '../maker-ipc/botWorkbenchTranscripts.js';-import { nextBotModelRoute, type BotHarness } from '../../shared/botModelChain.js';+import type { BotHarness } from '../../shared/botModelChain.js';import { readChatHistoryMessages } from './remoteChatHistory.js';import {formatPrStatuses,@@ -42,6 +47,15 @@ export interface DesktopTaskDigestHost {listSessionQueuedCounts(sessionIds: string[]): Promise<{ ok: true; counts: Record<string, number> } | { ok: false }>;/** 本机任务的 PR 状态(git-context 同一服务与缓存)。 */readSessionPrStatuses(sessionId: string): Promise<Parameters<typeof formatPrStatuses>[0]>;+ /**+ * 运行时对这件任务的读数:当前 runtime 的上下文用量(没有在跑为 null)、上一段 runtime 关闭那一刻+ * 固化的用量(没有为 null),与本轮终态错误的结构化字段(摘要投影里没有 sdkError / errorStatus / codexErrorInfo)。+ */+ readRuntimeFacts?(sessionId: string): Promise<{+ live: { contextTokens: number; contextWindow: number } | null;+ closed: { contextTokens: number; contextWindow: number } | null;+ terminalError: { sdkError?: string; errorStatus?: number; codexErrorInfo?: string } | null;+ }>;}const num = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) ? value : null);@@ -60,6 +74,18 @@ function routeFromProfile(profile: RuntimeLike['effectiveProfile']): TaskDigestRconst toBotHarness = (harness: TaskDigestRoute['harness']): BotHarness => (harness === 'claude-code' ? 'claude' : harness);const toDigestHarness = (harness: BotHarness): TaskDigestRoute['harness'] => (harness === 'claude' ? 'claude-code' : harness);+const toAgentKind = (harness: BotHarness): AgentKind => (harness === 'claude' ? 'claude-code' : harness);++/** 目录里核实过的窗口(与主机切换闸门同一口径);查不到返回 null。 */+function verifiedRouteWindow(harness: BotHarness, model: string, providerId: string | null): number | null {+ const catalog = getActiveCatalog();+ return lookupVerifiedContextWindow(+ (agentKind, modelId, pid) => resolveConfiguredContextWindow(catalog, agentKind as AgentKind, pid, modelId),+ model,+ providerId,+ toAgentKind(harness),+ );+}/** 调用方伙伴(主任务)的有效候选链。非伙伴调用方返回 null。 */async function readCallerBotChain(callerSessionId: string) {@@ -176,23 +202,32 @@ export function createDesktopTaskDigestDeps(host: DesktopTaskDigestHost): TaskDireturn result.ok ? (result.counts[sessionId] ?? 0) : null;},prStatus: async (sessionId) => formatPrStatuses(await host.readSessionPrStatuses(sessionId)),- suggestRoute: async ({ callerSessionId, targetSessionId, current }) => {+ suggestRoute: async ({ callerSessionId, targetSessionId, current, failure }) => {if (!callerSessionId) return null;const chain = await readCallerBotChain(callerSessionId);if (!chain?.length) return null;const [target] = await getDbClient()- .drizzle.select({ remoteHostId: sessions.remoteHostId })+ .drizzle.select({ remoteHostId: sessions.remoteHostId, contextTokens: sessions.contextTokens }).from(sessions).where(eq(sessions.id, targetSessionId)).limit(1);const harness = toBotHarness(current.harness);- const next = nextBotModelRoute(+ const runtime = (await host.readRuntimeFacts?.(targetSessionId)) ?? null;+ const usage = deriveFollowUpUsage({+ live: runtime?.live,+ closed: runtime?.closed,+ dbContextTokens: target?.contextTokens,+ });+ const next = suggestFollowUpRoute({chain,- { harness, model: current.model, providerId: current.provider_id },- getSessionRuntimeControlSnapshot(targetSessionId).visitedRoutes,- // SSH 远端任务不能跨 harness 切换(与候选链自动恢复同一口径)。- (candidate) => !target?.remoteHostId || candidate.harness === harness,- );+ current: { harness, model: current.model, providerId: current.provider_id },+ failure: { ...failure, ...(failure.phase === 'errored' ? runtime?.terminalError ?? {} : {}) },+ visitedRoutes: getSessionRuntimeControlSnapshot(targetSessionId).visitedRoutes,+ sameHarnessOnly: !!target?.remoteHostId,+ contextTokens: usage.contextTokens,+ currentContextWindow: usage.contextWindow ?? verifiedRouteWindow(harness, current.model, current.provider_id),+ windowOf: (candidate) => verifiedRouteWindow(candidate.harness, candidate.model, candidate.providerId),+ });return next? {harness: toDigestHarness(next.harness),diff --git a/apps/desktop/src/shared/botAutonomy.ts b/apps/desktop/src/shared/botAutonomy.tsindex f3afa607ac..7f321b3454 100644--- a/apps/desktop/src/shared/botAutonomy.ts+++ b/apps/desktop/src/shared/botAutonomy.ts@@ -88,6 +88,11 @@ export interface WatchedSession {*/canonicalOfBotId?: string | null;error: string | null;+ /**+ * 出错时 runtime 给的稳定原因(如 tool_use_loop_detected),不含原文;没有就是 null / 缺省。+ * 只用来判断换模型能不能解决,不展示给伙伴。+ */+ errorReason?: string | null;/** 哪个伙伴开的这件任务(bot_delegations / task-responsibility),没有就是 null。 */creatorBotId: string | null;/**diff --git a/apps/desktop/src/shared/botModelChain.ts b/apps/desktop/src/shared/botModelChain.tsindex fcf2e4db97..73f230def2 100644--- a/apps/desktop/src/shared/botModelChain.ts+++ b/apps/desktop/src/shared/botModelChain.ts@@ -83,6 +83,35 @@ export function primaryBotModelRoute(return normalizeBotModelChain(value, legacy)[0] ?? null;}+/**+ * Where the current route sits in the companion's chain, or -1 when the chain+ * does not contain it (for example a task whose model the user chose).+ */+export function botModelRouteIndex(+ chain: readonly BotModelRoute[],+ current: Pick<BotModelRoute, 'harness' | 'model' | 'providerId'>,+): number {+ const exact = chain.findIndex((route) =>+ route.harness === current.harness+ && route.model === current.model+ && route.providerId === current.providerId);+ if (exact >= 0) return exact;+ // A null provider is a single explicit "let the harness resolve it" route,+ // not a wildcard over every source serving the same model. Prefer a real+ // provider match above; only use this legacy/default route when unique.+ const implicitMatches = chain+ .map((route, index) => ({ route, index }))+ .filter(({ route }) =>+ route.harness === current.harness+ && route.model === current.model+ && route.providerId === null);+ if (implicitMatches.length === 1) return implicitMatches[0]!.index;+ const legacyMatches = chain+ .map((route, index) => ({ route, index }))+ .filter(({ route }) => route.harness === current.harness && route.model === current.model);+ return legacyMatches.length === 1 ? legacyMatches[0]!.index : -1;+}+/** Select the next explicit route; never invent one from the global catalog. */export function nextBotModelRoute(value: unknown,@@ -91,28 +120,7 @@ export function nextBotModelRoute(isUsable: (route: BotModelRoute) => boolean = () => true,): BotModelRoute | null {const chain = normalizeBotModelChain(value);- let currentIndex = chain.findIndex((route) =>- route.harness === current.harness- && route.model === current.model- && route.providerId === current.providerId);- if (currentIndex < 0) {- // A null provider is a single explicit "let the harness resolve it" route,- // not a wildcard over every source serving the same model. Prefer a real- // provider match above; only use this legacy/default route when unique.- const implicitMatches = chain- .map((route, index) => ({ route, index }))- .filter(({ route }) =>- route.harness === current.harness- && route.model === current.model- && route.providerId === null);- if (implicitMatches.length === 1) currentIndex = implicitMatches[0]!.index;- }- if (currentIndex < 0) {- const legacyMatches = chain- .map((route, index) => ({ route, index }))- .filter(({ route }) => route.harness === current.harness && route.model === current.model);- if (legacyMatches.length === 1) currentIndex = legacyMatches[0]!.index;- }+ const currentIndex = botModelRouteIndex(chain, current);for (let index = currentIndex + 1; index < chain.length; index += 1) {const route = chain[index]!;if (!isUsable(route)) continue;diff --git a/apps/desktop/src/shared/modelSwitchAssessment.ts b/apps/desktop/src/shared/modelSwitchAssessment.tsindex c61aeac9f5..b35fab5968 100644--- a/apps/desktop/src/shared/modelSwitchAssessment.ts+++ b/apps/desktop/src/shared/modelSwitchAssessment.ts@@ -96,3 +96,30 @@ export function shouldHandoffAfterContextAssessment(): boolean {return assessment.level === 'danger' || assessment.level === 'overflow';}++/**+ * 不经用户确认、由 Agent 代为换的模型(伙伴跟进时的换模型建议)只接受换过去仍宽裕的路线:+ * 目标窗口比当前小,且换过去后用量会到提醒线(warn 及以上)就不推荐,免得任务一换过去就挤满。+ * 窗口变大、目标窗口未知时与主机切换闸门同口径放行;用户自己切换不走这里。+ */+export function agentSwitchKeepsContextHeadroom(input: {+ /** null = 没有可信的当前用量:只放行不缩窗的目标。 */+ contextTokens: number | null;+ currentContextWindow: number | null | undefined;+ targetContextWindow: number | null | undefined;+}): boolean {+ const { contextTokens, currentContextWindow, targetContextWindow } = input;+ if (typeof targetContextWindow !== 'number' || !Number.isFinite(targetContextWindow) || targetContextWindow <= 0) {+ return true;+ }+ if (+ typeof currentContextWindow === 'number' &&+ Number.isFinite(currentContextWindow) &&+ currentContextWindow > 0 &&+ targetContextWindow >= currentContextWindow+ ) {+ return true;+ }+ if (contextTokens === null) return false;+ return assessModelSwitchContext({ contextTokens, targetContextWindow }).level === 'ok';+}diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 78ce26d02d..c2a2da66dc 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -705,6 +705,14 @@ Session 任务遵守同一套机制与呈现契约:内容,`continue_workbench_task` 让任务接着做(别的伙伴开的任务默认由那位伙伴跟,总调度只能读),换模型、停止当前一轮、更新待办与通知主人沿用既有工具;工具边界以各工具说明与宿主校验为准。跟进这一轮的回复不会自动发给主人,要主人知道的事必须显式通知(内置规则开启 `silentWhenIdle`)。+- 换模型只照摘要的 `suggested_route` 做:伙伴代主人换模型没有用户确认,也不会先交接重建上下文,所以宿主只在换过去+ 确实有用且装得下时给建议,否则为 null、由伙伴提醒主人(2026-10-19 用户反馈「伙伴把会话的模型切了,上下文直接满了」)。+ 具体:只在出错 / 用量上限时给;出错的原因换到哪个模型都一样(工具循环、上下文超限、请求本身无效、内容被拒等,+ 与供应商组 `decideProviderGroupFailure` 同一判定)或没有可判断的错误时不给;任务当前路线不在伙伴候选链里+ (主人自己选的模型,含同一模型换了明确不同的供应商)时不给,不退回链首;候选窗口比当前小、换过去用量会到 70%+ 提醒线时跳过该候选。失败判定同时用运行时记下的本轮终态结构化字段(SDK 错误类型、HTTP 状态、Codex 错误 tag);用量取+ 运行时读数(会话已关闭时取关闭那一刻固化的值),没有有效运行时读数时不推荐更小窗口——库里的用量在中断 / 崩溃后可能+ 低报;上一段运行时关闭时的读数仍作下限;运行时读数为 0(可能是 usage 回流前的占位)一律按未知处理。- 逐任务责任独立保存在伙伴 Home 的 `task-responsibility.v1.json`:历史只从 `bot_delegations` 读取可验证创建关系,`send_to_session` 新建成功后记录真实创建回执,`set_workbench_task_responsibility` 记录明确接手 / 解除。解除记录覆盖创建来源;损坏记录失败关闭,该伙伴不认领任何任务;账号切换时丢弃旧读取与写入;跨进程锁 + 原子替换,容量溢出明确拒绝。diff --git a/packages/lizi-mcps/src/xdt-helper/get_task_digest.ts b/packages/lizi-mcps/src/xdt-helper/get_task_digest.tsindex 71a181ca67..1dc78a8ef4 100644--- a/packages/lizi-mcps/src/xdt-helper/get_task_digest.ts+++ b/packages/lizi-mcps/src/xdt-helper/get_task_digest.ts@@ -109,7 +109,7 @@ export function boundTaskDigest(raw: TaskDigestWire): TaskDigestWire {const DESCRIPTION = ['读一件任务的短摘要(≤2KB):状态 phase、已持续分钟数、主人最后的要求、助手最后一句、待回答的问题、错误、当前模型路线、',- '建议换到的下一条路线(你的候选链里还没试过的那条,没有则 null)、PR 状态、排队消息数、谁开的 / 谁在跟。',+ '建议换到的下一条路线(只在出错或撞用量上限、换模型确实有用且装得下当前上下文时,给你候选链里还没试过的那条;否则 null,此时提醒主人)、PR 状态、排队消息数、谁开的 / 谁在跟。','idle_minutes 距最后一次动静的分钟数;tool_in_flight 为 true 表示有工具调用(如长时间构建、测试)正在执行,宿主不知道时不出现。','被程序叫醒跟进任务时先读这一份再决定;要看原文再用 get_chat_history。','作用范围:本机任务直接传 id;另一台电脑上的任务传 deviceId::sessionId(只读,对方须在线)。',diff --git a/packages/maker-core/src/session-control.test.ts b/packages/maker-core/src/session-control.test.tsindex 3f3d5f7951..0e929ac063 100644--- a/packages/maker-core/src/session-control.test.ts+++ b/packages/maker-core/src/session-control.test.ts@@ -568,6 +568,7 @@ describe('Session current-generation terminal observation', () => {reason: 'empty-response',sdkError: 'server_error',errorStatus: 529,+ codexErrorInfo: 'badRequest',},});await secondError;@@ -578,6 +579,7 @@ describe('Session current-generation terminal observation', () => {reason: 'empty-response',sdkError: 'server_error',errorStatus: 529,+ codexErrorInfo: 'badRequest',});stub.push({ type: 'done', data: {} });await vi.waitFor(() => expect(session.isTurnRunning()).toBe(false));@@ -588,6 +590,7 @@ describe('Session current-generation terminal observation', () => {reason: 'empty-response',sdkError: 'server_error',errorStatus: 529,+ codexErrorInfo: 'badRequest',});});diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 405ed81b9a..4d46b2d019 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -517,6 +517,8 @@ export class Session {sdkError?: string;errorStatus?: number;toolLoop?: import('./types/events.js').ToolLoopErrorDetails;+ /** Codex app-server 的结构化错误 tag(如 badRequest / cyberPolicy)。 */+ codexErrorInfo?: string;} | null = null;/** Survives N+1 reservation clearing the current snapshot; leftover done must not adopt. */private lastObservedTerminalGeneration: number | null = null;@@ -671,6 +673,7 @@ export class Session {sdkError?: string;errorStatus?: number;toolLoop?: import('./types/events.js').ToolLoopErrorDetails;+ codexErrorInfo?: string;} {if (this.turnGeneration <= 0 ||@@ -698,6 +701,9 @@ export class Session {...(this.terminalEventObservedErrorSignals?.toolLoop? { toolLoop: this.terminalEventObservedErrorSignals.toolLoop }: {}),+ ...(this.terminalEventObservedErrorSignals?.codexErrorInfo+ ? { codexErrorInfo: this.terminalEventObservedErrorSignals.codexErrorInfo }+ : {}),};}return { kind: 'done', generation: this.turnGeneration };@@ -710,6 +716,7 @@ export class Session {sdkError?: string;errorStatus?: number;toolLoop?: import('./types/events.js').ToolLoopErrorDetails;+ codexErrorInfo?: string;} | null;} {const errorData = (listenerEvent.data ?? null) as {@@ -718,6 +725,7 @@ export class Session {sdkError?: unknown;errorStatus?: unknown;toolLoop?: unknown;+ codexErrorInfo?: unknown;} | null;const errorMessage = errorData?.message;const signals: {@@ -725,6 +733,7 @@ export class Session {sdkError?: string;errorStatus?: number;toolLoop?: import('./types/events.js').ToolLoopErrorDetails;+ codexErrorInfo?: string;} = {};if (typeof errorData?.reason === 'string' && errorData.reason.length > 0) {signals.reason = errorData.reason;@@ -737,13 +746,18 @@ export class Session {}const toolLoop = parseToolLoopErrorDetails(errorData?.toolLoop);if (toolLoop) signals.toolLoop = toolLoop;+ // Codex 的结构化 tag 是有界枚举名(translator 只取 tag,不带原文),不需要脱敏。+ if (typeof errorData?.codexErrorInfo === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(errorData.codexErrorInfo)) {+ signals.codexErrorInfo = errorData.codexErrorInfo;+ }return {message: typeof errorMessage === 'string' && errorMessage.length > 0 ? errorMessage : null,signals:signals.reason ||signals.sdkError ||signals.errorStatus !== undefined ||- signals.toolLoop+ signals.toolLoop ||+ signals.codexErrorInfo? signals: null,};