Skip to content

fix(core): recover compaction from empty text history - #5238

Merged
7Sageer merged 3 commits into
mainfrom
loop-421-stack/05-recover-empty-text-compaction
Nov 23, 2026
Merged

7Sageer merged 3 commits into
mainfrom
loop-421-stack/05-recover-empty-text-compaction

Conversation

@sailist

@sailist sailist commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Part 5/7 of the loop stack onto main. Identical diff to #5214, previously reviewed and merged into the loop integration branch. Stacked on #5237; the shown diff contains only this PR's own changes.

Requirement or Bug

Web 2.7.1 用户使用 Kimi K3.1 Pro 执行 compact 时,历史消息中的空 text 会使压缩请求被 HTTP 400 Invalid request: text content is empty 拒绝,导致会话无法完成压缩。这个 PR 让包含空文本的旧会话在编码阶段得到清理,并让服务端的 empty-text 拒绝进入已有的 strict projection recovery。

相邻的 #4300 处理空工具结果;本 PR 覆盖普通 user/assistant 空文本、跨 provider 的签名空文本,以及对应的恢复分类。

Bug Reproduction Steps

  1. 让会话历史包含空/纯空白的 user 或 assistant text,或从 Gemini 会话带来带 thought_signature_b64 的空文本。
  2. 执行 compact。
  3. 修复前,协议编码会生成 content: "" 或含空 text block 的请求,服务端返回上述 400;该错误被归类为普通 status,不会触发 strict recovery。修复后,空内容在发送前被移除,残余结构错误会进入 strict projection 重试。

Root Cause

共享 runPipeline 没有接入已有的 cleanMessages(),所以空文本能一直到达协议出口。Gemini 所需的签名空文本也被无差别保留到其他协议,但这些协议不会保留其签名元数据,仍会发出空块。

同时,text content is empty 不在结构错误识别列表中,导致已有 strict projection recovery 无法接管。这个 PR 是在共享编码与错误分类层修复根因,不是迁移会话数据或针对单一 provider 的绕过。

Code Changes

 request
   legalize-media → relocate-tool-media
+  legalize-structure
+    Google GenAI: preserve signed blank text
+    other protocols: drop all blank text and empty non-structural messages
   legalize-tool-call-ids → provider patterns → convert → wire

 provider rejects empty text
-  status → compaction fails
+  request_structure → strict projection → retry
  • 在媒体合法化之后、工具 id 和 provider patterns 之前接入 legalize-structure,复用现有清理逻辑;工具调用、动态工具声明、媒体和有意义的文本继续保留,空工具结果仍由现有渲染逻辑生成非空状态文本。
  • 只有 Google GenAI 保留带签名的空文本;其他协议删除这类块,避免 Gemini 历史切换到 Kimi/OpenAI 后再次产生同类 400。
  • 将 text content is empty 识别为 request_structure,复用现有 strict projection recovery,不新增 compact 专用恢复循环。
  • 增加 Kimi/OpenAI 编码回归、Google 签名保留回归和错误分类回归;仅添加 @moonshot-ai/core patch changeset。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
普通空/纯空白 user、assistant 文本 编码为 content: "" 或空 text block 在发送前删除;正常文本不变 携带旧会话历史并执行 compact 或续聊的用户 不需要;被删除的是空内容
无结构意义的空消息 仍可能进入请求 删除;带工具调用、工具声明或工具结果的结构消息保留 旧版本写入的会话、跨恢复/回放路径 不需要;结构消息由回归测试固定
带 thought_signature_b64 的空文本 所有协议都可能保留,OpenAI 出口会丢元数据但留下空块 仅 Google GenAI 保留;其他协议删除 Gemini 历史切换到其他 provider 的会话 无配置开关;目标协议无法使用该签名,Google 行为由测试固定
服务端返回 text content is empty 归为普通 status,不进入 strict recovery 归为 request_structure,执行一次 strict projection 重试 返回该校验错误的 provider 及其 compact/普通请求 不需要;复用现有恢复路径
非空文本和已有工具结果状态文本 按原路径编码 不变 所有现有 provider 与客户端 不需要;无空白内容时清理返回原消息

验证结论:目标回归覆盖普通空白、签名空白、空 assistant、工具调用保留、空工具结果占位和错误分类;独立只读复审无 P0/P1/P2 发现。未做真实 provider 的 compact 端到端验证;最终基线的完整 core 套件交由 PR CI 验证。

验证明细
  • 最终 loop-refact 基线:Kimi/OpenAI、Google GenAI、错误分类目标测试 3 passed / 60 skipped。
  • packages/core 与 packages/agent-core-v2 TypeScript 检查通过。
  • 完整 pnpm lint 通过,包括 comments、oxlint、import boundaries、guards、ratchet、test-doubles、quarantine 和 instructions。
  • pnpm run check:duplication 3c7b8ecc7a8e85d2d06c38a6681ca4036288d876 通过,无新增重复。
  • 前一基线的远程 Linux 验证曾为 core 361/361、fullCompaction 117/117、klient 结构恢复 5/5;切换到最终基线后,远程环境 host key 变化使重跑未能开始,因此不将这些旧结果声明为最终基线结果。
  • 未验证真实 provider 的 HTTP 400 → strict projection → compact 成功端到端序列;编码和恢复分类由目标测试覆盖。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).(无外部 issue;问题、复现和相关工作已在上方说明。)
  • 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T04:57:44.005817Z bba9c9b 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.

@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: 4cb3ead559

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

Comment on lines +38 to +40
const structuralLegal = pass.messages('legalize-structure', relocated, (messages, ctx) =>
cleanMessages(messages, ctx.report, spec.preserveSignedBlankText === true),
);

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 Run cleanup after tool declaration deduplication

When a blank system message contains only tool declarations that are all shadowed by profile or newer declarations, this pass retains it because carriesStructure sees the pre-deduplication tools; the later legalizeTools pass then reduces tools to [], with no subsequent cleanup. The existing duplicate-declaration case in packages/core/test/llm/lifecycle/run.test.ts demonstrates that the resulting OpenAI request still contains { role: 'system', content: '' }, so providers returning the targeted empty-text 400 continue to fail and strict recovery rebuilds the same payload. Repeat cleanup after tool legalization or otherwise remove messages emptied by deduplication.

AGENTS.md reference: packages/core/src/llm/AGENTS.md:L1-L1

Useful? React with 👍 / 👎.

@pkg-pr-new

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

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

commit: bba9c9b

@7Sageer 7Sageer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

工具声明去重仍会产生本 PR 要消除的空 system 文本,需要在最终编码前再清理一次。

relocateToolMedia(messages, spec.media),
);
const idsLegal = pass.messages('legalize-tool-call-ids', relocated, (messages) =>
const structuralLegal = pass.messages('legalize-structure', relocated, (messages, ctx) =>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] legalize-structure 会把带 tools 的空 system 当结构消息保留,后续 legalizeTools 又可能将其所有声明作为旧重复项删除,留下 content: ''。当前 packages/core/test/llm/lifecycle/run.test.ts 新增用例的期望请求里已经包含这种 { role: 'system', content: '' },所以原报告的 provider 仍会 400。请在工具声明去重后清理这类已失去结构内容的消息,并把该 fixture 的期望改为不含空 system 文本。

7Sageer
7Sageer previously approved these changes Nov 23, 2026
@sailist
sailist changed the base branch from loop-421-stack/04-legalize-deferred-tools to main November 23, 2026 04:38
@sailist
sailist dismissed 7Sageer’s stale review November 23, 2026 04:38

The base branch was changed.

* refactor(core): run loop turns on an independent state machine

- add an actor runtime for loop and turn execution
- unify turn hooks and asynchronous lifecycle settlement
- simplify loop contracts and cover turn lifecycle behavior

* fix(core): park recorded notifications until intake

* fix(core): settle forced aborts past stuck hooks and tools

* docs(core): document loop emitted events and public API

* fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps
* refactor(core): unify llm event stream and harden behavior tests

- unify run boundaries, request summaries, delta events, retries, and outcomes
- migrate Loop, agent-core-v2, and klient consumers to the unified event vocabulary
- add aimock-backed transport coverage and restore historical LLM behavior tests
- update the Nix dependency hash and affected snapshots

* refactor(llm): legalize deferred tools in the resolver

- strip deferred metadata during legalize for models without dynamic loading
- stop convert from dropping deferred tools and dedupe declarations with top-level priority
- merge protocol capabilities once at the encode pipeline entry
- remove deferred tools in the dynamic loop resolver and announce their names first

* refactor(llm): unify deferred tool request views

- remove dynamic-only request branching from ToolSelect resolution
- keep non-dynamic system schemas out of top-level tools
- preserve baseline tools for side requests before capability shaping

* refactor(llm): share the tool select request view

- reuse deferred shaping in the resolver and request preview
- preserve initial tool announcements in request previews
- cover preview parity with deferred tools

* refactor(llm): strip deferred metadata in tool select

Remove deferred metadata from non-disclosure ToolSelect request views while preserving the loop baseline.
Keep core legalization as the fallback for requests that bypass ToolSelect.

* refactor(llm): contain tool disclosure in resolver

* refactor(llm): hash the full request tool list

- compute toolsHash over every input tool, including deferred ones
- note the resolver and legalization timing on the llm run events

* refactor(llm): remove the tool select experimental flag

- drop the tool-select flag, env var, and [experimental] config entry
- gate deferred tool disclosure solely on model capabilities
- remove the desktop forced env and update the MCP and env-var docs
- cover mid-loop active-tool requests with an empirical loop test

* test(desktop): assert browser tool disclosure in the request view

The previous assertions called loadableToolsAnnouncement() with no
arguments, a calling form no production code uses; the model-facing
disclosure is built per request by the ToolSelect resolver. Assert the
request view instead: requestTools strips the deferred browser tool
from the request tool list, shapeHistory injects the snapshot
announcement naming it, and a reminder step after the control switch
turns the removal into a <tools_removed> delta.
* test(core): cover empty text request recovery

* fix(core): clean empty text before request encoding

* chore: add empty text recovery changesets

* test(core): cover cross-provider signed empty text

* fix(core): drop unsupported signed blank text
@sailist
sailist force-pushed the loop-421-stack/05-recover-empty-text-compaction branch from 4cb3ead to bba9c9b Compare November 23, 2026 04:49
@sailist
sailist changed the base branch from main to loop-421-stack/04-legalize-deferred-tools November 23, 2026 04:49
@changeset-bot

changeset-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: bba9c9b

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

This PR includes changesets to release 3 packages
Name Type
@moonshot-ai/core Patch
@moonshot-ai/kap-server Patch
@moonshot-ai/agent-core-v2 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

Copy link
Copy Markdown

💡 Codex Review

return capabilities?.dynamically_loaded_tools === true && capabilities.tool_use === true;

P1 Badge Preserve the documented ToolSelect opt-out

When a user sets KIMI_CODE_EXPERIMENTAL_TOOL_SELECT=0 or [experimental] tool-select = false and the selected model advertises both capabilities, this condition now enables ToolSelect regardless because the flag check and definition were removed. The resolver can consequently strip deferred MCP schemas from the top-level tool list, so an existing opt-out is silently ignored without a replacement escape hatch or a changeset describing the lost behavior. Retain an equivalent opt-out unless this default change receives the required explicit approval and migration treatment.

AGENTS.md reference: AGENTS.md:L193-L197


const run = await runItem(item, control, [event, signal], isStepStartingDecision);
if (run.failure !== undefined) failures.push(run.failure);
const decided = run.decision?.blocked;

P1 Badge Continue applying step-starting message rewrites

For existing compiled or JavaScript Loop consumers whose step.starting hook returns { messages: rewritten }, the new validator still accepts the object because it allows extra properties, but this chain now reads only blocked and silently sends the original history. The prior regression test named applies history rewrites during step start and an in-flight request was deleted rather than moved, so compaction or context-rewrite hooks built on this contract lose their effect without an error. Preserve the rewrite path or explicitly reject and migrate this input.

AGENTS.md reference: AGENTS.md:L207-L209


if (seen.has(tool.name)) {
drop(tool.name);
messageChanged = true;

P2 Badge Update the direct ToolSelect example for legalization

When a caller uses the core requester directly without the Agent ToolSelect resolver, a system-message declaration sharing a name with a deferred profile tool is now dropped in favor of the profile entry. packages/klient/examples/kimi-select-tools.ts does exactly this for computer_screenshot and explicitly asserts that the schema remains in the message while staying out of top-level tools; the local wire probe will now fail because the declaration is removed and the profile tool is emitted instead. Update that direct example to apply the resolver/remove deferred profile entries, or retain compatible legalization for direct callers.

ℹ️ 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 force-pushed the loop-421-stack/04-legalize-deferred-tools branch from aff4491 to 59cea24 Compare November 23, 2026 05:24
Base automatically changed from loop-421-stack/04-legalize-deferred-tools to main November 23, 2026 05:43
@7Sageer
7Sageer merged commit 57200d5 into main Nov 23, 2026
27 checks passed
@7Sageer
7Sageer deleted the loop-421-stack/05-recover-empty-text-compaction branch November 23, 2026 05:44
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