The A/B experiment on this branch concluded in favor of the pure-JS
protocol, keeping the repo free of native dependencies:
- agent-core-v2 binds PureJsLockService unconditionally; the
KIMI_LOCK_IMPL switch and the kernel-backed CrossProcessLockService
are removed.
- packages/kernel-file-lock is deleted together with the
fs-native-extensions native dependency (flake.nix workspace lists,
CLI native packaging registry, SEA smoke checks and bundle externals
updated accordingly).
- minidb once again ships its built-in pure-JS writer lock as the
default tryAcquire; the injection interface is kept for tests and
hosts, and an explicit null still opts out. Tests that pinned
kernel-only semantics now pin the pure-JS equivalents (dead-pid
takeover, tampered-payload fencing), and dual-implementation
parameterization is removed throughout.
* feat(kap-server): bundle the desktop app log into session exports on request
* refactor(agent-core-v2): align the desktop log export with repo conventions
* refactor(agent-core-v2): rebuild undo as wire-level journal rewind
Replace the compensating context.undo op with a wire-layer rewind
primitive: a log.cut control record with a persisted target, applied
uniformly by the wire during fold. Turn boundaries become first-class
(TurnIndexModel indexing turn.prompt record positions), models declare
a temporal classification (rewindable), and a single
IAgentRewindService owns the undo pipeline (quiesce -> precheck ->
cut -> reconcile) with all entry points converged.
- wire: log.cut record, rewindable model flag, re-fold rebuild;
OpApplyContext.recordIndex for position-aware reducers
- rewind service: aborts the active turn, cancels in-flight
compaction, preserves the pending queue, rebases measured tokens,
reconciles lastPrompt, tracks conversation_undo
- todo list, plan mode, task-notification delivery and the turn index
now rewind together with the undone turns
- transcript reducer applies cut ranges so snapshot/messages surfaces
stay consistent with the model context
- REST/RPC/debug undo entry points converge on the rewind service;
TUI parses the v2 undo-unavailable error shape
- legacy context.undo records keep replaying for old journals
* refactor(agent-core-v2): keep undo domain-owned
* refactor: enhance /undo functionality for consistency and safety, including todo list rollback and improved event handling
* chore: clean up undo changeset artifacts
* refactor: rebuild rewind consistency
* fix: make conversation undo durable and consistent
* fix(agent-core-v2): stabilize undo restoration
* fix: keep TUI undo on legacy error contract
* refactor(agent-core-v2): drop unused full compaction cancel API
Undo now rejects with session.busy while compaction runs instead of
cancelling it, so the awaitable cancel() added for the earlier rewind
semantics has no callers left. Remove it from the interface and
implementation; the RPC cancel path keeps using the task abort
controller directly.
* fix(agent-core-v2): remove injected context on undo
* chore(agent-core-v2): regenerate wire manifest
* docs(agent-core-dev): rename rewind to undo in layer table
* fix(agent-core-v2): undo prompt-owned image reminders
* refactor: remove transcript undo reconciliation
* fix(kap-server): map undo busy errors
* refactor(agent-core-v2): rename undo participant registry and attribute checkpoint depth
- Rename IAgentConversationUndoReconciliationRegistry to
IAgentConversationUndoParticipantRegistry (conversationUndoParticipants).
- Return the limiting model from checkpointDepth and include it in the
SESSION_UNDO_UNAVAILABLE details; report checkpoint_lost instead of
compaction_boundary when no compaction explains the missing depth.
- Add a registry invariant test: every model reacting to context.* ops
must be registered via defineCheckpointedModel or explicitly exempt.
* Delete .changeset/fix-undo-injections.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
Only subscription events now enter the timed coalescing buffer.
server_hello, acks, resync_required, and global session events join the
outbound FIFO and flush it right away, so they no longer wait behind the
flush window and cannot overtake earlier buffered subscription frames.
The broadcaster marks global fan-out with the new BroadcastDelivery
'immediate' lane.
* fix(agent-core): continue goal pursuit when a goal turn hits the per-turn step limit
* chore(agent-core-v2): regenerate state manifest
* fix(agent-core): start goal pursuit when the goal-creating turn hits the step limit
* refactor(agent-core-v2): drop step-cap narration from goal module and test
* refactor(agent-core-v2): register agent tools as DI services with profile-aware activation
- replace module-level registerTool + Eager AgentBuiltinToolsRegistrar with registerAgentTool double registration (Agent-scope DI service + contribution table)
- add toolActivation domain: AgentToolActivationService filters contributions by the bound Profile's tool policy using declared names, resolves instances lazily via accessor.get, and re-activates on agent.status.updated
- rename BuiltinTool to AgentTool service interface; tools become Agent-scope services with decorator-injected dependencies (e.g. AgentTool -> SubagentTool/ISubagentTool)
- AgentLifecycleService.create runs one activation pass after restore and profile binding so tools reflect the Profile before the first turn
- update tool registrations, scripts, and tests; add toolActivationService tests
* refactor(agent-core-v2): centralize builtin tools under agent/tools
- move builtin tools from scattered domain folders (plan/tools,
goal/tools, os/backends/node-local/tools, task/tools, etc.) into a
unified agent/tools/ directory
- split each tool into a kebab-case definition file (bash.ts) and a
registration file (bashTool.ts) pairing with its prompt markdown
- update imports across src, tests, kap-server, and TUI comments
* fix(agent-core-v2): keep agent tools out of scope-creation instantiation
Main's instantiateAll constructs every registered service at scope
creation, but agent tool constructors may legitimately throw when their
host capability is absent (e.g. WebSearchTool without a configured
provider), and profile-aware activation must stay the only resolution
path so the runtime registry holds real instances, never proxies.
- add SyncDescriptor.instantiateWithScope (default true) and let
registerScopedService opt registrations out of the instantiateAll
sweep
- registerAgentTool passes the opt-out, restoring lazy
activation-driven construction on top of the eager-scope semantics
- regenerate docs/state-manifest.d.ts
* refactor(agent-core-v2): replace delayed DI with scope activation
- add explicit OnScopeCreated and OnDemand activation modes
- remove delayed proxy and idle initialization support
- migrate service registrations, tests, and DI guidance
* refactor(agent-core-v2): instantiate all registered services eagerly at scope creation
- add instantiateAll to scope creation: every service registered for a
scope tier is constructed when the scope is created, following the
static dependency graph; a failing constructor fails scope creation
- drop the hand-maintained eager-resolution lists: igniteEagerServices
in AgentLifecycleService, the force-instantiated session services in
SessionLifecycleService, and the kosong config bridge get in bootstrap
- update DI docs and agent-core-dev skill guidance for the new semantics
- adjust affected tests (registry hygiene, timer draining, listener
ordering) and add scope-tree coverage for eager instantiation
* feat(agent-core-v2): add per-scope keyed state container (state domain)
- add _base StateRegistry: typed StateKey/defineState descriptors with
register/get/set, per-key onDidChange and global onDidChangeAny events,
and BugIndicatingError on duplicate or unregistered key access
- bind thin per-scope services at each tier: IStateService (App),
ISessionStateService (Session), IAgentStateService (Agent), so scoped
plain-data state lives in one observable container that dies with the scope
- register the state domain in the layer check script and export the new
services from the package index
- add StateRegistry unit tests and scoped resolution tests
* refactor(agent-core-v2): move session-scope service state into ISessionStateService
- add StateRegistry.snapshot() with JSON-safe serialization for Map/Set/Date/circular values
- migrate plain-data fields of 13 session-scope services (cron, interaction, sessionActivity, agentProfileCatalog, fs, fsWatch, log, metadata, skillCatalog, toolPolicy, workspaceCommand, workspaceContext) to defineState keys registered in sessionState
- register SessionStateService in affected tests and add test/state/stubs.ts helper
* feat(kimi-inspect): rework chat layout with session pane and tabbed right dock
- add SessionPane column next to the sidebar: Services tab (pending
interactions + session Service panels) and State tab polling
ISessionStateService.snapshot() every second, rendered as a live
diff tree
- merge the transcript audit panel and the agent inspector into one
RightPanel with Audit/Agent tabs that keep panel state across switches
- extract InteractionsCard from Inspector into its own component
- collapse multiline strings in StateTree into a compact hover-preview
button with a viewport-clamped fixed popup
- test: cover StateRegistry.snapshot() conversions (Map/Set/circular);
pass a session state service to SessionInteractionService in kap-server
test fakes
- update the AGENTS.md project map for the new layout
* refactor(agent-core-v2): move agent-scope service mutable state into agentState
Register each Agent-scope service's mutable fields into the agent-state
container (IAgentStateService) via defineState keys, and access them
through get/set accessors backed by states.get/set. Promise locks,
disposables, and other mechanism-only fields stay plain instance fields.
- define per-service state keys (e.g. activityView.*, goal.*, toolDedupe.*)
and register them in each service constructor
- replace direct field reads/writes with states-backed accessors across
the touched services
- update the affected unit tests for the new IAgentStateService dependency
* fix(agent-core-v2): collapse class instances in state snapshots
- StateRegistry.snapshot() now stops at custom-prototype boundaries and
emits '(ClassName)' markers, so resource graphs reachable from registered
values (e.g. tool instances holding service references) can no longer
exhaust the heap during export; plain data keeps recursing
- add agent-scope state test covering the full assembled agent scope
- kimi-inspect: extract the session State card into a shared StateCard and
add an agent State tab in RightPanel polling IAgentStateService.snapshot()
- document the per-scope state container pattern in the agent-core-dev skill
* refactor(agent-core-v2): keep resource-holding state out of the state container
- move fields holding live resources (tool entries, managed tasks, turn
jobs, prompt records, MCP registrations, profile callbacks) back to
plain private fields so the agent state service only holds
snapshot-safe plain data
- add gen:state-manifest script that statically collects defineState
keys and their register call sites into docs/state-manifest.d.ts
- add state manifest freshness test and update agent-state docs
* chore: add changeset for session-scope state container
* docs(agent-core-v2): move eager-instantiation notes into the scope.ts header
* fix(kimi-inspect): suppress stale state tree while switching state owner
* fix(tui): steer user messages into the running turn while a goal is active
* fix(tui): reset request state when steering mid-goal input fails
* fix(agent-core): update session prompt metadata on steer
A/B experiment B side: port the historical minidb pure-JS lock protocol
(tmp+link publish, PID-liveness takeover, watch/bid sidecars, adaptive
settle, bid-rename takeover) into PureJsLockService implementing
ICrossProcessLockService, selectable via KIMI_LOCK_IMPL=kernel|purejs
(default kernel) at the App-scope DI binding.
minidb's writer exclusion is dependency-inverted: LockFile takes an
injected tryAcquire (MiniDb.open / ClusterDb options pass it through,
kernel-file-lock drops to a devDependency) and ships no lock
implementation; without an injection it assumes a single writer
(documented). MiniDbQueryStore injects the selected lock service's
tryAcquire adapter into its shard writers.
Lock-related tests are parameterized to run under both implementations,
with pure-JS-specific takeover cases added to the existing test files.
* feat(agent-core): defer registered user tools
Allow hosts to mark registered user tools as deferred so select_tools can discover and load their schemas on demand in both agent-core implementations.
* fix(agent-core): hide unregistered deferred tools
Filter loaded deferred user-tool schemas from provider history and loaded-state checks after unregister while preserving canonical history and disconnected MCP behavior.
* fix(agent-core-v2): drop stale inline schemas
Stop treating previously loaded user-tool schemas as active after the same tool is re-registered for inline disclosure.
Capability resolution now falls back from trait hooks (last declarer
wins) to the protocol base catalog to UNKNOWN_CAPABILITY; the
definition layer is removed from the chain.
- remove ProviderDefinition.capability and the definition branch in
ProtocolAdapterRegistry.explainCapability
- kimi contrib drops its UNKNOWN_CAPABILITY declarations, so base-known
model ids resolve through the base catalog instead of being
suppressed by a vendor-level UNKNOWN
- update composition tests for the new resolution order
* fix(agent-core-v2): honor explicit undefined field deletes in modelsToToml
The models TOML transform merged each entry as { ...oldRaw, ...converted },
so a field the new record carried with an explicit undefined — deleted from
'converted' by setDefined — was put right back from the old on-disk raw.
Field-level clears issued through config.replace (e.g. the provider write
routes dropping base_url, display_name, capabilities) only took effect in
memory and resurrected on the next boot. Merge via setDefined onto the old
raw directly, matching providerEntryToToml.
* feat(kap-server): add provider write endpoints and models.dev/registry import
Add the provider management write surface plus server-proxied catalogs so
API clients (the desktop app first) can manage providers without editing
config.toml by hand:
- POST/PUT/DELETE /providers: manual create, replace-style edit (new_id
rename with pointer migration, tri-state api_key, form-unknown fields
merged through), and delete with real alias removal.
- GET /providers/{id} additionally reveals the stored api_key for edit
prefill on the loopback+bearer transport; the list stays redacted.
- GET /catalog/providers[{id}]: pruned models.dev directory with import
eligibility resolved server-side (10-min cache, stale fallback, built-in
snapshot, shared in-flight fetch).
- POST /providers:import_catalog and :import_registry (collection actions
next to :refresh): catalog/registry imports with TUI-aligned
remove-then-apply refresh semantics, OAuth-managed guards, and the
registry source blob that scheduled refreshes rediscover.
Write-path consistency: field-level clears assign explicit undefined (the
TOML transforms only drop keys that way), import refreshes swap aliases in
two passes so stale on-disk fields cannot ride along, re-imports keep the
stored credential when api_key is omitted, and multi-step writes serialize
through a process-local chain. Global default_provider/default_model are
never modified by provider writes.
* fix(kap-server): cache the built-in catalog fallback and guard alias-key collisions on replace
- Cache the built-in snapshot on upstream failure, so an offline install no
longer pays the full upstream timeout on every catalog call.
- Reject a PUT whose rebuilt alias keys collide with an alias owned by
another provider (foreign-prefix keys are global), checked before any
write so a collision never lands half the edit.
* fix(kap-server): make toCatalogProviderItem's switch explicit for older TS control-flow
* chore(agent-core-v2): drop inline rationale per package comment conventions
* feat(kap-server): seed default_model on provider create/import when none is configured
A fresh setup has no global default model, so the first provider added
through the write endpoints left GET /auth permanently unready and new
sessions without a selected model. Seed default_model from the created
provider's default (or first) model on POST /providers, :import_catalog
and :import_registry when — and only when — no default is configured;
an existing pointer is never moved, not even a dangling one.
* refactor(agent-core-v2): own the models.dev provider import in the engine
kap-server's provider write endpoints imported @moonshot-ai/kosong and
@moonshot-ai/kimi-code-oauth directly for the models.dev browse/import
and custom-registry import. Move that capability behind a new App-scope
IModelsDevImportService so the server only talks to agent-core-v2:
- app/kosongConfig/modelsDev.ts mirrors the third-party api.json schema
and hosts the pure translation (wire inference, endpoint resolution,
model pruning, thinking/gateway overrides) ported from kosong's
catalog.ts; kosong's own type surface stays limited to built-in
vocabulary
- modelsDevUpstream.ts owns the directory fetch, 10-minute cache, and
built-in snapshot fallback; modelsDevImportService.ts owns the import
orchestration (tri-state api_key, two-pass alias swap, OAuth-managed
rejection, serialized writes) with coded modelsDev.* errors
- kap-server routes shrink to wire mapping (zod schemas + numeric error
code mapping) and drop the kosong/oauth dependencies
The /api/v1 surface is byte-identical: the apiSurface snapshot and all
existing modelCatalog tests pass unchanged.
* chore: drop the branch's changesets
* fix(agent-core-v2): route the models.dev always-thinking exemption through kosong
The zero-tolerance vendor-name gate forbids a 'kimi' compare outside the
kosong layer, and the engine-side models.dev port carried one inline.
Kosong (the vendor layer, owner of thinking semantics) now answers the
verdict — wireHasProtocolThinkingDisable — and kosongConfig/modelsDev.ts
asks it instead of comparing wire ids.
---------
Co-authored-by: haozhe.yang <yanghaozhe@moonshot.ai>
* chore: prune non-user-facing changesets
Remove entries covering only agent-core-v2 internals, kap-server
protocol/endpoint changes, and experimental-engine behavior; the
underlying changes still ship with the next user-facing release.
Downgrade the MCP timeout and web service env var additions from
minor to patch, as both extend existing configuration surfaces.
* chore: document user-facing criteria in gen-changesets skill
Add Core Rule 6 to skip changesets for changes users cannot
perceive, note pre-release pruning in the workflow, and classify
configuration additions to existing features as patch.
* feat: support a configurable secondary model for subagents
* refactor: move the subagent model config to a consumer-neutral [secondary_model]
The secondary model becomes a model-domain concept next to default_model so
future consumers beyond subagents can share it: [secondary_model] model /
effort in config.toml, KIMI_SECONDARY_MODEL / KIMI_SECONDARY_EFFORT env
overrides, and the Agent / AgentSwarm per-spawn choice renamed from
"subagent" to "secondary".
* docs: replace "v2 engine only" notes with the concrete effective surfaces
State that [secondary_model], its env overrides, the Agent/AgentSwarm
model parameter, and SYSTEM.md take effect only under kimi web and
experimental kimi -p (the TUI ignores them), and that --agent /
--agent-file are available only under experimental kimi -p. Also drop
the SYSTEM.md claim of parity with --agent/--agent-file, which was
inaccurate: SYSTEM.md is an agent-core-v2 app-domain feature and also
applies under kimi web, while the flags are gated at the CLI.
* fix: review follow-ups for the subagent secondary model
- Drop the "cheaper" claim from the Agent/AgentSwarm model parameter
descriptions and the advertised model list — the secondary model is
not necessarily the cheaper one.
- Downgrade the changeset to patch, note the kimi web / experimental
kimi -p effective surface, and tighten the wording.
- Remove the onWillRestore stub fields from two lifecycle stubs; they
belong to upcoming lifecycle work, not to this change.
* fix(agent-core-v2): prevent ghost agents from invalid model bindings
* fix: narrow the secondary-model error hint to missing-alias failures
The model catalog's not-configured throw now carries details.model, and
wrapSubagentModelError only decorates errors whose details.model matches
the bound model. Malformed [models.*] entries and unrelated config.invalid
failures during agent creation pass through untouched instead of being
misattributed to an invalid secondary-model alias.
* fix: mark subagent resume semantics as breaking
* chore(agent-core-v2): follow header-only comment convention
* fix(agent-core-v2): await agent restore preparation
* feat(agent-core-v2): support agent model preferences
* Update subagent-secondary-model.md
Signed-off-by: 7Sageer <12210216@mail.sustech.edu.cn>
* fix: validate secondary models before agent creation
* Delete .changeset/secondary-model-startup-warning.md
Signed-off-by: 7Sageer <12210216@mail.sustech.edu.cn>
* Add secondary_model config section for subagents
Individual agents can override this via the new `model_preference` field in their agent file.
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* feat(agent-core-v2): support override patches in [secondary_model]
The recipe is now `model` plus the flattened ModelOverride field set.
With any patch field set, a config overlay synthesizes a derived
registry entry (base copy, patch merged into overrides, aliases
dropped) so subagent spawning rides the standard effectiveModelConfig
merge; with none, subagents bind the pointed entry directly.
`default_effort` replaces `effort` (KIMI_SECONDARY_EFFORT rebinds)
and doubles as the explicit subagent thinking; unset, thinking
resolves naturally instead of inheriting the caller. The overlay
strips the derived entry (and any defaultModel pointer to it) from
writes, and the kap-server GET /models route hides it from pickers.
* fix(agent-core-v2): fire section events for overlay-rewritten domains
rebuildEffective only committed the caller-named domains, so a
ConfigEffectiveOverlay or section env binding that rewrote a sibling
domain (setting [secondary_model] synthesizes a derived models entry;
removing the recipe retracts it) left consumers of the models section
stale. Widen the commit candidates with every domain the recompute
actually changed; commit() deepEqual-guards each candidate, so the
widening costs nothing.
* feat(agent-core-v2): gate secondary model behind experimental flag
* Update subagent-secondary-model.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
---------
Signed-off-by: 7Sageer <12210216@mail.sustech.edu.cn>
Signed-off-by: 7Sageer <sag77r@hotmail.com>
OpenAI-compatible endpoints disagree on the wire field for reasoning
content: `reasoning_content` (DeepSeek/Moonshot convention, older vLLM)
vs `reasoning` (OpenAI GPT-OSS guidance, current vLLM — which also only
accepts `reasoning` on the request side, vllm-project/vllm#38488).
Reading only `reasoning_content` silently dropped thinking, and the lost
thinking then never made it back into later requests.
Add per-endpoint dialect detection: inbound responses are scanned in
priority order (reasoning_content, reasoning_details, reasoning; first
string value wins), the carrying key is remembered, and outbound
messages echo thinking under the same key (default reasoning_content).
An explicit `reasoningKey` / `reasoning_key` config still pins the
dialect.
- kosong: shared reasoning-key module; wire the kimi and openai-legacy
providers; the dialect cell is shared across per-step provider clones.
- agent-core-v2: same mechanism in the vendored openai-legacy base; the
kimi trait no longer pins reasoning_content (the default already is),
keeping Moonshot wire behavior byte-identical while adapting to vLLM.
- agent-core: memoize the base provider behind ConfigState.provider so
the detected dialect survives across turns instead of being rebuilt
per access.
* feat(session): add core work aggregate and consume it at WS/REST edges
- agent-core-v2: add the sessionActivity domain (ISessionActivityView,
Session scope) folding each agent's activity view and the interaction
kernel into busy / main_turn_active / pending_interaction /
last_turn_reason, firing cause-tagged change events only on real
tuple changes
- kap-server: resolveSessionFacts reads the core view; the WS
broadcaster drops its per-agent fold/dedup and delegates to the
view, deferring turn_ended emissions until after the turn.ended
frame so busy:false never precedes it; global events now fan out
to every established connection via addGlobalTarget without any
subscription
- kimi-inspect: add src/activity (GlobalEventsWs + SessionActivityHub
+ useSessionActivities) consuming the global push; the Sidebar
renders running / approval / question / failed badges per session
* feat(kap-server): decouple transcript stream from agent_filter
- transcript frames (transcript.reset/ops) are governed by the per-agent
transcript grades alone and bypass the legacy agent allowlist; the filter
still gates session_event delivery
- client_hello is handshake-only in code: hello and subscribe share one
attach path, and hello's inline subscription fields are deprecated
(subscriptions made optional) in both protocol packages
- flush deferred work_changed(busy:false) from a microtask so it always
lands after the matching turn.ended frame
* fix(kimi-inspect): restore session activity hub in the browser
- bind the default fetch in SessionActivityHub: a member call hits the
browser's Illegal invocation (receiver is not the global object), and
the swallowed error left the REST seed never firing, so the Sidebar
badges never populated on refresh
- create the hub in useEffect + useState instead of useMemo: under
StrictMode the first mount's cleanup closes the memo-created hub for
the rest of the page's life
* chore: add changeset for the global session work status push
* feat(kap-server): add transcript plan endpoint for ExitPlanMode calls
- add GET /sessions/{id}/transcript/plan projecting one ExitPlanMode
call's plan info (content, path, options, review outcome) from the
first available fact: the linked approval interaction's request
display, the live tool frame's display, or the tool result output
- add TOOL_CALL_NOT_FOUND (40416) error code
- add transcriptPlanResponseSchema to the transcript contract
- cover live, auto-mode, cold-rebuild, and error paths in tests
- update the API surface snapshot and AGENTS.md
* feat: move transcript subscriptions to subscribe_v2 and extend the plan endpoint
- add subscribe_v2 / unsubscribe_v2 WS control frames as the only
carrier of per-agent transcript grades and the transcript_since
cursor; client_hello / subscribe no longer accept transcript fields
- serialize control-frame handling per connection so interleaved
attaches cannot overwrite fresher subscription state
- make tool_call_id optional on GET /sessions/{id}/transcript/plan:
omitted lists every ExitPlanMode call with recoverable plan content
as a plans array
- add a Plan lookup card to the kimi-inspect agent inspector via
fetchTranscriptPlan
- add TOOL_CALL_NOT_FOUND (40416) to the shared protocol error codes
- update AGENTS.md and add changesets
* feat: configure web search/fetch services via KIMI_WEB_* env vars
KIMI_WEB_SEARCH_BASE_URL / KIMI_WEB_SEARCH_API_KEY and
KIMI_WEB_FETCH_BASE_URL / KIMI_WEB_FETCH_API_KEY overlay the
[services] config section field by field in both engines (env wins
over config.toml), so the WebSearch and FetchURL backends can be
pointed at a Moonshot service without OAuth login. The v2 engine now
also honors the explicit [services.moonshot_fetch] section
(config > managed OAuth > local), which it previously parsed but
never consumed.
* fix(agent-core-v2): guard stripServicesEnv against clearing the services section
config.replace(SERVICES_SECTION, undefined) — the logout deprovisioning
path in authService — passes undefined straight into the section strip,
and the composed stripServicesEnv dereferenced it (value[key]), throwing
TypeError and aborting logout mid-cleanup. Add the same isPlainObject
guard the other strip implementations (stripProvidersEnv,
stripEnvBoundFields) already have, plus a regression test that also
locks in the env overlay staying effective after the file value is
cleared.
* style(agent-core-v2): follow header-only comment convention
* fix: isolate env web service credentials
* Add env vars for web search and fetch services
The new environment variables `KIMI_WEB_SEARCH_BASE_URL`, `KIMI_WEB_SEARCH_API_KEY`, `KIMI_WEB_FETCH_BASE_URL`, and `KIMI_WEB_FETCH_API_KEY` take priority over the corresponding fields in `config.toml`. The `kimi web` backend now honors the `[services.moonshot_fetch]` config section.
Signed-off-by: 7Sageer <sag77r@hotmail.com>
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* feat: add global default MCP server startup timeout config
Add a `[mcp] startup_timeout_ms` config.toml section with a
`KIMI_MCP_STARTUP_TIMEOUT_MS` env override as the global default MCP
server connection (startup + tool discovery) timeout. Precedence:
per-server `startupTimeoutMs` in mcp.json > env var > config.toml >
built-in 30s default.
* feat: add global default MCP tool call timeout config
Extend the `[mcp]` section with `tool_timeout_ms` and the
`KIMI_MCP_TOOL_TIMEOUT_MS` env override as the global default for
single MCP tool calls, mirroring the startup timeout: a per-server
`toolTimeoutMs` in mcp.json still wins, and unset entries fall back to
the SDK built-in 60s default.
* chore: shorten the mcp timeouts changeset
* feat(agent-core): add global default MCP server timeout configs
Port the `[mcp]` section (`startup_timeout_ms` / `tool_timeout_ms`)
and the `KIMI_MCP_STARTUP_TIMEOUT_MS` / `KIMI_MCP_TOOL_TIMEOUT_MS` env
overrides to agent-core (v1), mirroring the v2 semantics: per-server
fields in mcp.json > env vars > config.toml > built-in defaults. The
v1 TOML loader gains explicit `mcp` read/write mappings, and both
connection-manager construction sites (Session, testGlobalMcpServer RPC)
pass the resolved defaults through.
* fix(agent-core): validate and apply MCP timeout defaults
* fix: propagate MCP startup timeout to SDK requests
* refactor(agent-core-v2): resolve MCP default timeouts at connect time
Keep the session connection manager synchronously lazy instead of gating
its existence on config readiness: resolveDefaultTimeouts is read from the
mcp config section at each (re)connect, so AgentMcpService's eager
construction stays unconditionally safe and reconnects pick up changed
preferences. The initial connect still awaits config.ready for a
deterministic snapshot. Also restore the ISessionMcpService method docs,
bump the changeset to minor, and fix the v1 env-parse comment.
* chore(agent-core-v2): regenerate config manifest for the mcp section
* Add global default MCP server timeouts configuration
Specify the new global default MCP server timeouts in both the config file and environment variables.
Signed-off-by: 7Sageer <sag77r@hotmail.com>
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
- klient: declare @moonshot-ai/kap-server devDependency (and lockfile) so
the e2e server-pair harness resolves on clean installs
- kap-server: import ProviderRefresh* from app/kosongConfig/discovery after
the upstream kosong decoupling moved it; narrow journal readError to
Error | undefined to satisfy no-redundant-type-constituents and
no-base-to-string
- agent-core-v2: align plan-file write integration tests with the guard's
pass-through adjudication (approval, deny rules, and fencing all apply)
- test harness: force synchronous activity-view instantiation so Delayed
ignition cannot race a test turn and drop agent.activity.updated events
* feat(agent-core-v2): add generated config section manifest
- add scripts/gen-config-manifest.mts: drains the live
registerConfigSection / registerConfigOverlay contributions and renders
docs/config-manifest.toml in the on-disk config.toml shape (owner,
scope, registered defaults, env bindings, schema fields)
- add a gen:config-manifest package script (--check mode included) and a
freshness test that rebuilds the manifest and compares byte-for-byte
- point the agent-core-dev config skill and the package AGENTS.md at the
generated manifest instead of the stale hand-maintained ownership map
* feat(agent-core-v2): add generated wire-protocol manifest
- add scripts/gen-wire-manifest.mts to generate docs/wire-manifest.d.ts
from defineOp registrations (payload interfaces, persist policy,
toEvent, cross-reducers) plus a WirePayloadMap
- extract shared JSON Schema helpers from gen-config-manifest.mts into
scripts/lib/jsonSchema.mts
- add gen:wire-manifest script and wireManifest.test.ts freshness check
- document the manifest in packages/agent-core-v2/AGENTS.md
* fix(agent-core-v2): keep array-of-tables manifest sections fully commented
A bare `[hooks]` header parses as a plain table, which array sections
reject on load; emit only the commented `[[hooks]]` shape so the
manifest matches the on-disk config.toml shape it documents.
Addresses a Codex review comment on PR #2086.
* refactor(agent-core-v2): decouple kosong from config persistence
- keep the kosong provider/model registries in memory and sync them with
config.toml through a new app/kosongConfig two-way bridge: hydrate on
startup, push config section changes into the registries, and persist
runtime mutations (discovery refresh, OAuth provisioning, default-model
pointer changes) back to disk
- declare the providers/models/thinking section constants, zod schemas,
env bindings, and TOML transforms in a single app/kosongConfig
configSection.ts; kosong keeps hand-written types only
- pin every schema to its kosong type at compile time via
AssertExact<Equal<...>> (_base/utils/typeEquality)
- register a transitional auth>kosongConfig exception in the domain-layer
checker for the OAuth provisioning flows
* chore(agent-core-v2): drop unused IConfigService import from authLegacy
* fix(agent-core-v2): reconcile registry with env-pinned default pointers
A registry-originated default-model/provider write lands only in the
config user layer when an effective overlay pins the section
(KIMI_MODEL_NAME pins defaultModel to the reserved env model): the
effective value does not move and no change event fires, so the registry
diverged from the effective config view — catalog/auth reads reported the
user pick while profile resolution kept the pinned model. After
persisting, the bridge now re-asserts the effective value into the
registry, restoring the pre-refactor behavior where every default-pointer
write was arbitrated by the effective view.
* fix(agent-core-v2): await persistence before resolving kosong registry mutations
ProviderService/ModelService mutations resolved as soon as the in-memory
registry updated, while the kosongConfig bridge persisted the change on an
unawaited private chain — callers (klient kosong.*, set_default route,
OAuth provision, discovery refresh) could observe success before the write
reached config.toml, and a restart right after could lose it.
- fire registry change events through AsyncEmitter and await delivery in
set/delete/replaceAll/setDefaultX, so a mutation resolves only after
listeners' waitUntil work completes; loadAll keeps synchronous timing
- the bridge hooks its persists into waitUntil, hoists the equality guards
into the listeners so config-originated echoes stay fully synchronous,
and serializes persists on the chain as before
- retry a failed persist with bounded backoff (3 attempts); failures are
logged, never rejected to callers, and the in-memory change stands
- default-pointer change events now carry an { id } payload (fireAsync
requires object events)
- add the klient kosong-config stress example covering read-after-write,
concurrent bursts, and restart durability
The CLI only used kernel-file-lock for setKernelFileLockBindingLoader.
The binding hook is a host integration point on the engine's lock layer,
so expose it from the agent-core-v2 package root and drop the direct
dependency. Behavior is unchanged: the loader registration is a
process-global Symbol.for slot and binding resolution stays lazy.
- fileFencing: adjudicate through the onBeforeExecuteTool veto event
(cold waitUntil probe after approval) instead of the removed
onBeforeExecuteTool hook slot
- sessionLifecycle: copy fork session files via materializeSession's new
beforeReady hook — under the target lease, yet before the readiness
awaits so the forked tool policy is loaded
- kap-server: kosong discovery import path, required broadcaster homeDir
- tests: writeText HostFileStat returns, sessions-dir listing
expectations, workspace-aliases lock wiring
- Updated `SessionEntry` interface to replace `registration` with `writeAdmissionRegistration` and `scope` with `storageScope`.
- Adjusted related logic in `SessionLifecycleService` to reflect new property names.
- Modified session flush and update methods to use `storageScope` instead of `scope`.
- Refactored `SkillRootWatcher` to replace `sentinel` with `ancestorWatch` for better clarity in root tracking.
- Changed `FileWorkspacePersistence` to use `sourceDocument` instead of `raw` for workspace catalog handling.
- Updated `CrossProcessLockService` to rename payload interfaces for better semantic understanding.
- Refactored session file ledger to use `FileRevision` instead of `FileStatTuple` for improved clarity in file state management.
- Adjusted tests to reflect changes in property names and types across various services.
Net -40% PR test lines (7504 -> 4508) while keeping a verified probe
for every failure mode the PR introduces:
- delete harness self-tests and the subprocess e2e harness (klient
dual-instance, spawn machinery) whose behavior is pinned by real
scenario tests; cover holder-death lock release with a cheap SIGKILL
unit test in kernel-file-lock instead
- drop duplicate verdict-matrix variants, trivially-true assertions,
and re-proven endpoint checks across fencing, ledger, journal,
broadcaster, fs-watch, config, and web suites
- compact shared rigs (sessionLease helpers, fileFencing/fileLedger
slim DI wiring, broadcaster it.each + shared sessionEvents helper,
ws-lifecycle shared setup)
- sacrifice a documented set of sole-probe tests for volume (fsService
gitignore cache, skill-listing reminder, kap-server ownership e2e,
journal LAST-header/malformed-middle, cross-process wait/deadline
paths); each is recoverable from history if the behavior regresses
- add a held_by=peer ownership-join probe to kap-server sessions tests
Unify the four ino/mtimeMs/size comparators into _base's
fileStatTuplesEqual, route persist.ts through the shared
assertScopeWritable gate, share HELD_BY_PEER_CREATING_DETAILS between
sessionLease and the lifecycle, extract dropCommittedLines in the
journal and subscribe-ack/classify helpers in wsConnectionV1, and drop
dead surface (unused PersistedWorkspaceFile export, unreachable
fsWatch guard, inline lstat conversion, private isDir copy).
- remove the unregistered-writer ownership variant and the dead
session.list_changed / skill_catalog.changed zod schemas (no producers
or runtime consumers)
- unpublish CrossProcessLockService.acquireWithWait and
KernelFileLockHandle.path; drop minidb's release() alias
- converge duplicated assertScopeWritable, keyed-exclusion queue,
special-file stat predicate, and stat-tuple comparison into shared
helpers; import syncDir from agent-core-v2 in kap-server
- extract a shared session-release hook for the three ws bridges and
delegate resolveSessionOwnership to heldByPeerDetailsFromInspection
- deduplicate test scaffolding (watch/authority/skill stubs, klient e2e
helpers) and remove or merge duplicate test cases
- revert unrelated formatting/comment churn and point design-doc
references at section numbers instead of a local scratch path
- merge the two overlapping lock changesets into one
Decouple the session file ledger from the fs watcher: verdicts come from
a fresh stat-tuple compare immediately before execution, with no watcher
ticks or cross-process file locks. Drop the dead dirty-tick and
ensured-roots surface from the session fs watch service so it is only a
confined, debounced change feed. Write fencing no longer keeps per-call
target bookkeeping: the did-hook baselines the ledger from the revision
the executed call attached to its own result. FileEditService verifies
stat stability across the read-transform-write window.