Repository navigation
feat(prediction): add experimental next-prompt suggestions - #4754
Conversation
🦋 Changeset detectedLatest commit: 41f4694 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 && |
There was a problem hiding this comment.
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 👍 / 👎.
| : input.source?.type === 'operation' && input.source.requestKind === 'prompt_prediction' | ||
| ? 'prediction' |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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 👍 / 👎.
| prediction_id: z.string().min(1).optional(), | ||
| expected_turn_id: z.number().int().nonnegative().optional(), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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( |
There was a problem hiding this comment.
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 👍 / 👎.
| active.outcome = finish.message.toolCalls.length > 0 ? 'tool_call' : 'invalid'; | ||
| return null; |
There was a problem hiding this comment.
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 👍 / 👎.
| if (this.active !== undefined) this.cancelActive('input'); | ||
| if (this.suggestion?.accepted === false) this.dismiss('input'); |
There was a problem hiding this comment.
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 👍 / 👎.
| this.telemetry.track2('prediction_requested', { | ||
| prediction_id: active.predictionId, | ||
| turn_id: active.expectedTurnId, | ||
| }); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| state.editor.inputMode === 'prompt' && | ||
| state.editor.getText().length === 0 && | ||
| state.editor.terminalFocused && | ||
| !state.editor.hasAutocompleteActivity() |
There was a problem hiding this comment.
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 👍 / 👎.
| currentTurn === undefined || | ||
| currentTurn.inputOther + currentTurn.inputCacheCreation > | ||
| PROMPT_PREDICTION_MAX_UNCACHED_INPUT_TOKENS | ||
| ) { | ||
| return null; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| if ( | ||
| (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) && | ||
| this.suggestion?.accepted === false && | ||
| !this.host.state.editor.hasAutocompleteActivity() |
There was a problem hiding this comment.
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 👍 / 👎.
fdfb49e to
2e795f9
Compare
There was a problem hiding this comment.
💡 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 && |
There was a problem hiding this comment.
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
cb08c48 to
41f4694
Compare
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.
Requirement or Bug
交互式 TUI 用户在主 Agent 正常完成一轮后,仍需要手动构思并输入下一步提示。这个 PR 按内部 RFC revision 154 新增默认关闭的实验性下一提示词预测:会话空闲且输入框为空时生成一条建议,用户按
Tab或→填入并继续编辑,只有明确按Enter才提交。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]这样组织是为了保持预测与正式会话隔离,同时复用正式 turn 的请求组装与缓存前缀,而不是另建一套模型请求路径。
tools === undefined,复用defaultTools和shapeHistorytoolsHash一致,避免缓存前缀被额外工具定义打破按阅读顺序建议先看:
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或→只填入,不自动提交。Behavior Changes and Affected Users
prompt_prediction的 TUI 用户/experiments关闭,或不设置KIMI_CODE_EXPERIMENTAL_PROMPT_PREDICTIONTab/→只填入可编辑文本,只有Enter才提交Esc清除,不会自动提交cancelled、failed、blocked不生成;新 turn、输入、会话切换等会取消或清除reason;旧调用未传时记为unspecifieddefaultTools和shapeHistorykind=prediction、usageScope=predictionfalse对应验证覆盖:实验开关与正常/异常 turn、严格一次、上下文与 Main Agent 过期隔离、用户取消、断连、tool call 零执行、默认 Requester 工具路径、按键接受与清除、klient/SDK/REST 契约、usage 类型及 vis 聚合。
Checklist
gen-changesetsskill — 已包含@moonshot-ai/kimi-code的 minor changeset。gen-docsskill — 已同步更新docs/en与docs/zh;仓库中不存在该技能提及的docs/scripts/sync-changelog.mjs,因此没有伪造 changelog 同步结果。验证结果
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;未将单次样本表述为总耗时必然下降。packages/agent-core-v2/test/remote/process.test.ts,未把这些失败记作全绿或修改无关测试。