Skip to content

feat(agent-core-v2): attach Kimi request metadata - #4753

Closed
7Sageer wants to merge 11 commits into
mainfrom
feat/request-internal-metadata
Closed

7Sageer wants to merge 11 commits into
mainfrom
feat/request-internal-metadata

Conversation

@7Sageer

@7Sageer 7Sageer commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

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"]
Loading

头里是一份 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 实时启动 subagent turn(spawn 或 resume)时采样父 Agent 当时的 activeRequestId;swarm 限流重试和 tower inbox 不重新采样,沿用旧值;仅重放历史记录、/init 和 /btw 不带。

阅读顺序:

  1. packages/agent-core-v2/src/agent/loop/requestMetadata.ts:角色、turn 原因、用户输入 ID 的映射,RequestMetadataTracker 的事件折叠,以及 header 编码。
  2. packages/agent-core-v2/src/session/requestAttribution/requestAttributionService.ts:Session 内各 Agent 的 userInputId、activeRequestId 与子 Agent 派发归因表。
  3. packages/agent-core-v2/src/agent/loop/requester.ts:AgentLoopRequestFactory 在统一请求装配点附加 metadata header。
  4. packages/agent-core-v2/src/agent/loop/requestObservation.ts:AgentLoopRequestObserver 在 request ID 生命周期边界更新 Session 归因。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
providerType === 'kimi' 的模型请求 HTTP headers 不带 X-Msh-Client-Metadata 带 agent_role、turn_trigger、step_reason,以及有值时的 user_input_id、parent_request_id。仅 Kimi provider 发送 无客户端或网关依赖该请求头的缺失 无
Kimi 压缩请求 与普通模型请求一样不带该头 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 有无,以及非 ASCII prompt_id 的 ByteString 转义。

验证

合并最新 main 后:

  • pnpm --filter @moonshot-ai/agent-core-v2 run typecheck 通过。
  • pnpm run lint 通过,无 error。
  • requester、request metadata、loop、projector 四个测试文件共 200 个测试通过。

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.

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.
Copilot AI balanced review requested due to automatic review settings November 9, 2026 06:35
@changeset-bot

changeset-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 1ceb6e8

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a 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.

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.
@7Hanrui

7Hanrui commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

@codex review

@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-11T05:29:05.481848Z 1ceb6e8 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: 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".

Comment on lines +783 to +784
const encode = getProviderDefinition(model.providerType, model.protocol)?.requestMetadataHeaders;
if (encode === undefined) return request;

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 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 👍 / 👎.

Comment on lines +206 to +210
'X-Msh-Internal-Metadata': JSON.stringify({
agent_role: metadata.agentRole,
turn_trigger: metadata.turnTrigger,
step_reason: metadata.stepReason,
user_input_id: metadata.userInputId,

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 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 👍 / 👎.

Comment on lines +793 to +795
const endpoint = contentsOf(request).endpoint;
return request.with({
endpoint: { headers: mergeHeaders(endpoint?.headers, header) },

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 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 👍 / 👎.

@7Hanrui

7Hanrui commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

@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.

@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: 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".

Comment on lines +206 to +210
'X-Msh-Client-Metadata': JSON.stringify({
agent_role: metadata.agentRole,
turn_trigger: metadata.turnTrigger,
step_reason: metadata.stepReason,
user_input_id: metadata.userInputId,

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 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 👍 / 👎.

Comment on lines +787 to +791
const header = encode({
agentRole: agentRoleOf(this.scopeContext.agentId, metadata),
turnTrigger: turn?.turnTrigger,
stepReason: turn?.stepReason,
userInputId: turn?.userInputId,

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 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.
@7Hanrui

7Hanrui commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

@codex review

@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: 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".

Comment on lines +273 to +276
userInputId:
agentId === 'main'
? undefined
: (opts.userInputId ?? this.userInputIdOfAgent(parentAgentId)),

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 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 👍 / 👎.

Comment on lines +18 to +19
labels: meta.labels,
userInputId: meta.userInputId,

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 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;

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 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.
@7Hanrui

7Hanrui commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 96125c3c85

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

@7Hanrui

7Hanrui commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

@codex review

@7Sageer
7Sageer marked this pull request as ready for review November 10, 2026 10:28
@pkg-pr-new

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

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

commit: 1ceb6e8

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

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 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
@7Hanrui

7Hanrui commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

@codex review

@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: 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".

Comment on lines +160 to +164
userInputId:
userInputIdOf(event.origin, event.promptId) ??
dispatched?.userInputId ??
state.userInputId,
parentRequestId: dispatched?.parentRequestId ?? state.parentRequestId,

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 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,

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 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);

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 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 👍 / 👎.

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.

3 participants