Compare commits

...

220 commits

Author SHA1 Message Date
Haozhe
9a715820c4
refactor(agent-core-v2): featurize todo/cron/interaction and migrate goal to agent runtime (#3184)
Some checks are pending
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* refactor(agent-core-v2): featurize todo/cron/interaction and migrate goal to agent runtime

* refactor(agent-core-v2): move cron scheduling helpers into features/cron/internal
2026-08-23 23:03:51 +08:00
Liu Zhongnuo
ea0626ad48
fix(agent-core): gate background questions on task controls (#3159)
* fix(agent-core): gate background questions on task controls

* fix(agent-core): recheck background question policy
2026-08-23 20:40:23 +08:00
Haozhe
ffa877cfd8
fix(agent-core-v2): stop refreshing the system prompt on AGENTS.md changes (#3182) 2026-08-23 20:35:55 +08:00
Haozhe
2adc6a1c6e
fix(acp-server): restore local execution fallback, stdio MCP, and session reload (#3183)
* fix(acp-server): restore local process execution fallback

* fix(acp-server): accept stdio MCP servers in ACP sessions

* fix(agent-core-v2): allow runtime re-registration after removal

* chore: add acp regression fixes changeset

* fix(agent-core-v2): prune staged runtime entries when removal teardown fails
2026-08-23 20:31:33 +08:00
Haozhe
368b4b7400
refactor(agent-core-v2): migrate agent domains to agent runtime architecture (#3175) 2026-08-23 17:36:59 +08:00
7Sageer
d723cc47ee
feat(agent-core-v2): add the unified MCP management plane (#3002)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* feat(agent-core-v2): add the unified MCP management plane

Port the v1 MCP management plane (#2858) onto the v2 DI x Scope engine:

- App-scope IMcpOAuthService shared by every workspace handler and
  session overlay: credential events, single-flight refresh, proactive
  refresh timers, OAuthTokenTransaction-serialized writes, offline
  tokenState, shutdown. Providers read tokens through the store so
  grants written or revoked by another process are honored immediately;
  http/sse transports ride the transaction fetch.
- IMcpConfigStore: the single write point for the user-level mcp.json
  over the filesystem byte store, byte-identical to v1's format, with
  per-entry validation, name normalization, __proto__-safe parsing, a
  mutation tail, and an onDidWrite event.
- IMcpRegistryService: the unified read view over the layered config
  files (with per-entry origins) and plugin manifests (full descriptors
  incl. disabled, with provenance); collisions stay visible and runtime
  resolution ranks an enabled plugin above the file layers.
- IMcpManagementService: guarded CRUD, connection-test probes, the
  locator-addressed inspection/auth-status surface, and
  locator-addressed OAuth begin/complete/cancel/reset with ambiguity
  rejection. Engine services stay ungated; the mcp_management flag
  gates the edge exposure.
- Workspace runtime aligns with v1 precedence (an enabled plugin entry
  wins over the file layers, shadows revive), and management writes
  reload immediately via onDidWrite instead of the watch debounce.
- node-sdk v2 facade delegates to the engine service (deleting its
  in-process duplication); kap-server exposes /api/v2/mcp/* and klient
  gains global.mcp.*, both flag-gated.

* fix(agent-core-v2): settle early and cancelled MCP OAuth callbacks

* refactor(node-sdk): write session MCP persists through the engine config store

* refactor(agent-core-v2): strip comments from the MCP management plane files

* fix(agent-core-v2): harden MCP management readiness

* test(node-sdk): cover offline MCP auth statuses

* fix(agent-core-v2): isolate stdio MCP probes

* fix(klient): normalize MCP OAuth errors

* fix(mcp): honor workspace CRUD context and refresh timing

* fix(mcp): drain OAuth refreshes during shutdown

* fix(mcp): guard CRUD across registry collisions

* fix(mcp): canonicalize trust and refresh scheduling

* fix(mcp): close callback listener on setup failure

* fix(mcp): preserve trust and oauth behavior

* fix(oauth): retain refresh tokens after SDK saves

* fix(oauth): stop proactive sweep during shutdown

* fix: await MCP workspace reconciliation

* fix: serialize MCP OAuth and trust cleanup

* fix: reject persisted MCP plugin collisions

* fix: reconcile MCP workspaces concurrently

* fix(mcp): check project-layer trust at the queried cwd

* fix(mcp): expire abandoned OAuth flows after an idle timeout

* fix(mcp): keep mutable user entries writable past read-only collisions

* fix(mcp): abort the auth::complete long poll on client disconnect

* fix(mcp): map OAuth flow failures to wire code 40929

* docs(mcp): note probe credential effects and plane semantics

* chore: add the SDK changeset for MCP management cwd params

* feat(mcp): expose the management plane without the experimental flag

* fix(mcp): preserve auth management semantics

* fix(agent-core-v2): bound MCP OAuth auth-server requests and the shutdown drain

* fix(node-sdk): restate engine MCP management errors as KimiError

* fix(agent-core-v2): preserve shared OAuth flow lifetime

* fix(agent-core-v2): close MCP OAuth cancellation and shutdown gaps

- bound the authorization-code exchange with the request timeout and the
  flow/caller abort signals, and make shutdown abort hung begins and close
  their callback listeners immediately
- keep token-transaction effect coalescing intact when durable tokens carry
  local stamps, and serialize the meta sidecar and tokens-saved event with
  the token write inside the lock
- drain transport-driven grants, their trailing SDK save continuations, and
  interactive completions during shutdown, with a cancellable deadline

* fix(agent-core-v2): harden MCP probe runtime resolution and path handling

- resolve stdio probes against the containing workspace's runtimes and
  reject out-of-workspace probes for non-local runtime_id instead of
  silently falling back to a local-only transient registry
- share one Windows-aware path canonicalization across the config loader,
  registry trust lookup, trust records, and workspace matching
- keep a UTF-8 BOM fatal for the user-level mcp.json store, matching the
  workspace loader and v1
- validate completeServerAuth timeoutMs bounds at the engine boundary

* fix(agent-core-v2): await workspace MCP reconciliation on plugin mutations

Plugin install/enable/disable/remove now resolve only after reload
listeners settle their waitUntil work, so a disabled plugin's MCP server
cannot linger connected and an enabled one is visible to the next
session, matching v1. The workspace MCP consumer joins the barrier while
keeping its log-only failure tolerance; delivery is awaited outside the
mutation queue to avoid self-deadlock through consumption reads.

* fix(mcp): close the SDK, klient, and server edge gaps

- register mcp.oauth_failed in the v1 error registry and restate unknown
  engine codes as internal instead of minting undeclared KimiError codes
- route persisted session MCP adds through the same KimiError restating
  as the global management methods
- give the klient IPC transport a per-call timeout so completeAuth's long
  poll outlives the 30s default, clamped to the Node timer ceiling, and
  align the contract timeoutMs upper bound with REST
- await the MCP OAuth service shutdown directly in SDK and server close
  before scope disposal

* fix(agent-core-v2): keep file-over-plugin MCP precedence and harden the plane

- Revert the v1-style precedence flip: the workspace merge and
  resolveRuntimeTarget keep the file entry above plugins (v2's historical
  order; the divergence from v1 is deliberate and documented in AGENTS.md).
- Guards follow each engine's winner: project-layer entries stay read-only,
  while plugin entries never block user-level writes, so a file entry may
  shadow a plugin and removing it revives the plugin. The parity suite pins
  the engine split for a persisted session add over a plugin-owned name.
- inspectServers tolerates a wire-encoded null targets array: klient's ipc
  transport sends null for an omitted leading optional argument.
- Fire the config store's onDidWrite after the mutation tail settles, so a
  write listener can re-enter the store without deadlocking the queue;
  concurrent-mutation and re-entrant-listener tests pin both contracts.

* chore: condense the sdk MCP changeset to one sentence

* test(node-sdk): pin verify:false auth-status parity and fix the sdk changeset
2026-08-22 18:22:37 +08:00
liruifengv
d4e0ad4b2d
chore: sync web dist from code-app (#3166)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Release (push) Waiting to run
* chore: sync web dist from code-app

code-app: 8c911c08adf094509dea5655becd2896352a72a2

* chore: drop the rc device switcher changeset
2026-08-21 21:03:29 +08:00
liruifengv
491ebd050f
chore: sync web dist from code-app (#3157)
code-app: 9c669bd16983e6b734ca5e4102f91ebc9f34935a
2026-08-21 15:30:17 +08:00
Haozhe
cd2d91020a
docs: document detailed parameters for all server API endpoints (#3155)
* docs: document detailed parameters for all server API endpoints

* docs: correct model alias id and skill attachment shapes in server api reference
2026-08-21 15:05:38 +08:00
Grapedge
54bb49e138
fix(kimi-code): keep the previous turn's answer visible when a cron turn ends (#3154) 2026-08-21 15:01:07 +08:00
wenhua020201-arch
e0936bfc3e
docs(plugins): rework Kimi Datasource section with authoritative source names (#3153)
- Name authoritative data sources in the intro (World Bank, IMF, OECD, FRED,
  WHO, FAO, NBS, Wind, S&P Capital IQ, SEC EDGAR, Caixin, Xinhua Finance,
  Gildata) so users can see what backs the plugin
- Turn the eight 'what you can do' scenarios into collapsible details blocks
  with question-style headers (title — question?) so the page stays scannable
- Coverage table: add a financial-news/industry-data row (Caixin, Xinhua
  Finance); name Yuandian Legal for the legal row; macroeconomics row now
  also covers China government data and IGO official statistics
- Only sources approved for both domestic and overseas publicity are named;
  restricted sources are described by capability instead
2026-08-21 14:59:49 +08:00
qer
0f44537c13
feat(agent-core-v2): turn /tower into a mode parallel to plan mode (#3099)
* feat(agent-core-v2): turn /tower into a mode parallel to plan mode

* feat(agent-core-v2): align /tower command semantics with the original skill behavior

* fix(tui): harden the /tower command against mid-turn objectives, legacy engines, and stale status

* fix(agent-core-v2): keep restored tower state inert while the feature flag is off

* fix(agent-core-v2): include TowerInit in the mode tool overlay and report flag-gated tower state

* feat(agent-core-v2): expose tower control tools statically and make the mode injection history-derived

* fix(tui): warn that tower mode needs a restart after a live flag flip; drop redundant undefined from SessionStatus mode fields

* fix(agent-core-v2): let tower mode exit clear persisted state while the flag is off

* fix(agent-core-v2): emit the tower exit reminder through a disabled flag and drop the redundant REST state comparison

* fix(tui): show the Tower mode status row only when the experiment is available

* fix(agent-core-v2): confine tower mode to the main agent and always re-assert it for objectives

* feat(kap-server): project tower mode into transcript modes and reassert explicit toggles

* fix(agent-core-v2): fold the main-agent invariant into the effective tower state

* fix(kap-server): gate the cold tower mode badge behind the experiment flag

* fix(agent-core-v2): reapply the tower tool overlay after a profile bind; fix(kap-server): clear cold tower badges on non-main agents

* fix(protocol): mirror towerMode and tower_mode in the shared zod schemas

* test(agent-core-v2): adapt tower tests to the agent lifecycle context architecture

* chore(agent-core-v2): regenerate the wire manifest; test(node-sdk): look up the main agent via findAgentHandle

* fix(agent-core-v2): exit a replayed tower mode when the workspace belongs to another session

* fix(agent-core-v2): carry tower ownership in the enter record so forks clear inherited mode

* fix(agent-core-v2): apply the tower overlay before dispatching enter and repair it on status updates

* fix(agent-core-v2): validate store ownership before entering tower mode

* fix(agent-core-v2): claim the repository tower owner at enter; fix(tui): confirm mode activation before reporting success

* fix(agent-core-v2): make the first tower claim exclusive and refuse adoption over a live owner

* feat(agent-core-v2): guard tower adoption and teardown with a cross-process ownership lease

* revert(agent-core-v2): drop the cross-process lease and enter-time claim, keep ownership checks process-local

* fix(agent-core): hide the v2-only tower flag from the legacy experiments list

* fix(agent-core-v2): keep tower mode inert until the tower feature is assembled

A live /experiments flip refreshes the flag but cannot re-run App-scope
feature assembly, so the tower tools/profile stay unregistered until a
restart. Gate enter()/isActive on the assembly fact and say so in the
TUI error. Also resolve the AGENTS.md conflict block committed by the
merge, and widen the TUI experimentalFlag type to string now that flags
live in two registries.

* fix(kap-server): gate the cold tower badge on tower feature assembly

Same live-flip gap as the mode machinery: a persisted tower_mode.enter
plus a flag enabled without a restart would still show the badge while
the feature is inert. Require isTowerFeatureAssembled() alongside the
flag, re-exported from agent-core-v2.

* fix(agent-core-v2): liveness-aware tower entry and per-App assembly state

enter() now mirrors TowerInit's adoption rule: a stored owner blocks
entry only while that session is live in this process, so a new session
can enter the mode and reach TowerInit to adopt a stale tower. The
assembly marker is keyed by each App's flag service (WeakSet) instead of
process-global module state, so coexisting Apps no longer leak assembly
into one another.

* fix(agent-core-v2): keep stale-owner adoption across resume; reject tower updates that do not take

exitForeignTower now treats a stored owner as foreign only while that
session is live, so a mode entered by adopting a dead owner's tower
survives close/restart. The TUI validates the model prerequisite before
enabling tower for an objective, and the REST agent_config path throws
session.tower_mode_invalid when enter() did not take effect instead of
acknowledging a no-op.

* fix(agent-core-v2): clear the tower assembly marker when the feature unloads

Register the WeakSet cleanup via the feature's onDispose so the
capability follows the managed unit's lifecycle — after
unprovideUnit('tower'), isActive/enter() no longer treat the retracted
tool set as assembled.

* fix(agent-core-v2): publish tower deactivation on gate loss; reject refused setTowerMode in the SDK

isActive now reconciles its projection: restore and feature-manager unit
changes publish AgentStatusUpdated({ towerMode: false }) when the
persisted mode lost a gate (flag off at runtime, feature unloaded), so
live transcript badges and TUI state stop showing an inert mode. The
SDK's setTowerMode(true) verifies the effective state and throws
session.tower_mode_invalid, matching the REST path.

* fix(agent-core-v2): reconcile tower projection on config changes and cold ownership moves

The last unreconciled gate inputs: a live setConfig writing the
experimental section (no session reload, no units event) now republishes
towerMode:false through the config-change subscription, and the cold
transcript badge mirrors the same ownership/liveness rule as enter() —
retained while the store owner is this session or no live session, cleared
once a live session elsewhere owns the tower.

* fix(agent-core-v2): reconcile the tower projection in both directions

The OFF-only reconcile left a hole: re-enabling the flag in the same
process made isActive true again with no towerMode:true publish, and
enter() could not heal it (it early-returns when already effective).
The projection now tracks the last published state and emits both
false→true and true→false transitions from the same restore/units/config
triggers; direct publishes (enter/exit/restoreTowerTools) keep the
tracker in sync.

* fix(agent-core-v2): validate forked tower ownership even while the flag is off

exitForeignTower's flag short-circuit let a fork restored while the
experiment was disabled keep its inherited enter record; re-enabling the
flag later revived both source and fork over the same store. Ownership
validation is flag-independent state hygiene, so restore now runs it
regardless of the effective flag — a live foreign owner clears the
fork's persisted mode before any gate can rise again.

* fix(agent-core-v2): veto tower tools while the tower experiment is off

With the feature assembled and the tool overlay active, disabling the
flag live left TowerInit/TowerTeardown callable — they have no flag
check — so prompts could still mutate or dismantle .tower/ while the
experiment reported disabled. A dedicated onBeforeExecuteTool hook now
denies every tower tool whenever the flag is off, mirroring the TodoList
veto.

* fix(agent-core-v2): keep tower worker write isolation when the flag turns off

The worker Write/Edit guard is identity-scoped (tower-worker profile),
not feature-activity-scoped: disabling the experiment live must not let
already-spawned detached workers write into the main checkout or other
worktrees. The guard no longer checks the flag; the tower-tool veto
added earlier covers protocol access instead.

* test(agent-core-v2): make tower tests hermetic for CI

Three CI-only failures: towerService git fixtures committed without a
repo-local identity (CI has no global gitconfig), the node-sdk tower
positive tests relied on the developer shell's
KIMI_CODE_EXPERIMENTAL_FLAG=1 master switch instead of enabling the
tower flag explicitly, and the legacy harness experimental-features
expectation still listed the tower entry removed from the v1 registry.
2026-08-21 14:47:37 +08:00
liruifengv
3090c1c482
chore: sync web dist from code-app (#3152)
Some checks are pending
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
code-app: a46821efc62fda06230f5100560aa7dda6058f14
2026-08-21 11:31:35 +08:00
wszqkzqk
30e7f62d2c
fix(kaos): resolve Git Bash POSIX paths for file tools on Windows (#2200)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Add a shell path bridge that translates between win32 paths and the
MSYS2/Git Bash path dialect. File tools resolve model-supplied paths
through it before canonicalization and workspace checks: drive-letter
forms translate lexically, root-relative paths resolve via cygpath -w
with per-segment caching, and every failure mode falls back to the
previous behavior.

Fixes #2199
2026-08-20 22:42:16 +08:00
Haozhe
381142aff1
fix(agent-core-v2): let session archive proceed after a failed resume (#3139)
A failed resume is cached by SessionManager and rethrown from
whenResumeSettled, so archiving a session whose workspace is gone
failed with the stale resume error even though cold archive only
rewrites session metadata. Swallow the settle failure: still wait for
an in-flight resume before the live/cold classification, but fall
through to the cold metadata path after a failed one.
2026-08-20 22:40:27 +08:00
qer
e9a99e5ec6
feat: add Tencent CloudBase plugin to the curated marketplace (#3136)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
2026-08-20 22:15:09 +08:00
7Sageer
f6736d7c0d
feat(agent-core-v2): add a fork parameter to the Agent tool (#3007)
* feat(agent-core-v2): add a fork parameter to the Agent tool

Spawning with fork: true starts the subagent from a one-time snapshot of
the calling agent's completed conversation history — same profile, tool
set, and model — instead of zero context. The seed trims the trailing
open tool exchange (the in-flight Agent call itself) before appending
into the child's context memory, and the first prompt carries an
inheritance notice framing the seeded history as reference material.

Fork rejects resume, a different subagent_type, or a model override as
tool errors, and skips the subagents allowlist since a self-inheritance
is not a delegation.

* fix(agent-core-v2): bind the stale-todo reminder only into the main agent

Subagents share the session todo list but no longer receive the
stale-todo nudge — the reminder injector now registers only on the main
agent, so delegated and forked agents are not prompted to maintain a
list they do not own.

* fix(agent-core-v2): inherit the caller's live binding and label fork launches correctly

Review follow-ups for the Agent tool fork mode:

- overlay the caller's live profile.data() via applyBindingSnapshot after
  the catalog re-bind, so ephemeral addActiveTool deltas, the rendered
  system prompt, and runtime model/subagents updates survive the fork;
  skip the profile prompt prefix since the caller's prefixed first
  prompt is already part of the seeded history
- resolve the fork activity label and approval-rule subject from the
  caller's own profile instead of falling back to the default subagent
  type, so an Agent(<other profile>) rule cannot approve a fork

* fix(agent-core-v2): close inherited in-flight tool calls instead of trimming them

Fork seeding now answers the source's trailing open tool calls with a
synthetic in-flight result instead of cutting the whole trailing
exchange: the seeded history stays protocol-valid, keeps the source's
final step visible as reference, and no longer confuses side-question
(btw) agents forked while the main agent is mid-turn. The close helper
is shared by the Agent tool fork and IAgentLifecycleService.fork.

Fork launches also stop requiring the caller's profile to still exist
in the session catalog: the child is created unbound and overlaid with
the caller's live binding snapshot, matching the lifecycle fork path,
and now records forkedFrom provenance.

* refactor(agent-core-v2): route Agent tool forks through agentLifecycle.fork

* feat(agent-core-v2): add a fork parameter to the AgentSwarm tool

* fix(agent-core-v2): seal partial assistant forks

* fix(agent-core-v2): align fork parameter descriptions

* fix(agent-core-v2): drop the main-only registration gate from goal tools

* fix(agent-core-v2): disclose dates via reminders to keep the system prompt byte-stable

* docs: condense the fork changesets to single sentences

* docs(agent-core-v2): frame the tool-contribution when gate as a fork parity trade-off

* test(agent-core-v2): plug fork coverage gaps and decouple swarm tests from spawn internals

* docs(agent-core-v2): keep the when-gate guidance in the contribution JSDoc only

* fix(agent-core-v2): contribute cron tools to every agent for fork prefix-cache parity

CronCreate/CronList/CronDelete were registered directly into the main
agent's tool registry by SessionCronServiceImpl, bypassing the
AgentToolContribution seam and keying on per-agent identity — so a forked
agent rebuilt a tool surface three tools shorter than its caller and the
inherited prompt prefix missed the cache.

Register the three tools through registerAgentToolService like the goal
tools do (no when gate, identical surface for every agent) and enforce
the main-agent restriction at execution time instead. Also fall back to
DEFAULT_CRON_CONFIG when the config section is absent, since the service
can now be constructed after the main agent exists.

* feat(agent-core-v2): track the fork parameter in the subagent_created event

* fix(agent-core-v2): gate tower orchestration tools at execution time

TowerInit/TowerPlan/TowerSpawn/TowerMerge/TowerTeardown were contributed
with a when predicate keyed on agentId === 'main', so a forked agent
rebuilt a tool surface missing TowerInit (always present for the default
profile) plus the rest of the tower set once it was enabled — breaking
prompt prefix-cache parity with the caller.

Contribute the tools with no when gate (profile policy still controls
visibility) and reject non-main callers at execution time instead.

* test(agent-core-v2): expect the fork field in the subagent_created mirror assertion

* test(agent-core-v2): cover fork subagent first-request prefix parity

* refactor(agent-core-v2): share the main-agent-only tool refusal across cron and goal tools

Goal tools rejected subagent callers by throwing GOAL_UNSUPPORTED_AGENT
from the service, which the executor wrapped as a resolution failure;
cron tools returned a clean refusal but each tool open-coded the same
identity check. Centralize the check and both messages in
agent/tools/mainAgentOnly.ts and use it from all seven tools, keeping
AgentGoalService.assertSupportedAgent as the coded boundary for RPC and
SDK callers.

* refactor(agent-core-v2): keep the goal main-agent gate at the tool layer only

* fix(agent-core-v2): preserve the fork tool surface when inheriting user tools

* Revert "refactor(agent-core-v2): keep the goal main-agent gate at the tool layer only"

This reverts commit fc09a8fa32.

* test(agent-core-v2): complete fork lifecycle stub

* Delete .changeset/btw-inflight-tool-calls.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* Delete .changeset/todo-reminder-main-only.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* Delete .changeset/swarm-fork-context.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* Add optional 'fork' parameter to subagent tools

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* docs(agent-core-v2): drop the fork JSDoc comments

* feat(agent-core-v2): add prompt_cache_probe telemetry for forked agents

* feat(agent-core-v2): gate the subagent fork parameter behind an experimental flag

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-08-20 21:50:44 +08:00
liruifengv
8ca1a3fd91
docs(changelog): sync 0.38.0 from apps/kimi-code/CHANGELOG.md (#3137) 2026-08-20 21:40:27 +08:00
github-actions[bot]
0999454bdc
ci: release packages (#3074)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-20 21:11:45 +08:00
liruifengv
2c5415f930
chore: sync web dist from code-app (#3135)
code-app: 6c99acc282b048208e457572309c808f6aeb00d5
2026-08-20 21:09:01 +08:00
Haozhe
3b69765cf3
fix(agent-core-v2): remove duplicate launch-time subagent.spawned (#3134) 2026-08-20 20:55:33 +08:00
Haozhe
fc0f275dd4
refactor(agent-core-v2): extract goal domain into a self-contained feature (#3130) 2026-08-20 19:52:57 +08:00
7Sageer
3899079a2c
fix(agent-core-v2): guard config persistence against lossy writes (#3121)
* fix(agent-core-v2): guard config persistence against lossy writes

- A failed load no longer clears the in-memory snapshot: the service keeps
  the last-known-good config, reports an error diagnostic, and taints.
  set/replace/replaceSections on the persisted layer then fail fast with
  Error2(config.persist_blocked) instead of erasing the file; memory-layer
  overrides stay available, and a successful reload clears the taint.
- persistDomains is now read-modify-write: the file is re-read and only the
  domains being written are applied on top of current disk content, so
  external edits are merged instead of clobbered, and an external delete is
  honored instead of resurrected.
- External changes absorbed at persist time trigger a full reload so change
  events fire for domains the writer did not touch.

* fix(agent-core-v2): rebase set() merges onto re-read config state

set(domain, patch) now merges the patch against the freshly re-read file
content and refreshes the in-memory snapshot from the same read, so external
edits to the same section survive a concurrent write instead of being
overwritten by the stale in-memory copy.

* fix(protocol): register config.persist_blocked in KimiErrorCode

Add the new code to the KimiErrorCode union and kimiErrorCodeSchema so the
persist-refusal error payload passes protocol validation across RPC
boundaries.

* fix(agent-core-v2): compute every config write against the re-read file

Move strip/merge/validate for set/replace/replaceSections into the persist
rebase callback so each write is derived from the file content re-read at
persist time. Overlay strip handlers (e.g. the KIMI_MODEL_* mask restoring
default_model) now read the fresh snapshot instead of the stale in-memory
one, and the unconditional snapshot sync makes the separate
absorbed-external reload redundant.

* fix(agent-core-v2): build defaults when the initial config load fails

A failed first load has no last-known-good state worth preserving, so fall
through with an empty document: registered section defaults are still
validated and applied (consumers of defaulted sections keep working), while
the taint keeps blocking persisted writes until a reload succeeds. Only
reload failures preserve the previous in-memory state.

* fix(agent-core-v2): stage re-read config snapshots until the write succeeds

Build the rebased raw/rawSnake snapshots in locals and publish them only
after the rebase and documentStore.set both succeed, so a validation error
or a storage failure cannot leave userValue and effective pointing at
different snapshots. stripEnv now takes the staged snapshots explicitly.
2026-08-20 18:04:59 +08:00
7Sageer
38c55501ad
docs: restructure the secondary_model config section for scannability (#3123)
Split the dense prose walls into a minimal config, a one-line-per-field
table, constraint bullets, a numbered resolution order, and a separate
advanced subsection for per-entry thinking efforts. All behavioral facts
are preserved; zh and en stay mirrored.
2026-08-20 17:25:13 +08:00
Haozhe
3fdce983f8
fix: drain in-flight persistence and log writes on session close and shutdown (#3122) 2026-08-20 17:19:20 +08:00
liruifengv
97c2159791
feat(kimi-code): load startup banner from client_configs (#3117)
The startup banner now comes from the backend client_configs endpoint
(config name client_banner) instead of the CDN-hosted tips.json, and is
fetched fresh on every startup with no caching. The payload keeps the
tips.json shape, plus two targeting additions:

- banner_platform (top level and fallback entries) limits display to
  the given platform; missing, empty, or all means every platform, and
  the CLI only shows entries targeting all or cli.
- banner_start_time/banner_end_time on fallback entries add scheduled
  visibility windows with the same semantics as the active banner.
2026-08-20 16:54:55 +08:00
Haozhe
a09d904140
refactor(agent-core-v2): migrate agent domains to model-as-container architecture (#3103) 2026-08-20 16:06:59 +08:00
Grapedge
cfc3350483
feat(kimi-code): collapse long ! shell command output (#3054)
Finished `!` output collapses to the first 10 visual rows with a `... (N more lines, ctrl+o to expand)` marker, sharing the global ctrl+o toggle with agent tool output; ctrl+o also expands the live buffer while the command runs. Replayed output mounts the same card and behaves identically. The shared truncation component, the running card's default view, and the agent bash path are unchanged.
2026-08-20 14:55:38 +08:00
qer
a34d02a64f
chore(datasource): add changeset for the 13 new sources (#3119) 2026-08-20 14:40:52 +08:00
qer
03dcfcf6d0
feat(datasource): add NDA/NBS, standards, IGO, xhcj, and caixin sources (#3115)
* feat(datasource): add NDA/NBS, standards, IGO, xhcj, and caixin sources

* fix(datasource): narrow real-time-news ban to coverage gaps, require PublishTime citation

* fix(datasource): scope the real-time-news limitation to coverage gaps only

* fix(datasource): trim redundant clause in the real-time-news limitation

* fix(datasource): stop on a result that covers the question, not the first success

* fix(datasource): front-load trigger terms in the skill listing description

* fix(datasource): exempt discovery calls from the one-call workflow
2026-08-20 14:16:15 +08:00
Haozhe
15da84606a
feat(kap-server): add workspace-grouped sessions view and lifecycle events (#3114)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Nix Build / Check flake.nix workspace sync (push) Waiting to run
GET /api/v2/sessions gains view=by_workspace: one request returns every
workspace with a matching session, each carrying its first group.page_size
sessions under the requested sort plus the workspace's full matching total,
with group-level page_token pagination (40922 on condition drift). Groups
key on the alias-canonical workspace id, so legacy split buckets of one
physical directory merge into a single group, matching the v1 alias
semantics. meta.has_prompt filters sessions by prompt presence (the v1
exclude_empty equivalent) in both views. The flat view and v1 routes stay
byte-compatible.

The global WS stream now fans out event.session.archived (live and cold
paths; payload carries the session id and workspace_id) and
event.workspace.created/updated/deleted, published by the core
IWorkspaceService on every mutation path including the implicit
createOrTouch on session creation.

kimi-inspect consumes the grouped projection as a single-column
workspace/session tree in the chat view; the session pane merges into the
right dock as the Session tab. The server API reference (en + zh) documents
the new parameters, the grouped response, and the new events.
2026-08-20 13:45:38 +08:00
liruifengv
f1208c8d72
feat(agent-core-v2): rework the title generation excerpts (#3109)
* feat(agent-core-v2): rework the title generation excerpts

- Rebalance the excerpt budgets toward the user's prompts (400 chars
  each) and trim the assistant segments (300) so titles follow the
  user's task instead of narrating the assistant's reply.
- Cap each prompt in the default user_prompts excerpt so one long
  paste no longer starves the remaining prompts.
- Compose the digest excerpt from the full conversation arc: every
  natural-language user prompt in the live window paired with its own
  turn's final assistant text, interleaved chronologically, with
  per-segment caps and a 3000-char total budget (middle turns elided).

* chore: scope the title changeset to agent-core-v2

* fix(agent-core-v2): dedupe digest prompts and elide whole turns

- Drop the redundant `| undefined` from the optional
  TitleDigestTurn.assistant per the monorepo optional-property
  convention.
- Deduplicate user messages by id when constructing digest turns, so a
  prompt already in the context and still active in the queue does not
  produce two turns.
- Elide the over-budget digest at whole-turn granularity, keeping each
  assistant line paired with its own user line.

* docs(agent-core-v2): describe the full-arc digest in the SessionTitleSource contract
2026-08-20 12:25:51 +08:00
Kimi Agent
d96b4a0149
fix: fail fast on provider-filtered empty responses (#3101)
* fix: fail fast on provider-filtered empty responses

An APIEmptyResponseError carrying finishReason 'filtered' (OpenAI
content_filter, Anthropic refusal) is deterministic: replaying the same
request re-triggers the provider safety filter. Both isRetryableGenerateError
implementations (kosong, agent-core-v2) treated every empty response as
retryable, so step retry replayed the doomed request the full 10 attempts
before the filter notice surfaced. Return non-retryable for filtered empty
responses in both engines; the error already carries the provider.filtered
code, so the turn fails immediately with the existing filter notice.

* fix: skip the compaction shrink-retry for filtered empty responses

Both full-compaction loops routed every APIEmptyResponseError into the
shrink-and-continue branch before isRetryableGenerateError was consulted,
so a filtered response was retried with shrinking input instead of failing
fast. Exclude finishReason 'filtered' from the shrink branch in both
engines; it now falls through to the retryability check and throws
immediately. Add end-to-end tests (real kosong generate over a filtered
think-only stream) asserting a single attempt with the history untouched.

---------

Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
2026-08-20 11:55:26 +08:00
liruifengv
3d7762003a
feat(kimi-code): support two OAuth login endpoints (#2862)
* feat(kimi-code): add China/International region selection for OAuth login

- Add region profiles (cn/overseas) and resolver in @moonshot-ai/kimi-code-oauth:
  env override → persisted login host → install-channel marker → default cn
- /login now offers Kimi Code (China) / Kimi Code (International); the CLI
  login entries (kimi login, kimi acp --login) accept --region cn|overseas
- Update/plugin/site/telemetry endpoints derive from the selected region;
  plugin trust list covers both .com and .ai hosts
- kap-server: POST /oauth/login accepts an optional region; new GET /oauth/region

* fix(oauth): keep an explicit default-slot login ahead of the install marker

A China login persists no oauthHost (the default credential slot carries
no host trace), so after switching back from International the resolver
fell through to a stale overseas install marker. Treat a persisted
default-slot oauth ref (key === oauth/kimi-code) as an explicit-cn signal
that outranks the marker; getRegion() on the v2 side mirrors it.

* fix(agent-core-v2): thread the default-slot key through capability region resolution

Capability installs resolved the region from the persisted oauthHost only,
so an explicit China login (which persists no host) lost to a stale
overseas install marker. Pass the oauth ref key through as well, matching
getRegion(). Also move the region contract notes into the auth.ts file
header per the package comment convention.

* fix(agent-core-v2): honor the region-marker opt-out for the telemetry endpoint

Hosts that set KIMI_CODE_REGION_MARKER=off (the desktop embedded server)
skip the install marker in getRegion(), but the default telemetry endpoint
still consulted it, so a stale overseas marker could split the reported
region from the telemetry destination.

* feat(cli): show region site domains in login platform selector

* chore: reword oauth login changesets

* fix: honor the region marker opt-out in the CLI and capability resolvers

* refactor: rename login region values to mainland-cn and global

* fix: keep the --region help text in English

* fix: simplify the --region help text to site domains

* feat: drop the suggested login platform order

* feat: split a browser-safe region profile table out of the region resolver

* Revert "feat: split a browser-safe region profile table out of the region resolver"

This reverts commit a037b1143e.

* fix: read the install marker from the bootstrapped home directory

* fix: resolve the server plugin marketplace from the active login region

* feat: expose the login region option through the klient auth facade

* fix: drop a comment from the v2 auth region test

* fix: keep scoped base-only logins on their environment for a bare login

* fix: invalidate the region cache on the provider-manager logout path

* fix: route client-config fetches through the active region profile

* fix: resolve the telemetry endpoint per flush so a login region switch applies in-process

* test: expect the telemetry endpoint resolver in the CLI init assertions

* fix: resolve the default telemetry endpoint from the bootstrapped home

* chore: reword the oauth login changeset around the two login methods

* chore: trim the oauth login changeset to the headline

* feat: let hosts override the region marker env through the server bootstrap env bag
2026-08-20 11:24:02 +08:00
Kimi Agent
05f2ad5dda
chore: rewrite unreleased changesets per the gen-changesets rules (#3108)
* chore: rewrite unreleased changesets per the gen-changesets rules

* chore: drop the WaitFor display entry — covered by the new-tool changeset

* chore: address Codex review — restore user-visible entries, tighten wording

---------

Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
2026-08-20 11:06:10 +08:00
Haozhe
ca87c58e62
fix(agent-core-v2): cap default subagent delegation at one level (#3012)
- give the builtin agent profile an explicit subagents allowlist (coder, explore, plan), restoring v1 semantics
- inherit the default profile's allowlist when a caller profile declares none, instead of leaving delegation unrestricted
- pass a lone "*" subagents field through as an explicit unrestricted marker
2026-08-20 09:53:11 +08:00
Kimi Agent
fa9865f2ee
docs: document KIMI_CODE_CUSTOM_HEADERS on the env vars page (#3097)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* docs: document KIMI_CODE_CUSTOM_HEADERS on the env vars page

* docs: address review on KIMI_CODE_CUSTOM_HEADERS entry

- use a neutral gateway header name in the example
- correct the release version to 0.20.2
- scope the override claim to exact-name matches and warn against
case-variant auth headers

* docs: describe protocol-dependent Authorization precedence

On the OpenAI-compatible protocols (kimi/openai/openai_responses) an
exact Authorization custom header is applied after the SDK-generated
bearer token and therefore replaces it; /models listing keeps its own
authentication.

* docs(zh): add the required space before the config-files link

Per the mixed-content spacing rule in docs/AGENTS.md.

---------

Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
2026-08-19 23:02:36 +08:00
Haozhe
67fbcdf1ba
feat(agent-core-v2): guard Edit and Write against stale or unread files (#3096)
* feat(agent-core-v2): guard Edit and Write against stale or unread files

* feat(agent-core-v2): guard Edit and Write against stale or unread files
2026-08-19 22:55:55 +08:00
Haozhe
4ff06f17e3
fix(kap-server): serve real session usage in snapshot and persist per-turn context readings (#3094)
* fix(kap-server): serve real session usage in snapshot and persist per-turn context readings

* fix(kap-server): omit unknown session usage fields instead of reporting zero
2026-08-19 22:06:53 +08:00
Haozhe
056f02c2de
fix(agent-core-v2): record step.end for failed or interrupted steps in wire log (#3095)
Some checks are pending
CI / build (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
Release / Publish native release assets (push) Blocked by required conditions
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
2026-08-19 21:30:56 +08:00
Haozhe
eac9ea88e8
refactor(agent-core-v2): persist cron tasks as durable wire records (#3093)
* refactor(agent-core-v2): persist cron tasks as durable wire records

- write CronAdd/CronDelete/CronCursor as durable wire records and rebuild the cron task table from dispatcher replay
- migrate legacy per-workspace cron JSON files into the wire on first resume, then drop the file-based persistence service, its registrations, and the bootstrap cron scope
- derive the session cron view from the agent replayable cron state and remove the redundant session-level copy
- let session forks inherit cron tasks through the copied wire instead of duplicating task files

* fix(agent-core-v2): keep legacy cron tasks on cold forks and flush before cleanup

- inherit legacy cron task files into a full fork's wire so cold sessions forked before their first post-upgrade resume do not silently lose scheduled tasks
- flush the migrated wire records before deleting legacy files so a crash cannot lose both copies

* refactor(agent-core-v2): drop the legacy cron file migration

- stop reading legacy per-workspace cron JSON files entirely; pre-upgrade tasks simply stop applying instead of being migrated into the wire
- remove the legacy read path, the fork-time legacy inheritance, and the now-unused session context/document store injections
2026-08-19 21:26:57 +08:00
Haozhe
c843d3a7f9
refactor(kap-server): table-driven dispatch for multi-action routes (#3092)
* refactor(kap-server): table-driven dispatch for multi-action routes

- add a shared action-dispatch helper; sessions, prompts, plugins, questions, and modelCatalog collection routes declare action tables with module-level handlers
- add ISessionManager.status returning the session summary; the archive action checks it instead of resuming the session
- archive cold sessions through the persisted-metadata path shared with batch archive

* fix(agent-core-v2): read-your-writes for session index point gets

Overlay pending mirror summaries in getFromReadModel so a freshly recorded
summary (e.g. cold-session archive) is visible to GET immediately, matching
the existing pending overlays in list and cursor resolution.
2026-08-19 21:19:50 +08:00
Kimi Agent
c8029f9f3b
docs: align contributor entry docs with approved-bug-fix-only policy (#3089)
* docs: align contributor entry docs with approved-bug-fix-only policy

* docs: align contributor entry docs with approved-bug-fix-only policy

* docs: align contributor entry docs with approved-bug-fix-only policy

* docs: align contributor entry docs with approved-bug-fix-only policy

* docs: link Chinese contributing guide

* docs: add Chinese contributing guide

* docs: add Chinese bug report form

* docs: add Chinese feature request form

* docs: bilingual PR template header note

* docs(zh-cn): naturalize intro, drop stale feature-PR template line

* docs: drop stale feature-PR template line

* docs: require approved issue in PR template

* docs: fix project layout (agent-core-v2 is current, v1 legacy)

* docs(zh-cn): fix project layout (agent-core-v2 is current, v1 legacy)
2026-08-19 20:31:56 +08:00
qer
38a5a934ae
feat: project prompt attachments into the live transcript and clear the transcript goal on clear (#3088)
* feat(agent-core-v2): carry prompt attachments on turn.started so the live transcript projects them

* fix(transcript): clear the transcript goal when the goal is cleared

* fix(agent-core-v2): count a prompt media part as a transcript attachment only when its id matches its daemon file URL

* test(kap-server): expect the session-media file id on converted prompt parts
2026-08-19 18:38:21 +08:00
7Sageer
2ea2ef62e4
feat(agent-core-v2): report the bound model alias in subagent_created telemetry (#3086) 2026-08-19 17:13:03 +08:00
Haozhe
16499408d5
refactor(agent-core-v2): extract externalHooks into a scope-organized feature (#2805)
Move the external hook services out of app/externalHooksRunner,
session/externalHooks, and agent/externalHooks into
features/externalHooks, assembled as the ExternalHooksFeature unit:

- services live under per-scope subdirectories (app/, session/, agent/);
  shared pure helpers (types, hook matching/dispatch, process spawn,
  prompt result rendering) live under internal/
- the runner and the two observers are contributed through the Feature
  seams (ScopeUnits materialization); the hooks config section stays on
  the static import=register channel
- update the package entry leaf exports, the plugin domain imports, the
  kap-server events-zod import, and the affected tests; regenerate the
  state manifest
2026-08-19 16:52:51 +08:00
Haozhe
cb8a7e5f81
feat(kap-server): expose engine feature list on /api/v1/meta (#3085) 2026-08-19 16:32:45 +08:00
7Sageer
571bcc2f75
fix(agent-core-v2): register needs-auth MCP authenticate tool regardless of settle timing (#3083) 2026-08-19 16:32:26 +08:00
Rick
35befdcef2
fix(vscode): multi-select question jumps to next after only one answe… (#3079)
* fix(vscode): multi-select question jumps to next after only one answer selected

* chore: add changeset

---------

Co-authored-by: gaoyuan <gaoyuan@moonshot.ai>
2026-08-19 16:27:07 +08:00
qer
be8e017597
fix(agent-core-v2): emit subagent.spawned after task registration (#3005)
* fix(agent-core-v2): emit subagent.spawned after task registration

The spawned signal previously fired at launch, before the run's task
registration, so clients learned the agent id with no task id to bind
cancel/status actions to; a failed registration also left a spawned row
behind for a run that never registered. Emit it only after registerTask
succeeds and carry the task id on the event.

* fix(agent-core-v2): keep spawned ahead of started for Agent-tool runs

The TUI drops subagent.started until spawned has established the row,
and a failed registration must not leave a started row behind with no
terminal event. Defer the mirrored started dispatch so the Agent tool
can emit it itself after registration and spawned.

* fix(agent-core-v2): void the deferred started dispatch

* fix(kap-server): key Agent-tool transcript rows by the registered task id

Transcript-protocol clients suppress the raw task.*/subagent.* session
events, so they only saw a subagent row keyed by agent id that cannot
address /tasks/{id}, plus a second row once task.started landed. Key the
spawned row by the task id it now carries, fold task.started and the
subagent lifecycle back into it, and keep the agent-id path for spawns
without a registration (swarm/session-init/tower). Statement-level
ordering notes move to the file headers per package convention.

* test(agent-core-v2): split the spawned/started ordering contract into its own test

* fix(kap-server): keep subagent result details across task termination and drop stale task mappings on taskless respawns

* fix(kap-server): recover the agent-to-task association from a backfilled task.started

* fix(kap-server): seed pre-attach Agent task mappings on the transcript binding

* fix(kap-server): seed the full in-flight task row on transcript bind, not only its id

* docs(agent-core-v2): name the state-domain event dispatcher in the Agent tool header

* style(kap-server): drop comments in transcript services per the no-comments lint rule
2026-08-19 14:58:55 +08:00
Luyu Cheng
01eeacb59b
feat(kimi-code): specialize the WaitFor tool's transcript display (#3066)
* feat(kimi-code): specialize the WaitFor tool's transcript display

* feat(agent-core-v2): emit status progress while WaitFor is pending

* fix(kimi-code): route WaitFor dimming through the TUI theme

* feat(kimi-code): support replaceable status updates in tool progress

* fix(kimi-code): forward status progress to subagent activity surfaces

* fix(agent-core-v2): drop the redundant undefined from ToolUpdate.replace

* fix(kimi-code): honor replace semantics in the subagent live status path

* test(agent-core-v2): drive the WaitFor progress test through a manual tick

* fix(kap-server): mirror ToolUpdate.replace in the ws event schema

* refactor(agent-core-v2): expose the WaitFor progress scheduler as a public seam

* fix(kimi-code): pass child wait statuses without the trailing newline

* feat(agent-core-v2): tick the WaitFor progress status every second

* feat(agent-core-v2): format WaitFor progress durations as 1m 15s

* feat(agent-core-v2): omit zero seconds and minutes in WaitFor durations
2026-08-19 14:15:38 +08:00
7Sageer
c908a39e32
refactor(agent-core-v2): unify the loop-event fold into one core with two materializations (#3018)
* refactor(agent-core-v2): unify the loop-event fold into one core with two materializations

The loop-event stream was reduced by two hand-mirrored state machines:
loopEventFold.ts for the live/replayed context and contextTranscript.ts
for the full transcript behind the messages endpoints, kept in sync by
comments alone and already drifted (transcript dropped tool-result note
metadata and never closed a dangling tool exchange at step.end).

createLoopEventFold now owns the shared state machine once (settle,
pending tool exchanges, deferred appends, vacuous tracking) and both
views plug in as LoopEventFoldSink materializations. New parity tests
pin the foldedLength === live length invariant the endpoints splice on.

* fix(agent-core-v2): drop every removed prompt's injections on multi-turn transcript undo

The transcript undo only walked prompt-owned injections off the oldest
counted anchor, so with count > 1 an injection owned by a newer removed
prompt (e.g. an image-compression caption) survived the display undo
while the live context removed it. Collect every counted anchor's id
during the walk and sweep their owned injections afterwards, keeping
the transcript's 'prompt-owned ones leave with their prompt' contract
for every count and matching the live view.

* refactor(agent-core-v2): drop module headers from the context fold modules

The comment-free zone lint only allows JSDoc on exported symbols.

* fix(agent-core-v2): recover fold state after rehydration

* fix(agent-core-v2): scope undo injections to their prompt

* fix(agent-core-v2): settle open transcript frames when compaction lands mid-fold

An overflow-triggered compaction arrives with the failed attempt's
frame still open. The transcript appended the summary marker and reset
the fold but left the frame, so a vacuous partial stayed in the entries
while the live context dropped it, and a pending tool exchange lost its
interrupted result. Settle through the shared fold core at the marker
instead: close pending tool calls, drop or seal the open frame, then
append the summary. recoverFoldedLength recomputes the absolute count
right after either way.

* fix(agent-core-v2): keep legacy compaction recovery on the pre-settlement count

A legacy context.apply_compaction record (compactedCount without
keptUserMessageCount) recovers foldedLength as 1 + (foldedLength -
compactedCount), and the live legacy tail shape keeps the unsettled
open frame inside history.slice(compactedCount). Settling the fold for
those records shifted foldedLength by the settlement delta before the
recovery read it, leaving the transcript count one off the live
context. Gate the settle to modern records; legacy records keep the
previous freeze-and-reset behavior.
2026-08-19 14:09:22 +08:00
7Sageer
f13f379044
fix(agent-core-v2): stop advertising unavailable ReadMediaFile to non-multimodal models (#3046)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
* fix(agent-core-v2): stop advertising unavailable ReadMediaFile to non-multimodal models

* fix(agent-core-v2): honor the effective tool policy before advertising ReadMediaFile

* fix(agent-core-v2): keep media-unavailable guidance reason-neutral and within the active toolset

* fix(agent-core-v2): recommend MCP fallbacks only when an active MCP tool exists

* fix(agent-core-v2): stop naming other tools in Read descriptions and errors

* fix(agent-core-v2): drop tool roster from plan agent prompt
2026-08-19 12:43:50 +08:00
Kai
6595a6989a
fix(kosong): emit null content for assistant messages with no text in chat completions (#3052)
Assistant messages carrying only tool calls were serialized without a
content key (JSON.stringify drops undefined), which strict
chat-completions validators such as LiteLLM reject with a 422,
permanently poisoning the session. Emit content: null for such messages
in both the kosong and agent-core-v2 converters, matching the shape
OpenAI responses use alongside tool_calls. The think-only empty-string
behavior in agent-core-v2 and both Kimi providers' deliberate content
omission are unchanged.
2026-08-19 11:39:32 +08:00
Luyu Cheng
8440801de4
feat(agent-core-v2): add the WaitFor tool for waiting on background tasks (#3060)
* feat(agent-core-v2): add the WaitFor tool for waiting on background tasks

* fix(agent-core-v2): mark WaitFor deliveries only after formatting succeeds

* fix(agent-core-v2): cancel losing waits once the WaitFor race resolves

* test(node-sdk): project WaitFor out of the v1-v2 resume parity roster

* fix(agent-core-v2): gate WaitFor goal guidance behind the wait_for flag

* fix(agent-core-v2): gate WaitFor goal guidance on actual tool availability

* fix(agent-core-v2): enforce the wait_for flag at WaitFor execution time

* fix(agent-core-v2): consult the live tool policy in the WaitFor availability check
2026-08-19 11:26:59 +08:00
qer
cdaa80b778
docs(changelog): sync 0.37.2 from apps/kimi-code/CHANGELOG.md (#3063)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
2026-08-19 02:05:30 +08:00
github-actions[bot]
c41fadf0f7
ci: release packages (#3062)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-19 01:37:58 +08:00
qer
5c661f4610
chore: sync web dist from code-app (#3061)
code-app: 221c548c98587fa1bd2aef458e1e20aaceece587
2026-08-19 01:33:29 +08:00
Haozhe
b478e95a2c
feat(agent-core-v2): reject duplicate scoped service registrations (#3057) 2026-08-19 00:17:12 +08:00
liruifengv
c11da4fbd8
docs(changelog): sync 0.37.1 from apps/kimi-code/CHANGELOG.md (#3055) 2026-08-18 22:50:19 +08:00
github-actions[bot]
1e553fc73b
ci: release packages (#3049)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-18 22:29:43 +08:00
7Sageer
95cede82b4
fix(agent-core-v2): stop the legacy video resolver from shadowing the media resolver (#3053)
#2593 replaced AgentVideoResolverService with the image+video
AgentMediaResolverService and reduced videoResolverService.ts to a pure
deprecated alias with no DI registration. #2909's squash merge restored
the pre-#2593 file wholesale, bringing back the legacy class and its
registerScopedService call. Both classes then registered the same token
('agentVideoResolverService') at the Agent scope and the legacy
video-only resolver won on the production import order, so image
kimi-file:// references reached the provider unresolved. Gateways
reject the unknown scheme with a 400 ("unsupported image url"), the
media-strip fallback then hid the image from the model, and pasted
images only worked on undo-resend via the inline base64 fallback.

Delete the legacy alias files and their index exports, drop the stale
alias assertion, and pin the behavior with a klient e2e regression:
a kimi-file image prompt part must reach the provider as a data: URL,
never verbatim.
2026-08-18 22:18:49 +08:00
7Sageer
c9c34ae5a8
fix(kimi-code): upload pasted videos to the daemon file store (#3047)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* fix(kimi-code): upload pasted videos to the daemon file store

Video paste staged a cache copy and submitted a bare file:// video_url,
which the v2 engine no longer resolves, so the submission failed and the
persisted history retried it on every turn. Mirror the image flow
instead: upload the paste to the daemon file store in the background and
submit a kimi-file:// reference that the engine's prompt intake
materializes. A video whose upload is still in flight, failed, or
expired now refuses the submission with an actionable error, since video
bytes have no inline fallback form.

* test(kimi-code): fix MessageDriver recallStashedMedia signature
2026-08-18 20:52:27 +08:00
liruifengv
589ed5467c
docs(changelog): sync 0.37.0 from apps/kimi-code/CHANGELOG.md (#3048)
* docs(changelog): sync 0.37.0 from apps/kimi-code/CHANGELOG.md

* docs(changelog): align English 0.37.0 entries with reviewed wording
2026-08-18 19:49:36 +08:00
github-actions[bot]
04944f380a
ci: release packages (#2932)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-18 19:19:18 +08:00
liruifengv
e31b3a335e
chore: sync web dist from code-app (#3043)
* chore: sync web dist from code-app

code-app: 1fb57f0ee3c424675d8768dcc70e56f5c953cd9f

* chore: sync web dist from code-app

code-app: 93da508d079b0118cc0338da97dcb738f0a3d46f

Adds the web session admin page. Built from the code-app PR #261 branch tip before its merge; the squash-merged main tree is expected to be identical (will be checked at merge time and rebuilt here if not).

* chore: correct the code-app trailer of the previous sync commit

The previous commit's trailer had a mistyped code-app SHA. The dist content is byte-identical to a build of code-app main at the merge below (tree verified identical to the branch tip it was built from), so the watermark for the next sync is:

code-app: 025805b33f1e87a4bc479574971c6177ad1403a0
2026-08-18 19:15:01 +08:00
liruifengv
8c865f4817
feat(kimi-code): support automatic updates for native installations via staged swap (#2994)
* feat(kimi-code): support automatic updates for native installations via staged swap

Native (SEA) installs previously could not self-update on Windows and
relied on 'curl | bash' re-install on Unix. Replace both with a staged
swap updater:

- startup swaps in a staged binary (verified against the release
  manifest sha256, smoke-checked via --version) and re-execs it, so the
  running process never replaces itself (Windows-safe)
- downloads run in a self-spawned hidden sub-command, in the background
  from the update preflight or in the foreground from 'kimi upgrade'
- rollback from .bak on any swap failure; install failures keep the
  existing retry/prompt thresholds

* fix(kimi-code): fully clean staged artifacts on swap discard paths

Real-binary smoke testing on macOS surfaced two cleanup gaps in the
discard path: the claimed metadata file was unlinked after the staging
dir rmdir (so the empty dir survived), and the staged exe was
rediscovered via the already-claimed staged.json (so it leaked on the
downgrade-guard path). Pass the known metadata through and order the
unlink before the rmdir.

* fix(kimi-code): restore staged metadata on swap failure and sweep update leftovers at startup

* fix(kimi-code): address codex review on lock contention and swap crash window

- The background native install no longer takes the outer install lock:
  the self-spawned downloader holds it for the whole download, and the
  parent's spawn-time lock raced the child into a false lastSuccess.
- Smoke-check the staged exe before moving anything, so a bad staged
  binary is discarded with the install path never left empty; the
  remaining crash window is two adjacent atomic renames (documented,
  recoverable via the .bak or by re-running the install script).

* test(kimi-code): align swap test expectation with smoke-before-rename order

The restore-on-failure case now observes the early smoke check's
--version spawn; only the re-exec spawn must be absent.

* fix(kimi-code): stage the bare CDN binary instead of unzipping

The published per-release artifacts are the bare platform binaries
(kimi-code-<target>[.exe]), not zip archives — the staging flow now
streams the download straight to the staged exe after the manifest
sha256 check, and the zip reader is dropped. Verified end-to-end on
macOS against the live CDN: download -> sha256 match -> swap ->
re-exec into the real released binary.

* fix(kimi-code): address second codex review round

- re-exec: forward 128 + signo when the swapped-in child dies by signal
  instead of reporting exit 0
- __update_download: only exit 0 without staging when the lock holder is
  staging the SAME version; a different in-flight version (or a vanished
  lock) no longer surfaces as a successful foreground upgrade
- staging: sweep orphaned .part downloads and unreferenced staged exes
  before downloading, preserving live swap claims and their payloads

* feat(kimi-code): show download progress for native updates

The foreground 'kimi upgrade' path streamed 180 MB with a single static
'Downloading…' line. Render progress instead: a throttled in-place
percentage line on a TTY, one line per 32 MB when piped, and plain MB
counts when Content-Length is unknown.

* fix(kimi-code): bound native update downloads with an idle timeout

Codex review: the manifest fetch cleared its timer once headers arrived,
so a stalled response body hung the worker forever, and the binary
download had no abort at all. The manifest timeout now covers body
consumption, and the binary stream aborts after 30 s without a chunk
(total duration stays unbounded for slow networks). The idle timeout is
injectable for tests.

* fix(kimi-code): retry native updates blocked by an orphaned active record

Windows real-machine verification surfaced that a parent exiting before
the downloader's exit event leaves a fresh-looking 'active' record that
silently blocks every background retry for the 6 h TTL. For native
installs, lock liveness is the truth past a 60 s spawn grace window:
a held lock means a download is running, a free lock means the record
is an orphan and a new attempt may start. Package-manager sources keep
the TTL behavior (no lock to prove liveness).

* fix: skip staged swap while another instance holds a fresh claim

sweepStaleNativeUpdateArtifacts already detected an in-progress swap in
a concurrent instance, but the result stayed inside the cleanup helper:
startup still claimed a newly published staged.json and ran a second
swap, so the two launchers could rename the install path and delete each
other's rollback backup. Propagate the in-progress signal and skip
claiming until the existing claim is released or goes stale.

* fix: keep the install lock while its holder process is alive

The install lock went stale purely by age (30 min), but the native
downloader is idle-bounded, not duration-bounded: a slow link can
legitimately take longer. Another startup would then sweep the lock and
spawn a second downloader, and both would write and clean the same
.staging paths. Past the age threshold, fall back to a pid liveness
probe (signal 0) — the lock is stale only when the holder is gone.

* fix: keep recovery artifacts on rollback failure and wait out same-version downloads

Two robustness fixes from review:

- native-swap: when moving the staged exe into place fails AND the
  rollback rename fails too (transient lock, AV), the install path is
  left absent and no next launch can start. Discarding the staged
  payload and claim on top of that removes the second recovery copy.
  rollback() now reports its result; on a double failure the swap keeps
  the .bak (which IS the old exe), the staged exe and the claim so
  manual recovery or a re-install still works.
- update-download: a foreground `kimi upgrade` racing a background
  downloader of the same version exited 0 immediately, so the CLI
  printed a success message for a download that could still fail. The
  worker now waits while the same-version holder is in flight, adopts
  the verified staged result (staged.json lands before the lock is
  released), and takes over the download when the holder finished
  without staging.

* fix: stamp the swap claim with a fresh mtime when claiming

rename() preserves the staged metadata's mtime, which can be arbitrarily
old — the background download often finishes hours before the next
launch claims it. A concurrent launch's sweep would then classify the
live claim as crash residue (older than the 5-minute window) and delete
the claim, the staged exe, and eventually the first swap's rollback
backup. Stamp the claim file with the claim time so the staleness check
measures the swap's liveness, not the download's age.

* fix: stamp the claim before the rename so it is born fresh

Stamping after the rename left a window: a concurrent launch could
inspect the claim between the two syscalls, see the staged metadata's
old mtime, and delete the staged executable mid-swap. utimes the state
file first so the claim carries a fresh timestamp from the instant it is
published — no fresh-looking-later intermediate state exists.

* fix: chmod the staged download before publishing it at its final name

A swap claims only the staged METADATA; the staged exe stays in
.staging/. A concurrent same-version downloader (possible because swaps
do not hold the install lock) then re-downloads and renames its .part
over that path. If the swap moves the file into the install path between
the downloader's rename and its post-publish chmod, the chmod lands on a
path that is already gone and the installation is left non-executable —
every future launch fails. Apply the executable mode to the private
.part file before the publishing rename so the staged exe is executable
from the instant it appears.

* fix: publish the install lock atomically via hard link

The 'wx' open exposed a momentarily empty lock file before its contents
were written. A concurrent acquirer reading in that window got a
SyntaxError, treated the lock as stale, swept it and also won — two
"holders" then ran stageNativeUpdate against the same .staging paths.
Write the lock contents to a unique temp file and hard-link it into
place: link() fails when the destination exists (same exclusivity as
'wx') and the lock path only ever appears fully written.

* fix: serialize stale-lock takeover through a secondary lock

A pathname-level delete can never be conditioned on the file still being
the inspected stale instance, so a plain compare-and-delete still loses
exclusivity: two workers classifying the same stale lock could interleave
unlink and publish such that both won (proven by a 20-way contention
test). Takeovers now go through a secondary create-if-absent lock
(install.lock.takeover): the delete+publish section only ever runs in
one process, staleness is re-validated inside it, and a fast-path creator
that wins the briefly-free path simply beats the takeover. The takeover
lock itself is age-swept (a live section lasts microseconds), and handles
only release the lock instance they own.

* fix: verify lock ownership after publish and preserve freshly staged exes

Two more race fixes from review:

- install-lock: the stale-marker sweep repeats the inspect-then-delete
  race one level up — two contenders sweeping the same aged takeover
  marker could both win and enter the main-lock section together.
  Pathname APIs offer no conditional delete, so both the takeover marker
  and the main lock now verify ownership after publishing (unique marker
  content, read-back compare): a racing sweep converts to a single
  survivor instead of two holders. The irreducible residual (a delete
  landing in the microsecond link-to-verify window) degrades to a wasted
  download cycle, never a corrupt install — swap claims guard the exe
  independently.
- native-swap: sweeping a stale swap claim deleted the exe it referenced
  even when a FRESH staged.json referenced the same version-derived name
  (a downloader re-staged the version after the swap crashed), throwing
  away a verified ~180 MB stage. The sweep now preserves any exe the
  current staged metadata still references.

* fix: reject mismatched manifests, take over from dead holders, unique .part names

Three robustness fixes from review:

- native-manifest: the per-release endpoint can answer with ANOTHER
  release's manifest (stale cache, mispublish); its checksums would then
  be applied to this version's binary and fail verification on every
  attempt. Compare the parsed manifest version with the requested one.
- install-lock/update-download: a killed lock holder skips its finally
  and never releases, stranding a waiting foreground `kimi upgrade`
  forever. A lock whose recorded pid is dead is now stale at any age
  (the atomic publish guarantees the pid was alive when written), and
  the same-version wait loop polls the acquisition itself, so a dead
  holder's lock is taken over within one poll instead of never.
  Package-manager spawns are unaffected: they hold the lock only around
  the spawn, and the active-record bookkeeping guards that layer.
- native-stage: the download intermediate is now unique per worker
  (`.part` carries pid + counter), so overlapping same-version workers
  can no longer interleave writes into the same file.

* fix: restrict staging cleanup to updater-owned names and retry short writes

- cleanupStagingOrphans recursively deleted anything it did not
  recognize; the staging dir sits next to the exe and can contain files
  belonging to the user or another tool. Deletion now requires a
  positive match on updater-owned artifact names (staged exes and .part
  intermediates) and only ever unlinks files.
- FileHandle.write may persist fewer bytes than requested (short write,
  e.g. near disk exhaustion) while the running hash and size already
  accounted for the whole chunk — publishing a truncated binary under a
  valid checksum. The chunk write now loops until fully persisted.

* fix: scope failure cleanup, recognize all semvers, reverify staged checksums

Three fixes from review:

- native-stage failure cleanup deleted whatever staged update was
  currently published — including a concurrent worker's valid result
  that its caller had already reported as success. The catch path now
  removes only this attempt's own artifacts: its unique .part file and
  its staged exe name when the current metadata does not reference it.
- The orphan-cleanup ownership check only matched stable x.y.z names;
  prerelease/build-metadata versions (1.2.3-rc.1, 1.2.3+build) would
  never be cleaned and accumulate ~180 MB each. Ownership now derives
  from the semver contract via the semver package's valid().
- The swap path trusted a staged exe whose size matched, though the
  metadata records the release checksum; post-download on-disk damage
  could pass the --version smoke check with corrupted bytes.
  claimStagedUpdate now re-verifies the staged exe's sha256 before
  claiming and discards the stage (for a later re-download) on mismatch
  — paid only when an update is actually pending.

* fix: validate versions before path derivation and honor the update opt-out in the swap

- native-stage: stageNativeUpdate derived staging paths (including the
  cleanup rm targets) from the version before fetchNativeReleaseManifest
  rejected it; a traversal string like `x/../../kimi` would resolve the
  staged-exe cleanup onto the running installation. The semver check now
  happens before any path is derived, and the staged-metadata schema
  constrains exeFileName to a plain file name.
- native-swap: the startup swap ran before the update preflight, so
  KIMI_CODE_NO_AUTO_UPDATE / KIMI_CLI_NO_AUTO_UPDATE stopped gating
  update behavior once a payload was pending. The swap now honors the
  same opt-out: the staged payload stays in place for a later launch
  without the variable, and the current exe starts.

* fix: restrict backup cleanup to updater-owned .bak names

cleanupBackups treated every <exe>.*.bak sibling as swap residue, so a
user's own backup like kimi.config.bak in a shared bin directory was
silently deleted on startup. Only the exact <exe>.bak and the numeric
PID fallback <exe>.<pid>.bak are updater-created — cleanup now
positively matches those two formats.

* fix: claim staged metadata before validating it and let manual upgrades bypass the opt-out

- native-swap: claimStagedUpdate validated the metadata and hashed the
  staged exe BEFORE the atomic rename, so a concurrent downloader
  superseding staged.json in between could get its fresh metadata
  claimed under the older object — the smoke check then failed and
  discard() deleted the newly published stage, recording a failure for
  the wrong version. The claim (utimes + rename) now happens first and
  validation acts on exactly the claimed file; discards use a new
  discardClaimedUpdate that never removes anything a meanwhile-published
  stage references.
- The auto-update env opt-out gated the startup swap unconditionally,
  so an explicit `kimi upgrade` with the variable set staged the
  version but no launch ever applied it. Stages now record
  `manual: true` when they answer a user-initiated install
  (`__update_download --manual`, threaded from installUpdate through
  the hidden sub-command), and the swap applies manual stages even when
  automatic updates are opted out.

* fix: promote adopted stages to manual and preserve claim-referenced payloads

Three follow-up fixes from review:

- An explicit `kimi upgrade` adopting an auto-staged payload (already
  on disk, or still downloading via the wait path) returned before the
  manual marker applied, so under the env opt-out the swap still skipped
  it despite the success message. Both adoption paths now promote the
  staged metadata to manual: true via a new promoteStagedUpdateToManual.
- The download-failure cleanup checked only the current staged metadata,
  but a live swap holds the metadata renamed aside as its claim — a
  failing same-version downloader could delete the exe an active swap
  was about to move into place. The catch path now also preserves names
  referenced by any live swap claim.
- Restoring a claimed stage after a failed exe move used rename, which
  on POSIX replaces a newer staged.json a downloader published during
  the smoke check. The restore is now a create-if-absent hard link: it
  only lands when the state-file path is still free, and the older claim
  is discarded when a newer stage has taken it.

* fix: drop exe deletion from stale-claim cleanup

The stale-claim sweep deleted the referenced exe based on a metadata
snapshot taken before the loop; a downloader republishing the same
version between the read and the unlink would have its fresh payload
deleted after reporting success. Publication can never be synchronized
with a pathname-level snapshot, so the sweep now removes only the claim
files themselves — genuinely unreferenced exes are reaped by the
downloader's own orphan cleanup (keep-set aware) before its next stage.

* fix: never delete the staged exe when discarding a claim

The same publication race existed one level down: a same-version
downloader can rename its fresh payload onto the shared exe path after
the discard's metadata snapshot but before the unlink (payloads publish
before their metadata), and the discard would delete a download whose
caller then reports success with nothing behind it. discardClaimedUpdate
now removes only the claimed metadata file; unreferenced exes are reaped
by the downloader's own orphan cleanup before its next stage.

* fix: only reap staging orphans old enough to be abandoned

The orphan sweep could delete a concurrent worker's freshly renamed
staged exe in the gap before its staged.json lands (payloads publish
before their metadata), turning the admitted duplicate-worker race into
a successful stage with no payload behind it. Unreferenced artifacts are
now only deleted once older than a one-hour grace period — publication
takes milliseconds, so unreferenced AND old means definitively
abandoned.

* fix: honor the persisted auto-update preference in the swap and drop claim-unsafe deletions

- The startup swap gated only on the env opt-out, so a payload staged
  automatically still installed after the user disabled automatic
  updates via [upgrade] auto_install = false. The swap now loads the
  persisted preference (only when an automatic stage is actually
  pending) and skips it, exactly like the env opt-out; manual stages
  still always apply.
- Superseding a staged version deleted its exe through an uncoordinated
  read-then-remove that could pull the payload from a live swap. The
  supersede now removes only the old metadata record — the metadata
  write atomically replaces it, and an unreferenced exe is reaped by a
  later orphan cleanup. removeStagedNativeUpdate, left with no callers,
  is removed.
- docs: the kimi upgrade reference (en + zh) no longer claims Windows
  native installations cannot upgrade automatically; native installs
  download and verify in the foreground and swap on the next start.

* fix: gate on claimed metadata, stop shared-path deletes on failure, exact smoke match

- The opt-out gate evaluated a pre-claim snapshot of the staged
  metadata, but the claim could pick up a different (automatic) stage a
  downloader published in between — smuggling it past the gate. The
  env/preference check now runs on the CLAIMED metadata; when disabled,
  the claim is restored via create-if-absent link so a newer stage is
  never overwritten and a later launch can still apply it. The checksum
  re-verify moves after the gates so opted-out launches stop paying for
  the hash.
- The download-failure cleanup still deleted the shared staged-exe path
  based on snapshot reference checks — the same publication race as the
  paths already fixed. It now removes only the attempt's privately owned
  .part file; the shared exe is left for the age-gated orphan cleanup.
- The smoke check accepted the staged version as a substring of the
  --version output, so a mispublished 1.2.30 binary would satisfy a
  1.2.3 target with a matching manifest checksum. It now requires the
  trimmed output to equal the staged version exactly.

* fix: confirm the manual marker before reporting stage adoption

promoteStagedUpdateToManual silently no-oped when a startup swap had
claimed the state file, while the adoption paths still reported success
with manual: true synthesized — under the env opt-out the restored
automatic metadata would then be skipped on every later launch despite
the upgrade's success message. The helper now verifies the marker with a
confirming read (one retry) and returns whether it persisted; the
already-staged branch falls through to a fresh stage when it does not,
and the same-version wait loop only adopts after a confirmed promotion.

* fix(cli): verify the staged payload digest before adopting it as already-staged

readStagedNativeUpdate checks only the recorded size, so a same-size
corruption after the download was adopted and reported as success, only
for the startup swap's claim-time re-verify to reject and discard it.
Compare the actual sha256 before returning already-staged; a mismatch
falls through and re-stages from the CDN.

* fix(cli): keep staged metadata until its replacement is ready

Two related races around staged.json, both reported against the
duplicate-downloader residual:

- stageNativeUpdate deleted the previous record before downloading its
  replacement; a pathname-only delete can remove a concurrent worker's
  freshly published record, orphaning a payload whose worker already
  reported success. The old record now stays until the final atomic
  metadata write replaces it.
- promoteStagedUpdateToManual wrote the marker unconditionally onto
  whichever generation owned staged.json. It now takes the adopted record
  and promotes only while the on-disk metadata still matches it, and the
  post-write confirmation requires the promoted candidate itself.

* fix(cli): preserve the exe referenced by the current staged record during orphan cleanup

Since the supersede path now keeps the previous staged.json until the
final atomic write replaces it, an aged staged exe is still the
applicable update while its replacement downloads — but
cleanupStagingOrphans only pinned exes referenced by swap claim files,
so a payload older than the grace period was unlinked out from under
its own record. Read staged.json itself in the pinning pass so the
current record's exe is preserved like any live claim's.

* chore(kimi-code): reword the native auto-update changeset

* chore(kimi-code): trim the native auto-update changeset

* fix(cli): support update locking on filesystems without hard links

link() fails with ENOTSUP/ENOSYS/EPERM on FAT/exFAT and some network
mounts, which aborted every native update before the download. Add a
shared createFileIfAbsent primitive (hard-link a fully written temp
file, falling back to an exclusive create + write) and use it for the
install lock, its takeover marker, and the swap's claim restore. The
fallback's create->write gap is observable, so the lock inspection now
grants young unparseable content a publish grace before sweeping it as
crash residue.

* fix(cli): publish staged exes under unique names and recover orphaned claims

Two related robustness fixes in the staged swap flow:

- A staged executable is now published under a unique per-worker name
  (kimi-<version>.<pid>.<epoch-ms>.<n>[.exe]) and never replaced; the
  atomic metadata write retargets the pointer. The pathname a swap
  validates at claim time can no longer be exchanged by a concurrent
  same-version publisher between validation and install.
- restoreClaimedUpdate only drops the claim when the restore landed or a
  newer stage holds the state-file path; transient failures retain it.
  The stale-claim sweep now restores aged claims (create-if-absent)
  instead of deleting them, so a stage orphaned by a dead swap or a
  transient restore failure is retried on a later launch.

* fix(cli): verify the staged payload digest in the lock-wait adoption path

waitForStagedUpdate relied on readStagedNativeUpdate, which checks only
the recorded size: while a holder re-stages a same-size-corrupted
payload (its metadata is replaced only when the repaired generation
publishes), a waiter could promote and report the corrupt stage as
downloaded, and startup would later reject its checksum. Apply the same
integrity bar as stageNativeUpdate's already-staged path — adopt only a
payload that hashes to its recorded checksum; a mismatch falls through
to the lock poll, which takes over once the holder finishes without
repairing it.

* fix(cli): serialize swap critical sections and preserve in-flight publishes

- The fresh-claim sweep is only a directory snapshot: two processes could
  both pass it before either claimed, then rename the same installed exe
  concurrently and delete each other's rollback backup. A create-if-absent
  swap mutex (swap.lock, age-gated like the takeover marker) now serializes
  the executable-renaming section; the loser restores its claim and defers.
  The mutex is released as soon as the new exe is in place, before the
  re-exec, so it is never held for the child session's lifetime.
- claimStagedUpdate no longer destroys a claimed record that is unparseable
  but was young at claim time: on filesystems without hard links the
  exclusive-create publish is observable mid-write, and discarding it would
  orphan the staged exe while the writer reports success. Such a record is
  put back with the same inode so the writer completes it; aged corrupt
  residue and well-formed records with a missing/changed exe are still
  discarded.

* fix(cli): keep backup cleanup inside the swap mutex

The early release let a subsequent swap rename the just-installed exe to
the shared .bak path while the previous swap's cleanup was still about to
unlink that same path, destroying the second swap's rollback source. The
mutex now covers the backup cleanup; the cosmetic staging-dir rmdir and
the re-exec stay outside it.
2026-08-18 17:17:18 +08:00
7Sageer
86674ac895
test: remove wording-pinning tests of model-facing prose across both suites (#3031)
* test: replace prose-pinning system-prompt tests with a structural sharing check

The two removed tests pinned exact sentences of the default system prompt
('reversibility and blast radius', 'premature abstraction', optional-tool
phrasings that must not appear, ...). They broke on any intentional
wording change while only catching regressions that reused the same words.

The one real contract underneath — shared, ungated sections must render
byte-identically in the root agent and every subagent profile — is now
checked structurally by slicing the section out of the root prompt and
asserting the other profiles contain it, regardless of its wording.

* test: remove wording-pinning tests of model-facing prose across both suites

Sweep of the class identified in #3030: assertions pinning the exact
English wording of product model-facing text (system prompt, reminder
and injection .md files, tool descriptions, shipped profile/skill
bodies). They break on any intentional rewording yet only catch
regressions that reuse the same words.

Across 35 files (~60 test cases, net -1131 lines):
- deleted dedicated wording tests: 'exposes current metadata and
  schema' description pins, goal/plan/todo reminder content tests,
  tower skill-body prose pins, goal-outcome.test.ts;
- trimmed wording assertions from behavioral tests that otherwise
  stand alone; kept identifiers (tool names, XML tags, section
  markers), structural properties (wrapping/escaping/gating/cadence),
  fixture data, tool outputs and error messages;
- re-anchored a few gating tests on exported constants
  (WINDOWS_PATH_HINT, DEFAULT_REPLY_STYLE_GUIDE) instead of prose
  literals.

Deferred for a follow-up decision: ~15 tests whose prose pin is the
only discriminator of which reminder/budget-band fired (constants not
exported). Wire baselines and snapshot machinery untouched.
2026-08-18 16:36:57 +08:00
7Sageer
5c8df5973e
test: drop the assertion for the removed ambiguous-means-task example (#3030)
#3028 removed the 'treat ambiguous requests as tasks' rule and its
'locate the method in the code' example from the default system prompt.
The profile test pinned that example verbatim, so it now fails on main.
The removal was intentional; update the test to the new contract.
2026-08-18 15:02:17 +08:00
Luyu Cheng
d6021fa036
feat(kap-server): accept bundled skill activations on the prompt submission route (#2982)
* feat(kap-server): accept bundled skill activations on the prompt submission route

The bundled-submission capability was only reachable through the
in-process klient transports; the App talks to kap-server over /api/v1.
The submit-prompt route now accepts an optional non-empty skills field
and delegates to IAgentSkillService.promptWithSkills — same validation,
events, and single bundled user message as the TUI path — skipping its
own prompt-metadata update (the engine owns it there) and mapping
skill.not_found / skill.type_unsupported onto the skills route's codes.
To return the submission's queue identity, the engine's promptWithSkills
now resolves with prompt_id / user_message_id / created_at / state (plus
turn_id once launched), mirrored through the klient contract.

* refactor(agent-core-v2): slim the promptWithSkills result contract

Drop the user_message_id field (it is always the same identity as
prompt_id — the route duplicates it) and narrow state to the
running/queued/blocked vocabulary, mapped at the engine edge instead of
exposing the internal seven-state PromptState on the wire.

* fix(kap-server): harden bundled skill submissions against review findings

- Validate bundled skill names and types before any media materialization
  or control override, so a rejected bundle leaves session state untouched
  (the engine still re-validates authoritatively).
- Declare the 40415/40912 outcomes on the submit route so the generated
  API documentation includes them.
- The klient output schema no longer tolerates a missing promptWithSkills
  result (a transport-level absence now raises instead of resolving
  undefined), and a failed launch surfaces as an error rather than a
  successful running result.
- Add the changeset for the new public API field.

* fix(kap-server): preflight bundled skills before agent materialization and stabilize listed content

- Skill preflight now runs on the session's catalog before the main agent
  is resolved, so a rejected bundle cannot mutate session metadata by
  registering main (regression test on a cold session without an agent).
- The prompts list projection strips the stored skill blocks from a
  bundled prompt, so GET /prompts returns the same caller-only content as
  the submit response.

* fix(kap-server): reject bundled prompt_id combos at preflight and clean queued staging

- The skills + prompt_id incompatibility rejection now runs at the initial
  bundled preflight, before the main agent is materialized or any
  override binds (previously a yolo override could bind before the 40001).
- Queued bundles no longer skip staging cleanup forever: the discard is
  deferred to the bundle's prompt.completed / prompt.aborted lifecycle
  event, mirroring the plain path's launch-raced cleanup.

* fix(kap-server): clean queued bundle staging on the steer path too

A queued bundle steered into the active turn is consumed at steer time,
but the engine publishes prompt.completed/aborted only for the parent —
the deferred cleanup never fired and its subscription leaked. The
prompt.steered event (matching promptIds) now counts as the child's
intake-completion signal.

* fix(agent-core-v2): materialize daemon-ref media on the steer and inject paths

startNext materializes daemon file references into the session media
store before a prompt's turn, but steer() and inject() enqueued the same
references without that intake, leaving the staging upload as the only
copy — any staging cleanup at steer time would delete the media the
turn is about to consume. Both paths now run the same intake before the
SteerStepRequest is created, so prompt.steered is a truthful
intake-complete signal.

* fix(kap-server): defer staging cleanup to turn settlement, never to steer time

Prompt-intake materialization is best-effort: when it degrades, the
daemon upload is the request-time resolver's fallback source. Discarding
staging at prompt.steered could therefore delete the only readable copy
before the parent's request ran. Cleanup is now uniformly event-driven —
the bundle's own prompt.completed/aborted, or the steer parent's — so
the upload always outlives the request it feeds.

* fix(kap-server): install settlement tracking before bundled enqueue

A hook-blocked bundle completes synchronously inside the submission
call, and an exceptionally fast launch can settle just as early — a
post-call subscription misses the only settlement event and leaks both
the staging blob and the listener. The tracker now subscribes before
enqueueing, buffers lifecycle events, and settles against the returned
prompt id (or its steer parent's).

* fix(kap-server): scope settlement tracking to the owning agent and dispose on rejection

- The tracker now subscribes through the agent-scoped IEventBus instead of
  the App-scoped IEventService: prompt lifecycle events from other
  sessions never reach it, so a colliding client-chosen prompt id cannot
  trigger a foreign settlement (and the steer re-target only follows this
  agent's parent).
- A bundled submission that rejects after the tracker was installed now
  disposes it on the error path instead of leaking a permanent listener.

* fix(agent-core-v2): keep steered prompts queued until their media intake finishes

Materializing a steered prompt's daemon-ref media awaits a file copy
during which the active turn may finish. Records are now spliced out of
the queue only after that copy completes, and when the turn is gone by
enqueue time they are restored to pending so startNext can launch them
as fresh prompts — their handles always launch or settle.

* fix(agent-core-v2): revalidate the queue and active turn after steer media intake

The daemon-ref copy yields, so settle/abort can consume selected records
and the active turn can rotate meanwhile. Only records still pending are
steered, and only into the turn that was active at entry; records that
vanish from the queue are left to their own launch path, and a missing
turn restores them to pending instead of splicing an unrelated tail
prompt. The intake/queue-preservation contract is documented in the
module header.

* fix(agent-core-v2): steer only the surviving records and keep their media truthful

- The steered content is rebuilt from the records that are still pending
  after the media intake, so an aborted or concurrently consumed record's
  text is never injected (or injected twice) alongside the surviving
  handles.
- The enqueue is wrapped so an activeTurnOnly rejection restores the
  records to pending (the loop throws instead of resolving a missing
  turn, which made the previous rollback unreachable).
- The merged origin now carries the union of every record's bundled
  skillActivations, and prompt.steered publishes the caller-only content,
  so the skill instructions reach the model with their metadata intact
  while the event projection stops leaking internal skill markdown.

* fix(agent-core-v2): harden steer rollback and register bundled prompt ids

* fix(agent-core-v2): strip bundled blocks from prompt.queued and reject partial steers

* fix(kap-server): update session metadata for bundled prompts routed to subagents

* fix(agent-core-v2): restart queue after raced steer rollback and prefix skill blocks in merged steer

* fix(agent-core-v2): block queue advancement during steer admission

* chore: drop the changeset for server-only protocol plumbing
2026-08-18 14:57:13 +08:00
7Sageer
40e1784089
fix: tone down over-proactiveness in the default system prompt (#3028)
* fix: tone down over-proactiveness in the default system prompt

The default system prompt pushed the agent to act before discussing:
ambiguous requests were explicitly resolved to tasks, the opening framed
the primary goal as taking action, and 'default to making progress, not
to asking' discouraged clarifying questions.

Trim both copies (agent-core and agent-core-v2) by deletion only:
the ambiguous-means-task rule and its example, the action-framed opening
clause, the 'default to taking action with tools' paragraph, the
duplicated must-use-tools sentence (kept once in Ultimate Reminders),
and the 'default to making progress, not to asking' bullet. Operational
guidance and the execution guards stay untouched.

* Delete .changeset/tame-system-prompt-proactiveness.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* fix: drop the tool-use and no-placeholder bullets from the default system prompt

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-08-18 14:47:52 +08:00
bj456736
d3150fe947
chore: remove internal-network references from comments and test fixtures (#3029)
* chore: remove internal-network references from comments and test fixtures

- Reword two comments that named the internal free-tokens model
  registration flow; the generic OAuth / managed wording carries the
  same meaning
- Replace the qianxun.example placeholder base URL in google-genai and
  runtime-provider tests with genai-gateway.example
- Swap realistic-looking LAN fixture IPs in the kimi web banner tests
  (192.168.98.66, 10.8.12.216) for RFC 5737 documentation addresses
  (192.0.2.66, 198.51.100.216)

* chore: retrigger CI (flaky kap-server searchRoute title-indexing test)

---------

Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
2026-08-18 14:14:56 +08:00
liruifengv
eaa3969dd3
feat(kap-server): add page mode, updated_before, and batch archive/restore to v2 sessions (#2983)
* feat(kap-server): add page-number mode and total to GET /api/v2/sessions

The v2 session list gains a stateless 1-based `page` parameter beside the
opaque page_token cursor for admin-style lists that jump arbitrarily:
each request stays a full independent snapshot, no token is minted, and
`page` + `page_token` together fail 40001. Every response now carries
`total` (the filtered/sorted set size) in both pagination modes.

* feat(kap-server): add meta.updated_before filter to GET /api/v2/sessions

Symmetric with meta.updated_after (inclusive boundary, Unix ms), applied
at the edge over the drained set and bound into the page_token query
fingerprint like every other condition.

* feat(kap-server): add POST /api/v2/sessions:archive and :restore batch endpoints

Batch archive/restore for session-management views: { ids } (non-empty,
≤5000 unique after dedup) answers per-item results in input order with
succeeded/failed counts — only a body validation failure fails the whole
request, and an unknown id folds into its own item as 40401.

The live/cold split keeps the batch cheap: a session with a live handle
goes through the full ISessionLifecycleService chain (agents drain,
scope teardown, mirror drain), while a cold session is never
materialized — the new setColdSessionArchived helper in agent-core-v2
patches the persisted state.json (archived/archivedAt, updatedAt
preserved, mirroring setArchived's touchUpdatedAt: false semantics),
mirrors the flipped summary into the read-model queue, and republishes
the same event.session.archived bus event the live lifecycle emits
(:restore publishes nothing, matching the live restore). Hot items run
with bounded concurrency and the batch ends with one shared
ISessionIndexMirror.drain().

* docs(server-api): document v2 sessions page mode, total, updated_before, and batch archive/restore

* fix(kap-server): deep-import workspace lifecycle symbols in the v2 sessions route

CI's tsgo/rolldown (Linux) fail to bind liveHandlerForSession and
IWorkspaceLifecycleService through the agent-core-v2 package-root
barrel even though it re-exports them; the same files use the
established deep-import pattern already used for the git domain.

* fix(kap-server): inline the live-handler lookup in the batch route

The previous deep imports still fail to resolve on CI's Linux toolchain
(tsgo TS2307, rolldown MISSING_EXPORT) while every other module path
from the same package binds fine. Keep the route self-contained: the
hot-path lookup is a five-line loop over IWorkspaceLifecycleService's
handlers (mirrors agent-core-v2's liveHandlerForSession), and the tests
assert non-materialization behaviorally via the live map instead of
importing the same two symbols for spies.

* fix(kap-server): drive the batch hot path through getLiveSessionById

The phantom only hits the workspaceLifecycle-group symbols in these two
files on CI's Linux toolchain; getLiveSessionById is observed to bind
fine there. It returns the session's live scope directly (no resume),
which is exactly what the batch hot path needs.

* refactor(kap-server): move the batch live/cold split into agent-core-v2

setSessionArchivedBatch owns the split next to the cold patch: live
sessions go through the full lifecycle chain via the workspace handler
accessor (the v1-proven resolution path), cold sessions through the
direct write. The route becomes a thin wire-code adapter, and the batch
tests assert the live chain behaviorally (disposal, events, index)
instead of spying through scope accessors.

* fix(agent-core-v2): import sessionLookup relatively from coldSessionArchive

The '#/app/workspaceLifecycle/*' specifier resolves from src/ and
src/app/* files on CI's Linux toolchain but not from
src/workspace/sessionLifecycle/ (tsgo TS2307, rolldown follows); a
relative import bypasses the package-imports mapping.

* fix(agent-core-v2): migrate the batch hot path to ISessionManager

Main's workspace/session DI refactor removed the workspaceLifecycle
lookup modules; the live branch now goes through the App-level
ISessionManager (the same entry the v1 action route uses post-refactor)
with getLiveSessionById from the new sessionManager lookup.

* feat(kap-server): add the id,archived item projection to GET /api/v2/sessions

fields=id,archived trims each item to { id, archived } for
select-all-matching flows (the session admin page's Gmail-style
select-all). Only that projection gets the relaxed page_size ceiling
(10000); unknown fields, non-pair subsets, and include=git combinations
are 40001, and the projection binds into the page_token fingerprint so
shapes never flip mid-pagination.

* fix(agent-core-v2): serialize the batch cold write against in-flight resumes

Codex review on #2983: while a resume is in flight the live registry
hides the handle, so the batch route could classify the session as cold
and its direct write would race the materializing metadata service (its
stale in-memory document wins the next write, silently un-archiving the
session after the endpoint reported success).

The batch now settles the resume first: SessionManager registers the
whole resume promise synchronously at the App level (controllerForSession
is async, so the controller's own resuming map learns about it a few
microtasks late) and whenResumeSettled awaits it before classification —
a settled resume lands the item on the live chain, a failed one falls
back to the cold path. Also folds the module header down to the
package's external-role comment convention.

* fix(agent-core-v2): publish SessionArchived as an Event2 class in cold archive

* fix(agent-core-v2): serialize batch archive/restore with session lifecycle transitions

* fix(agent-core-v2): serialize session delete with the lifecycle chain

* fix(agent-core-v2): mirror the persisted metadata on cold archive, not the index summary

* docs(agent-core-v2): bring sessionManager comments and new tests to package conventions

* fix(agent-core-v2): normalize legacy session metadata before the cold archive write

* fix(kap-server): serialize the v1 single-session archive with the lifecycle chain

* chore: drop changesets for internal-only protocol work

* fix(agent-core-v2): encode cold-archived metadata for v1 readers

* fix(agent-core-v2): serialize fork and createChild with the source session's chain

* refactor(agent-core-v2): chain every session lifecycle method and hand batch sections unguarded ops

* fix(agent-core-v2): propagate failed resumes to the next settle

* fix(agent-core-v2): roll back the unannounced handle when a resume fails mid-materialization

* fix(agent-core-v2): read and migrate the legacy session-meta location on cold archive

* fix(agent-core-v2): serialize explicit-id session creation with the lifecycle chain

create() with a caller-supplied sessionId bypassed the per-session chain,
so a concurrent batch archive could classify the half-created session as
cold and write archived state that the live metadata service later
overwrites. Creation now queues on the target id's chain whenever an
explicit id is present.

Also type the resume-failure maps as Error and normalize at the catch
site, satisfying only-throw-error.

* style(kap-server): strip comments from the session routes per the no-comments convention

* fix(agent-core-v2): serialize explicit fork and child target ids on the lifecycle chain

fork() and createChild() with a newSessionId locked only the source id, so
a batch archive of the target could slip into the creation window: the
index already knows the half-created session, the batch writes archived
state to its document, and the fork's in-memory metadata later overwrites
it. Both operations now acquire the deduped, sorted key set so multi-key
sections always take locks in one deterministic order.
2026-08-18 13:57:37 +08:00
Haozhe
5ae82cd5bc
feat(agent-core-v2): disable the tower feature entirely (#3023) 2026-08-18 13:38:13 +08:00
bj456736
13857f3832
chore: rewrite pending changesets for the new changelog conventions (#3026)
* Rewrite pending changesets for the new changelog conventions

* chore: drop the /tower changeset per reviewer request

* chore: trim pending changeset entries further per reviewer feedback

---------

Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
2026-08-18 13:06:14 +08:00
bj456736
8f5090782c
chore: simplify the gen-changesets skill (#3024)
* Simplify the gen-changesets skill

* chore: state only what changed, drop explanatory trailing clauses

* docs: require strict adherence to the changeset rules in AGENTS.md

---------

Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
2026-08-18 13:05:50 +08:00
Haozhe
98ebda840a
fix(kimi-code): revert the todo panel to its pre-turn state on undo (#3016)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* fix(kimi-code): revert the todo panel to its pre-turn state on undo

* fix(kimi-code): hide all-done todo lists on undo refresh and detach SDK todo state
2026-08-18 12:00:19 +08:00
Haozhe
8267bb8fce
feat(kap-server): add workspace fs:suggest file completion endpoint (#3019) 2026-08-18 11:53:48 +08:00
Haozhe
3ded08084a
fix(protocol): expose turn ended event time (#3011)
* fix(protocol): expose turn ended event time

* fix(protocol): expose turn ended event time

* chore(changeset): remove patch release entry

* test(node-sdk): align background task parity expectations
2026-08-18 10:16:12 +08:00
Haozhe
1ab19190e9
refactor(agent-core-v2): strip comments from agent-core-v2, kap-server, and transcript (#3010)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
2026-08-18 00:30:49 +08:00
bj456736
a7dc1ea284
fix(agent-core-v2): degrade media tool registration when the bound model alias is stale (#2985)
* fix(agent-core-v2): degrade media tool registration when the bound model alias is stale

A restored session replays its persisted profile.bind without catalog
validation, so the profile can carry a model alias that no longer
resolves (e.g. the managed kimi-code models were removed from
config.toml on logout). AgentMediaToolsRegistrar.refresh() called
modelCatalog.getRequester() unguarded on that alias; the throw escaped
the agent.status.updated listener and was reported as an [unexpected]
Error2 (config.invalid) on startup.

Catch the resolution failure and degrade to "no model": media tools
stay registered off the profile-reported capabilities, just without a
model-bound video uploader, matching the tryResolveRawModel style used
elsewhere in the profile service.

* test(agent-core-v2): reproduce the stale-alias regression with production-consistent collaborators

A stale alias makes the real AgentProfileService report
UNKNOWN_CAPABILITY, so the regression now binds unknown capabilities,
asserts the tool stays unregistered without surfacing an [unexpected]
error, and covers recovery once the alias resolves again. The rationale
moves into the mediaToolsRegistrar file header per the package comment
conventions.

---------

Co-authored-by: Mira <bj456736@users.noreply.github.com>
2026-08-17 21:46:52 +08:00
7Sageer
5dffed2545
refactor(agent-core-v2): rebuild context projection as a staged block pipeline (#3001)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* refactor(agent-core-v2): carry the context fold cursor in state and converge fold/projection internals

- ContextModel state is now { messages, fold }: the loop-event fold cursor
  (openStepUuid / pending / deferred) lives in the state instead of a
  module-level WeakMap keyed by array identity, so wholesale replacements
  (undo / clear / compaction / swarm exit) reset it structurally via
  EMPTY_FOLD instead of a manual resetFold at five call sites.
- The display transcript and the wire model now share one generic fold
  kernel (FoldFrame / FoldEntryAdapter), eliminating the mirrored second
  implementation. Events tagged with a non-open step uuid are dropped and
  step.end settles only the step it names — defensive in abnormal streams,
  identical on well-formed ones (v1 replay unaffected).
- IAgentContextProjectorService converges to project(messages, policy) with
  a ProjectionPolicy data object; llmRequester builds the policy from retry
  state instead of selecting among four methods.
- Blob rehydrate now also covers messages still deferred in the fold cursor.
- ContextState is deeply frozen at the op boundary to preserve the consumer
  immutability the wire's shallow freeze gave the bare array state.

* test(agent-core-v2): move fold parity rationales into the test file header

* docs(agent-core-v2): move fold declaration comments into module headers

* refactor(agent-core-v2): merge FoldFrame into generic ContextState

* refactor(agent-core-v2): compile-enforce part/event handling decisions in context memory

- isVacuousContentPart and dehydrateRecord now switch exhaustively over
  ContentPart / LoopRecordedEvent variants, so a new variant fails
  compilation until it takes an explicit position
- the transcript/model parity comparator spreads whole messages and masks
  only summary content, so new ContextMessage fields join the comparison
  automatically
- correct two stale header comments: local message ids persist with
  append_message records, and undo's prompt-owned-injection pairing
  depends on them after a resume

* refactor(agent-core-v2): converge undo-cut decision in conversationTime

The model Op and the display transcript each walked the undo anchors with
their own loop, and the transcript partially removed the tail when an undo
was blocked (compaction summary / clear floor / too few anchors) while the
model side no-ops at the precheck. Move the walk into conversationTime as
computeUndoCut/computeUndoCutFrom applied destructively by the context.undo
Op and non-destructively by the transcript reducer, so a blocked undo reads
identically on both sides.

Also: make isUndoAnchor exhaustive over origin kinds with a never assertion,
mirrors the compaction result message count via compactionHandoff, and
extend UndoCut with anchorIndex distinguishing the counted anchor from the
injection-extended cut point.

* fix(agent-core-v2): drop removed prompts' injections on multi-turn transcript undo

The transcript's kept-loop retained every injection after the oldest
counted anchor, so with count > 1 a prompt-owned injection of a newer
removed prompt (e.g. an image-compression caption) survived the display
undo while the model Op removed it. Collect the removed anchors' ids on
the same pass and keep only injections not owned by them, so the header's
'prompt-owned ones leave with their prompt' holds for every count.

* refactor(agent-core-v2): accumulate request projection repairs as policy

The llmRequester retry chain kept a RequestProjection union and translated
it into a ProjectionPolicy per attempt; repairs were mutually exclusive,
so a strict resend rejected again for body size or image format either
aborted or silently dropped the strict repair. Retry state is now the
ProjectionPolicy itself: each rejection adds its repair on its own axis
(media: 413 -> degraded -> strip; wire: structure -> strict) without
discarding the other, requestInput's translation layer and the unreachable
snapshot ??= disappear, and the persisted llm.request projection name
derives from the policy (the op enum gains strict-media-degraded /
strict-media-stripped). Also narrows ProjectionPolicy to the variants
actually produced (wire 'strict'; media 'degraded' | { strip }), dropping
the dead 'default'/'keep' literals and their guard.

* refactor(agent-core-v2): derive the visible context window from an append-only log

context.apply_compaction now appends a summary marker carrying the record
fields as CompactionMeta instead of replacing the folded history; the
model-visible window is derived at read time (visibleWindow) with the same
[head, elision?, tail, summary] layout, one deterministic derivation for
live dispatch and replay alike. The record format is unchanged, so v1- and
v2-written sessions keep replaying identically both ways.

- undo maps the visible-window cut back to a log position (the verbatim
  legacy-summary edge falls back to the pre-append-only destructive cut)
- replay rehydrate only loads blobs the window derivation can surface
- contextInjector drops position tracking; injection positions become a
  read-time scan that splices can never desync
- fullCompaction's safety check moves to the stable-identity log

* fix(agent-core-v2): rehydrate exactly the messages the visible window surfaces

The first append-only rehydrate rule kept pre-marker real user input plus
markers, but a legacyTail derivation keeps window.slice(compactedCount)
visible — assistant/tool media in that range stayed blobref after replay
and could be resent unresolved. Decide survivors by identity membership in
the derived window instead, which covers every derivation branch at once
and skips the unselected pre-marker pool as a bonus.

* fix(agent-core-v2): pop the visible-tail swarm reminder behind a legacy marker

SwarmService.exit decides the pop on the derived window's tail, but the
swarm_mode.exit reducer tested the raw log tail — after a legacyTail
compaction the survivor reminder is visible at the window tail while the
marker is the log tail, so the pop silently skipped and the stale reminder
stayed in the model context. Mirror the visible-tail decision in the
reducer and remove the entry by its stable log identity.

* fix(agent-core-v2): settle open transcript frames when compaction lands mid-fold

An overflow-triggered compaction arrives with the failed attempt's vacuous
partial still open. The transcript appended the summary marker and reset
the fold but left the frame; the retried step's step.begin then settled it
(-1) alongside the new frame (+1), so foldedLength stayed one short of the
model-visible window and kap-server's live-tail merge could duplicate the
retry tail. Settle the frame at the marker through the shared kernel;
recoverFoldedLength recomputes the absolute count right after either way.

* fix(agent-core-v2): settle open frames at the compaction marker

Apply settleModelOpenStep inside context.apply_compaction so a marker only
ever lands on a settled frame: no partial survives a marker and nothing
mutates the log behind one, making the append-only invariant structural
(the identity-prefix check in historySafeToCompact relied on it) instead
of timing-dependent. Mirrors the transcript's settle-at-marker.

Also freeze the derived visible window before caching it (an in-place
consumer mutation now throws instead of silently polluting the shared
cache), and drop the production-unreachable legacy branch of
buildContextCompactionShape so the legacy tail layout lives only in
deriveCompactionWindow.

* refactor(agent-core-v2): tighten naming and comments in context memory internals

- Slim file headers to the package header-only comment convention
- Rename PR-introduced identifiers for clarity: getMessageLog,
  ProjectionPolicy.structure, pendingToolCallIds/deferredEntries,
  removedEntryCount, deriveVisibleWindowAfterCompaction,
  compactedWindowMessageCount
- Extract nextProjectionPolicyForError, removeUndoOwnedEntries and
  summarizeProjectionRepairs; name fold intermediates after their
  business stage
- Regroup splice-replay tests by topic and unify projection-call
  recording in llmRequester tests

* fix(agent-core-v2): preserve bounded context state

* docs(agent-core-v2): restore the domain identity line in the compactionHandoff header

* refactor(agent-core-v2): rebuild context projection as a staged block pipeline

Split the 650-line projector service into three modules by concern:
mediaProjection (read-side media degrade/strip fallbacks), projection
(the structural transform), and the service (DI binding plus repair
reporting). Rebuild the structural projection as a two-stage pipeline:
pairBlocks groups tool exchanges into blocks that own their calls'
results, flattenBlocks serializes them back to wire order and merges
consecutive user prompts. The shared slot sentinel and index
back-patching are gone; the trailing-close and sizing-slice rules are
named and documented in the module header. Behavior is pinned unchanged
by the existing projector and llmRequester suites.

* docs(agent-core-v2): trim the projection helper header to its external role

* docs(agent-core-v2): keep the contextProjector module headers at the external-role level
2026-08-17 20:34:39 +08:00
bj456736
09976b0914
feat(cli): add --web-title and expose it via /meta (#2989)
* feat(cli): add --web-title and expose it via /meta

* refactor(kap-server): pass optional web_title directly in /meta

Per the repo rule for optional object properties, pass undefined directly
instead of a conditional spread; serialization omits the unset value.

* fix(cli): sync web bundle with instance tab title support

The committed dist-web bundle predates the document title feature, so a
released `kimi web --web-title` served a client that never read web_title.
Rebuilt from code-app (feat/web-document-title) via sync:web; the bundle
now titles tabs from web_title or the active workspace directory.

* ci: retrigger checks after flaky harness cleanup failure

---------

Co-authored-by: wbxl2000 <wbxl2000@outlook.com>
Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
2026-08-17 20:19:15 +08:00
7Sageer
02aa24e2f4
refactor(agent-core-v2): carry the context fold cursor in state and converge fold/projection internals (#2875)
* refactor(agent-core-v2): carry the context fold cursor in state and converge fold/projection internals

- ContextModel state is now { messages, fold }: the loop-event fold cursor
  (openStepUuid / pending / deferred) lives in the state instead of a
  module-level WeakMap keyed by array identity, so wholesale replacements
  (undo / clear / compaction / swarm exit) reset it structurally via
  EMPTY_FOLD instead of a manual resetFold at five call sites.
- The display transcript and the wire model now share one generic fold
  kernel (FoldFrame / FoldEntryAdapter), eliminating the mirrored second
  implementation. Events tagged with a non-open step uuid are dropped and
  step.end settles only the step it names — defensive in abnormal streams,
  identical on well-formed ones (v1 replay unaffected).
- IAgentContextProjectorService converges to project(messages, policy) with
  a ProjectionPolicy data object; llmRequester builds the policy from retry
  state instead of selecting among four methods.
- Blob rehydrate now also covers messages still deferred in the fold cursor.
- ContextState is deeply frozen at the op boundary to preserve the consumer
  immutability the wire's shallow freeze gave the bare array state.

* test(agent-core-v2): move fold parity rationales into the test file header

* docs(agent-core-v2): move fold declaration comments into module headers

* refactor(agent-core-v2): merge FoldFrame into generic ContextState

* refactor(agent-core-v2): compile-enforce part/event handling decisions in context memory

- isVacuousContentPart and dehydrateRecord now switch exhaustively over
  ContentPart / LoopRecordedEvent variants, so a new variant fails
  compilation until it takes an explicit position
- the transcript/model parity comparator spreads whole messages and masks
  only summary content, so new ContextMessage fields join the comparison
  automatically
- correct two stale header comments: local message ids persist with
  append_message records, and undo's prompt-owned-injection pairing
  depends on them after a resume

* refactor(agent-core-v2): converge undo-cut decision in conversationTime

The model Op and the display transcript each walked the undo anchors with
their own loop, and the transcript partially removed the tail when an undo
was blocked (compaction summary / clear floor / too few anchors) while the
model side no-ops at the precheck. Move the walk into conversationTime as
computeUndoCut/computeUndoCutFrom applied destructively by the context.undo
Op and non-destructively by the transcript reducer, so a blocked undo reads
identically on both sides.

Also: make isUndoAnchor exhaustive over origin kinds with a never assertion,
mirrors the compaction result message count via compactionHandoff, and
extend UndoCut with anchorIndex distinguishing the counted anchor from the
injection-extended cut point.

* fix(agent-core-v2): drop removed prompts' injections on multi-turn transcript undo

The transcript's kept-loop retained every injection after the oldest
counted anchor, so with count > 1 a prompt-owned injection of a newer
removed prompt (e.g. an image-compression caption) survived the display
undo while the model Op removed it. Collect the removed anchors' ids on
the same pass and keep only injections not owned by them, so the header's
'prompt-owned ones leave with their prompt' holds for every count.

* refactor(agent-core-v2): accumulate request projection repairs as policy

The llmRequester retry chain kept a RequestProjection union and translated
it into a ProjectionPolicy per attempt; repairs were mutually exclusive,
so a strict resend rejected again for body size or image format either
aborted or silently dropped the strict repair. Retry state is now the
ProjectionPolicy itself: each rejection adds its repair on its own axis
(media: 413 -> degraded -> strip; wire: structure -> strict) without
discarding the other, requestInput's translation layer and the unreachable
snapshot ??= disappear, and the persisted llm.request projection name
derives from the policy (the op enum gains strict-media-degraded /
strict-media-stripped). Also narrows ProjectionPolicy to the variants
actually produced (wire 'strict'; media 'degraded' | { strip }), dropping
the dead 'default'/'keep' literals and their guard.

* refactor(agent-core-v2): derive the visible context window from an append-only log

context.apply_compaction now appends a summary marker carrying the record
fields as CompactionMeta instead of replacing the folded history; the
model-visible window is derived at read time (visibleWindow) with the same
[head, elision?, tail, summary] layout, one deterministic derivation for
live dispatch and replay alike. The record format is unchanged, so v1- and
v2-written sessions keep replaying identically both ways.

- undo maps the visible-window cut back to a log position (the verbatim
  legacy-summary edge falls back to the pre-append-only destructive cut)
- replay rehydrate only loads blobs the window derivation can surface
- contextInjector drops position tracking; injection positions become a
  read-time scan that splices can never desync
- fullCompaction's safety check moves to the stable-identity log

* fix(agent-core-v2): rehydrate exactly the messages the visible window surfaces

The first append-only rehydrate rule kept pre-marker real user input plus
markers, but a legacyTail derivation keeps window.slice(compactedCount)
visible — assistant/tool media in that range stayed blobref after replay
and could be resent unresolved. Decide survivors by identity membership in
the derived window instead, which covers every derivation branch at once
and skips the unselected pre-marker pool as a bonus.

* fix(agent-core-v2): pop the visible-tail swarm reminder behind a legacy marker

SwarmService.exit decides the pop on the derived window's tail, but the
swarm_mode.exit reducer tested the raw log tail — after a legacyTail
compaction the survivor reminder is visible at the window tail while the
marker is the log tail, so the pop silently skipped and the stale reminder
stayed in the model context. Mirror the visible-tail decision in the
reducer and remove the entry by its stable log identity.

* fix(agent-core-v2): settle open transcript frames when compaction lands mid-fold

An overflow-triggered compaction arrives with the failed attempt's vacuous
partial still open. The transcript appended the summary marker and reset
the fold but left the frame; the retried step's step.begin then settled it
(-1) alongside the new frame (+1), so foldedLength stayed one short of the
model-visible window and kap-server's live-tail merge could duplicate the
retry tail. Settle the frame at the marker through the shared kernel;
recoverFoldedLength recomputes the absolute count right after either way.

* fix(agent-core-v2): settle open frames at the compaction marker

Apply settleModelOpenStep inside context.apply_compaction so a marker only
ever lands on a settled frame: no partial survives a marker and nothing
mutates the log behind one, making the append-only invariant structural
(the identity-prefix check in historySafeToCompact relied on it) instead
of timing-dependent. Mirrors the transcript's settle-at-marker.

Also freeze the derived visible window before caching it (an in-place
consumer mutation now throws instead of silently polluting the shared
cache), and drop the production-unreachable legacy branch of
buildContextCompactionShape so the legacy tail layout lives only in
deriveCompactionWindow.

* refactor(agent-core-v2): tighten naming and comments in context memory internals

- Slim file headers to the package header-only comment convention
- Rename PR-introduced identifiers for clarity: getMessageLog,
  ProjectionPolicy.structure, pendingToolCallIds/deferredEntries,
  removedEntryCount, deriveVisibleWindowAfterCompaction,
  compactedWindowMessageCount
- Extract nextProjectionPolicyForError, removeUndoOwnedEntries and
  summarizeProjectionRepairs; name fold intermediates after their
  business stage
- Regroup splice-replay tests by topic and unify projection-call
  recording in llmRequester tests

* fix(agent-core-v2): preserve bounded context state

* docs(agent-core-v2): restore the domain identity line in the compactionHandoff header
2026-08-17 18:14:44 +08:00
Haozhe
2265305e81
refactor(agent-core-v2): replace defineOp/Model with Event2 dispatch and replayable states (#2909)
* refactor(agent-core-v2): replace defineOp/Model with Event2 dispatch and replayable states

- replace defineOp/Op/OpDescriptor/toEvent and defineModel/defineCheckpointedModel with Event2 subclasses: durable classes declare static durable + schema, serialize() keeps the wire record shape byte-frozen, transient classes stay off the journal
- define states via defineState(...).replayable(...).on(Event2, fold): immer produceWithPatches folds with atomic prepare/commit, .undoable() trait drives prompt-submit checkpoints and context.undo, ephemeral kv keys keep imperative set
- degrade IWireService to a journal adapter; the agent event dispatcher owns the pipeline (fold -> set -> appendRecord -> publish) and silent restore
- align downstream event surfaces: kap-server WS envelope timestamp from event.time, klient event schemas gain time, node-sdk/acp-server/print wiring updated
- rewrite gen-wire-manifest/gen-state-manifest for the unified registry and replace the op-uniqueness lint with event-uniqueness

* fix(ci): repair Event2 prompt and media projections

- restore prompt admission and session media materialization
- align transcript, WS, SDK, and replayable media state projections
- update affected tests and generated state manifest

* fix(ci): update prompt event and projection expectations

- update snapshots for the durable prompt.accepted event
- normalize prompt.steered media in transcript projections
2026-08-17 17:38:50 +08:00
Haoyang Ma
1cf617d769
fix(google-genai): preserve Gemini tool-call thought signature and trailing user text order (#2914)
* fix(agent-core-v2): preserve tool call extras in tool.call loop events

* fix(google-genai): keep trailing user text before function results when merging

---------

Co-authored-by: Selene <mahaoyang@corp.netease.com>
2026-08-17 17:28:41 +08:00
7Sageer
ee55c4d523
fix(kimi-code): persist pasted-image originals into the session dir at dispatch (#2993)
* fix(kimi-code): persist pasted-image originals into the session dir at dispatch

Paste-time original persistence ran before the session existed on a
fresh TUI, so the compression caption baked a shared temp-dir path the
OS can reap. Keep the pre-compression bytes on the attachment in memory
and let dispatch-time caption resolution (sendMessageInternal,
steerMessage, runInlineSkillActivations) write them into the session's
media-originals dir — owned by the session, cleaned up with it, immune
to OS temp reaping.

* fix(kimi-code): harden pasted-image original lifecycle

Address review feedback:

- carry the pre-compression original in the resend snapshot so a
  cache-hint "new session" resend still persists it into the new
  session's originals dir and authors the compression caption
- release the in-memory original bytes once persistence succeeds,
  keeping only the metadata the caption needs
- apply the same 1 GiB mtime-bounded eviction to the sync originals
  store as the engine's async twin

* fix(kimi-code): keep compression captions consistent with the sent image

Address review feedback:

- author a caption only when the image part still matches the
  attachment's current state, so a paste whose ingestion landed after
  extraction (inline pre-compression fallback) is not described as
  downsampled
- leave the original's path unset when persistence fails so a later
  dispatch retries the write instead of dropping the original for good

* fix(kimi-code): keep staged media across lazy session creation

setSession() released ALL staging leases on the assumption that they
belong to the session being replaced. On the lazy first-creation path
there is no previous session: the outstanding lease belongs to the new
session's first prompt, whose dispatch continues right after. The
premature release deleted a pasted image's daemon upload before the
engine's intake could read it, so the model only received
'[image omitted: the uploaded file is no longer available]'.

Gate the release on actually replacing a live session; shutdown and
explicit close keep their own releaseAll().

* Delete .changeset/lazy-session-staging-lease.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* Delete .changeset/pasty-image-originals-session-dir.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-08-17 15:04:52 +08:00
7Sageer
59dde734f3
feat(agent-core): unify the v1 MCP management plane (#2858)
* feat(agent-core): unify the v1 MCP management plane

- McpServerRegistry: one config view over global (layered mcp.json),
  plugin (manifests, read-only, final effective config), and caller
  (SDK-injected) servers; name collisions keep both entries.
- Write plane: add/update/removeGlobalMcpServer mutate the user-level
  file and push into live sessions; getGlobalMcpServer returns the
  effective config; mutations of read-only entries are rejected.
- testGlobalMcpServer accepts an inline config; addSessionMcpServer
  connects a server in one live session with an optional persist flag;
  reconnect accepts a replacement config and re-resolves via the registry.
- One process-wide McpOAuthService shared with every session: obtained_at
  stamps, offline token state, single-flight and proactive refresh, and
  credential events. Sessions self-subscribe in the constructor, so even
  initializing sessions see every event; token writes serialize through
  the process-local OAuthTokenTransaction per credential identity.
- inspectAppMcpServers + locator-addressed begin/complete/cancel/reset
  cover plugin servers; inspection output redacts env/headers to sorted
  key lists; locator OAuth ops reject ambiguous shared runtime names.
- The legacy auth-status surface reads the registry (offline by default,
  verify=true probes) and never mutates credentials.
- VS Code panel receives source/origin/mutable and hides mutating
  actions on read-only entries.
- v2 client facade in node-sdk mirrors the surface over agent-core-v2
  (plugin inventory stays v1-only for now).

* fix(agent-core): close the v1 MCP live-session reconciliation gaps

Recompute each live session's MCP target from the registry's runtime
resolution (enabled plugin > project layer > user file; caller injection
shadows everything) behind every config mutation, instead of per-path
patching: shadowed file layers recover when a plugin winner is disabled or
removed, removing a user-level entry resurrects its project-layer shadow,
disabled plugin descriptors no longer block removals, persisted session
adds validate against the session's project layer and broadcast to other
live sessions, and per-session sync failures are logged with context.

Session status entries and read-only management entries now report
redacted config views (envKeys/headerKeys instead of literal env/headers
values); core-internal reconciliation compares full configs via the
connection manager's raw-entry accessor.

OAuth: interactive flows are serialized per credential (concurrent
begins join the in-flight flow instead of clobbering its PKCE/state), a
malformed credential meta sidecar no longer aborts core start, grants
inside the refresh-ahead window refresh immediately while far-future
grants re-arm through a max-length timer, and the service shuts its
timers and flows down with KimiCore/SDKRpcClient close.

* fix(agent-core): route the proactive MCP OAuth refresh through the token transaction

 refreshNow ran its /token request with the SDK default fetch, outside the
 credential-serializing OAuthTokenTransaction that every other token write
 uses; a slower response carrying an older rotating refresh token could
 overwrite a newer grant written by a concurrent transport-side refresh.

* fix(agent-core): keep disabled MCP servers out of auth-state classification

The unified mcpServerAuthState dropped the previous enabled short-circuit,
so a disabled oauth-flagged server reported oauth-required — or was even
probed over the network — instead of not-applicable.

* fix(kimi-code-sdk): short-circuit disabled MCP servers in the v2 auth-status classifier

The v2 parity copy of v1's mcpServerAuthState missed the same enabled
guard v1 just regained; a disabled oauth-flagged entry would report
oauth-required (or be probed). The parity suite now pins the disabled
case on both engines.

* fix(kimi-code): refresh the VS Code MCP list with the workspace cwd after mutations

The add/update/remove RPCs return a cwd-less management list, so the
webview broadcast dropped project-layer entries until the next full load;
re-list with the workspace cwd after every mutation instead.

* fix(agent-core): keep SDK token saves matched to the OAuth token transaction

saveTokens stamped obtained_at onto a fresh object before calling
tokenTransaction.save, so it never matched the exact payload the
transaction recorded for a grant fetch; the consume path was dead and
every save re-wrote. Between the fetch and the SDK callback an intervening
clear could then be overwritten — the resurrected grant came back after a
reset. The write callback stamps the durable record instead.

* fix(agent-core): reject ambiguous legacy name-based MCP auth lookups

The legacy begin/reset auth RPCs took the registry's first name match,
silently starting OAuth for one entry of a runtime-name collision while
the locator path refused the same ambiguity; align them on the shared
uniqueness rule and point callers at the locator-addressed variants.

* fix(agent-core): propagate registry errors during live-session MCP sync

resolveMcpRuntimeTarget collapsed every registry failure into "no target":
a project config file that turned malformed mid-session made sync treat a
still-configured server as gone (tearing down the live connection) and
made config-aware reconnects report "no longer configured" instead of the
actionable config error. Absence still resolves to undefined; malformed
config now propagates — per-session sync logs and keeps the entry, and
reconnect surfaces config.invalid.

* fix(agent-core): close the remaining registry-error and ambiguity gaps

The management guard lookup mapped every registry failure to "absent",
so a malformed project config let a persisted session add write a
user-level entry over an unknown state; only not-found is a miss now. And
the name-only connection test now shares the auth paths' uniqueness rule
instead of probing the first match of a runtime-name collision.

* fix(agent-core): probe the enabled MCP entry under a disabled-name collision

The name-only connection test counted enabled matches for its ambiguity
guard but still probed the first registry match, and the file layers list
before plugins. With a disabled file entry shadowing an enabled plugin of
the same runtime name, Test probed the disabled entry instead of the one a
live session would run. Select the sole enabled match, falling back to the
first entry only when every match is disabled so it reports as disabled.

* fix(agent-core): let session-local MCP adds shadow plugin entries

Caller injection shadows every registry source at session start, plugins
included, and reconciliation leaves caller entries untouched; the live
non-persist add path rejected plugin-owned names anyway, so SDK clients
could not apply the same per-session override without a restart. Gate the
plugin-source rejection on persist: session-local adds connect as caller,
while persisted adds stay rejected as user-level writes behind a read-only
owner.

* fix(agent-core): normalize session MCP names before connecting

The persisted store trims server names, but addSessionMcpServer used the
raw name for the live connect and cross-session reconciliation: a padded
name persisted under the trimmed key while the requesting session ran and
reconciled the raw one, and a blank name connected with no identity at
all. Normalize once up front (rejecting blank) so the store write, the
session entry, and reconciliation agree on the same server.

* fix(agent-core,node-sdk): close the collision-selection and probe-freshness gaps

The legacy name-only auth resolver started from the first registry match,
so a disabled file-layer shadow plus an enabled plugin of the same runtime
name was misread as an ambiguity conflict; select the sole enabled match
before judging ambiguity, exactly like the test probe path. On the v2
client, addSessionMcpServer connected the raw name while the store wrote
the trimmed key — normalize once for both, and route the verify-triggered
auth probes through the per-call OAuth service instead of the cached one
whose providers snapshot tokens at construction, so a grant saved after
the first probe is honored.

* fix(agent-core): normalize global MCP mutation names and guard disabled reconnect swaps

The global add/update/remove mutations guarded and reconciled with the raw
server name while the store persisted the trimmed key, so a padded name
left live sessions unreconciled and could slip past the plugin read-only
guard; normalize once before lookup, persistence, and reconciliation. And
a config-carrying reconnect assigned the replacement before the disabled
check fired, leaving a connected entry that reported the disabled config;
reject disabled replacements before mutating, keeping the same error.

* fix(agent-core): skip proactive refresh while an interactive flow owns the credential

refreshNow reset the shared provider's flow state before and after the
token request; when a proactive timer (or a manual refresh) fired while
beginAuthorization was waiting on the browser callback for the same store
key, that wiped the redirect URL, PKCE verifier, and state the in-flight
flow needed — complete() then failed the exchange even though the user
authorized. Refresh now skips when an interactive flow is active for the
credential: the flow delivers fresh tokens on completion, and the 401
transport path is the backstop if it fails.

* fix(agent-core): allow global MCP adds over disabled plugin descriptors

A disabled plugin entry is absent from the runtime target, but the
read-only guard still treated it as the owner, so a user-level fallback
could only exist if it predated the plugin disable. Relax the shared
guard: disabled plugin descriptors never block mutations (disabled
project entries still shadow the user file and keep their rejection).

* fix(node-sdk): close the v2 session-MCP parity gaps

A v2 reconnect with an explicit enabled:false replacement config used
connect()'s upsert semantics — closing the live client and reporting
success where v1's manager reconnect rejects before applying anything;
reject disabled replacements up front with the same error. And a persisted
v2 session add never consulted the workspace config, so a same-named
project-layer entry was silently shadowed: the user-level write never
takes effect while the direct workspace-manager upsert displaces the
project config for every live session. Resolve the workspace layers and
reject like v1's read-only rule.

* fix(agent-core): keep __proto__-named MCP servers through config parsing

A z.record() parse rebuilds its output via property assignment, so a
server literally named __proto__ hit the prototype setter and vanished
before validation; the layer merge then repeated the same trap with plain
object accumulators. Parse the server map entry-by-entry over the JSON own
keys and accumulate into null-prototype maps, so session startup and the
unified registry keep the declared server and its origin.

* fix(node-sdk): begin v2 MCP auth against a fresh OAuth service

The v2 begin path ran through the cached globalMcpOAuth, whose providers
snapshot tokens at construction: a grant another process saved (or reset)
after that cache materialized was invisible, so begin could open a browser
flow over a valid grant, or report already-authorized off a removed one.
Build the service per call — the read path and the verify probes already
do — and route the status list through the same helper. The test fixture
grows a real token endpoint honoring one rotating refresh token; the
regression fails against the cached-service implementation on v2.

* fix(agent-core): broadcast SDK-driven MCP token invalidations to live sessions

* test(agent-core-v2): give the no-op reconnect test runtime plumbing

The branch added the case against a bare McpConnectionManager, but #2961
made stdio connects resolve the runtime through runtimeResolver, matching
every other case in the file.
2026-08-17 13:19:51 +08:00
7Sageer
d833a1a893
feat: engine-native image references via kimi-file:// media resolver (#2593)
* feat: engine-native image references via kimi-file:// media resolver

* fix(agent-core-v2): regenerate state manifest for media resolver rename

* feat(agent-core-v2): add audio MediaKind and tag/ref fold helpers to media ref contract

* fix(agent-core-v2): synthesize image path tag when degrading bare file references

* fix(agent-core-v2): scrub dangling alias re-exports in contract type generator

* feat(transcript): project paired media tag+ref as single attachments in read models

* fix(kimi-code): fall back to inline image when cache write fails after upload

* fix(agent-core-v2): pair media path tags with refs by adjacency and path, keep unpaired tags

* fix(kap-server): fold media tag+ref pairs out of prompt snapshot projection

* fix(kap-server): list attachment-only prompts as empty user messages

* fix(kap-server): keep live attachment ids across transcript overlay and heal

* fix(kap-server): keep promptAttachments off the legacy session event wire

* fix(kap-server): inherit the backfilled turn header on mid-turn terminal projection

A projector that attached after turn.started built the terminal turn.upsert
with an empty header, and the whole-header replace downstream wiped the
backfilled origin / prompt / attachmentIds — only the debounced best-effort
heal could restore them. Fall back to the producer store's seeded header
(via a new optional ProjectorLookups.turn) when currentTurn misses, and
cover the mid-turn attach path with a service-level regression test.

* refactor(agent-core-v2): move media ref contract out of kosong into agent/media

The kimi-file:// daemon reference grammar, media path tags, and the tag/ref
fold are engine-internal conventions, not provider-wire contract; keep
src/kosong untouched. Root exports and SDK re-exports are unchanged.

* feat(agent-core-v2): materialize prompt media into the session media dir

Pasted and uploaded media now materialize under the session's own media/
dir instead of the shared cache, so the copies follow the session's
lifecycle: fork carries them along, session deletion cleans them up.

A new Session-scope ISessionMediaStore owns the dir: atomic tmp+rename
materialization with a unified extension policy, and canonical-vs-hint
display-path resolution. The persisted ?path= is a write-time snapshot —
readers prefer the session-canonical location, so fork and home relocation
never hand the model a dead path. Prompt intake normalizes every daemon
reference through the single enqueue funnel (REST edge, SDK prompt/steer,
gateway), serialized in arrival order to keep the FIFO across the async
file I/O. The kap-server edge materializes through the same store with a
shared-cache fallback, and the request-time resolver refreshes stale
persisted and memoized path tags; a claimed video reference degrades to
its tag alone instead of duplicating it.

* fix(agent-core-v2): take prompt media intake off the enqueue critical path

The record now joins the FIFO synchronously and its daemon-ref intake runs
as a per-record promise, awaited by the launch and steer paths before the
message is consumed — queue order, list/abort visibility, and prompt
submission latency no longer wait on file I/O, and a slow intake no longer
head-of-line blocks later prompts. The launching record is tracked so abort
and clear stay reachable inside the launch window; startNext re-checks
cancellation after every await (intake race, hook, turn admission), a
cancelled record is never re-queued, and a compaction requeue waits for
onDidFinishCompaction instead of busy-looping the scheduler.

* fix(agent-core-v2): record the claiming ref in the media path-tag pairing

pairMediaPathTagRefs now exposes claimingRefByTagIndex, and claimingRefIndex
reads it instead of recovering the claimer by path equality — which
mis-attributed a tag when two different fileIds carried the same path in an
interleaved sequence, breaking the pair and leaking the tag as user text.
Also covers the memoized-video-tag claimed-drop branch.

* fix(transcript): fold upload pairs in user-slash turns and pin pairing parity

The cold rebuild's user-slash branch now folds the turn-opening input like
any user turn (claimed tag out of the prompt text, one attachment entity),
matching the live projection. The ref extraction is consolidated into the
contract module (daemonFileRefFromPairingPart, the mirror of the engine's
daemonFileRefFromPart) and the mirror carries the new claimingRefByTagIndex
map. A new kap-server parity test imports both implementations and asserts
identical pairings over shared fixtures, so the engine/mirror pair can no
longer drift silently.

* fix(kap-server): fold upload media tags out of the search index

The global search indexer concatenated every text part of a persisted user
message, so the upload pair's <image path> tag made pure-image prompts
searchable and wrote the materialization path into the index — breaking the
module's documented pure-image invariant and diverging from the live route.
textOfContent now folds the pair like every other read model (with a
fold-safe coercion for malformed wire parts). Also pins the prompt-media
cache-dir fallback with a read-only session media dir test (skipped as root).

* feat(node-sdk): re-export the media fold helpers and cover the v1 uploadFile rejection

foldMediaPathTagRefs and matchSingleMediaPathTag join the daemon
file-reference helper re-exports so hosts can fold the upload tag+ref pair
without importing agent-core-v2; the v1 harness's uploadFile not_implemented
rejection is pinned by a test.

* fix(kimi-code): fold upload pairs in replay/export and keep media tags atomic in steer input

Resumed-session replay rendered the upload pair raw — the <image path> tag
as user text and the kimi-file:// url as an XML-ish reference — and the
markdown export leaked the tag into both the turn body and the overview
topic. contentPartsToText and the exporter now fold the pair, and daemon
references render as a bare [image]/[video] placeholder. combineSteerInput
moves to tui/utils/steer-input and no longer merges a standalone media tag
into adjacent text, which would have broken the engine-side pairing for
steered image messages.

* fix(kimi-code): drop the steer separator before a leading media tag

A queued pure-image message opens with a standalone `<media path>` tag,
which combineSteerInput keeps atomic. With the previous item ending in a
media part, the '\n\n' separator landed as a stranded whitespace-only text
part between the media part and the tag, normalizePromptInput rejected the
steer, and the already-cleared queue lost the messages. Treat a leading
standalone tag as media so the separator is dropped there.

* fix: clean staged media lifecycle

* refactor(agent-core-v2): narrow the mediaRef root exports and drop a deprecated alias

* fix: keep staged media alive through turn

* fix(agent-core-v2): reject non-upload ids at the session media store

A daemon reference's fileId becomes a storage key in the session media
store, but only the file domain validated the id shape — a crafted
kimi-file://<id> reaching the request-time resolver's canonical-read
fallback could traverse out of the session media dir. Share the file
domain's id regex and guard every store entry point: reads miss,
materialize declines, and the display path falls back to the hint.

* fix(kap-server): project steered prompt content without leaking daemon refs

prompt.steered published the raw engine content parts — kimi-file://
refs carrying the absolute materialization path plus the paired
<media path> tag — to both the legacy session_event wire (whose schema
declares the protocol content shape) and the transcript prompt entity.
Route both through one shared prompt-content projection: the upload
pair folds into a single {kind:'file'} part, matching the REST prompt
list and the no-path-leak rule every sibling surface already follows.

* refactor: align daemon-ref naming and drop a duplicate re-export

The deprecated videoResolverService alias also re-exported
mediaResolvedKey, which made the package root's star exports ambiguous
and silently dropped the name. The new transcript contract mirror now
uses the canonical daemon-ref vocabulary instead of the deprecated
kimi-file spelling.

* test(agent-core-v2): pin image abort rethrow, video canonical read-through, release-once

Mirror the video abort contract on the new image path (an aborted read
cancels the request instead of degrading to a tag), cover the video
fallback that uploads the session-canonical bytes after the transient
upload is released, and assert the staged-upload release fires exactly
once on the intake success path.

* fix(kimi-code): bind goal-steer staging leases to the running turn

sendMessageInternal read the turn context only after beginSessionRequest
had cleared it, so a steer buffered into a running goal turn never got
its staging lease bound — the staged daemon upload and cache copies
lived until session close instead of being released at the consuming
turn's end. Capture the live turn id before the reset (only while a
turn is actually streaming; the id outlives its turn otherwise).

Also move the staging-lease state machine off the KimiTUI coordinator
into a self-contained StagingLeaseTracker with injected effects, drop
the duplicate media-tag builder in image-placeholder in favor of the
SDK helper, and fix the paste-in-flight comment to match the gate's
real granularity.

* fix(kap-server): project prompt.queued content without leaking daemon refs

The broadcaster projected prompt.steered and stripped turn.started
attachments but forwarded prompt.queued raw, leaking kimi-file:// URLs
and absolute materialization paths to every subscribed WS connection
and the journal. Fold the tag+ref pair into a {kind:'file'} part, same
as steered.

* fix: keep compressed uploads retrievable and close the steer abort window

Two review fixes around prompt media intake:

- The compressed re-save was released right after intake (and carried a
  1h expiry) while every client read model projects its file id,
  leaving historical compressed images unfetchable. Keep the re-save as
  an ordinary upload; roll it back only when preparation or submission
  fails before the engine takes the prompt. The engine's
  PromptInput.release hook loses its only producer and is removed.
- A prompt aborted while its steer awaited the loop's step assignment
  was flipped back to 'steered' and its content could still
  materialize into a later turn. Re-check the reservations after the
  assignment await and abort the undispatched request when the check
  fails.

* perf(agent-core-v2): memoize inlined image parts across request steps

A successful image inline depends only on the immutable upload bytes, so
it is memoized per file id (size-bounded) in media.resolved and reused
across steps, retries, and media-recovery reprojections instead of
re-reading and re-encoding on every request. Degrade forms are never
memoized since they depend on the message's tag pairing. Also make the
never-empty message placeholder kind-aware (video vs image).

* refactor: author media tag+ref pairs in the engine prompt intake

Edges (TUI, kap-server REST) now submit bare kimi-file references and the
engine intake materializes the bytes, synthesizes the paired media path
tag, and falls back to the shared cache dir when the session store is
unavailable, replacing per-edge pair construction and duplicate
materialization copies.

Thread the prompt id from submission through to turn.started (REST
prompt_id, WS event, SDK prompt option) so the TUI binds staged-media
leases to turns exactly; the origin heuristic stays as fallback and
ambiguous claims now surface a staging_lease_invariant telemetry warning.

Also lands the pending resendable-extraction fix for cache-hint resubmits
after a session switch.

* fix: decouple media persistence from prompt intake

* refactor(agent-core-v2): project the turn prompt in a single fold pass

* test: slim redundant media-ref coverage across layers

Fold duplicate pinning of the same media tag+ref rules into shared
helpers and it.each tables, and drop assertions that restate behavior
already covered at another layer:

- drop the kimiFileUrl alias describe (mediaRef.test.ts covers the
  aliased functions with more cases)
- drop pairMediaPathTagRefs describe in favor of the parity fixtures
- merge the identical prompt.steered/prompt.queued broadcast tests
- parameterize the resolver degradation matrix and prompt intake
  fixtures (enqueueMedia/gatedImage/expectMediaPair helpers)
- drop REST-level context-memory pairing assertions (engine-level
  intake tests pin the same shapes); keep the caption->system-reminder
  assertion, the only cover of extractCompressionCaptions
- drop the turn-finish-during-intake steer-cancel vector and the
  switch-session release driver test (unit-level lease tests remain)

Net -762 lines; 645 tests green across agent-core-v2, kap-server,
transcript, node-sdk, klient, and the TUI.

* chore: fix oxlint warnings introduced by image-file-ref changes

* fix: harden image file reference lifecycle

* fix: close image reference lifecycle gaps

* fix: preserve session media paths on replay

* chore: streamline image-file-ref changesets

* refactor: make daemon media references self-contained, dropping tag+ref pairing

A daemon-ref media part now carries everything a read model needs — the
kind from the part type and the materialization path from the reference's
`?path=` — so prompt intake no longer authors a paired `<media path>`
tag, and the pairing/fold machinery (pairMediaPathTagRefs /
foldMediaPathTagRefs and their mirror copy) is deleted across the engine,
transcript, kap-server, node-sdk, and the TUI. The request-time resolver
synthesizes the degrade tag from the reference path whenever bytes cannot
reach the provider. Standalone tags stay user-visible text, and never
reach the search index or prompt metadata.

* fix: reconcile image file references with main after rebase

Main removed the agent RPC aggregation layer (agent/rpc) and moved
LifecycleScope to app/scopes. Fold the branch's RPC-side behavior into
the new structure: PromptPayload carries promptId/disabledTools, and
AgentPromptService.submit admits the client-chosen id through the
reservation (duplicate rejects before any session state changes) and
applies the denylist through toolPolicy. Regenerate the wire/state
manifests.

* fix(kimi-code): run paste ingestion in the background, wait bounded at submit

The paste callback awaited compression + original persistence + the
daemon upload while CustomEditor queued every keystroke, so a slow
ingestion stalled all typing. Settle the callback once the placeholder
lands and track the rest as ImageAttachment.pending; the send path gives
a referenced pending ingestion a bounded wait (2s) so paste-then-Enter
still submits the compressed/daemon-ref form, and falls back to the
inline form when ingestion has not finished. Media-free submits stay
fully synchronous.

* fix(protocol): mirror prompt_id in the shared prompt submission schema

kap-server's local REST schema accepts a client-chosen prompt_id, but
the shared promptSubmissionSchema stripped it as an unknown key, so
clients validating through @moonshot-ai/protocol lost the id and the
turn.started promptId correlation never matched.

* fix(klient): normalize file-store errors to public RPC errors on both transports

The fileService save/get wire adaptation ran outside the dispatcher's
error normalization, so a stale or expired upload id surfaced as the
engine's raw Error2 on the memory transport and as a generic 50001 on
ipc. Map file.not_found to the public NOT_FOUND RPCError in the shared
dispatcher so both transports reject identically, and pin the parity in
the conformance suite.

* fix(agent-core-v2): keep launching media prompts visible in the queue snapshot

startNext shifts the launching record out of pending before its media
intake settles, so list()/GET /prompts reported neither an active nor a
queued prompt during the intake window even though the submission was
accepted and abortable. Report the launching record as still queued,
matching the prompt.queued event already published for it.

* fix(node-sdk): strip internal promptAttachments from SDK turn.started events

The in-process v2 event mapper forwarded the whole domain event, so SDK
session.onEvent consumers saw the transcript-projection-only
promptAttachments field that kap-server explicitly strips from the WS
wire event. Drop it in the mapper so both consumers share the same
turn.started field set.

* fix(kimi-code): align staging lease id multiplicity with retain count

A lease's flat id list conflated two cases: one submission referencing
the same image twice (one retain) and a batched steer merging two queued
messages sharing the image (two retains). Occurrence-wise release
over-consumed in the first case and batch-wise release would
under-consume in the second. Dedupe each extraction's ids at the lease
creation sites so list multiplicity always equals the retain count, and
release one retain per occurrence.

* fix(agent-core-v2): check video_in before honoring memoized video uploads

The video memo hit path returned a cached ms:// part before the current
model's capability check, so switching to a same-provider model with
video_in:false sent a video part the model cannot accept instead of
degrading to the path tag. Gate on capability first, mirroring the image
strategy.

* fix(kimi-code): keep recalled queued media staged instead of releasing it

Recalling a queued media prompt into the editor is not a discard, but
the recall path released the staged files: image attachments lost their
daemon upload (resubmit silently downgraded to inline), and a recalled
video's cache copy was deleted even though re-materialization needs a
source that may already be gone. Recall now consumes only the retain
(the next submit re-retains), retires the cache copy to session
lifetime, and rebases the video attachment onto that copy.

* fix(agent-core-v2): count launching media prompts in prompt.queued queueLength

startNext shifts the record into launchingItem before publishQueued
computes the count, so a media prompt's prompt.queued reported
queueLength 0 even though the prompt is accepted, abortable, and listed
as queued. Compute the count from the same snapshot list() exposes.

* refactor(agent-core-v2): drop the session media shared-cache fallback

Intake keeps the upload-backed reference when the canonical write fails
instead of double-writing into an unowned global cache scope; the session
media store's reads collapse to the canonical scope, and non-filesystem
deployments no longer write every media blob twice.

* refactor(agent-core-v2): stop persisting materialization paths in daemon file references

The kimi-file:// reference persisted in context memory bundled a durable
identity (fileId) with a perishable machine-local absolute path (?path=),
which forked sessions and home relocations would stale. The reference now
carries only the file id; the display path is derived from the session
media store by file id at read time. Parsers tolerate and strip the legacy
?path= query so old records keep resolving.

* fix(agent-core-v2): skip atomic-write temp siblings in session media by-id resolution

The fs backend stages atomic writes at <key>.tmp.<pid>.<hex> next to the
target key, and the media store's prefix-listing predicate matched them, so
a lookup racing an unfinished materialize could return the partial copy as
the canonical file.

* fix(kimi-code): close the staging-lease gap between extraction and dispatch

Create the staging lease right after extraction so every pre-dispatch exit
releases through the tracker: validation/session failures release it,
queueing defers it to the queue item's raw ids/paths, and the cache-hint
stash takes over ownership. A forgotten exit now degrades to an unclaimed
lease swept at session close instead of a permanently retained upload.

The cache-hint restore exits (dismiss, chained restore, session switch
during fetch, failed compact/new-session) previously returned only the
text to the editor, leaking the extraction's retains and staged cache
copies. They now go through queue-recall semantics: retains are consumed,
staged copies retire, and recalled videos rebase onto them.

* fix(agent-core-v2): bound the inline image memo with a private byte-budgeted LRU

A memoized inline image part pins a multi-MB base64 string, and the agent
state registry's snapshot/inspect path serializes every registered state
in full — so the memo no longer lives in agentState. It is now a private
per-file-id LRU with the existing 8MB per-entry cap plus a 64MB total
budget; eviction simply re-reads the bytes on the next request. The video
memo stays in agentState.

* fix(kap-server): fall back to the staged upload on the session media route

Prompt intake materializes bytes into the session media store
asynchronously and best-effort, but a session_media ref is projected to
clients as soon as the prompt is queued — so the download route could 404
during the intake window, and forever after an intake failure. The route
now reads the canonical session store first and falls back to the App-scope
staged upload, adapting it to the same served shape; only a double miss is
a 404. The header note also records that resolving the store resumes cold
sessions, an accepted short-term semantic with a TODO for a cold-read
channel.
2026-08-17 13:11:28 +08:00
7Sageer
157c84f5d1
docs: fix thinking-effort examples in configuration docs (#2988)
Some checks are pending
CI / test-vscode-legacy (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
The secondary-model variant example could not work as written: a bare
[models] entry does not inherit the provisioned entry's metadata, and
default_effort only takes effect when it is a member of support_efforts,
which the kimi-for-coding family does not declare. Base the example on
kimi-code/k3 with the full metadata copied, and state both prerequisites.

Also align the full-config example's k3 support_efforts with what /login
provisions (low/high/max, so the shown thinking effort "high" is valid),
and stop describing kimi-for-coding-highspeed as cheap: it is priced
higher, so its pool hint now steers toward latency-sensitive tasks.
2026-08-17 12:03:29 +08:00
Haozhe
04d23e2dab
fix(agent-core-v2): unify text/binary classification for UTF-8 multibyte files (#2972) 2026-08-17 11:05:33 +08:00
Luyu Cheng
44a6c70e66
feat(kimi-code): recognize multiple inline skill activations in one prompt (#2935)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* feat(kimi-code): recognize multiple inline skill activations in one prompt

Inline /skill: tokens are recognized anywhere in the prompt (after
whitespace, including on following lines) with completion, highlighting,
and de-duplication. Submitting goes through session.promptWithSkills, so
the engine bundles every activation into the prompt's own user message —
one turn, one undo anchor. Replay rebuilds the per-skill cards from the
prompt origin's skillActivations and shows only the caller's own parts in
the user bubble; undo removes the prompt together with its marked bundle
cards; hook results ahead of a bundle are projected inside its window.
Enter accepts an inline completion without submitting (pi-tui
inlineSlashTrigger), and cache-hint plus /btw pass activations through.

* fix(kimi-code): harden bundled skill submissions against review findings

- Mark bundle cards by entry id, not by index into a captured array: the
  transcript window trim may replace the entries array mid-call.
- The replay turn limiter no longer cuts between a bundled prompt and the
  hook results recorded immediately before it; the oldest visible bundle
  keeps its hook context.
- A leading-combo bundle (/skill:a args /skill:b) now queues while busy
  like any other inline-skill prompt, instead of being rejected by the
  single-skill slash gate.

* fix(kimi-code): fetch one extra replay turn on resume

The SDK trims the replay to the requested limit before returning it, so a
trim landing between a bundled prompt and its preceding hook results would
make them unrecoverable to the TUI-side limiter. Resume now fetches one
extra turn of margin; preserveBundleHookResults does the final cut without
losing the hook context.

* fix(pi-tui): retrigger inline slash completion as the token grows

When the terminal delivers `/rev` in one stdin chunk, the slash starts an
autocomplete request but the following letters arrived to a null
autocomplete state and — unlike a leading slash command — matched no
retrigger context, so the stale request was discarded and the menu never
appeared. Typing token characters inside an inline slash token now
retriggers completion (with a regression test). Also aligns the startup
resume tests with REPLAY_FETCH_TURN_LIMIT.

* fix(pi-tui): retrigger inline completion on later lines too

isSlashMenuAllowed confines the slash-command menu to the first line, so
reusing it for the inline-slash retrigger context silently disabled
retriggering on every later line — the bare-slash request went stale and
the menu never appeared. The inline context now covers a token-opening
slash on subsequent lines as well (with a regression test).

* fix(kimi-code): activate leading skill tokens in /btw and repeated-token combos

- /btw's initial prompt lives entirely in the slash arguments, so a skill
  token there sits at position 0; scan it with includeLeading so
  `/btw /skill:review …` actually activates the skill.
- Combo-ness is now decided by the raw inline token count rather than the
  deduplicated activation count, so `/skill:review check /skill:review`
  submits as a bundled prompt instead of falling through to the
  single-skill path with the repeated token swallowed into the args.

* fix(kimi-code): rewrite media placeholders in leading combo arguments

A leading combo's first activation carries the raw slash arguments, so a
pasted media placeholder in them reached the engine unresolved — unlike
the standalone sendSkillActivation path, which rewrites placeholders into
escape-proof plain-text file references first. sendInlineSkillUserInput
now rewrites any arg-carrying activation the same way (covering the busy
queue and /btw intercept paths too), while the media themselves continue
to ride the prompt as extracted parts.

* refactor(kimi-code): skill mentions never carry args in bundled prompts

Align bundled submissions with the mention model: two or more skill
tokens anywhere in the input (the leading one included) make one bundled
prompt in which every token activates by name only, and args stay a
standalone /skill:<name> args concept. This removes the leading combo's
command+args parsing, so the first skill's arguments can no longer leak
the next token (displayed as a duplicated prompt under its card), media
placeholders no longer need arg rewriting, and newline-separated bundles
behave exactly like space-separated ones (parseSlashInput's literal-space
separator no longer decides bundle-ness).

* fix(kimi-code): recognized builtin and plugin commands outrank the bundle rule

The no-args bundle rule claimed any input with two or more skill tokens
before checking what led it, so `/btw check /skill:a /skill:b` was
submitted to the main agent as a bundled prompt instead of opening the
side panel. The intent is now resolved first: builtin and plugin commands
always keep their own path regardless of how many skill tokens their
arguments mention, while skill-led and newline-led inputs still bundle as
before.

* fix(pi-tui): retrigger inline completion on colons and register the local divergences

External skill tokens are shaped /skill:<name>, but the inline-slash
retrigger character classes excluded ':' — typing the colon launched no
replacement request, the bare-slash request went stale, and the menu never
appeared for prefixed skill names. Colons now retrigger completion like
other token characters (with a regression test). Also registers the
inlineSlashTrigger and autocomplete-data divergences in the package's
re-vendor protection list.

* fix(kimi-code): preserve FIFO behind unsteerable bundles and reach indented inline completion

- Ctrl-S steering now stops at the first inline-skill bundle: a later
  queued message (or the editor draft) no longer jumps ahead of the
  unsteerable bundle into the running turn, so the conversational order
  survives steering.
- The leading-whitespace slash-path suppression now yields to the inline
  skill context first, so an indented token (`  /skill:rev`) completes
  like its column-0 equivalent instead of being suppressed as a path.
2026-08-17 00:09:18 +08:00
Luyu Cheng
61591bce09
feat(agent-core-v2): bundle multiple skill activations into one prompt submission (#2934)
* feat(agent-core-v2): support grouped multi-skill prompt submissions

Add IAgentSkillService.promptWithSkills: one or more skill activations
are validated up front (an unknown or empty submission rejects with no
side effects), recorded with a shared submissionId, and enqueued ahead
of the prompt through the prompt queue's messagesBefore support, so the
whole group materializes atomically as a single turn. Undo cuts, the
transcript projection, and the undo precheck treat the group as one
unit (stopping at the next anchor even when submission ids collide);
hook-result messages are skipped like injections during those walks.
Submit hooks run against every message of the group, and user-slash
skill activations count as user-submitted content for the UserPromptSubmit
hook's origin filter.

Surface it through the contract layers: protocol gains submissionId on
the user / skill_activation origins and on the skill.activated event
(kap-server zod mirrored), klient exposes agentSkillContract.promptWithSkills
with parity assertions, and the SDK grows session.promptWithSkills —
implemented on the v2 engine and rejecting loudly on the deprecated v1
engine, which is otherwise untouched.

* fix(agent-core-v2): reject empty skill lists in grouped prompt submissions

- Validate that promptWithSkills receives at least one skill, enforced in
  the engine and as a non-empty constraint in the klient wire schema.
- Restore the released versions and changelog sections for agent-core-v2,
  klient, and node-sdk that the branch cut had reverted.
- Move statement-level narration into the owning file headers per the
  package comment conventions.
- Align the hook-result undo tests with the reachable record ordering
  (hook results are recorded before the group materializes).

* refactor(agent-core-v2): bundle grouped skill activations into the prompt message

Replace the submissionId-correlated message group with a single bundled
user message: the rendered skill blocks precede the caller's parts in the
content, and every activation's metadata rides the prompt origin's new
skillActivations field. The bundle is one anchor by construction, so undo
needs no group-cutting logic and the messagesBefore prompt seam disappears;
the submit hook fires once per submission. skill.activated still fires per
skill (transient ops, live-only); resume rebuilds the per-skill view from
the prompt origin. Contract chain (protocol, kap-server, klient, node-sdk)
drops submissionId accordingly.

* fix(agent-core-v2): keep bundled skill blocks out of prompt-facing projections

- The transcript cold rebuild expands a bundled prompt's origin
  skillActivations back into per-skill markers (the live path already
  projects them from skill.activated events).
- turn.started.prompt, the session title excerpt source, and the fork
  lastPrompt now derive from the caller's own parts, excluding the
  rendered skill blocks the engine prepends to the bundled content.
- Drop the redundant undefined unions from the new origin fields.
- Move the activateSkill test narration into the file header.
2026-08-17 00:09:18 +08:00
Haozhe
84da6629b1
refactor(agent-core-v2): decouple workspace from session DI via runtime binding (#2961)
* refactor(agent-core-v2): decouple workspace from session DI via runtime binding

* fix(agent-core-v2): unblock session external hooks and scope workspaceMcp seeds

- externalHooksService: inject App-level ISessionManager instead of the
  unregistered ISessionLifecycleService so SessionStart/SessionEnd hooks
  actually activate in production; keep sessionId matching and tolerate
  absent lifecycle events
- workspaceMcpService: ignore onWillCreateSession events whose session
  belongs to another workspace, preventing cross-workspace
  ISessionMcpHandle seed overrides
- update externalHooks integration tests, agent harness, and workspaceMcp
  tests; add reloadSources coverage in skillCatalog tests

* fix(agent-core-v2): honor the bound runtime in prompt context, swarm spawn, and ACP sessions

- map system-prompt cwd, directory listing, and additional dirs through
  RuntimeWorkspaceView, and skip the listing when the bound runtime has
  no fs capability
- pass the caller agent's runtime binding to AgentSwarm child creation
  and prompt-prefix execution instead of hardcoding local
- expose the ACP client filesystem through the ACP session runtime and
  build its shell/path environment from the probed host instead of
  hardcoded Linux
- dispatch klient facade createChild to sessionManager.createChild so
  child sessions keep their parent markers

* fix(agent-core-v2): resolve routed fs and tool paths with runtime path semantics

- WorkspaceFsService resolves via the bound runtime's RuntimePath (extended with basename/dirname) instead of node:path, so mapped roots such as C:\\repo stay runtime-local.
- Read/Write/Glob/Grep pass skill roots through mapRoots via RuntimeWorkspaceView input, matching Edit.
- acp-server unbinds session runtimes on session/close, not only on delete.
- apps/kimi-code drops the /runtime slash command; SDK runtime methods stay.

* fix(agent-core-v2): retire idle session controllers, untrack disposed runtime resources, and rebuild fs watches on generation replace

* fix(agent-core-v2): resolve oxlint errors in runtime lifecycle fixes

* fix(kap-server): untrack download stream from runtime generation on completion

* fix(kap-server): drop meaningless void operator on tracked dispose
2026-08-16 20:24:12 +08:00
Haozhe
ee564e5ec9
fix(agent-core-v2): persist token counting ledger so resume restores measured context size (#2969)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
2026-08-16 19:31:31 +08:00
tpoisonooo
f492cd7c9e
feat(agent-core): add tower command to orchestrate multi-agents (#2633)
* feat(packages): implement cowork

feat(packages): update throttle control

feat(agent-core): rename to /tower

feat(agent-core-v2): support tower mode

fix(packages): keep tower teardown from stranding submodule worktrees

A plain `git worktree remove` refuses worktrees containing initialized
submodules even when they are clean, so tower teardown silently left
behind exactly the worktrees whose workers had run builds (the failure
only reached the tool report, never the activity log).

The dirty check is the data-loss gate; once it passes, removal always
passes --force (harmless on a clean worktree, and precisely what
bypasses git's submodule refusal). Kept and failed removals now also
land in the activity log as worktree.keep / worktree.remove.failed.

feat(packages): allow the tower to AskUserQuestion, workers still cannot

The tower-mode AskUserQuestion deny only ever fired on the tower itself:
workers never enter tower mode, and their tower-worker profile simply
does not list the tool. Drop the deny so the tower can clarify
requirements with the human up front; workers and reviewers stay
ask-less and escalate via TowerSend. Auto permission mode still
disables AskUserQuestion for everyone.

fix(agent-core-v2): import LifecycleScope from #/app/scopes

main moved the enum out of #/_base/di/scope; follow the new location in
the two tower services.

test(agent-core-v2): refresh fullCompaction token expectations

main's #2699 counts compaction tokens on the full-request basis, so the
tower tool schemas (default registry) and the /tower skill catalog entry
(system prompt) shift the pinned numbers: +2789 with the default tool
set, +173 with the explicit harness tool list. The 20k-window test keeps
its shape with a 22k window so the post-compaction floor still fits.

feat(agent-core-v2): tower command support secondary model

fix(tower): disable todo-list tool

feat(tower): reviewer keep primary model

fix(tower): tower worker call for authroization

update

* refactor(tower): drop agent-core-v1 version

* feat(tower): remove builtin.ts

* fix(agent-core-v2): verify the recorded base branch before tower merges

* fix(agent-core-v2): activate tower missions only after a successful spawn

* chore(kap-server): correct the search-service activation comment

* fix(tower): allowActivationWhileBusy for all skill

* update

* update

---------

Co-authored-by: konghuanjun <konghuanjun@moonshot.ai>
2026-08-16 15:13:42 +08:00
bj456736
6b72345f8b
feat(tui): print the fork resume command and copy it to the clipboard (#2940)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* feat(tui): print the fork resume command and copy it to the clipboard

* fix(tui): use pushd in the Windows fork resume command so it switches drives

cmd.exe's `cd` only updates the target drive's remembered directory, so a
terminal on another drive would run `kimi --resume` in the wrong working
directory. `pushd` switches drive + directory in both cmd.exe and
PowerShell (`cd /d` would break PowerShell). Addresses the Codex review
comment.

* fix(tui): label OSC 52 clipboard delivery as unverified after fork

copyTextToClipboard falls back to an OSC 52 escape when no native
clipboard provider works; terminals without OSC 52 support silently
drop the sequence, so only native delivery may claim success. Matches
the wording convention of /copy. Addresses the Codex review comment.

---------

Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
2026-08-15 14:09:43 +08:00
Luyu Cheng
d96cd03770
fix(cli): pre-send warning and clearer error for over-long /goal objectives (#2928)
Some checks are pending
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* fix(cli): warn on over-long /goal objectives before sending and keep the input

- Show a live footer warning in the TUI while a typed /goal objective
  exceeds the 4000-character limit, measuring paste-expanded text only
  when the input can be a /goal command.
- Restore the rejected /goal input into the editor instead of losing it.
- Include the file-reference workaround in the GOAL_OBJECTIVE_TOO_LONG
  error messages (TUI, goal queue, agent-core, agent-core-v2).

* fix(cli): keep the /goal length warning in its own footer slot

A transient hint (exit confirm, detach, image paste) that displaced the
warning previously left the footer blank after clearing, because no
editor change re-applied it. The footer now renders the warning from a
dedicated slot whenever no transient hint is active, so the warning
returns on its own.

* fix(cli): gate the /goal length warning on trimmed text

Submitted text is trimmed before slash-command dispatch, so leading
whitespace still runs /goal — normalize with trimStart in the gate and
in the length check to match.

* fix(cli): restore input rejected by the slash-command busy gate

An idle-only command submitted while streaming/compacting was rejected
after the editor buffer had already been cleared, losing hand-typed
input (e.g. an over-long /goal objective that never reached the local
validation).

* fix(cli): restore input at the post-creation busy re-check

The lazy-session race rejects an idle-only command after a first prompt
has already started a turn; the editor buffer is long cleared by then,
so give the submitted input back like the dispatch blocked branch does.

* fix(cli): close the remaining input-loss and gate gaps around /goal

- Restore the submitted input when lazy session creation fails before a
  session-requiring command runs.
- Restore only into a still-empty editor after async gates, so a draft
  typed while creation was pending is never overwritten.
- Expand pastes that can complete a partially typed /goal command
  (e.g. /go[paste #1 …]) in the length-warning gate.

* fix(cli): never displace newer UI state with a delayed input restore

A session-less /goal submission restores its input only after an async
gap (lazy session creation). If the user opened an editor-replacement
panel meanwhile, restoring would tear it down (and leave activeDialog
inconsistent). Track editorReplacementMounted in TUIState and gate all
delayed restores through canRestoreSubmittedInput.

* refactor(cli): move canRestoreSubmittedInput into commands/resolve

Avoids the goal.ts <-> dispatch.ts runtime import cycle flagged by
import/no-cycle; the helper takes a structural host shape instead.

* fix(cli): match the slash parser's delimiter in the /goal length warning

parseSlashInput splits the command name at a literal space only, so a
newline or tab after /goal dispatches as a plain message — the warning
must not fire for inputs the dispatcher will not treat as a goal.
2026-08-15 02:55:33 +08:00
qer
a23680e293
docs(changelog): sync 0.36.1 from apps/kimi-code/CHANGELOG.md (#2926) 2026-08-14 21:56:20 +08:00
github-actions[bot]
13d86f8b7b
ci: release packages (#2881)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-14 20:51:17 +08:00
qer
d60d8ff7e8
chore: downgrade plan viewer changeset from minor to patch (#2923) 2026-08-14 20:46:50 +08:00
qer
cd489955bb
chore: sync web dist from code-app (#2922)
code-app: af7ed8fa03278bbe2f988732b3195649e7a6f2bc
2026-08-14 20:36:54 +08:00
qer
6cf315b7bd
fix(pi-tui): stop GFM autolinks at CJK punctuation boundaries (#2917)
* fix(pi-tui): stop GFM autolinks at CJK punctuation boundaries

marked's GFM autolink accepts any non-space characters after the domain
and its backpedal strips only ASCII trailing punctuation, so CJK or
full-width punctuation right after a bare URL was absorbed into the link
text and href (`.../pull/232(本地` rendered as one anchor whose OSC 8
target contained raw CJK and opened a broken address).

Register a CjkBoundaryUrlTokenizer (subclass of the upstream
StrictStrikethroughTokenizer, which stays byte-identical for
re-vendoring) that cuts the autolink match at the first CJK punctuation
character before the ASCII backpedal. CJK ideographs inside the URL path
itself are preserved. Guarded by new bare-URL CJK cases in
test/markdown.test.ts and listed in pi-tui's local-divergence inventory.

* fix(pi-tui): keep balanced full-width parens inside autolinked URLs

Address review feedback on the CJK autolink boundary: cutting at the
first full-width parenthesis anywhere in the match also truncated URLs
that legitimately contain balanced full-width parens in their path
(e.g. wiki disambiguation pages like .../wiki/中华人民共和国(1949年)).

Full-width parens now follow GFM's ASCII-paren rule: a paren-depth scan
keeps balanced pairs in the URL and only an unbalanced ( or )
terminates the match. Non-paren CJK punctuation still always terminates
it.

* fix(pi-tui): keep CJK punctuation inside balanced full-width parens

Punctuation inside a balanced full-width parenthetical is deliberate URL
content (e.g. .../wiki/中华人民共和国(北京,1949年)), so the non-paren
CJK terminator now only applies at paren depth 0. Prose parentheticals
contain spaces and never survive marked's match this far, and an
unbalanced ( still cuts the match at the open paren.
2026-08-14 20:15:33 +08:00
Grapedge
7475c2e2e3
feat(vscode): switch the extension to the v2 engine with a rollback switch (#2916)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
The extension now runs on the agent-core-v2 engine by default. The
interface, sessions, and workflows do not change. Two rollback paths
exist, and one function makes the decision
(config/vscode-settings.ts):

- the kimi.useAgentCoreV1 setting (temporary; a window reload applies
  the change);
- the KIMI_CODE_LEGACY_FLAG environment variable, which wins over the
  setting and has the same semantics as in the CLI.

An engine startup failure shows an explicit error that names the
rollback setting. There is no silent fallback. CI runs the extension
test suite on both engines: the sharded run covers the default v2
engine, and a new test-vscode-legacy job reruns the suite with
KIMI_CODE_LEGACY_FLAG=1.

To keep the v2 path identical to v1 for every method the extension
uses, this change also completes the v2-backed SDK client and the v2
engine:

- Implement session deletion in the v2 SDK client.
- Implement fork truncation at a turn index in the v2 engine, with the
  same rules as v1, and reject a fork while the source session has an
  active turn.
- Stop the session-level /init run when the turn is cancelled, as v1
  does.
- Read session metadata without the archived field as not-archived, so
  sessions written by the v1 engine open correctly.

The SDK parity suite now covers session deletion, cancel, and fork
truncation. The known-difference list for the methods the extension
uses is empty.
2026-08-14 17:22:10 +08:00
qer
741708f948
feat(kap-server): add plugin marketplace and capability REST routes (#2868)
* feat(agent-core-v2): surface a machine-key note from capability installs

CapabilityEntry.install now resolves an optional note exposed through
CapabilityInstallProgress.note (wire-visible). The webbridge entry
returns 'user-skill-migrated' when it migrates a pre-existing
standalone skill copy onto the plugin-managed one — clients can
localize the migration instead of the skill silently disappearing
from the user's directory.

* feat(kap-server): add plugin management and capability REST routes

Expose the App-scope plugin and capability services over the wire so
non-CLI hosts (desktop, web) can manage plugins and built-in
capabilities end to end:

- GET  /api/v1/plugins, POST /api/v1/plugins {source},
  POST /api/v1/plugins/{id}:{enable,disable,remove}
- GET  /api/v1/plugins/marketplace — catalog (pluginMarketplaceUrl
  server option / KIMI_CODE_PLUGIN_MARKETPLACE_URL env / production
  default) merged on demand with live install state; updateAvailable
  only on strict semver catalog > installed (no semver dependency)
- GET  /api/v1/capabilities, GET /api/v1/capabilities/{id},
  POST /api/v1/capabilities/{id}:install with client-polled progress
- New wire codes 40418 capability.not_found, 40419 plugin.not_found,
  40923 capability.install_in_progress, 40924 capability.unsupported

Mutations flow through IPluginService, so they serialize with other
install paths and fire onDidReload (session skill catalogs and the
capability shelf-install hook converge).

* fix(kap-server): map plugin input errors to 4xx and correct the unsupported test code

- mapPluginError now translates the domain's validation.failed (40001)
  and fs.path_not_found (40409) instead of collapsing client-fixable
  input mistakes (relative source, nonexistent local path) into a
  50001 internal error
- the non-macOS capability install test expected 40923, which this
  branch assigns to capability.install_in_progress; the unsupported
  code is 40924 (macOS runners skip the case, which is why it only
  fails on Linux/Windows CI)

* fix(kap-server): resolve catalog-relative marketplace sources and widen the unsupported-test skip

- The production CDN catalog carries sources relative to the catalog
  URL (./official/*.zip); clients handing them back to POST /plugins
  would hit the local-path normalizer's 40001. Resolve entry sources
  against the configured catalog URL so every returned source is
  directly installable.
- The 40924 install-rejection test only skipped macOS, but kimi-cu is
  also supported on Windows x64 — running it there would start the
  real installer. Skip on every supported platform.

* fix(kap-server): accept the legacy url/downloadUrl marketplace source aliases

Custom catalogs that the CLI already accepts can carry an entry's source
under url or downloadUrl instead of source; the route's strict schema
rejected the whole catalog with 50001. Normalize the aliases before
validation (same precedence as the CLI parser) so those catalogs keep
working through /api/v1/plugins/marketplace.

* fix(kap-server): support local marketplace catalogs and drop conditional spreads

- KIMI_CODE_PLUGIN_MARKETPLACE_URL accepts a plain path or file://
  catalog in the CLI loader; the route only fetched over HTTP, so local
  catalogs 50001'd for desktop/web hosts. Read local catalogs from disk
  and resolve their relative sources against the catalog's directory.
- Replace the marketplace mapping's conditional spreads with direct
  possibly-undefined properties per the repo rule.

* fix: surface capability install notes through klient and convert file:// entry sources

- The klient capabilities contract omitted install.note, so zod parsing
  stripped it and facade callers (node-sdk, TUI) never saw
  'user-skill-migrated'. Add the field and pin it in the facade test
  fixture.
- A marketplace entry source given as a file:// URL fell through to the
  relative-branch and came back as a garbage path; convert with
  fileURLToPath so the advertised source stays installable.

* test(kap-server): keep the new route tests portable to Windows x64

- The capabilities list assertion treated every non-macOS host as
  unsupported, but kimi-cu is supported on Windows x64 — derive the
  expectation from the same platform predicate.
- file:///abs/... is not a valid absolute file URL on Windows (no drive
  root); build the fixture with pathToFileURL from a temp path instead.

* refactor: align the capability note and test helper with repo conventions

- agent-core-v2 keeps explanatory docs in the top-of-file block only;
  the note contract already lives in the capability types header, so
  drop the two member-level doc blocks.
- The plugins route test helper sets the optional fetch body directly
  instead of via a conditional spread.

* fix(kap-server): expand ~ in local marketplace catalog paths

The CLI loader expands ~/ against the home directory; the route read
the path literally, so KIMI_CODE_PLUGIN_MARKETPLACE_URL=~/catalog.json
50001'd for desktop/web hosts while working in the CLI. Share one
localCatalogPath helper (file:// conversion + tilde expansion) between
the catalog read and the relative-source resolver.

* fix(kap-server): expand home-relative marketplace entry sources

A catalog entry with source '~/...' fell through to the catalog-relative
branch and came back as <catalog-dir>/~/... — unresolvable by POST
/plugins. Expand ~ via the shared helper before the absolute/relative
decision.

* fix(kap-server): match CLI field semantics for source aliases and stub the Windows home

- A blank or non-string source no longer shadows the url/downloadUrl
  aliases; the first valid (non-blank, trimmed) of source/url/downloadUrl
  wins, mirroring the CLI parser's stringField.
- The tilde test also stubs USERPROFILE so os.homedir() resolves to the
  fixture home on Windows runners.

* fix(kap-server): read a blank marketplace tier as missing

The CLI parser trims tier and treats a blank as absent (third-party);
the route's enum rejected the whole catalog with 50001. Normalize the
tier alongside the source aliases in the same preprocess.

* fix(kap-server): derive marketplace versions from GitHub release sources

Entries that omit version but encode it in a GitHub release/tag (or
tree/commit) source never surfaced updateAvailable. Derive the version
from the resolved source — same URL shapes as the CLI parser, validated
with the route's strict x.y.z rule (no semver dependency).

* fix(kap-server): fail catalog validation on a source with no usable value

A whitespace-only source with no valid alias passed z.string().min(1)
untrimmed and resolved against the catalog URL into nonsense. Drop the
key during normalization so the schema reports the entry as missing its
source (same outcome as the CLI's 'must define source').

* fix(kap-server): resolve latest versions for bare GitHub marketplace entries

A catalog row whose source is a bare GitHub repo (the production curated
rows are shaped this way) kept version undefined, so updateAvailable
never fired for exactly the entries most likely to update. Resolve the
latest release tag through the /releases/latest redirect — the UI route,
not the rate-limited API — same as the CLI, degrading to no version on
any failure.

* docs(kap-server): note the marketplace version resolution in the plugins route header

* feat(kap-server): mark capability wiring rows in the marketplace response

A client following only /plugins/marketplace + POST /plugins would
install a capability's wiring plugin without its binary runtime, with
no wire-level way to tell. Entries whose id matches a capability's
wiring plugin now carry capabilityId, so clients route them through
/capabilities/{id}:install — the client-side routing pattern the CLI
established (the upstream design that replaced the server-side hook).

* fix(kap-server): fall back to the source-checkout catalog for the default location

When the marketplace location is the built-in default (no server option
or env override) and the fetch fails, read the repo checkout's own
plugins/marketplace.json — the CLI loader's behavior for offline
source-checkout dev. An explicitly configured catalog still fails hard
with 50001. Bundled installs have no checkout file, so the fallback
simply never fires there.

* fix(kap-server): resolve fallback catalog sources against the fallback file

readMarketplaceCatalog returned only the JSON, so entries from the
source-checkout fallback resolved their relative sources against the
(unreachable) CDN URL — coming back as unusable https paths instead of
local directories. The reader now returns the location actually read,
and source resolution uses it.

* fix(kap-server): honor the CLI's marketplace metadata aliases

Custom catalogs using name / shortDescription / websiteURL (accepted by
the CLI parser) lost those fields to schema stripping, falling back to
the entry id. Normalize the aliases in the same preprocess as the
source/tier normalization.

* fix(kap-server): filter marketplace keywords instead of rejecting the catalog

A keywords array with non-string or blank members failed the strict
schema and took the whole catalog down with 50001. Normalize to the CLI
parser's semantics: non-array reads as missing, arrays keep trimmed
non-blank strings only.

* fix(kap-server): treat a blank or non-string marketplace version as missing

The CLI parser reads version through its lenient stringField and falls
through to source-derived versions; the route's schema rejected a
numeric version with 50001 for the whole catalog. Normalize version in
the preprocess like the other fields — the gh-plugin fixture now
carries a numeric version and still derives 2.0.0 from its tag source.

* fix(kap-server): trim marketplace entry ids before the install-state join

A whitespace-padded id survived validation raw and never matched the
installed records (updateAvailable silently lost). Normalize the id in
the preprocess — trimmed, blank rejected — matching the CLI's
requiredString.

* fix(kap-server): gate capability markers to the default catalog

A custom catalog (env or server option) may legitimately carry a
same-id fork of a capability's wiring plugin; marking it capabilityId
would route users to the built-in install. Apply the marker only for
the default catalog (including the source-checkout fallback), matching
the CLI injecting built-in rows only for the default catalog.

* fix(kap-server): compare marketplace versions with real semver

The hand-rolled strict x.y.z check rejected valid semver the CLI
accepts (v-prefixed, prerelease tags), so updateAvailable diverged
between CLI and wire clients. Take the semver package (already in the
monorepo via the CLI) for the update check and the two source-derived
version validators.

* fix(kap-server): validate marketplace entry types and count the dev server as default

- Custom catalog rows with an unsupported type (e.g. integration) were
  stripped by the schema and advertised as installable plugins; the CLI
  rejects the catalog outright. Model the same plugin/managed/guide
  vocabulary.
- scripts/dev.mjs marks its repo-owned catalog with
  KIMI_CODE_PLUGIN_MARKETPLACE_FROM_DEV_SERVER=1 — honor the flag in
  the isDefault check so capability markers and the checkout fallback
  behave exactly like the CLI under the dev marketplace.

* fix(kap-server): join capability rows through their platform wiring plugin id

kimi-cu installs its wiring plugin as kimi-cu-win on Windows x64, so a
catalog row keyed kimi-cu never matched the installed record there (no
installed state, no updateAvailable). The row mapping now knows each
capability's wiring plugin ids and joins through them.

* fix(kap-server): map plugin load failures to 40001

An install source pointing at a directory/zip with a missing or invalid
manifest throws plugin.load_failed — a client-fixable input error that
fell through to 50001. Map it to validation.failed alongside the other
input mistakes.

* build(kap-server): align @types/semver with the workspace version

sherif rejects multiple workspace versions of one dependency; the CLI
pins @types/semver at ^7.7.0.

* refactor(agent-core-v2): share the plugin marketplace client/parser across hosts

The kap-server marketplace route grew its own copy of the CLI's catalog
loading/parsing logic (lenient aliases, blank-means-missing fields,
source resolution, GitHub version derivation) — two implementations of
a public, hand-writable format would drift on every catalog change.
Move the read/parse/version machinery into the plugin domain as
app/plugin/marketplace (pure functions, no DI): the CLI keeps a thin
wrapper owning configured-source resolution and its checkout fallback,
and the route keeps only the wire concerns (install-state merge,
capabilityId markers, error envelopes). plugins.ts drops ~230 lines of
duplicated machinery.

One deliberate behavior fix rides along: tilde entry sources now expand
against the home directory at parse time (the CLI previously passed
them through literally, failing later at install validation).

* docs(agent-core-v2): fold the marketplace module's member docs into the file header

The package convention keeps explanatory comments in the top-of-file
block only; the moved parser carried several function/member-level
JSDoc blocks from its CLI home. The header now carries the format
contract, leniency rules, source/version resolution order, built-in
masking semantics, and the fallback gating rule.

* docs(agent-core-v2): drop the remaining statement comments in the marketplace module

The header carries the rationale (update semantics, GitHub ref shapes,
the releases/latest choice); the convention allows nothing beside
statements.

* fix(kimi-code): import the shared marketplace module by its deep path

constant/app.ts is evaluated on every CLI invocation; re-exporting from
the agent-core-v2 root would pull the whole engine module graph into
startup. The package's wildcard subpath export lets both CLI files take
only the pure marketplace module (node builtins + semver).

* feat(kap-server): fan plugin and capability lifecycle out as global WS events

Clients currently poll the plugins/capabilities REST surfaces and can
hold stale rows while another client mutates the set. Publish two global
events instead:

- event.plugin.changed — fired off IPluginService.onDidReload, so any
  install/enable/disable/remove from any client reaches every host
- event.capability.changed — every capability install progress
  transition (CapabilityService gains onDidChangeInstall), so rows
  update live and settle is observable without polling

Both ride the existing global fan-out (no subscription needed) and are
documented in the wire schema registry.

* fix: register the lifecycle events in the wire union and tidy the contract header

- event.plugin.changed / event.capability.changed were declared but not
  part of agentEventSchema, leaving the wire catalog incomplete.
- The onDidChangeInstall member doc moves into the capability contract
  file header (package comment convention).

* feat(protocol): mirror the plugin/capability lifecycle events in the shared WS schema

Clients and e2e harnesses validating server frames against
@moonshot-ai/protocol would reject event.plugin.changed /
event.capability.changed. Register both in the shared catalog (TS
interfaces, zod schemas, and both unions), matching the
model_catalog.changed precedent for global events.

* fix(kap-server): prefer the platform wiring plugin when joining capability rows

A stale same-id record (e.g. a raw kimi-cu plugin next to the real
kimi-cu-win wiring on Windows x64) previously won the join, showing the
wrong installed state and update availability. Capability rows now join
through the wiring plugin ids in platform preference order before
falling back to the catalog id.

* fix(kap-server): put the github metadata of plugin summaries on the wire schema

GitHub-sourced plugin summaries carry github {owner, repo, ref,
installedSha} from the domain; the route serializes raw domain objects,
so the field reached clients undocumented. Declare it in
pluginSummarySchema so the OpenAPI surface matches reality.

* test(node-sdk): cover the new lifecycle events in the exhaustive switch

The event-type exhaustiveness test broke when the shared protocol union
gained event.plugin.changed / event.capability.changed.

* fix(kap-server): mark capability progress events volatile

Per-chunk download progress transitions ride the same fan-out as
durable frames and were being persisted to the __global__ journal —
hundreds of stale frames per install. event.capability.changed is
live-only state, so it joins the volatile list alongside
event.di.unit_changed; the settle frame stays recoverable via a direct
capability read. event.plugin.changed remains durable (rare, and a
reconnecting client should replay it).

* feat(kap-server): inject built-in capability rows into the default catalog response

The checked-in production catalog carries kimi-webbridge but not
kimi-cu — the CLI injects built-in rows client-side, so wire clients
never saw Kimi Computer Use in /plugins/marketplace. For the default
catalog the route now appends supported capabilities the catalog lacks
(static descriptors via ICapabilityService.describeCapabilities — no
detector probes), marked with capabilityId and a capability:<id>
sentinel source so installs still route through the capability
surface.

* fix(kap-server): run injected capability rows through the install-state join

The injected kimi-cu row hardcoded installed: undefined, so an
already-installed capability still read as installable. Injection now
happens before projection, so injected rows get the same backing-plugin
join (installed state, update badge, capabilityId marker) as catalog
rows. Also moves the describeCapabilities note into the contract header
(package comment convention).

* test(kap-server): gate the injected-row assertions on platform support

kimi-cu injects only where supported (macOS / Windows x64); on Linux CI
the row is correctly absent.

* fix(protocol): classify capability progress as volatile in the shared catalog

kap-server never journals event.capability.changed (it is in the
server-local volatile list); shared-protocol clients reading
isVolatileEventType would treat per-chunk progress frames as durable
and replayable. Mirror the classification.

* fix(kap-server): hide capability rows on unsupported platforms

Catalog-carried capability rows (kimi-webbridge in the default catalog)
were marked with capabilityId regardless of host support — on an
unsupported platform clients would route into an impossible capability
install. Rows whose capability is unsupported are now excluded from the
default-catalog response entirely (the CLI hides its built-in rows the
same way).
2026-08-14 15:45:34 +08:00
7Sageer
249d8faa34
fix(agent-core-v2): mint interaction ids engine-side (#2911)
* fix(agent-core-v2): mint interaction ids engine-side

Self-hosted OpenAI-compatible endpoints may renumber tool call ids on
every response (Bash_0, Bash_1, ...). The approval/question/user_tool
facades used the provider toolCallId as the interaction id, so a
repeated id was silently swallowed by client-side pending-interaction
dedupe: the approval prompt never appeared and the turn parked
forever (#2908).

Interaction ids are now minted by the engine (approval_<uuid> /
question_<uuid> / user_tool_<uuid>); the provider toolCallId stays on
the payload for correlation. This matches v1 semantics, where the
approval id was already a daemon-minted id independent of the tool
call id.

* fix(agent-core-v2): normalize duplicate provider tool call ids at ingestion

Self-hosted OpenAI-compatible endpoints may renumber tool call ids on
every response (Bash_0, Bash_1, ...), and every downstream keying
assumes an id identifies exactly one call: context rebuild silently
drops the second tool result with a duplicated id, the strict
projector discards duplicate calls, transcript frames merge, and
approval/activity correlation misfires.

A per-agent ToolCallIdNormalizer in the llmRequester stream boundary
now tracks ids already claimed (seeded from the restored context).
The first occurrence passes through unchanged; later occurrences —
across responses or within one — are rewritten to a readable
<id>__<n> suffix, kept consistent between streamed deltas and the
finalized message, and logged for provenance. A failed attempt rolls
its claims back so a projection retry re-streams the same logical
calls under the same ids.

* fix(agent-core-v2): thread the minted approval id through events and status

The permission.approval.requested/resolved events only carried the
provider toolCallId, so AgentActivityView exposed approvalId =
toolCallId and the agent.status.updated approval phase forwarded an id
that POST /sessions/{sid}/approvals/{id} cannot resolve — the kernel
parks under the minted approval_<uuid>.

Mint the interaction id at the agent call site and include it in the
approval request payload: the kernel honors the explicit id, the
events carry it, and the activity view keys pendingApprovals by it
(falling back to the toolCallId for id-less events).

* fix(agent-core-v2): surface minted interaction ids in facade listPending

The approval/question facades returned only the original payload from
listPending(), so once the kernel id stopped deriving from the
provider toolCallId, hosts listing pending requests had no id to feed
back into decide()/answer()/dismiss() without reaching into the
kernel. Merge the parked interaction id into each returned request —
the klient contract schemas already carry the optional id field, so
the RPC surface becomes round-trippable as well.
2026-08-14 14:47:00 +08:00
weiwei Wang
53909d91e3
fix(kimi-web): cache content-hashed assets (#2865) 2026-08-14 13:08:30 +08:00
Haozhe
cb30a7799d
fix(kap-server): expose parent_tool_call_id and subagent_type in /tasks responses (#2912) 2026-08-14 13:03:56 +08:00
Haozhe
eb72aebeeb
fix(kap-server): remove the 64 MiB web session export limit (#2910) 2026-08-14 11:48:56 +08:00
Haozhe
325913a532
feat(kap-server): expose the subagent registry id in /tasks responses (#2907) 2026-08-14 11:28:07 +08:00
Louis Gu
245e3d56a6
fix(tui): sanitize background task output (#2863)
Co-authored-by: liruifengv <liruifeng1024@gmail.com>
2026-08-14 11:19:27 +08:00
oocz
102984aa66
fix: settle cancelled MCP OAuth callbacks (#2899)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Co-authored-by: yuchengzhen <yuchengzhen@moonshot.cn>
2026-08-13 22:56:06 +08:00
Haozhe
1414d46028
refactor(agent-core-v2): fold session lifecycle hooks into sessionLifecycle events (#2896) 2026-08-13 21:03:51 +08:00
7Sageer
5857ba23b0
test(kap-server): deflake three timing-sensitive tests (#2894)
* test(kap-server): poll the read-model immediate-read assertions

The 'prepares the read model at boot and serves immediate reads' test
sampled the session list / workspace session_count / paged read exactly
once after creating a session. While a mirror flush is in flight its
batch is only per-shard atomic and the pending-queue cleanup is not
linearized with reads, so a single-sample read landing inside that
window can transiently miss or double-count the new session (seen
twice on main CI as 'expected false to be true' and 'expected 0 to be
1'). Poll with vi.waitFor instead; the transient lasts at most one
in-flight flush (~100ms cadence).

* test(kap-server): retry the transcript test temp-dir teardown rm

The engine's file log writers flush synchronously on scope dispose but
their trailing async close can still create a file under the test home
after server.close() resolves, so the afterEach rm occasionally fails
with ENOTEMPTY on a loaded CI runner. Retry the rm (maxRetries: 5),
matching the existing pattern in questions.test.ts / fs.test.ts.

* test(kap-server): drain the in-flight search sync before appending

The 'serves the published generation without waiting for a blocked
background sync' test appended the delta right after a warm-up search
that had kicked a fire-and-forget background sync pass. On a starved
CI worker thread that pass can read the file after the append and
publish both documents early ('expected 2 to be 1'). settleSync before
the append makes 'no pass can index the delta' structural.
2026-08-13 21:02:34 +08:00
7Sageer
0473b3aac1
test(minidb): deflake the evict-lru compaction-churn guard (#2892)
The stress test asserted stats.compactions > 0 immediately after the
write loop, but auto-compaction is fire-and-forget through the
maintenance scheduler and the counter only increments once a run fully
completes. On a loaded CI runner the loop can finish before the first
compaction lands, failing the guard even though nothing is broken.

Wait for the first completed compaction with the existing waitFor
helper instead: the guard still proves the churn this scenario
requires happened, and a genuinely broken auto-trigger now fails via
the wait timeout.
2026-08-13 21:00:56 +08:00
Haozhe
67e73f3e76
refactor(agent-core-v2): extract date change feature (#2895)
Move date-change reminders behind the Feature lifecycle and make state registrations disposable so unloading removes the runtime seed.
2026-08-13 20:58:58 +08:00
7Sageer
c60e3e301d
docs: drop legacy secondary-model content and unify subagent terminology (#2891)
- Remove the legacy-engine secondary-model recipe section, the
  KIMI_SECONDARY_MODEL / KIMI_SECONDARY_EFFORT env entries, and the
  model_preference agent-file field: the default engine never reads
  them and the legacy engine is deprecated.
- Remove the backward-compat note for a lone [secondary_model] model
  key; the code still reads it, but the docs now only document the
  current pool scheme.
- Reframe the secondary_model section around the subagent model pool
  instead of a singular secondary model.
- Unify zh terminology: 子 Agent -> subagent, 主 Agent -> main agent,
  covering prose, headings, anchors, the sidebar label, and the
  docs/AGENTS.md term table.
2026-08-13 19:57:46 +08:00
Haozhe
4425409cea
fix(features): retract contributed service metadata (#2886)
* fix(features): retract contributed service metadata

- tie contributed service discovery to feature disposal
- reject duplicate providers for the same scope and service
- cover feature unload and debug channel resolution

* test(features): preserve contributed service registry

- remove the global contributed-service test reset
- keep provider cleanup local to each regression test

* fix(features): scope service discovery to each app

- store feature service metadata in the app-local collection tree
- bind debug lookup and test overrides to the owning app root
- keep duplicate provider activation atomic within one app
2026-08-13 19:13:00 +08:00
liruifengv
4a93f70aa2
feat(oauth): add browser-safe ./device subpath export (#2885)
Some checks are pending
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* feat(oauth): add browser-safe ./device subpath export

* fix(oauth): guard env override lookup for browser consumers

* chore(oauth): add changeset for ./device subpath export

* fix(oauth): resolve env overrides via globalThis for DOM-only consumers
2026-08-13 18:26:10 +08:00
liruifengv
1811bd4baf
fix(tui): keep banner main text readable with long tags on narrow terminals (#2884)
* fix(tui): keep banner main text readable with long tags on narrow terminals

The banner layout inlines the tag and wraps the main text into the
remaining width. Remote banner configs can set a full-sentence tag
(e.g. the 38-char K3 thinking-effort banner), which on narrow terminals
leaves the main text only a few columns, so it wraps into a ragged,
hard-broken column ("balan/ce", "capab/ility").

When the inline tag would leave the main text fewer than 16 columns,
render the tag on its own line and give the main text and subtext the
full width, aligned with the tag text. Short tags stay inline; tags
wider than the terminal are still dropped as before.

* chore: add changeset for banner narrow-terminal fix

---------

Co-authored-by: Mira <mira-bot@moonshot.cn>
2026-08-13 18:12:46 +08:00
Haozhe
4739284fb9
refactor(features): extract session init feature (#2887)
- move the session init domain under features
- contribute the session service through SessionInitFeature
- cover feature withdrawal and restoration
2026-08-13 18:12:08 +08:00
7Sageer
6be26978b1
feat: auto-generate session titles via the managed chat_title tool (#2351)
* feat: auto-generate session titles via the managed chat_title tool

With the auto-title experimental flag on and a managed OAuth login, the
session title is generated from the first prompt, replacing the
truncated-prompt easy title. A custom title set by the user is never
overwritten, and generation failures degrade silently to the easy title.

- oauth: fetchChatTitle for the platform /tools chat_title method
- agent-core (v1): fire-and-forget generation on the first prompt
- agent-core-v2: sessionTitle domain watching the easy-title event
- kap-server: POST /sessions/{id}/title/generate for manual regeneration

* fix: harden auto-generated session titles

* fix: preserve managed title request headers

* Pair auto-title endpoint overrides with matching OAuth credentials

* fix: preserve legacy custom session titles

* fix: preserve automatic session title invariants

* refactor: keep only the on-demand session title generation interface

Drop the automatic wiring on both engines: the v1 (TUI) first-prompt
trigger and the v2 easy-title event watcher. SessionTitleService's
generateTitle() stays as the single on-demand entry point behind the
auto-title flag, backing the kap-server title/generate route. The
changeset goes away too: with no shipped consumer, the remaining
surface is not user-perceivable.

* feat: generate session title from the first recorded prompts

Record up to three sanitized natural-language prompts in session
metadata (skill / plugin activations excluded) and compose the
chat_title input as order-labeled lines truncated to a 1000-char
budget, falling back to lastPrompt for sessions without recorded
prompts.

* test: make session title race tests deterministic

* Generate session titles from agent conversation history

* fix: reject title generation without user prompts

* fix: bound session title prompt history

* feat: enable session title generation without an experimental flag

* test: cover session title generation through the public REST path

* feat: request session title generation from the TUI after each turn

* Retry auto title generation for prompt-derived session titles

* feat: record session title source and harden the generation lifecycle

- persist titleSource (prompt/generated/custom); skip auto-generation over
  an already-generated title unless forced, and never over a custom one
- plumb the force option from the core through klient and node-sdk to the
  REST title/generate endpoint
- drop the title write-back when the session scope was superseded
  mid-flight, and retry once with a force-refreshed token on a 401
- stop closing sessions a concurrent public resume has handed out in the
  temporary resume paths (generateSessionTitle, renameSession)
- accept session.meta.updated patches without lastPrompt in klient event
  validation, and emit exactly one metadata event per applied title
- remove the retired prompts field heal and drop the changeset (the
  behavior is only perceivable on the experimental v2 engine)

* chore: follow agent-core comment convention

* fix: ignore stale session title callbacks

* fix: preserve session title state invariants

* refactor: seed session lifetime instead of querying the workspace handler

The session title service must not depend on the Workspace-tier handler
registry. The handler now seeds each session scope with an abort signal,
fires it synchronously when a close begins, and the title service carries
the signal on its request, drops the write-back once aborted, and drains
an in-flight generation through the onWillCloseSession hook.

* fix: honor the legacy custom title marker over a stale titleKind

A v1 rename spreads the original state.json document, so an explicit
isCustomTitle: true can travel with a stale titleKind. The explicit
marker now wins on load, and every persist double-writes the derived
isCustomTitle so released v1 builds keep recognizing the custom title.

* fix: serialize session access and expose the session title state

The temporary resume/rename/close paths and the public lifecycle
operations now share a per-session queue, so a public resume can never
receive a handle whose cleanup close is already in flight. Session
summaries carry the canonical title state, letting the TUI skip title
generation for sessions whose title was already generated or customized
instead of re-asking after every turn.

* chore: add session title changesets

* fix: close the session lifecycle races around close and title generation

A close/archive is now tracked in a closing registry from its first
synchronous step until disposal: get/list hide the closing session and
resume waits the close out instead of returning the doomed handle, and
fork waits out an in-flight source close. The title service tracks the
whole generateTitle call as the unit the close hook drains, and the
generated-title write re-checks the lifetime signal inside the serialized
metadata update so an abort landing while the update is queued still
vetoes the write-back.

* feat: project the session title state through the session index

readSummary and the read-model mirror carry titleKind, so listSessions
reports the same canonical title state as a resumed session's summary.

* fix: serialize the remaining session access paths in the SDK

forkSession and explicit-id createSession join the per-session queue, and
the harness resume fast path skips a session whose close is in flight
instead of returning the closing facade (which then failed every call
with session.closed); its late onClose no longer evicts the fresh
session either. The harness rename event now carries isCustomTitle so
the TUI stops asking for a generated title after a local rename.

* fix: detach the external abort listener once the chat title request settles

* fix: harden the session close/archive and create/fork lifecycle

The closing registry now records the operation kind: an archive arriving
during a plain close waits it out and lands the archived flag on the
persisted document instead of riding the close to success, and a failing
close hook no longer strands a half-closed session — the teardown always
completes while the hook error still reaches the caller. create and fork
reserve their target id synchronously with the existence check, so a
concurrent create/fork of the same id loses up front and can never tear
down the winner's scope or directory.

* fix: keep forced title regeneration independent and veto queued title writes atomically

Plain generateTitle calls still coalesce onto one shared in-flight
generation, but a forced regeneration always runs on its own so it is
neither swallowed by a plain call's early exit nor shares its result; the
close hook drains every active generation. The allowWhen veto now runs
inside applyUpdate with no await between the check and the mutation, so
an abort cannot slip into the gap.

* fix: carry the title state through the session index and klient contract

The klient session summary schema no longer strips titleKind, and the
index readSummary honors a legacy isCustomTitle marker over a stale
titleKind, so listSessions reports the same canonical title state as a
resumed session.

* fix: coalesce harness resumes, lock fork targets, and cover the title state end to end

Concurrent public resumeSession calls now share one in-flight resume and
one facade instead of building parallel facades over the same engine
handle (a close on either would strand the other). forkSession takes the
source and target queues in sorted order, so fork(A->X) is atomic against
create(X) and fork(B->X) without an ABBA deadlock. The emitMetaUpdated
patch type drops the redundant undefined union, and the SDK tests now
cover facade coalescing and the title state across list and resume.

* fix: serve the canonical title state from the session index and version the read-model cache

readSummary now derives the title state with the same priority chain as
the metadata document's canonical normalization (explicit custom marker,
valid titleKind, legacy false marker, customTitle, plain title), so list
and resume agree on legacy documents too. Read-model cache entries carry
a summary version stamp and older-stamped entries are treated as cold
misses, so an upgraded reader never serves a stale-shaped summary.

* fix: let the newest title generation request win the write-back

A forced regeneration could be followed on disk by an earlier plain
call's slower backend response. Each generation now carries a
monotonically increasing sequence (assigned only once a request actually
proceeds to generation), and the serialized metadata write is vetoed
unless the writer is still the newest request.

* fix: fold archive into close and own the create/fork rollback

An archive requested during a plain close is applied through the live
metadata during the teardown (or lands on the persisted document when it
arrives too late or the close fails), publishes the archived event, and
works on cold sessions too. A resume waiting on a failed close retries
instead of propagating the hook error, the teardown completes even when
the agent drain fails, and the create/fork rollback only ever removes
its own handle — a loser of the reservation race can no longer tear down
the winner's live scope.

* fix: key harness resume coalescing by the full input

Concurrent resumes only share a facade when their inputs match — a
caller passing different dirs, replay, profile, or kaos options gets its
own resume instead of having its options silently dropped.

* refactor(agent-core-v2): drop session close-awareness from title generation

Auto title is best-effort: a generation racing session close no longer
cancels its fetch or guards its write-back, so the per-session
sessionLifetime AbortSignal seed, the onWillCloseSession drain, and the
close-time invalidation go away. The newest-request-wins write-back
predicate stays.

* Delete .changeset/sdk-session-title-kind.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* refactor(session-title): drop the unused force regeneration path

Nothing calls force: with it gone, plain calls always coalesce onto the
shared in-flight generation, so the generation sequence and the
caller-supplied allowWhen veto lose their only purpose and go with it.
The title/generate REST route takes no body anymore.

* refactor(agent-core-v2): drop the title state projection from the session index

The listed-session titleKind had no consumer: the TUI's title-generation
gate seeds from the resumed summary, which reads the live metadata
document, and the kap-server REST wire never carried the field. Removing
the projection also retires the read-model summary version stamp (the
remaining shape is fully field-checkable) and the duplicate title-kind
derivation that had to stay in lockstep with sessionMetadata. The klient
list contract and the node-sdk list mapper drop the field with it; the
resumed/live summary still reports the canonical title state.

* refactor(agent-core-v2): inline the transcript live-tail merge into messageLegacy

mergeContextTranscriptWithLive had a single caller; move the logic into
messageLegacyService as the private mergeLiveTail and drop the export.

* refactor(agent-core-v2): drop the closing registry from the session lifecycle

Auto title no longer consumes close-awareness, so the machinery goes
back to the simple forms: close/archive run straight through, resume
no longer waits out an in-flight close, create/fork drop their target
reservation, and a cold archive is a no-op again. Reverts the behavior
of e7c397a7c and cd1cea0fd on top of the sessionLifecycle rename.

* fix(agent-core-v2): complete the HostRequestHeaders migration in the title test

The main merge reduced #/kosong/model/hostRequestHeaders to the pure
port contract; define the test's headers as a plain value matching it
and tidy the SDK test import grouping.

* fix(node-sdk): mark resume telemetry field ignored

* feat(tui): request the session title as soon as a prompt is accepted

* fix(agent-core-v2): drop the numbered user prefixes from the title request input

* refactor(tui): ask for the session title only once per session attach

* refactor(tui): drop the automatic session title trigger

Keep the capability only: the engine-side title generation service, the
POST /sessions/{id}/title/generate route, and the SDK generateSessionTitle
method stay; the TUI no longer requests a title on prompt accept or on
session attach. The changeset now covers the SDK capability instead of a
CLI-facing auto title.

* Delete .changeset/session-title-generation.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* feat(agent-core-v2): add forced session title regeneration

ISessionTitleService.generateTitle and the metadata write-back take an
optional force flag that bypasses the custom/generated guards, so an
explicit user request (the desktop/web rename field's Gen Title action)
can overwrite any current title; the applied title is marked generated.
Forced calls skip the in-flight coalescing, and a forced write is plain
last-writer-wins.

kap-server's POST /sessions/{id}/title/generate accepts an optional
{ "force": true } body; klient and the node-sdk plumb the option through
(GenerateSessionTitleInput.force).

Also renumber SESSION_TITLE_UNAVAILABLE to 40923: main assigned 40922 to
PAGE_TOKEN_MISMATCH after this branch forked.

* feat(agent-core-v2): selectable conversation excerpts for title generation

generateTitle gains a source option alongside force:

- user_prompts (default): the existing first-prompts window, unchanged.
- first_turn: the opening user prompt paired with the first turn's final
  assistant text — strict, so a caller asking before the first reply lands
  simply gets unavailable and can retry at the next turn boundary.
- digest: first prompt + latest prompt + the latest turn's final assistant
  text, tolerating a compacted window by using whatever segments survive;
  meant for explicit regeneration on multi-turn sessions.

Assistant segments keep only natural-language text parts (tool calls,
thinking, and media never contribute) and pass through the shared metadata
sanitizer, which redacts secrets and long base64-looking runs; each
segment is capped (user 300, assistant 600/400) so the composed
chat_content stays within the 1000-char budget. The kap-server route,
klient contract, and node-sdk plumb the option through. Excerpt extraction
is covered against the real context memory (loop-event folding), and the
REST surface gains a digest composition case.

* feat(agent-core-v2): gate session title generation behind an experimental flag

Registers the  flag (off by default; env
KIMI_CODE_EXPERIMENTAL_SESSION_TITLE, the master flag, or the
[experimental] config section) and makes generateTitle report
unavailable while it is off, so every entry point — the kap-server
route, klient, node-sdk, and through them the clients' auto trigger and
rename-field action — is inert unless the user opts in.

* refactor(agent-core-v2): rename the title flag to auto_session_title

Snake-case id matching search_worker / persistence_minidb_readmodel; env
KIMI_CODE_EXPERIMENTAL_AUTO_SESSION_TITLE.

* fix(agent-core-v2): land the merge resolution leftovers

The main-merge commit captured pre-fix snapshots of four files; the
actual resolutions only lived in my working tree: the LifecycleScope
import move to #/app/scopes, the titleKind port of
applyPromptMetadataUpdate, the Promise<void> pinning of the metadata
update queue, and the reloadSession runSessionAccess closure.

* test(node-sdk): enable the auto_session_title flag in the title suites

Generation now reports unavailable with the flag off, so the two
title-generation harnesses opt in through the written config's
[experimental] section.

* chore: changeset for the experimental web session titles

* chore: scope the title changeset to the SDK package

* chore: cover the internal packages in the title changesets

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
Co-authored-by: liruifengv <liruifeng1024@gmail.com>
2026-08-13 17:59:57 +08:00
7Sageer
5912d4c7d1
fix: stop repeated file-watcher errors on Windows drive-root and UNC workspaces (#2876) 2026-08-13 14:35:23 +08:00
liruifengv
f8a88c1bd9
docs(changelog): sync 0.36.0 from apps/kimi-code/CHANGELOG.md (#2880)
Also translate the Chinese pool-example descriptions in
docs/en/configuration/config-files.md into English.
2026-08-13 14:30:40 +08:00
github-actions[bot]
b6144f94ea
ci: release packages (#2846)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-13 13:47:30 +08:00
Haozhe
314b39489e
refactor(agent-core-v2): extract swarm into a scope-organized feature (#2874)
* refactor(agent-core-v2): extract swarm into a scope-organized feature

- move src/agent/swarm, src/session/swarm, and src/agent/tools/agent-swarm
  into src/features/swarm/{agent,session,tools/agent-swarm}; swarmOps.ts
  stays a static import=register wire channel at the feature root
- add SwarmFeature carrying the three runtime registrations
  (IAgentSwarmService, ISessionSwarmService, IAgentSwarmTool) with
  ScopeActivation.OnScopeCreated preserved
- switch src/index.ts to precise leaf exports and update import sites,
  including the kap-server and kimi-inspect deep-path imports
- move tests to test/features/swarm and re-assert service overrides in
  the test harness so stubs keep winning over feature contributions

* fix(agent-core-v2): keep feature-contributed tools in Agent tool descriptions

SubagentTool.knownToolReferences() now reads the full AgentToolContribution
collection (static registrations and feature contributions alike) instead
of the static contribution table. A caller profile that does not activate
a feature-contributed tool (e.g. AgentSwarm) no longer drops it from the
per-profile tool listings the description advertises for spawned profiles
when a workspace/session restriction forces explicit enumeration.

Add a regression test with a caller profile lacking AgentSwarm under a
global tool restriction.

* refactor(kap-server): lift session profile updates to the route edge

- add sessionProfile.ts/sessionAgentConfig.ts route helpers that resume
  the session and dispatch title/metadata and the agent_config patch to
  the native v2 services directly
- drop updateProfile from ISessionLegacyService, leaving only the
  status rollup and the goal read in the legacy adapter
- wire shape and client-visible behavior unchanged
2026-08-13 13:35:49 +08:00
7Sageer
6e31722df1
chore: drop deprecations for unreleased [subagent] pool keys (#2877)
The [subagent] default_model / models deprecations added in #2700 guard a
migration path that has no users: the pool keys only existed in #2700's own
intermediate commits and never shipped in any release, so no config written
against a released version can contain them. Remove the two deprecation
entries (the mechanism stays — the released loop_control renames still use
it), the migration notes in the en/zh config docs, the agent-core-dev skill
note, and the obsolete test; regenerate the config manifest.

No changeset: #2700 is still unreleased, so no published version ever
emitted these warnings — the removal is invisible to users.
2026-08-13 12:57:22 +08:00
7Sageer
c9bfe8b2c8
feat: replace the secondary-model experiment with a declarative subagent model pool (#2700)
* feat: replace secondary-model experiment with [subagent.models] pool

Add a declarative subagent model pool to agent-core-v2: [subagent.models]
maps [models] entry ids to selection hints rendered in the Agent/AgentSwarm
tool descriptions, and [subagent].default_model picks the spawn model when
the caller passes none. The tools' model parameter becomes a free-form
alias string (stripped when no pool is configured), description rendering
is caller-aware (primary (alias) [main model]), and a session-start
validation service fails fast with CONFIG_INVALID on a missing/invalid
default_model or an unresolvable pool alias.

Remove the secondary-model experiment from the v2 engine, node-sdk,
kap-server, and the TUI (the /secondary_model command), and drop the
agent-profile modelPreference / model_preference frontmatter field on v2.
The legacy v1 engine keeps the experiment unchanged; v2 ignores leftover
[secondary_model] config silently.

* fix(agent-core-v2): harden subagent model-pool validation and error/picker mapping

Deep-review follow-ups to the [subagent.models] pool:

- validate the pool before session materialization (after config.ready)
  and before the fork file copy, so a broken pool no longer leaves
  orphaned session dirs or leaked MCP overlay connections; the
  Session-scope validation service stays as a backstop
- reject the reserved "primary" pool alias at startup, and again
  defensively in resolveSubagentBinding so a pool broken by a runtime
  config edit fails loudly at spawn instead of binding the wrong model
- keep the [default] marker when the caller's own model is the pool
  default (primary (alias) [main model] [default])
- recompile the cached tool-args validator when a tool advertises a new
  schema object (mid-session pool edits no longer hit a stale validator)
- map config.invalid to VALIDATION_FAILED in kap-server's session routes,
  the debug transport mapper, and the catch-all error handler
- hide the v1-synthesized __secondary__ entry from the /model and
  /provider pickers again
- fold per-export doc blocks into file headers per package comment
  conventions; add pre-flight/reserved-key/validator/mapping tests and
  document that create/resume/fork all fail on a broken pool

* feat: re-add /secondary_model and accept a lone subagent default_model

- v2 engine: a pool-less [subagent] default_model forms an implicit
  single-entry pool — validated at session create/resume/fork like an
  explicit pool, and advertised through the Agent/AgentSwarm model
  parameter.
- Tool descriptions: the caller's own alias is a normal pool entry
  marked [main model]; the primary line stays distinct because only it
  inherits the caller's thinking level.
- TUI: /secondary_model returns, persisting [subagent] default_model
  (merging into an existing pool with an empty description); the picker
  hides the no-op Thinking footer and rejects the reserved primary
  alias.
- kap-server: /api/v1/config accepts and echoes subagent; the
  snake-to-camel patch conversion preserves user-defined map keys under
  providers/models/experimental/raw without leaking preserve mode into
  a colliding alias's own fields.
- v1 config schema learns subagent.defaultModel/models so the shared
  config.toml round-trips; the v1 engine still ignores them at runtime.
- Docs (en/zh) and changesets updated.

* docs: use public model identifiers in the subagent model pool examples

* refactor: rename /secondary_model to /secondary-model

* test: cover the /secondary-model command name resolution

* Revert "test: cover the /secondary-model command name resolution"

This reverts commit 98a4a6d999.

* feat(agent-core-v2): move the subagent model pool to [secondary_model]

The pool keys (default_model, [secondary_model.models]) now live in their
own [secondary_model] config section instead of [subagent], which keeps
only timeout_ms; legacy [subagent] pool keys are ignored with a
deprecation warning. The SDK config contract carries the pool on the
secondaryModel field, so the TUI /secondary-model command (now also
aliased /subagent-model) and the kap-server /config wire read and write
it directly with no translation layer.

* docs: correct default engine guidance

* feat(agent-core-v2): pin subagents to default_model with [secondary_model] force

force = true removes the main agent's per-spawn model choice: the Agent
and AgentSwarm tools stop advertising the model parameter and every spawn
binds default_model; an explicit choice, "primary" included, is rejected.
The setting requires default_model, rejects a [secondary_model.models]
table, and is validated loudly at session create/resume/fork (lifecycle
preflight plus the Session-scope backstop). The v1 engine declares the
key for write round-trips and excludes it from the recipe patch.

Also documents pool entries as per-alias thinking-level variants via
default_effort overrides.

* docs: use real managed model aliases in the secondary_model examples

The pool examples invented aliases (kimi-hs, fable, codex) and referenced
non-existent model IDs (model = "codex"); they now reference only the
managed aliases provisioned by /login (kimi-code/k3,
kimi-code/kimi-for-coding, kimi-code/kimi-for-coding-highspeed), with the
effort variant derived as kimi-for-coding-highspeed-deep. Also replaces the
versioned kimi-k2.5 alias with kimi-for-coding per the docs model-ID rule.

* chore: simplify the subagent model pool changeset

* feat(agent-core-v2): honor the legacy [secondary_model] model key as a fallback default

* refactor(node-sdk): export the reserved model-alias constants from the SDK

Restore the SECONDARY_DERIVED_MODEL_ALIAS re-export and add
PRIMARY_SUBAGENT_MODEL_CHOICE so the TUI imports both from
@moonshot-ai/kimi-code-sdk instead of vendoring local copies.

* feat(agent-core-v2): keep the subagent model pool behind the secondary-model experiment

Restore the secondary-model flag gating so this change only adds the pool:
with the experiment off the [secondary_model] pool keys stay inert — the
Agent/AgentSwarm tools strip the model parameter, spawns inherit the
caller's model, and startup pool validation is skipped. The /secondary-model
slash command is gated behind the experiment again, and the docs and
changeset describe the flag.

* fix(node-sdk): cascade provider removal into the subagent model pool

Deleting a provider left [secondary_model] entries pointing at the removed
model aliases; with the secondary-model experiment on, every subsequent
session create/resume/fork then failed pool validation. planProviderRemoval
now filters dangling pool entries, and drops the whole section when its
effective default (defaultModel, or the legacy recipe's model fallback)
dangles — folded into the same atomic multi-section replace.

* fix(agent-core-v2): close two subagent model pool validation gaps

Spawn-time resolveSubagentBinding now rejects force combined with a
[secondary_model.models] table, matching the startup pre-flight — a live
session could otherwise reach that invalid state through a deep-merged
config patch and only fail on the next create/resume. The session
lifecycle pre-flight also awaits the kosong model/provider registries'
ready alongside config.ready, so a cold bootstrap no longer fails a valid
pool with CONFIG_INVALID against an empty registry.

* test(agent-core-v2): stub the model/provider registries in handler-chain tests

SessionLifecycleService now awaits IModelService/IProviderService readiness
in its pool pre-flight, so the tests that assemble the real service through
a hand-built container must register the two tokens.

* fix(kap-server): cascade REST provider deletion into the subagent model pool

The DELETE /providers route rewrote only the providers and models
sections, so a pool referencing one of the deleted provider's aliases was
left dangling and the engine's create/resume/fork pool validation failed
every subsequent session until the user repaired the TOML by hand. Filter
dangling pool entries and drop the section when its effective default
dangles, mirroring the SDK's planProviderRemoval semantics.

* fix: keep the subagent pool consistent on provider replace and preserve legacy recipe fields

PUT /providers rebuilds the provider's alias set and can drop or rename
aliases referenced by [secondary_model]; the pool now cascades there too —
renamed aliases are repointed (mirroring the global default-pointer
migration), dropped aliases are filtered, and the section is cleared when
its effective default dangles.

The v2 [secondary_model] schema also declares the legacy recipe patch
fields (default_effort, max_output_size, ...) so validation no longer
strips them: pool resolution keeps ignoring them, but config reads/writes
now round-trip losslessly instead of silently deleting them from
config.toml on any pool write.

* fix(agent-core-v2): cascade the subagent pool on catalog refresh writes

A background provider/model refresh rewrites the [models] table without
touching [secondary_model], so a dropped alias left the pool dangling and
every subsequent session create/resume/fork failed validation until the
user repaired the TOML by hand — the same gap the SDK and REST write
paths already had, but triggered unattended.

The cascade helper now lives in agent-core-v2 next to the section it
protects (cascadeSubagentModelPool): the discovery service folds the pool
into the same atomic replaceSections transition, and kap-server's
provider write routes reuse the shared helper instead of a local copy.

* fix: cover the last two model-table write paths for the subagent pool

ModelsDevImportService's catalog and custom-registry imports rebuild the
[models] table without the pool cascade, so an import that drops a pooled
alias left a dangling pool behind; both final write passes now fold the
pool through cascadeSubagentModelPool (the drop passes deliberately skip
it). The StubConfigService test double now treats a null section value as
a delete, matching the real ConfigService.

The TUI's provider overwrite flow removes an existing provider before
re-adding it, which ran the removal cascade against a model table where
every alias of that provider was absent and silently dropped the pool;
the flow now snapshots secondaryModel up front and restores the entries
that survive the re-add, via the cascade helper re-exported from the SDK.
2026-08-13 12:29:03 +08:00
Liu Zhongnuo
504e6292ed
feat(mcp): inspect effective authorization state in v1 (#2856)
* feat(mcp): inspect effective authorization state

* test(agent-core-v2): register MCP auth coordinator fixture

* fix(mcp): validate runtime names against full catalog

* fix(mcp): reconnect after pending auth updates

* docs(mcp): describe auth coordinator collaborator

* fix(mcp): ignore disabled runtime name collisions

* fix(mcp): serialize OAuth token refresh

* test(mcp): await OAuth credential writes

* fix(mcp): queue trailing credential reconnect

* fix(oauth): preserve access-only refresh winners

* fix(mcp): preserve legacy offline auth state

* fix(mcp): redact inspection credentials

* refactor(mcp): keep app inspection on v1

* fix(mcp): guard legacy auth status mutations

* fix(mcp): avoid deterministic legacy auth probes

* fix(mcp): cover initialization credential updates

---------

Co-authored-by: 刘仲诺 <liuzhongnuo@dev.msh.team>
2026-08-13 12:00:04 +08:00
Haozhe
23e68eee8b
refactor(agent-core-v2): remove the agent RPC aggregation layer (#2871)
* refactor(agent-core-v2): remove the agent RPC aggregation layer

- delete src/agent/rpc/ (AgentRPCService, IAgentRPCService, core-api,
  prompt-metadata, types) and sink each method's orchestration into its
  owning domain service
- prompt: new submit/submitSteer composing disabledTools gating,
  MAIN-only session metadata, and engine-side {turn_id} settlement
- skill: activate now returns PromptLaunchResult and writes session
  metadata internally (MAIN-only, unified across prompt/steer/skill/
  pluginCommand); node-sdk and kap-server drop their edge-side writes
- pluginCommand: new agent-scope domain owning command activation and
  the plugin_command.activated domain event
- permissionMode/loop/fullCompaction: new setModeAndBroadcast /
  cancelFromUser / cancel; setMode and loop.cancel stay pure for
  internal callers
- klient: agentRpcContract split into per-domain contracts; facade
  re-routes to domain channels with its public API unchanged
- node-sdk, kap-server, kimi-inspect and the v2 test harness now call
  domain services directly; ctx.rpc keeps its name as a composed
  adapter
- externally visible: the agentRPCService debug channel is gone and
  session metadata writes are now MAIN-agent-only (see changeset)

* refactor(agent-core-v2): move disabledTools gating out of the prompt domain

Prompt should not own session tool policy: submit no longer accepts or
applies disabledTools. The klient facade keeps its prompt({ disabledTools })
API and composes it edge-side — applying agentToolPolicyService
setSessionDisabledTools before calling agentPromptService.submit, the same
way kap-server's prompt route already does. Over klient, a profile-less
engine now surfaces the raw profile error instead of request.invalid.

Also restores the RPC-removal changeset, which did not make it into the
previous commit.

* chore(agent-core-v2): drop the RPC-removal changeset

* refactor(klient): drop disabledTools from the prompt entry entirely

The prompt path no longer carries session tool gating on any surface:
the klient facade prompt() loses the disabledTools field and calls
agentPromptService.submit directly, and the node-sdk
SessionPromptRpcInput stops accepting or forwarding it (v1 always
ignored the field). Session tool gating remains available through
IAgentToolPolicyService.setSessionDisabledTools, composed at the edge
the way kap-server's prompt route does; the klient toolPolicy contract
added for facade-side composition is removed as unused.
2026-08-13 10:57:01 +08:00
qer
719da94648
chore: rebuild web dist against kimi-code 0.35.0 (#2853)
Some checks are pending
CI / lint (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
code-app: c5440b863d02f99457f48520c16c609eae73f12b
2026-08-13 01:27:30 +08:00
7Sageer
fe3cdae5f8
fix(agent-core-v2): drop interrupted thinking-only assistant messages at step settle (#2819)
* fix(agent-core-v2): drop interrupted thinking-only assistant messages at settle

A turn interrupted while the model is still streaming thinking leaves the
open assistant holding only an unsigned thinking fragment. The fold used
to seal it into history because a non-empty thinking block is not vacuous;
on OpenAI-compatible providers the serialized message then carries neither
content nor tool_calls, and strict gateways reject every later request
with a 400 (#1404). Treat unsigned-thinking-only content as unsendable at
settle so the fold drops the message instead — replaying the records of
an already bricked session repairs it.

* fix(agent-core-v2): preserve reasoning-only assistant history

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-08-12 22:17:02 +08:00
liruifengv
30f56a2d2d
fix(agent-core-v2): disable SDK-internal retries that blocked cancellation (#2855)
* fix(agent-core-v2): disable SDK-internal retries that blocked cancellation

The OpenAI and Anthropic SDK clients default to maxRetries=2 with a
backoff sleep that never observes the request AbortSignal, so Ctrl+C
during a 429/5xx/connection-error retry only took effect after the
sleep elapsed, and the hidden attempts were invisible to the engine
(no turn.step.retrying) while double-counting its retry budget.

Build those clients with maxRetries: 0 so retryable failures surface
to the engine's step-retry layer immediately (observable countdown,
abortable sleep, single retry budget). The Google GenAI main request
path only retries when httpOptions.retryOptions is explicitly set, so
there is nothing to disable; instead its error converter now recovers
the server-directed delay from the wire body's google.rpc.RetryInfo
detail, since the SDK's ApiError drops the Retry-After header.

* chore: simplify the retry-cancellation changeset entry

* fix(agent-core-v2): recover GenAI retry delay from prefixed mid-stream error chunks

Mid-stream error chunks throw ApiError with the message wrapped as
"got status: <STATUS>. {json}", so a strict JSON.parse of the whole
message missed the google.rpc.RetryInfo detail. Locate the JSON object
start before parsing; the non-stream path (pure JSON body) is
unaffected.
2026-08-12 20:40:20 +08:00
liruifengv
ec84a6f9a3
feat(kimi-code): re-baseline pi-tui on upstream v0.84.1 and add fullscreen tui_mode (#2830)
* feat(kimi-code): re-baseline pi-tui on upstream v0.84.1 and add fullscreen tui_mode

Re-baseline the vendored pi-tui fork on upstream @earendil-works/pi-tui
v0.84.1, keeping all local patches: narrow-terminal hardening,
processed-line render caching (re-implemented into TuiMainScreen), editor
history hooks, the paste-burst fallback, and multi-root @ completion.

Upstream highlights absorbed: the renderer splits into TuiMainScreen and
TuiAltScreen behind a TUI interface, the Markdown component gains opt-out
LaTeX rendering (disabled on the kimi-code side), paste-registry repair
on delete/undo, Windows input-latency and Shift+Enter fixes, and Kitty
image layout fixes. Editor.setText gains a preservePasteRegistry option
so paste-marker expansion survives wholesale text replacement.

New tui_mode = "fullscreen" preference mounts TuiAltScreen: the
transcript lives in a primary ScrollView with follow-end, the chrome
docks at the bottom, mouse selection and scrollbar come from the
renderer, and full-screen viewers (tasks browser, output viewer, approval
preview) swap the layout root via screen-takeover. Viewport navigation
keys fall through to the focused component when the primary scroll view
cannot scroll.

* feat(pi-tui): merge upstream main through 40a3d85 (post-0.84.1)

Bring in upstream's merged-but-unreleased changes on top of the v0.84.1
re-baseline:

- Fullscreen transcript search (ctrl+shift+f, next/previous navigation)
- Alternate-screen render-churn reduction (9-18x less per-frame
  allocation by painting full-width rows as direct line references)
- Unbound single-line scroll actions (tui.altScreen.lineUp/lineDown),
  wired into the fork's canScroll gating like the other viewport keys
- SSH-aware escape-timeout default and PI_TUI_ESC_TIMEOUT override
- Search snapping and SGR-mouse fragmentation fixes; LaTeX newline
  argument fix

Conflicts resolved by union: upstream's search/line scroll bindings stay
ungated, fork's primaryScrollable guard applies to all scroll actions.

* fix(kimi-code): keep fullscreen dock from crushing the editor box

The fullscreen layout gave the transcript ScrollView its intrinsic
content height as basis and let the dock participate in shrink
distribution with no minSize. Once the transcript exceeded the screen,
the VStack shrink pass crushed the dock to a couple of rows, and the
editor (3 rows: top border / input / bottom border) lost its bottom
border row to clipping.

Adopt pi's sizing contract: the ScrollView starts from basis 0 and
grows, the dock keeps its intrinsic height, the editor never shrinks
below 3 rows, and the footer below 1. Adds a VirtualTerminal-level
regression test that replays a full streaming cycle in fullscreen.

* docs(kimi-code): document the tui_mode preference in tui.toml

* fix(pi-tui): let terminal focus reports fan out in fullscreen

TuiAltScreen's viewport input listener consumed FOCUS_IN/FOCUS_OUT
reports. Since the renderer installs that listener at construction —
before any app-level listeners — terminal focus tracking and
clipboard-image hints never saw focus transitions in fullscreen mode
(notification_condition = "unfocused" went blind, refocus clipboard
hints stopped). Keep the selection cleanup but stop consuming, matching
the main-screen fan-out. Addresses Codex review on PR #2830.

* fix(kimi-code): wire openUrl and right-click paste in fullscreen

Mouse capture in the alternate screen intercepts the terminal's native
link activation, leaving OSC 8 hyperlinks (like the footer's PR link)
unclickable in fullscreen. Route renderer link clicks to the app's
openUrl, and on Windows feed right-clicks to the focused component as a
bracketed paste read from the clipboard.

* feat(kimi-code): fullscreen prompt navigation, exit replay, progress resync

- Mark user/assistant transcript messages with OSC 133 zones (start /
  end / final) so the fullscreen renderer's Ctrl-Shift-Up/Down prompt
  jumps work; GutterContainer keeps the markers at byte 0 when prefixing
  its gutter, and message render caches store already-marked lines.
- On exit from fullscreen, preserve the frame and replay the transcript
  through a fresh main-screen renderer so native scrollback gets the
  regular inline layout (pi's "transcript" exit form).
- Re-sync the OSC 9;4 progress indicator after a stop/start cycle:
  terminal.stop() clears it, and the cached progressActive flag used to
  suppress the re-send when returning from the external editor mid-turn.

* feat(kimi-code): enable Markdown LaTeX rendering with a render_latex opt-out

Align with the upstream pi-tui default: LaTeX math in Markdown messages
renders as Unicode text. The explicit renderLatex:false we set during
the re-baseline becomes a shared Markdown options helper fed by a new
tui.toml preference (render_latex, default true), wired at startup and
refreshed on /reload.

* refactor(kimi-code): gate fullscreen behind KIMI_CODE_TUI_FULL_SCREEN

Drop the public tui_mode preference from tui.toml before release; the
fullscreen UI is experimental, so enable it with the
KIMI_CODE_TUI_FULL_SCREEN=1 env var instead. Docs move from the
config-file reference to the env-vars page.

* chore(changesets): clarify fullscreen mode and LaTeX formula entries

* chore(changesets): trim fullscreen mode entry

* chore(changesets): trim LaTeX formula entry

* chore(changesets): drop redundant kimi-code entries

* test(kimi-code): add stepRetry to fullscreen layout fixture after main merge

* fix(kimi-code): apply render_latex before theme-driven Markdown rebuilds

Codex review on PR #2830: applyReloadedTuiConfig set the shared LaTeX
toggle after applyTheme(), but theme application invalidates transcript
components and their rebuilt Markdown children copy the options at
construction — so a /reload that only flipped render_latex kept the old
value until some later invalidation. Move the setter before applyTheme
and pin the ordering with a test.

* fix(kimi-code): carry renderLatex through TUI config saves

Codex review on PR #2830: currentTuiConfig omitted renderLatex, so
saving an unrelated preference (theme/editor/upgrade/cache-hint)
serialized render_latex as the default true and silently reset a user's
opt-out. Carry the appState value through the shared save payload.

* feat(kimi-code): report tui_mode in lifecycle telemetry

Tag startup_perf and exit events with the active renderer mode
(regular/fullscreen) so fullscreen adoption is measurable while it is
gated behind KIMI_CODE_TUI_FULL_SCREEN.
2026-08-12 18:23:41 +08:00
liruifengv
35d9a36a69
chore(changelog): thank security reporters in 0.35.0 entry (#2845)
Some checks are pending
CI / lint (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
2026-08-12 16:27:19 +08:00
Haozhe
3b0936d8e0
fix(agent-core): only discover the root SKILL.md for plugin skills fallback (#2847)
When a plugin manifest omits `skills` and the plugin root contains a
SKILL.md, the fallback treated the whole plugin root as a generic skill
scan directory, so sibling Markdown files such as CHANGELOG.md were
misidentified as skills and inflated the plugin skill count.

Mark the fallback root as root-skill-only so discovery parses only the
root SKILL.md; explicit `skills` entries (including "./") keep the
directory scan semantics. Applied to both agent-core and agent-core-v2.
2026-08-12 14:24:48 +08:00
7Sageer
f40bf04998
refactor(agent-core-v2): unify model-facing reminder scheduling (#2623)
* refactor(agent-core-v2): unify model-facing reminder scheduling

Route every model-facing reminder through the contextInjector boundary
scheduler. Past-tense events go through a persisted once-reminder queue
(reminderQueue) that delivers exactly once at turn, step, compaction,
and restore boundaries; present-tense state renders through
context-injection providers reconciled against live history.

- interruption, goal (cancel/budget/fork-cleared), image-compression
  captions, btw, and init reminders enqueue into reminderQueue instead
  of writing the context directly; the interruptionReminder wire model
  is removed and its recorded type is retired silently on replay
- swarm mode announcements render through a provider seeded from the
  replayed history on restore, replacing live side effects and the
  ContextModel pop reducer on swarm_mode.exit
- loadable-tools announcements become an isNewTurn-gated provider,
  dropping the compaction boundary flag
- plugin session-start guidance re-renders as a supersedes reminder at
  the next boundary via a dirty flag instead of appending immediately
- legacy system_trigger origins of migrated reminders still fold on
  replay

* fix(agent-core-v2): make system reminders undo-aware

* test(agent-core-v2): migrate plugin session-start harness

* fix(agent-core-v2): preserve reminder boundary ordering

* refactor(agent-core-v2): narrow reminder and swarm helper exposure

- drop the swarmInjection re-export from the package index; SwarmInjection
  stays a domain-internal collaborator like permissionMode/plan injections
- move INTERRUPTION_REMINDER text back to a private constant in the service;
  only the variant stays in the Ops module
- make reminderQueue.enqueue return void; no caller consumed the entry id

* chore(agent-core-v2): keep comments in module headers

* refactor(agent-core-v2): track reminder state via injection disclosure

- derive swarm active/inactive state from ctx.lastDisclosure instead of
  byte-matching rendered markdown, with variant-only fallback for legacy
  swarm_mode/swarm_mode_exit journal entries
- record once_reminder disclosure (entry id) on queue-appended messages
  and dedupe the crash window by the contiguous tail id set, covering
  multi-entry drains
- move reminderQueue draining behind a sync onWillInject event so the
  injector no longer depends on the queue domain
- centralize the system-reminder wrap format behind wrapSystemReminder /
  systemReminderContent and use injector-provided positions in the plugin
  session-start provider
- spell out the step-boundary fallback and sync-only contract of
  registerAtTurnStart via shouldRunAtBoundary

* fix(agent-core-v2): isolate failing turn-start providers and warn once per missing sessionStart skill

* refactor(agent-core-v2): compute injection positions on read

Drop the per-provider positions cache from the context injector: the
registration scan, the context.spliced index arithmetic, and the
post-restore resync all existed only to mirror what the history already
records. Each provider call now derives its injected positions by
scanning context memory for its surviving injection messages, so silent
history edits (such as vacuous-step folds) can no longer desync a
cached index.

* refactor(agent-core-v2): formalize injector once-channels and raw message results

* refactor(agent-core-v2): declare dynamic tool schemas at injection boundaries

Move the dynamic-tool schema declaration out of toolSelect.load(): the
loaded names are recorded as pending and drained by a dedicated
toolSelectSchemas provider through the contextInjector boundary
scheduler, so the declaration message lands at a quiescent boundary
instead of mid-step inside a streaming tool exchange. The folded
history remains the loaded-tool ledger, so undo, compaction, and
resume still self-heal by re-folding.

* refactor(agent-core-v2): deliver AGENTS.md reminders through the reminder queue

The tool hook now only observes and enqueues a once-per-agent reminder
through the reminderQueue once-channel instead of prepending text to
the tool result: results stay verbatim for the truncation pipeline and
the reminder can never be truncated away with an oversized output. The
reminderQueue is resolved lazily through the instantiation service at
enqueue time, breaking the contextInjector -> loop -> llmRequester ->
profile -> agentsMdReminder constructor cycle.

* refactor(agent-core-v2): make injection disclosures opaque and domain-owned

contextMemory no longer declares the ContextInjectionDisclosure union:
InjectionOrigin.disclosure becomes an opaque unknown, and providers
bind their own payload type through register<D>, so lastDisclosure
arrives at the provider already typed by its own variant. The date,
swarm_mode, and once_reminder payload shapes move into the dateChange,
swarm, and reminderQueue domains respectively; reminderQueue keeps a
runtime guard for its cross-message tail scan, the only place that
reads disclosures it did not write. Persisted origin shapes are
byte-identical, so existing journals replay unchanged.

* fix(agent-core-v2): isolate failing step context providers

A step or compaction boundary provider that threw or rejected made the
injector's inject() promise reject, which propagated through the
onWillBeginStep hook chain and failed the whole turn, and starved every
provider registered after it. Log and skip the bad provider instead,
matching the turn-start path's existing isolation.

* refactor(agent-core-v2): derive injector isNewTurn per injection boundary

Replace the shared read-and-clear isNewTurn flag (set by turn.started and
injectAfterCompaction, consumed by the first inject()) with values each
trigger supplies from an authoritative source: the loop marks a turn's
first step via BeforeStepContext.firstStepOfTurn (standalone runs never
count), and the compaction follow-up passes true explicitly, so
interleaved triggers can no longer consume or steal the marker.

A compaction follow-up that lands inside a step hook chain (the
auto-compaction path) doubles as that step's new-turn delivery: the
enclosing step then injects with isNewTurn false, so the upcoming request
receives one new-turn injection, not two.

* refactor(agent-core-v2): unify disclosure placement and injector param naming

* fix(agent-core-v2): keep pending tool schemas across compaction splices

A load announced by select_tools sits in pendingLoaded until the next
injection boundary declares it. A compaction fold in that window
publishes a replacement splice, and the splice-time reconciliation
dropped the pending entries before the post-compaction inject could
declare them — the model was told "Loaded: X" yet X never became
available. Drop pending entries only on removal splices (undo/clear,
which carry no replacement messages); compaction's replacement splice
keeps them so the declaration lands at the post-compaction boundary.

* fix(agent-core-v2): consume the plugin session-start refresh after a successful render

reconcileSessionStartReminder cleared the refresh-pending flag before
awaiting the render, so a throwing render (skipped by the injector's
provider isolation) lost the forced refresh until the next catalog
change. Consume the flag only after the render resolves, and move the
warn-once rationale into the module header per the comment convention.

* refactor(agent-core-v2): remove the generic reminder queue

* chore(agent-core-v2): drop the stale reminder-queue mention in systemReminder

* test(node-sdk): align side-question fork parity with event-point reminders

* chore(agent-core-v2): address reminder review standards

* docs(agent-core-v2): condense the model-facing reminders section

* refactor(agent-core-v2): write all system reminders through wrapSystemReminder

* fix(agent-core-v2): preserve reminder lifecycle invariants

* refactor(agent-core-v2): reconcile context injections at the step head

Unify the injector's delivery timings into one point on the
onWillBeginStep chain, before the step's request is built:

- providers run before every request instead of after every step, so
  reminders are visible from the first response of a turn
- a compaction splice re-arms the new-turn flag via context.spliced;
  when compaction runs inside the hook chain (full-compaction's
  beforeStep), a follow-up inject at the chain tail keeps the first
  post-compaction request covered
- registerAtTurnStart and injectAfterCompaction are removed;
  reconcileWhenIdle stays as the v1-parity surface for SDK-driven
  triggers (swarm toggle, plugin reload)

* refactor(agent-core-v2): clarify the injector's step-hook handler

Name the handler reconcileAroundStep, rename the rearm flag to
compactionRearmPending with a single takeCompactionRearm() consumer,
and extract isCompactionSplice. Consuming the flag into a local before
computing isNewTurn also avoids hiding the side effect inside a ||
short-circuit.
2026-08-12 13:52:08 +08:00
liruifengv
43c68f58f5
feat(agent-core-v2): keep session updatedAt stable across meta management writes (#2815)
* feat(agent-core-v2): keep session updatedAt stable across meta management writes

Rename, archive/restore, and fork no longer bump a session's updatedAt,
so recency-sorted session lists stop reshuffling on management actions:

- setTitle/setArchived pass touchUpdatedAt: false; an explicit
  patch.updatedAt always wins (fork inherits the source's recency, so a
  fork lands next to the source instead of floating to the top)
- new SessionMeta.archivedAt records the archive moment (cleared on
  restore) and is surfaced through the session index, the v1/v2 session
  routes (archived_at), and the klient contract, so the archived list
  keeps an accurate archive time without relying on the updatedAt bump

* fix(agent-core-v2): normalize a legacy ISO-string updatedAt when forking a cold session

A cold legacy/v1 state.json read from disk can still carry an ISO-string
updatedAt; passing it through as the fork's explicit patch.updatedAt
would persist a string into the v2 metadata. Normalize with toEpochMs
(falling back to now when absent/unparseable).

* fix(agent-core-v2): write fork metadata after agent recreation

Registering each copied agent during fork is an ordinary metadata write
that bumps updatedAt, which overwrote the inherited source recency and
still floated normal forks (sessions with agents) to the top. Move the
fork's metadata update after the agent recreation loop so the inherited
updatedAt is the final write.

* fix(agent-core-v2): preserve persisted recency when restoring a cold session

Resume creates the main agent for a cold session that has no persisted
agents.main entry (e.g. an empty session), and that registration bumps
updatedAt — so unarchiving an empty session still floated it to the
top. Capture the index summary's updatedAt before resume and re-apply
it in the restore write (archived:false, archivedAt cleared, explicit
updatedAt wins over the bump).

* fix(agent-core-v2): make agent registration non-touching for recency

Registering an agent is a structural write, not content activity — but
it went through an ordinary metadata update that bumped updatedAt. That
reordered recency-sorted listings whenever materialization created an
agent: resume of a cold session without a persisted agents.main (so
archive-via-resume and restore of empty sessions still floated), and
runtime subagent registration mid-turn. registerAgent now passes
touchUpdatedAt: false; restore goes back to the plain unarchive write
and no longer needs the capture/reapply workaround.

* fix(agent-core-v2): duplicate cron tasks only after the fork metadata is durable

With the metadata write moved after agent recreation, cron duplication
ran before it — a rejected metadata update left cloned cron records
pointing at a fork whose directory the catch block just removed. Keep
cron duplication after the durable metadata write.

* style(agent-core-v2): fold new invariants into module headers

The package convention keeps comments in the top-of-file block only —
move the touchUpdatedAt precedence, non-touching registration, and fork
ordering notes out of statement-level positions into the respective
module headers.

* chore: scope the changeset to agent-core-v2
2026-08-12 13:40:26 +08:00
Haozhe
c212ae9715
fix(kimi-code): show MCP launch targets in the workspace trust prompt (#2843)
* fix(kimi-code): show MCP launch targets in the workspace trust prompt

Render each gated project MCP server's launch target (transport, command,
args, cwd, or url) in the workspace trust prompt without leaking env or
header secrets, stripping terminal control characters from the
workspace-supplied text, default the prompt to "Don't trust", and
resolve fd binaries to absolute paths so untrusted workspaces cannot
plant a bare-name fd executable that runs before trust confirmation.

* fix(kimi-code): resolve stty to an absolute path before the trust gate
2026-08-12 13:34:32 +08:00
Haozhe
26a37f30a3
fix(kap-server): restrict debug RPC fallback to feature-contributed services (#2808)
The decorator-registry fallback resolved every decorator name, including
kernel tokens like instantiationService — a call to
instantiationService/dispose would tear down the root container. Record
Feature.contributeService tokens in a contributed-service table and fall
back to that table only, so runtime-contributed services stay callable
while unregistered kernel tokens remain unreachable.
2026-08-12 12:35:01 +08:00
Haozhe
dc8db90cdd
docs(server): add local server guide and API reference (#2839)
* docs(server): add local server guide and API reference

* docs(server): qualify binary endpoint HTTP semantics
2026-08-12 12:29:09 +08:00
qer
26ddc1d0fb
feat(plugins): add Modern Web Guidance to marketplace (#2842)
* feat(plugins): add Modern Web Guidance to marketplace

* chore: drop changeset

* chore: backfill 0.35.0 changelog entry
2026-08-12 12:28:36 +08:00
liruifengv
3fc841ff23
docs(changelog): sync 0.35.0 from apps/kimi-code/CHANGELOG.md (#2841)
* docs(changelog): sync 0.35.0 from apps/kimi-code/CHANGELOG.md

* docs(changelog): add Modern Web Guidance plugin entry to 0.35.0
2026-08-12 12:15:07 +08:00
github-actions[bot]
f6ee44e426
ci: release packages (#2710)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-12 11:45:35 +08:00
Haozhe
101c4d1997
feat(agent-core-v2): remove Agent and AgentSwarm from builtin profile tool lists (#2837)
* feat(agent-core-v2): remove Agent and AgentSwarm from builtin profile tool lists

The builtin agent and coder profiles no longer expose the Agent and
AgentSwarm tools, so sessions on the v2 engine do not offer subagent
delegation by default. The tools themselves remain registered; profiles
that list them explicitly can still opt in.

* feat(agent-core): remove Agent and AgentSwarm from builtin profile tool lists

Align the v1 builtin agent/coder profiles with the v2 change: the
default profiles no longer offer subagent delegation, while the tools
stay registered for profiles that list them explicitly.

The parity projection drops v1's inactive Agent/AgentSwarm roster
entries: v1 reports registered-but-inactive builtin tools where v2 only
registers the tools a profile lists, so an inactive entry has no v2
counterpart. Active entries still compare in full.

* fix: keep Agent and AgentSwarm in the builtin agent profile

Scope the removal to the coder subagent profile on both engines: the
main agent keeps Agent/AgentSwarm so default sessions can still
delegate, while coder subagents no longer spawn nested subagents by
default. Snapshots and token counts shift only for the embedded coder
tool list; the v1 parity projection needs no change since the main
agent rosters match again.
2026-08-12 11:41:02 +08:00
qer
68ce3c7a0c
chore: sync web dist from code-app (#2840) 2026-08-12 11:38:17 +08:00
liruifengv
df8ce73e45
feat(kimi-code): show step retry progress in the activity indicator (#2825)
* feat(kimi-code): show step retry progress in the activity indicator

Wire the engine's turn.step.retrying event into the TUI: while a failed
model request is backing off for another attempt, the waiting spinner
shows 'retrying (N/M) · errorName · in Xs' with a dim detail line for
the status code and provider error message, and the loading tip is
suppressed.

The retry state clears on the step's terminal events (completed /
interrupted), turn.ended, and tool.result. It intentionally survives
turn.step.started because the v2 engine re-emits that event for every
retried attempt of the same step.

* fix(kimi-code): show the retry indicator for mid-stream failures

A retryable failure raised after thinking/assistant deltas had already
streamed left the pane in thinking/composing mode, so the retry label
and detail never rendered during the backoff. Drive the pane and the
streaming phase back to waiting when a retry begins.

* fix(kimi-code): drop the stale retry countdown once the attempt starts

The v2 engine re-emits turn.step.started when the retried attempt
begins running after the backoff sleep. Track a backoff/attempt phase
so the label keeps showing the retry attempt and error but drops the
already-elapsed 'in Xs' countdown, instead of either clearing the
state or showing stale timing through a slow attempt.

* fix(kimi-code): advance the retry phase on a timer instead of step starts

The legacy engine retries inside the same step and never re-emits
turn.step.started, so the backoff-to-attempt transition keyed on that
event never fired there and the stale countdown stayed up through the
attempt. Schedule the flip from delayMs instead, which matches when
both engines actually start the next attempt, and drop the step-start
hook.

* fix(kimi-code): cancel the retry phase timer on TUI shutdown

A pending backoff timer survived KimiTUI.stop(), keeping the event
loop alive and firing setAppState against a disposed UI when stop()
runs without an immediate process exit. Expose the timer cleanup and
invoke it from the shutdown path.

* fix(kimi-code): align the retry detail line with the spinner label

* fix(kimi-code): capitalize the retry spinner label
2026-08-12 11:35:44 +08:00
liruifengv
3c9e3b297c
feat(kimi-code): paginate the session picker list (#2826)
* feat(kimi-code): paginate the session picker list

The /sessions picker and kimi -r used to materialize the full session
list before showing anything, which gets slow with hundreds of sessions.

- node-sdk: add listSessionsPage (limit/before -> items + nextCursor);
  the v2 engine pages through the session index (draining past entries
  whose workDir is unrecoverable), the v1 engine answers one full page
- TUI: open the picker on the first page, fetch the next page when the
  cursor reaches the fetched end, and drain remaining pages in the
  background once a search query is typed so search still covers all
  sessions
- kimi -r now fetches a one-item page for the latest session

* chore: simplify session picker changeset

* fix(kimi-code): join in-flight page fetch in session search drain

A query typed while a scroll-triggered page fetch was still running
stopped the background drain at the loadingMore early return, leaving
the search covering only the pages fetched so far. fetchMoreSessions
now optionally joins the in-flight fetch and continues with the next
page; scroll triggers still drop when busy.
2026-08-12 11:21:43 +08:00
Haozhe
e5be39164b
fix(kimi-code): resolve footer git status commands through PATH (#2838)
The footer git status cache spawns git (and gh for PR lookup) on the
startup path, before the workspace trust prompt. On Windows, a bare
command name lets cmd.exe resolve a git.exe planted in the workspace
before the user confirms trust — a gap left by #2695.

Resolve git once at cache creation and gh per lookup with
resolveCommandPath(), which returns an absolute PATH hit and refuses
matches inside the workspace; when resolution fails the cache reports
no repository instead of spawning anything.
2026-08-12 10:51:57 +08:00
qer
619564dcf9
fix(kap-server): add WebSocket heartbeat to survive proxy idle timeouts (#2813)
Some checks are pending
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Release (push) Waiting to run
CI / lint (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
The v1 WS connection had no keepalive: by design it stayed open until the
client disconnected, which only holds for direct connections. Behind a
reverse proxy or gateway with an idle timeout (30s defaults are common),
any quiet stretch — e.g. waiting on a slow model response — got the
connection killed, surfacing as a recurring 'Realtime connection error'
in the web UI.

Send an application-level ping every 10s and advertise heartbeat_ms in
server_hello (the schema and all shipped clients already answer pong).
Application-level rather than protocol-level ping because browser JS
cannot observe the latter, and the client's stale-socket detector keys
on incoming message frames. Any inbound frame refreshes liveness; after
two silent cycles the connection is presumed half-open and closed with
1001 so dead peers get reaped instead of leaking.
2026-08-12 00:28:03 +08:00
liruifengv
911d41b0f6
chore(changesets): simplify pending CLI changelog entries (#2823) 2026-08-11 21:37:00 +08:00
liruifengv
ad12ad8a14
feat(kimi-code): show live background agent activity in the /tasks panel (#2816)
* feat(kimi-code): show live background agent activity in the /tasks panel

Background agents (run_in_background or Ctrl+B) showed no run details:
the /tasks panel only had static metadata, and its output view stays
"[no output captured]" until completion because agent tasks capture
output only once at the end.

Tee child-agent events into a bounded in-memory per-agent activity
store segmented by the engine's own turn.step.started events (recent
10 steps, bounded text/output tails). The /tasks preview pane now
shows a live activity preview for agent tasks, and Enter/O opens a
full-screen detail view rendering step-grouped Markdown text and
per-tool results through the main transcript's renderers, with Ctrl+O
to expand. Agent tasks without an in-memory record (e.g. lost after
resume) fall back to the captured-output view.

* feat(kimi-code): retain 20 recent steps in the background agent activity view

* fix(kimi-code): cap the streaming-args buffer in the subagent activity store

* chore(kimi-code): simplify the background agent activity changeset

* fix(kimi-code): drop activity records of foreground-only subagents at terminal state

* fix(kimi-code): cap retained tool argument strings in the subagent activity store

* test(acp-server): retry temp-dir cleanup to deflake ENOTEMPTY on CI

* fix(kimi-code): tighten subagent activity store lifecycle edges

- drop delta-only arg buffers when their step is evicted
- keep records of spawn-time background agents even when the task sync lags
- mark records terminal on background.task.terminated for stopped agents
  that never emit subagent.failed

* fix(kimi-code): release leftover arg buffers when an activity record turns terminal

* fix(kimi-code): prune foreground-only activity records when the main turn ends
2026-08-11 21:32:39 +08:00
HydrogenE7
158c81d705
fix: surface a readable error when Git Bash is missing on Windows (#2814)
* fix: surface a readable error when Git Bash is missing on Windows

* fix(agent-core-v2): translate probe rejection into HostProcessError for ready awaiters

- HostEnvironmentService.ready now rejects with the translated
  HostProcessError(shell.git_bash_not_found) instead of the raw
  ProbeShellNotFoundError, matching what sync field reads throw and what
  SDKRpcClientV2.ensureConfigFile() surfaces, while an internal no-op
  handler keeps the rejection from becoming an unhandledRejection.
- Replace the Windows-gated probe-failure tests with vi.mock-stubbed
  deterministic suites that run identically on any platform.
- Move the ProbeShellNotFoundError explanation into the environmentProbe
  file header per the package comment convention.

* fix(agent-core-v2): narrow probe error to Error to satisfy only-throw-error lint

* fix(agent-core-v2): preserve probe error as cause when translating to HostProcessError

* fix(agent-core-v2): keep checked paths out of the public probe error message

* fix(node-sdk): gate the host-environment wait in ensureConfigFile to Windows

The missing-Git-Bash failure is Windows-only, and IHostEnvironment.ready
also covers the login-shell PATH enrichment, which spawns the user's login
shell with a 5s timeout. Awaiting it on POSIX coupled config-only commands
(kimi provider list/remove, export, ...) to the user's shell profile for no
benefit.

---------

Co-authored-by: liruifengv <liruifeng1024@gmail.com>
2026-08-11 21:13:08 +08:00
HydrogenE7
64abebc95a
fix(apps/kimi-code): allow deselecting Other option in multi-select question dialog (#2810) 2026-08-11 19:55:13 +08:00
Haozhe
860354976e
feat(agent-core-v2): add event-subscription introspection (#2806)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
- name Emitters and surface their subscriptions as on:<name> ledger
  labels through a named EventSubscription class and IDisposableDebugLabel
- add IDebugEventsService.subscriptions(), merging unit-book entries
  with per-bus listener counts, contributed at App scope by the new
  debugEvents feature
- kap-server debug dispatcher falls back to the global decorator
  registry so runtime-contributed services stay callable
- kimi-inspect: add an Events panel to the DI view
2026-08-11 14:55:08 +08:00
Haozhe
e702817124
fix(agent-core-v2): degrade idle-session steer to turn launch like v1 (#2723)
- return the enqueue-launched turn instead of rejecting with
  prompt.not_found when no prompt is pending at steer time
- report steer as queued when a manual compaction holds the context
- sync title/lastPrompt metadata on main-agent steer, matching v1
- update the v1-v2 parity test to assert converged behavior
2026-08-11 14:40:15 +08:00
Haozhe
71ff2a0fff
fix(kimi-code): close pre-trust-gate bare command resolution on Windows (#2695)
On Windows, cmd.exe / CreateProcess resolve a bare command name from the
current directory before PATH. Several startup-path child processes ran
before the workspace trust prompt, so a binary planted in an untrusted
workspace (stty.exe, npm.cmd, fd.exe) could execute before the user
confirmed trust.

- skip the POSIX-only stty save/restore entirely on win32
- defer fd detection from the KimiTUI field initializer to
  startBackgroundFdAutocomplete(), which runs after the trust gate
- add resolveCommandPath(): resolve commands through PATH (PATHEXT-aware
  on win32) to an absolute path and refuse hits inside the cwd
- route update-preflight package-manager spawns and the npm global-prefix
  probe through it
- run the workspace trust prompt before the migration branch as well,
  closing the blind spot where a pending ~/.kimi migration skipped it
- document the no-bare-command-before-trust-gate rule in
  apps/kimi-code/AGENTS.md
2026-08-11 12:53:52 +08:00
Haozhe
2acf22f66e
refactor(agent-core-v2): invert sessionLifecycle/MCP dependency via lifecycle event (#2803)
- add onWillCreateSession to ISessionLifecycleService: a synchronous
  participation event fired before a session's services activate, exposing
  a session-domain facade (readSeed / contributeSeed / onSessionDispose)
- workspaceMcp subscribes and activates ephemeral-server overlays itself:
  the configs travel as the new ISessionEphemeralMcpServers session seed,
  the stdio cwd is read from ISessionContext, the merged ISessionMcpHandle
  is contributed over the seed adapter's workspace projection, and the
  overlay shutdown is attached to the session's teardown
- sessionLifecycle drops its IWorkspaceMcpService dependency, the overlay
  tracking map, handle-dispose wrapping, and the dispose backstop
- rename ScopeOptions.extra to seeds and ScopeOptions.assemble to
  configureContainer
2026-08-11 12:31:47 +08:00
Haozhe
0401ec4286
refactor(agent-core-v2): extract btw into a features/btw Feature unit (#2724)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
Release / Publish native release assets (push) Blocked by required conditions
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
- move session/btw to features/btw, mirroring the plan feature layout
- contribute ISessionBtwService at Session scope through BtwFeature
  (contributeService) instead of a static registerScopedService call
- keep the package root exports unchanged; move the test to
  test/features/btw
2026-08-10 11:09:23 +08:00
oocz
01c74e9372
fix(agent-core): isolate builtin profile catalogs per session (#2740)
Some checks failed
CI / build (push) Has been cancelled
CI / test (1) (push) Has been cancelled
CI / test (2) (push) Has been cancelled
CI / test (3) (push) Has been cancelled
CI / test (4) (push) Has been cancelled
CI / test (5) (push) Has been cancelled
CI / test-pi-tui (push) Has been cancelled
CI / test-windows (push) Has been cancelled
CI / lint (push) Has been cancelled
CI / typecheck (push) Has been cancelled
Nix Build / Check flake.nix workspace sync (push) Has been cancelled
Release / Release (push) Has been cancelled
Release / Native release artifact (push) Has been cancelled
Nix Build / nix build .#kimi-code (push) Has been cancelled
Release / Deploy docs (push) Has been cancelled
Release / Publish native release assets (push) Has been cancelled
2026-08-08 14:26:17 +08:00
Liu Zhongnuo
437a1b8ba1
fix(sdk): probe MCP auth status through connection (#2731)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
2026-08-07 22:18:53 +08:00
Liu Zhongnuo
0b2e803d5e
feat(sdk): expose global MCP auth status (#2706)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
2026-08-07 13:11:18 +08:00
Haozhe
7cd64766c8
feat: isolate the full-text search index from the session index and the main thread (#2701)
* feat(minidb): instrument open lifecycle with phase timings and status

Add MiniDb.lifecycleStatus() exposing the no-generation/generation-load/
wal-catch-up/full-rebuild/ready/degraded state machine plus per-phase
timings (generation candidate load, store/non-text/text image load,
postings integrity check, WAL scan/apply, full recovery, text rebuild
hosting), so snapshot load, WAL catch-up and full rebuild can be told
apart in diagnostics.

Also add a repeatable open-lifecycle bench (small data, large WAL delta,
large full-text generation, corrupt generation) and fixtures proving a
healthy generation open performs no full-corpus tokenization while a
corrupt or missing generation falls back. Log search-index and
query-store open diagnostics in kap-server and agent-core-v2 so a
listSessions call can be attributed to the database it touches.

No persistence format or product behavior change.

* feat(agent-core-v2): isolate the session index from the global search index

Harden the separation between the session read model and the full-text
search index so session operations never depend on search availability:

- Reject text index definitions in MiniDbQueryStore at definition level,
  keeping the session query-store a structural-only read model with no
  postings/tokenizer artifacts, and assert its generation carries no
  full-text files.
- Share one authoritative scan between the first list and the initial
  projection (single-flight) instead of scanning twice; reads may only
  join an in-flight scan, and every fallback read folds the mirror's
  pending queue so read-your-writes holds while preparing.
- Keep withReadModel() fallback semantics pinned by tests:
  uninitialized/preparing reads hit authoritative metadata immediately,
  ready reads use the read model, degraded keeps falling back with a
  diagnosable status reason.
- Guard session metadata writes so a mirror failure degrades only the
  read model and never fails the session lifecycle.
- Prove via tests that listSessions/--resume/--continue never open the
  global search DB (including when search-index is unopenable), and that
  only real full-text search requests report building/stale/degraded.

* perf(minidb): slice open-time work so it never blocks the main thread

Make the whole generation-open path cooperative:

- Replace the synchronous postings/store CRC verification with chunked
  async variants (readGenerationFileCheckedAsync, verifyFileIntegrityAsync)
  that keep the exact bytes/crc-mismatch error semantics.
- Give the WAL-delta apply a primitive-op + wall-clock budget
  (walApplySlicer), so a batch frame unrolling into thousands of ops can
  no longer run as one uninterruptible slice; torn-tail, corrupt-batch
  and read-only behaviors are unchanged.
- Slice the big attach loops: Store.bulkLoadRefsAsync +
  SkipList.bulkLoadAsync for the store image, async parsers and
  loadImageAsync for secondary/compound images, and
  TextIndex.attachImageAsync for the docs/dictionary map construction.
- Queue text builds on worker-slot pressure (WorkerSlots.acquireBounded,
  bounded by MiniDb.textBuildSlotWaitMs, abort-aware) instead of falling
  back to an unbounded inline build; a persisted drought hosts the
  bounded inline core as the explicit last resort with stats accounting.

Bench (bench/open-lifecycle, seed 42): event-loop delay max across the
four open scenarios drops from 45/734/331/492 ms to ~12-28 ms with wall
time flat or better.

* feat(kap-server): run the global search index in a dedicated worker

Move the whole search-index MiniDb lifecycle (open, generation load,
WAL replay, sync, rebuild, compaction) off the main thread into a
long-lived worker_threads host, so it never shares the event loop with
TUI input:

- Add a versioned request/response protocol and worker entry hosting a
  host-agnostic SearchIndexCore; the same core also backs an inline
  backend kept as the explicit rollback
  (KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER=false, flag default ON).
- The worker exclusively owns the search-index handle. The lock token
  is reported at acquire time (new MiniDb OpenOptions.onLockAcquired
  hook) and reaped on dirty exit; an orphan-lock detector (same-pid
  lock row whose token no live holder owns) recovers the window where
  the token report is lost, so a mid-open crash can never freeze the
  index into a silent permanent read-only.
- Crash handling: in-flight requests are rejected with typed errors,
  respawn uses capped exponential backoff, per-request watchdogs
  terminate wedged workers, and beginClose propagates into the worker
  so dispose stays bounded during a long sync. Page tokens pin a
  boot-salted generation, so tokens issued before a transparent worker
  restart fail closed with invalid_page_token.
- The main process keeps the sync coordinator (debounce/coalescing/
  single-flight), live transcript routing, query normalization and
  page-token codec; searches keep reading the published generation and
  report building/stale/degraded instead of waiting for sync/rebuild.
- Wire the worker into the CLI packaging: self-contained worker bundles
  for npm dist and the SEA asset manifest/installer/smoke check, plus a
  dev runtime (type-stripping + .ts resolve hook) scoped to worker
  execArgv.

* feat(kap-server): model search and session-index lifecycles explicitly

Consolidate the two-index separation into explicit, diagnosable
lifecycles:

- Surface the global search state machine (stopped / opening / building
  / ready / degraded / closing) end to end: SearchIndexCore.lifecycleState,
  SearchWorkerHost lifecycle snapshots cached from RPC responses (and
  invalidated across worker generations), a never-throwing status()
  carrying the lifecycle, and a synchronous lifecycleReport() that
  neither kicks the open nor spawns the worker. Corrupt search-index
  rebuilds are announced with a dedicated warn log so building, stale,
  degraded, corrupt and worker-unavailable stay distinguishable.
- Turn MiniDb read-only replica catch-up fully cooperative:
  catchUpWalAsync scans frames with the windowed async scanner and
  yields per primitive op on the shared walApplySlicer budget, while a
  per-instance catchUpChain serializes concurrent catch-ups so each
  caller keeps its atomic watermark advance. The stale synchronous
  implementations are removed.
- Pin the dependency direction and availability timing with tests:
  session list/create/resume survive a corrupt or unopenable search
  index (also end-to-end with a dead query-store), search generation
  reuse and stale-serving keep working across restarts, concurrent cold
  callers open the index / spawn the worker exactly once, resume-then-
  fetchSessions performs no duplicate authoritative scan, and a clean
  dispose releases the lock and settles at stopped.
- Document the experimental flag surface (persistence_minidb_readmodel,
  search_worker) in the root guide.

* feat(agent-core-v2): default the session read model on and roll out the separation

Rollout and validation for the index separation plan:

- Flip persistence_minidb_readmodel to default ON (rollback via
  KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL=false or the
  experimental config section); session list/--resume/--continue now
  always go through the isolated session read model with the
  authoritative fallback. Test harnesses pin the flag off where shared
  fixtures require hermetic homes, while the dedicated suites keep
  explicit on/off coverage.
- Add a probe proving the main thread stays responsive while the
  search worker rebuilds and swaps a generation (reindex), completing
  the TUI responsiveness matrix.
- Record the rollout state in the agent-core-v2 guide (session index
  section) and the root flag line.
- Add changesets for the CLI (worker isolation, session index
  independence) and minidb (cooperative open lifecycle).

Validation: full suites green across minidb (551), agent-core-v2
(4760), kap-server (1005), node-sdk (343), klient (91) and the CLI app
(2567); open-lifecycle bench event-loop delay max is down from
45/734/331/492 ms to ~16-22 ms across the four scenarios with wall
time flat or better.

* fix(agent-core-v2): evict deleted sessions from the mirror queue and drain the index on close

Two issues surfaced by the read-model default in the acp-server suite:

- ISessionIndex.remove only deleted from the query store, but a summary
  still queued in the mirror was folded back into reads (and re-written
  by the next flush), resurrecting a deleted session in listings. The
  mirror now exposes evict(id): drop the queued summary and wait out an
  in-flight flush before the store delete.
- RunningAcpServer.close and SDKRpcClientV2.close disposed the engine
  without awaiting the asynchronous mirror flush / query-store close,
  so a host removing homeDir right after close() raced in-flight shard
  closes (ENOTEMPTY). Both now follow the kap-server shutdown order:
  drain the mirror while the store is open, dispose, then await the
  drains.

* fix(minidb): pause active expiry during the sliced bulk load

The store's active-expire timer is armed at construction, so during a
sliced bulkLoadRefsAsync a tick can fire mid-load: it reaps a TTL key
from the map while the order skiplist is still the old empty one, and
the final bulkLoadAsync then rebuilds order from the stale orderEntries
snapshot — resurrecting the expired key in the ordered index (and
duplicating it if the key is later set again). The sync bulkLoadRefs had
no yield windows, so guard the async path with a bulkLoading flag that
defers expiry ticks until the load settles (finally-safe).

* chore: consolidate changesets into the TUI startup freeze fix
2026-08-07 07:38:16 +08:00
Haozhe
c0b61c6e55
fix(agent-core-v2): count compaction tokens on the full-request basis (#2699)
Some checks are pending
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
- tokensBefore/tokensAfter now include the system prompt and non-deferred
  tool schemas, matching the measured-anchor basis the context gauge uses
  between exchanges
- the post-compaction ledger rebase carries the same full-request size, so
  the reported context size no longer dips to a messages-only estimate and
  jumps back on the next exchange
- the PreCompact hook tokenCount uses the same basis
2026-08-07 07:31:11 +08:00
qer
476787fec9
docs(agents): rework changelog curation rules for the user-facing changelog (#2708)
* docs(agents): rework changelog curation rules for the user-facing changelog

* docs(agents): refine catch-all wording and add reviewer notes to the changelog preview

* docs(agents): surface folded entries at the sync review checkpoint
2026-08-07 02:23:37 +08:00
qer
d9ec566e51
docs(changelog): sync 0.34.0 from apps/kimi-code/CHANGELOG.md (#2704)
Some checks are pending
CI / test (5) (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
* docs(changelog): sync 0.34.0 from apps/kimi-code/CHANGELOG.md

* chore: link
2026-08-06 22:55:50 +08:00
wenhua020201-arch
51ef78b8c9
docs: add Official Plugins section with WebBridge and Computer Use (#2653)
* docs: add Official Plugins section with WebBridge and Computer Use

Group the three official capabilities (Kimi Datasource, Kimi WebBridge,
Kimi Computer Use) under a new Official Plugins section on the plugins
page, with a single shared install/upgrade flow. Add an authorization
walkthrough screenshot for Computer Use and regroup the Datasource
coverage table by category with named data sources.

* docs: add browser extension install steps for Kimi WebBridge

Installing via /plugins is not enough on its own: AI can only drive the
browser after the Kimi WebBridge extension is present. Document both
install paths (Chrome Web Store / Edge Add-ons, and manual load-unpacked
via chrome://extensions with Developer mode) plus a quick way to verify.

* docs: split WebBridge manual install into illustrated steps

Break the manual extension install into numbered steps with per-step
screenshots: enable Developer mode on chrome://extensions, then load the
unpacked kimi-webbridge-extension folder.

* docs: tighten WebBridge install screenshots to the relevant area

* docs: add WebBridge ready-state verification screenshot

* docs: note WebBridge's two-part install in the shared install steps

* docs: even out WebBridge install screenshot edges

* docs: replace WebBridge install screenshots with clean crops

Re-shoot source images: split the two-step manual install guide into
per-step screenshots with clean edges, and replace the ready-state popup
screenshot with the toolbar-icon success indicator.

* docs: use newly provided WebBridge step screenshots

* docs: sharpen Computer Use auth screenshot and center it

Replace the downscaled auth-window image with a crisp native capture,
constrain its display width to 380px, and center it on the page. Also
move the WebBridge two-part install note into an info callout directly
under the shared install steps.

* docs: drop the coverage start year from the Datasource table

* docs: spell out the two WebBridge extension install options

* docs: show the Kimi Code toggle enabled in the Computer Use auth screenshot

* docs: show version badges for WebBridge and Computer Use, rework Computer Use scenarios

Add version badges next to all three official plugin names. Rewrite the
Computer Use capability list around verified task shapes and add a
warning callout for operations that should not be delegated. Keep the
final WebBridge install step inside the numbered list.

* docs: add Windows (WinCU) notes to Computer Use

Computer Use now ships a Windows runtime with a different install path
and behavior: it may briefly take over the real mouse and keyboard
instead of running fully in the background. Document the install
command, system requirements, permission model, and privilege matching,
and stop claiming the feature is macOS-only.

* docs: break up the plugin manager wall of text

Split the Installation and Management paragraph into bullets, drop the
parts duplicated by the Official Plugins section (including the outdated
macOS-only note), and link to that section instead.

* docs: list the plugin manager tabs and drop the tab-behavior block

* docs: give the WebBridge extension install section an English anchor

* docs: restore the /reload or /new activation step for official plugins

* docs: align the plugins page wording with the published docs site

* chore: retrigger CI

---------

Co-authored-by: qer <wbxl2000@outlook.com>
2026-08-06 22:51:27 +08:00
github-actions[bot]
f0614c53e5
ci: release packages (#2641)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-06 21:56:49 +08:00
Haozhe
794714ebef
fix(agent-core-v2): gate plugin changes behind session baselines and reminders (#2702)
* fix(agent-core-v2): gate plugin changes behind session baselines and reminders

- capture a per-session MCP server baseline (ISessionMcpHandle.isBaselineServer)
  so servers added mid-session (plugin install, mcp.json edit) never register
  tools in live sessions; they take effect on /new, /reload, or resume, while
  removed servers stay tombstoned and fail calls with a removal notice
- stop rebuilding the system prompt on plugin-source catalog changes: the
  frozen skill listing and plugin sections cannot move anyway, and the rebuild
  only churned the ${now} timestamp, invalidating the provider prompt cache
- freeze the Agent tool description's catalog profile list once the session
  catalog has loaded, keeping the tools payload byte-stable across mutations
- append a plugin_change system reminder to live sessions on plugin mutations
  (new IPluginService.onDidMutate; explicit reloadPlugins does not raise it)
- revert the TUI hint to "Run /new or /reload to apply plugin changes." and
  update the plugin/MCP docs and changesets to the corrected contract

* fix(agent-core-v2): import LifecycleScope from app/scopes in sessionOutcomeMirror

#2666 imported LifecycleScope from #/_base/di/scope, which does not export
it (it lives in #/app/scopes), breaking the package build and typecheck on
main.

* fix(agent-core-v2): close the mutation-driven session-start refresh and overlay baseline leaks

Codex review on the PR found two contract leaks:

- a plugin mutation re-pulls the plugin skill source, and the existing
  catalog listener answered with a fresh plugin_session_start reminder —
  injecting the newly installed plugin's instructions into the live session
  alongside (and contradicting) the plugin_change notice. The session-start
  refresh now skips mutation-driven catalog changes (one per mutation,
  counted; explicit reloads keep the old refresh behavior).
- a session created with ephemeral mcpServers kept its MCP baseline open
  until the overlay connect finished; a workspace server added in that
  window (plugin install, config edit) leaked into the live session through
  the merged view. The overlay handle's baseline now freezes on the
  workspace manager's initial load, with the ephemeral names baseline by
  construction.

* fix(agent-core-v2): drop duplicate LifecycleScope import in sessionOutcomeMirror test

---------

Signed-off-by: Haozhe <yanghaozhe@moonshot.ai>
2026-08-06 21:11:03 +08:00
qer
fa3325404b
fix(agent-core-v2): import LifecycleScope from the L3 scopes module (#2703)
The L3 unit layer refactor moved LifecycleScope out of the _base DI kernel
into the app tier, leaving the session outcome mirror with a stale import
that broke typecheck and import-time evaluation on main.
2026-08-06 20:56:54 +08:00
qer
03aa66ca0c
fix(tui): show WebBridge setup steps after install (#2692)
* fix(tui): show WebBridge setup steps after install

* fix(tui): scope WebBridge hint to capability install

* fix(tui): format WebBridge setup links

* fix(tui): align WebBridge setup with live reload

* fix(tui): retain WebBridge session activation step

* fix(tui): compact WebBridge setup links

* fix(tui): list WebBridge setup links clearly

* fix(tui): show clickable WebBridge URLs

* Revert "fix(tui): show clickable WebBridge URLs"

This reverts commit 373ffae4b8cf4256131002b990f9a1869e9ee156.

* fix(tui): restore WebBridge setup heading
2026-08-06 20:19:32 +08:00
qer
335588e259
feat(agent-core-v2): persist the last turn outcome into session metadata for cold listings (#2666)
* feat(agent-core-v2): persist the last turn outcome into session metadata for cold listings

A cold session (no live handle) reported no lastTurnReason, so after a
server restart the session list could not mark a session whose last turn
failed until it was opened and resumed.

A new Session-scope SessionOutcomeRecorder subscribes to the activity
aggregate's turn_ended changes and persists the outcome
(completed/failed) into the session metadata document; the summary
pipeline (mirror + cold reader) carries it as SessionSummary
.lastTurnReason, and toWireSession falls back to it when no live fact
exists. 'cancelled' is deliberately not persisted: it is also what an
in-flight turn ends with during scope disposal, and writing there races
the host's home-dir teardown.

Verified end to end with an isolated home and a dead provider: a turn
fails, the server restarts, and GET /sessions reports
last_turn_reason=failed without opening the session.

* fix(klient): carry lastTurnReason/lastTurnOutcome in the validated contracts

Review follow-up: zod strips unknown keys on parse, so the new outcome
fields never reached klient callers; add them to the session summary and
metadata/patch/key schemas (contract parity test covers the engine
mirror).

* fix(agent-core-v2): persist user-cancelled outcomes, never teardown aborts

Review follow-up: skipping every 'cancelled' left a stale earlier outcome
in the metadata (e.g. a prior failed reported for a session whose latest
turn was stopped by the user). The recorder now subscribes to the main
agent's turn.ended facts directly and keys on interruptReason:
user_cancelled is persisted like any other terminal state, while
programmatic aborts — including the cancel every in-flight turn suffers
during scope disposal — are never written, so no metadata write races the
host's home-dir teardown.

* fix(kap-server): only fall back to the persisted outcome for cold sessions

Review follow-up: a warm session that just started a new turn clears its
live lastTurn, and the unconditional ?? fallback would then report the
previous turn's persisted outcome for a turn that is still running.
SessionFacts now reports whether a live handle exists, and the wire
projection only reads the persisted value when the session is cold.

* docs(agent-core-v2): keep the outcome-recorder header at role level

* fix(agent-core-v2): settle turn outcomes on turn start and drain metadata writes on close

Review follow-ups:

- a new main turn now clears the persisted outcome (turn.started), so a
  process that dies mid-retry no longer reports the previous turn's
  terminal state for a turn that never ended
- the dedupe marker only advances after a successful write, so a failed
  persist no longer suppresses the next identical outcome
- session metadata writes are tracked in a module-level pending set with
  drainSessionMetadataWrites(), awaited by kap-server close alongside the
  mirror/query-store drains — an event-driven write (e.g. the outcome
  recorder) can no longer land in a session dir while the host removes it

* fix(agent-core-v2): track the metadata dispose flag locally

Disposable exposes no public isDisposed accessor; keep a class-local flag
set in the dispose override.

* fix(kap-server): drain session metadata writes before the mirror and disposal

A write still in flight when close() begins must settle before the mirror
flushes its summary into the read model and before scope disposal marks
the service disposed — not after.

* fix(agent-core-v2): reattach the recorder when the main agent is recreated

Review follow-up: a failed bootstrap still fires onDidCreate before the
handle is dropped; the subscription then pointed at a dead bus and the
guard blocked any later reattach. Track onDidDispose and reset so the
next main creation attaches cleanly.

* test(agent-core-v2): resolve the recorder through the scoped DI harness

Review follow-up: construct SessionOutcomeRecorder via registerScopedService
+ a Session-scope test host (stubbed lifecycle/metadata), so the test covers
the production registration path; add the durable-value adoption case.

* fix(agent-core-v2): unbreak CI — iterable Promise.all and the debug channel surface

- Promise.all takes the pending-writes set directly (oxlint error)
- the disposed flag moves into a _register'd marker instead of a public
  dispose() override, which the debug channels listing (and its test)
  correctly rejects as framework plumbing

* fix(kap-server): surface persisted failures on the v2 session status

The v2 list folds the outcome into activity.status, which previously
read only live facts — a cold session always looked idle. Cold sessions
now map a persisted failed outcome to status 'failed' (completed and
cancelled stay idle, matching the live fold); warm sessions are
unchanged, and the statuses filter inherits the mapping.

* refactor(agent-core-v2): name the persisted field lastTurnReason

Aligns with the established name for the same concept end to end
(activity view's lastTurnReason, the v1 wire's last_turn_reason, and the
SessionSummary mirror), instead of introducing a third variant.

* fix(agent-core-v2): drain pending metadata writes before session teardown

Review follow-up: closing/archiving a session right after a turn ended
could dispose the scope while the outcome write was still queued, and
delete() removes the session dir immediately after close. Await the
pending metadata writes before the handle goes away.

* fix(node-sdk): carry lastTurnReason through the SDK session summary

Review follow-up: the in-process SDK path maps the engine summary through
v2SummaryToSessionSummary, which dropped the new outcome field. Add it to
the public SessionSummary type and the mapper; the parity gate projects
it away (the v1 engine never records an outcome).

* fix(node-sdk): populate lastTurnReason on live SDK summaries

Review follow-up: resumeSession/reloadSession build their summary from the
live session's metadata document, which now carries the outcome — surface
it there too so the SDK reports it consistently for live and listed
sessions.

* fix(agent-core-v2): carry the last turn outcome across session forks

Review follow-up: fork skips state.json when copying the session dir, so
the fork's fresh metadata never had the outcome and a restart dropped a
marker the warm fork was still reporting. The fork's metadata patch now
inherits the source's lastTurnReason.

* fix(agent-core-v2): settle pending outcome writes before reading a fork source

Review follow-up: a fork requested right after the source's turn ended
could read the metadata before the recorder's queued write landed,
inheriting a stale or absent outcome. Drain pending metadata writes
first.

* fix(agent-core-v2): backfill restored outcomes into the session metadata

Review follow-up: for sessions whose last turn ended before this field
existed, the cold-resume seed restores the outcome into the activity view
without a turn.ended fact, so the recorder never persisted it and cold
listings stayed blank. The recorder now also watches the main agent's
activity updates and backfills the restored outcome when nothing is
persisted yet.

* fix(agent-core-v2): never backfill restored cancellations

Review follow-up: a restored 'cancelled' cannot be told apart from a
programmatic abort (the activity event carries no interruptReason), and
those are never persisted. Backfill now covers only completed/failed;
user stops are still persisted from the live turn.ended fact.

* refactor(agent-core-v2): rename the outcome recorder to outcome mirror

Mirror is the codebase's established term for a write side that reflects
live state into a store (SessionIndexMirror); Recorder has no precedent.

* fix(agent-core-v2): backfill without bumping recency; header-only comments

Review follow-ups:

- a mere resume must not float an old session to the top of the list:
  metadata updates accept touchUpdatedAt:false and the outcome mirror's
  backfill uses it (live outcome writes keep bumping — turn end is a
  recency moment)
- the mirror service's inline notes move into the file header per the
  package comment convention
- drop the redundant |undefined from the SDK's optional outcome field

* fix(node-sdk): read the live outcome for resumed session summaries

Review follow-up: on a fresh resume the restored outcome can still be
queued as a metadata backfill, so the document may lag a tick; the live
activity aggregate already holds it. Resume/reload summaries now prefer
the live value and fall back to the metadata field.

* fix(agent-core-v2): confine the outcome backfill to pure resumes

Review follow-up: the view publishes its turn.ended fold before this
mirror's own turn.ended handler runs, so a live ending reached the
backfill branch first and got persisted without the recency bump. The
backfill now only applies when no turn ever started in this process —
live endings always take the bumped write.

* fix(agent-core-v2): drain the session-index mirror before session teardown

Review follow-up: settling the metadata write alone left the fresh
summary in the mirror's pending queue, so a list right after close could
read a stale outcome from the read model. close/archive now also drain
ISessionIndexMirror. Test harnesses register a mirror stub for the new
dependency.

* docs(agent-core-v2): fold the metadata drain contract into the file header

* chore: include the SDK package in the changeset; fold the drain note into the header

* fix(agent-core-v2): backfill restored cancellations too, quietly

Review follow-ups: dropping every restored cancel loses legitimate user
stops whose live write never landed (or was rejected) before a restart —
cold surfaces never mark cancelled anyway, so healing them is harmless
and strictly more accurate. The metadata disposal note moves into the
file header per the comment convention.

* fix(node-sdk): prefer the live outcome over the index in SDK listings

Review follow-up: a live session that just started a new turn after a
failure can briefly keep the stale outcome in the index while the
mirror's clear is queued. listSessions now reads the live activity
aggregate for warm sessions, matching the kap-server cold-only fallback.

* fix(node-sdk): never read the metadata outcome for a live session

Review follow-up: with a retry in flight the live aggregate has no
outcome while the document may still hold the previous failure — the
fallback showed the stale one. Live summaries now take the live
aggregate's answer alone; the restored outcome is already seeded there
on resume.
2026-08-06 20:14:05 +08:00
liruifengv
e6e4ba2357
chore: sync web dist from code-app (#2697)
* chore: sync web dist from code-app

* chore: add changesets for the synced web UI changes

* chore: drop changesets already covered by the previous web bundle sync

* chore: correct the drop-folder changeset for web

* chore: drop the drop-folder changeset (desktop-only feature, no web announcement)
2026-08-06 19:58:01 +08:00
Haozhe
02c026d487
feat(agent-core-v2): tombstone removed MCP servers and freeze plugin prompt inputs (#2694)
* feat(mcp): tombstone removed MCP servers and apply plugin changes immediately (20 files)

- add 'removed' MCP server status: workspace config removals call markRemoved
  instead of remove, keeping tool registrations alive while short-circuiting
  calls with a removal notice
- fire onDidReload after every plugin mutation (install/enable/disable/remove)
  so workspace consumers refresh contributions immediately
- TUI renders the removed status in the MCP panel/startup summary and shows an
  apply-immediately hint on the v2 engine

* feat(agent-core-v2): freeze plugin prompt inputs for live agents (2 files)

- snapshot the model skill listing and plugin system-prompt sections on the
  first successful prompt build and reuse the frozen values for the agent's
  lifetime, so plugin install / enable / disable / remove / reload never
  rewrites a live agent's prompt (same keep-live-sessions-stable philosophy
  as the MCP tombstone)
- freeze only on success: a not-yet-ready skill catalog or a failed
  enabledSystemPrompts() read must not pin empty values for the agent's
  lifetime
- refreshSystemPrompt still rebuilds on catalog change events but reuses
  the frozen values, so the prompt only moves when non-plugin inputs change
  (AGENTS.md, [tools] section, session tool policy, compaction); new agents
  snapshot the then-current state

* chore(changeset): add changesets for MCP tombstone and frozen plugin prompt inputs

* docs: describe immediate plugin changes and the removed MCP status on the v2 engine

* fix(klient): mirror the removed MCP server status in the wire contract

* docs: drop the legacy-engine behavior notes from the plugin and MCP pages

* fix(agent-core-v2): freeze plugin sections only on a loaded snapshot

- enabledSystemPrompts() resolves to its consumption fallback (never
  rejects) while the initial plugin load has failed; freezing that empty
  read locked plugin sections out of the live agent even after a later
  successful reload
- expose hasLoadedSnapshot() on IPluginService so resolvePluginSections
  can tell a real empty snapshot from the fallback before freezing
2026-08-06 19:19:51 +08:00
liruifengv
cfd14a1fe2
feat(kap-server): accept attachments on skill activation (#2693)
* feat(kap-server): accept attachments on skill activation

The :activate endpoint only took {args?}, so REST clients (web/desktop
composers) could not attach uploads to a /skill invocation — attachments
were silently dropped at the edge.

- activateSkillRequestSchema gains an optional attachments field carrying
  the image/video/file subset of the prompt content wire shape.
- The skills route resolves them through the same edge pipeline as prompt
  submissions (validate file refs → materialize/compress → convert),
  extracted from routes/prompts.ts into lib/promptMedia.ts.
- AgentSkillService.activate appends the resolved parts after the rendered
  skill prompt in the activation's user message; SkillActivationInput
  gains an optional content field. The native RPC/TUI path is unchanged.
- Attachment failures map to 40407 file.not_found / 40001
  validation.failed, mirroring the prompts route.

* fix(kap-server): drop the unused parseKimiFileUrl import in promptMedia

* refactor: address review — header-only comments in the skill domain, provider id on protocol URL sources

- agent-core-v2 keeps comments solely in the top-of-file block (scoped
  guide): SkillActivationInput.content documented in the skill.ts header,
  the activate() note folded into the skillService.ts header.
- packages/protocol's image/video URL source gains the optional
  provider-issued id, matching the kap-server wire schema so parsing the
  public contract no longer strips it.

* fix(kap-server): validate the skill before materializing activation attachments

An unknown or non-user-activatable skill name with attachments ran the
media pipeline first, streaming bytes into the session/cache dirs and
compressing images for a request that activate() would reject with
40415/40912. The route now checks the session catalog up front (the
service still re-validates) so invalid activations leave no disk or CPU
side effects.
2026-08-06 19:09:32 +08:00
Haozhe
4d39f4fa6f
fix(agent-core-v2): omit max_context_tokens in REST session status when unknown (#2696)
- align the REST status rollup with the WS push: a bound alias that no
  longer resolves omits max_context_tokens instead of reporting 0 (0 is the
  engine's UNKNOWN_CAPABILITY marker, not a real limit)
- fall back to the default model's limit only when no model is bound,
  resolved through IModelService like the WS side
- mark max_context_tokens optional in the shared session status schema
2026-08-06 18:50:16 +08:00
Haozhe
8c766a6c30
feat(agent-core-v2): add the L3 unit layer and the Feature seam (#2678)
* feat(agent-core-v2): add the L3 unit layer and the Feature seam

- introduce the L3 Service/Fiber unit layer: the Service base class with this.provide/effect/on/get/ref capabilities, the fiber runtime with thenable FiberHandles, collection contribution points, and the per-scope-kind ScopeUnits materialization fold
- provide each scope's static registration batch as one atomic provideAll cascade transaction (waiting-area activation, sticky Failed on construction error)
- add the DI unit inspection surface: App-scope debug ledger / dependency graph / cascade history services and the kimi-inspect DI view
- add the Feature unit seam (IFeatureManager + feature assembly), port plan mode onto it, and add the contributed-command seam (agent-command domain + node-sdk RPC types)
- remove the legacy dep-graph tooling
- apply the header-only comment convention across src and test: strip non-header narration, keep the file header, tooling pragmas, and NOTE comments

* feat(kap-server): gate the event.di.* debug feed to kimi-inspect connections

- add an opt-in target set in SessionEventBroadcaster; the global fan-out
  now skips event.di.* frames for connections that never opted in, so
  kimi-web and other clients no longer receive the high-churn DI feed
- WsConnectionV1 opts a connection in when client_hello carries
  client_id 'kimi-inspect'; removeGlobalTarget drops the opt-in on close
- temporary gate until a client-declared event-type whitelist lands

* chore(agent-core-v2): fix oxlint errors in the DI unit layer

- build the live-ref container chain without aliasing this (no-this-alias)
- snapshot the materialized map with Array.from and document why the copy
  is required (no-useless-spread)

* test(klient): use string scope kinds in the lifecycle handle fakes

The engine's LifecycleScope is a string enum now; the facade test doubles
still returned the old numeric kinds and failed the handleWireSchema output
validation.

* build(nix): update the pnpmDeps fetch hash
2026-08-06 18:22:36 +08:00
qer
ef61084009
fix(kimi-code): select compatible PowerShell for Computer Use (#2686)
* fix(kimi-code): select compatible PowerShell for Computer Use

* fix(kimi-code): handle locked Computer Use plugin files

* fix(kimi-code): align Windows Computer Use name

* fix(agent-core-v2): reuse PowerShell fallback for detection

* fix(agent-core-v2): refresh ready Computer Use plugin
2026-08-06 18:08:28 +08:00
liruifengv
7b2784b9b7
feat: surface the bound model and thinking effort on subagent UIs (#2679)
* feat: surface the bound model on subagent UIs

The subagent.spawned event now carries the display-normalized model alias
(the derived __secondary__ entry resolves to its base alias), so clients can
show which model a subagent is bound to. The TUI subagent card, swarm panel
header, and background-agent entry show it at spawn; the WS snapshot roster
and REST /tasks (background/detached subagents) carry it too, keeping the
model visible across client reconnects.

* feat: carry the subagent thinking effort alongside the model

The spawned event, snapshot roster, and REST /tasks now also carry the
child's effective thinking effort (read from the child profile at spawn, the
same vocabulary as agent.status.updated). UIs show it only when it diverges
from the main session's current effort — an inherited level adds no
information, and 'off' is never shown.

* feat(tui): show the bound model and effort in the /tasks browser

The task browser's Detail pane renders Model and Effort rows for agent
tasks (raw alias and level — it is the inspector surface, so no diff
filtering), and its minimum height grows to fit the new rows. The values
were already persisted on SubagentTaskInfo; the TaskInfo union, its zod
schemas (protocol, kap-server, klient contract), and the v1 type
declaration now carry them so nothing strips them in transit.

* feat(tui): show concrete subagent effort levels unconditionally

Display rule simplified: any concrete effort tier (low/high/max/…) is
shown next to the model — including when it matches the main session's
level. Only the boolean states stay hidden: 'off' (no thinking) and 'on'
(generic thinking) carry no level information.

* docs: trim the changeset entry

* fix(tui): keep the model and effort on background-agent entries across resume

replayBackgroundProjection only copied agentId/parentToolCallId/
description, so a background subagent that outlived a resume lost its
model/effort on the later terminal transcript entry. The projection now
threads the persisted values (catalog-mapped model; boolean effort states
dropped), and session replay passes the loaded model catalog through.

* fix(agent-core-v2): normalize the derived secondary alias regardless of the flag

A child bound while the secondary-model experiment was on keeps
__secondary__ in its persisted binding; if the flag is later switched off
with the recipe still configured, resolveSecondaryModel() gated the
normalization and the sentinel leaked back onto resumed subagents.
subagentDisplayModel now reads the recipe straight from config (the flag
gates new bindings, not the interpretation of existing ones), which also
drops SessionSwarmService's now-unused IFlagService dependency. Also adds
the SDK package to the release: the new SubagentSpawnedEvent/AgentTaskInfo
fields are SDK-visible types.

* fix(agent-core-v2): normalize the status-frame model at the source

A derived-bound child republishes agent.status.updated right after spawn
with its raw modelAlias, which overwrote the spawned event's normalized
display model on single-subagent cards (swarm headers were first-wins and
escaped). emitStatusUpdated now maps through subagentDisplayModel, a no-op
for the never-derived main agent. Also moves the inline comments added by
this branch into top-of-file headers per the v2 comment convention.

* fix(tui): clamp the /tasks detail frame to the available body

At terminals near the minimum height the forced 10-row detail frame
overflowed the body and truncated the preview frame's border. The detail
height now caps out at whatever leaves the preview its borders plus one
content row, with a regression test at exactly MIN_HEIGHT.

* fix: normalize inherited derived aliases and keep model/effort on replayed terminal entries

- resolveSubagentBinding's caller-fallback branch also maps through
  subagentDisplayModel: a caller itself bound to the derived entry (a
  resumed subagent making a nested Agent call) no longer publishes
  __secondary__.
- The replayed background-task terminal notification builds its metadata
  with the persisted model (catalog-mapped) and concrete effort, matching
  the live completion path.
- Drops the inline comments this branch added inside v2 test bodies; the
  scenario context lives in the source file headers.
2026-08-06 16:59:45 +08:00
qer
013203421d
fix(tui): surface capability install errors (#2682)
Some checks are pending
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / build (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
2026-08-06 14:02:59 +08:00
liruifengv
3c75a27da6
feat(tui): add cache-expiry hint dialog for resumed and idle sessions (v2 engine) (#2646)
* feat(agent-core-v2): detect prompt-cache breaks from per-step usage and emit telemetry

Track consecutive turn-scoped LLM requests per agent; when the cache-read
token count drops by more than 5% and by more than 2000 tokens between
requests, log a debug line and emit cache_break_detected with both usages,
the drop ratio, and the interval. Operation requests (e.g. compaction) act
as a baseline barrier so expected drops are not reported.

* feat(tui): add cache-expiry hint dialog for resumed and idle sessions (v2 engine)

Resuming a long-idle session or submitting after a long idle stretch
re-sends the whole history with an expired context cache. Show a dialog
offering to compact, start a new session, continue as-is, or never ask
again (persisted as cache_expiry_hint in tui.toml). Thresholds come from
the client_configs endpoint (estimated_cache_duration) via a generic
per-name cached client; only OAuth-managed providers participate.

* fix(tui): preserve submit order and revalidate session in cache-hint flows

Cold-cache submits during the in-flight config fetch are now swallowed and
replayed through a FIFO chain, so a later prompt can never overtake the
stashed one. Both the resume and idle paths re-check the current session
after the async fetch: a switch mid-flight drops the dialog (resume) or
hands the stashed input back to the editor instead of sending it into the
wrong session (idle).

* chore(agent-core-v2): regenerate state manifest after merging main

* fix(tui): apply cache_expiry_hint on /reload and /reload-tui

* fix(agent-core-v2): skip unmeasured all-zero usage in cache break detection

* fix(tui): restore chained cache-hint submits when the dialog is not sent

When several submits are swallowed during the cold-config fetch and the
first dialog is dismissed (or its compact/new action fails), the stashed
inputs were restored while later chained submits were still released —
reordering the conversation. Chained submits now follow the fate of the
message that opened the dialog, and multiple restores append newline-joined
instead of overwriting the editor.

* fix(agent-core-v2): reset cache-break baseline on model change

Caches are per-model, so a cache-read drop after /model is expected, not a
break. The baseline now carries the model and only same-model records are
compared.

* fix(tui): only count LLM-activity replay records for the resume cache hint

The v2 resume replay also carries local-only state records (permission,
plan, config updates, approval results) that slash commands append without
an LLM request. Filter lastActiveAt to message/compaction records so a
recent local change no longer masks an expired cache.

* style(agent-core-v2): rewrite the cacheBreak impl header per package convention

State the domain role, collaborators, and scope instead of narrating
implementation steps; the behavior guards now live in the code alone.

* fix(tui): drop the resume cache hint when a turn started mid-fetch

The resume dialog is fire-and-forget over an async config fetch; if the
user already sent the first prompt by the time it resolves, mounting would
overlay an active turn and its actions would hit the live session. Re-check
streamingPhase/isCompacting after the await, next to the session check.

* style(agent-core-v2): trim the cacheBreak contract header to contract and scope

* refactor: report cache-break detection from the TUI client

Move the detector out of the engine so the telemetry event carries the
client's own identity (which client produced it is now attributable). The
TUI observes main-loop turn.step.completed usage directly, with the same
guards: first-step/unmeasured/all-zero records skipped, model change and
compaction reset the baseline. The agent-core-v2 cacheBreak module is
removed.

* chore: drop accidentally committed dist-web build output and ignore it

* chore: revert the dist-web ignore rule

* chore: restore dist-web to the tracked content from main

* feat(tui): record cache breaks caused by mid-session model/effort switches

A model or effort change mid-session busts the prompt-cache key — that is
a real cache break worth attributing, not noise. The baseline now carries
model and effort, the same-model exemption is gone, and cache_break_detected
reports prev/curr model and effort alongside both usages.

* chore(changeset): simplify the cache-expiry hint entry

* chore(changeset): trim the cache-expiry hint entry to one line

* fix(tui): cache-hint review follow-ups

- carry the pre-dialog media extraction through compact/new resends so
  pasted attachments survive the image-store clear on a new session
- reset the cache-break baseline after /undo — the context cut makes the
  next cache-read drop expected
- release the stashed submit when a foreground operation started during
  the cold-config fetch instead of mounting the dialog over it
- count a completed compaction as activity so the next submit is not
  judged against the pre-compaction timestamp

* chore(changeset): drop the v2-engine-only suffix

* fix(tui): seed the activity baseline when the resume check skips

* fix(tui): cache-hint review follow-ups

* fix(tui): record cache activity on completed steps, not turn begin

* feat(cli): persist the client-configs cache across restarts
2026-08-06 13:26:37 +08:00
liruifengv
713bf1a5a2
fix(kimi-code): render v2 background task notifications on session replay (#2677)
* fix(kimi-code): render v2 background task notifications on session replay

* chore: add changeset for v2 task notification replay fix
2026-08-06 13:00:53 +08:00
Haozhe
34c4181437
fix(kimi-code): keep kimi -p alive while background tasks are pending (#2675)
The 10-year default print wait ceiling (315360000s) overflowed Node's
setTimeout limit (2^31-1 ms) into a 1ms fire, so the steer/drain wait
returned instantly and kimi -p exited right after the main turn, killing
pending background tasks and subagents.

- add setClampedTimeout in agent-core-v2 _base, clamping delays to
  MAX_TIMER_DELAY_MS, and route every config-driven timer through it
  (timeoutOutcome, task wait/manager timeout, swarm attempt timeout)
- chunk the print turn-endings wait against the real deadline instead of
  returning null on the first clamped timer fire
- restore v1 semantics: a non-positive swarm subagent timeout is unbounded
- default print_wait_ceiling_s to 2147483s (~24.8 days, the timer maximum)
2026-08-06 11:02:34 +08:00
Haozhe
7bd3fd9f6e
feat(agent-core-v2): read UTF-16 text files by transcoding to UTF-8 (#2647)
- detect UTF-16 LE/BE from a BOM or a zero-byte parity heuristic
  (tolerant of CJK content), derived from VS Code's encoding detection
- Read tool and workspace fs.read transcode UTF-16 text to UTF-8
  instead of refusing it as binary; larger than 10 MiB still refused
- refuse other non-UTF encodings (e.g. GBK) with a clearer message
2026-08-06 10:39:21 +08:00
qer
d1ded01b7c
fix(agent-core-v2): seed the activity view's lastTurn from the persisted turn.ended record (#2648)
Some checks are pending
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* fix(agent-core-v2): seed the activity view's lastTurn from the persisted turn.ended record

A cold-resumed agent seeded its activity view only from live loop/task
state, so the last turn's outcome was lost on a server restart: sessions
came back with no lastTurnReason, and clients could not surface a
previously failed turn (e.g. a provider 429 that killed the turn before
the restart).

The loop already persists the terminal turn.ended record (reason, error,
durationMs); fold the latest one into the TurnModel as lastEnded and have
AgentActivityView.seedFromLoop adopt it when no turn is active, so the
session work aggregate (and everything built on it) reflects the last
turn's outcome again after a cold start.

* fix(agent-core-v2): seed lastTurn on wire restore and add a changeset

Review follow-up: the agent scope (and with it this view) is constructed
before wire.restore() replays the journal, so a constructor-time read of
TurnModel.lastEnded always saw the initial state on a cold resume. Move
the wire-backed seed behind the onDidRestore hook (constructor seed kept
for views built after a restore), and drop the inline comments in favor
of the file header per the package comment convention.

* docs(agent-core-v2): trim the activityView header to role and collaborators

Review follow-up: the previous revision narrated the restore-hook
mechanics in the header; the package convention keeps headers at the
module's external role plus collaborators, so drop the implementation
narrative.

* fix(agent-core-v2): keep TurnModel.lastEnded across clock advances

Review follow-up: advanceTurnClock built a fresh state object without
spreading, so a new prompt or a queued cancel silently dropped the stored
last-ended outcome even though no new turn had ended — after a restart the
activity view would again find nothing to seed. Spread the prior state and
cover the prompt/queued-cancel/replace cycle with a model-level test.

* fix(agent-core-v2): clear the stored turn outcome once a newer turn starts

Review follow-up: with the clock advances preserving lastEnded, a prompt
persisted without its turn ever starting would leave the previous turn's
outcome to be seeded after a restart, reporting a stale result for a turn
that never ended. The loop-event fold now drops lastEnded as soon as a
newer turn's events land, while prompts and queued cancels keep it.

* docs(agent-core-v2): keep the turnOps header at the domain role

Review follow-up: the lastEnded keep/clear mechanics read as
implementation narrative in the header; the convention there is role and
collaborators only.
2026-08-06 01:07:22 +08:00
qer
68ba740ebf
feat(kimi-code): support Kimi Computer Use on Windows (#2652)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
2026-08-05 21:15:02 +08:00
Haozhe
2b893733f9
fix(kap-server): bypass Node arg quoting for explorer /select, on Windows (#2645)
explorer.exe parses its raw command line rather than argv, so Node's
default spawn quoting breaks the `/select,` argument whenever the path
contains spaces: the command line becomes `"/select,\"C:\...\""`, which
explorer rejects, silently opening the Documents folder instead of
selecting the file. Quote only the path portion and launch with
windowsVerbatimArguments so the command line keeps the documented
`/select,"C:\some dir\f.txt"` form.
2026-08-05 20:15:27 +08:00
Haozhe
510fbe7ec5
refactor(kap-server): wrap /api/v2/sessions in the v1 response envelope (#2644)
- return the domain-grouped page payload inside { code, msg, data,
  request_id } and carry business outcomes in code (40001 invalid
  params with details, 40922 page_token mismatch) instead of raw HTTP
  statuses plus an { error: { code, message } } body
- add ErrorCode.PAGE_TOKEN_MISMATCH (40922)
- register the route via defineRoute (shared runtime validation and
  envelope-wrapped OpenAPI docs); fold include-domain validation into
  the query schema and replace the preprocess/doc-twin pair with
  scalar-or-array union params
- update the kimi-inspect client to unwrap the envelope and sync the
  two AGENTS.md guides
2026-08-05 18:20:00 +08:00
Haozhe
6f1cd7ca22
feat: add v2 sessions API and spreadsheet-like session table in kimi-inspect (#2640)
- kap-server: add GET /api/v2/sessions with a domain-grouped response
  (workspace / meta / activity, opt-in git), status / archived /
  updated_after filters, three sort orders, and fingerprint-bound opaque
  cursor pagination
- kimi-inspect: rebuild the chat sidebar as a spreadsheet-like session
  table on the v2 endpoint — preset views (All / Opened / Archived /
  By workspace / Git), column visibility config, header sort toggles,
  cursor-paged Load more, and localStorage-persisted panel prefs
- live activity frames from the WS hub override the REST status badge;
  session created / meta-updated events invalidate the v2-sessions query
2026-08-05 17:28:11 +08:00
7Sageer
858812193a
fix(kimi-code): open /feedback to all signed-in users (#2639)
* fix(kimi-code): open /feedback to all signed-in users

Gate the command on holding a kimi-for-coding OAuth token instead of
the active model's provider, so signed-in users on API-key models can
also submit feedback through the authenticated channel. When signed
out, open the sign-up page alongside GitHub Issues.

Also harden the failure paths: a failing auth status lookup or a
rejected submit promise now falls back to GitHub Issues, while
attachment-stage failures degrade to a non-fatal partial failure
instead of triggering the fallback.

* fix(kimi-code): print sign-up and issue links for signed-out /feedback

Opening two browser pages at once is jarring; just print the links in
the transcript instead.
2026-08-05 17:27:54 +08:00
liruifengv
7c919f0376
docs(changelog): sync 0.33.0 from apps/kimi-code/CHANGELOG.md (#2636)
* docs(changelog): sync 0.33.0 from apps/kimi-code/CHANGELOG.md

* docs(changelog): move the v2 engine entry to Refactors and the trust prompt to Polish
2026-08-05 16:46:10 +08:00
github-actions[bot]
53c832dfdf
ci: release packages (#2592)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-05 16:21:32 +08:00
qer
2b3e9a9f79
fix(tui): clarify curated plugin marketplace (#2635) 2026-08-05 16:18:50 +08:00
liruifengv
7a631522fb
chore(changeset): trim the v2 engine entry and drop the custom identity entry (#2634) 2026-08-05 16:08:42 +08:00
liruifengv
421e8f8065
fix(minidb): silence the transform-types warning from the dev worker (#2632) 2026-08-05 15:53:13 +08:00
liruifengv
3bd098b806
chore(changeset): add changesets for the v2 TUI and web UI updates (#2630) 2026-08-05 15:27:27 +08:00
qer
75fe068a01
fix(cli): stabilize built-in capability installation (#2601)
* fix(cli): show built-in capabilities before the first session exists

The lazy-session refactor left capability calls going through
requireSession(), so on a session-less v2 startup /plugins reported the
capabilities unavailable and hid the built-in rows behind the promo.
Like plugin management, capability readiness and installs are app-global
on the v2 engine: the node-sdk harness gains a capability facade over
the global channel, and the TUI resolves session-or-harness for every
capability call.

* fix(cli): count the dev marketplace server as the default catalog

dev.mjs always points KIMI_CODE_PLUGIN_MARKETPLACE_URL at its own
repo-serving server, which the override gate mistook for a user-configured
marketplace and suppressed the built-in capability rows in every dev run.
The dev server now marks itself, and the gate treats that marked URL as
the default catalog while still honoring real overrides (slash-command
source, user-set env, KIMI_CODE_DEV_MARKETPLACE_URL).

* fix(cli): align built-in capability updates
2026-08-05 14:55:04 +08:00
Haozhe
f881cdd970
feat(cli): default CLI surfaces to the agent-core-v2 engine (#2627)
Some checks are pending
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
* feat(cli): default to agent-core-v2 engine with KIMI_CODE_LEGACY_FLAG opt-out

- invert the engine gate: isKimiV2Enabled() now returns true unless
  KIMI_CODE_LEGACY_FLAG is truthy; KIMI_CODE_EXPERIMENTAL_FLAG no longer
  selects the engine
- replace the experimental `kimi acp-v2` command with the native v2
  implementation as the default `kimi acp`; the legacy acp-adapter path
  remains under the legacy flag
- drop the acp-v2 experimental flag from the registry
- rename the dev:cli:v2 script to dev:cli:legacy
- update en/zh docs for the new default engine and the legacy flag

* feat(cli): route export and provider through the engine gate

- select the harness via isKimiV2Enabled(): agent-core-v2 by default,
  the legacy harness when KIMI_CODE_LEGACY_FLAG is truthy
- close the harness after each one-shot command so the v2 engine's
  watchers do not keep the process alive
- document both commands in the KIMI_CODE_LEGACY_FLAG env-var entry
2026-08-05 14:42:23 +08:00
7Sageer
e3570280bd
fix(agent-core-v2): bound the project skill-root watch fd footprint (#2612)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* fix(agent-core-v2): bound the project skill-root watch fd footprint

The workspace skill-root source recursively watches the skill-root
candidates with chokidar, which holds one fs.watch fd per file and per
directory on macOS. A skill bundling a large runtime tree can exhaust
the process fd budget and break every subsequent spawn (EBADF).

Mirror the scanner's own pruning (node_modules / dot entries, scan
depth cap) in the watch filter, and add a signal mode to hostFsWatch:
rescan-style consumers get ONE native recursive fs.watch on
darwin/win32, whose fd footprint is constant in the subtree size.

* fix(agent-core-v2): align the skill watch with scanner semantics and harden signal mode

Review follow-up:

- The scanner probes every entry's direct SKILL.md before gating
  recursion, so the watch filter now keeps an excluded entry itself and
  its direct SKILL.md (keepEntryFile) instead of pruning them — skills
  under node_modules / dot directories keep their hot reload.
- The signal-mode native leg now owns its recovery: a native watch
  error fires one root invalidation and re-arms with capped exponential
  backoff; chokidar is used only where recursive fs.watch is
  unavailable, so a transient failure can neither silently end hot
  reload nor downgrade to the per-node watcher.
- Native event path resolution handles absolute filenames and the
  root-basename case, clamping out-of-root events to a root
  invalidation instead of dropping them.
- The event mapping is extracted into NativeSignalMapper with the stat
  call injected, so the native-branch decisions are unit-tested on any
  platform.

* Fix spawn EBADF issue on macOS for large file trees

The skill watcher no longer opens every file it watches, improving performance.

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* fix(agent-core-v2): harden native signal watch recovery

* fix(agent-core-v2): align skill watch with scanner traversal

* fix(agent-core-v2): make skill watch handoff converge

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-08-05 13:47:26 +08:00
Haozhe
2a4990182d
docs: slim root AGENTS.md, move deep package docs to package guides (#2626)
- move the kimi-inspect, kap-server, transcript, and minidb project-map
  entries into new package-level AGENTS.md files
- move the standalone Agent class rule to packages/agent-core/AGENTS.md
- merge root-only agent-core-v2 facts (MCP persistence, trust routes,
  seed contract examples) into packages/agent-core-v2/AGENTS.md
- compress the remaining long project-map entries to summaries with
  pointers, and add an anti-bloat rule for map entries
- drop the stale server-e2e entry; the package no longer exists
2026-08-05 13:43:33 +08:00
Haozhe
4e5f36aa66
test(agent-core-v2): stop the reconcile loop during the sessionIndex read baseline (#2625)
The baseline gates warm reads on behavioral work counts, including zero
directory listings inside each counting window. The service's background
reconcile loop (60s interval) runs an authoritative scan on every tick —
two storage.list calls — and once a slow CI runner stretches the test past
that interval, a tick lands inside a counting window on every attempt and
is attributed to the read under test, failing fsLists === 0 even with the
retry (observed on run 30975794688: 168s across two attempts, fsLists = 2
both times).

Freeze the loop right after prepare() via a new stopReconcileLoop() test
hook (sibling of reconcileNow/reprojectNow). The only remaining directory
listing sources inside a window are the fallback read paths themselves,
so a non-zero count is deterministically a real regression again.
2026-08-05 13:43:22 +08:00
liruifengv
541ddd2d89
chore(web): replace apps/kimi-web with the code-app web bundle (#2599)
* chore(web): remove apps/kimi-web in favor of the code-app web bundle

The web UI source now lives in the code-app repo (apps/web); this repo
only ships the prebuilt bundle at apps/kimi-code/dist-web, synced from
code-app via \.

- delete apps/kimi-web (source, tests, docs)
- root package.json: drop dev:web and the kimi-web typecheck leg
- apps/kimi-code: drop the workspace dep and the build-from-source step;
  replace copy-web-assets.mjs with check-web-assets.mjs so packaging
  fails fast when the committed bundle is missing
- CI: _native-build verifies the committed bundle instead of building
  from source; ci.yml and pkg-pr-new.yml drop the kimi-web legs
- docs: AGENTS.md project map, changeset README, gen-changesets and
  sync-changelog skills now key web UI entries on dist-web

* chore(web): stop ignoring dist-web now that the bundle is committed

The ignore entry predates the code-app sync flow, when dist-web was a
local build artifact. The bundle is now the canonical, committed form of
the web UI, so ignoring it only forces every sync to git add -f.

* docs(skills): drop the web-specific changeset and changelog rules

The web: prefix convention and the web-specific dedup guidance belonged
to the in-repo web app. With the source moved to code-app, web UI
changes follow the same generic rules as any other CLI-bundle change.

* chore(web): add changesets for the web UI changes in the bundle

* chore(web): collapse the bundle changesets into one umbrella entry

* ci: unbreak nix and lint after the kimi-web removal

- flake.nix: drop apps/kimi-web from the source fileset and package
  lists, and verify the committed dist-web in the native build phase
  instead of building the web app from source
- .oxlintrc.json: exclude dist-web (a committed build artifact) now
  that .gitignore no longer hides it from the linter

* ci(nix): update pnpmDeps hash for the post-kimi-web lockfile

* chore(web): resync dist-web from code-app main

Bundle rebuilt from code-app main (upstream parity ports #175, pinned
sidebar #176) with the CLI version 0.32.0 embedded.
2026-08-05 13:38:30 +08:00
Kai
e7d5a0aee7
test(agent-core-v2): give the sessionIndex list baseline CI headroom (#2615)
* test(agent-core-v2): give the sessionIndex list baseline CI headroom

* test(agent-core-v2): retry the sessionIndex baseline once to absorb runner load spikes

* test(agent-core-v2): gate the sessionIndex baseline on work counts, not wall clock

The baseline asserted wall-clock medians (list < 300ms, get/count < 50ms)
plus a relative time check — all still load-sensitive on shared CI runners.
Replace every time assertion with behavioral complexity assertions recorded
at the IQueryStore and fs seams: list must be served by bounded pageByColumn
fetches only, get is a single point lookup, count never touches the session
collection, no warm read enumerates session directories, and the per-op work
snapshot must be identical at 1k, 10k, and 50k sessions. Medians are still
logged for phase-to-phase comparison; the retry now absorbs a background
reconcile tick landing inside a counting window.

---------

Co-authored-by: haozhe.yang <yanghaozhe@moonshot.ai>
2026-08-05 10:59:28 +08:00
zy
2ee6e43124
fix(mcp): re-register the OAuth client when its redirect URI no longer matches (#2620)
The callback listener binds a random port per flow, while DCR
registration records the redirect URI of the flow that created it —
so every interactive authorization after the first was rejected with
"Invalid redirect URI", an error rendered only in the user's browser
while the client waited for a callback that never came. Detect the
mismatch before invoking auth() and drop the stale registration so the
flow re-registers with the current callback URI (v1 + v2).

Resolve #2606

Co-authored-by: zouying <zouying@moonshot.cn>
2026-08-05 10:24:24 +08:00
Kai
8db7d42f23
feat(tui): add /bug as an alias for /feedback (#2614)
Some checks are pending
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
2026-08-04 23:54:21 +08:00
Kai
98ee35afd2
feat(agent-core-v2): add custom agent identity (#2573)
* refactor(agent-core-v2): simplify context tags and shared copy

Rename the context-injection tags to `<skill-loaded>` and
`<plugin-instructions>`, drop the product prefix from the CronCreate tool
description and the default agent description, and point the MCP OAuth
callback page back to "your terminal" instead of naming one client.

The callback page is shared by the ACP host, the web UI, and embedding
hosts, so naming a single client was inaccurate there. The tags and the
two descriptions read exactly the same without the prefix. Verified no
runtime consumer matches the old tag names; the updated snapshots cover
the tool descriptions that changed.

* feat(agent-core-v2): add a switch for the product-documentation skills

Five builtin skills document this CLI itself — `update-config`,
`custom-theme`, `mcp-config`, `check-kimi-code-docs`, and
`import-from-cc-codex`. Their names and descriptions sit in the system
prompt on every turn, which is dead weight for runs that will never
reconfigure the CLI.

Add a top-level `builtin_product_skills` field (also settable through
`KIMI_CODE_BUILTIN_PRODUCT_SKILLS`) to drop them. On by default, so
nothing changes unless it is set; the trade when off is that the model
loses the guided flows for those tasks.

Filtering happens where the catalog is assembled — a later filter would
leave the skills advertised to the model. The whole section is one
scalar, so it exercises the section-level env binding branch and needs
its own strip: `stripEnvBoundFields` only walks object fields, so an env
override would otherwise be written back into `config.toml`.

* feat(agent-core-v2): add custom agent identity

Add an `[identity]` config section (`name`, optional `slug`, both also
settable through `KIMI_CODE_IDENTITY_NAME` / `KIMI_CODE_IDENTITY_SLUG`)
that sets the identity the agent presents: the name it calls itself in
the system prompt, the `User-Agent` product token sent to third-party
providers, and the client name announced to MCP servers. Leaving it
unset changes nothing.

Until now every one of these was fixed, which left no way to run the
agent as part of another product — an internal deployment, a fork with
its own branding, an embedding host.

The identity resolves inside the engine rather than being seeded by each
host, so it applies to every launch surface — including headless runs,
which today seed no display name at all and fall through to the built-in
default.

Two deliberate asymmetries:

- The display name is a filling value with a fallback chain (config >
  host-declared > the consumer's own default); the slug is a rewriting
  value with two states only, so with no identity configured the
  rewriting paths are equivalent to not existing.
- The rewrite happens in the outbound header assembly, the one layer
  that knows which vendor it is building for. Vendors declaring
  `hostHeaders: 'full'` keep the host's own product token, which that
  header set is built around and which backends key on; the configured
  identity applies to the third-party path.

Resolution is lazy throughout: config loads asynchronously, and a
constructor snapshot would freeze the pre-load value under some startup
orderings.

Two input edges the resolver has to absorb, since both would otherwise
reach the User-Agent builder and either break it or quietly rewrite the
header: blank and whitespace-only values read as unset in the file just
as they already did in the env, so a stray `name = ""` cannot claim an
identity; and a name that folds away to nothing under slug
normalization (a CJK-only name, say) falls back to a neutral token
rather than producing a blank product, which the builder rejects.

* fix(agent-core-v2): keep the file value when a scalar env binding fails to parse

`config.ts` documents that an env value failing its binding's `parse` is
ignored, and `applyEnvBindings` honors that for object fields by
assigning only when the resolved value is defined. `applySectionEnv`
returned the parse result straight through for whole-section scalar
bindings, so a blank or mistyped variable resolved to `undefined` and
cleared the configured file value instead of being ignored.

Nothing hit this before: every existing section either binds object
fields or is env-only. `builtin_product_skills` is the first
whole-section scalar binding, where exporting an empty or misspelled
`KIMI_CODE_BUILTIN_PRODUCT_SKILLS` would silently undo a configured
`false`.

* feat(agent-core-v2): extend the custom identity to discovery and global MCP

Two outbound paths still announced the built-in product name under a
configured identity:

- `DiscoveryService` read the host User-Agent straight from bootstrap
  args when refreshing provider models, so custom registries — which are
  third-party endpoints — saw the original token while chat requests to
  the same class of endpoint saw the configured one.
- `SDKRpcClientV2` builds its own global `McpOAuthService` plus a
  throwaway `McpConnectionManager` for server testing, neither of which
  goes through the workspace-owned manager that carries the resolver.

Both now resolve the identity from the App scope.

* refactor(agent-core-v2): neutralize remaining copy and align comments

The synthetic MCP authentication tool description is injected into the
model context and still named the product; it and the OAuth callback
pages now use client-neutral wording. "Return to your terminal" was no
improvement over naming a client — both assume what the host is, and
that page serves the ACP host, the web UI and embedding hosts alike.

Comments introduced by the identity work move into their module headers,
per the domain convention. Interface field docs stay: the rule names
functions, methods and statements, and field-level docs are established
across the codebase.

The new tests gain scenario headers and dispose the scoped hosts they
create, and the `[identity]` docs state which engine reads the section.

* fix(agent-core-v2): read the product-skill switch after config is ready

`BuiltinSkillSource` is the lowest-priority skill source, so the workspace
catalog loads it first — before `IConfigService` has finished loading — and
keeps the contribution it returns for the life of the handler, with no
reload path and no change event. Reading `builtin_product_skills` eagerly
therefore stranded the startup configuration: an explicit `false` could be
ignored for the whole process. `UserFileSkillSource` already awaits config
readiness for exactly this ordering; this source now does the same.

Also record the identity collaborator in the two module headers that gained
the dependency without documenting it, and scope the
`builtin_product_skills` docs to the engine that reads it, matching the
note the identity section already carries.

* fix(agent-core-v2): apply the product-skill switch to session-less listings

`builtin_product_skills = false` only reached the scoped skill source. The
SDK's `listWorkspaceSkills` and the server's `GET /workspaces/{id}/skills`
both composed the raw `BUILTIN_SKILLS` constant, and the web app feeds its
pre-session onboarding menu from that route — so the five product skills
stayed listed until a session existed, then vanished from the session's
catalog.

Move the decision into `visibleBuiltinSkills(enabled)` next to the constant
and route every consumer through it, reading the switch via the shared
`builtinProductSkillsEnabled`. Keeping "what counts as a product skill" in
one place is the point: three copies of the predicate would drift the next
time a builtin is added. The SDK listing also awaits config readiness,
which it did not do before.

* fix(node-sdk): await config before materializing the global MCP OAuth provider

`McpOAuthService` caches providers by store key and stamps the client name
when it first builds one, and the preceding `globalMcpConfig.get()` reads
`mcp.json` directly rather than through `IConfigService`. So a
`beginGlobalMcpServerAuth` call made right after the harness is created
could resolve the identity before config finished loading, pinning the
built-in label for the rest of the process — including the OAuth dynamic
registration a third-party MCP server records.

`testGlobalMcpServer` already awaited config readiness for its own reasons;
this path now does too.

* refactor(agent-core-v2): drop the unused builtin-skill registrar

`registerBuiltinSkills` stamped the raw constant into a catalog for "edge
composition without a Session" — exactly the shape that now has to respect
`builtin_product_skills`. It has no callers in v2 and is not exported from
the package index, so it was dead code that also stood as an invitation to
bypass the switch. v1 keeps its own copy.

Every remaining path composes builtins through `visibleBuiltinSkills`.

* fix(agent-core-v2): send the configured identity on custom-registry imports

`:import_registry` fetched a user-supplied third-party URL with a
hardcoded `kimi-code-kap-server` User-Agent, so the first request to a
registry announced the product while every scheduled refresh of the same
registry announced the configured identity. The hardcoded value was wrong
on its own terms too: that token names the server, and this path also runs
in the CLI.

Both services now project the identity through `identityUserAgent`, which
carries the two guards (no host header, or no identity) once instead of
per caller. The model catalog keeps an inline copy on purpose — kosong is
a foundational layer and must not import an app domain.

Sweeping the remaining outbound User-Agent sources found no further gaps:
WebFetch deliberately sends a Chrome-like UA, the models.dev catalog fetch
sends none from the CLI, and kap-server's `user-agent` reads are inbound.

* docs: scope the identity env vars and condense the changeset

The environment-variable reference advertised all three new variables
without noting that only the agent-core-v2 engine reads them; the
configuration page already carried that note. Added in both locales.

The changeset had grown into two paragraphs of implementation detail,
which is what would land in the CLI release changelog. `gen-changesets`
asks for one short sentence plus at most a one-line usage hint.

* docs(agent-core-v2): describe the identity as what the agent calls itself

The module headers had drifted into describing the feature by what it
keeps off the wire rather than what it configures. Reworded so they state
the capability: the identity is the name the agent uses for itself, and
the unset case is a no-op rather than something "safe". The product-skill
switch excludes skills rather than hiding them.

Wording only; behavior and structure unchanged.

* test(agent-core-v2): cover the identity on custom-registry imports

The import path switched from a hardcoded `kimi-code-kap-server` token to
the host User-Agent projected through the identity, but nothing asserted
it. Two cases pin both halves: a configured identity reaches the request,
and an unconfigured one leaves the host header intact — the second matters
because a single case would also pass if one hardcoded value had simply
replaced another.

Both fail against the previous implementation.

* fix(node-sdk): guard every global MCP OAuth path behind config readiness

`McpOAuthService` caches providers by store key and stamps the client name
when it first builds one, so any path that can materialize a provider has
to run after config has loaded. `beginGlobalMcpServerAuth` awaited
readiness, but `resetGlobalMcpServerAuth` reaches the same cache through
`invalidate()` -> `getProvider()` without waiting: resetting auth right
after the harness is constructed pinned the built-in client name, and the
await added to the begin path could not help because it then reused that
cached provider.

Rather than add the missing await, the accessor is now async and holds the
guard itself, so the service cannot be obtained before config is ready and
a future entry point cannot forget. The remaining `configReady` in
`testGlobalMcpServer` stays — that one is for its own `[mcp]` section read.

* fix(agent-core-v2): send the configured identity on models.dev requests

The directory fetch behind `listModelsDevProviders` / `getModelsDevProvider`
still hardcoded a `kimi-code-kap-server` User-Agent, so browsing or importing
from models.dev announced the built-in product — and claimed to be the server
even when running in the CLI. Only the custom-registry import had been fixed.

`getModelsDevCatalog` now takes the User-Agent from its caller: the module is
plain module-level state with no container access, and the value depends on
the host and the configured identity, which only the calling service can see.
All four third-party fetches in that service share one helper.

Where the host states no User-Agent, a neutral token stands in rather than
dropping the header — these are directories the service chooses to call, so
there is no host intent to preserve, unlike the provider requests the model
catalog assembles.

Both new tests fail against the previous hardcoded value.

* test(agent-core-v2): assert the product-skill set literally

The expected sets were derived from the same `productSpecific` field the
production filter reads, so a builtin silently losing its marker would just
move between sets and leave every assertion green — while staying visible to
the model once the switch is off. The five names are now literal, with a test
asserting the marked set matches them exactly.

Dropping the marker from one skill now fails four tests instead of none.

Also states the App scope in the identity contract header, per the domain's
comment convention for contract files.

* fix(agent-core-v2): normalize the host-declared display name too

Blank and padded values were normalized on the config side but not on the
host fallback, so an embedding host passing `displayName: "   "` rendered
"You are   ," into the system prompt, and a padded name kept its padding.
Same rule now applies to every source of the name.

Also names `agentIdentity` as the collaborator in the request-headers
adapter header, which described the value it obtains without saying which
domain resolves it.

The three new cases fail against the previous implementation.

* fix(agent-core-v2): keep the configured slug when the host sends no User-Agent

The neutral fallback added for hosts that state no `User-Agent` discarded a
configured identity along with it: `identityUserAgent` returns `undefined`
as soon as there is no host header to rewrite, so `?? DEFAULT_IDENTITY_SLUG`
sent the literal `agent` even when `[identity].slug` was set — precisely the
case that fallback exists to serve. The configured slug now stands on its
own, with the neutral token reserved for having neither.

The four combinations of (host header, configured slug) had three tests; the
missing one is the one that was wrong. It now fails without this change.

`outboundUserAgent` also awaits config readiness before reading the identity,
so a browse issued right after bootstrap cannot send the pre-load value — the
guard lives in the accessor rather than at its four call sites, matching how
the same race is handled elsewhere in this branch.

Both headers here and in `discoveryService` now name `agentIdentity` as the
collaborator resolving that token.

* test(acp-server): follow the renamed skill-activation tag

`acp-server` arrived on main after the tag rename, so its two assertions
still expected `kimi-skill-loaded` and failed once the branches met. Also
updates the web app's CSS comment, which named the old tag from the start
of this branch — a comment, so nothing ever failed on it.

Found by CI: the merge verification only ran agent-core-v2's suite, and
this package is neither a dependency nor a dependent of it.

* fix(agent-core-v2): present the configured slug on registry refreshes too

The previous round taught the import path to fall back to the configured
slug when the host states no `User-Agent`, but left the scheduled refresh
of the same registry on the bare projection — so one registry could see
`acme` on import and the runtime default on refresh.

Extracting `identityUserAgent` had made the two paths share a function
without sharing the policy. The choice itself is now the shared piece:
`identityUserAgentOrDefault` always yields a value, for the directories
this process chooses to call, while `identityUserAgent` stays the form
that rewrites only what the host already sends — what a provider request
needs, where the host's silence is its own choice.

* docs(agent-core-v2): move new member docs into the module headers

The domain's comment convention is absolute — comments live solely in the
top-of-file block — and I had read the "functions, methods, or statements"
clause as leaving interface members out. It does not: only 25 of 734 v2
sources carry an indented block, so the members I documented were the
exception, not the pattern.

Seven members across six files move into their headers. `types.ts` had no
header at all, so it gains one.

* fix(agent-core-v2): connect session MCP overlays after config is ready

The shared manager reaches `connectAll` through `initialize()`, which awaits
the config domain first; `sessionOverlay` called it straight away. A session
carrying ephemeral `mcpServers` created right after bootstrap therefore
resolved the client name before config had loaded and initialized under the
built-in one.

The blast radius is wider than that one connection: a remote server sends
the overlay through `hasTokens()`, which materializes an OAuth provider on
the *shared* service and caches it by store key — so the early name outlives
the connection that raced. The overlay now connects behind `mcpConfig.ready`,
leaving the returned readiness promise unchanged.

* fix(agent-core-v2): reload builtin skills when their switch changes

The workspace catalog keeps each source's contribution for the life of the
handler, so a `builtin_product_skills` toggle never reached an existing
handler's sessions. That was harmless while every surface read the same
constant — but routing the session-less listings through the config made the
two views disagree, since those read the switch on every call.

Follows `ExtraFileSkillSource`: subscribe to the owning section and fire
`onDidChange`, which the catalog already turns into a source reload. The
test asserts an unrelated section does not trigger it.

* fix(agent-core-v2): apply the identity to self-configured web services

`[services.moonshot_search]` and `[services.moonshot_fetch]` name their own
`base_url`, so both services can point at an endpoint the user chose — but
each forwarded the host request headers verbatim, sending the built-in
product token there under a configured identity.

Only the services-config path is rewritten; the managed OAuth path keeps the
host headers as they are, being the endpoint the session authenticated
against. The distinction is the same one the model catalog draws per vendor.

`identityHeaders` carries the rewrite across a whole header set, so this is
the fourth caller sharing the projection rather than repeating its guards.
A pair of tests pins both halves.

My earlier sweep classified these two as official by their names instead of
asking who chooses the URL, which is why they were missed. The contract
header is also condensed here, per the convention below.

* docs(agent-core-v2): condense the identity headers to their contracts

The comment convention is one sentence with two halves — comments live only
in the top-of-file block, *and* that block states the module's role without
narrating implementation. Moving the member docs up last round satisfied the
first and broke the second: the headers ended up spelling out the slug
folding algorithm, the strip mechanics, and the load order.

Kept what a caller or the next editor would get wrong without it (why the
value is read rather than snapshotted, what `undefined` obliges a consumer
to do, why this source waits for config). Dropped what the code already
says. 22/12/12/13 lines, against 53 in `catalogService.ts` — length was
never the problem.

* fix(agent-core-v2): rebuild active prompts when the builtin skills change

Reloading the catalog on a `builtin_product_skills` toggle left existing
agents holding the old listing: `AgentProfileService` refreshes the prompt
only for the plugin source, so a disabled switch kept advertising skills
that were gone, and enabling it left them missing until an unrelated
refresh.

The plugin source is special because it also contributes prompt sections
(#2314), and the file-backed sources are left out for cost — their fs
watches would rebuild every agent's prompt on each edit. The builtin source
has no watch: it changes only when its config switch is toggled, so it
belongs with the plugin source rather than with the file ones.

Subscribing to the catalog rather than the config section is load-bearing.
The catalog fires after the contribution is replaced, whereas a config
subscription would race the reload, and `resolveSkillListing` only awaits
the catalog's *initial* readiness — so the rebuilt prompt could read the
listing it was meant to replace.

The source id is a named constant now, so the subscription does not match
on a bare string.

* refactor(agent-core-v2): freeze the agent identity for the process lifetime

The identity is announced outward (MCP initialize, OAuth registration,
provider request logs) and cannot be re-announced, so mid-process changes
could only ever apply partially. Resolve it once when config first loads
and hold it for the life of the process: IAgentIdentity now hands out a
frozen snapshot via resolved()/current(), carrying finished products
(outbound User-Agent variants, rewritten header set) so call sites stop
composing host headers with the slug themselves. The kosong host-headers
port carries two finished layers and the catalog only picks one; consumers
gain no invalidation obligations because the value can never change after
the freeze. [identity] edits take effect on the next start (documented).

* fix(agent-core-v2): locate the User-Agent header case-insensitively

HTTP header names are case-insensitive, but the snapshot builder looked up
'User-Agent' by exact key: an embedding host spelling it 'user-agent' got no
third-party UA and kept its own product token on the services path even with
an identity configured. The builder now locates every case variant and
rewrites each in place, keeping the host's spelling. Also corrects the two
web-service headers that still described both paths as sending the bootstrap
headers, naming agentIdentity as the collaborator behind the config path,
and documents that a resumed session keeps its recorded system prompt.

* fix(agent-core-v2): attribute header provenance from the finished third-party layer

Inspection reconstructed the non-full host layer from the raw headers with an
exact-case 'User-Agent' lookup, so a host spelling the header 'user-agent'
got a resolved User-Agent with no provenance entry even though the runtime
sends the rewritten value. buildModel now captures the port's finished
third-party layer in the trace and attribution reads it, keeping inspect()
on the same resolution pass as get(). Also condenses the identity contract
header to its external role, and documents that an existing MCP OAuth
authorization keeps the client registration it was granted under (reset the
server's auth to register under the new identity).

* fix(agent-core-v2): keep web tool backends from racing the identity freeze

An env-configured [services] endpoint is visible before config finishes
loading, and FetchURLTool / WebSearchTool materialized their backends at
construction — so a fast bootstrap could hit the identity snapshot's
pre-freeze guard during agent creation, and the composed backend pinned
config and login state for the agent's lifetime against the service's
documented per-call resolution. Both tools now resolve their backend per
invocation, the WebSearch activation gate checks presence alone through the
new hasWebSearchProvider() (no provider composition, no identity read), and
bind() awaits the identity freeze before materializing the model, whose
resolution reads the identity through the host-headers port.
2026-08-04 22:35:15 +08:00
Haozhe
119a33f7f1
feat(minidb): persistent index generations and lifecycle hardening (#2604)
Some checks are pending
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* perf(minidb): skip idle everysec fsyncs and add lifecycle stats

- everysec WAL now fsyncs on the timer only while dirty (tracked by a
  write/sync generation watermark); close() keeps its unconditional
  final sync, and background sync failures surface via walFsyncErrors
  plus a sticky lastWalFsyncError instead of being silently swallowed
- add WAL queue/group-commit counters (walQueuedBytes,
  walMaxQueuedBytes, walGroupCommits, walGroupCommitFrames) and
  lifecycle phase stats: recovery bytes/frames/duration, index/text
  rebuild durations, compaction total/snapshot/rotation/postings
  durations, rotation pause, and query candidates/decoded/sorted
  rows; add a syncIntervalMs open option threaded through compaction
  WAL rotation
- rewrite the bench on fixed-seed synthetic data with a stable
  machine-readable JSON report (cold open 10k/50k/100k, word/ngram
  search, idle-fsync acceptance, 100k compaction, event-loop delay,
  peak heap/RSS per scenario) and pin the schema in
  test/bench-json.test.ts; add app-side baselines with loose
  complexity budgets in sessionIndex and searchService tests
- fix ClusterDb lock-pool closeAll() leaking in-flight shard opens
  and drain the query store's async close on server shutdown,
  eliminating the ENOTEMPTY directory-teardown race

* perf(minidb): bound startup rebuild and steady-state hot paths

- rebuild all derived indexes in one shared store walk: a single decode
  per record fans out to staged builders, dt rebuild reads record
  metadata only, and index-less opens no longer decode at all
- rank full-text results with a bounded min-heap plus a stable key
  tie-break instead of sorting every candidate
- remove/overwrite text docs via a docID -> delta-terms reverse map
  instead of scanning the whole delta vocabulary
- validate unique batches incrementally against touched postings
  instead of copying the full per-index owner map
- reap due TTL entries from the expiry heap on the write path instead
  of a full-store sweep per write

* feat(session-index): add minidb read model with keyset pagination

- add ISessionIndex read-model lifecycle (prepare/status, ready/degraded
  states) behind the persistence_minidb_readmodel experimental flag
- add ISessionIndexMirror write side recording fresh summaries into a
  bounded, coalescing queue after the authoritative document is durable
- replace the offset cursor with before/after keyset pagination; rename
  list/countActive to listRecent/count
- extend IQueryStore with ordered columns and pageByColumn, plus
  getMany/listKeys/dropCollection
- wire the read model through kap-server routes and start, and update the
  klient sessions contract
- index every session for global search instead of the 500 most recent

* feat(kap-server): bound search sync lifecycle, pagination, and query budgets

- split search requests from sync work: searchIndex() no longer awaits
  runSync/reopen/reindex; a single-flight sync coordinator with debounce
  and backpressure runs in the background, stale generations keep
  serving with explicit stale/degraded state, and refresh/sync/reindex
  failures surface via lastRefreshError instead of being swallowed
- scope file-meta keys by session id (\0meta\file\<sessionId>\<hash>)
  with lazy + one-shot background migration from the legacy hash-only
  keys, so one session sync only touches its own meta rows
- make authoritative scans incremental (mtime/ino/size rescan
  conditions, unchanged files no longer rewrite meta) and read wire
  deltas in 1 MiB chunks instead of whole-file buffer + split
- replace offset pagination with versioned v2 keyset page tokens
  (fingerprint + index generation + sort boundary); generation changes
  fail old tokens with invalid_page_token, legacy v1 offset tokens are
  served once and upgraded, and pages collect via bounded top-K instead
  of full sort + offset skip
- add query budgets enforced at the postings/score stage: max query
  terms, literal length cap, postings visit budget (minidb
  searchBounded/maxVisits with prefix decoding that never fabricates
  hits and skips the postings LRU), candidate caps, deadline and text
  budget; truncation is reported via incomplete reasons
  candidate_cap/postings_budget/deadline
- reopen read-only dbs by opening the next handle before closing the
  previous one so a failed refresh keeps the old generation serving;
  failed opens now self-heal through search traffic

100k-message bench: first page p95 < 300ms and page-100 cost on par
with page 1; event-loop delay during queries stays sub-millisecond.

* fix(minidb): poison, roll back, and recover the WAL on write failures

- give WAL writes a commit point: a failed flushBatch poisons the WAL
  (WAL_POISONED, tracked separately as walWriteErrors vs walFsyncErrors),
  rejects queued frames in reverse enqueue order, and stops scheduling
  further batches; everysec background sync failures stay non-rejecting
  per stage-1 semantics
- recover in place to a known-safe point: a serialized recovery chain
  truncates the WAL back to the first un-acked frame, rebuilds
  size/nextOffset, and clears the poison; writes queue behind the
  recovery gate (zero-cost when idle), a failed truncate flips the
  instance into an explicit writeDisabled state, and a stale truncate
  offset (WAL file replaced by a rotation) skips the truncate
- roll failed flush groups back as a unit: frames are stamped with
  their batchId, MiniDb keeps per-group earliest pre-state, and the
  first rejection restores every key of the group (rejected writes no
  longer reappear after reopen, and in-memory state matches reopen for
  any failure interleaving); the per-op seq guard remains for
  cross-group and rotation-retry races
- wrap applyOp and the following in-memory mutations so a contract
  violation poisons the WAL and rolls the group back instead of
  escaping as a half-commit; frames never enqueued (seal race) roll
  back per-op without poisoning
- tag errors past the commit point with ambiguous: true so callers can
  distinguish "definitely not applied" from "maybe applied but revoked"
- close() waits for the recovery chain to go idle and backup() fences
  behind in-flight recovery before copying files

Controlled A/B bench (22 alternating iterations, 100k concurrent sets):
write-path throughput regression is within the 2% budget.

* fix(minidb): turn the file lock into an instance-owned serialized lease

- distinguish lock ownership by instance instead of pid: every acquire
  mints a pid:uuid token carried by lock/bid/watch files, inspect().mine
  compares tokens, liveness still follows pid, tokenless legacy files
  keep the old stale-takeover path, and hasLiveForeignWatch excludes
  self by token so same-process contenders see each other (closing the
  double-win takeover and the cross-instance release); a live same-pid
  lock is still respected, and re-acquiring a held lock is idempotent
- serialize acquire/renew/release through a per-instance promise-chain
  mutex: renew re-checks held inside the chain and release waits for an
  in-flight renew, eliminating the renew/rename-after-unlink ghost lock
- make MiniDb.close() a state machine (open/closing/closed) with a
  shared closePromise: cleanup runs per-resource try/catch in
  dependency order (text indexes, store, valueReader, WAL, lock),
  aggregates every cleanup error into an AggregateError, stays in
  'closing' on failure so a retry finishes the cleanup, and no longer
  leaks the lock when the WAL close fails; a rejected in-flight
  compaction no longer escapes the cleanup pass

* fix(minidb): keep readers on one consistent file generation

- add an internal persistent-files module as the single source of truth
  for the persisted file set (snapshot, WAL, sidecars, postings
  pattern, fingerprint subset); lock-pool fingerprints, persistentFiles,
  open stale-tmp cleanup, and backup/restore filtering all derive from
  it, and fingerprints upgrade to dev:ino:size:mtimeMs so compound
  sidecar changes can no longer hide from cluster readers
- pair snapshot and WAL generations during recovery (transitional
  stat-pairing until stage-5 manifests): each pass anchors the fds it
  scans, re-stats afterwards, tolerates append-only WAL growth, retries
  bounded times on generation churn with a clean store reset, and
  throws RECOVERY_GENERATION_CHURN when churn exceeds the budget; the
  disk-mode ValueReader attach re-validates inodes so stale offsets
  never read a replaced file
- make the rotation directory fsyncs strict: failures abort the
  rotation through the existing rollback path instead of being
  swallowed, while platforms without directory fsync degrade once with
  a warn and stats.dirFsyncUnsupported

* fix(minidb): serialize index-definition sidecar mutations, persist before publish

- extract the promise-chain mutex into a shared createSerializer() and
  give each sidecar family (secondary/compound/text) its own chain:
  create/drop run uninterruptibly (memory change + rebuild + persist),
  different families stay independent, and the data write path never
  shares these chains
- reverse the publication order to staged -> persist -> publish: a
  create stages the definition, rebuilds via the staged builder,
  persists the sidecar including the new definition, then publishes
  atomically; any failure discards the staged state leaving live and
  sidecar untouched (no phantom indexes, retry-safe); a drop persists
  the sidecar without the definition before removing it live; text
  index create/drop adopt the same pattern, replacing the hand-rolled
  unwind, and a dropping marker keeps compaction postings rebuilds out
  of the persist window
- feed staged indexes from the incremental write path (add/remove/
  checkUnique/checkUniqueBatch visit live+staged) so writes landing in
  the persist window are not lost at publish; queries still see live
  only
- harden writeFileAtomic: instance-unique tmp names (.tmp-pid-seq),
  a strict fsyncDir after rename so a successful persist is crash
  durable, and whitelist-based stale-tmp cleanup that never touches
  lock tmp files

* fix(minidb): validate writes before any side effect, canonicalize values once

- canonical value at the write boundary: the json codec re-parses the
  encoded bytes once and every downstream consumer (unique checks,
  secondary/compound/text indexes, dt extraction) sees exactly the
  persisted representation, so getter/toJSON/Proxy documents can no
  longer diverge between the index view and the storage view
- reorder the set/batch pipeline so every fallible check happens before
  any visible side effect: prepare (key/ttl checks, encoding, canonical
  decode, index field extraction, tokenization) -> unique checks ->
  ensureMemoryFor eviction -> commit; a constraint failure now leaves
  the database untouched (no more evicted victims on rejected inserts),
  and applyOp is structurally pure against pre-validated data
- tokenize at the prepare boundary: TextIndex gains prepareAdd/
  addPrepared and the buildQueue carries validated key+tokens mutations
  instead of raw docs, so a throwing custom tokenizer can no longer
  poison the live view or the queue, and custom-tokenizer output is
  rejected per token over 0xffff bytes before it can permanently break
  postings rebuilds; prepared tokens are keyed by index instance so a
  same-name drop+create mid-write re-tokenizes instead of crossing
  tokenizers
- strict batch structure validation: scanBatchOpRefs/decodeBatchOps
  reject unknown op types, out-of-bounds lengths, and trailing bytes
  (offset must equal body length), so a valid-CRC but malformed batch is
  skipped as a unit and counted via RecoveryInfo.corruptBatches instead
  of being partially applied

Bench vs the stage-1 baseline: json write throughput regression is
within the 5% budget (median ~2-4% depending on the measurement).

* feat(minidb): add OpTracker drain primitive and atomic backup, harden tests

- introduce the internal OpTracker (close gate + in-flight counter with
  enter/leave/close/whenIdle and reference-counted pause/resume) and
  drive every shutdown/drain path from it: WAL background syncs are
  tracked so close() waits out an in-flight sync before closing the fd,
  cluster lock-pool closeAll() closes the gates and drains busy
  callbacks before closing handles, and MiniDb writes pass a write gate
- make backup() atomic with a defined linearization point: pause the
  write gate, drain in-flight writes (every acknowledged write is now
  included), copy to a sibling temp dir with per-file fsyncs, write the
  manifest last as the commit marker, and rename into place; failures
  clean up and leave no partial backup, and concurrent writes are
  rejected with BACKUP_IN_PROGRESS
- reap emptied compound-index groups on remove (the groups map no
  longer grows monotonically), move the open-time mkdir behind the
  readOnly check so a read-only open of a missing directory fails with
  ENOENT instead of creating it, and never run a destructive rebuild
  for a read-only open failure (explicit or onLockFail fallback)
- consolidate every review fault-injection repro into the formal suite
  behind deterministic barrier helpers (programmable writev/sync/
  rename/tokenize hooks) and convert the six timing-based tests to
  barrier/tick-driven assertions; the .tmp repro scripts are removed

The converted timing tests and the full suite pass 50 repeat runs
(including under CPU load injection) with zero flakes.

* feat(minidb): persist derived indexes as atomic generations, open from WAL delta

- checkpoint the store, dt/secondary/compound indexes, and text
  dictionary/postings/docs into immutable generations under
  generations/g-NNNNNN published atomically (tmp build, per-file
  checksums and fsyncs, dir rename, CURRENT swap, strict dir fsyncs);
  the manifest records the format version, WAL/snapshot checkpoint
  anchors, per-index definition hashes, and codec/value-mode
  compatibility
- open now loads the published generation and replays only the WAL
  delta after its checkpoint: no full value decode, corpus
  tokenization, or postings rewrite on a normal reopen (warm opens are
  3.5-13.8x faster at 100k/1M records); a definition change rebuilds
  only the affected index, and corrupt generation files fall back to
  the previous generation or the legacy full recovery without ever
  touching the authoritative snapshot/WAL
- build generations transactionally with compaction (rotation plus
  derived state publish as one unit, replacing the synchronous
  rebuildTextPostings tail), capture concurrent writes through a sealed
  op queue with byte/op caps, hard-link clean postings and the snapshot
  into the new generation, and repoint every live text base into the
  CURRENT generation after publish
- cluster/read-only refresh watches CURRENT and the WAL watermark:
  pure generation publishes keep readers on incremental catch-up while
  rotations reopen onto the new generation; writers building the next
  generation never disturb readers of the current one
- legacy databases open through the old path unchanged and gain their
  first generation in the background; OpenOptions.indexGenerations:
  false fully restores the pre-generation behavior

* feat(minidb): workerize text-index builds and split MiniDb into facets

- split the monolithic src/index.ts into facet modules (mini-db, types,
  value-codec, memory-guard, backup, query-engine, text-registry,
  wal-group, generation-builder/loader, write-path, read-path,
  index-admin, lifecycle, stats) and move text-index.ts to text-index/
- run corpus-scale text-index builds off the main thread via the bounded
  worker engine (src/worker/), exported through the new worker-runtime
  subpath, with inline fallback for small corpora and rollback switches
- defer the open-time fallback text rebuild into a maintenance task;
  searches on a not-yet-committed base raise TextIndexBuildingError
- add the unified maintenance scheduler, bounded async read surface,
  and a maintenance bench
- kap-server search: switch to searchBoundedAsync and serve the
  building page while the index base rebuilds after fallback recovery
- kimi-code: install the SEA-bundled minidb text-build worker at
  startup, bundle it via the native asset scripts, and add the
  startup-trace util plus the KIMI_TUI_INPUT_LATENCY debug probe

* fix(minidb): treat win32 EPERM as unsupported directory fsync

- extract isUnsupportedDirectoryFsyncError and cover win32 EPERM
- drop the one-shot console.warn; stats.dirFsyncUnsupported carries the degraded state

* fix(kap-server): harden search-index dispose and drain lifecycle

- dispose() now closes an OpTracker gate and drains in-flight sync/refresh
  passes before closing the db, so no background write can hit a closed
  handle; the deleteSessionDocs loop and trailing stats write skip once
  the gate closes (review #20)
- drainGlobalSearchDisposals loops to a fixpoint so disposals registered
  while a drain is in flight are also awaited (review #21)
- pin the post-open failure semantics with a regression test: a failed
  text-index setup closes the handle and the next open reacquires the
  writer lock instead of self-locking read-only (review #19)
- export OpTracker from the minidb root for the search service's drain

* chore: fix oxlint type-aware lint errors
2026-08-04 20:38:42 +08:00
zy
74c321e4c6
fix(mcp): drop protocol-reserved _meta keys from model-visible output (#2600)
* fix(mcp): drop protocol-reserved _meta keys from model-visible output

Follow-up to #2596. The MCP spec reserves _meta key prefixes whose labels
include "modelcontextprotocol" or "mcp" for protocol use; those entries
carry host/protocol plumbing rather than model-facing data, so filter them
out before serializing the <mcp-structured-result> block. Unprefixed and
vendor-prefixed keys still pass through — their semantics belong to the
server. Also moves the v2 implementation commentary into the module header
per the agent-core-v2 comment convention.

* fix(mcp): reserve _meta prefixes only when a label follows mcp/modelcontextprotocol

Per the spec's key-name rules a prefix is reserved when a
modelcontextprotocol or mcp label is followed by at least one more label;
a trailing reserved word (com.example.mcp/) is a legitimate vendor
namespace and now passes through.

---------

Co-authored-by: zouying <zouying@moonshot.cn>
2026-08-04 20:03:10 +08:00
zy
96f77fe392
fix(agent-core-v2): port the MCP auth:'oauth' opt-in from v1 (#2608)
v1 lets a remote MCP server combine static headers with OAuth via the
auth:'oauth' config marker; v2 neither parsed the field nor honored it,
so any configured headers were treated as static credentials — first
authorization never started and an expired refresh token left the entry
permanently failed. Add the field to the v2 remote config schemas and
mirror the v1 guard in shouldMarkNeedsAuth.

Resolve #2605

Co-authored-by: zouying <zouying@moonshot.cn>
2026-08-04 20:02:57 +08:00
zy
3126422757
feat(mcp): carry an absolute expiresAt on the OAuth authorization-url update (#2609)
* feat(mcp): carry an absolute expiresAt on the OAuth authorization-url update

The authenticate flow waits for the OAuth callback with a fixed budget,
but the authorization-url tool update surfaced to embedding hosts did not
say when that window ends — hosts had to hardcode a mirror of the
15-minute constant to render countdowns. Include the absolute deadline
(now + effective wait timeout) in the update payload for v1 and v2.

Resolve #2607

* fix(protocol,kap-server): accept expiresAt in the OAuth authorization-url update schemas

The zod validators mirrored the pre-expiresAt payload shape and would
strip the new field at the kap-server boundary.

---------

Co-authored-by: zouying <zouying@moonshot.cn>
2026-08-04 20:02:47 +08:00
7Sageer
aec755fad6
feat(agent-core-v2): announce date changes via a system reminder (#2564)
* feat(agent-core-v2): announce date changes via a system reminder

* refactor(agent-core-v2): hide profile rendering behind service

* refactor(agent-core-v2): normalize profile prompt rendering at registration

* chore: retrigger ci
2026-08-04 19:31:00 +08:00
zy
c32e661faa
fix(mcp): pass structuredContent and _meta through to model-visible tool output (#2596)
MCP tool results were narrowed to {content, isError}, dropping the
spec-defined structuredContent field and _meta metadata. Servers that
return structured contracts in these fields (validated against
outputSchema, or namespaced metadata such as browser-handoff payloads)
were invisible to the agent. Surface them as a serialized
<mcp-structured-result> block appended to the tool output, still subject
to the existing text budget.

Co-authored-by: zouying <zouying@moonshot.cn>
2026-08-04 18:01:42 +08:00
qer
0abcd00f7f
feat(cli): add built-in Computer Use and WebBridge capabilities (#2407)
* feat(agent-core-v2): add built-in capabilities (kimi-cu, kimi-webbridge) with REST routes

Add a capability domain holding a closed registry of built-in product
capabilities. Each entry owns layered readiness detection and idempotent
install orchestration: binary runtimes from fixed official CDN URLs
(KimiCU.app + launchd service + TCC permission state; the WebBridge
daemon with start-if-down semantics for Kimi Work coexistence) plus
agent wiring through the plugin service. The WebBridge wiring un-shadows
stale user-source skill copies (user priority beats plugin priority).

kap-server exposes the domain as GET /api/v1/capabilities,
GET /api/v1/capabilities/{id}, and POST /api/v1/capabilities/{id}:install
with client-polled progress and new wire codes 40418 / 40922 / 40923.

The plugin marketplace gains an official kimi-webbridge entry
(browser-control skills) packaged by the existing CDN build.

* fix(agent-core-v2): rename the webbridge wiring plugin to kimi-webbridge-skill

An official kimi-webbridge guide plugin (install/remove setup skills,
v3.0.4) already exists at the marketplace path the capability installer
pointed at — a different artifact owned by another release line. Give
the browser-control usage-skill plugin its own id/path instead of
colliding with (or overwriting) the guide plugin. The capability entry's
detect/install now tracks kimi-webbridge-skill; a machine with only the
guide plugin correctly reports the skill layer as missing.

* feat(agent-core-v2): shelf installs auto-complete capability binary layers

Two changes to make the plugin marketplace a first-class install path:

- Marketplace gains kimi-cu (sourced from the CU team's CDN zip — no
  repackaging) and the kimi-webbridge usage-skill plugin now claims the
  kimi-webbridge id at v4.0.0, deliberately superseding the WebBridge
  guide plugin (v3.0.4, install/remove guide skills): guide users get a
  version upgrade onto the real usage skill.
- The capability service subscribes to IPluginService.onDidReload: when
  a capability's wiring step flips to ok through ANY install path
  (shelf, TUI, CLI), it auto-completes the missing binary layers
  (KimiCU.app + service, or the WebBridge daemon). Triggers only on the
  false→true edge so completed installs with still-missing manual steps
  (TCC permissions) never retrigger heavy downloads on later reloads.

* fix(plugins): keep kimi-webbridge plugin version aligned with the upstream skill

The plugin version tracks the bundled official usage skill (1.11.3) so
version drift against the WebBridge release line stays visible, instead
of minting an independent 4.0.0.

* fix(agent-core-v2): never report the webbridge installer-script version as the product version

The on-disk ~/.kimi-webbridge/bin/kimi-webbridge.version file tracks the
installer's own lineage (3.1.x, bumps on every install/upgrade run),
not the product version (v1.11.3 — daemon, extension, and skills all
share it). A downed daemon would have shown the misleading installer
number; report no version instead (live /status remains the source of
truth).

* chore(plugins): list kimi-cu on the marketplace without a pinned version

Marketplace versions are optional by schema: rows display the version
detected from the installed plugin's manifest, and update prompts only
fire on a valid semver latest > local comparison. A hand-maintained
number would drift just like the guide plugin's did. The locally built
kimi-webbridge entry keeps its manifest-stamped version (1.11.3).

* fix(agent-core-v2): fire onDidReload on plugin mutations, not just explicit reload

installPlugin / setPluginEnabled / removePlugin changed the catalog
silently — consumers listening to onDidReload (session skill-catalog
convergence, the capability shelf-install hook) only converged on an
explicit reloadPlugins(). Fire the same summary-shaped event on every
mutation (added:[id] / [] / removed:[id]) so every install path
converges. This also unbreaks the shelf-install hook on real hosts:
its unit tests passed against a fake emitter that fired on installs,
which the real service never did.

* feat(kap-server): add plugin management and marketplace REST routes

Expose the App-scope plugin service over the wire so non-CLI hosts
(desktop, web) can manage plugins end to end:

- GET  /api/v1/plugins/marketplace — catalog (pluginMarketplaceUrl
  server option / KIMI_CODE_PLUGIN_MARKETPLACE_URL env / production
  default) merged on demand with live install state; updateAvailable
  only on strict semver catalog > installed (no semver dependency)
- GET  /api/v1/plugins, POST /api/v1/plugins {source}
- POST /api/v1/plugins/{id}:{enable,disable,remove}
- New wire code 40419 plugin.not_found

Mutations flow through IPluginService, so they serialize with other
install paths and fire onDidReload (session skill catalogs and the
capability shelf-install hook converge).

* feat(agent-core-v2): surface a machine-key note from capability installs

CapabilityEntry.install now resolves an optional note exposed through
CapabilityInstallProgress.note (wire-visible). The webbridge entry
returns 'user-skill-migrated' when it replaces a pre-existing
user-source skill (from the official installer) with the plugin-managed
copy — clients can localize the migration instead of the skill silently
disappearing from the user's directory.

* feat(tui): let the real WebBridge marketplace entry win over the pinned promo

The hardcoded Web Bridge row was built when WebBridge had no plugin
package — it pinned above the Official tab and shadowed any catalog
entry with the same id (open-in-browser only). Now that the marketplace
carries the real kimi-webbridge plugin, flip the precedence: the catalog
entry renders and installs normally, and the pinned promo becomes a
loading/error/legacy-catalog fallback only. Footer counts keep their old
semantics (catalog-only; the promo row is never counted).

* fix(tui): dim the installed state so it stops reading as the install action

Both badges shared a near-identical green-ish treatment in the same
column, making a quiet fact look like a clickable action. States now
recede (installed → textDim) while actions stay loud (install →
primary, update → warning).

* feat(agent-core-v2): converge plugin state across processes sharing a home

Multiple hosts share one KIMI_CODE_HOME (CLI, desktop, other agents), but
each PluginService kept a private in-memory snapshot: a plugin installed
or removed in one process stayed invisible to every other live process
until its next restart — new sessions there kept offering stale plugin
skills/MCP, and the capability shelf hook never saw peer installs.

Watch <home>/plugins for installed.json changes and reloadPlugins
(debounced, echo-suppressed around our own mutations) so all consumers
converge in well under a second: session skill catalogs, plugin MCP
mounts, and the capability shelf-install hook alike.

* fix(agent-core-v2): un-shadow webbridge user skills in BOTH user dirs

kimi-code resolves user-scope skills from two roots (~/.kimi-code/skills
and ~/.agents/skills), both at priority 20 — a stale copy in either
shadows the plugin-managed wiring (priority 5), and also keeps the
capability working after the plugin is removed, which reads as
'uninstall did nothing'. Migrate copies in both dirs during install;
other runtimes' dirs (~/.claude, ~/.codex) remain untouched.

* feat(tui): show live runtime-setup progress for capability installs

Installing a capability plugin (kimi-cu, kimi-webbridge) from the
/plugins shelf kicked off a silent background binary install — the row
flipped to installed while megabytes of runtime downloaded invisibly.
Route capability entries through the capability surface instead: the
panel's inline installing line now mirrors live progress (step +
percent) until the install settles, and the transcript reports
ready / failure-with-retry / still-running accordingly. Capability
removal prints an explicit note that runtime binaries are deliberately
left untouched (the capability keeps working), since that read as
'uninstall did nothing'.

Plumbs the capability service through klient's global facade
('capabilityService' decorator resolves in-process) and the node-sdk
v2 client; Session exposes it with a structural feature-detect so v1
engines fail clearly.

* docs(plugins): keep the kimi-cu marketplace blurb accurate for every client

Only the capability-aware clients auto-install the KimiCU.app runtime;
older builds still get wiring-only (the wrapper's error message then
points at the official setup script). Don't overpromise in the catalog
text every version reads.

* feat(agent-core-v2): install capability wiring from client-bundled plugin copies

The kimi-cu / kimi-webbridge wiring plugins ship inside the client release
instead of the marketplace catalog, binding their visibility to the client
version. Capability installs now resolve the bundled copy (env override,
then npm-layout and source-checkout probes from the module) and install it
as a local path, replacing the two CDN zip URLs. A missing bundle fails the
wiring step with a clear reinstall-or-upgrade message.

* build(cli): bundle the capability wiring plugins into client releases

Vendor the official kimi-cu plugin (v0.5.4, from the CU team's plugin zip)
next to kimi-webbridge under plugins/official, copy both into
apps/kimi-code/bundled-plugins at build time, and ship them in the npm
package (files) and the native SEA blob (a new bundled-plugins asset set
extracted into the native cache at startup, published to the engine via
KIMI_CODE_BUNDLED_PLUGINS_DIR). Desktop points the same variable at its
extraResources copy. The .gitignore build-output entries are anchored so
sources under src/native and test/native stop being silently ignored.

* revert(plugins): remove the kimi-cu and kimi-webbridge marketplace entries

Both capabilities now distribute with the client (bundled wiring), so the
catalog drops back to kimi-datasource / superpowers / vercel-plugin. Older
clients never see the entries; current clients install from the Built-in
section. This also reverts the marketplace blurb commit 0635e99c5.

* feat(tui): add a Built-in capabilities section to the plugins panel

The Official tab now opens with a Built-in section fed by the engine's
capability registry (kimi-cu / kimi-webbridge): per-row install state
(install / finish setup / ready), Enter runs the full capability install
with live progress, and unsupported rows hide (kimi-cu off macOS). The
WebBridge promo fallback only remains for v1 engines — on v2 the real
built-in entry wins. Rows double as the reinstall path: a client upgrade
ships newer wiring, and installing again upserts from the new bundle.

* docs(plugins): document the Built-in section and refresh the capability changeset

* build(nix): stage bundled capability plugins into the SEA build

The native SEA blob now embeds the bundled-plugins asset set, so the nix
derivation needs the plugins tree in its src fileset and the staging step
alongside copy-web-assets before build:native:sea.

* revert: drop the client-bundled wiring distribution

Built-in visibility is simpler to get by injecting the two capability
entries into the marketplace catalog at load time; the wiring plugins
themselves keep installing from their fixed official CDN zips. Removes
the vendored kimi-cu plugin, the bundled-plugins npm/SEA packaging and
flake staging, the engine bundle resolver, and the plugins panel's
Built-in section. Keeps the /agents/ and /native/ gitignore anchors so
sources under src/native and test/native are not silently ignored.

* feat(cli): inject the built-in capability entries into the marketplace catalog

The kimi-cu / kimi-webbridge entries are appended by the client at catalog
load time instead of being served by the remote marketplace.json, binding
their visibility to the client version (older clients never see them). No
version is pinned — reinstalling upserts the wiring — and ids the catalog
already carries always win. In a source checkout the webbridge entry
installs the repo's own plugin copy; packaged builds use the official CDN
zip. This reverts the docs paragraph about the Built-in section, which the
simpler approach makes unnecessary.

* test(tui): select the catalog's own first row in marketplace install tests

The client-injected capability entries suppress the WebBridge promo and
append after the catalog rows, so Kimi Datasource now leads the Official
tab — the extra down-key landed on kimi-cu instead.

* feat(cli): surface the built-in capabilities as client-injected marketplace entries

The kimi-cu / kimi-webbridge entries are injected into the marketplace
catalog by the client (v2 engine, default catalog only) instead of being
served remotely, binding their visibility to the client version; injected
rows mask same-id catalog rows, so what these ids mean stays decided by
the client release — a future official listing only reaches older clients,
whose fix is to upgrade.

The /plugins panel shows capability readiness on the rows (setup
incomplete / installing…), platform-gates kimi-cu to macOS, and Enter
finishes the runtime setup with live progress; v1 keeps the plain plugin
install path and the WebBridge promo fallback.

Capability and plugin calls move from the ad-hoc REST routes onto the
typed klient contract (capabilityService next to pluginService), so the
public REST surface returns to its pre-feature shape. Detection is
presence-only — version pins removed: the current version is always read
live (Info.plist, daemon status, install records), installs are
detect-first and idempotent so an interrupted setup can be retried, and
reinstalling pulls the latest managed artifacts (the passive upgrade
path).

* ci: retrigger checks

* fix(cli): recognize Computer Use CDN plugins as official

* fix(cli): keep built-in entries on catalog outage and isolate detector failures

Two review follow-ups: the client-injected entries no longer disappear when
the marketplace catalog is unreachable (they are not served by it), and a
single capability's failing detect probe degrades to a failed step on that
entry instead of rejecting the whole listCapabilities call.

* refactor(cli): simplify built-in capability integration

* refactor(cli): source built-in catalog rows from the engine and tighten detect probes

The injected marketplace entries are now derived from the engine's
capability registry (listCapabilities) instead of hardcoded client-side
copies — the util only owns the mask/append mechanics, and capability ids
are no longer pinned in the CLI (the remove note resolves them through the
registry too). kimi-cu's detect-path probes (service-status, xpc-ping) get
a 3s timeout — they answer in milliseconds when healthy but run on every
status listing, so a wedged binary must degrade quickly instead of
stalling the panel. Document the Official tab's built-in capability rows
in the plugins guide.

* fix(cli): answer capability id membership without running detectors

listCapabilities() runs every entry's detect probes (seconds on a wedged
binary), so using it to decide whether to print the post-remove hint made
every plugin removal pay a full detection round. The id set is part of the
client/engine contract (mirrored in the klient schema), not product data
that drifts — restore the closed-set check. The injected catalog rows keep
flowing from the registry.

* fix(agent-core-v2): make capability setup recover from disabled, partial, and wedged states

Three review follow-ups on the install path: setup now re-enables the
wiring plugin when a previous disable survived installPlugin's upsert
(detection requires enabled, so it would otherwise strand the capability
at partial); the webbridge daemon-binary step verifies the executable bit
on POSIX, so an install interrupted between rename and chmod re-downloads
instead of failing start with EACCES; and kimi-cu's detect degrades
wedged CLI probes (service-status, xpc-ping) to failed steps instead of
throwing, keeping the detect-first install able to repair the remaining
layers — with the probe timeout injectable for tests.

* fix(agent-core-v2): abort capability downloads whose byte stream stalls

downloadToFile had no inactivity deadline: a CDN connection that stops
producing bytes hung the background install forever, wedging the
capability in a permanent installing state (retries rejected as
in-progress) until the process restarted. An idle watchdog now fails the
download after 30s without a chunk; slow but flowing downloads are
unaffected.

* fix(tui): stop offering capability setup on unsupported platforms

An installed wiring plugin whose capability is unsupported on this
OS/arch (kimi-cu off macOS, webbridge on an unknown arch) was treated
like a partial setup: the Installed tab showed setup incomplete and
Enter routed to installCapability, which the service always rejects.
Setup actions are now gated to actionable states (not_installed /
partial); unsupported renders as a dim fact and Enter opens details.

* fix(agent-core-v2): cover the two remaining install wedge modes

Review follow-ups: the KimiCU app step now requires an executable binary,
so a ditto interrupted mid-copy reads as missing and the next setup
re-copies instead of failing EACCES forever; and downloadToFile's idle
budget now also covers the response-header phase via an AbortSignal on
the fetch itself, so a connection that never completes headers fails the
install (clearing the running state) instead of hanging it.

* fix(tui): render capability rows independently of the catalog fetch

While the marketplace catalog was loading or unreachable, the Official
tab showed only the pinned WebBridge promo — built-in runtime setup was
blocked by an unrelated remote fetch, and Enter opened the browser
instead of installing. Locally-known capability rows (from the engine
registry) now render and install in every catalog state; the promo
remains only as the v1 fallback.

* fix(agent-core-v2): keep KimiCU cleanup timeouts best-effort

stopOldProcesses is documented as || true, but runCommand propagates
timeouts: a wedged old binary made kimi-cu uninstall exceed the command
timeout and the reinstall died before ditto could replace the app.
Cleanup commands now swallow failures (the timeout already attempts a
kill) so the replacement always proceeds; the command timeout is
injectable for tests alongside the probe timeout.

* fix(cli): inject built-in entries only for the default marketplace catalog

Injection is part of the default catalog experience: any explicit
replacement (slash-command source or KIMI_CODE_PLUGIN_MARKETPLACE_URL)
now opts out wholesale — its same-id rows are never masked by the
built-ins, and an unreachable custom catalog surfaces its own failure
instead of being silently replaced by a built-in-only tab.

* refactor: align capability row rendering on the source marker and drop conditional spreads

Marketplace-row capability enrichment (status, badges, issue details,
platform filtering) now keys on the capability:<id> source marker — the
same condition Enter uses to route installs — so a custom catalog row
that merely reuses a built-in id renders and installs as a plain plugin.
Also replaces the conditional-spread optional fields with direct
undefined-valued assignments per the repo coding rules.

* refactor(agent-core-v2): move capability comments to the file headers

The domain's comment convention allows only the top-of-file block:
responsibility and scope context for the recent hardening (detect-first
idempotent install, executability gates, probe-failure degradation,
best-effort cleanup, download watchdog, per-entry detection isolation)
now lives in the module headers, and inline narration beside statements
and members is removed.

* fix(tui): follow an in-progress capability install instead of restarting it

Opening /plugins while a capability setup is already running showed the
installing… row, but Enter called installCapability again and the
service's duplicate-start rejection (40922) surfaced as a fake failure.
The panel now checks the live status first and, when an install is
already running, skips the start call and just polls for the existing
progress.

* fix: align two more replacement paths with their contracts

The EXDEV daemon-binary fallback now stages on the target filesystem and
atomically renames over the destination instead of opening a
possibly-running binary for write (ETXTBSY on Linux). And the panel's
fallback capability rows (catalog loading/error) now follow the same
default-catalog condition as the loader injection, so an explicitly
overridden marketplace fully replaces the Official tab.

* fix(tui): make the built-in row marker unforgeable

The capability:<id> source string was the trust signal for routing rows
into capability installs, but any catalog can write that string — a
custom marketplace could smuggle a row past the third-party trust path
into an official runtime install. Injected rows now carry an internal
builtIn flag that the field-by-field catalog parser never produces;
rendering and install routing key on the flag, and the source string is
purely diagnostic.

* fix(agent-core-v2): include MCP server enablement in capability readiness

A user who disabled the kimi-cu stdio MCP server (/plugins mcp disable)
got a ready capability with no Computer Use tools in new sessions: the
plugin step only checked the plugin toggle, and installPlugin's upsert
preserves per-server state. Readiness now requires every declared MCP
server enabled (reporting e.g. mcp 0/1 enabled), and setup re-enables
disabled servers alongside the plugin toggle.

* fix(agent-core-v2): shell-quote ditto paths in the elevated KimiCU copy

The elevated fallback escaped paths only for the AppleScript string
delimiters, not for the /bin/sh command line inside do shell script: a
TMPDIR with spaces broke the install, and shell metacharacters in the
temp path could inject commands into an administrator-privileged script.
Paths are now POSIX single-quoted first, then the assembled command is
AppleScript-escaped.

* fix(agent-core-v2): never break a working KimiCU on a failed update

The reinstall stopped and uninstalled the old service before the
downloaded archive was unpacked: a corrupt or captive-portal zip then
tore down a previously ready setup. The archive is now staged and
unpacked first, and the app step additionally requires the bundle's
Info.plist, so a partially copied bundle reads as missing and gets
re-copied instead of failing registration against a corrupt bundle.

* fix(agent-core-v2): limit the fetch deadline to the header phase

The 30s AbortSignal stayed attached for the whole request, so a
slow-but-healthy download of a large archive was aborted at 30s total
even while chunks kept arriving — exactly what the per-chunk idle
watchdog was meant to allow. The header phase now uses an
AbortController cleared once headers arrive; the body remains governed
by the inactivity watchdog alone.

* test(tui): provide the harness plugin facade in the capability command fakes

The lazy-session refactor routes session-less plugin calls through
host.harness; the fake host now mirrors that shape.
2026-08-04 17:59:16 +08:00
qer
da6646bf57
docs(changelog): fix 0.32.0 entry formatting and doc links (#2598) 2026-08-04 17:02:08 +08:00
7Sageer
278b6af19d
fix(agent-core-v2): make MCP initial connect non-blocking during startup (#2586)
* fix(agent-core-v2): make MCP initial connect non-blocking during startup

* Delete .changeset/mcp-nonblocking-startup.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* fix(agent-core-v2): wait for MCP readiness before first turn

* fix(klient): wait for MCP startup before listing

* fix(klient): keep MCP server listing non-blocking

* test(acp-server): allow pending MCP snapshot

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-08-04 16:47:55 +08:00
qer
85e4cf0346
docs(changelog): shorten the 0.32.0 loop_control and token_counting entries (#2595)
* docs(changelog): shorten the 0.32.0 loop_control and token_counting entries

* docs(changelog): tighten the 0.32.0 loop_control and token_counting entries further

* docs(changelog): reword 0.32.0 Polish entries from the user perspective
2026-08-04 16:41:59 +08:00
qer
c2e53aef6c
docs: polish the 0.32.0 changelog and fill 0.32.0 doc gaps (#2594)
* docs: polish the 0.32.0 changelog and fill 0.32.0 doc gaps

* docs(changelog): note SessionEnd archive and KIMI_TOKEN_COUNTING_STRATEGY for 0.32.0

* docs(changelog): move the 0.32.0 token_counting entry from Features to Polish
2026-08-04 16:31:25 +08:00
liruifengv
2c3c5a5879
feat(tui): lazy-create the session on first use with the v2 engine (#2458)
* feat(tui): lazy-create the session on first use with the v2 engine

Start the interactive TUI session-less under the v2 engine and create the
session on first use (message, bash input, or a session-requiring slash
command) instead of at startup. Skills and plugin commands are resolved
from the workspace/app-global catalogs without a session, and the footer
shows config defaults (model, permission, plan mode, thinking effort,
context cap) until the session exists.

* fix(tui): serialize lazy session creation and carry session-only thinking

Concurrent first-use triggers (double Enter, a slash command right after a
prompt) both observed `session === undefined` and created their own
session, letting the later setSession close the first one mid-dispatch.
Share an in-flight creation promise instead.

A session-only thinking choice (model picker Alt+S) made before the first
session exists only updated appState, so the lazy-created session fell back
to the engine default while the footer showed the chosen effort. Carry it
as a first-session thinking override and clear it on creation.

* fix(tui): don't re-enter plan mode when creating the lazy session

The v2 engine applies config.defaultPlanMode at session create time
(sessionLifecycleService), so passing the pre-filled appState.planMode as
the create override entered plan mode twice and threw 'Already in plan
mode' on the first message. Pass only the explicit CLI --plan intent for
session-less v2 creation; the config default stays footer-only.

* fix(tui): re-check the busy gate after lazy shell startup, keep /settings session-less

A bash command submitted while the first prompt is still being
lazy-created shared the in-flight creation promise but resumed past
handleUserInput's busy check, running runShellCommand concurrently with
the prompt. Re-check streamingPhase after the await and queue instead.

/settings is a local settings entry point: opening it must not require or
create a session, so it no longer triggers lazy creation; its
session-requiring sub-items keep their own errors.

* fix(tui): re-check busy state after lazy command creation, make /plugins session-free

A skill/plugin or idle-only slash command submitted while the first prompt
was still being lazy-created shared the in-flight creation promise but
resumed past the availability check resolved before the await, running
concurrently with the prompt's turn. Re-check the busy gate after the
shared await in the skill, plugin-command and builtin dispatch paths.

/plugins is app-global on the v2 engine, so a session-less startup no
longer creates a session (or fails with LLM-not-set) just to manage
plugins: the harness now exposes the global plugin API and the command
routes through it until a session exists.

* fix(tui): keep the read-only /add-dir forms session-less

The bare and `list` forms already tolerate a missing session, but the
blanket lazy-create gate forced a session (or failed with LLM-not-set)
before they could run. Only the path-adding form needs a live session, so
it now lazy-creates inside the handler instead of in the dispatch
preflight.

* fix(tui): reflect pending dirs in /add-dir list, refresh plugin commands after reload

/add-dir list looked only at session.summary, so pending startup
additionalDirs were reported as absent until a session existed; fall back
to appState when session-less.

/plugins reload updated the app-global service but left the TUI's plugin
slash-command map stale, so new or re-enabled commands kept parsing as
prompts; rebuild it from the reloaded service (which also covers the
app-global path before the first session exists).

* test(tui): add pluginCommandMap to the MessageDriver interface

* fix(tui): hydrate lazy defaults on sessionless reload, guard /plan re-entry

/reload refreshed only the model/provider dictionaries while session-less,
so defaults edited externally (or a newly added default model) left
appState.model empty/stale and the first lazy-created session failed with
LLM-not-set or used the old value. Reuse the startup default-hydration
path for the no-session reload case.

/plan on as the first command with defaultPlanMode=true re-entered plan
mode after the engine had already applied the config default at create,
throwing Already in plan mode. Skip the call when the session is already
in the requested mode.

* test(tui): widen the getConfig mock return type for the reload case

* fix(tui): clear stale lazy defaults when the default model disappears

hydrateLazyConfigDefaults only patched model when the reloaded config
still had a default, so removing defaultModel from config.toml left
appState.model stale and the first lazy-created session passed it
explicitly instead of failing or following the engine's current defaults.
Reset model and context cap when the default is gone.

* fix(tui): reset a removed permission default, don't re-enter plan on --plan

A removed defaultPermissionMode left appState carrying the old elevated
mode, which createSessionFromCurrentState then passed explicitly to the
first lazy-created session; reset to manual when no CLI permission flag
is present.

With both defaultPlanMode and --plan set, the create payload passed
planMode: true even though the engine already entered plan mode from the
config default, throwing Already in plan mode on the first prompt. Track
the config default separately and suppress the --plan override when it is
already active.

* fix(tui): keep read-only and mode commands session-less

Read-only views (/status, /usage, /mcp, bare /title) already degrade
gracefully without a session, so forcing lazy creation made them fail
with LLM-not-set or create an unused persisted session; they no longer
trigger creation, and /title <name> lazy-creates only for the mutation.

/permission, /auto and /yolo are pending-mode choices: with no session on
v2 they now record the mode in appState (which the lazy create path
passes to the engine) instead of failing or creating a session just to
pick a mode. The runtime permission is applied once a session exists.

* fix(tui): wait out lazy assembly in ensureSession, expose workspace MCP

setSession assigned host.session mid-assembly, so a follow-up prompt or
command in that window skipped the shared creation promise and dispatched
against a session whose subscription and runtime sync had not finished.
Check the in-flight promise before the assigned-session fast path.

/mcp required a live session even though the v2 connection set is
workspace-scoped, so it errored until an unrelated prompt created one.
Route it through a workspace-level MCP view (harness passthrough over the
handler's shared connection manager) before the first session exists.

* fix(tui): await workspace MCP readiness in the session-less /mcp list

* fix(tui): hydrate the model default thinking effort for the session-less picker

* style(tui): trim verbose comments in the lazy-default fixes

* fix(tui): hydrate lazy defaults after login, serialize /new with lazy creation

* fix(tui): re-check the busy gate after lazy /add-dir session creation

* fix(tui): let Shift-Tab lazy-create the session on a v2 session-less start

* fix(tui): hydrate session-less defaults on model-less login, refresh workspace commands on reload

* fix(tui): re-check the idle-only gate for /new after waiting out lazy creation

* fix(tui): wait out lazy creation before accepting model/effort switches

* fix(tui): wait out lazy creation before switching sessions from the picker

* fix(node-sdk): read session-less skills from the workspace skill catalog

* feat(tui): show a session-less notice on v2 startup
2026-08-04 16:09:01 +08:00
7Sageer
af43c5226d
feat(agent-core-v2): advertise model capabilities in the subagent model picker (#2591)
* feat(agent-core-v2): advertise model capabilities in the subagent model picker

* chore(agent-core-v2): follow header-only comment convention

* docs(agent-core-v2): note the model catalog collaborator in the AgentSwarmTool header
2026-08-04 15:57:04 +08:00
7Sageer
54c04bf03d
feat: /fork no longer switches to the forked session (#2565)
* feat: /fork no longer switches to the forked session

Forking used to switch to the new session, which closed the source
session and force-stopped its background tasks (and canceled any
in-flight turn). /fork now creates the copy and stays in the current
session; the fork can be opened explicitly via /sessions.

* fix(tui): release fork runtime when staying current
2026-08-04 15:24:12 +08:00
3185 changed files with 197815 additions and 126269 deletions

View file

@ -33,7 +33,7 @@ End-to-end procedures that span the stages. Reach for these before reading the s
## Stages
- [Stage 1 — Orient](orient.md): the DI black box (identity / dependencies / lifetime), the four `LifecycleScope` tiers and visibility, and the file-header comment convention. Read before touching business code.
- [Stage 1 — Orient](orient.md): the DI black box (identity / dependencies / lifetime), the four `LifecycleScope` tiers and visibility, and the no-comment convention. Read before touching business code.
- [Stage 2 — Design a service](design.md): pick a scope, split a domain across scopes, choose a calling style (direct call vs event vs hook), and direct dependencies. Decide *where things live and who knows whom* before coding.
- Topic: [Domain boundaries vs Scope](domain-boundaries.md) — keep `session` / `agent` / `turn` from becoming god objects; data-ownership test and their split conclusions.
- Topic: [Persistence layering](persistence.md) — the three-layer `Store → Storage → backend` model, naming Stores by access pattern, and which layer business code should depend on.
@ -67,4 +67,4 @@ Invariants that hold across every stage. Each is expanded in the stage file note
9. Throw coded errors; register codes centrally; branch on `code` across the wire, never `instanceof`. (errors.md)
10. Gate unreleased behavior behind a flag contributed via `registerFlagDefinition` and resolved through `IFlagService.enabled(id)`; no ad-hoc env toggles. (flags.md)
11. Tests resolve the SUT by interface; shared stubs live under `test/`, never `src/`. (test.md)
12. Config is the preference registry: only preferences that are persistable, schema'd, and user/operator-facing go in `IConfigService`. Domain-specific config (including env-only operational toggles) goes through `registerSection` + `envOverlay`. Facts → `IBootstrapService`, and host invocation arguments (CLI flags, host identity headers, prompt identity) → `BootstrapInput.args` / `IBootstrapService.args` — never new per-domain runtime-options services; domain runtime state (cron/flags/model) never goes onto `IBootstrapService`; session state → Session scope; constants → code. Business domains never call `IBootstrapService.getEnv()` directly. (config.md)
12. Config is the preference registry: only preferences that are persistable, schema'd, and user/operator-facing go in `IConfigService`. Domain-specific config (including env-only operational toggles) goes through `registerConfigSection` + `envOverlay`. Facts → `IBootstrapService`, and host invocation arguments (CLI flags, host identity headers, prompt identity) → `BootstrapInput.args` / `IBootstrapService.args` — never new per-domain runtime-options services; domain runtime state (cron/flags/model) never goes onto `IBootstrapService`; session state → Session scope; constants → code. Business domains never call `IBootstrapService.getEnv()` directly. (config.md)

View file

@ -157,7 +157,8 @@ import { InstantiationType, registerSingleton } from '../../di';
registerSingleton(IXxxService, XxxService, InstantiationType.Delayed);
// v2
import { LifecycleScope, ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
registerScopedService(LifecycleScope.Session, IXxxService, XxxService, ScopeActivation.OnDemand, 'xxx');
```

View file

@ -2,7 +2,7 @@
How the `config` domain works and how a domain owns its configuration section. Covers the section-registry model, the App vs Session split, the TOML on-disk format, and the recipe for adding or migrating a config section.
The `config` domain is a thin registry + loader: it does **not** know the shape of any individual section. Each domain owns the schema (and, where needed, the TOML transform) for the config it consumes, registers the section into `IConfigRegistry`, and reads it through `IConfigService`. There is no whole-config object passed around.
The `config` domain is a thin registry + loader: it does **not** know the shape of any individual section. Each domain owns the schema (and, where needed, the TOML transform) for the config it consumes, contributes the section (statically at module load via `registerConfigSection`, or at runtime as a `ConfigSectionContribution` collection record), and reads it through `IConfigService`. There is no whole-config object passed around.
## What belongs in Config
@ -93,13 +93,15 @@ pass `ConfigTarget.Memory` for a per-run override that is never written to disk.
## Layout
- `src/config/config.ts``IConfigRegistry` / `IConfigService` tokens, `ConfigSection`, `ConfigEffectiveOverlay`, event types.
- `src/config/configService.ts``ConfigRegistry` + `ConfigService` impl; self-registers at App scope.
- `src/config/toml.ts` — generic snake_case ↔ camelCase machinery plus the registry-aware `transformTomlData` / `applySectionToToml` entry points. Per-domain normalization lives in the section owner's `configSection.ts` (registered as `fromToml` / `toToml`); this module stays free of any other domain's semantics.
- `src/profile/thinking.ts` (owner domain, not `config`) — the `resolveThinkingEffort` helper; uses the authoritative `ThinkingConfig` from `configSection.ts`.
- `src/config/configPure.ts``isPlainObject`, `deepMerge`, `omitUndefined`, `describeUnknownError`.
- `src/app/config/config.ts``IConfigRegistry` / `IConfigService` tokens, `ConfigSection`, `ConfigEffectiveOverlay`, event types.
- `src/app/config/configService.ts``ConfigRegistry` + `ConfigService` impl; self-registers at App scope. The registry is also the fold of the `ConfigSectionContribution` collection: it drains the module-level contributions at construction, then refolds incrementally (`added``registerSection`, `removed``unregisterSection`).
- `src/app/config/configSectionContributions.ts` — the `ConfigSectionContribution` collection token (the runtime channel: a unit contributes with `this.provide(ConfigSectionContribution, …)`) plus the module-level `registerConfigSection` collector (the static channel, import = register).
- `src/app/config/configOverlayContributions.ts` — the module-level `registerConfigOverlay` collector for `ConfigEffectiveOverlay`s (drained at construction like the sections).
- `src/app/config/toml.ts` — generic snake_case ↔ camelCase machinery plus the registry-aware `transformTomlData` / `applySectionToToml` entry points. Per-domain normalization lives in the section owner's `configSection.ts` (registered as `fromToml` / `toToml`); this module stays free of any other domain's semantics.
- `src/kosong/model/thinking.ts` (owner domain, not `config`) — the `resolveThinkingEffort` helper and the authoritative `ThinkingConfig` type (the `thinking` section itself registers from `src/app/kosongConfig/configSection.ts`).
- `src/app/config/configPure.ts``isPlainObject`, `deepMerge`, `omitUndefined`, `describeUnknownError`.
A domain that owns a section keeps the schema in its own `configSection.ts` (e.g. `src/flag/flag.ts` for `experimental`, `src/loop/configSection.ts` for `loopControl`). Exception: kosong-owned sections (`providers`, `models`, `thinking`) — kosong is a pure, persistence-free abstraction layer that defines only the types (`src/kosong/{provider,model}`); the section constants, the zod schemas (re-derived from those types and compile-time pinned via `AssertExact<Equal<z.infer<typeof Schema>, Type>>`, see `_base/utils/typeEquality.ts`), the registrations, env bindings, and TOML transforms all live in the persistence wrapper `src/app/kosongConfig/configSection.ts`. (`modelCatalog` and `secondaryModel` have no kosong-side type at all — their sections are fully self-contained in `app/kosongConfig`, types derived from the schemas.) A cross-section env overlay (e.g. the `KIMI_MODEL_*` synthesis) lives in the wrapper too (`src/app/kosongConfig/envOverlay.ts`; the `[secondary_model]` derived-entry synthesis in `secondaryModelOverlay.ts`) and is registered via `IConfigRegistry.registerEffectiveOverlay`. The two-way sync between config sections and kosong's in-memory registries is owned by `IKosongConfigService` (`src/app/kosongConfig/kosongConfigService.ts`).
A domain that owns a section keeps the schema in its own `configSection.ts` (e.g. `src/app/flag/flag.ts` for `experimental`, `src/agent/loop/configSection.ts` for `loopControl`). Exception: kosong-owned sections (`providers`, `models`, `thinking`) — kosong is a pure, persistence-free abstraction layer that defines only the types (`src/kosong/{provider,model}`); the section constants, the zod schemas (re-derived from those types and compile-time pinned via `AssertExact<Equal<z.infer<typeof Schema>, Type>>`, see `_base/utils/typeEquality.ts`), the registrations, env bindings, and TOML transforms all live in the persistence wrapper `src/app/kosongConfig/configSection.ts`. (`modelCatalog` has no kosong-side type at all — its section is fully self-contained in `app/kosongConfig`, types derived from the schema.) A cross-section env overlay (e.g. the `KIMI_MODEL_*` synthesis in `src/app/kosongConfig/envOverlay.ts`) lives in the wrapper too and is registered via module-level `registerConfigOverlay`. The session subagent domain owns two sections in `src/session/subagent/configSection.ts`: `[subagent]` (`timeout_ms` on disk) and `[secondary_model]` (`default_model` plus the `[secondary_model.models]` pool, with a lone legacy v1 `model` key honored as a fallback default below `default_model`); neither carries a cross-section overlay. Cross-field pool validation (default present / in-pool / every key resolvable) runs at session creation in `subagentModelsValidationService.ts`, not in the schema. The two-way sync between config sections and kosong's in-memory registries is owned by `IKosongConfigService` (`src/app/kosongConfig/kosongConfigService.ts`).
## Scope
@ -117,9 +119,14 @@ A config section is identified by a camelCase domain key (`'providers'`, `'think
- `fromToml?: ConfigFromToml` — read-path transform (snake_case file value → in-memory shape). Defaults to a plain key-casing pass; owners register one when the on-disk shape needs custom normalization (record key preservation, nested object conversion, array entries, key renames, reshapes).
- `toToml?: ConfigToToml` — write-path transform (in-memory value → snake_case file value). Defaults to a plain camelCase→snake_case key mapping.
Two contribution channels:
- **Static (import = register)** — the owning domain calls `registerConfigSection(domain, schema, options)` at the top level of its `configSection.ts`; `ConfigRegistry` drains the collected contributions when it is constructed. Every in-repo section uses this channel.
- **Runtime (collection record)** — a unit contributes `this.provide(ConfigSectionContribution, { domain, schema, options })` (e.g. a feature assembled through `IFeatureManager`); the `ConfigRegistry` fold registers the section when the record lands and unregisters it when the record is withdrawn (provider disposed). User TOML values survive a withdrawal — they just stop being validated and effective.
Ownership rules:
- **One owner per section.** `registerSection` throws if a domain is registered twice.
- **One owner per section.** `registerSection` throws if a domain is registered twice — the static channel fails fast when `ConfigRegistry` drains it; a conflicting runtime record is reported through `onUnexpectedError` and the first registration wins (the fold is an event path and never throws).
- **The domain that consumes a config owns its schema.** This is what keeps `config` from depending on its consumers: `config` must not import `externalHooks` / `permissionRules` / `provider` / `kosong` / etc. for a section's schema. If a schema needs a domain's types, the schema lives in that domain.
- **Demand-driven.** Do not register sections for config that no domain reads yet; a section appears (with its schema in the owning domain) only when a consumer appears.
@ -131,7 +138,7 @@ Declare the bindings with `envBindings(schema, { … })` — the field names are
type-checked against the schema (no magic strings), and nested schemas recurse:
```ts
registerSection('thinking', ThinkingConfigSchema, {
registerConfigSection('thinking', ThinkingConfigSchema, {
env: envBindings(ThinkingConfigSchema, {
effort: 'KIMI_MODEL_THINKING_EFFORT',
}),
@ -139,7 +146,7 @@ registerSection('thinking', ThinkingConfigSchema, {
// nested / record section — outer key is a runtime constant, inner fields are
// checked against the value schema:
registerSection('providers', ProvidersSectionSchema, {
registerConfigSection('providers', ProvidersSectionSchema, {
env: envBindings(ProvidersSectionSchema, {
[ENV_MODEL_PROVIDER_KEY]: envBindings(ProviderConfigSchema, {
apiKey: 'KIMI_MODEL_API_KEY',
@ -184,21 +191,27 @@ never write their own env-merge logic.
export const MySectionSchema = z.object({ /* ... */ });
export type MySection = z.infer<typeof MySectionSchema>;
```
2. In the domain's service constructor, inject `IConfigRegistry` and register:
2. Register it at the top level of the same module (import = register):
```ts
constructor(@IConfigRegistry registry: IConfigRegistry) {
registry.registerSection(MY_SECTION, MySectionSchema, { defaultValue: {} });
}
// src/<domain>/configSection.ts
import { registerConfigSection } from '#/app/config/configSectionContributions';
registerConfigSection(MY_SECTION, MySectionSchema, { defaultValue: {} });
```
Pick a service whose scope matches when the config is first needed. Registering from an Agent-scope service is fine — see "Late registration".
3. Read it anywhere via `IConfigService`:
`ConfigRegistry` drains module-level contributions when it is constructed, so the section exists before any consumer resolves `IConfigService` — no owning Service needs to be constructed first. Make sure `src/index.ts` imports the leaf so the top-level call runs.
3. (Runtime variant) a dynamically loaded unit (e.g. one assembled through `IFeatureManager`) contributes the section as a collection record instead:
```ts
this.provide(ConfigSectionContribution, { domain: MY_SECTION, schema: MySectionSchema, options: { defaultValue: {} } });
```
The `ConfigRegistry` fold registers it incrementally and unregisters it when the unit is retracted (user TOML values survive) — see "Late registration".
4. Read it anywhere via `IConfigService`:
```ts
constructor(@IConfigService private readonly config: IConfigService) {}
// ...
const value = this.config.get<MySection>(MY_SECTION);
```
4. React to edits by subscribing `IConfigService.onDidChange` and filtering on `e.domain === MY_SECTION` (see `FlagService`).
5. Write it only through `IConfigService.set(domain, patch)` (merge) or `.replace(domain, value)` (wholesale). Never write `config.toml` directly.
5. React to edits by subscribing `IConfigService.onDidChange` and filtering on `e.domain === MY_SECTION` (see `FlagService`).
6. Write it only through `IConfigService.set(domain, patch)` (merge) or `.replace(domain, value)` (wholesale). Never write `config.toml` directly.
## Reads vs writes
@ -222,11 +235,11 @@ So `configure(...)` never overwrites the local file. Treat `config.toml` as the
## Late registration
`ConfigService` loads in its constructor (first `get(IConfigService)`). Domain services that register sections may be constructed later (especially Agent-scope services). To keep validation and defaults correct:
`ConfigService` loads in its constructor (first `get(IConfigService)`). Static sections are drained before that, but a runtime-contributed section (a `ConfigSectionContribution` record) can register at any later moment. To keep validation and defaults correct:
- `IConfigRegistry` emits `onDidRegisterSection` whenever a section is registered.
- `ConfigService` subscribes and, on registration, re-validates the already-loaded raw value for that domain, applies the default if the raw value is absent, re-runs the env overlay, and fires `onDidChange` if the effective value changed.
- Before a section is registered, `get(domain)` returns the raw (transformed, unvalidated) value; consumers that need validated values should read after the owning service is constructed, or react to `onDidChange`.
- `IConfigRegistry` emits `onDidRegisterSection` whenever a section is registered (and `onDidUnregisterSection` when a runtime record is withdrawn).
- `ConfigService` subscribes and, on registration, re-validates the already-loaded raw value for that domain, applies the default if the raw value is absent, re-runs the env overlay, and fires `onDidChange` if the effective value changed. On unregistration it devalidates the domain — `get(domain)` falls back to the raw value.
- Before a section is registered, `get(domain)` returns the raw (transformed, unvalidated) value; consumers that need validated values should read after the section lands, or react to `onDidChange`.
This means registration order is never a correctness concern — you do not need an eager bootstrap.
@ -263,11 +276,11 @@ registerSection(MY_SECTION, MySectionSchema, {
### `KIMI_MODEL_*` env overlay
When `KIMI_MODEL_NAME` is set, the `kosongConfig` wrapper's `kimiModelEnvOverlay` (`src/app/kosongConfig/envOverlay.ts`) injects a reserved model alias (`__kimi_env_model__`) into `effective`, points `defaultModel` at it, and merges the request `modelOverrides`; the reserved provider (`__kimi_env__`) comes from the `providers` section env bindings. The overlay is registered via `IConfigRegistry.registerEffectiveOverlay` and applied **only to `effective`**, never to `rawSnake`, so it is never persisted. Its `strip` (plus the providers section `stripEnv`) is the final guard so a caller that read `effective` (with the overlay) cannot write the reserved entries or the shell API key back to disk. `config` itself only runs registered overlays — it does not know the `KIMI_MODEL_*` semantics.
When `KIMI_MODEL_NAME` is set, the `kosongConfig` wrapper's `kimiModelEnvOverlay` (`src/app/kosongConfig/envOverlay.ts`) injects a reserved model alias (`__kimi_env_model__`) into `effective`, points `defaultModel` at it, and merges the request `modelOverrides`; the reserved provider (`__kimi_env__`) comes from the `providers` section env bindings. The overlay is registered via module-level `registerConfigOverlay` and applied **only to `effective`**, never to `rawSnake`, so it is never persisted. Its `strip` (plus the providers section `stripEnv`) is the final guard so a caller that read `effective` (with the overlay) cannot write the reserved entries or the shell API key back to disk. `config` itself only runs registered overlays — it does not know the `KIMI_MODEL_*` semantics.
## Owner-owned sections
`config` holds no monolithic config schema and no whole-config object. Every section is owned by the domain that consumes it: the schema (and any `fromToml` / `toToml` normalization and `stripEnv`) lives in that domain's `configSection.ts`, and the domain registers it via `IConfigRegistry.registerSection`. Cross-section env behavior (e.g. `KIMI_MODEL_*`) lives in an owner-registered `ConfigEffectiveOverlay`. To add a section, follow "Add a config section" above in the owning domain — never add schema or normalization to `config` itself.
`config` holds no monolithic config schema and no whole-config object. Every section is owned by the domain that consumes it: the schema (and any `fromToml` / `toToml` normalization and `stripEnv`) lives in that domain's `configSection.ts`, and the domain contributes it via module-level `registerConfigSection` (or a runtime `ConfigSectionContribution` record). Cross-section env behavior (e.g. `KIMI_MODEL_*`) lives in an owner-registered `ConfigEffectiveOverlay` (module-level `registerConfigOverlay`). To add a section, follow "Add a config section" above in the owning domain — never add schema or normalization to `config` itself.
## Ownership map (generated)
@ -287,13 +300,13 @@ The authoritative, always-current list of registered sections — rendered in th
## Red lines (this topic)
- One owner per section; `registerSection` throws on duplicate domains.
- One owner per section: a duplicate static registration throws when `ConfigRegistry` drains it; a conflicting runtime record is logged (`onUnexpectedError`) and the first registration wins.
- `config` never imports the domains that consume it — keep section schemas in the owning domain.
- Config is the **preference registry**: register only values that are preferences, persistable, schema'd, and user/operator-facing. Facts → `IBootstrapService`; session state → Session scope; constants → code.
- Business domains read `config.get(...)` or structured `IBootstrapService` facts; never call `IBootstrapService.getEnv()` directly — only `config` reads the raw env bag to build overlays.
- Keep `IBootstrapService` domain-agnostic: host invocation arguments (CLI flags, host identity headers, prompt identity) go into `BootstrapInput.args` / `IBootstrapService.args` — never into new per-domain runtime-options services; domain runtime state (cron, flags, model params, …) never goes onto `IBootstrapService` at all. Domain-specific config goes through `registerSection` + `envBindings`, read via `config.get(...)`.
- Keep `IBootstrapService` domain-agnostic: host invocation arguments (CLI flags, host identity headers, prompt identity) go into `BootstrapInput.args` / `IBootstrapService.args` — never into new per-domain runtime-options services; domain runtime state (cron, flags, model params, …) never goes onto `IBootstrapService` at all. Domain-specific config goes through `registerConfigSection` + `envBindings`, read via `config.get(...)`.
- Do not pass a whole config bag via options; read each section through `IConfigService`. There is no `KimiConfig` object — config is a registry of owner-owned sections.
- `config.toml` is snake_case on disk, camelCase in memory — never write camelCase keys to disk, and never write to `config.toml` except through `IConfigService.set/replace`.
- Reading config / calling `configure(...)` / switching model at runtime must not rewrite `config.toml`; runtime state lives in memory and the session wireRecord, not the file.
- Never persist env overlays (`__kimi_env__` / `__kimi_env_model__` / shell API key / experimental env); overlays live only in `effective` / `Memory`.
- Registering from an Agent-scope service is fine — the late-registration mechanism keeps validation correct; do not add an eager bootstrap.
- Runtime contribution (a `ConfigSectionContribution` record from a unit at any scope) is fine — the late-registration mechanism keeps validation correct; the static channel needs no eager bootstrap (import = register, drained at `ConfigRegistry` construction).

View file

@ -130,6 +130,8 @@ The three mechanisms above are also where a domain accepts new behavior without
| Step into an operation in order / veto | a **hook** (`onWill`/`onDid`, `OrderedHookSlot`) | the owning scope |
| Swap a backend (File ↔ DB ↔ S3) | a **Store / Storage token** at the byte layer (see persistence.md) | `App` (composition root) |
The standard shape of a "registry / catalog the domain queries" row is an L3 contribution point: the target domain owns a `collection<T>` token, contributors call `this.provide(token, record)` from a unit, and a fold service in the target domain injects the `CollectionView` (incremental `onDidChange`; provider death withdraws the record). The four in-repo seams are `ConfigSectionContribution``ConfigRegistry`, `AgentToolContribution``AgentToolActivationService`, `AgentProfileContribution``IAgentProfileRegistry`, and `WireModelContribution``WireService` (file-level pointers: `packages/agent-core-v2/AGENTS.md` §Units and contribution points).
Closed-for-modification means: the domain's own file is not where new scenarios branch. If a new scenario forces an edit here, an extension point is missing or misplaced.
## 5. Dependency direction

View file

@ -45,7 +45,7 @@ A Service method is directly exposable iff **all** hold:
3. Errors are `KimiError` (coded).
4. It is a command/query, not a factory, stream, byte-store, or sink.
If any fail → wrap in a **facade** (a Service that takes ids, returns data, throws `KimiError`) and expose the facade. The repo already ships a wire-shaped facade in `rpc/core-api.ts` (`CoreAPI` / `SessionAPI` / `AgentAPI`) behind `IAgentRPCService` / `ISessionRPCService` — prefer building the HTTP edge on top of it rather than re-deriving a new one.
If any fail → add a wire-safe orchestration method to the owning domain Service (e.g. `IAgentPromptService.submit` settles `{turn_id}` instead of returning the live `PromptHandle`) or compose several domain Services at the edge — kap-server's `routes/prompts.ts` is the reference for edge-side composition.
## 3. Per-scope `resource:action` map
@ -55,9 +55,9 @@ Read = `GET`, write = `POST`. `sid` = `session_id`, `aid` = `agent_id`.
| resource | action | Service.method | verb |
|---|---|---|---|
| `sessions` | `list` | ISessionIndex.list | GET |
| `sessions` | `listRecent` | ISessionIndex.listRecent | GET |
| `sessions` | `get` | ISessionIndex.get | GET |
| `sessions` | `countActive` | ISessionIndex.countActive | GET |
| `sessions` | `count` | ISessionIndex.count | GET |
| `workspaces` | `list` | IWorkspaceService.list | GET |
| `workspaces` | `get` | IWorkspaceService.get | GET |
| `workspaces` | `createOrTouch` | IWorkspaceService.createOrTouch | POST |

View file

@ -6,11 +6,11 @@ Gate not-yet-public features behind `IFlagService.enabled(id)`, per the reposito
## Layout
- `src/flag/flagRegistry.ts` — `IFlagRegistry` token + `FlagDefinitionInput` / `FlagId` / `FlagSurface` types + `registerFlagDefinition` / `getContributedFlags` (import-time contribution queue).
- `src/flag/flagRegistryService.ts` — `FlagRegistryService` impl; in-memory catalog seeded from import-time contributions; App scope.
- `src/flag/flag.ts` — `IFlagService` token + resolver types (`ExperimentalFlagMap`, `ExperimentalFlagConfig`, `ExperimentalFlagSource`, `ExperimentalFeatureState`) + `ExperimentalConfigSchema` / `ExperimentalConfig` (zod).
- `src/flag/flagService.ts` — `FlagService` impl + `MASTER_ENV` (`KIMI_CODE_EXPERIMENTAL_FLAG`) + `EXPERIMENTAL_SECTION` (`experimental`); reads definitions from `IFlagRegistry`; self-registers at App scope.
- `src/flag/index.ts` — **removed (no barrel)**; `src/index.ts` imports the `flag` leafs precisely instead (e.g. `import './flag/flagService'`).
- `src/app/flag/flagRegistry.ts` — `IFlagRegistry` token + `FlagDefinitionInput` / `FlagId` / `FlagSurface` types + `registerFlagDefinition` / `getContributedFlags` (import-time contribution queue).
- `src/app/flag/flagRegistryService.ts` — `FlagRegistryService` impl; in-memory catalog seeded from import-time contributions; App scope.
- `src/app/flag/flag.ts` — `IFlagService` token + resolver types (`ExperimentalFlagMap`, `ExperimentalFlagConfig`, `ExperimentalFlagSource`, `ExperimentalFeatureState`) + `EXPERIMENTAL_SECTION` (`experimental`) / `ExperimentalConfigSchema` (zod) + the module-level `registerConfigSection(EXPERIMENTAL_SECTION, …)` call that owns the section.
- `src/app/flag/flagService.ts` — `FlagService` impl + `MASTER_ENV` (`KIMI_CODE_EXPERIMENTAL_FLAG`); reads definitions from `IFlagRegistry` and overrides from `IConfigService`; self-registers at App scope.
- `src/app/flag/index.ts` — **removed (no barrel)**; `src/index.ts` imports the `flag` leafs precisely instead (e.g. `import './app/flag/flagService'`).
- `src/<domain>/flag.ts` — each domain that owns a flag declares it here and calls `registerFlagDefinition` at the module top level (e.g. `src/agent/toolSelect/flag.ts`). The directory already names the domain, so the file is just `flag.ts`.
## Public surface
@ -33,9 +33,9 @@ Highest wins; env is read live on every call (nothing cached):
## Config integration
- `FlagService` registers the `[experimental]` section into `IConfigRegistry` at construction (`registerSection('experimental', ExperimentalConfigSchema)`) and reads overrides from `IConfigService`.
- The flag domain owns the `[experimental]` section: `src/app/flag/flag.ts` registers it at module load via `registerConfigSection(EXPERIMENTAL_SECTION, ExperimentalConfigSchema, { fromToml, toToml })` (import = register, drained by `ConfigRegistry` at construction); `FlagService` reads overrides from `IConfigService`.
- It subscribes `IConfigService.onDidChange` and refreshes overrides whenever the `experimental` domain changes, so config edits apply live.
- `IConfigRegistry.registerSection` throws if a domain is registered twice — `experimental` is owned exclusively by `FlagService`.
- `ConfigRegistry.registerSection` throws if a domain is registered twice — `experimental` is owned exclusively by the flag domain.
- `setConfigOverrides(overrides)` is an imperative escape hatch for tests and hosts without an `IConfigService`; hosts on `IConfigService` should set the `[experimental]` section instead.
Config shape:
@ -54,7 +54,7 @@ Declare the definition in the owning domain's `flag.ts` and call `registerFlagDe
`src/<domain>/flag.ts`:
```ts
import { type FlagDefinitionInput, registerFlagDefinition } from '#/flag';
import { type FlagDefinitionInput, registerFlagDefinition } from '#/app/flag/flagRegistry';
export const myFeatureFlag: FlagDefinitionInput = {
id: 'my_feature',

View file

@ -31,7 +31,8 @@ export const IGreeter: ServiceIdentifier<IGreeter> = createDecorator<IGreeter>('
```ts
// greet/greetService.ts
import { LifecycleScope, registerScopedService, ScopeActivation } from '#/_base/di/scope';
import { LifecycleScope } from '#/app/scopes';
import { registerScopedService, ScopeActivation } from '#/_base/di/scope';
import { IGreeter } from './greet';
export class Greeter implements IGreeter {
@ -127,7 +128,8 @@ export class WSBroadcastService extends Disposable implements IWSBroadcastServic
- Extend `Disposable`, collect any `IDisposable` with `this._register(d)` (event subscriptions, `toDisposable(fn)`, etc.).
- The container calls `dispose()` automatically when the service is torn down; child resources release in turn.
- Disposal order is deterministic (orient.md): child scopes first, then reverse construction order within a scope.
- Disposal order is deterministic (orient.md): child scopes first; within a scope the Ledger (`src/_base/lifecycle/`) tears entries down in strict reverse registration order, serially — `Disposable` / `DisposableStore` delegate to it.
- Extend `Service` (from `#/_base/di/service`) instead when the unit needs capability calls on `this` (`provide` / `effect` / `on` / `get` / `ref`) — e.g. contributing a record to a `collection` token. `Service` extends `Disposable` (so `_register` is unchanged) and adds the two-phase construction protocol: `provide` / `on` / `effect` calls inside the constructor are buffered and flushed by the kernel after `Reflect.construct`; `get` / `ref` throw inside the constructor — dependencies stay constructor parameters. A manually `new`ed `Service` has no capabilities: every capability call throws.
## §5 Scope activation
@ -160,7 +162,7 @@ registerScopedService(
);
```
`ScopeActivation.OnScopeCreated` is the default fourth argument. Scope creation constructs every registration using this mode, after constructing its dependencies. If any constructor fails, scope creation fails. Use it for ordinary services and for constructor side effects that must exist when the scope becomes ready.
`ScopeActivation.OnScopeCreated` is the default fourth argument. Scope creation activates every registration using this mode, after constructing its dependencies. An eager constructor failure no longer fails scope creation: the unit lands in sticky `Failed` — scope creation succeeds, resolving the unit rethrows its error, and an explicit `update()` reloads it (see the bootstrap note below). Use it for ordinary services and for constructor side effects that must exist when the scope becomes ready.
`ScopeActivation.OnDemand` stores the descriptor without constructing the service. The first `get()` constructs and caches the real instance directly; later `get()` calls return that same instance. Use it only when construction should wait until the service is actually requested.
@ -168,6 +170,8 @@ Both modes use the same dependency graph and reject cycles with `CyclicDependenc
The complete registration signature is `registerScopedService(scope, id, ctor, activation = ScopeActivation.OnScopeCreated, domain?)`: activation is the fourth argument and domain is the fifth.
**Bootstrap shares the dynamic provide path.** Scope creation (`Scope.createApp` / `Scope.createChild` / `createScopedChildHandle` in `src/_base/di/scope.ts`) submits the scope kind's entire `registerScopedService` batch as ONE cascade transaction via `provideAll`: every token registers before the activation wave runs, so **registration order never matters**, and untracked transitive `createInstance` resolutions succeed inside the batch. A seed occupying a token (the `extra` tuple in `ScopeOptions`) overrides the static registration for that token. `activateScopeServices` is gone — there is no separate static activation path.
## §6 Using a service inside a plain function (`invokeFunction`)
When you do not want a new class and just need a service once, or when you expose a `ServicesAccessor` to the outside:
@ -198,7 +202,7 @@ class TurnRunner {
const runner = instantiation.createInstance(TurnRunner, 'hello', 1);
```
Static params come first (you pass them), service params follow (the container fills them), then `Reflect.construct` builds the instance. This object is **not** placed in any scope's singleton cache — every call is a fresh instance.
Static params come first (you pass them), service params follow (the container fills them), then `Reflect.construct` builds the instance. This object is **not** placed in any scope's singleton cache — every call is a fresh instance — and it is not tracked as a cascade unit either: `createInstance` products are cascade-exempt leaves that no cascade tears down or rebuilds; their owner disposes them.
> This is why service params must follow static params **for `createInstance`**: the container sorts by the parameter positions recorded via `@IX`. `_serviceBrand` lets the compiler tell the two kinds apart. Scoped services built by `registerScopedService` follow a different convention (`@IX` params first, optional static params after) — see service-authoring.md §constructor-conventions.
@ -234,7 +238,7 @@ Key points:
- `instantiation.createChild(collection)` builds a child container whose parent pointer is the current container — so the child resolves upward to `App` services (the visibility rule).
- Expose the child to the outside by wrapping it in a `ServicesAccessor` via `invokeFunction` (§6).
> Higher-level code usually calls `Scope.createChild(kind, id)` (it does the "filter descriptors + build child" for you). Drop to the manual `ServiceCollection` form only when you need explicit control.
> Higher-level code usually calls `Scope.createChild(kind, id)` (it does the "filter descriptors + build child" for you, then submits the whole batch through `provideAll` as one cascade transaction — see §5). Drop to the manual `ServiceCollection` form only when you need explicit control; to change bindings on an already-created container, prefer `provide` / `unprovide` / `update` over rebuilding a collection. Before the static batch lands, the scope-creation point runs the kernel's `ScopeUnits` fold (`_base/di/scopeUnits.ts` — materializes the recipes contributed to `ScopeUnits(kind)` as per-scope units) and then the `ScopeOptions.assemble` hook — the session domain uses the hook to construct its seed-adapter units (`session/sessionSeed/sessionSeedAdapters.ts`) so their provided tokens exist before the session services activate.
## §9 Cyclic dependencies (forbidden — refactor)
@ -276,6 +280,8 @@ Both `ScopeActivation.OnScopeCreated` and `ScopeActivation.OnDemand` construct t
| `Disposable` / `DisposableStore` / `IDisposable` | §4 | resource management and disposal |
| `Scope` / `LifecycleScope` | §3, §8 | the lifetime tree |
| `ScopeActivation` | §3, §5 | choose scope-created or first-`get()` construction |
| `Service` (`_base/di/service`) | §4 | unit base class — `this.provide/effect/on/get/ref` capabilities, two-phase construction |
| `collection<T>(name)` / `CollectionView<T>` (`_base/di/collection`) | §4 | contribution-point token + the fold's live view (provider death withdraws the record) |
| `SyncDescriptor` | (tests / low-level) | package a constructor + static args into a pending descriptor |
> Legacy export (not used in v2, just recognize it): `refineServiceDecorator` is a VS Code leftover DI helper. v2 src/test has zero references; always use `registerScopedService`.

View file

@ -17,24 +17,26 @@ Classes talk only to interfaces and never care how an implementation is construc
Lifetimes form a tree, from longest to shortest:
```text
App (0) process-wide, single global instance
└── Workspace (1) one workspace handler (a materialized workspace root)
└── Session (2) one session
└── Agent (3) one agent
App process-wide, single global instance
└── Workspace one workspace handler (a materialized workspace root)
└── Session one session
└── Agent one agent
```
```ts
// src/app/scopes.ts — the business layer declares the tiers and their order;
// the DI kernel only knows opaque string kinds plus the declared topology.
export enum LifecycleScope {
App = 0,
Workspace = 1,
Session = 2,
Agent = 3,
App = 'app',
Workspace = 'workspace',
Session = 'session',
Agent = 'agent',
}
```
- A larger number = shorter life = closer to a leaf.
- Later in the topology = shorter life = closer to a leaf.
- "Singleton" means **one per scope**: `ILogService` is global once; each `Session` scope has its own `ISessionMetadata`.
- `kind` strictly increases along the parent→child direction.
- `kind` must advance along the declared topology in the parent→child direction.
### Visibility rule
@ -47,7 +49,15 @@ A child scope sees its ancestors; a parent never sees its children. Resolution w
### Disposal order
Deterministic: **child scopes die first; within one scope, instances dispose in reverse construction order** (last constructed, first disposed). Business code declares which tier it lives in and never disposes by hand.
Deterministic: **child scopes die first; within one scope, teardown runs in strict reverse registration order, one entry at a time.** The mechanism is the Ledger (`src/_base/lifecycle/`): ordered effect bookkeeping, dual-track (sync + async disposers), serial reverse-order teardown (never parallel), with the teardown reason (`'scope-close' | 'cascade' | 'unload'`) passed through to every disposer. `Disposable` / `DisposableStore` (`src/_base/di/lifecycle.ts`) delegate to it — "reverse construction order" is a Ledger property, not a container convention. Business code declares which tier it lives in and never disposes by hand.
## Dynamic DI: units and cascades
Registration is not the end of the story. Every unit a container tracks — static registrations and runtime `provide`s alike — lives in a small state machine owned by the scope's cascade engine (`src/_base/di/cascadeEngine.ts`, one per scope container, orchestrating tree-wide). Vocabulary you will meet in errors, tests, and the debug surface:
- **Unit states**`Pending → Activating → Active`, plus `Unloading` during teardown and a sticky `Failed`. A construction failure parks the unit in `Failed` with no auto-retry: resolving it rethrows its error; an explicit `update()` reloads it.
- **Waiting area** — a unit whose declared dependencies are missing sits `Pending` and auto-activates when they arrive, including cross-scope wake-up when an ancestor gains the token. An `ondemand` unit counts as available: consumers pull it transitively at materialization.
- **Cascade transaction** — every `provide` / `unprovide` / `update` runs as one tree-wide transaction: contagion set from the persistent dependency graph (instance edges, child→parent across scopes) → abort hook → global reverse-topo teardown → apply the change → waiting-area recheck fixpoint → history ring. Static bootstrap shares this path: scope creation submits the kind's whole registration batch as one `provideAll`, so registration order never matters.
## Import boundaries
@ -56,45 +66,12 @@ There is no domain-layer numbering — a domain may import any other domain, gui
- v2 never imports v1 (`@moonshot-ai/agent-core` or any subpath).
- The kosong subtree (`src/kosong/{contract,protocol,provider,model}`) keeps its strict internal order (`contract ← protocol ← provider/model`), purity bans (no SDKs in `contract`/`protocol`), and the `provider/bases` registration boundary.
## File-header comment convention
## Comment convention
`packages/agent-core-v2/AGENTS.md` mandates a header-only comment style:
- **Header only.** Comments live solely in the top-of-file `/** */` block — never beside functions, methods, or statements. The code is the source of truth for *how*; the header states *what the module exposes and the responsibility it owns*.
- **Identity line first.** Start with `` `<domain>` domain — <one-line role>. `` Keep an existing `(cross-cutting)` label as-is. Write the role as a responsibility ("drives the turn lifecycle"), not a symbol list.
- **Scope is in the filename.** `workspace*.ts` = Workspace, `session*.ts` = Session, `agent*.ts` = Agent, no prefix = App (see service-authoring.md). State the same scope in the header so the two never drift.
- **Interface files** (`<name>.ts`) state the public contract + scope: which `IXxx` they define and what it is for.
- **Impl files** (`<name>Service.ts`) add collaborators + scope: list every imported cross-domain collaborator as a role ("persists records through `records`"); read scope from `registerScopedService(LifecycleScope.X, …)`.
- **Contribution files** (`<targetDomain>.ts` / `<what>.contrib.ts`) state what they register into the target domain (e.g. "registers the `log` config section into `config`").
- **Pure-function / `.types` / `.errors` files** state the responsibility only — they own no scoped state, so no scope line.
Impl file example (`sessionMetadataService.ts`):
```ts
/**
* `sessionMetadata` domain — `ISessionMetadata` implementation.
*
* Persists the session metadata document (`state.json`) through the `storage`
* access-pattern store (`IAtomicDocumentStore`), rooted at the `metaScope`
* namespace from `sessionContext`. Loads the existing document on
* construction (creating it on first run), and logs through `log`. Bound at
* Session scope.
*/
```
Contribution file example (`config.ts` inside `log/`):
```ts
/**
* `log` domain — registers the `log` config section into `config`.
*
* Owns the `log` section schema and its env overlay; imported for the
* registration side effect. Bound at App scope.
*/
```
`packages/agent-core-v2/AGENTS.md` bans comments: no file headers, no section banners, no statement-level narration — the code is the source of truth. The only exception is JSDoc attached to exported symbols, which flows into the generated `.d.ts` and the consumers' IDE hover. Tooling directives (`eslint-disable`, `@ts-expect-error`, …) are banned too: fix the underlying lint/type problem instead, and put negative type-safety cases in compiler-asserted fixtures. Scope is carried by the filename: `workspace*.ts` = Workspace, `session*.ts` = Session, `agent*.ts` = Agent, no prefix = App (see service-authoring.md).
## Red lines (this stage)
- Import via the `#/...` alias (mapped to `src/`); never reach into another domain's internals by relative path.
- Short-lived may inject long-lived; never the reverse.
- File-header comments describe role and scope only; never narrate implementation beside statements.
- No comments — not file headers, not beside statements; exported-symbol JSDoc is the only exception.

View file

@ -109,7 +109,8 @@ export const IAgentPromptService: ServiceIdentifier<IAgentPromptService> =
```ts
// promptService.ts — impl delegates to the native v2 Service
import { LifecycleScope, ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
constructor(@IAgentPromptService private readonly prompt: IAgentPromptService /*, ... */) {}
// submit() builds v2-native input, calls the native Service, projects the result
@ -127,7 +128,7 @@ registerScopedService(
Conventions:
- **Name** the domain `<domain>Legacy` and the interface with the scope prefix, `I<Scope><Domain>LegacyService` (e.g. `prompt` / `IAgentPromptService`), per service-authoring.md.
- **Header comment** must say it is an `edge adapter` and name both the v1 contract it implements and the native v2 Service it leaves untouched (see `prompt.ts`).
- **Role is carried by the name** — `<domain>Legacy` marks it as an `edge adapter`; the v1 contract it implements and the native v2 Service it leaves untouched stay evident from its delegation targets (see `prompt.ts`).
- **Scope** = the lifetime of the *legacy* state it holds (the `prompt` queue is per-agent → `LifecycleScope.Agent`). Apply [orient.md](orient.md) / [design.md](design.md) normally — a LegacyService is not exempt from scope rules.
- **Delegate, do not duplicate** business logic. The LegacyService translates the v1 contract into native-Service calls and translates results back; the real work stays in the native Service.
- **Contract types come from the v1 wire schema homes** (the owning v2 domain contract or `kap-server/src/protocol`), so the interface cannot drift from the wire shape.
@ -164,7 +165,7 @@ const route = defineRoute(
app.post(route.path, route.options, route.handler);
```
**For `/api/v2` (native):** add a `resource:action` entry to `actionMap` ([edge-exposure.md](edge-exposure.md) §3). If the method fails the direct-exposure rules (returns a handle / stream / bytes, takes a live object), wrap it in a wire-shaped facade first (`IAgentRPCService` / `ISessionRPCService`) and map to the facade — as `prompts:*` does via `IAgentRPCService`.
**For `/api/v2` (native):** add a `resource:action` entry to `actionMap` ([edge-exposure.md](edge-exposure.md) §3). If the method fails the direct-exposure rules (returns a handle / stream / bytes, takes a live object), add a wire-safe orchestration method to the owning domain Service first — as `prompts:submit` maps to `IAgentPromptService.submit`, which settles `{turn_id}` engine-side instead of returning the live `PromptHandle`.
### 5. Map errors
@ -217,7 +218,7 @@ This is the reference alignment (commits `feat(server-v2): port v1 /sessions/:si
**The split.**
- `/api/v2` keeps the native shape — `prompts:submit` / `steer` / `undo` / `clear` / `cancel` map to `IAgentRPCService` (a wire facade over the v2 turn driver) in `actionMap`. The native `IAgentPromptService` is untouched.
- `/api/v2` keeps the native shape — `prompts:submit` / `steer` / `undo` / `clear` / `cancel` map to the domain Services (`IAgentPromptService.submit` / `submitSteer`, `IAgentConversationUndoService.undo`, `IAgentLoopService.cancelFromUser`) in `actionMap`.
- `/api/v1` gets an `AgentPromptLegacyService` (`prompt/`, `LifecycleScope.Agent`) that re-implements the v1 scheduler — queue, `prompt_id`, steer/abort, auto-start-next — **on top of** the native `IAgentPromptService`. The `/api/v1` routes consume the LegacyService.
**The schema.** Both surfaces import `promptSubmissionSchema` / `promptSubmitResultSchema` / `promptListResponseSchema` / `promptSteerRequestSchema` / `promptSteerResultSchema` / `promptAbortResponseSchema` from the shared v1 wire schemas (see `packages/kap-server/src/protocol`). The `/api/v1` and `/api/v2` routes are therefore compatible with released clients by construction; the LegacyService projects v2 turn results back into those protocol shapes.
@ -235,7 +236,7 @@ Before submitting a server-align change:
- [ ] Request and response schemas come from their owning home (the `agent-core-v2` domain contract or `packages/kap-server/src/protocol`); no inline re-declaration in server-v2.
- [ ] Existing schema fields are unchanged in name, type, and semantics; only optional fields added (if any).
- [ ] Native v2 Service left clean; v1-only behavior isolated in a `<domain>Legacy` / `I<Domain>LegacyService` edge adapter when the semantics diverge.
- [ ] LegacyService registered with the correct `LifecycleScope` and a header comment naming it an edge adapter + the native Service it preserves.
- [ ] LegacyService registered with the correct `LifecycleScope` and named as the `<domain>Legacy` edge adapter preserving the native Service.
- [ ] Domain error codes registered in `agent-core-v2`; wire codes registered in `packages/kap-server/src/protocol`; route maps them in `sendMappedError`, matching v1's status codes and idempotent envelopes.
- [ ] Route resolves the scope from the URL by `accessor.get(IX)`; no cached scope; finishes before disposal.
- [ ] Tests assert the wire envelope + protocol shape; wire-shape guards added/updated where the route mirrors v1.

View file

@ -17,7 +17,7 @@ One folder per domain, **camelCase**: `session/`, `sessionActivity/`, `contextMe
```
- **Strictly one service per file.** An interface file holds exactly one injectable interface and exactly one `createDecorator(...)`; an impl file holds exactly one service implementation class and exactly one `registerScopedService(...)`. No exceptions for "tightly-coupled" groups: even same-scope collaborators each get their own `<name>.ts` + `<name>Service.ts` pair.
- **Scope is in the filename.** `workspace*.ts` = Workspace, `session*.ts` = Session, `agent*.ts` = Agent, no scope prefix = App (see [Naming](#naming)). The header comment restates the same scope.
- **Scope is in the filename.** `workspace*.ts` = Workspace, `session*.ts` = Session, `agent*.ts` = Agent, no scope prefix = App (see [Naming](#naming)).
- A domain therefore has as many impl files as it has services (e.g. `logService.ts` for the App `ILogService`, `sessionLogService.ts` for the Session `ISessionLogService`). See [Multi-Service domains](#multi-service-domains).
The package entry `src/index.ts` imports and `export *`s every domain's leaf files precisely (one line per leaf), so importing the package still runs every `registerScopedService(...)` side effect — exactly as the old per-domain barrels did.
@ -51,7 +51,7 @@ File names derive from the interface / class names so that scope and role are vi
| Shared-types file | `<domain>.types.ts` | `log.types.ts` |
| Errors file | `<name>.errors.ts` | `appendLogStore.errors.ts` |
Acronym-aware lowerCamelCase lowercases a leading acronym as a group: `ILLMRequester``llmRequester.ts`, `IWSGateway``wsGateway.ts`, `IOAuthToolkit``oauthToolkit.ts`, `IAgentRPCService` → `agentRpcService.ts`.
Acronym-aware lowerCamelCase lowercases a leading acronym as a group: `ILLMRequester``llmRequester.ts`, `IWSGateway``wsGateway.ts`, `IOAuthToolkit``oauthToolkit.ts`, `IMcpServerService` → `mcpServerService.ts`.
Because the impl class always ends in `Service` and the interface file never does, the two files of one service never collide — even for `Store` / `Registry` / `Resolver` interfaces (`IAppendLogStore``appendLogStore.ts` + `appendLogStoreService.ts`).
@ -137,7 +137,8 @@ Holds the concrete class(es) and the top-level registration. A typical impl:
* … collaborators as roles ("logs through `log`") … Bound at App scope.
*/
import { LifecycleScope, ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { ILogService } from '#/log';
import { type Greeting, IGreeter } from './greet';
@ -163,6 +164,8 @@ What belongs here:
- **Helper classes / functions** used only by this impl (e.g. a built-in writer, an `extractError` helper) — co-located in the same file.
- **Top-level `registerScopedService(...)`** — one per Service the file owns; importing the impl file runs the registration.
Base class: extend `Service` (from `#/_base/di/service`) when the unit needs capability calls on `this``provide` / `effect` / `on` / `get` / `ref` (e.g. contributing a record to a `collection` token). `Service` extends `Disposable`, so `_register` keeps working; constructor-time `provide` / `on` / `effect` calls are buffered and flushed by the kernel after construction, while `get` / `ref` throw inside the constructor (dependencies stay constructor parameters). Otherwise extend `Disposable` — both are full DI units; a service whose own members collide with the `Service` vocabulary (`name` / `state` / `config` / `get`) must stay on `Disposable` (leave a NOTE comment saying so).
## Constructor conventions
- Declare every dependency with `@IX` on a constructor parameter.
@ -290,11 +293,10 @@ Importing the package therefore fires every `register*` side effect, exactly as
- Load the impl file too — its top-level `registerScopedService(...)` only runs when the module is imported.
- `export *` helper modules only if they are part of the domain's public surface.
- Each leaf's file-header comment still names the domain, scope, and (for impls) the `register*` binding it owns.
## Comments
- **File-header comment is mandatory** and the only place comments live (orient.md). State the identity line, the role, collaborators (impls), and scope.
- **No comments** (orient.md): no file headers, no statement-level narration; the only exception is JSDoc attached to exported symbols.
- **Methods and fields carry no comments by default.** Well-named identifiers and types say *what*; the code is the source of truth for *how*.
- Write an inline comment only when the *why* is non-obvious (a hidden constraint, a subtle invariant, a workaround). One short line.
- For unimplemented stubs, throw `NotImplementedError('feature')` rather than `throw new Error('TODO: …')` (errors.md).
@ -317,7 +319,8 @@ export const IGreeter: ServiceIdentifier<IGreeter> = createDecorator<IGreeter>('
```ts
// greet/greetService.ts
import { LifecycleScope, ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { type Greeting, IGreeter } from './greet';
export class Greeter implements IGreeter {
@ -347,4 +350,4 @@ import './greet/greetService';
- Never `new` a `@IService`-carrying Service — except inside an explicit factory method, which is not a DI request.
- Events: typed per-Service event → `Event<T>`/`Emitter` from `'#/_base/event'`; cross-domain broadcast → `IEventService` from `'#/event'`.
- `src/index.ts` must import/export every leaf file (including the impl) so each `register*` side effect runs.
- File-header comment only; methods/fields carry no comments by default; stubs throw `NotImplementedError`.
- No comments by default (orient.md); stubs throw `NotImplementedError`.

View file

@ -79,8 +79,8 @@ Reach for this only when *which layer a service lives in* is itself the thing be
```ts
import { beforeEach, describe, expect, it } from 'vitest';
import { LifecycleScope } from '#/app/scopes';
import {
LifecycleScope,
ScopeActivation,
_clearScopedRegistryForTests,
registerScopedService,
@ -224,6 +224,14 @@ Do **not** add the system-under-test itself to the store. `TestInstantiationServ
Scope-host tests call `host.dispose()` in `afterEach` (or at the end of the `it`). Route teardown through the store so ordering is deterministic and nothing leaks when a test fails mid-way.
## Cascade: asserting unit state
The cascade engine's test vocabulary lives in two files: `test/_base/di/cascade.test.ts` (the mechanism matrix, including cross-scope orchestration) and `test/_base/di/provide.test.ts` (provide/unprovide semantics).
- **Assert unit states, not internals.** Every container exposes its engine as `container.cascade`: `stateOf(IX)``'Pending' | 'Activating' | 'Active' | 'Unloading' | 'Failed'`; `failureOf(IX)` → the sticky error of a `Failed` unit; `pendingSnapshot()` → the waiting-area contents.
- **The waiting area parks units with unregistered dependencies** — a unit whose declared deps are missing stays `Pending` (no throw), so a test must seed the full dependency chain. Example: a root→agent chain with no session container must seed the session-scope dependency explicitly — `ix.set(ISessionStateService, new SessionStateService())` in `test/session/agentLifecycle/agentLifecycle.test.ts` — or the dependent unit never activates.
- **Eager activation failure is sticky `Failed`, not a scope-creation throw.** Assert state + rethrow: `expect(ix.cascade.stateOf(IX)).toBe('Failed')`, then `expect(() => ix.invokeFunction((a) => a.get(IX))).toThrow(…)`. Do not expect scope/host creation itself to throw for a failing eager constructor.
## Assertions and naming
- One behavior per `it`; describe observable behavior (`child shadows parent registration`), not implementation (`calls _getOrCreateServiceInstance`).

View file

@ -21,7 +21,7 @@ Walk the stages you touched and confirm:
- **Design** — scope follows state identity; no `Map<sessionId, …>` at `App`; dependency arrows do not make a foundational layer know an upstream one; no cycle was routed around.
- **Implement** — no `new` on `@IService`-carrying classes; `@IX` on constructor params only (service params after static params); interface + impl carry `_serviceBrand`; decorator names unique; coded errors only; flags for unreleased behavior.
- **Test** — SUT resolved by interface; stubs under `test/`; scope tests re-register after `_clearScopedRegistryForTests()`; teardown through one `DisposableStore`.
- **Files**header comments describe role + scope only; registration runs from the impl file's top level; the new domain is exported from `src/index.ts`.
- **Files**no comments (exported-symbol JSDoc excepted); registration runs from the impl file's top level; the new domain is exported from `src/index.ts`.
Then re-read the [global red lines](SKILL.md#global-red-lines) once — they catch most cross-stage mistakes in a single scan.

View file

@ -1,99 +1,26 @@
---
name: gen-changesets
description: Use when generating changesets in the kimi-code repository, including package bump selection, internal package and CLI bundle handling, bump levels, major confirmation, and English changelog wording.
description: Use when generating changesets in the kimi-code repository — deciding whether to write one, which package to list, the bump level, the wording, and the confirmation workflow.
---
# Generate Changesets
`kimi-code` uses changesets to manage versions and changelogs. The current user-facing published package is:
The only user-facing published package is the CLI: `@moonshot-ai/kimi-code`. All other `@moonshot-ai/*` packages (sdk, agent-core, kosong, kaos, oauth, telemetry, and so on) are internal.
- `@moonshot-ai/kimi-code`: the CLI
## 1. Whether to Write
All other `@moonshot-ai/*` packages are treated as internal packages, including `@moonshot-ai/kimi-code-sdk`, `agent-core`, `kosong`, `kaos`, `kimi-code-oauth`, `kimi-telemetry`, and `migration-legacy`.
Rule of thumb: **if users cannot perceive the change, write no changeset.** A changeset is a user-facing changelog entry, not a shipping gate — internal changes merged to main ship with the next release anyway, so skipping loses nothing.
`@moonshot-ai/pi-tui` is a special internal package: it is a private fork (`private: true`) that is never published, but it keeps its own changelog through changesets. It is an exception to Core Rule 4 — see the dedicated section below.
Do not write:
- Docs-only or tests-only changes that never enter the shipped artifact.
- Changes internal to core/server packages — architecture, protocols, refactors, config/journal/wire mechanics — unless they fix a bug users care about.
- When you are unsure whether users can perceive a change, ask first.
## Core Rules
Do write: user-perceivable new features or behavior changes, and internal-package changes that fix a user-useful bug or change CLI output/behavior (list `@moonshot-ai/kimi-code` for those).
1. **Inspect the actual changes first.** Use `git status` / `git diff --name-only` to identify which packages were actually changed.
2. **List packages that changesets can release.** If a changed package is ignored in `.changeset/config.json`, do not put that ignored package in frontmatter together with a non-ignored package; changesets rejects mixed ignored/non-ignored frontmatter.
3. **Map ignored internal changes to the affected released package.** If an ignored internal package changes CLI output or behavior, list `@moonshot-ai/kimi-code` and describe the actual user-visible or release-artifact change in the changelog text.
4. **Internal package source changes that enter the CLI bundle must manually list the CLI — when they get a changeset at all.** `@moonshot-ai/kimi-code` inline-bundles `@moonshot-ai/*` source, but those internal packages are devDependencies from the CLI's perspective, so changesets will not automatically propagate bumps. If a change enters the CLI output and is user-perceivable, list `@moonshot-ai/kimi-code`. See rule 6 for when to skip the changeset entirely.
- **Web app (`@moonshot-ai/kimi-web`) changes always enter the CLI bundle.** `@moonshot-ai/kimi-web` is ignored by changesets (see `.changeset/config.json`) and cannot be mixed with `@moonshot-ai/kimi-code` in one changeset frontmatter. Describe the web change in the changelog text, but list `@moonshot-ai/kimi-code` so the CLI release carries the bundled `dist-web` output.
5. **Docs-only and tests-only changes usually do not need a changeset.** README, internal docs, and `test/` changes that do not enter package output do not trigger a CLI bump.
6. **Skip changes users cannot perceive — write no changeset at all.** The CLI changelog is user-facing; a changeset is a changelog entry, not a shipping gate. Internal changes merged to `main` still ship in the next release triggered by any user-facing changeset, so skipping the changeset loses nothing. Do not write changesets for:
- `agent-core-v2` internal architecture: new services, refactors, config-persistence or journal/wire mechanisms.
- `kap-server` WebSocket / REST protocol changes consumed only by the bundled web UI, kimi-inspect, or other dev tooling (new endpoints, subscribe protocols, stream baselines). A web-facing feature they back gets its own `web:` entry instead.
- Behavior that only takes effect on the experimental engine (e.g. experimental `kimi -p`), unless it exposes documented user configuration such as a `config.toml` section or env vars that also work on a shipped surface (TUI or `kimi web`).
- When unsure whether users can perceive a change, ask before writing.
7. `@moonshot-ai/vis` / `vis-server` / `vis-web` are ignored by changesets and should not be handled. `@moonshot-ai/kimi-inspect` (a private dev app that never ships) is likewise ignored and must never appear in a changeset frontmatter.
## 2. What to Write
## Workflow
1. List the changed packages and check whether each one is ignored by `.changeset/config.json`.
2. Decide whether the change is user-perceivable (Core Rule 6); if not, stop — no changeset.
3. Choose a bump level for each package.
4. If an ignored internal package change enters the CLI bundle, put `@moonshot-ai/kimi-code` in frontmatter instead of mixing the ignored package into the same changeset.
5. Create a short kebab-case file under `.changeset/`.
6. Split unrelated changes into separate changesets; keep one logical change in one file.
Before a release, review the accumulated `.changeset/` entries against Core Rule 6 and prune non-user-facing ones; the release PR regenerates from `.changeset/` on `main`, so deleting a changeset removes its changelog entry without affecting the shipped code.
Format:
```markdown
---
"<package A>": patch
"<package B>": minor
---
<English changelog entry>
```
## Bump Levels
| Level | When to use |
|---|---|
| `patch` | Bug fixes; build/package fixes; internal refactors that do not change behavior; wording tweaks; small dependency upgrades; small improvements to existing features with limited user-facing impact (e.g. a new keyboard shortcut, a flag alias, a minor UX tweak) |
| `minor` | A substantial new user-facing feature, such as a new slash command, a new built-in tool, or a new mode |
| `major` | Breaking changes: incompatible config changes, renamed or removed commands/arguments, behavior semantics changes, and similar |
When in doubt between `patch` and `minor`: if the change improves an existing feature and the user-facing impact is small, choose `patch` even when the change is technically "new". Reserve `minor` for a substantial new capability that introduces something users could not do before.
New configuration surface is not automatically `minor`. Additions to an existing feature's configuration — env var overlays, config-file fallbacks, global defaults under per-item settings — are `patch`. Examples: a global default MCP timeout when per-server timeouts already exist; env-based credentials for a service already configurable in `config.toml`.
### Major Rule
Never write `major` on your own.
If you believe a change qualifies as major, stop first, explain why, and ask the user for confirmation. Only write `major` after the user explicitly agrees. If the user does not reply, replies ambiguously, or disagrees, fall back to `minor`; if `minor` is also unclear, fall back to `patch`.
## Wording Rules
- Changelog entries **must be written in English**.
- **Keep the whole entry concise.** Aim for one short sentence that states what was done; at most a short sentence plus a one-line usage hint. Do not write a paragraph, do not pile on technical detail, and do not enumerate every sub-change.
- **For new user-facing features, append a brief usage hint** so users know how to try it. Keep it to a single short line — a command name, a subcommand, a flag, or a one-line "how to use". Do not explain design rationale or list edge cases. Skip the hint for bug fixes, internal changes, and refactors.
- Slash command: `Add the /foo slash command to list active sessions. Run /foo to see them.`
- CLI subcommand: `Add the kimi web subcommand to open the web UI. Run kimi web to launch it.`
- Flag: `Add a --bar flag to skip confirmation prompts. Pass --bar to skip.`
- Too long: `Add the /foo command to list active sessions. It accepts an optional --all flag to include background sessions, supports filtering by name with /foo <name>, and writes the result to the transcript...`
- User-facing CLI wording should only be used when CLI users can perceive the change.
- Internal changes that do not affect CLI users can still share a changeset with the CLI, but the wording must describe the real change honestly and must not present it as a user-facing feature.
- Do not mention file names, class names, function names, PR numbers, or commit hashes.
- Do not include real internal endpoints, key names, account names, or service names. If an example is needed, use neutral placeholders such as `example.com`, `example.test`, or `YOUR_API_KEY`.
- Avoid vague words such as `refactor`, `optimize`, and `improve`. Describe the actual change, or use more specific wording.
## When You Are Unsure About a Change
Generate the changeset from what the diff clearly shows. If part of a change is unclear and you cannot confidently describe what it does for users, do not guess or pad the entry with vague wording.
1. Finish the changeset for the parts that are clear.
2. Then ask the user once, in a short list: name the specific change(s) you do not understand, and ask whether you may dig into the repository (read related source, tests, or call sites) to describe it more accurately.
3. Only read more code after the user agrees. If the user says no or does not reply, keep the concise wording you already have and do not invent detail.
## Common Examples
An internal package fixes a bug visible to CLI users:
Create a short kebab-case file under `.changeset/`:
```markdown
---
@ -103,135 +30,34 @@ An internal package fixes a bug visible to CLI users:
Fix occasional loss of tool call results in long conversations.
```
A new user-facing slash command (note the short usage hint):
Wording:
- One short, user-facing English sentence that states only what changed. Drop trailing clauses that explain the cause, the benefit, or the mechanism.
- New features: say plainly what it is plus one line on how to use it, e.g. `Add the /foo slash command to list active sessions. Run /foo to see them.`
- Experimental features: also state how to enable them (the flag, config key, or env var).
- No file, class, or function names, and no PR numbers. No vague words like refactor, optimize, or improve. No real internal identifiers — use neutral placeholders such as `example.com` or `YOUR_API_KEY`.
- Internal packages' own changelogs (such as the sdk) are not curated for end users — write those entries honestly and technically.
- One logical change per changeset; split unrelated changes into separate files.
```markdown
---
"@moonshot-ai/kimi-code": minor
---
## 3. Bump Level
Add the /foo slash command to list active sessions. Run /foo to see them.
```
- `patch`: bug fixes, small improvements, configuration additions to existing features — when in doubt, use this.
- `minor`: a real new capability users could not do before (a new slash command, a new subcommand, a new mode).
- `major`: **never write it.** If you think a change qualifies, stop and ask the user; without explicit approval fall back to `minor`, or to `patch` if `minor` is also unclear.
A new CLI subcommand:
## 4. Which Package
```markdown
---
"@moonshot-ai/kimi-code": minor
---
- An internal change enters the CLI bundle and is user-perceivable → list `@moonshot-ai/kimi-code`.
- An internal change does not enter the CLI or is not user-perceivable → write nothing; if it is written, list only that internal package.
- Never mix packages ignored in `.changeset/config.json` with non-ignored packages in one frontmatter.
- pi-tui exception: pi-tui-only changes list `@moonshot-ai/pi-tui`; if the same change is also visible to CLI users, write a separate CLI changeset (two files, never mixed).
- kimi-inspect and the vis packages never appear in a changeset.
Add the kimi web subcommand to open the web UI. Run kimi web to launch it.
```
## 5. Workflow
A new flag on an existing command:
1. Run `git status` / `git diff --name-only` to see which packages actually changed.
2. Apply section 1; if no changeset is needed, stop.
3. Pick the package and the bump, and write the one sentence.
4. **Show the changeset text to whoever requested the work and get their confirmation before committing.**
5. Do not guess at changes you do not understand: finish the parts that are clear, then list what is unclear and ask whether you may dig into the code.
```markdown
---
"@moonshot-ai/kimi-code": patch
---
Add a --bar flag to skip confirmation prompts. Pass --bar to skip.
```
An internal package has an internal-only change, but it enters the CLI bundle:
```markdown
---
"@moonshot-ai/kimi-code": patch
---
Unify tool execution metadata handling.
```
Only SDK source changed, and the CLI does not use it:
```markdown
---
"@moonshot-ai/kimi-code-sdk": patch
---
Clarify session status typing for internal SDK callers.
```
## Web app changes
`@moonshot-ai/kimi-web` is ignored by changesets and must **never** appear in a changeset frontmatter. Because the web app is bundled into the CLI release artifact, any web change that ships must list `@moonshot-ai/kimi-code` instead and describe the actual web-facing change in the text.
- Prefix the changelog entry text with `web: ` (for example `web: Fix the chat not scrolling to the bottom after sending a message.`) so the synced docs changelog can mark web UI entries. Apply this whenever the change is to the web project (`@moonshot-ai/kimi-web`).
- If a PR ships a web UI feature backed by server API changes that exist solely to power that feature, prefer a single `web:` entry describing what the web user gets. Do not add a separate server-API changeset unless the API has independent user value (a public endpoint that SDK or server consumers call directly). The docs changelog sync also deduplicates this pattern, but catching it here avoids duplicate changesets.
- Do not enumerate every micro-tweak; keep it to one sentence that captures what the web user gets.
Web-only fix:
```markdown
---
"@moonshot-ai/kimi-code": patch
---
web: Fix the chat not scrolling to the bottom after sending a message.
```
Web UI plus backing server APIs in the same PR (prefer a single `web:` entry; the API is plumbing):
```markdown
---
"@moonshot-ai/kimi-code": minor
---
web: Add the server-hosted web UI, including chat layout and session list behaviors.
```
Split into two changesets only when the API has independent user value on its own (for example, a public endpoint SDK consumers call directly). In that case add the web entry above plus a separate one such as `Add a public REST API to list archived sessions for SDK consumers.`
## `@moonshot-ai/pi-tui` changes
`@moonshot-ai/pi-tui` is a vendored fork that lives in `packages/pi-tui`. It is `private: true` and is never published, but it is **not** ignored by changesets: changesets versions it and writes `packages/pi-tui/CHANGELOG.md` so the fork keeps its own history. Because it is bundled into the CLI like other internal packages, it is an exception to Core Rule 4 — do **not** list `@moonshot-ai/kimi-code` for a change that only touches pi-tui.
- Changes that only affect pi-tui (build, package, strict-mode cleanup, renderer fixes): list `@moonshot-ai/pi-tui` only. No CLI changeset.
- If the same change is also user-visible in the CLI (for example a terminal rendering fix that CLI users can see), add a **separate** changeset that lists `@moonshot-ai/kimi-code` with CLI-focused wording, in addition to the pi-tui changeset. Do not mix both packages in one frontmatter — the two changelogs need different wording.
pi-tui-only change:
```markdown
---
"@moonshot-ai/pi-tui": patch
---
Export the package manifest so the bundled binary can locate its native assets.
```
pi-tui change that is also visible in the CLI (two separate changesets):
```markdown
---
"@moonshot-ai/pi-tui": patch
---
Clamp the differential render to the visible viewport so scrolling up during streaming no longer jumps to the top.
```
```markdown
---
"@moonshot-ai/kimi-code": patch
---
Fix the transcript jumping to the top when scrolling up through history during streaming output.
```
## Red Flags
- You are about to write `major` without asking the user.
- You are writing a changeset for something users cannot perceive — `agent-core-v2` internals, `kap-server` WS/REST protocol plumbing, experimental-engine-only behavior. Skip the changeset instead (Core Rule 6).
- A new env var overlay or config fallback for an existing feature is bumped `minor` — configuration additions to existing features are `patch`.
- A new user-facing feature entry has no usage hint, or the hint runs to multiple lines and explains design rationale.
- You guessed wording for a change you do not understand instead of asking the user whether you may dig into the repo.
- Internal package source enters the CLI bundle, but `@moonshot-ai/kimi-code` is missing.
- A changeset frontmatter mixes ignored internal packages with non-ignored packages.
- `packages/node-sdk` was not changed, but `@moonshot-ai/kimi-code-sdk` was listed for "internal package sync".
- The changelog entry is in Chinese.
- The wording claims more than the diff actually did.
- The CLI wording mentions internal package names, class names, or PR numbers.
- The entry includes real internal identifiers instead of neutral placeholders.
- A change that only touches `@moonshot-ai/pi-tui` lists `@moonshot-ai/kimi-code` instead of `@moonshot-ai/pi-tui`, or mixes both packages in one frontmatter.
- A web app change entry is missing the `web: ` prefix.
- A server/API changeset exists only to back a web feature that a `web:` changeset already describes (use one `web:` entry instead, unless the API has independent user value).
Before a release, review the accumulated `.changeset/` entries and delete the non-user-facing ones — the release PR regenerates from `.changeset/` on main, so deleting a file removes its changelog entry without touching shipped code.

View file

@ -37,8 +37,9 @@ If the CLI changelog is not in the diff (for example an SDK-only release), stop
Process the version block exactly as `sync-changelog` does for the docs site, but only in memory:
- **Strip** (`sync-changelog` step 3): drop the H1, the `### Patch Changes` / `### Minor Changes` / `### Major Changes` subheadings, PR links, and commit-hash links; keep only each entry's body text. The `Thanks [@user](...)!` credit (including the multi-author form) must be removed every time. Within each entry, drop SDK-only and provider-internal sentences (SDK capability mapping / API exposure, provider wire-format mechanics, internal XML markers) and keep only the user-facing effect and required constraints.
- **Strip** (`sync-changelog` step 3): drop the H1, the `### Patch Changes` / `### Minor Changes` / `### Major Changes` subheadings, PR links, and commit-hash links; keep only each entry's body text. The `Thanks [@user](...)!` credit (including the multi-author form) must be removed every time. Within each entry, drop SDK-only and provider-internal sentences (SDK capability mapping / API exposure, provider wire-format mechanics, internal XML markers, hook/event payload mechanics such as what an event reports or carries) and keep only the user-facing effect and required constraints.
- **Merge and deduplicate** (`sync-changelog` step 4): merge micro-tweaks to the same surface into one higher-level entry; when three or more fixes target the same UI area or the same class of problem, merge them into one higher-level fix entry (do not merge broad or genuinely distinct fixes); and drop a server/API entry that only backs a web feature already listed.
- **Collapse low-signal entries** (`sync-changelog` step 4): keep standalone only entries that pass both gates — the reader-action test (the reader must do or re-evaluate something) and the channel test (the product cannot push it into the user's path: hidden controls, habit invalidations, capabilities users would not know to seek — a control merely sitting in the UI is not surfacing, users do not explore). Polish keeps only must-react items; experiences the product shows at the moment of need (recovery cards, post-install guidance) fold. Fixes keep only behavior-change entries (readers must update a habit, config, or workaround); loud failures fold (the fix itself notifies the victim), and silent past damage folds too — the changelog does not repair the past, and a notice that names no locatable instance and no realistic action is noise, not diligence. Section sizes follow density defaults (about 2 polish, 3 fixes) that yield to genuinely qualifying entries — flag the overflow for the reviewer instead of folding to hit the number. Fold everything else into one catch-all line placed last under 修复 — `修复了一些已知问题。` (or `修复了一些已知问题,并做了若干细节优化。` when non-fix entries were also collapsed; when nothing folded is a fix, place it under 优化 instead as `做了若干细节优化和内部改进。`), followed by a separate pointer sentence: `更详细的变更记录见 [GitHub](https://github.com/MoonshotAI/kimi-code/blob/main/apps/kimi-code/CHANGELOG.md)。` (file link, no version anchor; before the release PR merges, the target does not yet contain this version's block — expected for a preview).
- **Classify** (`sync-changelog` step 4): bucket into Features / Bug Fixes / Polish / Refactors / Other; order within each section by reader value (in Polish, user-visible improvements before protocol/internal adjustments).
- **Translate** (`sync-changelog` step 6): translate entry bodies to Chinese; keep one sentence per entry with a parallel rhythm within a section; section headings become 新功能 / 修复 / 优化 / 重构 / 其他.
@ -48,6 +49,10 @@ If an upstream entry is not in English, flag it and stop (changeset entries must
Print the preview directly. Use `<version>(预览)` as the heading because the version is not released yet. Write `无` for empty sections. Do not write any file.
After the preview block, append a reviewer-only section titled `### 审稿参考(不进入文档)`: list every entry folded into the catch-all (short English title, one line each), note any section that exceeds the density defaults, and flag borderline calls for the reviewer to confirm. This breakdown is how reviewers see what was folded — before merge, the catch-all pointer's target does not yet contain the version's block. Never write this section into the docs pages.
The preview is pasted into chat tools (for example Lark), where relative docs links do not resolve. Rewrite every docs link to its absolute published URL: map `../<path>.md[#anchor]` to `https://moonshotai.github.io/kimi-code/zh/<path>.html[#anchor]` — for example `../configuration/config-files.md#loop-control``https://moonshotai.github.io/kimi-code/zh/configuration/config-files.html#loop-control`. Never emit raw relative paths, and never wrap a link in backticks; code-style the link text inside the brackets instead ([`loop_control`](...)).
```
发版 PR: <url>

View file

@ -115,18 +115,11 @@ Drop SDK-only and provider-internal detail. This changelog serves `@moonshot-ai/
- Drop sentences about how the SDK maps a capability, builds model aliases, or exposes a flag through an API such as `getExperimentalFeatures()` — that belongs in the SDK changelog, not here.
- Drop provider / wire-format implementation mechanics (XML markers like `<tools_added>`, protocol field explanations, "the wire protocol is unchanged", cache-hit mechanics) unless they are the behavior a user perceives.
- Drop hook/event payload mechanics — clauses about what extra fields an event payload carries or what an event reports in a specific case (for example "enrich hook payloads with the session title and client type", "`SessionEnd` reports `archive` when a session is archived"). Keep the new events or capability itself and how to configure it.
- Keep the user-facing effect and any constraints users must follow (for example "question texts must be unique").
Do not change facts or drop a real user-facing behavior — only trim the internal-only scaffolding. For over-long, internal-heavy entries, this trim applies on the English page too, not only in translation.
Web UI prefix: if the entry is a web UI change, prefix the body text with `web: ` so readers can tell it affects the web UI:
```markdown
- web: <body text>
```
An entry counts as a web UI change when its upstream commit touches `apps/kimi-web/`. Check with `git show --name-only <hash>` (the commit hash is the one stripped above). `gen-changesets` writes this prefix for web changes, so it is usually already present in upstream — preserve it when it is there, and add it when a web entry lacks it. When a commit touches both web and non-web code, use `web:` only if the user-facing change described by the entry is in the web UI. Keep the `web:` prefix on the Chinese page too — it is a scope marker, not translated text.
Upstream language rule: `gen-changesets` requires changelog entries to be English. If the upstream CLI changelog contains a non-English entry, stop and report it to the user. Do not silently rewrite it while syncing docs.
Public-text rule: do not copy real internal endpoints, key names, account names, or service names into docs changelogs. Replace examples with neutral placeholders such as `example.com`, `example.test`, or `YOUR_API_KEY` while preserving the user-visible meaning.
@ -135,13 +128,21 @@ Public-text rule: do not copy real internal endpoints, key names, account names,
Before classifying, merge related entries and drop redundant ones from the user-facing changelog:
- **Merge micro-tweaks to the same surface.** Collapse several small tweaks to the same UI area or feature into one concise entry at the higher level. For example, "change the composer's default height" and "change the composer's default font" merge into "Polish the composer's default styling." Use the most specific common ancestor (composer, settings page, tool card, and so on). Classify the merged entry by its combined effect, and keep the `web:` prefix if the combined change is still web-facing.
- **Curate for end users: collapse low-signal entries into one catch-all line.** The docs changelog is the only curated, user-facing outlet; the full entry list always remains in the upstream package changelog, so hiding detail here loses nothing. Apply two gates to every candidate entry. Gate 1, the reader-action test: **after reading this, is there something the reader must do, or something they must re-evaluate?** Gate 2, the channel test: **is the changelog the only channel that can deliver this?** The changelog is the channel of last resort — when the product itself surfaces the information in context, at the moment of need, to exactly the affected users, the entry is redundant no matter how real the improvement is. "Surfaced" means pushed into the user's path, not merely present on screen: an event-triggered card, prompt, or post-install screen forces the encounter, while a toggle, menu item, command, or settings page only waits to be found. Users do not explore — a capability that lives only in ambient UI is effectively undiscoverable, so the changelog must announce it. What in-product surfacing cannot deliver: hidden controls (env vars, config keys, opt-out flags nobody would find unprompted), invalidations of existing habits or expectations (in-product discovery comes as confusion), and capabilities users would not know to seek. An entry that fails either gate folds. Anchor both gates to the changelog's reader, never to the bug's victim: someone who hit a loud failure does not need the changelog to confirm the fix — the product working again is the notification — and a reader who never hit it gets nothing from the entry.
- `Features`: keep when users would try it or must react to it — new capabilities create demand readers did not know to seek. Collapse only behavior that takes effect solely behind an experimental flag.
- `Polish`: keep only must-react items — a notification users may want to turn off, a behavior change to a command they already use, a default flip with an opt-out. Fold improved experiences the product surfaces in context (recovery cards, post-install guidance, progress or status displays): they are discovered at the moment of need, and pre-reading about them helps nobody. Also fold subtle or transient tweaks (status wording, spacing, animations) and internal-behavior adjustments — nobody acts on them.
- `Bug Fixes`: keep only **behavior-change** fixes — the fix changes how something works going forward, so readers must update a habit, a config, or a widely-adopted workaround. Everything else folds, for one of two opposite reasons. Loud failures (crashes, refusals, interrupted runs): the fix itself notifies whoever was hit — announcement value falls as bug visibility rises. Silent past damage (dropped data, wrong results the user never noticed): the changelog cannot repair the past, and in this product the notice names no locatable instance and no realistic action — users cannot enumerate which old sessions were affected, and they do not audit finished sessions; a "some past outputs may be wrong" line is anxiety without an outlet, not diligence. The rare exception is a retrospective notice with a concrete, locatable action (for example rotating a token after a credential-handling flaw); keep those. Never keep a fix merely because it was severe, and never keep one because the bug class feels important.
- Do not grade entries by engineering importance. Severity and effort are already represented upstream; the curated changelog is not a credit ledger — its only job is to change what the reader does or knows.
- **Density, not quota.** Standalone sections stay short so the changelog actually gets read — as a default, expect about 2 Polish and 3 Bug Fixes entries per version, while `Features` is gated by the test alone and has no count. The defaults yield whenever more entries genuinely pass the reader-action test: keep them and flag the overflow for the human reviewer; never fold a qualifying entry just to hit the number, and never pad a section to reach it. The reviewer owns the final cutoff — the curator's job is to surface the borderline calls, not to resolve them silently.
- Everything else collapses into a single catch-all bullet placed last under `Bug Fixes`: `Fix several known issues.` When entries beyond fixes were also collapsed, use `Fix several known issues and make various refinements.` instead (Chinese: `修复了一些已知问题。` / `修复了一些已知问题,并做了若干细节优化。`). End the catch-all line with a pointer to the upstream file so folded entries stay reachable, phrased as a separate short sentence — `See the [changelog on GitHub](https://github.com/MoonshotAI/kimi-code/blob/main/apps/kimi-code/CHANGELOG.md) for more technical entries.` (Chinese: `更详细的变更记录见 [GitHub](https://github.com/MoonshotAI/kimi-code/blob/main/apps/kimi-code/CHANGELOG.md)。`). Link the file itself, never a per-version anchor — GitHub's generated heading anchors are fragile. Keep the pointer wording restrained ("more technical entries"): upstream only contains changes that received a changeset, so never claim the list is complete.
- If no fix survives, the `Bug Fixes` section is the catch-all line alone; if the whole version has no user-facing change, the version block is a single section with that line. Match the catch-all to what was folded — never claim fixes that did not happen: when the folded entries include fixes, use the forms above under `Bug Fixes`; when everything folded is polish or internal work, place the catch-all under `Polish` as `Make several refinements and internal improvements.` (Chinese: `做了若干细节优化和内部改进。`).
- **Merge micro-tweaks to the same surface.** Collapse several small tweaks to the same UI area or feature into one concise entry at the higher level. For example, "change the composer's default height" and "change the composer's default font" merge into "Polish the composer's default styling." Use the most specific common ancestor (composer, settings page, tool card, and so on). Classify the merged entry by its combined effect
- **Merge same-surface or same-kind fixes when you have three or more.** The `Bug Fixes` section tends to accumulate many narrow UI/polish fixes that read as noise when listed one by one. When three or more fixes target the same area (for example several tool cards in the TUI, or the web session/conversation surface) or the same class of problem (for example several "jumping/flickering/collapsing during streaming" fixes), merge them into one higher-level entry. Examples:
- "Fix the Bash tool card collapsing...", "Fix the Edit tool card jumping in height...", "Fix the Edit tool card flickering while its result streams in" → "Fix several TUI tool cards jumping, flickering, or collapsing in height when results stream in or end with short output."
- "Fix the collapsed sidebar not hiding...", "Stop the chat history from replaying its entrance animation...", "Fix tool components jumping the conversation when expanded/collapsed" → "web: Fix several layout and display glitches when switching sessions, including the collapsed sidebar not hiding, the chat history replaying its entrance animation, and tool components jumping the conversation."
- Keep `web:` if the merged fixes are all web-facing. Classify as `Bug Fixes`.
- **Do not over-merge.** Leave a fix standalone when it is broad, high-value, or genuinely distinct (for example model/provider tool-calling bugs, session-list corruption, file-completion gaps). Merging is for low-reader-value, similar-shape fixes that read as a wall of similar bullets.
- **Drop server/API plumbing covered by a web entry.** If one entry adds a web UI feature (for example, an Archived sessions page) and another entry only adds the server or REST/WebSocket endpoints that exist solely to power that web feature, keep the `web:` entry and drop the API entry. CLI and web users perceive the web page; the backing API is implementation detail with no independent user value on this changelog. Keep the API entry only when it has independent user value — a new public endpoint that SDK or server consumers call directly, or a capability usable outside the web feature. When unsure, keep both and let the reviewer decide.
- "Fix the collapsed sidebar not hiding...", "Stop the chat history from replaying its entrance animation...", "Fix tool components jumping the conversation when expanded/collapsed" → "Fix several layout and display glitches when switching sessions, including the collapsed sidebar not hiding, the chat history replaying its entrance animation, and tool components jumping the conversation."
- Classify the merged fixes as `Bug Fixes`.
- **Do not over-merge.** Leave a fix standalone when it is broad, high-value, or genuinely distinct (for example model/provider tool-calling bugs, session-list corruption, file-completion gaps). Merging is for low-reader-value, similar-shape fixes that read as a wall of similar bullets. A merged fix entry must still pass the standalone test from the catch-all rule above; if the merged group is low-signal too, fold it into the catch-all line instead of listing it.
- **Drop server/API plumbing covered by a web entry.** If one entry adds a web UI feature (for example, an Archived sessions page) and another entry only adds the server or REST/WebSocket endpoints that exist solely to power that web feature, keep the web UI entry and drop the API entry. CLI and web users perceive the web page; the backing API is implementation detail with no independent user value on this changelog. Keep the API entry only when it has independent user value — a new public endpoint that SDK or server consumers call directly, or a capability usable outside the web feature. When unsure, keep both and let the reviewer decide.
The docs changelog uses five section types:
@ -153,6 +154,8 @@ The docs changelog uses five section types:
| `### Refactors` | `### 重构` | Internal changes with no user-visible behavior change, including build, CI, tests, dependency cleanup, and internal renames |
| `### Other` | `### 其他` | Anything that does not fit above, such as CDN/endpoint swaps and docs-related artifacts |
With the catch-all rule above, `Refactors` and `Other` rarely appear in newly synced versions: entries with no user-perceivable effect fold into the catch-all, and an entry that does change user-perceivable default behavior (for example an engine default flip with an opt-out flag) is classified by that effect, usually `Polish`. Reserve `Other` for genuinely unclassifiable but user-facing entries. Older versions keep whatever sections they already have — do not rewrite history.
Classification process:
1. Classify from the stripped entry text first.
@ -229,6 +232,8 @@ Example:
- Update the native release workflow to use current GitHub artifact actions.
```
Doc links: an entry that changes a documented config surface may end with a pointer to the docs page — `see [X](...) for details` (Chinese: `详见 [X](...)。`). Keep it a real Markdown link into the docs tree with a relative path (for example `../configuration/config-files.md#loop-control`). When the link text is a config key or another identifier, code-style the text inside the brackets: [`loop_control`](../configuration/config-files.md#loop-control). Never wrap the whole link in backticks — `` `[loop_control](...)` `` renders as raw inline code that exposes the relative path instead of a clickable link.
### 6. Translate The Increment Into Chinese
After updating the English page, translate only the newly added English content into `docs/zh/release-notes/changelog.md`.
@ -281,7 +286,7 @@ Guidelines:
- **Keep usage hints to one short clause**.
- Bad: `传入 --allowed-host 以允许额外的 host。例如 ... (多句展开)`
- Better: `例如 kimi web --allowed-host example.com。`
- **Do not translate technical identifiers**: keep command names, flag names, file names, env vars, config keys, and the `web:` scope prefix as-is.
- **Do not translate technical identifiers**: keep command names, flag names, file names, env vars, config keys as-is.
- **Keep parallel rhythm within a section.** When several entries fix similar web surfaces (layout, animation, sizing), phrase them with a consistent structure (for example 修复 <问题>,现 <行为>) so the section reads as a tidy list rather than a mix of shapes.
Example — translating a feature entry:
@ -319,9 +324,11 @@ Check:
- Each version has the same section set and order on both pages.
- Each section has the same number of entries on both pages.
- Within each section, the most valuable, obvious, and larger entries appear before smaller or narrower entries.
- Low-signal entries were collapsed into the single catch-all line, placed last under `Bug Fixes` — or under `Polish` when nothing folded is a fix (both the reader-action test and the channel test applied); the catch-all wording matches what was folded and never claims fixes that did not happen; section sizes stay within the density defaults (about 2 Polish, 3 Bug Fixes) unless extra qualifying entries were deliberately kept and flagged for review. The catch-all line ends with the upstream changelog pointer (file link, no version anchor).
- PR links and commit hashes were stripped.
- No `Thanks ...!` credit remains (remove it every time).
- Real internal identifiers were replaced with neutral placeholders.
- Doc links are real Markdown links (code-styled text inside the brackets when needed), never wrapped in backticks.
- There are no empty sections.
- Markdown indentation and blank lines are intact.
@ -346,7 +353,7 @@ If the user chooses review:
git diff docs/en/release-notes/changelog.md docs/zh/release-notes/changelog.md
```
2. Summarize synced versions, section counts, and anything that needed manual classification.
2. Summarize synced versions, section counts, and anything that needed manual classification. List every entry folded into a catch-all line (short titles, one line each), any section that exceeds the density defaults, and every borderline call flagged during curation — the reviewer cannot own a cutoff they cannot see.
3. Tell the user to reply when they are done reviewing, or to ask for edits.
4. Do **not** commit, push, or open a PR until the user explicitly says review is complete, or asks to proceed.
@ -426,7 +433,6 @@ Return the PR URL to the user when done.
- The English docs changelog is the source of truth.
- Never edit upstream `apps/kimi-code/CHANGELOG.md`.
- Do not backfill unreleased `.changeset/*.md` drafts into the docs site.
- Prefix web UI entries with `web: ` (when the upstream commit touches `apps/kimi-web/`), and keep the prefix on both the English and Chinese pages.
- If upstream wording is wrong, leave upstream alone and fix it in a future changeset.
- Always sync on a `docs/changelog-sync-*` branch and open a PR; never push changelog docs sync directly to `main`.
- Wait for the human review checkpoint before committing, pushing, or opening a PR.
@ -440,7 +446,15 @@ Return the PR URL to the user when done.
| Leaving the `Thanks ...!` credit in docs | Remove it every time, including the multi-author form |
| Leaving near-duplicate micro-tweaks as separate bullets | Merge small tweaks to the same surface into one higher-level entry (e.g. composer height + font → composer's default styling) |
| Listing many narrow fixes to the same surface as separate bullets | When three or more fixes target the same UI area or the same class of problem, merge them into one higher-level fix entry; keep genuinely distinct or high-value fixes standalone |
| Listing a server/API entry that only backs a web feature already listed | Drop the API entry and keep the `web:` entry, unless the API has independent user value |
| Listing low-signal fixes or internal changes as standalone bullets | Collapse them into the single catch-all line (`Fix several known issues.`) placed last under Bug Fixes; treat the section-size defaults (about 2 Polish, 3 Bug Fixes) as a density guard, not a quota |
| Folding a qualifying entry just to hit the section-size default | The defaults are density guards; keep entries that genuinely pass the reader-action test and flag the overflow for the human reviewer |
| Keeping a fix because it was severe or hard-won | Severity makes the announcement redundant — the fix itself notifies whoever was hit; keep only behavior-change fixes and retrospective notices with a concrete, locatable action |
| Keeping an improvement the product surfaces in context (recovery cards, post-install guidance, progress displays) | The product is the better channel — right users, moment of need; fold it (channel test) |
| Folding a new capability because its control is visible somewhere in the UI | Visible is not discoverable — users do not explore; a toggle, menu item, or settings page that only waits to be found needs the changelog announcement |
| Keeping a silent-impact fix out of diligence (dropped data, wrong results the user never noticed) | The changelog does not repair the past; if the notice names no locatable instance and no realistic action, it is anxiety without an outlet — fold it |
| Overstating the catch-all pointer (for example claiming the upstream changelog is complete) | Keep the pointer restrained — `See the [changelog on GitHub](...) for more technical entries.`; upstream only contains changes that received a changeset |
| Writing `Fix several known issues.` when nothing folded is a fix | Never claim fixes that did not happen; all-polish/internal folds go under Polish as `Make several refinements and internal improvements.` |
| Listing a server/API entry that only backs a web feature already listed | Drop the API entry and keep the web UI entry, unless the API has independent user value |
| Rewording upstream English entries | Upstream is frozen; copy the body text unless the user explicitly asks otherwise |
| Leaving English text untranslated in the Chinese page | The Chinese page must be fully Chinese except preserved technical terms |
| Editing upstream changelog text | Do not edit upstream |
@ -454,12 +468,13 @@ Return the PR URL to the user when done.
| Leaving empty sections | Delete sections with no entries |
| Putting everything under Other for convenience | Classify what can be classified first |
| Translating tool names, command names, or config keys | Keep them as written |
| Wrapping a whole doc link in backticks | Code-style the link text inside the brackets instead, so the link stays clickable: [`loop_control`](...) |
| Keeping hook/event payload-mechanics clauses | Drop what an event reports or carries; keep the new capability and how to configure it |
| Creating a changeset for docs sync | Do not create one |
| Committing or pushing directly on `main` | Create `docs/changelog-sync-<version>`, commit there, then open a PR |
| Committing or opening a PR before the user skips review or confirms review is done | Wait at the human review checkpoint |
| Using curly quotes or half-width Chinese punctuation | Follow `docs/AGENTS.md` |
| Omitting the release date from a version heading, or guessing it | Add ` (YYYY-MM-DD)` (full-width `` in Chinese) taken from the published tag |
| Forgetting or translating the `web:` prefix on web UI entries | Prefix web UI entries (commit touches `apps/kimi-web/`) with `web: ` on both pages; keep the prefix as-is when translating |
## Stop Signals

View file

@ -20,7 +20,6 @@ All other workspace packages are private internal packages, are not published to
- `@moonshot-ai/kaos`
- `@moonshot-ai/kimi-code-oauth`
- `@moonshot-ai/kimi-telemetry`
- `@moonshot-ai/kimi-web`
- `@moonshot-ai/kosong`
- `@moonshot-ai/migration-legacy`
- `@moonshot-ai/protocol`

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: fix thinking blocks in the subagent detail panel being stuck expanded and not collapsible.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
Fix sessions failing to archive when their workspace folder no longer exists.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix pressing Esc to cancel an IME candidate also closing the BTW side chat.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix the composer not receiving focus after opening the BTW side chat via the shortcut or /btw.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
Add the Tencent CloudBase plugin to the curated marketplace.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix composer toolbar buttons squeezing and overlapping each other in very narrow windows.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
Fix the latest reply disappearing from the transcript after a scheduled cron reminder fires.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
Fix ACP session regressions: Bash, Grep, and Glob failing when the editor does not support terminal command execution, session creation failing with stdio MCP servers, and reopening a closed session failing with an internal error.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix memory usage growing steadily after repeatedly switching sessions and toggling the side chat and subagent panels.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix unsent composer attachments such as images being lost after switching sessions on the new-session page.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix long question text in question cards being truncated with an ellipsis instead of wrapping.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
Prevent AskUserQuestion from starting background tasks when task controls are unavailable.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Remove the redundant parenthesized domain from the login entry card titles.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix the send and stop button icons rendering too small in the mobile composer.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": minor
---
web: Fix the slash-command and @-mention panels failing to open on mobile — both panels and the + menu are now grab-handle bottom sheets on small screens.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Present the mobile model picker as a bottom sheet consistent with the other mobile drawers.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix the oversized appearance theme cards in the mobile first-run wizard.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Temporarily remove the custom-provider entry from the mobile first-run wizard.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Improve mobile UI styling.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": minor
---
web: Add a flat/by-workspace tab to the mobile session list — the flat view sorts purely by recency and the grouped view orders each workspace by its latest session.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix tool-call rows alternating heights on mobile by unifying them to the compact row height.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Collapse the composer model picker to an icon when space is tight; hovering still shows the model and reasoning effort.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix the composer permission mode label being hidden even when there is enough space.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Remove the /auto, /yolo, and /thinking slash commands; permission mode and thinking effort remain adjustable from their settings UI.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
Respect workspace trust and configuration readiness when managing MCP servers.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code-sdk": patch
---
Add an optional `cwd` parameter to the global MCP management methods; `verify: false` on the global MCP authorization-status listing now returns a fully offline classification instead of behaving like an omitted `verify`.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix mismatched left and right margins in the sidebar session list, and show the scrollbar only while hovering or scrolling.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": minor
---
Add an optional `fork` parameter to the subagent and swarm tools that starts the subagent with a snapshot of the calling agents conversation history instead of an empty context. Experimental: enable it by setting `KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK=true` or `subagent_fork = true` under `[experimental]` in config.toml.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Restyle background task notifications as a lighter notice that shows the task summary, output files, and output preview directly.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": minor
---
Add tower mode as a plan-parallel mode gated behind the experimental flag `KIMI_CODE_EXPERIMENTAL_TOWER` (off by default): /tower reports status, /tower on|off toggles the mode with a footer indicator, and /tower <objective> starts multi-agent orchestration.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
web: Fix the reset-time hint in the sidebar usage panel being ellipsized even when there is enough room.

View file

@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---
Fix file tools and shell working directories failing to resolve Git Bash paths such as /c/Users or /tmp on Windows.

View file

@ -13,7 +13,7 @@ body:
Please try to include as much information as possible.
If you plan to submit a fix: link this issue in your PR. Small, reproducible bugs can go straight to a PR; for broader or uncertain fixes, wait for maintainer feedback first.
If you plan to submit a fix: check the Contribution box below and wait for a maintainer's `/approve` comment in this issue before opening a PR.
- type: input
id: version
@ -65,3 +65,10 @@ body:
attributes:
label: Additional information
description: Is there anything else you think we should know?
- type: checkboxes
id: willing-to-pr
attributes:
label: Contribution
options:
- label: I am willing to submit a PR for this bug fix myself (please wait for maintainer approval in this issue first)

View file

@ -11,7 +11,7 @@ body:
Before you submit a feature:
1. Search existing issues for similar features. If you find one, 👍 it rather than opening a new one.
2. The Kimi Code team will try to balance the varying needs of the community when prioritizing or rejecting new features. Please understand that not all features will be accepted.
3. Do not open a feature PR until maintainers have had a chance to respond here. PRs without prior discussion may be closed without review.
3. Do not open a feature PR. External feature PRs are not accepted — features are discussed and decided in this issue; if accepted, the team will implement it or explicitly invite you to contribute.
- type: textarea
id: feature

View file

@ -0,0 +1,73 @@
name: Bug 报告
description: 报告需要修复的问题
labels:
- bug
- needs triage
body:
- type: markdown
attributes:
value: |
感谢你提交 bug 报告!这能帮助 Kimi Code 变得更好。
请确认你正在运行最新版本的 Kimi Code CLI——你遇到的问题可能已经被修复。
请尽量提供完整的信息。
如果你打算提交修复:勾选下方 Contribution 选项,并等待维护者在本 issue 中以 `/approve` 评论批准后再提 PR。
- type: input
id: version
attributes:
label: 你运行的 Kimi Code 版本是?
description: 复制 `kimi --version` 或 `/version` 的输出
validations:
required: true
- type: input
id: plan
attributes:
label: 你使用的是哪个开放平台/订阅?
description: 运行 `/login` 时选择的那个
validations:
required: true
- type: input
id: model
attributes:
label: 你使用的是哪个模型?
description: 底部状态栏可见,如 `kimi-k2.6`、`kimi-for-coding` 等
- type: input
id: platform
attributes:
label: 你的电脑平台是?
description: |
macOS 和 Linux复制 `uname -mprs` 的输出
Windows在 PowerShell 中运行 `"$([Environment]::OSVersion | ForEach-Object VersionString) $(if ([Environment]::Is64BitOperatingSystem) { "x64" } else { "x86" })"` 并复制输出
- type: textarea
id: actual
attributes:
label: 你遇到了什么问题?
description: 请包含完整的错误信息和提示词(隐去隐私信息)。如可能,请提供文本而非截图。
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤?
description: 说明 bug 并给出可复现的代码片段。如适用,请提供 session id 和上下文用量。
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望的行为是什么?
description: 如可能,请提供文本而非截图。
- type: textarea
id: notes
attributes:
label: 补充信息
description: 还有什么想让我们知道的?
- type: checkboxes
id: willing-to-pr
attributes:
label: Contribution
options:
- label: 我愿意自己提交修复此 bug 的 PR请先等待维护者在本 issue 中批准)

View file

@ -0,0 +1,26 @@
name: 功能建议
description: 为 Kimi Code 提议新功能
labels:
- enhancement
body:
- type: markdown
attributes:
value: |
Kimi Code 缺少你想要的某个功能?欢迎在这里提议。
提交功能建议前:
1. 先搜索已有 issue如有类似功能点 👍 而不是新开 issue。
2. Kimi Code 团队会在排序或拒绝新功能时尽量平衡社区的不同需求,请理解并非所有功能都会被接受。
3. 不要提交 feature PR。不接受外部功能 PR——功能在本 issue 中讨论和决定;如被接受,由团队实现或明确邀请你来贡献。
- type: textarea
id: feature
attributes:
label: 你希望看到什么功能?
validations:
required: true
- type: textarea
id: notes
attributes:
label: 补充信息
description: 还有什么想让我们知道的?

View file

@ -1,13 +1,14 @@
<!--
Thank you for your contribution to Kimi Code!
Please open an issue before sending a feature PR — PRs without prior discussion may be closed without review.
External PRs are accepted for approved bug fixes only: link an issue that a maintainer has approved (an `/approve` comment). External feature PRs are not accepted.
外部 PR 仅接受获批准的 bug 修复:请链接维护者已批准(`/approve` 评论)的 issue不接受外部 feature PR。
See https://github.com/MoonshotAI/kimi-code/blob/main/CONTRIBUTING.md for more.
-->
## Related Issue
<!-- Link the issue this feature came from. If there is no issue, explain the problem in the next section instead. -->
<!-- Link the issue this change came from. External PRs must link an issue approved by a maintainer (an `/approve` comment) — PRs without one may be closed. -->
Resolve #(issue_number)
@ -22,7 +23,7 @@ Resolve #(issue_number)
## Checklist
- [ ] I have read the [CONTRIBUTING](https://github.com/MoonshotAI/kimi-code/blob/main/CONTRIBUTING.md) document.
- [ ] I have linked a related issue, or explained the problem above.
- [ ] I have linked a related issue (external PRs: the issue must have a maintainer's `/approve`).
- [ ] I have added tests that prove my feature works.
- [ ] Ran `gen-changesets` skill, or this PR needs no changeset.
- [ ] Ran `gen-docs` skill, or this PR needs no doc update.

View file

@ -86,11 +86,9 @@ jobs:
echo "KIMI_CODE_BUILT_IN_CATALOG_FILE=$CATALOG_FILE" >> "$GITHUB_ENV"
- name: Build Kimi web assets
# The SEA blob step embeds apps/kimi-code/dist-web; build the web app
# and stage its assets before producing the native executable.
run: |
pnpm --filter @moonshot-ai/kimi-web run build
node apps/kimi-code/scripts/copy-web-assets.mjs
# The SEA blob step embeds apps/kimi-code/dist-web. The bundle is
# committed (synced from the code-app repo) — just verify it is in place.
run: node apps/kimi-code/scripts/check-web-assets.mjs
- name: Build native executable (release profile, macOS signed)
if: runner.os == 'macOS' && inputs.sign-macos

View file

@ -66,6 +66,27 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @moonshot-ai/pi-tui test
# The VS Code extension suite runs on the default (v2) engine as part of the
# sharded root run above; this job reruns it on the legacy v1 engine, which
# the extension selects through the rollback env var.
test-vscode-legacy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm --filter kimi-code test
env:
KIMI_CODE_LEGACY_FLAG: "1"
test-windows:
runs-on: windows-latest
# Temporarily disabled while Windows tests are being stabilized.
@ -127,8 +148,6 @@ jobs:
done
- name: Typecheck VS Code extension
run: pnpm --filter kimi-code run typecheck
- name: Typecheck kimi-web (vue-tsc)
run: pnpm --filter @moonshot-ai/kimi-web run typecheck
- name: Typecheck vis-server
run: pnpm --filter @moonshot-ai/vis-server run typecheck
- name: Typecheck vis-web

View file

@ -36,9 +36,6 @@ jobs:
- name: Build package dependencies
run: pnpm run build:packages
- name: Build Kimi web assets
run: pnpm --filter @moonshot-ai/kimi-web run build
- name: Generate Kimi Code built-in catalog
shell: bash
run: |

1
.gitignore vendored
View file

@ -1,6 +1,5 @@
node_modules/
dist/
dist-web/
dist-single/
dist-native/
.tmp-api-extractor/

View file

@ -90,6 +90,30 @@
"eslint/no-console": "off"
}
},
{
// The worker closures: these modules (and everything
// packages/minidb/src/worker/ and
// packages/kap-server/src/search/worker/ pull in) are loaded by a bare
// node:worker_threads Worker under Node's native type stripping with
// `execArgv: ['--experimental-transform-types']`, which requires
// explicit `.ts` import specifiers (the strip loader does not remap
// `.js` -> `.ts`). Keep the exception scoped to exactly those closures.
"files": [
"packages/minidb/src/worker/**/*.ts",
"packages/minidb/src/codec.ts",
"packages/minidb/src/crc32.ts",
"packages/minidb/src/trigram.ts",
"packages/minidb/src/text-postings.ts",
"packages/minidb/src/text-index/tokenize.ts",
"packages/minidb/src/gen-codec.ts",
"packages/kap-server/src/search/worker/**/*.ts",
"packages/kap-server/src/search/indexCore.ts",
"packages/kap-server/src/search/match.ts"
],
"rules": {
"import/extensions": "off"
}
},
{
"files": ["packages/kosong/src/providers/**/*.ts"],
"rules": {
@ -146,6 +170,7 @@
],
"ignorePatterns": [
"dist/",
"dist-web/",
"coverage/",
"node_modules/",
"apps/*/scripts/",

File diff suppressed because one or more lines are too long

View file

@ -1,5 +1,7 @@
# Contributing to kimi-code
[中文版](CONTRIBUTING.zh-CN.md)
Thanks for taking the time to contribute! This project moves quickly, and thoughtful contributions from the community are what keep it sharp. The guide below walks you through how we work so your PR has the best chance of landing smoothly.
## Before You Start
@ -10,27 +12,25 @@ We hold AI-assisted contributions to the same standard as hand-written ones. **Y
We only merge PRs aligned with the roadmap. Drive-by refactors without context are unlikely to land.
**Discuss first** — open an issue before coding. PRs without prior discussion may be closed without review:
**External PRs are accepted for approved bug fixes only.** Open an issue first and wait for a maintainer to approve it with an `/approve` comment, then link that issue in your PR. PRs without an approved linked issue may be closed without review; once the issue is approved, ask a maintainer to reopen your PR.
- New features or user-visible behavior changes (regardless of size)
**Discuss first** — open an issue before coding:
- Bug fixes, including small or typo-level ones: open a bug issue and wait for a maintainer's `/approve` before opening the PR
- New features or user-visible behavior changes (regardless of size): external feature PRs are not accepted — features are discussed and decided in issues, and accepted features are implemented by the team or by explicit maintainer invitation
- Refactors or other changes larger than ~100 lines
- Public API or compatibility changes
- Bug fixes where the cause or fix approach is still unclear
**Can open a PR directly** — link an existing issue when there is one:
- Clear, reproducible bug fixes with a focused diff
- Typos, documentation-only changes, and small CI/build fixes
- Small changes that clearly match an existing issue or maintainer request
## Project Layout
This is a pnpm monorepo. The most relevant entry points are:
- `apps/kimi-code` — CLI / TUI
- `apps/vis` — session replay & debugging visualizer
- `apps/vscode` — VS Code extension
- `apps/vis` — session debug visualizer
- `packages/node-sdk` — public TypeScript SDK (`@moonshot-ai/kimi-code-sdk`)
- `packages/agent-core`, `kosong`, `kaos`, `oauth`, `telemetry` — internal engine packages
- `packages/agent-core-v2` — the agent engine (v2, DI Scope architecture); `packages/agent-core` is v1 and being phased out
- `packages/klient`, `kap-server`, `protocol`, `transcript`, `kosong`, `kaos`, `oauth`, `telemetry` — internal engine packages
- `docs/` — VitePress bilingual docs site
For the full project map, see [AGENTS.md](AGENTS.md).
@ -84,9 +84,7 @@ This repo uses [changesets](https://github.com/changesets/changesets) to manage
## Pull Requests
Use the [PR template](.github/pull_request_template.md) when opening a feature pull request.
PR titles must follow [Conventional Commits](#commit-convention); CI runs `pnpm lint`, `pnpm typecheck`, and `pnpm test` on every PR. Update user-facing docs in `docs/` when behavior changes — use the `gen-docs` skill when working with coding agents.
Every PR opens with the [PR template](.github/pull_request_template.md). PR titles must follow [Conventional Commits](#commit-convention); CI runs `pnpm lint`, `pnpm typecheck`, and `pnpm test` on every PR. Update user-facing docs in `docs/` when behavior changes — use the `gen-docs` skill when working with coding agents.
## Code Style

102
CONTRIBUTING.zh-CN.md Normal file
View file

@ -0,0 +1,102 @@
# 为 kimi-code 贡献代码
[English version](CONTRIBUTING.md)
感谢你花时间参与贡献!这个项目迭代很快,离不开社区认真的贡献。下面的指南介绍我们的工作方式,帮助你的 PR 顺利合入。
## 开始之前
Kimi Code 对 CLI/TUI 行为、agent 工作流和公开 API 已有自己的主张。如果你的改动会改变这些方向,请先开 issue 对齐,再投入时间写 PR。
我们对 AI 辅助贡献与手写代码一视同仁。**你应该理解自己提交的内容**——改了什么、边界情况下表现如何、为什么适合这个代码库。如果你解释不清楚,这个 PR 就还没准备好接受评审。
我们只合入与路线图一致的 PR。缺乏上下文背景的顺手重构很难被接受。
**外部 PR 仅接受获批准的 bug 修复。** 先开 issue等待维护者以 `/approve` 评论明确批准,然后在 PR 中链接该 issue。没有已批准关联 issue 的 PR 可能会不经评审直接关闭issue 获批后,可联系维护者重开你的 PR。
**先讨论**——写代码前先开 issue
- bug 修复(包括小的、错别字级别的):先开 bug issue等待维护者 `/approve` 后再提 PR
- 新功能或用户可见的行为变更(无论大小):不接受外部 feature PR——功能在 issue 中讨论和决定,被接受的功能由团队实现,或由维护者明确邀请你贡献
- 重构或其他超过约 100 行的改动
- 公开 API 或兼容性变更
## 项目结构
本仓库是 pnpm monorepo最常用的入口
- `apps/kimi-code` — CLI / TUI
- `apps/vscode` — VS Code 插件
- `apps/vis` — 会话调试可视化工具
- `packages/node-sdk` — 公开 TypeScript SDK`@moonshot-ai/kimi-code-sdk`
- `packages/agent-core-v2` — 当前的 agent 引擎v2DI Scope 架构);`packages/agent-core` 为 v1正在逐步废弃
- `packages/klient``kap-server``protocol``transcript``kosong``kaos``oauth``telemetry` — 内部引擎包
- `docs/` — VitePress 双语文档站
完整项目地图见 [AGENTS.md](AGENTS.md)。
## 开发环境
前置要求Node.js >= 24.15.0、pnpm 10.33.0、Git。
```sh
git clone https://github.com/MoonshotAI/kimi-code.git
cd kimi-code
pnpm install
```
常用脚本:
- `pnpm dev:cli` — 开发模式运行 CLI
- `pnpm test` — 运行测试vitest
- `pnpm typecheck` — TypeScript 检查(注意:会先构建各包)
- `pnpm lint` — oxlint
- `pnpm lint:fix` — oxlint 自动修复
- `pnpm build` — 构建全部包
## 提交规范
所有 commit 和 PR 标题必须遵循 [Conventional Commits](https://www.conventionalcommits.org/)。
| 类型 | 用途 | 示例 |
|----------|------------------------------------------|----------------------------------------|
| feat | 新功能 | feat(agent-core): add tool dedup |
| fix | bug 修复 | fix(tui): correct status bar alignment |
| docs | 仅文档 | docs: clarify install instructions |
| chore | 工具 / 杂务 | chore: bump dependencies |
| refactor | 无行为变更的内部重构 | refactor(kosong): extract retry helper |
| test | 新增或改进测试 | test(agent-core): cover skill resolver |
| ci | CI / 构建流水线变更 | ci: cache pnpm store |
| build | 构建系统 / 产物变更 | build(native): add win32-arm64 target |
| perf | 性能优化 | perf(session): batch event flushes |
| style | 仅格式化(无逻辑变更) | style: apply oxlint --fix |
PR 标题由 `pr-title-checker` 工作流强制校验——不合规的标题会阻止合并。
## Changesets
本仓库使用 [changesets](https://github.com/changesets/changesets) 管理版本与发布。
- 每个影响发布产物(代码、行为、公开 API的 PR **必须**包含 changeset。
- 仅文档、仅测试或仅 CI 的 PR 可以不加。
- 用 `pnpm changeset` 生成并按提示操作(涉及哪些包、什么 bump 级别)。
- 包选择与 bump 级别的仓库约定见 `.changeset/README.md`。在本仓库使用编程 agent 时,使用 `gen-changesets` 技能。
## Pull Requests
PR 会自动套用 [PR 模板](.github/pull_request_template.md)。PR 标题必须遵循 [Conventional Commits](#提交规范);每个 PR 的 CI 会运行 `pnpm lint``pnpm typecheck``pnpm test`。行为变更时请同步更新 `docs/` 下的用户文档——使用编程 agent 时使用 `gen-docs` 技能。
## 代码风格
- 全仓库 TypeScript。
- 使用 `oxlint`(配置见 `.oxlintrc.json`)。
- 用 `pnpm lint:fix` 自动格式化。
- lint 规则未覆盖的风格选择,跟随周边现有写法。
## 报告安全问题
发现安全问题?请查看 [SECURITY.md](SECURITY.md),不要开公开 issue。
## 许可证
向本仓库贡献即表示你同意你的贡献按 [MIT 许可证](LICENSE) 授权。

View file

@ -229,3 +229,4 @@ goal ID 不应暴露给模型,因为它只是 runtime/UI 内部标识,没有
goal 创建、暂停、恢复、阻塞、完成、清除都应发出 goal updated 事件。lifecycle 变化和 completion 变化应区分。completion 是一次终局事件,然后 snapshot 变 null。blocked/paused 保留 snapshotUI 可以继续展示可恢复 goal。
session 恢复时active goal 会变 paused避免重启后自动继续。fork session 时不继承 goal并提醒模型不要继续源 session 的目标。

View file

@ -8,4 +8,4 @@ agents/
src/generated/vis-web-asset.ts
# Copied from packages/pi-tui/native at build time by scripts/copy-native-assets.mjs
native/
/native/

View file

@ -65,6 +65,7 @@ The theme apply/switch mechanics live in the `write-tui` skill. The following ru
## General Coding Requirements
- The startup path before the workspace trust gate (`KimiTUI.start()` -> `maybeRunWorkspaceTrustPrompt()`) must not spawn child processes by bare command name — on Windows, cmd.exe / CreateProcess resolve them from the current directory first, so a binary planted in an untrusted workspace would run before the user confirms trust. When an external command is unavoidable, resolve it with `resolveCommandPath` from `src/utils/process/resolve-command.ts`, which returns an absolute PATH hit and refuses matches inside the cwd.
- For optional object properties, pass `undefined` directly — do not use conditional spread.
- Optional object properties do not need to additionally allow `undefined` in the type.
- Internal methods with only a single parameter should not be turned into options objects just for stylistic uniformity.

View file

@ -1,5 +1,425 @@
# @moonshot-ai/kimi-code
## 0.38.0
### Minor Changes
- [#2862](https://github.com/MoonshotAI/kimi-code/pull/2862) [`3d77620`](https://github.com/MoonshotAI/kimi-code/commit/3d7762003a4a35cbeb8571d471c6898a006152e6) Thanks [@liruifengv](https://github.com/liruifengv)! - Support two OAuth login methods — kimi.ai and kimi.com.
- [#3060](https://github.com/MoonshotAI/kimi-code/pull/3060) [`8440801`](https://github.com/MoonshotAI/kimi-code/commit/8440801de47ddae29224430048e1228b80cde370) Thanks [@chengluyu](https://github.com/chengluyu)! - Add the WaitFor tool: the agent can now wait for a background task to finish within the current turn instead of ending the turn and being re-invoked.
### Patch Changes
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Label inline subagent cards in the message stream with their foreground or background mode.
- [#3121](https://github.com/MoonshotAI/kimi-code/pull/3121) [`3899079`](https://github.com/MoonshotAI/kimi-code/commit/3899079a2c851bd0b3f1cbf1d3d2fd9026fc6abb) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix config.toml entries being lost when the file had a syntax error or was edited outside the app.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Add copy buttons next to the server version and server address in settings.
- [#3119](https://github.com/MoonshotAI/kimi-code/pull/3119) [`a34d02a`](https://github.com/MoonshotAI/kimi-code/commit/a34d02a64f9b1526ec84e161d8c377654b413624) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Add 13 data sources to the official Kimi Datasource plugin — Chinese government data (NDA/NBS) and standards (GB/HB/DB/TT), eight international organization datasets (WHO, FAO, UNSD, ECB, Eurostat, UNICEF, OECD, FRED), Xinhua Finance, and Caixin. Update the plugin from the Official tab in /plugins.
- [#3096](https://github.com/MoonshotAI/kimi-code/pull/3096) [`67fbcdf`](https://github.com/MoonshotAI/kimi-code/commit/67fbcdf1ba7dceeebb58875b3b7c81b4b30cf0de) Thanks [@sailist](https://github.com/sailist)! - Edit and Write now require reading an existing file before modifying it, and reject the write when the file changed on disk since it was last read.
- [#3101](https://github.com/MoonshotAI/kimi-code/pull/3101) [`d96b4a0`](https://github.com/MoonshotAI/kimi-code/commit/d96b4a0149f3ddf3d4910cc6eb87366dbb130ede) Thanks [@kimi-agent-bot](https://github.com/kimi-agent-bot)! - Stop retrying requests blocked by the provider content filter; the filter notice now shows immediately.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Keep empty workspace groups visible in the legacy sidebar after their last session is archived.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Hide button hover tooltips outside a menu while the menu is open.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Keep the model picker menu on the workspace home within the viewport.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix the workspace group title showing untranslated text in the search dialog.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix the settings dialog dropdown list being clipped by the scroll area, and lock the content behind it while the list is open.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Keep the slash command and @ mention panels on the workspace home within the viewport.
- [#3052](https://github.com/MoonshotAI/kimi-code/pull/3052) [`6595a69`](https://github.com/MoonshotAI/kimi-code/commit/6595a6989a68163e10a85c8edf1726b30d6d2c2b) Thanks [@RealKai42](https://github.com/RealKai42)! - Fix 422 errors from some OpenAI-compatible providers when a conversation includes tool calls.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Prevent text selection in the sidebar user menu and its plan usage submenu.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix slow session list loading when there are many workspaces.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Auto-open the browser authorization page after choosing a login region, redesign the authorization waiting page, and refresh the login state as soon as the window regains focus instead of waiting for the poll.
- [#3083](https://github.com/MoonshotAI/kimi-code/pull/3083) [`571bcc2`](https://github.com/MoonshotAI/kimi-code/commit/571bcc2f751f02a37b0475b074a1e859c7fc4368) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix the missing OAuth authenticate tool for remote MCP servers that require login.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Upgrade the @ mention menu: file and skill candidates are merged and ranked by match quality, file search is faster, with path-fragment matching and hit highlighting.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Round menu items concentric with their menu frames.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Add a Pin action to the chat header more-menu to pin the current session to the sidebar pinned section.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Allow dragging the divider between the pinned section and the session list to resize both areas, with fade hints at the edges when the pinned section scrolls.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Improve the prompt queue interaction, with per-row steer and send.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Add kimi.com and kimi.ai OAuth login entries, and switch update and help links to the site matching the current login.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Remove sessions archived from another client from the session list immediately, without a manual refresh.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Label the timestamp at the bottom of the session menu as last active and tighten that row's padding.
- [#3054](https://github.com/MoonshotAI/kimi-code/pull/3054) [`cfc3350`](https://github.com/MoonshotAI/kimi-code/commit/cfc335048378d3708666e11959c8d34507a1d659) Thanks [@Grapedge](https://github.com/Grapedge)! - Collapse long `!` shell command output instead of flooding the transcript. Press ctrl+o to expand or collapse it together with tool output.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix misaligned action buttons between the sidebar section headers and the session rows.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Remove the skill-activated card from skill activation messages.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Make skill-activation turns undoable so they can be withdrawn and resent.
- [#3012](https://github.com/MoonshotAI/kimi-code/pull/3012) [`ca87c58`](https://github.com/MoonshotAI/kimi-code/commit/ca87c58e6205ddf0638e5d737a5f8e939e2132b9) Thanks [@sailist](https://github.com/sailist)! - Sub-agents no longer spawn their own sub-agents by default; custom agent profiles can still allow it explicitly.
- [#3005](https://github.com/MoonshotAI/kimi-code/pull/3005) [`be8e017`](https://github.com/MoonshotAI/kimi-code/commit/be8e017597b83142282d7e6640076368bf244eae) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Fix background agent rows that could not be stopped right after they appeared, and stray rows left behind when an agent failed to start.
- [#3046](https://github.com/MoonshotAI/kimi-code/pull/3046) [`f13f379`](https://github.com/MoonshotAI/kimi-code/commit/f13f3790448f64448c76a415500041443ae754e6) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix the model being directed to unavailable tools when it encounters an image or binary file.
- [#3108](https://github.com/MoonshotAI/kimi-code/pull/3108) [`05f2ad5`](https://github.com/MoonshotAI/kimi-code/commit/05f2ad5ddad1addf10ead6f5274554ca10cde1f4) Thanks [@kimi-agent-bot](https://github.com/kimi-agent-bot)! - web: clearing a goal now removes it from the transcript view instead of leaving the stale goal displayed.
- [#3108](https://github.com/MoonshotAI/kimi-code/pull/3108) [`05f2ad5`](https://github.com/MoonshotAI/kimi-code/commit/05f2ad5ddad1addf10ead6f5274554ca10cde1f4) Thanks [@kimi-agent-bot](https://github.com/kimi-agent-bot)! - web: attachments sent with a prompt now appear in the live transcript immediately instead of only after a reload.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Tighten the row height and spacing of the account menu and its submenus to match the standard menu density.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Give WaitFor tool calls a dedicated quiet-line display showing completed tasks, wait timeouts, and how many tasks are still running.
## 0.37.2
### Patch Changes
- [#3061](https://github.com/MoonshotAI/kimi-code/pull/3061) [`5c661f4`](https://github.com/MoonshotAI/kimi-code/commit/5c661f4610f36481dbf2f9598aa63f49004e4980) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: the subagent detail panel now keeps the working process fully expanded and drops the end-of-turn timestamp footer.
- [#3061](https://github.com/MoonshotAI/kimi-code/pull/3061) [`5c661f4`](https://github.com/MoonshotAI/kimi-code/commit/5c661f4610f36481dbf2f9598aa63f49004e4980) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Settings gains a Lab tab with a multi-tab sidebar toggle (off by default); when enabled, the sidebar shows the Open / Done / Workspaces tabs.
## 0.37.1
### Patch Changes
- [#3053](https://github.com/MoonshotAI/kimi-code/pull/3053) [`95cede8`](https://github.com/MoonshotAI/kimi-code/commit/95cede82b4d3b6cb1845c66e87896ab2e5fd9ba5) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix pasted images failing to reach the model on first send.
- [#3047](https://github.com/MoonshotAI/kimi-code/pull/3047) [`c9c34ae`](https://github.com/MoonshotAI/kimi-code/commit/c9c34ae5a8626f133bd1b9c34cac0f3270e35b8d) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix pasted videos failing to submit instead of reaching the model.
## 0.37.0
### Minor Changes
- [#2935](https://github.com/MoonshotAI/kimi-code/pull/2935) [`44a6c70`](https://github.com/MoonshotAI/kimi-code/commit/44a6c70e66762ea9e122f8dceae16dc759086a7c) Thanks [@chengluyu](https://github.com/chengluyu)! - Activate multiple skills in a single prompt. Type `/` after whitespace to insert a skill token.
- [#2994](https://github.com/MoonshotAI/kimi-code/pull/2994) [`8c865f4`](https://github.com/MoonshotAI/kimi-code/commit/8c865f48173011439cfc2e140e45586e59b6bfcf) Thanks [@liruifengv](https://github.com/liruifengv)! - The Windows native (single-binary) CLI now supports automatic updates.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: the sidebar gains Open / Done / Workspaces tabs, and sessions can be marked as done (and reopened) to keep the open list focused.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: added a session management page (from the sidebar's list-management menu) for cross-workspace triage — filter by workspace, status, and updated time, and batch mark sessions as done or reopen them.
### Patch Changes
- [#2593](https://github.com/MoonshotAI/kimi-code/pull/2593) [`d833a1a`](https://github.com/MoonshotAI/kimi-code/commit/d833a1a893c4d69d96af542f40557442992085e0) Thanks [@7Sageer](https://github.com/7Sageer)! - Keep pasted image and video attachments available in session history.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: @-mentioned files, folders, and skills in chat messages now render as icon pills.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: renamed the Subagent panel to "Background Agent".
- [#2914](https://github.com/MoonshotAI/kimi-code/pull/2914) [`1cf617d`](https://github.com/MoonshotAI/kimi-code/commit/1cf617d769a887f5d8306ebc16a1e078b5e47049) Thanks [@SeleneXX](https://github.com/SeleneXX)! - Fix Gemini tool-calling sessions failing on follow-up requests.
- [#2972](https://github.com/MoonshotAI/kimi-code/pull/2972) [`04d23e2`](https://github.com/MoonshotAI/kimi-code/commit/04d23e2dab776c480d24cfa033c9500543c75a3b) Thanks [@sailist](https://github.com/sailist)! - Fix text files containing Chinese or emoji being misdetected as binary in the web UI.
- [#2940](https://github.com/MoonshotAI/kimi-code/pull/2940) [`6b72345`](https://github.com/MoonshotAI/kimi-code/commit/6b72345f8bb03487e3bcc05b541e65484818428c) Thanks [@bj456736](https://github.com/bj456736)! - Print and copy the full `kimi --resume` command after `/fork`.
- [#2928](https://github.com/MoonshotAI/kimi-code/pull/2928) [`d96cd03`](https://github.com/MoonshotAI/kimi-code/commit/d96cd037702637305422222e985139e51ff83c8c) Thanks [@chengluyu](https://github.com/chengluyu)! - Warn when a typed `/goal` objective exceeds the 4000-character limit, and keep the input if it is rejected.
- [#2633](https://github.com/MoonshotAI/kimi-code/pull/2633) [`f492cd7`](https://github.com/MoonshotAI/kimi-code/commit/f492cd7c9e03666ecfd10dc47ca9b48c35de2318) Thanks [@tpoisonooo](https://github.com/tpoisonooo)! - Fix slow startup by loading the global search index on demand.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed YAML frontmatter in messages rendering as a giant heading — it now shows as a small meta block.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed plain text like "(c)", "(tm)", and "--" in messages being rewritten as ©, ™, and dashes — message text now renders verbatim.
- [#2985](https://github.com/MoonshotAI/kimi-code/pull/2985) [`a7dc1ea`](https://github.com/MoonshotAI/kimi-code/commit/a7dc1ea28445555d5944066936fdf6e1b21d27ea) Thanks [@bj456736](https://github.com/bj456736)! - Fix a startup error when a restored session references a model that is no longer configured.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: hovering a mention pill now shows a detail bubble (full path for files and folders, description plus an open button for skills), skill and file mentions in messages are clickable, long file names middle-ellipsize, and deleted files are struck through.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed long task panel titles pushing the status badge, copy, and close buttons out of view — titles now ellipsize and show the full text on hover.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed pasting a copied folder into the composer failing the upload with a connection error — folders are now skipped instead.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: reduced animation power draw — the mascot and home doodle pause while hidden or scrolled offscreen, and looping animations play once and stop when the system's "reduce motion" setting is on.
- [#2969](https://github.com/MoonshotAI/kimi-code/pull/2969) [`ee564e5`](https://github.com/MoonshotAI/kimi-code/commit/ee564e5ec90afd068123b8052928c53f1fd5a27d) Thanks [@sailist](https://github.com/sailist)! - Fix the displayed context size dropping to a smaller estimate after archiving and resuming a session.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: the plan review feedback box now auto-grows with its content, so longer rejection reasons are easier to write.
- [#2633](https://github.com/MoonshotAI/kimi-code/pull/2633) [`f492cd7`](https://github.com/MoonshotAI/kimi-code/commit/f492cd7c9e03666ecfd10dc47ca9b48c35de2318) Thanks [@tpoisonooo](https://github.com/tpoisonooo)! - Queue slash skill commands entered while the agent is busy instead of rejecting them.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: the search dialog now finds workspaces too, and picking a workspace or session result expands the sidebar and scrolls the item into view.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed sent image and video attachments rendering broken in session history after a refresh or reopen.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed empty replies left by manually stopped answers still showing a completion time after reloading the page.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed background agent tasks not being cancellable during their first moments after starting.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed foreground subagents leaking into the Background Agent panel, which broke the count and left finished rows stuck as running and unstoppable.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: merged the task panel's two copy icons into a single button with a dropdown menu (copy command / copy output / copy all), with keyboard and touch-friendly targets.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed cancelled or abnormally ended background tasks showing as completed.
- [#3016](https://github.com/MoonshotAI/kimi-code/pull/3016) [`98ebda8`](https://github.com/MoonshotAI/kimi-code/commit/98ebda840a1e420f57a05ec680cbeca41a2419d7) Thanks [@sailist](https://github.com/sailist)! - Fix /undo not restoring the todo list to its state before the undone turn.
- [#2858](https://github.com/MoonshotAI/kimi-code/pull/2858) [`59dde73`](https://github.com/MoonshotAI/kimi-code/commit/59dde734f37596db5c77794060f81bfb3c1dbeb6) Thanks [@7Sageer](https://github.com/7Sageer)! - On the legacy engine, plugin MCP server changes and OAuth sign-in now take effect in open sessions immediately.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: the browser tab title now shows the current workspace directory name (override with the new `--web-title` flag), making instances on multiple machines easier to tell apart.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed Ctrl+K in the composer opening session search on macOS instead of deleting to end of line — session search now only answers to Cmd+K.
- [#2989](https://github.com/MoonshotAI/kimi-code/pull/2989) [`09976b0`](https://github.com/MoonshotAI/kimi-code/commit/09976b09140c412f81a38cc00191f88bee4a9437) Thanks [@bj456736](https://github.com/bj456736)! - Add `kimi web --web-title <title>` to set a custom browser tab title for the web UI.
## 0.36.1
### Patch Changes
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: The timestamp under assistant replies now shows the message time instead of the work duration.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the slash command and @ file mention menus: matched fragments are bold-highlighted in the slash menu, and long lists in both menus get a scroll fade and a draggable floating scrollbar.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: The background Bash panel now supports filtering by status, and clicking a task shows its command and output on the right.
- [#2865](https://github.com/MoonshotAI/kimi-code/pull/2865) [`53909d9`](https://github.com/MoonshotAI/kimi-code/commit/53909d91e3ca570d4b565ba1abd00f027ca78d6b) Thanks [@weivwang](https://github.com/weivwang)! - Cache content-hashed Kimi Web assets across reloads while keeping the app entry point revalidated.
- [#2916](https://github.com/MoonshotAI/kimi-code/pull/2916) [`7475c2e`](https://github.com/MoonshotAI/kimi-code/commit/7475c2e2e3dd86ac0b8a8d51d4f1d233ed7df797) Thanks [@Grapedge](https://github.com/Grapedge)! - Cancel an in-flight /init run together with the turn instead of letting it run to completion.
- [#2911](https://github.com/MoonshotAI/kimi-code/pull/2911) [`249d8fa`](https://github.com/MoonshotAI/kimi-code/commit/249d8faa3447427665185a900926d048213d2ac7) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix sessions hanging on the second approval prompt and tool call results being dropped or mixed up in history when using a self-hosted OpenAI-compatible endpoint that renumbers tool call ids on every response.
- [#2917](https://github.com/MoonshotAI/kimi-code/pull/2917) [`6cf315b`](https://github.com/MoonshotAI/kimi-code/commit/6cf315b7bdea8a04cfaeba1bb8931c1730853aec) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Fix bare URLs in chat output absorbing the CJK characters that follow them, which made the link unclickable or open a broken address.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix the slash command panel staying open after switching sessions or when the composer loses focus.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Replace the composer mode menu with mutually exclusive plan/goal pills on the left of the input area (arm via /plan or /goal, exit with ×); Swarm becomes a separate toolbar toggle.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the work status pills above the composer with a borderless rounded look.
- [#2910](https://github.com/MoonshotAI/kimi-code/pull/2910) [`eb72aeb`](https://github.com/MoonshotAI/kimi-code/commit/eb72aebeeb972b2fcc238d5650dd991a5580f96b) Thanks [@sailist](https://github.com/sailist)! - Remove the 64 MiB limit on web session exports, so large sessions no longer fail with a file-too-large error when downloaded from the web UI.
- [#2884](https://github.com/MoonshotAI/kimi-code/pull/2884) [`1811bd4`](https://github.com/MoonshotAI/kimi-code/commit/1811bd4baf5b75ba076e2a24825f9c4f82c13341) Thanks [@liruifengv](https://github.com/liruifengv)! - Fix startup banner text wrapping on narrow terminals.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix `$` content inside inline code spans being misrendered as inline math.
- [#2899](https://github.com/MoonshotAI/kimi-code/pull/2899) [`102984a`](https://github.com/MoonshotAI/kimi-code/commit/102984aa660d752ba8dd7d1aba155575f32affe2) Thanks [@oocz](https://github.com/oocz)! - Fix MCP OAuth cancellation leaving an in-flight authorization waiting for its callback timeout.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix the thinking-effort flyout being unreachable when selecting the last model in the subagent model list.
- [#2876](https://github.com/MoonshotAI/kimi-code/pull/2876) [`5912d4c`](https://github.com/MoonshotAI/kimi-code/commit/5912d4c7d19d68975e85b007976b1bef59edae5c) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix repeated file-watcher errors on Windows when the workspace is a drive root (such as `E:\`) or a UNC network share.
- [#2916](https://github.com/MoonshotAI/kimi-code/pull/2916) [`7475c2e`](https://github.com/MoonshotAI/kimi-code/commit/7475c2e2e3dd86ac0b8a8d51d4f1d233ed7df797) Thanks [@Grapedge](https://github.com/Grapedge)! - Show a clear error when forking a session while its turn is running, instead of copying a partially written turn.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix forking sessions with very long histories always failing with a timeout.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Selecting /goal from the slash menu now immediately arms a removable goal pill in the composer; typing and sending creates the goal without requiring the goal text after the command.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the goal panel: the goal text and elapsed time move to the header, and actions become icon buttons.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix CJK text immediately after a bare URL being swallowed into the link, which made the link unopenable.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Adjust when plan mode takes effect: enabling it now arms a removable plan pill in the composer and only activates when the message is sent, matching goal mode behavior.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Add a plan viewer panel: click a plan entry in the work bar to see the full plan, review results, and feedback.
- [#2863](https://github.com/MoonshotAI/kimi-code/pull/2863) [`245e3d5`](https://github.com/MoonshotAI/kimi-code/commit/245e3d56a6de45e74d55449ef26cd65304a3250a) Thanks [@LouisDM](https://github.com/LouisDM)! - Prevent background task output from disrupting terminal pane borders.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Show a clear top-center confirmation toast after exporting a session, and a clearer error message when the export fails because the session is too large.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix the session list PR badge not refreshing after a PR is created from within a session.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the session list PR badge as a small tag with a background.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Unify session status display in the sidebar and stabilize session list ordering.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Slash commands now support fuzzy search: find commands by description text, pinyin, or pinyin initials.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Rework the subagent panel into a card grid layout with status filtering, showing in-progress and recently finished tasks by default.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix server request timeouts being misreported as "cannot connect to the Kimi server".
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the todo panel as frosted cards and add a current-progress completion count.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Increase the font size and row height of the user menu and the plan usage flyout.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Rename the user menu's "Upgrade" entry to "Upgrade membership" and label the plan usage percentage as used.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Add experimental automatic session title generation, with on-demand regeneration from the session list.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Add a "sort by recent activity" option to the workspace-grouped sidebar view (switched in the view options menu); newly added workspaces now sort to the top.
## 0.36.0
### Minor Changes
- [#2830](https://github.com/MoonshotAI/kimi-code/pull/2830) [`ec84a6f`](https://github.com/MoonshotAI/kimi-code/commit/ec84a6f9a3eb35e1118f8a327f7a11b3978a899c) Thanks [@liruifengv](https://github.com/liruifengv)! - Add an experimental fullscreen TUI mode. Set the `KIMI_CODE_TUI_FULL_SCREEN=1` environment variable to enable it.
- [#2700](https://github.com/MoonshotAI/kimi-code/pull/2700) [`c9bfe8b`](https://github.com/MoonshotAI/kimi-code/commit/c9bfe8b2c8314ba4ef8806fb3b92ac654c1d1860) Thanks [@7Sageer](https://github.com/7Sageer)! - Add a configurable model pool for spawned subagents behind the `secondary-model` experiment (`KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=1`, or the master flag): with the experiment on, the `/secondary-model` command or the `[secondary_model]` section in config.toml sets a default model or a small named pool that the main agent picks from per spawn. A lone legacy `model` key in the same section keeps working as the fallback default.
### Patch Changes
- [#2830](https://github.com/MoonshotAI/kimi-code/pull/2830) [`ec84a6f`](https://github.com/MoonshotAI/kimi-code/commit/ec84a6f9a3eb35e1118f8a327f7a11b3978a899c) Thanks [@liruifengv](https://github.com/liruifengv)! - Render LaTeX math formulas (`$…$` / `$$…$$`) in messages as Unicode formulas.
- [#2855](https://github.com/MoonshotAI/kimi-code/pull/2855) [`30f56a2`](https://github.com/MoonshotAI/kimi-code/commit/30f56a2d2da332cbf0c36a13cbe01aac5d319c7b) Thanks [@liruifengv](https://github.com/liruifengv)! - Fix Ctrl+C being ignored during automatic retries of failed API requests.
- [#2819](https://github.com/MoonshotAI/kimi-code/pull/2819) [`fe3cdae`](https://github.com/MoonshotAI/kimi-code/commit/fe3cdae5f8ab40be71b65eff32319eb94a53c17d) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix sessions failing with a provider 400 error on every follow-up request after a turn is interrupted while the model is still thinking, on strict OpenAI-compatible providers.
- [#2847](https://github.com/MoonshotAI/kimi-code/pull/2847) [`3b0936d`](https://github.com/MoonshotAI/kimi-code/commit/3b0936d8e025c5a944759c40593d5f21bfb3e621) Thanks [@sailist](https://github.com/sailist)! - Fix plain Markdown files (such as CHANGELOG.md) in an installed plugin's root directory being misidentified as skills when the plugin relies on the root SKILL.md fallback.
- [#2843](https://github.com/MoonshotAI/kimi-code/pull/2843) [`c212ae9`](https://github.com/MoonshotAI/kimi-code/commit/c212ae9715371c0d7939c15e664acbe0d7cf7fc3) Thanks [@sailist](https://github.com/sailist)! - Show project MCP launch targets in the workspace trust prompt, default to declining trust, and resolve fd and stty binaries to absolute paths so untrusted workspaces cannot plant bare-name executables before confirmation.
`@moonshot-ai/kimi-code-sdk` contract change: `WorkspaceTrustInfo.gatedMcpServers` now carries structured `WorkspaceTrustMcpServerInfo` records (`name`, `transport`, and `command`/`args`/`cwd` or `url`) instead of plain strings, so SDK consumers rendering a trust prompt can show the full launch target.
- [#2856](https://github.com/MoonshotAI/kimi-code/pull/2856) [`504e629`](https://github.com/MoonshotAI/kimi-code/commit/504e6292ede448367d1341751f9f98b24cc2994f) Thanks [@pvzheroes125](https://github.com/pvzheroes125)! - Refresh active MCP connections after OAuth credentials are added or reset.
## 0.35.0
### Minor Changes
- [#2816](https://github.com/MoonshotAI/kimi-code/pull/2816) [`ad12ad8`](https://github.com/MoonshotAI/kimi-code/commit/ad12ad8a140d24051d93ec98a4a6921ab33723ff) Thanks [@liruifengv](https://github.com/liruifengv)! - Show the live work progress of background subagents in the `/tasks` panel.
- [#2840](https://github.com/MoonshotAI/kimi-code/pull/2840) [`68ce3c7`](https://github.com/MoonshotAI/kimi-code/commit/68ce3c7a0ccffe32b51d4fdb57cdeced3931ddcc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Image and video tool results now open in a fullscreen preview on click, with zoom support for images.
### Patch Changes
- [#2731](https://github.com/MoonshotAI/kimi-code/pull/2731) [`437a1b8`](https://github.com/MoonshotAI/kimi-code/commit/437a1b8ba1b7e0f6662bdadc669564fdc58c3f5a) Thanks [@pvzheroes125](https://github.com/pvzheroes125)! - Detect MCP servers that require OAuth without needing `auth: "oauth"` in the config.
- [#2840](https://github.com/MoonshotAI/kimi-code/pull/2840) [`68ce3c7`](https://github.com/MoonshotAI/kimi-code/commit/68ce3c7a0ccffe32b51d4fdb57cdeced3931ddcc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Reduce UI stutter while AI responses stream in long sessions.
- [#2699](https://github.com/MoonshotAI/kimi-code/pull/2699) [`c0b61c6`](https://github.com/MoonshotAI/kimi-code/commit/c0b61c6e558521fd003de786cad150a3aeb01667) Thanks [@sailist](https://github.com/sailist)! - Fix the token counts reported after compaction reading far below the real context size; they now match the numbers shown while the session runs.
- [#2810](https://github.com/MoonshotAI/kimi-code/pull/2810) [`64abebc`](https://github.com/MoonshotAI/kimi-code/commit/64abebc95a13b066fefc4f96b062824ea5ec996b) Thanks [@huangzheng2016](https://github.com/huangzheng2016)! - Fix multi-select "Other" options so they can be deselected after being committed.
- [#2701](https://github.com/MoonshotAI/kimi-code/pull/2701) [`7cd6476`](https://github.com/MoonshotAI/kimi-code/commit/7cd64766c8eeff30f3de4bd6467870555d9440db) Thanks [@sailist](https://github.com/sailist)! - Fix multi-second freezes at startup or while idle when a large search index loads, replays, or rebuilds.
- [#2814](https://github.com/MoonshotAI/kimi-code/pull/2814) [`158c81d`](https://github.com/MoonshotAI/kimi-code/commit/158c81d7055587d582ca424f9b913426fca42559) Thanks [@huangzheng2016](https://github.com/huangzheng2016)! - Show a clear error message on Windows when Git for Windows is not installed, instead of exiting silently.
- [#2838](https://github.com/MoonshotAI/kimi-code/pull/2838) [`e5be391`](https://github.com/MoonshotAI/kimi-code/commit/e5be39164b1b47d0b721aad49c41fdf4ec61a7c5) Thanks [@sailist](https://github.com/sailist)! - Close a Windows binary-planting gap in the footer git status: the git and gh commands used for the branch/dirty badge are now resolved to an absolute PATH location, so an executable planted in an untrusted workspace can no longer run before the workspace trust prompt.
- [#2840](https://github.com/MoonshotAI/kimi-code/pull/2840) [`68ce3c7`](https://github.com/MoonshotAI/kimi-code/commit/68ce3c7a0ccffe32b51d4fdb57cdeced3931ddcc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Add hover tooltips to icon-only buttons.
- [#2840](https://github.com/MoonshotAI/kimi-code/pull/2840) [`68ce3c7`](https://github.com/MoonshotAI/kimi-code/commit/68ce3c7a0ccffe32b51d4fdb57cdeced3931ddcc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Add breathing room around the fullscreen image preview so images no longer touch the screen edges.
- [#2740](https://github.com/MoonshotAI/kimi-code/pull/2740) [`01c74e9`](https://github.com/MoonshotAI/kimi-code/commit/01c74e9372fcbbbe99614e859b53b505ed1664a8) Thanks [@oocz](https://github.com/oocz)! - Fix subagent tool changes in one session leaking into builtin profiles in later sessions.
- [#2840](https://github.com/MoonshotAI/kimi-code/pull/2840) [`68ce3c7`](https://github.com/MoonshotAI/kimi-code/commit/68ce3c7a0ccffe32b51d4fdb57cdeced3931ddcc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Unify the fullscreen image and video previews with a shared circular close button and the same background overlay.
- [#2826](https://github.com/MoonshotAI/kimi-code/pull/2826) [`3c9e3b2`](https://github.com/MoonshotAI/kimi-code/commit/3c9e3b297cf5286c761159c1b4d642c478fd394d) Thanks [@liruifengv](https://github.com/liruifengv)! - Page the /sessions picker list so it opens fast with large session counts.
- [#2840](https://github.com/MoonshotAI/kimi-code/pull/2840) [`68ce3c7`](https://github.com/MoonshotAI/kimi-code/commit/68ce3c7a0ccffe32b51d4fdb57cdeced3931ddcc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Widen the sidebar's minimum draggable width.
- [#2723](https://github.com/MoonshotAI/kimi-code/pull/2723) [`e702817`](https://github.com/MoonshotAI/kimi-code/commit/e7028171244789aff58f93da80d477ce3afc939a) Thanks [@sailist](https://github.com/sailist)! - Fix a spurious "Failed to steer" error when sending a message while a goal run is between turns.
- [#2840](https://github.com/MoonshotAI/kimi-code/pull/2840) [`68ce3c7`](https://github.com/MoonshotAI/kimi-code/commit/68ce3c7a0ccffe32b51d4fdb57cdeced3931ddcc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Reduce memory and CPU usage when the app stays open for a long time.
- [#2825](https://github.com/MoonshotAI/kimi-code/pull/2825) [`df8ce73`](https://github.com/MoonshotAI/kimi-code/commit/df8ce73e45e3c473cb58e69311c1213e327f0c01) Thanks [@liruifengv](https://github.com/liruifengv)! - Show retry progress in the loading indicator when a model request fails and is retried, with the attempt count and a detail line for the provider error.
- [#2840](https://github.com/MoonshotAI/kimi-code/pull/2840) [`68ce3c7`](https://github.com/MoonshotAI/kimi-code/commit/68ce3c7a0ccffe32b51d4fdb57cdeced3931ddcc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Reduce memory usage and stutter during long sessions.
- [#2837](https://github.com/MoonshotAI/kimi-code/pull/2837) [`101c4d1`](https://github.com/MoonshotAI/kimi-code/commit/101c4d199746bf2ed4f26375b65a6fcb6cba2a60) Thanks [@sailist](https://github.com/sailist)! - Remove the Agent and AgentSwarm tools from the built-in coder subagent profile, so coder subagents no longer delegate further by default. Custom profiles that list these tools explicitly can still opt in.
- [#2695](https://github.com/MoonshotAI/kimi-code/pull/2695) [`71ff2a0`](https://github.com/MoonshotAI/kimi-code/commit/71ff2a0fffb2ebf399194436ef2d4b599c9988ad) Thanks [@sailist](https://github.com/sailist)! - Fix a Windows security risk where commands launched before the workspace trust prompt could run a malicious executable placed in the current folder.
- [#2813](https://github.com/MoonshotAI/kimi-code/pull/2813) [`619564d`](https://github.com/MoonshotAI/kimi-code/commit/619564dcf9ee10a3cfbf7ecbc764c6b9b63fc91b) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Fix the web UI repeatedly losing its realtime connection every ~30 seconds when the server runs behind a reverse proxy or gateway with an idle connection timeout; the server now sends a WebSocket heartbeat and only closes connections that stop responding entirely.
- [#2842](https://github.com/MoonshotAI/kimi-code/pull/2842) [`e476c5a`](https://github.com/MoonshotAI/kimi-code/commit/e476c5a8bbe68fb0b6eb0096aa1efcb893b1a8fc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Add the Modern Web Guidance plugin to the bundled plugin marketplace. Run /plugins and select Modern Web Guidance to install it.
- Thanks [@Leakless](https://github.com/Leakless) and [@winmin](https://github.com/winmin) for reporting the Windows binary-planting issues fixed in this release.
## 0.34.0
### Minor Changes
- [#2646](https://github.com/MoonshotAI/kimi-code/pull/2646) [`3c75a27`](https://github.com/MoonshotAI/kimi-code/commit/3c75a27da66e522ae670ec8ce9093ea71d091d27) Thanks [@liruifengv](https://github.com/liruifengv)! - Show a cache-expiry reminder when resuming a long-idle session or submitting after a long idle stretch.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: When a model request fails and interrupts a conversation, a persistent failure card now stays in the session with one-click resume.
- [#2652](https://github.com/MoonshotAI/kimi-code/pull/2652) [`68ba740`](https://github.com/MoonshotAI/kimi-code/commit/68ba740ebfb3e32ad9abdb8607f48d4387cf6f69) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Add Windows support for the built-in Kimi Computer Use capability and show the underlying error when capability setup fails. Install it from `/plugins` on Windows x64.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Add a flat view to the sidebar session list.
### Patch Changes
- [#2648](https://github.com/MoonshotAI/kimi-code/pull/2648) [`d1ded01`](https://github.com/MoonshotAI/kimi-code/commit/d1ded01b7c50c9847440f4645fe13f588becdc66) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Restore how the last turn ended (completed, cancelled, or failed) when a session is resumed after a server restart, so clients can still surface a previously failed turn instead of the session looking silently stopped.
- [#2666](https://github.com/MoonshotAI/kimi-code/pull/2666) [`335588e`](https://github.com/MoonshotAI/kimi-code/commit/335588e2594a61a767ce258b34b4049a32b18fe5) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Session listings keep how the last turn ended (completed, cancelled, or failed) across server restarts, so clients can mark previously failed sessions before they are opened.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix the model picker overflowing the screen when many models are available, leaving the bottom options unreachable.
- [#2639](https://github.com/MoonshotAI/kimi-code/pull/2639) [`8588121`](https://github.com/MoonshotAI/kimi-code/commit/858812193a267fcb9382e351137f892646ef79aa) Thanks [@7Sageer](https://github.com/7Sageer)! - /feedback now works for any signed-in user regardless of the active model; signed-out users are shown the sign-up page and GitHub Issues links instead.
- [#2675](https://github.com/MoonshotAI/kimi-code/pull/2675) [`34c4181`](https://github.com/MoonshotAI/kimi-code/commit/34c418143759a9e80cdda97e95e609c5a993916d) Thanks [@sailist](https://github.com/sailist)! - Fix kimi -p exiting right after the main turn instead of waiting for background tasks and subagents to finish.
- [#2694](https://github.com/MoonshotAI/kimi-code/pull/2694) [`02c026d`](https://github.com/MoonshotAI/kimi-code/commit/02c026d4871a14cd5e7b4b0e0ec71ba815f643df) Thanks [@sailist](https://github.com/sailist)! - Keep live sessions stable when an MCP server is removed from the workspace config or uninstalled with its plugin: its tools stay registered in open sessions but calls fail with a removal notice, and the MCP panel shows the removed status. Servers added mid-session — by a plugin install or a config edit — are not registered in open sessions; they take effect in new sessions or after `/new` or `/reload`.
- [#2647](https://github.com/MoonshotAI/kimi-code/pull/2647) [`7bd3fd9`](https://github.com/MoonshotAI/kimi-code/commit/7bd3fd9f6e6c10f88d33b85760631ad6212b5f58) Thanks [@sailist](https://github.com/sailist)! - Read UTF-16 LE/BE text files (with or without a BOM) by transcoding them to UTF-8 instead of refusing them as binary; the web UI file viewer displays them as text as well.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: The sidebar error marker now only appears when the last turn failed; manually cancelled sessions are no longer flagged.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix attachments being silently dropped when sent together with a skill command.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix a manually chosen thinking level being reset to the model default when the first message of a new session is a skill command.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix session renaming during IME composition — Enter no longer submits mid-composition and Esc no longer exits the editor while composing.
- [#2686](https://github.com/MoonshotAI/kimi-code/pull/2686) [`ef61084`](https://github.com/MoonshotAI/kimi-code/commit/ef610840098a57819d62d407f33256e14b512c77) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Use a compatible PowerShell for Windows Kimi Computer Use installation, provide actionable recovery for locked plugin files, and keep its marketplace name consistent after installation.
- [#2679](https://github.com/MoonshotAI/kimi-code/pull/2679) [`7b2784b`](https://github.com/MoonshotAI/kimi-code/commit/7b2784b9b7bf4749058da48923ecbbc8019eb7af) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Subagent tasks now show the model and thinking level they use.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix text selection while renaming a session or workspace — dragging no longer moves the whole list item.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix the chevron direction on the "show less" button of the changed-files summary card.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: During automatic retries after a failed model request, the working status now shows retry progress (attempt N of M) instead of looking unresponsive.
- [#2677](https://github.com/MoonshotAI/kimi-code/pull/2677) [`713bf1a`](https://github.com/MoonshotAI/kimi-code/commit/713bf1a5a2b388e4c5f9d3f471a728b8edbf5811) Thanks [@liruifengv](https://github.com/liruifengv)! - Fix resumed sessions rendering background task completion notifications as raw protocol text instead of a task status card.
- [#2692](https://github.com/MoonshotAI/kimi-code/pull/2692) [`03aa66c`](https://github.com/MoonshotAI/kimi-code/commit/03aa66ca0cca5880dc3a4a89e4f46d09acbe47ae) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Show browser extension links and activation steps after installing Kimi WebBridge.
- [#2645](https://github.com/MoonshotAI/kimi-code/pull/2645) [`2b89373`](https://github.com/MoonshotAI/kimi-code/commit/2b893733f9853dc0aaeb775d9670d277db8e0381) Thanks [@sailist](https://github.com/sailist)! - Fix the web UI opening the Documents folder instead of the requested file on Windows when the file path contains spaces.
- [#2697](https://github.com/MoonshotAI/kimi-code/pull/2697) [`e6e4ba2`](https://github.com/MoonshotAI/kimi-code/commit/e6e4ba2357cc659ebd0fd44c9492b498adc33d0e) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix the background-tasks and todos pills being pushed to the top of the window when the plan approval dialog expands.
## 0.33.0
### Minor Changes
- [#2407](https://github.com/MoonshotAI/kimi-code/pull/2407) [`0abcd00`](https://github.com/MoonshotAI/kimi-code/commit/0abcd00f7fd3e3cbf087509ffef1c54a6f8d396d) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Add Kimi Computer Use and Kimi WebBridge as built-in official marketplace entries in the v2 CLI. Installing from `/plugins` sets up the latest managed runtime and plugin together, reports incomplete manual steps, and supports retrying interrupted setup.
- [#2627](https://github.com/MoonshotAI/kimi-code/pull/2627) [`f881cdd`](https://github.com/MoonshotAI/kimi-code/commit/f881cdd97073475c43272ec5734bbc39290dd399) Thanks [@sailist](https://github.com/sailist)! - Run the CLI surfaces (interactive TUI, `kimi -p`, `kimi acp`, `kimi export`, `kimi provider`) on the agent-core-v2 engine by default. Set `KIMI_CODE_LEGACY_FLAG=1` to fall back to the legacy engine.
- [#2565](https://github.com/MoonshotAI/kimi-code/pull/2565) [`54c04bf`](https://github.com/MoonshotAI/kimi-code/commit/54c04bf03ddbeb46d02b2edb460ea091ae194509) Thanks [@7Sageer](https://github.com/7Sageer)! - `/fork` no longer switches to the forked session: the current session stays active and its background tasks keep running. Find the fork in `/sessions`.
- [#2630](https://github.com/MoonshotAI/kimi-code/pull/2630) [`3bd098b`](https://github.com/MoonshotAI/kimi-code/commit/3bd098b80643c99eabdc602b767dbc53fc47cedd) Thanks [@liruifengv](https://github.com/liruifengv)! - Ask whether to trust the current folder on startup.
- [#2630](https://github.com/MoonshotAI/kimi-code/pull/2630) [`3bd098b`](https://github.com/MoonshotAI/kimi-code/commit/3bd098b80643c99eabdc602b767dbc53fc47cedd) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Add and manage custom providers in settings.
- [#2599](https://github.com/MoonshotAI/kimi-code/pull/2599) [`541ddd2`](https://github.com/MoonshotAI/kimi-code/commit/541ddd2d898c4880a312874b1c539f85888bf0c1) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Overhaul the UI/UX and fix known issues.
### Patch Changes
- [#2601](https://github.com/MoonshotAI/kimi-code/pull/2601) [`75fe068`](https://github.com/MoonshotAI/kimi-code/commit/75fe068a01261ff6b34f176530b338ec6a24918e) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Fix built-in capability availability and installed status in `/plugins`, preserve legacy WebBridge skills as backups during updates, and prevent Computer Use updates from duplicating or disconnecting MCP servers.
- [#2635](https://github.com/MoonshotAI/kimi-code/pull/2635) [`2b3e9a9`](https://github.com/MoonshotAI/kimi-code/commit/2b3e9a9f7910b0bb8050380068fa122c2c2cee91) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Rename the partner plugin marketplace tab to Curated and clarify that it contains third-party plugins from Kimi partners.
- [#2614](https://github.com/MoonshotAI/kimi-code/pull/2614) [`8db7d42`](https://github.com/MoonshotAI/kimi-code/commit/8db7d42f23472a692eb389a0e0e5a3e18aa1b94d) Thanks [@RealKai42](https://github.com/RealKai42)! - Add /bug as an alias for the /feedback slash command. Type /bug to submit feedback.
- [#2586](https://github.com/MoonshotAI/kimi-code/pull/2586) [`278b6af`](https://github.com/MoonshotAI/kimi-code/commit/278b6af19d8708ec0f3eb2696d62a8d8209d497d) Thanks [@7Sageer](https://github.com/7Sageer)! - Ensure the first request waits for MCP startup to finish while the interface still opens immediately.
- [#2620](https://github.com/MoonshotAI/kimi-code/pull/2620) [`2ee6e43`](https://github.com/MoonshotAI/kimi-code/commit/2ee6e431240a4a31034e0a403011dd6b2bfef9df) Thanks [@xpzouying](https://github.com/xpzouying)! - Fixed MCP OAuth re-authorization always failing with "Invalid redirect URI": the OAuth callback listener binds a random port per flow, but the dynamic client registration recorded the first flow's port, so every later interactive authorization was rejected at the authorization endpoint. A stale registration is now dropped automatically and the flow re-registers with the current callback URI.
- [#2596](https://github.com/MoonshotAI/kimi-code/pull/2596) [`c32e661`](https://github.com/MoonshotAI/kimi-code/commit/c32e661faa931df9fdc72e63230f3ebebc00dce5) Thanks [@xpzouying](https://github.com/xpzouying)! - MCP tool results now surface the spec-defined `structuredContent` field and `_meta` server metadata to the model as a serialized `<mcp-structured-result>` block, instead of silently dropping them. Servers that return their machine-readable contract in these fields work the same as on other MCP hosts.
- [#2612](https://github.com/MoonshotAI/kimi-code/pull/2612) [`e357028`](https://github.com/MoonshotAI/kimi-code/commit/e3570280bde775a153ee04388393506da7ac4cc1) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix all tool calls failing with spawn EBADF on macOS when a skill folder contains a very large file tree.
- [#2630](https://github.com/MoonshotAI/kimi-code/pull/2630) [`3bd098b`](https://github.com/MoonshotAI/kimi-code/commit/3bd098b80643c99eabdc602b767dbc53fc47cedd) Thanks [@liruifengv](https://github.com/liruifengv)! - Start the interactive TUI without creating a session.
- [#2630](https://github.com/MoonshotAI/kimi-code/pull/2630) [`3bd098b`](https://github.com/MoonshotAI/kimi-code/commit/3bd098b80643c99eabdc602b767dbc53fc47cedd) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Show the signed-in account and plan usage.
- [#2630](https://github.com/MoonshotAI/kimi-code/pull/2630) [`3bd098b`](https://github.com/MoonshotAI/kimi-code/commit/3bd098b80643c99eabdc602b767dbc53fc47cedd) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Set an emoji for the session title.
- [#2630](https://github.com/MoonshotAI/kimi-code/pull/2630) [`3bd098b`](https://github.com/MoonshotAI/kimi-code/commit/3bd098b80643c99eabdc602b767dbc53fc47cedd) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Pin sessions to the top of the sidebar.
## 0.32.0
### Minor Changes

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show more