mirror of
https://github.com/MoonshotAI/kimi-code.git
synced 2026-08-23 15:46:26 +00:00
179 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
a09d904140
|
refactor(agent-core-v2): migrate agent domains to model-as-container architecture (#3103) | ||
|
|
3d7762003a
|
feat(kimi-code): support two OAuth login endpoints (#2862)
* feat(kimi-code): add China/International region selection for OAuth login
- Add region profiles (cn/overseas) and resolver in @moonshot-ai/kimi-code-oauth:
env override → persisted login host → install-channel marker → default cn
- /login now offers Kimi Code (China) / Kimi Code (International); the CLI
login entries (kimi login, kimi acp --login) accept --region cn|overseas
- Update/plugin/site/telemetry endpoints derive from the selected region;
plugin trust list covers both .com and .ai hosts
- kap-server: POST /oauth/login accepts an optional region; new GET /oauth/region
* fix(oauth): keep an explicit default-slot login ahead of the install marker
A China login persists no oauthHost (the default credential slot carries
no host trace), so after switching back from International the resolver
fell through to a stale overseas install marker. Treat a persisted
default-slot oauth ref (key === oauth/kimi-code) as an explicit-cn signal
that outranks the marker; getRegion() on the v2 side mirrors it.
* fix(agent-core-v2): thread the default-slot key through capability region resolution
Capability installs resolved the region from the persisted oauthHost only,
so an explicit China login (which persists no host) lost to a stale
overseas install marker. Pass the oauth ref key through as well, matching
getRegion(). Also move the region contract notes into the auth.ts file
header per the package comment convention.
* fix(agent-core-v2): honor the region-marker opt-out for the telemetry endpoint
Hosts that set KIMI_CODE_REGION_MARKER=off (the desktop embedded server)
skip the install marker in getRegion(), but the default telemetry endpoint
still consulted it, so a stale overseas marker could split the reported
region from the telemetry destination.
* feat(cli): show region site domains in login platform selector
* chore: reword oauth login changesets
* fix: honor the region marker opt-out in the CLI and capability resolvers
* refactor: rename login region values to mainland-cn and global
* fix: keep the --region help text in English
* fix: simplify the --region help text to site domains
* feat: drop the suggested login platform order
* feat: split a browser-safe region profile table out of the region resolver
* Revert "feat: split a browser-safe region profile table out of the region resolver"
This reverts commit
|
||
|
|
8440801de4
|
feat(agent-core-v2): add the WaitFor tool for waiting on background tasks (#3060)
* feat(agent-core-v2): add the WaitFor tool for waiting on background tasks * fix(agent-core-v2): mark WaitFor deliveries only after formatting succeeds * fix(agent-core-v2): cancel losing waits once the WaitFor race resolves * test(node-sdk): project WaitFor out of the v1-v2 resume parity roster * fix(agent-core-v2): gate WaitFor goal guidance behind the wait_for flag * fix(agent-core-v2): gate WaitFor goal guidance on actual tool availability * fix(agent-core-v2): enforce the wait_for flag at WaitFor execution time * fix(agent-core-v2): consult the live tool policy in the WaitFor availability check |
||
|
|
04944f380a
|
ci: release packages (#2932)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
98ebda840a
|
fix(kimi-code): revert the todo panel to its pre-turn state on undo (#3016)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* fix(kimi-code): revert the todo panel to its pre-turn state on undo * fix(kimi-code): hide all-done todo lists on undo refresh and detach SDK todo state |
||
|
|
3ded08084a
|
fix(protocol): expose turn ended event time (#3011)
* fix(protocol): expose turn ended event time * fix(protocol): expose turn ended event time * chore(changeset): remove patch release entry * test(node-sdk): align background task parity expectations |
||
|
|
2265305e81
|
refactor(agent-core-v2): replace defineOp/Model with Event2 dispatch and replayable states (#2909)
* refactor(agent-core-v2): replace defineOp/Model with Event2 dispatch and replayable states - replace defineOp/Op/OpDescriptor/toEvent and defineModel/defineCheckpointedModel with Event2 subclasses: durable classes declare static durable + schema, serialize() keeps the wire record shape byte-frozen, transient classes stay off the journal - define states via defineState(...).replayable(...).on(Event2, fold): immer produceWithPatches folds with atomic prepare/commit, .undoable() trait drives prompt-submit checkpoints and context.undo, ephemeral kv keys keep imperative set - degrade IWireService to a journal adapter; the agent event dispatcher owns the pipeline (fold -> set -> appendRecord -> publish) and silent restore - align downstream event surfaces: kap-server WS envelope timestamp from event.time, klient event schemas gain time, node-sdk/acp-server/print wiring updated - rewrite gen-wire-manifest/gen-state-manifest for the unified registry and replace the op-uniqueness lint with event-uniqueness * fix(ci): repair Event2 prompt and media projections - restore prompt admission and session media materialization - align transcript, WS, SDK, and replayable media state projections - update affected tests and generated state manifest * fix(ci): update prompt event and projection expectations - update snapshots for the durable prompt.accepted event - normalize prompt.steered media in transcript projections |
||
|
|
59dde734f3
|
feat(agent-core): unify the v1 MCP management plane (#2858)
* feat(agent-core): unify the v1 MCP management plane - McpServerRegistry: one config view over global (layered mcp.json), plugin (manifests, read-only, final effective config), and caller (SDK-injected) servers; name collisions keep both entries. - Write plane: add/update/removeGlobalMcpServer mutate the user-level file and push into live sessions; getGlobalMcpServer returns the effective config; mutations of read-only entries are rejected. - testGlobalMcpServer accepts an inline config; addSessionMcpServer connects a server in one live session with an optional persist flag; reconnect accepts a replacement config and re-resolves via the registry. - One process-wide McpOAuthService shared with every session: obtained_at stamps, offline token state, single-flight and proactive refresh, and credential events. Sessions self-subscribe in the constructor, so even initializing sessions see every event; token writes serialize through the process-local OAuthTokenTransaction per credential identity. - inspectAppMcpServers + locator-addressed begin/complete/cancel/reset cover plugin servers; inspection output redacts env/headers to sorted key lists; locator OAuth ops reject ambiguous shared runtime names. - The legacy auth-status surface reads the registry (offline by default, verify=true probes) and never mutates credentials. - VS Code panel receives source/origin/mutable and hides mutating actions on read-only entries. - v2 client facade in node-sdk mirrors the surface over agent-core-v2 (plugin inventory stays v1-only for now). * fix(agent-core): close the v1 MCP live-session reconciliation gaps Recompute each live session's MCP target from the registry's runtime resolution (enabled plugin > project layer > user file; caller injection shadows everything) behind every config mutation, instead of per-path patching: shadowed file layers recover when a plugin winner is disabled or removed, removing a user-level entry resurrects its project-layer shadow, disabled plugin descriptors no longer block removals, persisted session adds validate against the session's project layer and broadcast to other live sessions, and per-session sync failures are logged with context. Session status entries and read-only management entries now report redacted config views (envKeys/headerKeys instead of literal env/headers values); core-internal reconciliation compares full configs via the connection manager's raw-entry accessor. OAuth: interactive flows are serialized per credential (concurrent begins join the in-flight flow instead of clobbering its PKCE/state), a malformed credential meta sidecar no longer aborts core start, grants inside the refresh-ahead window refresh immediately while far-future grants re-arm through a max-length timer, and the service shuts its timers and flows down with KimiCore/SDKRpcClient close. * fix(agent-core): route the proactive MCP OAuth refresh through the token transaction refreshNow ran its /token request with the SDK default fetch, outside the credential-serializing OAuthTokenTransaction that every other token write uses; a slower response carrying an older rotating refresh token could overwrite a newer grant written by a concurrent transport-side refresh. * fix(agent-core): keep disabled MCP servers out of auth-state classification The unified mcpServerAuthState dropped the previous enabled short-circuit, so a disabled oauth-flagged server reported oauth-required — or was even probed over the network — instead of not-applicable. * fix(kimi-code-sdk): short-circuit disabled MCP servers in the v2 auth-status classifier The v2 parity copy of v1's mcpServerAuthState missed the same enabled guard v1 just regained; a disabled oauth-flagged entry would report oauth-required (or be probed). The parity suite now pins the disabled case on both engines. * fix(kimi-code): refresh the VS Code MCP list with the workspace cwd after mutations The add/update/remove RPCs return a cwd-less management list, so the webview broadcast dropped project-layer entries until the next full load; re-list with the workspace cwd after every mutation instead. * fix(agent-core): keep SDK token saves matched to the OAuth token transaction saveTokens stamped obtained_at onto a fresh object before calling tokenTransaction.save, so it never matched the exact payload the transaction recorded for a grant fetch; the consume path was dead and every save re-wrote. Between the fetch and the SDK callback an intervening clear could then be overwritten — the resurrected grant came back after a reset. The write callback stamps the durable record instead. * fix(agent-core): reject ambiguous legacy name-based MCP auth lookups The legacy begin/reset auth RPCs took the registry's first name match, silently starting OAuth for one entry of a runtime-name collision while the locator path refused the same ambiguity; align them on the shared uniqueness rule and point callers at the locator-addressed variants. * fix(agent-core): propagate registry errors during live-session MCP sync resolveMcpRuntimeTarget collapsed every registry failure into "no target": a project config file that turned malformed mid-session made sync treat a still-configured server as gone (tearing down the live connection) and made config-aware reconnects report "no longer configured" instead of the actionable config error. Absence still resolves to undefined; malformed config now propagates — per-session sync logs and keeps the entry, and reconnect surfaces config.invalid. * fix(agent-core): close the remaining registry-error and ambiguity gaps The management guard lookup mapped every registry failure to "absent", so a malformed project config let a persisted session add write a user-level entry over an unknown state; only not-found is a miss now. And the name-only connection test now shares the auth paths' uniqueness rule instead of probing the first match of a runtime-name collision. * fix(agent-core): probe the enabled MCP entry under a disabled-name collision The name-only connection test counted enabled matches for its ambiguity guard but still probed the first registry match, and the file layers list before plugins. With a disabled file entry shadowing an enabled plugin of the same runtime name, Test probed the disabled entry instead of the one a live session would run. Select the sole enabled match, falling back to the first entry only when every match is disabled so it reports as disabled. * fix(agent-core): let session-local MCP adds shadow plugin entries Caller injection shadows every registry source at session start, plugins included, and reconciliation leaves caller entries untouched; the live non-persist add path rejected plugin-owned names anyway, so SDK clients could not apply the same per-session override without a restart. Gate the plugin-source rejection on persist: session-local adds connect as caller, while persisted adds stay rejected as user-level writes behind a read-only owner. * fix(agent-core): normalize session MCP names before connecting The persisted store trims server names, but addSessionMcpServer used the raw name for the live connect and cross-session reconciliation: a padded name persisted under the trimmed key while the requesting session ran and reconciled the raw one, and a blank name connected with no identity at all. Normalize once up front (rejecting blank) so the store write, the session entry, and reconciliation agree on the same server. * fix(agent-core,node-sdk): close the collision-selection and probe-freshness gaps The legacy name-only auth resolver started from the first registry match, so a disabled file-layer shadow plus an enabled plugin of the same runtime name was misread as an ambiguity conflict; select the sole enabled match before judging ambiguity, exactly like the test probe path. On the v2 client, addSessionMcpServer connected the raw name while the store wrote the trimmed key — normalize once for both, and route the verify-triggered auth probes through the per-call OAuth service instead of the cached one whose providers snapshot tokens at construction, so a grant saved after the first probe is honored. * fix(agent-core): normalize global MCP mutation names and guard disabled reconnect swaps The global add/update/remove mutations guarded and reconciled with the raw server name while the store persisted the trimmed key, so a padded name left live sessions unreconciled and could slip past the plugin read-only guard; normalize once before lookup, persistence, and reconciliation. And a config-carrying reconnect assigned the replacement before the disabled check fired, leaving a connected entry that reported the disabled config; reject disabled replacements before mutating, keeping the same error. * fix(agent-core): skip proactive refresh while an interactive flow owns the credential refreshNow reset the shared provider's flow state before and after the token request; when a proactive timer (or a manual refresh) fired while beginAuthorization was waiting on the browser callback for the same store key, that wiped the redirect URL, PKCE verifier, and state the in-flight flow needed — complete() then failed the exchange even though the user authorized. Refresh now skips when an interactive flow is active for the credential: the flow delivers fresh tokens on completion, and the 401 transport path is the backstop if it fails. * fix(agent-core): allow global MCP adds over disabled plugin descriptors A disabled plugin entry is absent from the runtime target, but the read-only guard still treated it as the owner, so a user-level fallback could only exist if it predated the plugin disable. Relax the shared guard: disabled plugin descriptors never block mutations (disabled project entries still shadow the user file and keep their rejection). * fix(node-sdk): close the v2 session-MCP parity gaps A v2 reconnect with an explicit enabled:false replacement config used connect()'s upsert semantics — closing the live client and reporting success where v1's manager reconnect rejects before applying anything; reject disabled replacements up front with the same error. And a persisted v2 session add never consulted the workspace config, so a same-named project-layer entry was silently shadowed: the user-level write never takes effect while the direct workspace-manager upsert displaces the project config for every live session. Resolve the workspace layers and reject like v1's read-only rule. * fix(agent-core): keep __proto__-named MCP servers through config parsing A z.record() parse rebuilds its output via property assignment, so a server literally named __proto__ hit the prototype setter and vanished before validation; the layer merge then repeated the same trap with plain object accumulators. Parse the server map entry-by-entry over the JSON own keys and accumulate into null-prototype maps, so session startup and the unified registry keep the declared server and its origin. * fix(node-sdk): begin v2 MCP auth against a fresh OAuth service The v2 begin path ran through the cached globalMcpOAuth, whose providers snapshot tokens at construction: a grant another process saved (or reset) after that cache materialized was invisible, so begin could open a browser flow over a valid grant, or report already-authorized off a removed one. Build the service per call — the read path and the verify probes already do — and route the status list through the same helper. The test fixture grows a real token endpoint honoring one rotating refresh token; the regression fails against the cached-service implementation on v2. * fix(agent-core): broadcast SDK-driven MCP token invalidations to live sessions * test(agent-core-v2): give the no-op reconnect test runtime plumbing The branch added the case against a bare McpConnectionManager, but #2961 made stdio connects resolve the runtime through runtimeResolver, matching every other case in the file. |
||
|
|
d833a1a893
|
feat: engine-native image references via kimi-file:// media resolver (#2593)
* feat: engine-native image references via kimi-file:// media resolver
* fix(agent-core-v2): regenerate state manifest for media resolver rename
* feat(agent-core-v2): add audio MediaKind and tag/ref fold helpers to media ref contract
* fix(agent-core-v2): synthesize image path tag when degrading bare file references
* fix(agent-core-v2): scrub dangling alias re-exports in contract type generator
* feat(transcript): project paired media tag+ref as single attachments in read models
* fix(kimi-code): fall back to inline image when cache write fails after upload
* fix(agent-core-v2): pair media path tags with refs by adjacency and path, keep unpaired tags
* fix(kap-server): fold media tag+ref pairs out of prompt snapshot projection
* fix(kap-server): list attachment-only prompts as empty user messages
* fix(kap-server): keep live attachment ids across transcript overlay and heal
* fix(kap-server): keep promptAttachments off the legacy session event wire
* fix(kap-server): inherit the backfilled turn header on mid-turn terminal projection
A projector that attached after turn.started built the terminal turn.upsert
with an empty header, and the whole-header replace downstream wiped the
backfilled origin / prompt / attachmentIds — only the debounced best-effort
heal could restore them. Fall back to the producer store's seeded header
(via a new optional ProjectorLookups.turn) when currentTurn misses, and
cover the mid-turn attach path with a service-level regression test.
* refactor(agent-core-v2): move media ref contract out of kosong into agent/media
The kimi-file:// daemon reference grammar, media path tags, and the tag/ref
fold are engine-internal conventions, not provider-wire contract; keep
src/kosong untouched. Root exports and SDK re-exports are unchanged.
* feat(agent-core-v2): materialize prompt media into the session media dir
Pasted and uploaded media now materialize under the session's own media/
dir instead of the shared cache, so the copies follow the session's
lifecycle: fork carries them along, session deletion cleans them up.
A new Session-scope ISessionMediaStore owns the dir: atomic tmp+rename
materialization with a unified extension policy, and canonical-vs-hint
display-path resolution. The persisted ?path= is a write-time snapshot —
readers prefer the session-canonical location, so fork and home relocation
never hand the model a dead path. Prompt intake normalizes every daemon
reference through the single enqueue funnel (REST edge, SDK prompt/steer,
gateway), serialized in arrival order to keep the FIFO across the async
file I/O. The kap-server edge materializes through the same store with a
shared-cache fallback, and the request-time resolver refreshes stale
persisted and memoized path tags; a claimed video reference degrades to
its tag alone instead of duplicating it.
* fix(agent-core-v2): take prompt media intake off the enqueue critical path
The record now joins the FIFO synchronously and its daemon-ref intake runs
as a per-record promise, awaited by the launch and steer paths before the
message is consumed — queue order, list/abort visibility, and prompt
submission latency no longer wait on file I/O, and a slow intake no longer
head-of-line blocks later prompts. The launching record is tracked so abort
and clear stay reachable inside the launch window; startNext re-checks
cancellation after every await (intake race, hook, turn admission), a
cancelled record is never re-queued, and a compaction requeue waits for
onDidFinishCompaction instead of busy-looping the scheduler.
* fix(agent-core-v2): record the claiming ref in the media path-tag pairing
pairMediaPathTagRefs now exposes claimingRefByTagIndex, and claimingRefIndex
reads it instead of recovering the claimer by path equality — which
mis-attributed a tag when two different fileIds carried the same path in an
interleaved sequence, breaking the pair and leaking the tag as user text.
Also covers the memoized-video-tag claimed-drop branch.
* fix(transcript): fold upload pairs in user-slash turns and pin pairing parity
The cold rebuild's user-slash branch now folds the turn-opening input like
any user turn (claimed tag out of the prompt text, one attachment entity),
matching the live projection. The ref extraction is consolidated into the
contract module (daemonFileRefFromPairingPart, the mirror of the engine's
daemonFileRefFromPart) and the mirror carries the new claimingRefByTagIndex
map. A new kap-server parity test imports both implementations and asserts
identical pairings over shared fixtures, so the engine/mirror pair can no
longer drift silently.
* fix(kap-server): fold upload media tags out of the search index
The global search indexer concatenated every text part of a persisted user
message, so the upload pair's <image path> tag made pure-image prompts
searchable and wrote the materialization path into the index — breaking the
module's documented pure-image invariant and diverging from the live route.
textOfContent now folds the pair like every other read model (with a
fold-safe coercion for malformed wire parts). Also pins the prompt-media
cache-dir fallback with a read-only session media dir test (skipped as root).
* feat(node-sdk): re-export the media fold helpers and cover the v1 uploadFile rejection
foldMediaPathTagRefs and matchSingleMediaPathTag join the daemon
file-reference helper re-exports so hosts can fold the upload tag+ref pair
without importing agent-core-v2; the v1 harness's uploadFile not_implemented
rejection is pinned by a test.
* fix(kimi-code): fold upload pairs in replay/export and keep media tags atomic in steer input
Resumed-session replay rendered the upload pair raw — the <image path> tag
as user text and the kimi-file:// url as an XML-ish reference — and the
markdown export leaked the tag into both the turn body and the overview
topic. contentPartsToText and the exporter now fold the pair, and daemon
references render as a bare [image]/[video] placeholder. combineSteerInput
moves to tui/utils/steer-input and no longer merges a standalone media tag
into adjacent text, which would have broken the engine-side pairing for
steered image messages.
* fix(kimi-code): drop the steer separator before a leading media tag
A queued pure-image message opens with a standalone `<media path>` tag,
which combineSteerInput keeps atomic. With the previous item ending in a
media part, the '\n\n' separator landed as a stranded whitespace-only text
part between the media part and the tag, normalizePromptInput rejected the
steer, and the already-cleared queue lost the messages. Treat a leading
standalone tag as media so the separator is dropped there.
* fix: clean staged media lifecycle
* refactor(agent-core-v2): narrow the mediaRef root exports and drop a deprecated alias
* fix: keep staged media alive through turn
* fix(agent-core-v2): reject non-upload ids at the session media store
A daemon reference's fileId becomes a storage key in the session media
store, but only the file domain validated the id shape — a crafted
kimi-file://<id> reaching the request-time resolver's canonical-read
fallback could traverse out of the session media dir. Share the file
domain's id regex and guard every store entry point: reads miss,
materialize declines, and the display path falls back to the hint.
* fix(kap-server): project steered prompt content without leaking daemon refs
prompt.steered published the raw engine content parts — kimi-file://
refs carrying the absolute materialization path plus the paired
<media path> tag — to both the legacy session_event wire (whose schema
declares the protocol content shape) and the transcript prompt entity.
Route both through one shared prompt-content projection: the upload
pair folds into a single {kind:'file'} part, matching the REST prompt
list and the no-path-leak rule every sibling surface already follows.
* refactor: align daemon-ref naming and drop a duplicate re-export
The deprecated videoResolverService alias also re-exported
mediaResolvedKey, which made the package root's star exports ambiguous
and silently dropped the name. The new transcript contract mirror now
uses the canonical daemon-ref vocabulary instead of the deprecated
kimi-file spelling.
* test(agent-core-v2): pin image abort rethrow, video canonical read-through, release-once
Mirror the video abort contract on the new image path (an aborted read
cancels the request instead of degrading to a tag), cover the video
fallback that uploads the session-canonical bytes after the transient
upload is released, and assert the staged-upload release fires exactly
once on the intake success path.
* fix(kimi-code): bind goal-steer staging leases to the running turn
sendMessageInternal read the turn context only after beginSessionRequest
had cleared it, so a steer buffered into a running goal turn never got
its staging lease bound — the staged daemon upload and cache copies
lived until session close instead of being released at the consuming
turn's end. Capture the live turn id before the reset (only while a
turn is actually streaming; the id outlives its turn otherwise).
Also move the staging-lease state machine off the KimiTUI coordinator
into a self-contained StagingLeaseTracker with injected effects, drop
the duplicate media-tag builder in image-placeholder in favor of the
SDK helper, and fix the paste-in-flight comment to match the gate's
real granularity.
* fix(kap-server): project prompt.queued content without leaking daemon refs
The broadcaster projected prompt.steered and stripped turn.started
attachments but forwarded prompt.queued raw, leaking kimi-file:// URLs
and absolute materialization paths to every subscribed WS connection
and the journal. Fold the tag+ref pair into a {kind:'file'} part, same
as steered.
* fix: keep compressed uploads retrievable and close the steer abort window
Two review fixes around prompt media intake:
- The compressed re-save was released right after intake (and carried a
1h expiry) while every client read model projects its file id,
leaving historical compressed images unfetchable. Keep the re-save as
an ordinary upload; roll it back only when preparation or submission
fails before the engine takes the prompt. The engine's
PromptInput.release hook loses its only producer and is removed.
- A prompt aborted while its steer awaited the loop's step assignment
was flipped back to 'steered' and its content could still
materialize into a later turn. Re-check the reservations after the
assignment await and abort the undispatched request when the check
fails.
* perf(agent-core-v2): memoize inlined image parts across request steps
A successful image inline depends only on the immutable upload bytes, so
it is memoized per file id (size-bounded) in media.resolved and reused
across steps, retries, and media-recovery reprojections instead of
re-reading and re-encoding on every request. Degrade forms are never
memoized since they depend on the message's tag pairing. Also make the
never-empty message placeholder kind-aware (video vs image).
* refactor: author media tag+ref pairs in the engine prompt intake
Edges (TUI, kap-server REST) now submit bare kimi-file references and the
engine intake materializes the bytes, synthesizes the paired media path
tag, and falls back to the shared cache dir when the session store is
unavailable, replacing per-edge pair construction and duplicate
materialization copies.
Thread the prompt id from submission through to turn.started (REST
prompt_id, WS event, SDK prompt option) so the TUI binds staged-media
leases to turns exactly; the origin heuristic stays as fallback and
ambiguous claims now surface a staging_lease_invariant telemetry warning.
Also lands the pending resendable-extraction fix for cache-hint resubmits
after a session switch.
* fix: decouple media persistence from prompt intake
* refactor(agent-core-v2): project the turn prompt in a single fold pass
* test: slim redundant media-ref coverage across layers
Fold duplicate pinning of the same media tag+ref rules into shared
helpers and it.each tables, and drop assertions that restate behavior
already covered at another layer:
- drop the kimiFileUrl alias describe (mediaRef.test.ts covers the
aliased functions with more cases)
- drop pairMediaPathTagRefs describe in favor of the parity fixtures
- merge the identical prompt.steered/prompt.queued broadcast tests
- parameterize the resolver degradation matrix and prompt intake
fixtures (enqueueMedia/gatedImage/expectMediaPair helpers)
- drop REST-level context-memory pairing assertions (engine-level
intake tests pin the same shapes); keep the caption->system-reminder
assertion, the only cover of extractCompressionCaptions
- drop the turn-finish-during-intake steer-cancel vector and the
switch-session release driver test (unit-level lease tests remain)
Net -762 lines; 645 tests green across agent-core-v2, kap-server,
transcript, node-sdk, klient, and the TUI.
* chore: fix oxlint warnings introduced by image-file-ref changes
* fix: harden image file reference lifecycle
* fix: close image reference lifecycle gaps
* fix: preserve session media paths on replay
* chore: streamline image-file-ref changesets
* refactor: make daemon media references self-contained, dropping tag+ref pairing
A daemon-ref media part now carries everything a read model needs — the
kind from the part type and the materialization path from the reference's
`?path=` — so prompt intake no longer authors a paired `<media path>`
tag, and the pairing/fold machinery (pairMediaPathTagRefs /
foldMediaPathTagRefs and their mirror copy) is deleted across the engine,
transcript, kap-server, node-sdk, and the TUI. The request-time resolver
synthesizes the degrade tag from the reference path whenever bytes cannot
reach the provider. Standalone tags stay user-visible text, and never
reach the search index or prompt metadata.
* fix: reconcile image file references with main after rebase
Main removed the agent RPC aggregation layer (agent/rpc) and moved
LifecycleScope to app/scopes. Fold the branch's RPC-side behavior into
the new structure: PromptPayload carries promptId/disabledTools, and
AgentPromptService.submit admits the client-chosen id through the
reservation (duplicate rejects before any session state changes) and
applies the denylist through toolPolicy. Regenerate the wire/state
manifests.
* fix(kimi-code): run paste ingestion in the background, wait bounded at submit
The paste callback awaited compression + original persistence + the
daemon upload while CustomEditor queued every keystroke, so a slow
ingestion stalled all typing. Settle the callback once the placeholder
lands and track the rest as ImageAttachment.pending; the send path gives
a referenced pending ingestion a bounded wait (2s) so paste-then-Enter
still submits the compressed/daemon-ref form, and falls back to the
inline form when ingestion has not finished. Media-free submits stay
fully synchronous.
* fix(protocol): mirror prompt_id in the shared prompt submission schema
kap-server's local REST schema accepts a client-chosen prompt_id, but
the shared promptSubmissionSchema stripped it as an unknown key, so
clients validating through @moonshot-ai/protocol lost the id and the
turn.started promptId correlation never matched.
* fix(klient): normalize file-store errors to public RPC errors on both transports
The fileService save/get wire adaptation ran outside the dispatcher's
error normalization, so a stale or expired upload id surfaced as the
engine's raw Error2 on the memory transport and as a generic 50001 on
ipc. Map file.not_found to the public NOT_FOUND RPCError in the shared
dispatcher so both transports reject identically, and pin the parity in
the conformance suite.
* fix(agent-core-v2): keep launching media prompts visible in the queue snapshot
startNext shifts the launching record out of pending before its media
intake settles, so list()/GET /prompts reported neither an active nor a
queued prompt during the intake window even though the submission was
accepted and abortable. Report the launching record as still queued,
matching the prompt.queued event already published for it.
* fix(node-sdk): strip internal promptAttachments from SDK turn.started events
The in-process v2 event mapper forwarded the whole domain event, so SDK
session.onEvent consumers saw the transcript-projection-only
promptAttachments field that kap-server explicitly strips from the WS
wire event. Drop it in the mapper so both consumers share the same
turn.started field set.
* fix(kimi-code): align staging lease id multiplicity with retain count
A lease's flat id list conflated two cases: one submission referencing
the same image twice (one retain) and a batched steer merging two queued
messages sharing the image (two retains). Occurrence-wise release
over-consumed in the first case and batch-wise release would
under-consume in the second. Dedupe each extraction's ids at the lease
creation sites so list multiplicity always equals the retain count, and
release one retain per occurrence.
* fix(agent-core-v2): check video_in before honoring memoized video uploads
The video memo hit path returned a cached ms:// part before the current
model's capability check, so switching to a same-provider model with
video_in:false sent a video part the model cannot accept instead of
degrading to the path tag. Gate on capability first, mirroring the image
strategy.
* fix(kimi-code): keep recalled queued media staged instead of releasing it
Recalling a queued media prompt into the editor is not a discard, but
the recall path released the staged files: image attachments lost their
daemon upload (resubmit silently downgraded to inline), and a recalled
video's cache copy was deleted even though re-materialization needs a
source that may already be gone. Recall now consumes only the retain
(the next submit re-retains), retires the cache copy to session
lifetime, and rebases the video attachment onto that copy.
* fix(agent-core-v2): count launching media prompts in prompt.queued queueLength
startNext shifts the record into launchingItem before publishQueued
computes the count, so a media prompt's prompt.queued reported
queueLength 0 even though the prompt is accepted, abortable, and listed
as queued. Compute the count from the same snapshot list() exposes.
* refactor(agent-core-v2): drop the session media shared-cache fallback
Intake keeps the upload-backed reference when the canonical write fails
instead of double-writing into an unowned global cache scope; the session
media store's reads collapse to the canonical scope, and non-filesystem
deployments no longer write every media blob twice.
* refactor(agent-core-v2): stop persisting materialization paths in daemon file references
The kimi-file:// reference persisted in context memory bundled a durable
identity (fileId) with a perishable machine-local absolute path (?path=),
which forked sessions and home relocations would stale. The reference now
carries only the file id; the display path is derived from the session
media store by file id at read time. Parsers tolerate and strip the legacy
?path= query so old records keep resolving.
* fix(agent-core-v2): skip atomic-write temp siblings in session media by-id resolution
The fs backend stages atomic writes at <key>.tmp.<pid>.<hex> next to the
target key, and the media store's prefix-listing predicate matched them, so
a lookup racing an unfinished materialize could return the partial copy as
the canonical file.
* fix(kimi-code): close the staging-lease gap between extraction and dispatch
Create the staging lease right after extraction so every pre-dispatch exit
releases through the tracker: validation/session failures release it,
queueing defers it to the queue item's raw ids/paths, and the cache-hint
stash takes over ownership. A forgotten exit now degrades to an unclaimed
lease swept at session close instead of a permanently retained upload.
The cache-hint restore exits (dismiss, chained restore, session switch
during fetch, failed compact/new-session) previously returned only the
text to the editor, leaking the extraction's retains and staged cache
copies. They now go through queue-recall semantics: retains are consumed,
staged copies retire, and recalled videos rebase onto them.
* fix(agent-core-v2): bound the inline image memo with a private byte-budgeted LRU
A memoized inline image part pins a multi-MB base64 string, and the agent
state registry's snapshot/inspect path serializes every registered state
in full — so the memo no longer lives in agentState. It is now a private
per-file-id LRU with the existing 8MB per-entry cap plus a 64MB total
budget; eviction simply re-reads the bytes on the next request. The video
memo stays in agentState.
* fix(kap-server): fall back to the staged upload on the session media route
Prompt intake materializes bytes into the session media store
asynchronously and best-effort, but a session_media ref is projected to
clients as soon as the prompt is queued — so the download route could 404
during the intake window, and forever after an intake failure. The route
now reads the canonical session store first and falls back to the App-scope
staged upload, adapting it to the same served shape; only a double miss is
a 404. The header note also records that resolving the store resumes cold
sessions, an accepted short-term semantic with a TODO for a cold-read
channel.
|
||
|
|
61591bce09
|
feat(agent-core-v2): bundle multiple skill activations into one prompt submission (#2934)
* feat(agent-core-v2): support grouped multi-skill prompt submissions Add IAgentSkillService.promptWithSkills: one or more skill activations are validated up front (an unknown or empty submission rejects with no side effects), recorded with a shared submissionId, and enqueued ahead of the prompt through the prompt queue's messagesBefore support, so the whole group materializes atomically as a single turn. Undo cuts, the transcript projection, and the undo precheck treat the group as one unit (stopping at the next anchor even when submission ids collide); hook-result messages are skipped like injections during those walks. Submit hooks run against every message of the group, and user-slash skill activations count as user-submitted content for the UserPromptSubmit hook's origin filter. Surface it through the contract layers: protocol gains submissionId on the user / skill_activation origins and on the skill.activated event (kap-server zod mirrored), klient exposes agentSkillContract.promptWithSkills with parity assertions, and the SDK grows session.promptWithSkills — implemented on the v2 engine and rejecting loudly on the deprecated v1 engine, which is otherwise untouched. * fix(agent-core-v2): reject empty skill lists in grouped prompt submissions - Validate that promptWithSkills receives at least one skill, enforced in the engine and as a non-empty constraint in the klient wire schema. - Restore the released versions and changelog sections for agent-core-v2, klient, and node-sdk that the branch cut had reverted. - Move statement-level narration into the owning file headers per the package comment conventions. - Align the hook-result undo tests with the reachable record ordering (hook results are recorded before the group materializes). * refactor(agent-core-v2): bundle grouped skill activations into the prompt message Replace the submissionId-correlated message group with a single bundled user message: the rendered skill blocks precede the caller's parts in the content, and every activation's metadata rides the prompt origin's new skillActivations field. The bundle is one anchor by construction, so undo needs no group-cutting logic and the messagesBefore prompt seam disappears; the submit hook fires once per submission. skill.activated still fires per skill (transient ops, live-only); resume rebuilds the per-skill view from the prompt origin. Contract chain (protocol, kap-server, klient, node-sdk) drops submissionId accordingly. * fix(agent-core-v2): keep bundled skill blocks out of prompt-facing projections - The transcript cold rebuild expands a bundled prompt's origin skillActivations back into per-skill markers (the live path already projects them from skill.activated events). - turn.started.prompt, the session title excerpt source, and the fork lastPrompt now derive from the caller's own parts, excluding the rendered skill blocks the engine prepends to the bundled content. - Drop the redundant undefined unions from the new origin fields. - Move the activateSkill test narration into the file header. |
||
|
|
84da6629b1
|
refactor(agent-core-v2): decouple workspace from session DI via runtime binding (#2961)
* refactor(agent-core-v2): decouple workspace from session DI via runtime binding * fix(agent-core-v2): unblock session external hooks and scope workspaceMcp seeds - externalHooksService: inject App-level ISessionManager instead of the unregistered ISessionLifecycleService so SessionStart/SessionEnd hooks actually activate in production; keep sessionId matching and tolerate absent lifecycle events - workspaceMcpService: ignore onWillCreateSession events whose session belongs to another workspace, preventing cross-workspace ISessionMcpHandle seed overrides - update externalHooks integration tests, agent harness, and workspaceMcp tests; add reloadSources coverage in skillCatalog tests * fix(agent-core-v2): honor the bound runtime in prompt context, swarm spawn, and ACP sessions - map system-prompt cwd, directory listing, and additional dirs through RuntimeWorkspaceView, and skip the listing when the bound runtime has no fs capability - pass the caller agent's runtime binding to AgentSwarm child creation and prompt-prefix execution instead of hardcoding local - expose the ACP client filesystem through the ACP session runtime and build its shell/path environment from the probed host instead of hardcoded Linux - dispatch klient facade createChild to sessionManager.createChild so child sessions keep their parent markers * fix(agent-core-v2): resolve routed fs and tool paths with runtime path semantics - WorkspaceFsService resolves via the bound runtime's RuntimePath (extended with basename/dirname) instead of node:path, so mapped roots such as C:\\repo stay runtime-local. - Read/Write/Glob/Grep pass skill roots through mapRoots via RuntimeWorkspaceView input, matching Edit. - acp-server unbinds session runtimes on session/close, not only on delete. - apps/kimi-code drops the /runtime slash command; SDK runtime methods stay. * fix(agent-core-v2): retire idle session controllers, untrack disposed runtime resources, and rebuild fs watches on generation replace * fix(agent-core-v2): resolve oxlint errors in runtime lifecycle fixes * fix(kap-server): untrack download stream from runtime generation on completion * fix(kap-server): drop meaningless void operator on tracked dispose |
||
|
|
f492cd7c9e
|
feat(agent-core): add tower command to orchestrate multi-agents (#2633)
* feat(packages): implement cowork feat(packages): update throttle control feat(agent-core): rename to /tower feat(agent-core-v2): support tower mode fix(packages): keep tower teardown from stranding submodule worktrees A plain `git worktree remove` refuses worktrees containing initialized submodules even when they are clean, so tower teardown silently left behind exactly the worktrees whose workers had run builds (the failure only reached the tool report, never the activity log). The dirty check is the data-loss gate; once it passes, removal always passes --force (harmless on a clean worktree, and precisely what bypasses git's submodule refusal). Kept and failed removals now also land in the activity log as worktree.keep / worktree.remove.failed. feat(packages): allow the tower to AskUserQuestion, workers still cannot The tower-mode AskUserQuestion deny only ever fired on the tower itself: workers never enter tower mode, and their tower-worker profile simply does not list the tool. Drop the deny so the tower can clarify requirements with the human up front; workers and reviewers stay ask-less and escalate via TowerSend. Auto permission mode still disables AskUserQuestion for everyone. fix(agent-core-v2): import LifecycleScope from #/app/scopes main moved the enum out of #/_base/di/scope; follow the new location in the two tower services. test(agent-core-v2): refresh fullCompaction token expectations main's #2699 counts compaction tokens on the full-request basis, so the tower tool schemas (default registry) and the /tower skill catalog entry (system prompt) shift the pinned numbers: +2789 with the default tool set, +173 with the explicit harness tool list. The 20k-window test keeps its shape with a 22k window so the post-compaction floor still fits. feat(agent-core-v2): tower command support secondary model fix(tower): disable todo-list tool feat(tower): reviewer keep primary model fix(tower): tower worker call for authroization update * refactor(tower): drop agent-core-v1 version * feat(tower): remove builtin.ts * fix(agent-core-v2): verify the recorded base branch before tower merges * fix(agent-core-v2): activate tower missions only after a successful spawn * chore(kap-server): correct the search-service activation comment * fix(tower): allowActivationWhileBusy for all skill * update * update --------- Co-authored-by: konghuanjun <konghuanjun@moonshot.ai> |
||
|
|
13d86f8b7b
|
ci: release packages (#2881)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
7475c2e2e3
|
feat(vscode): switch the extension to the v2 engine with a rollback switch (#2916)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
The extension now runs on the agent-core-v2 engine by default. The interface, sessions, and workflows do not change. Two rollback paths exist, and one function makes the decision (config/vscode-settings.ts): - the kimi.useAgentCoreV1 setting (temporary; a window reload applies the change); - the KIMI_CODE_LEGACY_FLAG environment variable, which wins over the setting and has the same semantics as in the CLI. An engine startup failure shows an explicit error that names the rollback setting. There is no silent fallback. CI runs the extension test suite on both engines: the sharded run covers the default v2 engine, and a new test-vscode-legacy job reruns the suite with KIMI_CODE_LEGACY_FLAG=1. To keep the v2 path identical to v1 for every method the extension uses, this change also completes the v2-backed SDK client and the v2 engine: - Implement session deletion in the v2 SDK client. - Implement fork truncation at a turn index in the v2 engine, with the same rules as v1, and reject a fork while the source session has an active turn. - Stop the session-level /init run when the turn is cancelled, as v1 does. - Read session metadata without the archived field as not-archived, so sessions written by the v1 engine open correctly. The SDK parity suite now covers session deletion, cancel, and fork truncation. The known-difference list for the methods the extension uses is empty. |
||
|
|
741708f948
|
feat(kap-server): add plugin marketplace and capability REST routes (#2868)
* feat(agent-core-v2): surface a machine-key note from capability installs
CapabilityEntry.install now resolves an optional note exposed through
CapabilityInstallProgress.note (wire-visible). The webbridge entry
returns 'user-skill-migrated' when it migrates a pre-existing
standalone skill copy onto the plugin-managed one — clients can
localize the migration instead of the skill silently disappearing
from the user's directory.
* feat(kap-server): add plugin management and capability REST routes
Expose the App-scope plugin and capability services over the wire so
non-CLI hosts (desktop, web) can manage plugins and built-in
capabilities end to end:
- GET /api/v1/plugins, POST /api/v1/plugins {source},
POST /api/v1/plugins/{id}:{enable,disable,remove}
- GET /api/v1/plugins/marketplace — catalog (pluginMarketplaceUrl
server option / KIMI_CODE_PLUGIN_MARKETPLACE_URL env / production
default) merged on demand with live install state; updateAvailable
only on strict semver catalog > installed (no semver dependency)
- GET /api/v1/capabilities, GET /api/v1/capabilities/{id},
POST /api/v1/capabilities/{id}:install with client-polled progress
- New wire codes 40418 capability.not_found, 40419 plugin.not_found,
40923 capability.install_in_progress, 40924 capability.unsupported
Mutations flow through IPluginService, so they serialize with other
install paths and fire onDidReload (session skill catalogs and the
capability shelf-install hook converge).
* fix(kap-server): map plugin input errors to 4xx and correct the unsupported test code
- mapPluginError now translates the domain's validation.failed (40001)
and fs.path_not_found (40409) instead of collapsing client-fixable
input mistakes (relative source, nonexistent local path) into a
50001 internal error
- the non-macOS capability install test expected 40923, which this
branch assigns to capability.install_in_progress; the unsupported
code is 40924 (macOS runners skip the case, which is why it only
fails on Linux/Windows CI)
* fix(kap-server): resolve catalog-relative marketplace sources and widen the unsupported-test skip
- The production CDN catalog carries sources relative to the catalog
URL (./official/*.zip); clients handing them back to POST /plugins
would hit the local-path normalizer's 40001. Resolve entry sources
against the configured catalog URL so every returned source is
directly installable.
- The 40924 install-rejection test only skipped macOS, but kimi-cu is
also supported on Windows x64 — running it there would start the
real installer. Skip on every supported platform.
* fix(kap-server): accept the legacy url/downloadUrl marketplace source aliases
Custom catalogs that the CLI already accepts can carry an entry's source
under url or downloadUrl instead of source; the route's strict schema
rejected the whole catalog with 50001. Normalize the aliases before
validation (same precedence as the CLI parser) so those catalogs keep
working through /api/v1/plugins/marketplace.
* fix(kap-server): support local marketplace catalogs and drop conditional spreads
- KIMI_CODE_PLUGIN_MARKETPLACE_URL accepts a plain path or file://
catalog in the CLI loader; the route only fetched over HTTP, so local
catalogs 50001'd for desktop/web hosts. Read local catalogs from disk
and resolve their relative sources against the catalog's directory.
- Replace the marketplace mapping's conditional spreads with direct
possibly-undefined properties per the repo rule.
* fix: surface capability install notes through klient and convert file:// entry sources
- The klient capabilities contract omitted install.note, so zod parsing
stripped it and facade callers (node-sdk, TUI) never saw
'user-skill-migrated'. Add the field and pin it in the facade test
fixture.
- A marketplace entry source given as a file:// URL fell through to the
relative-branch and came back as a garbage path; convert with
fileURLToPath so the advertised source stays installable.
* test(kap-server): keep the new route tests portable to Windows x64
- The capabilities list assertion treated every non-macOS host as
unsupported, but kimi-cu is supported on Windows x64 — derive the
expectation from the same platform predicate.
- file:///abs/... is not a valid absolute file URL on Windows (no drive
root); build the fixture with pathToFileURL from a temp path instead.
* refactor: align the capability note and test helper with repo conventions
- agent-core-v2 keeps explanatory docs in the top-of-file block only;
the note contract already lives in the capability types header, so
drop the two member-level doc blocks.
- The plugins route test helper sets the optional fetch body directly
instead of via a conditional spread.
* fix(kap-server): expand ~ in local marketplace catalog paths
The CLI loader expands ~/ against the home directory; the route read
the path literally, so KIMI_CODE_PLUGIN_MARKETPLACE_URL=~/catalog.json
50001'd for desktop/web hosts while working in the CLI. Share one
localCatalogPath helper (file:// conversion + tilde expansion) between
the catalog read and the relative-source resolver.
* fix(kap-server): expand home-relative marketplace entry sources
A catalog entry with source '~/...' fell through to the catalog-relative
branch and came back as <catalog-dir>/~/... — unresolvable by POST
/plugins. Expand ~ via the shared helper before the absolute/relative
decision.
* fix(kap-server): match CLI field semantics for source aliases and stub the Windows home
- A blank or non-string source no longer shadows the url/downloadUrl
aliases; the first valid (non-blank, trimmed) of source/url/downloadUrl
wins, mirroring the CLI parser's stringField.
- The tilde test also stubs USERPROFILE so os.homedir() resolves to the
fixture home on Windows runners.
* fix(kap-server): read a blank marketplace tier as missing
The CLI parser trims tier and treats a blank as absent (third-party);
the route's enum rejected the whole catalog with 50001. Normalize the
tier alongside the source aliases in the same preprocess.
* fix(kap-server): derive marketplace versions from GitHub release sources
Entries that omit version but encode it in a GitHub release/tag (or
tree/commit) source never surfaced updateAvailable. Derive the version
from the resolved source — same URL shapes as the CLI parser, validated
with the route's strict x.y.z rule (no semver dependency).
* fix(kap-server): fail catalog validation on a source with no usable value
A whitespace-only source with no valid alias passed z.string().min(1)
untrimmed and resolved against the catalog URL into nonsense. Drop the
key during normalization so the schema reports the entry as missing its
source (same outcome as the CLI's 'must define source').
* fix(kap-server): resolve latest versions for bare GitHub marketplace entries
A catalog row whose source is a bare GitHub repo (the production curated
rows are shaped this way) kept version undefined, so updateAvailable
never fired for exactly the entries most likely to update. Resolve the
latest release tag through the /releases/latest redirect — the UI route,
not the rate-limited API — same as the CLI, degrading to no version on
any failure.
* docs(kap-server): note the marketplace version resolution in the plugins route header
* feat(kap-server): mark capability wiring rows in the marketplace response
A client following only /plugins/marketplace + POST /plugins would
install a capability's wiring plugin without its binary runtime, with
no wire-level way to tell. Entries whose id matches a capability's
wiring plugin now carry capabilityId, so clients route them through
/capabilities/{id}:install — the client-side routing pattern the CLI
established (the upstream design that replaced the server-side hook).
* fix(kap-server): fall back to the source-checkout catalog for the default location
When the marketplace location is the built-in default (no server option
or env override) and the fetch fails, read the repo checkout's own
plugins/marketplace.json — the CLI loader's behavior for offline
source-checkout dev. An explicitly configured catalog still fails hard
with 50001. Bundled installs have no checkout file, so the fallback
simply never fires there.
* fix(kap-server): resolve fallback catalog sources against the fallback file
readMarketplaceCatalog returned only the JSON, so entries from the
source-checkout fallback resolved their relative sources against the
(unreachable) CDN URL — coming back as unusable https paths instead of
local directories. The reader now returns the location actually read,
and source resolution uses it.
* fix(kap-server): honor the CLI's marketplace metadata aliases
Custom catalogs using name / shortDescription / websiteURL (accepted by
the CLI parser) lost those fields to schema stripping, falling back to
the entry id. Normalize the aliases in the same preprocess as the
source/tier normalization.
* fix(kap-server): filter marketplace keywords instead of rejecting the catalog
A keywords array with non-string or blank members failed the strict
schema and took the whole catalog down with 50001. Normalize to the CLI
parser's semantics: non-array reads as missing, arrays keep trimmed
non-blank strings only.
* fix(kap-server): treat a blank or non-string marketplace version as missing
The CLI parser reads version through its lenient stringField and falls
through to source-derived versions; the route's schema rejected a
numeric version with 50001 for the whole catalog. Normalize version in
the preprocess like the other fields — the gh-plugin fixture now
carries a numeric version and still derives 2.0.0 from its tag source.
* fix(kap-server): trim marketplace entry ids before the install-state join
A whitespace-padded id survived validation raw and never matched the
installed records (updateAvailable silently lost). Normalize the id in
the preprocess — trimmed, blank rejected — matching the CLI's
requiredString.
* fix(kap-server): gate capability markers to the default catalog
A custom catalog (env or server option) may legitimately carry a
same-id fork of a capability's wiring plugin; marking it capabilityId
would route users to the built-in install. Apply the marker only for
the default catalog (including the source-checkout fallback), matching
the CLI injecting built-in rows only for the default catalog.
* fix(kap-server): compare marketplace versions with real semver
The hand-rolled strict x.y.z check rejected valid semver the CLI
accepts (v-prefixed, prerelease tags), so updateAvailable diverged
between CLI and wire clients. Take the semver package (already in the
monorepo via the CLI) for the update check and the two source-derived
version validators.
* fix(kap-server): validate marketplace entry types and count the dev server as default
- Custom catalog rows with an unsupported type (e.g. integration) were
stripped by the schema and advertised as installable plugins; the CLI
rejects the catalog outright. Model the same plugin/managed/guide
vocabulary.
- scripts/dev.mjs marks its repo-owned catalog with
KIMI_CODE_PLUGIN_MARKETPLACE_FROM_DEV_SERVER=1 — honor the flag in
the isDefault check so capability markers and the checkout fallback
behave exactly like the CLI under the dev marketplace.
* fix(kap-server): join capability rows through their platform wiring plugin id
kimi-cu installs its wiring plugin as kimi-cu-win on Windows x64, so a
catalog row keyed kimi-cu never matched the installed record there (no
installed state, no updateAvailable). The row mapping now knows each
capability's wiring plugin ids and joins through them.
* fix(kap-server): map plugin load failures to 40001
An install source pointing at a directory/zip with a missing or invalid
manifest throws plugin.load_failed — a client-fixable input error that
fell through to 50001. Map it to validation.failed alongside the other
input mistakes.
* build(kap-server): align @types/semver with the workspace version
sherif rejects multiple workspace versions of one dependency; the CLI
pins @types/semver at ^7.7.0.
* refactor(agent-core-v2): share the plugin marketplace client/parser across hosts
The kap-server marketplace route grew its own copy of the CLI's catalog
loading/parsing logic (lenient aliases, blank-means-missing fields,
source resolution, GitHub version derivation) — two implementations of
a public, hand-writable format would drift on every catalog change.
Move the read/parse/version machinery into the plugin domain as
app/plugin/marketplace (pure functions, no DI): the CLI keeps a thin
wrapper owning configured-source resolution and its checkout fallback,
and the route keeps only the wire concerns (install-state merge,
capabilityId markers, error envelopes). plugins.ts drops ~230 lines of
duplicated machinery.
One deliberate behavior fix rides along: tilde entry sources now expand
against the home directory at parse time (the CLI previously passed
them through literally, failing later at install validation).
* docs(agent-core-v2): fold the marketplace module's member docs into the file header
The package convention keeps explanatory comments in the top-of-file
block only; the moved parser carried several function/member-level
JSDoc blocks from its CLI home. The header now carries the format
contract, leniency rules, source/version resolution order, built-in
masking semantics, and the fallback gating rule.
* docs(agent-core-v2): drop the remaining statement comments in the marketplace module
The header carries the rationale (update semantics, GitHub ref shapes,
the releases/latest choice); the convention allows nothing beside
statements.
* fix(kimi-code): import the shared marketplace module by its deep path
constant/app.ts is evaluated on every CLI invocation; re-exporting from
the agent-core-v2 root would pull the whole engine module graph into
startup. The package's wildcard subpath export lets both CLI files take
only the pure marketplace module (node builtins + semver).
* feat(kap-server): fan plugin and capability lifecycle out as global WS events
Clients currently poll the plugins/capabilities REST surfaces and can
hold stale rows while another client mutates the set. Publish two global
events instead:
- event.plugin.changed — fired off IPluginService.onDidReload, so any
install/enable/disable/remove from any client reaches every host
- event.capability.changed — every capability install progress
transition (CapabilityService gains onDidChangeInstall), so rows
update live and settle is observable without polling
Both ride the existing global fan-out (no subscription needed) and are
documented in the wire schema registry.
* fix: register the lifecycle events in the wire union and tidy the contract header
- event.plugin.changed / event.capability.changed were declared but not
part of agentEventSchema, leaving the wire catalog incomplete.
- The onDidChangeInstall member doc moves into the capability contract
file header (package comment convention).
* feat(protocol): mirror the plugin/capability lifecycle events in the shared WS schema
Clients and e2e harnesses validating server frames against
@moonshot-ai/protocol would reject event.plugin.changed /
event.capability.changed. Register both in the shared catalog (TS
interfaces, zod schemas, and both unions), matching the
model_catalog.changed precedent for global events.
* fix(kap-server): prefer the platform wiring plugin when joining capability rows
A stale same-id record (e.g. a raw kimi-cu plugin next to the real
kimi-cu-win wiring on Windows x64) previously won the join, showing the
wrong installed state and update availability. Capability rows now join
through the wiring plugin ids in platform preference order before
falling back to the catalog id.
* fix(kap-server): put the github metadata of plugin summaries on the wire schema
GitHub-sourced plugin summaries carry github {owner, repo, ref,
installedSha} from the domain; the route serializes raw domain objects,
so the field reached clients undocumented. Declare it in
pluginSummarySchema so the OpenAPI surface matches reality.
* test(node-sdk): cover the new lifecycle events in the exhaustive switch
The event-type exhaustiveness test broke when the shared protocol union
gained event.plugin.changed / event.capability.changed.
* fix(kap-server): mark capability progress events volatile
Per-chunk download progress transitions ride the same fan-out as
durable frames and were being persisted to the __global__ journal —
hundreds of stale frames per install. event.capability.changed is
live-only state, so it joins the volatile list alongside
event.di.unit_changed; the settle frame stays recoverable via a direct
capability read. event.plugin.changed remains durable (rare, and a
reconnecting client should replay it).
* feat(kap-server): inject built-in capability rows into the default catalog response
The checked-in production catalog carries kimi-webbridge but not
kimi-cu — the CLI injects built-in rows client-side, so wire clients
never saw Kimi Computer Use in /plugins/marketplace. For the default
catalog the route now appends supported capabilities the catalog lacks
(static descriptors via ICapabilityService.describeCapabilities — no
detector probes), marked with capabilityId and a capability:<id>
sentinel source so installs still route through the capability
surface.
* fix(kap-server): run injected capability rows through the install-state join
The injected kimi-cu row hardcoded installed: undefined, so an
already-installed capability still read as installable. Injection now
happens before projection, so injected rows get the same backing-plugin
join (installed state, update badge, capabilityId marker) as catalog
rows. Also moves the describeCapabilities note into the contract header
(package comment convention).
* test(kap-server): gate the injected-row assertions on platform support
kimi-cu injects only where supported (macOS / Windows x64); on Linux CI
the row is correctly absent.
* fix(protocol): classify capability progress as volatile in the shared catalog
kap-server never journals event.capability.changed (it is in the
server-local volatile list); shared-protocol clients reading
isVolatileEventType would treat per-chunk progress frames as durable
and replayable. Mirror the classification.
* fix(kap-server): hide capability rows on unsupported platforms
Catalog-carried capability rows (kimi-webbridge in the default catalog)
were marked with capabilityId regardless of host support — on an
unsupported platform clients would route into an impossible capability
install. Rows whose capability is unsupported are now excluded from the
default-catalog response entirely (the CLI hides its built-in rows the
same way).
|
||
|
|
1414d46028
|
refactor(agent-core-v2): fold session lifecycle hooks into sessionLifecycle events (#2896) | ||
|
|
6be26978b1
|
feat: auto-generate session titles via the managed chat_title tool (#2351)
* feat: auto-generate session titles via the managed chat_title tool
With the auto-title experimental flag on and a managed OAuth login, the
session title is generated from the first prompt, replacing the
truncated-prompt easy title. A custom title set by the user is never
overwritten, and generation failures degrade silently to the easy title.
- oauth: fetchChatTitle for the platform /tools chat_title method
- agent-core (v1): fire-and-forget generation on the first prompt
- agent-core-v2: sessionTitle domain watching the easy-title event
- kap-server: POST /sessions/{id}/title/generate for manual regeneration
* fix: harden auto-generated session titles
* fix: preserve managed title request headers
* Pair auto-title endpoint overrides with matching OAuth credentials
* fix: preserve legacy custom session titles
* fix: preserve automatic session title invariants
* refactor: keep only the on-demand session title generation interface
Drop the automatic wiring on both engines: the v1 (TUI) first-prompt
trigger and the v2 easy-title event watcher. SessionTitleService's
generateTitle() stays as the single on-demand entry point behind the
auto-title flag, backing the kap-server title/generate route. The
changeset goes away too: with no shipped consumer, the remaining
surface is not user-perceivable.
* feat: generate session title from the first recorded prompts
Record up to three sanitized natural-language prompts in session
metadata (skill / plugin activations excluded) and compose the
chat_title input as order-labeled lines truncated to a 1000-char
budget, falling back to lastPrompt for sessions without recorded
prompts.
* test: make session title race tests deterministic
* Generate session titles from agent conversation history
* fix: reject title generation without user prompts
* fix: bound session title prompt history
* feat: enable session title generation without an experimental flag
* test: cover session title generation through the public REST path
* feat: request session title generation from the TUI after each turn
* Retry auto title generation for prompt-derived session titles
* feat: record session title source and harden the generation lifecycle
- persist titleSource (prompt/generated/custom); skip auto-generation over
an already-generated title unless forced, and never over a custom one
- plumb the force option from the core through klient and node-sdk to the
REST title/generate endpoint
- drop the title write-back when the session scope was superseded
mid-flight, and retry once with a force-refreshed token on a 401
- stop closing sessions a concurrent public resume has handed out in the
temporary resume paths (generateSessionTitle, renameSession)
- accept session.meta.updated patches without lastPrompt in klient event
validation, and emit exactly one metadata event per applied title
- remove the retired prompts field heal and drop the changeset (the
behavior is only perceivable on the experimental v2 engine)
* chore: follow agent-core comment convention
* fix: ignore stale session title callbacks
* fix: preserve session title state invariants
* refactor: seed session lifetime instead of querying the workspace handler
The session title service must not depend on the Workspace-tier handler
registry. The handler now seeds each session scope with an abort signal,
fires it synchronously when a close begins, and the title service carries
the signal on its request, drops the write-back once aborted, and drains
an in-flight generation through the onWillCloseSession hook.
* fix: honor the legacy custom title marker over a stale titleKind
A v1 rename spreads the original state.json document, so an explicit
isCustomTitle: true can travel with a stale titleKind. The explicit
marker now wins on load, and every persist double-writes the derived
isCustomTitle so released v1 builds keep recognizing the custom title.
* fix: serialize session access and expose the session title state
The temporary resume/rename/close paths and the public lifecycle
operations now share a per-session queue, so a public resume can never
receive a handle whose cleanup close is already in flight. Session
summaries carry the canonical title state, letting the TUI skip title
generation for sessions whose title was already generated or customized
instead of re-asking after every turn.
* chore: add session title changesets
* fix: close the session lifecycle races around close and title generation
A close/archive is now tracked in a closing registry from its first
synchronous step until disposal: get/list hide the closing session and
resume waits the close out instead of returning the doomed handle, and
fork waits out an in-flight source close. The title service tracks the
whole generateTitle call as the unit the close hook drains, and the
generated-title write re-checks the lifetime signal inside the serialized
metadata update so an abort landing while the update is queued still
vetoes the write-back.
* feat: project the session title state through the session index
readSummary and the read-model mirror carry titleKind, so listSessions
reports the same canonical title state as a resumed session's summary.
* fix: serialize the remaining session access paths in the SDK
forkSession and explicit-id createSession join the per-session queue, and
the harness resume fast path skips a session whose close is in flight
instead of returning the closing facade (which then failed every call
with session.closed); its late onClose no longer evicts the fresh
session either. The harness rename event now carries isCustomTitle so
the TUI stops asking for a generated title after a local rename.
* fix: detach the external abort listener once the chat title request settles
* fix: harden the session close/archive and create/fork lifecycle
The closing registry now records the operation kind: an archive arriving
during a plain close waits it out and lands the archived flag on the
persisted document instead of riding the close to success, and a failing
close hook no longer strands a half-closed session — the teardown always
completes while the hook error still reaches the caller. create and fork
reserve their target id synchronously with the existence check, so a
concurrent create/fork of the same id loses up front and can never tear
down the winner's scope or directory.
* fix: keep forced title regeneration independent and veto queued title writes atomically
Plain generateTitle calls still coalesce onto one shared in-flight
generation, but a forced regeneration always runs on its own so it is
neither swallowed by a plain call's early exit nor shares its result; the
close hook drains every active generation. The allowWhen veto now runs
inside applyUpdate with no await between the check and the mutation, so
an abort cannot slip into the gap.
* fix: carry the title state through the session index and klient contract
The klient session summary schema no longer strips titleKind, and the
index readSummary honors a legacy isCustomTitle marker over a stale
titleKind, so listSessions reports the same canonical title state as a
resumed session.
* fix: coalesce harness resumes, lock fork targets, and cover the title state end to end
Concurrent public resumeSession calls now share one in-flight resume and
one facade instead of building parallel facades over the same engine
handle (a close on either would strand the other). forkSession takes the
source and target queues in sorted order, so fork(A->X) is atomic against
create(X) and fork(B->X) without an ABBA deadlock. The emitMetaUpdated
patch type drops the redundant undefined union, and the SDK tests now
cover facade coalescing and the title state across list and resume.
* fix: serve the canonical title state from the session index and version the read-model cache
readSummary now derives the title state with the same priority chain as
the metadata document's canonical normalization (explicit custom marker,
valid titleKind, legacy false marker, customTitle, plain title), so list
and resume agree on legacy documents too. Read-model cache entries carry
a summary version stamp and older-stamped entries are treated as cold
misses, so an upgraded reader never serves a stale-shaped summary.
* fix: let the newest title generation request win the write-back
A forced regeneration could be followed on disk by an earlier plain
call's slower backend response. Each generation now carries a
monotonically increasing sequence (assigned only once a request actually
proceeds to generation), and the serialized metadata write is vetoed
unless the writer is still the newest request.
* fix: fold archive into close and own the create/fork rollback
An archive requested during a plain close is applied through the live
metadata during the teardown (or lands on the persisted document when it
arrives too late or the close fails), publishes the archived event, and
works on cold sessions too. A resume waiting on a failed close retries
instead of propagating the hook error, the teardown completes even when
the agent drain fails, and the create/fork rollback only ever removes
its own handle — a loser of the reservation race can no longer tear down
the winner's live scope.
* fix: key harness resume coalescing by the full input
Concurrent resumes only share a facade when their inputs match — a
caller passing different dirs, replay, profile, or kaos options gets its
own resume instead of having its options silently dropped.
* refactor(agent-core-v2): drop session close-awareness from title generation
Auto title is best-effort: a generation racing session close no longer
cancels its fetch or guards its write-back, so the per-session
sessionLifetime AbortSignal seed, the onWillCloseSession drain, and the
close-time invalidation go away. The newest-request-wins write-back
predicate stays.
* Delete .changeset/sdk-session-title-kind.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* refactor(session-title): drop the unused force regeneration path
Nothing calls force: with it gone, plain calls always coalesce onto the
shared in-flight generation, so the generation sequence and the
caller-supplied allowWhen veto lose their only purpose and go with it.
The title/generate REST route takes no body anymore.
* refactor(agent-core-v2): drop the title state projection from the session index
The listed-session titleKind had no consumer: the TUI's title-generation
gate seeds from the resumed summary, which reads the live metadata
document, and the kap-server REST wire never carried the field. Removing
the projection also retires the read-model summary version stamp (the
remaining shape is fully field-checkable) and the duplicate title-kind
derivation that had to stay in lockstep with sessionMetadata. The klient
list contract and the node-sdk list mapper drop the field with it; the
resumed/live summary still reports the canonical title state.
* refactor(agent-core-v2): inline the transcript live-tail merge into messageLegacy
mergeContextTranscriptWithLive had a single caller; move the logic into
messageLegacyService as the private mergeLiveTail and drop the export.
* refactor(agent-core-v2): drop the closing registry from the session lifecycle
Auto title no longer consumes close-awareness, so the machinery goes
back to the simple forms: close/archive run straight through, resume
no longer waits out an in-flight close, create/fork drop their target
reservation, and a cold archive is a no-op again. Reverts the behavior
of
|
||
|
|
b6144f94ea
|
ci: release packages (#2846)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
c9bfe8b2c8
|
feat: replace the secondary-model experiment with a declarative subagent model pool (#2700)
* feat: replace secondary-model experiment with [subagent.models] pool
Add a declarative subagent model pool to agent-core-v2: [subagent.models]
maps [models] entry ids to selection hints rendered in the Agent/AgentSwarm
tool descriptions, and [subagent].default_model picks the spawn model when
the caller passes none. The tools' model parameter becomes a free-form
alias string (stripped when no pool is configured), description rendering
is caller-aware (primary (alias) [main model]), and a session-start
validation service fails fast with CONFIG_INVALID on a missing/invalid
default_model or an unresolvable pool alias.
Remove the secondary-model experiment from the v2 engine, node-sdk,
kap-server, and the TUI (the /secondary_model command), and drop the
agent-profile modelPreference / model_preference frontmatter field on v2.
The legacy v1 engine keeps the experiment unchanged; v2 ignores leftover
[secondary_model] config silently.
* fix(agent-core-v2): harden subagent model-pool validation and error/picker mapping
Deep-review follow-ups to the [subagent.models] pool:
- validate the pool before session materialization (after config.ready)
and before the fork file copy, so a broken pool no longer leaves
orphaned session dirs or leaked MCP overlay connections; the
Session-scope validation service stays as a backstop
- reject the reserved "primary" pool alias at startup, and again
defensively in resolveSubagentBinding so a pool broken by a runtime
config edit fails loudly at spawn instead of binding the wrong model
- keep the [default] marker when the caller's own model is the pool
default (primary (alias) [main model] [default])
- recompile the cached tool-args validator when a tool advertises a new
schema object (mid-session pool edits no longer hit a stale validator)
- map config.invalid to VALIDATION_FAILED in kap-server's session routes,
the debug transport mapper, and the catch-all error handler
- hide the v1-synthesized __secondary__ entry from the /model and
/provider pickers again
- fold per-export doc blocks into file headers per package comment
conventions; add pre-flight/reserved-key/validator/mapping tests and
document that create/resume/fork all fail on a broken pool
* feat: re-add /secondary_model and accept a lone subagent default_model
- v2 engine: a pool-less [subagent] default_model forms an implicit
single-entry pool — validated at session create/resume/fork like an
explicit pool, and advertised through the Agent/AgentSwarm model
parameter.
- Tool descriptions: the caller's own alias is a normal pool entry
marked [main model]; the primary line stays distinct because only it
inherits the caller's thinking level.
- TUI: /secondary_model returns, persisting [subagent] default_model
(merging into an existing pool with an empty description); the picker
hides the no-op Thinking footer and rejects the reserved primary
alias.
- kap-server: /api/v1/config accepts and echoes subagent; the
snake-to-camel patch conversion preserves user-defined map keys under
providers/models/experimental/raw without leaking preserve mode into
a colliding alias's own fields.
- v1 config schema learns subagent.defaultModel/models so the shared
config.toml round-trips; the v1 engine still ignores them at runtime.
- Docs (en/zh) and changesets updated.
* docs: use public model identifiers in the subagent model pool examples
* refactor: rename /secondary_model to /secondary-model
* test: cover the /secondary-model command name resolution
* Revert "test: cover the /secondary-model command name resolution"
This reverts commit
|
||
|
|
504e6292ed
|
feat(mcp): inspect effective authorization state in v1 (#2856)
* feat(mcp): inspect effective authorization state * test(agent-core-v2): register MCP auth coordinator fixture * fix(mcp): validate runtime names against full catalog * fix(mcp): reconnect after pending auth updates * docs(mcp): describe auth coordinator collaborator * fix(mcp): ignore disabled runtime name collisions * fix(mcp): serialize OAuth token refresh * test(mcp): await OAuth credential writes * fix(mcp): queue trailing credential reconnect * fix(oauth): preserve access-only refresh winners * fix(mcp): preserve legacy offline auth state * fix(mcp): redact inspection credentials * refactor(mcp): keep app inspection on v1 * fix(mcp): guard legacy auth status mutations * fix(mcp): avoid deterministic legacy auth probes * fix(mcp): cover initialization credential updates --------- Co-authored-by: 刘仲诺 <liuzhongnuo@dev.msh.team> |
||
|
|
23e68eee8b
|
refactor(agent-core-v2): remove the agent RPC aggregation layer (#2871)
* refactor(agent-core-v2): remove the agent RPC aggregation layer
- delete src/agent/rpc/ (AgentRPCService, IAgentRPCService, core-api,
prompt-metadata, types) and sink each method's orchestration into its
owning domain service
- prompt: new submit/submitSteer composing disabledTools gating,
MAIN-only session metadata, and engine-side {turn_id} settlement
- skill: activate now returns PromptLaunchResult and writes session
metadata internally (MAIN-only, unified across prompt/steer/skill/
pluginCommand); node-sdk and kap-server drop their edge-side writes
- pluginCommand: new agent-scope domain owning command activation and
the plugin_command.activated domain event
- permissionMode/loop/fullCompaction: new setModeAndBroadcast /
cancelFromUser / cancel; setMode and loop.cancel stay pure for
internal callers
- klient: agentRpcContract split into per-domain contracts; facade
re-routes to domain channels with its public API unchanged
- node-sdk, kap-server, kimi-inspect and the v2 test harness now call
domain services directly; ctx.rpc keeps its name as a composed
adapter
- externally visible: the agentRPCService debug channel is gone and
session metadata writes are now MAIN-agent-only (see changeset)
* refactor(agent-core-v2): move disabledTools gating out of the prompt domain
Prompt should not own session tool policy: submit no longer accepts or
applies disabledTools. The klient facade keeps its prompt({ disabledTools })
API and composes it edge-side — applying agentToolPolicyService
setSessionDisabledTools before calling agentPromptService.submit, the same
way kap-server's prompt route already does. Over klient, a profile-less
engine now surfaces the raw profile error instead of request.invalid.
Also restores the RPC-removal changeset, which did not make it into the
previous commit.
* chore(agent-core-v2): drop the RPC-removal changeset
* refactor(klient): drop disabledTools from the prompt entry entirely
The prompt path no longer carries session tool gating on any surface:
the klient facade prompt() loses the disabledTools field and calls
agentPromptService.submit directly, and the node-sdk
SessionPromptRpcInput stops accepting or forwarding it (v1 always
ignored the field). Session tool gating remains available through
IAgentToolPolicyService.setSessionDisabledTools, composed at the edge
the way kap-server's prompt route does; the klient toolPolicy contract
added for facade-side composition is removed as unused.
|
||
|
|
f40bf04998
|
refactor(agent-core-v2): unify model-facing reminder scheduling (#2623)
* refactor(agent-core-v2): unify model-facing reminder scheduling Route every model-facing reminder through the contextInjector boundary scheduler. Past-tense events go through a persisted once-reminder queue (reminderQueue) that delivers exactly once at turn, step, compaction, and restore boundaries; present-tense state renders through context-injection providers reconciled against live history. - interruption, goal (cancel/budget/fork-cleared), image-compression captions, btw, and init reminders enqueue into reminderQueue instead of writing the context directly; the interruptionReminder wire model is removed and its recorded type is retired silently on replay - swarm mode announcements render through a provider seeded from the replayed history on restore, replacing live side effects and the ContextModel pop reducer on swarm_mode.exit - loadable-tools announcements become an isNewTurn-gated provider, dropping the compaction boundary flag - plugin session-start guidance re-renders as a supersedes reminder at the next boundary via a dirty flag instead of appending immediately - legacy system_trigger origins of migrated reminders still fold on replay * fix(agent-core-v2): make system reminders undo-aware * test(agent-core-v2): migrate plugin session-start harness * fix(agent-core-v2): preserve reminder boundary ordering * refactor(agent-core-v2): narrow reminder and swarm helper exposure - drop the swarmInjection re-export from the package index; SwarmInjection stays a domain-internal collaborator like permissionMode/plan injections - move INTERRUPTION_REMINDER text back to a private constant in the service; only the variant stays in the Ops module - make reminderQueue.enqueue return void; no caller consumed the entry id * chore(agent-core-v2): keep comments in module headers * refactor(agent-core-v2): track reminder state via injection disclosure - derive swarm active/inactive state from ctx.lastDisclosure instead of byte-matching rendered markdown, with variant-only fallback for legacy swarm_mode/swarm_mode_exit journal entries - record once_reminder disclosure (entry id) on queue-appended messages and dedupe the crash window by the contiguous tail id set, covering multi-entry drains - move reminderQueue draining behind a sync onWillInject event so the injector no longer depends on the queue domain - centralize the system-reminder wrap format behind wrapSystemReminder / systemReminderContent and use injector-provided positions in the plugin session-start provider - spell out the step-boundary fallback and sync-only contract of registerAtTurnStart via shouldRunAtBoundary * fix(agent-core-v2): isolate failing turn-start providers and warn once per missing sessionStart skill * refactor(agent-core-v2): compute injection positions on read Drop the per-provider positions cache from the context injector: the registration scan, the context.spliced index arithmetic, and the post-restore resync all existed only to mirror what the history already records. Each provider call now derives its injected positions by scanning context memory for its surviving injection messages, so silent history edits (such as vacuous-step folds) can no longer desync a cached index. * refactor(agent-core-v2): formalize injector once-channels and raw message results * refactor(agent-core-v2): declare dynamic tool schemas at injection boundaries Move the dynamic-tool schema declaration out of toolSelect.load(): the loaded names are recorded as pending and drained by a dedicated toolSelectSchemas provider through the contextInjector boundary scheduler, so the declaration message lands at a quiescent boundary instead of mid-step inside a streaming tool exchange. The folded history remains the loaded-tool ledger, so undo, compaction, and resume still self-heal by re-folding. * refactor(agent-core-v2): deliver AGENTS.md reminders through the reminder queue The tool hook now only observes and enqueues a once-per-agent reminder through the reminderQueue once-channel instead of prepending text to the tool result: results stay verbatim for the truncation pipeline and the reminder can never be truncated away with an oversized output. The reminderQueue is resolved lazily through the instantiation service at enqueue time, breaking the contextInjector -> loop -> llmRequester -> profile -> agentsMdReminder constructor cycle. * refactor(agent-core-v2): make injection disclosures opaque and domain-owned contextMemory no longer declares the ContextInjectionDisclosure union: InjectionOrigin.disclosure becomes an opaque unknown, and providers bind their own payload type through register<D>, so lastDisclosure arrives at the provider already typed by its own variant. The date, swarm_mode, and once_reminder payload shapes move into the dateChange, swarm, and reminderQueue domains respectively; reminderQueue keeps a runtime guard for its cross-message tail scan, the only place that reads disclosures it did not write. Persisted origin shapes are byte-identical, so existing journals replay unchanged. * fix(agent-core-v2): isolate failing step context providers A step or compaction boundary provider that threw or rejected made the injector's inject() promise reject, which propagated through the onWillBeginStep hook chain and failed the whole turn, and starved every provider registered after it. Log and skip the bad provider instead, matching the turn-start path's existing isolation. * refactor(agent-core-v2): derive injector isNewTurn per injection boundary Replace the shared read-and-clear isNewTurn flag (set by turn.started and injectAfterCompaction, consumed by the first inject()) with values each trigger supplies from an authoritative source: the loop marks a turn's first step via BeforeStepContext.firstStepOfTurn (standalone runs never count), and the compaction follow-up passes true explicitly, so interleaved triggers can no longer consume or steal the marker. A compaction follow-up that lands inside a step hook chain (the auto-compaction path) doubles as that step's new-turn delivery: the enclosing step then injects with isNewTurn false, so the upcoming request receives one new-turn injection, not two. * refactor(agent-core-v2): unify disclosure placement and injector param naming * fix(agent-core-v2): keep pending tool schemas across compaction splices A load announced by select_tools sits in pendingLoaded until the next injection boundary declares it. A compaction fold in that window publishes a replacement splice, and the splice-time reconciliation dropped the pending entries before the post-compaction inject could declare them — the model was told "Loaded: X" yet X never became available. Drop pending entries only on removal splices (undo/clear, which carry no replacement messages); compaction's replacement splice keeps them so the declaration lands at the post-compaction boundary. * fix(agent-core-v2): consume the plugin session-start refresh after a successful render reconcileSessionStartReminder cleared the refresh-pending flag before awaiting the render, so a throwing render (skipped by the injector's provider isolation) lost the forced refresh until the next catalog change. Consume the flag only after the render resolves, and move the warn-once rationale into the module header per the comment convention. * refactor(agent-core-v2): remove the generic reminder queue * chore(agent-core-v2): drop the stale reminder-queue mention in systemReminder * test(node-sdk): align side-question fork parity with event-point reminders * chore(agent-core-v2): address reminder review standards * docs(agent-core-v2): condense the model-facing reminders section * refactor(agent-core-v2): write all system reminders through wrapSystemReminder * fix(agent-core-v2): preserve reminder lifecycle invariants * refactor(agent-core-v2): reconcile context injections at the step head Unify the injector's delivery timings into one point on the onWillBeginStep chain, before the step's request is built: - providers run before every request instead of after every step, so reminders are visible from the first response of a turn - a compaction splice re-arms the new-turn flag via context.spliced; when compaction runs inside the hook chain (full-compaction's beforeStep), a follow-up inject at the chain tail keeps the first post-compaction request covered - registerAtTurnStart and injectAfterCompaction are removed; reconcileWhenIdle stays as the v1-parity surface for SDK-driven triggers (swarm toggle, plugin reload) * refactor(agent-core-v2): clarify the injector's step-hook handler Name the handler reconcileAroundStep, rename the rearm flag to compactionRearmPending with a single takeCompactionRearm() consumer, and extract isCompactionSplice. Consuming the flag into a local before computing isNewTurn also avoids hiding the side effect inside a || short-circuit. |
||
|
|
c212ae9715
|
fix(kimi-code): show MCP launch targets in the workspace trust prompt (#2843)
* fix(kimi-code): show MCP launch targets in the workspace trust prompt Render each gated project MCP server's launch target (transport, command, args, cwd, or url) in the workspace trust prompt without leaking env or header secrets, stripping terminal control characters from the workspace-supplied text, default the prompt to "Don't trust", and resolve fd binaries to absolute paths so untrusted workspaces cannot plant a bare-name fd executable that runs before trust confirmation. * fix(kimi-code): resolve stty to an absolute path before the trust gate |
||
|
|
f6ee44e426
|
ci: release packages (#2710)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
3c9e3b297c
|
feat(kimi-code): paginate the session picker list (#2826)
* feat(kimi-code): paginate the session picker list The /sessions picker and kimi -r used to materialize the full session list before showing anything, which gets slow with hundreds of sessions. - node-sdk: add listSessionsPage (limit/before -> items + nextCursor); the v2 engine pages through the session index (draining past entries whose workDir is unrecoverable), the v1 engine answers one full page - TUI: open the picker on the first page, fetch the next page when the cursor reaches the fetched end, and drain remaining pages in the background once a search query is typed so search still covers all sessions - kimi -r now fetches a one-item page for the latest session * chore: simplify session picker changeset * fix(kimi-code): join in-flight page fetch in session search drain A query typed while a scroll-triggered page fetch was still running stopped the background drain at the loadingMore early return, leaving the search covering only the pages fetched so far. fetchMoreSessions now optionally joins the in-flight fetch and continues with the next page; scroll triggers still drop when busy. |
||
|
|
158c81d705
|
fix: surface a readable error when Git Bash is missing on Windows (#2814)
* fix: surface a readable error when Git Bash is missing on Windows * fix(agent-core-v2): translate probe rejection into HostProcessError for ready awaiters - HostEnvironmentService.ready now rejects with the translated HostProcessError(shell.git_bash_not_found) instead of the raw ProbeShellNotFoundError, matching what sync field reads throw and what SDKRpcClientV2.ensureConfigFile() surfaces, while an internal no-op handler keeps the rejection from becoming an unhandledRejection. - Replace the Windows-gated probe-failure tests with vi.mock-stubbed deterministic suites that run identically on any platform. - Move the ProbeShellNotFoundError explanation into the environmentProbe file header per the package comment convention. * fix(agent-core-v2): narrow probe error to Error to satisfy only-throw-error lint * fix(agent-core-v2): preserve probe error as cause when translating to HostProcessError * fix(agent-core-v2): keep checked paths out of the public probe error message * fix(node-sdk): gate the host-environment wait in ensureConfigFile to Windows The missing-Git-Bash failure is Windows-only, and IHostEnvironment.ready also covers the login-shell PATH enrichment, which spawns the user's login shell with a 5s timeout. Awaiting it on POSIX coupled config-only commands (kimi provider list/remove, export, ...) to the user's shell profile for no benefit. --------- Co-authored-by: liruifengv <liruifeng1024@gmail.com> |
||
|
|
e702817124
|
fix(agent-core-v2): degrade idle-session steer to turn launch like v1 (#2723)
- return the enqueue-launched turn instead of rejecting with prompt.not_found when no prompt is pending at steer time - report steer as queued when a manual compaction holds the context - sync title/lastPrompt metadata on main-agent steer, matching v1 - update the v1-v2 parity test to assert converged behavior |
||
|
|
437a1b8ba1
|
fix(sdk): probe MCP auth status through connection (#2731)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
|
||
|
|
0b2e803d5e
|
feat(sdk): expose global MCP auth status (#2706)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
|
||
|
|
7cd64766c8
|
feat: isolate the full-text search index from the session index and the main thread (#2701)
* feat(minidb): instrument open lifecycle with phase timings and status Add MiniDb.lifecycleStatus() exposing the no-generation/generation-load/ wal-catch-up/full-rebuild/ready/degraded state machine plus per-phase timings (generation candidate load, store/non-text/text image load, postings integrity check, WAL scan/apply, full recovery, text rebuild hosting), so snapshot load, WAL catch-up and full rebuild can be told apart in diagnostics. Also add a repeatable open-lifecycle bench (small data, large WAL delta, large full-text generation, corrupt generation) and fixtures proving a healthy generation open performs no full-corpus tokenization while a corrupt or missing generation falls back. Log search-index and query-store open diagnostics in kap-server and agent-core-v2 so a listSessions call can be attributed to the database it touches. No persistence format or product behavior change. * feat(agent-core-v2): isolate the session index from the global search index Harden the separation between the session read model and the full-text search index so session operations never depend on search availability: - Reject text index definitions in MiniDbQueryStore at definition level, keeping the session query-store a structural-only read model with no postings/tokenizer artifacts, and assert its generation carries no full-text files. - Share one authoritative scan between the first list and the initial projection (single-flight) instead of scanning twice; reads may only join an in-flight scan, and every fallback read folds the mirror's pending queue so read-your-writes holds while preparing. - Keep withReadModel() fallback semantics pinned by tests: uninitialized/preparing reads hit authoritative metadata immediately, ready reads use the read model, degraded keeps falling back with a diagnosable status reason. - Guard session metadata writes so a mirror failure degrades only the read model and never fails the session lifecycle. - Prove via tests that listSessions/--resume/--continue never open the global search DB (including when search-index is unopenable), and that only real full-text search requests report building/stale/degraded. * perf(minidb): slice open-time work so it never blocks the main thread Make the whole generation-open path cooperative: - Replace the synchronous postings/store CRC verification with chunked async variants (readGenerationFileCheckedAsync, verifyFileIntegrityAsync) that keep the exact bytes/crc-mismatch error semantics. - Give the WAL-delta apply a primitive-op + wall-clock budget (walApplySlicer), so a batch frame unrolling into thousands of ops can no longer run as one uninterruptible slice; torn-tail, corrupt-batch and read-only behaviors are unchanged. - Slice the big attach loops: Store.bulkLoadRefsAsync + SkipList.bulkLoadAsync for the store image, async parsers and loadImageAsync for secondary/compound images, and TextIndex.attachImageAsync for the docs/dictionary map construction. - Queue text builds on worker-slot pressure (WorkerSlots.acquireBounded, bounded by MiniDb.textBuildSlotWaitMs, abort-aware) instead of falling back to an unbounded inline build; a persisted drought hosts the bounded inline core as the explicit last resort with stats accounting. Bench (bench/open-lifecycle, seed 42): event-loop delay max across the four open scenarios drops from 45/734/331/492 ms to ~12-28 ms with wall time flat or better. * feat(kap-server): run the global search index in a dedicated worker Move the whole search-index MiniDb lifecycle (open, generation load, WAL replay, sync, rebuild, compaction) off the main thread into a long-lived worker_threads host, so it never shares the event loop with TUI input: - Add a versioned request/response protocol and worker entry hosting a host-agnostic SearchIndexCore; the same core also backs an inline backend kept as the explicit rollback (KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER=false, flag default ON). - The worker exclusively owns the search-index handle. The lock token is reported at acquire time (new MiniDb OpenOptions.onLockAcquired hook) and reaped on dirty exit; an orphan-lock detector (same-pid lock row whose token no live holder owns) recovers the window where the token report is lost, so a mid-open crash can never freeze the index into a silent permanent read-only. - Crash handling: in-flight requests are rejected with typed errors, respawn uses capped exponential backoff, per-request watchdogs terminate wedged workers, and beginClose propagates into the worker so dispose stays bounded during a long sync. Page tokens pin a boot-salted generation, so tokens issued before a transparent worker restart fail closed with invalid_page_token. - The main process keeps the sync coordinator (debounce/coalescing/ single-flight), live transcript routing, query normalization and page-token codec; searches keep reading the published generation and report building/stale/degraded instead of waiting for sync/rebuild. - Wire the worker into the CLI packaging: self-contained worker bundles for npm dist and the SEA asset manifest/installer/smoke check, plus a dev runtime (type-stripping + .ts resolve hook) scoped to worker execArgv. * feat(kap-server): model search and session-index lifecycles explicitly Consolidate the two-index separation into explicit, diagnosable lifecycles: - Surface the global search state machine (stopped / opening / building / ready / degraded / closing) end to end: SearchIndexCore.lifecycleState, SearchWorkerHost lifecycle snapshots cached from RPC responses (and invalidated across worker generations), a never-throwing status() carrying the lifecycle, and a synchronous lifecycleReport() that neither kicks the open nor spawns the worker. Corrupt search-index rebuilds are announced with a dedicated warn log so building, stale, degraded, corrupt and worker-unavailable stay distinguishable. - Turn MiniDb read-only replica catch-up fully cooperative: catchUpWalAsync scans frames with the windowed async scanner and yields per primitive op on the shared walApplySlicer budget, while a per-instance catchUpChain serializes concurrent catch-ups so each caller keeps its atomic watermark advance. The stale synchronous implementations are removed. - Pin the dependency direction and availability timing with tests: session list/create/resume survive a corrupt or unopenable search index (also end-to-end with a dead query-store), search generation reuse and stale-serving keep working across restarts, concurrent cold callers open the index / spawn the worker exactly once, resume-then- fetchSessions performs no duplicate authoritative scan, and a clean dispose releases the lock and settles at stopped. - Document the experimental flag surface (persistence_minidb_readmodel, search_worker) in the root guide. * feat(agent-core-v2): default the session read model on and roll out the separation Rollout and validation for the index separation plan: - Flip persistence_minidb_readmodel to default ON (rollback via KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL=false or the experimental config section); session list/--resume/--continue now always go through the isolated session read model with the authoritative fallback. Test harnesses pin the flag off where shared fixtures require hermetic homes, while the dedicated suites keep explicit on/off coverage. - Add a probe proving the main thread stays responsive while the search worker rebuilds and swaps a generation (reindex), completing the TUI responsiveness matrix. - Record the rollout state in the agent-core-v2 guide (session index section) and the root flag line. - Add changesets for the CLI (worker isolation, session index independence) and minidb (cooperative open lifecycle). Validation: full suites green across minidb (551), agent-core-v2 (4760), kap-server (1005), node-sdk (343), klient (91) and the CLI app (2567); open-lifecycle bench event-loop delay max is down from 45/734/331/492 ms to ~16-22 ms across the four scenarios with wall time flat or better. * fix(agent-core-v2): evict deleted sessions from the mirror queue and drain the index on close Two issues surfaced by the read-model default in the acp-server suite: - ISessionIndex.remove only deleted from the query store, but a summary still queued in the mirror was folded back into reads (and re-written by the next flush), resurrecting a deleted session in listings. The mirror now exposes evict(id): drop the queued summary and wait out an in-flight flush before the store delete. - RunningAcpServer.close and SDKRpcClientV2.close disposed the engine without awaiting the asynchronous mirror flush / query-store close, so a host removing homeDir right after close() raced in-flight shard closes (ENOTEMPTY). Both now follow the kap-server shutdown order: drain the mirror while the store is open, dispose, then await the drains. * fix(minidb): pause active expiry during the sliced bulk load The store's active-expire timer is armed at construction, so during a sliced bulkLoadRefsAsync a tick can fire mid-load: it reaps a TTL key from the map while the order skiplist is still the old empty one, and the final bulkLoadAsync then rebuilds order from the stale orderEntries snapshot — resurrecting the expired key in the ordered index (and duplicating it if the key is later set again). The sync bulkLoadRefs had no yield windows, so guard the async path with a bulkLoading flag that defers expiry ticks until the load settles (finally-safe). * chore: consolidate changesets into the TUI startup freeze fix |
||
|
|
f0614c53e5
|
ci: release packages (#2641)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
335588e259
|
feat(agent-core-v2): persist the last turn outcome into session metadata for cold listings (#2666)
* feat(agent-core-v2): persist the last turn outcome into session metadata for cold listings A cold session (no live handle) reported no lastTurnReason, so after a server restart the session list could not mark a session whose last turn failed until it was opened and resumed. A new Session-scope SessionOutcomeRecorder subscribes to the activity aggregate's turn_ended changes and persists the outcome (completed/failed) into the session metadata document; the summary pipeline (mirror + cold reader) carries it as SessionSummary .lastTurnReason, and toWireSession falls back to it when no live fact exists. 'cancelled' is deliberately not persisted: it is also what an in-flight turn ends with during scope disposal, and writing there races the host's home-dir teardown. Verified end to end with an isolated home and a dead provider: a turn fails, the server restarts, and GET /sessions reports last_turn_reason=failed without opening the session. * fix(klient): carry lastTurnReason/lastTurnOutcome in the validated contracts Review follow-up: zod strips unknown keys on parse, so the new outcome fields never reached klient callers; add them to the session summary and metadata/patch/key schemas (contract parity test covers the engine mirror). * fix(agent-core-v2): persist user-cancelled outcomes, never teardown aborts Review follow-up: skipping every 'cancelled' left a stale earlier outcome in the metadata (e.g. a prior failed reported for a session whose latest turn was stopped by the user). The recorder now subscribes to the main agent's turn.ended facts directly and keys on interruptReason: user_cancelled is persisted like any other terminal state, while programmatic aborts — including the cancel every in-flight turn suffers during scope disposal — are never written, so no metadata write races the host's home-dir teardown. * fix(kap-server): only fall back to the persisted outcome for cold sessions Review follow-up: a warm session that just started a new turn clears its live lastTurn, and the unconditional ?? fallback would then report the previous turn's persisted outcome for a turn that is still running. SessionFacts now reports whether a live handle exists, and the wire projection only reads the persisted value when the session is cold. * docs(agent-core-v2): keep the outcome-recorder header at role level * fix(agent-core-v2): settle turn outcomes on turn start and drain metadata writes on close Review follow-ups: - a new main turn now clears the persisted outcome (turn.started), so a process that dies mid-retry no longer reports the previous turn's terminal state for a turn that never ended - the dedupe marker only advances after a successful write, so a failed persist no longer suppresses the next identical outcome - session metadata writes are tracked in a module-level pending set with drainSessionMetadataWrites(), awaited by kap-server close alongside the mirror/query-store drains — an event-driven write (e.g. the outcome recorder) can no longer land in a session dir while the host removes it * fix(agent-core-v2): track the metadata dispose flag locally Disposable exposes no public isDisposed accessor; keep a class-local flag set in the dispose override. * fix(kap-server): drain session metadata writes before the mirror and disposal A write still in flight when close() begins must settle before the mirror flushes its summary into the read model and before scope disposal marks the service disposed — not after. * fix(agent-core-v2): reattach the recorder when the main agent is recreated Review follow-up: a failed bootstrap still fires onDidCreate before the handle is dropped; the subscription then pointed at a dead bus and the guard blocked any later reattach. Track onDidDispose and reset so the next main creation attaches cleanly. * test(agent-core-v2): resolve the recorder through the scoped DI harness Review follow-up: construct SessionOutcomeRecorder via registerScopedService + a Session-scope test host (stubbed lifecycle/metadata), so the test covers the production registration path; add the durable-value adoption case. * fix(agent-core-v2): unbreak CI — iterable Promise.all and the debug channel surface - Promise.all takes the pending-writes set directly (oxlint error) - the disposed flag moves into a _register'd marker instead of a public dispose() override, which the debug channels listing (and its test) correctly rejects as framework plumbing * fix(kap-server): surface persisted failures on the v2 session status The v2 list folds the outcome into activity.status, which previously read only live facts — a cold session always looked idle. Cold sessions now map a persisted failed outcome to status 'failed' (completed and cancelled stay idle, matching the live fold); warm sessions are unchanged, and the statuses filter inherits the mapping. * refactor(agent-core-v2): name the persisted field lastTurnReason Aligns with the established name for the same concept end to end (activity view's lastTurnReason, the v1 wire's last_turn_reason, and the SessionSummary mirror), instead of introducing a third variant. * fix(agent-core-v2): drain pending metadata writes before session teardown Review follow-up: closing/archiving a session right after a turn ended could dispose the scope while the outcome write was still queued, and delete() removes the session dir immediately after close. Await the pending metadata writes before the handle goes away. * fix(node-sdk): carry lastTurnReason through the SDK session summary Review follow-up: the in-process SDK path maps the engine summary through v2SummaryToSessionSummary, which dropped the new outcome field. Add it to the public SessionSummary type and the mapper; the parity gate projects it away (the v1 engine never records an outcome). * fix(node-sdk): populate lastTurnReason on live SDK summaries Review follow-up: resumeSession/reloadSession build their summary from the live session's metadata document, which now carries the outcome — surface it there too so the SDK reports it consistently for live and listed sessions. * fix(agent-core-v2): carry the last turn outcome across session forks Review follow-up: fork skips state.json when copying the session dir, so the fork's fresh metadata never had the outcome and a restart dropped a marker the warm fork was still reporting. The fork's metadata patch now inherits the source's lastTurnReason. * fix(agent-core-v2): settle pending outcome writes before reading a fork source Review follow-up: a fork requested right after the source's turn ended could read the metadata before the recorder's queued write landed, inheriting a stale or absent outcome. Drain pending metadata writes first. * fix(agent-core-v2): backfill restored outcomes into the session metadata Review follow-up: for sessions whose last turn ended before this field existed, the cold-resume seed restores the outcome into the activity view without a turn.ended fact, so the recorder never persisted it and cold listings stayed blank. The recorder now also watches the main agent's activity updates and backfills the restored outcome when nothing is persisted yet. * fix(agent-core-v2): never backfill restored cancellations Review follow-up: a restored 'cancelled' cannot be told apart from a programmatic abort (the activity event carries no interruptReason), and those are never persisted. Backfill now covers only completed/failed; user stops are still persisted from the live turn.ended fact. * refactor(agent-core-v2): rename the outcome recorder to outcome mirror Mirror is the codebase's established term for a write side that reflects live state into a store (SessionIndexMirror); Recorder has no precedent. * fix(agent-core-v2): backfill without bumping recency; header-only comments Review follow-ups: - a mere resume must not float an old session to the top of the list: metadata updates accept touchUpdatedAt:false and the outcome mirror's backfill uses it (live outcome writes keep bumping — turn end is a recency moment) - the mirror service's inline notes move into the file header per the package comment convention - drop the redundant |undefined from the SDK's optional outcome field * fix(node-sdk): read the live outcome for resumed session summaries Review follow-up: on a fresh resume the restored outcome can still be queued as a metadata backfill, so the document may lag a tick; the live activity aggregate already holds it. Resume/reload summaries now prefer the live value and fall back to the metadata field. * fix(agent-core-v2): confine the outcome backfill to pure resumes Review follow-up: the view publishes its turn.ended fold before this mirror's own turn.ended handler runs, so a live ending reached the backfill branch first and got persisted without the recency bump. The backfill now only applies when no turn ever started in this process — live endings always take the bumped write. * fix(agent-core-v2): drain the session-index mirror before session teardown Review follow-up: settling the metadata write alone left the fresh summary in the mirror's pending queue, so a list right after close could read a stale outcome from the read model. close/archive now also drain ISessionIndexMirror. Test harnesses register a mirror stub for the new dependency. * docs(agent-core-v2): fold the metadata drain contract into the file header * chore: include the SDK package in the changeset; fold the drain note into the header * fix(agent-core-v2): backfill restored cancellations too, quietly Review follow-ups: dropping every restored cancel loses legitimate user stops whose live write never landed (or was rejected) before a restart — cold surfaces never mark cancelled anyway, so healing them is harmless and strictly more accurate. The metadata disposal note moves into the file header per the comment convention. * fix(node-sdk): prefer the live outcome over the index in SDK listings Review follow-up: a live session that just started a new turn after a failure can briefly keep the stale outcome in the index while the mirror's clear is queued. listSessions now reads the live activity aggregate for warm sessions, matching the kap-server cold-only fallback. * fix(node-sdk): never read the metadata outcome for a live session Review follow-up: with a retry in flight the live aggregate has no outcome while the document may still hold the previous failure — the fallback showed the stale one. Live summaries now take the live aggregate's answer alone; the restored outcome is already seeded there on resume. |
||
|
|
8c766a6c30
|
feat(agent-core-v2): add the L3 unit layer and the Feature seam (#2678)
* feat(agent-core-v2): add the L3 unit layer and the Feature seam - introduce the L3 Service/Fiber unit layer: the Service base class with this.provide/effect/on/get/ref capabilities, the fiber runtime with thenable FiberHandles, collection contribution points, and the per-scope-kind ScopeUnits materialization fold - provide each scope's static registration batch as one atomic provideAll cascade transaction (waiting-area activation, sticky Failed on construction error) - add the DI unit inspection surface: App-scope debug ledger / dependency graph / cascade history services and the kimi-inspect DI view - add the Feature unit seam (IFeatureManager + feature assembly), port plan mode onto it, and add the contributed-command seam (agent-command domain + node-sdk RPC types) - remove the legacy dep-graph tooling - apply the header-only comment convention across src and test: strip non-header narration, keep the file header, tooling pragmas, and NOTE comments * feat(kap-server): gate the event.di.* debug feed to kimi-inspect connections - add an opt-in target set in SessionEventBroadcaster; the global fan-out now skips event.di.* frames for connections that never opted in, so kimi-web and other clients no longer receive the high-churn DI feed - WsConnectionV1 opts a connection in when client_hello carries client_id 'kimi-inspect'; removeGlobalTarget drops the opt-in on close - temporary gate until a client-declared event-type whitelist lands * chore(agent-core-v2): fix oxlint errors in the DI unit layer - build the live-ref container chain without aliasing this (no-this-alias) - snapshot the materialized map with Array.from and document why the copy is required (no-useless-spread) * test(klient): use string scope kinds in the lifecycle handle fakes The engine's LifecycleScope is a string enum now; the facade test doubles still returned the old numeric kinds and failed the handleWireSchema output validation. * build(nix): update the pnpmDeps fetch hash |
||
|
|
34c4181437
|
fix(kimi-code): keep kimi -p alive while background tasks are pending (#2675)
The 10-year default print wait ceiling (315360000s) overflowed Node's setTimeout limit (2^31-1 ms) into a 1ms fire, so the steer/drain wait returned instantly and kimi -p exited right after the main turn, killing pending background tasks and subagents. - add setClampedTimeout in agent-core-v2 _base, clamping delays to MAX_TIMER_DELAY_MS, and route every config-driven timer through it (timeoutOutcome, task wait/manager timeout, swarm attempt timeout) - chunk the print turn-endings wait against the real deadline instead of returning null on the first clamped timer fire - restore v1 semantics: a non-positive swarm subagent timeout is unbounded - default print_wait_ceiling_s to 2147483s (~24.8 days, the timer maximum) |
||
|
|
53c832dfdf
|
ci: release packages (#2592)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
75fe068a01
|
fix(cli): stabilize built-in capability installation (#2601)
* fix(cli): show built-in capabilities before the first session exists The lazy-session refactor left capability calls going through requireSession(), so on a session-less v2 startup /plugins reported the capabilities unavailable and hid the built-in rows behind the promo. Like plugin management, capability readiness and installs are app-global on the v2 engine: the node-sdk harness gains a capability facade over the global channel, and the TUI resolves session-or-harness for every capability call. * fix(cli): count the dev marketplace server as the default catalog dev.mjs always points KIMI_CODE_PLUGIN_MARKETPLACE_URL at its own repo-serving server, which the override gate mistook for a user-configured marketplace and suppressed the built-in capability rows in every dev run. The dev server now marks itself, and the gate treats that marked URL as the default catalog while still honoring real overrides (slash-command source, user-set env, KIMI_CODE_DEV_MARKETPLACE_URL). * fix(cli): align built-in capability updates |
||
|
|
f881cdd970
|
feat(cli): default CLI surfaces to the agent-core-v2 engine (#2627)
Some checks are pending
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
* feat(cli): default to agent-core-v2 engine with KIMI_CODE_LEGACY_FLAG opt-out - invert the engine gate: isKimiV2Enabled() now returns true unless KIMI_CODE_LEGACY_FLAG is truthy; KIMI_CODE_EXPERIMENTAL_FLAG no longer selects the engine - replace the experimental `kimi acp-v2` command with the native v2 implementation as the default `kimi acp`; the legacy acp-adapter path remains under the legacy flag - drop the acp-v2 experimental flag from the registry - rename the dev:cli:v2 script to dev:cli:legacy - update en/zh docs for the new default engine and the legacy flag * feat(cli): route export and provider through the engine gate - select the harness via isKimiV2Enabled(): agent-core-v2 by default, the legacy harness when KIMI_CODE_LEGACY_FLAG is truthy - close the harness after each one-shot command so the v2 engine's watchers do not keep the process alive - document both commands in the KIMI_CODE_LEGACY_FLAG env-var entry |
||
|
|
98ee35afd2
|
feat(agent-core-v2): add custom agent identity (#2573)
* refactor(agent-core-v2): simplify context tags and shared copy
Rename the context-injection tags to `<skill-loaded>` and
`<plugin-instructions>`, drop the product prefix from the CronCreate tool
description and the default agent description, and point the MCP OAuth
callback page back to "your terminal" instead of naming one client.
The callback page is shared by the ACP host, the web UI, and embedding
hosts, so naming a single client was inaccurate there. The tags and the
two descriptions read exactly the same without the prefix. Verified no
runtime consumer matches the old tag names; the updated snapshots cover
the tool descriptions that changed.
* feat(agent-core-v2): add a switch for the product-documentation skills
Five builtin skills document this CLI itself — `update-config`,
`custom-theme`, `mcp-config`, `check-kimi-code-docs`, and
`import-from-cc-codex`. Their names and descriptions sit in the system
prompt on every turn, which is dead weight for runs that will never
reconfigure the CLI.
Add a top-level `builtin_product_skills` field (also settable through
`KIMI_CODE_BUILTIN_PRODUCT_SKILLS`) to drop them. On by default, so
nothing changes unless it is set; the trade when off is that the model
loses the guided flows for those tasks.
Filtering happens where the catalog is assembled — a later filter would
leave the skills advertised to the model. The whole section is one
scalar, so it exercises the section-level env binding branch and needs
its own strip: `stripEnvBoundFields` only walks object fields, so an env
override would otherwise be written back into `config.toml`.
* feat(agent-core-v2): add custom agent identity
Add an `[identity]` config section (`name`, optional `slug`, both also
settable through `KIMI_CODE_IDENTITY_NAME` / `KIMI_CODE_IDENTITY_SLUG`)
that sets the identity the agent presents: the name it calls itself in
the system prompt, the `User-Agent` product token sent to third-party
providers, and the client name announced to MCP servers. Leaving it
unset changes nothing.
Until now every one of these was fixed, which left no way to run the
agent as part of another product — an internal deployment, a fork with
its own branding, an embedding host.
The identity resolves inside the engine rather than being seeded by each
host, so it applies to every launch surface — including headless runs,
which today seed no display name at all and fall through to the built-in
default.
Two deliberate asymmetries:
- The display name is a filling value with a fallback chain (config >
host-declared > the consumer's own default); the slug is a rewriting
value with two states only, so with no identity configured the
rewriting paths are equivalent to not existing.
- The rewrite happens in the outbound header assembly, the one layer
that knows which vendor it is building for. Vendors declaring
`hostHeaders: 'full'` keep the host's own product token, which that
header set is built around and which backends key on; the configured
identity applies to the third-party path.
Resolution is lazy throughout: config loads asynchronously, and a
constructor snapshot would freeze the pre-load value under some startup
orderings.
Two input edges the resolver has to absorb, since both would otherwise
reach the User-Agent builder and either break it or quietly rewrite the
header: blank and whitespace-only values read as unset in the file just
as they already did in the env, so a stray `name = ""` cannot claim an
identity; and a name that folds away to nothing under slug
normalization (a CJK-only name, say) falls back to a neutral token
rather than producing a blank product, which the builder rejects.
* fix(agent-core-v2): keep the file value when a scalar env binding fails to parse
`config.ts` documents that an env value failing its binding's `parse` is
ignored, and `applyEnvBindings` honors that for object fields by
assigning only when the resolved value is defined. `applySectionEnv`
returned the parse result straight through for whole-section scalar
bindings, so a blank or mistyped variable resolved to `undefined` and
cleared the configured file value instead of being ignored.
Nothing hit this before: every existing section either binds object
fields or is env-only. `builtin_product_skills` is the first
whole-section scalar binding, where exporting an empty or misspelled
`KIMI_CODE_BUILTIN_PRODUCT_SKILLS` would silently undo a configured
`false`.
* feat(agent-core-v2): extend the custom identity to discovery and global MCP
Two outbound paths still announced the built-in product name under a
configured identity:
- `DiscoveryService` read the host User-Agent straight from bootstrap
args when refreshing provider models, so custom registries — which are
third-party endpoints — saw the original token while chat requests to
the same class of endpoint saw the configured one.
- `SDKRpcClientV2` builds its own global `McpOAuthService` plus a
throwaway `McpConnectionManager` for server testing, neither of which
goes through the workspace-owned manager that carries the resolver.
Both now resolve the identity from the App scope.
* refactor(agent-core-v2): neutralize remaining copy and align comments
The synthetic MCP authentication tool description is injected into the
model context and still named the product; it and the OAuth callback
pages now use client-neutral wording. "Return to your terminal" was no
improvement over naming a client — both assume what the host is, and
that page serves the ACP host, the web UI and embedding hosts alike.
Comments introduced by the identity work move into their module headers,
per the domain convention. Interface field docs stay: the rule names
functions, methods and statements, and field-level docs are established
across the codebase.
The new tests gain scenario headers and dispose the scoped hosts they
create, and the `[identity]` docs state which engine reads the section.
* fix(agent-core-v2): read the product-skill switch after config is ready
`BuiltinSkillSource` is the lowest-priority skill source, so the workspace
catalog loads it first — before `IConfigService` has finished loading — and
keeps the contribution it returns for the life of the handler, with no
reload path and no change event. Reading `builtin_product_skills` eagerly
therefore stranded the startup configuration: an explicit `false` could be
ignored for the whole process. `UserFileSkillSource` already awaits config
readiness for exactly this ordering; this source now does the same.
Also record the identity collaborator in the two module headers that gained
the dependency without documenting it, and scope the
`builtin_product_skills` docs to the engine that reads it, matching the
note the identity section already carries.
* fix(agent-core-v2): apply the product-skill switch to session-less listings
`builtin_product_skills = false` only reached the scoped skill source. The
SDK's `listWorkspaceSkills` and the server's `GET /workspaces/{id}/skills`
both composed the raw `BUILTIN_SKILLS` constant, and the web app feeds its
pre-session onboarding menu from that route — so the five product skills
stayed listed until a session existed, then vanished from the session's
catalog.
Move the decision into `visibleBuiltinSkills(enabled)` next to the constant
and route every consumer through it, reading the switch via the shared
`builtinProductSkillsEnabled`. Keeping "what counts as a product skill" in
one place is the point: three copies of the predicate would drift the next
time a builtin is added. The SDK listing also awaits config readiness,
which it did not do before.
* fix(node-sdk): await config before materializing the global MCP OAuth provider
`McpOAuthService` caches providers by store key and stamps the client name
when it first builds one, and the preceding `globalMcpConfig.get()` reads
`mcp.json` directly rather than through `IConfigService`. So a
`beginGlobalMcpServerAuth` call made right after the harness is created
could resolve the identity before config finished loading, pinning the
built-in label for the rest of the process — including the OAuth dynamic
registration a third-party MCP server records.
`testGlobalMcpServer` already awaited config readiness for its own reasons;
this path now does too.
* refactor(agent-core-v2): drop the unused builtin-skill registrar
`registerBuiltinSkills` stamped the raw constant into a catalog for "edge
composition without a Session" — exactly the shape that now has to respect
`builtin_product_skills`. It has no callers in v2 and is not exported from
the package index, so it was dead code that also stood as an invitation to
bypass the switch. v1 keeps its own copy.
Every remaining path composes builtins through `visibleBuiltinSkills`.
* fix(agent-core-v2): send the configured identity on custom-registry imports
`:import_registry` fetched a user-supplied third-party URL with a
hardcoded `kimi-code-kap-server` User-Agent, so the first request to a
registry announced the product while every scheduled refresh of the same
registry announced the configured identity. The hardcoded value was wrong
on its own terms too: that token names the server, and this path also runs
in the CLI.
Both services now project the identity through `identityUserAgent`, which
carries the two guards (no host header, or no identity) once instead of
per caller. The model catalog keeps an inline copy on purpose — kosong is
a foundational layer and must not import an app domain.
Sweeping the remaining outbound User-Agent sources found no further gaps:
WebFetch deliberately sends a Chrome-like UA, the models.dev catalog fetch
sends none from the CLI, and kap-server's `user-agent` reads are inbound.
* docs: scope the identity env vars and condense the changeset
The environment-variable reference advertised all three new variables
without noting that only the agent-core-v2 engine reads them; the
configuration page already carried that note. Added in both locales.
The changeset had grown into two paragraphs of implementation detail,
which is what would land in the CLI release changelog. `gen-changesets`
asks for one short sentence plus at most a one-line usage hint.
* docs(agent-core-v2): describe the identity as what the agent calls itself
The module headers had drifted into describing the feature by what it
keeps off the wire rather than what it configures. Reworded so they state
the capability: the identity is the name the agent uses for itself, and
the unset case is a no-op rather than something "safe". The product-skill
switch excludes skills rather than hiding them.
Wording only; behavior and structure unchanged.
* test(agent-core-v2): cover the identity on custom-registry imports
The import path switched from a hardcoded `kimi-code-kap-server` token to
the host User-Agent projected through the identity, but nothing asserted
it. Two cases pin both halves: a configured identity reaches the request,
and an unconfigured one leaves the host header intact — the second matters
because a single case would also pass if one hardcoded value had simply
replaced another.
Both fail against the previous implementation.
* fix(node-sdk): guard every global MCP OAuth path behind config readiness
`McpOAuthService` caches providers by store key and stamps the client name
when it first builds one, so any path that can materialize a provider has
to run after config has loaded. `beginGlobalMcpServerAuth` awaited
readiness, but `resetGlobalMcpServerAuth` reaches the same cache through
`invalidate()` -> `getProvider()` without waiting: resetting auth right
after the harness is constructed pinned the built-in client name, and the
await added to the begin path could not help because it then reused that
cached provider.
Rather than add the missing await, the accessor is now async and holds the
guard itself, so the service cannot be obtained before config is ready and
a future entry point cannot forget. The remaining `configReady` in
`testGlobalMcpServer` stays — that one is for its own `[mcp]` section read.
* fix(agent-core-v2): send the configured identity on models.dev requests
The directory fetch behind `listModelsDevProviders` / `getModelsDevProvider`
still hardcoded a `kimi-code-kap-server` User-Agent, so browsing or importing
from models.dev announced the built-in product — and claimed to be the server
even when running in the CLI. Only the custom-registry import had been fixed.
`getModelsDevCatalog` now takes the User-Agent from its caller: the module is
plain module-level state with no container access, and the value depends on
the host and the configured identity, which only the calling service can see.
All four third-party fetches in that service share one helper.
Where the host states no User-Agent, a neutral token stands in rather than
dropping the header — these are directories the service chooses to call, so
there is no host intent to preserve, unlike the provider requests the model
catalog assembles.
Both new tests fail against the previous hardcoded value.
* test(agent-core-v2): assert the product-skill set literally
The expected sets were derived from the same `productSpecific` field the
production filter reads, so a builtin silently losing its marker would just
move between sets and leave every assertion green — while staying visible to
the model once the switch is off. The five names are now literal, with a test
asserting the marked set matches them exactly.
Dropping the marker from one skill now fails four tests instead of none.
Also states the App scope in the identity contract header, per the domain's
comment convention for contract files.
* fix(agent-core-v2): normalize the host-declared display name too
Blank and padded values were normalized on the config side but not on the
host fallback, so an embedding host passing `displayName: " "` rendered
"You are ," into the system prompt, and a padded name kept its padding.
Same rule now applies to every source of the name.
Also names `agentIdentity` as the collaborator in the request-headers
adapter header, which described the value it obtains without saying which
domain resolves it.
The three new cases fail against the previous implementation.
* fix(agent-core-v2): keep the configured slug when the host sends no User-Agent
The neutral fallback added for hosts that state no `User-Agent` discarded a
configured identity along with it: `identityUserAgent` returns `undefined`
as soon as there is no host header to rewrite, so `?? DEFAULT_IDENTITY_SLUG`
sent the literal `agent` even when `[identity].slug` was set — precisely the
case that fallback exists to serve. The configured slug now stands on its
own, with the neutral token reserved for having neither.
The four combinations of (host header, configured slug) had three tests; the
missing one is the one that was wrong. It now fails without this change.
`outboundUserAgent` also awaits config readiness before reading the identity,
so a browse issued right after bootstrap cannot send the pre-load value — the
guard lives in the accessor rather than at its four call sites, matching how
the same race is handled elsewhere in this branch.
Both headers here and in `discoveryService` now name `agentIdentity` as the
collaborator resolving that token.
* test(acp-server): follow the renamed skill-activation tag
`acp-server` arrived on main after the tag rename, so its two assertions
still expected `kimi-skill-loaded` and failed once the branches met. Also
updates the web app's CSS comment, which named the old tag from the start
of this branch — a comment, so nothing ever failed on it.
Found by CI: the merge verification only ran agent-core-v2's suite, and
this package is neither a dependency nor a dependent of it.
* fix(agent-core-v2): present the configured slug on registry refreshes too
The previous round taught the import path to fall back to the configured
slug when the host states no `User-Agent`, but left the scheduled refresh
of the same registry on the bare projection — so one registry could see
`acme` on import and the runtime default on refresh.
Extracting `identityUserAgent` had made the two paths share a function
without sharing the policy. The choice itself is now the shared piece:
`identityUserAgentOrDefault` always yields a value, for the directories
this process chooses to call, while `identityUserAgent` stays the form
that rewrites only what the host already sends — what a provider request
needs, where the host's silence is its own choice.
* docs(agent-core-v2): move new member docs into the module headers
The domain's comment convention is absolute — comments live solely in the
top-of-file block — and I had read the "functions, methods, or statements"
clause as leaving interface members out. It does not: only 25 of 734 v2
sources carry an indented block, so the members I documented were the
exception, not the pattern.
Seven members across six files move into their headers. `types.ts` had no
header at all, so it gains one.
* fix(agent-core-v2): connect session MCP overlays after config is ready
The shared manager reaches `connectAll` through `initialize()`, which awaits
the config domain first; `sessionOverlay` called it straight away. A session
carrying ephemeral `mcpServers` created right after bootstrap therefore
resolved the client name before config had loaded and initialized under the
built-in one.
The blast radius is wider than that one connection: a remote server sends
the overlay through `hasTokens()`, which materializes an OAuth provider on
the *shared* service and caches it by store key — so the early name outlives
the connection that raced. The overlay now connects behind `mcpConfig.ready`,
leaving the returned readiness promise unchanged.
* fix(agent-core-v2): reload builtin skills when their switch changes
The workspace catalog keeps each source's contribution for the life of the
handler, so a `builtin_product_skills` toggle never reached an existing
handler's sessions. That was harmless while every surface read the same
constant — but routing the session-less listings through the config made the
two views disagree, since those read the switch on every call.
Follows `ExtraFileSkillSource`: subscribe to the owning section and fire
`onDidChange`, which the catalog already turns into a source reload. The
test asserts an unrelated section does not trigger it.
* fix(agent-core-v2): apply the identity to self-configured web services
`[services.moonshot_search]` and `[services.moonshot_fetch]` name their own
`base_url`, so both services can point at an endpoint the user chose — but
each forwarded the host request headers verbatim, sending the built-in
product token there under a configured identity.
Only the services-config path is rewritten; the managed OAuth path keeps the
host headers as they are, being the endpoint the session authenticated
against. The distinction is the same one the model catalog draws per vendor.
`identityHeaders` carries the rewrite across a whole header set, so this is
the fourth caller sharing the projection rather than repeating its guards.
A pair of tests pins both halves.
My earlier sweep classified these two as official by their names instead of
asking who chooses the URL, which is why they were missed. The contract
header is also condensed here, per the convention below.
* docs(agent-core-v2): condense the identity headers to their contracts
The comment convention is one sentence with two halves — comments live only
in the top-of-file block, *and* that block states the module's role without
narrating implementation. Moving the member docs up last round satisfied the
first and broke the second: the headers ended up spelling out the slug
folding algorithm, the strip mechanics, and the load order.
Kept what a caller or the next editor would get wrong without it (why the
value is read rather than snapshotted, what `undefined` obliges a consumer
to do, why this source waits for config). Dropped what the code already
says. 22/12/12/13 lines, against 53 in `catalogService.ts` — length was
never the problem.
* fix(agent-core-v2): rebuild active prompts when the builtin skills change
Reloading the catalog on a `builtin_product_skills` toggle left existing
agents holding the old listing: `AgentProfileService` refreshes the prompt
only for the plugin source, so a disabled switch kept advertising skills
that were gone, and enabling it left them missing until an unrelated
refresh.
The plugin source is special because it also contributes prompt sections
(#2314), and the file-backed sources are left out for cost — their fs
watches would rebuild every agent's prompt on each edit. The builtin source
has no watch: it changes only when its config switch is toggled, so it
belongs with the plugin source rather than with the file ones.
Subscribing to the catalog rather than the config section is load-bearing.
The catalog fires after the contribution is replaced, whereas a config
subscription would race the reload, and `resolveSkillListing` only awaits
the catalog's *initial* readiness — so the rebuilt prompt could read the
listing it was meant to replace.
The source id is a named constant now, so the subscription does not match
on a bare string.
* refactor(agent-core-v2): freeze the agent identity for the process lifetime
The identity is announced outward (MCP initialize, OAuth registration,
provider request logs) and cannot be re-announced, so mid-process changes
could only ever apply partially. Resolve it once when config first loads
and hold it for the life of the process: IAgentIdentity now hands out a
frozen snapshot via resolved()/current(), carrying finished products
(outbound User-Agent variants, rewritten header set) so call sites stop
composing host headers with the slug themselves. The kosong host-headers
port carries two finished layers and the catalog only picks one; consumers
gain no invalidation obligations because the value can never change after
the freeze. [identity] edits take effect on the next start (documented).
* fix(agent-core-v2): locate the User-Agent header case-insensitively
HTTP header names are case-insensitive, but the snapshot builder looked up
'User-Agent' by exact key: an embedding host spelling it 'user-agent' got no
third-party UA and kept its own product token on the services path even with
an identity configured. The builder now locates every case variant and
rewrites each in place, keeping the host's spelling. Also corrects the two
web-service headers that still described both paths as sending the bootstrap
headers, naming agentIdentity as the collaborator behind the config path,
and documents that a resumed session keeps its recorded system prompt.
* fix(agent-core-v2): attribute header provenance from the finished third-party layer
Inspection reconstructed the non-full host layer from the raw headers with an
exact-case 'User-Agent' lookup, so a host spelling the header 'user-agent'
got a resolved User-Agent with no provenance entry even though the runtime
sends the rewritten value. buildModel now captures the port's finished
third-party layer in the trace and attribution reads it, keeping inspect()
on the same resolution pass as get(). Also condenses the identity contract
header to its external role, and documents that an existing MCP OAuth
authorization keeps the client registration it was granted under (reset the
server's auth to register under the new identity).
* fix(agent-core-v2): keep web tool backends from racing the identity freeze
An env-configured [services] endpoint is visible before config finishes
loading, and FetchURLTool / WebSearchTool materialized their backends at
construction — so a fast bootstrap could hit the identity snapshot's
pre-freeze guard during agent creation, and the composed backend pinned
config and login state for the agent's lifetime against the service's
documented per-call resolution. Both tools now resolve their backend per
invocation, the WebSearch activation gate checks presence alone through the
new hasWebSearchProvider() (no provider composition, no identity read), and
bind() awaits the identity freeze before materializing the model, whose
resolution reads the identity through the host-headers port.
|
||
|
|
0abcd00f7f
|
feat(cli): add built-in Computer Use and WebBridge capabilities (#2407)
* feat(agent-core-v2): add built-in capabilities (kimi-cu, kimi-webbridge) with REST routes
Add a capability domain holding a closed registry of built-in product
capabilities. Each entry owns layered readiness detection and idempotent
install orchestration: binary runtimes from fixed official CDN URLs
(KimiCU.app + launchd service + TCC permission state; the WebBridge
daemon with start-if-down semantics for Kimi Work coexistence) plus
agent wiring through the plugin service. The WebBridge wiring un-shadows
stale user-source skill copies (user priority beats plugin priority).
kap-server exposes the domain as GET /api/v1/capabilities,
GET /api/v1/capabilities/{id}, and POST /api/v1/capabilities/{id}:install
with client-polled progress and new wire codes 40418 / 40922 / 40923.
The plugin marketplace gains an official kimi-webbridge entry
(browser-control skills) packaged by the existing CDN build.
* fix(agent-core-v2): rename the webbridge wiring plugin to kimi-webbridge-skill
An official kimi-webbridge guide plugin (install/remove setup skills,
v3.0.4) already exists at the marketplace path the capability installer
pointed at — a different artifact owned by another release line. Give
the browser-control usage-skill plugin its own id/path instead of
colliding with (or overwriting) the guide plugin. The capability entry's
detect/install now tracks kimi-webbridge-skill; a machine with only the
guide plugin correctly reports the skill layer as missing.
* feat(agent-core-v2): shelf installs auto-complete capability binary layers
Two changes to make the plugin marketplace a first-class install path:
- Marketplace gains kimi-cu (sourced from the CU team's CDN zip — no
repackaging) and the kimi-webbridge usage-skill plugin now claims the
kimi-webbridge id at v4.0.0, deliberately superseding the WebBridge
guide plugin (v3.0.4, install/remove guide skills): guide users get a
version upgrade onto the real usage skill.
- The capability service subscribes to IPluginService.onDidReload: when
a capability's wiring step flips to ok through ANY install path
(shelf, TUI, CLI), it auto-completes the missing binary layers
(KimiCU.app + service, or the WebBridge daemon). Triggers only on the
false→true edge so completed installs with still-missing manual steps
(TCC permissions) never retrigger heavy downloads on later reloads.
* fix(plugins): keep kimi-webbridge plugin version aligned with the upstream skill
The plugin version tracks the bundled official usage skill (1.11.3) so
version drift against the WebBridge release line stays visible, instead
of minting an independent 4.0.0.
* fix(agent-core-v2): never report the webbridge installer-script version as the product version
The on-disk ~/.kimi-webbridge/bin/kimi-webbridge.version file tracks the
installer's own lineage (3.1.x, bumps on every install/upgrade run),
not the product version (v1.11.3 — daemon, extension, and skills all
share it). A downed daemon would have shown the misleading installer
number; report no version instead (live /status remains the source of
truth).
* chore(plugins): list kimi-cu on the marketplace without a pinned version
Marketplace versions are optional by schema: rows display the version
detected from the installed plugin's manifest, and update prompts only
fire on a valid semver latest > local comparison. A hand-maintained
number would drift just like the guide plugin's did. The locally built
kimi-webbridge entry keeps its manifest-stamped version (1.11.3).
* fix(agent-core-v2): fire onDidReload on plugin mutations, not just explicit reload
installPlugin / setPluginEnabled / removePlugin changed the catalog
silently — consumers listening to onDidReload (session skill-catalog
convergence, the capability shelf-install hook) only converged on an
explicit reloadPlugins(). Fire the same summary-shaped event on every
mutation (added:[id] / [] / removed:[id]) so every install path
converges. This also unbreaks the shelf-install hook on real hosts:
its unit tests passed against a fake emitter that fired on installs,
which the real service never did.
* feat(kap-server): add plugin management and marketplace REST routes
Expose the App-scope plugin service over the wire so non-CLI hosts
(desktop, web) can manage plugins end to end:
- GET /api/v1/plugins/marketplace — catalog (pluginMarketplaceUrl
server option / KIMI_CODE_PLUGIN_MARKETPLACE_URL env / production
default) merged on demand with live install state; updateAvailable
only on strict semver catalog > installed (no semver dependency)
- GET /api/v1/plugins, POST /api/v1/plugins {source}
- POST /api/v1/plugins/{id}:{enable,disable,remove}
- New wire code 40419 plugin.not_found
Mutations flow through IPluginService, so they serialize with other
install paths and fire onDidReload (session skill catalogs and the
capability shelf-install hook converge).
* feat(agent-core-v2): surface a machine-key note from capability installs
CapabilityEntry.install now resolves an optional note exposed through
CapabilityInstallProgress.note (wire-visible). The webbridge entry
returns 'user-skill-migrated' when it replaces a pre-existing
user-source skill (from the official installer) with the plugin-managed
copy — clients can localize the migration instead of the skill silently
disappearing from the user's directory.
* feat(tui): let the real WebBridge marketplace entry win over the pinned promo
The hardcoded Web Bridge row was built when WebBridge had no plugin
package — it pinned above the Official tab and shadowed any catalog
entry with the same id (open-in-browser only). Now that the marketplace
carries the real kimi-webbridge plugin, flip the precedence: the catalog
entry renders and installs normally, and the pinned promo becomes a
loading/error/legacy-catalog fallback only. Footer counts keep their old
semantics (catalog-only; the promo row is never counted).
* fix(tui): dim the installed state so it stops reading as the install action
Both badges shared a near-identical green-ish treatment in the same
column, making a quiet fact look like a clickable action. States now
recede (installed → textDim) while actions stay loud (install →
primary, update → warning).
* feat(agent-core-v2): converge plugin state across processes sharing a home
Multiple hosts share one KIMI_CODE_HOME (CLI, desktop, other agents), but
each PluginService kept a private in-memory snapshot: a plugin installed
or removed in one process stayed invisible to every other live process
until its next restart — new sessions there kept offering stale plugin
skills/MCP, and the capability shelf hook never saw peer installs.
Watch <home>/plugins for installed.json changes and reloadPlugins
(debounced, echo-suppressed around our own mutations) so all consumers
converge in well under a second: session skill catalogs, plugin MCP
mounts, and the capability shelf-install hook alike.
* fix(agent-core-v2): un-shadow webbridge user skills in BOTH user dirs
kimi-code resolves user-scope skills from two roots (~/.kimi-code/skills
and ~/.agents/skills), both at priority 20 — a stale copy in either
shadows the plugin-managed wiring (priority 5), and also keeps the
capability working after the plugin is removed, which reads as
'uninstall did nothing'. Migrate copies in both dirs during install;
other runtimes' dirs (~/.claude, ~/.codex) remain untouched.
* feat(tui): show live runtime-setup progress for capability installs
Installing a capability plugin (kimi-cu, kimi-webbridge) from the
/plugins shelf kicked off a silent background binary install — the row
flipped to installed while megabytes of runtime downloaded invisibly.
Route capability entries through the capability surface instead: the
panel's inline installing line now mirrors live progress (step +
percent) until the install settles, and the transcript reports
ready / failure-with-retry / still-running accordingly. Capability
removal prints an explicit note that runtime binaries are deliberately
left untouched (the capability keeps working), since that read as
'uninstall did nothing'.
Plumbs the capability service through klient's global facade
('capabilityService' decorator resolves in-process) and the node-sdk
v2 client; Session exposes it with a structural feature-detect so v1
engines fail clearly.
* docs(plugins): keep the kimi-cu marketplace blurb accurate for every client
Only the capability-aware clients auto-install the KimiCU.app runtime;
older builds still get wiring-only (the wrapper's error message then
points at the official setup script). Don't overpromise in the catalog
text every version reads.
* feat(agent-core-v2): install capability wiring from client-bundled plugin copies
The kimi-cu / kimi-webbridge wiring plugins ship inside the client release
instead of the marketplace catalog, binding their visibility to the client
version. Capability installs now resolve the bundled copy (env override,
then npm-layout and source-checkout probes from the module) and install it
as a local path, replacing the two CDN zip URLs. A missing bundle fails the
wiring step with a clear reinstall-or-upgrade message.
* build(cli): bundle the capability wiring plugins into client releases
Vendor the official kimi-cu plugin (v0.5.4, from the CU team's plugin zip)
next to kimi-webbridge under plugins/official, copy both into
apps/kimi-code/bundled-plugins at build time, and ship them in the npm
package (files) and the native SEA blob (a new bundled-plugins asset set
extracted into the native cache at startup, published to the engine via
KIMI_CODE_BUNDLED_PLUGINS_DIR). Desktop points the same variable at its
extraResources copy. The .gitignore build-output entries are anchored so
sources under src/native and test/native stop being silently ignored.
* revert(plugins): remove the kimi-cu and kimi-webbridge marketplace entries
Both capabilities now distribute with the client (bundled wiring), so the
catalog drops back to kimi-datasource / superpowers / vercel-plugin. Older
clients never see the entries; current clients install from the Built-in
section. This also reverts the marketplace blurb commit 0635e99c5.
* feat(tui): add a Built-in capabilities section to the plugins panel
The Official tab now opens with a Built-in section fed by the engine's
capability registry (kimi-cu / kimi-webbridge): per-row install state
(install / finish setup / ready), Enter runs the full capability install
with live progress, and unsupported rows hide (kimi-cu off macOS). The
WebBridge promo fallback only remains for v1 engines — on v2 the real
built-in entry wins. Rows double as the reinstall path: a client upgrade
ships newer wiring, and installing again upserts from the new bundle.
* docs(plugins): document the Built-in section and refresh the capability changeset
* build(nix): stage bundled capability plugins into the SEA build
The native SEA blob now embeds the bundled-plugins asset set, so the nix
derivation needs the plugins tree in its src fileset and the staging step
alongside copy-web-assets before build:native:sea.
* revert: drop the client-bundled wiring distribution
Built-in visibility is simpler to get by injecting the two capability
entries into the marketplace catalog at load time; the wiring plugins
themselves keep installing from their fixed official CDN zips. Removes
the vendored kimi-cu plugin, the bundled-plugins npm/SEA packaging and
flake staging, the engine bundle resolver, and the plugins panel's
Built-in section. Keeps the /agents/ and /native/ gitignore anchors so
sources under src/native and test/native are not silently ignored.
* feat(cli): inject the built-in capability entries into the marketplace catalog
The kimi-cu / kimi-webbridge entries are appended by the client at catalog
load time instead of being served by the remote marketplace.json, binding
their visibility to the client version (older clients never see them). No
version is pinned — reinstalling upserts the wiring — and ids the catalog
already carries always win. In a source checkout the webbridge entry
installs the repo's own plugin copy; packaged builds use the official CDN
zip. This reverts the docs paragraph about the Built-in section, which the
simpler approach makes unnecessary.
* test(tui): select the catalog's own first row in marketplace install tests
The client-injected capability entries suppress the WebBridge promo and
append after the catalog rows, so Kimi Datasource now leads the Official
tab — the extra down-key landed on kimi-cu instead.
* feat(cli): surface the built-in capabilities as client-injected marketplace entries
The kimi-cu / kimi-webbridge entries are injected into the marketplace
catalog by the client (v2 engine, default catalog only) instead of being
served remotely, binding their visibility to the client version; injected
rows mask same-id catalog rows, so what these ids mean stays decided by
the client release — a future official listing only reaches older clients,
whose fix is to upgrade.
The /plugins panel shows capability readiness on the rows (setup
incomplete / installing…), platform-gates kimi-cu to macOS, and Enter
finishes the runtime setup with live progress; v1 keeps the plain plugin
install path and the WebBridge promo fallback.
Capability and plugin calls move from the ad-hoc REST routes onto the
typed klient contract (capabilityService next to pluginService), so the
public REST surface returns to its pre-feature shape. Detection is
presence-only — version pins removed: the current version is always read
live (Info.plist, daemon status, install records), installs are
detect-first and idempotent so an interrupted setup can be retried, and
reinstalling pulls the latest managed artifacts (the passive upgrade
path).
* ci: retrigger checks
* fix(cli): recognize Computer Use CDN plugins as official
* fix(cli): keep built-in entries on catalog outage and isolate detector failures
Two review follow-ups: the client-injected entries no longer disappear when
the marketplace catalog is unreachable (they are not served by it), and a
single capability's failing detect probe degrades to a failed step on that
entry instead of rejecting the whole listCapabilities call.
* refactor(cli): simplify built-in capability integration
* refactor(cli): source built-in catalog rows from the engine and tighten detect probes
The injected marketplace entries are now derived from the engine's
capability registry (listCapabilities) instead of hardcoded client-side
copies — the util only owns the mask/append mechanics, and capability ids
are no longer pinned in the CLI (the remove note resolves them through the
registry too). kimi-cu's detect-path probes (service-status, xpc-ping) get
a 3s timeout — they answer in milliseconds when healthy but run on every
status listing, so a wedged binary must degrade quickly instead of
stalling the panel. Document the Official tab's built-in capability rows
in the plugins guide.
* fix(cli): answer capability id membership without running detectors
listCapabilities() runs every entry's detect probes (seconds on a wedged
binary), so using it to decide whether to print the post-remove hint made
every plugin removal pay a full detection round. The id set is part of the
client/engine contract (mirrored in the klient schema), not product data
that drifts — restore the closed-set check. The injected catalog rows keep
flowing from the registry.
* fix(agent-core-v2): make capability setup recover from disabled, partial, and wedged states
Three review follow-ups on the install path: setup now re-enables the
wiring plugin when a previous disable survived installPlugin's upsert
(detection requires enabled, so it would otherwise strand the capability
at partial); the webbridge daemon-binary step verifies the executable bit
on POSIX, so an install interrupted between rename and chmod re-downloads
instead of failing start with EACCES; and kimi-cu's detect degrades
wedged CLI probes (service-status, xpc-ping) to failed steps instead of
throwing, keeping the detect-first install able to repair the remaining
layers — with the probe timeout injectable for tests.
* fix(agent-core-v2): abort capability downloads whose byte stream stalls
downloadToFile had no inactivity deadline: a CDN connection that stops
producing bytes hung the background install forever, wedging the
capability in a permanent installing state (retries rejected as
in-progress) until the process restarted. An idle watchdog now fails the
download after 30s without a chunk; slow but flowing downloads are
unaffected.
* fix(tui): stop offering capability setup on unsupported platforms
An installed wiring plugin whose capability is unsupported on this
OS/arch (kimi-cu off macOS, webbridge on an unknown arch) was treated
like a partial setup: the Installed tab showed setup incomplete and
Enter routed to installCapability, which the service always rejects.
Setup actions are now gated to actionable states (not_installed /
partial); unsupported renders as a dim fact and Enter opens details.
* fix(agent-core-v2): cover the two remaining install wedge modes
Review follow-ups: the KimiCU app step now requires an executable binary,
so a ditto interrupted mid-copy reads as missing and the next setup
re-copies instead of failing EACCES forever; and downloadToFile's idle
budget now also covers the response-header phase via an AbortSignal on
the fetch itself, so a connection that never completes headers fails the
install (clearing the running state) instead of hanging it.
* fix(tui): render capability rows independently of the catalog fetch
While the marketplace catalog was loading or unreachable, the Official
tab showed only the pinned WebBridge promo — built-in runtime setup was
blocked by an unrelated remote fetch, and Enter opened the browser
instead of installing. Locally-known capability rows (from the engine
registry) now render and install in every catalog state; the promo
remains only as the v1 fallback.
* fix(agent-core-v2): keep KimiCU cleanup timeouts best-effort
stopOldProcesses is documented as || true, but runCommand propagates
timeouts: a wedged old binary made kimi-cu uninstall exceed the command
timeout and the reinstall died before ditto could replace the app.
Cleanup commands now swallow failures (the timeout already attempts a
kill) so the replacement always proceeds; the command timeout is
injectable for tests alongside the probe timeout.
* fix(cli): inject built-in entries only for the default marketplace catalog
Injection is part of the default catalog experience: any explicit
replacement (slash-command source or KIMI_CODE_PLUGIN_MARKETPLACE_URL)
now opts out wholesale — its same-id rows are never masked by the
built-ins, and an unreachable custom catalog surfaces its own failure
instead of being silently replaced by a built-in-only tab.
* refactor: align capability row rendering on the source marker and drop conditional spreads
Marketplace-row capability enrichment (status, badges, issue details,
platform filtering) now keys on the capability:<id> source marker — the
same condition Enter uses to route installs — so a custom catalog row
that merely reuses a built-in id renders and installs as a plain plugin.
Also replaces the conditional-spread optional fields with direct
undefined-valued assignments per the repo coding rules.
* refactor(agent-core-v2): move capability comments to the file headers
The domain's comment convention allows only the top-of-file block:
responsibility and scope context for the recent hardening (detect-first
idempotent install, executability gates, probe-failure degradation,
best-effort cleanup, download watchdog, per-entry detection isolation)
now lives in the module headers, and inline narration beside statements
and members is removed.
* fix(tui): follow an in-progress capability install instead of restarting it
Opening /plugins while a capability setup is already running showed the
installing… row, but Enter called installCapability again and the
service's duplicate-start rejection (40922) surfaced as a fake failure.
The panel now checks the live status first and, when an install is
already running, skips the start call and just polls for the existing
progress.
* fix: align two more replacement paths with their contracts
The EXDEV daemon-binary fallback now stages on the target filesystem and
atomically renames over the destination instead of opening a
possibly-running binary for write (ETXTBSY on Linux). And the panel's
fallback capability rows (catalog loading/error) now follow the same
default-catalog condition as the loader injection, so an explicitly
overridden marketplace fully replaces the Official tab.
* fix(tui): make the built-in row marker unforgeable
The capability:<id> source string was the trust signal for routing rows
into capability installs, but any catalog can write that string — a
custom marketplace could smuggle a row past the third-party trust path
into an official runtime install. Injected rows now carry an internal
builtIn flag that the field-by-field catalog parser never produces;
rendering and install routing key on the flag, and the source string is
purely diagnostic.
* fix(agent-core-v2): include MCP server enablement in capability readiness
A user who disabled the kimi-cu stdio MCP server (/plugins mcp disable)
got a ready capability with no Computer Use tools in new sessions: the
plugin step only checked the plugin toggle, and installPlugin's upsert
preserves per-server state. Readiness now requires every declared MCP
server enabled (reporting e.g. mcp 0/1 enabled), and setup re-enables
disabled servers alongside the plugin toggle.
* fix(agent-core-v2): shell-quote ditto paths in the elevated KimiCU copy
The elevated fallback escaped paths only for the AppleScript string
delimiters, not for the /bin/sh command line inside do shell script: a
TMPDIR with spaces broke the install, and shell metacharacters in the
temp path could inject commands into an administrator-privileged script.
Paths are now POSIX single-quoted first, then the assembled command is
AppleScript-escaped.
* fix(agent-core-v2): never break a working KimiCU on a failed update
The reinstall stopped and uninstalled the old service before the
downloaded archive was unpacked: a corrupt or captive-portal zip then
tore down a previously ready setup. The archive is now staged and
unpacked first, and the app step additionally requires the bundle's
Info.plist, so a partially copied bundle reads as missing and gets
re-copied instead of failing registration against a corrupt bundle.
* fix(agent-core-v2): limit the fetch deadline to the header phase
The 30s AbortSignal stayed attached for the whole request, so a
slow-but-healthy download of a large archive was aborted at 30s total
even while chunks kept arriving — exactly what the per-chunk idle
watchdog was meant to allow. The header phase now uses an
AbortController cleared once headers arrive; the body remains governed
by the inactivity watchdog alone.
* test(tui): provide the harness plugin facade in the capability command fakes
The lazy-session refactor routes session-less plugin calls through
host.harness; the fake host now mirrors that shape.
|
||
|
|
278b6af19d
|
fix(agent-core-v2): make MCP initial connect non-blocking during startup (#2586)
* fix(agent-core-v2): make MCP initial connect non-blocking during startup * Delete .changeset/mcp-nonblocking-startup.md Signed-off-by: 7Sageer <sag77r@hotmail.com> * fix(agent-core-v2): wait for MCP readiness before first turn * fix(klient): wait for MCP startup before listing * fix(klient): keep MCP server listing non-blocking * test(acp-server): allow pending MCP snapshot --------- Signed-off-by: 7Sageer <sag77r@hotmail.com> |
||
|
|
2c3c5a5879
|
feat(tui): lazy-create the session on first use with the v2 engine (#2458)
* feat(tui): lazy-create the session on first use with the v2 engine Start the interactive TUI session-less under the v2 engine and create the session on first use (message, bash input, or a session-requiring slash command) instead of at startup. Skills and plugin commands are resolved from the workspace/app-global catalogs without a session, and the footer shows config defaults (model, permission, plan mode, thinking effort, context cap) until the session exists. * fix(tui): serialize lazy session creation and carry session-only thinking Concurrent first-use triggers (double Enter, a slash command right after a prompt) both observed `session === undefined` and created their own session, letting the later setSession close the first one mid-dispatch. Share an in-flight creation promise instead. A session-only thinking choice (model picker Alt+S) made before the first session exists only updated appState, so the lazy-created session fell back to the engine default while the footer showed the chosen effort. Carry it as a first-session thinking override and clear it on creation. * fix(tui): don't re-enter plan mode when creating the lazy session The v2 engine applies config.defaultPlanMode at session create time (sessionLifecycleService), so passing the pre-filled appState.planMode as the create override entered plan mode twice and threw 'Already in plan mode' on the first message. Pass only the explicit CLI --plan intent for session-less v2 creation; the config default stays footer-only. * fix(tui): re-check the busy gate after lazy shell startup, keep /settings session-less A bash command submitted while the first prompt is still being lazy-created shared the in-flight creation promise but resumed past handleUserInput's busy check, running runShellCommand concurrently with the prompt. Re-check streamingPhase after the await and queue instead. /settings is a local settings entry point: opening it must not require or create a session, so it no longer triggers lazy creation; its session-requiring sub-items keep their own errors. * fix(tui): re-check busy state after lazy command creation, make /plugins session-free A skill/plugin or idle-only slash command submitted while the first prompt was still being lazy-created shared the in-flight creation promise but resumed past the availability check resolved before the await, running concurrently with the prompt's turn. Re-check the busy gate after the shared await in the skill, plugin-command and builtin dispatch paths. /plugins is app-global on the v2 engine, so a session-less startup no longer creates a session (or fails with LLM-not-set) just to manage plugins: the harness now exposes the global plugin API and the command routes through it until a session exists. * fix(tui): keep the read-only /add-dir forms session-less The bare and `list` forms already tolerate a missing session, but the blanket lazy-create gate forced a session (or failed with LLM-not-set) before they could run. Only the path-adding form needs a live session, so it now lazy-creates inside the handler instead of in the dispatch preflight. * fix(tui): reflect pending dirs in /add-dir list, refresh plugin commands after reload /add-dir list looked only at session.summary, so pending startup additionalDirs were reported as absent until a session existed; fall back to appState when session-less. /plugins reload updated the app-global service but left the TUI's plugin slash-command map stale, so new or re-enabled commands kept parsing as prompts; rebuild it from the reloaded service (which also covers the app-global path before the first session exists). * test(tui): add pluginCommandMap to the MessageDriver interface * fix(tui): hydrate lazy defaults on sessionless reload, guard /plan re-entry /reload refreshed only the model/provider dictionaries while session-less, so defaults edited externally (or a newly added default model) left appState.model empty/stale and the first lazy-created session failed with LLM-not-set or used the old value. Reuse the startup default-hydration path for the no-session reload case. /plan on as the first command with defaultPlanMode=true re-entered plan mode after the engine had already applied the config default at create, throwing Already in plan mode. Skip the call when the session is already in the requested mode. * test(tui): widen the getConfig mock return type for the reload case * fix(tui): clear stale lazy defaults when the default model disappears hydrateLazyConfigDefaults only patched model when the reloaded config still had a default, so removing defaultModel from config.toml left appState.model stale and the first lazy-created session passed it explicitly instead of failing or following the engine's current defaults. Reset model and context cap when the default is gone. * fix(tui): reset a removed permission default, don't re-enter plan on --plan A removed defaultPermissionMode left appState carrying the old elevated mode, which createSessionFromCurrentState then passed explicitly to the first lazy-created session; reset to manual when no CLI permission flag is present. With both defaultPlanMode and --plan set, the create payload passed planMode: true even though the engine already entered plan mode from the config default, throwing Already in plan mode on the first prompt. Track the config default separately and suppress the --plan override when it is already active. * fix(tui): keep read-only and mode commands session-less Read-only views (/status, /usage, /mcp, bare /title) already degrade gracefully without a session, so forcing lazy creation made them fail with LLM-not-set or create an unused persisted session; they no longer trigger creation, and /title <name> lazy-creates only for the mutation. /permission, /auto and /yolo are pending-mode choices: with no session on v2 they now record the mode in appState (which the lazy create path passes to the engine) instead of failing or creating a session just to pick a mode. The runtime permission is applied once a session exists. * fix(tui): wait out lazy assembly in ensureSession, expose workspace MCP setSession assigned host.session mid-assembly, so a follow-up prompt or command in that window skipped the shared creation promise and dispatched against a session whose subscription and runtime sync had not finished. Check the in-flight promise before the assigned-session fast path. /mcp required a live session even though the v2 connection set is workspace-scoped, so it errored until an unrelated prompt created one. Route it through a workspace-level MCP view (harness passthrough over the handler's shared connection manager) before the first session exists. * fix(tui): await workspace MCP readiness in the session-less /mcp list * fix(tui): hydrate the model default thinking effort for the session-less picker * style(tui): trim verbose comments in the lazy-default fixes * fix(tui): hydrate lazy defaults after login, serialize /new with lazy creation * fix(tui): re-check the busy gate after lazy /add-dir session creation * fix(tui): let Shift-Tab lazy-create the session on a v2 session-less start * fix(tui): hydrate session-less defaults on model-less login, refresh workspace commands on reload * fix(tui): re-check the idle-only gate for /new after waiting out lazy creation * fix(tui): wait out lazy creation before accepting model/effort switches * fix(tui): wait out lazy creation before switching sessions from the picker * fix(node-sdk): read session-less skills from the workspace skill catalog * feat(tui): show a session-less notice on v2 startup |
||
|
|
4ac7240fff
|
ci: release packages (#2469)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
f412e105b3
|
feat(acp-server): bridge questions via elicitation and support host slash commands (#2583)
* fix(acp): preserve cancels that arrive before the turn id is known A session/cancel landing between prompt submission and the launch round-trip found driver.turnId undefined and was dropped entirely; the turn then ran to completion and the prompt resolved end_turn despite the client's cancel. The engine's cancel payload makes turnId optional (an empty call cancels the active turn — the same contract kap-server's cancel route relies on), so cancel() now issues an unaddressed cancel in that window and flags the driver; the launch handler re-issues a precisely addressed cancel once the id lands, and a no-launch outcome settles cancelled instead of end_turn. * fix(agent-core-v2): shut session MCP overlays down on service teardown The ephemeral per-session MCP overlay was only shut down by the session handle's dispose wrapper, but the DI container disposes session scopes directly on workspace/app teardown, bypassing the wrapper — so overlays of sessions still live at shutdown leaked their MCP connections and stdio child processes. Track live overlays in the lifecycle service: the handle wrapper deletes-then-shuts-down (atomic, so close and service disposal can never double-shutdown), and the service's own dispose shuts down whatever is still tracked. * feat(acp-server): bridge questions via elicitation and support host slash commands - route AskUserQuestion through `elicitation/create` for form-capable clients (native multi-question + multi-select), falling back to the `request_permission` bridge on RPC failure - add a `slashCommands` resolver option so hosts can merge their own command palette and skill aliases into `available_commands_update`; `/help` now lists the merged palette - bridge `appendText`/`writeBytes` through client text capabilities (read-modify-write append, UTF-8-checked byte writes) with local filesystem fallbacks - defer `available_commands_update` until after the lifecycle response settles so clients like Zed do not drop the notification - propagate plan-toggle errors from `setMode` instead of silently reporting the new mode; make server `close()` idempotent * style(acp-server): satisfy oxlint eqeqeq and await-thenable rules * test(node-sdk): assert v1-v2 tokenCount parity for imports after eager counting |
||
|
|
1328b32037
|
feat(acp): add experimental agent-core-v2 ACP server (kimi acp-v2) (#2571)
* feat(acp): add agent-core-v2 ACP server - add ACP session lifecycle, configuration, permissions, and event bridging - expose the experimental kimi acp-v2 command with terminal authentication - add integration coverage and workspace build configuration * test: use neutral example domains in test fixtures and docs - replace placeholder hostnames (evil.com, foo.com, internal.corp, real.corp) with example.test / example.com in agent-core-v2 and kap-server tests - replace fixture emails (x@y.com, a@x.com) with example addresses in minidb tests and README * fix(acp): align acp-server with agent-core-v2 interfaces and address review - add missing appendText to AcpHostFileSystem (IHostFileSystem drift) - replace IAgentPromptService.prompt with inject - use Turn.cancel() instead of abortController - gate FS reverse-RPCs on client capabilities, fallback to local FS - return PROTOCOL_VERSION constant instead of echoing client version - remove misleading mcpCapabilities from initialize response - dispose old session wrapper before replacing on load/resume - fix object stringification lint error in convert.ts - add acp-v2 to expected CLI sub-command list in test * fix(acp): use enqueue for prompt submission, stop advertising unimplemented builtins - replace IAgentPromptService.inject with enqueue so onBeforeSubmitPrompt hooks (prompt-blocking policy) are not bypassed - stop advertising builtin slash commands (/help, /status, etc.) until builtin command execution is implemented - add comment explaining appendText stays local (ACP has no append RPC) - update skills test to match new availableCommands behavior * fix(acp): filter turn events by turnId, surface auth failures as auth_required - track turnId in driveTurn and ignore events from unrelated turns, preventing queued prompts from settling on the running turn - reject prompt requests with auth_required when turn fails with an auth-related error code, enabling ACP client re-auth flow * fix(acp): gate acp-v2 behind experimental flag, filter sessions by cwd - add acp-v2 experimental flag (KIMI_CODE_EXPERIMENTAL_ACP_V2) and gate CLI command registration behind it - filter session/list results by requested cwd instead of returning sessions from all workspaces - detect hook-blocked prompts via PromptHandle.state and add TODO for streaming block messages once the hook context exposes them * refactor(acp-server): rewire ACP server onto the klient facade - replace direct agent-core-v2 scope/service access (ISessionLifecycleService, ISessionIndex, IEventBus, ISessionInteractionService, etc.) with the Klient facade: klient.global.sessions / klient.session(id) / agent('main') handles - drive turns via agent.prompt() + session-level agent event subscriptions instead of per-prompt IEventBus wiring; settle on turn.ended - route approval/question bridging through session.interactions events - hide the thinking config option and skill catalog behind KLIENT-GAP markers until klient exposes those surfaces - acp-fs: pass realpath through to the local inner backend - klient: session.restore() rejects both null and undefined handles * feat(agent-core-v2): add session delete and ephemeral per-session MCP servers - add ISessionLifecycleService.delete: close a live session first, then remove its persisted data, evict the index read-model entry, and append a deleted tombstone to session_index.jsonl; unknown ids raise session.not_found - add CreateSessionOptions/ResumeSessionOptions.mcpServers: session-owned MCP overlay merged over the workspace manager via MergedMcpConnectionView (an ephemeral name shadows a workspace server), never persisted, released when the session scope tears down - return PromptLaunchResult from activateSkill so callers get the launched turn id and activation failures (unknown skill, busy) surface - add ISessionSkillCatalog.list() as a wire-friendly catalog snapshot - add ISessionIndex.remove for read-model eviction on delete * feat(klient): expose session delete, per-session MCP, skills, and stream events - session lifecycle contract: delete, resume/restore options, and CreateSessionOptions.mcpServers (ephemeral per-session MCP servers) - add the session skills contract and facade accessors for the wire-friendly skill catalog snapshot - register tool.call.delta, tool.progress, and compaction.* agent stream events so consumers can subscribe with typed payloads * feat(acp-server): align ACP v2 server with acp-adapter capabilities - complete the klient-facade rewire: ACP client connection holder and the terminal/* reverse-RPC runner routed through the Agent scope - negotiate the protocol version on initialize instead of pinning v1 - compress oversized prompt images at the ACP ingestion point with a format gate, caption, and persisted originals; a cancel arriving mid-compression settles the prompt as cancelled without a turn - stream tool call args via tool.call.delta (lazy pending create, cumulative replace, started upgrade) and refresh titles via tool.progress status updates - report compaction progress and results after /compact via the compaction.* events - answer unknown slash commands locally instead of sending them to the model - accept legacy "<id>,thinking" model ids and legacy approve / approve_for_session approval option ids - keep sessions without cwd metadata in cwd-filtered session/list - sanitize wire errors: auth codes map to auth_required, turn.agent_busy to invalid_request, everything else to a fixed internal-error message - bump @agentclientprotocol/sdk to ^1.3.0 * fix(cli): drop stale registerServerCommand call and sherif ACP SDK split - commands.ts called registerServerCommand, which no longer exists on current main (the deprecated `kimi server` shim is registered via registerWebCommand), breaking typecheck, build, and every CLI test that builds the program - sherif rejects the @agentclientprotocol/sdk major split between acp-adapter (^0.23.0, production kimi acp) and acp-server (^1.3.0, experimental); the two hosts legitimately target different SDK majors, so ignore the dependency in the sherif invocation * test: update fixtures for acp-v2 flag and domain rename, refresh nix deps hash - kap-server origin.test: two CORS cases still used foo.com after the whitelist moved to foo.example.com, so the origin was no longer whitelisted and the expected CORS headers were withheld - node-sdk config.test: expect the new acp-v2 experimental flag in the harness feature metadata - flake.nix: update the fetchPnpmDeps hash for the @agentclientprotocol/sdk 1.3.0 lockfile change * fix(acp): widen the ACP v2 auth gate beyond OAuth-only providers The gate consulted only auth.summarize(), which iterates providers declaring an oauth section — configurations that authenticate with a plain apiKey or provider env-bag credentials (no OAuth at all) were rejected with auth_required even though the default model is fully usable. - klient: expose authSummaryService.ensureReady on the global auth facade (the contract already declared it) - acp-server: gate on the engine's own readiness probe for the default model — config apiKey / env-bag / OAuth token all count, matching how the model is actually used — and fall back to "any logged-in OAuth provider" (the legacy adapter's first branch) - test: an apiKey-only config passes the gate with auth enforcement on; the OAuth logout regression is unchanged * fix(acp): reject concurrent prompts instead of displacing the in-flight turn A second session/prompt while a turn is running overwrote the session's only TurnDriver: the engine quietly queues plain prompts submitted during an active turn (the launch resolves undefined, indistinguishable from a hook-blocked launch), so the first prompt never settled and both turns' events went unattributed. Guard both model-bound launch paths (plain prompt and skill activation) with a synchronous in-flight check and reject with invalid_request (turn.agent_busy), matching the legacy adapter's busy semantics. Local slash handling (builtins, unknown-command answers) is unaffected. |
||
|
|
21185447fe
|
feat(agent-core-v2): add tokenCounting service with strategy config and measured anchors (#2563)
* feat(agent-core-v2): add tokenCounting service with strategy config and measured anchors - add IAgentTokenCountingService as the single owner of token counts: context size, full-request size, and estimate primitives, replacing the scattered contextSize/tokenEstimate/fullCompaction paths - add [token_counting] config section with strategy = measured+estimated (default) / measured / estimated, plus the KIMI_TOKEN_COUNTING_STRATEGY env override; measured zeroes all estimates, estimated ignores anchors - keep a live measured-anchor ledger in TokenCountingModel: each LLM exchange writes a real anchor, undo truncates the ledger so the surviving prefix restores its REAL measured size instead of a re-estimate, and compaction rebases to a single anchor that blends the compaction exchange's measured summary output tokens - skip writing an anchor when the stream reports no usage event instead of anchoring emptyUsage() zeros, which zeroed the context size and silenced compaction for providers without usage reporting - return the strategy-resolved size (not measured) from rpc getContext so the tokenCount contract stays correct under the estimated strategy - migrate all consumers (contextMemory, fullCompaction, llmRequester, rpc, mirrorAgentRun, sessionLegacy, kap-server legacyStatus, node-sdk, kimi-inspect) to the new service; edge bridges no longer read the wire model directly - document [token_counting] and KIMI_TOKEN_COUNTING_STRATEGY in the bilingual config reference * fix(kap-server): omit maxContextTokens instead of pushing 0 when unknown - readLegacyStatus falls back to the default model's context limit when no model is bound, and omits maxContextTokens entirely when the limit is unknown (0 is the engine's UNKNOWN_CAPABILITY marker, not a real limit) - profileService no longer emits maxContextTokens in agent.status.updated when the bound model alias does not resolve * fix(agent-core-v2): resolve token_counting strategy only at the reporting edge - keep measured anchors and heuristic estimates both recorded and feeding internal logic (compaction triggers, budgets, overflow backoff) regardless of the configured strategy - add IAgentTokenCountingService.statusSize() as the single strategy-resolved outward reading and route the WS/REST/RPC status surfaces through it - fix the context-size display falling back to provider-reported usage under the estimated strategy - fix compaction overflow backoff retrying identical messages until failure under the measured strategy (the strategy-gated estimator read as 0) |
||
|
|
75395f6abb
|
feat(agent-core-v2): add lifecycle hook events and enrich hook payloads (#2558)
* feat(agent-core-v2): add lifecycle hook events and enrich hook payloads New hook events: - TurnStarted: fired from the turn.started bus event, covering queued turns, stop-hook continuations, and background/system turns that UserPromptSubmit misses - UserPromptQueued: fired when a prompt cannot launch immediately, carrying the queue length - TaskStarted: fired from the existing task.started bus event, so background tasks no longer only produce a completion-time Notification - SessionHeartbeat: per-session 60s liveness beat, armed only when the event has hooks registered, letting hook consumers distinguish a session hanging on a long permission wait from a crashed one Payload enrichment: - client_type (host platform identity) on every event - session_title on every session/agent-scoped event - model and profile on SessionStart - SessionEnd reason is now 'exit' or 'archive' instead of a hardcoded 'exit' - SubagentStart/SubagentStop now carry session_id/cwd like every other event * fix(agent-core-v2): re-sync SessionHeartbeat timer on hook-index reloads The heartbeat timer was armed once after the runner's initial load, so a SessionHeartbeat hook contributed later by a plugin reload never produced beats for existing sessions. The runner now exposes onDidReload (fired after every index build), and the session adapter re-syncs on it: arming when a heartbeat hook appears, disarming when none remains. * fix(node-sdk): keep the v1 PluginInfo contract assignable with v2-only hook events The v2 hook-event union is now a superset of v1's, which broke the node-sdk type projection in two places: - the klient contract's hookDefSchema rejected plugin manifests using the new events (TurnStarted, UserPromptQueued, TaskStarted, SessionHeartbeat) at validation time — accept them - getPluginInfo returned the v2 PluginInfo where the SDK contract promises the v1 shape — project manifest.hooks through the v1-known event list (read from the legacy HookDefSchema), mirroring how the config mapper drops domains v1 does not know |
||
|
|
eaab2b6f28
|
fix(cli): fall back to built-in models.dev catalog when fetch fails (#2416)
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
When the remote models.dev catalog cannot be fetched, fall back to the built-in catalog so CLI/TUI model selection keeps working offline or under network failure. Import the shared helper via the #/utils alias. |
||
|
|
44d34bbd56
|
refactor(agent-core-v2): move host runtime args onto IBootstrapService (#2460)
* fix(agent-core-v2): resolve package self-references in check-import-boundaries Imports spelled @moonshot-ai/agent-core-v2/<path> (the legal `./*` export self-reference) were treated as external packages, letting kosong layer violations through that spelling pass the checker. * refactor(agent-core-v2): move host runtime args onto IBootstrapService - Add HostArgs under BootstrapInput.args / IBootstrapService.args (agentFiles, skillDirs, requestHeaders, displayName, replyStyleGuide), mirroring VS Code's NativeParsedArgs on the environment service - Remove the narrow per-domain runtime-options services and their seed functions: IAgentCatalogRuntimeOptions, ISkillCatalogRuntimeOptions, IHostIdentity - Reduce IHostRequestHeaders to a pure kosong port contract and bridge it from bootstrap args via a new app/kosongConfig adapter, keeping kosong free of app-layer imports - Pass host args through bootstrap() at the composition roots (kap-server, v2 print CLI, node-sdk) instead of seeding services - Persist SDK provider removal as one atomic multi-section config replace * fix(config): persist provider refresh updates atomically - expose atomic multi-section config replacement through klient and SDK - stage provider removals before one atomic write in TUI refresh - briefly drain startup refresh during shutdown |
||
|
|
32d693f644
|
feat(tui): ask for workspace trust on startup with the v2 engine (#2453)
* feat(node-sdk): expose workspace trust state and trust grant on the v2 client * feat(tui): ask for workspace trust on startup with the v2 engine |
||
|
|
ed7a4cc095
|
feat(kap-server): add session-less POST /workspace/fs:search route (#2437)
* feat(kap-server): let fs:search resolve a workspace ref for draft sessions
- fs:search accepts a workspace id or absolute root in the session_id slot
so the @ file mention works before the session exists
- kimi-web searchFiles falls back to the active workspace id in draft state
* fix(agent-core-v2): report empty thinking level for unbound main agent
- sessionLegacyService.status returns thinking_level '' when the main
agent has no bound model (mirroring model: undefined), so clients
fall back to the catalog default instead of folding in the wire
model's 'off' zero value
- add regression test for a never-bound main agent status
- add web changesets: draft @ file mention, new-session thinking level
* perf(minidb): make text index rebuilds async and non-blocking
- TextIndex.build() yields to the event loop during tokenization and
batches postings writes (~1 MiB), so large rebuilds no longer
hard-block the host process
- writes landing mid-build are queued and replayed onto the new base at
swap time, keeping the rebuilt index exact
- PostingsFile.rebuildSync renamed to async rebuild with a synchronous
commit section (beforeRename hook + atomic rename)
- onCompacted hook is now awaited (sync or async); open-time compaction
runs in the background so open() returns without blocking on the
snapshot rewrite and postings rebuild
- compaction skips the postings rebuild when the index's write buffer is
clean (needsRebuild)
- createTextIndex registers before building so concurrent writes feed
the build queue; dropTextIndex throws while a build is in flight
* refactor(agent-core-v2): rename workspaceHandler to sessionLifecycle
- rename IWorkspaceHandlerService to ISessionLifecycleService and move
src/workspace/workspaceHandler/ to src/workspace/sessionLifecycle/;
update all consumers (gateway, sessionExport, sessionLegacy,
sessionLookup, kap-server, klient, node-sdk, kimi-inspect, kimi-code)
- rename IStateService to IAppStateService and add the Workspace-scope
IWorkspaceStateService, so the state domain spans all four scope tiers
- add cascading StateRegistry.inspect(): each tier injects the parent
tier's registry and folds App to current scope into one StateInspection
tree; check-domain-layers gains a Rule 2b exemption for state-on-state
imports
* feat(kap-server): add session-less POST /workspace/fs:search route
Carry the workspace reference (registered id or absolute root) in the
request body and resolve it to the same Workspace-scope fs service the
session route uses, so clients no longer borrow the session route's
{session_id} slot. kimi-web's @ file mention now calls this route with
the workspace ref instead of a session id; the session-route fallback
stays for wire compatibility.
* refactor(agent-core-v2): register workspace-scope service state into IWorkspaceStateService
- move workspaceDirs / workspaceInstructions / workspaceSkillCatalog / workspaceTrust
runtime state from bare instance fields into the workspace state container
- extend gen-state-manifest.mts to scan app/workspace scopes, emitting
AppStateSnapshot / WorkspaceStateSnapshot alongside Session/Agent
- regenerate docs/state-manifest.d.ts and update AGENTS.md + agent-core-dev skill
- update affected tests to register the state services and assert the new state keys
|