The main merge reduced #/kosong/model/hostRequestHeaders to the pure
port contract; define the test's headers as a plain value matching it
and tidy the SDK test import grouping.
Auto title no longer consumes close-awareness, so the machinery goes
back to the simple forms: close/archive run straight through, resume
no longer waits out an in-flight close, create/fork drop their target
reservation, and a cold archive is a no-op again. Reverts the behavior
of e7c397a7c and cd1cea0fd on top of the sessionLifecycle rename.
* fix(agent-core-v2): resolve package self-references in check-import-boundaries
Imports spelled @moonshot-ai/agent-core-v2/<path> (the legal `./*` export
self-reference) were treated as external packages, letting kosong layer
violations through that spelling pass the checker.
* refactor(agent-core-v2): move host runtime args onto IBootstrapService
- Add HostArgs under BootstrapInput.args / IBootstrapService.args
(agentFiles, skillDirs, requestHeaders, displayName, replyStyleGuide),
mirroring VS Code's NativeParsedArgs on the environment service
- Remove the narrow per-domain runtime-options services and their seed
functions: IAgentCatalogRuntimeOptions, ISkillCatalogRuntimeOptions,
IHostIdentity
- Reduce IHostRequestHeaders to a pure kosong port contract and bridge it
from bootstrap args via a new app/kosongConfig adapter, keeping kosong
free of app-layer imports
- Pass host args through bootstrap() at the composition roots (kap-server,
v2 print CLI, node-sdk) instead of seeding services
- Persist SDK provider removal as one atomic multi-section config replace
* fix(config): persist provider refresh updates atomically
- expose atomic multi-section config replacement through klient and SDK
- stage provider removals before one atomic write in TUI refresh
- briefly drain startup refresh during shutdown
The listed-session titleKind had no consumer: the TUI's title-generation
gate seeds from the resumed summary, which reads the live metadata
document, and the kap-server REST wire never carried the field. Removing
the projection also retires the read-model summary version stamp (the
remaining shape is fully field-checkable) and the duplicate title-kind
derivation that had to stay in lockstep with sessionMetadata. The klient
list contract and the node-sdk list mapper drop the field with it; the
resumed/live summary still reports the canonical title state.
* feat(agent-core-v2): persist the terminal turn.ended wire record
- add a persisted turn.ended op (turnId, reason, error, durationMs)
dispatched from the loop's runTurn finally block, alongside the event
- fold the record back in the transcript cold rebuild: terminal state
(blocked folded into failed, mirroring the live wire edge), durationMs,
error message and endedAt; journals without the record keep the
grouping default
- restrict the test harness's snapshot waiters to emit entries so the
same-named wire record no longer shadows the turn.ended event
* chore(agent-core-v2): stabilize unique-symbol keys in the state manifest
The checker names a unique symbol key __@name@NNNN, where NNNN is a
compilation-global counter that shifts with unrelated type additions and
churns the generated manifest. Render the stable __@name form instead.
* fix(transcript): map turn.ended around hidden turns in the cold fold
RetryStepRequest opens a real engine turn with origin 'retry' but
contributes no context messages, and a queued-then-cancelled
reservation consumes an engine id without starting. Both make engine
turn ids drift from the grouping ordinals, so matching turn.ended by
ordinal could stamp a later visible turn with the wrong terminal state.
Replay the loop's turn-clock records (turn.prompt / turn.cancel) and
map engine ids to ordinals past the hidden ids; the hidden turns' own
end records map nowhere and are dropped.
Nothing calls force: with it gone, plain calls always coalesce onto the
shared in-flight generation, so the generation sequence and the
caller-supplied allowWhen veto lose their only purpose and go with it.
The title/generate REST route takes no body anymore.
Auto title is best-effort: a generation racing session close no longer
cancels its fetch or guards its write-back, so the per-session
sessionLifetime AbortSignal seed, the onWillCloseSession drain, and the
close-time invalidation go away. The newest-request-wins write-back
predicate stays.
Concurrent resumes only share a facade when their inputs match — a
caller passing different dirs, replay, profile, or kaos options gets its
own resume instead of having its options silently dropped.
An archive requested during a plain close is applied through the live
metadata during the teardown (or lands on the persisted document when it
arrives too late or the close fails), publishes the archived event, and
works on cold sessions too. A resume waiting on a failed close retries
instead of propagating the hook error, the teardown completes even when
the agent drain fails, and the create/fork rollback only ever removes
its own handle — a loser of the reservation race can no longer tear down
the winner's live scope.
A forced regeneration could be followed on disk by an earlier plain
call's slower backend response. Each generation now carries a
monotonically increasing sequence (assigned only once a request actually
proceeds to generation), and the serialized metadata write is vetoed
unless the writer is still the newest request.
readSummary now derives the title state with the same priority chain as
the metadata document's canonical normalization (explicit custom marker,
valid titleKind, legacy false marker, customTitle, plain title), so list
and resume agree on legacy documents too. Read-model cache entries carry
a summary version stamp and older-stamped entries are treated as cold
misses, so an upgraded reader never serves a stale-shaped summary.
Concurrent public resumeSession calls now share one in-flight resume and
one facade instead of building parallel facades over the same engine
handle (a close on either would strand the other). forkSession takes the
source and target queues in sorted order, so fork(A->X) is atomic against
create(X) and fork(B->X) without an ABBA deadlock. The emitMetaUpdated
patch type drops the redundant undefined union, and the SDK tests now
cover facade coalescing and the title state across list and resume.
The klient session summary schema no longer strips titleKind, and the
index readSummary honors a legacy isCustomTitle marker over a stale
titleKind, so listSessions reports the same canonical title state as a
resumed session.
Plain generateTitle calls still coalesce onto one shared in-flight
generation, but a forced regeneration always runs on its own so it is
neither swallowed by a plain call's early exit nor shares its result; the
close hook drains every active generation. The allowWhen veto now runs
inside applyUpdate with no await between the check and the mutation, so
an abort cannot slip into the gap.
The closing registry now records the operation kind: an archive arriving
during a plain close waits it out and lands the archived flag on the
persisted document instead of riding the close to success, and a failing
close hook no longer strands a half-closed session — the teardown always
completes while the hook error still reaches the caller. create and fork
reserve their target id synchronously with the existence check, so a
concurrent create/fork of the same id loses up front and can never tear
down the winner's scope or directory.
* refactor(agent-core-v2): move workspace-domain internals into internal/ dirs
- move sessionLifecycle/addressing into internal/
- move workspaceFs errors/fsProcess/fsSearch/rgLocator/runRg into internal/
- move workspaceMcpConfig/config-loader into internal/
- update import paths in services, index.ts, and tests
* docs(agent-core-v2): strip non-header comments, make headers file-local
- remove all symbol JSDoc and inline // and /* */ comments under src/;
file-top header comments and directive comments (eslint, @ts-*) are kept
- rewrite file headers to describe only what the file itself does, dropping
references to other files and see-X / lives-in / consumed-by relationships
- no code changes
* refactor(agent-core-v2): remove the L0-L7 domain layering and its lint guard
- replace check-domain-layers.mjs with check-import-boundaries.mjs,
keeping only the v1-import ban and the kosong subtree rules
- rename the lint:domain package script to lint:imports
- drop the (Ln) layer label from every file-header identity line
- update AGENTS.md, package docs, and the agent-core-dev skill to match
forkSession and explicit-id createSession join the per-session queue, and
the harness resume fast path skips a session whose close is in flight
instead of returning the closing facade (which then failed every call
with session.closed); its late onClose no longer evicts the fresh
session either. The harness rename event now carries isCustomTitle so
the TUI stops asking for a generated title after a local rename.
A close/archive is now tracked in a closing registry from its first
synchronous step until disposal: get/list hide the closing session and
resume waits the close out instead of returning the doomed handle, and
fork waits out an in-flight source close. The title service tracks the
whole generateTitle call as the unit the close hook drains, and the
generated-title write re-checks the lifetime signal inside the serialized
metadata update so an abort landing while the update is queued still
vetoes the write-back.
* web: reorder default permission options in Agent settings
Align the Agent settings default-permission segmented control with the
Composer toolbar order, arranging modes from safest (manual) to most
permissive (auto).
* web: reorder mobile permission cycle from safest to most permissive
The mobile settings sheet still cycled manual → auto → yolo, jumping from
the safest mode straight to the most permissive one on a single tap. Align
the tap-to-cycle order with the Composer menu and Agent settings
(manual → yolo → auto).
* web: align permission risk colors with the Composer's progression
Both the desktop status panel and the mobile settings sheet mapped
yolo → danger and auto → warning, the inverse of the Composer menu
(yolo → warning, auto → danger). Since auto is the most permissive
mode, it should carry the danger color everywhere.
---------
Co-authored-by: qer <wbxl2000@outlook.com>
The Agent/AgentSwarm tool schemas always advertised a \`model\` choice
parameter, so the secondary-model concept entered the prompt even with
the experiment disabled. Gate the advertised JSON schema on the flag in
both engines: off (the default) drops the parameter, on keeps it, and
spawn-time resolution already falls back to the caller's model either
way.
Also scrub ambient KIMI_CODE_EXPERIMENTAL_* env vars in both packages'
vitest setup so flag-dependent tool schemas in llm.tools_snapshot stay
deterministic regardless of the developer shell.
The temporary resume/rename/close paths and the public lifecycle
operations now share a per-session queue, so a public resume can never
receive a handle whose cleanup close is already in flight. Session
summaries carry the canonical title state, letting the TUI skip title
generation for sessions whose title was already generated or customized
instead of re-asking after every turn.
A v1 rename spreads the original state.json document, so an explicit
isCustomTitle: true can travel with a stale titleKind. The explicit
marker now wins on load, and every persist double-writes the derived
isCustomTitle so released v1 builds keep recognizing the custom title.
The session title service must not depend on the Workspace-tier handler
registry. The handler now seeds each session scope with an abort signal,
fires it synchronously when a close begins, and the title service carries
the signal on its request, drops the write-back once aborted, and drains
an in-flight generation through the onWillCloseSession hook.
* feat(kap-server): let fs:search resolve a workspace ref for draft sessions
- fs:search accepts a workspace id or absolute root in the session_id slot
so the @ file mention works before the session exists
- kimi-web searchFiles falls back to the active workspace id in draft state
* fix(agent-core-v2): report empty thinking level for unbound main agent
- sessionLegacyService.status returns thinking_level '' when the main
agent has no bound model (mirroring model: undefined), so clients
fall back to the catalog default instead of folding in the wire
model's 'off' zero value
- add regression test for a never-bound main agent status
- add web changesets: draft @ file mention, new-session thinking level
* perf(minidb): make text index rebuilds async and non-blocking
- TextIndex.build() yields to the event loop during tokenization and
batches postings writes (~1 MiB), so large rebuilds no longer
hard-block the host process
- writes landing mid-build are queued and replayed onto the new base at
swap time, keeping the rebuilt index exact
- PostingsFile.rebuildSync renamed to async rebuild with a synchronous
commit section (beforeRename hook + atomic rename)
- onCompacted hook is now awaited (sync or async); open-time compaction
runs in the background so open() returns without blocking on the
snapshot rewrite and postings rebuild
- compaction skips the postings rebuild when the index's write buffer is
clean (needsRebuild)
- createTextIndex registers before building so concurrent writes feed
the build queue; dropTextIndex throws while a build is in flight
* refactor(agent-core-v2): rename workspaceHandler to sessionLifecycle
- rename IWorkspaceHandlerService to ISessionLifecycleService and move
src/workspace/workspaceHandler/ to src/workspace/sessionLifecycle/;
update all consumers (gateway, sessionExport, sessionLegacy,
sessionLookup, kap-server, klient, node-sdk, kimi-inspect, kimi-code)
- rename IStateService to IAppStateService and add the Workspace-scope
IWorkspaceStateService, so the state domain spans all four scope tiers
- add cascading StateRegistry.inspect(): each tier injects the parent
tier's registry and folds App to current scope into one StateInspection
tree; check-domain-layers gains a Rule 2b exemption for state-on-state
imports
* feat(kap-server): add session-less POST /workspace/fs:search route
Carry the workspace reference (registered id or absolute root) in the
request body and resolve it to the same Workspace-scope fs service the
session route uses, so clients no longer borrow the session route's
{session_id} slot. kimi-web's @ file mention now calls this route with
the workspace ref instead of a session id; the session-route fallback
stays for wire compatibility.
* refactor(agent-core-v2): register workspace-scope service state into IWorkspaceStateService
- move workspaceDirs / workspaceInstructions / workspaceSkillCatalog / workspaceTrust
runtime state from bare instance fields into the workspace state container
- extend gen-state-manifest.mts to scan app/workspace scopes, emitting
AppStateSnapshot / WorkspaceStateSnapshot alongside Session/Agent
- regenerate docs/state-manifest.d.ts and update AGENTS.md + agent-core-dev skill
- update affected tests to register the state services and assert the new state keys
* feat(agent-core-v2): insert Workspace lifecycle scope and remove mutable cwd paths
- Insert LifecycleScope.Workspace between App and Session
- Delete session/workspaceCommand domain (addAdditionalDir) and node-sdk RPC
- Remove profile cwd mutation; cwd is fixed at creation
- Make ISessionWorkspaceContext read-only; seed additionalDirs at creation
- Remove TUI and vscode /add-dir commands (to return workspace-scoped)
* feat(agent-core-v2): add Workspace scope with handler-owned session lifecycle
- Add IWorkspaceLifecycleService (App scope): handler registry,
create-or-get handlerFor with inflight join
- Add workspace/workspaceContext seed and workspace/workspaceHandler
(session create/resume/fork as handler child scopes)
- Delete App-level ISessionLifecycleService; callers compose
index -> handlerFor -> handler via sessionLookup helpers
- Slim IBootstrapService; persistence addressing via handler chain
(disk layout byte-identical)
- kap-server routes rewire internally; /api/v1 wire unchanged,
debug surface gains workspace addressing
- Pin red line in domain lint: session/agent must not import
workspace domains
* feat(agent-core-v2): collect workspace resources into the handler scope
- Add Workspace-scope catalogs for skills and agent profiles,
instructions service, and a shared MCP connection manager
(built at materialization, refreshed by watch/plugin events)
- Session catalogs keep their APIs but read seeded snapshots and
refresh via change events; ISessionMcpService removed
- Session create options carry no mcpServers; MCP sources are
config file (wins on name conflicts) and plugins only
- Agent profile/mcp consume the seeded providers
* feat(agent-core-v2): restore add-dir as a workspace-level capability
- Add workspace/workspaceDirs: shared additional-dir set with
addDir({path, persist}); persist=true writes .kimi-code/local.toml,
local.toml watch drives cross-process refresh
- ISessionWorkspaceContext becomes a live read view fed by the
ISessionWorkspaceInfo seed contract and change events
- Restore Session.addAdditionalDir in kimi-code-sdk 1:1, mapping to
the workspace service; restore TUI/vscode /add-dir verbatim
* feat(agent-core-v2): collect os-level services into the workspace scope
- Move fs service, fs watch (shared subscription fan-out), process
runner, and a git facade to Workspace scope; sessionFs domain removed
- Add IWorkspaceToolPolicy with workspace veto wired through tool
activation, execution guard, composed evaluation, and profile
prompt projection; injected via ISessionToolPolicyGate seed
- kap-server fs routes and fs.watch bridge remap to the workspace
services; wire unchanged
* refactor(agent-core-v2): clean up workspace-domain leftovers and docs
- Drop dead code: v2 mergeCallerMcpServers, the transitional
ISessionContext.additionalDirs field, an unreachable guard
- Fix stale domain references in comments; correct test names
- Give the fs-watch refresh test a realistic wait budget under load
- Document the four-scope model and workspace domain in AGENTS.md,
agent-core-v2 docs, and the agent-core-dev skill
* test(node-sdk): wait for the initial MCP connect to settle in the parity list test
v1 connects in the background after create resolves while v2 awaits it
inside create, so an immediate list can catch either side still pending
under CI load
* refactor(agent-core-v2): extract git work-tree discovery into the git domain
- add the pure findGitWorkTree probe in app/git/workTree and expose it
as IGitService.findWorkTree
- switch the git permission policies off the local
findLocalGitWorkTreeMarker helper to the DI service
- reuse findGitWorkTree for AGENTS.md project-root discovery in
agent/profile/context.ts
- add findWorkTree coverage to gitService.test.ts
* feat(kimi-inspect): add Workspace Services view
- add WorkspaceServicesView rail view with a workspace picker on top;
proxies resolve workspace-scope Services on the /workspace/:id route
- extend ChannelScope, ServiceTarget, and ServicePanelDef scope with
'workspace', routed via client.workspace(id).service
- wire the new view into NavRail and App
* refactor(agent-core-v2): extract mcpCore and workspaceMcpConfig domains
- move the scope-agnostic MCP connection layer (stdio/http/sse clients,
connection manager, oauth, config schema, tool naming) from agent/mcp
to the new mcpCore domain
- move the [mcp] config section to app/mcpConfig and OAuth credential
persistence to app/mcpConfig/oauthStore
- introduce the workspace/workspaceMcpConfig domain owning the effective
MCP server set (mcp.json files + plugin contributions, refreshed by
fs watch); workspaceMcp keeps pure connection orchestration
- update the plugin domain, session MCP handle, klient/node-sdk
contracts, and tests accordingly
* refactor(agent-core-v2): remove the fault-injection experimental feature
- delete the faultInjection domain (flag definition, IFaultInjectionService
contract, FaultInjectionService implementation)
- drop the requester-side take() injection point and the constructor
dependency from llmRequester
- remove the flag-gated test cases and the IFlagService stub they needed
- regenerate the state manifest without the faultInjection state keys
* feat(agent-core-v2): gate project-level MCP config behind workspace trust
Add the Workspace-scope IWorkspaceTrust service: an explicit, per-workspace
trust marker persisted under the home (IAtomicDocumentStore, keyed by
encodeWorkDirKey(root)) so a checked-out tree cannot pre-trust itself.
While a workspace is untrusted, workspaceMcpConfig skips the project-level
.mcp.json and .kimi-code/mcp.json files (user-level config and plugin
contributions still load); a trust flip reuses the reload path, so project
servers connect on trust and disconnect on untrust.
Expose the state over kap-server REST: GET /workspaces/{id}/trust,
POST /workspaces/{id}/trust, POST /workspaces/{id}/untrust.
* feat(kimi-inspect): replace the workspace picker with a directory browser
The Workspace Services view now keeps a server-side directory browser in a
left sidebar (over IHostFolderBrowser) instead of a <select> of registered
workspaces. Entries that are registered workspaces carry a workspace badge
plus their IWorkspaceTrust trust state; selecting an unregistered folder
registers it on demand via IWorkspaceService.createOrTouch.
* fix(agent-core-v2): resolve the effective cwd into the profile binding
A default-bound agent recorded no cwd in its profile.bind payload, and no
caller configures ProfileServiceOptions.cwd, so the profile service's cwd
getter fell through to '' and refreshSystemPrompt() rebuilt the prompt
from the server process's cwd: an AGENTS.md edit dropped the workspace
instructions (or swapped in unrelated ones).
bind() now persists the resolved effective cwd (the input's, or the
session's when the input omits it) into profile.bind — the Model's cwd
stays creation-fixed and is always set. The getter's last resort is the
session's own cwd (the value legacy bindings resolved against) instead of
a bare ''.
* refactor(agent-core-v2): introduce the contribution/registry/catalog extension point for agent profiles
- App-scope IAgentProfileRegistry: any scope can register an
AgentProfileContribution keyed by (sourceId, workspaceKey); dedup per
source id, change events drive catalog re-projection
- workspaceAgentProfileLoader domain owns agent-file discovery end to end
(parse / roots / SYSTEM.md / explicit runtime files) with five
Workspace-scope loaders (workspace / user / plugin / extra / explicit)
tagged with the handler's workspaceId; internals live under internal/
- SessionAgentProfileCatalog projects the registry directly (name dedup,
priority adjudication, builtin override rule, inspect()); the
workspace-catalog + sessionData seed relay is gone
- builtin code contributions register as the 'builtin' entry via
BuiltinAgentProfileLoader; plugin agent roots are provided by the
plugin domain as PluginAgentRoot
- remove cwd from the profile binding chain (BindAgentInput /
ProfileBindingSnapshot / AgentConfigData / ProfileModelState /
profile.bind op) — it is always the session's frozen cwd; legacy
wire.jsonl records replay fine (the schema strips the field)
- share markdown frontmatter parsing via _base/text/frontmatter
* fix(agent-core-v2): reconcile the workspace refactor with main
- restore the branch's klient workspaceId scope extension lost to a
file-level conflict resolution (main had no further changes there)
- stub the plugin system-prompt dependencies main added to the profile
service in the profileOps / skillCatalog tests
- correct PLUGIN_SKILL_SOURCE_ID to the App skillSource domain (Agent
scope must not import the Workspace domain)
- kap-server workspaceLayout test supplies the now-required hostIdentity
- regenerate wire/state/config manifests
* fix(agent-core-v2): export the agent-file parse primitives the v2 print CLI consumes
The internal/ split kept parseAgentFileText / resolveAgentPath off the
package entry, but apps/kimi-code's v2 print runner imports them from
@moonshot-ai/agent-core-v2 for --agent-file. Export the two symbols by
name; everything else under internal/ stays domain-private.
* feat(agent-core-v2): return cwd listing for empty fs:search query
An empty fs:search query used to fail request validation (query had a
minimum length of 1), so @-mention pickers had no starting set right
after typing "@". The workspace fs service now answers an empty query
with the workspace root's top-level entries — directories first,
hidden entries excluded, gitignore and exclude_globs honored — mapped
into the search-hit shape (score 1, empty match positions) and capped
by limit. The mirrored protocol wire schema is relaxed in sync.
* test: cover cron-fired steer context and titled session creation
- agent-core-v2: e2e asserting a cron-fired steer turn carries earlier
tool results (the CronCreate job id) into the provider request
- klient: conformance case creating a titled session through implicit
workspace materialization
- persist titleSource (prompt/generated/custom); skip auto-generation over
an already-generated title unless forced, and never over a custom one
- plumb the force option from the core through klient and node-sdk to the
REST title/generate endpoint
- drop the title write-back when the session scope was superseded
mid-flight, and retry once with a force-refreshed token on a 401
- stop closing sessions a concurrent public resume has handed out in the
temporary resume paths (generateSessionTitle, renameSession)
- accept session.meta.updated patches without lastPrompt in klient event
validation, and emit exactly one metadata event per applied title
- remove the retired prompts field heal and drop the changeset (the
behavior is only perceivable on the experimental v2 engine)
* fix(agent-core-v2): write refresh results in one atomic config transition
- add IConfigService.replaceSections: applies several domains in a single
state transition — one disk write, one effective rebuild, change events
fire only after all domains took effect
- rework ProviderDiscoveryService to absorb the orchestrator's two-phase
removeProvider/setConfig host contract into one replaceSections write, so
the kosong registries never pass through a halfway-removed catalog
- stop writing the env-synthesized __kimi_env__ slice to config; the
bridge's event-driven sync carries it into the registries on its own
- fixes sporadic "model is not configured" errors when starting kimi web,
caused by the background refresh transiently clearing the model catalog
while the first session was being created
* fix(agent-core-v2): stage replaceSections writes before mutating raw config
Validate and strip every domain into a staged copy of the raw/memory layer
first, then swap it in only after the whole batch succeeds — previously a
later domain failing validation left earlier domains already applied to
this.raw/this.memory while the call reported failure, exposing a partially
applied user layer to inspect() and future merges.