Skip to content

feat(prediction): add experimental next-prompt suggestions - #4754

Merged
sailist merged 12 commits into
mainfrom
feat-331-11-04-prompt-prediction
Nov 11, 2026
Merged

sailist merged 12 commits into
mainfrom
feat-331-11-04-prompt-prediction

Conversation

@sailist

@sailist sailist commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

交互式 TUI 用户在主 Agent 正常完成一轮后,仍需要手动构思并输入下一步提示。这个 PR 按内部 RFC revision 154 新增默认关闭的实验性下一提示词预测:会话空闲且输入框为空时生成一条建议,用户按 Tab 或 → 填入并继续编辑,只有明确按 Enter 才提交。

CleanShot 2026-11-09 at 21 39 31@2x

Bug Reproduction Steps

N/A — 本 PR 是实验功能,不是 bug 修复。

Root Cause

N/A — 本 PR 是实验功能,不是 bug 修复。

Code Changes

核心思路是在 Session 作用域提供按需预测服务,每次调用时重新解析 Main Agent,并复用其现有 Loop Requester 做旁路单次采样。预测不进入正式 Agent loop、不执行工具、不追加正式会话;TUI 只负责 ghost text 展示与接受/取消交互。

flowchart LR
    A[Main Agent turn completed] --> B{Session idle and editor empty?}
    B -- No --> Z[Skip prediction]
    B -- Yes --> C[Session prompt prediction service]
    C --> D[Main Agent Loop Requester]
    D --> E[Single side sample without tool execution]
    E --> F[TUI ghost text]
    F --> G{Tab or Right Arrow}
    G --> H[Editable prompt in the input box]
    H --> I[Enter submits explicitly]
Loading

这样组织是为了保持预测与正式会话隔离,同时复用正式 turn 的请求组装与缓存前缀,而不是另建一套模型请求路径。

Decision Choice Alternative not taken Reason
Service ownership Session-scoped service,按需解析 Main Agent Agent-scoped service 或长期持有 fork 与 Main Agent 生命周期解耦,避免过期 scope 和正式上下文污染
Request configuration 保持 tools === undefined,复用 defaultTools 和 shapeHistory 显式读取完整 ToolRegistry 与正常 turn 的 toolsHash 一致,避免缓存前缀被额外工具定义打破
Cost and staleness 每个 source turn 严格一次,并校验 turn、上下文快照和 activity 自动重试或后台补预测 控制成本并避免把过期建议展示给用户
Observability 记录取消原因、缓存、分段耗时和 usage 记录预测文本 能定位取消与慢请求,同时不保存预测文本或用户实际输入
Rollout 实验开关默认关闭 默认对所有用户启用 保持现有用户的请求和界面不变

按阅读顺序建议先看:

  • packages/agent-core-v2/src/features/promptPrediction/:严格一次、成本与空闲守门、过期/取消隔离,以及默认 Requester 工具路径。
  • apps/kimi-code/src/tui/controllers/prompt-prediction.ts:turn 收尾后的自动触发、ghost text 生命周期和按键处理。
  • packages/klient、packages/node-sdk、packages/kap-server:预测与取消接口;取消原因为可选字段,旧调用记为 unspecified。
  • packages/agent-core-v2/src/agent/loop/llmRequestOps.ts、packages/vis:prediction 类型的请求与 usage 展示。
  • docs/en、docs/zh:实验开关、预测行为与快捷键说明。

Screenshots / Recordings

以下是本 PR 原生 TUI 在隔离 aimock 场景中真实运行得到的文本快照。正常回答完成后,空输入框中显示 PREDICTED_NEXT_PROMPT 建议;Tab 或 → 只填入,不自动提交。

 ❯ Say hello

 ● MAIN_REPLY_DONE
   [Debug] TTFT: 648ms | tokens in 7k

 ╭────────────────────────────────────────────────────────────╮
 │ > PREDICTED_NEXT_PROMPT                                    │
 ╰────────────────────────────────────────────────────────────╯

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
默认请求与界面 没有下一提示词预测 实验开关默认关闭;未开启时不新增请求或 UI 所有未开启实验功能的现有用户 无需操作,默认即保持原行为
正常完成 turn 后的提示 手动输入下一步提示 开启实验后,在交互式、空输入、空闲且聚焦时显示一条 ghost text 主动开启 prompt_prediction 的 TUI 用户 在 /experiments 关闭,或不设置 KIMI_CODE_EXPERIMENTAL_PROMPT_PREDICTION
接受与提交 直接输入并提交 Tab/→ 只填入可编辑文本,只有 Enter 才提交 需要审核或编辑建议的用户 输入其他内容或按 Esc 清除,不会自动提交
取消与异常 turn 无预测请求 cancelled、failed、blocked 不生成;新 turn、输入、会话切换等会取消或清除 取消任务、切换会话或进入其他交互状态的用户 原预测生命周期行为保持一致
取消 API 无预测取消接口 新增可选 reason;旧调用未传时记为 unspecified klient、Node SDK、kap-server 客户端 可选字段向后兼容,旧调用无需修改
工具与缓存前缀 prediction 使用独立工具列表 与正常 turn 一样由 Requester 决定 defaultTools 和 shapeHistory 使用 prompt cache 的预测请求 不改变普通 turn;实验关闭时不产生 prediction 请求
Wire/usage 记录 只有普通 turn/session 类型 实际预测请求新增 kind=prediction、usageScope=prediction vis 与离线成本分析 旧记录保持不变;仅在真实发起预测时产生新记录
v1 与未开启客户端 无预测能力 v1 继续返回空预测或 false 旧引擎及未接入预测的客户端 无需迁移

对应验证覆盖:实验开关与正常/异常 turn、严格一次、上下文与 Main Agent 过期隔离、用户取消、断连、tool call 零执行、默认 Requester 工具路径、按键接受与清除、klient/SDK/REST 契约、usage 类型及 vis 聚合。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue — N/A,本 PR 为团队内部实验功能,按内部 RFC revision 154 实施。
  • I have added tests that prove my feature works — 在现有测试中扩展覆盖,测试声明总数净变化为 0。
  • The behavior-change table above is complete — 无默认翻转或移除旧行为;实验开关是显式退出路径。
  • Ran gen-changesets skill — 已包含 @moonshot-ai/kimi-code 的 minor changeset。
  • Ran gen-docs skill — 已同步更新 docs/en 与 docs/zh;仓库中不存在该技能提及的 docs/scripts/sync-changelog.mjs,因此没有伪造 changelog 同步结果。
验证结果
  • 首轮 Core、klient、Node SDK、kap-server、vis 与 TUI 相关测试:448/448 通过。
  • 取消原因与接口相关测试:235/235 通过;焦点与 prediction controller 追加测试:4/4 通过。
  • Requester、ToolSelect、prediction 最新相关测试:162/162 通过。
  • Core、klient、Node SDK、kap-server、CLI typecheck 通过;相关 oxlint --type-aware 为 0 errors;comment-free 检查通过。
  • build:native:sea 与原生 smoke 通过;原生隔离 TUI 场景完成正常 turn + prediction 两次请求,Wire 中两者 systemPromptHash 与 toolsHash 相同。
  • 真实模型验证中,cache_read_pct 从修复前 30.72% 提升到 98.22%,inputOther 从 18475 降至 380;未将单次样本表述为总耗时必然下降。
  • 首轮全量远程回归为 17143 通过 / 2 失败 / 27 跳过;两个失败均位于未改动的 packages/agent-core-v2/test/remote/process.test.ts,未把这些失败记作全绿或修改无关测试。

@changeset-bot

changeset-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 41f4694

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 Minor

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 9, 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-11T12:46:17.267493Z 41f4694 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 9, 2026 •

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

commit: 41f4694

@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: 8c4ab4dce8

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

const parts = finish.message.content;
if (parts.some((part) => part.type !== 'text' && part.type !== 'think')) return null;
const text = parts.map((part) => part.type === 'text' ? part.text : '').join('').trim();
if (text.length === 0 || text.length > PROMPT_PREDICTION_MAX_CHARS || text.includes('\0')) return null;

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 Reject terminal control sequences from predictions

When the experimental feature is enabled, a provider response containing ESC, BEL, or another C0/C1 control character passes this validation because only NUL is rejected. The TUI then renders the string through truncateToWidth, which preserves CSI/OSC sequences, so a prompt-injected or malformed prediction can emit terminal commands such as screen erasure, hyperlinks, title changes, or OSC clipboard operations before the user accepts it. Reject terminal control characters here, allowing only the intended text whitespace.

Useful? React with 👍 / 👎.

state.appState.streamingPhase === 'idle' &&
!state.appState.isCompacting &&
!state.appState.isReplaying &&
!state.appState.planMode &&

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 Dismiss suggestions when plan mode changes

If a suggestion is already visible and the user presses Shift-Tab, handlePlanToggle changes modes without notifying this controller. This condition is only checked while starting or resolving the prediction, so the old suggestion remains rendered and Tab/Right still accepts it after planMode becomes true, allowing a prediction generated for agent mode to be submitted in plan mode. Revalidate or dismiss the suggestion as part of the mode transition.

Useful? React with 👍 / 👎.

Comment on lines +38 to +39
: input.source?.type === 'operation' && input.source.requestKind === 'prompt_prediction'
? 'prediction'

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 Preserve compatibility with older Vis readers

When an opted-in user generates a prediction and later opens that session with the previous release, this new wire value reaches the old context projector, whose byScope has only session and turn; indexing it with prediction passes undefined to addUsage and throws while loading the context view. The wire format needs a backward-compatible encoding or migration so sessions written by this release remain inspectable after downgrade.

AGENTS.md reference: AGENTS.md:L121-L123

Useful? React with 👍 / 👎.

}

function predictionText(finish: AgentLLMRequestFinish): string | null {
if (finish.providerFinishReason === 'truncated' || finish.message.toolCalls.length > 0) return null;

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 Reject filtered and incomplete prediction responses

If a provider emits partial text and terminates with filtered, paused, or other, this helper accepts the text because it rejects only truncated and tool-call responses. The TUI can therefore display content the provider marked safety-filtered or an incomplete paused/error response while telemetry records it as successfully generated. Accept only completed responses, or explicitly reject every non-completed terminal reason.

Useful? React with 👍 / 👎.

Comment on lines +198 to +199
prediction_id: z.string().min(1).optional(),
expected_turn_id: z.number().int().nonnegative().optional(),

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 Pass REST cancellation reasons through validation

When a REST client posts { prediction_id, reason } to :cancel-prompt-prediction, the request first passes through this outer Zod object, which strips unknown properties; because reason is absent here, the action-specific schema and handler always receive undefined. Explicit cancellation reasons such as escape or input are therefore silently recorded as unspecified, despite being part of the new REST contract. Add the reason field to this schema or preserve it through the outer validation.

Useful? React with 👍 / 👎.

@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: 9b597bd600

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

prediction_id: active.predictionId,
turn_id: active.expectedTurnId,
});
const task = scope.loop.requester.start(

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 Hold the session lock during prediction requests

When prediction is enabled and a request remains in flight after the three-second idle grace period, this direct requester call bypasses the loop's run gate and never marks session activity as busy. The session lock can therefore be released while the requester is still producing durable llm.request or usage.record entries; if another process opens the same session then, both writers can interleave the session log. Keep the run gate/session lock held for the prediction's entire lifetime, including predictions started against a cold-resumed session.

Useful? React with 👍 / 👎.

Comment on lines +173 to +174
active.outcome = finish.message.toolCalls.length > 0 ? 'tool_call' : 'invalid';
return null;

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 Record silent model responses as empty

When the model follows the instruction's "Or nothing" option and returns no text or only whitespace, predictionText returns null, but this branch classifies every such response without a tool call as invalid. The declared empty outcome is therefore unreachable, so experiment telemetry systematically conflates intentional silence with malformed predictions; distinguish an empty response before assigning the generic invalid outcome.

Useful? React with 👍 / 👎.

Comment on lines +110 to +111
if (this.active !== undefined) this.cancelActive('input');
if (this.suggestion?.accepted === false) this.dismiss('input');

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 Stop counting cleared predictions as submitted

After a user accepts a prediction, deleting all of its text leaves suggestion.accepted intact because editor changes dismiss only unaccepted suggestions. Pressing Enter on that now-empty editor still runs handleSubmit, which emits prediction_submitted, while handleUserInput subsequently drops the empty prompt, falsely counting a submission that never occurred and inflating the experiment's acceptance funnel. Preserve the accepted association only for an actual non-empty submission, or dismiss it when the accepted draft is cleared.

Useful? React with 👍 / 👎.

Comment on lines +150 to +153
this.telemetry.track2('prediction_requested', {
prediction_id: active.predictionId,
turn_id: active.expectedTurnId,
});

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 Bind prediction telemetry to the main agent

These are declared as agent-scoped telemetry events, but this service is session-scoped and its injected telemetry binding contains only session_id; unlike telemetry obtained from the resolved main-agent scope, it has no agent_id. Every prediction_requested and prediction_generated record therefore violates the event's context contract and cannot be reliably joined or grouped with the main-agent turn it references. Emit through the main agent's telemetry binding or otherwise attach the required agent context.

Useful? React with 👍 / 👎.

@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: d85e9428c8

ℹ️ 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 +201 to +204
state.editor.inputMode === 'prompt' &&
state.editor.getText().length === 0 &&
state.editor.terminalFocused &&
!state.editor.hasAutocompleteActivity()

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 Require actual editor focus for predictions

When keyboard focus moves to the Updates panel via Ctrl+N, terminalFocused remains true because it tracks terminal-window focus rather than component focus, and focusNotifyPanel() does not dismiss this controller. A turn completing while that panel is active can therefore generate a suggestion—or preserve an existing one—that reappears ready to accept when the user returns to the editor, despite the feature's focused-editor eligibility rule. Check editor.focused here and cancel or dismiss predictions when keyboard focus leaves the editor.

Useful? React with 👍 / 👎.

Comment on lines +123 to +127
currentTurn === undefined ||
currentTurn.inputOther + currentTurn.inputCacheCreation >
PROMPT_PREDICTION_MAX_UNCACHED_INPUT_TOKENS
) {
return null;

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 Restore last-turn usage before serving cold predictions

When :predict-prompt or the klient facade is invoked after a session was cold-resumed, replay reconstructs UsageAgentModel.byModel but never its private currentTurn, which is assigned only by the live record() path. This condition therefore returns null for an otherwise eligible completed turn, making the new public contract silently stop producing predictions after session reclamation or a server restart. Persist or reconstruct the last turn's usage, or use another durable input for this cost gate.

AGENTS.md reference: AGENTS.md:L121-L123

Useful? React with 👍 / 👎.

@sailist

sailist commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

@codex

@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: 1b2c3341da

ℹ️ 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 +100 to +103
if (
(matchesKey(data, Key.tab) || matchesKey(data, Key.right)) &&
this.suggestion?.accepted === false &&
!this.host.state.editor.hasAutocompleteActivity()

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 Prevent prediction acceptance in Bash mode

If a suggestion is visible and the user types !, the editor switches to Bash mode without dismissing the retained suggestion; pressing Tab or Right Arrow then still enters this branch and inserts the prediction into the shell-command buffer. A prediction such as git push can therefore replace the Bash completion the user requested and run as a shell command when they press Enter. Dismiss predictions on input-mode changes or require inputMode === 'prompt' before accepting them.

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the feat-331-11-04-prompt-prediction branch from fdfb49e to 2e795f9 Compare November 9, 2026 13:18

@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: 2e795f9389

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

state.livePane.pendingQuestion === null &&
state.editor.inputMode === 'prompt' &&
state.editor.getText().length === 0 &&
state.editor.terminalFocused &&

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 Dismiss predictions when terminal focus leaves

When a prediction is already visible and the terminal emits a focus-out event, focus tracking only sets terminalFocused to false; this condition is evaluated only while starting or resolving a prediction, so the stored suggestion survives and becomes acceptable again when the user returns, potentially after the terminal has been unattended for an arbitrary time. Wire focus-out to dismiss/cancel the prediction using the already-declared visibility reason.

Useful? React with 👍 / 👎.

- reuse the requester's default tool shaping for predictions
- propagate cancellation reasons through SDK and server APIs
- add cache, timing, and outcome logging for prediction requests
- explain the experimental flag and TUI interaction in English and Chinese
- add the confirmed minor changeset for the CLI
- adopt CC-inspired next-prompt guidance
- allow 20 seconds for prediction requests
- preserve visibility cancellation reasons through REST
- dismiss predictions when entering plan mode
- reject terminal control characters
- accept only completed prediction responses
@sailist
sailist force-pushed the feat-331-11-04-prompt-prediction branch from cb08c48 to 41f4694 Compare November 11, 2026 12:41
@sailist
sailist merged commit 482936a into main Nov 11, 2026
16 checks passed
@sailist
sailist deleted the feat-331-11-04-prompt-prediction branch November 11, 2026 13:35
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 11, 2026
Ingest the 15 upstream commits landed after the 2.5.3 release sync and
cluster the open backlog into themed batches. Three rows stay unassigned
pending a scope decision: prediction (MoonshotAI#4754, six packages), upgrade
prompts (MoonshotAI#4756), and the desktop-titled retry fix (MoonshotAI#4831) whose content
lives in agent-core-v2/kap-server.
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