* feat(kap-server): add remote control device deletion
* fix(kap-server): coordinate with the local tunnel before deleting this machine's device
Co-authored-by: liruifengv <liruifeng1024@gmail.com>
* feat(kap-server): add remote control device management
* feat(remote-control): tag share URLs with the caller's platform source
The share link's from query parameter was hardcoded to kimi_code_cli, so
links created by the desktop app were mislabeled as CLI traffic.
buildRemoteControlUrl now takes the source explicitly and
RemoteControlOptions carries it as urlSource; kap-server threads
hostIdentity.platform through, so desktop hosts produce
from=kimi_code_desktop while CLI hosts keep from=kimi_code_cli.
* fix(kap-server): stop the local tunnel when the current device is deactivated or deleted
The device management routes only called the cloud API. When the target
device is the machine itself, the local tunnel kept running: after the
relay drops it, the client reconnects and re-registers, so the device
came back online (or was recreated after a delete) and the local status
never returned to off.
After a successful cloud deactivate/delete of the current device, the
routes now also disable the local tunnel manager.
* feat(kap-server)!: drop the remote-control device delete route
Device removal is collapsed to a single deactivate verb: the desktop UI
deactivates devices instead of deleting them, so the DELETE
/remote-control/devices/{id} route and the device client's deleteDevice
go away before this API ever ships.
* feat(kap-server): carry the lock holder in the already-running error
The enable route now returns the RemoteControlAlreadyRunningError holder
(pid, local origin, device id, url, started_at) in the error envelope's
details, documented with a details schema, so desktop can render a
structured conflict state instead of the raw message.
* feat(kap-server): expose the lock conflict in the remote control status
The manager now surfaces the holder when its last enable error is an
already-running lock conflict, and GET /remote-control returns it as a
structured conflict field, so clients can present the conflict state
proactively instead of parsing the error message.
* feat(kap-server): resolve the remote control lock conflict live in status
GET /remote-control now re-inspects the machine lock whenever the
manager is off: a live holder is reported as the conflict even without
a prior enable attempt in this process, and a stored conflict plus its
error text are dropped once the holder's process is gone. Panel state
refreshes such as after device deactivation now reflect reality.
* feat(kap-server): wait for the lock holder to release on current-device deactivation
When the deactivated device is the machine's own and the lock is held
by another live process (e.g. a CLI instance whose tunnel the relay is
about to terminate with user_requested), the route now polls the lock
for up to two seconds before responding, so a client's immediately
following status read sees the settled conflict-free state.
* style(kap-server): silence promise-executor-return in lock release wait
* test(remote-control): pass urlSource in the close-reason cases
* feat(kap-server)!: register remote control devices with the host product name
* refactor(cli): source the remote control identity from app constants
* fix(remote-control): make starts cancellable and harden logout cleanup
* fix(remote-control): close the remaining cancellation and invalidation races
* fix(kap-server): sweep remote control cleanup once more after logout
* docs: note the lock-release failure of remote control deactivation
* fix(remote-control): key cloud sessions by credential and settle cancelled starts
* fix(kap-server): block remote control starts during logout and serialize tunnel toggles
* fix(kap-server): gate local starts during current-device deactivation
* fix(kap-server): match active tunnel ids on deactivation and re-clear sessions after logout
* fix(kap-server): serialize Kimi logouts, harden lock cleanup, and whitelist device fields
* fix(remote-control): abort pending handshakes on close and answer logout before tunnel teardown
* fix(remote-control): cancel enables that are still queued behind a pending disable
* fix(kap-server): recognize foreign logout gates and retry post-logout tunnel teardown
* fix(remote-control): verify the machine lock after disable and recheck deactivation
* feat(kap-server): export loadOrCreateServerToken for host token provisioning
* feat(agent-core-v2): report fork request prefix parity in the prompt cache probe
The fork prompt cache probe only reported the child's cache usage, so a low
hit rate could not be told apart between a client-side prefix divergence and
a server-side miss, and the hit rate itself was diluted by the new tail that
can never be cached.
The requester now keeps a snapshot of each agent's last completed turn
request (the tools and system prompt hashes it already records in
llm.request, input tokens and timing). A forked agent captures its parent's
snapshot when it is created and reports tools_match, system_prompt_match,
parent_input_tokens and parent_request_gap_ms with its first request.
* fix(agent-core-v2): clear the parent request snapshot when the context is rewritten
Undo and compaction rewrite the parent context without touching the
non-persisted snapshot, so a /btw fork made before the next turn request
compared against a request whose input the child no longer inherits.
* fix(agent-core-v2): drop stale parent baselines from the fork cache probe
The probe compared the child's first request against the parent snapshot
captured at scope creation, but a parent undo or compaction landing
before the context copy left that snapshot describing a request the
child no longer inherits, and a model switch between the parent's last
turn and the fork compared across cache namespaces that can never share
a prompt cache.
The probe now watches the parent's ContextSpliced/ContextUndone events
and drops the captured snapshot once the parent context is rewritten,
and the snapshot carries the model alias so the comparison fields and
the parent input token baseline are only reported when both sides ran
the same model.
* fix(agent-core-v2): keep the turn request snapshot across conversation undo
Undo only truncates the tail of the parent context, so the request a
/btw fork inherits is still a strict prefix of the request the parent
last cached: the server cache keeps hitting and the snapshot's hashes
stay accurate. Clearing the snapshot on undo threw away a baseline
that was still valid, and made the requester depend on the undo
domain for no benefit. Only compaction rewrites the prefix, so it
remains the sole event that clears the snapshot.
* refactor(agent-core-v2): validate the fork cache probe baseline by context prefix revision
The requester subscribed to ContextSpliced solely to keep a telemetry
snapshot fresh, which made the module understand context rewrites and
grow an event bus dependency for the probe's sake. The probe's own
subscription could not cover forks created after a compaction either,
which is the only reason the requester had to listen at all.
Context memory now exposes a prefix revision that increments on every
deleting splice, the turn request snapshot records the revision it was
taken at, and the probe compares it with the parent's current revision
at probe time. Read-time validation covers both the compact-then-fork
and the fork-then-compact windows with no subscriptions, and the
requester is back to only recording facts about its own requests.
* fix(agent-core-v2): stamp the turn request snapshot with the build-time context revision
The public SDK clearContext path has no busy check and can empty the
parent context while a turn request is in flight. Reading the revision
at completion stamped the snapshot with the post-clear value, so a
later fork saw matching revisions and hashes and silently attributed
the client-side prefix divergence to the server. The request input is
fixed by recordRequest time, so capture the revision in the same
synchronous block; a mid-flight clear then leaves the snapshot on the
pre-clear revision and the probe drops the baseline on comparison.
* fix(agent-core-v2): capture the snapshot context revision where the request messages are copied
The build-time capture still ran after the awaited media resolution,
so a clearContext or compaction landing in that window stamped the
snapshot with the post-rewrite revision for a request whose messages
were copied earlier. resolveRequest is synchronous and copies the
context messages there, so the revision captured alongside the copy
always describes the same context the request was built from.
* fix(agent-core-v2): omit the parent token baseline when the parent request reported no usage
A provider that completes without a usage event left the snapshot with
inputTokens: 0, so a later same-model fork emitted parent_input_tokens: 0
and the input_cache_read / parent_input_tokens analysis divided by zero
or treated an unknown baseline as real. The field is now optional and
absent for that snapshot, which the optional telemetry property already
allows.
* feat: show NotifyUser progress in desktop and web
Give NotifyUser a one-line title, report the latest update on the
session status, and forward subagent updates to the parent so GUI
clients can show them on subagent cards.
* feat: turn on NotifyUser progress updates by default
Flip the notify_user flag default to true; the flag stays as the opt-out
(`[experimental] notify_user = false` or KIMI_CODE_EXPERIMENTAL_NOTIFY_USER=0).
Register the new subagent.update wire record in the vis renderers and
record-type union so the manifest coverage test passes.
* refactor: trim NotifyUser surfaces to conversation progress rows
* feat: make NotifyUser title optional and enforce single-line titles
* feat: make NotifyUser opt-in via the settings lab
* docs: describe NotifyUser as off by default with the settings lab opt-in
* fix(remote-control): exit the web server when the relay takes the device offline
* test(cli): satisfy the remote-control handle contract in tui web tests
* feat(tower): coordinate missions with deterministic orchestration
* fix(tower): disable goal mode
* feat(tower): degrade gracefully on tower state loss
When .tower/comms is deleted while .tower/ survives (e.g. git clean),
tower tools no longer hard-fail with not-initialized:
- TowerStatus returns a state-lost report; never-initialized repos
(no .tower/ at all) keep the existing not-initialized behavior
- TowerSend/TowerComplete recover a minimal state (directory skeleton,
empty missions/roster, recoveredAt marker, base taken from the
current checkout branch) and keep delivering; a caller whose roster
entry was lost is re-registered as a placeholder named after its
agent id
- TowerComplete degrades explicitly after a loss: the report is
delivered to the tower as a completion-report-state-lost message and
no mission is marked completed
- TowerMerge/TowerRebase and every other locked mutation fail with an
explicit state-lost error instead of silently running against an
empty history
- the recoveredAt marker is shown on the TowerStatus dashboard and in
the status summary, reminding the tower to report the history loss
to the user
* feat(tower): veto destructive bash commands in the tower main checkout
* fix(tower): allow git clean dot pathspecs inside tower worktrees
* fix(tower): restore attachment guidance for mission context
* fix(tower): engage bash guard only while the workspace has an owner
* fix(tower): veto git clean only with force and -x/-X; drop markInboxRead
* chore(tower): drop per-fix changesets to keep a single concise one
* fix(tower): check tower owner before preparing the user base
* feat(tower): show a notice when goal activation ends tower mode
* fix(tower): unify the mode-mutex exit reason across goal, plan, and swarm
* refactor(tower): drop token stamping from protocol artifacts
* fix(agent-core-v2): deny tower workers subagent delegation
Remove the Agent tool and the subagents allowlist from the tower-worker
profile so workers and reviewers cannot nest subagents inside a mission;
nested subagents bypassed the tower concurrency budget and the tower's
steering. Drop the now-unreachable reviewer-only Agent-resume veto and
its tests; the branch-lease and foreground-resume vetoes stay.
* test(tower): stub ILogService in every AgentTowerService test scope
The fork-restore tests build second DI scopes that register
AgentTowerService without stubbing ILogService, leaving this.log
undefined. When reconcileForeignTower fires a fire-and-forget exit and
the ownership release rejects, the rejection handler's this.log.warn
throws a TypeError that surfaces as an unhandled rejection in the full
suite. Add ix2.stub(ILogService, stubLog()) to all nine scopes that
lacked it, matching the existing sibling pattern.
---------
Co-authored-by: konghuanjun <konghuanjun@moonshot.ai>
* fix(agent-core-v2): stop discouraging mid-turn progress notes and calm NotifyUser nudges
- system prompt: drop the inaccurate "text between tool calls may not be
shown" premise; ask for one- or two-sentence progress notes instead
- remove the mid-turn text nudge that asked the model to repost visible
text as a NotifyUser update
- count the silence nudge in tool-call rounds (one per step) instead of
individual tool calls, so parallel calls no longer trip it early
* feat(agent-core-v2): track NotifyUser nudges and updates
- notify_user_nudge_shown: rounds since the last update and the nudge's
position within the current silent stretch
- notify_user_sent: rounds before the update, whether a nudge preceded
it, message length (no content), and whether it was displayed
* chore: add changeset for mid-turn progress notes and NotifyUser nudges
* feat(kap-server): add allow_ignored_globs to fs:list for un-ignoring named paths
The list filter keeps gitignored entries hidden unless they match the
new allow_ignored_globs request field, letting callers surface
specific ignored paths (e.g. .tmp) while the rest of gitignore still
applies.
* docs: document allow_ignored_globs in the fs:list API reference
* fix: traverse ignored ancestor directories of allow_ignored_globs matches
A nested allow glob such as ignored-dir/keep.txt or ignored-dir/** used
to be unreachable in recursive listings because the ignored parent was
skipped before any child could match. Keep an ignored entry when it is a
literal-prefix ancestor of an allowed glob (directories only), and
document that dot-path allowances additionally require show_hidden.
* fix: match ignored ancestor directories across wildcard glob segments
The literal-prefix check still dropped ancestors when a directory
segment of an allow glob contained a wildcard, e.g. ignored-*/keep.txt
or ignored-dir/**/keep.txt. Decide reachability by consuming the
candidate path segment-wise against a prefix of the glob instead.
* fix: correct and harden workspace fs glob matching
Compile **/ to (?:[^/]+/)* so recursive wildcards preserve path
segment boundaries; a/**/b no longer matches a/xxb. This affects
include_globs, exclude_globs, and allow_ignored_globs across
fs:list / fs:search / fs:suggest / fs:grep.
Match glob prefixes iteratively in globCanMatchBelow so deeply
segmented globs cannot exhaust the call stack.
* chore: add changesets for allow_ignored_globs and the glob boundary fix
* fix: satisfy noUncheckedIndexedAccess in the glob prefix grid
* fix: restrict globstar segment expansion to whole path segments
foo**/keep.txt regressed when **/ gained segment-boundary semantics:
the stars sat mid-segment but were expanded as a whole-segment
globstar. Only expand **/ when the stars open a path segment, treat
mid-segment stars as an ordinary within-segment wildcard, and keep a
trailing ** matching across segments as before.
* fix: match workspace fs globs with picomatch and probe speculative ancestors
Replace the hand-rolled glob compiler with picomatch, the standard
engine already used elsewhere in the package, which settles segment
boundary, mid-segment globstar, and deep-pattern complexity edge
cases for good. An ignored directory kept only as a possible ancestor
of an allow glob is now probed (depth and entry capped, fail-open) and
withheld when no descendant actually matches.
* fix: cast readonly glob list for picomatch isMatch
* fix: parse globs whole in the ancestor check and share the probe budget
Splitting allow globs on '/' corrupts brace and extglob constructs
that contain slashes; take path segments from picomatch.scan instead
and fall back to a conservative answer for opaque single-token globs,
letting the descendant probe decide visibility with whole-pattern
matching.
Probe budgets are now shared across one fs:list request instead of
resetting per candidate directory, so a tree full of speculative
ancestors cannot multiply filesystem operations.
* fix: tolerate empty globs and slash-bearing alternatives
picomatch throws on empty patterns where the old compiler simply
never matched, turning previously valid requests into server errors;
filter them out up front. Brace and extglob alternatives that embed
a slash inside one scanned part now fall back to the conservative
ancestor answer as well, leaving visibility to the whole-pattern
descendant probe.
* fix: disable picomatch negation in workspace fs globs
A leading exclamation mark was a literal character in the old
matcher, so exclude_globs like !foo only matched a path literally
named !foo; as a picomatch negation the same request would exclude
everything except foo. Pin the prior semantics with nonegate.
* fix: scan allowance globs with nonegate and skip empty segments
The scan call still used default negation, stripping a literal
leading bang from allowance prefixes like !foo/keep.txt. Consecutive
separators produced empty scanned segments that made picomatch throw
during prefix compilation; empty segments now simply match nothing.
---------
Co-authored-by: qer <wbxl2000@outlook.com>
Fork copies the wire journal, so cron tasks persisted as cron.add
records were inherited by the fork and fired from both sessions.
Fold the forked marker record into the cron actor: the task table is
cleared at the fork point and a one-time cron_fork_cleared reminder is
delivered (tracked by a durable forkNotice flag confirmed via
ContextAppendMessage), mirroring the goal feature's fork handling.
The forked event class moves from features/goal to
session/agentLifecycle so both features share it.
* fix(agent-core-v2): fold UserPromptSubmit hook output into prompt content parts
UserPromptSubmit hook messages now merge into the user prompt message as
meta-marked text content parts (contentType text/xml, source 'user prompt
submit hook') at content position 0 instead of a standalone hook_result
user message, so one prompt always yields exactly one user message and
turn pairing can no longer shift. Structured hook JSON without a message
field (e.g. {"continue":true}) no longer injects anything; plain-text
stdout still falls through. turn.prompt records, TurnStarted prompts,
fold turn openings, and steer content keys all strip hook parts; existing
wires with standalone hook_result messages keep their current behavior.
* feat(agent-core-v2): keep UserPromptSubmit hook parts in turn records and handle them across client surfaces
* feat(agent-core-v2): meta-mark bundled skill parts and replace positional slicing
Bundled skill blocks are now constructed with meta { source: 'skill
activation' }, matching the hook-part convention. Every former
content.slice(skillActivations.length) site — turn prompt text, steer
merge/echo, session and fork titles, transcript fold, TUI replay — now
annotates then filters by meta, so prompt content no longer depends on
block positions and the loop needs no hook-part knowledge. A shared
annotate step keeps legacy wires working: leading unmarked blocks (one
per bundled activation) are marked on read before filtering.
* feat(agent-core-v2): strip hook parts from the public TurnStarted prompt at construction
* feat(kimi-code): show what trusting activates in the workspace trust prompt
* fix(kimi-code): keep trust prompt non-blocking and disclose only external additional dirs
* fix(kimi-code): mark trust disclosure incomplete when discovery times out or fails
* fix(kimi-code): exclude disabled MCP servers from trust disclosure and cap key lists
* fix(kimi-code): disclose disabled user MCP servers shadowed by project config
* test(kimi-code): merge redundant trust prompt disclosure cases
* test(node-sdk): merge mirrored user/project MCP override cases
* Update trust-panel-disclosure.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix(kimi-code): disclose symlinked additional dirs by real target in the trust prompt
* fix(kimi-code): bound trust disclosure I/O and harden path containment
* fix(kimi-code): tighten trust prompt disclosure copy
* refactor(kimi-code): compute the trust disclosure inside the engine
The disclosure composition (project-origin MCP servers, additional dirs
with realpath containment, instruction sources) moves from the SDK into
agent-core-v2's workspace scope as WorkspaceTrustDisclosureService,
constructed alongside the other generation services. The SDK's
getWorkspaceTrustInfo becomes a thin forward, so the config-merge
semantics live next to the workspaceTrust gate that owns them instead
of being re-derived downstream.
Also drops the shadowed-user-server section and the per-section
deadlines with their disclosureComplete flag: the engine reads the
same loaded state session creation awaits, so the prompt needs no
timeout plumbing of its own, and the empty state stays a single honest
copy.
* refactor(kimi-code): compress trust disclosure tests and disclose only effective profiles
Merge mirrored test cases across the three suites and share fixtures;
small source trims (shared wrap helper, context.workspaceId).
The disclosed agent profiles now pass the same resolution the session
catalog applies: a workspace profile clashing with a builtin without
override: true, or losing to a higher-priority candidate, is no longer
reported as activated.
* test(kimi-code): drop the engine disclosure suite in favor of e2e coverage
The SDK e2e suite exercises the disclosure through the real engine, so
the stub-based engine unit file duplicated it; a builtin-clash agent
case moves there to keep the suppressed-profile behavior pinned.
Also folds the sanitize vectors into the MCP render case and trims the
trust type docs.
* fix(kimi-code): cap untrusted MCP target fields and correct profile wording
A crafted .mcp.json can supply arbitrarily long command/args/url
strings; each field now truncates at 80 chars before wrapping. The
profiles line no longer claims they feed the agent — a non-default
workspace profile is only made available as a subagent, the default
agent still binds the default profile.
* fix(kimi-code): honor profile overrides and reveal instruction symlinks in trust disclosure
A workspace profile with override: true replaces a same-name builtin
or higher-priority candidate in the session catalog, so the disclosure
now applies the same replace semantics instead of dropping it.
Instruction paths get the same realpath treatment as additional dirs:
a project AGENTS.md symlinked to a file outside the project renders
its real target instead of hiding behind the lexical path.
* fix(kimi-code): disclose skill roots escaping the project in the trust prompt
Read/Write/Edit/Grep/Glob all add getSkillRoots() to their allowed
roots, so a .kimi-code/skills symlink to an external directory is an
outside-project file access grant that trusting activates. The
disclosure now merges those roots (resolved via the same projectRoots()
the skill source uses) into the outside-directories list. Also caps
each displayed MCP key name, not just the key count.
* fix(kimi-code): cap the bearer-token env var label in the trust prompt
* refactor(kimi-code): disclose only real locations in the trust prompt
The path → realPath arrow is dropped; gated directories and AGENTS.md
entries are disclosed as their resolved real locations, and the pair
type collapses back to plain strings. Entries resolving to the same
real directory collapse into one.
* fix(kimi-code): tighten the trust prompt list caps to fit one screen
* fix(kimi-code): lower the trust prompt list caps further
* fix(agent-core-v2): keep explicit agent-file precedence in the trust disclosure
* Revert "fix(agent-core-v2): keep explicit agent-file precedence in the trust disclosure"
This reverts commit 6e5c45d1b69061a041cc991a0882b1c651fc6003.
* fix(agent-core-v2): preserve profile priority in trust disclosure
* fix(kimi-code): keep workspace trust choices visible
* fix(kimi-code): align trust prompt paging keys
* docs: remove trust prompt keyboard additions
* feat(kimi-code): summarize workspace trust with configuration sources
* chore(agent-core-v2): sync workspace instruction state manifest
* fix(kimi-code): recognize dot-prefixed project directories in trust summary
* refactor(kimi-code): reuse existing trust configuration sources
* fix(kimi-code): keep trust disclosure independent of skill watchers
* refactor(kimi-code): condense additional directory disclosure
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* feat: trust workspace via KIMI_CODE_TRUST_WORKSPACE env var
* fix: honor trust env override in MCP registry and untrust route
* test: add getEnv to mcpManagement bootstrap mock
* test: fold trust-env route case into existing workspaces suite
* fix(cli): mention KIMI_CODE_TRUST_WORKSPACE in the print-mode MCP trust warning
* docs: describe KIMI_CODE_TRUST_WORKSPACE by its semantics, not its MCP effect
The nudge reminders were gated on the notify_user flag and on the tool
being registered, but not on the host. A session created in the TUI keeps
the tool after it is reopened elsewhere, so a host that cannot display
updates kept telling the agent to send them while every call reported
that nothing was displayed.
Gate the reminders on the same availability check the tool uses when it
runs: the flag is on and the host declared the update_panel capability.
- tower mode: a message sent while the agent is running aborts the in-progress inbox-wake turn and runs as its own turn; notification-seeded turn waiters now settle launched/completion
- TowerTeardown: keeps worktrees of live agents (not overridable with force), supports exclude and dry_run
- tower roster: died/revived store writes are guarded to the active tower session and attributed with session+pid; agents stopped by the user are marked dead by intent with no revival nag, and unintended deaths get diagnose-first guidance
- workers must TowerInbox before marking a mission completed: the store refuses completion with unread inbox messages, and the briefing carries the inbox-before-completion, mission re-read, and long-operation chunking instructions
- tower store: state.json read-modify-write is serialized with a cross-process lockfile (token-checked release) and written atomically via per-writer tmp + rename
Co-authored-by: konghuanjun <konghuanjun@moonshot.ai>
* revert: roll back workspace trust-boundary hardening
Roll back the hardening added in #3964 that guarded against malicious
content inside an already-trusted repository:
- background git invocations no longer override repo-local git config
(fsmonitor, hooksPath, filters, drivers, gpg, editor)
- agent file tools no longer re-resolve paths through symlinks
- project-local local.toml applies without workspace-trust gating,
additional_dir entries are no longer rejected for resolving to the
home directory or filesystem root, and writing it is auto-approved
again inside a git worktree
Kept, since they only affect the pre-trust window or the trust prompt
itself: the fail-closed trust prompt and lazy footer git detection.
* Update revert-trust-boundary-hardening.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix(remote-control): pick credential slot and relay from login region
Global login stores tokens in kimi-code-env-*.json and should use
code-rc.kimi.ai; Remote Control always read kimi-code.json and
code-rc.kimi.com. Resolve both from the persisted oauth ref.
* fix(telemetry): skip the dead global collector and keep shutdown alive
The global collector host has no DNS. Drop it from the region profile and
skip the send instead of falling back to the mainland endpoint. Keep the
shutdown timeout timer referenced so a failed flush cannot exit before the
TUI hands the process to the foreground server.
* fix(remote-control): require explicit relay origin and drop hardcoded .com defaults
* feat(agent-core-v2): add repeat_breaker config switch
Add a top-level repeat_breaker boolean (default true) to config.toml,
overridable with the KIMI_CODE_REPEAT_BREAKER env var. When disabled,
the agent skips repeat reminders and forced stops on consecutively
repeated identical tool calls; same-step dedupe is unaffected.
* Update repeat-breaker-config-switch.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* feat(agent-core-v2): add tool_dedupe config switch
* refactor(agent-core-v2): drop the tool_dedupe config switch
Same-step dedupe stays always on. repeat_breaker remains the only public switch.
* refactor(agent-core-v2): read the repeat breaker from the environment only
KIMI_CODE_REPEAT_BREAKER is the only switch. Unset keeps reminders and forced stops on.
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix: restore swarm members from persisted lifecycle events
* test(agent-core-v2): register subagent lifecycle records in the wire vocabulary
* chore(agent-core-v2): regenerate the wire manifest for subagent lifecycle records
The manifest inventory drives the vis wire-renderer coverage check, so vis gains a renderer for each new record type and treats them as timeline-neutral in the context projector.
* fix(transcript): associate a folded subagent with the task registered after its spawn
Some emitters register the task after publishing the spawn, so the durable
spawn record carries no task id and the cold fold keyed the member by its
agent id. A later task.started then created a second task that no subagent
terminal event ever reached, leaving a duplicate stuck in the running state.
Folding task.started now records the agent-to-task association the live
projector keeps, and terminal subagent records update both representations
when both are retained.
* fix(transcript): restore subagent token usage when folding a completed member
The durable subagent.completed record carries the member's token usage and the
live projector copies it onto the task, but the cold fold dropped it, so a
reopened conversation showed a completed member without usage metadata. The
fold now validates the payload's four counters and restores them.
* fix(kap-server): base the lost-member decision on the turn that spawned it
The cold snapshot only terminalised an unfinished foreground member when the
parent agent was idle, so a member left behind by a restart stayed marked as
running forever once the user started a new parent turn before backfill.
The restored agent refs already name the tool call that spawned each member,
so the decision now uses the turn owning that call: a member is lost when its
own loop is not running and its spawning turn is not the turn the parent is
running now.
* fix(transcript): adopt the spawn placeholder into the task registered afterwards
A spawn published before its task is registered — the Tower worker path —
carries no task id, so the fold created a placeholder keyed by the agent id
and the later task.started added a second task under the registered id. Only
the registered task was ever terminalised, and the detached placeholder was
skipped by the lost-member pass, so a restored transcript kept a duplicate
worker shown as running forever. task.started now folds the placeholder into
the registered task instead of leaving it behind.
* fix(kap-server): drain the live wire before reading a cold snapshot
The append log buffers records and writes them in batches, which is why its
own reader flushes the log first. The cold transcript reads the wire file
directly and skipped that drain, so a snapshot could stop on a stale prefix.
When the transcript binding is created after a turn has already ended, the
whole store is built from that snapshot and nothing repairs it afterwards,
leaving the turn's last tool call without its result and its member marked
lost. Reading now drains the live agent's wire first, as session export
already does before it reads the same files.
* feat(tower): enforce protocol invariants and deny AgentSwarm in tower mode
- split missions by functional boundary and workload; simplify spawn briefings
- flip completed missions back to active on non-clean reviews and brief respawns with review history
- refuse completed with open tasks or zero-diff build branches; cap review rounds at 5 with a task_drop escape hatch
- name the next step in review/merge/status tool results; flag unspawned missions in TowerStatus
- veto AgentSwarm execution while tower mode is active
- deflake kap-server catalog test: waitForServerState timeout 3s to 10s
* fix(spawnTool): remove striction
---------
Co-authored-by: konghuanjun <konghuanjun@moonshot.ai>
* feat(cli): support audience targeting for startup banners
* feat(cli): rename the banner audience field to kfc_audience
* chore: revert unintended oxlint autofixes introduced by the merge commit
The lint-staged oxlint --fix pass applied warning-level unicorn autofixes to
main's files during the merge (prefer-at, prefer-string-replace-all,
toSorted, catch-error-name). The catch-error-name rename also renamed object
shorthand properties (reason -> error), which no longer matches the declared
types and fails tsc. Restore main's versions of these four files; committing
with --no-verify so the same autofix does not re-apply.
* refactor(cli): type the banner wire shape concretely
* refactor(cli): narrow the banner audience fields to literal unions
* fix(cli): classify 403 as anonymous and map REGION_OVERSEA in banner audience
* refactor(cli): require banner_id for banner entries
* fix(cli): drop the banner subtext indent when it cannot fit
* fix(cli): avoid cache filename collisions across config endpoints
* fix(cli): keep banner loading from rejecting when the token lookup fails
* fix(kap-server): reject malformed and null Origins
isOriginAllowed conflated an unparseable Origin header with an absent
one and allowed both, so a sandboxed document (Origin: null) passed the
WebSocket upgrade check and had its Origin echoed by the CORS hook.
An absent Origin is still allowed for non-browser clients, but a
present Origin that fails to parse, is null, or uses a non-http(s)
scheme is now rejected: the WS upgrade responds 403 and the CORS hook
withholds Access-Control-Allow-Origin.
* fix(kimi-code): sync web bundle for kimi_origin query gating
* fix(agent-core-v2): gate workspace local.toml behind trust and tighten additional_dir
* fix(agent-core-v2): block symlink escapes in agent file tools
* fix: harden background git invocations against repo-local config
* fix(agent-core-v2): close trust-gate gaps in add-dir and additional_dir validation
* fix: neutralize repo-configured clean and process filters in hardened git calls
* fix(agent-core-v2): fail closed when a path is too deep to verify
* fix: probe worktree-scoped filter config in hardened git calls
* fix: fail closed when git filter discovery fails and cache probes for repo subdirectories
* fix(agent-core-v2): block symlink aliases of the project-local config in write tools
* fix: neutralize smudge, merge drivers, and repo-controlled commit signing in hardened git calls
* fix: expand included git configs when discovering repo-defined drivers
* Revert "fix(kimi-code): sync web bundle for kimi_origin query gating"
This reverts commit cd6af49cf1dfebe505f0e890453c3207a74d3e80.
* fix: keep git hardening fail-closed on includes and probe failures in scanners
* fix: fail closed on uncodable driver names and disable repo-controlled signature verification
* fix: neutralize repo-controlled editors and match include sections case-insensitively
* fix: probe config names only and reject dangling symlinks in file tools
* fix: fail closed when core.worktree escapes the repository
* fix(agent-core-v2): match project config paths across separators and case
* fix: arm footer git only after workspace trust persists
* fix(agent-core-v2): check resolved sensitive targets for absolute outside paths
* fix: only skip git config caching for actual include sections
* refactor: share git config hardening primitives between agent-core-v2 and the CLI
* fix(agent-core-v2): clear trusted additional dirs synchronously on trust revocation
* fix(agent-core-v2): compare resolved write targets with Windows path semantics
* fix: fail closed when the git directory disappears during hardening probes
* refactor: move shared git hardening primitives into @moonshot-ai/git-hardening
* fix: close symlinked-gitdir and submodule-recurse gaps in git hardening
* fix(agent-core-v2): reject home-directory ancestors as additional_dir roots
* fix: compare core.worktree with Windows path semantics
* fix: skip git config probes on renders after a negative repo detection
* fix: resolve gitfile pointers against the .git file directory and match includeIf sections
* test: drop duplicated symlink and plain-file cases covered elsewhere
* fix: only treat project-config writes as aliased when the lexical path misses the config pattern
* test: move the realpath guard matrix into a module test
* test: cover git-hardening primitives in the shared package
* refactor: inline git hardening helpers and drop the shared package
Keep the constants and parsers next to the async engine spawn path and
the sync CLI spawn path instead of a third workspace package.
* refactor: drop footer git trust gate and config probing
Workspace trust is a process-level decision, so the TUI never mounts
the footer until the user has trusted. Footer git status now uses
static hardening flags only.
* refactor: route git execution through IGitService.runGit
- Add runGit(cwd, args, options) to IGitService as the public door for
running git with repo-local config hardening applied.
- GitService implements runGit using the existing hardenedGitConfigArgs
helper; status/diff now delegate to it.
- collectGitContext drops its own spawn/probe logic and calls
IGitService.runGit instead, receiving the service through the
promptPrefix context.
- Tower keeps its own git() function (accepted gap).
* refactor: move git hardening helpers to app/git/hardening
* Revert "fix(kap-server): reject malformed and null Origins"
This reverts commit b799a21d0390ff0e4e66437f0d7b90c0b8171efe.
* perf: cut CLI startup time and memory in the native binary and config reads
Ship the single-file binary with a V8 code cache and a 16 MB semi-space
(execArgv), lower dynamic import() to require() in the CommonJS bundle and
fail the native build if any survives, and stop the engine from redoing
work on every config read: env-bound sections are re-validated only when
their env values change, the tool policy service caches the global tools
section and refreshes it on section-change events, Ajv instances are built
lazily, the macOS product version is read from SystemVersion.plist instead
of spawning sw_vers, and the host time zone and date formatter are cached.
Measured on the 100-round mock benchmark: CU 4.1-4.4 -> 3.0-3.2,
CPU 2.6-2.8 -> 2.0-2.2 core-seconds, peak RSS 550-610 MB -> 370-465 MB,
`kimi --version` 0.48 s / 401 MB -> 0.33 s / 311 MB.
* fix(native): keep dynamic import() in the code-cached binary and cover plugin entries in smoke
Lowering import() to require() broke `__plugin_run_node` (the bundler dropped
the node:url binding, and require() cannot load file:// URLs or top-level-await
modules), so every plugin MCP server that runs on Node failed under the native
binary. The CommonJS SEA main script keeps a working import() with the V8 code
cache on Node 24, so the lowering and the lexer guard go away and the native
smoke now runs a plugin entry. Also assert that tool policy checks do not read
the tools section, and drop the host time zone cache.
* fix(agent-core-v2): key the env-bound config memo by section identity
A domain re-registered by a different section definition could hit the memo
entry left by the previous definition when the validated base and env values
were unchanged, returning a value parsed by the old schema.
* feat(agent-core-v2): report active plugins and plugin toggles in telemetry
* fix(agent-core-v2): refresh active plugin context before recording plugin_toggle
* refactor(agent-core-v2): publish plugin telemetry from committed state
* refactor(agent-core-v2): split plugin value import from type imports
* refactor(agent-core-v2): report enabled plugins on turn and toggle events
* feat(transcript): include step timing and usage in cold-folded steps
* refactor(transcript): carry only TTFT and stream duration in cold-folded steps
* refactor(transcript): rename step timing field to llmTiming
* fix(agent-core-v2): floor the human turn clock at the wire-wide max on engine journal reset
* fix(kap-server): fold the cold transcript snapshot over the restorable branch chain
* fix(agent-core-v2): advance the human turn clock when a turn starts
* fix(kap-server): split reused wire turn ids in the live transcript projector
* fix(kap-server): adopt the completed cold tip for mid-turn attach events
Continuation deltas after a lazy transcript attach belong on the last
cold turn, not a newly split export id.