mirror of
https://github.com/MoonshotAI/kimi-code.git
synced 2026-08-31 02:14:58 +00:00
143 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
58b74cfeab
|
fix(transcript): preserve turn prompt identity (#3377)
Some checks are pending
CI / lint (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (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
Publish VS Code extension / Publish VSIX to marketplaces (push) Waiting to run
* fix(transcript): preserve turn prompt identity * fix(transcript): backfill active prompt identity * fix(transcript): seed late-bound turn identity * fix(transcript): persist turn prompt identity * fix(transcript): skip undone prompt identities * fix(transcript): hide undone continuation turns * docs(agent-core): update wire manifest * fix(transcript): match cold turns by prompt identity * fix(transcript): match internal prompt turns by origin * fix(transcript): align undo anchors with context * fix(transcript): prioritize cold turn matches * fix(transcript): retire unmatched turn boundaries * style(transcript): align cold matcher |
||
|
|
cbe0a77f3d
|
fix(transcript): preserve steer provenance (#3374)
* fix(transcript): preserve bundled prompt origin * refactor(transcript): narrow steer origin projection |
||
|
|
9d2304c23c
|
fix(persistence): guard file reads against torn writes from external editors (#3348)
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 / Native release artifact (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
Publish VS Code extension / Publish VSIX to marketplaces (push) Waiting to run
* fix(persistence): guard file reads against torn writes from external editors A config.toml overwritten in place (truncate + write, the way plain writeFile and some editors save) can be read mid-write by a concurrent config reload -- the truncated head often parses as valid TOML, so the reload silently adopts a config with the models/providers sections missing and wipes the model table until the next watcher-driven reload. Observed as the prompts.test.ts flake: ProviderDiscoveryService's reload raced the test's writeFile and setModel then failed with "Model stub is not configured". FileStorageService.read now verifies the read against the file's size after the read and retries briefly on mismatch, and prompts.test.ts swaps its in-place config overwrites for atomic tmp+rename writes. * fix(persistence): confirm hot files with a second stat, list the CLI package in the changeset A size match alone is not proof of a stable snapshot: a writer that truncates or writes a partial chunk and then pauses lets read and stat observe the same transient length. When the file's mtime is within 100ms of now, the read is only accepted after a second stat 15ms later reports the same size and mtime; settled files still return after one stat. The changeset now lists @moonshot-ai/kimi-code per the changeset rules for user-perceivable fixes shipped through the CLI. * revert(persistence): drop the hot-file double-stat confirmation The confirmation delayed every read of a recently written file by 15ms (45ms for files being appended), which shifted server boot and reload timing enough to break real tests in CI (config changedFields baseline, fork parity). The simple size-verify guard covers the race that was actually observed; a read-side guard cannot be airtight against an in-place writer paused mid-write anyway -- atomic writes are the real contract. --------- Co-authored-by: user <user@userdeMacBook-Pro.local> |
||
|
|
dc6028dc6b
|
fix(kap-server): only fold user-origin steers by content in the cold transcript (#3328)
* fix(kap-server): only fold user-origin steers by content in the cold transcript * fix(transcript): check marker-only origins before the steer content match * fix(transcript): limit the steer bypass to marker-only skill triggers * fix(transcript): consume the steer count for marker-only activations * fix(transcript): pair steered contents with messages by origin kind * refactor(kap-server): read the steer origin kind without nested casts --------- Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com> |
||
|
|
2bf7ed22d7
|
feat(auth): split model readiness from sign-in state in /api/v1/auth (#3293)
* feat(auth): split model readiness from sign-in state in /api/v1/auth
GET /api/v1/auth now reports models_ready (the default model resolves
against the configured catalog, providerless and env-injected models
included) instead of the compound ready flag, and no longer carries
default_model — config values are served by /config alone. The v1
summary schema follows.
OAuth managed-model refreshes now heal a lost default model: the
refresh snapshot includes defaultModel, so an unchanged catalog with
a missing default still lands the write-back branch and re-selects
one. The refresh also rebases onto a fresh config read after the
remote fetch, so a model or thinking change made during the fetch is
no longer overwritten. The shared discovery refresh path (scheduler,
POST /providers/{id}:refresh) heals the default the same way.
Config changes are now published to WS clients on every write path:
a debounced+trailing publisher bridges IConfigService section changes
to ConfigChanged with camelCase changedFields and a full config
projection, and the broadcaster forwards event.config.changed and
event.model_catalog.changed (both previously published but never
delivered). All three event types are registered in the event unions,
so session_event parsing and AsyncAPI describe them.
BREAKING CHANGE: GET /api/v1/auth drops the ready and default_model
fields in favor of models_ready; event.config.changed's changedFields
is now camelCase domain names instead of the raw snake_case request
keys (v1 summary schema follows).
* fix(kap-server): expose the session model in session list projections
GET /api/v1/sessions hardcoded agent_config.model to '' and the v2
projection had no model field at all, so clients could only learn a
session's model via the post-select /status read — which races the WS
replay and often never lands. SessionFacts now carries the live
session's model (same source as the snapshot route), toWireSession
emits it, and the v2 activity domain gains a nullable model field.
* fix(kap-server): gate prompt submission on the effective session model
The submit gate called ensureReady() with no override, so it only ever
validated config.default_model: a session with a bound model (or a
prompt carrying one) was rejected with 40113 whenever default_model was
missing or dangling. Pass the effective model (request model, then the
agent profile's bound model, falling back to default_model inside
ensureReady) on both the prompt submit and btw routes.
* fix(agent-core-v2): honor defaultProvider in model readiness resolution
resolveModelForReady stopped at the flat baseUrl fallback, so a model
that omits provider/providerId and relies on the configured
defaultProvider resolved at runtime (ModelCatalog.resolveProviderContext
falls back to it) while /api/v1/auth reported models_ready:false and the
send gate rejected the prompt. Mirror the runtime order (providerId ->
provider -> defaultProvider -> flat baseUrl) and pass the configured
default provider from both readiness callers.
* fix(kap-server): redact inline model credentials from config responses
toConfigResponse only redacted the providers section, so a model's
inline apiKey/oauth rode GET /config verbatim and, via the new
event.config.changed publisher, every WS connection plus the persistent
event journal. Project the models section the same way: strip
credential fields and report has_api_key.
* fix(agent-core-v2): honor defaultProvider in ensureReady credential checks
The readiness phase learned the defaultProvider fallback, but the
credential phase right after still derived the provider only from the
model's explicit fields: a model omitting provider/providerId passed
readiness yet missed the default provider's apiKey/OAuth material and
prompts failed with auth.token_missing. Mirror the same provider chain
(providerId -> provider -> defaultProvider) when resolving credentials.
* fix(kap-server): validate the model a profile bind will select at the prompt gate
The gate validated the session's current model even for a prompt that
switches profile without a model — but bind falls back to defaultModel
in that case, so a stale session model drew a misleading 40113 before
bind could run. Gate on bind's selection order instead: the request's
explicit model, then the default on a profile switch, then the session's
bound model.
* fix(kap-server): redact inline service credentials from config responses
The earlier redaction covered providers and models, but toConfigResponse
still passed the services section through verbatim: inline or
env-injected apiKey, oauth references, and credential-bearing
customHeaders rode GET /config and, via the event.config.changed
publisher, every WS connection plus the persistent event journal.
Project services the same way: strip apiKey/oauth into has_api_key and
report only the header names as custom_header_keys (the MCP
envKeys/headerKeys convention).
* fix(kap-server): keep unlisted config domains through event validation
The config.changed broadcaster returned the zod-parsed config, which
strips domains absent from configResponseSchema (mcp, identity,
model_catalog, image, tools, token_counting): changedFields named them
while the advertised full snapshot no longer matched GET /api/v1/config.
Make the response projection passthrough (defineRoute validates only
requests, so REST responses are unaffected).
* fix(agent-core-v2): use the exact configured key for model readiness lookups
resolveModelForReady trimmed the model id before the models-table lookup
while ModelCatalog and ensureReady use the configured string as an exact
record key: a whitespace-padded default_model was reported ready and then
crashed the submit gate with an internal error instead of 40113, and a
legitimate key containing spaces was reported dangling. Trim only rejects
blank values now; the lookup always uses the raw key.
* fix(protocol): keep unlisted config domains in the shared event projection
The shared configResponseSchema stripped domains it does not enumerate
(mcp, identity, model_catalog, image, tools, token_counting, subagent,
secondary_model), so event.config.changed parsed through agentEventSchema
named them in changedFields while omitting their values. Make the shared
projection passthrough like the kap-server-local one.
* fix(agent-core-v2): use the exact default_provider key in readiness checks
The defaultProvider fallback trimmed the configured value before the
providers-table lookup while ProviderService and ModelCatalog use the
configured string verbatim: a whitespace-padded default_provider could
build successfully yet report not-ready (40113), or report ready for a
provider runtime resolution cannot find. Trim only rejects blank values;
the lookup uses the raw key.
* chore: sync web dist from code-app
Rebuild the bundled web UI against this branch's /auth contract (models_ready, no ready/default_model): the previous bundle still read the old fields and stayed in the not-ready flow against this server.
code-app: 000d2594ff3e95b553be326126bab3f939b62944
* Revert "chore: sync web dist from code-app"
This reverts commit 9400a24a03863b3e8b780dda251540f824f02f3a.
* fix(oauth): rebase the default selection after the refresh fetch
A provider refresh snapshots the config before the remote catalog fetch;
when the user selects a default model while the fetch is in flight, the
stale snapshot's empty default made an otherwise unchanged catalog enter
the write path and the self-heal persisted the generated default over the
user's newer selection. Each branch now re-reads and rebases the
default/thinking selection after its fetch, before cloning, comparing,
or writing.
* style(kap-server): pass optional custom_header_keys without conditional spread
|
||
|
|
4e7738b73c
|
feat(kap-server): support server-local path attachments (#3247)
* feat(kap-server): support server-local path attachments Web and desktop clients can now attach files, images, and videos to a prompt by server-local absolute path instead of uploading a copy. The daemon validates the path (absolute, realpath-resolved, non-sensitive, local runtime only) and references the original file in place, so the agent reads the original path; the upload flow is unchanged. Submitted file attachments are also recorded on the prompt origin and projected as typed transcript attachments, so web clients render attachment chips for plain files without parsing the model-facing notice text. * fix(kap-server): forward file attachment metadata from skill activations * Delete .changeset/web-attach-by-path.md Signed-off-by: 7Sageer <sag77r@hotmail.com> --------- Signed-off-by: 7Sageer <sag77r@hotmail.com> |
||
|
|
bd5e32f683
|
fix(secondary-model): stop rewriting the section when providers refresh or are removed (#3284)
* fix(secondary-model): stop rewriting the section when providers refresh or are removed Provider refresh, provider deletion/rename, catalog/registry import, OAuth logout, and SDK removeProvider used to cascade into the user's [secondary_model] block: pool entries were silently pruned, and the whole section was deleted when its effective default dangled. The cascade ran from a cache-refresh path (including an unattended 6h scheduler), so upstream model-list changes could irreversibly destroy hand-written configuration without any notice. Config is user intent; the catalog is an availability snapshot. Stop rewriting the section on every provider/models writer. An entry whose model no longer resolves fails pool validation on the next session create with a message naming the offending alias, which is the same fail-fast contract hand-written typos already had. * chore(sdk): add changeset for the removed secondary-model cascade export * Delete .changeset/sdk-remove-secondary-model-cascade.md Signed-off-by: 7Sageer <sag77r@hotmail.com> * Delete .changeset/secondary-model-no-silent-rewrite.md Signed-off-by: 7Sageer <sag77r@hotmail.com> --------- Signed-off-by: 7Sageer <sag77r@hotmail.com> |
||
|
|
f143130c07
|
fix(transcript): carry the orchestrator's prompt on subagent turns (#3289)
* fix(transcript): carry the orchestrator's prompt on subagent turns * chore: add changeset for subagent turn prompts |
||
|
|
692bb0a409
|
feat(kap-server): add task detach action to move foreground tasks to background (#3273)
* feat(kap-server): add task detach action to move foreground tasks to background * test(kimi-code-sdk): normalize v2-only parentToolCallId in task parity projections * fix(agent-core-v2): distinguish user-initiated detach in tool result text * feat(agent-core-v2): mention user-initiated backgrounding in the bash tool description * feat(agent-core-v2): use a client-agnostic background-task panel hint in the bash tool description * ci: retrigger checks * feat(agent-core-v2): client-agnostic human_shell_hint and a detached_by_user marker in tool results * fix(protocol,docs): declare parent_tool_call_id in the shared task schema and document the detach action * style: remove added comments |
||
|
|
7de7b18ee9
|
feat(agent-core-v2): self-heal corrupted wire journals during restore (#3281) | ||
|
|
b3f08b68c8
|
fix(kap-server): include stable question and option ids in transcript question entities (#3272) | ||
|
|
5634cb556f
|
fix(kap-server): project steered messages as live user frames in the transcript (#3262) | ||
|
|
c488586091
|
fix(kap-server): remove undone turns from the live transcript projection (#3259)
* fix(kap-server): remove undone turns from the live transcript projection * fix(agent-core-v2): report the earliest removed turn id on conversation undo |
||
|
|
f35f214e20
|
test(kap-server): use a neutral model name in transcript projector tests (#3256)
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com> |
||
|
|
6595955b31
|
fix(kap-server): report run_in_background on the task wire (#3239)
Some checks are pending
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (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
* fix(kap-server): report run_in_background on the task wire The /tasks wire now carries the task's detached flag as run_in_background (schema in both the kap-server local copy and the public protocol package). A running foreground subagent used to be indistinguishable from a background one on this surface — clients that defaulted the missing field to true would treat it as background. * chore: add changeset for the run_in_background wire fix * fix(kap-server): make run_in_background a required wire field The field is always emitted (ghost-restored records pre-dating it read true: the persisted store only lists terminal-and-detached or running tasks, which all carry a concrete flag). Making the contract required means a producer that omits it fails as an ordinary protocol error instead of clients silently re-interpreting the row as foreground * fix(protocol): keep run_in_background optional in the public task schema The public schema types the agent-core v1 task service too, which does not emit the field — making it required there is a breaking protocol change (and broke agent-core's typecheck). kap-server's own local schema stays required: it is the sole writer of the /tasks response and always emits. Consumers apply the foreground fallback when the field is absent |
||
|
|
f0a609487f
|
feat(kimi-code): add remote control web tunnel (#3034)
* feat(kimi-code): add remote control web tunnel Add CLI and TUI entry points for exposing the local web UI remotely. Bridge HTTP and WebSocket traffic with local authentication and reconnect handling. * fix(kimi-code): prevent remote control websocket crash * fix(kimi-code): align websocket dependency versions * fix(kimi-code): harden remote control connection setup Reconnect when management closes during the HTTP tunnel handshake. Reject non-loopback Remote Control binds whose CSP blocks path bootstrap. * fix(kimi-code): fix remote control rewriting, caching, and WS frame loss * feat(kimi-code): add remote control QR output * build: update pnpm dependencies hash * refactor(kimi-code): remove the --allow-remote-terminals flag * feat(kimi-code): add remote control lock, rc command, and QR fixes * fix(kap-server): broadcast user prompts to all session clients on submit - agent-core-v2: emit prompt.submitted (status running|queued) at enqueue and prompt.started when the turn launches - kap-server: project prompt.submitted/prompt.started into transcript prompt entities and the live transcript REST response - update flake.nix pnpmDeps hash for the PR lockfile * fix(node-sdk): drop v2-only prompt.started from SDK event stream - event-mapper: add prompt.started to the dropped v2-only prompt lifecycle types (parity with submitted/completed/aborted/steered) - cli test: assert only visible sub-commands and stub the experimental flag env for determinism * ci(pkg-pr-new): post custom install comment for npm 12 compatibility * feat(kimi-code): render remote control QR as inline image on capable terminals * feat(kimi-code): improve remote control terminal output - add onboarding, security, device management, and help guidance - show compact clickable links and QR image fallback details - report relay and remote device connection lifecycle * test(agent-core-v2): update tool event snapshot * revert(ci): keep preview workflow unchanged in rc pr --------- Co-authored-by: liruifengv <liruifeng1024@gmail.com> |
||
|
|
1ade345171
|
refactor: ban JSDoc in comment-free packages (#3226)
* refactor: ban JSDoc in comment-free packages * fix: scan comments after a shebang in check-no-comments |
||
|
|
4d5147ba5d
|
fix(agent-core-v2): keep agent lifecycle context active through scope teardown (#3206)
* fix(agent-core-v2): keep agent lifecycle context active through scope teardown * fix(agent-core-v2): deactivate agents after scope-units teardown * fix(kap-server): install process handlers only after successful startup * fix(agent-core-v2): let the teardown finalizer own create-failure deactivation * fix(agent-core-v2): await asynchronous scope-units teardown before deactivation * fix(agent-core-v2): await agent scope teardown before completing removal * fix(agent-core-v2): mark fire-and-forget scope disposals after awaitable dispose * fix(agent-core-v2): return the in-flight promise from repeated disposeAsync * fix(agent-core-v2): await child containers and keep kap-server handlers through shutdown |
||
|
|
71caabdc6d
|
feat(kap-server): add workspace-agnostic multi-root POST /api/v1/fs:suggest (#3210) | ||
|
|
09858919c4
|
refactor(kap-server): serve WS fs watch from the engine workspace fs watch service (#3196) | ||
|
|
2f12469301
|
fix(transcript): fold mid-turn task notifications into the current turn on cold rebuild (#3102)
* fix(transcript): fold mid-turn task notifications into the current turn on cold rebuild * chore: changeset for the notification fold fix * fix(transcript): key the notification fold on persisted task-turn boundaries, not the previous message role * fix(transcript): collect background_task turn origins too, and fall back when the wire has no turn.started records * fix(transcript): fold consecutive task notifications into the same turn * fix(transcript): normalize folded notification text to the live title/body form * fix(transcript): stop folded notification text before child blocks, preserve legacy background_task turns absent from the boundary set * fix(transcript): truncate folded notification text at the first child-block tag, not just the tag lines * fix(transcript): drop folded notifications without a persisted step, truncate only at output blocks * fix(transcript): attach mid-turn task notifications to the following step, cold and live * fix(transcript): keep other tasks' notifications in task-origin turns * fix(transcript): derive task-turn boundaries from durable turn.prompt records * feat(transcript): carry subagent model and thinking effort on task entities * fix(transcript): mirror turn liveness into meta.activity, live and cold * fix(transcript): populate the prompts entity from prompt.accepted/queued engine events * fix(transcript): reconcile liveness and the prompt queue at backfill from the live loop state * fix(transcript): include the prompts entity in the REST transcript response * fix(agent-core-v2): publish prompt.accepted on the event bus * test(transcript): add the contract-level e2e covering every entity the client renders from * fix(transcript): guard the prompt backfill against missing services; align stream expectations with prompt.accepted on the bus * test(agent-core-v2): re-record event stream snapshots with prompt.accepted published * fix(transcript): settle the spawned agent row when its lifecycle redirects to the task row * test(transcript): move the contract e2e timeout to the describe arg (jest lint) * fix(transcript): declare task model fields in the wire schema, carry prompt content on accepted, normalize queued content - transcriptTaskSchema declares model/thinkingEffort: Zod strips undeclared keys, so schema-driven REST/WS consumers lost both fields the projector now populates. - PromptAccepted carries the admitted content (it is the only event a first-turn prompt ever emits, and the bare id left the prompts entity permanently partial) — projected with userMessageId and the public content shape via projectPromptContentParts, same as queued and the live backfill. - Regenerate the wire manifest and re-record the affected event-stream snapshots. * fix(transcript): preserve task model fields across termination and accepted prompt details across queueing - onTaskLifecycle carried resultSummary/usage/error/stateReason but dropped model/thinkingEffort: a completed detached-Agent row lost the metadata spawned set while running. - prompt.queued rebuilt the entity from scratch, discarding the userMessageId and createdAt that prompt.accepted had just stamped — build the queued update from prev. * fix(transcript): keep prompt.accepted out of the public v1 event stream The observable marker made the broadcaster forward every accepted prompt to v1 WS clients, but events-zod has no accepted variant (v1 surfaces submission through the service-synthesized prompt.submitted) and the SDK mapper didn't drop it — schema-driven clients could reject the frame. Drop it at the WS edge and in the SDK's dropped set; the transcript projection keeps consuming it internally. * fix(transcript): derive cold task-turn boundaries through undo anchor replays * fix(transcript): flush trailing folded notifications into the open turn * fix(transcript): drop trailing buffered notifications to match the live projector * chore: split transcript changesets per logical change * fix(transcript): parse only the generated Title/Severity header lines in folded notifications |
||
|
|
9a715820c4
|
refactor(agent-core-v2): featurize todo/cron/interaction and migrate goal to agent runtime (#3184)
Some checks are pending
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (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
* refactor(agent-core-v2): featurize todo/cron/interaction and migrate goal to agent runtime * refactor(agent-core-v2): move cron scheduling helpers into features/cron/internal |
||
|
|
368b4b7400
|
refactor(agent-core-v2): migrate agent domains to agent runtime architecture (#3175) | ||
|
|
d723cc47ee
|
feat(agent-core-v2): add the unified MCP management plane (#3002)
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
* feat(agent-core-v2): add the unified MCP management plane Port the v1 MCP management plane (#2858) onto the v2 DI x Scope engine: - App-scope IMcpOAuthService shared by every workspace handler and session overlay: credential events, single-flight refresh, proactive refresh timers, OAuthTokenTransaction-serialized writes, offline tokenState, shutdown. Providers read tokens through the store so grants written or revoked by another process are honored immediately; http/sse transports ride the transaction fetch. - IMcpConfigStore: the single write point for the user-level mcp.json over the filesystem byte store, byte-identical to v1's format, with per-entry validation, name normalization, __proto__-safe parsing, a mutation tail, and an onDidWrite event. - IMcpRegistryService: the unified read view over the layered config files (with per-entry origins) and plugin manifests (full descriptors incl. disabled, with provenance); collisions stay visible and runtime resolution ranks an enabled plugin above the file layers. - IMcpManagementService: guarded CRUD, connection-test probes, the locator-addressed inspection/auth-status surface, and locator-addressed OAuth begin/complete/cancel/reset with ambiguity rejection. Engine services stay ungated; the mcp_management flag gates the edge exposure. - Workspace runtime aligns with v1 precedence (an enabled plugin entry wins over the file layers, shadows revive), and management writes reload immediately via onDidWrite instead of the watch debounce. - node-sdk v2 facade delegates to the engine service (deleting its in-process duplication); kap-server exposes /api/v2/mcp/* and klient gains global.mcp.*, both flag-gated. * fix(agent-core-v2): settle early and cancelled MCP OAuth callbacks * refactor(node-sdk): write session MCP persists through the engine config store * refactor(agent-core-v2): strip comments from the MCP management plane files * fix(agent-core-v2): harden MCP management readiness * test(node-sdk): cover offline MCP auth statuses * fix(agent-core-v2): isolate stdio MCP probes * fix(klient): normalize MCP OAuth errors * fix(mcp): honor workspace CRUD context and refresh timing * fix(mcp): drain OAuth refreshes during shutdown * fix(mcp): guard CRUD across registry collisions * fix(mcp): canonicalize trust and refresh scheduling * fix(mcp): close callback listener on setup failure * fix(mcp): preserve trust and oauth behavior * fix(oauth): retain refresh tokens after SDK saves * fix(oauth): stop proactive sweep during shutdown * fix: await MCP workspace reconciliation * fix: serialize MCP OAuth and trust cleanup * fix: reject persisted MCP plugin collisions * fix: reconcile MCP workspaces concurrently * fix(mcp): check project-layer trust at the queried cwd * fix(mcp): expire abandoned OAuth flows after an idle timeout * fix(mcp): keep mutable user entries writable past read-only collisions * fix(mcp): abort the auth::complete long poll on client disconnect * fix(mcp): map OAuth flow failures to wire code 40929 * docs(mcp): note probe credential effects and plane semantics * chore: add the SDK changeset for MCP management cwd params * feat(mcp): expose the management plane without the experimental flag * fix(mcp): preserve auth management semantics * fix(agent-core-v2): bound MCP OAuth auth-server requests and the shutdown drain * fix(node-sdk): restate engine MCP management errors as KimiError * fix(agent-core-v2): preserve shared OAuth flow lifetime * fix(agent-core-v2): close MCP OAuth cancellation and shutdown gaps - bound the authorization-code exchange with the request timeout and the flow/caller abort signals, and make shutdown abort hung begins and close their callback listeners immediately - keep token-transaction effect coalescing intact when durable tokens carry local stamps, and serialize the meta sidecar and tokens-saved event with the token write inside the lock - drain transport-driven grants, their trailing SDK save continuations, and interactive completions during shutdown, with a cancellable deadline * fix(agent-core-v2): harden MCP probe runtime resolution and path handling - resolve stdio probes against the containing workspace's runtimes and reject out-of-workspace probes for non-local runtime_id instead of silently falling back to a local-only transient registry - share one Windows-aware path canonicalization across the config loader, registry trust lookup, trust records, and workspace matching - keep a UTF-8 BOM fatal for the user-level mcp.json store, matching the workspace loader and v1 - validate completeServerAuth timeoutMs bounds at the engine boundary * fix(agent-core-v2): await workspace MCP reconciliation on plugin mutations Plugin install/enable/disable/remove now resolve only after reload listeners settle their waitUntil work, so a disabled plugin's MCP server cannot linger connected and an enabled one is visible to the next session, matching v1. The workspace MCP consumer joins the barrier while keeping its log-only failure tolerance; delivery is awaited outside the mutation queue to avoid self-deadlock through consumption reads. * fix(mcp): close the SDK, klient, and server edge gaps - register mcp.oauth_failed in the v1 error registry and restate unknown engine codes as internal instead of minting undeclared KimiError codes - route persisted session MCP adds through the same KimiError restating as the global management methods - give the klient IPC transport a per-call timeout so completeAuth's long poll outlives the 30s default, clamped to the Node timer ceiling, and align the contract timeoutMs upper bound with REST - await the MCP OAuth service shutdown directly in SDK and server close before scope disposal * fix(agent-core-v2): keep file-over-plugin MCP precedence and harden the plane - Revert the v1-style precedence flip: the workspace merge and resolveRuntimeTarget keep the file entry above plugins (v2's historical order; the divergence from v1 is deliberate and documented in AGENTS.md). - Guards follow each engine's winner: project-layer entries stay read-only, while plugin entries never block user-level writes, so a file entry may shadow a plugin and removing it revives the plugin. The parity suite pins the engine split for a persisted session add over a plugin-owned name. - inspectServers tolerates a wire-encoded null targets array: klient's ipc transport sends null for an omitted leading optional argument. - Fire the config store's onDidWrite after the mutation tail settles, so a write listener can re-enter the store without deadlocking the queue; concurrent-mutation and re-entrant-listener tests pin both contracts. * chore: condense the sdk MCP changeset to one sentence * test(node-sdk): pin verify:false auth-status parity and fix the sdk changeset |
||
|
|
0f44537c13
|
feat(agent-core-v2): turn /tower into a mode parallel to plan mode (#3099)
* feat(agent-core-v2): turn /tower into a mode parallel to plan mode
* feat(agent-core-v2): align /tower command semantics with the original skill behavior
* fix(tui): harden the /tower command against mid-turn objectives, legacy engines, and stale status
* fix(agent-core-v2): keep restored tower state inert while the feature flag is off
* fix(agent-core-v2): include TowerInit in the mode tool overlay and report flag-gated tower state
* feat(agent-core-v2): expose tower control tools statically and make the mode injection history-derived
* fix(tui): warn that tower mode needs a restart after a live flag flip; drop redundant undefined from SessionStatus mode fields
* fix(agent-core-v2): let tower mode exit clear persisted state while the flag is off
* fix(agent-core-v2): emit the tower exit reminder through a disabled flag and drop the redundant REST state comparison
* fix(tui): show the Tower mode status row only when the experiment is available
* fix(agent-core-v2): confine tower mode to the main agent and always re-assert it for objectives
* feat(kap-server): project tower mode into transcript modes and reassert explicit toggles
* fix(agent-core-v2): fold the main-agent invariant into the effective tower state
* fix(kap-server): gate the cold tower mode badge behind the experiment flag
* fix(agent-core-v2): reapply the tower tool overlay after a profile bind; fix(kap-server): clear cold tower badges on non-main agents
* fix(protocol): mirror towerMode and tower_mode in the shared zod schemas
* test(agent-core-v2): adapt tower tests to the agent lifecycle context architecture
* chore(agent-core-v2): regenerate the wire manifest; test(node-sdk): look up the main agent via findAgentHandle
* fix(agent-core-v2): exit a replayed tower mode when the workspace belongs to another session
* fix(agent-core-v2): carry tower ownership in the enter record so forks clear inherited mode
* fix(agent-core-v2): apply the tower overlay before dispatching enter and repair it on status updates
* fix(agent-core-v2): validate store ownership before entering tower mode
* fix(agent-core-v2): claim the repository tower owner at enter; fix(tui): confirm mode activation before reporting success
* fix(agent-core-v2): make the first tower claim exclusive and refuse adoption over a live owner
* feat(agent-core-v2): guard tower adoption and teardown with a cross-process ownership lease
* revert(agent-core-v2): drop the cross-process lease and enter-time claim, keep ownership checks process-local
* fix(agent-core): hide the v2-only tower flag from the legacy experiments list
* fix(agent-core-v2): keep tower mode inert until the tower feature is assembled
A live /experiments flip refreshes the flag but cannot re-run App-scope
feature assembly, so the tower tools/profile stay unregistered until a
restart. Gate enter()/isActive on the assembly fact and say so in the
TUI error. Also resolve the AGENTS.md conflict block committed by the
merge, and widen the TUI experimentalFlag type to string now that flags
live in two registries.
* fix(kap-server): gate the cold tower badge on tower feature assembly
Same live-flip gap as the mode machinery: a persisted tower_mode.enter
plus a flag enabled without a restart would still show the badge while
the feature is inert. Require isTowerFeatureAssembled() alongside the
flag, re-exported from agent-core-v2.
* fix(agent-core-v2): liveness-aware tower entry and per-App assembly state
enter() now mirrors TowerInit's adoption rule: a stored owner blocks
entry only while that session is live in this process, so a new session
can enter the mode and reach TowerInit to adopt a stale tower. The
assembly marker is keyed by each App's flag service (WeakSet) instead of
process-global module state, so coexisting Apps no longer leak assembly
into one another.
* fix(agent-core-v2): keep stale-owner adoption across resume; reject tower updates that do not take
exitForeignTower now treats a stored owner as foreign only while that
session is live, so a mode entered by adopting a dead owner's tower
survives close/restart. The TUI validates the model prerequisite before
enabling tower for an objective, and the REST agent_config path throws
session.tower_mode_invalid when enter() did not take effect instead of
acknowledging a no-op.
* fix(agent-core-v2): clear the tower assembly marker when the feature unloads
Register the WeakSet cleanup via the feature's onDispose so the
capability follows the managed unit's lifecycle — after
unprovideUnit('tower'), isActive/enter() no longer treat the retracted
tool set as assembled.
* fix(agent-core-v2): publish tower deactivation on gate loss; reject refused setTowerMode in the SDK
isActive now reconciles its projection: restore and feature-manager unit
changes publish AgentStatusUpdated({ towerMode: false }) when the
persisted mode lost a gate (flag off at runtime, feature unloaded), so
live transcript badges and TUI state stop showing an inert mode. The
SDK's setTowerMode(true) verifies the effective state and throws
session.tower_mode_invalid, matching the REST path.
* fix(agent-core-v2): reconcile tower projection on config changes and cold ownership moves
The last unreconciled gate inputs: a live setConfig writing the
experimental section (no session reload, no units event) now republishes
towerMode:false through the config-change subscription, and the cold
transcript badge mirrors the same ownership/liveness rule as enter() —
retained while the store owner is this session or no live session, cleared
once a live session elsewhere owns the tower.
* fix(agent-core-v2): reconcile the tower projection in both directions
The OFF-only reconcile left a hole: re-enabling the flag in the same
process made isActive true again with no towerMode:true publish, and
enter() could not heal it (it early-returns when already effective).
The projection now tracks the last published state and emits both
false→true and true→false transitions from the same restore/units/config
triggers; direct publishes (enter/exit/restoreTowerTools) keep the
tracker in sync.
* fix(agent-core-v2): validate forked tower ownership even while the flag is off
exitForeignTower's flag short-circuit let a fork restored while the
experiment was disabled keep its inherited enter record; re-enabling the
flag later revived both source and fork over the same store. Ownership
validation is flag-independent state hygiene, so restore now runs it
regardless of the effective flag — a live foreign owner clears the
fork's persisted mode before any gate can rise again.
* fix(agent-core-v2): veto tower tools while the tower experiment is off
With the feature assembled and the tool overlay active, disabling the
flag live left TowerInit/TowerTeardown callable — they have no flag
check — so prompts could still mutate or dismantle .tower/ while the
experiment reported disabled. A dedicated onBeforeExecuteTool hook now
denies every tower tool whenever the flag is off, mirroring the TodoList
veto.
* fix(agent-core-v2): keep tower worker write isolation when the flag turns off
The worker Write/Edit guard is identity-scoped (tower-worker profile),
not feature-activity-scoped: disabling the experiment live must not let
already-spawned detached workers write into the main checkout or other
worktrees. The guard no longer checks the flag; the tower-tool veto
added earlier covers protocol access instead.
* test(agent-core-v2): make tower tests hermetic for CI
Three CI-only failures: towerService git fixtures committed without a
repo-local identity (CI has no global gitconfig), the node-sdk tower
positive tests relied on the developer shell's
KIMI_CODE_EXPERIMENTAL_FLAG=1 master switch instead of enabling the
tower flag explicitly, and the legacy harness experimental-features
expectation still listed the tower entry removed from the v1 registry.
|
||
|
|
381142aff1
|
fix(agent-core-v2): let session archive proceed after a failed resume (#3139)
A failed resume is cached by SessionManager and rethrown from whenResumeSettled, so archiving a session whose workspace is gone failed with the stale resume error even though cold archive only rewrites session metadata. Swallow the settle failure: still wait for an in-flight resume before the live/cold classification, but fall through to the cold metadata path after a failed one. |
||
|
|
f6736d7c0d
|
feat(agent-core-v2): add a fork parameter to the Agent tool (#3007)
* feat(agent-core-v2): add a fork parameter to the Agent tool
Spawning with fork: true starts the subagent from a one-time snapshot of
the calling agent's completed conversation history — same profile, tool
set, and model — instead of zero context. The seed trims the trailing
open tool exchange (the in-flight Agent call itself) before appending
into the child's context memory, and the first prompt carries an
inheritance notice framing the seeded history as reference material.
Fork rejects resume, a different subagent_type, or a model override as
tool errors, and skips the subagents allowlist since a self-inheritance
is not a delegation.
* fix(agent-core-v2): bind the stale-todo reminder only into the main agent
Subagents share the session todo list but no longer receive the
stale-todo nudge — the reminder injector now registers only on the main
agent, so delegated and forked agents are not prompted to maintain a
list they do not own.
* fix(agent-core-v2): inherit the caller's live binding and label fork launches correctly
Review follow-ups for the Agent tool fork mode:
- overlay the caller's live profile.data() via applyBindingSnapshot after
the catalog re-bind, so ephemeral addActiveTool deltas, the rendered
system prompt, and runtime model/subagents updates survive the fork;
skip the profile prompt prefix since the caller's prefixed first
prompt is already part of the seeded history
- resolve the fork activity label and approval-rule subject from the
caller's own profile instead of falling back to the default subagent
type, so an Agent(<other profile>) rule cannot approve a fork
* fix(agent-core-v2): close inherited in-flight tool calls instead of trimming them
Fork seeding now answers the source's trailing open tool calls with a
synthetic in-flight result instead of cutting the whole trailing
exchange: the seeded history stays protocol-valid, keeps the source's
final step visible as reference, and no longer confuses side-question
(btw) agents forked while the main agent is mid-turn. The close helper
is shared by the Agent tool fork and IAgentLifecycleService.fork.
Fork launches also stop requiring the caller's profile to still exist
in the session catalog: the child is created unbound and overlaid with
the caller's live binding snapshot, matching the lifecycle fork path,
and now records forkedFrom provenance.
* refactor(agent-core-v2): route Agent tool forks through agentLifecycle.fork
* feat(agent-core-v2): add a fork parameter to the AgentSwarm tool
* fix(agent-core-v2): seal partial assistant forks
* fix(agent-core-v2): align fork parameter descriptions
* fix(agent-core-v2): drop the main-only registration gate from goal tools
* fix(agent-core-v2): disclose dates via reminders to keep the system prompt byte-stable
* docs: condense the fork changesets to single sentences
* docs(agent-core-v2): frame the tool-contribution when gate as a fork parity trade-off
* test(agent-core-v2): plug fork coverage gaps and decouple swarm tests from spawn internals
* docs(agent-core-v2): keep the when-gate guidance in the contribution JSDoc only
* fix(agent-core-v2): contribute cron tools to every agent for fork prefix-cache parity
CronCreate/CronList/CronDelete were registered directly into the main
agent's tool registry by SessionCronServiceImpl, bypassing the
AgentToolContribution seam and keying on per-agent identity — so a forked
agent rebuilt a tool surface three tools shorter than its caller and the
inherited prompt prefix missed the cache.
Register the three tools through registerAgentToolService like the goal
tools do (no when gate, identical surface for every agent) and enforce
the main-agent restriction at execution time instead. Also fall back to
DEFAULT_CRON_CONFIG when the config section is absent, since the service
can now be constructed after the main agent exists.
* feat(agent-core-v2): track the fork parameter in the subagent_created event
* fix(agent-core-v2): gate tower orchestration tools at execution time
TowerInit/TowerPlan/TowerSpawn/TowerMerge/TowerTeardown were contributed
with a when predicate keyed on agentId === 'main', so a forked agent
rebuilt a tool surface missing TowerInit (always present for the default
profile) plus the rest of the tower set once it was enabled — breaking
prompt prefix-cache parity with the caller.
Contribute the tools with no when gate (profile policy still controls
visibility) and reject non-main callers at execution time instead.
* test(agent-core-v2): expect the fork field in the subagent_created mirror assertion
* test(agent-core-v2): cover fork subagent first-request prefix parity
* refactor(agent-core-v2): share the main-agent-only tool refusal across cron and goal tools
Goal tools rejected subagent callers by throwing GOAL_UNSUPPORTED_AGENT
from the service, which the executor wrapped as a resolution failure;
cron tools returned a clean refusal but each tool open-coded the same
identity check. Centralize the check and both messages in
agent/tools/mainAgentOnly.ts and use it from all seven tools, keeping
AgentGoalService.assertSupportedAgent as the coded boundary for RPC and
SDK callers.
* refactor(agent-core-v2): keep the goal main-agent gate at the tool layer only
* fix(agent-core-v2): preserve the fork tool surface when inheriting user tools
* Revert "refactor(agent-core-v2): keep the goal main-agent gate at the tool layer only"
This reverts commit
|
||
|
|
a09d904140
|
refactor(agent-core-v2): migrate agent domains to model-as-container architecture (#3103) | ||
|
|
15da84606a
|
feat(kap-server): add workspace-grouped sessions view and lifecycle events (#3114)
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 / 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
Nix Build / Check flake.nix workspace sync (push) Waiting to run
GET /api/v2/sessions gains view=by_workspace: one request returns every workspace with a matching session, each carrying its first group.page_size sessions under the requested sort plus the workspace's full matching total, with group-level page_token pagination (40922 on condition drift). Groups key on the alias-canonical workspace id, so legacy split buckets of one physical directory merge into a single group, matching the v1 alias semantics. meta.has_prompt filters sessions by prompt presence (the v1 exclude_empty equivalent) in both views. The flat view and v1 routes stay byte-compatible. The global WS stream now fans out event.session.archived (live and cold paths; payload carries the session id and workspace_id) and event.workspace.created/updated/deleted, published by the core IWorkspaceService on every mutation path including the implicit createOrTouch on session creation. kimi-inspect consumes the grouped projection as a single-column workspace/session tree in the chat view; the session pane merges into the right dock as the Session tab. The server API reference (en + zh) documents the new parameters, the grouped response, and the new events. |
||
|
|
f1208c8d72
|
feat(agent-core-v2): rework the title generation excerpts (#3109)
* feat(agent-core-v2): rework the title generation excerpts - Rebalance the excerpt budgets toward the user's prompts (400 chars each) and trim the assistant segments (300) so titles follow the user's task instead of narrating the assistant's reply. - Cap each prompt in the default user_prompts excerpt so one long paste no longer starves the remaining prompts. - Compose the digest excerpt from the full conversation arc: every natural-language user prompt in the live window paired with its own turn's final assistant text, interleaved chronologically, with per-segment caps and a 3000-char total budget (middle turns elided). * chore: scope the title changeset to agent-core-v2 * fix(agent-core-v2): dedupe digest prompts and elide whole turns - Drop the redundant `| undefined` from the optional TitleDigestTurn.assistant per the monorepo optional-property convention. - Deduplicate user messages by id when constructing digest turns, so a prompt already in the context and still active in the queue does not produce two turns. - Elide the over-budget digest at whole-turn granularity, keeping each assistant line paired with its own user line. * docs(agent-core-v2): describe the full-arc digest in the SessionTitleSource contract |
||
|
|
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
|
||
|
|
4ff06f17e3
|
fix(kap-server): serve real session usage in snapshot and persist per-turn context readings (#3094)
* fix(kap-server): serve real session usage in snapshot and persist per-turn context readings * fix(kap-server): omit unknown session usage fields instead of reporting zero |
||
|
|
eac9ea88e8
|
refactor(agent-core-v2): persist cron tasks as durable wire records (#3093)
* refactor(agent-core-v2): persist cron tasks as durable wire records - write CronAdd/CronDelete/CronCursor as durable wire records and rebuild the cron task table from dispatcher replay - migrate legacy per-workspace cron JSON files into the wire on first resume, then drop the file-based persistence service, its registrations, and the bootstrap cron scope - derive the session cron view from the agent replayable cron state and remove the redundant session-level copy - let session forks inherit cron tasks through the copied wire instead of duplicating task files * fix(agent-core-v2): keep legacy cron tasks on cold forks and flush before cleanup - inherit legacy cron task files into a full fork's wire so cold sessions forked before their first post-upgrade resume do not silently lose scheduled tasks - flush the migrated wire records before deleting legacy files so a crash cannot lose both copies * refactor(agent-core-v2): drop the legacy cron file migration - stop reading legacy per-workspace cron JSON files entirely; pre-upgrade tasks simply stop applying instead of being migrated into the wire - remove the legacy read path, the fork-time legacy inheritance, and the now-unused session context/document store injections |
||
|
|
38a5a934ae
|
feat: project prompt attachments into the live transcript and clear the transcript goal on clear (#3088)
* feat(agent-core-v2): carry prompt attachments on turn.started so the live transcript projects them * fix(transcript): clear the transcript goal when the goal is cleared * fix(agent-core-v2): count a prompt media part as a transcript attachment only when its id matches its daemon file URL * test(kap-server): expect the session-media file id on converted prompt parts |
||
|
|
cb8a7e5f81
|
feat(kap-server): expose engine feature list on /api/v1/meta (#3085) | ||
|
|
be8e017597
|
fix(agent-core-v2): emit subagent.spawned after task registration (#3005)
* fix(agent-core-v2): emit subagent.spawned after task registration
The spawned signal previously fired at launch, before the run's task
registration, so clients learned the agent id with no task id to bind
cancel/status actions to; a failed registration also left a spawned row
behind for a run that never registered. Emit it only after registerTask
succeeds and carry the task id on the event.
* fix(agent-core-v2): keep spawned ahead of started for Agent-tool runs
The TUI drops subagent.started until spawned has established the row,
and a failed registration must not leave a started row behind with no
terminal event. Defer the mirrored started dispatch so the Agent tool
can emit it itself after registration and spawned.
* fix(agent-core-v2): void the deferred started dispatch
* fix(kap-server): key Agent-tool transcript rows by the registered task id
Transcript-protocol clients suppress the raw task.*/subagent.* session
events, so they only saw a subagent row keyed by agent id that cannot
address /tasks/{id}, plus a second row once task.started landed. Key the
spawned row by the task id it now carries, fold task.started and the
subagent lifecycle back into it, and keep the agent-id path for spawns
without a registration (swarm/session-init/tower). Statement-level
ordering notes move to the file headers per package convention.
* test(agent-core-v2): split the spawned/started ordering contract into its own test
* fix(kap-server): keep subagent result details across task termination and drop stale task mappings on taskless respawns
* fix(kap-server): recover the agent-to-task association from a backfilled task.started
* fix(kap-server): seed pre-attach Agent task mappings on the transcript binding
* fix(kap-server): seed the full in-flight task row on transcript bind, not only its id
* docs(agent-core-v2): name the state-domain event dispatcher in the Agent tool header
* style(kap-server): drop comments in transcript services per the no-comments lint rule
|
||
|
|
b478e95a2c
|
feat(agent-core-v2): reject duplicate scoped service registrations (#3057) | ||
|
|
d6021fa036
|
feat(kap-server): accept bundled skill activations on the prompt submission route (#2982)
* feat(kap-server): accept bundled skill activations on the prompt submission route The bundled-submission capability was only reachable through the in-process klient transports; the App talks to kap-server over /api/v1. The submit-prompt route now accepts an optional non-empty skills field and delegates to IAgentSkillService.promptWithSkills — same validation, events, and single bundled user message as the TUI path — skipping its own prompt-metadata update (the engine owns it there) and mapping skill.not_found / skill.type_unsupported onto the skills route's codes. To return the submission's queue identity, the engine's promptWithSkills now resolves with prompt_id / user_message_id / created_at / state (plus turn_id once launched), mirrored through the klient contract. * refactor(agent-core-v2): slim the promptWithSkills result contract Drop the user_message_id field (it is always the same identity as prompt_id — the route duplicates it) and narrow state to the running/queued/blocked vocabulary, mapped at the engine edge instead of exposing the internal seven-state PromptState on the wire. * fix(kap-server): harden bundled skill submissions against review findings - Validate bundled skill names and types before any media materialization or control override, so a rejected bundle leaves session state untouched (the engine still re-validates authoritatively). - Declare the 40415/40912 outcomes on the submit route so the generated API documentation includes them. - The klient output schema no longer tolerates a missing promptWithSkills result (a transport-level absence now raises instead of resolving undefined), and a failed launch surfaces as an error rather than a successful running result. - Add the changeset for the new public API field. * fix(kap-server): preflight bundled skills before agent materialization and stabilize listed content - Skill preflight now runs on the session's catalog before the main agent is resolved, so a rejected bundle cannot mutate session metadata by registering main (regression test on a cold session without an agent). - The prompts list projection strips the stored skill blocks from a bundled prompt, so GET /prompts returns the same caller-only content as the submit response. * fix(kap-server): reject bundled prompt_id combos at preflight and clean queued staging - The skills + prompt_id incompatibility rejection now runs at the initial bundled preflight, before the main agent is materialized or any override binds (previously a yolo override could bind before the 40001). - Queued bundles no longer skip staging cleanup forever: the discard is deferred to the bundle's prompt.completed / prompt.aborted lifecycle event, mirroring the plain path's launch-raced cleanup. * fix(kap-server): clean queued bundle staging on the steer path too A queued bundle steered into the active turn is consumed at steer time, but the engine publishes prompt.completed/aborted only for the parent — the deferred cleanup never fired and its subscription leaked. The prompt.steered event (matching promptIds) now counts as the child's intake-completion signal. * fix(agent-core-v2): materialize daemon-ref media on the steer and inject paths startNext materializes daemon file references into the session media store before a prompt's turn, but steer() and inject() enqueued the same references without that intake, leaving the staging upload as the only copy — any staging cleanup at steer time would delete the media the turn is about to consume. Both paths now run the same intake before the SteerStepRequest is created, so prompt.steered is a truthful intake-complete signal. * fix(kap-server): defer staging cleanup to turn settlement, never to steer time Prompt-intake materialization is best-effort: when it degrades, the daemon upload is the request-time resolver's fallback source. Discarding staging at prompt.steered could therefore delete the only readable copy before the parent's request ran. Cleanup is now uniformly event-driven — the bundle's own prompt.completed/aborted, or the steer parent's — so the upload always outlives the request it feeds. * fix(kap-server): install settlement tracking before bundled enqueue A hook-blocked bundle completes synchronously inside the submission call, and an exceptionally fast launch can settle just as early — a post-call subscription misses the only settlement event and leaks both the staging blob and the listener. The tracker now subscribes before enqueueing, buffers lifecycle events, and settles against the returned prompt id (or its steer parent's). * fix(kap-server): scope settlement tracking to the owning agent and dispose on rejection - The tracker now subscribes through the agent-scoped IEventBus instead of the App-scoped IEventService: prompt lifecycle events from other sessions never reach it, so a colliding client-chosen prompt id cannot trigger a foreign settlement (and the steer re-target only follows this agent's parent). - A bundled submission that rejects after the tracker was installed now disposes it on the error path instead of leaking a permanent listener. * fix(agent-core-v2): keep steered prompts queued until their media intake finishes Materializing a steered prompt's daemon-ref media awaits a file copy during which the active turn may finish. Records are now spliced out of the queue only after that copy completes, and when the turn is gone by enqueue time they are restored to pending so startNext can launch them as fresh prompts — their handles always launch or settle. * fix(agent-core-v2): revalidate the queue and active turn after steer media intake The daemon-ref copy yields, so settle/abort can consume selected records and the active turn can rotate meanwhile. Only records still pending are steered, and only into the turn that was active at entry; records that vanish from the queue are left to their own launch path, and a missing turn restores them to pending instead of splicing an unrelated tail prompt. The intake/queue-preservation contract is documented in the module header. * fix(agent-core-v2): steer only the surviving records and keep their media truthful - The steered content is rebuilt from the records that are still pending after the media intake, so an aborted or concurrently consumed record's text is never injected (or injected twice) alongside the surviving handles. - The enqueue is wrapped so an activeTurnOnly rejection restores the records to pending (the loop throws instead of resolving a missing turn, which made the previous rollback unreachable). - The merged origin now carries the union of every record's bundled skillActivations, and prompt.steered publishes the caller-only content, so the skill instructions reach the model with their metadata intact while the event projection stops leaking internal skill markdown. * fix(agent-core-v2): harden steer rollback and register bundled prompt ids * fix(agent-core-v2): strip bundled blocks from prompt.queued and reject partial steers * fix(kap-server): update session metadata for bundled prompts routed to subagents * fix(agent-core-v2): restart queue after raced steer rollback and prefix skill blocks in merged steer * fix(agent-core-v2): block queue advancement during steer admission * chore: drop the changeset for server-only protocol plumbing |
||
|
|
eaa3969dd3
|
feat(kap-server): add page mode, updated_before, and batch archive/restore to v2 sessions (#2983)
* feat(kap-server): add page-number mode and total to GET /api/v2/sessions
The v2 session list gains a stateless 1-based `page` parameter beside the
opaque page_token cursor for admin-style lists that jump arbitrarily:
each request stays a full independent snapshot, no token is minted, and
`page` + `page_token` together fail 40001. Every response now carries
`total` (the filtered/sorted set size) in both pagination modes.
* feat(kap-server): add meta.updated_before filter to GET /api/v2/sessions
Symmetric with meta.updated_after (inclusive boundary, Unix ms), applied
at the edge over the drained set and bound into the page_token query
fingerprint like every other condition.
* feat(kap-server): add POST /api/v2/sessions:archive and :restore batch endpoints
Batch archive/restore for session-management views: { ids } (non-empty,
≤5000 unique after dedup) answers per-item results in input order with
succeeded/failed counts — only a body validation failure fails the whole
request, and an unknown id folds into its own item as 40401.
The live/cold split keeps the batch cheap: a session with a live handle
goes through the full ISessionLifecycleService chain (agents drain,
scope teardown, mirror drain), while a cold session is never
materialized — the new setColdSessionArchived helper in agent-core-v2
patches the persisted state.json (archived/archivedAt, updatedAt
preserved, mirroring setArchived's touchUpdatedAt: false semantics),
mirrors the flipped summary into the read-model queue, and republishes
the same event.session.archived bus event the live lifecycle emits
(:restore publishes nothing, matching the live restore). Hot items run
with bounded concurrency and the batch ends with one shared
ISessionIndexMirror.drain().
* docs(server-api): document v2 sessions page mode, total, updated_before, and batch archive/restore
* fix(kap-server): deep-import workspace lifecycle symbols in the v2 sessions route
CI's tsgo/rolldown (Linux) fail to bind liveHandlerForSession and
IWorkspaceLifecycleService through the agent-core-v2 package-root
barrel even though it re-exports them; the same files use the
established deep-import pattern already used for the git domain.
* fix(kap-server): inline the live-handler lookup in the batch route
The previous deep imports still fail to resolve on CI's Linux toolchain
(tsgo TS2307, rolldown MISSING_EXPORT) while every other module path
from the same package binds fine. Keep the route self-contained: the
hot-path lookup is a five-line loop over IWorkspaceLifecycleService's
handlers (mirrors agent-core-v2's liveHandlerForSession), and the tests
assert non-materialization behaviorally via the live map instead of
importing the same two symbols for spies.
* fix(kap-server): drive the batch hot path through getLiveSessionById
The phantom only hits the workspaceLifecycle-group symbols in these two
files on CI's Linux toolchain; getLiveSessionById is observed to bind
fine there. It returns the session's live scope directly (no resume),
which is exactly what the batch hot path needs.
* refactor(kap-server): move the batch live/cold split into agent-core-v2
setSessionArchivedBatch owns the split next to the cold patch: live
sessions go through the full lifecycle chain via the workspace handler
accessor (the v1-proven resolution path), cold sessions through the
direct write. The route becomes a thin wire-code adapter, and the batch
tests assert the live chain behaviorally (disposal, events, index)
instead of spying through scope accessors.
* fix(agent-core-v2): import sessionLookup relatively from coldSessionArchive
The '#/app/workspaceLifecycle/*' specifier resolves from src/ and
src/app/* files on CI's Linux toolchain but not from
src/workspace/sessionLifecycle/ (tsgo TS2307, rolldown follows); a
relative import bypasses the package-imports mapping.
* fix(agent-core-v2): migrate the batch hot path to ISessionManager
Main's workspace/session DI refactor removed the workspaceLifecycle
lookup modules; the live branch now goes through the App-level
ISessionManager (the same entry the v1 action route uses post-refactor)
with getLiveSessionById from the new sessionManager lookup.
* feat(kap-server): add the id,archived item projection to GET /api/v2/sessions
fields=id,archived trims each item to { id, archived } for
select-all-matching flows (the session admin page's Gmail-style
select-all). Only that projection gets the relaxed page_size ceiling
(10000); unknown fields, non-pair subsets, and include=git combinations
are 40001, and the projection binds into the page_token fingerprint so
shapes never flip mid-pagination.
* fix(agent-core-v2): serialize the batch cold write against in-flight resumes
Codex review on #2983: while a resume is in flight the live registry
hides the handle, so the batch route could classify the session as cold
and its direct write would race the materializing metadata service (its
stale in-memory document wins the next write, silently un-archiving the
session after the endpoint reported success).
The batch now settles the resume first: SessionManager registers the
whole resume promise synchronously at the App level (controllerForSession
is async, so the controller's own resuming map learns about it a few
microtasks late) and whenResumeSettled awaits it before classification —
a settled resume lands the item on the live chain, a failed one falls
back to the cold path. Also folds the module header down to the
package's external-role comment convention.
* fix(agent-core-v2): publish SessionArchived as an Event2 class in cold archive
* fix(agent-core-v2): serialize batch archive/restore with session lifecycle transitions
* fix(agent-core-v2): serialize session delete with the lifecycle chain
* fix(agent-core-v2): mirror the persisted metadata on cold archive, not the index summary
* docs(agent-core-v2): bring sessionManager comments and new tests to package conventions
* fix(agent-core-v2): normalize legacy session metadata before the cold archive write
* fix(kap-server): serialize the v1 single-session archive with the lifecycle chain
* chore: drop changesets for internal-only protocol work
* fix(agent-core-v2): encode cold-archived metadata for v1 readers
* fix(agent-core-v2): serialize fork and createChild with the source session's chain
* refactor(agent-core-v2): chain every session lifecycle method and hand batch sections unguarded ops
* fix(agent-core-v2): propagate failed resumes to the next settle
* fix(agent-core-v2): roll back the unannounced handle when a resume fails mid-materialization
* fix(agent-core-v2): read and migrate the legacy session-meta location on cold archive
* fix(agent-core-v2): serialize explicit-id session creation with the lifecycle chain
create() with a caller-supplied sessionId bypassed the per-session chain,
so a concurrent batch archive could classify the half-created session as
cold and write archived state that the live metadata service later
overwrites. Creation now queues on the target id's chain whenever an
explicit id is present.
Also type the resume-failure maps as Error and normalize at the catch
site, satisfying only-throw-error.
* style(kap-server): strip comments from the session routes per the no-comments convention
* fix(agent-core-v2): serialize explicit fork and child target ids on the lifecycle chain
fork() and createChild() with a newSessionId locked only the source id, so
a batch archive of the target could slip into the creation window: the
index already knows the half-created session, the batch writes archived
state to its document, and the fork's in-memory metadata later overwrites
it. Both operations now acquire the deduped, sorted key set so multi-key
sections always take locks in one deterministic order.
|
||
|
|
8267bb8fce
|
feat(kap-server): add workspace fs:suggest file completion endpoint (#3019) | ||
|
|
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 |
||
|
|
1ab19190e9
|
refactor(agent-core-v2): strip comments from agent-core-v2, kap-server, and transcript (#3010)
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
|
||
|
|
09976b0914
|
feat(cli): add --web-title and expose it via /meta (#2989)
* feat(cli): add --web-title and expose it via /meta * refactor(kap-server): pass optional web_title directly in /meta Per the repo rule for optional object properties, pass undefined directly instead of a conditional spread; serialization omits the unset value. * fix(cli): sync web bundle with instance tab title support The committed dist-web bundle predates the document title feature, so a released `kimi web --web-title` served a client that never read web_title. Rebuilt from code-app (feat/web-document-title) via sync:web; the bundle now titles tabs from web_title or the active workspace directory. * ci: retrigger checks after flaky harness cleanup failure --------- Co-authored-by: wbxl2000 <wbxl2000@outlook.com> Co-authored-by: bj456736 <bj456736@users.noreply.github.com> |
||
|
|
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 |
||
|
|
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.
|
||
|
|
04d23e2dab
|
fix(agent-core-v2): unify text/binary classification for UTF-8 multibyte files (#2972) | ||
|
|
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 |
||
|
|
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).
|
||
|
|
249d8faa34
|
fix(agent-core-v2): mint interaction ids engine-side (#2911)
* fix(agent-core-v2): mint interaction ids engine-side Self-hosted OpenAI-compatible endpoints may renumber tool call ids on every response (Bash_0, Bash_1, ...). The approval/question/user_tool facades used the provider toolCallId as the interaction id, so a repeated id was silently swallowed by client-side pending-interaction dedupe: the approval prompt never appeared and the turn parked forever (#2908). Interaction ids are now minted by the engine (approval_<uuid> / question_<uuid> / user_tool_<uuid>); the provider toolCallId stays on the payload for correlation. This matches v1 semantics, where the approval id was already a daemon-minted id independent of the tool call id. * fix(agent-core-v2): normalize duplicate provider tool call ids at ingestion Self-hosted OpenAI-compatible endpoints may renumber tool call ids on every response (Bash_0, Bash_1, ...), and every downstream keying assumes an id identifies exactly one call: context rebuild silently drops the second tool result with a duplicated id, the strict projector discards duplicate calls, transcript frames merge, and approval/activity correlation misfires. A per-agent ToolCallIdNormalizer in the llmRequester stream boundary now tracks ids already claimed (seeded from the restored context). The first occurrence passes through unchanged; later occurrences — across responses or within one — are rewritten to a readable <id>__<n> suffix, kept consistent between streamed deltas and the finalized message, and logged for provenance. A failed attempt rolls its claims back so a projection retry re-streams the same logical calls under the same ids. * fix(agent-core-v2): thread the minted approval id through events and status The permission.approval.requested/resolved events only carried the provider toolCallId, so AgentActivityView exposed approvalId = toolCallId and the agent.status.updated approval phase forwarded an id that POST /sessions/{sid}/approvals/{id} cannot resolve — the kernel parks under the minted approval_<uuid>. Mint the interaction id at the agent call site and include it in the approval request payload: the kernel honors the explicit id, the events carry it, and the activity view keys pendingApprovals by it (falling back to the toolCallId for id-less events). * fix(agent-core-v2): surface minted interaction ids in facade listPending The approval/question facades returned only the original payload from listPending(), so once the kernel id stopped deriving from the provider toolCallId, hosts listing pending requests had no id to feed back into decide()/answer()/dismiss() without reaching into the kernel. Merge the parked interaction id into each returned request — the klient contract schemas already carry the optional id field, so the RPC surface becomes round-trippable as well. |
||
|
|
53909d91e3
|
fix(kimi-web): cache content-hashed assets (#2865) |