The drain probe treated any callTool failure as proof the transport close
had been processed, but a stdin write error (EPIPE) can win the race
against the child's exit notification, so the listener could be registered
before the close was buffered and the synchronous replay never fired.
Break the drain loop only on errors that are impossible before the SDK's
_onclose ran ('Not connected' / 'Connection closed' / the transport's
not-running guard).
Also drop the assertion that the replayed reason contains the child's
final stderr: the reason snapshots the stderr buffer at close time, which
can legitimately race delivery of the last stderr chunk (reproduced 2/40
under CPU load). Tail capture itself stays covered by the stderrSnapshot
assertion. Finally, flush the fixture's banner through the stderr write
callback before process.exit so the write cannot be truncated.
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
- turn.started now derives the attachment file id from the kimi-file URL when the media part carries no id, so prompt images uploaded through the global file library stay attached in the live transcript instead of vanishing until the post-turn heal
- an explicit id must still match the URL file id, and non-kimi-file URLs are still ignored
- restore the turn.started prompt-attachment regression coverage dropped by the model-as-container refactor and extend it to the id-less kimi-file form
* docs: rework web guide, interaction and getting-started pages (zh/en)
* docs: rename guides/server to guides/web to match the reworked page
* docs: neutralize screenshot workspace names and sync en web guide to zh
* docs: trim web UI screenshot to a single neutral workspace
* fix(kap-server): remove undone turns from the live transcript projection
* fix(agent-core-v2): report the earliest removed turn id on conversation undo
* fix(agent-core-v2): spill oversized tool outputs and surface dropped content
* fix(agent-core-v2): preserve spill fields through tool result normalization
normalizeToolResult rebuilds every tool result with a field whitelist,
which stripped untruncatedOutput / untruncatedOutputTotalChars /
spillExempt before ToolResultTruncationService could see them: the
spill-on-truncation path never fired for Bash/Grep/FetchURL/WebSearch,
and reads of spill files were not exempted from re-spilling.
Pass the three engine-internal fields through, and add executor-level
integration tests that run a retainFullOutput tool and a spill-exempt
result through the real ToolResultTruncationService.
* refactor(agent-core-v2): drop banned JSDoc and fix harness error typing
main banned JSDoc in comment-free packages (#3226); remove the doc
blocks on the new contract fields and on isSpillFilePath. Type the
harness scripted stream error as Error to satisfy only-throw-error
under oxlint --type-aware.
* fix(agent-core-v2): preserve completion status when spilling output
* fix(agent-core-v2): mirror dedupe reminders into the spill suffix
appendReminder additions lived only in the final output, so they were
dropped when the spill pointer replaced it; mirror the reminder into
untruncatedOutputSuffix for retained results, widening ToolDedupeResult
to ExecutableToolResult plus its message field. Also stop claiming the
full output was saved when retention capped out, narrow spillExempt to
'true' per the optional-property convention, and pass traceId directly
in the harness.
* fix(agent-core-v2): prefer persisted Bash task logs
* refactor(agent-core-v2): unify tool-result truncation in the spill pipeline
Route every tool result through ToolResultTruncationService.truncateForModel
as the single model-context decision point: spillExempt pass-through, the
50k char budget, per-line shaping, spill persistence with a 10MB retention
cap, and append-or-replace pointer rendering. Tools no longer declare
truncation options; sources keep only memory-safety caps.
- rename ToolResultBuilder to ToolOutputAccumulator and drop its options
- mcp keeps only its media pipeline and shares the unified 50k budget
- bash persists foreground logs at the spill threshold and reuses them as
spill.outputPath only within the retention budget
- carry completion/error messages in spill.suffix so retention capping
cannot drop them
- render a bounded preview when spill persistence fails
- suppress suffix lines already present inline in append mode
- call out text-only persistence when media parts stay attached
* fix(agent-core-v2): preserve success status in spilled output
* fix(agent-core-v2): reuse the complete task log for spilled bash output beyond 10MB
* Update tool-result-spill.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
v2 engine status events carry contextTokens/maxContextTokens but never
contextUsage, so appState.contextUsage was only refreshed by getStatus
pulls and then went stale while the token counts kept updating live.
The /usage panel and footer render the ratio as a bar but recompute the
percentage text from the counts, so a stale ratio showed as a bar that
disagreed with the percentage (e.g. bar ~74% next to "18% (180k / 1M)"
after compaction or a model switch).
Recompute the ratio from the post-patch token counts whenever a status
update touches contextTokens or maxContextTokens without carrying an
explicit contextUsage. v1 events carry the ratio and are unaffected.
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
* fix(kap-server): report run_in_background on the task wire
The /tasks wire now carries the task's detached flag as
run_in_background (schema in both the kap-server local copy and the
public protocol package). A running foreground subagent used to be
indistinguishable from a background one on this surface — clients that
defaulted the missing field to true would treat it as background.
* chore: add changeset for the run_in_background wire fix
* fix(kap-server): make run_in_background a required wire field
The field is always emitted (ghost-restored records pre-dating it read
true: the persisted store only lists terminal-and-detached or running
tasks, which all carry a concrete flag). Making the contract required
means a producer that omits it fails as an ordinary protocol error
instead of clients silently re-interpreting the row as foreground
* fix(protocol): keep run_in_background optional in the public task schema
The public schema types the agent-core v1 task service too, which does
not emit the field — making it required there is a breaking protocol
change (and broke agent-core's typecheck). kap-server's own local
schema stays required: it is the sole writer of the /tasks response
and always emits. Consumers apply the foreground fallback when the
field is absent
* fix(kimi-code): render newlines instead of literal backslash-n in rc output
* fix(kimi-code): print plain URL in rc output when hyperlinks are unsupported
* feat(kimi-code): add remote control web tunnel
Add CLI and TUI entry points for exposing the local web UI remotely.
Bridge HTTP and WebSocket traffic with local authentication and reconnect handling.
* fix(kimi-code): prevent remote control websocket crash
* fix(kimi-code): align websocket dependency versions
* fix(kimi-code): harden remote control connection setup
Reconnect when management closes during the HTTP tunnel handshake.
Reject non-loopback Remote Control binds whose CSP blocks path bootstrap.
* fix(kimi-code): fix remote control rewriting, caching, and WS frame loss
* feat(kimi-code): add remote control QR output
* build: update pnpm dependencies hash
* refactor(kimi-code): remove the --allow-remote-terminals flag
* feat(kimi-code): add remote control lock, rc command, and QR fixes
* fix(kap-server): broadcast user prompts to all session clients on submit
- agent-core-v2: emit prompt.submitted (status running|queued) at enqueue and prompt.started when the turn launches
- kap-server: project prompt.submitted/prompt.started into transcript prompt entities and the live transcript REST response
- update flake.nix pnpmDeps hash for the PR lockfile
* fix(node-sdk): drop v2-only prompt.started from SDK event stream
- event-mapper: add prompt.started to the dropped v2-only prompt lifecycle types (parity with submitted/completed/aborted/steered)
- cli test: assert only visible sub-commands and stub the experimental flag env for determinism
* ci(pkg-pr-new): post custom install comment for npm 12 compatibility
* feat(kimi-code): render remote control QR as inline image on capable terminals
* feat(kimi-code): improve remote control terminal output
- add onboarding, security, device management, and help guidance
- show compact clickable links and QR image fallback details
- report relay and remote device connection lifecycle
* test(agent-core-v2): update tool event snapshot
* revert(ci): keep preview workflow unchanged in rc pr
---------
Co-authored-by: liruifengv <liruifeng1024@gmail.com>
- retry every failed LLM request indefinitely in runRequest when
KIMI_CODE_INFINITE_RETRY is set, covering turn steps and operation
requests such as compaction
- keep projection recovery ahead of the infinite retry branch, honor
Retry-After, and keep abort effective during backoff waits
- exclude context overflow from infinite retry so the deterministic
turn-level and compaction-level overflow recovery paths still run
- extract retryBackoffDelay for single-attempt backoff computation
* fix(tui): render /plugins marketplace before version lookups resolve
The Third-party/Official tabs waited on the slowest GitHub
releases/latest lookup before painting any catalog row, with no
timeout (undici defaults: 10s connect, 300s headers) and no caching,
so a stalled connection to github.com left the panel on "Loading
marketplace…" for minutes on every /plugins open.
Load in two phases: render the catalog as soon as it is parsed, then
resolve latest versions in the background (5s per-lookup timeout,
per-entry failures degrade to a missing badge) and refresh when they
land. Update badges appear slightly later; row order is unaffected
since sorting only depends on installed state.
* refactor(tui): move marketplace version lookup timeout to constants
Per AGENTS.md, application constants live in src/constant/ — moves
MARKETPLACE_VERSION_LOOKUP_TIMEOUT_MS next to the other marketplace
constants in constant/app.ts.
* fix(tui): resolve marketplace versions before built-in injection
Phase 1 injected built-in capability rows into the marketplace before
phase 2 ran, masking the matching catalog entries' GitHub sources
behind capability:<id> rows — so installed built-ins could never
receive update badges (the pre-change resolve-then-inject ordering
preserved them).
Keep the raw parsed catalog for phase 2, re-apply withBuiltInEntries
after versions resolve (resolved versions flow onto capability rows),
and keep the built-ins-only fallback when the catalog is unreachable.
* fix(tui): surface marketplace parse errors instead of masking them
The phase-1 catch converted every failure into a built-ins-only loaded
marketplace, hiding malformed-catalog errors behind a silently empty
Curated tab. Restore the error state for all phase-1 failures — the
panel already keeps built-in capability rows installable in the
Official tab while the error is displayed.
---------
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
- replace the Agent-scoped DI service with an eager non-durable Agent Runtime; the date_change injection provider registration now lives in an actor effect owned by the actor lifecycle, and the seed memo moves from the dateChange.seed state key into machine context
- honor eager: true for non-durable runtimes in AgentRuntimeSet so consumer-less runtimes still materialize
* fix(kimi-code): persist picked thinking effort up to the model's default effort
The persistence gate kept the model's top declared effort session-only
unconditionally, so users whose delivered default_effort is the top tier
(e.g. max) could never save an explicit pick of it. Compare the pick
against the model's default_effort instead, using support_efforts as the
strength ordering: picks above the default stay session-only, picks at
or below it persist. Models without a declared default keep the
historical top-tier rule. The same change lands in the VS Code
extension's mirrored logic.
* docs(kimi-code): document the effective-default ceiling for effort persistence
Clarify in both apps' comments, the changeset, and the config docs that
the persistence ceiling is the model's effective default effort, whether
declared via the catalog / overrides or synthesized by the protocol
profile inference (Claude models resolve to high, so an xhigh pick is
session-only there). Pin the inference path with tests in both apps.
* fix(vscode): resolve the save-config model with its provider type
Mirror the TUI's effectiveModelForHost: without the provider type the
Anthropic fallback profile (e.g. claude-latest) never matches, so the
inferred default effort that gates persistence was missed and an
above-default pick could persist where the TUI keeps it session-only.
* Delete .changeset/persist-effort-up-to-model-default.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix(vscode): seed the persisted effort with the effective-default ceiling
* fix(vscode): project webview models with the provider type
* fix(kimi-code): apply a session-only effort pick to the runtime in the /provider flow
* fix(vscode): update the persisted-effort seed on model-switch saves
* docs(kimi-code): drop the default_effort persistence-ceiling note
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix(agent-core-v2): keep agent lifecycle context active through scope teardown
* fix(agent-core-v2): deactivate agents after scope-units teardown
* fix(kap-server): install process handlers only after successful startup
* fix(agent-core-v2): let the teardown finalizer own create-failure deactivation
* fix(agent-core-v2): await asynchronous scope-units teardown before deactivation
* fix(agent-core-v2): await agent scope teardown before completing removal
* fix(agent-core-v2): mark fire-and-forget scope disposals after awaitable dispose
* fix(agent-core-v2): return the in-flight promise from repeated disposeAsync
* fix(agent-core-v2): await child containers and keep kap-server handlers through shutdown
* fix(tower): remove command queue
* feat(agent-core-v2): support an explicit base branch in TowerInit
* fix(kimi-code): keep tower objective order across a mid-turn compaction
* feat(agent-core-v2): add abandoned tower mission status to release stale scopes
* chore: consolidate tower changesets into one feature entry
* chore: consolidate tower changesets into one feature entry
---------
Co-authored-by: konghuanjun <konghuanjun@moonshot.ai>
Add a dedicated [swarm] config section so AgentSwarm subagent timeouts no longer follow [subagent] timeout_ms: timeout_ms (default 7200000, i.e. 2 hours; 0 = no timeout) with the KIMI_CODE_SWARM_TIMEOUT_MS env override, mirroring the [subagent] section. Deliberate behavior change with no fallback: a value previously set in [subagent] timeout_ms to cover swarms needs to move to [swarm]. Print mode (kimi -p) keeps its no wall-clock cap semantics: [swarm] timeout_ms also defaults to 0 there unless explicitly set. Docs updated in both locales (config-files, env-vars, tools) and the config manifest regenerated.
- define the AgentSkill contract and SkillRuntime (activate /
promptWithSkills / recordModelToolActivation) with a lazy, non-durable
provider; recordActivation dispatches SkillActivated directly and the
skillKey / SkillActivate relay is gone
- allow agent runtime descriptors to omit logic (durable definitions
still require it), making skill the first pure-API domain
- featurize the skill domain: app/skillCatalog,
workspace/workspaceSkillCatalog, session/sessionSkillCatalog,
agent/skill, and agent/tools/skill move under src/features/skill;
the static Skill tool registration and the AgentSkillService are gone
- resolve the runtime at the edge: kap-server routes and node-sdk
activateSkill go through IAgentLifecycleService.resolve, and the
klient dispatcher keeps the agentSkillService wire name over a
per-agent view
* fix(transcript): fold mid-turn task notifications into the current turn on cold rebuild
* chore: changeset for the notification fold fix
* fix(transcript): key the notification fold on persisted task-turn boundaries, not the previous message role
* fix(transcript): collect background_task turn origins too, and fall back when the wire has no turn.started records
* fix(transcript): fold consecutive task notifications into the same turn
* fix(transcript): normalize folded notification text to the live title/body form
* fix(transcript): stop folded notification text before child blocks, preserve legacy background_task turns absent from the boundary set
* fix(transcript): truncate folded notification text at the first child-block tag, not just the tag lines
* fix(transcript): drop folded notifications without a persisted step, truncate only at output blocks
* fix(transcript): attach mid-turn task notifications to the following step, cold and live
* fix(transcript): keep other tasks' notifications in task-origin turns
* fix(transcript): derive task-turn boundaries from durable turn.prompt records
* feat(transcript): carry subagent model and thinking effort on task entities
* fix(transcript): mirror turn liveness into meta.activity, live and cold
* fix(transcript): populate the prompts entity from prompt.accepted/queued engine events
* fix(transcript): reconcile liveness and the prompt queue at backfill from the live loop state
* fix(transcript): include the prompts entity in the REST transcript response
* fix(agent-core-v2): publish prompt.accepted on the event bus
* test(transcript): add the contract-level e2e covering every entity the client renders from
* fix(transcript): guard the prompt backfill against missing services; align stream expectations with prompt.accepted on the bus
* test(agent-core-v2): re-record event stream snapshots with prompt.accepted published
* fix(transcript): settle the spawned agent row when its lifecycle redirects to the task row
* test(transcript): move the contract e2e timeout to the describe arg (jest lint)
* fix(transcript): declare task model fields in the wire schema, carry prompt content on accepted, normalize queued content
- transcriptTaskSchema declares model/thinkingEffort: Zod strips
undeclared keys, so schema-driven REST/WS consumers lost both fields
the projector now populates.
- PromptAccepted carries the admitted content (it is the only event a
first-turn prompt ever emits, and the bare id left the prompts entity
permanently partial) — projected with userMessageId and the public
content shape via projectPromptContentParts, same as queued and the
live backfill.
- Regenerate the wire manifest and re-record the affected event-stream
snapshots.
* fix(transcript): preserve task model fields across termination and accepted prompt details across queueing
- onTaskLifecycle carried resultSummary/usage/error/stateReason but
dropped model/thinkingEffort: a completed detached-Agent row lost the
metadata spawned set while running.
- prompt.queued rebuilt the entity from scratch, discarding the
userMessageId and createdAt that prompt.accepted had just stamped —
build the queued update from prev.
* fix(transcript): keep prompt.accepted out of the public v1 event stream
The observable marker made the broadcaster forward every accepted
prompt to v1 WS clients, but events-zod has no accepted variant (v1
surfaces submission through the service-synthesized prompt.submitted)
and the SDK mapper didn't drop it — schema-driven clients could reject
the frame. Drop it at the WS edge and in the SDK's dropped set; the
transcript projection keeps consuming it internally.
* fix(transcript): derive cold task-turn boundaries through undo anchor replays
* fix(transcript): flush trailing folded notifications into the open turn
* fix(transcript): drop trailing buffered notifications to match the live projector
* chore: split transcript changesets per logical change
* fix(transcript): parse only the generated Title/Severity header lines in folded notifications
* fix(agent-core-v2): honor default_effort for secondary-bound subagents
[secondary_model].default_effort was parsed but never consumed, so a
subagent bound to a secondary/pool model resolved its thinking effort
from the main-oriented global [thinking].effort or the middle of the
bound model's support_efforts. Pass the section's default_effort as the
explicit spawn thinking, then fall back to the bound model entry's own
declared default_effort, both ahead of the global thinking config.
* docs(configuration): document secondary_model default_effort precedence
* fix(agent-core-v2): apply the model-default thinking fallback to tower spawns
TowerSpawnTool resolves the subagent binding directly and bypasses
planSpawn, so pool-bound tower workers never saw the bound model
entry's default_effort fallback. Apply the same resolution in launch.
* fix(agent-core-v2): preserve disabled thinking for subagents
* feat(agent-core-v2): add the unified MCP management plane
Port the v1 MCP management plane (#2858) onto the v2 DI x Scope engine:
- App-scope IMcpOAuthService shared by every workspace handler and
session overlay: credential events, single-flight refresh, proactive
refresh timers, OAuthTokenTransaction-serialized writes, offline
tokenState, shutdown. Providers read tokens through the store so
grants written or revoked by another process are honored immediately;
http/sse transports ride the transaction fetch.
- IMcpConfigStore: the single write point for the user-level mcp.json
over the filesystem byte store, byte-identical to v1's format, with
per-entry validation, name normalization, __proto__-safe parsing, a
mutation tail, and an onDidWrite event.
- IMcpRegistryService: the unified read view over the layered config
files (with per-entry origins) and plugin manifests (full descriptors
incl. disabled, with provenance); collisions stay visible and runtime
resolution ranks an enabled plugin above the file layers.
- IMcpManagementService: guarded CRUD, connection-test probes, the
locator-addressed inspection/auth-status surface, and
locator-addressed OAuth begin/complete/cancel/reset with ambiguity
rejection. Engine services stay ungated; the mcp_management flag
gates the edge exposure.
- Workspace runtime aligns with v1 precedence (an enabled plugin entry
wins over the file layers, shadows revive), and management writes
reload immediately via onDidWrite instead of the watch debounce.
- node-sdk v2 facade delegates to the engine service (deleting its
in-process duplication); kap-server exposes /api/v2/mcp/* and klient
gains global.mcp.*, both flag-gated.
* fix(agent-core-v2): settle early and cancelled MCP OAuth callbacks
* refactor(node-sdk): write session MCP persists through the engine config store
* refactor(agent-core-v2): strip comments from the MCP management plane files
* fix(agent-core-v2): harden MCP management readiness
* test(node-sdk): cover offline MCP auth statuses
* fix(agent-core-v2): isolate stdio MCP probes
* fix(klient): normalize MCP OAuth errors
* fix(mcp): honor workspace CRUD context and refresh timing
* fix(mcp): drain OAuth refreshes during shutdown
* fix(mcp): guard CRUD across registry collisions
* fix(mcp): canonicalize trust and refresh scheduling
* fix(mcp): close callback listener on setup failure
* fix(mcp): preserve trust and oauth behavior
* fix(oauth): retain refresh tokens after SDK saves
* fix(oauth): stop proactive sweep during shutdown
* fix: await MCP workspace reconciliation
* fix: serialize MCP OAuth and trust cleanup
* fix: reject persisted MCP plugin collisions
* fix: reconcile MCP workspaces concurrently
* fix(mcp): check project-layer trust at the queried cwd
* fix(mcp): expire abandoned OAuth flows after an idle timeout
* fix(mcp): keep mutable user entries writable past read-only collisions
* fix(mcp): abort the auth::complete long poll on client disconnect
* fix(mcp): map OAuth flow failures to wire code 40929
* docs(mcp): note probe credential effects and plane semantics
* chore: add the SDK changeset for MCP management cwd params
* feat(mcp): expose the management plane without the experimental flag
* fix(mcp): preserve auth management semantics
* fix(agent-core-v2): bound MCP OAuth auth-server requests and the shutdown drain
* fix(node-sdk): restate engine MCP management errors as KimiError
* fix(agent-core-v2): preserve shared OAuth flow lifetime
* fix(agent-core-v2): close MCP OAuth cancellation and shutdown gaps
- bound the authorization-code exchange with the request timeout and the
flow/caller abort signals, and make shutdown abort hung begins and close
their callback listeners immediately
- keep token-transaction effect coalescing intact when durable tokens carry
local stamps, and serialize the meta sidecar and tokens-saved event with
the token write inside the lock
- drain transport-driven grants, their trailing SDK save continuations, and
interactive completions during shutdown, with a cancellable deadline
* fix(agent-core-v2): harden MCP probe runtime resolution and path handling
- resolve stdio probes against the containing workspace's runtimes and
reject out-of-workspace probes for non-local runtime_id instead of
silently falling back to a local-only transient registry
- share one Windows-aware path canonicalization across the config loader,
registry trust lookup, trust records, and workspace matching
- keep a UTF-8 BOM fatal for the user-level mcp.json store, matching the
workspace loader and v1
- validate completeServerAuth timeoutMs bounds at the engine boundary
* fix(agent-core-v2): await workspace MCP reconciliation on plugin mutations
Plugin install/enable/disable/remove now resolve only after reload
listeners settle their waitUntil work, so a disabled plugin's MCP server
cannot linger connected and an enabled one is visible to the next
session, matching v1. The workspace MCP consumer joins the barrier while
keeping its log-only failure tolerance; delivery is awaited outside the
mutation queue to avoid self-deadlock through consumption reads.
* fix(mcp): close the SDK, klient, and server edge gaps
- register mcp.oauth_failed in the v1 error registry and restate unknown
engine codes as internal instead of minting undeclared KimiError codes
- route persisted session MCP adds through the same KimiError restating
as the global management methods
- give the klient IPC transport a per-call timeout so completeAuth's long
poll outlives the 30s default, clamped to the Node timer ceiling, and
align the contract timeoutMs upper bound with REST
- await the MCP OAuth service shutdown directly in SDK and server close
before scope disposal
* fix(agent-core-v2): keep file-over-plugin MCP precedence and harden the plane
- Revert the v1-style precedence flip: the workspace merge and
resolveRuntimeTarget keep the file entry above plugins (v2's historical
order; the divergence from v1 is deliberate and documented in AGENTS.md).
- Guards follow each engine's winner: project-layer entries stay read-only,
while plugin entries never block user-level writes, so a file entry may
shadow a plugin and removing it revives the plugin. The parity suite pins
the engine split for a persisted session add over a plugin-owned name.
- inspectServers tolerates a wire-encoded null targets array: klient's ipc
transport sends null for an omitted leading optional argument.
- Fire the config store's onDidWrite after the mutation tail settles, so a
write listener can re-enter the store without deadlocking the queue;
concurrent-mutation and re-entrant-listener tests pin both contracts.
* chore: condense the sdk MCP changeset to one sentence
* test(node-sdk): pin verify:false auth-status parity and fix the sdk changeset
- Name authoritative data sources in the intro (World Bank, IMF, OECD, FRED,
WHO, FAO, NBS, Wind, S&P Capital IQ, SEC EDGAR, Caixin, Xinhua Finance,
Gildata) so users can see what backs the plugin
- Turn the eight 'what you can do' scenarios into collapsible details blocks
with question-style headers (title — question?) so the page stays scannable
- Coverage table: add a financial-news/industry-data row (Caixin, Xinhua
Finance); name Yuandian Legal for the legal row; macroeconomics row now
also covers China government data and IGO official statistics
- Only sources approved for both domestic and overseas publicity are named;
restricted sources are described by capability instead
* feat(agent-core-v2): turn /tower into a mode parallel to plan mode
* feat(agent-core-v2): align /tower command semantics with the original skill behavior
* fix(tui): harden the /tower command against mid-turn objectives, legacy engines, and stale status
* fix(agent-core-v2): keep restored tower state inert while the feature flag is off
* fix(agent-core-v2): include TowerInit in the mode tool overlay and report flag-gated tower state
* feat(agent-core-v2): expose tower control tools statically and make the mode injection history-derived
* fix(tui): warn that tower mode needs a restart after a live flag flip; drop redundant undefined from SessionStatus mode fields
* fix(agent-core-v2): let tower mode exit clear persisted state while the flag is off
* fix(agent-core-v2): emit the tower exit reminder through a disabled flag and drop the redundant REST state comparison
* fix(tui): show the Tower mode status row only when the experiment is available
* fix(agent-core-v2): confine tower mode to the main agent and always re-assert it for objectives
* feat(kap-server): project tower mode into transcript modes and reassert explicit toggles
* fix(agent-core-v2): fold the main-agent invariant into the effective tower state
* fix(kap-server): gate the cold tower mode badge behind the experiment flag
* fix(agent-core-v2): reapply the tower tool overlay after a profile bind; fix(kap-server): clear cold tower badges on non-main agents
* fix(protocol): mirror towerMode and tower_mode in the shared zod schemas
* test(agent-core-v2): adapt tower tests to the agent lifecycle context architecture
* chore(agent-core-v2): regenerate the wire manifest; test(node-sdk): look up the main agent via findAgentHandle
* fix(agent-core-v2): exit a replayed tower mode when the workspace belongs to another session
* fix(agent-core-v2): carry tower ownership in the enter record so forks clear inherited mode
* fix(agent-core-v2): apply the tower overlay before dispatching enter and repair it on status updates
* fix(agent-core-v2): validate store ownership before entering tower mode
* fix(agent-core-v2): claim the repository tower owner at enter; fix(tui): confirm mode activation before reporting success
* fix(agent-core-v2): make the first tower claim exclusive and refuse adoption over a live owner
* feat(agent-core-v2): guard tower adoption and teardown with a cross-process ownership lease
* revert(agent-core-v2): drop the cross-process lease and enter-time claim, keep ownership checks process-local
* fix(agent-core): hide the v2-only tower flag from the legacy experiments list
* fix(agent-core-v2): keep tower mode inert until the tower feature is assembled
A live /experiments flip refreshes the flag but cannot re-run App-scope
feature assembly, so the tower tools/profile stay unregistered until a
restart. Gate enter()/isActive on the assembly fact and say so in the
TUI error. Also resolve the AGENTS.md conflict block committed by the
merge, and widen the TUI experimentalFlag type to string now that flags
live in two registries.
* fix(kap-server): gate the cold tower badge on tower feature assembly
Same live-flip gap as the mode machinery: a persisted tower_mode.enter
plus a flag enabled without a restart would still show the badge while
the feature is inert. Require isTowerFeatureAssembled() alongside the
flag, re-exported from agent-core-v2.
* fix(agent-core-v2): liveness-aware tower entry and per-App assembly state
enter() now mirrors TowerInit's adoption rule: a stored owner blocks
entry only while that session is live in this process, so a new session
can enter the mode and reach TowerInit to adopt a stale tower. The
assembly marker is keyed by each App's flag service (WeakSet) instead of
process-global module state, so coexisting Apps no longer leak assembly
into one another.
* fix(agent-core-v2): keep stale-owner adoption across resume; reject tower updates that do not take
exitForeignTower now treats a stored owner as foreign only while that
session is live, so a mode entered by adopting a dead owner's tower
survives close/restart. The TUI validates the model prerequisite before
enabling tower for an objective, and the REST agent_config path throws
session.tower_mode_invalid when enter() did not take effect instead of
acknowledging a no-op.
* fix(agent-core-v2): clear the tower assembly marker when the feature unloads
Register the WeakSet cleanup via the feature's onDispose so the
capability follows the managed unit's lifecycle — after
unprovideUnit('tower'), isActive/enter() no longer treat the retracted
tool set as assembled.
* fix(agent-core-v2): publish tower deactivation on gate loss; reject refused setTowerMode in the SDK
isActive now reconciles its projection: restore and feature-manager unit
changes publish AgentStatusUpdated({ towerMode: false }) when the
persisted mode lost a gate (flag off at runtime, feature unloaded), so
live transcript badges and TUI state stop showing an inert mode. The
SDK's setTowerMode(true) verifies the effective state and throws
session.tower_mode_invalid, matching the REST path.
* fix(agent-core-v2): reconcile tower projection on config changes and cold ownership moves
The last unreconciled gate inputs: a live setConfig writing the
experimental section (no session reload, no units event) now republishes
towerMode:false through the config-change subscription, and the cold
transcript badge mirrors the same ownership/liveness rule as enter() —
retained while the store owner is this session or no live session, cleared
once a live session elsewhere owns the tower.
* fix(agent-core-v2): reconcile the tower projection in both directions
The OFF-only reconcile left a hole: re-enabling the flag in the same
process made isActive true again with no towerMode:true publish, and
enter() could not heal it (it early-returns when already effective).
The projection now tracks the last published state and emits both
false→true and true→false transitions from the same restore/units/config
triggers; direct publishes (enter/exit/restoreTowerTools) keep the
tracker in sync.
* fix(agent-core-v2): validate forked tower ownership even while the flag is off
exitForeignTower's flag short-circuit let a fork restored while the
experiment was disabled keep its inherited enter record; re-enabling the
flag later revived both source and fork over the same store. Ownership
validation is flag-independent state hygiene, so restore now runs it
regardless of the effective flag — a live foreign owner clears the
fork's persisted mode before any gate can rise again.
* fix(agent-core-v2): veto tower tools while the tower experiment is off
With the feature assembled and the tool overlay active, disabling the
flag live left TowerInit/TowerTeardown callable — they have no flag
check — so prompts could still mutate or dismantle .tower/ while the
experiment reported disabled. A dedicated onBeforeExecuteTool hook now
denies every tower tool whenever the flag is off, mirroring the TodoList
veto.
* fix(agent-core-v2): keep tower worker write isolation when the flag turns off
The worker Write/Edit guard is identity-scoped (tower-worker profile),
not feature-activity-scoped: disabling the experiment live must not let
already-spawned detached workers write into the main checkout or other
worktrees. The guard no longer checks the flag; the tower-tool veto
added earlier covers protocol access instead.
* test(agent-core-v2): make tower tests hermetic for CI
Three CI-only failures: towerService git fixtures committed without a
repo-local identity (CI has no global gitconfig), the node-sdk tower
positive tests relied on the developer shell's
KIMI_CODE_EXPERIMENTAL_FLAG=1 master switch instead of enabling the
tower flag explicitly, and the legacy harness experimental-features
expectation still listed the tower entry removed from the v1 registry.
Add a shell path bridge that translates between win32 paths and the
MSYS2/Git Bash path dialect. File tools resolve model-supplied paths
through it before canonicalization and workspace checks: drive-letter
forms translate lexically, root-relative paths resolve via cygpath -w
with per-segment caching, and every failure mode falls back to the
previous behavior.
Fixes#2199
A failed resume is cached by SessionManager and rethrown from
whenResumeSettled, so archiving a session whose workspace is gone
failed with the stale resume error even though cold archive only
rewrites session metadata. Swallow the settle failure: still wait for
an in-flight resume before the live/cold classification, but fall
through to the cold metadata path after a failed one.
* feat(agent-core-v2): add a fork parameter to the Agent tool
Spawning with fork: true starts the subagent from a one-time snapshot of
the calling agent's completed conversation history — same profile, tool
set, and model — instead of zero context. The seed trims the trailing
open tool exchange (the in-flight Agent call itself) before appending
into the child's context memory, and the first prompt carries an
inheritance notice framing the seeded history as reference material.
Fork rejects resume, a different subagent_type, or a model override as
tool errors, and skips the subagents allowlist since a self-inheritance
is not a delegation.
* fix(agent-core-v2): bind the stale-todo reminder only into the main agent
Subagents share the session todo list but no longer receive the
stale-todo nudge — the reminder injector now registers only on the main
agent, so delegated and forked agents are not prompted to maintain a
list they do not own.
* fix(agent-core-v2): inherit the caller's live binding and label fork launches correctly
Review follow-ups for the Agent tool fork mode:
- overlay the caller's live profile.data() via applyBindingSnapshot after
the catalog re-bind, so ephemeral addActiveTool deltas, the rendered
system prompt, and runtime model/subagents updates survive the fork;
skip the profile prompt prefix since the caller's prefixed first
prompt is already part of the seeded history
- resolve the fork activity label and approval-rule subject from the
caller's own profile instead of falling back to the default subagent
type, so an Agent(<other profile>) rule cannot approve a fork
* fix(agent-core-v2): close inherited in-flight tool calls instead of trimming them
Fork seeding now answers the source's trailing open tool calls with a
synthetic in-flight result instead of cutting the whole trailing
exchange: the seeded history stays protocol-valid, keeps the source's
final step visible as reference, and no longer confuses side-question
(btw) agents forked while the main agent is mid-turn. The close helper
is shared by the Agent tool fork and IAgentLifecycleService.fork.
Fork launches also stop requiring the caller's profile to still exist
in the session catalog: the child is created unbound and overlaid with
the caller's live binding snapshot, matching the lifecycle fork path,
and now records forkedFrom provenance.
* refactor(agent-core-v2): route Agent tool forks through agentLifecycle.fork
* feat(agent-core-v2): add a fork parameter to the AgentSwarm tool
* fix(agent-core-v2): seal partial assistant forks
* fix(agent-core-v2): align fork parameter descriptions
* fix(agent-core-v2): drop the main-only registration gate from goal tools
* fix(agent-core-v2): disclose dates via reminders to keep the system prompt byte-stable
* docs: condense the fork changesets to single sentences
* docs(agent-core-v2): frame the tool-contribution when gate as a fork parity trade-off
* test(agent-core-v2): plug fork coverage gaps and decouple swarm tests from spawn internals
* docs(agent-core-v2): keep the when-gate guidance in the contribution JSDoc only
* fix(agent-core-v2): contribute cron tools to every agent for fork prefix-cache parity
CronCreate/CronList/CronDelete were registered directly into the main
agent's tool registry by SessionCronServiceImpl, bypassing the
AgentToolContribution seam and keying on per-agent identity — so a forked
agent rebuilt a tool surface three tools shorter than its caller and the
inherited prompt prefix missed the cache.
Register the three tools through registerAgentToolService like the goal
tools do (no when gate, identical surface for every agent) and enforce
the main-agent restriction at execution time instead. Also fall back to
DEFAULT_CRON_CONFIG when the config section is absent, since the service
can now be constructed after the main agent exists.
* feat(agent-core-v2): track the fork parameter in the subagent_created event
* fix(agent-core-v2): gate tower orchestration tools at execution time
TowerInit/TowerPlan/TowerSpawn/TowerMerge/TowerTeardown were contributed
with a when predicate keyed on agentId === 'main', so a forked agent
rebuilt a tool surface missing TowerInit (always present for the default
profile) plus the rest of the tower set once it was enabled — breaking
prompt prefix-cache parity with the caller.
Contribute the tools with no when gate (profile policy still controls
visibility) and reject non-main callers at execution time instead.
* test(agent-core-v2): expect the fork field in the subagent_created mirror assertion
* test(agent-core-v2): cover fork subagent first-request prefix parity
* refactor(agent-core-v2): share the main-agent-only tool refusal across cron and goal tools
Goal tools rejected subagent callers by throwing GOAL_UNSUPPORTED_AGENT
from the service, which the executor wrapped as a resolution failure;
cron tools returned a clean refusal but each tool open-coded the same
identity check. Centralize the check and both messages in
agent/tools/mainAgentOnly.ts and use it from all seven tools, keeping
AgentGoalService.assertSupportedAgent as the coded boundary for RPC and
SDK callers.
* refactor(agent-core-v2): keep the goal main-agent gate at the tool layer only
* fix(agent-core-v2): preserve the fork tool surface when inheriting user tools
* Revert "refactor(agent-core-v2): keep the goal main-agent gate at the tool layer only"
This reverts commit fc09a8fa32.
* test(agent-core-v2): complete fork lifecycle stub
* Delete .changeset/btw-inflight-tool-calls.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* Delete .changeset/todo-reminder-main-only.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* Delete .changeset/swarm-fork-context.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* Add optional 'fork' parameter to subagent tools
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* docs(agent-core-v2): drop the fork JSDoc comments
* feat(agent-core-v2): add prompt_cache_probe telemetry for forked agents
* feat(agent-core-v2): gate the subagent fork parameter behind an experimental flag
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix(agent-core-v2): guard config persistence against lossy writes
- A failed load no longer clears the in-memory snapshot: the service keeps
the last-known-good config, reports an error diagnostic, and taints.
set/replace/replaceSections on the persisted layer then fail fast with
Error2(config.persist_blocked) instead of erasing the file; memory-layer
overrides stay available, and a successful reload clears the taint.
- persistDomains is now read-modify-write: the file is re-read and only the
domains being written are applied on top of current disk content, so
external edits are merged instead of clobbered, and an external delete is
honored instead of resurrected.
- External changes absorbed at persist time trigger a full reload so change
events fire for domains the writer did not touch.
* fix(agent-core-v2): rebase set() merges onto re-read config state
set(domain, patch) now merges the patch against the freshly re-read file
content and refreshes the in-memory snapshot from the same read, so external
edits to the same section survive a concurrent write instead of being
overwritten by the stale in-memory copy.
* fix(protocol): register config.persist_blocked in KimiErrorCode
Add the new code to the KimiErrorCode union and kimiErrorCodeSchema so the
persist-refusal error payload passes protocol validation across RPC
boundaries.
* fix(agent-core-v2): compute every config write against the re-read file
Move strip/merge/validate for set/replace/replaceSections into the persist
rebase callback so each write is derived from the file content re-read at
persist time. Overlay strip handlers (e.g. the KIMI_MODEL_* mask restoring
default_model) now read the fresh snapshot instead of the stale in-memory
one, and the unconditional snapshot sync makes the separate
absorbed-external reload redundant.
* fix(agent-core-v2): build defaults when the initial config load fails
A failed first load has no last-known-good state worth preserving, so fall
through with an empty document: registered section defaults are still
validated and applied (consumers of defaulted sections keep working), while
the taint keeps blocking persisted writes until a reload succeeds. Only
reload failures preserve the previous in-memory state.
* fix(agent-core-v2): stage re-read config snapshots until the write succeeds
Build the rebased raw/rawSnake snapshots in locals and publish them only
after the rebase and documentStore.set both succeed, so a validation error
or a storage failure cannot leave userValue and effective pointing at
different snapshots. stripEnv now takes the staged snapshots explicitly.
Split the dense prose walls into a minimal config, a one-line-per-field
table, constraint bullets, a numbered resolution order, and a separate
advanced subsection for per-entry thinking efforts. All behavioral facts
are preserved; zh and en stay mirrored.
The startup banner now comes from the backend client_configs endpoint
(config name client_banner) instead of the CDN-hosted tips.json, and is
fetched fresh on every startup with no caching. The payload keeps the
tips.json shape, plus two targeting additions:
- banner_platform (top level and fallback entries) limits display to
the given platform; missing, empty, or all means every platform, and
the CLI only shows entries targeting all or cli.
- banner_start_time/banner_end_time on fallback entries add scheduled
visibility windows with the same semantics as the active banner.
Finished `!` output collapses to the first 10 visual rows with a `... (N more lines, ctrl+o to expand)` marker, sharing the global ctrl+o toggle with agent tool output; ctrl+o also expands the live buffer while the command runs. Replayed output mounts the same card and behaves identically. The shared truncation component, the running card's default view, and the agent bash path are unchanged.
* feat(datasource): add NDA/NBS, standards, IGO, xhcj, and caixin sources
* fix(datasource): narrow real-time-news ban to coverage gaps, require PublishTime citation
* fix(datasource): scope the real-time-news limitation to coverage gaps only
* fix(datasource): trim redundant clause in the real-time-news limitation
* fix(datasource): stop on a result that covers the question, not the first success
* fix(datasource): front-load trigger terms in the skill listing description
* fix(datasource): exempt discovery calls from the one-call workflow
GET /api/v2/sessions gains view=by_workspace: one request returns every
workspace with a matching session, each carrying its first group.page_size
sessions under the requested sort plus the workspace's full matching total,
with group-level page_token pagination (40922 on condition drift). Groups
key on the alias-canonical workspace id, so legacy split buckets of one
physical directory merge into a single group, matching the v1 alias
semantics. meta.has_prompt filters sessions by prompt presence (the v1
exclude_empty equivalent) in both views. The flat view and v1 routes stay
byte-compatible.
The global WS stream now fans out event.session.archived (live and cold
paths; payload carries the session id and workspace_id) and
event.workspace.created/updated/deleted, published by the core
IWorkspaceService on every mutation path including the implicit
createOrTouch on session creation.
kimi-inspect consumes the grouped projection as a single-column
workspace/session tree in the chat view; the session pane merges into the
right dock as the Session tab. The server API reference (en + zh) documents
the new parameters, the grouped response, and the new events.
* feat(agent-core-v2): rework the title generation excerpts
- Rebalance the excerpt budgets toward the user's prompts (400 chars
each) and trim the assistant segments (300) so titles follow the
user's task instead of narrating the assistant's reply.
- Cap each prompt in the default user_prompts excerpt so one long
paste no longer starves the remaining prompts.
- Compose the digest excerpt from the full conversation arc: every
natural-language user prompt in the live window paired with its own
turn's final assistant text, interleaved chronologically, with
per-segment caps and a 3000-char total budget (middle turns elided).
* chore: scope the title changeset to agent-core-v2
* fix(agent-core-v2): dedupe digest prompts and elide whole turns
- Drop the redundant `| undefined` from the optional
TitleDigestTurn.assistant per the monorepo optional-property
convention.
- Deduplicate user messages by id when constructing digest turns, so a
prompt already in the context and still active in the queue does not
produce two turns.
- Elide the over-budget digest at whole-turn granularity, keeping each
assistant line paired with its own user line.
* docs(agent-core-v2): describe the full-arc digest in the SessionTitleSource contract
* fix: fail fast on provider-filtered empty responses
An APIEmptyResponseError carrying finishReason 'filtered' (OpenAI
content_filter, Anthropic refusal) is deterministic: replaying the same
request re-triggers the provider safety filter. Both isRetryableGenerateError
implementations (kosong, agent-core-v2) treated every empty response as
retryable, so step retry replayed the doomed request the full 10 attempts
before the filter notice surfaced. Return non-retryable for filtered empty
responses in both engines; the error already carries the provider.filtered
code, so the turn fails immediately with the existing filter notice.
* fix: skip the compaction shrink-retry for filtered empty responses
Both full-compaction loops routed every APIEmptyResponseError into the
shrink-and-continue branch before isRetryableGenerateError was consulted,
so a filtered response was retried with shrinking input instead of failing
fast. Exclude finishReason 'filtered' from the shrink branch in both
engines; it now falls through to the retryability check and throws
immediately. Add end-to-end tests (real kosong generate over a filtered
think-only stream) asserting a single attempt with the history untouched.
---------
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
* feat(kimi-code): add China/International region selection for OAuth login
- Add region profiles (cn/overseas) and resolver in @moonshot-ai/kimi-code-oauth:
env override → persisted login host → install-channel marker → default cn
- /login now offers Kimi Code (China) / Kimi Code (International); the CLI
login entries (kimi login, kimi acp --login) accept --region cn|overseas
- Update/plugin/site/telemetry endpoints derive from the selected region;
plugin trust list covers both .com and .ai hosts
- kap-server: POST /oauth/login accepts an optional region; new GET /oauth/region
* fix(oauth): keep an explicit default-slot login ahead of the install marker
A China login persists no oauthHost (the default credential slot carries
no host trace), so after switching back from International the resolver
fell through to a stale overseas install marker. Treat a persisted
default-slot oauth ref (key === oauth/kimi-code) as an explicit-cn signal
that outranks the marker; getRegion() on the v2 side mirrors it.
* fix(agent-core-v2): thread the default-slot key through capability region resolution
Capability installs resolved the region from the persisted oauthHost only,
so an explicit China login (which persists no host) lost to a stale
overseas install marker. Pass the oauth ref key through as well, matching
getRegion(). Also move the region contract notes into the auth.ts file
header per the package comment convention.
* fix(agent-core-v2): honor the region-marker opt-out for the telemetry endpoint
Hosts that set KIMI_CODE_REGION_MARKER=off (the desktop embedded server)
skip the install marker in getRegion(), but the default telemetry endpoint
still consulted it, so a stale overseas marker could split the reported
region from the telemetry destination.
* feat(cli): show region site domains in login platform selector
* chore: reword oauth login changesets
* fix: honor the region marker opt-out in the CLI and capability resolvers
* refactor: rename login region values to mainland-cn and global
* fix: keep the --region help text in English
* fix: simplify the --region help text to site domains
* feat: drop the suggested login platform order
* feat: split a browser-safe region profile table out of the region resolver
* Revert "feat: split a browser-safe region profile table out of the region resolver"
This reverts commit a037b1143e.
* fix: read the install marker from the bootstrapped home directory
* fix: resolve the server plugin marketplace from the active login region
* feat: expose the login region option through the klient auth facade
* fix: drop a comment from the v2 auth region test
* fix: keep scoped base-only logins on their environment for a bare login
* fix: invalidate the region cache on the provider-manager logout path
* fix: route client-config fetches through the active region profile
* fix: resolve the telemetry endpoint per flush so a login region switch applies in-process
* test: expect the telemetry endpoint resolver in the CLI init assertions
* fix: resolve the default telemetry endpoint from the bootstrapped home
* chore: reword the oauth login changeset around the two login methods
* chore: trim the oauth login changeset to the headline
* feat: let hosts override the region marker env through the server bootstrap env bag
- give the builtin agent profile an explicit subagents allowlist (coder, explore, plan), restoring v1 semantics
- inherit the default profile's allowlist when a caller profile declares none, instead of leaving delegation unrestricted
- pass a lone "*" subagents field through as an explicit unrestricted marker
* docs: document KIMI_CODE_CUSTOM_HEADERS on the env vars page
* docs: address review on KIMI_CODE_CUSTOM_HEADERS entry
- use a neutral gateway header name in the example
- correct the release version to 0.20.2
- scope the override claim to exact-name matches and warn against
case-variant auth headers
* docs: describe protocol-dependent Authorization precedence
On the OpenAI-compatible protocols (kimi/openai/openai_responses) an
exact Authorization custom header is applied after the SDK-generated
bearer token and therefore replaces it; /models listing keeps its own
authentication.
* docs(zh): add the required space before the config-files link
Per the mixed-content spacing rule in docs/AGENTS.md.
---------
Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
* fix(kap-server): serve real session usage in snapshot and persist per-turn context readings
* fix(kap-server): omit unknown session usage fields instead of reporting zero
* refactor(agent-core-v2): persist cron tasks as durable wire records
- write CronAdd/CronDelete/CronCursor as durable wire records and rebuild the cron task table from dispatcher replay
- migrate legacy per-workspace cron JSON files into the wire on first resume, then drop the file-based persistence service, its registrations, and the bootstrap cron scope
- derive the session cron view from the agent replayable cron state and remove the redundant session-level copy
- let session forks inherit cron tasks through the copied wire instead of duplicating task files
* fix(agent-core-v2): keep legacy cron tasks on cold forks and flush before cleanup
- inherit legacy cron task files into a full fork's wire so cold sessions forked before their first post-upgrade resume do not silently lose scheduled tasks
- flush the migrated wire records before deleting legacy files so a crash cannot lose both copies
* refactor(agent-core-v2): drop the legacy cron file migration
- stop reading legacy per-workspace cron JSON files entirely; pre-upgrade tasks simply stop applying instead of being migrated into the wire
- remove the legacy read path, the fork-time legacy inheritance, and the now-unused session context/document store injections
* refactor(kap-server): table-driven dispatch for multi-action routes
- add a shared action-dispatch helper; sessions, prompts, plugins, questions, and modelCatalog collection routes declare action tables with module-level handlers
- add ISessionManager.status returning the session summary; the archive action checks it instead of resuming the session
- archive cold sessions through the persisted-metadata path shared with batch archive
* fix(agent-core-v2): read-your-writes for session index point gets
Overlay pending mirror summaries in getFromReadModel so a freshly recorded
summary (e.g. cold-session archive) is visible to GET immediately, matching
the existing pending overlays in list and cursor resolution.
* feat(agent-core-v2): carry prompt attachments on turn.started so the live transcript projects them
* fix(transcript): clear the transcript goal when the goal is cleared
* fix(agent-core-v2): count a prompt media part as a transcript attachment only when its id matches its daemon file URL
* test(kap-server): expect the session-media file id on converted prompt parts
Move the external hook services out of app/externalHooksRunner,
session/externalHooks, and agent/externalHooks into
features/externalHooks, assembled as the ExternalHooksFeature unit:
- services live under per-scope subdirectories (app/, session/, agent/);
shared pure helpers (types, hook matching/dispatch, process spawn,
prompt result rendering) live under internal/
- the runner and the two observers are contributed through the Feature
seams (ScopeUnits materialization); the hooks config section stays on
the static import=register channel
- update the package entry leaf exports, the plugin domain imports, the
kap-server events-zod import, and the affected tests; regenerate the
state manifest
* fix(vscode): multi-select question jumps to next after only one answer selected
* chore: add changeset
---------
Co-authored-by: gaoyuan <gaoyuan@moonshot.ai>
* fix(agent-core-v2): emit subagent.spawned after task registration
The spawned signal previously fired at launch, before the run's task
registration, so clients learned the agent id with no task id to bind
cancel/status actions to; a failed registration also left a spawned row
behind for a run that never registered. Emit it only after registerTask
succeeds and carry the task id on the event.
* fix(agent-core-v2): keep spawned ahead of started for Agent-tool runs
The TUI drops subagent.started until spawned has established the row,
and a failed registration must not leave a started row behind with no
terminal event. Defer the mirrored started dispatch so the Agent tool
can emit it itself after registration and spawned.
* fix(agent-core-v2): void the deferred started dispatch
* fix(kap-server): key Agent-tool transcript rows by the registered task id
Transcript-protocol clients suppress the raw task.*/subagent.* session
events, so they only saw a subagent row keyed by agent id that cannot
address /tasks/{id}, plus a second row once task.started landed. Key the
spawned row by the task id it now carries, fold task.started and the
subagent lifecycle back into it, and keep the agent-id path for spawns
without a registration (swarm/session-init/tower). Statement-level
ordering notes move to the file headers per package convention.
* test(agent-core-v2): split the spawned/started ordering contract into its own test
* fix(kap-server): keep subagent result details across task termination and drop stale task mappings on taskless respawns
* fix(kap-server): recover the agent-to-task association from a backfilled task.started
* fix(kap-server): seed pre-attach Agent task mappings on the transcript binding
* fix(kap-server): seed the full in-flight task row on transcript bind, not only its id
* docs(agent-core-v2): name the state-domain event dispatcher in the Agent tool header
* style(kap-server): drop comments in transcript services per the no-comments lint rule
* feat(kimi-code): specialize the WaitFor tool's transcript display
* feat(agent-core-v2): emit status progress while WaitFor is pending
* fix(kimi-code): route WaitFor dimming through the TUI theme
* feat(kimi-code): support replaceable status updates in tool progress
* fix(kimi-code): forward status progress to subagent activity surfaces
* fix(agent-core-v2): drop the redundant undefined from ToolUpdate.replace
* fix(kimi-code): honor replace semantics in the subagent live status path
* test(agent-core-v2): drive the WaitFor progress test through a manual tick
* fix(kap-server): mirror ToolUpdate.replace in the ws event schema
* refactor(agent-core-v2): expose the WaitFor progress scheduler as a public seam
* fix(kimi-code): pass child wait statuses without the trailing newline
* feat(agent-core-v2): tick the WaitFor progress status every second
* feat(agent-core-v2): format WaitFor progress durations as 1m 15s
* feat(agent-core-v2): omit zero seconds and minutes in WaitFor durations
* refactor(agent-core-v2): unify the loop-event fold into one core with two materializations
The loop-event stream was reduced by two hand-mirrored state machines:
loopEventFold.ts for the live/replayed context and contextTranscript.ts
for the full transcript behind the messages endpoints, kept in sync by
comments alone and already drifted (transcript dropped tool-result note
metadata and never closed a dangling tool exchange at step.end).
createLoopEventFold now owns the shared state machine once (settle,
pending tool exchanges, deferred appends, vacuous tracking) and both
views plug in as LoopEventFoldSink materializations. New parity tests
pin the foldedLength === live length invariant the endpoints splice on.
* fix(agent-core-v2): drop every removed prompt's injections on multi-turn transcript undo
The transcript undo only walked prompt-owned injections off the oldest
counted anchor, so with count > 1 an injection owned by a newer removed
prompt (e.g. an image-compression caption) survived the display undo
while the live context removed it. Collect every counted anchor's id
during the walk and sweep their owned injections afterwards, keeping
the transcript's 'prompt-owned ones leave with their prompt' contract
for every count and matching the live view.
* refactor(agent-core-v2): drop module headers from the context fold modules
The comment-free zone lint only allows JSDoc on exported symbols.
* fix(agent-core-v2): recover fold state after rehydration
* fix(agent-core-v2): scope undo injections to their prompt
* fix(agent-core-v2): settle open transcript frames when compaction lands mid-fold
An overflow-triggered compaction arrives with the failed attempt's
frame still open. The transcript appended the summary marker and reset
the fold but left the frame, so a vacuous partial stayed in the entries
while the live context dropped it, and a pending tool exchange lost its
interrupted result. Settle through the shared fold core at the marker
instead: close pending tool calls, drop or seal the open frame, then
append the summary. recoverFoldedLength recomputes the absolute count
right after either way.
* fix(agent-core-v2): keep legacy compaction recovery on the pre-settlement count
A legacy context.apply_compaction record (compactedCount without
keptUserMessageCount) recovers foldedLength as 1 + (foldedLength -
compactedCount), and the live legacy tail shape keeps the unsettled
open frame inside history.slice(compactedCount). Settling the fold for
those records shifted foldedLength by the settlement delta before the
recovery read it, leaving the transcript count one off the live
context. Gate the settle to modern records; legacy records keep the
previous freeze-and-reset behavior.
* fix(agent-core-v2): stop advertising unavailable ReadMediaFile to non-multimodal models
* fix(agent-core-v2): honor the effective tool policy before advertising ReadMediaFile
* fix(agent-core-v2): keep media-unavailable guidance reason-neutral and within the active toolset
* fix(agent-core-v2): recommend MCP fallbacks only when an active MCP tool exists
* fix(agent-core-v2): stop naming other tools in Read descriptions and errors
* fix(agent-core-v2): drop tool roster from plan agent prompt
Assistant messages carrying only tool calls were serialized without a
content key (JSON.stringify drops undefined), which strict
chat-completions validators such as LiteLLM reject with a 422,
permanently poisoning the session. Emit content: null for such messages
in both the kosong and agent-core-v2 converters, matching the shape
OpenAI responses use alongside tool_calls. The think-only empty-string
behavior in agent-core-v2 and both Kimi providers' deliberate content
omission are unchanged.
* feat(agent-core-v2): add the WaitFor tool for waiting on background tasks
* fix(agent-core-v2): mark WaitFor deliveries only after formatting succeeds
* fix(agent-core-v2): cancel losing waits once the WaitFor race resolves
* test(node-sdk): project WaitFor out of the v1-v2 resume parity roster
* fix(agent-core-v2): gate WaitFor goal guidance behind the wait_for flag
* fix(agent-core-v2): gate WaitFor goal guidance on actual tool availability
* fix(agent-core-v2): enforce the wait_for flag at WaitFor execution time
* fix(agent-core-v2): consult the live tool policy in the WaitFor availability check
#2593 replaced AgentVideoResolverService with the image+video
AgentMediaResolverService and reduced videoResolverService.ts to a pure
deprecated alias with no DI registration. #2909's squash merge restored
the pre-#2593 file wholesale, bringing back the legacy class and its
registerScopedService call. Both classes then registered the same token
('agentVideoResolverService') at the Agent scope and the legacy
video-only resolver won on the production import order, so image
kimi-file:// references reached the provider unresolved. Gateways
reject the unknown scheme with a 400 ("unsupported image url"), the
media-strip fallback then hid the image from the model, and pasted
images only worked on undo-resend via the inline base64 fallback.
Delete the legacy alias files and their index exports, drop the stale
alias assertion, and pin the behavior with a klient e2e regression:
a kimi-file image prompt part must reach the provider as a data: URL,
never verbatim.
* fix(kimi-code): upload pasted videos to the daemon file store
Video paste staged a cache copy and submitted a bare file:// video_url,
which the v2 engine no longer resolves, so the submission failed and the
persisted history retried it on every turn. Mirror the image flow
instead: upload the paste to the daemon file store in the background and
submit a kimi-file:// reference that the engine's prompt intake
materializes. A video whose upload is still in flight, failed, or
expired now refuses the submission with an actionable error, since video
bytes have no inline fallback form.
* test(kimi-code): fix MessageDriver recallStashedMedia signature
* chore: sync web dist from code-app
code-app: 1fb57f0ee3
* chore: sync web dist from code-app
code-app: 93da508d079b0118cc0338da97dcb738f0a3d46f
Adds the web session admin page. Built from the code-app PR #261 branch tip before its merge; the squash-merged main tree is expected to be identical (will be checked at merge time and rebuilt here if not).
* chore: correct the code-app trailer of the previous sync commit
The previous commit's trailer had a mistyped code-app SHA. The dist content is byte-identical to a build of code-app main at the merge below (tree verified identical to the branch tip it was built from), so the watermark for the next sync is:
code-app: 025805b33f
* feat(kimi-code): support automatic updates for native installations via staged swap
Native (SEA) installs previously could not self-update on Windows and
relied on 'curl | bash' re-install on Unix. Replace both with a staged
swap updater:
- startup swaps in a staged binary (verified against the release
manifest sha256, smoke-checked via --version) and re-execs it, so the
running process never replaces itself (Windows-safe)
- downloads run in a self-spawned hidden sub-command, in the background
from the update preflight or in the foreground from 'kimi upgrade'
- rollback from .bak on any swap failure; install failures keep the
existing retry/prompt thresholds
* fix(kimi-code): fully clean staged artifacts on swap discard paths
Real-binary smoke testing on macOS surfaced two cleanup gaps in the
discard path: the claimed metadata file was unlinked after the staging
dir rmdir (so the empty dir survived), and the staged exe was
rediscovered via the already-claimed staged.json (so it leaked on the
downgrade-guard path). Pass the known metadata through and order the
unlink before the rmdir.
* fix(kimi-code): restore staged metadata on swap failure and sweep update leftovers at startup
* fix(kimi-code): address codex review on lock contention and swap crash window
- The background native install no longer takes the outer install lock:
the self-spawned downloader holds it for the whole download, and the
parent's spawn-time lock raced the child into a false lastSuccess.
- Smoke-check the staged exe before moving anything, so a bad staged
binary is discarded with the install path never left empty; the
remaining crash window is two adjacent atomic renames (documented,
recoverable via the .bak or by re-running the install script).
* test(kimi-code): align swap test expectation with smoke-before-rename order
The restore-on-failure case now observes the early smoke check's
--version spawn; only the re-exec spawn must be absent.
* fix(kimi-code): stage the bare CDN binary instead of unzipping
The published per-release artifacts are the bare platform binaries
(kimi-code-<target>[.exe]), not zip archives — the staging flow now
streams the download straight to the staged exe after the manifest
sha256 check, and the zip reader is dropped. Verified end-to-end on
macOS against the live CDN: download -> sha256 match -> swap ->
re-exec into the real released binary.
* fix(kimi-code): address second codex review round
- re-exec: forward 128 + signo when the swapped-in child dies by signal
instead of reporting exit 0
- __update_download: only exit 0 without staging when the lock holder is
staging the SAME version; a different in-flight version (or a vanished
lock) no longer surfaces as a successful foreground upgrade
- staging: sweep orphaned .part downloads and unreferenced staged exes
before downloading, preserving live swap claims and their payloads
* feat(kimi-code): show download progress for native updates
The foreground 'kimi upgrade' path streamed 180 MB with a single static
'Downloading…' line. Render progress instead: a throttled in-place
percentage line on a TTY, one line per 32 MB when piped, and plain MB
counts when Content-Length is unknown.
* fix(kimi-code): bound native update downloads with an idle timeout
Codex review: the manifest fetch cleared its timer once headers arrived,
so a stalled response body hung the worker forever, and the binary
download had no abort at all. The manifest timeout now covers body
consumption, and the binary stream aborts after 30 s without a chunk
(total duration stays unbounded for slow networks). The idle timeout is
injectable for tests.
* fix(kimi-code): retry native updates blocked by an orphaned active record
Windows real-machine verification surfaced that a parent exiting before
the downloader's exit event leaves a fresh-looking 'active' record that
silently blocks every background retry for the 6 h TTL. For native
installs, lock liveness is the truth past a 60 s spawn grace window:
a held lock means a download is running, a free lock means the record
is an orphan and a new attempt may start. Package-manager sources keep
the TTL behavior (no lock to prove liveness).
* fix: skip staged swap while another instance holds a fresh claim
sweepStaleNativeUpdateArtifacts already detected an in-progress swap in
a concurrent instance, but the result stayed inside the cleanup helper:
startup still claimed a newly published staged.json and ran a second
swap, so the two launchers could rename the install path and delete each
other's rollback backup. Propagate the in-progress signal and skip
claiming until the existing claim is released or goes stale.
* fix: keep the install lock while its holder process is alive
The install lock went stale purely by age (30 min), but the native
downloader is idle-bounded, not duration-bounded: a slow link can
legitimately take longer. Another startup would then sweep the lock and
spawn a second downloader, and both would write and clean the same
.staging paths. Past the age threshold, fall back to a pid liveness
probe (signal 0) — the lock is stale only when the holder is gone.
* fix: keep recovery artifacts on rollback failure and wait out same-version downloads
Two robustness fixes from review:
- native-swap: when moving the staged exe into place fails AND the
rollback rename fails too (transient lock, AV), the install path is
left absent and no next launch can start. Discarding the staged
payload and claim on top of that removes the second recovery copy.
rollback() now reports its result; on a double failure the swap keeps
the .bak (which IS the old exe), the staged exe and the claim so
manual recovery or a re-install still works.
- update-download: a foreground `kimi upgrade` racing a background
downloader of the same version exited 0 immediately, so the CLI
printed a success message for a download that could still fail. The
worker now waits while the same-version holder is in flight, adopts
the verified staged result (staged.json lands before the lock is
released), and takes over the download when the holder finished
without staging.
* fix: stamp the swap claim with a fresh mtime when claiming
rename() preserves the staged metadata's mtime, which can be arbitrarily
old — the background download often finishes hours before the next
launch claims it. A concurrent launch's sweep would then classify the
live claim as crash residue (older than the 5-minute window) and delete
the claim, the staged exe, and eventually the first swap's rollback
backup. Stamp the claim file with the claim time so the staleness check
measures the swap's liveness, not the download's age.
* fix: stamp the claim before the rename so it is born fresh
Stamping after the rename left a window: a concurrent launch could
inspect the claim between the two syscalls, see the staged metadata's
old mtime, and delete the staged executable mid-swap. utimes the state
file first so the claim carries a fresh timestamp from the instant it is
published — no fresh-looking-later intermediate state exists.
* fix: chmod the staged download before publishing it at its final name
A swap claims only the staged METADATA; the staged exe stays in
.staging/. A concurrent same-version downloader (possible because swaps
do not hold the install lock) then re-downloads and renames its .part
over that path. If the swap moves the file into the install path between
the downloader's rename and its post-publish chmod, the chmod lands on a
path that is already gone and the installation is left non-executable —
every future launch fails. Apply the executable mode to the private
.part file before the publishing rename so the staged exe is executable
from the instant it appears.
* fix: publish the install lock atomically via hard link
The 'wx' open exposed a momentarily empty lock file before its contents
were written. A concurrent acquirer reading in that window got a
SyntaxError, treated the lock as stale, swept it and also won — two
"holders" then ran stageNativeUpdate against the same .staging paths.
Write the lock contents to a unique temp file and hard-link it into
place: link() fails when the destination exists (same exclusivity as
'wx') and the lock path only ever appears fully written.
* fix: serialize stale-lock takeover through a secondary lock
A pathname-level delete can never be conditioned on the file still being
the inspected stale instance, so a plain compare-and-delete still loses
exclusivity: two workers classifying the same stale lock could interleave
unlink and publish such that both won (proven by a 20-way contention
test). Takeovers now go through a secondary create-if-absent lock
(install.lock.takeover): the delete+publish section only ever runs in
one process, staleness is re-validated inside it, and a fast-path creator
that wins the briefly-free path simply beats the takeover. The takeover
lock itself is age-swept (a live section lasts microseconds), and handles
only release the lock instance they own.
* fix: verify lock ownership after publish and preserve freshly staged exes
Two more race fixes from review:
- install-lock: the stale-marker sweep repeats the inspect-then-delete
race one level up — two contenders sweeping the same aged takeover
marker could both win and enter the main-lock section together.
Pathname APIs offer no conditional delete, so both the takeover marker
and the main lock now verify ownership after publishing (unique marker
content, read-back compare): a racing sweep converts to a single
survivor instead of two holders. The irreducible residual (a delete
landing in the microsecond link-to-verify window) degrades to a wasted
download cycle, never a corrupt install — swap claims guard the exe
independently.
- native-swap: sweeping a stale swap claim deleted the exe it referenced
even when a FRESH staged.json referenced the same version-derived name
(a downloader re-staged the version after the swap crashed), throwing
away a verified ~180 MB stage. The sweep now preserves any exe the
current staged metadata still references.
* fix: reject mismatched manifests, take over from dead holders, unique .part names
Three robustness fixes from review:
- native-manifest: the per-release endpoint can answer with ANOTHER
release's manifest (stale cache, mispublish); its checksums would then
be applied to this version's binary and fail verification on every
attempt. Compare the parsed manifest version with the requested one.
- install-lock/update-download: a killed lock holder skips its finally
and never releases, stranding a waiting foreground `kimi upgrade`
forever. A lock whose recorded pid is dead is now stale at any age
(the atomic publish guarantees the pid was alive when written), and
the same-version wait loop polls the acquisition itself, so a dead
holder's lock is taken over within one poll instead of never.
Package-manager spawns are unaffected: they hold the lock only around
the spawn, and the active-record bookkeeping guards that layer.
- native-stage: the download intermediate is now unique per worker
(`.part` carries pid + counter), so overlapping same-version workers
can no longer interleave writes into the same file.
* fix: restrict staging cleanup to updater-owned names and retry short writes
- cleanupStagingOrphans recursively deleted anything it did not
recognize; the staging dir sits next to the exe and can contain files
belonging to the user or another tool. Deletion now requires a
positive match on updater-owned artifact names (staged exes and .part
intermediates) and only ever unlinks files.
- FileHandle.write may persist fewer bytes than requested (short write,
e.g. near disk exhaustion) while the running hash and size already
accounted for the whole chunk — publishing a truncated binary under a
valid checksum. The chunk write now loops until fully persisted.
* fix: scope failure cleanup, recognize all semvers, reverify staged checksums
Three fixes from review:
- native-stage failure cleanup deleted whatever staged update was
currently published — including a concurrent worker's valid result
that its caller had already reported as success. The catch path now
removes only this attempt's own artifacts: its unique .part file and
its staged exe name when the current metadata does not reference it.
- The orphan-cleanup ownership check only matched stable x.y.z names;
prerelease/build-metadata versions (1.2.3-rc.1, 1.2.3+build) would
never be cleaned and accumulate ~180 MB each. Ownership now derives
from the semver contract via the semver package's valid().
- The swap path trusted a staged exe whose size matched, though the
metadata records the release checksum; post-download on-disk damage
could pass the --version smoke check with corrupted bytes.
claimStagedUpdate now re-verifies the staged exe's sha256 before
claiming and discards the stage (for a later re-download) on mismatch
— paid only when an update is actually pending.
* fix: validate versions before path derivation and honor the update opt-out in the swap
- native-stage: stageNativeUpdate derived staging paths (including the
cleanup rm targets) from the version before fetchNativeReleaseManifest
rejected it; a traversal string like `x/../../kimi` would resolve the
staged-exe cleanup onto the running installation. The semver check now
happens before any path is derived, and the staged-metadata schema
constrains exeFileName to a plain file name.
- native-swap: the startup swap ran before the update preflight, so
KIMI_CODE_NO_AUTO_UPDATE / KIMI_CLI_NO_AUTO_UPDATE stopped gating
update behavior once a payload was pending. The swap now honors the
same opt-out: the staged payload stays in place for a later launch
without the variable, and the current exe starts.
* fix: restrict backup cleanup to updater-owned .bak names
cleanupBackups treated every <exe>.*.bak sibling as swap residue, so a
user's own backup like kimi.config.bak in a shared bin directory was
silently deleted on startup. Only the exact <exe>.bak and the numeric
PID fallback <exe>.<pid>.bak are updater-created — cleanup now
positively matches those two formats.
* fix: claim staged metadata before validating it and let manual upgrades bypass the opt-out
- native-swap: claimStagedUpdate validated the metadata and hashed the
staged exe BEFORE the atomic rename, so a concurrent downloader
superseding staged.json in between could get its fresh metadata
claimed under the older object — the smoke check then failed and
discard() deleted the newly published stage, recording a failure for
the wrong version. The claim (utimes + rename) now happens first and
validation acts on exactly the claimed file; discards use a new
discardClaimedUpdate that never removes anything a meanwhile-published
stage references.
- The auto-update env opt-out gated the startup swap unconditionally,
so an explicit `kimi upgrade` with the variable set staged the
version but no launch ever applied it. Stages now record
`manual: true` when they answer a user-initiated install
(`__update_download --manual`, threaded from installUpdate through
the hidden sub-command), and the swap applies manual stages even when
automatic updates are opted out.
* fix: promote adopted stages to manual and preserve claim-referenced payloads
Three follow-up fixes from review:
- An explicit `kimi upgrade` adopting an auto-staged payload (already
on disk, or still downloading via the wait path) returned before the
manual marker applied, so under the env opt-out the swap still skipped
it despite the success message. Both adoption paths now promote the
staged metadata to manual: true via a new promoteStagedUpdateToManual.
- The download-failure cleanup checked only the current staged metadata,
but a live swap holds the metadata renamed aside as its claim — a
failing same-version downloader could delete the exe an active swap
was about to move into place. The catch path now also preserves names
referenced by any live swap claim.
- Restoring a claimed stage after a failed exe move used rename, which
on POSIX replaces a newer staged.json a downloader published during
the smoke check. The restore is now a create-if-absent hard link: it
only lands when the state-file path is still free, and the older claim
is discarded when a newer stage has taken it.
* fix: drop exe deletion from stale-claim cleanup
The stale-claim sweep deleted the referenced exe based on a metadata
snapshot taken before the loop; a downloader republishing the same
version between the read and the unlink would have its fresh payload
deleted after reporting success. Publication can never be synchronized
with a pathname-level snapshot, so the sweep now removes only the claim
files themselves — genuinely unreferenced exes are reaped by the
downloader's own orphan cleanup (keep-set aware) before its next stage.
* fix: never delete the staged exe when discarding a claim
The same publication race existed one level down: a same-version
downloader can rename its fresh payload onto the shared exe path after
the discard's metadata snapshot but before the unlink (payloads publish
before their metadata), and the discard would delete a download whose
caller then reports success with nothing behind it. discardClaimedUpdate
now removes only the claimed metadata file; unreferenced exes are reaped
by the downloader's own orphan cleanup before its next stage.
* fix: only reap staging orphans old enough to be abandoned
The orphan sweep could delete a concurrent worker's freshly renamed
staged exe in the gap before its staged.json lands (payloads publish
before their metadata), turning the admitted duplicate-worker race into
a successful stage with no payload behind it. Unreferenced artifacts are
now only deleted once older than a one-hour grace period — publication
takes milliseconds, so unreferenced AND old means definitively
abandoned.
* fix: honor the persisted auto-update preference in the swap and drop claim-unsafe deletions
- The startup swap gated only on the env opt-out, so a payload staged
automatically still installed after the user disabled automatic
updates via [upgrade] auto_install = false. The swap now loads the
persisted preference (only when an automatic stage is actually
pending) and skips it, exactly like the env opt-out; manual stages
still always apply.
- Superseding a staged version deleted its exe through an uncoordinated
read-then-remove that could pull the payload from a live swap. The
supersede now removes only the old metadata record — the metadata
write atomically replaces it, and an unreferenced exe is reaped by a
later orphan cleanup. removeStagedNativeUpdate, left with no callers,
is removed.
- docs: the kimi upgrade reference (en + zh) no longer claims Windows
native installations cannot upgrade automatically; native installs
download and verify in the foreground and swap on the next start.
* fix: gate on claimed metadata, stop shared-path deletes on failure, exact smoke match
- The opt-out gate evaluated a pre-claim snapshot of the staged
metadata, but the claim could pick up a different (automatic) stage a
downloader published in between — smuggling it past the gate. The
env/preference check now runs on the CLAIMED metadata; when disabled,
the claim is restored via create-if-absent link so a newer stage is
never overwritten and a later launch can still apply it. The checksum
re-verify moves after the gates so opted-out launches stop paying for
the hash.
- The download-failure cleanup still deleted the shared staged-exe path
based on snapshot reference checks — the same publication race as the
paths already fixed. It now removes only the attempt's privately owned
.part file; the shared exe is left for the age-gated orphan cleanup.
- The smoke check accepted the staged version as a substring of the
--version output, so a mispublished 1.2.30 binary would satisfy a
1.2.3 target with a matching manifest checksum. It now requires the
trimmed output to equal the staged version exactly.
* fix: confirm the manual marker before reporting stage adoption
promoteStagedUpdateToManual silently no-oped when a startup swap had
claimed the state file, while the adoption paths still reported success
with manual: true synthesized — under the env opt-out the restored
automatic metadata would then be skipped on every later launch despite
the upgrade's success message. The helper now verifies the marker with a
confirming read (one retry) and returns whether it persisted; the
already-staged branch falls through to a fresh stage when it does not,
and the same-version wait loop only adopts after a confirmed promotion.
* fix(cli): verify the staged payload digest before adopting it as already-staged
readStagedNativeUpdate checks only the recorded size, so a same-size
corruption after the download was adopted and reported as success, only
for the startup swap's claim-time re-verify to reject and discard it.
Compare the actual sha256 before returning already-staged; a mismatch
falls through and re-stages from the CDN.
* fix(cli): keep staged metadata until its replacement is ready
Two related races around staged.json, both reported against the
duplicate-downloader residual:
- stageNativeUpdate deleted the previous record before downloading its
replacement; a pathname-only delete can remove a concurrent worker's
freshly published record, orphaning a payload whose worker already
reported success. The old record now stays until the final atomic
metadata write replaces it.
- promoteStagedUpdateToManual wrote the marker unconditionally onto
whichever generation owned staged.json. It now takes the adopted record
and promotes only while the on-disk metadata still matches it, and the
post-write confirmation requires the promoted candidate itself.
* fix(cli): preserve the exe referenced by the current staged record during orphan cleanup
Since the supersede path now keeps the previous staged.json until the
final atomic write replaces it, an aged staged exe is still the
applicable update while its replacement downloads — but
cleanupStagingOrphans only pinned exes referenced by swap claim files,
so a payload older than the grace period was unlinked out from under
its own record. Read staged.json itself in the pinning pass so the
current record's exe is preserved like any live claim's.
* chore(kimi-code): reword the native auto-update changeset
* chore(kimi-code): trim the native auto-update changeset
* fix(cli): support update locking on filesystems without hard links
link() fails with ENOTSUP/ENOSYS/EPERM on FAT/exFAT and some network
mounts, which aborted every native update before the download. Add a
shared createFileIfAbsent primitive (hard-link a fully written temp
file, falling back to an exclusive create + write) and use it for the
install lock, its takeover marker, and the swap's claim restore. The
fallback's create->write gap is observable, so the lock inspection now
grants young unparseable content a publish grace before sweeping it as
crash residue.
* fix(cli): publish staged exes under unique names and recover orphaned claims
Two related robustness fixes in the staged swap flow:
- A staged executable is now published under a unique per-worker name
(kimi-<version>.<pid>.<epoch-ms>.<n>[.exe]) and never replaced; the
atomic metadata write retargets the pointer. The pathname a swap
validates at claim time can no longer be exchanged by a concurrent
same-version publisher between validation and install.
- restoreClaimedUpdate only drops the claim when the restore landed or a
newer stage holds the state-file path; transient failures retain it.
The stale-claim sweep now restores aged claims (create-if-absent)
instead of deleting them, so a stage orphaned by a dead swap or a
transient restore failure is retried on a later launch.
* fix(cli): verify the staged payload digest in the lock-wait adoption path
waitForStagedUpdate relied on readStagedNativeUpdate, which checks only
the recorded size: while a holder re-stages a same-size-corrupted
payload (its metadata is replaced only when the repaired generation
publishes), a waiter could promote and report the corrupt stage as
downloaded, and startup would later reject its checksum. Apply the same
integrity bar as stageNativeUpdate's already-staged path — adopt only a
payload that hashes to its recorded checksum; a mismatch falls through
to the lock poll, which takes over once the holder finishes without
repairing it.
* fix(cli): serialize swap critical sections and preserve in-flight publishes
- The fresh-claim sweep is only a directory snapshot: two processes could
both pass it before either claimed, then rename the same installed exe
concurrently and delete each other's rollback backup. A create-if-absent
swap mutex (swap.lock, age-gated like the takeover marker) now serializes
the executable-renaming section; the loser restores its claim and defers.
The mutex is released as soon as the new exe is in place, before the
re-exec, so it is never held for the child session's lifetime.
- claimStagedUpdate no longer destroys a claimed record that is unparseable
but was young at claim time: on filesystems without hard links the
exclusive-create publish is observable mid-write, and discarding it would
orphan the staged exe while the writer reports success. Such a record is
put back with the same inode so the writer completes it; aged corrupt
residue and well-formed records with a missing/changed exe are still
discarded.
* fix(cli): keep backup cleanup inside the swap mutex
The early release let a subsequent swap rename the just-installed exe to
the shared .bak path while the previous swap's cleanup was still about to
unlink that same path, destroying the second swap's rollback source. The
mutex now covers the backup cleanup; the cosmetic staging-dir rmdir and
the re-exec stay outside it.
* test: replace prose-pinning system-prompt tests with a structural sharing check
The two removed tests pinned exact sentences of the default system prompt
('reversibility and blast radius', 'premature abstraction', optional-tool
phrasings that must not appear, ...). They broke on any intentional
wording change while only catching regressions that reused the same words.
The one real contract underneath — shared, ungated sections must render
byte-identically in the root agent and every subagent profile — is now
checked structurally by slicing the section out of the root prompt and
asserting the other profiles contain it, regardless of its wording.
* test: remove wording-pinning tests of model-facing prose across both suites
Sweep of the class identified in #3030: assertions pinning the exact
English wording of product model-facing text (system prompt, reminder
and injection .md files, tool descriptions, shipped profile/skill
bodies). They break on any intentional rewording yet only catch
regressions that reuse the same words.
Across 35 files (~60 test cases, net -1131 lines):
- deleted dedicated wording tests: 'exposes current metadata and
schema' description pins, goal/plan/todo reminder content tests,
tower skill-body prose pins, goal-outcome.test.ts;
- trimmed wording assertions from behavioral tests that otherwise
stand alone; kept identifiers (tool names, XML tags, section
markers), structural properties (wrapping/escaping/gating/cadence),
fixture data, tool outputs and error messages;
- re-anchored a few gating tests on exported constants
(WINDOWS_PATH_HINT, DEFAULT_REPLY_STYLE_GUIDE) instead of prose
literals.
Deferred for a follow-up decision: ~15 tests whose prose pin is the
only discriminator of which reminder/budget-band fired (constants not
exported). Wire baselines and snapshot machinery untouched.
#3028 removed the 'treat ambiguous requests as tasks' rule and its
'locate the method in the code' example from the default system prompt.
The profile test pinned that example verbatim, so it now fails on main.
The removal was intentional; update the test to the new contract.
* feat(kap-server): accept bundled skill activations on the prompt submission route
The bundled-submission capability was only reachable through the
in-process klient transports; the App talks to kap-server over /api/v1.
The submit-prompt route now accepts an optional non-empty skills field
and delegates to IAgentSkillService.promptWithSkills — same validation,
events, and single bundled user message as the TUI path — skipping its
own prompt-metadata update (the engine owns it there) and mapping
skill.not_found / skill.type_unsupported onto the skills route's codes.
To return the submission's queue identity, the engine's promptWithSkills
now resolves with prompt_id / user_message_id / created_at / state (plus
turn_id once launched), mirrored through the klient contract.
* refactor(agent-core-v2): slim the promptWithSkills result contract
Drop the user_message_id field (it is always the same identity as
prompt_id — the route duplicates it) and narrow state to the
running/queued/blocked vocabulary, mapped at the engine edge instead of
exposing the internal seven-state PromptState on the wire.
* fix(kap-server): harden bundled skill submissions against review findings
- Validate bundled skill names and types before any media materialization
or control override, so a rejected bundle leaves session state untouched
(the engine still re-validates authoritatively).
- Declare the 40415/40912 outcomes on the submit route so the generated
API documentation includes them.
- The klient output schema no longer tolerates a missing promptWithSkills
result (a transport-level absence now raises instead of resolving
undefined), and a failed launch surfaces as an error rather than a
successful running result.
- Add the changeset for the new public API field.
* fix(kap-server): preflight bundled skills before agent materialization and stabilize listed content
- Skill preflight now runs on the session's catalog before the main agent
is resolved, so a rejected bundle cannot mutate session metadata by
registering main (regression test on a cold session without an agent).
- The prompts list projection strips the stored skill blocks from a
bundled prompt, so GET /prompts returns the same caller-only content as
the submit response.
* fix(kap-server): reject bundled prompt_id combos at preflight and clean queued staging
- The skills + prompt_id incompatibility rejection now runs at the initial
bundled preflight, before the main agent is materialized or any
override binds (previously a yolo override could bind before the 40001).
- Queued bundles no longer skip staging cleanup forever: the discard is
deferred to the bundle's prompt.completed / prompt.aborted lifecycle
event, mirroring the plain path's launch-raced cleanup.
* fix(kap-server): clean queued bundle staging on the steer path too
A queued bundle steered into the active turn is consumed at steer time,
but the engine publishes prompt.completed/aborted only for the parent —
the deferred cleanup never fired and its subscription leaked. The
prompt.steered event (matching promptIds) now counts as the child's
intake-completion signal.
* fix(agent-core-v2): materialize daemon-ref media on the steer and inject paths
startNext materializes daemon file references into the session media
store before a prompt's turn, but steer() and inject() enqueued the same
references without that intake, leaving the staging upload as the only
copy — any staging cleanup at steer time would delete the media the
turn is about to consume. Both paths now run the same intake before the
SteerStepRequest is created, so prompt.steered is a truthful
intake-complete signal.
* fix(kap-server): defer staging cleanup to turn settlement, never to steer time
Prompt-intake materialization is best-effort: when it degrades, the
daemon upload is the request-time resolver's fallback source. Discarding
staging at prompt.steered could therefore delete the only readable copy
before the parent's request ran. Cleanup is now uniformly event-driven —
the bundle's own prompt.completed/aborted, or the steer parent's — so
the upload always outlives the request it feeds.
* fix(kap-server): install settlement tracking before bundled enqueue
A hook-blocked bundle completes synchronously inside the submission
call, and an exceptionally fast launch can settle just as early — a
post-call subscription misses the only settlement event and leaks both
the staging blob and the listener. The tracker now subscribes before
enqueueing, buffers lifecycle events, and settles against the returned
prompt id (or its steer parent's).
* fix(kap-server): scope settlement tracking to the owning agent and dispose on rejection
- The tracker now subscribes through the agent-scoped IEventBus instead of
the App-scoped IEventService: prompt lifecycle events from other
sessions never reach it, so a colliding client-chosen prompt id cannot
trigger a foreign settlement (and the steer re-target only follows this
agent's parent).
- A bundled submission that rejects after the tracker was installed now
disposes it on the error path instead of leaking a permanent listener.
* fix(agent-core-v2): keep steered prompts queued until their media intake finishes
Materializing a steered prompt's daemon-ref media awaits a file copy
during which the active turn may finish. Records are now spliced out of
the queue only after that copy completes, and when the turn is gone by
enqueue time they are restored to pending so startNext can launch them
as fresh prompts — their handles always launch or settle.
* fix(agent-core-v2): revalidate the queue and active turn after steer media intake
The daemon-ref copy yields, so settle/abort can consume selected records
and the active turn can rotate meanwhile. Only records still pending are
steered, and only into the turn that was active at entry; records that
vanish from the queue are left to their own launch path, and a missing
turn restores them to pending instead of splicing an unrelated tail
prompt. The intake/queue-preservation contract is documented in the
module header.
* fix(agent-core-v2): steer only the surviving records and keep their media truthful
- The steered content is rebuilt from the records that are still pending
after the media intake, so an aborted or concurrently consumed record's
text is never injected (or injected twice) alongside the surviving
handles.
- The enqueue is wrapped so an activeTurnOnly rejection restores the
records to pending (the loop throws instead of resolving a missing
turn, which made the previous rollback unreachable).
- The merged origin now carries the union of every record's bundled
skillActivations, and prompt.steered publishes the caller-only content,
so the skill instructions reach the model with their metadata intact
while the event projection stops leaking internal skill markdown.
* fix(agent-core-v2): harden steer rollback and register bundled prompt ids
* fix(agent-core-v2): strip bundled blocks from prompt.queued and reject partial steers
* fix(kap-server): update session metadata for bundled prompts routed to subagents
* fix(agent-core-v2): restart queue after raced steer rollback and prefix skill blocks in merged steer
* fix(agent-core-v2): block queue advancement during steer admission
* chore: drop the changeset for server-only protocol plumbing
* fix: tone down over-proactiveness in the default system prompt
The default system prompt pushed the agent to act before discussing:
ambiguous requests were explicitly resolved to tasks, the opening framed
the primary goal as taking action, and 'default to making progress, not
to asking' discouraged clarifying questions.
Trim both copies (agent-core and agent-core-v2) by deletion only:
the ambiguous-means-task rule and its example, the action-framed opening
clause, the 'default to taking action with tools' paragraph, the
duplicated must-use-tools sentence (kept once in Ultimate Reminders),
and the 'default to making progress, not to asking' bullet. Operational
guidance and the execution guards stay untouched.
* Delete .changeset/tame-system-prompt-proactiveness.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix: drop the tool-use and no-placeholder bullets from the default system prompt
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* chore: remove internal-network references from comments and test fixtures
- Reword two comments that named the internal free-tokens model
registration flow; the generic OAuth / managed wording carries the
same meaning
- Replace the qianxun.example placeholder base URL in google-genai and
runtime-provider tests with genai-gateway.example
- Swap realistic-looking LAN fixture IPs in the kimi web banner tests
(192.168.98.66, 10.8.12.216) for RFC 5737 documentation addresses
(192.0.2.66, 198.51.100.216)
* chore: retrigger CI (flaky kap-server searchRoute title-indexing test)
---------
Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
* feat(kap-server): add page-number mode and total to GET /api/v2/sessions
The v2 session list gains a stateless 1-based `page` parameter beside the
opaque page_token cursor for admin-style lists that jump arbitrarily:
each request stays a full independent snapshot, no token is minted, and
`page` + `page_token` together fail 40001. Every response now carries
`total` (the filtered/sorted set size) in both pagination modes.
* feat(kap-server): add meta.updated_before filter to GET /api/v2/sessions
Symmetric with meta.updated_after (inclusive boundary, Unix ms), applied
at the edge over the drained set and bound into the page_token query
fingerprint like every other condition.
* feat(kap-server): add POST /api/v2/sessions:archive and :restore batch endpoints
Batch archive/restore for session-management views: { ids } (non-empty,
≤5000 unique after dedup) answers per-item results in input order with
succeeded/failed counts — only a body validation failure fails the whole
request, and an unknown id folds into its own item as 40401.
The live/cold split keeps the batch cheap: a session with a live handle
goes through the full ISessionLifecycleService chain (agents drain,
scope teardown, mirror drain), while a cold session is never
materialized — the new setColdSessionArchived helper in agent-core-v2
patches the persisted state.json (archived/archivedAt, updatedAt
preserved, mirroring setArchived's touchUpdatedAt: false semantics),
mirrors the flipped summary into the read-model queue, and republishes
the same event.session.archived bus event the live lifecycle emits
(:restore publishes nothing, matching the live restore). Hot items run
with bounded concurrency and the batch ends with one shared
ISessionIndexMirror.drain().
* docs(server-api): document v2 sessions page mode, total, updated_before, and batch archive/restore
* fix(kap-server): deep-import workspace lifecycle symbols in the v2 sessions route
CI's tsgo/rolldown (Linux) fail to bind liveHandlerForSession and
IWorkspaceLifecycleService through the agent-core-v2 package-root
barrel even though it re-exports them; the same files use the
established deep-import pattern already used for the git domain.
* fix(kap-server): inline the live-handler lookup in the batch route
The previous deep imports still fail to resolve on CI's Linux toolchain
(tsgo TS2307, rolldown MISSING_EXPORT) while every other module path
from the same package binds fine. Keep the route self-contained: the
hot-path lookup is a five-line loop over IWorkspaceLifecycleService's
handlers (mirrors agent-core-v2's liveHandlerForSession), and the tests
assert non-materialization behaviorally via the live map instead of
importing the same two symbols for spies.
* fix(kap-server): drive the batch hot path through getLiveSessionById
The phantom only hits the workspaceLifecycle-group symbols in these two
files on CI's Linux toolchain; getLiveSessionById is observed to bind
fine there. It returns the session's live scope directly (no resume),
which is exactly what the batch hot path needs.
* refactor(kap-server): move the batch live/cold split into agent-core-v2
setSessionArchivedBatch owns the split next to the cold patch: live
sessions go through the full lifecycle chain via the workspace handler
accessor (the v1-proven resolution path), cold sessions through the
direct write. The route becomes a thin wire-code adapter, and the batch
tests assert the live chain behaviorally (disposal, events, index)
instead of spying through scope accessors.
* fix(agent-core-v2): import sessionLookup relatively from coldSessionArchive
The '#/app/workspaceLifecycle/*' specifier resolves from src/ and
src/app/* files on CI's Linux toolchain but not from
src/workspace/sessionLifecycle/ (tsgo TS2307, rolldown follows); a
relative import bypasses the package-imports mapping.
* fix(agent-core-v2): migrate the batch hot path to ISessionManager
Main's workspace/session DI refactor removed the workspaceLifecycle
lookup modules; the live branch now goes through the App-level
ISessionManager (the same entry the v1 action route uses post-refactor)
with getLiveSessionById from the new sessionManager lookup.
* feat(kap-server): add the id,archived item projection to GET /api/v2/sessions
fields=id,archived trims each item to { id, archived } for
select-all-matching flows (the session admin page's Gmail-style
select-all). Only that projection gets the relaxed page_size ceiling
(10000); unknown fields, non-pair subsets, and include=git combinations
are 40001, and the projection binds into the page_token fingerprint so
shapes never flip mid-pagination.
* fix(agent-core-v2): serialize the batch cold write against in-flight resumes
Codex review on #2983: while a resume is in flight the live registry
hides the handle, so the batch route could classify the session as cold
and its direct write would race the materializing metadata service (its
stale in-memory document wins the next write, silently un-archiving the
session after the endpoint reported success).
The batch now settles the resume first: SessionManager registers the
whole resume promise synchronously at the App level (controllerForSession
is async, so the controller's own resuming map learns about it a few
microtasks late) and whenResumeSettled awaits it before classification —
a settled resume lands the item on the live chain, a failed one falls
back to the cold path. Also folds the module header down to the
package's external-role comment convention.
* fix(agent-core-v2): publish SessionArchived as an Event2 class in cold archive
* fix(agent-core-v2): serialize batch archive/restore with session lifecycle transitions
* fix(agent-core-v2): serialize session delete with the lifecycle chain
* fix(agent-core-v2): mirror the persisted metadata on cold archive, not the index summary
* docs(agent-core-v2): bring sessionManager comments and new tests to package conventions
* fix(agent-core-v2): normalize legacy session metadata before the cold archive write
* fix(kap-server): serialize the v1 single-session archive with the lifecycle chain
* chore: drop changesets for internal-only protocol work
* fix(agent-core-v2): encode cold-archived metadata for v1 readers
* fix(agent-core-v2): serialize fork and createChild with the source session's chain
* refactor(agent-core-v2): chain every session lifecycle method and hand batch sections unguarded ops
* fix(agent-core-v2): propagate failed resumes to the next settle
* fix(agent-core-v2): roll back the unannounced handle when a resume fails mid-materialization
* fix(agent-core-v2): read and migrate the legacy session-meta location on cold archive
* fix(agent-core-v2): serialize explicit-id session creation with the lifecycle chain
create() with a caller-supplied sessionId bypassed the per-session chain,
so a concurrent batch archive could classify the half-created session as
cold and write archived state that the live metadata service later
overwrites. Creation now queues on the target id's chain whenever an
explicit id is present.
Also type the resume-failure maps as Error and normalize at the catch
site, satisfying only-throw-error.
* style(kap-server): strip comments from the session routes per the no-comments convention
* fix(agent-core-v2): serialize explicit fork and child target ids on the lifecycle chain
fork() and createChild() with a newSessionId locked only the source id, so
a batch archive of the target could slip into the creation window: the
index already knows the half-created session, the batch writes archived
state to its document, and the fork's in-memory metadata later overwrites
it. Both operations now acquire the deduped, sorted key set so multi-key
sections always take locks in one deterministic order.
* Rewrite pending changesets for the new changelog conventions
* chore: drop the /tower changeset per reviewer request
* chore: trim pending changeset entries further per reviewer feedback
---------
Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
* Simplify the gen-changesets skill
* chore: state only what changed, drop explanatory trailing clauses
* docs: require strict adherence to the changeset rules in AGENTS.md
---------
Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
* fix(kimi-code): revert the todo panel to its pre-turn state on undo
* fix(kimi-code): hide all-done todo lists on undo refresh and detach SDK todo state
* fix(agent-core-v2): degrade media tool registration when the bound model alias is stale
A restored session replays its persisted profile.bind without catalog
validation, so the profile can carry a model alias that no longer
resolves (e.g. the managed kimi-code models were removed from
config.toml on logout). AgentMediaToolsRegistrar.refresh() called
modelCatalog.getRequester() unguarded on that alias; the throw escaped
the agent.status.updated listener and was reported as an [unexpected]
Error2 (config.invalid) on startup.
Catch the resolution failure and degrade to "no model": media tools
stay registered off the profile-reported capabilities, just without a
model-bound video uploader, matching the tryResolveRawModel style used
elsewhere in the profile service.
* test(agent-core-v2): reproduce the stale-alias regression with production-consistent collaborators
A stale alias makes the real AgentProfileService report
UNKNOWN_CAPABILITY, so the regression now binds unknown capabilities,
asserts the tool stays unregistered without surfacing an [unexpected]
error, and covers recovery once the alias resolves again. The rationale
moves into the mediaToolsRegistrar file header per the package comment
conventions.
---------
Co-authored-by: Mira <bj456736@users.noreply.github.com>
* refactor(agent-core-v2): carry the context fold cursor in state and converge fold/projection internals
- ContextModel state is now { messages, fold }: the loop-event fold cursor
(openStepUuid / pending / deferred) lives in the state instead of a
module-level WeakMap keyed by array identity, so wholesale replacements
(undo / clear / compaction / swarm exit) reset it structurally via
EMPTY_FOLD instead of a manual resetFold at five call sites.
- The display transcript and the wire model now share one generic fold
kernel (FoldFrame / FoldEntryAdapter), eliminating the mirrored second
implementation. Events tagged with a non-open step uuid are dropped and
step.end settles only the step it names — defensive in abnormal streams,
identical on well-formed ones (v1 replay unaffected).
- IAgentContextProjectorService converges to project(messages, policy) with
a ProjectionPolicy data object; llmRequester builds the policy from retry
state instead of selecting among four methods.
- Blob rehydrate now also covers messages still deferred in the fold cursor.
- ContextState is deeply frozen at the op boundary to preserve the consumer
immutability the wire's shallow freeze gave the bare array state.
* test(agent-core-v2): move fold parity rationales into the test file header
* docs(agent-core-v2): move fold declaration comments into module headers
* refactor(agent-core-v2): merge FoldFrame into generic ContextState
* refactor(agent-core-v2): compile-enforce part/event handling decisions in context memory
- isVacuousContentPart and dehydrateRecord now switch exhaustively over
ContentPart / LoopRecordedEvent variants, so a new variant fails
compilation until it takes an explicit position
- the transcript/model parity comparator spreads whole messages and masks
only summary content, so new ContextMessage fields join the comparison
automatically
- correct two stale header comments: local message ids persist with
append_message records, and undo's prompt-owned-injection pairing
depends on them after a resume
* refactor(agent-core-v2): converge undo-cut decision in conversationTime
The model Op and the display transcript each walked the undo anchors with
their own loop, and the transcript partially removed the tail when an undo
was blocked (compaction summary / clear floor / too few anchors) while the
model side no-ops at the precheck. Move the walk into conversationTime as
computeUndoCut/computeUndoCutFrom applied destructively by the context.undo
Op and non-destructively by the transcript reducer, so a blocked undo reads
identically on both sides.
Also: make isUndoAnchor exhaustive over origin kinds with a never assertion,
mirrors the compaction result message count via compactionHandoff, and
extend UndoCut with anchorIndex distinguishing the counted anchor from the
injection-extended cut point.
* fix(agent-core-v2): drop removed prompts' injections on multi-turn transcript undo
The transcript's kept-loop retained every injection after the oldest
counted anchor, so with count > 1 a prompt-owned injection of a newer
removed prompt (e.g. an image-compression caption) survived the display
undo while the model Op removed it. Collect the removed anchors' ids on
the same pass and keep only injections not owned by them, so the header's
'prompt-owned ones leave with their prompt' holds for every count.
* refactor(agent-core-v2): accumulate request projection repairs as policy
The llmRequester retry chain kept a RequestProjection union and translated
it into a ProjectionPolicy per attempt; repairs were mutually exclusive,
so a strict resend rejected again for body size or image format either
aborted or silently dropped the strict repair. Retry state is now the
ProjectionPolicy itself: each rejection adds its repair on its own axis
(media: 413 -> degraded -> strip; wire: structure -> strict) without
discarding the other, requestInput's translation layer and the unreachable
snapshot ??= disappear, and the persisted llm.request projection name
derives from the policy (the op enum gains strict-media-degraded /
strict-media-stripped). Also narrows ProjectionPolicy to the variants
actually produced (wire 'strict'; media 'degraded' | { strip }), dropping
the dead 'default'/'keep' literals and their guard.
* refactor(agent-core-v2): derive the visible context window from an append-only log
context.apply_compaction now appends a summary marker carrying the record
fields as CompactionMeta instead of replacing the folded history; the
model-visible window is derived at read time (visibleWindow) with the same
[head, elision?, tail, summary] layout, one deterministic derivation for
live dispatch and replay alike. The record format is unchanged, so v1- and
v2-written sessions keep replaying identically both ways.
- undo maps the visible-window cut back to a log position (the verbatim
legacy-summary edge falls back to the pre-append-only destructive cut)
- replay rehydrate only loads blobs the window derivation can surface
- contextInjector drops position tracking; injection positions become a
read-time scan that splices can never desync
- fullCompaction's safety check moves to the stable-identity log
* fix(agent-core-v2): rehydrate exactly the messages the visible window surfaces
The first append-only rehydrate rule kept pre-marker real user input plus
markers, but a legacyTail derivation keeps window.slice(compactedCount)
visible — assistant/tool media in that range stayed blobref after replay
and could be resent unresolved. Decide survivors by identity membership in
the derived window instead, which covers every derivation branch at once
and skips the unselected pre-marker pool as a bonus.
* fix(agent-core-v2): pop the visible-tail swarm reminder behind a legacy marker
SwarmService.exit decides the pop on the derived window's tail, but the
swarm_mode.exit reducer tested the raw log tail — after a legacyTail
compaction the survivor reminder is visible at the window tail while the
marker is the log tail, so the pop silently skipped and the stale reminder
stayed in the model context. Mirror the visible-tail decision in the
reducer and remove the entry by its stable log identity.
* fix(agent-core-v2): settle open transcript frames when compaction lands mid-fold
An overflow-triggered compaction arrives with the failed attempt's vacuous
partial still open. The transcript appended the summary marker and reset
the fold but left the frame; the retried step's step.begin then settled it
(-1) alongside the new frame (+1), so foldedLength stayed one short of the
model-visible window and kap-server's live-tail merge could duplicate the
retry tail. Settle the frame at the marker through the shared kernel;
recoverFoldedLength recomputes the absolute count right after either way.
* fix(agent-core-v2): settle open frames at the compaction marker
Apply settleModelOpenStep inside context.apply_compaction so a marker only
ever lands on a settled frame: no partial survives a marker and nothing
mutates the log behind one, making the append-only invariant structural
(the identity-prefix check in historySafeToCompact relied on it) instead
of timing-dependent. Mirrors the transcript's settle-at-marker.
Also freeze the derived visible window before caching it (an in-place
consumer mutation now throws instead of silently polluting the shared
cache), and drop the production-unreachable legacy branch of
buildContextCompactionShape so the legacy tail layout lives only in
deriveCompactionWindow.
* refactor(agent-core-v2): tighten naming and comments in context memory internals
- Slim file headers to the package header-only comment convention
- Rename PR-introduced identifiers for clarity: getMessageLog,
ProjectionPolicy.structure, pendingToolCallIds/deferredEntries,
removedEntryCount, deriveVisibleWindowAfterCompaction,
compactedWindowMessageCount
- Extract nextProjectionPolicyForError, removeUndoOwnedEntries and
summarizeProjectionRepairs; name fold intermediates after their
business stage
- Regroup splice-replay tests by topic and unify projection-call
recording in llmRequester tests
* fix(agent-core-v2): preserve bounded context state
* docs(agent-core-v2): restore the domain identity line in the compactionHandoff header
* refactor(agent-core-v2): rebuild context projection as a staged block pipeline
Split the 650-line projector service into three modules by concern:
mediaProjection (read-side media degrade/strip fallbacks), projection
(the structural transform), and the service (DI binding plus repair
reporting). Rebuild the structural projection as a two-stage pipeline:
pairBlocks groups tool exchanges into blocks that own their calls'
results, flattenBlocks serializes them back to wire order and merges
consecutive user prompts. The shared slot sentinel and index
back-patching are gone; the trailing-close and sizing-slice rules are
named and documented in the module header. Behavior is pinned unchanged
by the existing projector and llmRequester suites.
* docs(agent-core-v2): trim the projection helper header to its external role
* docs(agent-core-v2): keep the contextProjector module headers at the external-role level
* feat(cli): add --web-title and expose it via /meta
* refactor(kap-server): pass optional web_title directly in /meta
Per the repo rule for optional object properties, pass undefined directly
instead of a conditional spread; serialization omits the unset value.
* fix(cli): sync web bundle with instance tab title support
The committed dist-web bundle predates the document title feature, so a
released `kimi web --web-title` served a client that never read web_title.
Rebuilt from code-app (feat/web-document-title) via sync:web; the bundle
now titles tabs from web_title or the active workspace directory.
* ci: retrigger checks after flaky harness cleanup failure
---------
Co-authored-by: wbxl2000 <wbxl2000@outlook.com>
Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
* refactor(agent-core-v2): carry the context fold cursor in state and converge fold/projection internals
- ContextModel state is now { messages, fold }: the loop-event fold cursor
(openStepUuid / pending / deferred) lives in the state instead of a
module-level WeakMap keyed by array identity, so wholesale replacements
(undo / clear / compaction / swarm exit) reset it structurally via
EMPTY_FOLD instead of a manual resetFold at five call sites.
- The display transcript and the wire model now share one generic fold
kernel (FoldFrame / FoldEntryAdapter), eliminating the mirrored second
implementation. Events tagged with a non-open step uuid are dropped and
step.end settles only the step it names — defensive in abnormal streams,
identical on well-formed ones (v1 replay unaffected).
- IAgentContextProjectorService converges to project(messages, policy) with
a ProjectionPolicy data object; llmRequester builds the policy from retry
state instead of selecting among four methods.
- Blob rehydrate now also covers messages still deferred in the fold cursor.
- ContextState is deeply frozen at the op boundary to preserve the consumer
immutability the wire's shallow freeze gave the bare array state.
* test(agent-core-v2): move fold parity rationales into the test file header
* docs(agent-core-v2): move fold declaration comments into module headers
* refactor(agent-core-v2): merge FoldFrame into generic ContextState
* refactor(agent-core-v2): compile-enforce part/event handling decisions in context memory
- isVacuousContentPart and dehydrateRecord now switch exhaustively over
ContentPart / LoopRecordedEvent variants, so a new variant fails
compilation until it takes an explicit position
- the transcript/model parity comparator spreads whole messages and masks
only summary content, so new ContextMessage fields join the comparison
automatically
- correct two stale header comments: local message ids persist with
append_message records, and undo's prompt-owned-injection pairing
depends on them after a resume
* refactor(agent-core-v2): converge undo-cut decision in conversationTime
The model Op and the display transcript each walked the undo anchors with
their own loop, and the transcript partially removed the tail when an undo
was blocked (compaction summary / clear floor / too few anchors) while the
model side no-ops at the precheck. Move the walk into conversationTime as
computeUndoCut/computeUndoCutFrom applied destructively by the context.undo
Op and non-destructively by the transcript reducer, so a blocked undo reads
identically on both sides.
Also: make isUndoAnchor exhaustive over origin kinds with a never assertion,
mirrors the compaction result message count via compactionHandoff, and
extend UndoCut with anchorIndex distinguishing the counted anchor from the
injection-extended cut point.
* fix(agent-core-v2): drop removed prompts' injections on multi-turn transcript undo
The transcript's kept-loop retained every injection after the oldest
counted anchor, so with count > 1 a prompt-owned injection of a newer
removed prompt (e.g. an image-compression caption) survived the display
undo while the model Op removed it. Collect the removed anchors' ids on
the same pass and keep only injections not owned by them, so the header's
'prompt-owned ones leave with their prompt' holds for every count.
* refactor(agent-core-v2): accumulate request projection repairs as policy
The llmRequester retry chain kept a RequestProjection union and translated
it into a ProjectionPolicy per attempt; repairs were mutually exclusive,
so a strict resend rejected again for body size or image format either
aborted or silently dropped the strict repair. Retry state is now the
ProjectionPolicy itself: each rejection adds its repair on its own axis
(media: 413 -> degraded -> strip; wire: structure -> strict) without
discarding the other, requestInput's translation layer and the unreachable
snapshot ??= disappear, and the persisted llm.request projection name
derives from the policy (the op enum gains strict-media-degraded /
strict-media-stripped). Also narrows ProjectionPolicy to the variants
actually produced (wire 'strict'; media 'degraded' | { strip }), dropping
the dead 'default'/'keep' literals and their guard.
* refactor(agent-core-v2): derive the visible context window from an append-only log
context.apply_compaction now appends a summary marker carrying the record
fields as CompactionMeta instead of replacing the folded history; the
model-visible window is derived at read time (visibleWindow) with the same
[head, elision?, tail, summary] layout, one deterministic derivation for
live dispatch and replay alike. The record format is unchanged, so v1- and
v2-written sessions keep replaying identically both ways.
- undo maps the visible-window cut back to a log position (the verbatim
legacy-summary edge falls back to the pre-append-only destructive cut)
- replay rehydrate only loads blobs the window derivation can surface
- contextInjector drops position tracking; injection positions become a
read-time scan that splices can never desync
- fullCompaction's safety check moves to the stable-identity log
* fix(agent-core-v2): rehydrate exactly the messages the visible window surfaces
The first append-only rehydrate rule kept pre-marker real user input plus
markers, but a legacyTail derivation keeps window.slice(compactedCount)
visible — assistant/tool media in that range stayed blobref after replay
and could be resent unresolved. Decide survivors by identity membership in
the derived window instead, which covers every derivation branch at once
and skips the unselected pre-marker pool as a bonus.
* fix(agent-core-v2): pop the visible-tail swarm reminder behind a legacy marker
SwarmService.exit decides the pop on the derived window's tail, but the
swarm_mode.exit reducer tested the raw log tail — after a legacyTail
compaction the survivor reminder is visible at the window tail while the
marker is the log tail, so the pop silently skipped and the stale reminder
stayed in the model context. Mirror the visible-tail decision in the
reducer and remove the entry by its stable log identity.
* fix(agent-core-v2): settle open transcript frames when compaction lands mid-fold
An overflow-triggered compaction arrives with the failed attempt's vacuous
partial still open. The transcript appended the summary marker and reset
the fold but left the frame; the retried step's step.begin then settled it
(-1) alongside the new frame (+1), so foldedLength stayed one short of the
model-visible window and kap-server's live-tail merge could duplicate the
retry tail. Settle the frame at the marker through the shared kernel;
recoverFoldedLength recomputes the absolute count right after either way.
* fix(agent-core-v2): settle open frames at the compaction marker
Apply settleModelOpenStep inside context.apply_compaction so a marker only
ever lands on a settled frame: no partial survives a marker and nothing
mutates the log behind one, making the append-only invariant structural
(the identity-prefix check in historySafeToCompact relied on it) instead
of timing-dependent. Mirrors the transcript's settle-at-marker.
Also freeze the derived visible window before caching it (an in-place
consumer mutation now throws instead of silently polluting the shared
cache), and drop the production-unreachable legacy branch of
buildContextCompactionShape so the legacy tail layout lives only in
deriveCompactionWindow.
* refactor(agent-core-v2): tighten naming and comments in context memory internals
- Slim file headers to the package header-only comment convention
- Rename PR-introduced identifiers for clarity: getMessageLog,
ProjectionPolicy.structure, pendingToolCallIds/deferredEntries,
removedEntryCount, deriveVisibleWindowAfterCompaction,
compactedWindowMessageCount
- Extract nextProjectionPolicyForError, removeUndoOwnedEntries and
summarizeProjectionRepairs; name fold intermediates after their
business stage
- Regroup splice-replay tests by topic and unify projection-call
recording in llmRequester tests
* fix(agent-core-v2): preserve bounded context state
* docs(agent-core-v2): restore the domain identity line in the compactionHandoff header
* refactor(agent-core-v2): replace defineOp/Model with Event2 dispatch and replayable states
- replace defineOp/Op/OpDescriptor/toEvent and defineModel/defineCheckpointedModel with Event2 subclasses: durable classes declare static durable + schema, serialize() keeps the wire record shape byte-frozen, transient classes stay off the journal
- define states via defineState(...).replayable(...).on(Event2, fold): immer produceWithPatches folds with atomic prepare/commit, .undoable() trait drives prompt-submit checkpoints and context.undo, ephemeral kv keys keep imperative set
- degrade IWireService to a journal adapter; the agent event dispatcher owns the pipeline (fold -> set -> appendRecord -> publish) and silent restore
- align downstream event surfaces: kap-server WS envelope timestamp from event.time, klient event schemas gain time, node-sdk/acp-server/print wiring updated
- rewrite gen-wire-manifest/gen-state-manifest for the unified registry and replace the op-uniqueness lint with event-uniqueness
* fix(ci): repair Event2 prompt and media projections
- restore prompt admission and session media materialization
- align transcript, WS, SDK, and replayable media state projections
- update affected tests and generated state manifest
* fix(ci): update prompt event and projection expectations
- update snapshots for the durable prompt.accepted event
- normalize prompt.steered media in transcript projections
* fix(agent-core-v2): preserve tool call extras in tool.call loop events
* fix(google-genai): keep trailing user text before function results when merging
---------
Co-authored-by: Selene <mahaoyang@corp.netease.com>
* fix(kimi-code): persist pasted-image originals into the session dir at dispatch
Paste-time original persistence ran before the session existed on a
fresh TUI, so the compression caption baked a shared temp-dir path the
OS can reap. Keep the pre-compression bytes on the attachment in memory
and let dispatch-time caption resolution (sendMessageInternal,
steerMessage, runInlineSkillActivations) write them into the session's
media-originals dir — owned by the session, cleaned up with it, immune
to OS temp reaping.
* fix(kimi-code): harden pasted-image original lifecycle
Address review feedback:
- carry the pre-compression original in the resend snapshot so a
cache-hint "new session" resend still persists it into the new
session's originals dir and authors the compression caption
- release the in-memory original bytes once persistence succeeds,
keeping only the metadata the caption needs
- apply the same 1 GiB mtime-bounded eviction to the sync originals
store as the engine's async twin
* fix(kimi-code): keep compression captions consistent with the sent image
Address review feedback:
- author a caption only when the image part still matches the
attachment's current state, so a paste whose ingestion landed after
extraction (inline pre-compression fallback) is not described as
downsampled
- leave the original's path unset when persistence fails so a later
dispatch retries the write instead of dropping the original for good
* fix(kimi-code): keep staged media across lazy session creation
setSession() released ALL staging leases on the assumption that they
belong to the session being replaced. On the lazy first-creation path
there is no previous session: the outstanding lease belongs to the new
session's first prompt, whose dispatch continues right after. The
premature release deleted a pasted image's daemon upload before the
engine's intake could read it, so the model only received
'[image omitted: the uploaded file is no longer available]'.
Gate the release on actually replacing a live session; shutdown and
explicit close keep their own releaseAll().
* Delete .changeset/lazy-session-staging-lease.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* Delete .changeset/pasty-image-originals-session-dir.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* feat(agent-core): unify the v1 MCP management plane
- McpServerRegistry: one config view over global (layered mcp.json),
plugin (manifests, read-only, final effective config), and caller
(SDK-injected) servers; name collisions keep both entries.
- Write plane: add/update/removeGlobalMcpServer mutate the user-level
file and push into live sessions; getGlobalMcpServer returns the
effective config; mutations of read-only entries are rejected.
- testGlobalMcpServer accepts an inline config; addSessionMcpServer
connects a server in one live session with an optional persist flag;
reconnect accepts a replacement config and re-resolves via the registry.
- One process-wide McpOAuthService shared with every session: obtained_at
stamps, offline token state, single-flight and proactive refresh, and
credential events. Sessions self-subscribe in the constructor, so even
initializing sessions see every event; token writes serialize through
the process-local OAuthTokenTransaction per credential identity.
- inspectAppMcpServers + locator-addressed begin/complete/cancel/reset
cover plugin servers; inspection output redacts env/headers to sorted
key lists; locator OAuth ops reject ambiguous shared runtime names.
- The legacy auth-status surface reads the registry (offline by default,
verify=true probes) and never mutates credentials.
- VS Code panel receives source/origin/mutable and hides mutating
actions on read-only entries.
- v2 client facade in node-sdk mirrors the surface over agent-core-v2
(plugin inventory stays v1-only for now).
* fix(agent-core): close the v1 MCP live-session reconciliation gaps
Recompute each live session's MCP target from the registry's runtime
resolution (enabled plugin > project layer > user file; caller injection
shadows everything) behind every config mutation, instead of per-path
patching: shadowed file layers recover when a plugin winner is disabled or
removed, removing a user-level entry resurrects its project-layer shadow,
disabled plugin descriptors no longer block removals, persisted session
adds validate against the session's project layer and broadcast to other
live sessions, and per-session sync failures are logged with context.
Session status entries and read-only management entries now report
redacted config views (envKeys/headerKeys instead of literal env/headers
values); core-internal reconciliation compares full configs via the
connection manager's raw-entry accessor.
OAuth: interactive flows are serialized per credential (concurrent
begins join the in-flight flow instead of clobbering its PKCE/state), a
malformed credential meta sidecar no longer aborts core start, grants
inside the refresh-ahead window refresh immediately while far-future
grants re-arm through a max-length timer, and the service shuts its
timers and flows down with KimiCore/SDKRpcClient close.
* fix(agent-core): route the proactive MCP OAuth refresh through the token transaction
refreshNow ran its /token request with the SDK default fetch, outside the
credential-serializing OAuthTokenTransaction that every other token write
uses; a slower response carrying an older rotating refresh token could
overwrite a newer grant written by a concurrent transport-side refresh.
* fix(agent-core): keep disabled MCP servers out of auth-state classification
The unified mcpServerAuthState dropped the previous enabled short-circuit,
so a disabled oauth-flagged server reported oauth-required — or was even
probed over the network — instead of not-applicable.
* fix(kimi-code-sdk): short-circuit disabled MCP servers in the v2 auth-status classifier
The v2 parity copy of v1's mcpServerAuthState missed the same enabled
guard v1 just regained; a disabled oauth-flagged entry would report
oauth-required (or be probed). The parity suite now pins the disabled
case on both engines.
* fix(kimi-code): refresh the VS Code MCP list with the workspace cwd after mutations
The add/update/remove RPCs return a cwd-less management list, so the
webview broadcast dropped project-layer entries until the next full load;
re-list with the workspace cwd after every mutation instead.
* fix(agent-core): keep SDK token saves matched to the OAuth token transaction
saveTokens stamped obtained_at onto a fresh object before calling
tokenTransaction.save, so it never matched the exact payload the
transaction recorded for a grant fetch; the consume path was dead and
every save re-wrote. Between the fetch and the SDK callback an intervening
clear could then be overwritten — the resurrected grant came back after a
reset. The write callback stamps the durable record instead.
* fix(agent-core): reject ambiguous legacy name-based MCP auth lookups
The legacy begin/reset auth RPCs took the registry's first name match,
silently starting OAuth for one entry of a runtime-name collision while
the locator path refused the same ambiguity; align them on the shared
uniqueness rule and point callers at the locator-addressed variants.
* fix(agent-core): propagate registry errors during live-session MCP sync
resolveMcpRuntimeTarget collapsed every registry failure into "no target":
a project config file that turned malformed mid-session made sync treat a
still-configured server as gone (tearing down the live connection) and
made config-aware reconnects report "no longer configured" instead of the
actionable config error. Absence still resolves to undefined; malformed
config now propagates — per-session sync logs and keeps the entry, and
reconnect surfaces config.invalid.
* fix(agent-core): close the remaining registry-error and ambiguity gaps
The management guard lookup mapped every registry failure to "absent",
so a malformed project config let a persisted session add write a
user-level entry over an unknown state; only not-found is a miss now. And
the name-only connection test now shares the auth paths' uniqueness rule
instead of probing the first match of a runtime-name collision.
* fix(agent-core): probe the enabled MCP entry under a disabled-name collision
The name-only connection test counted enabled matches for its ambiguity
guard but still probed the first registry match, and the file layers list
before plugins. With a disabled file entry shadowing an enabled plugin of
the same runtime name, Test probed the disabled entry instead of the one a
live session would run. Select the sole enabled match, falling back to the
first entry only when every match is disabled so it reports as disabled.
* fix(agent-core): let session-local MCP adds shadow plugin entries
Caller injection shadows every registry source at session start, plugins
included, and reconciliation leaves caller entries untouched; the live
non-persist add path rejected plugin-owned names anyway, so SDK clients
could not apply the same per-session override without a restart. Gate the
plugin-source rejection on persist: session-local adds connect as caller,
while persisted adds stay rejected as user-level writes behind a read-only
owner.
* fix(agent-core): normalize session MCP names before connecting
The persisted store trims server names, but addSessionMcpServer used the
raw name for the live connect and cross-session reconciliation: a padded
name persisted under the trimmed key while the requesting session ran and
reconciled the raw one, and a blank name connected with no identity at
all. Normalize once up front (rejecting blank) so the store write, the
session entry, and reconciliation agree on the same server.
* fix(agent-core,node-sdk): close the collision-selection and probe-freshness gaps
The legacy name-only auth resolver started from the first registry match,
so a disabled file-layer shadow plus an enabled plugin of the same runtime
name was misread as an ambiguity conflict; select the sole enabled match
before judging ambiguity, exactly like the test probe path. On the v2
client, addSessionMcpServer connected the raw name while the store wrote
the trimmed key — normalize once for both, and route the verify-triggered
auth probes through the per-call OAuth service instead of the cached one
whose providers snapshot tokens at construction, so a grant saved after
the first probe is honored.
* fix(agent-core): normalize global MCP mutation names and guard disabled reconnect swaps
The global add/update/remove mutations guarded and reconciled with the raw
server name while the store persisted the trimmed key, so a padded name
left live sessions unreconciled and could slip past the plugin read-only
guard; normalize once before lookup, persistence, and reconciliation. And
a config-carrying reconnect assigned the replacement before the disabled
check fired, leaving a connected entry that reported the disabled config;
reject disabled replacements before mutating, keeping the same error.
* fix(agent-core): skip proactive refresh while an interactive flow owns the credential
refreshNow reset the shared provider's flow state before and after the
token request; when a proactive timer (or a manual refresh) fired while
beginAuthorization was waiting on the browser callback for the same store
key, that wiped the redirect URL, PKCE verifier, and state the in-flight
flow needed — complete() then failed the exchange even though the user
authorized. Refresh now skips when an interactive flow is active for the
credential: the flow delivers fresh tokens on completion, and the 401
transport path is the backstop if it fails.
* fix(agent-core): allow global MCP adds over disabled plugin descriptors
A disabled plugin entry is absent from the runtime target, but the
read-only guard still treated it as the owner, so a user-level fallback
could only exist if it predated the plugin disable. Relax the shared
guard: disabled plugin descriptors never block mutations (disabled
project entries still shadow the user file and keep their rejection).
* fix(node-sdk): close the v2 session-MCP parity gaps
A v2 reconnect with an explicit enabled:false replacement config used
connect()'s upsert semantics — closing the live client and reporting
success where v1's manager reconnect rejects before applying anything;
reject disabled replacements up front with the same error. And a persisted
v2 session add never consulted the workspace config, so a same-named
project-layer entry was silently shadowed: the user-level write never
takes effect while the direct workspace-manager upsert displaces the
project config for every live session. Resolve the workspace layers and
reject like v1's read-only rule.
* fix(agent-core): keep __proto__-named MCP servers through config parsing
A z.record() parse rebuilds its output via property assignment, so a
server literally named __proto__ hit the prototype setter and vanished
before validation; the layer merge then repeated the same trap with plain
object accumulators. Parse the server map entry-by-entry over the JSON own
keys and accumulate into null-prototype maps, so session startup and the
unified registry keep the declared server and its origin.
* fix(node-sdk): begin v2 MCP auth against a fresh OAuth service
The v2 begin path ran through the cached globalMcpOAuth, whose providers
snapshot tokens at construction: a grant another process saved (or reset)
after that cache materialized was invisible, so begin could open a browser
flow over a valid grant, or report already-authorized off a removed one.
Build the service per call — the read path and the verify probes already
do — and route the status list through the same helper. The test fixture
grows a real token endpoint honoring one rotating refresh token; the
regression fails against the cached-service implementation on v2.
* fix(agent-core): broadcast SDK-driven MCP token invalidations to live sessions
* test(agent-core-v2): give the no-op reconnect test runtime plumbing
The branch added the case against a bare McpConnectionManager, but #2961
made stdio connects resolve the runtime through runtimeResolver, matching
every other case in the file.
* feat: engine-native image references via kimi-file:// media resolver
* fix(agent-core-v2): regenerate state manifest for media resolver rename
* feat(agent-core-v2): add audio MediaKind and tag/ref fold helpers to media ref contract
* fix(agent-core-v2): synthesize image path tag when degrading bare file references
* fix(agent-core-v2): scrub dangling alias re-exports in contract type generator
* feat(transcript): project paired media tag+ref as single attachments in read models
* fix(kimi-code): fall back to inline image when cache write fails after upload
* fix(agent-core-v2): pair media path tags with refs by adjacency and path, keep unpaired tags
* fix(kap-server): fold media tag+ref pairs out of prompt snapshot projection
* fix(kap-server): list attachment-only prompts as empty user messages
* fix(kap-server): keep live attachment ids across transcript overlay and heal
* fix(kap-server): keep promptAttachments off the legacy session event wire
* fix(kap-server): inherit the backfilled turn header on mid-turn terminal projection
A projector that attached after turn.started built the terminal turn.upsert
with an empty header, and the whole-header replace downstream wiped the
backfilled origin / prompt / attachmentIds — only the debounced best-effort
heal could restore them. Fall back to the producer store's seeded header
(via a new optional ProjectorLookups.turn) when currentTurn misses, and
cover the mid-turn attach path with a service-level regression test.
* refactor(agent-core-v2): move media ref contract out of kosong into agent/media
The kimi-file:// daemon reference grammar, media path tags, and the tag/ref
fold are engine-internal conventions, not provider-wire contract; keep
src/kosong untouched. Root exports and SDK re-exports are unchanged.
* feat(agent-core-v2): materialize prompt media into the session media dir
Pasted and uploaded media now materialize under the session's own media/
dir instead of the shared cache, so the copies follow the session's
lifecycle: fork carries them along, session deletion cleans them up.
A new Session-scope ISessionMediaStore owns the dir: atomic tmp+rename
materialization with a unified extension policy, and canonical-vs-hint
display-path resolution. The persisted ?path= is a write-time snapshot —
readers prefer the session-canonical location, so fork and home relocation
never hand the model a dead path. Prompt intake normalizes every daemon
reference through the single enqueue funnel (REST edge, SDK prompt/steer,
gateway), serialized in arrival order to keep the FIFO across the async
file I/O. The kap-server edge materializes through the same store with a
shared-cache fallback, and the request-time resolver refreshes stale
persisted and memoized path tags; a claimed video reference degrades to
its tag alone instead of duplicating it.
* fix(agent-core-v2): take prompt media intake off the enqueue critical path
The record now joins the FIFO synchronously and its daemon-ref intake runs
as a per-record promise, awaited by the launch and steer paths before the
message is consumed — queue order, list/abort visibility, and prompt
submission latency no longer wait on file I/O, and a slow intake no longer
head-of-line blocks later prompts. The launching record is tracked so abort
and clear stay reachable inside the launch window; startNext re-checks
cancellation after every await (intake race, hook, turn admission), a
cancelled record is never re-queued, and a compaction requeue waits for
onDidFinishCompaction instead of busy-looping the scheduler.
* fix(agent-core-v2): record the claiming ref in the media path-tag pairing
pairMediaPathTagRefs now exposes claimingRefByTagIndex, and claimingRefIndex
reads it instead of recovering the claimer by path equality — which
mis-attributed a tag when two different fileIds carried the same path in an
interleaved sequence, breaking the pair and leaking the tag as user text.
Also covers the memoized-video-tag claimed-drop branch.
* fix(transcript): fold upload pairs in user-slash turns and pin pairing parity
The cold rebuild's user-slash branch now folds the turn-opening input like
any user turn (claimed tag out of the prompt text, one attachment entity),
matching the live projection. The ref extraction is consolidated into the
contract module (daemonFileRefFromPairingPart, the mirror of the engine's
daemonFileRefFromPart) and the mirror carries the new claimingRefByTagIndex
map. A new kap-server parity test imports both implementations and asserts
identical pairings over shared fixtures, so the engine/mirror pair can no
longer drift silently.
* fix(kap-server): fold upload media tags out of the search index
The global search indexer concatenated every text part of a persisted user
message, so the upload pair's <image path> tag made pure-image prompts
searchable and wrote the materialization path into the index — breaking the
module's documented pure-image invariant and diverging from the live route.
textOfContent now folds the pair like every other read model (with a
fold-safe coercion for malformed wire parts). Also pins the prompt-media
cache-dir fallback with a read-only session media dir test (skipped as root).
* feat(node-sdk): re-export the media fold helpers and cover the v1 uploadFile rejection
foldMediaPathTagRefs and matchSingleMediaPathTag join the daemon
file-reference helper re-exports so hosts can fold the upload tag+ref pair
without importing agent-core-v2; the v1 harness's uploadFile not_implemented
rejection is pinned by a test.
* fix(kimi-code): fold upload pairs in replay/export and keep media tags atomic in steer input
Resumed-session replay rendered the upload pair raw — the <image path> tag
as user text and the kimi-file:// url as an XML-ish reference — and the
markdown export leaked the tag into both the turn body and the overview
topic. contentPartsToText and the exporter now fold the pair, and daemon
references render as a bare [image]/[video] placeholder. combineSteerInput
moves to tui/utils/steer-input and no longer merges a standalone media tag
into adjacent text, which would have broken the engine-side pairing for
steered image messages.
* fix(kimi-code): drop the steer separator before a leading media tag
A queued pure-image message opens with a standalone `<media path>` tag,
which combineSteerInput keeps atomic. With the previous item ending in a
media part, the '\n\n' separator landed as a stranded whitespace-only text
part between the media part and the tag, normalizePromptInput rejected the
steer, and the already-cleared queue lost the messages. Treat a leading
standalone tag as media so the separator is dropped there.
* fix: clean staged media lifecycle
* refactor(agent-core-v2): narrow the mediaRef root exports and drop a deprecated alias
* fix: keep staged media alive through turn
* fix(agent-core-v2): reject non-upload ids at the session media store
A daemon reference's fileId becomes a storage key in the session media
store, but only the file domain validated the id shape — a crafted
kimi-file://<id> reaching the request-time resolver's canonical-read
fallback could traverse out of the session media dir. Share the file
domain's id regex and guard every store entry point: reads miss,
materialize declines, and the display path falls back to the hint.
* fix(kap-server): project steered prompt content without leaking daemon refs
prompt.steered published the raw engine content parts — kimi-file://
refs carrying the absolute materialization path plus the paired
<media path> tag — to both the legacy session_event wire (whose schema
declares the protocol content shape) and the transcript prompt entity.
Route both through one shared prompt-content projection: the upload
pair folds into a single {kind:'file'} part, matching the REST prompt
list and the no-path-leak rule every sibling surface already follows.
* refactor: align daemon-ref naming and drop a duplicate re-export
The deprecated videoResolverService alias also re-exported
mediaResolvedKey, which made the package root's star exports ambiguous
and silently dropped the name. The new transcript contract mirror now
uses the canonical daemon-ref vocabulary instead of the deprecated
kimi-file spelling.
* test(agent-core-v2): pin image abort rethrow, video canonical read-through, release-once
Mirror the video abort contract on the new image path (an aborted read
cancels the request instead of degrading to a tag), cover the video
fallback that uploads the session-canonical bytes after the transient
upload is released, and assert the staged-upload release fires exactly
once on the intake success path.
* fix(kimi-code): bind goal-steer staging leases to the running turn
sendMessageInternal read the turn context only after beginSessionRequest
had cleared it, so a steer buffered into a running goal turn never got
its staging lease bound — the staged daemon upload and cache copies
lived until session close instead of being released at the consuming
turn's end. Capture the live turn id before the reset (only while a
turn is actually streaming; the id outlives its turn otherwise).
Also move the staging-lease state machine off the KimiTUI coordinator
into a self-contained StagingLeaseTracker with injected effects, drop
the duplicate media-tag builder in image-placeholder in favor of the
SDK helper, and fix the paste-in-flight comment to match the gate's
real granularity.
* fix(kap-server): project prompt.queued content without leaking daemon refs
The broadcaster projected prompt.steered and stripped turn.started
attachments but forwarded prompt.queued raw, leaking kimi-file:// URLs
and absolute materialization paths to every subscribed WS connection
and the journal. Fold the tag+ref pair into a {kind:'file'} part, same
as steered.
* fix: keep compressed uploads retrievable and close the steer abort window
Two review fixes around prompt media intake:
- The compressed re-save was released right after intake (and carried a
1h expiry) while every client read model projects its file id,
leaving historical compressed images unfetchable. Keep the re-save as
an ordinary upload; roll it back only when preparation or submission
fails before the engine takes the prompt. The engine's
PromptInput.release hook loses its only producer and is removed.
- A prompt aborted while its steer awaited the loop's step assignment
was flipped back to 'steered' and its content could still
materialize into a later turn. Re-check the reservations after the
assignment await and abort the undispatched request when the check
fails.
* perf(agent-core-v2): memoize inlined image parts across request steps
A successful image inline depends only on the immutable upload bytes, so
it is memoized per file id (size-bounded) in media.resolved and reused
across steps, retries, and media-recovery reprojections instead of
re-reading and re-encoding on every request. Degrade forms are never
memoized since they depend on the message's tag pairing. Also make the
never-empty message placeholder kind-aware (video vs image).
* refactor: author media tag+ref pairs in the engine prompt intake
Edges (TUI, kap-server REST) now submit bare kimi-file references and the
engine intake materializes the bytes, synthesizes the paired media path
tag, and falls back to the shared cache dir when the session store is
unavailable, replacing per-edge pair construction and duplicate
materialization copies.
Thread the prompt id from submission through to turn.started (REST
prompt_id, WS event, SDK prompt option) so the TUI binds staged-media
leases to turns exactly; the origin heuristic stays as fallback and
ambiguous claims now surface a staging_lease_invariant telemetry warning.
Also lands the pending resendable-extraction fix for cache-hint resubmits
after a session switch.
* fix: decouple media persistence from prompt intake
* refactor(agent-core-v2): project the turn prompt in a single fold pass
* test: slim redundant media-ref coverage across layers
Fold duplicate pinning of the same media tag+ref rules into shared
helpers and it.each tables, and drop assertions that restate behavior
already covered at another layer:
- drop the kimiFileUrl alias describe (mediaRef.test.ts covers the
aliased functions with more cases)
- drop pairMediaPathTagRefs describe in favor of the parity fixtures
- merge the identical prompt.steered/prompt.queued broadcast tests
- parameterize the resolver degradation matrix and prompt intake
fixtures (enqueueMedia/gatedImage/expectMediaPair helpers)
- drop REST-level context-memory pairing assertions (engine-level
intake tests pin the same shapes); keep the caption->system-reminder
assertion, the only cover of extractCompressionCaptions
- drop the turn-finish-during-intake steer-cancel vector and the
switch-session release driver test (unit-level lease tests remain)
Net -762 lines; 645 tests green across agent-core-v2, kap-server,
transcript, node-sdk, klient, and the TUI.
* chore: fix oxlint warnings introduced by image-file-ref changes
* fix: harden image file reference lifecycle
* fix: close image reference lifecycle gaps
* fix: preserve session media paths on replay
* chore: streamline image-file-ref changesets
* refactor: make daemon media references self-contained, dropping tag+ref pairing
A daemon-ref media part now carries everything a read model needs — the
kind from the part type and the materialization path from the reference's
`?path=` — so prompt intake no longer authors a paired `<media path>`
tag, and the pairing/fold machinery (pairMediaPathTagRefs /
foldMediaPathTagRefs and their mirror copy) is deleted across the engine,
transcript, kap-server, node-sdk, and the TUI. The request-time resolver
synthesizes the degrade tag from the reference path whenever bytes cannot
reach the provider. Standalone tags stay user-visible text, and never
reach the search index or prompt metadata.
* fix: reconcile image file references with main after rebase
Main removed the agent RPC aggregation layer (agent/rpc) and moved
LifecycleScope to app/scopes. Fold the branch's RPC-side behavior into
the new structure: PromptPayload carries promptId/disabledTools, and
AgentPromptService.submit admits the client-chosen id through the
reservation (duplicate rejects before any session state changes) and
applies the denylist through toolPolicy. Regenerate the wire/state
manifests.
* fix(kimi-code): run paste ingestion in the background, wait bounded at submit
The paste callback awaited compression + original persistence + the
daemon upload while CustomEditor queued every keystroke, so a slow
ingestion stalled all typing. Settle the callback once the placeholder
lands and track the rest as ImageAttachment.pending; the send path gives
a referenced pending ingestion a bounded wait (2s) so paste-then-Enter
still submits the compressed/daemon-ref form, and falls back to the
inline form when ingestion has not finished. Media-free submits stay
fully synchronous.
* fix(protocol): mirror prompt_id in the shared prompt submission schema
kap-server's local REST schema accepts a client-chosen prompt_id, but
the shared promptSubmissionSchema stripped it as an unknown key, so
clients validating through @moonshot-ai/protocol lost the id and the
turn.started promptId correlation never matched.
* fix(klient): normalize file-store errors to public RPC errors on both transports
The fileService save/get wire adaptation ran outside the dispatcher's
error normalization, so a stale or expired upload id surfaced as the
engine's raw Error2 on the memory transport and as a generic 50001 on
ipc. Map file.not_found to the public NOT_FOUND RPCError in the shared
dispatcher so both transports reject identically, and pin the parity in
the conformance suite.
* fix(agent-core-v2): keep launching media prompts visible in the queue snapshot
startNext shifts the launching record out of pending before its media
intake settles, so list()/GET /prompts reported neither an active nor a
queued prompt during the intake window even though the submission was
accepted and abortable. Report the launching record as still queued,
matching the prompt.queued event already published for it.
* fix(node-sdk): strip internal promptAttachments from SDK turn.started events
The in-process v2 event mapper forwarded the whole domain event, so SDK
session.onEvent consumers saw the transcript-projection-only
promptAttachments field that kap-server explicitly strips from the WS
wire event. Drop it in the mapper so both consumers share the same
turn.started field set.
* fix(kimi-code): align staging lease id multiplicity with retain count
A lease's flat id list conflated two cases: one submission referencing
the same image twice (one retain) and a batched steer merging two queued
messages sharing the image (two retains). Occurrence-wise release
over-consumed in the first case and batch-wise release would
under-consume in the second. Dedupe each extraction's ids at the lease
creation sites so list multiplicity always equals the retain count, and
release one retain per occurrence.
* fix(agent-core-v2): check video_in before honoring memoized video uploads
The video memo hit path returned a cached ms:// part before the current
model's capability check, so switching to a same-provider model with
video_in:false sent a video part the model cannot accept instead of
degrading to the path tag. Gate on capability first, mirroring the image
strategy.
* fix(kimi-code): keep recalled queued media staged instead of releasing it
Recalling a queued media prompt into the editor is not a discard, but
the recall path released the staged files: image attachments lost their
daemon upload (resubmit silently downgraded to inline), and a recalled
video's cache copy was deleted even though re-materialization needs a
source that may already be gone. Recall now consumes only the retain
(the next submit re-retains), retires the cache copy to session
lifetime, and rebases the video attachment onto that copy.
* fix(agent-core-v2): count launching media prompts in prompt.queued queueLength
startNext shifts the record into launchingItem before publishQueued
computes the count, so a media prompt's prompt.queued reported
queueLength 0 even though the prompt is accepted, abortable, and listed
as queued. Compute the count from the same snapshot list() exposes.
* refactor(agent-core-v2): drop the session media shared-cache fallback
Intake keeps the upload-backed reference when the canonical write fails
instead of double-writing into an unowned global cache scope; the session
media store's reads collapse to the canonical scope, and non-filesystem
deployments no longer write every media blob twice.
* refactor(agent-core-v2): stop persisting materialization paths in daemon file references
The kimi-file:// reference persisted in context memory bundled a durable
identity (fileId) with a perishable machine-local absolute path (?path=),
which forked sessions and home relocations would stale. The reference now
carries only the file id; the display path is derived from the session
media store by file id at read time. Parsers tolerate and strip the legacy
?path= query so old records keep resolving.
* fix(agent-core-v2): skip atomic-write temp siblings in session media by-id resolution
The fs backend stages atomic writes at <key>.tmp.<pid>.<hex> next to the
target key, and the media store's prefix-listing predicate matched them, so
a lookup racing an unfinished materialize could return the partial copy as
the canonical file.
* fix(kimi-code): close the staging-lease gap between extraction and dispatch
Create the staging lease right after extraction so every pre-dispatch exit
releases through the tracker: validation/session failures release it,
queueing defers it to the queue item's raw ids/paths, and the cache-hint
stash takes over ownership. A forgotten exit now degrades to an unclaimed
lease swept at session close instead of a permanently retained upload.
The cache-hint restore exits (dismiss, chained restore, session switch
during fetch, failed compact/new-session) previously returned only the
text to the editor, leaking the extraction's retains and staged cache
copies. They now go through queue-recall semantics: retains are consumed,
staged copies retire, and recalled videos rebase onto them.
* fix(agent-core-v2): bound the inline image memo with a private byte-budgeted LRU
A memoized inline image part pins a multi-MB base64 string, and the agent
state registry's snapshot/inspect path serializes every registered state
in full — so the memo no longer lives in agentState. It is now a private
per-file-id LRU with the existing 8MB per-entry cap plus a 64MB total
budget; eviction simply re-reads the bytes on the next request. The video
memo stays in agentState.
* fix(kap-server): fall back to the staged upload on the session media route
Prompt intake materializes bytes into the session media store
asynchronously and best-effort, but a session_media ref is projected to
clients as soon as the prompt is queued — so the download route could 404
during the intake window, and forever after an intake failure. The route
now reads the canonical session store first and falls back to the App-scope
staged upload, adapting it to the same served shape; only a double miss is
a 404. The header note also records that resolving the store resumes cold
sessions, an accepted short-term semantic with a TODO for a cold-read
channel.
The secondary-model variant example could not work as written: a bare
[models] entry does not inherit the provisioned entry's metadata, and
default_effort only takes effect when it is a member of support_efforts,
which the kimi-for-coding family does not declare. Base the example on
kimi-code/k3 with the full metadata copied, and state both prerequisites.
Also align the full-config example's k3 support_efforts with what /login
provisions (low/high/max, so the shown thinking effort "high" is valid),
and stop describing kimi-for-coding-highspeed as cheap: it is priced
higher, so its pool hint now steers toward latency-sensitive tasks.
* feat(kimi-code): recognize multiple inline skill activations in one prompt
Inline /skill: tokens are recognized anywhere in the prompt (after
whitespace, including on following lines) with completion, highlighting,
and de-duplication. Submitting goes through session.promptWithSkills, so
the engine bundles every activation into the prompt's own user message —
one turn, one undo anchor. Replay rebuilds the per-skill cards from the
prompt origin's skillActivations and shows only the caller's own parts in
the user bubble; undo removes the prompt together with its marked bundle
cards; hook results ahead of a bundle are projected inside its window.
Enter accepts an inline completion without submitting (pi-tui
inlineSlashTrigger), and cache-hint plus /btw pass activations through.
* fix(kimi-code): harden bundled skill submissions against review findings
- Mark bundle cards by entry id, not by index into a captured array: the
transcript window trim may replace the entries array mid-call.
- The replay turn limiter no longer cuts between a bundled prompt and the
hook results recorded immediately before it; the oldest visible bundle
keeps its hook context.
- A leading-combo bundle (/skill:a args /skill:b) now queues while busy
like any other inline-skill prompt, instead of being rejected by the
single-skill slash gate.
* fix(kimi-code): fetch one extra replay turn on resume
The SDK trims the replay to the requested limit before returning it, so a
trim landing between a bundled prompt and its preceding hook results would
make them unrecoverable to the TUI-side limiter. Resume now fetches one
extra turn of margin; preserveBundleHookResults does the final cut without
losing the hook context.
* fix(pi-tui): retrigger inline slash completion as the token grows
When the terminal delivers `/rev` in one stdin chunk, the slash starts an
autocomplete request but the following letters arrived to a null
autocomplete state and — unlike a leading slash command — matched no
retrigger context, so the stale request was discarded and the menu never
appeared. Typing token characters inside an inline slash token now
retriggers completion (with a regression test). Also aligns the startup
resume tests with REPLAY_FETCH_TURN_LIMIT.
* fix(pi-tui): retrigger inline completion on later lines too
isSlashMenuAllowed confines the slash-command menu to the first line, so
reusing it for the inline-slash retrigger context silently disabled
retriggering on every later line — the bare-slash request went stale and
the menu never appeared. The inline context now covers a token-opening
slash on subsequent lines as well (with a regression test).
* fix(kimi-code): activate leading skill tokens in /btw and repeated-token combos
- /btw's initial prompt lives entirely in the slash arguments, so a skill
token there sits at position 0; scan it with includeLeading so
`/btw /skill:review …` actually activates the skill.
- Combo-ness is now decided by the raw inline token count rather than the
deduplicated activation count, so `/skill:review check /skill:review`
submits as a bundled prompt instead of falling through to the
single-skill path with the repeated token swallowed into the args.
* fix(kimi-code): rewrite media placeholders in leading combo arguments
A leading combo's first activation carries the raw slash arguments, so a
pasted media placeholder in them reached the engine unresolved — unlike
the standalone sendSkillActivation path, which rewrites placeholders into
escape-proof plain-text file references first. sendInlineSkillUserInput
now rewrites any arg-carrying activation the same way (covering the busy
queue and /btw intercept paths too), while the media themselves continue
to ride the prompt as extracted parts.
* refactor(kimi-code): skill mentions never carry args in bundled prompts
Align bundled submissions with the mention model: two or more skill
tokens anywhere in the input (the leading one included) make one bundled
prompt in which every token activates by name only, and args stay a
standalone /skill:<name> args concept. This removes the leading combo's
command+args parsing, so the first skill's arguments can no longer leak
the next token (displayed as a duplicated prompt under its card), media
placeholders no longer need arg rewriting, and newline-separated bundles
behave exactly like space-separated ones (parseSlashInput's literal-space
separator no longer decides bundle-ness).
* fix(kimi-code): recognized builtin and plugin commands outrank the bundle rule
The no-args bundle rule claimed any input with two or more skill tokens
before checking what led it, so `/btw check /skill:a /skill:b` was
submitted to the main agent as a bundled prompt instead of opening the
side panel. The intent is now resolved first: builtin and plugin commands
always keep their own path regardless of how many skill tokens their
arguments mention, while skill-led and newline-led inputs still bundle as
before.
* fix(pi-tui): retrigger inline completion on colons and register the local divergences
External skill tokens are shaped /skill:<name>, but the inline-slash
retrigger character classes excluded ':' — typing the colon launched no
replacement request, the bare-slash request went stale, and the menu never
appeared for prefixed skill names. Colons now retrigger completion like
other token characters (with a regression test). Also registers the
inlineSlashTrigger and autocomplete-data divergences in the package's
re-vendor protection list.
* fix(kimi-code): preserve FIFO behind unsteerable bundles and reach indented inline completion
- Ctrl-S steering now stops at the first inline-skill bundle: a later
queued message (or the editor draft) no longer jumps ahead of the
unsteerable bundle into the running turn, so the conversational order
survives steering.
- The leading-whitespace slash-path suppression now yields to the inline
skill context first, so an indented token (` /skill:rev`) completes
like its column-0 equivalent instead of being suppressed as a path.
* feat(agent-core-v2): support grouped multi-skill prompt submissions
Add IAgentSkillService.promptWithSkills: one or more skill activations
are validated up front (an unknown or empty submission rejects with no
side effects), recorded with a shared submissionId, and enqueued ahead
of the prompt through the prompt queue's messagesBefore support, so the
whole group materializes atomically as a single turn. Undo cuts, the
transcript projection, and the undo precheck treat the group as one
unit (stopping at the next anchor even when submission ids collide);
hook-result messages are skipped like injections during those walks.
Submit hooks run against every message of the group, and user-slash
skill activations count as user-submitted content for the UserPromptSubmit
hook's origin filter.
Surface it through the contract layers: protocol gains submissionId on
the user / skill_activation origins and on the skill.activated event
(kap-server zod mirrored), klient exposes agentSkillContract.promptWithSkills
with parity assertions, and the SDK grows session.promptWithSkills —
implemented on the v2 engine and rejecting loudly on the deprecated v1
engine, which is otherwise untouched.
* fix(agent-core-v2): reject empty skill lists in grouped prompt submissions
- Validate that promptWithSkills receives at least one skill, enforced in
the engine and as a non-empty constraint in the klient wire schema.
- Restore the released versions and changelog sections for agent-core-v2,
klient, and node-sdk that the branch cut had reverted.
- Move statement-level narration into the owning file headers per the
package comment conventions.
- Align the hook-result undo tests with the reachable record ordering
(hook results are recorded before the group materializes).
* refactor(agent-core-v2): bundle grouped skill activations into the prompt message
Replace the submissionId-correlated message group with a single bundled
user message: the rendered skill blocks precede the caller's parts in the
content, and every activation's metadata rides the prompt origin's new
skillActivations field. The bundle is one anchor by construction, so undo
needs no group-cutting logic and the messagesBefore prompt seam disappears;
the submit hook fires once per submission. skill.activated still fires per
skill (transient ops, live-only); resume rebuilds the per-skill view from
the prompt origin. Contract chain (protocol, kap-server, klient, node-sdk)
drops submissionId accordingly.
* fix(agent-core-v2): keep bundled skill blocks out of prompt-facing projections
- The transcript cold rebuild expands a bundled prompt's origin
skillActivations back into per-skill markers (the live path already
projects them from skill.activated events).
- turn.started.prompt, the session title excerpt source, and the fork
lastPrompt now derive from the caller's own parts, excluding the
rendered skill blocks the engine prepends to the bundled content.
- Drop the redundant undefined unions from the new origin fields.
- Move the activateSkill test narration into the file header.
* refactor(agent-core-v2): decouple workspace from session DI via runtime binding
* fix(agent-core-v2): unblock session external hooks and scope workspaceMcp seeds
- externalHooksService: inject App-level ISessionManager instead of the
unregistered ISessionLifecycleService so SessionStart/SessionEnd hooks
actually activate in production; keep sessionId matching and tolerate
absent lifecycle events
- workspaceMcpService: ignore onWillCreateSession events whose session
belongs to another workspace, preventing cross-workspace
ISessionMcpHandle seed overrides
- update externalHooks integration tests, agent harness, and workspaceMcp
tests; add reloadSources coverage in skillCatalog tests
* fix(agent-core-v2): honor the bound runtime in prompt context, swarm spawn, and ACP sessions
- map system-prompt cwd, directory listing, and additional dirs through
RuntimeWorkspaceView, and skip the listing when the bound runtime has
no fs capability
- pass the caller agent's runtime binding to AgentSwarm child creation
and prompt-prefix execution instead of hardcoding local
- expose the ACP client filesystem through the ACP session runtime and
build its shell/path environment from the probed host instead of
hardcoded Linux
- dispatch klient facade createChild to sessionManager.createChild so
child sessions keep their parent markers
* fix(agent-core-v2): resolve routed fs and tool paths with runtime path semantics
- WorkspaceFsService resolves via the bound runtime's RuntimePath (extended with basename/dirname) instead of node:path, so mapped roots such as C:\\repo stay runtime-local.
- Read/Write/Glob/Grep pass skill roots through mapRoots via RuntimeWorkspaceView input, matching Edit.
- acp-server unbinds session runtimes on session/close, not only on delete.
- apps/kimi-code drops the /runtime slash command; SDK runtime methods stay.
* fix(agent-core-v2): retire idle session controllers, untrack disposed runtime resources, and rebuild fs watches on generation replace
* fix(agent-core-v2): resolve oxlint errors in runtime lifecycle fixes
* fix(kap-server): untrack download stream from runtime generation on completion
* fix(kap-server): drop meaningless void operator on tracked dispose
* feat(packages): implement cowork
feat(packages): update throttle control
feat(agent-core): rename to /tower
feat(agent-core-v2): support tower mode
fix(packages): keep tower teardown from stranding submodule worktrees
A plain `git worktree remove` refuses worktrees containing initialized
submodules even when they are clean, so tower teardown silently left
behind exactly the worktrees whose workers had run builds (the failure
only reached the tool report, never the activity log).
The dirty check is the data-loss gate; once it passes, removal always
passes --force (harmless on a clean worktree, and precisely what
bypasses git's submodule refusal). Kept and failed removals now also
land in the activity log as worktree.keep / worktree.remove.failed.
feat(packages): allow the tower to AskUserQuestion, workers still cannot
The tower-mode AskUserQuestion deny only ever fired on the tower itself:
workers never enter tower mode, and their tower-worker profile simply
does not list the tool. Drop the deny so the tower can clarify
requirements with the human up front; workers and reviewers stay
ask-less and escalate via TowerSend. Auto permission mode still
disables AskUserQuestion for everyone.
fix(agent-core-v2): import LifecycleScope from #/app/scopes
main moved the enum out of #/_base/di/scope; follow the new location in
the two tower services.
test(agent-core-v2): refresh fullCompaction token expectations
main's #2699 counts compaction tokens on the full-request basis, so the
tower tool schemas (default registry) and the /tower skill catalog entry
(system prompt) shift the pinned numbers: +2789 with the default tool
set, +173 with the explicit harness tool list. The 20k-window test keeps
its shape with a 22k window so the post-compaction floor still fits.
feat(agent-core-v2): tower command support secondary model
fix(tower): disable todo-list tool
feat(tower): reviewer keep primary model
fix(tower): tower worker call for authroization
update
* refactor(tower): drop agent-core-v1 version
* feat(tower): remove builtin.ts
* fix(agent-core-v2): verify the recorded base branch before tower merges
* fix(agent-core-v2): activate tower missions only after a successful spawn
* chore(kap-server): correct the search-service activation comment
* fix(tower): allowActivationWhileBusy for all skill
* update
* update
---------
Co-authored-by: konghuanjun <konghuanjun@moonshot.ai>
* feat(tui): print the fork resume command and copy it to the clipboard
* fix(tui): use pushd in the Windows fork resume command so it switches drives
cmd.exe's `cd` only updates the target drive's remembered directory, so a
terminal on another drive would run `kimi --resume` in the wrong working
directory. `pushd` switches drive + directory in both cmd.exe and
PowerShell (`cd /d` would break PowerShell). Addresses the Codex review
comment.
* fix(tui): label OSC 52 clipboard delivery as unverified after fork
copyTextToClipboard falls back to an OSC 52 escape when no native
clipboard provider works; terminals without OSC 52 support silently
drop the sequence, so only native delivery may claim success. Matches
the wording convention of /copy. Addresses the Codex review comment.
---------
Co-authored-by: bj456736 <bj456736@users.noreply.github.com>
* fix(cli): warn on over-long /goal objectives before sending and keep the input
- Show a live footer warning in the TUI while a typed /goal objective
exceeds the 4000-character limit, measuring paste-expanded text only
when the input can be a /goal command.
- Restore the rejected /goal input into the editor instead of losing it.
- Include the file-reference workaround in the GOAL_OBJECTIVE_TOO_LONG
error messages (TUI, goal queue, agent-core, agent-core-v2).
* fix(cli): keep the /goal length warning in its own footer slot
A transient hint (exit confirm, detach, image paste) that displaced the
warning previously left the footer blank after clearing, because no
editor change re-applied it. The footer now renders the warning from a
dedicated slot whenever no transient hint is active, so the warning
returns on its own.
* fix(cli): gate the /goal length warning on trimmed text
Submitted text is trimmed before slash-command dispatch, so leading
whitespace still runs /goal — normalize with trimStart in the gate and
in the length check to match.
* fix(cli): restore input rejected by the slash-command busy gate
An idle-only command submitted while streaming/compacting was rejected
after the editor buffer had already been cleared, losing hand-typed
input (e.g. an over-long /goal objective that never reached the local
validation).
* fix(cli): restore input at the post-creation busy re-check
The lazy-session race rejects an idle-only command after a first prompt
has already started a turn; the editor buffer is long cleared by then,
so give the submitted input back like the dispatch blocked branch does.
* fix(cli): close the remaining input-loss and gate gaps around /goal
- Restore the submitted input when lazy session creation fails before a
session-requiring command runs.
- Restore only into a still-empty editor after async gates, so a draft
typed while creation was pending is never overwritten.
- Expand pastes that can complete a partially typed /goal command
(e.g. /go[paste #1 …]) in the length-warning gate.
* fix(cli): never displace newer UI state with a delayed input restore
A session-less /goal submission restores its input only after an async
gap (lazy session creation). If the user opened an editor-replacement
panel meanwhile, restoring would tear it down (and leave activeDialog
inconsistent). Track editorReplacementMounted in TUIState and gate all
delayed restores through canRestoreSubmittedInput.
* refactor(cli): move canRestoreSubmittedInput into commands/resolve
Avoids the goal.ts <-> dispatch.ts runtime import cycle flagged by
import/no-cycle; the helper takes a structural host shape instead.
* fix(cli): match the slash parser's delimiter in the /goal length warning
parseSlashInput splits the command name at a literal space only, so a
newline or tab after /goal dispatches as a plain message — the warning
must not fire for inputs the dispatcher will not treat as a goal.
* 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.
* feat(agent-core-v2): surface a machine-key note from capability installs
CapabilityEntry.install now resolves an optional note exposed through
CapabilityInstallProgress.note (wire-visible). The webbridge entry
returns 'user-skill-migrated' when it migrates a pre-existing
standalone skill copy onto the plugin-managed one — clients can
localize the migration instead of the skill silently disappearing
from the user's directory.
* feat(kap-server): add plugin management and capability REST routes
Expose the App-scope plugin and capability services over the wire so
non-CLI hosts (desktop, web) can manage plugins and built-in
capabilities end to end:
- GET /api/v1/plugins, POST /api/v1/plugins {source},
POST /api/v1/plugins/{id}:{enable,disable,remove}
- GET /api/v1/plugins/marketplace — catalog (pluginMarketplaceUrl
server option / KIMI_CODE_PLUGIN_MARKETPLACE_URL env / production
default) merged on demand with live install state; updateAvailable
only on strict semver catalog > installed (no semver dependency)
- GET /api/v1/capabilities, GET /api/v1/capabilities/{id},
POST /api/v1/capabilities/{id}:install with client-polled progress
- New wire codes 40418 capability.not_found, 40419 plugin.not_found,
40923 capability.install_in_progress, 40924 capability.unsupported
Mutations flow through IPluginService, so they serialize with other
install paths and fire onDidReload (session skill catalogs and the
capability shelf-install hook converge).
* fix(kap-server): map plugin input errors to 4xx and correct the unsupported test code
- mapPluginError now translates the domain's validation.failed (40001)
and fs.path_not_found (40409) instead of collapsing client-fixable
input mistakes (relative source, nonexistent local path) into a
50001 internal error
- the non-macOS capability install test expected 40923, which this
branch assigns to capability.install_in_progress; the unsupported
code is 40924 (macOS runners skip the case, which is why it only
fails on Linux/Windows CI)
* fix(kap-server): resolve catalog-relative marketplace sources and widen the unsupported-test skip
- The production CDN catalog carries sources relative to the catalog
URL (./official/*.zip); clients handing them back to POST /plugins
would hit the local-path normalizer's 40001. Resolve entry sources
against the configured catalog URL so every returned source is
directly installable.
- The 40924 install-rejection test only skipped macOS, but kimi-cu is
also supported on Windows x64 — running it there would start the
real installer. Skip on every supported platform.
* fix(kap-server): accept the legacy url/downloadUrl marketplace source aliases
Custom catalogs that the CLI already accepts can carry an entry's source
under url or downloadUrl instead of source; the route's strict schema
rejected the whole catalog with 50001. Normalize the aliases before
validation (same precedence as the CLI parser) so those catalogs keep
working through /api/v1/plugins/marketplace.
* fix(kap-server): support local marketplace catalogs and drop conditional spreads
- KIMI_CODE_PLUGIN_MARKETPLACE_URL accepts a plain path or file://
catalog in the CLI loader; the route only fetched over HTTP, so local
catalogs 50001'd for desktop/web hosts. Read local catalogs from disk
and resolve their relative sources against the catalog's directory.
- Replace the marketplace mapping's conditional spreads with direct
possibly-undefined properties per the repo rule.
* fix: surface capability install notes through klient and convert file:// entry sources
- The klient capabilities contract omitted install.note, so zod parsing
stripped it and facade callers (node-sdk, TUI) never saw
'user-skill-migrated'. Add the field and pin it in the facade test
fixture.
- A marketplace entry source given as a file:// URL fell through to the
relative-branch and came back as a garbage path; convert with
fileURLToPath so the advertised source stays installable.
* test(kap-server): keep the new route tests portable to Windows x64
- The capabilities list assertion treated every non-macOS host as
unsupported, but kimi-cu is supported on Windows x64 — derive the
expectation from the same platform predicate.
- file:///abs/... is not a valid absolute file URL on Windows (no drive
root); build the fixture with pathToFileURL from a temp path instead.
* refactor: align the capability note and test helper with repo conventions
- agent-core-v2 keeps explanatory docs in the top-of-file block only;
the note contract already lives in the capability types header, so
drop the two member-level doc blocks.
- The plugins route test helper sets the optional fetch body directly
instead of via a conditional spread.
* fix(kap-server): expand ~ in local marketplace catalog paths
The CLI loader expands ~/ against the home directory; the route read
the path literally, so KIMI_CODE_PLUGIN_MARKETPLACE_URL=~/catalog.json
50001'd for desktop/web hosts while working in the CLI. Share one
localCatalogPath helper (file:// conversion + tilde expansion) between
the catalog read and the relative-source resolver.
* fix(kap-server): expand home-relative marketplace entry sources
A catalog entry with source '~/...' fell through to the catalog-relative
branch and came back as <catalog-dir>/~/... — unresolvable by POST
/plugins. Expand ~ via the shared helper before the absolute/relative
decision.
* fix(kap-server): match CLI field semantics for source aliases and stub the Windows home
- A blank or non-string source no longer shadows the url/downloadUrl
aliases; the first valid (non-blank, trimmed) of source/url/downloadUrl
wins, mirroring the CLI parser's stringField.
- The tilde test also stubs USERPROFILE so os.homedir() resolves to the
fixture home on Windows runners.
* fix(kap-server): read a blank marketplace tier as missing
The CLI parser trims tier and treats a blank as absent (third-party);
the route's enum rejected the whole catalog with 50001. Normalize the
tier alongside the source aliases in the same preprocess.
* fix(kap-server): derive marketplace versions from GitHub release sources
Entries that omit version but encode it in a GitHub release/tag (or
tree/commit) source never surfaced updateAvailable. Derive the version
from the resolved source — same URL shapes as the CLI parser, validated
with the route's strict x.y.z rule (no semver dependency).
* fix(kap-server): fail catalog validation on a source with no usable value
A whitespace-only source with no valid alias passed z.string().min(1)
untrimmed and resolved against the catalog URL into nonsense. Drop the
key during normalization so the schema reports the entry as missing its
source (same outcome as the CLI's 'must define source').
* fix(kap-server): resolve latest versions for bare GitHub marketplace entries
A catalog row whose source is a bare GitHub repo (the production curated
rows are shaped this way) kept version undefined, so updateAvailable
never fired for exactly the entries most likely to update. Resolve the
latest release tag through the /releases/latest redirect — the UI route,
not the rate-limited API — same as the CLI, degrading to no version on
any failure.
* docs(kap-server): note the marketplace version resolution in the plugins route header
* feat(kap-server): mark capability wiring rows in the marketplace response
A client following only /plugins/marketplace + POST /plugins would
install a capability's wiring plugin without its binary runtime, with
no wire-level way to tell. Entries whose id matches a capability's
wiring plugin now carry capabilityId, so clients route them through
/capabilities/{id}:install — the client-side routing pattern the CLI
established (the upstream design that replaced the server-side hook).
* fix(kap-server): fall back to the source-checkout catalog for the default location
When the marketplace location is the built-in default (no server option
or env override) and the fetch fails, read the repo checkout's own
plugins/marketplace.json — the CLI loader's behavior for offline
source-checkout dev. An explicitly configured catalog still fails hard
with 50001. Bundled installs have no checkout file, so the fallback
simply never fires there.
* fix(kap-server): resolve fallback catalog sources against the fallback file
readMarketplaceCatalog returned only the JSON, so entries from the
source-checkout fallback resolved their relative sources against the
(unreachable) CDN URL — coming back as unusable https paths instead of
local directories. The reader now returns the location actually read,
and source resolution uses it.
* fix(kap-server): honor the CLI's marketplace metadata aliases
Custom catalogs using name / shortDescription / websiteURL (accepted by
the CLI parser) lost those fields to schema stripping, falling back to
the entry id. Normalize the aliases in the same preprocess as the
source/tier normalization.
* fix(kap-server): filter marketplace keywords instead of rejecting the catalog
A keywords array with non-string or blank members failed the strict
schema and took the whole catalog down with 50001. Normalize to the CLI
parser's semantics: non-array reads as missing, arrays keep trimmed
non-blank strings only.
* fix(kap-server): treat a blank or non-string marketplace version as missing
The CLI parser reads version through its lenient stringField and falls
through to source-derived versions; the route's schema rejected a
numeric version with 50001 for the whole catalog. Normalize version in
the preprocess like the other fields — the gh-plugin fixture now
carries a numeric version and still derives 2.0.0 from its tag source.
* fix(kap-server): trim marketplace entry ids before the install-state join
A whitespace-padded id survived validation raw and never matched the
installed records (updateAvailable silently lost). Normalize the id in
the preprocess — trimmed, blank rejected — matching the CLI's
requiredString.
* fix(kap-server): gate capability markers to the default catalog
A custom catalog (env or server option) may legitimately carry a
same-id fork of a capability's wiring plugin; marking it capabilityId
would route users to the built-in install. Apply the marker only for
the default catalog (including the source-checkout fallback), matching
the CLI injecting built-in rows only for the default catalog.
* fix(kap-server): compare marketplace versions with real semver
The hand-rolled strict x.y.z check rejected valid semver the CLI
accepts (v-prefixed, prerelease tags), so updateAvailable diverged
between CLI and wire clients. Take the semver package (already in the
monorepo via the CLI) for the update check and the two source-derived
version validators.
* fix(kap-server): validate marketplace entry types and count the dev server as default
- Custom catalog rows with an unsupported type (e.g. integration) were
stripped by the schema and advertised as installable plugins; the CLI
rejects the catalog outright. Model the same plugin/managed/guide
vocabulary.
- scripts/dev.mjs marks its repo-owned catalog with
KIMI_CODE_PLUGIN_MARKETPLACE_FROM_DEV_SERVER=1 — honor the flag in
the isDefault check so capability markers and the checkout fallback
behave exactly like the CLI under the dev marketplace.
* fix(kap-server): join capability rows through their platform wiring plugin id
kimi-cu installs its wiring plugin as kimi-cu-win on Windows x64, so a
catalog row keyed kimi-cu never matched the installed record there (no
installed state, no updateAvailable). The row mapping now knows each
capability's wiring plugin ids and joins through them.
* fix(kap-server): map plugin load failures to 40001
An install source pointing at a directory/zip with a missing or invalid
manifest throws plugin.load_failed — a client-fixable input error that
fell through to 50001. Map it to validation.failed alongside the other
input mistakes.
* build(kap-server): align @types/semver with the workspace version
sherif rejects multiple workspace versions of one dependency; the CLI
pins @types/semver at ^7.7.0.
* refactor(agent-core-v2): share the plugin marketplace client/parser across hosts
The kap-server marketplace route grew its own copy of the CLI's catalog
loading/parsing logic (lenient aliases, blank-means-missing fields,
source resolution, GitHub version derivation) — two implementations of
a public, hand-writable format would drift on every catalog change.
Move the read/parse/version machinery into the plugin domain as
app/plugin/marketplace (pure functions, no DI): the CLI keeps a thin
wrapper owning configured-source resolution and its checkout fallback,
and the route keeps only the wire concerns (install-state merge,
capabilityId markers, error envelopes). plugins.ts drops ~230 lines of
duplicated machinery.
One deliberate behavior fix rides along: tilde entry sources now expand
against the home directory at parse time (the CLI previously passed
them through literally, failing later at install validation).
* docs(agent-core-v2): fold the marketplace module's member docs into the file header
The package convention keeps explanatory comments in the top-of-file
block only; the moved parser carried several function/member-level
JSDoc blocks from its CLI home. The header now carries the format
contract, leniency rules, source/version resolution order, built-in
masking semantics, and the fallback gating rule.
* docs(agent-core-v2): drop the remaining statement comments in the marketplace module
The header carries the rationale (update semantics, GitHub ref shapes,
the releases/latest choice); the convention allows nothing beside
statements.
* fix(kimi-code): import the shared marketplace module by its deep path
constant/app.ts is evaluated on every CLI invocation; re-exporting from
the agent-core-v2 root would pull the whole engine module graph into
startup. The package's wildcard subpath export lets both CLI files take
only the pure marketplace module (node builtins + semver).
* feat(kap-server): fan plugin and capability lifecycle out as global WS events
Clients currently poll the plugins/capabilities REST surfaces and can
hold stale rows while another client mutates the set. Publish two global
events instead:
- event.plugin.changed — fired off IPluginService.onDidReload, so any
install/enable/disable/remove from any client reaches every host
- event.capability.changed — every capability install progress
transition (CapabilityService gains onDidChangeInstall), so rows
update live and settle is observable without polling
Both ride the existing global fan-out (no subscription needed) and are
documented in the wire schema registry.
* fix: register the lifecycle events in the wire union and tidy the contract header
- event.plugin.changed / event.capability.changed were declared but not
part of agentEventSchema, leaving the wire catalog incomplete.
- The onDidChangeInstall member doc moves into the capability contract
file header (package comment convention).
* feat(protocol): mirror the plugin/capability lifecycle events in the shared WS schema
Clients and e2e harnesses validating server frames against
@moonshot-ai/protocol would reject event.plugin.changed /
event.capability.changed. Register both in the shared catalog (TS
interfaces, zod schemas, and both unions), matching the
model_catalog.changed precedent for global events.
* fix(kap-server): prefer the platform wiring plugin when joining capability rows
A stale same-id record (e.g. a raw kimi-cu plugin next to the real
kimi-cu-win wiring on Windows x64) previously won the join, showing the
wrong installed state and update availability. Capability rows now join
through the wiring plugin ids in platform preference order before
falling back to the catalog id.
* fix(kap-server): put the github metadata of plugin summaries on the wire schema
GitHub-sourced plugin summaries carry github {owner, repo, ref,
installedSha} from the domain; the route serializes raw domain objects,
so the field reached clients undocumented. Declare it in
pluginSummarySchema so the OpenAPI surface matches reality.
* test(node-sdk): cover the new lifecycle events in the exhaustive switch
The event-type exhaustiveness test broke when the shared protocol union
gained event.plugin.changed / event.capability.changed.
* fix(kap-server): mark capability progress events volatile
Per-chunk download progress transitions ride the same fan-out as
durable frames and were being persisted to the __global__ journal —
hundreds of stale frames per install. event.capability.changed is
live-only state, so it joins the volatile list alongside
event.di.unit_changed; the settle frame stays recoverable via a direct
capability read. event.plugin.changed remains durable (rare, and a
reconnecting client should replay it).
* feat(kap-server): inject built-in capability rows into the default catalog response
The checked-in production catalog carries kimi-webbridge but not
kimi-cu — the CLI injects built-in rows client-side, so wire clients
never saw Kimi Computer Use in /plugins/marketplace. For the default
catalog the route now appends supported capabilities the catalog lacks
(static descriptors via ICapabilityService.describeCapabilities — no
detector probes), marked with capabilityId and a capability:<id>
sentinel source so installs still route through the capability
surface.
* fix(kap-server): run injected capability rows through the install-state join
The injected kimi-cu row hardcoded installed: undefined, so an
already-installed capability still read as installable. Injection now
happens before projection, so injected rows get the same backing-plugin
join (installed state, update badge, capabilityId marker) as catalog
rows. Also moves the describeCapabilities note into the contract header
(package comment convention).
* test(kap-server): gate the injected-row assertions on platform support
kimi-cu injects only where supported (macOS / Windows x64); on Linux CI
the row is correctly absent.
* fix(protocol): classify capability progress as volatile in the shared catalog
kap-server never journals event.capability.changed (it is in the
server-local volatile list); shared-protocol clients reading
isVolatileEventType would treat per-chunk progress frames as durable
and replayable. Mirror the classification.
* fix(kap-server): hide capability rows on unsupported platforms
Catalog-carried capability rows (kimi-webbridge in the default catalog)
were marked with capabilityId regardless of host support — on an
unsupported platform clients would route into an impossible capability
install. Rows whose capability is unsupported are now excluded from the
default-catalog response entirely (the CLI hides its built-in rows the
same way).
* 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.
* test(kap-server): poll the read-model immediate-read assertions
The 'prepares the read model at boot and serves immediate reads' test
sampled the session list / workspace session_count / paged read exactly
once after creating a session. While a mirror flush is in flight its
batch is only per-shard atomic and the pending-queue cleanup is not
linearized with reads, so a single-sample read landing inside that
window can transiently miss or double-count the new session (seen
twice on main CI as 'expected false to be true' and 'expected 0 to be
1'). Poll with vi.waitFor instead; the transient lasts at most one
in-flight flush (~100ms cadence).
* test(kap-server): retry the transcript test temp-dir teardown rm
The engine's file log writers flush synchronously on scope dispose but
their trailing async close can still create a file under the test home
after server.close() resolves, so the afterEach rm occasionally fails
with ENOTEMPTY on a loaded CI runner. Retry the rm (maxRetries: 5),
matching the existing pattern in questions.test.ts / fs.test.ts.
* test(kap-server): drain the in-flight search sync before appending
The 'serves the published generation without waiting for a blocked
background sync' test appended the delta right after a warm-up search
that had kicked a fire-and-forget background sync pass. On a starved
CI worker thread that pass can read the file after the append and
publish both documents early ('expected 2 to be 1'). settleSync before
the append makes 'no pass can index the delta' structural.
The stress test asserted stats.compactions > 0 immediately after the
write loop, but auto-compaction is fire-and-forget through the
maintenance scheduler and the counter only increments once a run fully
completes. On a loaded CI runner the loop can finish before the first
compaction lands, failing the guard even though nothing is broken.
Wait for the first completed compaction with the existing waitFor
helper instead: the guard still proves the churn this scenario
requires happened, and a genuinely broken auto-trigger now fails via
the wait timeout.
- Remove the legacy-engine secondary-model recipe section, the
KIMI_SECONDARY_MODEL / KIMI_SECONDARY_EFFORT env entries, and the
model_preference agent-file field: the default engine never reads
them and the legacy engine is deprecated.
- Remove the backward-compat note for a lone [secondary_model] model
key; the code still reads it, but the docs now only document the
current pool scheme.
- Reframe the secondary_model section around the subagent model pool
instead of a singular secondary model.
- Unify zh terminology: 子 Agent -> subagent, 主 Agent -> main agent,
covering prose, headings, anchors, the sidebar label, and the
docs/AGENTS.md term table.
* fix(features): retract contributed service metadata
- tie contributed service discovery to feature disposal
- reject duplicate providers for the same scope and service
- cover feature unload and debug channel resolution
* test(features): preserve contributed service registry
- remove the global contributed-service test reset
- keep provider cleanup local to each regression test
* fix(features): scope service discovery to each app
- store feature service metadata in the app-local collection tree
- bind debug lookup and test overrides to the owning app root
- keep duplicate provider activation atomic within one app
* 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>
* refactor(agent-core-v2): extract swarm into a scope-organized feature
- move src/agent/swarm, src/session/swarm, and src/agent/tools/agent-swarm
into src/features/swarm/{agent,session,tools/agent-swarm}; swarmOps.ts
stays a static import=register wire channel at the feature root
- add SwarmFeature carrying the three runtime registrations
(IAgentSwarmService, ISessionSwarmService, IAgentSwarmTool) with
ScopeActivation.OnScopeCreated preserved
- switch src/index.ts to precise leaf exports and update import sites,
including the kap-server and kimi-inspect deep-path imports
- move tests to test/features/swarm and re-assert service overrides in
the test harness so stubs keep winning over feature contributions
* fix(agent-core-v2): keep feature-contributed tools in Agent tool descriptions
SubagentTool.knownToolReferences() now reads the full AgentToolContribution
collection (static registrations and feature contributions alike) instead
of the static contribution table. A caller profile that does not activate
a feature-contributed tool (e.g. AgentSwarm) no longer drops it from the
per-profile tool listings the description advertises for spawned profiles
when a workspace/session restriction forces explicit enumeration.
Add a regression test with a caller profile lacking AgentSwarm under a
global tool restriction.
* refactor(kap-server): lift session profile updates to the route edge
- add sessionProfile.ts/sessionAgentConfig.ts route helpers that resume
the session and dispatch title/metadata and the agent_config patch to
the native v2 services directly
- drop updateProfile from ISessionLegacyService, leaving only the
status rollup and the goal read in the legacy adapter
- wire shape and client-visible behavior unchanged
The [subagent] default_model / models deprecations added in #2700 guard a
migration path that has no users: the pool keys only existed in #2700's own
intermediate commits and never shipped in any release, so no config written
against a released version can contain them. Remove the two deprecation
entries (the mechanism stays — the released loop_control renames still use
it), the migration notes in the en/zh config docs, the agent-core-dev skill
note, and the obsolete test; regenerate the config manifest.
No changeset: #2700 is still unreleased, so no published version ever
emitted these warnings — the removal is invisible to users.
* 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.
* refactor(agent-core-v2): remove the agent RPC aggregation layer
- delete src/agent/rpc/ (AgentRPCService, IAgentRPCService, core-api,
prompt-metadata, types) and sink each method's orchestration into its
owning domain service
- prompt: new submit/submitSteer composing disabledTools gating,
MAIN-only session metadata, and engine-side {turn_id} settlement
- skill: activate now returns PromptLaunchResult and writes session
metadata internally (MAIN-only, unified across prompt/steer/skill/
pluginCommand); node-sdk and kap-server drop their edge-side writes
- pluginCommand: new agent-scope domain owning command activation and
the plugin_command.activated domain event
- permissionMode/loop/fullCompaction: new setModeAndBroadcast /
cancelFromUser / cancel; setMode and loop.cancel stay pure for
internal callers
- klient: agentRpcContract split into per-domain contracts; facade
re-routes to domain channels with its public API unchanged
- node-sdk, kap-server, kimi-inspect and the v2 test harness now call
domain services directly; ctx.rpc keeps its name as a composed
adapter
- externally visible: the agentRPCService debug channel is gone and
session metadata writes are now MAIN-agent-only (see changeset)
* refactor(agent-core-v2): move disabledTools gating out of the prompt domain
Prompt should not own session tool policy: submit no longer accepts or
applies disabledTools. The klient facade keeps its prompt({ disabledTools })
API and composes it edge-side — applying agentToolPolicyService
setSessionDisabledTools before calling agentPromptService.submit, the same
way kap-server's prompt route already does. Over klient, a profile-less
engine now surfaces the raw profile error instead of request.invalid.
Also restores the RPC-removal changeset, which did not make it into the
previous commit.
* chore(agent-core-v2): drop the RPC-removal changeset
* refactor(klient): drop disabledTools from the prompt entry entirely
The prompt path no longer carries session tool gating on any surface:
the klient facade prompt() loses the disabledTools field and calls
agentPromptService.submit directly, and the node-sdk
SessionPromptRpcInput stops accepting or forwarding it (v1 always
ignored the field). Session tool gating remains available through
IAgentToolPolicyService.setSessionDisabledTools, composed at the edge
the way kap-server's prompt route does; the klient toolPolicy contract
added for facade-side composition is removed as unused.
* 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.
* refactor(agent-core-v2): unify model-facing reminder scheduling
Route every model-facing reminder through the contextInjector boundary
scheduler. Past-tense events go through a persisted once-reminder queue
(reminderQueue) that delivers exactly once at turn, step, compaction,
and restore boundaries; present-tense state renders through
context-injection providers reconciled against live history.
- interruption, goal (cancel/budget/fork-cleared), image-compression
captions, btw, and init reminders enqueue into reminderQueue instead
of writing the context directly; the interruptionReminder wire model
is removed and its recorded type is retired silently on replay
- swarm mode announcements render through a provider seeded from the
replayed history on restore, replacing live side effects and the
ContextModel pop reducer on swarm_mode.exit
- loadable-tools announcements become an isNewTurn-gated provider,
dropping the compaction boundary flag
- plugin session-start guidance re-renders as a supersedes reminder at
the next boundary via a dirty flag instead of appending immediately
- legacy system_trigger origins of migrated reminders still fold on
replay
* fix(agent-core-v2): make system reminders undo-aware
* test(agent-core-v2): migrate plugin session-start harness
* fix(agent-core-v2): preserve reminder boundary ordering
* refactor(agent-core-v2): narrow reminder and swarm helper exposure
- drop the swarmInjection re-export from the package index; SwarmInjection
stays a domain-internal collaborator like permissionMode/plan injections
- move INTERRUPTION_REMINDER text back to a private constant in the service;
only the variant stays in the Ops module
- make reminderQueue.enqueue return void; no caller consumed the entry id
* chore(agent-core-v2): keep comments in module headers
* refactor(agent-core-v2): track reminder state via injection disclosure
- derive swarm active/inactive state from ctx.lastDisclosure instead of
byte-matching rendered markdown, with variant-only fallback for legacy
swarm_mode/swarm_mode_exit journal entries
- record once_reminder disclosure (entry id) on queue-appended messages
and dedupe the crash window by the contiguous tail id set, covering
multi-entry drains
- move reminderQueue draining behind a sync onWillInject event so the
injector no longer depends on the queue domain
- centralize the system-reminder wrap format behind wrapSystemReminder /
systemReminderContent and use injector-provided positions in the plugin
session-start provider
- spell out the step-boundary fallback and sync-only contract of
registerAtTurnStart via shouldRunAtBoundary
* fix(agent-core-v2): isolate failing turn-start providers and warn once per missing sessionStart skill
* refactor(agent-core-v2): compute injection positions on read
Drop the per-provider positions cache from the context injector: the
registration scan, the context.spliced index arithmetic, and the
post-restore resync all existed only to mirror what the history already
records. Each provider call now derives its injected positions by
scanning context memory for its surviving injection messages, so silent
history edits (such as vacuous-step folds) can no longer desync a
cached index.
* refactor(agent-core-v2): formalize injector once-channels and raw message results
* refactor(agent-core-v2): declare dynamic tool schemas at injection boundaries
Move the dynamic-tool schema declaration out of toolSelect.load(): the
loaded names are recorded as pending and drained by a dedicated
toolSelectSchemas provider through the contextInjector boundary
scheduler, so the declaration message lands at a quiescent boundary
instead of mid-step inside a streaming tool exchange. The folded
history remains the loaded-tool ledger, so undo, compaction, and
resume still self-heal by re-folding.
* refactor(agent-core-v2): deliver AGENTS.md reminders through the reminder queue
The tool hook now only observes and enqueues a once-per-agent reminder
through the reminderQueue once-channel instead of prepending text to
the tool result: results stay verbatim for the truncation pipeline and
the reminder can never be truncated away with an oversized output. The
reminderQueue is resolved lazily through the instantiation service at
enqueue time, breaking the contextInjector -> loop -> llmRequester ->
profile -> agentsMdReminder constructor cycle.
* refactor(agent-core-v2): make injection disclosures opaque and domain-owned
contextMemory no longer declares the ContextInjectionDisclosure union:
InjectionOrigin.disclosure becomes an opaque unknown, and providers
bind their own payload type through register<D>, so lastDisclosure
arrives at the provider already typed by its own variant. The date,
swarm_mode, and once_reminder payload shapes move into the dateChange,
swarm, and reminderQueue domains respectively; reminderQueue keeps a
runtime guard for its cross-message tail scan, the only place that
reads disclosures it did not write. Persisted origin shapes are
byte-identical, so existing journals replay unchanged.
* fix(agent-core-v2): isolate failing step context providers
A step or compaction boundary provider that threw or rejected made the
injector's inject() promise reject, which propagated through the
onWillBeginStep hook chain and failed the whole turn, and starved every
provider registered after it. Log and skip the bad provider instead,
matching the turn-start path's existing isolation.
* refactor(agent-core-v2): derive injector isNewTurn per injection boundary
Replace the shared read-and-clear isNewTurn flag (set by turn.started and
injectAfterCompaction, consumed by the first inject()) with values each
trigger supplies from an authoritative source: the loop marks a turn's
first step via BeforeStepContext.firstStepOfTurn (standalone runs never
count), and the compaction follow-up passes true explicitly, so
interleaved triggers can no longer consume or steal the marker.
A compaction follow-up that lands inside a step hook chain (the
auto-compaction path) doubles as that step's new-turn delivery: the
enclosing step then injects with isNewTurn false, so the upcoming request
receives one new-turn injection, not two.
* refactor(agent-core-v2): unify disclosure placement and injector param naming
* fix(agent-core-v2): keep pending tool schemas across compaction splices
A load announced by select_tools sits in pendingLoaded until the next
injection boundary declares it. A compaction fold in that window
publishes a replacement splice, and the splice-time reconciliation
dropped the pending entries before the post-compaction inject could
declare them — the model was told "Loaded: X" yet X never became
available. Drop pending entries only on removal splices (undo/clear,
which carry no replacement messages); compaction's replacement splice
keeps them so the declaration lands at the post-compaction boundary.
* fix(agent-core-v2): consume the plugin session-start refresh after a successful render
reconcileSessionStartReminder cleared the refresh-pending flag before
awaiting the render, so a throwing render (skipped by the injector's
provider isolation) lost the forced refresh until the next catalog
change. Consume the flag only after the render resolves, and move the
warn-once rationale into the module header per the comment convention.
* refactor(agent-core-v2): remove the generic reminder queue
* chore(agent-core-v2): drop the stale reminder-queue mention in systemReminder
* test(node-sdk): align side-question fork parity with event-point reminders
* chore(agent-core-v2): address reminder review standards
* docs(agent-core-v2): condense the model-facing reminders section
* refactor(agent-core-v2): write all system reminders through wrapSystemReminder
* fix(agent-core-v2): preserve reminder lifecycle invariants
* refactor(agent-core-v2): reconcile context injections at the step head
Unify the injector's delivery timings into one point on the
onWillBeginStep chain, before the step's request is built:
- providers run before every request instead of after every step, so
reminders are visible from the first response of a turn
- a compaction splice re-arms the new-turn flag via context.spliced;
when compaction runs inside the hook chain (full-compaction's
beforeStep), a follow-up inject at the chain tail keeps the first
post-compaction request covered
- registerAtTurnStart and injectAfterCompaction are removed;
reconcileWhenIdle stays as the v1-parity surface for SDK-driven
triggers (swarm toggle, plugin reload)
* refactor(agent-core-v2): clarify the injector's step-hook handler
Name the handler reconcileAroundStep, rename the rearm flag to
compactionRearmPending with a single takeCompactionRearm() consumer,
and extract isCompactionSplice. Consuming the flag into a local before
computing isNewTurn also avoids hiding the side effect inside a ||
short-circuit.
* 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
The decorator-registry fallback resolved every decorator name, including
kernel tokens like instantiationService — a call to
instantiationService/dispose would tear down the root container. Record
Feature.contributeService tokens in a contributed-service table and fall
back to that table only, so runtime-contributed services stay callable
while unregistered kernel tokens remain unreachable.
@ -33,7 +33,7 @@ End-to-end procedures that span the stages. Reach for these before reading the s
## Stages
## Stages
- [Stage 1 — Orient](orient.md): the DI black box (identity / dependencies / lifetime), the four `LifecycleScope` tiers and visibility, and the file-header comment convention. Read before touching business code.
- [Stage 1 — Orient](orient.md): the DI black box (identity / dependencies / lifetime), the four `LifecycleScope` tiers and visibility, and the no-comment convention. Read before touching business code.
- [Stage 2 — Design a service](design.md): pick a scope, split a domain across scopes, choose a calling style (direct call vs event vs hook), and direct dependencies. Decide *where things live and who knows whom* before coding.
- [Stage 2 — Design a service](design.md): pick a scope, split a domain across scopes, choose a calling style (direct call vs event vs hook), and direct dependencies. Decide *where things live and who knows whom* before coding.
- Topic: [Domain boundaries vs Scope](domain-boundaries.md) — keep `session` / `agent` / `turn` from becoming god objects; data-ownership test and their split conclusions.
- Topic: [Domain boundaries vs Scope](domain-boundaries.md) — keep `session` / `agent` / `turn` from becoming god objects; data-ownership test and their split conclusions.
- Topic: [Persistence layering](persistence.md) — the three-layer `Store → Storage → backend` model, naming Stores by access pattern, and which layer business code should depend on.
- Topic: [Persistence layering](persistence.md) — the three-layer `Store → Storage → backend` model, naming Stores by access pattern, and which layer business code should depend on.
@ -101,7 +101,7 @@ pass `ConfigTarget.Memory` for a per-run override that is never written to disk.
- `src/kosong/model/thinking.ts` (owner domain, not `config`) — the `resolveThinkingEffort` helper and the authoritative `ThinkingConfig` type (the `thinking` section itself registers from `src/app/kosongConfig/configSection.ts`).
- `src/kosong/model/thinking.ts` (owner domain, not `config`) — the `resolveThinkingEffort` helper and the authoritative `ThinkingConfig` type (the `thinking` section itself registers from `src/app/kosongConfig/configSection.ts`).
A domain that owns a section keeps the schema in its own `configSection.ts` (e.g. `src/app/flag/flag.ts` for `experimental`, `src/agent/loop/configSection.ts` for `loopControl`). Exception: kosong-owned sections (`providers`, `models`, `thinking`) — kosong is a pure, persistence-free abstraction layer that defines only the types (`src/kosong/{provider,model}`); the section constants, the zod schemas (re-derived from those types and compile-time pinned via `AssertExact<Equal<z.infer<typeof Schema>, Type>>`, see `_base/utils/typeEquality.ts`), the registrations, env bindings, and TOML transforms all live in the persistence wrapper `src/app/kosongConfig/configSection.ts`. (`modelCatalog`and `secondaryModel` have no kosong-side type at all — their sections are fully self-contained in `app/kosongConfig`, types derived from the schemas.) A cross-section env overlay (e.g. the `KIMI_MODEL_*` synthesis) lives in the wrapper too (`src/app/kosongConfig/envOverlay.ts`; the `[secondary_model]` derived-entry synthesis in `secondaryModelOverlay.ts`) and is registered via module-level `registerConfigOverlay`. The two-way sync between config sections and kosong's in-memory registries is owned by `IKosongConfigService` (`src/app/kosongConfig/kosongConfigService.ts`).
A domain that owns a section keeps the schema in its own `configSection.ts` (e.g. `src/app/flag/flag.ts` for `experimental`, `src/agent/loop/configSection.ts` for `loopControl`). Exception: kosong-owned sections (`providers`, `models`, `thinking`) — kosong is a pure, persistence-free abstraction layer that defines only the types (`src/kosong/{provider,model}`); the section constants, the zod schemas (re-derived from those types and compile-time pinned via `AssertExact<Equal<z.infer<typeof Schema>, Type>>`, see `_base/utils/typeEquality.ts`), the registrations, env bindings, and TOML transforms all live in the persistence wrapper `src/app/kosongConfig/configSection.ts`. (`modelCatalog`has no kosong-side type at all — its section is fully self-contained in `app/kosongConfig`, types derived from the schema.) A cross-section env overlay (e.g. the `KIMI_MODEL_*` synthesis in `src/app/kosongConfig/envOverlay.ts`) lives in the wrapper too and is registered via module-level `registerConfigOverlay`. The session subagent domain owns two sections in `src/session/subagent/configSection.ts`: `[subagent]` (`timeout_ms` on disk) and `[secondary_model]` (`default_model` plus the `[secondary_model.models]` pool, with a lone legacy v1 `model` key honored as a fallback default below `default_model`); neither carries a cross-section overlay. Cross-field pool validation (default present / in-pool / every key resolvable) runs at session creation in `subagentModelsValidationService.ts`, not in the schema. The two-way sync between config sections and kosong's in-memory registries is owned by `IKosongConfigService` (`src/app/kosongConfig/kosongConfigService.ts`).
@ -45,7 +45,7 @@ A Service method is directly exposable iff **all** hold:
3. Errors are `KimiError` (coded).
3. Errors are `KimiError` (coded).
4. It is a command/query, not a factory, stream, byte-store, or sink.
4. It is a command/query, not a factory, stream, byte-store, or sink.
If any fail → wrap in a **facade** (a Service that takes ids, returns data, throws `KimiError`) and expose the facade. The repo already ships a wire-shaped facade in `rpc/core-api.ts` (`CoreAPI` / `SessionAPI` / `AgentAPI`) behind `IAgentRPCService` / `ISessionRPCService` — prefer building the HTTP edge on top of it rather than re-deriving a new one.
If any fail → add a wire-safe orchestration method to the owning domain Service (e.g. `IAgentPromptService.submit` settles `{turn_id}` instead of returning the live `PromptHandle`) or compose several domain Services at the edge — kap-server's `routes/prompts.ts` is the reference for edge-side composition.
@ -66,45 +66,12 @@ There is no domain-layer numbering — a domain may import any other domain, gui
- v2 never imports v1 (`@moonshot-ai/agent-core` or any subpath).
- v2 never imports v1 (`@moonshot-ai/agent-core` or any subpath).
- The kosong subtree (`src/kosong/{contract,protocol,provider,model}`) keeps its strict internal order (`contract ← protocol ← provider/model`), purity bans (no SDKs in `contract`/`protocol`), and the `provider/bases` registration boundary.
- The kosong subtree (`src/kosong/{contract,protocol,provider,model}`) keeps its strict internal order (`contract ← protocol ← provider/model`), purity bans (no SDKs in `contract`/`protocol`), and the `provider/bases` registration boundary.
## File-header comment convention
## Comment convention
`packages/agent-core-v2/AGENTS.md` mandates a header-only comment style:
`packages/agent-core-v2/AGENTS.md` bans comments entirely: no file headers, no section banners, no statement-level narration, no JSDoc (not even on exported symbols) — the code is the source of truth. The only exception is a load-bearing lint-suppression directive (`oxlint-disable` / `eslint-disable`) for a deliberate pattern; other tooling directives (`@ts-expect-error`, …) are banned: fix the underlying lint/type problem instead, and put negative type-safety cases in compiler-asserted fixtures. Scope is carried by the filename: `workspace*.ts` = Workspace, `session*.ts` = Session, `agent*.ts` = Agent, no prefix = App (see service-authoring.md).
- **Header only.** Comments live solely in the top-of-file `/** */` block — never beside functions, methods, or statements. The code is the source of truth for *how*; the header states *what the module exposes and the responsibility it owns*.
- **Identity line first.** Start with `` `<domain>` domain — <one-line role>. `` Keep an existing `(cross-cutting)` label as-is. Write the role as a responsibility ("drives the turn lifecycle"), not a symbol list.
- **Scope is in the filename.**`workspace*.ts` = Workspace, `session*.ts` = Session, `agent*.ts` = Agent, no prefix = App (see service-authoring.md). State the same scope in the header so the two never drift.
- **Interface files** (`<name>.ts`) state the public contract + scope: which `IXxx` they define and what it is for.
- **Impl files** (`<name>Service.ts`) add collaborators + scope: list every imported cross-domain collaborator as a role ("persists records through `records`"); read scope from `registerScopedService(LifecycleScope.X, …)`.
- **Contribution files** (`<targetDomain>.ts` / `<what>.contrib.ts`) state what they register into the target domain (e.g. "registers the `log` config section into `config`").
- **Pure-function / `.types` / `.errors` files** state the responsibility only — they own no scoped state, so no scope line.
- **Name** the domain `<domain>Legacy` and the interface with the scope prefix, `I<Scope><Domain>LegacyService` (e.g. `prompt` / `IAgentPromptService`), per service-authoring.md.
- **Name** the domain `<domain>Legacy` and the interface with the scope prefix, `I<Scope><Domain>LegacyService` (e.g. `prompt` / `IAgentPromptService`), per service-authoring.md.
- **Header comment** must say it is an `edge adapter` and name both the v1 contract it implements and the native v2 Service it leaves untouched (see `prompt.ts`).
- **Role is carried by the name** — `<domain>Legacy` marks it as an `edge adapter`; the v1 contract it implements and the native v2 Service it leaves untouched stay evident from its delegation targets (see `prompt.ts`).
- **Scope** = the lifetime of the *legacy* state it holds (the `prompt` queue is per-agent → `LifecycleScope.Agent`). Apply [orient.md](orient.md) / [design.md](design.md) normally — a LegacyService is not exempt from scope rules.
- **Scope** = the lifetime of the *legacy* state it holds (the `prompt` queue is per-agent → `LifecycleScope.Agent`). Apply [orient.md](orient.md) / [design.md](design.md) normally — a LegacyService is not exempt from scope rules.
- **Delegate, do not duplicate** business logic. The LegacyService translates the v1 contract into native-Service calls and translates results back; the real work stays in the native Service.
- **Delegate, do not duplicate** business logic. The LegacyService translates the v1 contract into native-Service calls and translates results back; the real work stays in the native Service.
- **Contract types come from the v1 wire schema homes** (the owning v2 domain contract or `kap-server/src/protocol`), so the interface cannot drift from the wire shape.
- **Contract types come from the v1 wire schema homes** (the owning v2 domain contract or `kap-server/src/protocol`), so the interface cannot drift from the wire shape.
**For `/api/v2` (native):** add a `resource:action` entry to `actionMap` ([edge-exposure.md](edge-exposure.md) §3). If the method fails the direct-exposure rules (returns a handle / stream / bytes, takes a live object), wrap it in a wire-shaped facade first (`IAgentRPCService` / `ISessionRPCService`) and map to the facade — as `prompts:*` does via `IAgentRPCService`.
**For `/api/v2` (native):** add a `resource:action` entry to `actionMap` ([edge-exposure.md](edge-exposure.md) §3). If the method fails the direct-exposure rules (returns a handle / stream / bytes, takes a live object), add a wire-safe orchestration method to the owning domain Service first — as `prompts:submit` maps to `IAgentPromptService.submit`, which settles `{turn_id}` engine-side instead of returning the live `PromptHandle`.
### 5. Map errors
### 5. Map errors
@ -218,7 +218,7 @@ This is the reference alignment (commits `feat(server-v2): port v1 /sessions/:si
**The split.**
**The split.**
- `/api/v2` keeps the native shape — `prompts:submit` / `steer` / `undo` / `clear` / `cancel` map to `IAgentRPCService` (a wire facade over the v2 turn driver) in `actionMap`. The native `IAgentPromptService` is untouched.
- `/api/v2` keeps the native shape — `prompts:submit` / `steer` / `undo` / `clear` / `cancel` map to the domain Services (`IAgentPromptService.submit` / `submitSteer`, `IAgentConversationUndoService.undo`, `IAgentLoopService.cancelFromUser`) in `actionMap`.
- `/api/v1` gets an `AgentPromptLegacyService` (`prompt/`, `LifecycleScope.Agent`) that re-implements the v1 scheduler — queue, `prompt_id`, steer/abort, auto-start-next — **on top of** the native `IAgentPromptService`. The `/api/v1` routes consume the LegacyService.
- `/api/v1` gets an `AgentPromptLegacyService` (`prompt/`, `LifecycleScope.Agent`) that re-implements the v1 scheduler — queue, `prompt_id`, steer/abort, auto-start-next — **on top of** the native `IAgentPromptService`. The `/api/v1` routes consume the LegacyService.
**The schema.** Both surfaces import `promptSubmissionSchema` / `promptSubmitResultSchema` / `promptListResponseSchema` / `promptSteerRequestSchema` / `promptSteerResultSchema` / `promptAbortResponseSchema` from the shared v1 wire schemas (see `packages/kap-server/src/protocol`). The `/api/v1` and `/api/v2` routes are therefore compatible with released clients by construction; the LegacyService projects v2 turn results back into those protocol shapes.
**The schema.** Both surfaces import `promptSubmissionSchema` / `promptSubmitResultSchema` / `promptListResponseSchema` / `promptSteerRequestSchema` / `promptSteerResultSchema` / `promptAbortResponseSchema` from the shared v1 wire schemas (see `packages/kap-server/src/protocol`). The `/api/v1` and `/api/v2` routes are therefore compatible with released clients by construction; the LegacyService projects v2 turn results back into those protocol shapes.
@ -236,7 +236,7 @@ Before submitting a server-align change:
- [ ] Request and response schemas come from their owning home (the `agent-core-v2` domain contract or `packages/kap-server/src/protocol`); no inline re-declaration in server-v2.
- [ ] Request and response schemas come from their owning home (the `agent-core-v2` domain contract or `packages/kap-server/src/protocol`); no inline re-declaration in server-v2.
- [ ] Existing schema fields are unchanged in name, type, and semantics; only optional fields added (if any).
- [ ] Existing schema fields are unchanged in name, type, and semantics; only optional fields added (if any).
- [ ] Native v2 Service left clean; v1-only behavior isolated in a `<domain>Legacy` / `I<Domain>LegacyService` edge adapter when the semantics diverge.
- [ ] Native v2 Service left clean; v1-only behavior isolated in a `<domain>Legacy` / `I<Domain>LegacyService` edge adapter when the semantics diverge.
- [ ] LegacyService registered with the correct `LifecycleScope` and a header comment naming it an edge adapter + the native Service it preserves.
- [ ] LegacyService registered with the correct `LifecycleScope` and named as the `<domain>Legacy` edge adapter preserving the native Service.
- [ ] Domain error codes registered in `agent-core-v2`; wire codes registered in `packages/kap-server/src/protocol`; route maps them in `sendMappedError`, matching v1's status codes and idempotent envelopes.
- [ ] Domain error codes registered in `agent-core-v2`; wire codes registered in `packages/kap-server/src/protocol`; route maps them in `sendMappedError`, matching v1's status codes and idempotent envelopes.
- [ ] Route resolves the scope from the URL by `accessor.get(IX)`; no cached scope; finishes before disposal.
- [ ] Route resolves the scope from the URL by `accessor.get(IX)`; no cached scope; finishes before disposal.
- [ ] Tests assert the wire envelope + protocol shape; wire-shape guards added/updated where the route mirrors v1.
- [ ] Tests assert the wire envelope + protocol shape; wire-shape guards added/updated where the route mirrors v1.
@ -17,7 +17,7 @@ One folder per domain, **camelCase**: `session/`, `sessionActivity/`, `contextMe
```
```
- **Strictly one service per file.** An interface file holds exactly one injectable interface and exactly one `createDecorator(...)`; an impl file holds exactly one service implementation class and exactly one `registerScopedService(...)`. No exceptions for "tightly-coupled" groups: even same-scope collaborators each get their own `<name>.ts` + `<name>Service.ts` pair.
- **Strictly one service per file.** An interface file holds exactly one injectable interface and exactly one `createDecorator(...)`; an impl file holds exactly one service implementation class and exactly one `registerScopedService(...)`. No exceptions for "tightly-coupled" groups: even same-scope collaborators each get their own `<name>.ts` + `<name>Service.ts` pair.
- **Scope is in the filename.**`workspace*.ts` = Workspace, `session*.ts` = Session, `agent*.ts` = Agent, no scope prefix = App (see [Naming](#naming)). The header comment restates the same scope.
- **Scope is in the filename.**`workspace*.ts` = Workspace, `session*.ts` = Session, `agent*.ts` = Agent, no scope prefix = App (see [Naming](#naming)).
- A domain therefore has as many impl files as it has services (e.g. `logService.ts` for the App `ILogService`, `sessionLogService.ts` for the Session `ISessionLogService`). See [Multi-Service domains](#multi-service-domains).
- A domain therefore has as many impl files as it has services (e.g. `logService.ts` for the App `ILogService`, `sessionLogService.ts` for the Session `ISessionLogService`). See [Multi-Service domains](#multi-service-domains).
The package entry `src/index.ts` imports and `export *`s every domain's leaf files precisely (one line per leaf), so importing the package still runs every `registerScopedService(...)` side effect — exactly as the old per-domain barrels did.
The package entry `src/index.ts` imports and `export *`s every domain's leaf files precisely (one line per leaf), so importing the package still runs every `registerScopedService(...)` side effect — exactly as the old per-domain barrels did.
@ -51,7 +51,7 @@ File names derive from the interface / class names so that scope and role are vi
Acronym-aware lowerCamelCase lowercases a leading acronym as a group: `ILLMRequester` → `llmRequester.ts`, `IWSGateway` → `wsGateway.ts`, `IOAuthToolkit` → `oauthToolkit.ts`, `IAgentRPCService` → `agentRpcService.ts`.
Acronym-aware lowerCamelCase lowercases a leading acronym as a group: `ILLMRequester` → `llmRequester.ts`, `IWSGateway` → `wsGateway.ts`, `IOAuthToolkit` → `oauthToolkit.ts`, `IMcpServerService` → `mcpServerService.ts`.
Because the impl class always ends in `Service` and the interface file never does, the two files of one service never collide — even for `Store` / `Registry` / `Resolver` interfaces (`IAppendLogStore` → `appendLogStore.ts` + `appendLogStoreService.ts`).
Because the impl class always ends in `Service` and the interface file never does, the two files of one service never collide — even for `Store` / `Registry` / `Resolver` interfaces (`IAppendLogStore` → `appendLogStore.ts` + `appendLogStoreService.ts`).
@ -293,13 +293,11 @@ Importing the package therefore fires every `register*` side effect, exactly as
- Load the impl file too — its top-level `registerScopedService(...)` only runs when the module is imported.
- Load the impl file too — its top-level `registerScopedService(...)` only runs when the module is imported.
- `export *` helper modules only if they are part of the domain's public surface.
- `export *` helper modules only if they are part of the domain's public surface.
- Each leaf's file-header comment still names the domain, scope, and (for impls) the `register*` binding it owns.
## Comments
## Comments
- **File-header comment is mandatory** and the only place comments live (orient.md). State the identity line, the role, collaborators (impls), and scope.
- **No comments** (orient.md): no file headers, no statement-level narration, no JSDoc — not on exported symbols either; the only exception is a load-bearing `oxlint-disable` / `eslint-disable` directive.
- **Methods and fields carry no comments by default.** Well-named identifiers and types say *what*; the code is the source of truth for *how*.
- **Methods and fields carry no comments.** Well-named identifiers and types say *what*; the code is the source of truth for *how*.
- Write an inline comment only when the *why* is non-obvious (a hidden constraint, a subtle invariant, a workaround). One short line.
- For unimplemented stubs, throw `NotImplementedError('feature')` rather than `throw new Error('TODO: …')` (errors.md).
- For unimplemented stubs, throw `NotImplementedError('feature')` rather than `throw new Error('TODO: …')` (errors.md).
## Complete minimal example
## Complete minimal example
@ -351,4 +349,4 @@ import './greet/greetService';
- Never `new` a `@IService`-carrying Service — except inside an explicit factory method, which is not a DI request.
- Never `new` a `@IService`-carrying Service — except inside an explicit factory method, which is not a DI request.
- Events: typed per-Service event → `Event<T>`/`Emitter` from `'#/_base/event'`; cross-domain broadcast → `IEventService` from `'#/event'`.
- Events: typed per-Service event → `Event<T>`/`Emitter` from `'#/_base/event'`; cross-domain broadcast → `IEventService` from `'#/event'`.
- `src/index.ts` must import/export every leaf file (including the impl) so each `register*` side effect runs.
- `src/index.ts` must import/export every leaf file (including the impl) so each `register*` side effect runs.
- File-header comment only; methods/fields carry no comments by default; stubs throw `NotImplementedError`.
- No comments by default (orient.md); stubs throw `NotImplementedError`.
@ -21,7 +21,7 @@ Walk the stages you touched and confirm:
- **Design** — scope follows state identity; no `Map<sessionId, …>` at `App`; dependency arrows do not make a foundational layer know an upstream one; no cycle was routed around.
- **Design** — scope follows state identity; no `Map<sessionId, …>` at `App`; dependency arrows do not make a foundational layer know an upstream one; no cycle was routed around.
- **Implement** — no `new` on `@IService`-carrying classes; `@IX` on constructor params only (service params after static params); interface + impl carry `_serviceBrand`; decorator names unique; coded errors only; flags for unreleased behavior.
- **Implement** — no `new` on `@IService`-carrying classes; `@IX` on constructor params only (service params after static params); interface + impl carry `_serviceBrand`; decorator names unique; coded errors only; flags for unreleased behavior.
- **Test** — SUT resolved by interface; stubs under `test/`; scope tests re-register after `_clearScopedRegistryForTests()`; teardown through one `DisposableStore`.
- **Test** — SUT resolved by interface; stubs under `test/`; scope tests re-register after `_clearScopedRegistryForTests()`; teardown through one `DisposableStore`.
- **Files** — header comments describe role + scope only; registration runs from the impl file's top level; the new domain is exported from `src/index.ts`.
- **Files** — no comments at all (no JSDoc either; only load-bearing `oxlint-disable` / `eslint-disable` survive); registration runs from the impl file's top level; the new domain is exported from `src/index.ts`.
Then re-read the [global red lines](SKILL.md#global-red-lines) once — they catch most cross-stage mistakes in a single scan.
Then re-read the [global red lines](SKILL.md#global-red-lines) once — they catch most cross-stage mistakes in a single scan.
description: Use when generating changesets in the kimi-code repository, including package bump selection, internal package and CLI bundle handling, bump levels, major confirmation, and English changelog wording.
description: Use when generating changesets in the kimi-code repository — deciding whether to write one, which package to list, the bump level, the wording, and the confirmation workflow.
---
---
# Generate Changesets
# Generate Changesets
`kimi-code` uses changesets to manage versions and changelogs. The current user-facing published package is:
The only user-facing published package is the CLI: `@moonshot-ai/kimi-code`. All other `@moonshot-ai/*` packages (sdk, agent-core, kosong, kaos, oauth, telemetry, and so on) are internal.
- `@moonshot-ai/kimi-code`: the CLI
## 1. Whether to Write
All other `@moonshot-ai/*` packages are treated as internal packages, including `@moonshot-ai/kimi-code-sdk`, `agent-core`, `kosong`, `kaos`, `kimi-code-oauth`, `kimi-telemetry`, and `migration-legacy`.
Rule of thumb: **if users cannot perceive the change, write no changeset.** A changeset is a user-facing changelog entry, not a shipping gate — internal changes merged to main ship with the next release anyway, so skipping loses nothing.
`@moonshot-ai/pi-tui` is a special internal package: it is a private fork (`private: true`) that is never published, but it keeps its own changelog through changesets. It is an exception to Core Rule 4 — see the dedicated section below.
Do not write:
- Docs-only or tests-only changes that never enter the shipped artifact.
- Changes internal to core/server packages — architecture, protocols, refactors, config/journal/wire mechanics — unless they fix a bug users care about.
- When you are unsure whether users can perceive a change, ask first.
Only the CLI changelog gets a curated, user-facing presentation (the docs-site changelog sync). The SDK and other internal package changelogs are raw changesets output kept for version history — nobody curates them, so write those entries honestly and technically; their wording does not need to suit end users.
Do write: user-perceivable new features or behavior changes, and internal-package changes that fix a user-useful bug or change CLI output/behavior (list `@moonshot-ai/kimi-code` for those).
## Core Rules
## 2. What to Write
1. **Inspect the actual changes first.** Use `git status` / `git diff --name-only` to identify which packages were actually changed.
Create a short kebab-case file under `.changeset/`:
2. **List packages that changesets can release.** If a changed package is ignored in `.changeset/config.json`, do not put that ignored package in frontmatter together with a non-ignored package; changesets rejects mixed ignored/non-ignored frontmatter.
3. **Map ignored internal changes to the affected released package.** If an ignored internal package changes CLI output or behavior, list `@moonshot-ai/kimi-code` and describe the actual user-visible or release-artifact change in the changelog text.
4. **Internal package source changes that enter the CLI bundle must manually list the CLI — when they get a changeset at all.**`@moonshot-ai/kimi-code` inline-bundles `@moonshot-ai/*` source, but those internal packages are devDependencies from the CLI's perspective, so changesets will not automatically propagate bumps. If a change enters the CLI output and is user-perceivable, list `@moonshot-ai/kimi-code`. See rule 6 for when to skip the changeset entirely.
5. **Docs-only and tests-only changes usually do not need a changeset.** README, internal docs, and `test/` changes that do not enter package output do not trigger a CLI bump.
6. **Skip changes users cannot perceive — write no changeset at all.** The CLI changelog is user-facing; a changeset is a changelog entry, not a shipping gate. Internal changes merged to `main` still ship in the next release triggered by any user-facing changeset, so skipping the changeset loses nothing. Do not write changesets for:
- `agent-core-v2` internal architecture: new services, refactors, config-persistence or journal/wire mechanisms.
- `kap-server` WebSocket / REST protocol changes consumed only by the bundled web UI, kimi-inspect, or other dev tooling (new endpoints, subscribe protocols, stream baselines).
- Behavior that only takes effect on the experimental engine (e.g. experimental `kimi -p`), unless it exposes documented user configuration such as a `config.toml` section or env vars that also work on a shipped surface (TUI or `kimi web`).
- When unsure whether users can perceive a change, ask before writing.
7. `@moonshot-ai/vis` / `vis-server` / `vis-web` are ignored by changesets and should not be handled. `@moonshot-ai/kimi-inspect` (a private dev app that never ships) is likewise ignored and must never appear in a changeset frontmatter.
## Workflow
1. List the changed packages and check whether each one is ignored by `.changeset/config.json`.
2. Decide whether the change is user-perceivable (Core Rule 6); if not, stop — no changeset.
3. Choose a bump level for each package.
4. If an ignored internal package change enters the CLI bundle, put `@moonshot-ai/kimi-code` in frontmatter instead of mixing the ignored package into the same changeset.
5. Create a short kebab-case file under `.changeset/`.
6. Split unrelated changes into separate changesets; keep one logical change in one file.
Before a release, review the accumulated `.changeset/` entries against Core Rule 6 and prune non-user-facing ones; the release PR regenerates from `.changeset/` on `main`, so deleting a changeset removes its changelog entry without affecting the shipped code.
Format:
```markdown
---
"<packageA>": patch
"<packageB>": minor
---
<Englishchangelogentry>
```
## Bump Levels
| Level | When to use |
|---|---|
| `patch` | Bug fixes; build/package fixes; internal refactors that do not change behavior; wording tweaks; small dependency upgrades; small improvements to existing features with limited user-facing impact (e.g. a new keyboard shortcut, a flag alias, a minor UX tweak) |
| `minor` | A substantial new user-facing feature, such as a new slash command, a new built-in tool, or a new mode |
| `major` | Breaking changes: incompatible config changes, renamed or removed commands/arguments, behavior semantics changes, and similar |
When in doubt between `patch` and `minor`: if the change improves an existing feature and the user-facing impact is small, choose `patch` even when the change is technically "new". Reserve `minor` for a substantial new capability that introduces something users could not do before.
New configuration surface is not automatically `minor`. Additions to an existing feature's configuration — env var overlays, config-file fallbacks, global defaults under per-item settings — are `patch`. Examples: a global default MCP timeout when per-server timeouts already exist; env-based credentials for a service already configurable in `config.toml`.
### Major Rule
Never write `major` on your own.
If you believe a change qualifies as major, stop first, explain why, and ask the user for confirmation. Only write `major` after the user explicitly agrees. If the user does not reply, replies ambiguously, or disagrees, fall back to `minor`; if `minor` is also unclear, fall back to `patch`.
## Wording Rules
- Changelog entries **must be written in English**.
- **Keep the whole entry concise.** Aim for one short sentence that states what was done; at most a short sentence plus a one-line usage hint. Do not write a paragraph, do not pile on technical detail, and do not enumerate every sub-change.
- **For new user-facing features, append a brief usage hint** so users know how to try it. Keep it to a single short line — a command name, a subcommand, a flag, or a one-line "how to use". Do not explain design rationale or list edge cases. Skip the hint for bug fixes, internal changes, and refactors.
- Slash command: `Add the /foo slash command to list active sessions. Run /foo to see them.`
- CLI subcommand: `Add the kimi web subcommand to open the web UI. Run kimi web to launch it.`
- Flag: `Add a --bar flag to skip confirmation prompts. Pass --bar to skip.`
- Too long: `Add the /foo command to list active sessions. It accepts an optional --all flag to include background sessions, supports filtering by name with /foo <name>, and writes the result to the transcript...`
- User-facing CLI wording should only be used when CLI users can perceive the change.
- Internal changes that do not affect CLI users can still share a changeset with the CLI, but the wording must describe the real change honestly and must not present it as a user-facing feature.
- Do not mention file names, class names, function names, PR numbers, or commit hashes.
- Do not include real internal endpoints, key names, account names, or service names. If an example is needed, use neutral placeholders such as `example.com`, `example.test`, or `YOUR_API_KEY`.
- Avoid vague words such as `refactor`, `optimize`, and `improve`. Describe the actual change, or use more specific wording.
## When You Are Unsure About a Change
Generate the changeset from what the diff clearly shows. If part of a change is unclear and you cannot confidently describe what it does for users, do not guess or pad the entry with vague wording.
1. Finish the changeset for the parts that are clear.
2. Then ask the user once, in a short list: name the specific change(s) you do not understand, and ask whether you may dig into the repository (read related source, tests, or call sites) to describe it more accurately.
3. Only read more code after the user agrees. If the user says no or does not reply, keep the concise wording you already have and do not invent detail.
## Common Examples
An internal package fixes a bug visible to CLI users:
```markdown
```markdown
---
---
@ -104,103 +30,34 @@ An internal package fixes a bug visible to CLI users:
Fix occasional loss of tool call results in long conversations.
Fix occasional loss of tool call results in long conversations.
```
```
A new user-facing slash command (note the short usage hint):
Wording:
- One short, user-facing English sentence that states only what changed. Drop trailing clauses that explain the cause, the benefit, or the mechanism.
- New features: say plainly what it is plus one line on how to use it, e.g. `Add the /foo slash command to list active sessions. Run /foo to see them.`
- Experimental features: also state how to enable them (the flag, config key, or env var).
- No file, class, or function names, and no PR numbers. No vague words like refactor, optimize, or improve. No real internal identifiers — use neutral placeholders such as `example.com` or `YOUR_API_KEY`.
- Internal packages' own changelogs (such as the sdk) are not curated for end users — write those entries honestly and technically.
- One logical change per changeset; split unrelated changes into separate files.
```markdown
## 3. Bump Level
---
"@moonshot-ai/kimi-code": minor
---
Add the /foo slash command to list active sessions. Run /foo to see them.
- `patch`: bug fixes, small improvements, configuration additions to existing features — when in doubt, use this.
```
- `minor`: a real new capability users could not do before (a new slash command, a new subcommand, a new mode).
- `major`: **never write it.** If you think a change qualifies, stop and ask the user; without explicit approval fall back to `minor`, or to `patch` if `minor` is also unclear.
A new CLI subcommand:
## 4. Which Package
```markdown
- An internal change enters the CLI bundle and is user-perceivable → list `@moonshot-ai/kimi-code`.
---
- An internal change does not enter the CLI or is not user-perceivable → write nothing; if it is written, list only that internal package.
"@moonshot-ai/kimi-code": minor
- Never mix packages ignored in `.changeset/config.json` with non-ignored packages in one frontmatter.
---
- pi-tui exception: pi-tui-only changes list `@moonshot-ai/pi-tui`; if the same change is also visible to CLI users, write a separate CLI changeset (two files, never mixed).
- kimi-inspect and the vis packages never appear in a changeset.
Add the kimi web subcommand to open the web UI. Run kimi web to launch it.
## 5. Workflow
```
A new flag on an existing command:
1. Run `git status` / `git diff --name-only` to see which packages actually changed.
2. Apply section 1; if no changeset is needed, stop.
3. Pick the package and the bump, and write the one sentence.
4. **Show the changeset text to whoever requested the work and get their confirmation before committing.**
5. Do not guess at changes you do not understand: finish the parts that are clear, then list what is unclear and ask whether you may dig into the code.
```markdown
Before a release, review the accumulated `.changeset/` entries and delete the non-user-facing ones — the release PR regenerates from `.changeset/` on main, so deleting a file removes its changelog entry without touching shipped code.
---
"@moonshot-ai/kimi-code": patch
---
Add a --bar flag to skip confirmation prompts. Pass --bar to skip.
```
An internal package has an internal-only change, but it enters the CLI bundle:
```markdown
---
"@moonshot-ai/kimi-code": patch
---
Unify tool execution metadata handling.
```
Only SDK source changed, and the CLI does not use it:
```markdown
---
"@moonshot-ai/kimi-code-sdk": patch
---
Clarify session status typing for internal SDK callers.
```
## `@moonshot-ai/pi-tui` changes
`@moonshot-ai/pi-tui` is a vendored fork that lives in `packages/pi-tui`. It is `private: true` and is never published, but it is **not** ignored by changesets: changesets versions it and writes `packages/pi-tui/CHANGELOG.md` so the fork keeps its own history. Because it is bundled into the CLI like other internal packages, it is an exception to Core Rule 4 — do **not** list `@moonshot-ai/kimi-code` for a change that only touches pi-tui.
- Changes that only affect pi-tui (build, package, strict-mode cleanup, renderer fixes): list `@moonshot-ai/pi-tui` only. No CLI changeset.
- If the same change is also user-visible in the CLI (for example a terminal rendering fix that CLI users can see), add a **separate** changeset that lists `@moonshot-ai/kimi-code` with CLI-focused wording, in addition to the pi-tui changeset. Do not mix both packages in one frontmatter — the two changelogs need different wording.
pi-tui-only change:
```markdown
---
"@moonshot-ai/pi-tui": patch
---
Export the package manifest so the bundled binary can locate its native assets.
```
pi-tui change that is also visible in the CLI (two separate changesets):
```markdown
---
"@moonshot-ai/pi-tui": patch
---
Clamp the differential render to the visible viewport so scrolling up during streaming no longer jumps to the top.
```
```markdown
---
"@moonshot-ai/kimi-code": patch
---
Fix the transcript jumping to the top when scrolling up through history during streaming output.
```
## Red Flags
- You are about to write `major` without asking the user.
- You are writing a changeset for something users cannot perceive — `agent-core-v2` internals, `kap-server` WS/REST protocol plumbing, experimental-engine-only behavior. Skip the changeset instead (Core Rule 6).
- A new env var overlay or config fallback for an existing feature is bumped `minor` — configuration additions to existing features are `patch`.
- A new user-facing feature entry has no usage hint, or the hint runs to multiple lines and explains design rationale.
- You guessed wording for a change you do not understand instead of asking the user whether you may dig into the repo.
- Internal package source enters the CLI bundle, but `@moonshot-ai/kimi-code` is missing.
- A changeset frontmatter mixes ignored internal packages with non-ignored packages.
- `packages/node-sdk` was not changed, but `@moonshot-ai/kimi-code-sdk` was listed for "internal package sync".
- The changelog entry is in Chinese.
- The wording claims more than the diff actually did.
- The CLI wording mentions internal package names, class names, or PR numbers.
- The entry includes real internal identifiers instead of neutral placeholders.
- A change that only touches `@moonshot-ai/pi-tui` lists `@moonshot-ai/kimi-code` instead of `@moonshot-ai/pi-tui`, or mixes both packages in one frontmatter.
Add Remote Control as an experimental feature for accessing a local web session remotely. Enable it with `KIMI_CODE_EXPERIMENTAL_REMOTE_CONTROL=1`, then run `kimi rc`, `kimi web --remote-control`, or `/remote-control` to start it.
Fix ACP session regressions: Bash, Grep, and Glob failing when the editor does not support terminal command execution, session creation failing with stdio MCP servers, and reopening a closed session failing with an internal error.
web: Fix the slash-command and @-mention panels failing to open on mobile — both panels and the + menu are now grab-handle bottom sheets on small screens.
Add an optional `cwd` parameter to the global MCP management methods; `verify: false` on the global MCP authorization-status listing now returns a fully offline classification instead of behaving like an omitted `verify`.
Add an optional `fork` parameter to subagent and swarm tools that starts the subagent with a snapshot of the calling agent's conversation history; set `KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK=1` or `subagent_fork = true` under `[experimental]` in config.toml to enable it.
Add a dedicated `[swarm] timeout_ms` config option (or the `KIMI_CODE_SWARM_TIMEOUT_MS` env var) for AgentSwarm subagent timeouts, which no longer follow `[subagent] timeout_ms`.
Save oversized tool output within safety limits for later inspection, report omitted MCP content, and retain partial assistant responses when streams fail.
Add experimental tower mode for multi-agent orchestration; set `KIMI_CODE_EXPERIMENTAL_TOWER=1`, then run `/tower on` and `/tower <objective>` to start.
Please try to include as much information as possible.
Please try to include as much information as possible.
If you plan to submit a fix:link this issue in your PR. Small, reproducible bugs can go straight to a PR; for broader or uncertain fixes, wait for maintainer feedback first.
If you plan to submit a fix:check the Contribution box below and wait for a maintainer's `/approve` comment in this issue before opening a PR.
- type:input
- type:input
id:version
id:version
@ -65,3 +65,10 @@ body:
attributes:
attributes:
label:Additional information
label:Additional information
description:Is there anything else you think we should know?
description:Is there anything else you think we should know?
- type:checkboxes
id:willing-to-pr
attributes:
label:Contribution
options:
- label:I am willing to submit a PR for this bug fix myself (please wait for maintainer approval in this issue first)
1. Search existing issues for similar features. If you find one, 👍 it rather than opening a new one.
1. Search existing issues for similar features. If you find one, 👍 it rather than opening a new one.
2. The Kimi Code team will try to balance the varying needs of the community when prioritizing or rejecting new features. Please understand that not all features will be accepted.
2. The Kimi Code team will try to balance the varying needs of the community when prioritizing or rejecting new features. Please understand that not all features will be accepted.
3. Do not open a feature PR until maintainers have had a chance to respond here. PRs without prior discussion may be closed without review.
3. Do not open a feature PR. External feature PRs are not accepted — features are discussed and decided in this issue; if accepted, the team will implement it or explicitly invite you to contribute.
Please open an issue before sending a feature PR — PRs without prior discussion may be closed without review.
External PRs are accepted for approved bug fixes only: link an issue that a maintainer has approved (an `/approve` comment). External feature PRs are not accepted.
See https://github.com/MoonshotAI/kimi-code/blob/main/CONTRIBUTING.md for more.
See https://github.com/MoonshotAI/kimi-code/blob/main/CONTRIBUTING.md for more.
-->
-->
## Related Issue
## Related Issue
<!-- Link the issue this feature came from. If there is no issue, explain the problem in the next section instead. -->
<!-- Link the issue this change came from. External PRs must link an issue approved by a maintainer (an `/approve` comment) — PRs without one may be closed. -->
Resolve #(issue_number)
Resolve #(issue_number)
@ -22,7 +23,7 @@ Resolve #(issue_number)
## Checklist
## Checklist
- [ ] I have read the [CONTRIBUTING](https://github.com/MoonshotAI/kimi-code/blob/main/CONTRIBUTING.md) document.
- [ ] I have read the [CONTRIBUTING](https://github.com/MoonshotAI/kimi-code/blob/main/CONTRIBUTING.md) document.
- [ ] I have linked a related issue, or explained the problem above.
- [ ] I have linked a related issue (external PRs: the issue must have a maintainer's `/approve`).
- [ ] I have added tests that prove my feature works.
- [ ] I have added tests that prove my feature works.
- [ ] Ran `gen-changesets` skill, or this PR needs no changeset.
- [ ] Ran `gen-changesets` skill, or this PR needs no changeset.
- [ ] Ran `gen-docs` skill, or this PR needs no doc update.
- [ ] Ran `gen-docs` skill, or this PR needs no doc update.
@ -48,6 +48,7 @@ This is a TypeScript monorepo built for agent-assisted development. Keep the roo
## General Coding Rules
## General Coding Rules
- `packages/agent-core-v2`, `packages/kap-server`, and `packages/transcript` are comment-free zones: no comments of any kind — no line/block comments, no JSDoc (not even on exported symbols); the only exception is load-bearing lint-suppression directives (`oxlint-disable` / `eslint-disable`), while other tooling directives (`@ts-expect-error`, …) stay banned. Enforced by `scripts/check-no-comments.mjs` over `.ts`/`.tsx`/`.mts`/`.mjs` under `src/`/`test/`/`scripts/`, which runs as part of `pnpm lint`.
- For optional object properties, pass `undefined` directly instead of using conditional spread.
- For optional object properties, pass `undefined` directly instead of using conditional spread.
- YES: `{ user }`
- YES: `{ user }`
- NO: `{ ...(user ? { user } : undefined) }`
- NO: `{ ...(user ? { user } : undefined) }`
@ -82,6 +83,7 @@ This is a TypeScript monorepo built for agent-assisted development. Keep the roo
- When an AI agent opens or updates a PR, fill in `.github/pull_request_template.md` — link the related issue or explain the problem, then describe what changed. Do not leave placeholder text or submit a generic summary of the diff.
- When an AI agent opens or updates a PR, fill in `.github/pull_request_template.md` — link the related issue or explain the problem, then describe what changed. Do not leave placeholder text or submit a generic summary of the diff.
- Do not submit vague AI-generated PR text. The human author must understand the change well enough to explain the code, edge cases, and why the approach fits this repository.
- Do not submit vague AI-generated PR text. The human author must understand the change well enough to explain the code, edge cases, and why the approach fits this repository.
- After finishing a task and before submitting a PR, you must run the `gen-changesets` skill (see `.agents/skills/gen-changesets/SKILL.md`) and generate a changeset under `.changeset/` according to its rules.
- After finishing a task and before submitting a PR, you must run the `gen-changesets` skill (see `.agents/skills/gen-changesets/SKILL.md`) and generate a changeset under `.changeset/` according to its rules.
- Changesets must strictly follow the rules in `.agents/skills/gen-changesets/SKILL.md`: write one short user-facing sentence that states only what changed, and skip any change users cannot perceive.
- When generating a changeset, **never** decide on a `major` bump on your own — stop, explain, and get explicit user confirmation first; default to `minor`, fall back to `patch`. See `.agents/skills/gen-changesets/SKILL.md`.
- When generating a changeset, **never** decide on a `major` bump on your own — stop, explain, and get explicit user confirmation first; default to `minor`, fall back to `patch`. See `.agents/skills/gen-changesets/SKILL.md`.
- Prefer importing via `import ... from '#/...'`, which serves the same purpose as `import ... from '@/...'`.
- Prefer importing via `import ... from '#/...'`, which serves the same purpose as `import ... from '@/...'`.
- Do not commit throwaway scratch or exploratory files. Never stage:
- Do not commit throwaway scratch or exploratory files. Never stage:
Thanks for taking the time to contribute! This project moves quickly, and thoughtful contributions from the community are what keep it sharp. The guide below walks you through how we work so your PR has the best chance of landing smoothly.
Thanks for taking the time to contribute! This project moves quickly, and thoughtful contributions from the community are what keep it sharp. The guide below walks you through how we work so your PR has the best chance of landing smoothly.
## Before You Start
## Before You Start
@ -10,27 +12,25 @@ We hold AI-assisted contributions to the same standard as hand-written ones. **Y
We only merge PRs aligned with the roadmap. Drive-by refactors without context are unlikely to land.
We only merge PRs aligned with the roadmap. Drive-by refactors without context are unlikely to land.
**Discuss first** — open an issue before coding. PRs without prior discussion may be closed without review:
**External PRs are accepted for approved bug fixes only.** Open an issue first and wait for a maintainer to approve it with an `/approve` comment, then link that issue in your PR. PRs without an approved linked issue may be closed without review; once the issue is approved, ask a maintainer to reopen your PR.
- New features or user-visible behavior changes (regardless of size)
**Discuss first** — open an issue before coding:
- Bug fixes, including small or typo-level ones: open a bug issue and wait for a maintainer's `/approve` before opening the PR
- New features or user-visible behavior changes (regardless of size): external feature PRs are not accepted — features are discussed and decided in issues, and accepted features are implemented by the team or by explicit maintainer invitation
- Refactors or other changes larger than ~100 lines
- Refactors or other changes larger than ~100 lines
- Public API or compatibility changes
- Public API or compatibility changes
- Bug fixes where the cause or fix approach is still unclear
**Can open a PR directly** — link an existing issue when there is one:
- Clear, reproducible bug fixes with a focused diff
- Typos, documentation-only changes, and small CI/build fixes
- Small changes that clearly match an existing issue or maintainer request
## Project Layout
## Project Layout
This is a pnpm monorepo. The most relevant entry points are:
This is a pnpm monorepo. The most relevant entry points are:
For the full project map, see [AGENTS.md](AGENTS.md).
For the full project map, see [AGENTS.md](AGENTS.md).
@ -84,9 +84,7 @@ This repo uses [changesets](https://github.com/changesets/changesets) to manage
## Pull Requests
## Pull Requests
Use the [PR template](.github/pull_request_template.md) when opening a feature pull request.
Every PR opens with the [PR template](.github/pull_request_template.md). PR titles must follow [Conventional Commits](#commit-convention); CI runs `pnpm lint`, `pnpm typecheck`, and `pnpm test` on every PR. Update user-facing docs in `docs/` when behavior changes — use the `gen-docs` skill when working with coding agents.
PR titles must follow [Conventional Commits](#commit-convention); CI runs `pnpm lint`, `pnpm typecheck`, and `pnpm test` on every PR. Update user-facing docs in `docs/` when behavior changes — use the `gen-docs` skill when working with coding agents.
- [#2862](https://github.com/MoonshotAI/kimi-code/pull/2862) [`3d77620`](https://github.com/MoonshotAI/kimi-code/commit/3d7762003a4a35cbeb8571d471c6898a006152e6) Thanks [@liruifengv](https://github.com/liruifengv)! - Support two OAuth login methods — kimi.ai and kimi.com.
- [#3060](https://github.com/MoonshotAI/kimi-code/pull/3060) [`8440801`](https://github.com/MoonshotAI/kimi-code/commit/8440801de47ddae29224430048e1228b80cde370) Thanks [@chengluyu](https://github.com/chengluyu)! - Add the WaitFor tool: the agent can now wait for a background task to finish within the current turn instead of ending the turn and being re-invoked.
### Patch Changes
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Label inline subagent cards in the message stream with their foreground or background mode.
- [#3121](https://github.com/MoonshotAI/kimi-code/pull/3121) [`3899079`](https://github.com/MoonshotAI/kimi-code/commit/3899079a2c851bd0b3f1cbf1d3d2fd9026fc6abb) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix config.toml entries being lost when the file had a syntax error or was edited outside the app.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Add copy buttons next to the server version and server address in settings.
- [#3119](https://github.com/MoonshotAI/kimi-code/pull/3119) [`a34d02a`](https://github.com/MoonshotAI/kimi-code/commit/a34d02a64f9b1526ec84e161d8c377654b413624) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Add 13 data sources to the official Kimi Datasource plugin — Chinese government data (NDA/NBS) and standards (GB/HB/DB/TT), eight international organization datasets (WHO, FAO, UNSD, ECB, Eurostat, UNICEF, OECD, FRED), Xinhua Finance, and Caixin. Update the plugin from the Official tab in /plugins.
- [#3096](https://github.com/MoonshotAI/kimi-code/pull/3096) [`67fbcdf`](https://github.com/MoonshotAI/kimi-code/commit/67fbcdf1ba7dceeebb58875b3b7c81b4b30cf0de) Thanks [@sailist](https://github.com/sailist)! - Edit and Write now require reading an existing file before modifying it, and reject the write when the file changed on disk since it was last read.
- [#3101](https://github.com/MoonshotAI/kimi-code/pull/3101) [`d96b4a0`](https://github.com/MoonshotAI/kimi-code/commit/d96b4a0149f3ddf3d4910cc6eb87366dbb130ede) Thanks [@kimi-agent-bot](https://github.com/kimi-agent-bot)! - Stop retrying requests blocked by the provider content filter; the filter notice now shows immediately.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Keep empty workspace groups visible in the legacy sidebar after their last session is archived.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Hide button hover tooltips outside a menu while the menu is open.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Keep the model picker menu on the workspace home within the viewport.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix the workspace group title showing untranslated text in the search dialog.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix the settings dialog dropdown list being clipped by the scroll area, and lock the content behind it while the list is open.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Keep the slash command and @ mention panels on the workspace home within the viewport.
- [#3052](https://github.com/MoonshotAI/kimi-code/pull/3052) [`6595a69`](https://github.com/MoonshotAI/kimi-code/commit/6595a6989a68163e10a85c8edf1726b30d6d2c2b) Thanks [@RealKai42](https://github.com/RealKai42)! - Fix 422 errors from some OpenAI-compatible providers when a conversation includes tool calls.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Prevent text selection in the sidebar user menu and its plan usage submenu.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix slow session list loading when there are many workspaces.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Auto-open the browser authorization page after choosing a login region, redesign the authorization waiting page, and refresh the login state as soon as the window regains focus instead of waiting for the poll.
- [#3083](https://github.com/MoonshotAI/kimi-code/pull/3083) [`571bcc2`](https://github.com/MoonshotAI/kimi-code/commit/571bcc2f751f02a37b0475b074a1e859c7fc4368) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix the missing OAuth authenticate tool for remote MCP servers that require login.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Upgrade the @ mention menu: file and skill candidates are merged and ranked by match quality, file search is faster, with path-fragment matching and hit highlighting.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Round menu items concentric with their menu frames.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Add a Pin action to the chat header more-menu to pin the current session to the sidebar pinned section.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Allow dragging the divider between the pinned section and the session list to resize both areas, with fade hints at the edges when the pinned section scrolls.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Improve the prompt queue interaction, with per-row steer and send.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Add kimi.com and kimi.ai OAuth login entries, and switch update and help links to the site matching the current login.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Remove sessions archived from another client from the session list immediately, without a manual refresh.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Label the timestamp at the bottom of the session menu as last active and tighten that row's padding.
- [#3054](https://github.com/MoonshotAI/kimi-code/pull/3054) [`cfc3350`](https://github.com/MoonshotAI/kimi-code/commit/cfc335048378d3708666e11959c8d34507a1d659) Thanks [@Grapedge](https://github.com/Grapedge)! - Collapse long `!` shell command output instead of flooding the transcript. Press ctrl+o to expand or collapse it together with tool output.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Fix misaligned action buttons between the sidebar section headers and the session rows.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Remove the skill-activated card from skill activation messages.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Make skill-activation turns undoable so they can be withdrawn and resent.
- [#3012](https://github.com/MoonshotAI/kimi-code/pull/3012) [`ca87c58`](https://github.com/MoonshotAI/kimi-code/commit/ca87c58e6205ddf0638e5d737a5f8e939e2132b9) Thanks [@sailist](https://github.com/sailist)! - Sub-agents no longer spawn their own sub-agents by default; custom agent profiles can still allow it explicitly.
- [#3005](https://github.com/MoonshotAI/kimi-code/pull/3005) [`be8e017`](https://github.com/MoonshotAI/kimi-code/commit/be8e017597b83142282d7e6640076368bf244eae) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Fix background agent rows that could not be stopped right after they appeared, and stray rows left behind when an agent failed to start.
- [#3046](https://github.com/MoonshotAI/kimi-code/pull/3046) [`f13f379`](https://github.com/MoonshotAI/kimi-code/commit/f13f3790448f64448c76a415500041443ae754e6) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix the model being directed to unavailable tools when it encounters an image or binary file.
- [#3108](https://github.com/MoonshotAI/kimi-code/pull/3108) [`05f2ad5`](https://github.com/MoonshotAI/kimi-code/commit/05f2ad5ddad1addf10ead6f5274554ca10cde1f4) Thanks [@kimi-agent-bot](https://github.com/kimi-agent-bot)! - web: clearing a goal now removes it from the transcript view instead of leaving the stale goal displayed.
- [#3108](https://github.com/MoonshotAI/kimi-code/pull/3108) [`05f2ad5`](https://github.com/MoonshotAI/kimi-code/commit/05f2ad5ddad1addf10ead6f5274554ca10cde1f4) Thanks [@kimi-agent-bot](https://github.com/kimi-agent-bot)! - web: attachments sent with a prompt now appear in the live transcript immediately instead of only after a reload.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Tighten the row height and spacing of the account menu and its submenus to match the standard menu density.
- [#3135](https://github.com/MoonshotAI/kimi-code/pull/3135) [`2c5415f`](https://github.com/MoonshotAI/kimi-code/commit/2c5415f930db3edef3e79a4e88c4ee74af123600) Thanks [@liruifengv](https://github.com/liruifengv)! - web: Give WaitFor tool calls a dedicated quiet-line display showing completed tasks, wait timeouts, and how many tasks are still running.
## 0.37.2
### Patch Changes
- [#3061](https://github.com/MoonshotAI/kimi-code/pull/3061) [`5c661f4`](https://github.com/MoonshotAI/kimi-code/commit/5c661f4610f36481dbf2f9598aa63f49004e4980) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: the subagent detail panel now keeps the working process fully expanded and drops the end-of-turn timestamp footer.
- [#3061](https://github.com/MoonshotAI/kimi-code/pull/3061) [`5c661f4`](https://github.com/MoonshotAI/kimi-code/commit/5c661f4610f36481dbf2f9598aa63f49004e4980) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Settings gains a Lab tab with a multi-tab sidebar toggle (off by default); when enabled, the sidebar shows the Open / Done / Workspaces tabs.
## 0.37.1
### Patch Changes
- [#3053](https://github.com/MoonshotAI/kimi-code/pull/3053) [`95cede8`](https://github.com/MoonshotAI/kimi-code/commit/95cede82b4d3b6cb1845c66e87896ab2e5fd9ba5) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix pasted images failing to reach the model on first send.
- [#3047](https://github.com/MoonshotAI/kimi-code/pull/3047) [`c9c34ae`](https://github.com/MoonshotAI/kimi-code/commit/c9c34ae5a8626f133bd1b9c34cac0f3270e35b8d) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix pasted videos failing to submit instead of reaching the model.
## 0.37.0
### Minor Changes
- [#2935](https://github.com/MoonshotAI/kimi-code/pull/2935) [`44a6c70`](https://github.com/MoonshotAI/kimi-code/commit/44a6c70e66762ea9e122f8dceae16dc759086a7c) Thanks [@chengluyu](https://github.com/chengluyu)! - Activate multiple skills in a single prompt. Type `/` after whitespace to insert a skill token.
- [#2994](https://github.com/MoonshotAI/kimi-code/pull/2994) [`8c865f4`](https://github.com/MoonshotAI/kimi-code/commit/8c865f48173011439cfc2e140e45586e59b6bfcf) Thanks [@liruifengv](https://github.com/liruifengv)! - The Windows native (single-binary) CLI now supports automatic updates.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: the sidebar gains Open / Done / Workspaces tabs, and sessions can be marked as done (and reopened) to keep the open list focused.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: added a session management page (from the sidebar's list-management menu) for cross-workspace triage — filter by workspace, status, and updated time, and batch mark sessions as done or reopen them.
### Patch Changes
- [#2593](https://github.com/MoonshotAI/kimi-code/pull/2593) [`d833a1a`](https://github.com/MoonshotAI/kimi-code/commit/d833a1a893c4d69d96af542f40557442992085e0) Thanks [@7Sageer](https://github.com/7Sageer)! - Keep pasted image and video attachments available in session history.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: @-mentioned files, folders, and skills in chat messages now render as icon pills.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: renamed the Subagent panel to "Background Agent".
- [#2972](https://github.com/MoonshotAI/kimi-code/pull/2972) [`04d23e2`](https://github.com/MoonshotAI/kimi-code/commit/04d23e2dab776c480d24cfa033c9500543c75a3b) Thanks [@sailist](https://github.com/sailist)! - Fix text files containing Chinese or emoji being misdetected as binary in the web UI.
- [#2940](https://github.com/MoonshotAI/kimi-code/pull/2940) [`6b72345`](https://github.com/MoonshotAI/kimi-code/commit/6b72345f8bb03487e3bcc05b541e65484818428c) Thanks [@bj456736](https://github.com/bj456736)! - Print and copy the full `kimi --resume` command after `/fork`.
- [#2928](https://github.com/MoonshotAI/kimi-code/pull/2928) [`d96cd03`](https://github.com/MoonshotAI/kimi-code/commit/d96cd037702637305422222e985139e51ff83c8c) Thanks [@chengluyu](https://github.com/chengluyu)! - Warn when a typed `/goal` objective exceeds the 4000-character limit, and keep the input if it is rejected.
- [#2633](https://github.com/MoonshotAI/kimi-code/pull/2633) [`f492cd7`](https://github.com/MoonshotAI/kimi-code/commit/f492cd7c9e03666ecfd10dc47ca9b48c35de2318) Thanks [@tpoisonooo](https://github.com/tpoisonooo)! - Fix slow startup by loading the global search index on demand.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed YAML frontmatter in messages rendering as a giant heading — it now shows as a small meta block.
- [#2985](https://github.com/MoonshotAI/kimi-code/pull/2985) [`a7dc1ea`](https://github.com/MoonshotAI/kimi-code/commit/a7dc1ea28445555d5944066936fdf6e1b21d27ea) Thanks [@bj456736](https://github.com/bj456736)! - Fix a startup error when a restored session references a model that is no longer configured.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: hovering a mention pill now shows a detail bubble (full path for files and folders, description plus an open button for skills), skill and file mentions in messages are clickable, long file names middle-ellipsize, and deleted files are struck through.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed long task panel titles pushing the status badge, copy, and close buttons out of view — titles now ellipsize and show the full text on hover.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed pasting a copied folder into the composer failing the upload with a connection error — folders are now skipped instead.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: reduced animation power draw — the mascot and home doodle pause while hidden or scrolled offscreen, and looping animations play once and stop when the system's "reduce motion" setting is on.
- [#2969](https://github.com/MoonshotAI/kimi-code/pull/2969) [`ee564e5`](https://github.com/MoonshotAI/kimi-code/commit/ee564e5ec90afd068123b8052928c53f1fd5a27d) Thanks [@sailist](https://github.com/sailist)! - Fix the displayed context size dropping to a smaller estimate after archiving and resuming a session.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: the plan review feedback box now auto-grows with its content, so longer rejection reasons are easier to write.
- [#2633](https://github.com/MoonshotAI/kimi-code/pull/2633) [`f492cd7`](https://github.com/MoonshotAI/kimi-code/commit/f492cd7c9e03666ecfd10dc47ca9b48c35de2318) Thanks [@tpoisonooo](https://github.com/tpoisonooo)! - Queue slash skill commands entered while the agent is busy instead of rejecting them.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: the search dialog now finds workspaces too, and picking a workspace or session result expands the sidebar and scrolls the item into view.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed sent image and video attachments rendering broken in session history after a refresh or reopen.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed empty replies left by manually stopped answers still showing a completion time after reloading the page.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed background agent tasks not being cancellable during their first moments after starting.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed foreground subagents leaking into the Background Agent panel, which broke the count and left finished rows stuck as running and unstoppable.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: merged the task panel's two copy icons into a single button with a dropdown menu (copy command / copy output / copy all), with keyboard and touch-friendly targets.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed cancelled or abnormally ended background tasks showing as completed.
- [#3016](https://github.com/MoonshotAI/kimi-code/pull/3016) [`98ebda8`](https://github.com/MoonshotAI/kimi-code/commit/98ebda840a1e420f57a05ec680cbeca41a2419d7) Thanks [@sailist](https://github.com/sailist)! - Fix /undo not restoring the todo list to its state before the undone turn.
- [#2858](https://github.com/MoonshotAI/kimi-code/pull/2858) [`59dde73`](https://github.com/MoonshotAI/kimi-code/commit/59dde734f37596db5c77794060f81bfb3c1dbeb6) Thanks [@7Sageer](https://github.com/7Sageer)! - On the legacy engine, plugin MCP server changes and OAuth sign-in now take effect in open sessions immediately.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: the browser tab title now shows the current workspace directory name (override with the new `--web-title` flag), making instances on multiple machines easier to tell apart.
- [#3043](https://github.com/MoonshotAI/kimi-code/pull/3043) [`e31b3a3`](https://github.com/MoonshotAI/kimi-code/commit/e31b3a335ed49139c1aa3abb6b45a244fa17356a) Thanks [@liruifengv](https://github.com/liruifengv)! - web: fixed Ctrl+K in the composer opening session search on macOS instead of deleting to end of line — session search now only answers to Cmd+K.
- [#2989](https://github.com/MoonshotAI/kimi-code/pull/2989) [`09976b0`](https://github.com/MoonshotAI/kimi-code/commit/09976b09140c412f81a38cc00191f88bee4a9437) Thanks [@bj456736](https://github.com/bj456736)! - Add `kimi web --web-title <title>` to set a custom browser tab title for the web UI.
## 0.36.1
### Patch Changes
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: The timestamp under assistant replies now shows the message time instead of the work duration.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the slash command and @ file mention menus: matched fragments are bold-highlighted in the slash menu, and long lists in both menus get a scroll fade and a draggable floating scrollbar.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: The background Bash panel now supports filtering by status, and clicking a task shows its command and output on the right.
- [#2865](https://github.com/MoonshotAI/kimi-code/pull/2865) [`53909d9`](https://github.com/MoonshotAI/kimi-code/commit/53909d91e3ca570d4b565ba1abd00f027ca78d6b) Thanks [@weivwang](https://github.com/weivwang)! - Cache content-hashed Kimi Web assets across reloads while keeping the app entry point revalidated.
- [#2916](https://github.com/MoonshotAI/kimi-code/pull/2916) [`7475c2e`](https://github.com/MoonshotAI/kimi-code/commit/7475c2e2e3dd86ac0b8a8d51d4f1d233ed7df797) Thanks [@Grapedge](https://github.com/Grapedge)! - Cancel an in-flight /init run together with the turn instead of letting it run to completion.
- [#2911](https://github.com/MoonshotAI/kimi-code/pull/2911) [`249d8fa`](https://github.com/MoonshotAI/kimi-code/commit/249d8faa3447427665185a900926d048213d2ac7) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix sessions hanging on the second approval prompt and tool call results being dropped or mixed up in history when using a self-hosted OpenAI-compatible endpoint that renumbers tool call ids on every response.
- [#2917](https://github.com/MoonshotAI/kimi-code/pull/2917) [`6cf315b`](https://github.com/MoonshotAI/kimi-code/commit/6cf315b7bdea8a04cfaeba1bb8931c1730853aec) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Fix bare URLs in chat output absorbing the CJK characters that follow them, which made the link unclickable or open a broken address.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix the slash command panel staying open after switching sessions or when the composer loses focus.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Replace the composer mode menu with mutually exclusive plan/goal pills on the left of the input area (arm via /plan or /goal, exit with ×); Swarm becomes a separate toolbar toggle.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the work status pills above the composer with a borderless rounded look.
- [#2910](https://github.com/MoonshotAI/kimi-code/pull/2910) [`eb72aeb`](https://github.com/MoonshotAI/kimi-code/commit/eb72aebeeb972b2fcc238d5650dd991a5580f96b) Thanks [@sailist](https://github.com/sailist)! - Remove the 64 MiB limit on web session exports, so large sessions no longer fail with a file-too-large error when downloaded from the web UI.
- [#2884](https://github.com/MoonshotAI/kimi-code/pull/2884) [`1811bd4`](https://github.com/MoonshotAI/kimi-code/commit/1811bd4baf5b75ba076e2a24825f9c4f82c13341) Thanks [@liruifengv](https://github.com/liruifengv)! - Fix startup banner text wrapping on narrow terminals.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix `$` content inside inline code spans being misrendered as inline math.
- [#2899](https://github.com/MoonshotAI/kimi-code/pull/2899) [`102984a`](https://github.com/MoonshotAI/kimi-code/commit/102984aa660d752ba8dd7d1aba155575f32affe2) Thanks [@oocz](https://github.com/oocz)! - Fix MCP OAuth cancellation leaving an in-flight authorization waiting for its callback timeout.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix the thinking-effort flyout being unreachable when selecting the last model in the subagent model list.
- [#2876](https://github.com/MoonshotAI/kimi-code/pull/2876) [`5912d4c`](https://github.com/MoonshotAI/kimi-code/commit/5912d4c7d19d68975e85b007976b1bef59edae5c) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix repeated file-watcher errors on Windows when the workspace is a drive root (such as `E:\`) or a UNC network share.
- [#2916](https://github.com/MoonshotAI/kimi-code/pull/2916) [`7475c2e`](https://github.com/MoonshotAI/kimi-code/commit/7475c2e2e3dd86ac0b8a8d51d4f1d233ed7df797) Thanks [@Grapedge](https://github.com/Grapedge)! - Show a clear error when forking a session while its turn is running, instead of copying a partially written turn.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix forking sessions with very long histories always failing with a timeout.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Selecting /goal from the slash menu now immediately arms a removable goal pill in the composer; typing and sending creates the goal without requiring the goal text after the command.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the goal panel: the goal text and elapsed time move to the header, and actions become icon buttons.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix CJK text immediately after a bare URL being swallowed into the link, which made the link unopenable.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Adjust when plan mode takes effect: enabling it now arms a removable plan pill in the composer and only activates when the message is sent, matching goal mode behavior.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Add a plan viewer panel: click a plan entry in the work bar to see the full plan, review results, and feedback.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Show a clear top-center confirmation toast after exporting a session, and a clearer error message when the export fails because the session is too large.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix the session list PR badge not refreshing after a PR is created from within a session.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the session list PR badge as a small tag with a background.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Unify session status display in the sidebar and stabilize session list ordering.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Slash commands now support fuzzy search: find commands by description text, pinyin, or pinyin initials.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Rework the subagent panel into a card grid layout with status filtering, showing in-progress and recently finished tasks by default.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Fix server request timeouts being misreported as "cannot connect to the Kimi server".
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Restyle the todo panel as frosted cards and add a current-progress completion count.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Increase the font size and row height of the user menu and the plan usage flyout.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Rename the user menu's "Upgrade" entry to "Upgrade membership" and label the plan usage percentage as used.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Add experimental automatic session title generation, with on-demand regeneration from the session list.
- [#2922](https://github.com/MoonshotAI/kimi-code/pull/2922) [`cd48995`](https://github.com/MoonshotAI/kimi-code/commit/cd489955bb42c4a8055de9545d0b699b93bba98a) Thanks [@wbxl2000](https://github.com/wbxl2000)! - web: Add a "sort by recent activity" option to the workspace-grouped sidebar view (switched in the view options menu); newly added workspaces now sort to the top.
## 0.36.0
### Minor Changes
- [#2830](https://github.com/MoonshotAI/kimi-code/pull/2830) [`ec84a6f`](https://github.com/MoonshotAI/kimi-code/commit/ec84a6f9a3eb35e1118f8a327f7a11b3978a899c) Thanks [@liruifengv](https://github.com/liruifengv)! - Add an experimental fullscreen TUI mode. Set the `KIMI_CODE_TUI_FULL_SCREEN=1` environment variable to enable it.
- [#2700](https://github.com/MoonshotAI/kimi-code/pull/2700) [`c9bfe8b`](https://github.com/MoonshotAI/kimi-code/commit/c9bfe8b2c8314ba4ef8806fb3b92ac654c1d1860) Thanks [@7Sageer](https://github.com/7Sageer)! - Add a configurable model pool for spawned subagents behind the `secondary-model` experiment (`KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=1`, or the master flag): with the experiment on, the `/secondary-model` command or the `[secondary_model]` section in config.toml sets a default model or a small named pool that the main agent picks from per spawn. A lone legacy `model` key in the same section keeps working as the fallback default.
### Patch Changes
- [#2830](https://github.com/MoonshotAI/kimi-code/pull/2830) [`ec84a6f`](https://github.com/MoonshotAI/kimi-code/commit/ec84a6f9a3eb35e1118f8a327f7a11b3978a899c) Thanks [@liruifengv](https://github.com/liruifengv)! - Render LaTeX math formulas (`$…$` / `$$…$$`) in messages as Unicode formulas.
- [#2855](https://github.com/MoonshotAI/kimi-code/pull/2855) [`30f56a2`](https://github.com/MoonshotAI/kimi-code/commit/30f56a2d2da332cbf0c36a13cbe01aac5d319c7b) Thanks [@liruifengv](https://github.com/liruifengv)! - Fix Ctrl+C being ignored during automatic retries of failed API requests.
- [#2819](https://github.com/MoonshotAI/kimi-code/pull/2819) [`fe3cdae`](https://github.com/MoonshotAI/kimi-code/commit/fe3cdae5f8ab40be71b65eff32319eb94a53c17d) Thanks [@7Sageer](https://github.com/7Sageer)! - Fix sessions failing with a provider 400 error on every follow-up request after a turn is interrupted while the model is still thinking, on strict OpenAI-compatible providers.
- [#2847](https://github.com/MoonshotAI/kimi-code/pull/2847) [`3b0936d`](https://github.com/MoonshotAI/kimi-code/commit/3b0936d8e025c5a944759c40593d5f21bfb3e621) Thanks [@sailist](https://github.com/sailist)! - Fix plain Markdown files (such as CHANGELOG.md) in an installed plugin's root directory being misidentified as skills when the plugin relies on the root SKILL.md fallback.
- [#2843](https://github.com/MoonshotAI/kimi-code/pull/2843) [`c212ae9`](https://github.com/MoonshotAI/kimi-code/commit/c212ae9715371c0d7939c15e664acbe0d7cf7fc3) Thanks [@sailist](https://github.com/sailist)! - Show project MCP launch targets in the workspace trust prompt, default to declining trust, and resolve fd and stty binaries to absolute paths so untrusted workspaces cannot plant bare-name executables before confirmation.
`@moonshot-ai/kimi-code-sdk` contract change: `WorkspaceTrustInfo.gatedMcpServers` now carries structured `WorkspaceTrustMcpServerInfo` records (`name`, `transport`, and `command`/`args`/`cwd` or `url`) instead of plain strings, so SDK consumers rendering a trust prompt can show the full launch target.
- [#2856](https://github.com/MoonshotAI/kimi-code/pull/2856) [`504e629`](https://github.com/MoonshotAI/kimi-code/commit/504e6292ede448367d1341751f9f98b24cc2994f) Thanks [@pvzheroes125](https://github.com/pvzheroes125)! - Refresh active MCP connections after OAuth credentials are added or reset.
## 0.35.0
## 0.35.0
### Minor Changes
### Minor Changes
@ -50,6 +322,10 @@
- [#2813](https://github.com/MoonshotAI/kimi-code/pull/2813) [`619564d`](https://github.com/MoonshotAI/kimi-code/commit/619564dcf9ee10a3cfbf7ecbc764c6b9b63fc91b) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Fix the web UI repeatedly losing its realtime connection every ~30 seconds when the server runs behind a reverse proxy or gateway with an idle connection timeout; the server now sends a WebSocket heartbeat and only closes connections that stop responding entirely.
- [#2813](https://github.com/MoonshotAI/kimi-code/pull/2813) [`619564d`](https://github.com/MoonshotAI/kimi-code/commit/619564dcf9ee10a3cfbf7ecbc764c6b9b63fc91b) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Fix the web UI repeatedly losing its realtime connection every ~30 seconds when the server runs behind a reverse proxy or gateway with an idle connection timeout; the server now sends a WebSocket heartbeat and only closes connections that stop responding entirely.
- [#2842](https://github.com/MoonshotAI/kimi-code/pull/2842) [`e476c5a`](https://github.com/MoonshotAI/kimi-code/commit/e476c5a8bbe68fb0b6eb0096aa1efcb893b1a8fc) Thanks [@wbxl2000](https://github.com/wbxl2000)! - Add the Modern Web Guidance plugin to the bundled plugin marketplace. Run /plugins and select Modern Web Guidance to install it.
- Thanks [@Leakless](https://github.com/Leakless) and [@winmin](https://github.com/winmin) for reporting the Windows binary-planting issues fixed in this release.
import{casO,wasI,aasJ,fasP,basE,sasA}from"./chunk-RYQCIY6F-Df2V79id.js";import{_asw,amasv,anasD,aoasH,apasY,l,cas_,aqasW,aras$,agasj,asasq,ahasR,afasF,atasz,auasK,avasG}from"./mermaid.core-CJB1tAev.js";import{GasQ}from"./graph-DOmOIIwC.js";import{lasU}from"./layout-D-LzfAck.js";import"./map-DxJ2ADlA.js";import"./index-D-7nOosq.js";import"./_commonjsHelpers-CqkleIqs.js";varC=w((s,t,g)=>Math.max(t,Math.min(g,s)),"clamp"),B=w((s="TB")=>{switch(s){case"BT":return"bottom";case"LR":return"right";case"RL":return"left";case"TB":default:return"top"}},"getDefaultSelfLoopSide"),V=w(s=>s==="flowchart"||s==="flowchart-v2"||s==="stateDiagram","shouldMergeSelfLoopSegments"),Z=w((s,t,g,m,c)=>{consto=[],r=newSet;if(g.forEach(({start:i,end:n})=>{i!==m&&r.add(i),n!==m&&r.add(n)}),r.forEach(i=>{constn=s.node(i);typeofn?.x=="number"&&typeofn?.y=="number"&&o.push(n)}),o.length===0&&g.forEach(({edge:i})=>{(i.points??[]).forEach(n=>{typeofn?.x=="number"&&typeofn?.y=="number"&&o.push(n)})}),o.length===0)returnB(c);constf=o.reduce((i,n)=>({x:i.x+n.x/o.length,y:i.y+n.y/o.length}),{x:0,y:0}),h=f.x-t.x,a=f.y-t.y;returnMath.abs(h)>Math.abs(a)?h>0?"right":"left":Math.abs(a)>0?a>0?"bottom":"top":B(c)},"getSelfLoopSide"),ee=w((s,t="top",g=0,m=0)=>{constc=s.x,o=s.y-g,r=s.width/2,f=s.height/2,h=Math.max(36,Math.min(100,s.width*.8)),a=C(Math.max(m,s.width*.35),36,h),i=C(Math.min(s.width,s.height)*.45,24,48);switch(t){case"bottom":{constn=o+f;return[{x:c-a/2,y:n},{x:c-a/2,y:n+i},{x:c+a/2,y:n+i},{x:c+a/2,y:n}]}case"right":{constn=c+r;return[{x:n,y:o-a/2},{x:n+i,y:o-a/2},{x:n+i,y:o+a/2},{x:n,y:o+a/2}]}case"left":{constn=c-r;return[{x:n,y:o-a/2},{x:n-i,y:o-a/2},{x:n-i,y:o+a/2},{x:n,y:o+a/2}]}case"top":default:{constn=o-f;return[{x:c-a/2,y:n},{x:c-a/2,y:n-i},{x:c+a/2,y:n-i},{x:c+a/2,y:n}]}}},"getSelfLoopPoints"),te=w((s,t,g="top",m=0,c={})=>{constr=s.x,f=s.y-m,h=c.width??0,a=c.height??0;switch(g){case"bottom":return{x:r,y:Math.max(...t.map(i=>i.y))+a/2+4};case"right":return{x:Math.max(...t.map(i=>i.x))+h/2+4,y:f};case"left":return{x:Math.min(...t.map(i=>i.x))-h/2-4,y:f};case"top":default:return{x:r,y:Math.min(...t.map(i=>i.y))-a/2-4}}},"getSelfLoopLabelPosition"),ne=w((s,t=0,{mergeSelfLoops:g=!0}={})=>{constm=newMap,c=[],o=s.graph()?.rankdir;returns.edges().forEach(r=>{constf=s.edge(r);if(g&&f.selfLoop){consth=f.selfLoop.id;m.has(h)||m.set(h,[]),m.get(h).push({edge:f,start:r.v,end:r.w})}elsec.push({edge:f,start:r.v,end:r.w})}),m.forEach(r=>{if(r.length!==3){r.forEach(L=>c.push(L));return}r.sort((L,d)=>L.edge.selfLoop.order-d.edge.selfLoop.order);const[f,h,a]=r,i=f.edge.originalEdge??h.edge.originalEdge??a.edge.originalEdge??h.edge,n=s.node(i.start);if(!n){r.forEach(L=>c.push(L));return}constp={width:h.edge.width,height:h.edge.height},y=Z(s,n,r,i.start,o),X=ee(n,y,t,p.width??0),S=te(n,X,y,t,p),b={...h.edge,...i,id:i.id,points:X,start:i.start,end:i.end,x:S.x,y:S.y,width:p.width,height:p.height,labelStyle:h.edge.labelStyle,fromCluster:f.edge.fromCluster??h.edge.fromCluster??a.edge.fromCluster,toCluster:f.edge.toCluster??h.edge.toCluster??a.edge.toCluster};deleteb.selfLoop,deleteb.originalEdge,c.push({edge:b,start:b.start,end:b.end})}),c},"getEdgesToRender"),T=w(async(s,t,g,m,c,o)=>{l.warn("Graph in recursive render:XAX",I(t),c);constr=t.graph().rankdir;l.trace("Dir in recursive render - dir:",r);constf=s.insert("g").attr("class","root");t.nodes()?l.info("Recursive render XXX",t.nodes()):l.info("No nodes found for",t),t.edges().length>0&&l.info("Recursive edges",t.edge(t.edges()[0]));consth=f.insert("g").attr("class","clusters"),a=f.insert("g").attr("class","edgePaths"),i=f.insert("g").attr("class","edgeLabels"),n=f.insert("g").attr("class","nodes"),p=V(g);awaitPromise.all(t.nodes().map(asyncfunction(d){conste=t.node(d);if(c!==void0){constu=JSON.parse(JSON.stringify(c.clusterData));l.trace(`Setting data for parent cluster XXX
import{casO,wasI,aasJ,fasP,basE,sasA}from"./chunk-RYQCIY6F-D1Yl7opn.js";import{_asw,amasv,anasD,aoasH,apasY,l,cas_,aqasW,aras$,agasj,asasq,ahasR,afasF,atasz,auasK,avasG}from"./mermaid.core-DaDTfY6S.js";import{GasQ}from"./graph-DOmOIIwC.js";import{lasU}from"./layout-D-LzfAck.js";import"./map-DxJ2ADlA.js";import"./index-D1h84VfZ.js";import"./_commonjsHelpers-CqkleIqs.js";varC=w((s,t,g)=>Math.max(t,Math.min(g,s)),"clamp"),B=w((s="TB")=>{switch(s){case"BT":return"bottom";case"LR":return"right";case"RL":return"left";case"TB":default:return"top"}},"getDefaultSelfLoopSide"),V=w(s=>s==="flowchart"||s==="flowchart-v2"||s==="stateDiagram","shouldMergeSelfLoopSegments"),Z=w((s,t,g,m,c)=>{consto=[],r=newSet;if(g.forEach(({start:i,end:n})=>{i!==m&&r.add(i),n!==m&&r.add(n)}),r.forEach(i=>{constn=s.node(i);typeofn?.x=="number"&&typeofn?.y=="number"&&o.push(n)}),o.length===0&&g.forEach(({edge:i})=>{(i.points??[]).forEach(n=>{typeofn?.x=="number"&&typeofn?.y=="number"&&o.push(n)})}),o.length===0)returnB(c);constf=o.reduce((i,n)=>({x:i.x+n.x/o.length,y:i.y+n.y/o.length}),{x:0,y:0}),h=f.x-t.x,a=f.y-t.y;returnMath.abs(h)>Math.abs(a)?h>0?"right":"left":Math.abs(a)>0?a>0?"bottom":"top":B(c)},"getSelfLoopSide"),ee=w((s,t="top",g=0,m=0)=>{constc=s.x,o=s.y-g,r=s.width/2,f=s.height/2,h=Math.max(36,Math.min(100,s.width*.8)),a=C(Math.max(m,s.width*.35),36,h),i=C(Math.min(s.width,s.height)*.45,24,48);switch(t){case"bottom":{constn=o+f;return[{x:c-a/2,y:n},{x:c-a/2,y:n+i},{x:c+a/2,y:n+i},{x:c+a/2,y:n}]}case"right":{constn=c+r;return[{x:n,y:o-a/2},{x:n+i,y:o-a/2},{x:n+i,y:o+a/2},{x:n,y:o+a/2}]}case"left":{constn=c-r;return[{x:n,y:o-a/2},{x:n-i,y:o-a/2},{x:n-i,y:o+a/2},{x:n,y:o+a/2}]}case"top":default:{constn=o-f;return[{x:c-a/2,y:n},{x:c-a/2,y:n-i},{x:c+a/2,y:n-i},{x:c+a/2,y:n}]}}},"getSelfLoopPoints"),te=w((s,t,g="top",m=0,c={})=>{constr=s.x,f=s.y-m,h=c.width??0,a=c.height??0;switch(g){case"bottom":return{x:r,y:Math.max(...t.map(i=>i.y))+a/2+4};case"right":return{x:Math.max(...t.map(i=>i.x))+h/2+4,y:f};case"left":return{x:Math.min(...t.map(i=>i.x))-h/2-4,y:f};case"top":default:return{x:r,y:Math.min(...t.map(i=>i.y))-a/2-4}}},"getSelfLoopLabelPosition"),ne=w((s,t=0,{mergeSelfLoops:g=!0}={})=>{constm=newMap,c=[],o=s.graph()?.rankdir;returns.edges().forEach(r=>{constf=s.edge(r);if(g&&f.selfLoop){consth=f.selfLoop.id;m.has(h)||m.set(h,[]),m.get(h).push({edge:f,start:r.v,end:r.w})}elsec.push({edge:f,start:r.v,end:r.w})}),m.forEach(r=>{if(r.length!==3){r.forEach(L=>c.push(L));return}r.sort((L,d)=>L.edge.selfLoop.order-d.edge.selfLoop.order);const[f,h,a]=r,i=f.edge.originalEdge??h.edge.originalEdge??a.edge.originalEdge??h.edge,n=s.node(i.start);if(!n){r.forEach(L=>c.push(L));return}constp={width:h.edge.width,height:h.edge.height},y=Z(s,n,r,i.start,o),X=ee(n,y,t,p.width??0),S=te(n,X,y,t,p),b={...h.edge,...i,id:i.id,points:X,start:i.start,end:i.end,x:S.x,y:S.y,width:p.width,height:p.height,labelStyle:h.edge.labelStyle,fromCluster:f.edge.fromCluster??h.edge.fromCluster??a.edge.fromCluster,toCluster:f.edge.toCluster??h.edge.toCluster??a.edge.toCluster};deleteb.selfLoop,deleteb.originalEdge,c.push({edge:b,start:b.start,end:b.end})}),c},"getEdgesToRender"),T=w(async(s,t,g,m,c,o)=>{l.warn("Graph in recursive render:XAX",I(t),c);constr=t.graph().rankdir;l.trace("Dir in recursive render - dir:",r);constf=s.insert("g").attr("class","root");t.nodes()?l.info("Recursive render XXX",t.nodes()):l.info("No nodes found for",t),t.edges().length>0&&l.info("Recursive edges",t.edge(t.edges()[0]));consth=f.insert("g").attr("class","clusters"),a=f.insert("g").attr("class","edgePaths"),i=f.insert("g").attr("class","edgeLabels"),n=f.insert("g").attr("class","nodes"),p=V(g);awaitPromise.all(t.nodes().map(asyncfunction(d){conste=t.node(d);if(c!==void0){constu=JSON.parse(JSON.stringify(c.clusterData));l.trace(`Setting data for parent cluster XXX
Node.id=`,d,`
Node.id=`,d,`
data=`,u.height,`
data=`,u.height,`
Parentcluster`,c.height),t.setNode(c.id,u),t.parent(d)||(l.trace("Setting parent",d,c.id),t.setParent(d,c.id,u))}if(l.info("(Insert) Node XXX"+d+": "+JSON.stringify(t.node(d))),e?.clusterNode){l.info("Cluster identified XBX",d,e.width,t.node(d));const{ranksep:u,nodesep:x}=t.graph();e.graph.setGraph({...e.graph.graph(),ranksep:u+25,nodesep:x});const N=await T(n,e.graph,g,m,t.node(d),o),M=N.elem;W(e,M),e.diff=N.diff||0,l.info("New compound node after recursive render XAX",d,"width",e.width,"height",e.height),$(M,e)}else t.children(d).length>0?(l.trace("Cluster - the non recursive path XBX",d,e.id,e,e.width,"Graph:",t),l.trace(P(e.id,t)),E.set(e.id,{id:P(e.id,t),node:e})):(l.trace("Node - the non recursive path XAX",d,n,t.node(d),r),await j(n,t.node(d),{config:o,dir:r}))})),await w(async()=>{const d=t.edges().map(async function(e){const u=t.edge(e.v,e.w,e.name);if(l.info("Edge "+e.v+" -> "+e.w+": "+JSON.stringify(e)),l.info("Edge "+e.v+" -> "+e.w+": ",e," ",JSON.stringify(t.edge(e))),l.info("Fix",E,"ids:",e.v,e.w,"Translating: ",E.get(e.v),E.get(e.w)),p&&u.selfLoop){if(u.selfLoop.order!==1)return;const x=u.id;u.id=u.selfLoop.id,await G(i,u),u.id=x;return}await G(i,u)});await Promise.all(d)},"processEdges")(),l.info("Graph before layout:",JSON.stringify(I(t))),l.info("############################################# XXX"),l.info("### Layout ### XXX"),l.info("############################################# XXX"),U(t),l.info("Graph after layout:",JSON.stringify(I(t)));let X=0,{subGraphTitleTotalMargin:S}=q(o);await Promise.all(A(t).map(async function(d){const e=t.node(d);if(l.info("Position XBX => "+d+": ("+e.x,","+e.y,") width: ",e.width," height: ",e.height),e?.clusterNode)e.y+=S,l.info("A tainted cluster node XBX1",d,e.id,e.width,e.height,e.x,e.y,t.parent(d)),E.get(e.id).node=e,R(e);else if(t.children(d).length>0){l.info("A pure cluster node XBX1",d,e.id,e.x,e.y,e.width,e.height,t.parent(d)),e.height+=S,t.node(e.parentId);const u=e?.padding/2||0,x=e?.labelBBox?.height||0,N=x-u||0;l.debug("OffsetY",N,"labelHeight",x,"halfPadding",u),await F(h,e),E.get(e.id).node=e}else{const u=t.node(e.parentId);e.y+=S/2,l.info("A regular node XBX1 - using the padding",e.id,"parent",e.parentId,e.width,e.height,e.x,e.y,"offsetY",e.offsetY,"parent",u,u?.offsetY,e),R(e)}}));const b=S/2;return ne(t,b,{mergeSelfLoops:p}).forEach(function({edge:d,start:e,end:u}){l.info("Edge "+e+" -> "+u+": "+JSON.stringify(d),d),d.points.forEach(k=>k.y+=b);const x=t.node(e),N=t.node(u),M=z(a,d,E,g,x,N,m);K(d,M)}),t.nodes().forEach(function(d){const e=t.node(d);l.info(d,e.type,e.diff),e.isGroup&&(X=e.diff)}),l.warn("Returning from recursive render XAX",f,X),{elem:f,diff:X}},"recursiveRender"),le=w(async(s,t)=>{const g=new Q({multigraph:!0,compound:!0}).setGraph({rankdir:s.direction,nodesep:s.config?.nodeSpacing||s.config?.flowchart?.nodeSpacing||s.nodeSpacing,ranksep:s.config?.rankSpacing||s.config?.flowchart?.rankSpacing||s.rankSpacing,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}}),m=t.select("g");v(m,s.markers,s.type,s.diagramId),D(),H(),Y(),O(),s.nodes.forEach(o=>{g.setNode(o.id,{...o}),o.parentId&&g.setParent(o.id,o.parentId)}),l.debug("Edges:",s.edges),s.edges.forEach(o=>{if(o.start===o.end){const r=o.start,f=r+"---"+r+"---1",h=r+"---"+r+"---2",a=g.node(r);g.setNode(f,{domId:f,id:f,parentId:a.parentId,labelStyle:"",label:"",padding:0,shape:"labelRect",style:"",width:10,height:10}),g.setParent(f,a.parentId),g.setNode(h,{domId:h,id:h,parentId:a.parentId,labelStyle:"",padding:0,shape:"labelRect",label:"",style:"",width:10,height:10}),g.setParent(h,a.parentId);const i=structuredClone(o),n=structuredClone(o),p=structuredClone(o),y=structuredClone(o);n.originalEdge=i,n.selfLoop={id:i.id,order:0},p.originalEdge=i,p.selfLoop={id:i.id,order:1},y.originalEdge=i,y.selfLoop={id:i.id,order:2},n.label="",n.arrowTypeEnd="none",n.endLabelLeft="",n.endLabelRight="",n.startLabelLeft="",n.id=r+"-cyclic-special-1",p.startLabelRight="",p.startLabelLeft="",p.endLabelLeft="",p.endLabelRight="",p.arrowTypeStart="none",p.arrowTypeEnd="none",p.id=r+"-cyclic-special-mid",y.label="",y.startLabelRight="",y.startLabelLeft="",y.arrowTypeStart="none",a.isGroup&&(n.fromCluster=r,y.toCluster=r),y.id=r+"-cyclic-special-2",y.arrowTypeStart="none",g.setEdge(r,f,n,r+"-cyclic-special-0"),g.setEdge(f,h,p,r+"-cyclic-special-1"),g.setEdge(h,r,y,r+"-cyclic-special-2")}else g.setEdge(o.start,o.end,{...o},o.id)}),l.warn("Graph at first:",JSON.stringify(I(g))),J(g),l.warn("Graph after XAX:",JSON.stringify(I(g)));const c=_();await T(m,g,s.type,s.diagramId,void 0,c)},"render");export{ne as getEdgesToRender,le as render};
Parentcluster`,c.height),t.setNode(c.id,u),t.parent(d)||(l.trace("Setting parent",d,c.id),t.setParent(d,c.id,u))}if(l.info("(Insert) Node XXX"+d+": "+JSON.stringify(t.node(d))),e?.clusterNode){l.info("Cluster identified XBX",d,e.width,t.node(d));const{ranksep:u,nodesep:x}=t.graph();e.graph.setGraph({...e.graph.graph(),ranksep:u+25,nodesep:x});const N=await T(n,e.graph,g,m,t.node(d),o),M=N.elem;W(e,M),e.diff=N.diff||0,l.info("New compound node after recursive render XAX",d,"width",e.width,"height",e.height),$(M,e)}else t.children(d).length>0?(l.trace("Cluster - the non recursive path XBX",d,e.id,e,e.width,"Graph:",t),l.trace(P(e.id,t)),E.set(e.id,{id:P(e.id,t),node:e})):(l.trace("Node - the non recursive path XAX",d,n,t.node(d),r),await j(n,t.node(d),{config:o,dir:r}))})),await w(async()=>{const d=t.edges().map(async function(e){const u=t.edge(e.v,e.w,e.name);if(l.info("Edge "+e.v+" -> "+e.w+": "+JSON.stringify(e)),l.info("Edge "+e.v+" -> "+e.w+": ",e," ",JSON.stringify(t.edge(e))),l.info("Fix",E,"ids:",e.v,e.w,"Translating: ",E.get(e.v),E.get(e.w)),p&&u.selfLoop){if(u.selfLoop.order!==1)return;const x=u.id;u.id=u.selfLoop.id,await G(i,u),u.id=x;return}await G(i,u)});await Promise.all(d)},"processEdges")(),l.info("Graph before layout:",JSON.stringify(I(t))),l.info("############################################# XXX"),l.info("### Layout ### XXX"),l.info("############################################# XXX"),U(t),l.info("Graph after layout:",JSON.stringify(I(t)));let X=0,{subGraphTitleTotalMargin:S}=q(o);await Promise.all(A(t).map(async function(d){const e=t.node(d);if(l.info("Position XBX => "+d+": ("+e.x,","+e.y,") width: ",e.width," height: ",e.height),e?.clusterNode)e.y+=S,l.info("A tainted cluster node XBX1",d,e.id,e.width,e.height,e.x,e.y,t.parent(d)),E.get(e.id).node=e,R(e);else if(t.children(d).length>0){l.info("A pure cluster node XBX1",d,e.id,e.x,e.y,e.width,e.height,t.parent(d)),e.height+=S,t.node(e.parentId);const u=e?.padding/2||0,x=e?.labelBBox?.height||0,N=x-u||0;l.debug("OffsetY",N,"labelHeight",x,"halfPadding",u),await F(h,e),E.get(e.id).node=e}else{const u=t.node(e.parentId);e.y+=S/2,l.info("A regular node XBX1 - using the padding",e.id,"parent",e.parentId,e.width,e.height,e.x,e.y,"offsetY",e.offsetY,"parent",u,u?.offsetY,e),R(e)}}));const b=S/2;return ne(t,b,{mergeSelfLoops:p}).forEach(function({edge:d,start:e,end:u}){l.info("Edge "+e+" -> "+u+": "+JSON.stringify(d),d),d.points.forEach(k=>k.y+=b);const x=t.node(e),N=t.node(u),M=z(a,d,E,g,x,N,m);K(d,M)}),t.nodes().forEach(function(d){const e=t.node(d);l.info(d,e.type,e.diff),e.isGroup&&(X=e.diff)}),l.warn("Returning from recursive render XAX",f,X),{elem:f,diff:X}},"recursiveRender"),le=w(async(s,t)=>{const g=new Q({multigraph:!0,compound:!0}).setGraph({rankdir:s.direction,nodesep:s.config?.nodeSpacing||s.config?.flowchart?.nodeSpacing||s.nodeSpacing,ranksep:s.config?.rankSpacing||s.config?.flowchart?.rankSpacing||s.rankSpacing,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}}),m=t.select("g");v(m,s.markers,s.type,s.diagramId),D(),H(),Y(),O(),s.nodes.forEach(o=>{g.setNode(o.id,{...o}),o.parentId&&g.setParent(o.id,o.parentId)}),l.debug("Edges:",s.edges),s.edges.forEach(o=>{if(o.start===o.end){const r=o.start,f=r+"---"+r+"---1",h=r+"---"+r+"---2",a=g.node(r);g.setNode(f,{domId:f,id:f,parentId:a.parentId,labelStyle:"",label:"",padding:0,shape:"labelRect",style:"",width:10,height:10}),g.setParent(f,a.parentId),g.setNode(h,{domId:h,id:h,parentId:a.parentId,labelStyle:"",padding:0,shape:"labelRect",label:"",style:"",width:10,height:10}),g.setParent(h,a.parentId);const i=structuredClone(o),n=structuredClone(o),p=structuredClone(o),y=structuredClone(o);n.originalEdge=i,n.selfLoop={id:i.id,order:0},p.originalEdge=i,p.selfLoop={id:i.id,order:1},y.originalEdge=i,y.selfLoop={id:i.id,order:2},n.label="",n.arrowTypeEnd="none",n.endLabelLeft="",n.endLabelRight="",n.startLabelLeft="",n.id=r+"-cyclic-special-1",p.startLabelRight="",p.startLabelLeft="",p.endLabelLeft="",p.endLabelRight="",p.arrowTypeStart="none",p.arrowTypeEnd="none",p.id=r+"-cyclic-special-mid",y.label="",y.startLabelRight="",y.startLabelLeft="",y.arrowTypeStart="none",a.isGroup&&(n.fromCluster=r,y.toCluster=r),y.id=r+"-cyclic-special-2",y.arrowTypeStart="none",g.setEdge(r,f,n,r+"-cyclic-special-0"),g.setEdge(f,h,p,r+"-cyclic-special-1"),g.setEdge(h,r,y,r+"-cyclic-special-2")}else g.setEdge(o.start,o.end,{...o},o.id)}),l.warn("Graph at first:",JSON.stringify(I(g))),J(g),l.warn("Graph after XAX:",JSON.stringify(I(g)));const c=_();await T(m,g,s.type,s.diagramId,void 0,c)},"render");export{ne as getEdgesToRender,le as render};
import{pasB}from"./chunk-JWPE2WC7-Dsg3gA8l.js";import{_asb,Basu,Fas$,easC,lasm,basS,aasD,oasT,pasz,gasF,sasP,zasE,DasA,qasW}from"./mermaid.core-CJB1tAev.js";import{pas_}from"./cynefin-VYW2F7L2-BIlq342y.js";import"./index-D-7nOosq.js";import"./_commonjsHelpers-CqkleIqs.js";varN=A.packet,w=class{constructor(){this.packet=[],this.setAccTitle=S,this.getAccTitle=D,this.setDiagramTitle=T,this.getDiagramTitle=z,this.getAccDescription=F,this.setAccDescription=P}static{b(this,"PacketDB")}getConfig(){constt=u({...N,...E().packet});returnt.showBits&&(t.paddingY+=10),t}getPacket(){returnthis.packet}pushWord(t){t.length>0&&this.packet.push(t)}clear(){W(),this.packet=[]}},L=1e4,M=b((t,e)=>{B(t,e);letr=-1,o=[],n=1;const{bitsPerRow:l}=e.getConfig();for(let{start:a,end:i,bits:d,label:c}oft.blocks){if(a!==void0&&i!==void0&&i<a)thrownewError(`Packet block ${a} - ${i} is invalid. End must be greater than start.`);if(a??=r+1,a!==r+1)thrownewError(`Packet block ${a} - ${i??a} is not contiguous. It should start from ${r+1}.`);if(d===0)thrownewError(`Packet block ${a} is invalid. Cannot have a zero bit field.`);for(i??=a+(d??1)-1,d??=i-a+1,r=i,m.debug(`Packet block ${a} - ${r} with label ${c}`);o.length<=l+1&&e.getPacket().length<L;){const[p,s]=Y({start:a,end:i,bits:d,label:c},n,l);if(o.push(p),p.end+1===n*l&&(e.pushWord(o),o=[],n++),!s)break;({start:a,end:i,bits:d,label:c}=s)}}e.pushWord(o)},"populate"),Y=b((t,e,r)=>{if(t.start===void0)thrownewError("start should have been set during first phase");if(t.end===void0)thrownewError("end should have been set during first phase");if(t.start>t.end)thrownewError(`Block start ${t.start} is greater than block end ${t.end}.`);if(t.end+1<=e*r)return[t,void0];consto=e*r-1,n=e*r;return[{start:t.start,end:o,label:t.label,bits:o-t.start},{start:n,end:t.end,label:t.label,bits:t.end-n}]},"getNextFittingBlock"),v={parser:{yy:void0},parse:b(asynct=>{conste=await_("packet",t),r=v.parser?.yy;if(!(rinstanceofw))thrownewError("parser.parser?.yy was not a PacketDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");m.debug(e),M(e,r)},"parse")},I=b((t,e,r,o)=>{constn=o.db,l=n.getConfig(),{rowHeight:a,paddingY:i,bitWidth:d,bitsPerRow:c}=l,p=n.getPacket(),s=n.getDiagramTitle(),h=a+i,g=h*(p.length+1)-(s?0:a),k=d*c+2,f=$(e);f.attr("viewBox",`0 0 ${k}${g}`),C(f,g,k,l.useMaxWidth);for(const[x,y]ofp.entries())O(f,y,x,l);f.append("text").text(s).attr("x",k/2).attr("y",g-h/2).attr("dominant-baseline","middle").attr("text-anchor","middle").attr("class","packetTitle")},"draw"),O=b((t,e,r,{rowHeight:o,paddingX:n,paddingY:l,bitWidth:a,bitsPerRow:i,showBits:d})=>{constc=t.append("g"),p=r*(o+l)+l;for(constsofe){consth=s.start%i*a+1,g=(s.end-s.start+1)*a-n;if(c.append("rect").attr("x",h).attr("y",p).attr("width",g).attr("height",o).attr("class","packetBlock"),c.append("text").attr("x",h+g/2).attr("y",p+o/2).attr("class","packetLabel").attr("dominant-baseline","middle").attr("text-anchor","middle").text(s.label),!d)continue;constk=s.end===s.start,f=p-2;c.append("text").attr("x",h+(k?g/2:0)).attr("y",f).attr("class","packetByte start").attr("dominant-baseline","auto").attr("text-anchor",k?"middle":"start").text(s.start),k||c.append("text").attr("x",h+g).attr("y",f).attr("class","packetByte end").attr("dominant-baseline","auto").attr("text-anchor","end").text(s.end)}},"drawWord"),j={draw:I},q={byteFontSize:"10px",startByteColor:"black",endByteColor:"black",labelColor:"black",labelFontSize:"12px",titleColor:"black",titleFontSize:"14px",blockStrokeColor:"black",blockStrokeWidth:"1",blockFillColor:"#efefef"},G=b(({packet:t}={})=>{conste=u(q,t);return`
import{pasB}from"./chunk-JWPE2WC7-XhS5NGpP.js";import{_asb,Basu,Fas$,easC,lasm,basS,aasD,oasT,pasz,gasF,sasP,zasE,DasA,qasW}from"./mermaid.core-DaDTfY6S.js";import{pas_}from"./cynefin-VYW2F7L2-0NmB13eq.js";import"./index-D1h84VfZ.js";import"./_commonjsHelpers-CqkleIqs.js";varN=A.packet,w=class{constructor(){this.packet=[],this.setAccTitle=S,this.getAccTitle=D,this.setDiagramTitle=T,this.getDiagramTitle=z,this.getAccDescription=F,this.setAccDescription=P}static{b(this,"PacketDB")}getConfig(){constt=u({...N,...E().packet});returnt.showBits&&(t.paddingY+=10),t}getPacket(){returnthis.packet}pushWord(t){t.length>0&&this.packet.push(t)}clear(){W(),this.packet=[]}},L=1e4,M=b((t,e)=>{B(t,e);letr=-1,o=[],n=1;const{bitsPerRow:l}=e.getConfig();for(let{start:a,end:i,bits:d,label:c}oft.blocks){if(a!==void0&&i!==void0&&i<a)thrownewError(`Packet block ${a} - ${i} is invalid. End must be greater than start.`);if(a??=r+1,a!==r+1)thrownewError(`Packet block ${a} - ${i??a} is not contiguous. It should start from ${r+1}.`);if(d===0)thrownewError(`Packet block ${a} is invalid. Cannot have a zero bit field.`);for(i??=a+(d??1)-1,d??=i-a+1,r=i,m.debug(`Packet block ${a} - ${r} with label ${c}`);o.length<=l+1&&e.getPacket().length<L;){const[p,s]=Y({start:a,end:i,bits:d,label:c},n,l);if(o.push(p),p.end+1===n*l&&(e.pushWord(o),o=[],n++),!s)break;({start:a,end:i,bits:d,label:c}=s)}}e.pushWord(o)},"populate"),Y=b((t,e,r)=>{if(t.start===void0)thrownewError("start should have been set during first phase");if(t.end===void0)thrownewError("end should have been set during first phase");if(t.start>t.end)thrownewError(`Block start ${t.start} is greater than block end ${t.end}.`);if(t.end+1<=e*r)return[t,void0];consto=e*r-1,n=e*r;return[{start:t.start,end:o,label:t.label,bits:o-t.start},{start:n,end:t.end,label:t.label,bits:t.end-n}]},"getNextFittingBlock"),v={parser:{yy:void0},parse:b(asynct=>{conste=await_("packet",t),r=v.parser?.yy;if(!(rinstanceofw))thrownewError("parser.parser?.yy was not a PacketDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");m.debug(e),M(e,r)},"parse")},I=b((t,e,r,o)=>{constn=o.db,l=n.getConfig(),{rowHeight:a,paddingY:i,bitWidth:d,bitsPerRow:c}=l,p=n.getPacket(),s=n.getDiagramTitle(),h=a+i,g=h*(p.length+1)-(s?0:a),k=d*c+2,f=$(e);f.attr("viewBox",`0 0 ${k}${g}`),C(f,g,k,l.useMaxWidth);for(const[x,y]ofp.entries())O(f,y,x,l);f.append("text").text(s).attr("x",k/2).attr("y",g-h/2).attr("dominant-baseline","middle").attr("text-anchor","middle").attr("class","packetTitle")},"draw"),O=b((t,e,r,{rowHeight:o,paddingX:n,paddingY:l,bitWidth:a,bitsPerRow:i,showBits:d})=>{constc=t.append("g"),p=r*(o+l)+l;for(constsofe){consth=s.start%i*a+1,g=(s.end-s.start+1)*a-n;if(c.append("rect").attr("x",h).attr("y",p).attr("width",g).attr("height",o).attr("class","packetBlock"),c.append("text").attr("x",h+g/2).attr("y",p+o/2).attr("class","packetLabel").attr("dominant-baseline","middle").attr("text-anchor","middle").text(s.label),!d)continue;constk=s.end===s.start,f=p-2;c.append("text").attr("x",h+(k?g/2:0)).attr("y",f).attr("class","packetByte start").attr("dominant-baseline","auto").attr("text-anchor",k?"middle":"start").text(s.start),k||c.append("text").attr("x",h+g).attr("y",f).attr("class","packetByte end").attr("dominant-baseline","auto").attr("text-anchor","end").text(s.end)}},"drawWord"),j={draw:I},q={byteFontSize:"10px",startByteColor:"black",endByteColor:"black",labelColor:"black",labelFontSize:"12px",titleColor:"black",titleFontSize:"14px",blockStrokeColor:"black",blockStrokeWidth:"1",blockFillColor:"#efefef"},G=b(({packet:t}={})=>{conste=u(q,t);return`
.packetByte{
.packetByte{
font-size:${e.byteFontSize};
font-size:${e.byteFontSize};
}
}
Some files were not shown because too many files have changed in this diff
Show more