Commit graph

480 commits

Author SHA1 Message Date
github-actions[bot]
5cc194956f
ci: release packages (#1785)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-17 20:45:40 +08:00
qer
56ba8e0196
fix(server): allow inline styles in CSP so web math renders on non-loopback binds (#1847)
* fix(server): allow inline styles in CSP so web math renders on non-loopback binds

The security CSP fell back to default-src 'self' for styles, which strips
the inline style attributes that KaTeX (injected via innerHTML) uses for
all glyph positioning — formulas collapsed into overlapping characters on
any non-loopback-served web UI. Shiki highlighting and Mermaid diagrams
hit the same mechanism. Add style-src 'self' 'unsafe-inline'; scripts
remain strictly restricted.

* test(server): assert the effective script-src in the CSP regression test

A negative substring check only rejects one exact string: default-src
gaining 'unsafe-inline' (inline <script> allowed via fallback) or an
explicit script-src 'unsafe-inline' would both slip through. Parse the
directives and assert the effective script policy (script-src, falling
back to default-src) excludes 'unsafe-inline'/'unsafe-eval'/data:.
2026-07-17 20:21:10 +08:00
7Sageer
fa7e4ba421
fix(agent-core-v2): follow symlinks when loading AGENTS.md (#1840) 2026-07-17 18:55:46 +08:00
liruifengv
bfecd0128f
feat: refresh model list for API-key providers at the managed endpoint (#1824)
* feat: refresh model list for API-key providers at the managed endpoint

* docs: simplify changeset wording

* docs: add kimi-code/k3 to the default config example

* fix: clear stale default model when a refresh drops its alias

* fix: clear refresh defaults via replace; set(undefined) cannot delete

* docs: drop the auto model refresh paragraph from providers page

* docs: simplify changeset wording
2026-07-17 17:17:58 +08:00
Haozhe
44f3341919
feat(minidb): ClusterDb sharding, incremental reader catch-up, and engine hardening (#1816)
* feat(minidb): add ClusterDb sharding and harden engine under stress

Cluster layer:
- add ClusterDb: hash-routed keys over N MiniDb shard directories with a
  per-shard lock pool (lease renewal, lockHoldMs yield, takeover on dead PID),
  merged ordered scans, cross-shard index registry, live cross-process read
  visibility, and crash-recovery handoff
- add cluster bench suite and multi-process test suites

Engine hardening (stress-driven fixes):
- compaction: pre-copy now gives up when the tail copy is not converging and
  rotation seals the old WAL (retryable), so compaction always terminates
  under sustained write storms and no committed write slips through rotation
- recovery: re-sync WAL size bookkeeping after torn-tail truncation; read-only
  opens create/modify no files and never compact under a live writer
- lockfile: stale-lock takeover via atomic bid-rename + settle; release only
  unlinks its own pid
- query: streaming candidates with skip/limit applied before materialization,
  plus Store.rawKeys for value-free key scans
- eviction: O(1) LRU victim picking via insertion-ordered access set
- TTL: adaptive expire budget drains simultaneous-expiry storms in seconds
- store: O(1) size fast path when no TTL is set; has() no longer materializes
  disk-backed values
- openOrRebuild preserves data when only a sidecar definition file is corrupt;
  sidecar definitions written atomically; stale compaction temps cleaned on open
- RESP server serializes replies per connection; over-64KiB tokens can no
  longer poison the full-text index

* feat(minidb): incremental WAL catch-up for cluster readers

- cluster readers: track a per-shard WAL watermark (dev/ino/offset) and
  catch up from appended frames instead of fully reopening; fall back to a
  full reopen on rotation, truncation, or index-definition changes
- MiniDb.catchUpFromWal applies WAL tail frames to a live instance (store
  plus secondary/dt/compound/text indexes), sharing recover()'s frame
  interpretation; RecoveryInfo exposes walScanEnd/dev/ino as the safe anchor
- lock-pool: incremental refresh with stats (incrementalCatchups,
  catchupFramesApplied); bench/reader-catchup shows p50 read latency drop
  from 130ms to 0.4ms at 10k keys and from 532ms to 0.4ms at 50k keys
  while a neighbor process writes
- compaction: keep the db writable on rotation failure (fresh WAL swap,
  remap once); count stats.compactions only on full success including the
  onCompacted hook
- restoreKey: seq guard so a failed op never wipes a concurrently
  committed value; eviction DELs retry on WAL seal
- text index: atomic build (stage then swap), createTextIndex registers
  only after a successful build, open-time cleanup of db.text-*.postings.tmp
- RESP server: swallow per-connection socket errors, reset the parser
  buffer after an oversized request, isolate per-command errors while
  preserving reply order

* chore(minidb): add changesets for reader catch-up and review hardening

* fix(minidb): support Windows in WAL rotation and lock takeover

- compaction rotation: on Windows, renaming over an open destination is
  EPERM, so replace renames with a retrying renameReplace helper and let
  go of the db's own ValueReader handles for the renames (reopened right
  after the pointer remap)
- value reader: hold snapshot/WAL handles only in valueMode 'disk'; in
  memory mode the handles were idle and, on Windows, blocked rotation
- lock takeover: retry the takeover bid's rename on Windows, but re-check
  the corpse before every attempt — a blind retry loop could land our bid
  late and overwrite an already-verified winner, double-holding the lock
- lock takeover: raise the co-bidder settle window to 50ms so loaded CI
  machines with tens-of-milliseconds descheduling still elect one winner
- test hardening for shared CI runners: a 30s minidb-wide timeout floor,
  batched prefills instead of sequential setup loops, explicit timeouts
  for process-spawning and heavy e2e tests, and Vitest 4 test() signature
  normalization

Verified green across macOS (arm64), Windows Server 2022 (x64, 2-core),
and Ubuntu 22.04 (launchpad aarch64): 321 passed, 1 skipped in each.

* fix(minidb): make stale-lock takeover exactly-one under CI load

- takeover now registers a liveness watch file before touching the lock,
  so every contender is visible to every other for the whole attempt;
  the settle/verify loop abstains while any live foreign watch exists.
  Settle-only heuristics could not survive a bidder descheduled before
  its bid write on shard-parallel CI runners (observed double-holds on
  ubuntu-latest and on a 2-core Windows box).
- adaptive settle scales with the attempt's own wall clock (floored,
  capped), replacing the fixed window.
- keep the Windows EPERM tolerance in the bid rename, re-inspecting the
  corpse before every attempt on ALL platforms, not just win32.
- lint: fix restrict-template-expressions in an e2e RESP helper.
- test: widen the cluster wait-read budget for slow CI spawns.

* fix(minidb): clean remaining CI lint and consumer-test failures

- wrap the compaction-storm error interpolation as String() so the
  type-aware restrict-template-expressions lint passes
- agent-core-v2's minidb query-store corruption test now expects the
  intended semantics: a corrupt index-definition sidecar is dropped while
  the data survives, and the definition can be re-registered

* fix(minidb): harden ClusterDb index administration across processes

Address three multi-process administration races in the cluster layer:

- findRange now merges candidates from all shards first and only then
  applies reverse/offset/count globally, instead of clipping per shard
  and discarding reverse
- cluster.indexes.json mutations go through a compare-and-swap loop
  (reload, re-apply idempotently, publish, verify) with an in-process
  mutex, so concurrent create/drop from two processes loses neither
  registry entries nor shard sidecars
- a failed createIndex/createTextIndex fan-out now rolls back exactly the
  shards it already created on, so the registry and every shard agree
  whether an index exists

Also make LockFile sidecars (tmp/bid/watch) unique per acquire attempt:
two lock users in the same process (independent shard pools) must never
share a path, or one user's cleanup would delete the other's in-flight
file.
2026-07-17 15:57:10 +08:00
Haozhe
9b496946dc
feat(kimi-inspect): add kap-server web inspector with dev-only /api/v1/debug RPC surface (#1806)
* feat(kimi-inspect): add web inspector for kap-server /api/v2 surface

- new apps/kimi-inspect app: connect screen (server URL + optional bearer
  token, persisted in localStorage, deep-linkable via ?url=/?token=),
  workspace/session browser sidebar, per-session chat view, and live
  Service panels with data and trigger buttons for Session/Agent scopes
- built on @moonshot-ai/klient (HTTP for calls, /api/v2/ws for events);
  Vite dev server proxies /api to a running kap-server
- register the workspace in AGENTS.md project map and flake.nix
  workspacePaths/workspaceNames

* fix(kimi-inspect): align dependency versions with the workspace (sherif)

* feat: dev /api/v1/debug RPC surface and kimi-inspect channel rework

- kimi-inspect: replace @moonshot-ai/klient with an in-app old-klient-style
  channel layer (service-bound IChannel, HTTP ProxyChannel, shared /api/v2/ws
  socket with ref-counted event listens), typed by agent-core-v2 interfaces;
  /channels descriptors + serviceByName keep every wire protocol loaded 1:1
- kimi-inspect: local server auto-discovery (Vite middleware over the
  kap-server instance registry + home token), zero-config startup connect,
  and a header switcher for runtime server switching
- kap-server: wire the dormant --debug-endpoints flag to a new
  whitelist-free /api/v1/debug dispatcher (every scoped service callable),
  gated to loopback binds; repo dev scripts pass the flag
- kimi-inspect: probe the debug surface at connect, falling back to /api/v2
  on servers without it
- tests: channel + discovery unit tests in kimi-inspect; debug RPC and
  loopback-gating coverage in the kap-server rpc/debugNonloopback suites

* chore(changesets): ignore @moonshot-ai/kimi-inspect

The private dev app never ships, so it should never appear in a changeset.
Add it to the changeset config ignore list (next to vis*) and note the rule
in the gen-changesets skill.
2026-07-17 15:56:53 +08:00
Haozhe
56a321d4d1
fix(workspace): dedupe workspaces across Windows path spelling variants (#1809)
* fix(workspace): dedupe workspaces across Windows path spelling variants

The same directory reached the workspace registry as distinct strings on
Windows (drive-letter casing, typed vs on-disk casing, slash style), and
every identity check compared exact strings, so one folder could appear
as multiple workspaces with sessions split across hash-keyed buckets.

- add workspaceRootKey (slash-normalize + case-fold Windows-shaped
  paths) in agent-core, agent-core-v2, and the web app, and compare
  roots by identity key everywhere instead of exact strings
- registry createOrTouch folds alias spellings onto the existing entry
  instead of minting a new workspace id; session buckets reuse the
  registered id via a resolver in the v1 session store
- list endpoints expand alias buckets (resolveAliasIds /
  resolveAliasWorkDirs, including session-index-only spellings) so
  previously split workspaces list all sessions and counts under one
  merged group; session_index entries use the registry-resolved id

* fix(workspace): fold the runtime touch path and drive-root identity keys

Two gaps in the Windows path-spelling folding, both reachable in the
v1 session-create flow:

- touchWorkspaceRegistry minted the alias spelling's id outright; the
  freshly persisted alias entry then became the resolver's preferred id
  on the next create, splitting sessions into a duplicate bucket again.
  It now folds onto the identity-matching existing entry, mirroring the
  registry service.
- workspaceRootKey stripped trailing separators before testing the
  Windows shape, so a drive root (C:\) collapsed to C: and escaped the
  case-fold. The shape test now runs before the strip in all three
  copies (agent-core, agent-core-v2, web).

* fix(workspace): unfold symmetric operations that escaped the identity key

Two asymmetric spots left the folded comparison one-sided:

- the web app matched hidden roots by folded key but cleared them on
  re-add by exact string, so hiding C:\Foo and re-adding c:\foo kept
  the workspace hidden forever; clearing now folds too
- registry delete (both engines) removed and tombstoned only the exact
  id, so a legacy split sibling resurfaced as the directory's
  representative on the next list; delete now removes every registered
  spelling sharing the root's identity key and tombstones the full
  alias set (registered ids plus session-index spelling mints), so the
  session-index merge cannot resurrect the directory either
2026-07-17 14:56:06 +08:00
qer
b53e00db91
fix(oauth): include the transport root cause in connection error messages (#1808)
* fix(oauth): include the transport root cause in connection error messages

* chore: add changeset for oauth connection error diagnostics
2026-07-17 14:45:16 +08:00
Haozhe
31449728b7
fix(security): close FetchURL SSRF bypasses and DNS-rebinding window (#1791)
Some checks are pending
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Desktop 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
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 / VSIX package audit (darwin-arm64) (push) Waiting to run
CI / VSIX package audit (all) (push) Waiting to run
CI / VSIX package audit (win32-x64) (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 / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Release / Native release artifact (push) Blocked by required conditions
* fix(security): close FetchURL SSRF bypasses and DNS-rebinding window

- resolve hostnames via DNS and reject any target resolving to loopback /
  RFC1918 / link-local / CGNAT / ULA ranges, including IPv4-mapped IPv6
  forms (e.g. localtest.me, [::ffff:7f00:1]) — the static host denylist
  only matched literals and could be bypassed by crafted domains
- follow redirects manually with full per-hop revalidation (10-hop cap)
  instead of auto-following, so a public URL cannot 302 the fetcher at
  internal services or cloud metadata endpoints
- pin each connection to the DNS answers the check validated (per-hop
  undici Agent with a pinned lookup), closing the TOCTOU / DNS-rebinding
  window between the check and the connect; skipped when a proxy is
  configured or allowPrivateAddresses is set
- apply to both agent-core and agent-core-v2 providers, with SSRF /
  redirect / pinning test coverage

* chore: add changeset for FetchURL SSRF hardening

* test: bridge undici type declarations in fetch pinning tests

* fix(security): keep dispatcher option lib-agnostic for DOM typecheck consumers

* fix(security): address review — pin NO_PROXY bypasses, drain oversized bodies, header-only comments
2026-07-17 11:21:05 +08:00
Kai
373abb02f0
fix(agent-core): record and close tool calls interrupted mid-stream (#1790)
Some checks are pending
CI / build (push) Waiting to run
CI / VSIX package audit (darwin-arm64) (push) Waiting to run
CI / VSIX package audit (all) (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / VSIX package audit (win32-x64) (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
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 / Desktop release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
When the provider stream breaks off mid-tool-call (pause_turn, engine
overload, token limit), the step ended with the partial tool call dropped
silently: never executed, never recorded. If the response carried no other
usable content, the persisted assistant message was effectively empty and
every subsequent request — including compaction — was rejected with
"assistant must not be empty" (HTTP 400), wedging the session.

Record each unexecuted call instead (arguments sanitized to {} when the
truncated JSON is unparseable) and immediately close it with a synthetic
interrupted error result. The exchange stays wire-valid, the history stays
truthful, and the model learns the calls never ran so it can re-issue them.
2026-07-16 21:12:00 +08:00
Haozhe
319001ae5c
refactor: remove git detection from workspace wire and folder browse (#1787) 2026-07-16 21:05:19 +08:00
Kai
365ba0001d
fix: use timestamped default filename for session debug exports (#1788)
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 / VSIX package audit (darwin-arm64) (push) Waiting to run
CI / VSIX package audit (all) (push) Waiting to run
CI / VSIX package audit (win32-x64) (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Release / Native release artifact (push) Blocked by required conditions
Release / Desktop 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
Both engine implementations defaulted the export ZIP path to
<sessionId>.zip, so running /export-debug-zip or kimi export twice for
the same session silently overwrote the first archive. The default
filename is now kimi-debug-<shortId>-<timestamp>.zip (UTC, second
precision), matching the /export-md naming convention. Explicit
-o/outputPath behavior is unchanged.
2026-07-16 19:32:06 +08:00
github-actions[bot]
36b05820cb
ci: release packages (#1767)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-16 18:54:29 +08:00
Haozhe
d465591eb3
fix(agent-core-v2): skip no-op agent registration on session resume (#1784)
- SessionMetadata.registerAgent now compares the incoming metadata with
  the persisted entry (tolerating persisted-JSON artifacts: dropped
  undefined keys, null parentAgentId, label order) and skips the write
  entirely when nothing changed
- previously the first resume per server process rewrote state.json via
  the status rollup's ensureMainAgent -> doCreate path, bumping
  updatedAt and pushing the session to the top of the list
2026-07-16 18:50:12 +08:00
Haozhe
072eed476b
fix(agent-core-v2): keep context size readings on the measured path (#1782)
* fix(agent-core-v2): keep context size readings on the measured path

The step fold creates the assistant message in the context before the
exchange finishes (a skeleton at step.begin, filled by content.part folds
during streaming), and the input array llmRequester passes to
contextSize.measured() is that same live array — it already includes the
output. Taking input.length + output.length therefore counted the folded
output twice, storing a measured prefix length one past the live context.
The inflated length permanently failed get()'s measured fast path, so
reads silently fell back to per-message estimates (e.g. ~50 tokens shown
for a ~29k-token "hi").

Take the live context length as the measured prefix instead (input and
context are identical under the identity guard), and clamp the measured
prefix to the context length in get() so a bad record can never knock
reads off the measured path again.

Add contextSize tests driving real turns that assert the wire model,
get(), and rpc getContext against the exchange totals.

* feat(klient): add context-usage example tracing a fresh session

Polls agent.getContext()/agent.getUsage() and streams agent events for a
new session after one "hi" against a real server, printing a timeline of
when the context/token readings move, plus a final consistency check
comparing the measured tokenCount to cumulative usage. Model seeding is
optional via KIMI_EXAMPLE_* env; the server token resolves from
<kimi-home>/server.token like the v2 e2e helpers.

* chore: add changeset for the context size fix
2026-07-16 18:37:28 +08:00
_Kerman
09e855401b
fix: report task stop reasons to the model (#1781)
* fix: report task stop reasons to the model

* chore: add task stop reason changeset
2026-07-16 18:32:06 +08:00
Kai
d531398d01
fix: scope Anthropic effort fallback profile to non-Kimi providers (#1765)
* fix: scope Anthropic effort fallback profile to non-Kimi providers

Managed Kimi models routed through the Anthropic protocol (protocol =
"anthropic", no catalog-declared think_efforts) inherited the inferred
latest-Opus effort profile, so the UI showed reasoning effort choices the
server never declared. The fallback now applies only when the provider type
is known, non-kimi, and the effective wire protocol is Anthropic; Kimi
providers keep catalog-declared efforts only, and callers without provider
context fall back to name matching.

* fix: align v2 catalog with resolver for providerless Anthropic models

Flat models (inline base_url, no named provider) and providers without a
declared type now fall back to the model's own protocol when deciding the
Anthropic fallback effort profile, so the model catalog stays consistent
with runtime resolution.

* fix: keep flat Anthropic model effort metadata in TUI and ACP catalogs

Flat models without a named provider (inline base_url, protocol:
"anthropic") have no provider entry to look up; fall back to the
model's own protocol as the provider identity so the effort picker and
ACP catalog stay consistent with runtime resolution.

* style: move v2 anthropic fallback rationale into the modelAuth header

The v2 comment convention keeps comments in the top-of-file block only;
drop the inline explanations added beside functions and statements.
2026-07-16 17:30:20 +08:00
qer
d1ca65e1de
feat(vscode): migrate extension to Node SDK (#1769)
* feat(vscode): migrate extension to Node SDK

* fix(vscode): address CI failures

* fix(vis): handle token count records

* fix(vscode): keep chat toolbar and header readable at narrow widths

* fix(vscode): map yolo to core yolo permission and honor the global yolo setting

* docs(vscode): record Node SDK migration design

* docs(vscode): split breaking changes out of the 0.6.0 changelog

* fix(vscode): keep a resumed session's thinking effort instead of reapplying the default

* fix(vscode): announce session status when a view attaches so the display matches it

* fix(vscode): align webview thinking effort handling with the TUI
2026-07-16 17:27:21 +08:00
Haozhe
ffaf0b98ca
feat(agent-core): align coder subagent tools with v2 and drain background tasks (#1776)
* feat(agent-core): align coder subagent tools with v2 and drain background tasks

- align the bundled coder subagent profile tools with agent-core-v2
  CODER_TOOLS (Skill, Agent, AgentSwarm, Task* trio, plan-mode tools,
  TodoList); cron tools stay declared-but-undelivered on sub agents,
  matching v2
- rebuild builtin tools in setActiveTools: profile-gated capabilities
  (Bash/Agent allowBackground via the Task* trio) were baked at
  construction with an empty enabled set, so profiles applied later
  (every subagent) silently lost them
- hold subagent completion until the child agent's background tasks
  settle (print-mode drain semantics) and suppress their terminal
  notifications, so no unobserved follow-up turn runs on a finished
  subagent; the run's timeout/cancel signal bounds the drain
- cover with real-Session e2e (tool execution, nested Agent/AgentSwarm,
  drain blocking and cancel) and update profile/subagent-host tests

* chore: add changeset for coder subagent tool alignment

* docs(agents): sync sub-agent capabilities with expanded coder tool set

- coder sub-agents can now dispatch nested sub-agents and use background
  tasks, todo lists, Plan mode, and skills; drop the stale claim that
  sub-agents cannot schedule nested sub-agents
- note that a sub-agent run reports completion only after its background
  tasks settle

* fix(agent-core): close drain race for tasks settled before completion

A background task that terminated before the drain's suppression pass was
excluded from the active-only list, so its terminal notification escaped
suppression and could still steer an orphan turn onto the finished
subagent. Suppress every child task (including settled ones whose
notification may still be in flight) and run the pass both before and
after the settle wait; notification delivery re-checks suppression after
its async output snapshot, which makes the block deterministic. Cover the
mid-turn delivery path with an e2e case.
2026-07-16 17:14:53 +08:00
Kai
3d5d630c12
fix: honor explicit thinking off on OpenAI-compatible providers (#1774)
An explicit withThinking('off') collapsed to the same internal state as
"never configured" on chat-completions providers, so the history-based
auto reasoning_effort injection (#1616) silently switched reasoning back
on and could leak the field to models that reject it. Store the requested
effort verbatim and derive the wire encoding per request, suppress the
auto-enable for an explicit 'off', and report the accurate current effort
('on'/'off') instead of recording 'off' for both.
2026-07-16 17:11:18 +08:00
Kai
1169a6d5fd
fix: replay empty thinking verbatim on preserved-thinking endpoints (#1773)
Remove the wire-level fallback that substituted a space for empty
thinking content when replaying assistant history to Anthropic-compatible
and Kimi endpoints with thinking keep=all. The strict endpoints that
motivated the placeholder no longer reject empty thinking, so the
placeholder only distorted replayed history.
2026-07-16 17:00:06 +08:00
Haozhe
9e3e6700f9
fix(agent-core-v2): settle killed subagent runs only after the child loop goes idle (#1759)
- awaitRun: cancel by turn id so aborts also reach turns still queued, not just the active turn
- awaitTurn: cancel first, then wait for turn.result instead of racing against the abort signal, so task settlement, the task.killed notification, and the resume guard never observe the run as finished while the loop is still unwinding
- rethrow the original abort reason so consumers keep matching it by identity
- add regression test for the manual stop -> auto-resume "already running" race
2026-07-16 16:47:56 +08:00
Haozhe
4cffd732c2
feat(klient): contract-driven facade with http/ipc/memory transports (#1768)
* feat(klient): contract-driven facade with http/ipc/memory transports

- add zod-validated contract sections (global/session/agent) under
  src/contract and a facade exposing global.*, session(id).*, agent(id).*
- select transport once at creation via subpath entries
  (@moonshot-ai/klient/http|ipc|memory); drop legacy channel/client/
  httpChannel/wsChannel/wsKlient/proxy implementations
- absorb packages/server-e2e into packages/klient test/e2e suites
  (dual-backend, legacy v1, v2 wire) and remove the server-e2e workspace
- expose model registry and catalog services on kap-server v2 RPC surface

* fix(klient): derive session status from agentActivityView

The engine retired its sessionActivity service in #1751 (session busy is
now derived from agent activity views), but the facade still called the
deleted wire channel and imported the deleted engine module, breaking
typecheck and every klient suite at import time.

- drop the sessionActivity contract/registry entries and mirror the
  agentActivityView service instead (agent scope)
- compose session status() client-side from the pending interaction lists
  and each agent's agentActivityView, keeping the retired service's
  precedence and typing SessionStatus locally in the facade
- replace the deleted-channel call in the v2 smoke suite with a
  sessionInteractionService probe
- fix the legacy image-file suite to wait with the harness's
  waitForSessionBusy
2026-07-16 16:43:09 +08:00
Haozhe
78967e283d
refactor(model-catalog): drop WS catalog-changed event; refresh on picker open (#1772)
- kap-server: remove event.model_catalog.changed from the v1 WS union,
  broadcaster forwarding, and the zod event registry
- web: refresh all providers (POST /providers:refresh) before loading
  models when the model picker opens, replacing the event-driven refresh
- keep domain publishers, the protocol schema, and the web receiver for
  compatibility with older daemons
2026-07-16 16:34:32 +08:00
7Sageer
70211a727f
feat: attach trace_id to telemetry events (#1724)
* feat: attach KFC trace_id to telemetry events

Capture the x-trace-id response header in both kimi providers (kosong
and agent-core-v2 llmProtocol) via the openai SDK withResponse(), and
thread it through the request result chain into telemetry so events can
be joined with server-side request logs by trace id instead of
session_id + time window.

- kosong / llmProtocol: StreamedMessage/GenerateResult.traceId,
  GenerateOptions.onTraceId early capture (available mid-stream),
  APIStatusError.traceId on the error path
- v1 (agent-core): per-turn traceIdByTurn on TurnFlow; attach trace_id
  to turn_ended/turn_interrupted/api_error/cancel/tool_call(+dedup,
  repeat)/permission_approval_result/question_*/compaction_*
- v2 (agent-core-v2): AgentTelemetryContext carries turn_id/trace_id
  updated by llmRequester; registry gains trace_id on 13 events plus
  turn_id on turn_* and turn_id/step_no on api_error

* fix: attribute trace_id to the failed request on error paths

Review follow-ups for trace_id attribution on failure paths:

- v1: chatWithRetry feeds a failed attempt's APIStatusError trace id into
  the turn's traceIdByTurn before the loop dispatches turn.interrupted,
  so turn_ended/turn_interrupted on error turns attribute to the failed
  request instead of the previous successful step.
- v2: llmRequester keeps the onTraceId-captured trace in per-request
  state and trackApiError prefers it over error extraction, so failures
  after response headers arrived (empty response, mid-stream decode
  errors) no longer clear the ambient trace_id.
- v2: compaction_failed falls back to the ambient trace_id once a
  summarizer request actually hit the wire, covering mid-stream failures
  whose error carries no trace.
- kosong: parseTraceId filters empty x-trace-id headers and both kimi
  providers read the header through it.
- v2 test harness forwards onTraceId to GenerateFn so tests can simulate
  the early header capture.

* fix: attribute v1 api_error to the in-flight request on post-headers failures

- v1: a failure after response headers arrived (mid-stream decode error,
  empty response) carries no trace on the error itself, so api_error lost
  the trace the client had already captured via onTraceId. Add a per-step
  in-flight capture (written by onTraceId, cleared at step begin/end) and
  fall back to it when the error carries no trace, aligning with v2's
  per-request requestTraceId. Failures before any response headers
  (network errors, local aborts) still report no trace rather than
  leaking a previous request's.
- v2: document that ambient trace_id distribution assumes serialized LLM
  requests per agent, naming the two supported paths that break it
  (after-step compaction below the block ratio; inject-path turns during
  a manual compaction).

* fix: isolate telemetry trace attribution

* fix: isolate telemetry trace by request

* fix: declare @moonshot-ai/protocol dependency of agent-core-v2

The trace-by-request refactor imports types from @moonshot-ai/protocol
in toolContract and toolExecutorService, but the package was not
declared, failing clean CI installs (TS2307). Also drop three type
imports that are unused after the merge with main.
2026-07-16 09:14:12 +08:00
Kai
1d7c205e83
fix: close two silent-exit vectors around unhandled rejections (#1758)
Some checks are pending
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 / 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
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
CI / typecheck (push) Waiting to run
Release / Native release artifact (push) Blocked by required conditions
Release / Desktop release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* fix: record crash telemetry for unhandled promise rejections

The crash handler only listened on uncaughtExceptionMonitor, which never
fires for a rejection that has a listener — and the TUI always registers
one, converting rejections into a silent exit(1) with no telemetry at
all. Observe unhandledRejection directly so those crashes still leave a
trace. Since registering a real listener suppresses Node's default
crash-on-rejection, rethrow when we are the only listener (print /
server modes), deduped so the monitor does not double-report.

* fix: fall back to text paste when the clipboard image handler rejects

The Ctrl+V image-paste dispatch chained off the async handler without a
rejection branch, so any failure inside it became an unhandled
rejection — which the CLI's crash path turns into a silent exit(1).
Treat a rejection like "no image available" and paste as text.

* fix: dedupe all rethrown rejection reasons at the crash monitor

Non-Error rejection reasons (plain objects, strings, null) were recorded
by the rejection handler but not added to the dedupe set, so the
uncaughtExceptionMonitor pass after the rethrow reported a second crash
for the same failure; null/undefined reasons also crashed the monitor's
own error-type extraction. Use a Set so primitives dedupe by value, add
every rethrown reason, and classify monitor crashes null-safely.
2026-07-16 02:14:14 +08:00
Kai
918c1354d9
fix: align Anthropic-compatible model capabilities (#1746)
* fix: align Anthropic-compatible model capabilities

* fix: warn on Anthropic effort mismatches

* fix: harden Anthropic model resolution

* fix: align Anthropic replay and ACP thinking state

* fix: normalize Anthropic thinking stream payloads

* fix: backfill non-empty preserved thinking

* fix: resolve session thinking effort with provider context

* fix: honor adaptive thinking opt-out in effort resolution
2026-07-16 01:31:38 +08:00
Kai
f0c8a103c6
fix: preserve the crash error in diagnostic logs on unexpected exit (#1757)
The TUI crash path (uncaughtException / unhandledRejection) logged the
error into an asynchronously-drained sink and then called process.exit()
on the same tick, so the one line explaining the crash was never written
to disk. Flush the diagnostic logs synchronously before exiting.
2026-07-16 01:26:27 +08:00
_Kerman
df75a0f5c2
refactor(agent-core-v2): derive session busy from agent activity (#1751) 2026-07-15 23:33:58 +08:00
Haozhe
d8ddabb605
fix(kap-server): close auth bypass via percent-encoded API paths (#1753)
* fix(kap-server): fail closed on percent-encoded API paths in auth bypass

The auth hook checked the raw, still percent-encoded request URL against
its bypass policy, while find-my-way matches routes against the decoded
path. A raw /%61pi/v1/... URL therefore skipped the bearer-token check
yet still reached the /api/... handlers, allowing unauthenticated access
to every API route.

Decode the request path the same way the router does before matching,
and fail closed when the path cannot be decoded. Add tests covering
encoded /api/ paths, encoded meta documents, the encoded healthz probe,
and unaffected non-API bypasses.

* fix(agent-core-v2): make session fs path confinement symlink-aware

SessionFsService confined paths only lexically, so a symlink planted
inside the workspace could steer read, list, stat, mkdir, resolvePath
and resolveDownload to host files outside the session directory.

- add IHostFileSystem.realpath (Node fs.realpath semantics) and
  implement it in the node-local HostFileSystem
- resolveWithin now re-verifies each candidate through realpath of the
  longest existing prefix (so not-yet-created paths still work) and
  rejects paths escaping the canonicalized workspace roots, which are
  resolved once and cached
- cover symlink escapes for every fs entry point plus kap-server
  read/download e2e; in-workspace symlink targets remain allowed

* fix(agent-core-v2): accept workspace roots given through a symlink

WorkspaceRegistryService.createOrTouch probes the root with the
lstat-based IHostFileSystem.stat, so a root given as a symlink to a
directory reported isDirectory=false and session creation was rejected
with fs.path_not_found ("not a directory").

Re-check a non-directory root through IHostFileSystem.realpath before
failing, while keeping the workspace identity lexical (v1 deliberately
never realpaths the root either). Covered by a unit test for a
symlink-form root and a kap-server e2e that creates a session with a
symlinked cwd and reads a file through it.
2026-07-15 23:05:19 +08:00
_Kerman
4f99114342
refactor(kap-server): drop the @moonshot-ai/protocol dependency (#1755) 2026-07-15 22:40:05 +08:00
Haozhe
0b790cdc05
feat(web): allow attaching any file type and fix CSP on non-loopback binds (#1731)
* feat(web): allow attaching any file type in chat

- Composer, paste, and drop no longer filter out non-media files;
  arbitrary files upload as generic icon chips and are submitted as
  file content parts
- kap-server materializes file parts into the session's attachments
  dir and replaces them with a path reference, so the model opens the
  file with the Read tool on demand instead of receiving inline bytes
- Images rejected by the provider format gate (SVG, AVIF, ...) are now
  persisted and referenced by path instead of being dropped with a
  notice; uploaded file names are sanitized before hitting disk

* fix(server): stop CSP from blocking web bootstrap script and fonts

- Move the anti-FOUC bootstrap from an inline <script> in index.html
  to /boot.js: CSP 'self' never covers inline scripts, while a classic
  same-origin script keeps the same render-blocking timing
- Allow data: in font-src — KaTeX and the Inter / JetBrains Mono
  Variable fonts ship @font-face data URIs in their distributed CSS
- Set explicit form-action, base-uri, and frame-ancestors, which do
  not fall back to default-src
- Add a regression test asserting the served index.html carries no
  inline scripts or inline event handlers

* fix(web): normalize empty attachment MIME so extensionless files submit

Files with an empty File.type (Makefile, LICENSE, other extensionless
or unknown types) stored mediaType: '' on the chip, and the submit
fallback used ?? which does not catch empty strings — the wire schema
requires a non-empty media_type, so the prompt was rejected. Normalize
to application/octet-stream at attachment creation, adopt the
server-recorded MIME after upload completes, and make both submit
mappings use || so reloaded chips with '' are covered too.

* feat(web): render all user-turn attachments as chips

* feat(web): attach files by dropping them anywhere in the window

* refactor(web): share one attachment chip between composer and chat bubble

* fix(web): neutral attachment chips, paperclip attach icon, and clickable file chips

* fix(web): drop the extension badge from attachment chips

* fix(web): use the tabler paperclip for the attach button

* fix(web): whitelist attachment previews, reject active document types

Clicking a file chip navigated a new tab to a blob: URL of the uploaded
bytes whenever the type looked browser-renderable. blob: inherits the
web origin, so a text/html or image/svg+xml attachment would execute
same-origin script with the daemon credential (localStorage) and a live
window.opener.

Preview is now restricted to inert types (pdf, non-SVG images, video,
audio, non-HTML text), the blob is re-wrapped with the whitelisted MIME
instead of trusting the recorded content-type, and window.opener is
severed. Non-whitelisted types no longer silently download: the chip
reports 'unsupported' and the pane shows a transient hint.

* fix(web): recover file attachment chips from the server notice

The kap-server prompt route replaces file parts with an "Attached file
…" text notice before enqueueing, so after any snapshot resync the
attachment chip degraded into raw notice text leaking the absolute
server path — unlike image/video uploads, which already recover their
chip from the <video|image path> tag. Parse the notice the same way:
the materialized basename carries the file id, so the chip becomes
clickable again (and editable back into the composer); inline-base64
notices (content-hash named, no file id) still collapse into a
non-clickable chip instead of raw text.

The notice wording is now a client/server contract — flagged on
buildAttachedFileNotice.

* fix(web): preserve UUID file ids when rebuilding attachment chips

* fix(web): skip unresendable file chips when loading attachments for edit

---------

Co-authored-by: qer <wbxl2000@outlook.com>
2026-07-15 21:54:48 +08:00
qer
72f425e18d
fix(agent-core-v2): make Gemini tool call ids unique across turns (#1730)
* fix(agent-core-v2): make Gemini tool call ids unique across turns

* fix(kosong): recover tool names from entropy-suffixed Gemini call ids

The orphan tool-message fallback in toolCallIdToName stripped only one
trailing "_<suffix>" segment, so with the new
"{tool_name}_{upstream_id}_{entropy}" id shape it returned
"AgentSwarm_0" instead of "AgentSwarm" once the preceding assistant
call had been compacted away. Strip the fixed 8-hex entropy suffix
first, then the upstream id segment, in both the kosong and
agent-core-v2 providers. Also drop the inline implementation comment
that agent-core-v2 forbids outside the file header.

---------

Co-authored-by: haozhe.yang <yanghaozhe@moonshot.ai>
2026-07-15 17:47:53 +08:00
Haozhe
1824e73020
style(agent-core-v2): fold retry-budget note into the file header (#1742)
packages/agent-core-v2/AGENTS.md requires comments to live only in the
top-of-file block, never beside statements.
2026-07-15 17:10:04 +08:00
_Kerman
27236bd75f
refactor(agent-core-v2): drop the @moonshot-ai/protocol dependency (#1745) 2026-07-15 16:03:19 +08:00
Luyu Cheng
481b28b8f4
fix(agent-core-v2): correct goal lifecycle error guidance (#1743)
* fix(agent-core-v2): correct goal lifecycle error guidance

* refactor(agent-core-v2): remove unused goal service API
2026-07-15 15:42:39 +08:00
Luyu Cheng
8a3f1ffa6f
fix(kap-server): derive session title from first skill slash command (#1741) 2026-07-15 15:42:25 +08:00
Haozhe
a160915596
test(klient): add real-server smoke coverage (#1713)
Add transport and persisted-session smoke scripts for HTTP, WebSocket, and scoped service calls.
Type-check all examples and document remote-server usage and side effects.
2026-07-15 15:24:36 +08:00
Haozhe
a74ab44ac7
feat: raise default per-step LLM retry budget to 10 attempts (#1740)
* feat: raise default per-step LLM retry budget to 10 attempts

The default of 3 attempts only produced ~1.5s of backoff (0.5s/1s), so
sustained provider overload (429) surfaced to the user almost
immediately. With 10 attempts the exponential ramp (500ms base, x2,
32s cap, 25% jitter) waits out multi-minute overload windows before
failing the turn. Applies to both agent-core (chatWithRetry) and
agent-core-v2 (stepRetry service); loop_control.max_retries_per_step
still overrides.

* test(agent-core): pin retry-dependent tests to the new default budget

- error-paths: the warn-log attempt field now reads 1/10 with the
  default 10-attempt budget
- goal-session pause tests: every LLM call throws a retryable error, so
  the default 10-attempt backoff (~2min) blew the 5s test timeout; pin
  maxRetriesPerStep=1 since the pause behavior does not depend on the
  retry count
2026-07-15 15:24:17 +08:00
Haozhe
5d6ff022b1
feat(agent-core): drop default timeouts for print-mode background tasks (#1737)
* feat(agent-core): drop default timeouts for print-mode background tasks

- add `bash_task_timeout_s` config under [background] (0 = no timeout),
  covering the background Bash default and the re-arm after a foreground
  command is moved to the background on timeout
- allow `[subagent] timeout_ms = 0` (no timeout) and thread it through
  Agent/AgentSwarm task registration and the swarm batch timer
- fill both with 0 in print-mode config defaults so `kimi -p` never kills
  background work by wall-clock and only the model stops a task;
  interactive defaults are unchanged
- sync the Bash tool description/parameter text with the effective
  default and update user docs (en/zh) plus changeset

* test(agent-core): satisfy KimiConfig providers requirement in print-defaults tests

* fix(agent-core): clear the foreground deadline on detach when the background timeout is disabled

`detach()` only re-arms when `detachTimeoutMs` is defined, so passing
`undefined` with `bash_task_timeout_s = 0` kept the armed foreground
deadline and a manually detached command was still killed at its
foreground timeout. Pass `0` instead so the reset clears the timer.
Caught by Codex review on #1737.
2026-07-15 14:35:32 +08:00
Luyu Cheng
513f374aa0
fix(agent-core-v2): validate goal records (#1694) 2026-07-15 14:19:03 +08:00
qer
b24a347e20
fix(kap-server): carry the live subagent roster in the session snapshot (#1719)
* fix(kap-server): carry the live subagent roster in the session snapshot

* fix(kap-server): clear the subagent roster on the next main turn start

* fix(kap-server): exclude background subagents from the snapshot roster

* fix(kap-server): finalize live roster entries when the main turn aborts

* fix(kap-server): drop roster entries when foreground subagents detach

* fix(web): expand the swarm card by default while subagents are running

* docs(kap-server): qualify the roster-clearing durability claim
2026-07-15 12:40:30 +08:00
_Kerman
2591395158
refactor(agent-core-v2): remove dead ExecutableToolResult.message field (#1729) 2026-07-15 12:32:25 +08:00
7Sageer
c291ee2ddb
fix(telemetry): deliver session_started in v2 headless mode (#1687)
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 / Desktop 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
Release / Native release artifact (push) Blocked by required conditions
* fix(telemetry): deliver session_started in v2 headless mode

session_started/session_load_failed fire inside create()/resume(), but the CloudAppender was installed only after resolveNativeSession() returned, so they were dropped to the null appender.

- run-v2-print: install the appender before resolving the session; reconcile a resumed session's real model via setContext afterwards.
- sessionLifecycle: bind the session id in announceCreated before emitting so session_started carries session_id.
- CloudAppender.setContext: allow updating the model context.

* fix(agent-core-v2): bind session id on session_load_failed

The resume failure path emitted session_load_failed without binding the
session id first, so the event went out with session_id null even though
the service knows which session failed to load. Bind it via setContext
before track2, mirroring the announceCreated path for session_started,
and update the two tests that locked the empty context in as expected.
2026-07-15 11:52:01 +08:00
liruifengv
286d3e7aca
feat: add check-kimi-code-docs builtin skill (#1727)
* feat(agent-core): add check-kimi-code-docs builtin skill

* feat(agent-core-v2): add check-kimi-code-docs builtin skill

* docs: list check-kimi-code-docs in builtin skill commands

* chore: add changeset for check-kimi-code-docs skill
2026-07-15 11:42:47 +08:00
Haozhe
3703d0346e
feat(agent-core): default print mode to steer with unbounded limits (#1722)
- change the default print background mode from 'exit' to 'steer' so
  `kimi -p` stays alive while background tasks are pending and each
  completion steers a new main turn
- add print-mode config defaults (applyPrintModeConfigDefaults):
  effectively unbounded wait ceiling and turn cap, 72h subagent
  timeout; explicit user config always wins
- thread the new `uiMode` option from SDKRpcClient through KimiCore
  into session create/resume
- clamp setTimeout delays to 0x7fffffff so huge timeouts are not
  clamped to 1ms by Node
2026-07-15 11:11:00 +08:00
liruifengv
3770447e57
fix(agent-core-v2): run stdio node plugins with the bundled Electron Node on Electron hosts (#1723) 2026-07-15 11:00:45 +08:00
Luyu Cheng
7de218a909
fix(kimi-web): resume paused goals (#1693)
Some checks are pending
Release / Release (push) Waiting to run
CI / typecheck (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 / test (2) (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 / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Desktop release artifact (push) Blocked by required conditions
* fix(kimi-web): resume paused goals

* fix(agent-core-v2): defer paused goal continuation
2026-07-15 00:00:29 +08:00
Luyu Cheng
2bf009fe27
fix(agent-core-v2): reject subagent goals (#1697)
* fix(agent-core-v2): reject subagent goals

* fix(kap-server): guard reflected subagent goals
2026-07-14 23:30:30 +08:00
Luyu Cheng
722694adf9
fix(agent-core-v2): enforce goal deadlines (#1698) 2026-07-14 23:00:05 +08:00