Repository navigation
Conversation
Send agent role, turn trigger, step reason, and user input id on Kimi model requests so request logs can be joined back to the loop.
|
There was a problem hiding this comment.
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.
Ask the provider definition whether a request should carry internal metadata instead of comparing the provider name.
Consume retry and recovery reasons once at the gate, so they no longer stick to later steps and the first step reports turn_start. Move the header encoding onto the Kimi provider definition and reuse the existing agent role helpers.
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3e41cfe09d
ℹ️ 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 encode = getProviderDefinition(model.providerType, model.protocol)?.requestMetadataHeaders; | ||
| if (encode === undefined) return request; |
There was a problem hiding this comment.
Restrict internal metadata to official Kimi endpoints
When an existing provider config uses type = "kimi" with a custom baseUrl—a supported configuration used for Kimi-compatible backends—this check keys only on providerType, so every request to that arbitrary endpoint receives X-Msh-Internal-Metadata, including the agent role, turn trigger, and user-input correlation ID. This unexpectedly discloses internal metadata to third-party endpoints and contradicts the stated claim that the header is not forwarded to third-party providers; gate it on an official/managed endpoint or make it an explicit provider opt-in.
AGENTS.md reference: AGENTS.md:L109-L111
Useful? React with 👍 / 👎.
| 'X-Msh-Internal-Metadata': JSON.stringify({ | ||
| agent_role: metadata.agentRole, | ||
| turn_trigger: metadata.turnTrigger, | ||
| step_reason: metadata.stepReason, | ||
| user_input_id: metadata.userInputId, |
There was a problem hiding this comment.
Escape non-ASCII prompt IDs before adding the header
For a Kimi prompt whose accepted prompt_id contains CJK characters or emoji, JSON.stringify preserves those characters in user_input_id, but the HTTP Headers implementation requires header values to be ByteStrings and throws before sending the model request. The REST contract accepts any nonempty string as a prompt ID, so this turns previously valid client requests into failed turns; encode the metadata into an ASCII-safe representation or escape non-ASCII code points before using it as a header value.
AGENTS.md reference: AGENTS.md:L109-L111
Useful? React with 👍 / 👎.
| const endpoint = contentsOf(request).endpoint; | ||
| return request.with({ | ||
| endpoint: { headers: mergeHeaders(endpoint?.headers, header) }, |
There was a problem hiding this comment.
Replace the reserved header case-insensitively
When customHeaders, KIMI_CODE_CUSTOM_HEADERS, or forwarded host headers already contain x-msh-internal-metadata with different casing, mergeHeaders retains both record keys because it compares them case-sensitively. HTTP Headers then combines the two values into one comma-delimited value, which is no longer valid JSON, so the gateway silently loses the request metadata this change is intended to provide; remove any case-insensitive match before installing the generated header or merge through Headers.set.
AGENTS.md reference: AGENTS.md:L129-L131
Useful? React with 👍 / 👎.
|
@codex review |
Retries and recoveries reuse the reason of the step they resend, and a notification riding a tool-result request no longer replaces it. A spawned agent inherits the parent turn user input id when its own turn has none.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 628f7de2d9
ℹ️ 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".
| 'X-Msh-Client-Metadata': JSON.stringify({ | ||
| agent_role: metadata.agentRole, | ||
| turn_trigger: metadata.turnTrigger, | ||
| step_reason: metadata.stepReason, | ||
| user_input_id: metadata.userInputId, |
There was a problem hiding this comment.
Bound prompt IDs before copying them into headers
When a REST, SDK, or Klient caller supplies a several-thousand-character prompt_id, the request is valid because those contracts enforce only non-emptiness, but this code copies the complete ID into an HTTP header; non-ASCII IDs expand to six bytes per UTF-16 code unit during escaping, so ordinary server header-size limits can reject the subsequent Kimi model request with 431 even though the same prompt worked before this change. Limit the accepted ID length or send a bounded/hash representation in the metadata header.
AGENTS.md reference: AGENTS.md:L109-L111
Useful? React with 👍 / 👎.
| const header = encode({ | ||
| agentRole: agentRoleOf(this.scopeContext.agentId, metadata), | ||
| turnTrigger: turn?.turnTrigger, | ||
| stepReason: turn?.stepReason, | ||
| userInputId: turn?.userInputId, |
There was a problem hiding this comment.
Recompute metadata for each HTTP retry attempt
When generateModel() retries internally after a structure or media recovery, or when KIMI_CODE_INFINITE_RETRY reruns the request, it reuses the requester constructed here without re-entering the loop gate. Consequently every resent HTTP request retains the original step_reason (such as turn_start) instead of reporting recovery or retry, even though distinguishing those requests is the purpose of this metadata. Install or update the metadata at each actual attempt rather than once in resolveRequest().
Useful? React with 👍 / 👎.
Carry AgentMeta on IAgentScopeContext and inherit activeUserInputId in AgentLifecycleService so AgentLoopRequester no longer depends on ISessionMetadata.current() or features/* constants.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d3281fabcf
ℹ️ 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".
| userInputId: | ||
| agentId === 'main' | ||
| ? undefined | ||
| : (opts.userInputId ?? this.userInputIdOfAgent(parentAgentId)), |
There was a problem hiding this comment.
Preserve the stored ID when rebuilding swarm members
When AgentSwarm resumes or retries a member whose live scope has been evicted, SessionSwarmService.rebuildSubagent() recreates it without passing the persisted meta.userInputId. This fallback therefore samples the caller's currently active input ID and overwrites the original correlation stored for that member, so its subsequent Kimi requests are attributed to the resume prompt instead of the input that created it. The other restoration paths in agentTool.ts and getOrRestoreAgent.ts explicitly pass meta.userInputId; the swarm rebuild should do the same.
Useful? React with 👍 / 👎.
| labels: meta.labels, | ||
| userInputId: meta.userInputId, |
There was a problem hiding this comment.
Preserve legacy labels when restoring agents
When a subagent from an older session stores its parent or swarm identity in the legacy top-level AgentMeta.parentAgentId or AgentMeta.swarmItem fields, this generic restore passes only meta.labels. The recreated scope metadata therefore loses those fields, and the newly added agentRoleOf() path reports a restored swarm member as a plain subagent; nested agents can also fall back to the main agent when deriving request correlation. Pass labelsFromAgentMeta(meta), as the specialized rebuild paths do, so previous-release session metadata remains effective.
AGENTS.md reference: AGENTS.md:L109-L111
Useful? React with 👍 / 👎.
| readonly forkedFrom?: string; | ||
| readonly labels?: Readonly<Record<string, string>>; | ||
| readonly swarmItem?: string; | ||
| readonly userInputId?: string; |
There was a problem hiding this comment.
Carry user input IDs into forked session metadata
When a session containing persisted subagents is forked, including through createChild(), SessionLifecycleService.fork() reconstructs each AgentMeta but does not copy this new field from sourceAgent. Restoring one of those subagents in the target session has no live parent from which to infer the original ID, so its subsequent Kimi requests omit user_input_id even though the source session retained it. Copy sourceAgent.userInputId into the reconstructed metadata alongside forkedFrom and labels.
Useful? React with 👍 / 👎.
Kimi requests now include compact as a step reason, reuse the last user input id, and attach the parent step trace id on subagent requests.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d082c00059
ℹ️ 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".
| userInputId: | ||
| userInputIdOf(event.origin, event.promptId) ?? | ||
| dispatched?.userInputId ?? | ||
| state.userInputId, |
There was a problem hiding this comment.
Clear stale user IDs for independent turns
When an agent that handled a client prompt later runs a scheduled cron job, deliverFire() submits a new turn with a cron_job origin (packages/agent-core-v2/src/features/cron/cronService.ts:185-200), but this fallback retains the prior prompt’s ID because userInputIdOf() returns no ID for that origin; TurnEnded only clears activeTurn (requestMetadata.ts:183-185). The cron request, and any subagent it starts, is therefore silently attributed to the earlier prompt. Clear the stored ID for independent triggers while preserving it for continuations.
Useful? React with 👍 / 👎.
…-metadata # Conflicts: # packages/agent-core-v2/src/agent/loop/requester.ts # packages/agent-core-v2/test/agent/llmRequester/llmRequesterService.test.ts # packages/agent-core-v2/test/agent/loop/loop.test.ts
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1ceb6e8163
ℹ️ 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".
| userInputId: | ||
| userInputIdOf(event.origin, event.promptId) ?? | ||
| dispatched?.userInputId ?? | ||
| state.userInputId, | ||
| parentRequestId: dispatched?.parentRequestId ?? state.parentRequestId, |
There was a problem hiding this comment.
Restore subagent attribution after cold reloads
When a session is cold-reloaded and a persisted non-fork subagent is resumed through a swarm retry rather than a fresh system_trigger/subagent dispatch, the session-scoped attribution map starts empty and replay is silent, so both dispatched and state.userInputId are undefined here; the child journal contains only its subagent prompt ID, which userInputIdOf rejects. Subsequent Kimi requests therefore omit the inherited user_input_id and parent_request_id; persist or reconstruct the sampled attribution instead of relying solely on the in-memory map.
Useful? React with 👍 / 👎.
| userInputIdOf(event.origin, event.promptId) ?? | ||
| dispatched?.userInputId ?? | ||
| state.userInputId, | ||
| parentRequestId: dispatched?.parentRequestId ?? state.parentRequestId, |
There was a problem hiding this comment.
Clear stale parent IDs on a fresh dispatch
When a reused subagent is dispatched from a new parent request whose response has no parsed request ID—for example, a Kimi-compatible endpoint omits x-trace-id—noteSubagentDispatch() falls back to the child's previous parentRequestId, and this fallback preserves it again. The new task's metadata is then attributed to the request that launched an earlier task; a fresh subagent dispatch should replace or clear the stored parent ID when the parent has no active request ID.
Useful? React with 👍 / 👎.
| if (source.type === 'turn') this.telemetry.setContext({ request_id: requestId }); | ||
| if (source.type !== 'turn') return; | ||
| this.telemetry.setContext({ request_id: requestId }); | ||
| this.attribution.noteActiveRequest(this.scopeContext.agentId, requestId); |
There was a problem hiding this comment.
Keep third-party request IDs out of Kimi parent attribution
When a parent agent uses an OpenAI or Anthropic provider and launches a child configured for Kimi, this records the third-party provider's request ID in the shared attribution map. The child then sends that unrelated ID as parent_request_id to Kimi even though Kimi's logs cannot resolve it—and an accidental ID collision can create a false parent link. Record parent IDs only for requests in the same metadata namespace, or retain provider identity with the ID before forwarding it.
Useful? React with 👍 / 👎.
Requirement or Bug
分析 Kimi Code 的模型请求时,服务端日志只有 HTTP 请求本身,分不出这条请求来自哪种 Agent、这一轮为什么开始、这一步为什么发出、以及它属于用户哪一次输入。这个 PR 让声明了
requestMetadata的 provider 在模型请求上附带X-Msh-Client-Metadata头,供请求日志关联。目前只有 Kimi 声明了这个能力。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
归因由
RequestMetadataTracker与 Session 级的ISessionRequestAttributionService完成。AgentLoopRequestFactory.resolveRequest()在组好协议请求后附加 HTTP header,AgentLoopRequestObserver.setRequestId()统一上报当前 turn 的 request ID;要不要带这个头由 provider definition 上的requestMetadata: true决定(与hostHeaders: 'full'同级)。Core Loop、SessionMetadata、SubagentService与各工具不需要透传归因参数。flowchart LR meta["IAgentScopeContext.meta"] --> role["agent_role"] prompt["TurnPrompt"] --> trigger["turn_trigger"] prompt --> inputId["user_input_id"] stepDone["TurnStepCompleted"] --> stepReason["step_reason"] compact["full_compaction"] --> compactReason["step_reason compact"] trace["turn request traceId"] --> sessionAttr["ISessionRequestAttributionService"] inputId --> sessionAttr sessionAttr --> subDispatch["subagent TurnPrompt"] role --> metadata["RequestMetadataTracker.resolve"] trigger --> metadata inputId --> metadata stepReason --> metadata compactReason --> metadata subDispatch --> metadata metadata --> attach{"provider declares requestMetadata?"} attach -- yes --> header["attach X-Msh-Client-Metadata"] header --> request["model request"] attach -- no --> skip["request unchanged"]头里是一份 JSON。
agent_role、turn_trigger、step_reason必有;user_input_id和parent_request_id没有值时省略。非 ASCII 会转成\uXXXX,保证 header 是合法的 HTTP ByteString。agent_role从IAgentScopeContext.meta映射:main、btw、tower_worker、swarm_member、subagent、other。turn_trigger来自这一轮TurnPrompt的origin。压缩请求如果发生在 turn 内,沿用当前 turn 的 trigger;idle/compact归为user。step_reason由RequestMetadataTracker根据当前 turn 事件决定:收到TurnPrompt时为turn_start(首步 retry / recovery 未触发TurnStepCompleted,重发时保持turn_start),收到TurnStepCompleted后切换为tool_results。requestKind === 'full_compaction'的请求为compact。user_input_id是用户本人发出的prompt_id(普通输入、用户斜杠 skill、插件命令)。这个值随TurnPrompt记录(重放wire.jsonl时自动恢复),之后的cron、background_task、goal_continuation以及 idle 压缩都沿用它。子 Agent 在收到实时subagent任务派发或从父 Agent fork 时通过ISessionRequestAttributionService继承父 Agent 的user_input_id。parent_request_id只在子 Agent 上有值。AgentLoopRequestObserver在每步 turn 请求拿到x-trace-id时写入ISessionRequestAttributionService,子 Agent 实时启动subagentturn(spawn 或 resume)时采样父 Agent 当时的activeRequestId;swarm 限流重试和 tower inbox 不重新采样,沿用旧值;仅重放历史记录、/init和/btw不带。阅读顺序:
packages/agent-core-v2/src/agent/loop/requestMetadata.ts:角色、turn 原因、用户输入 ID 的映射,RequestMetadataTracker的事件折叠,以及 header 编码。packages/agent-core-v2/src/session/requestAttribution/requestAttributionService.ts:Session 内各 Agent 的userInputId、activeRequestId与子 Agent 派发归因表。packages/agent-core-v2/src/agent/loop/requester.ts:AgentLoopRequestFactory在统一请求装配点附加 metadata header。packages/agent-core-v2/src/agent/loop/requestObservation.ts:AgentLoopRequestObserver在 request ID 生命周期边界更新 Session 归因。Behavior Changes and Affected Users
providerType === 'kimi'的模型请求 HTTP headersX-Msh-Client-Metadataagent_role、turn_trigger、step_reason,以及有值时的user_input_id、parent_request_id。仅 Kimi provider 发送step_reason为compact;idle 时turn_trigger为user,并沿用上一轮user_input_id其他 provider 的请求不变。客户端请求体、会话状态契约(
state-manifest.d.ts)、会话回放和工具协议不变。覆盖了角色和 turn 原因映射、压缩请求的
compact、父子 Agent 的user_input_id与parent_request_id派发及驱逐重建保留、仅重放时不吸附父请求、主 Agent 从wire.jsonl恢复用户输入 id、声明与未声明 provider 的 header 有无,以及非 ASCIIprompt_id的 ByteString 转义。验证
合并最新
main后:pnpm --filter @moonshot-ai/agent-core-v2 run typecheck通过。pnpm run lint通过,无 error。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.