Repository navigation
Conversation
🦋 Changeset detectedLatest commit: bc56926 The changes in this PR will be included in the next version bump. This PR includes changesets to release 4 packages
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 |
# Conflicts: # packages/kap-server/test/apiSurface.test.ts
|
@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: 90a6316924
ℹ️ 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".
| export async function probeRunningDaemon(homeDir: string): Promise<RunningDaemonInfo | undefined> { | ||
| const socketPath = daemonSocketPath(homeDir); | ||
| const metaRes = await daemonHttpRequest<MetaWire>(socketPath, 'GET', '/api/v1/meta', undefined, 2_000); | ||
| if (metaRes === undefined || metaRes.status !== 200 || metaRes.envelope.code !== 0) { |
There was a problem hiding this comment.
Fall back to JSONL when probing old daemons
When upgrading while the previous release's SSH daemon is still serving active work, this raw-HTTP probe cannot detect it because that daemon's Unix socket accepts only JSONL RPC. ensureSharedDaemon therefore starts a second server, whose startup unlinks and rebinds the same socket while the old process continues serving existing SSH streams; both processes can then operate on the same home and session data concurrently. Probe through the legacy JSONL protocol before concluding that the daemon is absent.
AGENTS.md reference: AGENTS.md:L112-L116
Useful? React with 👍 / 👎.
| const STOP_GRACE_MS = 5_000; | ||
| const KILL_GRACE_MS = 2_000; | ||
|
|
||
| const MANAGED_DAEMON_ENV_KEYS = [ |
There was a problem hiding this comment.
Track every daemon-affecting environment override
This allowlist omits documented invocation-level settings such as KIMI_MODEL_API_KEY, KIMI_MODEL_BASE_URL, KIMI_CODE_DANGEROUS_COMMAND_GUARD, and KIMI_WEB_SEARCH_API_KEY. After the first daemon starts, changing one of these variables and running kimi web again produces no mismatch error and silently continues with the original value, whereas the former foreground process inherited each invocation's environment. The daemon hash must cover all bootstrap-consumed environment overrides rather than this subset.
AGENTS.md reference: AGENTS.md:L207-L209
Useful? React with 👍 / 👎.
| const dataDir = getDataDir(); | ||
| let daemonResult: Awaited<ReturnType<typeof ensureSharedDaemon>>; | ||
| try { | ||
| daemonResult = await ensureSharedDaemon({ homeDir: dataDir }); |
There was a problem hiding this comment.
Validate the daemon environment from TUI handoffs
When a daemon was started under a different environment, /web reuses it without checkEnv: true; /remote-control repeats the same omission at line 96. Consequently even tracked settings such as KIMI_CODE_PASSWORD are silently ignored for TUI users, unlike the equivalent kimi web and kimi rc commands, which reject the mismatch and explain how to restart or use the foreground path.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
| const dir = dirname(socketPath); | ||
| await mkdir(dir, { recursive: true, mode: 0o700 }); | ||
| await chmod(dir, 0o700).catch(() => {}); |
There was a problem hiding this comment.
Avoid chmod on the shared temporary directory
When a long home path makes daemonSocketPath() fall back to ${tmpdir()}/kimi-daemon-*.sock, dir here is the system temporary directory itself. A privileged/root invocation can therefore change /tmp to mode 0700, preventing other users and services from accessing it; on user-owned platform temp directories it also overwrites permissions that this process did not establish. Create a daemon-owned private subdirectory or only chmod directories created under the Kimi home.
Useful? React with 👍 / 👎.
| const daemon = await probeRunningDaemon(options.homeDir); | ||
| const state = await readDaemonState(options.homeDir); | ||
| const pid = daemon?.pid ?? (state !== undefined && pidAlive(state.pid) ? state.pid : undefined); |
There was a problem hiding this comment.
Do not signal an unverified PID from stale state
If the daemon crashes without deleting daemon.json and the OS later reuses its PID, a failed socket probe still accepts that unrelated live PID here. stopSharedDaemon then sends it SIGTERM and potentially SIGKILL, so kimi daemon stop or restart can terminate an unrelated user process. Treat the state as stale when no daemon answers, or record and verify a process-start identity before signaling.
Useful? React with 👍 / 👎.
| const incompatibleFlags = collectExplicitForegroundFlags(opts); | ||
| if (incompatibleFlags.length > 0) { | ||
| throw new Error( | ||
| `Cannot apply ${incompatibleFlags.join(', ')} to the shared background daemon. Re-run with '--no-daemon' to start an independent foreground server with these options.`, | ||
| ); |
There was a problem hiding this comment.
Keep the documented dev server scripts in foreground mode
On macOS/Linux this rejects the explicit --debug-endpoints used by apps/kimi-code/package.json's dev:server, dev:kap-server, and dev:kap-server:multi scripts, so each documented local server command exits with the --no-daemon error before starting. Update those scripts to pass --no-daemon (or exempt the development path) when introducing this guard.
AGENTS.md reference: apps/kimi-code/AGENTS.md:L70-L74
Useful? React with 👍 / 👎.
| '/api/v1/sessions?busy=true&page_size=50', | ||
| undefined, | ||
| 3_000, | ||
| ); | ||
| if (res === undefined || res.status !== 200 || res.envelope.code !== 0) return []; |
There was a problem hiding this comment.
Fail closed when active-session inspection fails
When this request times out or returns a non-success response, it is converted to an empty session list, so kimi daemon stop and restart proceed without --force or confirmation and then signal the daemon even if work is active. Propagate inspection failures instead of treating them as proof that the daemon is idle.
AGENTS.md reference: AGENTS.md:L113-L116
Useful? React with 👍 / 👎.
| const origin = `http://${v2.host}:${String(v2.port)}`; | ||
| await writeDaemonState(homeDir, { |
There was a problem hiding this comment.
Publish the bound address before reporting daemon readiness
When the default TCP port is occupied and the server selects a later port, the Unix-socket listener can answer /meta before this state write completes. During that window probeRunningDaemon substitutes 127.0.0.1:58627, so the spawning kimi web invocation can report or open the unrelated service occupying that port instead of the new daemon. Make readiness contingent on publishing the selected address, or obtain the bound address directly from the probe response.
Useful? React with 👍 / 👎.
| const origin = `http://${v2.host}:${String(v2.port)}`; | ||
| await writeDaemonState(homeDir, { |
There was a problem hiding this comment.
Publish the bound address before reporting daemon readiness
When the default TCP port is occupied and the server selects a later port, the Unix-socket listener can answer /meta before this state write completes. During that window probeRunningDaemon substitutes 127.0.0.1:58627, so the spawning kimi web can print or open an unrelated service on the occupied default port instead of the newly started daemon. Publish the selected address before the socket becomes probeable, or make the probe wait for matching state.
Useful? React with 👍 / 👎.
| await opts.persistPreference?.(false).catch((persistError: unknown) => { | ||
| requestLog(req)?.warn({ err: persistError }, 'remote-control preference clear failed'); | ||
| }); | ||
| const status = await opts.service.disable(); |
There was a problem hiding this comment.
Serialize Remote Control preference updates with toggles
When one client sends disable while another enable request is still waiting for the tunnel to start, this path persists false before entering RemoteControlManager's serialized disable queue. The enable request can then finish and persist true at line 159 before the queued disable turns the tunnel off, leaving the saved preference enabled; the next daemon restart unexpectedly restores remote access despite the successful stop. Persist the final state inside the same serialized operation as the tunnel transition.
Useful? React with 👍 / 👎.
# Conflicts: # docs/en/reference/kimi-command.md # docs/zh/reference/kimi-command.md # packages/kap-server/test/apiSurface.test.ts # tests/e2e/AGENTS.md
# Conflicts: # tests/e2e/AGENTS.md # tests/e2e/surfaces/web.ts
# Conflicts: # packages/kap-server/test/apiSurface.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: 70bbf46e7a
ℹ️ 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".
|
|
||
| let rc: Awaited<ReturnType<typeof enableDaemonRemoteControl>>; | ||
| try { | ||
| rc = await enableDaemonRemoteControl(daemonResult.daemon.socketPath); |
There was a problem hiding this comment.
Resolve the token before enabling Remote Control
When server.token is missing or unreadable while the daemon is already running, this call successfully enables Remote Control and persists the enabled preference before the later token check reports an error and returns. The user remains in the TUI believing the handoff failed, but the tunnel stays active and can be restored after a daemon restart; validate the token before enabling the tunnel or disable it on this failure path.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
| exiting = true; | ||
| await removeDaemonStateForPid(homeDir, process.pid).catch(() => {}); | ||
| await shutdownTelemetry({ timeoutMs: CLI_SHUTDOWN_TIMEOUT_MS }).catch(() => {}); | ||
| process.exit(0); |
There was a problem hiding this comment.
Do not force a successful exit after cleanup failures
When any daemon shutdown cleanup rejects—for example while closing the server or draining session metadata—finalizeExit still terminates the process with status 0. In the core-drain path, onDidClose is invoked from a finally block and calls this function before the rejection can even propagate; kimi daemon stop consequently observes a dead process and reports success although cleanup may have been skipped and state may not have been flushed. Preserve the cleanup failure through daemon termination and surface it to the management command instead of unconditionally forcing a successful exit.
AGENTS.md reference: AGENTS.md:L211-L213
Useful? React with 👍 / 👎.
Screenshots / Recordings
kimi web、kimi rc与新增的kimi daemon在 macOS / Linux 上的终端输出对比(默认拉起或复用后台共享 daemon 并立即返回终端提示符):新增
kimi daemon status输出:Requirement or Bug
在同一台机器上同时使用
kimi web、kimi rc(Remote Control)和桌面端 SSH 远程连接时,此前每次命令都会独立拉起一个新的kap-server进程:Web 端口递增分裂、Remote Control 发生单实例锁冲突,会话和运行状态也无法在多端之间实时共享;同时桌面端通过 SSH 连接远程主机时,缺少独立的 KAP 协议版本双向校验。本 PR 在 macOS 和 Linux 上引入共享的常驻后台
kap-serverdaemon(同时监听 loopback TCP 与daemon.sock,统一托管会话与 Remote Control 偏好),提供kimi daemon status|stop|restart与kimi rc stop管理命令及--no-daemon前台逃生口,并在/api/v1/meta与 SSHensure-daemon握手中暴露独立的kap_version实现两端版本双向兼容拦截。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
核心思路
把原先散落在
kimi web(前台常驻 TCP)、kimi rc(前台常驻 TCP + 独立隧道)和kimi server ensure-daemon(仅监听 UDS 且 10 分钟空闲退出)的三套独立进程模型,收敛为单个常驻后台kap-serverdaemon:同一个进程同时监听本机 loopback TCP(强制 Bearer token 鉴权)与0700目录下的daemon.sock(免鉴权,按首非空白字节自动分流 JSONL RPC 与 HTTP/WS)。所有客户端入口都不拥有 daemon 生命周期,命令打印地址或二维码后立即返回;TUI 本体与桌面端本地会话保持现有进程内路径不变,Windows 本期保持独立前台运行;同时通过独立的kap_version在连接建立阶段拦截远端过旧或本机客户端过旧的不兼容组合。概念
kimi daemonkap-server同时监听127.0.0.1:<port>与daemon.sock,常驻不按空闲自动退出,由kimi daemon stop|restart管理daemon.sock首字节嗅探0700目录下免鉴权;连接首非空白字节为{时走JsonlRpcStream,否则作为受信 Unix HTTP/WS 连接交给 Fastifyhttp.Serverdaemon-settings.json)remote_control_enabled: true,启动时自动恢复;kimi rc stop、Web 关闭 RC、OAuth 登出或网页端主动下线设备时清除kap_versionGET /api/v1/meta与ensure-daemon握手中返回实际运行 daemon 的kap_version;远端偏低报executor_outdated(或升级后旧 daemon 忙时报remote_busy),远端偏高报client_outdated结构图
flowchart TB Browser["浏览器 (本机)"] -->|"HTTP / WS + Bearer Token"| TCP Phone["手机 / 远程浏览器"] -->|"Relay 隧道"| RC DesktopSSH["桌面端 (SSH)"] -->|"SSH stdio (JSONL)"| UDS CLI["CLI: kimi web / rc / daemon"] -->|"UDS HTTP 控制请求"| UDS subgraph Daemon["kimi daemon (kap-server)"] TCP["Loopback TCP Listener (127.0.0.1:58627+)"] RC["RemoteControlManager (偏好持久化于 daemon-settings.json)"] UDS["daemon.sock (0700 目录免鉴权 · JSONL + HTTP 首字节嗅探)"] Engine["共享引擎 Scope: 会话 / 回合 / 审批 / 配置 / MCP / 日志"] RC --> TCP TCP --> Engine UDS --> Engine end因为 TCP 暴露在本机回环网络栈上而
daemon.sock受限于0700用户目录权限,所以鉴权钩子通过进程内WeakSet仅放行来自daemon.sock的连接与 RPC 注入请求,保证 loopback TCP 上的所有 REST 与 WebSocket 请求依然严格校验server.token。关键决策
daemon.sockkimi web/rc在前台起轻量网关转发到 UDSCtrl+C与后台会话生命周期语义割裂;直接双监听结构最简单且多端状态天然一致--no-daemon时直接报错退出,提示kimi daemon restart或--no-daemon--host已生效,静默回退又会重新制造端口分裂stderr提示(SSH 侧仅在旧 daemon 的kap_version不兼容时报remote_busy)kap_version一致,SSH 与本地 CLI 都能无感继续工作kap_version,不匹配时明确区分提示升级远端 CLI 或更新本机应用阅读指南
packages/kap-server/src/transport/stdioRpc.ts与packages/kap-server/src/start.ts:看双监听如何同时挂载 TCP 与daemon.sock、如何做 JSONL/HTTP 首字节嗅探并隔离 Unix 免鉴权与 TCP Bearer 鉴权,以及 RC 偏好恢复。packages/kap-server/src/services/daemonSettings.ts、routes/remoteControl.ts、routes/oauth.ts:看remote_control_enabled何时写入、恢复与清除。packages/kap-server/src/services/hosts/sshKapBridge.ts与apps/kimi-code/src/cli/sub/web/ensure-daemon.ts:看kap_version如何从实际运行的 daemon 透传到握手标记,并在两端不匹配时区分executor_outdated、remote_busy与client_outdated。apps/kimi-code/src/cli/sub/web/daemon-client.ts、cli/sub/daemon.ts、cli/sub/web/run.ts:看daemon.lock串行拉起、daemon.json状态与受管理环境变量摘要比对、kimi web/kimi rc [stop]/kimi daemon status|stop|restart的完整控制流。apps/kimi-code/src/tui/commands/web.ts:看 TUI 内/web与/remote-control如何改为复用共享 daemon 并打开已持久化会话。packages/app-*、packages/kap-server/schema/*与docs/{zh,en}/*为client_outdated文案映射、OpenAPI 契约刷新与中英文用户文档同步,可快速略读。具体变化大纲
SshKapBridge.checkBootstrapOutput(marker) protocol < HOST_PROTOCOL_VERSION -> throw HostConnectError('executor_outdated') + protocol > HOST_PROTOCOL_VERSION -> throw HostConnectError('client_outdated') remoteKap = marker.kap_version ?? marker.api_level - remoteKap < HOST_API_LEVEL -> throw HostConnectError('executor_outdated') + remoteKap < KAP_VERSION: + marker.cli_version !== marker.version -> throw HostConnectError('remote_busy') + otherwise -> throw HostConnectError('executor_outdated') + remoteKap > KAP_VERSION -> throw HostConnectError('client_outdated')Behavior Changes and Affected Users
kimi webCtrl+C停止~/.kimi-code/server/daemon.logkimi web在前台阻塞进程(如 systemd/supervisor 脚本或临时单次启动)的 macOS / Linux CLI 用户--no-daemon(或脚本集成使用--json);停止后台服务用kimi daemon stopkimi rc/kimi web --rcCtrl+C下线;若已有 RC 实例则报锁冲突Ctrl+C关闭远程控制隧道的远程控制用户kimi rc stop;需要前台独立进程时传--no-daemon--no-daemon给kimi web传入--host、--port、--log-level、--dangerous-bypass-auth等服务参数--host)或指定端口的 Web 用户--no-daemon(例如kimi web --no-daemon --host)KIMI_*或代理环境变量与运行中 daemon 启动时不一致kimi web/kimi rc检测到摘要不一致时报错退出,不静默沿用旧环境KIMI_CODE_PASSWORD、HTTPS_PROXY、KIMI_CODE_EXPERIMENTAL_*等环境变量后运行kimi web的用户kimi daemon restart应用新环境,或传入--no-daemon/web或/remote-control(macOS / Linux)/web、/remote-control交接会话的用户--no-daemonkimi server ensure-daemon生命周期与升级忙碌行为version_mismatch_busy拒绝连接kap_version,仅在kap_version < KAP_VERSION时报remote_busykimi daemon stop或kimi daemon restartremote > local)checkBootstrapOutput只检查<,放行更高协议版本后可能在后续请求中因未知不兼容报错client_outdated,UI 提示更新本机 Kimi Code 应用(不显示误导性的远端kimi upgrade命令)GET /api/v1/meta响应结构kimi_agent_protocol_version、server_version等字段kap_version(当前为1)旧路径能力对照(前台独立服务 -> 共享 daemon +
--no-daemon)--port/--host/--allowed-host/--insecure-no-tls/--allow-remote-shutdown/--dangerous-bypass-auth/--log-level/--debug-endpoints/--web-title:全部保留在--no-daemon前台模式中;未加--no-daemon时显式拦截并提示。--json(供外部 Agent 子进程拉起一次性服务):保持原有独立前台内存 token 行为不变。isSharedDaemonSupported()在win32返回false,kimi web、kimi rc与 TUI/web、/rc原样走独立前台路径。SSH_AUTH_SOCK转发:在共享 daemon 每次拉起与ensure-daemon连接时原子更新~/.kimi-code/server/forwarded-ssh-agent.sock符号链接,保持不变。server.token与kimi web rotate-token:共享 daemon 继续读取同一server.token并注册到server/instances/,轮换 token 无需重启。受影响模块与验证结论
packages/kap-server、packages/remote-control、apps/kimi-code(CLIweb/rc/daemon与 TUI/web、/rc)、packages/app-core、packages/app-components、packages/app-i18n、docs/{zh,en}。detached子进程)与信号停止逻辑,已在 macOS(Darwin)上通过真实startServer双监听套接字(TCP +daemon.sockJSONL/HTTP 嗅探)及 CLI/TUI 单元与集成测试验证;Windows 分支通过platform: 'win32'/isSharedDaemonSupported() === false单测验证保持前台回退逻辑,未在真实 Windows 机器上实机运行。验证命令与测试覆盖明细
pnpm lint:0 退出(通过cli-dependencies、check-comments、oxlint --type-aware --deny-warnings、check-import-boundaries、guards、ratchet、test-doubles、legacy-e2e、quarantine、instructions、e2e-boundary)。pnpm run check:duplication <base-sha>:检查新增源码无重复克隆。packages/remote-control、packages/kap-server、apps/kimi-code、apps/desktop(主进程tsc与渲染进程vue-tsc)均 0 错误通过。packages/kap-server/test/apiSurface.test.ts:验证/api/v1/meta新增kap_version契约快照与HOST_API_LEVEL摘要。packages/kap-server/test/hosts.test.ts:覆盖kap_version双向拦截(executor_outdated/client_outdated/ 升级忙碌时的remote_busy与兼容复用)、双监听 TCP Bearer 鉴权 +daemon.sock免鉴权 JSONL/HTTP 首字节嗅探、daemon-settings.json原子读写。apps/kimi-code/test/cli/web/web.test.ts&apps/kimi-code/test/cli/options.test.ts:覆盖kimi web/kimi rc默认共享 daemon 返回、显式前台参数拦截、受管理KIMI_*环境变量摘要冲突报错、升级忙碌复用提示、kimi daemon status|stop|restart及--probe。apps/kimi-code/test/tui/commands/web.test.ts:覆盖 TUI/web与/remote-control复用共享 daemon、RC 冲突留守 TUI 报错提示,以及非支持平台回退前台服务。packages/app-components/test/hostsPanel.test.ts:覆盖client_outdated在主机设置测试面板中的本地升级提示且不渲染远端kimi upgrade复制按钮。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.