Commit graph

1713 commits

Author SHA1 Message Date
7Sageer
0af13f5a99 feat(agent-core-v2): transcribe context-ownership spine view from SpineCodex
Replace the rule-manual <spine_view> text with the upstream rewrite
(SPINE_JIT_INSTRUCTIONS, through 97f4eb1a): node boundaries derive from
context ownership and lifecycle, shared context lives in the lowest common
ancestor, and execution rules cover one transition per turn, batching, and
transition attribution. Local adaptations: spine_open/next/close tool
spellings, no code-mode exec clause, and no trim segment (upstream leaves
SPINE_TRIM_INSTRUCTIONS empty pending approved copy).
2026-08-04 14:54:29 +08:00
7Sageer
9cdba7ac49 feat(agent-core-v2): align spine spawn collaboration prompt with SpineCodex
Transcribe the branch collaboration contract model (upstream 18523b3e9):
independent execution is the default, and branches that need coordination
declare a shared collaboration directory, a per-branch collaboration file,
the artifact protocol, synchronization points, and a bounded fallback in
the task prompt. Replaces the mandatory shared-blackboard wording in the
spawn envelope and the spine_spawn tool/prompt descriptions.
2026-08-04 14:54:16 +08:00
7Sageer
5f8e0969ae fix(tui): keep spine tree visible after all nodes close
The tree-mode todo panel hid the moment the spine cursor stack emptied,
which made the all-done tree vanish right when the run completed. The
projection now only returns empty before the first spine_open; once
nodes exist, an empty cursor stack projects the all-done forest, and
the next spine_open starts a fresh root beside it.
2026-08-04 12:21:48 +08:00
7Sageer
de03c4c0c0 feat(agent-core-v2): align spine branch control tools with SpineCodex
Spawned execution branches now register spine_open / spine_close /
spine_next: the fork stamps a spineBranch=true label (new
ForkAgentOptions.labels, persisted via registerAgent and seeded into
IAgentScopeContext.labels), and the three control tools gate on
isSpineControlHost (main or labeled branch) instead of main-only.
spine_spawn / spine_trim / spine_tree stay main-only, so nested spawn
remains structurally disabled — the upstream agents.max_depth config
(general agent-thread nesting, default 1) is deliberately not ported.

Branch envelope: restore the two ported sentences — the
spine_open/close/next descendant-work sentence and the
<spine_tran_status> telemetry paragraph (emitted locally since the
projection-pipeline alignment), tool names in local flat spelling.

f4f4ba6e3 (close spawned agent trees at join) verified N/A by
construction: session resume only re-materializes the main agent, no
path re-materializes a settled branch from metadata, and
lifecycle.remove() is terminal — no persisted spawn edges to close.
2026-08-03 19:20:04 +08:00
7Sageer
3a3770f5c3 feat(agent-core-v2): align spine projection pipeline with SpineCodex
Status line: replace the per-request synthetic <spine_status> projection
artifact with the upstream <spine_tran_status> contract — persisted into
history by the service only after a step that applied a transition
(cursor-stack signature), surviving resume, rendering as an ordinary
live-range message, and folding away with its closing span; undo /
restore / splice re-baseline the signature without re-emitting. Keeps
the local raw_context / projected_context field extras.

Trim: run the trim projection standalone (upstream
materialize_trim_only_context) — KIMI_CODE_SPINE_TRIM no longer requires
KIMI_CODE_SPINE; the tool registers on its own flag, acceptTrim drops the
spine-flag precondition, and the projector fold maps labels / masks over
the plain history when the tree fold is off.

Re-slicing verified a non-gap: upstream reducer's Sliced(body) arm is
unreachable defensive code (id lookup matches Tagged only), so upstream
main is one-shot like the local semantics; recorded in the plan doc.
2026-08-03 18:55:35 +08:00
7Sageer
5335c9b888 feat(agent-core-v2): align spine spawn capacity failure form with SpineCodex
Capacity-shortfall admission no longer rejects the whole spawn call with a
tool error. Matching upstream capacity_rejection_receipts, the call succeeds
with a full spine.spawn.result.v1 receipt whose per-task errored results
carry the upstream diagnostic, so the rejected batch is recorded in the tree
and the model can retry with fewer tasks.

The receipt also gains the optional execution_ref field carrying the forked
child agent id for started branches; derive validates it must be a non-empty
string when present, mirroring the upstream model check.
2026-08-03 18:10:03 +08:00
7Sageer
09cbe338cb feat(agent-core-v2): align spine gating semantics with SpineCodex
- Plan mode now rejects every spine transition (open/close/next/spawn/trim)
  with the upstream 'Spine transitions are not allowed in Plan mode' reason,
  read off the persisted PlanModel so it follows undo/restore.
- Same-response double control calls turn silent: the per-step transition
  budget is gone, every individually valid call earns its accepted receipt,
  and the derivation classifies one assistant message as one tool-call group
  (a lone accepted control applies; two or more, or any mix with spine_spawn,
  applies none), matching the upstream reducer's classify_control.
- Spawn mixing/duplication moves to a loud executor before-execute veto with
  the upstream messages (cannot be mixed / at most once per response), so a
  vetoed spawn never starts branch work.

Recorded in plan/spine-v3-alignment.md (P8), including the intentional
difference that spawn stays registered (but errors) in plan mode because
local tool registration is static per agent.
2026-08-03 17:50:05 +08:00
7Sageer
fb2c1f42df chore(agent-core-v2): regenerate config manifest for the spineSpawn section 2026-08-03 17:49:14 +08:00
7Sageer
55c1c43537 feat(agent-core-v2): align experimental spine spawn with SpineCodex 0.2.2
- Rewrite the spine_spawn description and branch envelope for the
  peer-branch model: peer roster injection, shared-blackboard
  read/write duties, and duplicate task-summary rejection.
- Salvage terminal memory from branches that fail with a
  retryable-class error through a bounded no-tool request; the spawn
  receipt keeps the errored outcome and carries the salvaged memory.
- Add the [spine_spawn] config.toml section
  (max_concurrent_threads_per_session, int >= 2) with
  KIMI_CODE_SPINE_SPAWN_MAX_THREADS kept as an env override; spawn
  admission and tool gating now resolve through IConfigService.

All parts stay behind the experimental KIMI_CODE_SPINE_SPAWN flag.
2026-08-03 15:56:13 +08:00
7Sageer
017a213d01 Merge remote-tracking branch 'origin/main' into spine-v2
Resolve 43 conflicted files: union spine features (rawContextTokens gauge,
snapshot chain, prompt contributions, compaction guards, skill sources) with
upstream's agentState/sessionState migration, Workspace domain, scoped tool
services, and the L0-L7 layering removal. Port spine + TUI facade code to the
new APIs (AgentTool/registerAgentToolService, ScopeActivation, IBootstrapService
renames, Workspace session lookup, async undo domain).

Left out pending facade ports in apps/kimi-code/src/core: workspace-trust
startup prompt, --agent/--agent-file TUI binding, atomic config replace on
provider refresh (each recoverable from origin/main).

Verified: agent-core-v2 typecheck + 4576 tests, kap-server typecheck + 938
tests, kimi-code typecheck + tests, all packages typecheck, build:packages.
2026-08-03 13:23:06 +08:00
liruifengv
e22479a62e
feat(kap-server): expose effective experimental flags in /meta (#2417)
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
Release / Release (push) Has been cancelled
Nix Build / Check flake.nix workspace sync (push) Has been cancelled
Release / Deploy docs (push) Has been cancelled
Release / Native release artifact (push) Has been cancelled
Release / Publish native release assets (push) Has been cancelled
Nix Build / nix build .#kimi-code (push) Has been cancelled
2026-08-01 10:22:23 +08:00
Sampson
a5960b3905
test(agent-core-v2): disables commit.gpgsign (#2475) 2026-08-01 10:16:51 +08:00
StaR4y
bfa00807c9
fix(web): correct dark monochrome composer styling (#2083)
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 / nix build .#kimi-code (push) Blocked by required conditions
Nix Build / Check flake.nix workspace sync (push) Waiting to run
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
Co-authored-by: StaR4y <star4y@origin.pw>
Co-authored-by: qer <wbxl2000@outlook.com>
2026-07-31 22:38:45 +08:00
qer
7648874730
docs(changelog): sync 0.31.1 from apps/kimi-code/CHANGELOG.md (#2470) 2026-07-31 20:21:53 +08:00
Mangesh Raut
eaab2b6f28
fix(cli): fall back to built-in models.dev catalog when fetch fails (#2416)
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 / nix build .#kimi-code (push) Blocked by required conditions
Nix Build / Check flake.nix workspace sync (push) Waiting to run
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
When the remote models.dev catalog cannot be fetched, fall back to the
built-in catalog so CLI/TUI model selection keeps working offline or
under network failure. Import the shared helper via the #/utils alias.
2026-07-31 19:54:09 +08:00
github-actions[bot]
6b56c11697
ci: release packages (#2403)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-31 19:29:29 +08:00
qer
326e1fb6ce
fix(web): restore chat code block styling after the markstream upgrade (#2459)
* fix(web): restore chat code block styling after the markstream upgrade

markstream-vue 1.0.9 renders shiki code blocks through stream-diffs
(code-editor-container) instead of <pre>, and drives font size, line
height, and font family from monacoOptions applied as inline styles.
With only lineNumbers passed, blocks fell back to 12px/18px in the
inherited proportional UI font, and the pre/copy-button/content CSS
overrides in Markdown.vue no longer matched anything.

Pass fontSize/lineHeight/fontFamily/padding through codeBlockProps
monacoOptions (the only channel that reaches the shiki renderer),
retarget the dead overrides to code-block-shell-content and
code-action-btn, and hide the loading fallback's hardcoded line-number
gutter so the highlight upgrade no longer shifts layout.

* fix(web): keep code block metrics in sync

* fix(web): pin chat code font to 13px and align the loading fallback

Tying the code font size to the Appearance UI font size setting changed the
default rendering from the 13px design token to 14px and broke the 15/14/13
type scale; revert to the fixed token size. Keep the fallback ↔ settled
alignment: the restored monaco padding option feeds the fallback pre's
inline padding (12px, ignored by the shadow-root renderer), and a relative
1.65 line-height with !important beats the inline 1.5x default upstream
stamps on the fallback.

* chore(web): pin markstream-vue and its renderer stack to exact versions

The markstream family ships breaking rendering changes in patch releases
(1.0.8 swapped the code-block engine and renamed its DOM classes), so a
floating caret range hands merge control to upstream. Pin markstream-vue,
stream-diffs, stream-markdown and stream-monaco exactly — upgrades become
deliberate actions with a visual check, same posture as @chenglou/pretext
in the same file.
2026-07-31 19:14:02 +08:00
7Sageer
1f3f5dadaa
feat(agent-core-v2): interruption reminder for user-cancelled turns (#2400)
* feat(agent-core-v2): interruption reminder for user-cancelled turns

When the user interrupts a turn with Esc, append a durable
<system-reminder> (origin: injection/interruption) to the agent context
via a new loop aspect watching turn.ended, so the model learns the
previous turn was deliberately cut off. The marker persists to the
wire, replays on resume, stays hidden from transcripts, skips non-user
aborts and steer, and does not stack on repeated cancels.

Two supporting fixes:

- An aborted LLM stream now persists its accumulated partial
  text/thinking as content.part loop events instead of dropping every
  produced token; gated on the turn signal so retried or
  step-cancelled attempts keep their partial output out of the record.
- The turn.cancel wire op carries an optional reason
  ('user_cancelled' | 'aborted') so cold readers can tell deliberate
  interrupts from programmatic aborts. Goal-lifecycle cancels now pass
  an explicit programmatic reason to keep that field honest.

* feat(transcript): mark user-cancelled turns with an interruption marker

Project the deliberate user interrupt onto the transcript timeline: the
live projector emits an 'interruption' marker when a turn ends with
interruptReason 'user_cancelled', and the cold fold consumes the
persisted turn.cancel reason into the same marker. Programmatic aborts
keep surfacing through their own outlets (errors, goal/task state), and
queued cancels that left no visible residue are skipped.

* fix(agent-core-v2): make user-turn cancellation idempotent and reconcile interruption reminders on restore

* fix(transcript): dedupe user-cancelled interruption markers by turn in the cold fold

* chore(agent-core-v2): regenerate state manifest after merging main

* refactor(agent-core-v2): split interruptionReminder out of the loop domain

The loop domain owns turn execution mechanics; whether an interrupted turn
should produce a model-visible reminder is a model-context policy. Move it
into its own L4 domain with its own wire model that cross-reduces the
loop's turn.cancel fact, and rename the op to interruptionReminder.recorded.

---------

Signed-off-by: Haozhe <yanghaozhe@moonshot.ai>
Co-authored-by: Haozhe <yanghaozhe@moonshot.ai>
2026-07-31 18:17:14 +08:00
Rick
302b2cd680
fix(vscode): all AskUserQuestions should be answered and added to the context (#2326)
Co-authored-by: rickgao <rickgao@tencent.com>
Co-authored-by: qer <wbxl2000@outlook.com>
2026-07-31 17:40:12 +08:00
Haozhe
44d34bbd56
refactor(agent-core-v2): move host runtime args onto IBootstrapService (#2460)
* fix(agent-core-v2): resolve package self-references in check-import-boundaries

Imports spelled @moonshot-ai/agent-core-v2/<path> (the legal `./*` export
self-reference) were treated as external packages, letting kosong layer
violations through that spelling pass the checker.

* refactor(agent-core-v2): move host runtime args onto IBootstrapService

- Add HostArgs under BootstrapInput.args / IBootstrapService.args
  (agentFiles, skillDirs, requestHeaders, displayName, replyStyleGuide),
  mirroring VS Code's NativeParsedArgs on the environment service
- Remove the narrow per-domain runtime-options services and their seed
  functions: IAgentCatalogRuntimeOptions, ISkillCatalogRuntimeOptions,
  IHostIdentity
- Reduce IHostRequestHeaders to a pure kosong port contract and bridge it
  from bootstrap args via a new app/kosongConfig adapter, keeping kosong
  free of app-layer imports
- Pass host args through bootstrap() at the composition roots (kap-server,
  v2 print CLI, node-sdk) instead of seeding services
- Persist SDK provider removal as one atomic multi-section config replace

* fix(config): persist provider refresh updates atomically

- expose atomic multi-section config replacement through klient and SDK
- stage provider removals before one atomic write in TUI refresh
- briefly drain startup refresh during shutdown
2026-07-31 16:47:34 +08:00
7Sageer
52dfd155d8 feat(agent-core-v2): add spine_trim and spine_spawn experimental tools
spine_trim: model-driven tool-response trimming as a pure derivation over
the message stream. Tool results over 10 KiB (non-spine, text-only) carry
a byte-stable TRIM_ID tag; the model can snip or slice (head/tail/anchor)
the immediately preceding tool-result batch. Host validation shares the
single eligibility derivation with rendering; consumed, out-of-window, or
unknown ids reject with do-not-retry. Gated on KIMI_CODE_SPINE +
KIMI_CODE_SPINE_TRIM.

spine_spawn: fission the current node into >=2 concurrent forked branches
(lifecycle.fork plus trailing tool-call batch trim) and join their
terminal memories as closed child nodes synthesized from the structured
spine.spawn.result.v1 receipt in the message stream. All-or-nothing
capacity admission (default 4 threads including main, override via
KIMI_CODE_SPINE_SPAWN_MAX_THREADS), whole-batch abort on start failure,
guaranteed branch release. Gated on KIMI_CODE_SPINE + KIMI_CODE_SPINE_SPAWN.

Also adds legacyReplay regression coverage: five sanitized real old-session
wire logs restore with zero unknown-op skips, pinning op-replay vs
pure-derivation equivalence and the documented historical divergences
(receipt anchors, assembled memory bodies, undo witness erasure).
2026-07-31 16:27:38 +08:00
Haozhe
4c4df1bb05
feat(agent-core-v2): persist the terminal turn.ended wire record (#2457)
* feat(agent-core-v2): persist the terminal turn.ended wire record

- add a persisted turn.ended op (turnId, reason, error, durationMs)
  dispatched from the loop's runTurn finally block, alongside the event
- fold the record back in the transcript cold rebuild: terminal state
  (blocked folded into failed, mirroring the live wire edge), durationMs,
  error message and endedAt; journals without the record keep the
  grouping default
- restrict the test harness's snapshot waiters to emit entries so the
  same-named wire record no longer shadows the turn.ended event

* chore(agent-core-v2): stabilize unique-symbol keys in the state manifest

The checker names a unique symbol key __@name@NNNN, where NNNN is a
compilation-global counter that shifts with unrelated type additions and
churns the generated manifest. Render the stable __@name form instead.

* fix(transcript): map turn.ended around hidden turns in the cold fold

RetryStepRequest opens a real engine turn with origin 'retry' but
contributes no context messages, and a queued-then-cancelled
reservation consumes an engine id without starting. Both make engine
turn ids drift from the grouping ordinals, so matching turn.ended by
ordinal could stamp a later visible turn with the wrong terminal state.
Replay the loop's turn-clock records (turn.prompt / turn.cancel) and
map engine ids to ordinals past the hidden ids; the hidden turns' own
end records map nowhere and are dropped.
2026-07-31 16:25:43 +08:00
liruifengv
32d693f644
feat(tui): ask for workspace trust on startup with the v2 engine (#2453)
* feat(node-sdk): expose workspace trust state and trust grant on the v2 client

* feat(tui): ask for workspace trust on startup with the v2 engine
2026-07-31 14:21:04 +08:00
Haozhe
071d56940f
refactor(agent-core-v2): remove the L0-L7 domain layering and clean up comment conventions (#2451)
* refactor(agent-core-v2): move workspace-domain internals into internal/ dirs

- move sessionLifecycle/addressing into internal/
- move workspaceFs errors/fsProcess/fsSearch/rgLocator/runRg into internal/
- move workspaceMcpConfig/config-loader into internal/
- update import paths in services, index.ts, and tests

* docs(agent-core-v2): strip non-header comments, make headers file-local

- remove all symbol JSDoc and inline // and /* */ comments under src/;
  file-top header comments and directive comments (eslint, @ts-*) are kept
- rewrite file headers to describe only what the file itself does, dropping
  references to other files and see-X / lives-in / consumed-by relationships
- no code changes

* refactor(agent-core-v2): remove the L0-L7 domain layering and its lint guard

- replace check-domain-layers.mjs with check-import-boundaries.mjs,
  keeping only the v1-import ban and the kosong subtree rules
- rename the lint:domain package script to lint:imports
- drop the (Ln) layer label from every file-header identity line
- update AGENTS.md, package docs, and the agent-core-dev skill to match
2026-07-31 13:45:33 +08:00
Bowen Liang
e111c878fd
fix(web): unify permission mode order and risk colors across settings surfaces (#2125)
* web: reorder default permission options in Agent settings

Align the Agent settings default-permission segmented control with the
Composer toolbar order, arranging modes from safest (manual) to most
permissive (auto).

* web: reorder mobile permission cycle from safest to most permissive

The mobile settings sheet still cycled manual → auto → yolo, jumping from
the safest mode straight to the most permissive one on a single tap. Align
the tap-to-cycle order with the Composer menu and Agent settings
(manual → yolo → auto).

* web: align permission risk colors with the Composer's progression

Both the desktop status panel and the mobile settings sheet mapped
yolo → danger and auto → warning, the inverse of the Composer menu
(yolo → warning, auto → danger). Since auto is the most permissive
mode, it should carry the danger color everywhere.

---------

Co-authored-by: qer <wbxl2000@outlook.com>
2026-07-31 13:28:05 +08:00
7Sageer
95a656ca61
fix(agent-core): strip the no-op subagent model parameter while the secondary-model experiment is off (#2449)
The Agent/AgentSwarm tool schemas always advertised a \`model\` choice
parameter, so the secondary-model concept entered the prompt even with
the experiment disabled. Gate the advertised JSON schema on the flag in
both engines: off (the default) drops the parameter, on keeps it, and
spawn-time resolution already falls back to the caller's model either
way.

Also scrub ambient KIMI_CODE_EXPERIMENTAL_* env vars in both packages'
vitest setup so flag-dependent tool schemas in llm.tools_snapshot stay
deterministic regardless of the developer shell.
2026-07-31 13:09:56 +08:00
Haozhe
ed7a4cc095
feat(kap-server): add session-less POST /workspace/fs:search route (#2437)
* feat(kap-server): let fs:search resolve a workspace ref for draft sessions

- fs:search accepts a workspace id or absolute root in the session_id slot
  so the @ file mention works before the session exists
- kimi-web searchFiles falls back to the active workspace id in draft state

* fix(agent-core-v2): report empty thinking level for unbound main agent

- sessionLegacyService.status returns thinking_level '' when the main
  agent has no bound model (mirroring model: undefined), so clients
  fall back to the catalog default instead of folding in the wire
  model's 'off' zero value
- add regression test for a never-bound main agent status
- add web changesets: draft @ file mention, new-session thinking level

* perf(minidb): make text index rebuilds async and non-blocking

- TextIndex.build() yields to the event loop during tokenization and
  batches postings writes (~1 MiB), so large rebuilds no longer
  hard-block the host process
- writes landing mid-build are queued and replayed onto the new base at
  swap time, keeping the rebuilt index exact
- PostingsFile.rebuildSync renamed to async rebuild with a synchronous
  commit section (beforeRename hook + atomic rename)
- onCompacted hook is now awaited (sync or async); open-time compaction
  runs in the background so open() returns without blocking on the
  snapshot rewrite and postings rebuild
- compaction skips the postings rebuild when the index's write buffer is
  clean (needsRebuild)
- createTextIndex registers before building so concurrent writes feed
  the build queue; dropTextIndex throws while a build is in flight

* refactor(agent-core-v2): rename workspaceHandler to sessionLifecycle

- rename IWorkspaceHandlerService to ISessionLifecycleService and move
  src/workspace/workspaceHandler/ to src/workspace/sessionLifecycle/;
  update all consumers (gateway, sessionExport, sessionLegacy,
  sessionLookup, kap-server, klient, node-sdk, kimi-inspect, kimi-code)
- rename IStateService to IAppStateService and add the Workspace-scope
  IWorkspaceStateService, so the state domain spans all four scope tiers
- add cascading StateRegistry.inspect(): each tier injects the parent
  tier's registry and folds App to current scope into one StateInspection
  tree; check-domain-layers gains a Rule 2b exemption for state-on-state
  imports

* feat(kap-server): add session-less POST /workspace/fs:search route

Carry the workspace reference (registered id or absolute root) in the
request body and resolve it to the same Workspace-scope fs service the
session route uses, so clients no longer borrow the session route's
{session_id} slot. kimi-web's @ file mention now calls this route with
the workspace ref instead of a session id; the session-route fallback
stays for wire compatibility.

* refactor(agent-core-v2): register workspace-scope service state into IWorkspaceStateService

- move workspaceDirs / workspaceInstructions / workspaceSkillCatalog / workspaceTrust
  runtime state from bare instance fields into the workspace state container
- extend gen-state-manifest.mts to scan app/workspace scopes, emitting
  AppStateSnapshot / WorkspaceStateSnapshot alongside Session/Agent
- regenerate docs/state-manifest.d.ts and update AGENTS.md + agent-core-dev skill
- update affected tests to register the state services and assert the new state keys
2026-07-31 12:11:26 +08:00
liruifengv
bb2919eb81
fix(tui): reduce frequent full-screen redraws (#2442)
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-07-31 11:35:39 +08:00
Haozhe
17dfd49768
feat(agent-core-v2): introduce the Workspace domain and the agent-profile registry extension point (#2366)
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
* feat(agent-core-v2): insert Workspace lifecycle scope and remove mutable cwd paths

- Insert LifecycleScope.Workspace between App and Session
- Delete session/workspaceCommand domain (addAdditionalDir) and node-sdk RPC
- Remove profile cwd mutation; cwd is fixed at creation
- Make ISessionWorkspaceContext read-only; seed additionalDirs at creation
- Remove TUI and vscode /add-dir commands (to return workspace-scoped)

* feat(agent-core-v2): add Workspace scope with handler-owned session lifecycle

- Add IWorkspaceLifecycleService (App scope): handler registry,
  create-or-get handlerFor with inflight join
- Add workspace/workspaceContext seed and workspace/workspaceHandler
  (session create/resume/fork as handler child scopes)
- Delete App-level ISessionLifecycleService; callers compose
  index -> handlerFor -> handler via sessionLookup helpers
- Slim IBootstrapService; persistence addressing via handler chain
  (disk layout byte-identical)
- kap-server routes rewire internally; /api/v1 wire unchanged,
  debug surface gains workspace addressing
- Pin red line in domain lint: session/agent must not import
  workspace domains

* feat(agent-core-v2): collect workspace resources into the handler scope

- Add Workspace-scope catalogs for skills and agent profiles,
  instructions service, and a shared MCP connection manager
  (built at materialization, refreshed by watch/plugin events)
- Session catalogs keep their APIs but read seeded snapshots and
  refresh via change events; ISessionMcpService removed
- Session create options carry no mcpServers; MCP sources are
  config file (wins on name conflicts) and plugins only
- Agent profile/mcp consume the seeded providers

* feat(agent-core-v2): restore add-dir as a workspace-level capability

- Add workspace/workspaceDirs: shared additional-dir set with
  addDir({path, persist}); persist=true writes .kimi-code/local.toml,
  local.toml watch drives cross-process refresh
- ISessionWorkspaceContext becomes a live read view fed by the
  ISessionWorkspaceInfo seed contract and change events
- Restore Session.addAdditionalDir in kimi-code-sdk 1:1, mapping to
  the workspace service; restore TUI/vscode /add-dir verbatim

* feat(agent-core-v2): collect os-level services into the workspace scope

- Move fs service, fs watch (shared subscription fan-out), process
  runner, and a git facade to Workspace scope; sessionFs domain removed
- Add IWorkspaceToolPolicy with workspace veto wired through tool
  activation, execution guard, composed evaluation, and profile
  prompt projection; injected via ISessionToolPolicyGate seed
- kap-server fs routes and fs.watch bridge remap to the workspace
  services; wire unchanged

* refactor(agent-core-v2): clean up workspace-domain leftovers and docs

- Drop dead code: v2 mergeCallerMcpServers, the transitional
  ISessionContext.additionalDirs field, an unreachable guard
- Fix stale domain references in comments; correct test names
- Give the fs-watch refresh test a realistic wait budget under load
- Document the four-scope model and workspace domain in AGENTS.md,
  agent-core-v2 docs, and the agent-core-dev skill

* test(node-sdk): wait for the initial MCP connect to settle in the parity list test

v1 connects in the background after create resolves while v2 awaits it
inside create, so an immediate list can catch either side still pending
under CI load

* refactor(agent-core-v2): extract git work-tree discovery into the git domain

- add the pure findGitWorkTree probe in app/git/workTree and expose it
  as IGitService.findWorkTree
- switch the git permission policies off the local
  findLocalGitWorkTreeMarker helper to the DI service
- reuse findGitWorkTree for AGENTS.md project-root discovery in
  agent/profile/context.ts
- add findWorkTree coverage to gitService.test.ts

* feat(kimi-inspect): add Workspace Services view

- add WorkspaceServicesView rail view with a workspace picker on top;
  proxies resolve workspace-scope Services on the /workspace/:id route
- extend ChannelScope, ServiceTarget, and ServicePanelDef scope with
  'workspace', routed via client.workspace(id).service
- wire the new view into NavRail and App

* refactor(agent-core-v2): extract mcpCore and workspaceMcpConfig domains

- move the scope-agnostic MCP connection layer (stdio/http/sse clients,
  connection manager, oauth, config schema, tool naming) from agent/mcp
  to the new mcpCore domain
- move the [mcp] config section to app/mcpConfig and OAuth credential
  persistence to app/mcpConfig/oauthStore
- introduce the workspace/workspaceMcpConfig domain owning the effective
  MCP server set (mcp.json files + plugin contributions, refreshed by
  fs watch); workspaceMcp keeps pure connection orchestration
- update the plugin domain, session MCP handle, klient/node-sdk
  contracts, and tests accordingly

* refactor(agent-core-v2): remove the fault-injection experimental feature

- delete the faultInjection domain (flag definition, IFaultInjectionService
  contract, FaultInjectionService implementation)
- drop the requester-side take() injection point and the constructor
  dependency from llmRequester
- remove the flag-gated test cases and the IFlagService stub they needed
- regenerate the state manifest without the faultInjection state keys

* feat(agent-core-v2): gate project-level MCP config behind workspace trust

Add the Workspace-scope IWorkspaceTrust service: an explicit, per-workspace
trust marker persisted under the home (IAtomicDocumentStore, keyed by
encodeWorkDirKey(root)) so a checked-out tree cannot pre-trust itself.
While a workspace is untrusted, workspaceMcpConfig skips the project-level
.mcp.json and .kimi-code/mcp.json files (user-level config and plugin
contributions still load); a trust flip reuses the reload path, so project
servers connect on trust and disconnect on untrust.

Expose the state over kap-server REST: GET /workspaces/{id}/trust,
POST /workspaces/{id}/trust, POST /workspaces/{id}/untrust.

* feat(kimi-inspect): replace the workspace picker with a directory browser

The Workspace Services view now keeps a server-side directory browser in a
left sidebar (over IHostFolderBrowser) instead of a <select> of registered
workspaces. Entries that are registered workspaces carry a workspace badge
plus their IWorkspaceTrust trust state; selecting an unregistered folder
registers it on demand via IWorkspaceService.createOrTouch.

* fix(agent-core-v2): resolve the effective cwd into the profile binding

A default-bound agent recorded no cwd in its profile.bind payload, and no
caller configures ProfileServiceOptions.cwd, so the profile service's cwd
getter fell through to '' and refreshSystemPrompt() rebuilt the prompt
from the server process's cwd: an AGENTS.md edit dropped the workspace
instructions (or swapped in unrelated ones).

bind() now persists the resolved effective cwd (the input's, or the
session's when the input omits it) into profile.bind — the Model's cwd
stays creation-fixed and is always set. The getter's last resort is the
session's own cwd (the value legacy bindings resolved against) instead of
a bare ''.

* refactor(agent-core-v2): introduce the contribution/registry/catalog extension point for agent profiles

- App-scope IAgentProfileRegistry: any scope can register an
  AgentProfileContribution keyed by (sourceId, workspaceKey); dedup per
  source id, change events drive catalog re-projection
- workspaceAgentProfileLoader domain owns agent-file discovery end to end
  (parse / roots / SYSTEM.md / explicit runtime files) with five
  Workspace-scope loaders (workspace / user / plugin / extra / explicit)
  tagged with the handler's workspaceId; internals live under internal/
- SessionAgentProfileCatalog projects the registry directly (name dedup,
  priority adjudication, builtin override rule, inspect()); the
  workspace-catalog + sessionData seed relay is gone
- builtin code contributions register as the 'builtin' entry via
  BuiltinAgentProfileLoader; plugin agent roots are provided by the
  plugin domain as PluginAgentRoot
- remove cwd from the profile binding chain (BindAgentInput /
  ProfileBindingSnapshot / AgentConfigData / ProfileModelState /
  profile.bind op) — it is always the session's frozen cwd; legacy
  wire.jsonl records replay fine (the schema strips the field)
- share markdown frontmatter parsing via _base/text/frontmatter

* fix(agent-core-v2): reconcile the workspace refactor with main

- restore the branch's klient workspaceId scope extension lost to a
  file-level conflict resolution (main had no further changes there)
- stub the plugin system-prompt dependencies main added to the profile
  service in the profileOps / skillCatalog tests
- correct PLUGIN_SKILL_SOURCE_ID to the App skillSource domain (Agent
  scope must not import the Workspace domain)
- kap-server workspaceLayout test supplies the now-required hostIdentity
- regenerate wire/state/config manifests

* fix(agent-core-v2): export the agent-file parse primitives the v2 print CLI consumes

The internal/ split kept parseAgentFileText / resolveAgentPath off the
package entry, but apps/kimi-code's v2 print runner imports them from
@moonshot-ai/agent-core-v2 for --agent-file. Export the two symbols by
name; everything else under internal/ stays domain-private.

* feat(agent-core-v2): return cwd listing for empty fs:search query

An empty fs:search query used to fail request validation (query had a
minimum length of 1), so @-mention pickers had no starting set right
after typing "@". The workspace fs service now answers an empty query
with the workspace root's top-level entries — directories first,
hidden entries excluded, gitignore and exclude_globs honored — mapped
into the search-hit shape (score 1, empty match positions) and capped
by limit. The mirrored protocol wire schema is relaxed in sync.

* test: cover cron-fired steer context and titled session creation

- agent-core-v2: e2e asserting a cron-fired steer turn carries earlier
  tool results (the CronCreate job id) into the provider request
- klient: conformance case creating a titled session through implicit
  workspace materialization
2026-07-31 00:38:11 +08:00
qer
5c0ec2938a
fix(web): upgrade markstream-vue to 1.0.9-beta.1 and enable Monaco code highlighting (#2415)
* fix(web): upgrade markstream-vue to 1.0.9-beta.1 and enable Monaco code highlighting

* fix(nix): update pnpm deps hash for markstream-vue 1.0.9-beta.1
2026-07-30 20:01:57 +08:00
Haozhe
f1a3475ad5
fix(agent-core-v2): write refresh results in one atomic config transition (#2410)
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): write refresh results in one atomic config transition

- add IConfigService.replaceSections: applies several domains in a single
  state transition — one disk write, one effective rebuild, change events
  fire only after all domains took effect
- rework ProviderDiscoveryService to absorb the orchestrator's two-phase
  removeProvider/setConfig host contract into one replaceSections write, so
  the kosong registries never pass through a halfway-removed catalog
- stop writing the env-synthesized __kimi_env__ slice to config; the
  bridge's event-driven sync carries it into the registries on its own
- fixes sporadic "model is not configured" errors when starting kimi web,
  caused by the background refresh transiently clearing the model catalog
  while the first session was being created

* fix(agent-core-v2): stage replaceSections writes before mutating raw config

Validate and strip every domain into a staged copy of the raw/memory layer
first, then swap it in only after the whole batch succeeds — previously a
later domain failing validation left earlier domains already applied to
this.raw/this.memory while the call reported failure, exposing a partially
applied user layer to inspect() and future merges.
2026-07-30 18:42:20 +08:00
liruifengv
d8f455d694
docs(changelog): sync 0.31.0 from apps/kimi-code/CHANGELOG.md (#2404)
* docs(changelog): sync 0.31.0 from apps/kimi-code/CHANGELOG.md

* docs(changelog): polish 0.31.0 entries and note secondary model as experimental
2026-07-30 15:39:17 +08:00
qer
479403e701
chore(vscode): release 0.6.6 (#2401)
* chore(vscode): release 0.6.6

* chore(vscode): release 0.6.7

* chore(vscode): fold the sign-in wording fix into 0.6.6

* chore(vscode): backfill the 0.6.5 changelog entry
2026-07-30 15:33:19 +08:00
qer
0f3b106c42
fix(vscode): reword the sign-in waiting message to authentication (#2402) 2026-07-30 15:13:57 +08:00
liruifengv
ea81c9a3c5
feat(kap-server): expose the managed-account profile at GET /oauth/userinfo (#2363)
* feat(kap-server): expose the managed-account profile at GET /oauth/userinfo

* refactor(oauth): serve the userinfo profile as the camelCase domain type end to end

* style(agent-core-v2): drop the method-local comment on getManagedUserInfo

* chore: drop the userinfo endpoint changeset

* test(kap-server): pass the required host identity in the userinfo route test
2026-07-30 15:05:55 +08:00
github-actions[bot]
bc28e9d802
ci: release packages (#2342)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-30 14:56:30 +08:00
qer
6d0a046488
fix(vscode): keep sign-in reachable from the no-models screen (#2393)
* fix(vscode): keep sign-in reachable from the no-models screen

* fix(vscode): stop flagging bundled this.require(...) calls as VSIX runtime dependencies
2026-07-30 14:47:37 +08:00
Haozhe
d36f4c58f6
refactor(agent-core-v2): remove the fault-injection experimental feature (#2399)
- delete the faultInjection domain (IFaultInjectionService, its Agent-scope
  implementation, and the fault-injection experimental flag)
- drop the llmRequester's per-attempt fault consumption point and the
  faultToError helper
- remove the fault-injection test cases and DI wiring from the requester
  service tests, and the domain's layer-registry entry
- regenerate the state manifest without the faultInjection.* state keys
2026-07-30 14:45:31 +08:00
Haozhe
d10b1c1308
fix(agent-core-v2): treat cache entries missing required fields as cold misses (#2395)
* fix(agent-core-v2): treat cache entries missing required fields as cold misses

- normalize `archived` to a boolean when mirroring session metadata to the
  read model, so entries for pre-`archived` sessions no longer lose the key
  during JSON serialization
- add a runtime shape check on read-model cache hits; entries missing
  required fields are rebuilt from disk and overwritten, self-healing
  poisoned entries written before the fix
- log a warning when the TUI session picker fails to fetch sessions instead
  of silently showing "No sessions found."

* chore: add changeset for session index cold-miss fix
2026-07-30 14:28:28 +08:00
liruifengv
40172c7ca9
feat: unify the host identity across OAuth, telemetry, and kap-server (#2382)
* refactor(oauth): make X-Msh-Platform an explicit host identity field

X-Msh-Platform was hardcoded to kimi_code_cli in createKimiDeviceHeaders,
so non-CLI hosts could not state their own platform and the desktop had
to patch the header after the fact. KimiHostIdentity now carries a
required platform (every host declares its own value; the CLI constant
stays the fallback only for direct createKimiDeviceHeaders callers), and
userAgentProduct is renamed to productName so the transport identity
uses one name everywhere.

All in-repo identity constructions pass platform explicitly; the wire
value for CLI and VS Code hosts is unchanged (kimi_code_cli).

* feat(agent-core-v2): carry the host identity in the bootstrap snapshot

Replace the flat clientVersion field with a required clientIdentity
(KimiHostIdentity) so every consumer reads the same host identity
object: OAuthToolkitService now passes it to the OAuth toolkit, which
means the OAuth device-flow endpoints (device authorization, token
polling, refresh) on the kap-server path finally send the full X-Msh-*
device headers instead of none, and the telemetry cloud appender reads
client_version from the same source. A built-in CLI fallback keeps bare
bootstrap() calls in tests working; composition roots must pass their
own identity.

The session export manifest grows an optional desktopVersion field
(payload plumbed through; filled by kap-server in a follow-up).

* feat(agent-core): thread the host identity into the managed auth facades

The v1 managed auth facade constructed its OAuth toolkit without an
identity, so token refreshes from inside the core went out without any
X-Msh-* device headers. createManagedAuthFacade now takes an optional
KimiHostIdentity and every call site supplies one:
CoreProcessService._defaultOAuthTokenResolver forwards the core
process's options.identity (the same source _defaultKimiRequestHeaders
uses), and the DI-held services (oauth / auth summary / model catalog)
read it from a new optional identity field on IEnvironmentService. The
library-level "no identity, no device headers" contract is unchanged.

* feat(kap-server)!: require the host identity and derive request headers from it

ServerStartOptions.hostIdentity is now a required ServerHostIdentity
(KimiHostIdentity + optional prompt display fields), replacing both the
old optional HostIdentityOverrides (renamed to PromptIdentityOverrides,
its productName field now displayName) and the version option (renamed
to serverVersion — it is the engine version reported as server_version,
while the host product version travels in hostIdentity.version).

The server now feeds bootstrap's clientIdentity from hostIdentity and
derives the default outbound headers (User-Agent + X-Msh-*) from it via
createKimiDefaultHeaders, so kap-server-hosted OAuth flows and model /
WebSearch requests carry the real host identity instead of a hardcoded
kimi-code-cli fallback UA. Explicit header seeds still win as an escape
hatch.

Session export manifests record the host product version: kimiCodeVersion
now carries hostIdentity.version (the engine version no longer appears),
and desktop exports (desktop: true) are additionally stamped with a
desktopVersion field. The instance registry keeps its host_version wire
field for compatibility (kimi-inspect reads it); only the in-memory name
changed to serverVersion.

* feat(cli): wire the CLI host identity into the kimi web server

kimi web now passes createKimiCodeHostIdentity(version) as the server's
hostIdentity, so web-UI OAuth flows and the engine's outbound requests
carry the explicit CLI identity (productName + version + platform). The
explicit hostRequestHeadersSeed is dropped — kap-server derives the same
headers from hostIdentity — and buildKimiDefaultHeaders goes away with
its only consumer.

* test(klient): drop clientVersion from the bootstrap contract parity list

* chore: add changesets for the host identity unification

* feat(cli): tag kimi web requests with a (web) User-Agent suffix

kimi web shares the CLI product token and platform, so its outbound
requests were indistinguishable from direct CLI runs upstream. Its host
identity now carries userAgentSuffix 'web', putting web-UI traffic at
kimi-code-cli/<version> (web) while X-Msh-Platform stays kimi_code_cli.

* fix(klient): keep the env() clientVersion wire field after the bootstrap identity switch

The bootstrap snapshot replaced the flat clientVersion scalar with
clientIdentity, which broke klient's env() fan-out (RPCError: method not
found). The wire surface keeps clientVersion — now sourced from
clientIdentity.version — and bootstrapService gains a clientIdentity
read (registered in envContract with an object schema) for consumers
that want the full identity.

* feat(oauth): send the product User-Agent on OAuth requests

The OAuth endpoints used to receive only the X-Msh-* device headers
(undici's default UA otherwise), which left the OAuth host unable to
distinguish runtime surfaces — notably kimi web, whose platform matches
the CLI and whose only distinguishing mark is the (web) UA suffix. The
toolkit now feeds the full identity headers (User-Agent + X-Msh-*) into
every device authorization, token polling, and refresh request; the
request-header type widens from DeviceHeaders to OAuthRequestHeaders.

* feat(vscode): report kimi_code_vscode as the extension's platform

The VS Code extension inherited the CLI's hardcoded X-Msh-Platform value;
with platform now an explicit identity field it declares its own, so the
managed endpoints and OAuth host can tell extension traffic apart from
CLI runs.

* refactor(agent-core-v2)!: require the client identity at the composition root

The bootstrap fallback identity fabricated a kimi-code-cli/unknown host
for any caller that forgot to pass one — the same silent-misreport
pattern this series set out to remove, and it made "required" a lie.
BootstrapInput.clientIdentity is now required, so a missing identity
fails at compile time instead of being papered over. Test and example
callers pass a shared fixture (klient examples and test engines get one
each); the node-sdk v2 client asserts its host identity with the oauth
helper. Also folds DeviceHeaders from an interface into a type alias so
it stays assignable to the widened OAuthRequestHeaders record.

* feat(oauth)!: require and validate the platform in device headers

Drops the quiet CLI fallback in createKimiDeviceHeaders (the same
silent-misreport pattern removed from the bootstrap identity): platform
is now a required option, validated with the same required-ASCII rule as
the version — empty or all-non-ASCII values throw instead of emitting a
blank X-Msh-Platform, and header-unsafe characters are stripped rather
than sent raw.

* fix(node-sdk): seed the host request headers on the v2 client path

The interactive v2 engine path (experimental flag) bootstrapped without
a hostRequestHeaders seed, so managed vendor calls went out with the
SDK's default User-Agent (OpenAI/JS) and no X-Msh-* at all — v1 passes
the full identity headers on the same requests. The v2 client now seeds
the headers from its asserted host identity, and a test pins the seed.

* chore: simplify the CLI changeset wording
2026-07-30 13:45:41 +08:00
Kai
691ec4679e
fix: remove the blocking wait from the TaskOutput tool (#2379)
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: remove the blocking wait from the TaskOutput tool

The block/timeout parameters let a model stall the whole turn waiting
for a background task (up to 3600s), even though completion already
arrives via automatic notification. Remove both parameters from the v1
and v2 engines (kept in model-facing parity), simplify retrieval_status
to success/not_ready, and update the tool, Bash, and Agent prompt
wording plus user docs accordingly. Stale callers passing block are
silently treated as a non-blocking snapshot.

* fix: align background-task prompts with the non-blocking TaskOutput

The compaction reminder promised TaskOutput could fetch a task's result
for tasks that are still running, where it now returns not_ready —
reword it to snapshot semantics and point at the completion
notification. Also list AskUserQuestion(background=true) as a task
source in the TaskOutput description.

* test: exercise stale TaskOutput args through the runtime validator

A stale block/timeout argument never reaches the tool: the executor's
preflight validates args against the closed tool schema and rejects
them immediately, so the old test documented silent-tolerance semantics
the runtime never exhibits. Assert the real behavior through
compileToolArgsValidator/validateToolArgs instead, and drop
statement-adjacent comments to match the package's header-only comment
convention.
2026-07-30 01:26:56 +08:00
7Sageer
fa2c5ce18b
feat: support plugin-contributed custom agents (#2365)
* feat: support plugin-contributed custom agents

* fix: await plugin loading before agent catalog

* fix: refresh plugin agents on v1 reload

* test(agent-core-v2): add enabledSystemPrompts to the plugin service stub
2026-07-29 21:59:48 +08:00
7Sageer
1896d1a13a
Revert "fix(kosong): match Kimi's standalone "Unsupported image." rejection (…" (#2368)
This reverts commit dbb69a2678.
2026-07-29 20:56:41 +08:00
7Sageer
02d77b20d9
feat(agent-core-v2): let plugins contribute system prompt instructions via the manifest systemPrompt field (#2314)
* feat(agent-core-v2): let plugins contribute system prompt instructions via the manifest systemPrompt field

* feat(agent-core-v2): add systemPromptPath to load plugin system prompt from a file

* docs: explain plugin system prompt templates

* fix(agent-core-v2): refresh plugin system prompts after changes

* fix(agent-core-v2): freeze restored profile bindings and converge plugin contributions at session scope

- restore no longer re-renders or re-persists prompts: a resumed agent
  keeps its replayed profile binding (prompt and tool set) as persisted
- a new Session-level convergence point reloads plugin skills into the
  session skill catalog before fanning out to every live agent prompt,
  and every catalog-kind plugin mutation awaits the whole pipeline;
  MCP-only toggles carry a distinct change kind and skip it
- live refreshes after a restart re-resolve the bound profile by name
  and rebind the full slice (prompt, disallowed tools, active tools)
  atomically, warning and keeping the persisted state when the profile
  is gone; renders reuse the first-render timestamp and unchanged
  prompts are not re-persisted, so convergence never churns the wire
- cap plugin system-prompt contributions (32 KB per field/file, 64 KB
  aggregate per prompt build) with manifest diagnostics and warnings
- bump the changeset to minor: this is a new user-facing capability

* fix(agent-core-v2): register the new session domain and dedupe the missing-profile warning

- add sessionPluginContribution to the domain-layer registry so
  lint:domain stays green
- emit system-prompt-refresh-profile-missing once per profile name,
  matching the service's other deduped warnings
- document the convergence timeout escape hatch and the klient
  exclusion of enabledSystemPrompts

* fix(agent-core-v2): dedupe the plugin budget warning and surface section read failures

- emit plugin-sections-oversized once per skipped-plugin signature
- let enabledSystemPrompts failures propagate to the refresh catch
  (keeps the current prompt and warns) instead of silently rendering
  and persisting a prompt without plugin instructions
- cover the convergence timeout cut-off with a fake-timers test
- clarify that the first-render timestamp anchors per process

* fix(agent-core-v2): serialize session convergence and restore onDidReload timing

- run at most one convergence per session and bound each change's wait
  by the timeout, so a fan-out emitter never interleaves deliveries
  after a timed-out convergence
- fire onDidReload as soon as the reload commits again, keeping hook
  reloads independent of prompt convergence
- sign the plugin budget warning with an unambiguous key

* docs(agent-core-v2): align convergence wording with the serialized semantics

- the timeout retry promise only holds once stalled work clears
- note the per-session serial delivery cost model on the plugin change
  contract and the dual-queue invariant on the service

* fix(agent-core-v2): keep empty plugin sections byte-neutral in the prompt template

- place ${plugin_sections} on the same template line as
  ${skills_section} so prompts without either block render exactly as
  before this feature
- note on the change contract that waitUntil work must not call back
  into plugin mutations, and spell out the per-session convergence
  order in the user docs

* fix(agent-core-v2): pin a fork's profile so refresh triggers never rebind it

- applyBindingSnapshot left the fork with no pinned profile, which
  routed in-process forks into the post-restart catalog rebind and
  could reset an inherited tool set; forks now inherit the source
  agent's pinned profile object
- pin the first-render timestamp reuse with a ${now}-embedding test
  and document the anchored ${now} semantics
- tighten the plugin docs budget and resume-refresh wording

* fix(agent-core-v2): join in-flight convergence during agent bootstrap

- an agent created while a plugin convergence is in flight now waits
  for it, and a restored agent refreshes once after it, so a plugin
  mutation never straddles an agent's bootstrap
- warn on a non-string systemPrompt field and strip a UTF-8 BOM from
  systemPromptPath files before trimming
- correct the consumption-surface wording (every CLI surface on the
  experimental flag, not just kimi -p), the per-session queueing note,
  and the single-plugin combined budget clause

* fix(agent-core-v2): bound the bootstrap convergence join by the timeout

A permanently wedged convergence kept convergeTail pending forever,
and the unconditional settled() wait in bindBootstrap would have
blocked every later agent creation in that session; the join now
races the shared convergence timeout and continues (a restored agent
still refreshes once, which never touches the tail), and the timeout
constant moves to the contract for reuse

* fix(agent-core-v2): close the convergence race against in-progress restores

- a convergence fan-out could land while an agent's wire log is still
  replaying, dispatching a replay-visible config record whose effect
  the rest of the replay then overwrites; refreshSystemPrompt now
  skips while the wire restore is in progress
- convergence completion is tracked by a generation counter; bootstrap
  compares it (after a bounded join) and refreshes a restored agent
  exactly once when a round completed after its creation began,
  replacing the wasConverging flag that could miss both windows

* fix(agent-core-v2): bound each convergence so a wedged participant cannot stop the pipeline

- the fan-out now races the convergence timeout, so convergeTail always
  settles: a permanently hung refresh delays its round (blocked entries
  drain oldest-first on later changes) instead of killing the session's
  convergence for good
- warn when agent bootstrap stops waiting on a stalled convergence
- diagnose a blank systemPromptPath and pin the plugin-root escape
  guard with traversal, absolute-path, and symlink tests

* fix(agent-core-v2): bound the skill reload, preserve user-tool overlays, roll the prompt clock daily

- the convergence's skill-reload segment now races the same timeout as
  the fan-out, so no segment of the pipeline can wedge a session for
  good; it continues with the previous catalog and retries next change
- a cold rebind that resets the tool set replays session-added user
  tools onto the new base instead of dropping them for the rest of the
  process
- the rendered timestamp re-anchors when the UTC date rolls over, so
  long-lived processes keep a fresh clock while steady-state renders
  stay byte-stable within a day
- the plugin budget warning dedupes per plugin id, and the docs note
  that systemPromptPath content is frozen until the next reload

* feat(agent-core-v2): converge cold plugin changes on resume through a drift-free gate

- restore replays the persisted binding untouched, then bootstrap
  refreshes only when drift-free inputs changed while the session was
  cold: the catalog profile's tool set/denylist, or the plugin-sections
  baseline persisted alongside the prompt on the existing bind/update
  payloads; directory-listing and date drift wait for live triggers,
  so quiet resumes append no replay-visible records
- the rendered timestamp is day-precision (UTC date at 00:00,
  re-anchored on rollover), keeping steady-state renders byte-stable
  across resumes and sessions on the same day
- consolidate both timeout helpers onto a shared raceOutcome, and drop
  the generation counter the gate supersedes
- align the plugin-sections precedence prose with the AGENTS.md
  disclaimer (no self-granted authority, system instructions win on
  conflict)

* fix(agent-core-v2): bound the restored-prompt gate and land the sections baseline

- the gate's plugin-sections read now races the convergence timeout, so
  agent creation never blocks behind an unrelated plugin mutation
- refreshes serialize per agent through a tail, so overlapping triggers
  cannot write prompts out of order
- when plugin sections change but a plugin-free custom prompt does not,
  the new baseline lands as a sections-only update instead of making
  every later resume re-render in vain
- align the system prompt's Date and Time paragraph with the
  day-precision anchored timestamp

* Update plugin system-prompt instructions in changeset

Live sessions pick up plugin changes, while the default TUI and `kimi -p` paths ignore these fields.

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

* refactor(agent-core-v2): keep plugin skill reload user-driven

Plugin mutations still converge live agent prompts, but the session
skill catalog goes back to refreshing only on explicit plugin reload,
as before: the prompt feature does not need skill convergence, and the
pre-existing manual-reload semantics stay uniform across all plugin
contributions. Removes the convergence-driven skill reload, the
reloadSource de-privatization, and their tests; restores the
PluginSkillSource onDidReload forwarding and its catalog tests.

* refactor(agent-core-v2): apply plugin system-prompt changes only on explicit reload

Drop the live convergence machinery (the plugin onDidChange barrier,
the sessionPluginContribution fan-out, the restored-prompt drift gate,
and the day-precision render clock) so plugin system-prompt sections
take effect at the same point as every other plugin contribution:
/plugins reload or a new session. The profile now refreshes when the
session skill catalog re-pulls its plugin source on reload, reading
both the skill list and the prompt sections fresh.

* feat(agent-core): let plugins contribute system prompt instructions via the manifest systemPrompt field

* chore(agent-core-v2): remove inline implementation comment

* docs: clarify plugin prompt refresh semantics

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-07-29 20:30:07 +08:00
STAR-QUAKE
dbb69a2678
fix(kosong): match Kimi's standalone "Unsupported image." rejection (#2362)
Some checks are pending
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
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
isImageFormatError missed the production phrasing "Unsupported image.
Please try another one." — the existing pattern requires a url/format/
type suffix, so the deterministic image rejection never triggered the
media-stripped resend, and the session failed on every later request.

Add a standalone-sentence pattern (punctuation- or end-terminated) to
both the kosong and agent-core-v2 classifiers, keeping the deliberate
boundary that count/size phrasings must not match.

Co-authored-by: fengchenchen <fengchenchen@moonshot.ai>
2026-07-29 18:54:07 +08:00
wenhua020201-arch
f8ec3d1656
docs: fix dead anchor links in en/zh docs (#2348)
* docs: fix dead anchor links in en/zh docs

- #loop_control -> #loop-control (heading slug uses hyphens)
- #secondary_model -> #secondary-model
- env-vars model section anchors: kimi_model -> kimi-model
- provider credential section anchors: configtoml -> config-toml
- /provider management anchors: point at the renamed heading in each locale
- hooks: point the stale config-files#hooks reference at the local Configuration section
- en files: replace two leftover Chinese anchors with their English targets

* docs: add missing .md extension to themes page links

---------

Co-authored-by: qer <wbxl2000@outlook.com>
2026-07-29 15:57:48 +08:00
7Sageer
b850c5f8f5
fix(node-sdk): wire applyPersistedSecondaryModel to agent-core-v2 (#2345)
* test(node-sdk): drop v1-only subagentNames from the resume parity projection

Custom agent files made v1's resumed agent config carry the bound
profile's delegatable subagent roster; v2's resumed agent state has no
equivalent field, so the resume parity cases fail on main. Project the
engine-owned field away instead of pinning it as a resume-data gap.

* fix(node-sdk): wire applyPersistedSecondaryModel to agent-core-v2

On the v2 engine route the /secondary_model command persisted the recipe
but failed to apply it to the current session: the SDK method fell
through to the base class's not_implemented getRpc().

v1 pushes a reloaded config snapshot into the session because its spawn
binding, tool descriptions, and cached startup warning all read that
snapshot. agent-core-v2 resolves the secondary model live against
IConfigService at spawn time and rebuilds the tool description per read,
so the setConfig write already takes effect session-wide. The override
keeps the rest of v1's contract: config reload, the same loud
validations (session lookup, persist-first recipe check, pointed-model
resolution wrapped at [secondary_model].model), and a warning-cache
refresh via a new recheckSecondaryModelWarning on the session warning
service. getSessionWarnings also surfaces the v2 secondary-model warning
next to the AGENTS.md one, matching v1's aggregate.

* fix(agent-core-v2): surface the subagent's bound model on status events

The v2 model slice rides only the bind-time agent.status.updated, which
precedes subagent.spawned and is dropped by clients that key child events
off the spawn, so subagent cards never learned the model — and a
single-step run emits no usage/context slice until it ends, so the model
only appeared at completion. Re-affirm the binding right after the spawn
announcement via a new IAgentProfileService.republishStatus, and fold a
consistent usage/context/model snapshot into every status event at both
v1 edges (kap-server's broadcaster and the in-process SDK session
wiring, resolving the secondary-model derived id to a readable display
name.
EOF
)

* Delete .changeset/subagent-card-model.md

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

* style(agent-core-v2): remove inline implementation comments

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-07-29 15:40:42 +08:00
liruifengv
37d9bdc585
docs(changelog): sync 0.30.0 from apps/kimi-code/CHANGELOG.md (#2343) 2026-07-29 12:13:20 +08:00
7Sageer
efac96c8a9
feat(agent-core): custom agent files and secondary model on the v1 engine (#2232)
* feat(agent-core): custom agent files and secondary model on the v1 engine

Migrate the custom agentfile and secondary-model capabilities from
agent-core-v2 to the v1 engine so they work in the TUI and plain
kimi -p sessions:

- discover Markdown agent files from user/project/extra/explicit
  directories with the v2 precedence rules, a merged session profile
  catalog replacing the hardcoded builtin profile lookups, SYSTEM.md
  main prompt override, and ${base_prompt} backed by the effective
  default
- --agent/--agent-file now work in print mode on the default engine;
  CreateSessionOptions gains agentProfile/agentFiles
- [secondary_model] config + KIMI_SECONDARY_MODEL/EFFORT bind newly
  spawned subagents to a cheaper model behind the secondary-model
  experiment flag, with primary/secondary model params on Agent and
  AgentSwarm and upfront session warnings
- full disallowedTools deny semantics (exact names + mcp__ globs)
  evaluated by the tool manager and persisted in the agent wire

* fix(cli): guard optional agentFiles in the prompt runner

runPrompt is also driven programmatically (headless goal flow) with
options that never pass through the CLI parser defaults, so agentFiles
can be undefined; mirror the addDirs optional-chaining pattern. Also
extend the SDK experimental-feature assertion with the secondary-model
flag.

* fix(agent-core): preserve custom agent bindings on v1

* fix(agent-core): narrow secondary model error hints

* fix(agent-core): persist custom agent profile bindings

* Delete .changeset/sdk-agent-profile-options.md

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

* Update v1-custom-agent-files.md

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

* Update v1-secondary-model.md

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

* Update v1-custom-agent-files.md

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

* fix(agent-core): keep SYSTEM.md a prompt-only overlay for delegation

* docs: update agent file and secondary model availability wording

* fix(cli): reject --agent-file combined with session resume

The resume path only forwards the agent file's name for the bound-profile
assertion; the file's content is never re-applied (the session keeps its
creation-time catalog snapshot). Previously the combination was silently
accepted, so an edited file (or a same-named one) appeared to apply but did
not. Reject it at option validation and document the constraint.

* refactor(agent-core): share prompt-section prose and note v2 twins in agentfile headers

The Windows notes, additional-dirs and skills prose blocks existed twice:
inline in the builtin default template (system.md) and as constants in the
agent-file renderer (from-file.ts). Extract them to profile/prompt-sections.ts
as the single source: system.md renders them through injected KIMI_* template
variables and from-file.ts imports the same constants. Rendered prompts are
byte-identical for all four builtin profiles across macOS/Windows and
skills/dirs on/off; a new test pins system.md to the shared constants.

Also mark each profile/agentfile file with the path of its agent-core-v2
counterpart so format/semantics changes land in both engines.

* feat(cli): add /secondary_model command for the subagent model

Mirror /model: a picker with a thinking-effort step that persists [secondary_model] and live-applies to the current session via a new Session.setSecondaryModel RPC (node-sdk wrapper included), so newly spawned subagents bind the new model right away. The /model picker now hides the synthesized __secondary__ derived entry; docs and the update-config builtin skill mention the section.

* feat(tui): show the bound model in subagent run stats

Subagents report their model alias via agent.status.updated after spawn; resolve it to a display name and surface it in tool-call subagent stats and agent-group rows.

* fix(agent-core): validate agent profile before session persistence

* fix(agent-core): refresh subagent tools after model switch

* fix(agent-core): show subagent model preferences

* fix(agent-core): preserve secondary model recipe on live apply

* fix(agent-core): make secondary model apply explicit

* fix(tui): refresh secondary model display state

* chore: merge secondary model changesets into one

* Add /secondary_model command for subagent configuration

Show each subagent's model in the subagent card header and agent-group rows. Requires the secondary-model experiment (KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=1); run /secondary_model to pick a model and thinking effort, applied to the current session immediately.

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

* fix(agent-core): align explicit agent file precedence

* fix(agent-core): let disallowedTools deny select_tools

* chore(cli): drop engine mention from --agent/--agent-file help text

* feat(cli): support --agent/--agent-file in the interactive TUI

Bind the selected agent profile to the startup session when launching
the TUI with --agent/--agent-file, including the session created after
an OAuth login at startup. Sessions created later in the process (/new)
keep the default profile.

Make both flags creation-only in every mode: combining them with
--session/--continue is now rejected in print mode too, since resume
restores the bound agent from the session automatically.

* fix(agent-core): persist new secondary-model selections under env overrides

stripSecondaryModelConfig restored secondary_model.model/default_effort
from raw whenever KIMI_SECONDARY_MODEL/KIMI_SECONDARY_EFFORT was set, so
a /secondary_model pick made under the env vars was silently discarded
on write. Restore from raw only when the value being written still
equals the env value (an overlay round-trip), mirroring the pointer
check in stripEnvModelConfig; a genuinely different selection now
reaches config.toml.

* fix(cli): report the effective secondary model when env overrides the pick

/secondary_model toasted the picked alias even when
KIMI_SECONDARY_MODEL/KIMI_SECONDARY_EFFORT made the session bind a
different model. Read the effective binding back from the reloaded
config (as /model does from session status) and warn with the
env-overridden values instead.

* feat(tui): show the bound model name in the AgentSwarm panel header

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-07-29 12:06:26 +08:00
github-actions[bot]
16c7189bd5
ci: release packages (#2244)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-29 11:35:59 +08:00