* fix(pi-tui): stop GFM autolinks at CJK punctuation boundaries
marked's GFM autolink accepts any non-space characters after the domain
and its backpedal strips only ASCII trailing punctuation, so CJK or
full-width punctuation right after a bare URL was absorbed into the link
text and href (`.../pull/232(本地` rendered as one anchor whose OSC 8
target contained raw CJK and opened a broken address).
Register a CjkBoundaryUrlTokenizer (subclass of the upstream
StrictStrikethroughTokenizer, which stays byte-identical for
re-vendoring) that cuts the autolink match at the first CJK punctuation
character before the ASCII backpedal. CJK ideographs inside the URL path
itself are preserved. Guarded by new bare-URL CJK cases in
test/markdown.test.ts and listed in pi-tui's local-divergence inventory.
* fix(pi-tui): keep balanced full-width parens inside autolinked URLs
Address review feedback on the CJK autolink boundary: cutting at the
first full-width parenthesis anywhere in the match also truncated URLs
that legitimately contain balanced full-width parens in their path
(e.g. wiki disambiguation pages like .../wiki/中华人民共和国(1949年)).
Full-width parens now follow GFM's ASCII-paren rule: a paren-depth scan
keeps balanced pairs in the URL and only an unbalanced ( or )
terminates the match. Non-paren CJK punctuation still always terminates
it.
* fix(pi-tui): keep CJK punctuation inside balanced full-width parens
Punctuation inside a balanced full-width parenthetical is deliberate URL
content (e.g. .../wiki/中华人民共和国(北京,1949年)), so the non-paren
CJK terminator now only applies at paren depth 0. Prose parentheticals
contain spaces and never survive marked's match this far, and an
unbalanced ( still cuts the match at the open paren.
The extension now runs on the agent-core-v2 engine by default. The
interface, sessions, and workflows do not change. Two rollback paths
exist, and one function makes the decision
(config/vscode-settings.ts):
- the kimi.useAgentCoreV1 setting (temporary; a window reload applies
the change);
- the KIMI_CODE_LEGACY_FLAG environment variable, which wins over the
setting and has the same semantics as in the CLI.
An engine startup failure shows an explicit error that names the
rollback setting. There is no silent fallback. CI runs the extension
test suite on both engines: the sharded run covers the default v2
engine, and a new test-vscode-legacy job reruns the suite with
KIMI_CODE_LEGACY_FLAG=1.
To keep the v2 path identical to v1 for every method the extension
uses, this change also completes the v2-backed SDK client and the v2
engine:
- Implement session deletion in the v2 SDK client.
- Implement fork truncation at a turn index in the v2 engine, with the
same rules as v1, and reject a fork while the source session has an
active turn.
- Stop the session-level /init run when the turn is cancelled, as v1
does.
- Read session metadata without the archived field as not-archived, so
sessions written by the v1 engine open correctly.
The SDK parity suite now covers session deletion, cancel, and fork
truncation. The known-difference list for the methods the extension
uses is empty.
* fix(agent-core-v2): mint interaction ids engine-side
Self-hosted OpenAI-compatible endpoints may renumber tool call ids on
every response (Bash_0, Bash_1, ...). The approval/question/user_tool
facades used the provider toolCallId as the interaction id, so a
repeated id was silently swallowed by client-side pending-interaction
dedupe: the approval prompt never appeared and the turn parked
forever (#2908).
Interaction ids are now minted by the engine (approval_<uuid> /
question_<uuid> / user_tool_<uuid>); the provider toolCallId stays on
the payload for correlation. This matches v1 semantics, where the
approval id was already a daemon-minted id independent of the tool
call id.
* fix(agent-core-v2): normalize duplicate provider tool call ids at ingestion
Self-hosted OpenAI-compatible endpoints may renumber tool call ids on
every response (Bash_0, Bash_1, ...), and every downstream keying
assumes an id identifies exactly one call: context rebuild silently
drops the second tool result with a duplicated id, the strict
projector discards duplicate calls, transcript frames merge, and
approval/activity correlation misfires.
A per-agent ToolCallIdNormalizer in the llmRequester stream boundary
now tracks ids already claimed (seeded from the restored context).
The first occurrence passes through unchanged; later occurrences —
across responses or within one — are rewritten to a readable
<id>__<n> suffix, kept consistent between streamed deltas and the
finalized message, and logged for provenance. A failed attempt rolls
its claims back so a projection retry re-streams the same logical
calls under the same ids.
* fix(agent-core-v2): thread the minted approval id through events and status
The permission.approval.requested/resolved events only carried the
provider toolCallId, so AgentActivityView exposed approvalId =
toolCallId and the agent.status.updated approval phase forwarded an id
that POST /sessions/{sid}/approvals/{id} cannot resolve — the kernel
parks under the minted approval_<uuid>.
Mint the interaction id at the agent call site and include it in the
approval request payload: the kernel honors the explicit id, the
events carry it, and the activity view keys pendingApprovals by it
(falling back to the toolCallId for id-less events).
* fix(agent-core-v2): surface minted interaction ids in facade listPending
The approval/question facades returned only the original payload from
listPending(), so once the kernel id stopped deriving from the
provider toolCallId, hosts listing pending requests had no id to feed
back into decide()/answer()/dismiss() without reaching into the
kernel. Merge the parked interaction id into each returned request —
the klient contract schemas already carry the optional id field, so
the RPC surface becomes round-trippable as well.
* fix(tui): keep banner main text readable with long tags on narrow terminals
The banner layout inlines the tag and wraps the main text into the
remaining width. Remote banner configs can set a full-sentence tag
(e.g. the 38-char K3 thinking-effort banner), which on narrow terminals
leaves the main text only a few columns, so it wraps into a ragged,
hard-broken column ("balan/ce", "capab/ility").
When the inline tag would leave the main text fewer than 16 columns,
render the tag on its own line and give the main text and subtext the
full width, aligned with the tag text. Short tags stay inline; tags
wider than the terminal are still dropped as before.
* chore: add changeset for banner narrow-terminal fix
---------
Co-authored-by: Mira <mira-bot@moonshot.cn>
* feat: auto-generate session titles via the managed chat_title tool
With the auto-title experimental flag on and a managed OAuth login, the
session title is generated from the first prompt, replacing the
truncated-prompt easy title. A custom title set by the user is never
overwritten, and generation failures degrade silently to the easy title.
- oauth: fetchChatTitle for the platform /tools chat_title method
- agent-core (v1): fire-and-forget generation on the first prompt
- agent-core-v2: sessionTitle domain watching the easy-title event
- kap-server: POST /sessions/{id}/title/generate for manual regeneration
* fix: harden auto-generated session titles
* fix: preserve managed title request headers
* Pair auto-title endpoint overrides with matching OAuth credentials
* fix: preserve legacy custom session titles
* fix: preserve automatic session title invariants
* refactor: keep only the on-demand session title generation interface
Drop the automatic wiring on both engines: the v1 (TUI) first-prompt
trigger and the v2 easy-title event watcher. SessionTitleService's
generateTitle() stays as the single on-demand entry point behind the
auto-title flag, backing the kap-server title/generate route. The
changeset goes away too: with no shipped consumer, the remaining
surface is not user-perceivable.
* feat: generate session title from the first recorded prompts
Record up to three sanitized natural-language prompts in session
metadata (skill / plugin activations excluded) and compose the
chat_title input as order-labeled lines truncated to a 1000-char
budget, falling back to lastPrompt for sessions without recorded
prompts.
* test: make session title race tests deterministic
* Generate session titles from agent conversation history
* fix: reject title generation without user prompts
* fix: bound session title prompt history
* feat: enable session title generation without an experimental flag
* test: cover session title generation through the public REST path
* feat: request session title generation from the TUI after each turn
* Retry auto title generation for prompt-derived session titles
* feat: record session title source and harden the generation lifecycle
- persist titleSource (prompt/generated/custom); skip auto-generation over
an already-generated title unless forced, and never over a custom one
- plumb the force option from the core through klient and node-sdk to the
REST title/generate endpoint
- drop the title write-back when the session scope was superseded
mid-flight, and retry once with a force-refreshed token on a 401
- stop closing sessions a concurrent public resume has handed out in the
temporary resume paths (generateSessionTitle, renameSession)
- accept session.meta.updated patches without lastPrompt in klient event
validation, and emit exactly one metadata event per applied title
- remove the retired prompts field heal and drop the changeset (the
behavior is only perceivable on the experimental v2 engine)
* chore: follow agent-core comment convention
* fix: ignore stale session title callbacks
* fix: preserve session title state invariants
* refactor: seed session lifetime instead of querying the workspace handler
The session title service must not depend on the Workspace-tier handler
registry. The handler now seeds each session scope with an abort signal,
fires it synchronously when a close begins, and the title service carries
the signal on its request, drops the write-back once aborted, and drains
an in-flight generation through the onWillCloseSession hook.
* fix: honor the legacy custom title marker over a stale titleKind
A v1 rename spreads the original state.json document, so an explicit
isCustomTitle: true can travel with a stale titleKind. The explicit
marker now wins on load, and every persist double-writes the derived
isCustomTitle so released v1 builds keep recognizing the custom title.
* fix: serialize session access and expose the session title state
The temporary resume/rename/close paths and the public lifecycle
operations now share a per-session queue, so a public resume can never
receive a handle whose cleanup close is already in flight. Session
summaries carry the canonical title state, letting the TUI skip title
generation for sessions whose title was already generated or customized
instead of re-asking after every turn.
* chore: add session title changesets
* fix: close the session lifecycle races around close and title generation
A close/archive is now tracked in a closing registry from its first
synchronous step until disposal: get/list hide the closing session and
resume waits the close out instead of returning the doomed handle, and
fork waits out an in-flight source close. The title service tracks the
whole generateTitle call as the unit the close hook drains, and the
generated-title write re-checks the lifetime signal inside the serialized
metadata update so an abort landing while the update is queued still
vetoes the write-back.
* feat: project the session title state through the session index
readSummary and the read-model mirror carry titleKind, so listSessions
reports the same canonical title state as a resumed session's summary.
* fix: serialize the remaining session access paths in the SDK
forkSession and explicit-id createSession join the per-session queue, and
the harness resume fast path skips a session whose close is in flight
instead of returning the closing facade (which then failed every call
with session.closed); its late onClose no longer evicts the fresh
session either. The harness rename event now carries isCustomTitle so
the TUI stops asking for a generated title after a local rename.
* fix: detach the external abort listener once the chat title request settles
* fix: harden the session close/archive and create/fork lifecycle
The closing registry now records the operation kind: an archive arriving
during a plain close waits it out and lands the archived flag on the
persisted document instead of riding the close to success, and a failing
close hook no longer strands a half-closed session — the teardown always
completes while the hook error still reaches the caller. create and fork
reserve their target id synchronously with the existence check, so a
concurrent create/fork of the same id loses up front and can never tear
down the winner's scope or directory.
* fix: keep forced title regeneration independent and veto queued title writes atomically
Plain generateTitle calls still coalesce onto one shared in-flight
generation, but a forced regeneration always runs on its own so it is
neither swallowed by a plain call's early exit nor shares its result; the
close hook drains every active generation. The allowWhen veto now runs
inside applyUpdate with no await between the check and the mutation, so
an abort cannot slip into the gap.
* fix: carry the title state through the session index and klient contract
The klient session summary schema no longer strips titleKind, and the
index readSummary honors a legacy isCustomTitle marker over a stale
titleKind, so listSessions reports the same canonical title state as a
resumed session.
* fix: coalesce harness resumes, lock fork targets, and cover the title state end to end
Concurrent public resumeSession calls now share one in-flight resume and
one facade instead of building parallel facades over the same engine
handle (a close on either would strand the other). forkSession takes the
source and target queues in sorted order, so fork(A->X) is atomic against
create(X) and fork(B->X) without an ABBA deadlock. The emitMetaUpdated
patch type drops the redundant undefined union, and the SDK tests now
cover facade coalescing and the title state across list and resume.
* fix: serve the canonical title state from the session index and version the read-model cache
readSummary now derives the title state with the same priority chain as
the metadata document's canonical normalization (explicit custom marker,
valid titleKind, legacy false marker, customTitle, plain title), so list
and resume agree on legacy documents too. Read-model cache entries carry
a summary version stamp and older-stamped entries are treated as cold
misses, so an upgraded reader never serves a stale-shaped summary.
* fix: let the newest title generation request win the write-back
A forced regeneration could be followed on disk by an earlier plain
call's slower backend response. Each generation now carries a
monotonically increasing sequence (assigned only once a request actually
proceeds to generation), and the serialized metadata write is vetoed
unless the writer is still the newest request.
* fix: fold archive into close and own the create/fork rollback
An archive requested during a plain close is applied through the live
metadata during the teardown (or lands on the persisted document when it
arrives too late or the close fails), publishes the archived event, and
works on cold sessions too. A resume waiting on a failed close retries
instead of propagating the hook error, the teardown completes even when
the agent drain fails, and the create/fork rollback only ever removes
its own handle — a loser of the reservation race can no longer tear down
the winner's live scope.
* fix: key harness resume coalescing by the full input
Concurrent resumes only share a facade when their inputs match — a
caller passing different dirs, replay, profile, or kaos options gets its
own resume instead of having its options silently dropped.
* refactor(agent-core-v2): drop session close-awareness from title generation
Auto title is best-effort: a generation racing session close no longer
cancels its fetch or guards its write-back, so the per-session
sessionLifetime AbortSignal seed, the onWillCloseSession drain, and the
close-time invalidation go away. The newest-request-wins write-back
predicate stays.
* Delete .changeset/sdk-session-title-kind.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* refactor(session-title): drop the unused force regeneration path
Nothing calls force: with it gone, plain calls always coalesce onto the
shared in-flight generation, so the generation sequence and the
caller-supplied allowWhen veto lose their only purpose and go with it.
The title/generate REST route takes no body anymore.
* refactor(agent-core-v2): drop the title state projection from the session index
The listed-session titleKind had no consumer: the TUI's title-generation
gate seeds from the resumed summary, which reads the live metadata
document, and the kap-server REST wire never carried the field. Removing
the projection also retires the read-model summary version stamp (the
remaining shape is fully field-checkable) and the duplicate title-kind
derivation that had to stay in lockstep with sessionMetadata. The klient
list contract and the node-sdk list mapper drop the field with it; the
resumed/live summary still reports the canonical title state.
* refactor(agent-core-v2): inline the transcript live-tail merge into messageLegacy
mergeContextTranscriptWithLive had a single caller; move the logic into
messageLegacyService as the private mergeLiveTail and drop the export.
* refactor(agent-core-v2): drop the closing registry from the session lifecycle
Auto title no longer consumes close-awareness, so the machinery goes
back to the simple forms: close/archive run straight through, resume
no longer waits out an in-flight close, create/fork drop their target
reservation, and a cold archive is a no-op again. Reverts the behavior
of e7c397a7c and cd1cea0fd on top of the sessionLifecycle rename.
* fix(agent-core-v2): complete the HostRequestHeaders migration in the title test
The main merge reduced #/kosong/model/hostRequestHeaders to the pure
port contract; define the test's headers as a plain value matching it
and tidy the SDK test import grouping.
* fix(node-sdk): mark resume telemetry field ignored
* feat(tui): request the session title as soon as a prompt is accepted
* fix(agent-core-v2): drop the numbered user prefixes from the title request input
* refactor(tui): ask for the session title only once per session attach
* refactor(tui): drop the automatic session title trigger
Keep the capability only: the engine-side title generation service, the
POST /sessions/{id}/title/generate route, and the SDK generateSessionTitle
method stay; the TUI no longer requests a title on prompt accept or on
session attach. The changeset now covers the SDK capability instead of a
CLI-facing auto title.
* Delete .changeset/session-title-generation.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* feat(agent-core-v2): add forced session title regeneration
ISessionTitleService.generateTitle and the metadata write-back take an
optional force flag that bypasses the custom/generated guards, so an
explicit user request (the desktop/web rename field's Gen Title action)
can overwrite any current title; the applied title is marked generated.
Forced calls skip the in-flight coalescing, and a forced write is plain
last-writer-wins.
kap-server's POST /sessions/{id}/title/generate accepts an optional
{ "force": true } body; klient and the node-sdk plumb the option through
(GenerateSessionTitleInput.force).
Also renumber SESSION_TITLE_UNAVAILABLE to 40923: main assigned 40922 to
PAGE_TOKEN_MISMATCH after this branch forked.
* feat(agent-core-v2): selectable conversation excerpts for title generation
generateTitle gains a source option alongside force:
- user_prompts (default): the existing first-prompts window, unchanged.
- first_turn: the opening user prompt paired with the first turn's final
assistant text — strict, so a caller asking before the first reply lands
simply gets unavailable and can retry at the next turn boundary.
- digest: first prompt + latest prompt + the latest turn's final assistant
text, tolerating a compacted window by using whatever segments survive;
meant for explicit regeneration on multi-turn sessions.
Assistant segments keep only natural-language text parts (tool calls,
thinking, and media never contribute) and pass through the shared metadata
sanitizer, which redacts secrets and long base64-looking runs; each
segment is capped (user 300, assistant 600/400) so the composed
chat_content stays within the 1000-char budget. The kap-server route,
klient contract, and node-sdk plumb the option through. Excerpt extraction
is covered against the real context memory (loop-event folding), and the
REST surface gains a digest composition case.
* feat(agent-core-v2): gate session title generation behind an experimental flag
Registers the flag (off by default; env
KIMI_CODE_EXPERIMENTAL_SESSION_TITLE, the master flag, or the
[experimental] config section) and makes generateTitle report
unavailable while it is off, so every entry point — the kap-server
route, klient, node-sdk, and through them the clients' auto trigger and
rename-field action — is inert unless the user opts in.
* refactor(agent-core-v2): rename the title flag to auto_session_title
Snake-case id matching search_worker / persistence_minidb_readmodel; env
KIMI_CODE_EXPERIMENTAL_AUTO_SESSION_TITLE.
* fix(agent-core-v2): land the merge resolution leftovers
The main-merge commit captured pre-fix snapshots of four files; the
actual resolutions only lived in my working tree: the LifecycleScope
import move to #/app/scopes, the titleKind port of
applyPromptMetadataUpdate, the Promise<void> pinning of the metadata
update queue, and the reloadSession runSessionAccess closure.
* test(node-sdk): enable the auto_session_title flag in the title suites
Generation now reports unavailable with the flag off, so the two
title-generation harnesses opt in through the written config's
[experimental] section.
* chore: changeset for the experimental web session titles
* chore: scope the title changeset to the SDK package
* chore: cover the internal packages in the title changesets
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
Co-authored-by: liruifengv <liruifeng1024@gmail.com>
* feat: replace secondary-model experiment with [subagent.models] pool
Add a declarative subagent model pool to agent-core-v2: [subagent.models]
maps [models] entry ids to selection hints rendered in the Agent/AgentSwarm
tool descriptions, and [subagent].default_model picks the spawn model when
the caller passes none. The tools' model parameter becomes a free-form
alias string (stripped when no pool is configured), description rendering
is caller-aware (primary (alias) [main model]), and a session-start
validation service fails fast with CONFIG_INVALID on a missing/invalid
default_model or an unresolvable pool alias.
Remove the secondary-model experiment from the v2 engine, node-sdk,
kap-server, and the TUI (the /secondary_model command), and drop the
agent-profile modelPreference / model_preference frontmatter field on v2.
The legacy v1 engine keeps the experiment unchanged; v2 ignores leftover
[secondary_model] config silently.
* fix(agent-core-v2): harden subagent model-pool validation and error/picker mapping
Deep-review follow-ups to the [subagent.models] pool:
- validate the pool before session materialization (after config.ready)
and before the fork file copy, so a broken pool no longer leaves
orphaned session dirs or leaked MCP overlay connections; the
Session-scope validation service stays as a backstop
- reject the reserved "primary" pool alias at startup, and again
defensively in resolveSubagentBinding so a pool broken by a runtime
config edit fails loudly at spawn instead of binding the wrong model
- keep the [default] marker when the caller's own model is the pool
default (primary (alias) [main model] [default])
- recompile the cached tool-args validator when a tool advertises a new
schema object (mid-session pool edits no longer hit a stale validator)
- map config.invalid to VALIDATION_FAILED in kap-server's session routes,
the debug transport mapper, and the catch-all error handler
- hide the v1-synthesized __secondary__ entry from the /model and
/provider pickers again
- fold per-export doc blocks into file headers per package comment
conventions; add pre-flight/reserved-key/validator/mapping tests and
document that create/resume/fork all fail on a broken pool
* feat: re-add /secondary_model and accept a lone subagent default_model
- v2 engine: a pool-less [subagent] default_model forms an implicit
single-entry pool — validated at session create/resume/fork like an
explicit pool, and advertised through the Agent/AgentSwarm model
parameter.
- Tool descriptions: the caller's own alias is a normal pool entry
marked [main model]; the primary line stays distinct because only it
inherits the caller's thinking level.
- TUI: /secondary_model returns, persisting [subagent] default_model
(merging into an existing pool with an empty description); the picker
hides the no-op Thinking footer and rejects the reserved primary
alias.
- kap-server: /api/v1/config accepts and echoes subagent; the
snake-to-camel patch conversion preserves user-defined map keys under
providers/models/experimental/raw without leaking preserve mode into
a colliding alias's own fields.
- v1 config schema learns subagent.defaultModel/models so the shared
config.toml round-trips; the v1 engine still ignores them at runtime.
- Docs (en/zh) and changesets updated.
* docs: use public model identifiers in the subagent model pool examples
* refactor: rename /secondary_model to /secondary-model
* test: cover the /secondary-model command name resolution
* Revert "test: cover the /secondary-model command name resolution"
This reverts commit 98a4a6d999.
* feat(agent-core-v2): move the subagent model pool to [secondary_model]
The pool keys (default_model, [secondary_model.models]) now live in their
own [secondary_model] config section instead of [subagent], which keeps
only timeout_ms; legacy [subagent] pool keys are ignored with a
deprecation warning. The SDK config contract carries the pool on the
secondaryModel field, so the TUI /secondary-model command (now also
aliased /subagent-model) and the kap-server /config wire read and write
it directly with no translation layer.
* docs: correct default engine guidance
* feat(agent-core-v2): pin subagents to default_model with [secondary_model] force
force = true removes the main agent's per-spawn model choice: the Agent
and AgentSwarm tools stop advertising the model parameter and every spawn
binds default_model; an explicit choice, "primary" included, is rejected.
The setting requires default_model, rejects a [secondary_model.models]
table, and is validated loudly at session create/resume/fork (lifecycle
preflight plus the Session-scope backstop). The v1 engine declares the
key for write round-trips and excludes it from the recipe patch.
Also documents pool entries as per-alias thinking-level variants via
default_effort overrides.
* docs: use real managed model aliases in the secondary_model examples
The pool examples invented aliases (kimi-hs, fable, codex) and referenced
non-existent model IDs (model = "codex"); they now reference only the
managed aliases provisioned by /login (kimi-code/k3,
kimi-code/kimi-for-coding, kimi-code/kimi-for-coding-highspeed), with the
effort variant derived as kimi-for-coding-highspeed-deep. Also replaces the
versioned kimi-k2.5 alias with kimi-for-coding per the docs model-ID rule.
* chore: simplify the subagent model pool changeset
* feat(agent-core-v2): honor the legacy [secondary_model] model key as a fallback default
* refactor(node-sdk): export the reserved model-alias constants from the SDK
Restore the SECONDARY_DERIVED_MODEL_ALIAS re-export and add
PRIMARY_SUBAGENT_MODEL_CHOICE so the TUI imports both from
@moonshot-ai/kimi-code-sdk instead of vendoring local copies.
* feat(agent-core-v2): keep the subagent model pool behind the secondary-model experiment
Restore the secondary-model flag gating so this change only adds the pool:
with the experiment off the [secondary_model] pool keys stay inert — the
Agent/AgentSwarm tools strip the model parameter, spawns inherit the
caller's model, and startup pool validation is skipped. The /secondary-model
slash command is gated behind the experiment again, and the docs and
changeset describe the flag.
* fix(node-sdk): cascade provider removal into the subagent model pool
Deleting a provider left [secondary_model] entries pointing at the removed
model aliases; with the secondary-model experiment on, every subsequent
session create/resume/fork then failed pool validation. planProviderRemoval
now filters dangling pool entries, and drops the whole section when its
effective default (defaultModel, or the legacy recipe's model fallback)
dangles — folded into the same atomic multi-section replace.
* fix(agent-core-v2): close two subagent model pool validation gaps
Spawn-time resolveSubagentBinding now rejects force combined with a
[secondary_model.models] table, matching the startup pre-flight — a live
session could otherwise reach that invalid state through a deep-merged
config patch and only fail on the next create/resume. The session
lifecycle pre-flight also awaits the kosong model/provider registries'
ready alongside config.ready, so a cold bootstrap no longer fails a valid
pool with CONFIG_INVALID against an empty registry.
* test(agent-core-v2): stub the model/provider registries in handler-chain tests
SessionLifecycleService now awaits IModelService/IProviderService readiness
in its pool pre-flight, so the tests that assemble the real service through
a hand-built container must register the two tokens.
* fix(kap-server): cascade REST provider deletion into the subagent model pool
The DELETE /providers route rewrote only the providers and models
sections, so a pool referencing one of the deleted provider's aliases was
left dangling and the engine's create/resume/fork pool validation failed
every subsequent session until the user repaired the TOML by hand. Filter
dangling pool entries and drop the section when its effective default
dangles, mirroring the SDK's planProviderRemoval semantics.
* fix: keep the subagent pool consistent on provider replace and preserve legacy recipe fields
PUT /providers rebuilds the provider's alias set and can drop or rename
aliases referenced by [secondary_model]; the pool now cascades there too —
renamed aliases are repointed (mirroring the global default-pointer
migration), dropped aliases are filtered, and the section is cleared when
its effective default dangles.
The v2 [secondary_model] schema also declares the legacy recipe patch
fields (default_effort, max_output_size, ...) so validation no longer
strips them: pool resolution keeps ignoring them, but config reads/writes
now round-trip losslessly instead of silently deleting them from
config.toml on any pool write.
* fix(agent-core-v2): cascade the subagent pool on catalog refresh writes
A background provider/model refresh rewrites the [models] table without
touching [secondary_model], so a dropped alias left the pool dangling and
every subsequent session create/resume/fork failed validation until the
user repaired the TOML by hand — the same gap the SDK and REST write
paths already had, but triggered unattended.
The cascade helper now lives in agent-core-v2 next to the section it
protects (cascadeSubagentModelPool): the discovery service folds the pool
into the same atomic replaceSections transition, and kap-server's
provider write routes reuse the shared helper instead of a local copy.
* fix: cover the last two model-table write paths for the subagent pool
ModelsDevImportService's catalog and custom-registry imports rebuild the
[models] table without the pool cascade, so an import that drops a pooled
alias left a dangling pool behind; both final write passes now fold the
pool through cascadeSubagentModelPool (the drop passes deliberately skip
it). The StubConfigService test double now treats a null section value as
a delete, matching the real ConfigService.
The TUI's provider overwrite flow removes an existing provider before
re-adding it, which ran the removal cascade against a model table where
every alias of that provider was absent and silently dropped the pool;
the flow now snapshots secondaryModel up front and restores the entries
that survive the re-add, via the cascade helper re-exported from the SDK.
* fix(agent-core-v2): drop interrupted thinking-only assistant messages at settle
A turn interrupted while the model is still streaming thinking leaves the
open assistant holding only an unsigned thinking fragment. The fold used
to seal it into history because a non-empty thinking block is not vacuous;
on OpenAI-compatible providers the serialized message then carries neither
content nor tool_calls, and strict gateways reject every later request
with a 400 (#1404). Treat unsigned-thinking-only content as unsendable at
settle so the fold drops the message instead — replaying the records of
an already bricked session repairs it.
* fix(agent-core-v2): preserve reasoning-only assistant history
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix(agent-core-v2): disable SDK-internal retries that blocked cancellation
The OpenAI and Anthropic SDK clients default to maxRetries=2 with a
backoff sleep that never observes the request AbortSignal, so Ctrl+C
during a 429/5xx/connection-error retry only took effect after the
sleep elapsed, and the hidden attempts were invisible to the engine
(no turn.step.retrying) while double-counting its retry budget.
Build those clients with maxRetries: 0 so retryable failures surface
to the engine's step-retry layer immediately (observable countdown,
abortable sleep, single retry budget). The Google GenAI main request
path only retries when httpOptions.retryOptions is explicitly set, so
there is nothing to disable; instead its error converter now recovers
the server-directed delay from the wire body's google.rpc.RetryInfo
detail, since the SDK's ApiError drops the Retry-After header.
* chore: simplify the retry-cancellation changeset entry
* fix(agent-core-v2): recover GenAI retry delay from prefixed mid-stream error chunks
Mid-stream error chunks throw ApiError with the message wrapped as
"got status: <STATUS>. {json}", so a strict JSON.parse of the whole
message missed the google.rpc.RetryInfo detail. Locate the JSON object
start before parsing; the non-stream path (pure JSON body) is
unaffected.
* feat(kimi-code): re-baseline pi-tui on upstream v0.84.1 and add fullscreen tui_mode
Re-baseline the vendored pi-tui fork on upstream @earendil-works/pi-tui
v0.84.1, keeping all local patches: narrow-terminal hardening,
processed-line render caching (re-implemented into TuiMainScreen), editor
history hooks, the paste-burst fallback, and multi-root @ completion.
Upstream highlights absorbed: the renderer splits into TuiMainScreen and
TuiAltScreen behind a TUI interface, the Markdown component gains opt-out
LaTeX rendering (disabled on the kimi-code side), paste-registry repair
on delete/undo, Windows input-latency and Shift+Enter fixes, and Kitty
image layout fixes. Editor.setText gains a preservePasteRegistry option
so paste-marker expansion survives wholesale text replacement.
New tui_mode = "fullscreen" preference mounts TuiAltScreen: the
transcript lives in a primary ScrollView with follow-end, the chrome
docks at the bottom, mouse selection and scrollbar come from the
renderer, and full-screen viewers (tasks browser, output viewer, approval
preview) swap the layout root via screen-takeover. Viewport navigation
keys fall through to the focused component when the primary scroll view
cannot scroll.
* feat(pi-tui): merge upstream main through 40a3d85 (post-0.84.1)
Bring in upstream's merged-but-unreleased changes on top of the v0.84.1
re-baseline:
- Fullscreen transcript search (ctrl+shift+f, next/previous navigation)
- Alternate-screen render-churn reduction (9-18x less per-frame
allocation by painting full-width rows as direct line references)
- Unbound single-line scroll actions (tui.altScreen.lineUp/lineDown),
wired into the fork's canScroll gating like the other viewport keys
- SSH-aware escape-timeout default and PI_TUI_ESC_TIMEOUT override
- Search snapping and SGR-mouse fragmentation fixes; LaTeX newline
argument fix
Conflicts resolved by union: upstream's search/line scroll bindings stay
ungated, fork's primaryScrollable guard applies to all scroll actions.
* fix(kimi-code): keep fullscreen dock from crushing the editor box
The fullscreen layout gave the transcript ScrollView its intrinsic
content height as basis and let the dock participate in shrink
distribution with no minSize. Once the transcript exceeded the screen,
the VStack shrink pass crushed the dock to a couple of rows, and the
editor (3 rows: top border / input / bottom border) lost its bottom
border row to clipping.
Adopt pi's sizing contract: the ScrollView starts from basis 0 and
grows, the dock keeps its intrinsic height, the editor never shrinks
below 3 rows, and the footer below 1. Adds a VirtualTerminal-level
regression test that replays a full streaming cycle in fullscreen.
* docs(kimi-code): document the tui_mode preference in tui.toml
* fix(pi-tui): let terminal focus reports fan out in fullscreen
TuiAltScreen's viewport input listener consumed FOCUS_IN/FOCUS_OUT
reports. Since the renderer installs that listener at construction —
before any app-level listeners — terminal focus tracking and
clipboard-image hints never saw focus transitions in fullscreen mode
(notification_condition = "unfocused" went blind, refocus clipboard
hints stopped). Keep the selection cleanup but stop consuming, matching
the main-screen fan-out. Addresses Codex review on PR #2830.
* fix(kimi-code): wire openUrl and right-click paste in fullscreen
Mouse capture in the alternate screen intercepts the terminal's native
link activation, leaving OSC 8 hyperlinks (like the footer's PR link)
unclickable in fullscreen. Route renderer link clicks to the app's
openUrl, and on Windows feed right-clicks to the focused component as a
bracketed paste read from the clipboard.
* feat(kimi-code): fullscreen prompt navigation, exit replay, progress resync
- Mark user/assistant transcript messages with OSC 133 zones (start /
end / final) so the fullscreen renderer's Ctrl-Shift-Up/Down prompt
jumps work; GutterContainer keeps the markers at byte 0 when prefixing
its gutter, and message render caches store already-marked lines.
- On exit from fullscreen, preserve the frame and replay the transcript
through a fresh main-screen renderer so native scrollback gets the
regular inline layout (pi's "transcript" exit form).
- Re-sync the OSC 9;4 progress indicator after a stop/start cycle:
terminal.stop() clears it, and the cached progressActive flag used to
suppress the re-send when returning from the external editor mid-turn.
* feat(kimi-code): enable Markdown LaTeX rendering with a render_latex opt-out
Align with the upstream pi-tui default: LaTeX math in Markdown messages
renders as Unicode text. The explicit renderLatex:false we set during
the re-baseline becomes a shared Markdown options helper fed by a new
tui.toml preference (render_latex, default true), wired at startup and
refreshed on /reload.
* refactor(kimi-code): gate fullscreen behind KIMI_CODE_TUI_FULL_SCREEN
Drop the public tui_mode preference from tui.toml before release; the
fullscreen UI is experimental, so enable it with the
KIMI_CODE_TUI_FULL_SCREEN=1 env var instead. Docs move from the
config-file reference to the env-vars page.
* chore(changesets): clarify fullscreen mode and LaTeX formula entries
* chore(changesets): trim fullscreen mode entry
* chore(changesets): trim LaTeX formula entry
* chore(changesets): drop redundant kimi-code entries
* test(kimi-code): add stepRetry to fullscreen layout fixture after main merge
* fix(kimi-code): apply render_latex before theme-driven Markdown rebuilds
Codex review on PR #2830: applyReloadedTuiConfig set the shared LaTeX
toggle after applyTheme(), but theme application invalidates transcript
components and their rebuilt Markdown children copy the options at
construction — so a /reload that only flipped render_latex kept the old
value until some later invalidation. Move the setter before applyTheme
and pin the ordering with a test.
* fix(kimi-code): carry renderLatex through TUI config saves
Codex review on PR #2830: currentTuiConfig omitted renderLatex, so
saving an unrelated preference (theme/editor/upgrade/cache-hint)
serialized render_latex as the default true and silently reset a user's
opt-out. Carry the appState value through the shared save payload.
* feat(kimi-code): report tui_mode in lifecycle telemetry
Tag startup_perf and exit events with the active renderer mode
(regular/fullscreen) so fullscreen adoption is measurable while it is
gated behind KIMI_CODE_TUI_FULL_SCREEN.
When a plugin manifest omits `skills` and the plugin root contains a
SKILL.md, the fallback treated the whole plugin root as a generic skill
scan directory, so sibling Markdown files such as CHANGELOG.md were
misidentified as skills and inflated the plugin skill count.
Mark the fallback root as root-skill-only so discovery parses only the
root SKILL.md; explicit `skills` entries (including "./") keep the
directory scan semantics. Applied to both agent-core and agent-core-v2.
* feat(agent-core-v2): keep session updatedAt stable across meta management writes
Rename, archive/restore, and fork no longer bump a session's updatedAt,
so recency-sorted session lists stop reshuffling on management actions:
- setTitle/setArchived pass touchUpdatedAt: false; an explicit
patch.updatedAt always wins (fork inherits the source's recency, so a
fork lands next to the source instead of floating to the top)
- new SessionMeta.archivedAt records the archive moment (cleared on
restore) and is surfaced through the session index, the v1/v2 session
routes (archived_at), and the klient contract, so the archived list
keeps an accurate archive time without relying on the updatedAt bump
* fix(agent-core-v2): normalize a legacy ISO-string updatedAt when forking a cold session
A cold legacy/v1 state.json read from disk can still carry an ISO-string
updatedAt; passing it through as the fork's explicit patch.updatedAt
would persist a string into the v2 metadata. Normalize with toEpochMs
(falling back to now when absent/unparseable).
* fix(agent-core-v2): write fork metadata after agent recreation
Registering each copied agent during fork is an ordinary metadata write
that bumps updatedAt, which overwrote the inherited source recency and
still floated normal forks (sessions with agents) to the top. Move the
fork's metadata update after the agent recreation loop so the inherited
updatedAt is the final write.
* fix(agent-core-v2): preserve persisted recency when restoring a cold session
Resume creates the main agent for a cold session that has no persisted
agents.main entry (e.g. an empty session), and that registration bumps
updatedAt — so unarchiving an empty session still floated it to the
top. Capture the index summary's updatedAt before resume and re-apply
it in the restore write (archived:false, archivedAt cleared, explicit
updatedAt wins over the bump).
* fix(agent-core-v2): make agent registration non-touching for recency
Registering an agent is a structural write, not content activity — but
it went through an ordinary metadata update that bumped updatedAt. That
reordered recency-sorted listings whenever materialization created an
agent: resume of a cold session without a persisted agents.main (so
archive-via-resume and restore of empty sessions still floated), and
runtime subagent registration mid-turn. registerAgent now passes
touchUpdatedAt: false; restore goes back to the plain unarchive write
and no longer needs the capture/reapply workaround.
* fix(agent-core-v2): duplicate cron tasks only after the fork metadata is durable
With the metadata write moved after agent recreation, cron duplication
ran before it — a rejected metadata update left cloned cron records
pointing at a fork whose directory the catch block just removed. Keep
cron duplication after the durable metadata write.
* style(agent-core-v2): fold new invariants into module headers
The package convention keeps comments in the top-of-file block only —
move the touchUpdatedAt precedence, non-touching registration, and fork
ordering notes out of statement-level positions into the respective
module headers.
* chore: scope the changeset to agent-core-v2
* fix(kimi-code): show MCP launch targets in the workspace trust prompt
Render each gated project MCP server's launch target (transport, command,
args, cwd, or url) in the workspace trust prompt without leaking env or
header secrets, stripping terminal control characters from the
workspace-supplied text, default the prompt to "Don't trust", and
resolve fd binaries to absolute paths so untrusted workspaces cannot
plant a bare-name fd executable that runs before trust confirmation.
* fix(kimi-code): resolve stty to an absolute path before the trust gate
* feat(agent-core-v2): remove Agent and AgentSwarm from builtin profile tool lists
The builtin agent and coder profiles no longer expose the Agent and
AgentSwarm tools, so sessions on the v2 engine do not offer subagent
delegation by default. The tools themselves remain registered; profiles
that list them explicitly can still opt in.
* feat(agent-core): remove Agent and AgentSwarm from builtin profile tool lists
Align the v1 builtin agent/coder profiles with the v2 change: the
default profiles no longer offer subagent delegation, while the tools
stay registered for profiles that list them explicitly.
The parity projection drops v1's inactive Agent/AgentSwarm roster
entries: v1 reports registered-but-inactive builtin tools where v2 only
registers the tools a profile lists, so an inactive entry has no v2
counterpart. Active entries still compare in full.
* fix: keep Agent and AgentSwarm in the builtin agent profile
Scope the removal to the coder subagent profile on both engines: the
main agent keeps Agent/AgentSwarm so default sessions can still
delegate, while coder subagents no longer spawn nested subagents by
default. Snapshots and token counts shift only for the embedded coder
tool list; the v1 parity projection needs no change since the main
agent rosters match again.
* feat(kimi-code): show step retry progress in the activity indicator
Wire the engine's turn.step.retrying event into the TUI: while a failed
model request is backing off for another attempt, the waiting spinner
shows 'retrying (N/M) · errorName · in Xs' with a dim detail line for
the status code and provider error message, and the loading tip is
suppressed.
The retry state clears on the step's terminal events (completed /
interrupted), turn.ended, and tool.result. It intentionally survives
turn.step.started because the v2 engine re-emits that event for every
retried attempt of the same step.
* fix(kimi-code): show the retry indicator for mid-stream failures
A retryable failure raised after thinking/assistant deltas had already
streamed left the pane in thinking/composing mode, so the retry label
and detail never rendered during the backoff. Drive the pane and the
streaming phase back to waiting when a retry begins.
* fix(kimi-code): drop the stale retry countdown once the attempt starts
The v2 engine re-emits turn.step.started when the retried attempt
begins running after the backoff sleep. Track a backoff/attempt phase
so the label keeps showing the retry attempt and error but drops the
already-elapsed 'in Xs' countdown, instead of either clearing the
state or showing stale timing through a slow attempt.
* fix(kimi-code): advance the retry phase on a timer instead of step starts
The legacy engine retries inside the same step and never re-emits
turn.step.started, so the backoff-to-attempt transition keyed on that
event never fired there and the stale countdown stayed up through the
attempt. Schedule the flip from delayMs instead, which matches when
both engines actually start the next attempt, and drop the step-start
hook.
* fix(kimi-code): cancel the retry phase timer on TUI shutdown
A pending backoff timer survived KimiTUI.stop(), keeping the event
loop alive and firing setAppState against a disposed UI when stop()
runs without an immediate process exit. Expose the timer cleanup and
invoke it from the shutdown path.
* fix(kimi-code): align the retry detail line with the spinner label
* fix(kimi-code): capitalize the retry spinner label
* feat(kimi-code): paginate the session picker list
The /sessions picker and kimi -r used to materialize the full session
list before showing anything, which gets slow with hundreds of sessions.
- node-sdk: add listSessionsPage (limit/before -> items + nextCursor);
the v2 engine pages through the session index (draining past entries
whose workDir is unrecoverable), the v1 engine answers one full page
- TUI: open the picker on the first page, fetch the next page when the
cursor reaches the fetched end, and drain remaining pages in the
background once a search query is typed so search still covers all
sessions
- kimi -r now fetches a one-item page for the latest session
* chore: simplify session picker changeset
* fix(kimi-code): join in-flight page fetch in session search drain
A query typed while a scroll-triggered page fetch was still running
stopped the background drain at the loadingMore early return, leaving
the search covering only the pages fetched so far. fetchMoreSessions
now optionally joins the in-flight fetch and continues with the next
page; scroll triggers still drop when busy.
The footer git status cache spawns git (and gh for PR lookup) on the
startup path, before the workspace trust prompt. On Windows, a bare
command name lets cmd.exe resolve a git.exe planted in the workspace
before the user confirms trust — a gap left by #2695.
Resolve git once at cache creation and gh per lookup with
resolveCommandPath(), which returns an absolute PATH hit and refuses
matches inside the workspace; when resolution fails the cache reports
no repository instead of spawning anything.
The v1 WS connection had no keepalive: by design it stayed open until the
client disconnected, which only holds for direct connections. Behind a
reverse proxy or gateway with an idle timeout (30s defaults are common),
any quiet stretch — e.g. waiting on a slow model response — got the
connection killed, surfacing as a recurring 'Realtime connection error'
in the web UI.
Send an application-level ping every 10s and advertise heartbeat_ms in
server_hello (the schema and all shipped clients already answer pong).
Application-level rather than protocol-level ping because browser JS
cannot observe the latter, and the client's stale-socket detector keys
on incoming message frames. Any inbound frame refreshes liveness; after
two silent cycles the connection is presumed half-open and closed with
1001 so dead peers get reaped instead of leaking.
* feat(kimi-code): show live background agent activity in the /tasks panel
Background agents (run_in_background or Ctrl+B) showed no run details:
the /tasks panel only had static metadata, and its output view stays
"[no output captured]" until completion because agent tasks capture
output only once at the end.
Tee child-agent events into a bounded in-memory per-agent activity
store segmented by the engine's own turn.step.started events (recent
10 steps, bounded text/output tails). The /tasks preview pane now
shows a live activity preview for agent tasks, and Enter/O opens a
full-screen detail view rendering step-grouped Markdown text and
per-tool results through the main transcript's renderers, with Ctrl+O
to expand. Agent tasks without an in-memory record (e.g. lost after
resume) fall back to the captured-output view.
* feat(kimi-code): retain 20 recent steps in the background agent activity view
* fix(kimi-code): cap the streaming-args buffer in the subagent activity store
* chore(kimi-code): simplify the background agent activity changeset
* fix(kimi-code): drop activity records of foreground-only subagents at terminal state
* fix(kimi-code): cap retained tool argument strings in the subagent activity store
* test(acp-server): retry temp-dir cleanup to deflake ENOTEMPTY on CI
* fix(kimi-code): tighten subagent activity store lifecycle edges
- drop delta-only arg buffers when their step is evicted
- keep records of spawn-time background agents even when the task sync lags
- mark records terminal on background.task.terminated for stopped agents
that never emit subagent.failed
* fix(kimi-code): release leftover arg buffers when an activity record turns terminal
* fix(kimi-code): prune foreground-only activity records when the main turn ends
* fix: surface a readable error when Git Bash is missing on Windows
* fix(agent-core-v2): translate probe rejection into HostProcessError for ready awaiters
- HostEnvironmentService.ready now rejects with the translated
HostProcessError(shell.git_bash_not_found) instead of the raw
ProbeShellNotFoundError, matching what sync field reads throw and what
SDKRpcClientV2.ensureConfigFile() surfaces, while an internal no-op
handler keeps the rejection from becoming an unhandledRejection.
- Replace the Windows-gated probe-failure tests with vi.mock-stubbed
deterministic suites that run identically on any platform.
- Move the ProbeShellNotFoundError explanation into the environmentProbe
file header per the package comment convention.
* fix(agent-core-v2): narrow probe error to Error to satisfy only-throw-error lint
* fix(agent-core-v2): preserve probe error as cause when translating to HostProcessError
* fix(agent-core-v2): keep checked paths out of the public probe error message
* fix(node-sdk): gate the host-environment wait in ensureConfigFile to Windows
The missing-Git-Bash failure is Windows-only, and IHostEnvironment.ready
also covers the login-shell PATH enrichment, which spawns the user's login
shell with a 5s timeout. Awaiting it on POSIX coupled config-only commands
(kimi provider list/remove, export, ...) to the user's shell profile for no
benefit.
---------
Co-authored-by: liruifengv <liruifeng1024@gmail.com>
- return the enqueue-launched turn instead of rejecting with
prompt.not_found when no prompt is pending at steer time
- report steer as queued when a manual compaction holds the context
- sync title/lastPrompt metadata on main-agent steer, matching v1
- update the v1-v2 parity test to assert converged behavior
On Windows, cmd.exe / CreateProcess resolve a bare command name from the
current directory before PATH. Several startup-path child processes ran
before the workspace trust prompt, so a binary planted in an untrusted
workspace (stty.exe, npm.cmd, fd.exe) could execute before the user
confirmed trust.
- skip the POSIX-only stty save/restore entirely on win32
- defer fd detection from the KimiTUI field initializer to
startBackgroundFdAutocomplete(), which runs after the trust gate
- add resolveCommandPath(): resolve commands through PATH (PATHEXT-aware
on win32) to an absolute path and refuse hits inside the cwd
- route update-preflight package-manager spawns and the npm global-prefix
probe through it
- run the workspace trust prompt before the migration branch as well,
closing the blind spot where a pending ~/.kimi migration skipped it
- document the no-bare-command-before-trust-gate rule in
apps/kimi-code/AGENTS.md
* feat(minidb): instrument open lifecycle with phase timings and status
Add MiniDb.lifecycleStatus() exposing the no-generation/generation-load/
wal-catch-up/full-rebuild/ready/degraded state machine plus per-phase
timings (generation candidate load, store/non-text/text image load,
postings integrity check, WAL scan/apply, full recovery, text rebuild
hosting), so snapshot load, WAL catch-up and full rebuild can be told
apart in diagnostics.
Also add a repeatable open-lifecycle bench (small data, large WAL delta,
large full-text generation, corrupt generation) and fixtures proving a
healthy generation open performs no full-corpus tokenization while a
corrupt or missing generation falls back. Log search-index and
query-store open diagnostics in kap-server and agent-core-v2 so a
listSessions call can be attributed to the database it touches.
No persistence format or product behavior change.
* feat(agent-core-v2): isolate the session index from the global search index
Harden the separation between the session read model and the full-text
search index so session operations never depend on search availability:
- Reject text index definitions in MiniDbQueryStore at definition level,
keeping the session query-store a structural-only read model with no
postings/tokenizer artifacts, and assert its generation carries no
full-text files.
- Share one authoritative scan between the first list and the initial
projection (single-flight) instead of scanning twice; reads may only
join an in-flight scan, and every fallback read folds the mirror's
pending queue so read-your-writes holds while preparing.
- Keep withReadModel() fallback semantics pinned by tests:
uninitialized/preparing reads hit authoritative metadata immediately,
ready reads use the read model, degraded keeps falling back with a
diagnosable status reason.
- Guard session metadata writes so a mirror failure degrades only the
read model and never fails the session lifecycle.
- Prove via tests that listSessions/--resume/--continue never open the
global search DB (including when search-index is unopenable), and that
only real full-text search requests report building/stale/degraded.
* perf(minidb): slice open-time work so it never blocks the main thread
Make the whole generation-open path cooperative:
- Replace the synchronous postings/store CRC verification with chunked
async variants (readGenerationFileCheckedAsync, verifyFileIntegrityAsync)
that keep the exact bytes/crc-mismatch error semantics.
- Give the WAL-delta apply a primitive-op + wall-clock budget
(walApplySlicer), so a batch frame unrolling into thousands of ops can
no longer run as one uninterruptible slice; torn-tail, corrupt-batch
and read-only behaviors are unchanged.
- Slice the big attach loops: Store.bulkLoadRefsAsync +
SkipList.bulkLoadAsync for the store image, async parsers and
loadImageAsync for secondary/compound images, and
TextIndex.attachImageAsync for the docs/dictionary map construction.
- Queue text builds on worker-slot pressure (WorkerSlots.acquireBounded,
bounded by MiniDb.textBuildSlotWaitMs, abort-aware) instead of falling
back to an unbounded inline build; a persisted drought hosts the
bounded inline core as the explicit last resort with stats accounting.
Bench (bench/open-lifecycle, seed 42): event-loop delay max across the
four open scenarios drops from 45/734/331/492 ms to ~12-28 ms with wall
time flat or better.
* feat(kap-server): run the global search index in a dedicated worker
Move the whole search-index MiniDb lifecycle (open, generation load,
WAL replay, sync, rebuild, compaction) off the main thread into a
long-lived worker_threads host, so it never shares the event loop with
TUI input:
- Add a versioned request/response protocol and worker entry hosting a
host-agnostic SearchIndexCore; the same core also backs an inline
backend kept as the explicit rollback
(KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER=false, flag default ON).
- The worker exclusively owns the search-index handle. The lock token
is reported at acquire time (new MiniDb OpenOptions.onLockAcquired
hook) and reaped on dirty exit; an orphan-lock detector (same-pid
lock row whose token no live holder owns) recovers the window where
the token report is lost, so a mid-open crash can never freeze the
index into a silent permanent read-only.
- Crash handling: in-flight requests are rejected with typed errors,
respawn uses capped exponential backoff, per-request watchdogs
terminate wedged workers, and beginClose propagates into the worker
so dispose stays bounded during a long sync. Page tokens pin a
boot-salted generation, so tokens issued before a transparent worker
restart fail closed with invalid_page_token.
- The main process keeps the sync coordinator (debounce/coalescing/
single-flight), live transcript routing, query normalization and
page-token codec; searches keep reading the published generation and
report building/stale/degraded instead of waiting for sync/rebuild.
- Wire the worker into the CLI packaging: self-contained worker bundles
for npm dist and the SEA asset manifest/installer/smoke check, plus a
dev runtime (type-stripping + .ts resolve hook) scoped to worker
execArgv.
* feat(kap-server): model search and session-index lifecycles explicitly
Consolidate the two-index separation into explicit, diagnosable
lifecycles:
- Surface the global search state machine (stopped / opening / building
/ ready / degraded / closing) end to end: SearchIndexCore.lifecycleState,
SearchWorkerHost lifecycle snapshots cached from RPC responses (and
invalidated across worker generations), a never-throwing status()
carrying the lifecycle, and a synchronous lifecycleReport() that
neither kicks the open nor spawns the worker. Corrupt search-index
rebuilds are announced with a dedicated warn log so building, stale,
degraded, corrupt and worker-unavailable stay distinguishable.
- Turn MiniDb read-only replica catch-up fully cooperative:
catchUpWalAsync scans frames with the windowed async scanner and
yields per primitive op on the shared walApplySlicer budget, while a
per-instance catchUpChain serializes concurrent catch-ups so each
caller keeps its atomic watermark advance. The stale synchronous
implementations are removed.
- Pin the dependency direction and availability timing with tests:
session list/create/resume survive a corrupt or unopenable search
index (also end-to-end with a dead query-store), search generation
reuse and stale-serving keep working across restarts, concurrent cold
callers open the index / spawn the worker exactly once, resume-then-
fetchSessions performs no duplicate authoritative scan, and a clean
dispose releases the lock and settles at stopped.
- Document the experimental flag surface (persistence_minidb_readmodel,
search_worker) in the root guide.
* feat(agent-core-v2): default the session read model on and roll out the separation
Rollout and validation for the index separation plan:
- Flip persistence_minidb_readmodel to default ON (rollback via
KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL=false or the
experimental config section); session list/--resume/--continue now
always go through the isolated session read model with the
authoritative fallback. Test harnesses pin the flag off where shared
fixtures require hermetic homes, while the dedicated suites keep
explicit on/off coverage.
- Add a probe proving the main thread stays responsive while the
search worker rebuilds and swaps a generation (reindex), completing
the TUI responsiveness matrix.
- Record the rollout state in the agent-core-v2 guide (session index
section) and the root flag line.
- Add changesets for the CLI (worker isolation, session index
independence) and minidb (cooperative open lifecycle).
Validation: full suites green across minidb (551), agent-core-v2
(4760), kap-server (1005), node-sdk (343), klient (91) and the CLI app
(2567); open-lifecycle bench event-loop delay max is down from
45/734/331/492 ms to ~16-22 ms across the four scenarios with wall
time flat or better.
* fix(agent-core-v2): evict deleted sessions from the mirror queue and drain the index on close
Two issues surfaced by the read-model default in the acp-server suite:
- ISessionIndex.remove only deleted from the query store, but a summary
still queued in the mirror was folded back into reads (and re-written
by the next flush), resurrecting a deleted session in listings. The
mirror now exposes evict(id): drop the queued summary and wait out an
in-flight flush before the store delete.
- RunningAcpServer.close and SDKRpcClientV2.close disposed the engine
without awaiting the asynchronous mirror flush / query-store close,
so a host removing homeDir right after close() raced in-flight shard
closes (ENOTEMPTY). Both now follow the kap-server shutdown order:
drain the mirror while the store is open, dispose, then await the
drains.
* fix(minidb): pause active expiry during the sliced bulk load
The store's active-expire timer is armed at construction, so during a
sliced bulkLoadRefsAsync a tick can fire mid-load: it reaps a TTL key
from the map while the order skiplist is still the old empty one, and
the final bulkLoadAsync then rebuilds order from the stale orderEntries
snapshot — resurrecting the expired key in the ordered index (and
duplicating it if the key is later set again). The sync bulkLoadRefs had
no yield windows, so guard the async path with a bulkLoading flag that
defers expiry ticks until the load settles (finally-safe).
* chore: consolidate changesets into the TUI startup freeze fix
- tokensBefore/tokensAfter now include the system prompt and non-deferred
tool schemas, matching the measured-anchor basis the context gauge uses
between exchanges
- the post-compaction ledger rebase carries the same full-request size, so
the reported context size no longer dips to a messages-only estimate and
jumps back on the next exchange
- the PreCompact hook tokenCount uses the same basis
* fix(agent-core-v2): gate plugin changes behind session baselines and reminders
- capture a per-session MCP server baseline (ISessionMcpHandle.isBaselineServer)
so servers added mid-session (plugin install, mcp.json edit) never register
tools in live sessions; they take effect on /new, /reload, or resume, while
removed servers stay tombstoned and fail calls with a removal notice
- stop rebuilding the system prompt on plugin-source catalog changes: the
frozen skill listing and plugin sections cannot move anyway, and the rebuild
only churned the ${now} timestamp, invalidating the provider prompt cache
- freeze the Agent tool description's catalog profile list once the session
catalog has loaded, keeping the tools payload byte-stable across mutations
- append a plugin_change system reminder to live sessions on plugin mutations
(new IPluginService.onDidMutate; explicit reloadPlugins does not raise it)
- revert the TUI hint to "Run /new or /reload to apply plugin changes." and
update the plugin/MCP docs and changesets to the corrected contract
* fix(agent-core-v2): import LifecycleScope from app/scopes in sessionOutcomeMirror
#2666 imported LifecycleScope from #/_base/di/scope, which does not export
it (it lives in #/app/scopes), breaking the package build and typecheck on
main.
* fix(agent-core-v2): close the mutation-driven session-start refresh and overlay baseline leaks
Codex review on the PR found two contract leaks:
- a plugin mutation re-pulls the plugin skill source, and the existing
catalog listener answered with a fresh plugin_session_start reminder —
injecting the newly installed plugin's instructions into the live session
alongside (and contradicting) the plugin_change notice. The session-start
refresh now skips mutation-driven catalog changes (one per mutation,
counted; explicit reloads keep the old refresh behavior).
- a session created with ephemeral mcpServers kept its MCP baseline open
until the overlay connect finished; a workspace server added in that
window (plugin install, config edit) leaked into the live session through
the merged view. The overlay handle's baseline now freezes on the
workspace manager's initial load, with the ephemeral names baseline by
construction.
* fix(agent-core-v2): drop duplicate LifecycleScope import in sessionOutcomeMirror test
---------
Signed-off-by: Haozhe <yanghaozhe@moonshot.ai>
* feat(agent-core-v2): persist the last turn outcome into session metadata for cold listings
A cold session (no live handle) reported no lastTurnReason, so after a
server restart the session list could not mark a session whose last turn
failed until it was opened and resumed.
A new Session-scope SessionOutcomeRecorder subscribes to the activity
aggregate's turn_ended changes and persists the outcome
(completed/failed) into the session metadata document; the summary
pipeline (mirror + cold reader) carries it as SessionSummary
.lastTurnReason, and toWireSession falls back to it when no live fact
exists. 'cancelled' is deliberately not persisted: it is also what an
in-flight turn ends with during scope disposal, and writing there races
the host's home-dir teardown.
Verified end to end with an isolated home and a dead provider: a turn
fails, the server restarts, and GET /sessions reports
last_turn_reason=failed without opening the session.
* fix(klient): carry lastTurnReason/lastTurnOutcome in the validated contracts
Review follow-up: zod strips unknown keys on parse, so the new outcome
fields never reached klient callers; add them to the session summary and
metadata/patch/key schemas (contract parity test covers the engine
mirror).
* fix(agent-core-v2): persist user-cancelled outcomes, never teardown aborts
Review follow-up: skipping every 'cancelled' left a stale earlier outcome
in the metadata (e.g. a prior failed reported for a session whose latest
turn was stopped by the user). The recorder now subscribes to the main
agent's turn.ended facts directly and keys on interruptReason:
user_cancelled is persisted like any other terminal state, while
programmatic aborts — including the cancel every in-flight turn suffers
during scope disposal — are never written, so no metadata write races the
host's home-dir teardown.
* fix(kap-server): only fall back to the persisted outcome for cold sessions
Review follow-up: a warm session that just started a new turn clears its
live lastTurn, and the unconditional ?? fallback would then report the
previous turn's persisted outcome for a turn that is still running.
SessionFacts now reports whether a live handle exists, and the wire
projection only reads the persisted value when the session is cold.
* docs(agent-core-v2): keep the outcome-recorder header at role level
* fix(agent-core-v2): settle turn outcomes on turn start and drain metadata writes on close
Review follow-ups:
- a new main turn now clears the persisted outcome (turn.started), so a
process that dies mid-retry no longer reports the previous turn's
terminal state for a turn that never ended
- the dedupe marker only advances after a successful write, so a failed
persist no longer suppresses the next identical outcome
- session metadata writes are tracked in a module-level pending set with
drainSessionMetadataWrites(), awaited by kap-server close alongside the
mirror/query-store drains — an event-driven write (e.g. the outcome
recorder) can no longer land in a session dir while the host removes it
* fix(agent-core-v2): track the metadata dispose flag locally
Disposable exposes no public isDisposed accessor; keep a class-local flag
set in the dispose override.
* fix(kap-server): drain session metadata writes before the mirror and disposal
A write still in flight when close() begins must settle before the mirror
flushes its summary into the read model and before scope disposal marks
the service disposed — not after.
* fix(agent-core-v2): reattach the recorder when the main agent is recreated
Review follow-up: a failed bootstrap still fires onDidCreate before the
handle is dropped; the subscription then pointed at a dead bus and the
guard blocked any later reattach. Track onDidDispose and reset so the
next main creation attaches cleanly.
* test(agent-core-v2): resolve the recorder through the scoped DI harness
Review follow-up: construct SessionOutcomeRecorder via registerScopedService
+ a Session-scope test host (stubbed lifecycle/metadata), so the test covers
the production registration path; add the durable-value adoption case.
* fix(agent-core-v2): unbreak CI — iterable Promise.all and the debug channel surface
- Promise.all takes the pending-writes set directly (oxlint error)
- the disposed flag moves into a _register'd marker instead of a public
dispose() override, which the debug channels listing (and its test)
correctly rejects as framework plumbing
* fix(kap-server): surface persisted failures on the v2 session status
The v2 list folds the outcome into activity.status, which previously
read only live facts — a cold session always looked idle. Cold sessions
now map a persisted failed outcome to status 'failed' (completed and
cancelled stay idle, matching the live fold); warm sessions are
unchanged, and the statuses filter inherits the mapping.
* refactor(agent-core-v2): name the persisted field lastTurnReason
Aligns with the established name for the same concept end to end
(activity view's lastTurnReason, the v1 wire's last_turn_reason, and the
SessionSummary mirror), instead of introducing a third variant.
* fix(agent-core-v2): drain pending metadata writes before session teardown
Review follow-up: closing/archiving a session right after a turn ended
could dispose the scope while the outcome write was still queued, and
delete() removes the session dir immediately after close. Await the
pending metadata writes before the handle goes away.
* fix(node-sdk): carry lastTurnReason through the SDK session summary
Review follow-up: the in-process SDK path maps the engine summary through
v2SummaryToSessionSummary, which dropped the new outcome field. Add it to
the public SessionSummary type and the mapper; the parity gate projects
it away (the v1 engine never records an outcome).
* fix(node-sdk): populate lastTurnReason on live SDK summaries
Review follow-up: resumeSession/reloadSession build their summary from the
live session's metadata document, which now carries the outcome — surface
it there too so the SDK reports it consistently for live and listed
sessions.
* fix(agent-core-v2): carry the last turn outcome across session forks
Review follow-up: fork skips state.json when copying the session dir, so
the fork's fresh metadata never had the outcome and a restart dropped a
marker the warm fork was still reporting. The fork's metadata patch now
inherits the source's lastTurnReason.
* fix(agent-core-v2): settle pending outcome writes before reading a fork source
Review follow-up: a fork requested right after the source's turn ended
could read the metadata before the recorder's queued write landed,
inheriting a stale or absent outcome. Drain pending metadata writes
first.
* fix(agent-core-v2): backfill restored outcomes into the session metadata
Review follow-up: for sessions whose last turn ended before this field
existed, the cold-resume seed restores the outcome into the activity view
without a turn.ended fact, so the recorder never persisted it and cold
listings stayed blank. The recorder now also watches the main agent's
activity updates and backfills the restored outcome when nothing is
persisted yet.
* fix(agent-core-v2): never backfill restored cancellations
Review follow-up: a restored 'cancelled' cannot be told apart from a
programmatic abort (the activity event carries no interruptReason), and
those are never persisted. Backfill now covers only completed/failed;
user stops are still persisted from the live turn.ended fact.
* refactor(agent-core-v2): rename the outcome recorder to outcome mirror
Mirror is the codebase's established term for a write side that reflects
live state into a store (SessionIndexMirror); Recorder has no precedent.
* fix(agent-core-v2): backfill without bumping recency; header-only comments
Review follow-ups:
- a mere resume must not float an old session to the top of the list:
metadata updates accept touchUpdatedAt:false and the outcome mirror's
backfill uses it (live outcome writes keep bumping — turn end is a
recency moment)
- the mirror service's inline notes move into the file header per the
package comment convention
- drop the redundant |undefined from the SDK's optional outcome field
* fix(node-sdk): read the live outcome for resumed session summaries
Review follow-up: on a fresh resume the restored outcome can still be
queued as a metadata backfill, so the document may lag a tick; the live
activity aggregate already holds it. Resume/reload summaries now prefer
the live value and fall back to the metadata field.
* fix(agent-core-v2): confine the outcome backfill to pure resumes
Review follow-up: the view publishes its turn.ended fold before this
mirror's own turn.ended handler runs, so a live ending reached the
backfill branch first and got persisted without the recency bump. The
backfill now only applies when no turn ever started in this process —
live endings always take the bumped write.
* fix(agent-core-v2): drain the session-index mirror before session teardown
Review follow-up: settling the metadata write alone left the fresh
summary in the mirror's pending queue, so a list right after close could
read a stale outcome from the read model. close/archive now also drain
ISessionIndexMirror. Test harnesses register a mirror stub for the new
dependency.
* docs(agent-core-v2): fold the metadata drain contract into the file header
* chore: include the SDK package in the changeset; fold the drain note into the header
* fix(agent-core-v2): backfill restored cancellations too, quietly
Review follow-ups: dropping every restored cancel loses legitimate user
stops whose live write never landed (or was rejected) before a restart —
cold surfaces never mark cancelled anyway, so healing them is harmless
and strictly more accurate. The metadata disposal note moves into the
file header per the comment convention.
* fix(node-sdk): prefer the live outcome over the index in SDK listings
Review follow-up: a live session that just started a new turn after a
failure can briefly keep the stale outcome in the index while the
mirror's clear is queued. listSessions now reads the live activity
aggregate for warm sessions, matching the kap-server cold-only fallback.
* fix(node-sdk): never read the metadata outcome for a live session
Review follow-up: with a retry in flight the live aggregate has no
outcome while the document may still hold the previous failure — the
fallback showed the stale one. Live summaries now take the live
aggregate's answer alone; the restored outcome is already seeded there
on resume.
* chore: sync web dist from code-app
* chore: add changesets for the synced web UI changes
* chore: drop changesets already covered by the previous web bundle sync
* chore: correct the drop-folder changeset for web
* chore: drop the drop-folder changeset (desktop-only feature, no web announcement)
* feat(mcp): tombstone removed MCP servers and apply plugin changes immediately (20 files)
- add 'removed' MCP server status: workspace config removals call markRemoved
instead of remove, keeping tool registrations alive while short-circuiting
calls with a removal notice
- fire onDidReload after every plugin mutation (install/enable/disable/remove)
so workspace consumers refresh contributions immediately
- TUI renders the removed status in the MCP panel/startup summary and shows an
apply-immediately hint on the v2 engine
* feat(agent-core-v2): freeze plugin prompt inputs for live agents (2 files)
- snapshot the model skill listing and plugin system-prompt sections on the
first successful prompt build and reuse the frozen values for the agent's
lifetime, so plugin install / enable / disable / remove / reload never
rewrites a live agent's prompt (same keep-live-sessions-stable philosophy
as the MCP tombstone)
- freeze only on success: a not-yet-ready skill catalog or a failed
enabledSystemPrompts() read must not pin empty values for the agent's
lifetime
- refreshSystemPrompt still rebuilds on catalog change events but reuses
the frozen values, so the prompt only moves when non-plugin inputs change
(AGENTS.md, [tools] section, session tool policy, compaction); new agents
snapshot the then-current state
* chore(changeset): add changesets for MCP tombstone and frozen plugin prompt inputs
* docs: describe immediate plugin changes and the removed MCP status on the v2 engine
* fix(klient): mirror the removed MCP server status in the wire contract
* docs: drop the legacy-engine behavior notes from the plugin and MCP pages
* fix(agent-core-v2): freeze plugin sections only on a loaded snapshot
- enabledSystemPrompts() resolves to its consumption fallback (never
rejects) while the initial plugin load has failed; freezing that empty
read locked plugin sections out of the live agent even after a later
successful reload
- expose hasLoadedSnapshot() on IPluginService so resolvePluginSections
can tell a real empty snapshot from the fallback before freezing
* fix(kimi-code): select compatible PowerShell for Computer Use
* fix(kimi-code): handle locked Computer Use plugin files
* fix(kimi-code): align Windows Computer Use name
* fix(agent-core-v2): reuse PowerShell fallback for detection
* fix(agent-core-v2): refresh ready Computer Use plugin
* feat: surface the bound model on subagent UIs
The subagent.spawned event now carries the display-normalized model alias
(the derived __secondary__ entry resolves to its base alias), so clients can
show which model a subagent is bound to. The TUI subagent card, swarm panel
header, and background-agent entry show it at spawn; the WS snapshot roster
and REST /tasks (background/detached subagents) carry it too, keeping the
model visible across client reconnects.
* feat: carry the subagent thinking effort alongside the model
The spawned event, snapshot roster, and REST /tasks now also carry the
child's effective thinking effort (read from the child profile at spawn, the
same vocabulary as agent.status.updated). UIs show it only when it diverges
from the main session's current effort — an inherited level adds no
information, and 'off' is never shown.
* feat(tui): show the bound model and effort in the /tasks browser
The task browser's Detail pane renders Model and Effort rows for agent
tasks (raw alias and level — it is the inspector surface, so no diff
filtering), and its minimum height grows to fit the new rows. The values
were already persisted on SubagentTaskInfo; the TaskInfo union, its zod
schemas (protocol, kap-server, klient contract), and the v1 type
declaration now carry them so nothing strips them in transit.
* feat(tui): show concrete subagent effort levels unconditionally
Display rule simplified: any concrete effort tier (low/high/max/…) is
shown next to the model — including when it matches the main session's
level. Only the boolean states stay hidden: 'off' (no thinking) and 'on'
(generic thinking) carry no level information.
* docs: trim the changeset entry
* fix(tui): keep the model and effort on background-agent entries across resume
replayBackgroundProjection only copied agentId/parentToolCallId/
description, so a background subagent that outlived a resume lost its
model/effort on the later terminal transcript entry. The projection now
threads the persisted values (catalog-mapped model; boolean effort states
dropped), and session replay passes the loaded model catalog through.
* fix(agent-core-v2): normalize the derived secondary alias regardless of the flag
A child bound while the secondary-model experiment was on keeps
__secondary__ in its persisted binding; if the flag is later switched off
with the recipe still configured, resolveSecondaryModel() gated the
normalization and the sentinel leaked back onto resumed subagents.
subagentDisplayModel now reads the recipe straight from config (the flag
gates new bindings, not the interpretation of existing ones), which also
drops SessionSwarmService's now-unused IFlagService dependency. Also adds
the SDK package to the release: the new SubagentSpawnedEvent/AgentTaskInfo
fields are SDK-visible types.
* fix(agent-core-v2): normalize the status-frame model at the source
A derived-bound child republishes agent.status.updated right after spawn
with its raw modelAlias, which overwrote the spawned event's normalized
display model on single-subagent cards (swarm headers were first-wins and
escaped). emitStatusUpdated now maps through subagentDisplayModel, a no-op
for the never-derived main agent. Also moves the inline comments added by
this branch into top-of-file headers per the v2 comment convention.
* fix(tui): clamp the /tasks detail frame to the available body
At terminals near the minimum height the forced 10-row detail frame
overflowed the body and truncated the preview frame's border. The detail
height now caps out at whatever leaves the preview its borders plus one
content row, with a regression test at exactly MIN_HEIGHT.
* fix: normalize inherited derived aliases and keep model/effort on replayed terminal entries
- resolveSubagentBinding's caller-fallback branch also maps through
subagentDisplayModel: a caller itself bound to the derived entry (a
resumed subagent making a nested Agent call) no longer publishes
__secondary__.
- The replayed background-task terminal notification builds its metadata
with the persisted model (catalog-mapped) and concrete effort, matching
the live completion path.
- Drops the inline comments this branch added inside v2 test bodies; the
scenario context lives in the source file headers.