Skip to content

refactor(kap-server): compact session state, global events, and snake_case contracts - #4963

Merged
wbxl2000 merged 7 commits into
mainfrom
refactor/kap-session-and-events
Nov 17, 2026
Merged

wbxl2000 merged 7 commits into
mainfrom
refactor/kap-session-and-events

Conversation

@wbxl2000

@wbxl2000 wbxl2000 commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

基于 #4891(已合入 main),与客户端 MoonshotAI/kimi-code-app#1320 同步配套;公开协议文档在同栈后续 #4966 中统一更新。

收敛 KAP 会话与事件的核心数据形态,消除历史空占位字段、嵌套全局信封和混合命名风格,为后续清理旧路由与发布协议文档打底。本 PR 落地精简版 Session、把上下文窗口水位帧从 usage 正名为 context、将 12 种旧 event.* 全局帧收敛为平铺帧、GET /api/v1/meta 补充协议版本号并移除恒定为 v2 的 backend 字段,同时将 /mcp/*、/plugins/*、/capabilities/* 的公开载荷统一为 snake_case。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路

服务端对会话与全局状态只输出一套无历史包袱的平铺投影:客户端收到 session、workspace、config、invalidated 等全局帧或 context 状态帧时直接整包替换或按需重拉,不再合并残缺增量,也不再区分两套字段命名约定。

flowchart LR
  Engine[agent-core-v2 生命周期与状态] --> Projection[kap-server 统一协议投影]
  Projection -->|Session 顶层 cwd/activity/last_turn_outcome| REST["/api/v1/sessions & /profile"]
  Projection -->|平铺 session / workspace / config / invalidated| GlobalWS["/api/v1/ws 全局广播"]
  Projection -->|agent / context / goal / todo| AgentWS["/api/v1/ws Agent 状态流"]
  Engine -->|显式 snake_case Wire 映射| CatalogREST["/api/v1/mcp & /plugins & /capabilities"]
Loading

因为上下文窗口当前占用(可涨可跌的水位)与累计 Token 计费账单语义截然不同,所以将原 WebSocket usage 帧改名为 context;同时在路由边界增加显式 Wire 映射函数,把引擎内部的驼峰对象转换为 snake_case,既不侵入磁盘 mcp.json / installed.json 存储格式,又保证对外协议命名一致。

协议事件与字段 + / - 清单

1. Session 对象与会话接口(GET /sessions、GET /sessions/{id}、POST /sessions、POST /sessions/{id}/profile)

  {
    id: string
    workspace_id: string
+   cwd: string                                        // 从 metadata.cwd 提升到顶层必填
    title: string
    created_at: string
    updated_at: string
-   busy: boolean
-   main_turn_active?: boolean
+   activity: 'idle' | 'turn' | 'background'           // 合一 busy + main_turn_active
    pending_interaction?: 'none' | 'approval' | 'question'
-   last_turn_reason?: 'completed' | 'cancelled' | 'failed'
+   last_turn_outcome?: 'completed' | 'interrupted' | 'failed'  // 对齐 Turn.outcome
    archived?: boolean
    archived_at?: string
-   current_prompt_id?: string
    last_prompt?: string
-   metadata: { cwd: string, ... }
+   metadata?: Record<string, unknown>                 // 仅保留自定义键值,空时省略
-   agent_config: SessionAgentConfig                   // 移至 WS `agent` 帧 & `/profile` 响应
-   usage: SessionUsage                                // 单轮在 `Turn.usage`,水位在 WS `context` 帧
-   permission_rules: PermissionRule[]
-   message_count: number
    git?: SessionGit
  }

  // POST /api/v1/sessions 请求体
+ cwd?: string                                         // 新增顶层 cwd(metadata.cwd 仍兼容)

  // POST /api/v1/sessions/{session_id}/profile 响应 data
- Session
+ { session: Session, agent: AgentState }              // 同时支持 goal_control: 'edit' 原地改目标

2. WebSocket Agent 状态帧(/api/v1/ws 订阅推送)

  // agent 帧:新增已终结状态 'ended'
  {
    type: 'agent',
    event_created_at: string,
    session_id: string,
    agent_id: string,
-   status: 'idle' | 'running',
+   status: 'idle' | 'running' | 'ended',
    compacting: boolean,
    model?: string, thinking?: string, permission_mode?: string,
    plan_mode: boolean, swarm_mode: boolean, tower_mode: boolean,
  }

  // usage 帧重命名为 context 帧(字段不变,250ms 节流)
  {
-   type: 'usage',
+   type: 'context',
    event_created_at: string,
    session_id: string,
    agent_id: string,
    context_tokens: number,
    max_context_tokens?: number,
  }

3. WebSocket 全局事件帧(去 { session_id, timestamp, payload } 外层信封 + 归并平铺)

- { type: 'event.session.created',      session_id, timestamp, payload: { session } }
- { type: 'session.meta.updated',       session_id, timestamp, payload: { title?, patch? } }
- { type: 'event.session.work_changed', session_id, timestamp, payload: { busy, main_turn_active?, pending_interaction?, last_turn_reason? } }
- { type: 'event.session.archived',     session_id, timestamp, payload: { workspace_id } }
- { type: 'event.session.restored',     session_id, timestamp, payload: { workspace_id } }
- { type: 'event.session.deleted',      session_id, timestamp, payload: { workspace_id } }
+ { type: 'session', event_created_at, change: 'created' | 'updated' | 'archived' | 'restored' | 'deleted', session: Session }

- { type: 'event.workspace.created',    session_id, timestamp, payload: { workspace } }
- { type: 'event.workspace.updated',    session_id, timestamp, payload: { workspace } }
- { type: 'event.workspace.deleted',    session_id, timestamp, payload: { workspace_id, root } }
+ { type: 'workspace', event_created_at, change: 'created' | 'updated' | 'deleted', workspace: Workspace }

- { type: 'event.config.changed',       session_id, timestamp, payload: { changedFields, config } }
- { type: 'event.config.warning',       session_id, timestamp, payload: { warnings } }
+ { type: 'config', event_created_at, config: ConfigResponse, warnings?: { domain?, message }[] }

- { type: 'event.model_catalog.changed', session_id, timestamp, payload: { changed, failures?, retiredDefault? } }
- { type: 'event.plugin.changed',        session_id, timestamp, payload: {} }
+ { type: 'invalidated', event_created_at, kind: 'models' | 'plugins' }

- { type: 'event.capability.changed', session_id, timestamp, payload: { capability_id, install: { ..., confirmationRequired? } } }
+ { type: 'event.capability.changed', event_created_at, capability_id, install: { ..., confirmation_required? } }

4. GET /api/v1/meta 与插件 / MCP / 能力 snake_case 收口

  // GET /api/v1/meta
+ kimi_agent_protocol_version: '0.1.0'
- backend?: 'v1' | 'v2'

  // /api/v1/capabilities/*
- pluginId, displayName, confirmationRequired, stopRunningProcesses
+ plugin_id, display_name, confirmation_required, stop_running_processes

  // /api/v1/plugins/*(列表 / 详情 / 市场 / 预览 / 安装)
- displayName, shortDescription, longDescription, cliDescription
+ display_name, short_description, long_description, cli_description
- skillCount, mcpServerCount, enabledMcpServerCount, hookCount, commandCount, hasErrors
+ skill_count, mcp_server_count, enabled_mcp_server_count, hook_count, command_count, has_errors
- catalogId, installedAt, originalSource, installedSha, updatedAt
+ catalog_id, installed_at, original_source, installed_sha, updated_at
- manifestKind, manifestPath, shadowedManifestPath, mcpServers
+ manifest_kind, manifest_path, shadowed_manifest_path, mcp_servers
- iconUrl, runtimeName, envKeys, headerKeys, defaultLocale, defaultInstall, userLevel, updateAvailable, capabilityId
+ icon_url, runtime_name, env_keys, header_keys, default_locale, default_install, user_level, update_available, capability_id
- marketplaceId, expectedVersion, expectedSha256
+ marketplace_id, expected_version, expected_sha256

  // /api/v1/mcp/*(配置 / 定位器 / 探针 / OAuth 鉴权)
- startupTimeoutMs, toolTimeoutMs, enabledTools, disabledTools, bearerTokenEnvVar, envKeys, headerKeys
+ startup_timeout_ms, tool_timeout_ms, enabled_tools, disabled_tools, bearer_token_env_var, env_keys, header_keys
- pluginId, serverName, serverId, runtimeName, canonicalUrl, authStatus, checkedAt
+ plugin_id, server_name, server_id, runtime_name, canonical_url, auth_status, checked_at
- flowId, timeoutMs, authorizationUrl
+ flow_id, timeout_ms, authorization_url

阅读指南

  • packages/kap-server/src/protocol/session.ts、src/routes/sessions.ts:精简后的 Session(顶层 cwd、activity、last_turn_outcome)、创建会话顶层 cwd 支持,以及 POST /sessions/{id}/profile 返回 { session, agent }(纯修改标题/metadata 时不额外实体化未创建的主 Agent)。
  • packages/kap-server/src/protocol/ws-agent.ts、src/transport/ws/v1/sessionAgentFeed.ts:原 usage 帧正名为 context,以及 Agent 关闭时推送最终 status: "ended" 帧并自动释放空订阅条目。
  • packages/kap-server/src/protocol/events-zod.ts、src/transport/ws/v1/sessionEventBroadcaster.ts:平铺全局事件构建与广播(优先读取内存实时 ISessionMetadata,归档/恢复事件显式投影 archived 状态,:reload 保留 main 订阅)。
  • packages/kap-server/src/routes/meta.ts:kimi_agent_protocol_version: "0.1.0" 与移除 backend 字段。
  • packages/kap-server/src/routes/{mcp,plugins,capabilities}.ts 与 src/protocol/rest-{plugin,capability}.ts:请求与响应边界上的 snake_case 双向映射。
  • 测试文件(packages/kap-server/test/*、packages/klient/test/e2e/*)验证上述新契约,可按需略读。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Session 字段 含 busy、main_turn_active、last_turn_reason,以及恒为空/零的 agent_config、usage、permission_rules、message_count;cwd 仅在 metadata.cwd 顶层提供 cwd、activity(idle/turn/background)、last_turn_outcome(completed/interrupted/failed);移除空占位字段;创建会话接受顶层 cwd(仍兼容传入 metadata.cwd) Desktop / Web 会话列表与外部 KAP 脚本 读取顶层 cwd、activity、last_turn_outcome;模型与上下文水位从对应 Agent 帧读取(维护者已在本系列计划中确认,无旧字段回退)
POST /api/v1/sessions/{id}/profile 响应与目标编辑 仅返回 Session;goal_control 不支持 edit 返回 { session, agent };支持 goal_control: "edit" 配合 goal_objective 原地修改目标 更新模型、思考档位或编辑 Goal 的客户端 从 data.session 与 data.agent 读取(客户端同层 PR 同步适配)
WebSocket 上下文窗口水位帧 type: "usage" type: "context"(载荷保持 context_tokens、max_context_tokens) Desktop / Web 状态栏圆环与外部 WebSocket 订阅方 按 type: "context" 消费
WebSocket 全局事件 12 种带 session_id、timestamp、payload 外层信封的 event.* / session.meta.updated 帧 顶层平铺 session、workspace、config、invalidated(及扁平化 event.capability.changed),统一带 event_created_at 与完整对象 Desktop / Web 事件 reducer 与外部连接 消费平铺全局事件并按完整对象替换本地状态
GET /api/v1/meta 返回 backend: "v2",无协议版本号 新增 kimi_agent_protocol_version: "0.1.0",移除 backend 字段 读取 /meta 的客户端与探针 使用 kimi_agent_protocol_version 识别协议版本
/api/v1/mcp/*、/plugins/*、/capabilities/* 字段命名 透传引擎内部 camelCase(如 flowId、authStatus、displayName、marketplaceId、stopRunningProcesses) 请求体与响应体统一为 snake_case(如 flow_id、auth_status、display_name、marketplace_id、stop_running_processes) Desktop / Web 插件与 MCP 设置面板及外部管理脚本 改用 snake_case 字段名(CLI /plugins 走进程内服务不受影响)

受影响模块与验证

  • 受影响模块:packages/kap-server、packages/agent-core-v2(工作区与会话删除事件附带快照、goal_control: "edit" schema)、packages/klient(live e2e 适配平铺 session 帧)。
  • 验证结论:kap-server 全量 70 个测试文件通过;agent-core-v2 workspaceService.test.ts 通过;kap-server、agent-core-v2、klient 类型检查与 oxlint --type-aware 0 错误。
验证命令与输出摘要
  • pnpm --filter @moonshot-ai/kap-server test → 70 passed (70), 1366 passed | 1 skipped
  • pnpm --filter @moonshot-ai/agent-core-v2 exec vitest run test/app/workspace/workspaceService.test.ts → 71 passed
  • pnpm --filter @moonshot-ai/agent-core-v2 --filter @moonshot-ai/kap-server --filter @moonshot-ai/klient typecheck → 通过
  • pnpm exec oxlint --type-aware --quiet packages/agent-core-v2 packages/kap-server packages/klient → 0 errors

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.

@changeset-bot

changeset-bot Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 6db18fa

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 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-16T13:11:26.637221Z 6db18fa 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.

@pkg-pr-new

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

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

commit: 6db18fa

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

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

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

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

@wbxl2000

Copy link
Copy Markdown
Collaborator Author

@codex review
已 resolve 的主题代表我们的判断取舍与当前代码现状,请勿重复提出(其余约定同首轮:只审本 PR 相对 base 的 diff;同类问题一次列全;纯风格意见不发,每条标注 P0/P1/P2)。

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e291814ded

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

@wbxl2000
wbxl2000 force-pushed the refactor/converge-api-v1 branch from 747c49b to b282d7a Compare November 16, 2026 09:39
@wbxl2000
wbxl2000 force-pushed the refactor/kap-session-and-events branch from e291814 to 52e6f0b Compare November 16, 2026 09:40

@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: 52e6f0bcbd

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

@wbxl2000

Copy link
Copy Markdown
Collaborator Author

@codex review
已 resolve 的主题代表我们的判断取舍与当前代码现状,请勿重复提出(其余约定同首轮:只审本 PR 相对 base 的 diff;同类问题一次列全;纯风格意见不发,每条标注 P0/P1/P2)。

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

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

@wbxl2000
wbxl2000 force-pushed the refactor/kap-session-and-events branch from 16d898c to 199cb75 Compare November 16, 2026 10:16
@wbxl2000

Copy link
Copy Markdown
Collaborator Author

@codex review
已 resolve 的主题代表我们的判断取舍与当前代码现状,请勿重复提出(其余约定同首轮:只审本 PR 相对 base 的 diff;同类问题一次列全;纯风格意见不发,每条标注 P0/P1/P2)。

@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: 199cb75234

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

Base automatically changed from refactor/converge-api-v1 to main November 16, 2026 12:02
@wbxl2000
wbxl2000 force-pushed the refactor/kap-session-and-events branch from 199cb75 to d094752 Compare November 16, 2026 12:08
@wbxl2000

Copy link
Copy Markdown
Collaborator Author

@codex review
已 resolve 的主题代表我们的判断取舍与当前代码现状,请勿重复提出(其余约定同首轮:只审本 PR 相对 base 的 diff;base 存量问题单列为 note 不作阻塞意见;同类问题一次列全;纯风格意见不发,每条标注 P0/P1/P2)。

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

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

…rializing main agent on profile metadata updates
@wbxl2000

Copy link
Copy Markdown
Collaborator Author

@codex review
已 resolve 的主题代表我们的判断取舍与当前代码现状,请勿重复提出(其余约定同首轮:只审本 PR 相对 base 的 diff;base 存量问题单列为 note 不作阻塞意见;同类问题一次列全;纯风格意见不发,每条标注 P0/P1/P2)。

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

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

@wbxl2000

Copy link
Copy Markdown
Collaborator Author

@codex review
已 resolve 的主题代表我们的判断取舍与当前代码现状(含本栈 #4966 独立承载 KAP v1 文档更新的分工),请勿重复提出(其余约定同首轮:只审本 PR 相对 base 的 diff;base 存量问题单列为 note 不作阻塞意见;同类问题一次列全;纯风格意见不发,每条标注 P0/P1/P2)。

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 6db18fab7d

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

@wbxl2000
wbxl2000 merged commit 2f33641 into main Nov 17, 2026
39 of 41 checks passed
@wbxl2000
wbxl2000 deleted the refactor/kap-session-and-events branch November 17, 2026 03:51
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