Skip to content

fix(agent-core-v2): preserve Gemini context across turns - #4827

Merged
7Sageer merged 2 commits into
MoonshotAI:mainfrom
7Sageer:gemini-context
Nov 11, 2026
Merged

7Sageer merged 2 commits into
MoonshotAI:mainfrom
7Sageer:gemini-context

Conversation

@7Sageer

@7Sageer 7Sageer commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

使用 Gemini 进行多轮工具调用时,Kimi Code 没有完整保留模型返回的思考签名、原生调用 ID 和多模态工具响应结构。历史再次发送给 Gemini 时会丢失这些上下文。

本 PR 让新产生的 Gemini 历史可以跨请求、进程重启和会话回放保留这些信息,并按 Gemini 3 及更新版本支持的响应结构回传工具图片。

Bug Reproduction Steps

  1. Gemini 在一轮响应中返回带 thoughtSignature 的普通文本或空文本,再返回带原生 ID 的 functionCall。
  2. 执行工具,将包含文本和图片的结果追加到会话历史,随后请求模型继续回答。
  3. 第二次请求应满足以下条件:
    • 签名仍在原先所在的文本 part 上,包括 { text: "", thoughtSignature: "..." }。
    • functionCall.id 与对应 functionResponse.id 相同。
    • Gemini 3 及更新版本的图片位于 functionResponse.parts 中。

修复前,文本和空文本签名被丢弃,调用 ID 不回传,工具图片放在函数响应外部。持久化工具事件还会丢失已解析的原生 ID。

Root Cause

这是根本修复,覆盖从协议解码、消息保存到再次编码的完整链路:

  • Google GenAI 解码器只保存 thinking part 和工具调用的签名,忽略普通文本及空文本上的签名。
  • 工具响应没有使用服务端下发的原生 ID;事件回放也缺少这个字段。
  • 空内容清洗和流式文本合并会破坏签名所在的原始 part 边界。
  • 所有 Gemini 版本的工具媒体都采用旧式外置布局,没有使用新版 functionResponse.parts。

Code Changes

核心思路是保留服务端上下文的归属和位置,内部工具执行 ID 与 Gemini 原生 ID 分别保存。无需新增公开消息类型或配置。

 Gemini response
-  keep signatures only on thinking and functionCall parts
+  preserve signatures on text, empty text and functionCall parts
+  retain native functionCall.id as ToolCall.rawId
        |
        v
 message accumulator + journal + session replay
-  drop blank signed text and merge signed text into adjacent text
+  retain the original signed part and its position
+  persist rawId with the tool event
        |
        v
 next Gemini request
-  functionCall and functionResponse omit the native ID
+  replay matching native IDs on both sides
+  Gemini 3+: nest tool media in functionResponse.parts

三个关键决定:

  • 签名按原 part 保存,不把它移动到相邻可见文本,避免改变服务端返回的上下文结构。
  • rawId 只用于 Gemini 出站协议;内部工具执行、排序和本地结果关联继续使用已有 ID。
  • 2.5 保留工具媒体外置路径;新版模型使用 SDK 已支持的嵌套 parts 结构。

阅读顺序:

  1. packages/agent-core-v2/src/human/llm/builtin/protocol/google-genai/decode.ts:签名与原生 ID 的接收。
  2. packages/agent-core-v2/src/human/llm/message.ts:签名 part 的流式边界与空内容判断。
  3. packages/agent-core-v2/src/agent/loop/journal.ts 及回放相关文件:工具原生 ID 的保存与恢复。
  4. packages/agent-core-v2/src/human/llm/builtin/protocol/google-genai/lower.ts:下一轮请求中的签名、ID 和媒体布局。

最小示例:

 {
   "role": "model",
   "parts": [
-    { "text": "ORCHID-426" },
-    { "functionCall": { "name": "get_weather", "args": { "city": "sf" } } }
+    { "text": "ORCHID-426", "thoughtSignature": "sig-text" },
+    { "text": "", "thoughtSignature": "sig-end" },
+    {
+      "functionCall": { "id": "call_weather", "name": "get_weather", "args": { "city": "sf" } },
+      "thoughtSignature": "sig-tool"
+    }
   ]
 }
{
  "functionResponse": {
    "id": "call_weather",
    "name": "get_weather",
    "response": { "output": "sunny" },
    "parts": [{ "inlineData": { "mimeType": "image/png", "data": "..." } }]
  }
}

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
普通及空文本思考签名 签名在接收或清洗时丢失 保存在原 part,下一轮原位置回传 使用 Google GenAI 协议的新会话历史 无;恢复协议要求的上下文
Gemini 工具原生 ID 不回传;事件回放后也无法恢复 调用与结果回传同一原生 ID 返回原生 functionCall.id 的 Gemini 端点 无;旧历史没有 ID 时仍省略
工具媒体布局 所有版本均外置 Gemini 3 及更新版本把 PNG、JPEG、WebP、PDF、纯文本的内联数据嵌套进 functionResponse.parts;其他类型(GIF、音频、视频、URL 引用)和 2.5 保持外置 使用 Gemini 原生工具媒体输入的客户端 无;官方未列出的嵌套类型保持原有布局
无媒体函数响应的 parts 空数组 省略可选字段 Google GenAI 协议调用方 无;均表示没有附加响应 part
Gemini 会话切换到 Anthropic 模型 空文本在清洗时被丢弃,不会发送 带签名的空文本保留在历史中,Anthropic 请求转换时跳过空白文本 同一会话中切换模型的用户 无需迁移
已有本地 ID、角色和工具配对 本地 ID 用于执行及结果关联 保持原有本地关联,只有 Gemini 出站原生 ID 改变 TUI、print、desktop/web、VS Code、ACP、SDK 的既有工具执行 无需迁移
旧版本写入的历史 缺失的签名与 ID 无法恢复 新历史完整保存;旧数据不伪造缺失字段 重启后继续旧会话的用户 继续使用已有历史,下一轮保留新上下文

测试覆盖:

  • Google GenAI 两轮请求:接收三个签名 part 与原生工具调用,JSON 恢复历史后,断言第二轮最终发送的签名、调用/结果 ID 和嵌套图片。
  • Gemini 2.5:保留外置媒体与无原生 ID 的调用路径。
  • Gemini 3:只嵌套官方支持的内联媒体类型,GIF、音频和 URL 引用保持外置。
  • Anthropic:带签名的空文本不会生成空 text block。
  • 通用消息清洗:空签名文本不会消失。
  • Journal、context transcript 和 wire replay:保存并恢复签名与原生工具 ID。
验证结果与范围
  • 相关回归:10 个测试文件、91 个测试通过。
  • loop/replay 扩展回归:11 个测试文件、152 个测试通过。
  • agent-core-v2 全量:374 个测试文件、7830 个测试通过。
  • agent-core-v2 类型检查与包构建通过。
  • 改动文件 lint 无 error。
  • 基线 lint:imports 有 4 个既有违规,位于 fullCompactionService.ts、completionRestore.ts、taskOutput.ts、human/agent/origin.ts,均不在本 PR 的 diff 中。
  • 已验证协议结构和真实 requester 两轮调用,尚未进行长时间线上会话的质量 A/B;本 PR 不宣称所有 Gemini 长任务表现问题均已量化解决。
  • 没有 UI 变化,因此无截图或录屏。

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.

Copilot AI balanced review requested due to automatic review settings November 11, 2026 07:29
@changeset-bot

changeset-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7a9a01b

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

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code 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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@7Hanrui

7Hanrui commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 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-11T09:19:14.718095Z 7a9a01b Manual request
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 445fc543d3

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

function isBlankText(part: ContentPart): boolean {
return part.type === 'text' && part.text.trim().length === 0;
return part.type === 'text' &&
part.meta?.['thought_signature_b64'] === undefined &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Drop Gemini-only blank parts before non-Gemini lowering

When a user switches from Gemini to an Anthropic-backed model after a Gemini tool turn containing the now-preserved { text: '', thoughtSignature: ... } part, this provider-agnostic exemption (also added in message.ts:165 and structure.ts:15-18) keeps that empty block in the projected history. anthropic/lower.ts:183-184 then serializes it as { type: 'text', text: '' }, which Anthropic rejects, whereas this history worked before because blank text was removed. Keep the signature carrier in stored history for Gemini replay, but omit it when lowering to protocols that cannot represent it.

Useful? React with 👍 / 👎.

@7Sageer
7Sageer marked this pull request as ready for review November 11, 2026 08:27
@pkg-pr-new

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

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

commit: 7a9a01b

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 445fc543d3

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

parts.push(thinkPart);
} else if (p['text']) {
parts.push({ type: 'text', text: p['text'] as string });
} else if (typeof p['text'] === 'string') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude blank text carriers from success detection

When Gemini returns only empty text part(s), with or without a signature, this branch leaves message.content nonempty. emptyResponseError() then skips its empty-array case, and because there is no think-only content, settleLlmRequest() reports done with no visible output instead of returning an empty_response; keep signed carriers in replay history but exclude blank text when checking for usable output.

AGENTS.md reference: AGENTS.md:L112-L112

Useful? React with 👍 / 👎.

…on responses

Skip blank text when lowering for Anthropic so signed Gemini parts do not
produce empty text blocks after a model switch.
@7Hanrui

7Hanrui commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 7a9a01b609

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@7Sageer
7Sageer merged commit 5518d54 into MoonshotAI:main Nov 11, 2026
17 checks passed
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.

4 participants