Skip to content

refactor: deliver subagent model choices via system reminder - #5190

Merged
7Sageer merged 3 commits into
mainfrom
refactor/subagent-model-reminder
Nov 20, 2026
Merged

7Sageer merged 3 commits into
mainfrom
refactor/subagent-model-reminder

Conversation

@7Sageer

@7Sageer 7Sageer commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

会话第一次请求时,Agent、AgentSwarm、TowerSpawn 的工具定义会被冻结进会话快照(tool_select.initialized),之后每次请求都复用这份快照,所以 Prompt Cache 不受影响。但这三个工具的 model 参数和 Available models (pass via model): ... 描述是按 [secondary_model] 实时生成的:会话中途改了模型池(/secondary-model、改配置文件、:reload),快照里的列表就过时了,模型还会收到一条 Tool "Agent" has an update, but the update is not applied in this session 提醒,要求继续用旧版本;而运行期的 resolveSubagentBinding 已经按新配置校验和派发。结果是模型拿着旧列表选模型,选到已删除的别名就报错重试,新增的模型也看不到。ChangeNotifier 里比较模型池增删的补丁只在 profile 名单变化或 reload 时运行,覆盖不全。

本 PR 让这三个工具的定义保持静态,改用 <system-reminder> 把当前的模型池告诉模型:模型池一变,下一轮就能看到,前缀缓存也不受影响。同时把 resume 时被静默忽略的 model 参数改成显式报错。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路

把工具的静态定义(parameters、description)和运行期的模型池状态拆开。三个派生工具始终带一个可选的 model: string 参数,描述里不再拼模型列表;新增的 Agent 作用域服务 AgentSubagentModelsReminderService 在每次请求前比较"当前模型池"和"历史里最后一次告诉模型的内容"(origin.disclosure),有变化才注入一条 <system-reminder>。没配 [secondary_model] 的会话不发任何提醒,行为和 main 一致;只有模型池在会话中途被删掉时,才发一次"列表已撤回"的提醒。

结构图

flowchart LR
    Config["IConfigService<br/>([secondary_model])"] --> Reminder["AgentSubagentModelsReminderService"]
    Gate["受绑定 profile +<br/>激活了 Agent / AgentSwarm / TowerSpawn"] --> Reminder
    History["上下文历史<br/>(最后一次 disclosure)"] --> Reminder
    Reminder -->|"有变化才注入"| SR["&lt;system-reminder&gt;<br/>subagent_models"]
    Tools["静态工具定义<br/>(Agent / AgentSwarm / TowerSpawn)"] -->|"校验 resume 与 model"| Binding["resolveSubagentBinding"]
    Config --> Binding
Loading

提醒追加在当前轮消息的末尾,不改动 tools[] 和已有历史,所以前缀缓存不受影响。每次都发完整列表而不是增删 diff,压缩丢掉旧提醒之后,下一轮也能重新给出一份完整的当前列表。

关键决策

决策 选择 没选 理由
模型列表的下发通道 IAgentReminderService 注册的 subagent_models 提醒,用 origin.disclosure 去重 继续拼进工具描述;或由 ChangeNotifier 发增删 diff 工具定义被会话快照冻结,改描述到不了模型;diff 依赖特定事件触发,压缩后也无法自洽
模型池变化是即时告知还是等 /reload 即时(下一轮) 和 subagent profile 一样等 reload profile 要 reload 才进会话,通知和生效同步;[secondary_model] 由 bindSubagentModel 每次实时读取,改完立刻生效,只有即时告知才不会和运行期不一致
没配模型池时 不发提醒,显式传任何 model 都报错(含调用方自己的别名) 列出调用方自己的模型作为唯一选项 默认配置的会话占多数,没得选的列表只是噪声;而且列出自己的模型会让提醒依赖主模型,每次 /model 切换都要重发
resume 时传 model 显式报错 静默忽略 被恢复的 subagent 不会换模型,静默忽略会让模型以为切换成功

阅读指南

  1. packages/agent-core-v2/src/agent/subagentModelsReminder/subagentModelsReminderService.ts:提醒的准入条件、disclosure 的构造(没配池时为空)、去重,以及首次 / 变化 / 撤回三种文本。
  2. packages/agent-core-v2/src/agent/tools/agent/agentTool.ts、features/swarm/tools/agent-swarm/agentSwarmTool.ts、features/tower/tools/spawn/spawnTool.ts:三个工具静态化后的定义,以及 resume(或只有 resume_agent_ids)时对 model 的拒绝。
  3. packages/agent-core-v2/src/session/subagent/configSection.ts:删掉了按配置裁剪 schema 和拼描述的辅助函数;bindSubagentModel 的行为与 main 相同。
  4. packages/agent-core-v2/src/agent/changeNotifier/changeNotifierService.ts:删掉模型池比较;新增 prepareForReload() / notifyAllChanges(),把 kap-server 和 SDK 里各写一遍的 reload 通知流程收进服务。快照里的 modelPool 字段类型保留,用于旧会话回放。

agent.ts、agent-swarm.ts、spawn.ts、spawn.md 是参数描述措辞,sessions.ts、sdk-rpc-client-v2.ts 是 reload 调用的替换,其余是测试和中英文文档,可以略读。

具体逻辑变化

inject(lastDisclosure)
  if profile is unbound or none of {Agent, AgentSwarm, TowerSpawn} is active -> skip
  current = [secondary_model] pool with ≥1 model
    ? { defaultModel, models }
    : { models: {} }                       # no pool
  if lastDisclosure is undefined
    if current is empty -> skip            # default config: never announce
  else if same(lastDisclosure, current) -> skip
  emit:
    empty current            -> "The subagent model list was withdrawn ... Omit the model parameter"
    first announcement       -> "Available subagent models (pass via model):" + [default] first
    changed                  -> "...the list below replaces any earlier subagent model list." + list
 Agent.execute(params)
+  if params.resume && params.model !== undefined
+    return error RESUME_WITH_MODEL_UNAVAILABLE

 AgentSwarm.execute(params)
+  if items is empty && params.model !== undefined
+    throw SWARM_RESUME_ONLY_WITH_MODEL_UNAVAILABLE

Behavior Changes and Affected Users

行为 改动前 改动后 依赖旧行为的人群 退路
Agent / AgentSwarm / TowerSpawn 的 JSON schema 是否有 model 没配模型池或单条目池时 Agent / AgentSwarm 去掉 model;没配池时 TowerSpawn 去掉 model 始终有可选的 model: string 所有客户端(TUI、print、Desktop/Web、VS Code、ACP、SDK)中默认配置或单条目池的会话 无;不传 model 时的绑定结果不变
工具描述里的模型列表 配了模型池时末尾拼 Available models (pass via model): ... 描述保持静态;列表改由 <system-reminder> 注入给激活了派生工具的受绑定 profile 配了 [secondary_model] 的会话,主 agent 和能派生的自定义 agent 无;提醒提供同样的列表,运行期仍强校验
新增 subagent_models 提醒 无 配了模型池时首轮注入一次;模型池变化后下一轮发完整新列表;模型池被删时发一次撤回提醒;压缩后重发。没配模型池的会话不注入;explore、coder 这类没有派生工具的 profile 不注入 配了 [secondary_model] 的会话 无
会话中途改 [secondary_model] 后模型看到的内容 快照里的旧列表,外加 Tool "Agent" has an update, but the update is not applied in this session 提醒 下一轮收到新列表;工具定义不变,不再触发这条 update 提醒 运行中用 /secondary-model、改配置文件或 :reload 修改模型池的会话 无
旧版本创建的会话恢复后 — 快照里冻结的旧描述与新定义不同,会按现有机制收到一次 tool_update_pending 提醒;之后模型列表以 subagent_models 提醒为准 升级前创建、升级后恢复的会话 无
没配模型池时显式传 model Agent / AgentSwarm / TowerSpawn 的 schema 里没有 model,被参数校验拒绝(must NOT have additional property 'model') 通过参数校验,由 bindSubagentModel 拒绝:Invalid model "<x>": no [secondary_model] pool is configured, so subagents inherit the caller's model (omit the model parameter). 默认配置会话中显式传 model 的调用 无;仍然报错,只是错误文本不同
单条目池时显式传 model Agent / AgentSwarm 的 schema 里没有 model,被参数校验拒绝 传池中别名时正常绑定;传其他值报 Invalid model "<x>". Available models: <alias>. 单条目池会话中显式传 model 的调用 无
Agent 同时传 resume 和 model;AgentSwarm 只传 resume_agent_ids 又传 model model 被静默忽略 返回工具错误 RESUME_WITH_MODEL_UNAVAILABLE / SWARM_RESUME_ONLY_WITH_MODEL_UNAVAILABLE;AgentSwarm 同时有 items 时仍可传 model,只作用于新建的 subagent 所有客户端中恢复 subagent 时附带 model 的调用 无;去掉 model 重试即可。这是收紧,请维护者确认
subagents_change 提醒 标题 The available subagent profiles and models changed:,含 Models added/removed、Model descriptions updated、Default model changed 等行 标题 The available subagent profiles changed:,只报 profile 增删;模型池变化交给 subagent_models 增删 subagent profile 或修改模型池的会话;回放旧快照的会话 无;快照里的 modelPool 字段类型保留,旧会话可正常回放。wire-manifest.d.ts、state-manifest.d.ts 无变化
reload 失败后的补发通知 四类通知并行发出 四类通知按 AGENTS.md → skill → subagent → 工作目录的顺序依次发出 kap-server :reload / SDK reload 失败的会话 无

提示词文本的变化(每句一行):

位置 改动前 改动后 原来约束什么 / 现在由什么约束
Agent 的 model 参数描述 one of the aliases listed under "Available models" in this tool description ... Ignored when resuming chosen from the available subagent models announced in <system-reminder> ... Cannot be set when resuming 约束模型从哪里取合法别名、resume 时能否传;现在指向提醒,resume 由工具显式报错兜底
AgentSwarm 的 model 参数描述 同上,Resumed subagents always keep their own model 指向提醒;补充 cannot be set when resuming without items 同上,由 SWARM_RESUME_ONLY_WITH_MODEL_UNAVAILABLE 兜底
TowerSpawn 的 model 参数描述 one of the aliases listed under "Available models" in this tool description chosen from the available subagent models announced in <system-reminder> 约束合法别名的来源;收到者为开启 KIMI_CODE_EXPERIMENTAL_TOWER 的会话
spawn.md 的 Model selection 段 The allowed choices are the configured secondary-pool aliases ...;The model parameter is available whenever a pool is configured. 第一句改为指向提醒;删掉第二句 第二句描述的是"按配置显隐参数",参数改为始终存在后已不成立;合法值仍由 resolveSubagentBinding 校验

受影响模块与测试覆盖

  • @moonshot-ai/agent-core-v2:subagentModelsReminder、session/subagent、agentTool、agentSwarmTool、tower/spawn、changeNotifier
  • @moonshot-ai/kap-server:/api/v1/sessions/:id:reload 改用 prepareForReload / notifyAllChanges
  • @moonshot-ai/kimi-code-sdk:reload RPC 同上
  • docs/{en,zh}:reference/tools.md、configuration/config-files.md、guides/tower.md

对应测试:

  • schema 固定带 model、描述保持静态、热更新模型池不改变 tools[]:test/tool/tool.test.ts、test/features/swarm/swarm.test.ts、test/features/tower/tools/spawnTool.test.ts
  • 提醒:没配池时不发(含切换主模型)、中途加池后发一次并去重、默认模型排第一并带描述、池变化后重发、池删除后发一次撤回且不重复、没有派生工具的 profile 不发:test/tool/tool.test.ts
  • 没配池时显式传任何 model(含调用方别名)都拒绝:test/tool/tool.test.ts、test/features/tower/tools/spawnTool.test.ts、test/app/config/config.test.ts
  • 默认配置的会话请求里不出现这条提醒:packages/klient/test/e2e/invalid-input-matrix.test.ts(与 main 相同,无需过滤)
  • resume + model 报错;AgentSwarm 只有 resume_agent_ids + model 报错,items + resume_agent_ids + model 保持旧行为:test/tool/tool.test.ts、test/features/swarm/swarm.test.ts
  • ChangeNotifier 只跟进 profile 增删、prepareForReload 失败恢复、:reload 集成:test/agent/changeNotifier/changeNotifier.test.ts、packages/kap-server/test/sessions.test.ts

验证结论

在 Linux(Node.js 24)上跑了 pnpm lint、agent-core-v2 / kap-server / node-sdk 的类型检查,以及受影响的测试文件,全部通过。未运行三个包的全量测试、桌面端和 GUI 测试(本 PR 不涉及渲染端和 CLI 交互层代码)。

验证命令与结果
  • pnpm lint:通过(check-comments、oxlint --type-aware --deny-warnings、check-import-boundaries、guards、ratchet、instructions)
  • pnpm exec tsc -p packages/agent-core-v2/tsconfig.json --noEmit:通过
  • pnpm exec tsc -p packages/kap-server/tsconfig.json --noEmit:通过
  • pnpm exec tsc -p packages/node-sdk/tsconfig.json --noEmit:通过
  • pnpm exec vitest run packages/agent-core-v2/test/tool/tool.test.ts packages/agent-core-v2/test/features/tower/tools/spawnTool.test.ts packages/agent-core-v2/test/features/swarm/swarm.test.ts packages/agent-core-v2/test/session/subagent/spawn.test.ts packages/agent-core-v2/test/app/config/config.test.ts packages/agent-core-v2/test/agent/changeNotifier/changeNotifier.test.ts packages/agent-core-v2/test/agent/profile packages/kap-server/test/sessions.test.ts:13 个文件 / 766 个用例通过
  • pnpm exec vitest run packages/klient/test/e2e/invalid-input-matrix.test.ts:23 个用例通过

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

Keep the optional `model` parameter static on `Agent`, `AgentSwarm`, and
`TowerSpawn` instead of stripping it or appending available model lists
to top-level tool descriptions.

Inject available subagent models via `<system-reminder>` for bound
profiles with active subagent tools (deduplicated via `origin.disclosure`
and updated on `setModel`, `[secondary_model]` reloads, and compaction),
and explicitly reject invalid or resume-time `model` arguments.
@changeset-bot

changeset-bot Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 37611da

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 5 packages
Name Type
@moonshot-ai/kimi-code Patch
kimi-code-app Patch
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/kap-server Patch
@moonshot-ai/kimi-code-sdk Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T10:10:53.400979Z 37611da New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@37611da
npx https://pkg.pr.new/@moonshot-ai/kimi-code@37611da

commit: 37611da

- Extract SubagentTool.parseSubagentInput so resolveExecution and execution share argument validation without triggering jscpd clones.
- Add prepareForReload and notifyAllChanges on IAgentChangeNotifierService so kap-server and node-sdk session reload flows delegate change-notifier lifecycle handling to the service.
- Include the baseline subagent_models <system-reminder> marker alongside date_change in klient's invalid-input-matrix helper while keeping interruption reminder assertions intact.
Skip the subagent model reminder without a [secondary_model] pool, send a
one-time withdrawal notice when the pool is removed mid-session, and keep
rejecting any explicit model when no pool is configured. Also simplify the
reminder disclosure typing, Agent resume parsing, and reload failure recovery.
@7Sageer
7Sageer merged commit 1ef139e into main Nov 20, 2026
28 of 29 checks passed
@7Sageer
7Sageer deleted the refactor/subagent-model-reminder branch November 20, 2026 10:56
@github-actions github-actions Bot mentioned this pull request Nov 24, 2026
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Remove the experimental `fork` parameter from the Agent and AgentSwarm
tools (MoonshotAI#5254): the subagent_fork flag and its /experiments entry, the
schema parameters and flag-gated parameter sets, the lifecycle fork spawn
path and its reminder notice, the `fork` plan field, the subagent_created
telemetry field, the fork-only backend compatibility rule, and the pending
changeset that announced the feature. Docs drop the env var and the
parameter text in both locales; six changesets describe the removal for
the CLI, engine, desktop, migration, SDK and VS Code packages.

Fork adaptations: the external-backend parameter, the subagent depth
labels and the fork's DI shapes stay. The unrelated model-with-resume-only
rejection that the merge resolution had carried from the still-pending
MoonshotAI#5190 is dropped, so the fork keeps ignoring `model` when resuming without
items. The port also fixes two defects in that resolution which the tests
exposed: planSpawn reads the caller profile through IAgentProfileService,
and spawn passes the computed labels so the subagentDepth label survives.

Verified: agent-core-v2 affected files 285 pass / 2 fail, both failures
pre-existing at 2fa1821 (tool.test registered-user-tools wire snapshot,
forkParity TaskStop timeout); swarm 32, sessionSwarm 50, spawn 22,
experiments 13, node-sdk flags 1, node-sdk prompt events 18, kap-server
meta 10; typecheck clean for agent-core-v2, kap-server, node-sdk and
kimi-code; check:no-comments and the locale gates green.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Port upstream MoonshotAI#5190 (1ef139e). The available [secondary_model] choices are
announced through a scoped reminder service instead of being rendered into the
Agent / AgentSwarm / TowerSpawn tool descriptions, so tool definitions stay
static when the pool changes mid-session. Resume-time and no-pool model
arguments are rejected explicitly.

Fork adaptations:
- the reminder service injects IAgentProfileService (the fork's data() owner)
  instead of upstream IAgentLoopService;
- the Agent tool keeps the fork-only subagent backend parameter handling while
  parseSubagentInput owns the shared resume/model validation;
- reload paths keep the fork's reloadWorkspaceCatalogs and
  refreshPluginSessionStarts methods behind prepareForReload/notifyAllChanges;
- reminder tests await restorePersisted() because the fork harness does not
  auto-restore the reminder actor.

Verification:
- agent-core-v2 typecheck passes; bun scripts/check-no-comments.mjs OK.
- bun test --isolate on tool, changeNotifier, apply-profile, binding, swarm and
  spawnTool: 315 pass, 1 fail (pre-existing loadable-tools snapshot mismatch at
  HEAD after ce35274, unrelated); changeNotifier alone 44 pass.
- kap-server sessions and node-sdk reload suites resolve
  @moonshot-ai/agent-core-v2 through the root node_modules junction to the main
  checkout, so they see the old notifier interface; kap-server typecheck reports
  the same two missing members. Re-run after integration.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants