* fix(agent-core-v2): spill oversized tool outputs and surface dropped content
* fix(agent-core-v2): preserve spill fields through tool result normalization
normalizeToolResult rebuilds every tool result with a field whitelist,
which stripped untruncatedOutput / untruncatedOutputTotalChars /
spillExempt before ToolResultTruncationService could see them: the
spill-on-truncation path never fired for Bash/Grep/FetchURL/WebSearch,
and reads of spill files were not exempted from re-spilling.
Pass the three engine-internal fields through, and add executor-level
integration tests that run a retainFullOutput tool and a spill-exempt
result through the real ToolResultTruncationService.
* refactor(agent-core-v2): drop banned JSDoc and fix harness error typing
main banned JSDoc in comment-free packages (#3226); remove the doc
blocks on the new contract fields and on isSpillFilePath. Type the
harness scripted stream error as Error to satisfy only-throw-error
under oxlint --type-aware.
* fix(agent-core-v2): preserve completion status when spilling output
* fix(agent-core-v2): mirror dedupe reminders into the spill suffix
appendReminder additions lived only in the final output, so they were
dropped when the spill pointer replaced it; mirror the reminder into
untruncatedOutputSuffix for retained results, widening ToolDedupeResult
to ExecutableToolResult plus its message field. Also stop claiming the
full output was saved when retention capped out, narrow spillExempt to
'true' per the optional-property convention, and pass traceId directly
in the harness.
* fix(agent-core-v2): prefer persisted Bash task logs
* refactor(agent-core-v2): unify tool-result truncation in the spill pipeline
Route every tool result through ToolResultTruncationService.truncateForModel
as the single model-context decision point: spillExempt pass-through, the
50k char budget, per-line shaping, spill persistence with a 10MB retention
cap, and append-or-replace pointer rendering. Tools no longer declare
truncation options; sources keep only memory-safety caps.
- rename ToolResultBuilder to ToolOutputAccumulator and drop its options
- mcp keeps only its media pipeline and shares the unified 50k budget
- bash persists foreground logs at the spill threshold and reuses them as
spill.outputPath only within the retention budget
- carry completion/error messages in spill.suffix so retention capping
cannot drop them
- render a bounded preview when spill persistence fails
- suppress suffix lines already present inline in append mode
- call out text-only persistence when media parts stay attached
* fix(agent-core-v2): preserve success status in spilled output
* fix(agent-core-v2): reuse the complete task log for spilled bash output beyond 10MB
* Update tool-result-spill.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
v2 engine status events carry contextTokens/maxContextTokens but never
contextUsage, so appState.contextUsage was only refreshed by getStatus
pulls and then went stale while the token counts kept updating live.
The /usage panel and footer render the ratio as a bar but recompute the
percentage text from the counts, so a stale ratio showed as a bar that
disagreed with the percentage (e.g. bar ~74% next to "18% (180k / 1M)"
after compaction or a model switch).
Recompute the ratio from the post-patch token counts whenever a status
update touches contextTokens or maxContextTokens without carrying an
explicit contextUsage. v1 events carry the ratio and are unaffected.
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
* fix(kap-server): report run_in_background on the task wire
The /tasks wire now carries the task's detached flag as
run_in_background (schema in both the kap-server local copy and the
public protocol package). A running foreground subagent used to be
indistinguishable from a background one on this surface — clients that
defaulted the missing field to true would treat it as background.
* chore: add changeset for the run_in_background wire fix
* fix(kap-server): make run_in_background a required wire field
The field is always emitted (ghost-restored records pre-dating it read
true: the persisted store only lists terminal-and-detached or running
tasks, which all carry a concrete flag). Making the contract required
means a producer that omits it fails as an ordinary protocol error
instead of clients silently re-interpreting the row as foreground
* fix(protocol): keep run_in_background optional in the public task schema
The public schema types the agent-core v1 task service too, which does
not emit the field — making it required there is a breaking protocol
change (and broke agent-core's typecheck). kap-server's own local
schema stays required: it is the sole writer of the /tasks response
and always emits. Consumers apply the foreground fallback when the
field is absent
* fix(kimi-code): render newlines instead of literal backslash-n in rc output
* fix(kimi-code): print plain URL in rc output when hyperlinks are unsupported
* feat(kimi-code): add remote control web tunnel
Add CLI and TUI entry points for exposing the local web UI remotely.
Bridge HTTP and WebSocket traffic with local authentication and reconnect handling.
* fix(kimi-code): prevent remote control websocket crash
* fix(kimi-code): align websocket dependency versions
* fix(kimi-code): harden remote control connection setup
Reconnect when management closes during the HTTP tunnel handshake.
Reject non-loopback Remote Control binds whose CSP blocks path bootstrap.
* fix(kimi-code): fix remote control rewriting, caching, and WS frame loss
* feat(kimi-code): add remote control QR output
* build: update pnpm dependencies hash
* refactor(kimi-code): remove the --allow-remote-terminals flag
* feat(kimi-code): add remote control lock, rc command, and QR fixes
* fix(kap-server): broadcast user prompts to all session clients on submit
- agent-core-v2: emit prompt.submitted (status running|queued) at enqueue and prompt.started when the turn launches
- kap-server: project prompt.submitted/prompt.started into transcript prompt entities and the live transcript REST response
- update flake.nix pnpmDeps hash for the PR lockfile
* fix(node-sdk): drop v2-only prompt.started from SDK event stream
- event-mapper: add prompt.started to the dropped v2-only prompt lifecycle types (parity with submitted/completed/aborted/steered)
- cli test: assert only visible sub-commands and stub the experimental flag env for determinism
* ci(pkg-pr-new): post custom install comment for npm 12 compatibility
* feat(kimi-code): render remote control QR as inline image on capable terminals
* feat(kimi-code): improve remote control terminal output
- add onboarding, security, device management, and help guidance
- show compact clickable links and QR image fallback details
- report relay and remote device connection lifecycle
* test(agent-core-v2): update tool event snapshot
* revert(ci): keep preview workflow unchanged in rc pr
---------
Co-authored-by: liruifengv <liruifeng1024@gmail.com>
- retry every failed LLM request indefinitely in runRequest when
KIMI_CODE_INFINITE_RETRY is set, covering turn steps and operation
requests such as compaction
- keep projection recovery ahead of the infinite retry branch, honor
Retry-After, and keep abort effective during backoff waits
- exclude context overflow from infinite retry so the deterministic
turn-level and compaction-level overflow recovery paths still run
- extract retryBackoffDelay for single-attempt backoff computation
* fix(tui): render /plugins marketplace before version lookups resolve
The Third-party/Official tabs waited on the slowest GitHub
releases/latest lookup before painting any catalog row, with no
timeout (undici defaults: 10s connect, 300s headers) and no caching,
so a stalled connection to github.com left the panel on "Loading
marketplace…" for minutes on every /plugins open.
Load in two phases: render the catalog as soon as it is parsed, then
resolve latest versions in the background (5s per-lookup timeout,
per-entry failures degrade to a missing badge) and refresh when they
land. Update badges appear slightly later; row order is unaffected
since sorting only depends on installed state.
* refactor(tui): move marketplace version lookup timeout to constants
Per AGENTS.md, application constants live in src/constant/ — moves
MARKETPLACE_VERSION_LOOKUP_TIMEOUT_MS next to the other marketplace
constants in constant/app.ts.
* fix(tui): resolve marketplace versions before built-in injection
Phase 1 injected built-in capability rows into the marketplace before
phase 2 ran, masking the matching catalog entries' GitHub sources
behind capability:<id> rows — so installed built-ins could never
receive update badges (the pre-change resolve-then-inject ordering
preserved them).
Keep the raw parsed catalog for phase 2, re-apply withBuiltInEntries
after versions resolve (resolved versions flow onto capability rows),
and keep the built-ins-only fallback when the catalog is unreachable.
* fix(tui): surface marketplace parse errors instead of masking them
The phase-1 catch converted every failure into a built-ins-only loaded
marketplace, hiding malformed-catalog errors behind a silently empty
Curated tab. Restore the error state for all phase-1 failures — the
panel already keeps built-in capability rows installable in the
Official tab while the error is displayed.
---------
Co-authored-by: kimi-agent-bot <kimi-agent-bot@users.noreply.github.com>
- replace the Agent-scoped DI service with an eager non-durable Agent Runtime; the date_change injection provider registration now lives in an actor effect owned by the actor lifecycle, and the seed memo moves from the dateChange.seed state key into machine context
- honor eager: true for non-durable runtimes in AgentRuntimeSet so consumer-less runtimes still materialize
* fix(kimi-code): persist picked thinking effort up to the model's default effort
The persistence gate kept the model's top declared effort session-only
unconditionally, so users whose delivered default_effort is the top tier
(e.g. max) could never save an explicit pick of it. Compare the pick
against the model's default_effort instead, using support_efforts as the
strength ordering: picks above the default stay session-only, picks at
or below it persist. Models without a declared default keep the
historical top-tier rule. The same change lands in the VS Code
extension's mirrored logic.
* docs(kimi-code): document the effective-default ceiling for effort persistence
Clarify in both apps' comments, the changeset, and the config docs that
the persistence ceiling is the model's effective default effort, whether
declared via the catalog / overrides or synthesized by the protocol
profile inference (Claude models resolve to high, so an xhigh pick is
session-only there). Pin the inference path with tests in both apps.
* fix(vscode): resolve the save-config model with its provider type
Mirror the TUI's effectiveModelForHost: without the provider type the
Anthropic fallback profile (e.g. claude-latest) never matches, so the
inferred default effort that gates persistence was missed and an
above-default pick could persist where the TUI keeps it session-only.
* Delete .changeset/persist-effort-up-to-model-default.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix(vscode): seed the persisted effort with the effective-default ceiling
* fix(vscode): project webview models with the provider type
* fix(kimi-code): apply a session-only effort pick to the runtime in the /provider flow
* fix(vscode): update the persisted-effort seed on model-switch saves
* docs(kimi-code): drop the default_effort persistence-ceiling note
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* fix(agent-core-v2): keep agent lifecycle context active through scope teardown
* fix(agent-core-v2): deactivate agents after scope-units teardown
* fix(kap-server): install process handlers only after successful startup
* fix(agent-core-v2): let the teardown finalizer own create-failure deactivation
* fix(agent-core-v2): await asynchronous scope-units teardown before deactivation
* fix(agent-core-v2): await agent scope teardown before completing removal
* fix(agent-core-v2): mark fire-and-forget scope disposals after awaitable dispose
* fix(agent-core-v2): return the in-flight promise from repeated disposeAsync
* fix(agent-core-v2): await child containers and keep kap-server handlers through shutdown
* fix(tower): remove command queue
* feat(agent-core-v2): support an explicit base branch in TowerInit
* fix(kimi-code): keep tower objective order across a mid-turn compaction
* feat(agent-core-v2): add abandoned tower mission status to release stale scopes
* chore: consolidate tower changesets into one feature entry
* chore: consolidate tower changesets into one feature entry
---------
Co-authored-by: konghuanjun <konghuanjun@moonshot.ai>
Add a dedicated [swarm] config section so AgentSwarm subagent timeouts no longer follow [subagent] timeout_ms: timeout_ms (default 7200000, i.e. 2 hours; 0 = no timeout) with the KIMI_CODE_SWARM_TIMEOUT_MS env override, mirroring the [subagent] section. Deliberate behavior change with no fallback: a value previously set in [subagent] timeout_ms to cover swarms needs to move to [swarm]. Print mode (kimi -p) keeps its no wall-clock cap semantics: [swarm] timeout_ms also defaults to 0 there unless explicitly set. Docs updated in both locales (config-files, env-vars, tools) and the config manifest regenerated.
- define the AgentSkill contract and SkillRuntime (activate /
promptWithSkills / recordModelToolActivation) with a lazy, non-durable
provider; recordActivation dispatches SkillActivated directly and the
skillKey / SkillActivate relay is gone
- allow agent runtime descriptors to omit logic (durable definitions
still require it), making skill the first pure-API domain
- featurize the skill domain: app/skillCatalog,
workspace/workspaceSkillCatalog, session/sessionSkillCatalog,
agent/skill, and agent/tools/skill move under src/features/skill;
the static Skill tool registration and the AgentSkillService are gone
- resolve the runtime at the edge: kap-server routes and node-sdk
activateSkill go through IAgentLifecycleService.resolve, and the
klient dispatcher keeps the agentSkillService wire name over a
per-agent view
* fix(transcript): fold mid-turn task notifications into the current turn on cold rebuild
* chore: changeset for the notification fold fix
* fix(transcript): key the notification fold on persisted task-turn boundaries, not the previous message role
* fix(transcript): collect background_task turn origins too, and fall back when the wire has no turn.started records
* fix(transcript): fold consecutive task notifications into the same turn
* fix(transcript): normalize folded notification text to the live title/body form
* fix(transcript): stop folded notification text before child blocks, preserve legacy background_task turns absent from the boundary set
* fix(transcript): truncate folded notification text at the first child-block tag, not just the tag lines
* fix(transcript): drop folded notifications without a persisted step, truncate only at output blocks
* fix(transcript): attach mid-turn task notifications to the following step, cold and live
* fix(transcript): keep other tasks' notifications in task-origin turns
* fix(transcript): derive task-turn boundaries from durable turn.prompt records
* feat(transcript): carry subagent model and thinking effort on task entities
* fix(transcript): mirror turn liveness into meta.activity, live and cold
* fix(transcript): populate the prompts entity from prompt.accepted/queued engine events
* fix(transcript): reconcile liveness and the prompt queue at backfill from the live loop state
* fix(transcript): include the prompts entity in the REST transcript response
* fix(agent-core-v2): publish prompt.accepted on the event bus
* test(transcript): add the contract-level e2e covering every entity the client renders from
* fix(transcript): guard the prompt backfill against missing services; align stream expectations with prompt.accepted on the bus
* test(agent-core-v2): re-record event stream snapshots with prompt.accepted published
* fix(transcript): settle the spawned agent row when its lifecycle redirects to the task row
* test(transcript): move the contract e2e timeout to the describe arg (jest lint)
* fix(transcript): declare task model fields in the wire schema, carry prompt content on accepted, normalize queued content
- transcriptTaskSchema declares model/thinkingEffort: Zod strips
undeclared keys, so schema-driven REST/WS consumers lost both fields
the projector now populates.
- PromptAccepted carries the admitted content (it is the only event a
first-turn prompt ever emits, and the bare id left the prompts entity
permanently partial) — projected with userMessageId and the public
content shape via projectPromptContentParts, same as queued and the
live backfill.
- Regenerate the wire manifest and re-record the affected event-stream
snapshots.
* fix(transcript): preserve task model fields across termination and accepted prompt details across queueing
- onTaskLifecycle carried resultSummary/usage/error/stateReason but
dropped model/thinkingEffort: a completed detached-Agent row lost the
metadata spawned set while running.
- prompt.queued rebuilt the entity from scratch, discarding the
userMessageId and createdAt that prompt.accepted had just stamped —
build the queued update from prev.
* fix(transcript): keep prompt.accepted out of the public v1 event stream
The observable marker made the broadcaster forward every accepted
prompt to v1 WS clients, but events-zod has no accepted variant (v1
surfaces submission through the service-synthesized prompt.submitted)
and the SDK mapper didn't drop it — schema-driven clients could reject
the frame. Drop it at the WS edge and in the SDK's dropped set; the
transcript projection keeps consuming it internally.
* fix(transcript): derive cold task-turn boundaries through undo anchor replays
* fix(transcript): flush trailing folded notifications into the open turn
* fix(transcript): drop trailing buffered notifications to match the live projector
* chore: split transcript changesets per logical change
* fix(transcript): parse only the generated Title/Severity header lines in folded notifications
* fix(agent-core-v2): honor default_effort for secondary-bound subagents
[secondary_model].default_effort was parsed but never consumed, so a
subagent bound to a secondary/pool model resolved its thinking effort
from the main-oriented global [thinking].effort or the middle of the
bound model's support_efforts. Pass the section's default_effort as the
explicit spawn thinking, then fall back to the bound model entry's own
declared default_effort, both ahead of the global thinking config.
* docs(configuration): document secondary_model default_effort precedence
* fix(agent-core-v2): apply the model-default thinking fallback to tower spawns
TowerSpawnTool resolves the subagent binding directly and bypasses
planSpawn, so pool-bound tower workers never saw the bound model
entry's default_effort fallback. Apply the same resolution in launch.
* fix(agent-core-v2): preserve disabled thinking for subagents
* feat(agent-core-v2): add the unified MCP management plane
Port the v1 MCP management plane (#2858) onto the v2 DI x Scope engine:
- App-scope IMcpOAuthService shared by every workspace handler and
session overlay: credential events, single-flight refresh, proactive
refresh timers, OAuthTokenTransaction-serialized writes, offline
tokenState, shutdown. Providers read tokens through the store so
grants written or revoked by another process are honored immediately;
http/sse transports ride the transaction fetch.
- IMcpConfigStore: the single write point for the user-level mcp.json
over the filesystem byte store, byte-identical to v1's format, with
per-entry validation, name normalization, __proto__-safe parsing, a
mutation tail, and an onDidWrite event.
- IMcpRegistryService: the unified read view over the layered config
files (with per-entry origins) and plugin manifests (full descriptors
incl. disabled, with provenance); collisions stay visible and runtime
resolution ranks an enabled plugin above the file layers.
- IMcpManagementService: guarded CRUD, connection-test probes, the
locator-addressed inspection/auth-status surface, and
locator-addressed OAuth begin/complete/cancel/reset with ambiguity
rejection. Engine services stay ungated; the mcp_management flag
gates the edge exposure.
- Workspace runtime aligns with v1 precedence (an enabled plugin entry
wins over the file layers, shadows revive), and management writes
reload immediately via onDidWrite instead of the watch debounce.
- node-sdk v2 facade delegates to the engine service (deleting its
in-process duplication); kap-server exposes /api/v2/mcp/* and klient
gains global.mcp.*, both flag-gated.
* fix(agent-core-v2): settle early and cancelled MCP OAuth callbacks
* refactor(node-sdk): write session MCP persists through the engine config store
* refactor(agent-core-v2): strip comments from the MCP management plane files
* fix(agent-core-v2): harden MCP management readiness
* test(node-sdk): cover offline MCP auth statuses
* fix(agent-core-v2): isolate stdio MCP probes
* fix(klient): normalize MCP OAuth errors
* fix(mcp): honor workspace CRUD context and refresh timing
* fix(mcp): drain OAuth refreshes during shutdown
* fix(mcp): guard CRUD across registry collisions
* fix(mcp): canonicalize trust and refresh scheduling
* fix(mcp): close callback listener on setup failure
* fix(mcp): preserve trust and oauth behavior
* fix(oauth): retain refresh tokens after SDK saves
* fix(oauth): stop proactive sweep during shutdown
* fix: await MCP workspace reconciliation
* fix: serialize MCP OAuth and trust cleanup
* fix: reject persisted MCP plugin collisions
* fix: reconcile MCP workspaces concurrently
* fix(mcp): check project-layer trust at the queried cwd
* fix(mcp): expire abandoned OAuth flows after an idle timeout
* fix(mcp): keep mutable user entries writable past read-only collisions
* fix(mcp): abort the auth::complete long poll on client disconnect
* fix(mcp): map OAuth flow failures to wire code 40929
* docs(mcp): note probe credential effects and plane semantics
* chore: add the SDK changeset for MCP management cwd params
* feat(mcp): expose the management plane without the experimental flag
* fix(mcp): preserve auth management semantics
* fix(agent-core-v2): bound MCP OAuth auth-server requests and the shutdown drain
* fix(node-sdk): restate engine MCP management errors as KimiError
* fix(agent-core-v2): preserve shared OAuth flow lifetime
* fix(agent-core-v2): close MCP OAuth cancellation and shutdown gaps
- bound the authorization-code exchange with the request timeout and the
flow/caller abort signals, and make shutdown abort hung begins and close
their callback listeners immediately
- keep token-transaction effect coalescing intact when durable tokens carry
local stamps, and serialize the meta sidecar and tokens-saved event with
the token write inside the lock
- drain transport-driven grants, their trailing SDK save continuations, and
interactive completions during shutdown, with a cancellable deadline
* fix(agent-core-v2): harden MCP probe runtime resolution and path handling
- resolve stdio probes against the containing workspace's runtimes and
reject out-of-workspace probes for non-local runtime_id instead of
silently falling back to a local-only transient registry
- share one Windows-aware path canonicalization across the config loader,
registry trust lookup, trust records, and workspace matching
- keep a UTF-8 BOM fatal for the user-level mcp.json store, matching the
workspace loader and v1
- validate completeServerAuth timeoutMs bounds at the engine boundary
* fix(agent-core-v2): await workspace MCP reconciliation on plugin mutations
Plugin install/enable/disable/remove now resolve only after reload
listeners settle their waitUntil work, so a disabled plugin's MCP server
cannot linger connected and an enabled one is visible to the next
session, matching v1. The workspace MCP consumer joins the barrier while
keeping its log-only failure tolerance; delivery is awaited outside the
mutation queue to avoid self-deadlock through consumption reads.
* fix(mcp): close the SDK, klient, and server edge gaps
- register mcp.oauth_failed in the v1 error registry and restate unknown
engine codes as internal instead of minting undeclared KimiError codes
- route persisted session MCP adds through the same KimiError restating
as the global management methods
- give the klient IPC transport a per-call timeout so completeAuth's long
poll outlives the 30s default, clamped to the Node timer ceiling, and
align the contract timeoutMs upper bound with REST
- await the MCP OAuth service shutdown directly in SDK and server close
before scope disposal
* fix(agent-core-v2): keep file-over-plugin MCP precedence and harden the plane
- Revert the v1-style precedence flip: the workspace merge and
resolveRuntimeTarget keep the file entry above plugins (v2's historical
order; the divergence from v1 is deliberate and documented in AGENTS.md).
- Guards follow each engine's winner: project-layer entries stay read-only,
while plugin entries never block user-level writes, so a file entry may
shadow a plugin and removing it revives the plugin. The parity suite pins
the engine split for a persisted session add over a plugin-owned name.
- inspectServers tolerates a wire-encoded null targets array: klient's ipc
transport sends null for an omitted leading optional argument.
- Fire the config store's onDidWrite after the mutation tail settles, so a
write listener can re-enter the store without deadlocking the queue;
concurrent-mutation and re-entrant-listener tests pin both contracts.
* chore: condense the sdk MCP changeset to one sentence
* test(node-sdk): pin verify:false auth-status parity and fix the sdk changeset
- Name authoritative data sources in the intro (World Bank, IMF, OECD, FRED,
WHO, FAO, NBS, Wind, S&P Capital IQ, SEC EDGAR, Caixin, Xinhua Finance,
Gildata) so users can see what backs the plugin
- Turn the eight 'what you can do' scenarios into collapsible details blocks
with question-style headers (title — question?) so the page stays scannable
- Coverage table: add a financial-news/industry-data row (Caixin, Xinhua
Finance); name Yuandian Legal for the legal row; macroeconomics row now
also covers China government data and IGO official statistics
- Only sources approved for both domestic and overseas publicity are named;
restricted sources are described by capability instead
* feat(agent-core-v2): turn /tower into a mode parallel to plan mode
* feat(agent-core-v2): align /tower command semantics with the original skill behavior
* fix(tui): harden the /tower command against mid-turn objectives, legacy engines, and stale status
* fix(agent-core-v2): keep restored tower state inert while the feature flag is off
* fix(agent-core-v2): include TowerInit in the mode tool overlay and report flag-gated tower state
* feat(agent-core-v2): expose tower control tools statically and make the mode injection history-derived
* fix(tui): warn that tower mode needs a restart after a live flag flip; drop redundant undefined from SessionStatus mode fields
* fix(agent-core-v2): let tower mode exit clear persisted state while the flag is off
* fix(agent-core-v2): emit the tower exit reminder through a disabled flag and drop the redundant REST state comparison
* fix(tui): show the Tower mode status row only when the experiment is available
* fix(agent-core-v2): confine tower mode to the main agent and always re-assert it for objectives
* feat(kap-server): project tower mode into transcript modes and reassert explicit toggles
* fix(agent-core-v2): fold the main-agent invariant into the effective tower state
* fix(kap-server): gate the cold tower mode badge behind the experiment flag
* fix(agent-core-v2): reapply the tower tool overlay after a profile bind; fix(kap-server): clear cold tower badges on non-main agents
* fix(protocol): mirror towerMode and tower_mode in the shared zod schemas
* test(agent-core-v2): adapt tower tests to the agent lifecycle context architecture
* chore(agent-core-v2): regenerate the wire manifest; test(node-sdk): look up the main agent via findAgentHandle
* fix(agent-core-v2): exit a replayed tower mode when the workspace belongs to another session
* fix(agent-core-v2): carry tower ownership in the enter record so forks clear inherited mode
* fix(agent-core-v2): apply the tower overlay before dispatching enter and repair it on status updates
* fix(agent-core-v2): validate store ownership before entering tower mode
* fix(agent-core-v2): claim the repository tower owner at enter; fix(tui): confirm mode activation before reporting success
* fix(agent-core-v2): make the first tower claim exclusive and refuse adoption over a live owner
* feat(agent-core-v2): guard tower adoption and teardown with a cross-process ownership lease
* revert(agent-core-v2): drop the cross-process lease and enter-time claim, keep ownership checks process-local
* fix(agent-core): hide the v2-only tower flag from the legacy experiments list
* fix(agent-core-v2): keep tower mode inert until the tower feature is assembled
A live /experiments flip refreshes the flag but cannot re-run App-scope
feature assembly, so the tower tools/profile stay unregistered until a
restart. Gate enter()/isActive on the assembly fact and say so in the
TUI error. Also resolve the AGENTS.md conflict block committed by the
merge, and widen the TUI experimentalFlag type to string now that flags
live in two registries.
* fix(kap-server): gate the cold tower badge on tower feature assembly
Same live-flip gap as the mode machinery: a persisted tower_mode.enter
plus a flag enabled without a restart would still show the badge while
the feature is inert. Require isTowerFeatureAssembled() alongside the
flag, re-exported from agent-core-v2.
* fix(agent-core-v2): liveness-aware tower entry and per-App assembly state
enter() now mirrors TowerInit's adoption rule: a stored owner blocks
entry only while that session is live in this process, so a new session
can enter the mode and reach TowerInit to adopt a stale tower. The
assembly marker is keyed by each App's flag service (WeakSet) instead of
process-global module state, so coexisting Apps no longer leak assembly
into one another.
* fix(agent-core-v2): keep stale-owner adoption across resume; reject tower updates that do not take
exitForeignTower now treats a stored owner as foreign only while that
session is live, so a mode entered by adopting a dead owner's tower
survives close/restart. The TUI validates the model prerequisite before
enabling tower for an objective, and the REST agent_config path throws
session.tower_mode_invalid when enter() did not take effect instead of
acknowledging a no-op.
* fix(agent-core-v2): clear the tower assembly marker when the feature unloads
Register the WeakSet cleanup via the feature's onDispose so the
capability follows the managed unit's lifecycle — after
unprovideUnit('tower'), isActive/enter() no longer treat the retracted
tool set as assembled.
* fix(agent-core-v2): publish tower deactivation on gate loss; reject refused setTowerMode in the SDK
isActive now reconciles its projection: restore and feature-manager unit
changes publish AgentStatusUpdated({ towerMode: false }) when the
persisted mode lost a gate (flag off at runtime, feature unloaded), so
live transcript badges and TUI state stop showing an inert mode. The
SDK's setTowerMode(true) verifies the effective state and throws
session.tower_mode_invalid, matching the REST path.
* fix(agent-core-v2): reconcile tower projection on config changes and cold ownership moves
The last unreconciled gate inputs: a live setConfig writing the
experimental section (no session reload, no units event) now republishes
towerMode:false through the config-change subscription, and the cold
transcript badge mirrors the same ownership/liveness rule as enter() —
retained while the store owner is this session or no live session, cleared
once a live session elsewhere owns the tower.
* fix(agent-core-v2): reconcile the tower projection in both directions
The OFF-only reconcile left a hole: re-enabling the flag in the same
process made isActive true again with no towerMode:true publish, and
enter() could not heal it (it early-returns when already effective).
The projection now tracks the last published state and emits both
false→true and true→false transitions from the same restore/units/config
triggers; direct publishes (enter/exit/restoreTowerTools) keep the
tracker in sync.
* fix(agent-core-v2): validate forked tower ownership even while the flag is off
exitForeignTower's flag short-circuit let a fork restored while the
experiment was disabled keep its inherited enter record; re-enabling the
flag later revived both source and fork over the same store. Ownership
validation is flag-independent state hygiene, so restore now runs it
regardless of the effective flag — a live foreign owner clears the
fork's persisted mode before any gate can rise again.
* fix(agent-core-v2): veto tower tools while the tower experiment is off
With the feature assembled and the tool overlay active, disabling the
flag live left TowerInit/TowerTeardown callable — they have no flag
check — so prompts could still mutate or dismantle .tower/ while the
experiment reported disabled. A dedicated onBeforeExecuteTool hook now
denies every tower tool whenever the flag is off, mirroring the TodoList
veto.
* fix(agent-core-v2): keep tower worker write isolation when the flag turns off
The worker Write/Edit guard is identity-scoped (tower-worker profile),
not feature-activity-scoped: disabling the experiment live must not let
already-spawned detached workers write into the main checkout or other
worktrees. The guard no longer checks the flag; the tower-tool veto
added earlier covers protocol access instead.
* test(agent-core-v2): make tower tests hermetic for CI
Three CI-only failures: towerService git fixtures committed without a
repo-local identity (CI has no global gitconfig), the node-sdk tower
positive tests relied on the developer shell's
KIMI_CODE_EXPERIMENTAL_FLAG=1 master switch instead of enabling the
tower flag explicitly, and the legacy harness experimental-features
expectation still listed the tower entry removed from the v1 registry.
Add a shell path bridge that translates between win32 paths and the
MSYS2/Git Bash path dialect. File tools resolve model-supplied paths
through it before canonicalization and workspace checks: drive-letter
forms translate lexically, root-relative paths resolve via cygpath -w
with per-segment caching, and every failure mode falls back to the
previous behavior.
Fixes#2199
A failed resume is cached by SessionManager and rethrown from
whenResumeSettled, so archiving a session whose workspace is gone
failed with the stale resume error even though cold archive only
rewrites session metadata. Swallow the settle failure: still wait for
an in-flight resume before the live/cold classification, but fall
through to the cold metadata path after a failed one.
* feat(agent-core-v2): add a fork parameter to the Agent tool
Spawning with fork: true starts the subagent from a one-time snapshot of
the calling agent's completed conversation history — same profile, tool
set, and model — instead of zero context. The seed trims the trailing
open tool exchange (the in-flight Agent call itself) before appending
into the child's context memory, and the first prompt carries an
inheritance notice framing the seeded history as reference material.
Fork rejects resume, a different subagent_type, or a model override as
tool errors, and skips the subagents allowlist since a self-inheritance
is not a delegation.
* fix(agent-core-v2): bind the stale-todo reminder only into the main agent
Subagents share the session todo list but no longer receive the
stale-todo nudge — the reminder injector now registers only on the main
agent, so delegated and forked agents are not prompted to maintain a
list they do not own.
* fix(agent-core-v2): inherit the caller's live binding and label fork launches correctly
Review follow-ups for the Agent tool fork mode:
- overlay the caller's live profile.data() via applyBindingSnapshot after
the catalog re-bind, so ephemeral addActiveTool deltas, the rendered
system prompt, and runtime model/subagents updates survive the fork;
skip the profile prompt prefix since the caller's prefixed first
prompt is already part of the seeded history
- resolve the fork activity label and approval-rule subject from the
caller's own profile instead of falling back to the default subagent
type, so an Agent(<other profile>) rule cannot approve a fork
* fix(agent-core-v2): close inherited in-flight tool calls instead of trimming them
Fork seeding now answers the source's trailing open tool calls with a
synthetic in-flight result instead of cutting the whole trailing
exchange: the seeded history stays protocol-valid, keeps the source's
final step visible as reference, and no longer confuses side-question
(btw) agents forked while the main agent is mid-turn. The close helper
is shared by the Agent tool fork and IAgentLifecycleService.fork.
Fork launches also stop requiring the caller's profile to still exist
in the session catalog: the child is created unbound and overlaid with
the caller's live binding snapshot, matching the lifecycle fork path,
and now records forkedFrom provenance.
* refactor(agent-core-v2): route Agent tool forks through agentLifecycle.fork
* feat(agent-core-v2): add a fork parameter to the AgentSwarm tool
* fix(agent-core-v2): seal partial assistant forks
* fix(agent-core-v2): align fork parameter descriptions
* fix(agent-core-v2): drop the main-only registration gate from goal tools
* fix(agent-core-v2): disclose dates via reminders to keep the system prompt byte-stable
* docs: condense the fork changesets to single sentences
* docs(agent-core-v2): frame the tool-contribution when gate as a fork parity trade-off
* test(agent-core-v2): plug fork coverage gaps and decouple swarm tests from spawn internals
* docs(agent-core-v2): keep the when-gate guidance in the contribution JSDoc only
* fix(agent-core-v2): contribute cron tools to every agent for fork prefix-cache parity
CronCreate/CronList/CronDelete were registered directly into the main
agent's tool registry by SessionCronServiceImpl, bypassing the
AgentToolContribution seam and keying on per-agent identity — so a forked
agent rebuilt a tool surface three tools shorter than its caller and the
inherited prompt prefix missed the cache.
Register the three tools through registerAgentToolService like the goal
tools do (no when gate, identical surface for every agent) and enforce
the main-agent restriction at execution time instead. Also fall back to
DEFAULT_CRON_CONFIG when the config section is absent, since the service
can now be constructed after the main agent exists.
* feat(agent-core-v2): track the fork parameter in the subagent_created event
* fix(agent-core-v2): gate tower orchestration tools at execution time
TowerInit/TowerPlan/TowerSpawn/TowerMerge/TowerTeardown were contributed
with a when predicate keyed on agentId === 'main', so a forked agent
rebuilt a tool surface missing TowerInit (always present for the default
profile) plus the rest of the tower set once it was enabled — breaking
prompt prefix-cache parity with the caller.
Contribute the tools with no when gate (profile policy still controls
visibility) and reject non-main callers at execution time instead.
* test(agent-core-v2): expect the fork field in the subagent_created mirror assertion
* test(agent-core-v2): cover fork subagent first-request prefix parity
* refactor(agent-core-v2): share the main-agent-only tool refusal across cron and goal tools
Goal tools rejected subagent callers by throwing GOAL_UNSUPPORTED_AGENT
from the service, which the executor wrapped as a resolution failure;
cron tools returned a clean refusal but each tool open-coded the same
identity check. Centralize the check and both messages in
agent/tools/mainAgentOnly.ts and use it from all seven tools, keeping
AgentGoalService.assertSupportedAgent as the coded boundary for RPC and
SDK callers.
* refactor(agent-core-v2): keep the goal main-agent gate at the tool layer only
* fix(agent-core-v2): preserve the fork tool surface when inheriting user tools
* Revert "refactor(agent-core-v2): keep the goal main-agent gate at the tool layer only"
This reverts commit fc09a8fa32de43bb6223bf96fcab9a7b200ac051.
* test(agent-core-v2): complete fork lifecycle stub
* Delete .changeset/btw-inflight-tool-calls.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* Delete .changeset/todo-reminder-main-only.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* Delete .changeset/swarm-fork-context.md
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* Add optional 'fork' parameter to subagent tools
Signed-off-by: 7Sageer <sag77r@hotmail.com>
* docs(agent-core-v2): drop the fork JSDoc comments
* feat(agent-core-v2): add prompt_cache_probe telemetry for forked agents
* feat(agent-core-v2): gate the subagent fork parameter behind an experimental flag
---------
Signed-off-by: 7Sageer <sag77r@hotmail.com>