Skip to content

fix: Surface API-provided error messages for OAuth and managed API failures - #11

Merged
liruifengv merged 2 commits into
mainfrom
error-msg-fix
May 25, 2026
Merged

liruifengv merged 2 commits into
mainfrom
error-msg-fix

Conversation

@liruifengv

@liruifengv liruifengv commented May 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related Issue

Resolve #(issue_number)

Description

fix: Surface API-provided error messages for OAuth and managed API failures

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked the related issue, if any.
  • I have added tests that prove my fix is effective or that my feature works.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@liruifengv
liruifengv merged commit 15b018f into main May 25, 2026
7 checks passed
@liruifengv
liruifengv deleted the error-msg-fix branch May 25, 2026 06:10
@github-actions github-actions Bot mentioned this pull request May 26, 2026
asdshuaishuai pushed a commit to d2rabbit/kimi-code that referenced this pull request Jul 21, 2026
…, diff drawer, more rounded corners

Five user-reported issues fixed in this batch:

MoonshotAI#3 Font-size adjustment now actually works
  Root cause: App.svelte's :global(body) used the `font:` shorthand
  with a hardcoded 13px, which won over the global.css
  `body { font-size: var(--ui-font-size) }` rule (same specificity,
  later in cascade). The shorthand resets font-size and the slider had
  no effect.
  Fix: replace shorthand with individual properties
  (font-family/size/line-height), keep font-size: var(--ui-font-size).
  Verified via headless Chromium: default 14px, slider to 20px → 20px,
  back to 14px → 14px.

MoonshotAI#8 Plugin enable/disable ACL error
  Root cause: PluginPanel called Command.sidecar('kimi', ['plugin',
  'disable', id]) which needs shell:allow-execute permission that
  isn't (and shouldn't be) granted in tauri.conf.json.
  Fix: added Rust `toggle_plugin(plugin_id, enabled)` command that
  directly edits ~/.kimi-code/plugins/installed.json (atomic tmp+rename).
  PluginPanel now invoke()s the new command instead of spawning a
  sidecar. No ACL needed.

MoonshotAI#11 Softer UI — bumped radius tokens
  --r-sm 6→8, --r-md 8→10, --r-lg 10→14, --r-xl 12→18.
  Legacy scale bumped in parallel (--radius-xs 6→8, etc.). All
  components using these tokens get the bump automatically.

MoonshotAI#2 Sidebar workspace/session hierarchy
  Workspace headers are now visually bigger (30px tall, 12.5px bold,
  with a top border + subtle bg gradient) and the session rows are
  indented (margin-left: 20px, smaller 11.5px font-weight 400).
  Workspace count badge becomes a pill instead of plain text. The
  hierarchy reads cleanly now.

MoonshotAI#1 Working-directory diff → second-level right drawer
  New DiffDrawer.svelte component (540px, slides in from right with
  spring animation). Clicking a file in the '工作区改动' section of
  RightPanel opens the drawer; inline expansion is gone. Commit-
  history diffs stay inline (only the working-directory section was
  changed per UX request). Esc / ✕ / mask click closes.

MoonshotAI#9 Composer compact moved into the main control row
  '压缩' is now a pill button next to mode/model/thinking instead of
  a separate FAB below. Per UX request: 'mode / model / thinking /
  compact all in one row'.

Verified: svelte-check 0 errors, cargo check 0 warnings.
7Sageer added a commit that referenced this pull request Oct 29, 2026
… 1: creation-time binding) (#4062)

* fix: release remote program generation leases while no controller uses them

A ProgramGeneration no longer pins its environment for its whole lifetime: the build lease is released as soon as the generation is constructed, re-acquired lazily when a session controller is created, and released again when the last controller reference drops. Retired generations keep their lease until final disposal so replaced controllers stay valid. With zero leases the registry reports the environment idle, so the provider's idle TTL reaping can actually close unused remote connections and reconnect on the next use.

* fix: resolve subagent prompt context and file history on the bound environment

When a subagent is spawned on an environment different from the caller's, the prompt prefix (git context) now runs against the target environment and its cwd instead of the caller's. File-history checkpoints forwarded from such a subagent now carry the emitting agent's environment id on each backup entry, so start/end captures and live change reads go through the subagent environment's filesystem instead of inspecting a same-named file on the main agent's environment.

* fix: resolve the sessionless fs suggest workspace from the environment registration

The sessionless /fs::suggest route no longer derives a registry workspace id from roots[0] for a non-local environment_id — remote roots such as /srv/project never resolve to the carrier workspace that owns the environment. The route now looks up the materialized workspace whose registry holds the environment and acquires the lease there, returning ENVIRONMENT_NOT_FOUND when no workspace has it registered.

* chore: changeset for the environment binding fixes

* fix: degrade file-history reads to unreadable when a stamped environment is unavailable

readCurrent now catches EnvironmentError from the environment acquire and returns 'unreadable' instead of throwing, matching the probeProjectContext idiom. After an idle reap or a transient drop, a turn's end checkpoint still completes its remaining paths instead of losing every end entry for the turn.

* feat(agent-core-v2): enable agent environment tools by default

Flip agentEnvironmentToolsFlag default to true so the main agent gets
change_environment and connect out of the box (the flag remains as an
opt-out, and the towerModeInactive when-condition stays). The 'agent'
profile's explicit tool allowlist is the second gate: bind()/useProfile()
now append ENVIRONMENT_SWITCH_TOOL_NAMES for the main agent under the
same main-agent + flag + non-tower conditions as the environments
prompt section, so the tools survive profile-driven activation.

CI fixes for the prepareSwitch cwd guard (environment.invalid_cwd):
- kap-server rpc.test.ts: pass cwd in the missing-environment POST so it
  still exercises 40420, and give the fake remote an fs + cwd for the
  switch half of the test.
- kap-server prompts.test.ts: bindRemoteEnvironment passes a real cwd
  and disposes the provider when binding fails (no cascade).
- agent-core-v2 config.test.ts: the date_change reminder embeds the host
  timezone in estimated-token snapshots; pin IHostClock's timeZone so the
  snapshot is deterministic across machine timezones.

Regenerate the tool-list/tool-hash snapshots shifted by the newly
default-on tools (loop, tool, resume, config, fullCompaction).

* docs: agent environment tools are default-on with opt-out

* docs: list change_environment and connect in the tools reference

Add an Environment Tools section to docs/en/reference/tools.md (mirrored
in docs/zh/reference/tools.md) covering the two agent environment tools
that M69 turned on by default: parameters, turn-boundary switch
semantics, temporary-environment lifecycle, and the main-agent-only /
Plan mode / tower mode / permission-mode constraints. Also link the
remote environments guide from the page's Next steps.

* docs: add environment parameter to Agent tool entry in tools reference

* docs: fix zh link spacing in Agent environment parameter entry

* fix(agent-core-v2): give union tool parameter schemas a top-level object type

toInputJsonSchema converts a z.union/z.discriminatedUnion input schema to
{ anyOf: [...] } / { oneOf: [...] } with no top-level type, which strict
OpenAI-compatible providers reject with 400
'tools.function.parameters.type is required and must be "object"'.
This broke every request carrying the connect tool, the only builtin
tool with a union-typed parameters schema.

Add type: 'object' at the top level whenever the converted schema lacks
a type but carries anyOf/oneOf. The addition runs after closeObjectNodes
on purpose: the top level must not gain additionalProperties: false,
which (with no sibling properties) would reject every non-empty object.

Tests:
- input-schema.test.ts: union and discriminated-union conversion plus
  runtime validation of branch inputs.
- environmentTools.test.ts: connect parameters validate as a
  strict-provider object schema for all three branches.
- tool.test.ts: permanent sweep asserting every registered tool exposes
  a top-level object type, with default flags and with all experimental
  flags enabled.
- Regenerate two llm.tools_snapshot inline snapshots (hash-only diffs).

* fix(agent-core-v2): ask for environment switch confirmation only in manual mode

change_environment and connect previously prompted in both manual and
yolo permission modes. The environment-switch-ask policy now abstains
outside manual mode, so yolo falls through to yolo-mode-approve like
every other tool. Tool descriptions and policy tests updated to match.

* docs: environment switching asks only in Always Ask mode

change_environment and connect now ask for confirmation only in Always
Ask (manual) mode; Ask When Needed and Never Ask modes proceed without
asking. Updates the tools reference and remote-environment guide in
both locales to match the policy change.

* fix: revert the environment binding on conversation undo

The environment binding state key was replayed from the full wire
journal instead of the surviving branch, so a switch cut by the undo
fork was folded back in and the reconcile step saw nothing to revert.
Mark the key undoable so it replays from the restorable chain.

Also make change_environment take effect for the next tool call in
the same turn: the binding commits immediately when no other tool
calls are in flight (deferring to the turn boundary only under genuine
in-flight concurrency), the turn environment snapshot and workDir
follow the commit, and the tool copy reflects the new timing.

* fix: drop a parked environment switch once a newer switch commits

A switch deferred under in-flight tool calls stayed parked after a
later switch committed in the same turn, so the turn-end flush
committed the stale one over the newer binding. Clearing the parked
switch in commit() makes the latest switch win on every path.

* docs: environment switch takes effect on the next tool call

change_environment now commits immediately when no other tool calls are
in flight, so the next tool call in the same turn runs on the new
environment; only genuine in-flight concurrency defers the switch to
the turn boundary. The /environment dialog and REST switch are still
refused while tool calls are executing or an approval is pending, and
an accepted switch takes effect immediately.

Updates the remote-environment guide, env-vars flag row, server-api
40901 entry, and tools reference in both locales.

* feat: split pending environment status from disconnected

An environment with no live connection and no observed failure — never
connected, or deliberately reaped after idling past its TTL — now reports
'pending' instead of 'disconnected'. 'disconnected' is reserved for
observed failures (connect failure, connection lost) and always carries
connectError. The TUI footer renders pending dim like ready instead of
error-colored with a failure banner, the /environment manager offers the
same Enter/R reconnect on a pending bound row, and the disconnect notice
no longer fires on a routine idle reap. Control flow is unchanged:
environmentStatusAllows still returns false for pending, so acquire
triggers a connect on demand exactly as before.

* fix: update the footer environment slot after conversation undo

The engine already reverts the environment binding on undo: an
integration test driving the real AgentConversationUndoService.undo
path (switchBranch + restore + reconcileAfterUndo) shows the binding,
workDir, change event, and revert reminder all land. The gap was
client-side: the TUI footer environment slot only re-polls the
binding on session load, turn end, /environment actions, and
environment.status.changed hints, so an undo that reverted a switch
left the footer showing the pre-undo environment.

Fire refreshEnvironmentSlot after a successful /undo, matching the
existing fire-and-forget refresh pattern.

* docs: remove user confirmation note for environment connection and switching

* fix(remote-exec): guard ExecBridge stdin EPIPE and resolve docker tilde remoteBin

ExecBridge never listened for 'error' on child.stdin, so a write landing
in the window between the launcher process dying and stdout ending raised
an uncaught EPIPE that crashed the host (kap-server). The constructor now
mirrors the server-side processManager guard: stdin errors break the pipe
quietly, child 'exit' also surfaces the disconnect, and write()/end()
drop once stdin is broken.

docker exec passes argv to execve without a shell, so the default
~/.kimi-code/bin/kimi remoteBin failed with exit 126 on every connect and
fell into the auto-install/manual-guidance flow. A docker launcher with a
tilde-prefixed remoteBin now resolves the container user's $HOME with one
shell probe before the first exec attempt; connectWithAutoInstall resolves
on every path, and the provider caches the absolute path on the record
keyed by the declaration fingerprint so reconnects (including after idle
reaping) skip both the probe and the failing handshake.

Also annotate process/read and its output replay buffer as reserved codex
exec-server dialect surface with no live consumer (README), and note the
docker tilde resolution in the remoteBin config reference.

* feat(mcp): start stdio servers in remote environments with env overlay control

EnvironmentStdioTransport now connects a pending environment before
acquiring it (inspect -> connect -> acquireWhenReady, mirroring the
tool-side pattern), so a cold remote environment can start an MCP
server on demand. For non-local environments the spawn env is only an
overlay: literal config.env plus envVars entries resolved locally,
matching codex's create_env_overlay_for_remote_mcp_server; PATH, HOME
and proxy variables come from the target. The new optional envVars
field accepts variable names or { name, source } with source 'local'
(sent from this machine) or 'remote' (resolved on the target). The
unimplemented executor schema field is removed.

* fix: make persisted environment binding resolution branch-aware via a shared resolver

The two peekPersistedBinding variants read the raw wire journal for the
last environment.set_binding record, ignoring the branch model: a
remote binding abandoned by conversation undo resurrected on resume,
triggering a proactive reconnect with no environment reminder.

Introduce the App-scope IEnvironmentDeclarationService owning
declaration resolution, defaultCwd derivation, connect, cwd stat
validation, and readPersistedEnvironmentBinding built on
parseTree + restorableChain so abandoned-branch records are excluded.
Migrate sessionManager, environmentBinding, subagent, and the
change_environment tool onto it, deleting both peeks; the binding
service restore now relies on dispatcher replay alone. The kap-server
environment list route resolves declarations through the same service.

* fix: align persisted binding journal projection with replay line numbering

readPersistedEnvironmentBinding now counts every raw candidate and
filters through isWireRecord, mirroring WireService.readEntries so
JSON-valid non-wire-record lines cannot shift the line numbers that
persisted agent.switched base/legacyUndoLine references point at.
Adds a regression test with such an anomalous line ahead of the
binding and switch records, asserting the restorable boundary holds.

* feat(tui): background-connect --environment at startup and fail fast on unknown ids

Starting with --environment used to freeze the whole TUI: the session is
created lazily on the first prompt, so the remote connect (10-30s
handshake plus auto-install) ran inline with the UI showing nothing — no
prompt echo, no busy state, no footer environment slot — and an unknown
environment id only surfaced at that point, silently dropping the first
prompt. The engine awaits the connect deliberately (the controller must
be built on the remote root), so the fix is TUI-side.

init() now validates the startup id against the merged [environments]
declarations and fails startup with a non-zero exit when it is unknown or
lacks defaultCwd, matching print mode's create-time failure. Validation
runs after the workspace-trust prompt so project-level declarations in a
freshly trusted folder resolve correctly. The session is then pre-created
in the background, with a synthetic connecting EnvironmentSlotState
driving the existing footer spinner until refreshEnvironmentSlot takes
over. The first prompt submission is announced (transcript entry plus
waiting phase) before awaiting the lazy creation, so the UI keeps
rendering and the prompt stays visible even when creation fails; input
queued during the creation is preserved through the runtime reset.

The SDK gains a session-less listEnvironmentDeclarations(workDir),
composed from the same engine services the session manager's create-time
validation uses, mirroring the getWorkspaceTrustInfo pattern.

Agent tool cards and the agent-group rows now show a dim env <id> badge
when the subagent runs in a non-local environment, read from the Agent
tool's environment argument.

Also remove the dead executor field from the MCP stdio config schema
mirror, following its removal from the engine schema and klient contract.

* fix(agent-core-v2,remote-exec): stop leaking the host cwd into remote bindings and report missing spawn cwd explicitly

- profileService builds the system-prompt workDir from the same agent-scope
  ISessionWorkspaceContext the tools use, so remote-bound agents are told the
  binding cwd instead of the host session cwd
- register AgentWorkspaceContextService in the prod module graph so agent-scope
  path resolution derives from each agent's own environment binding
- remote-exec processManager validates the spawn cwd exists and is a directory
  before spawning, failing with an explicit cwd error for pipe, pty and
  terminal spawns
- node-local HostProcessService mirrors the same cwd existence check locally
- test harness default environment stub derives workspaceRoots from the session
  instead of a hardcoded /workspace

* test(agent-core-v2): cover agent-scope workspace resolution and refresh stale tool snapshots

- assert ISessionWorkspaceContext resolves to SessionWorkspaceContextService at
  session scope and to the binding-derived AgentWorkspaceContextService at
  agent scope, including the session-roots fallback while the environment
  service is not materialized
- assert Bash resolves an omitted cwd from the bound environment workspace
  instead of the host session cwd
- refresh inline snapshots that went stale when the environment-tool
  confirmation note was removed

* fix(tui): stop the event loop when startup fails after the trust prompt

The trust prompt starts the event loop before initMainTui() runs, so a
startup failure in the normal branch (e.g. an unknown --environment id
failing fast) left the terminal in raw mode with the Kitty keyboard push
installed: neither start()'s outer catch nor the run-shell catch restores
the terminal, and process.exit(1) then leaks it into the user's shell.
Wrap initMainTui() with the migration branch's disposeTerminalTracking()
+ ui.stop() cleanup, gated on the trust prompt having started the loop.

* fix: evict stale environment reminders from the model context on undo

Environment switch and project context reminders are ownerless
injections, so the undo fork's restorable chain re-includes them:
after undoing a switch turn the model kept the stale switch reminder
next to the revert reminder, and repeated switch/undo cycles
accumulated more.

Make contextMemoryKey's ContextAppendMessage fold latest-wins for the
state-derived variants (environment_binding, project_context):
appending one drops earlier injections of the same variant, on live
dispatch, replay, resume, and cold rebuild alike. The filter runs on
original(draft) because filtering the immer draft itself leaks revoked
proxies into the stored state.

* feat(agent-core-v2): fail change_environment fast while foreign tool calls are in flight

Replace the pendingSwitch deferral with an immediate environment.conflict
error that names the in-flight count and tells the model to retry once no
other calls are running. The deferred commit let a parallel batch report
contradictory outcomes (Bash results from the old environment plus a
"scheduled" switch) and carried a stale-parked-switch race against later
immediate commits; failing fast removes the whole class.

- connectAndSwitchAtTurnBoundary is now connectAndSwitchInTurn: it rejects
  before connecting when any non-change_environment call is active, and
  commits immediately otherwise (sequential change_environment calls keep
  latest-wins semantics).
- Drop pendingSwitch, flushPendingSwitch, and the TurnEnded flush hook
  along with the ISessionEventBus dependency of the binding service.
- The tool result no longer has a scheduled branch: success always means
  committed, and the conflict error is model-actionable.
- Sync the tool description, the system-prompt environments paragraph,
  and the en/zh docs with the fail-fast behavior, and refresh the
  llm.tools_snapshot inline snapshots.

* fix(agent-core-v2): harden non-local binding cwd fallback and explicit environment id validation

* fix: await declaration reconciliation after workspace trust

trustWorkspace() resolved as soon as the trust record was written, while
the remote environment provider only queued its declaration reconcile
onto its serialized tail. A session created immediately after the await
could miss the just-trusted project environments in the registry and
start with a local controller under a persisted remote binding.

The trust change event now carries waitUntil semantics end to end
(AsyncEmitter, matching the sessionLifecycle/provider-service pattern):
WorkspaceTrustService.trust()/untrust() await listener waitUntil
promises, Program forwards them through its re-fired event, and the
remote environment provider hands its reconcile promise to the event.
trustWorkspace() therefore resolves only after the triggered reconcile
has published project declarations to the registry. Reconcile failures
stay observable via logs without hanging or rejecting the trust call.
Environment removal on untrust remains fire-and-forget so revoking
trust cannot block on the registry drain.

* feat(agent-core-v2): reject environment switches in plan mode, dedupe environment helpers

- Add a shared acquireOrWhenReady helper and use it in the seven
  environment-backed tools instead of per-tool acquire ternaries.
- Merge the duplicated subagent environment-flag gate into one check
  shared by resolveExecution and execution.
- Sink the listEnvironments entry assembly into agent-core-v2 and call
  it from both kap-server and node-sdk.
- Reject switch/connectAndSwitch/connectAndSwitchInTurn while plan
  mode is active so the active plan file is not stranded on the old
  environment, covering tool, REST, and SDK paths in one place.

* refactor(agent-core-v2): harden host cwd contract, program fake deps, and lease resource tracking

- add cwd? to HostEnvironmentInfo and read it directly instead of
  cross-package type assertions in subagentService and agentEnvironment
- narrow WorkspaceFsService's workspaceDirs param to the one member it
  reads and GitService's workspace manager param to a minimal
  GitWorkspaceLocator, dropping both as-unknown-as fakes in program.ts
- keep EnvironmentLease.track records in a per-generation set and wrap
  tracked resources in a non-mutating proxy instead of rewriting
  resource.dispose, so frozen resources no longer throw and multiple
  leases tracking one resource stay independent

* fix: post-M90 CI regressions — watch-flag test opt-ins and ACP switch cwd

Three CI failures on the integration branch, three distinct root causes
(none in M90 itself):

- acp-server e2e-turn: real regression from M88 (aa3876f2c). ACP terminal
  sessions bind the ACP pseudo-environment via switch() without a cwd, and
  M88's non-local undefined-cwd fallback (host.cwd ?? host.homeDir) then
  resolved Bash spawn cwd to the real host home instead of the session
  cwd. Pass the session cwd at the switch call site, matching the
  non-local-binding-requires-cwd model.

- remote-exec watcher test, kap-server and node-sdk declare tests:
  fallout of upstream f17a22ebf (filesystem watch now off by default)
  entering CI through the pull_request merge ref. Their project
  declaration registration rides the global watch switch, so the
  declarations never registered and the tests timed out. Enable the
  watch explicitly in these suites, mirroring the upstream idiom for
  watch-dependent tests.

* fix(kap-server): map environment route errors to declared codes and connect pending environments on demand for attachments

* fix(cli): load node-pty from SEA native assets to restore remote terminal

The SEA bundle force-bundled node-pty's JS, but the package locates its
.node binding through a runtime-concatenated require that cannot resolve
inside a single-executable binary, so every tty spawn in the shipped
binary failed (remote executor processManager and the local
hostTerminalService alike).

- tsdown.native.config.ts: externalize node-pty (kept as a native
  dynamic import in the CJS bundle).
- scripts/native/native-deps.mjs: register node-pty — package.json + lib
  JS + per-target binding (linux: source-built build/Release/pty.node
  via a new ensureNativeBuild hook running the package install script;
  darwin/win32: prebuilds incl. spawn-helper and conpty/winpty helpers).
- scripts/native/assets.mjs: run ensureNativeBuild hooks and record the
  executable bit in package manifests so spawn-helper survives SEA
  extraction.
- src/native/module-hook.ts: redirect the ESM resolution of 'node-pty'
  (module.registerHooks) to the extracted native-asset package; the CJS
  Module._load patch cannot see native dynamic imports.
- src/main.ts: install the hook on the exec-server light path too (it
  bypasses cli/main.ts), behind a dynamic import to keep the guarded
  static import graph light.
- scripts/native/check-bundle.mjs: allowlist the external node-pty
  specifier.
- scripts/native/smoke.mjs: spawn a real tty through the exec-server
  protocol and assert output + exit code, gating all six CI targets.

* chore: add changeset for standalone local terminal fix

* fix(agent-core-v2): degrade resume when the bound remote environment is unreachable

Resume and restore attempted to connect the persisted remote environment
before selecting the session controller and rejected the whole resume
when the target was unreachable, leaving no working recovery entry
(REST reconnect/switch and the /environment dialog all go through
resume). A connect failure now logs a warning and loads the session
with the binding kept: the controller falls back to the local carrier
and the first tool call reconnects on demand.

* feat(node-sdk): validate the local workDir before registering a workspace

createSession and the session-less workspace queries (listWorkspaceSkills,
suggestFiles, getWorkspaceTrustInfo, trustWorkspace, listWorkspaceMcpServers)
silently registered a missing or non-directory root as a workspace because
the engine's createOrTouch swallows stat failures. They now stat the local
root first and reject with fs.path_not_found, the same code the
POST /workspaces route returns (40409); a file-root regression test pins
the REST side.

* docs: align remote environment resume and reconnect semantics

The reconnect reference and the guide described the overturned
intermediate state (no reconnect at resume, tool calls fail until an
explicit reconnect). The final semantics: resume tries the restored
binding once and loads degraded with the binding kept when the target
is unreachable, and the next tool call retries the connection on
demand; the two pending changesets are rewritten to match.

* feat(remote-exec): replace executor auto-install with detection and install guidance

Connecting to a remote environment no longer downloads or copies the
executor binary. A missing or timing-out executor fails the connect with
per-launcher install guidance; a too-old executor fails with upgrade
guidance. When an artifact locator and client version are configured, the
failure path probes the target (uname + remote $HOME) and locates the
release artifact, so the guidance prints ready-to-run commands (curl +
scp/docker cp + chmod/mv) naming the concrete URL and pinned sha256;
tilde-prefixed remoteBin values resolve against the probed home, with a
"$HOME" runtime form as fallback. Probe or locate failures degrade to
generic release-CDN wording, and command launchers always get the generic
form. Guidance generation never masks the original handshake failure.

executorInstaller.ts/installTrigger.ts are replaced by
executorDetect.ts/connectGuidance.ts; the autoInstall/installFetch
factory options are removed and installRunner is renamed probeRunner.

* feat(remote-exec): add a pinned-hash verify step to the executor guidance

The concrete install/upgrade commands now verify the downloaded binary
against the manifest's sha256 before it leaves for the target
(sha256sum/shasum per the local platform), keeping the removed
auto-installer's pinned-hash discipline in the manual flow. The docker
context in the printed commands is shell-quoted.

* fix(agent-core-v2): keep environment-bound tools callable across on-demand reconnects

An idle-reaped or dropped remote environment is replaced in the registry
by a pending placeholder. The tool activation service treated the
placeholder as unavailable and unregistered Bash/Write/Edit/Grep/Glob/
Agent, so the next call failed with 'Tool not found' instead of
reconnecting. environmentAllows now also admits environments that expose
an on-demand connect().

Once the tools stay registered, their generation guard misfired: it was
resolved against the placeholder's generation and the self-reconnect
swapped in the ready generation, producing a spurious 'Environment
changed before execution' error. The new pinnedGeneration helper pins a
generation only when the resolve-time environment could actually serve
an acquire, so the self-reconnect path adopts the connected generation
while a genuine concurrent environment switch is still rejected.

* chore: add changeset for environment tool reconnect fix

* feat(remote-exec): share executor connections across workspaces via an app-level pool

One connection per declaration fingerprint: RemoteConnectionPool (factory
singleton) hands out refcounted handles so N workspaces targeting the same
remote share one bridge, one exec-server, one handshake. Idle reaping moves
to the pool: a connection is destroyed only after every workspace holder
stayed idle for the TTL (min over conflicting declarations, 0 = never wins),
so one workspace going idle no longer reaps a connection another workspace
is actively using. DeclaredEnvironmentRecord keeps a pool handle instead of
the connection; declaration resolution and trust checks stay per workspace;
ephemeral environments stay out of the pool.

Also add the F12 half-open detection: RemoteEnvironment pings
environment/status every 30s, reusing the 60s control-call timeout so a
wedged executor (e.g. docker exec without ServerAlive) flips to
disconnected instead of showing ready until every business call times out.

* chore: add changesets for the remote connection pool and half-open detection

* feat(remote-exec): coordinate reconnects pool-wide and vote on idle reaps

A reconnect from any workspace now replaces the pooled connection for
every workspace bound to the same target: the pool supersedes the current
connection (its version guard rejects stale in-flight installs), drives
one factory run that concurrent replacers join, and broadcasts the
replacement to every holder. Each workspace view swaps to the new
connection with its fresh generation, so turns pinned to the old
generation fail through the registry drain and the disposed connection —
the same shape as a connection drop, only triggered from another
workspace. The replaced connection is disposed once every view settled,
keeping the old generation's drain grace. A view the broadcast has not
reached yet catches up to the pooled connection instead of forcing
another replacement.

Idle reaping becomes a two-phase vote: after every holder stayed idle for
the TTL, each holder drops its view and votes; a lease landing in the
reap window vetoes the reap and the connection survives — the pre-pool
second-chance abort — while views already dropped rejoin on their next
connect.

Interfaces are unchanged: kap-server's reconnectEnvironment and the TUI
/environment dialog drive the same connect path, and ephemeral
environments stay out of the pool.

* fix(agent-core-v2): root remote stdio MCP cwd in the target environment

A stdio MCP server bound to a remote environment with no configured cwd
was spawned with the carrier's local workspace path as its remote working
directory, so the remote process start rejected the nonexistent path and
every such server failed to connect. Resolve the spawn base per entry:
local targets keep the workspace-rooted defaultCwd, remote targets use
the target environment's own host.cwd with host.homeDir as fallback.

* fix(remote-exec): re-validate the holder set after the reap vote

An acquire landing mid-vote joined the still-installed entry and was
invalidated without ever voting, stranding its record on a dead entry
(handle.connection reading undefined, TypeError on every reconnect).
Reap now aborts when the holder set gained a member during the vote;
holders that left mid-vote are safe to proceed without. Defense in
depth: a record whose handle reads back a dead entry falls through to
the acquire path instead of treating it as a live lease.

* fix: chunk large remote readBytes and dispose tracked handles on terminal/MCP close

* test(agent-core-v2): give the mcpManagement probe fixture a valid host homeDir

The probe of a non-local environment_id spawns the stdio server at the
target environment's host.cwd ?? host.homeDir since 3692c827, but the
suite's FakeEnvironment kept the default homeDir /home/fake, which does
not exist on disk, so the real HostProcessService spawn failed and the
probe reported success=false. Point the fixture's homeDir at the real
temporary home, mirroring the client-stdio harness.

* fix(nix): add python3 to the kimi-code build inputs for node-gyp

node-pty ships no Linux prebuilds, so the SEA asset step source-builds
it with node-gyp inside the nix sandbox. node-gyp discovers a Python
interpreter through PATH and the sandbox had none, failing the build
with 'Could not find any Python installation to use'.

* fix(nix): point node-gyp at the store Node headers for the offline sandbox

node-gyp downloads the Node headers from nodejs.org unless nodedir is
set, and the nix sandbox has no network, so the node-pty source build
died with EAI_AGAIN. Export npm_config_nodedir as the same nodejs the
derivation builds with; its out output carries the full header set
under include/node (nixpkgs installs the node-gyp headers there).
nodedir is the root containing include/node, not the include dir.

* fix(agent-core-v2): resolve workspace paths with the bound environment and preserve remote additional dirs

R1: workspacePaths helpers now take the bound environment's path
semantics (EnvironmentPath) instead of host-native node:path, so a
Windows host no longer mangles POSIX paths of SSH/Docker targets.
AgentWorkspaceContextService derives the semantics from the active
environment (falling back to host semantics when no environment is
inspectable), and SessionWorkspaceContextService stops re-resolving
already-absolute environment paths with node:path.

R2: AgentEnvironmentService.workspaceRoots() no longer drops the
session-state additional dirs for non-local bindings, so remote
workspace.additional_dir roots stay usable.

* fix: environment path semantics for file history and bounded remote readText

fileHistoryService resolved and case-folded capture paths with host path
math, so cross-environment subagent captures were mangled against the
host workDir and case-folded by host rules; readCurrent, pathKey, and the
comparison key now use the capturing environment's path semantics (host
semantics only as fallback when no environment is inspectable).

RemoteFileSystem.readText issued one unbounded fs/readFile, failing for
files over the 32 MiB whole-file limit; it now reads bounded ranges until
EOF, same as readBytes.

kap-server fs routes fake IWorkspaceDirs/IWorkspaceInstanceManager with
as-unknown-as casts that are redundant since the consumers declare
minimal parameter shapes; the fakes are now typed as those shapes.

* fix(agent-core-v2): serialize env switches, guard generation replacement, and root local hook/MCP/rg spawns locally

- change_environment now counts a same-name in-flight call as foreign, so
  parallel switches in one turn conflict and serialize instead of
  committing in async completion order (#11)
- program reconcileGeneration drops and retires the previous generation
  when its replacement cannot be built, so new sessions fail fast instead
  of reusing a draining controller; registry change events drive the
  retry (#12)
- session-overlay stdio MCP entries with environment_id "local" spawn
  with the local workspace root rather than the session cwd, which may be
  a remote path (#14)
- the Grep rg bootstrap probes (--version / cached / chmod) spawn in the
  session workspace directory instead of the executor default (#17)

#13 was already fixed on main by 7cd157ba7 (M41): every hook trigger
passes the session local cwd and failures surface warn-once; verified by
the existing externalHooks suites.

* fix: tighten remote environment security boundaries

- command launchers no longer forward the host's full process.env to the
  executor; the child gets a minimal whitelist (PATH/HOME/LANG family)
  plus the declaration's literal env, so LLM keys stay off the launcher
  process and everything spawned through it
- ssh/docker launcher operands are validated (a leading '-' host or
  container is rejected as an option-injection vector) and the ssh
  remote command is shell-quoted against remote re-parsing
- server notifications are field-validated and dispatched inside a
  try/catch so a malformed process/terminal frame can no longer crash
  the host process
- project-scope environment declares now require a trusted workspace on
  both the REST and node-sdk paths, and the global-scope duplicate check
  rides the config service's compare-and-swap so a concurrent declare
  fails instead of silently overwriting
- the SDK config schema gains the [environments] domain, so
  parseConfigString/getConfig/setConfig no longer strip it

* chore: add changesets for launcher validation, frame guard, and config schema

* fix: environment binding correctness across REST, approvals, acp, and attachment staging

- kap-server POST /sessions accepts environment_id/environment_cwd and
  binds the new session's main agent to the declared environment,
  surfacing undeclared ids as 40001 and connect failures as 40926
- approval panel badge resolves the environment of the agent that
  raised the approval (subagents included) instead of always showing
  the main session binding
- kimi acp rejects a root-level --environment loudly instead of
  silently ignoring it
- prompt media staging removes remotely staged attachment files when
  preparation fails, including partial writes; files staged by earlier
  prompts are left untouched

* fix: reclaim remotely staged attachments on pre-enqueue prompt failures

PromptMediaPreparation gains discardStaged(), which removes the staged
attachment files recorded during preparation in addition to the daemon
file-store ids discard() already reclaims. The two pure-failure route
call sites use it: the prompts route's !enqueued branch (setModel /
setSessionDisabledTools / promptWithSkills / submit throwing after a
successful resolve) and the skills route's activate() catch. Success
paths keep calling discard() only — staged attachments must survive
for the turn's Read tool calls.

* chore: add changeset for acp --environment rejection

* fix(remote-exec): bound output backpressure, cancel timed-out starts, reap orphan groups

- client process output honors push() backpressure via a new process/flow
  notification: the executor pauses only the stalled child's streams, so an
  unread flood stays bounded without head-of-line blocking call responses
  (advertised through the processFlow capability for old executors)
- process/terminal start timeouts now cancel the late spawn: the client
  replays process/terminate for the processId, and the server refuses starts
  whose terminate overtook them on the control lane
- terminateAll also kills groups whose leader exited and aged out of the map,
  so detached descendants no longer escape the shutdown
- the stdin write chain always settles and retries a timed-out write with the
  same writeId (server-side dedup makes the replay exactly-once)
- fs writes are sliced into bounded 1MiB chunks (first chunk keeps the mode,
  the rest append), so payloads above the 64MiB frame cap succeed
- readdir results that exceed the entry cap now carry an explicit truncated
  marker instead of being silently cut
- remote terminal spawn passes TerminalSpawnOptions.env through
- the glob tool's rg probe spawns in the session workspace cwd

* refactor(remote-exec): drop idle connection reaping

Pooled remote connections now live for the app lifetime, matching the
codex exec-server model: a connection is torn down only when the last
workspace holder lets go, and a dropped one reconnects on demand.

Removes the idleTtlSeconds declaration field, the pool's two-phase reap
vote, and the registry idleness event chain whose only consumer was the
reaper. Lease, drain, and tracked-resource bookkeeping stay unchanged.

* fix(kimi-code): keep remote connection startup responsive

* refactor: prune dead code from remote environments

- environmentUnitHost: drop the update path and the provide/imports/local
  channels (no production callers); provider manifests narrow to root-only
- workspaceFs rgLocator: drop the unused rgUnavailableMessage copy
- remote-exec: runExecServer keeps only version; drop the unreachable
  capabilities/stderr-limit options, dead subpath exports, and re-export
  shims; the standalone bundle reports a fixed version
- agent-core-v2: drop the unused environment entry types, provider context
  metadata, workspace-view generation, and the sessionControllerGeneration
  getter
- TUI/SDK: drop the unread FieldDef.required flag, the dead reconnect
  guard/parameter, and the unread environment DTO fields

* fix(remote-exec): give the terminal connection-drop test its own connection

* fix(remote-exec): realpath the defaultCwd expectation for the macOS /var symlink

* fix(scripts): resolve node-pty from remote-exec after packages/services was removed

* feat(agent-core-v2): default agent environment tools to off

The change_environment/connect tools and the Agent environment parameter
are now opt-in via KIMI_CODE_EXPERIMENTAL_AGENT_ENVIRONMENT_TOOLS=1 or
[experimental] agent_environment_tools = true. The rest of the remote
environments feature stays on by default.

* fix(remote-exec): drop unused shQuote import

* fix(agent-core-v2): wire session controllers to the local host filesystem

Program.createSessionController passed the bound environment's fs into
SessionLifecycleService's hostFs slot, but every hostFs call site there
operates on local session dirs. Deleting or forking a remote-bound
session could delete same-named paths on the remote host or fail with
NOT_FOUND. Drop fs from ProgramSessionControllerInput and inject the
app-scope IHostFileSystem at the construction site instead.

* fix(remote-exec): keep streaming descendant output after retention eviction

pump treated a missing map entry as host disposal, so once the exited
retention timer evicted the leader's entry, output from still-running
detached descendants was silently dropped. Only drop output for entries
removed while still running (spawn failure or shutdown); an exited entry
that aged out keeps streaming until its streams close.

* refactor(remote-exec, agent-core-v2): prune speculative machinery from the remote-environment stack

Removes mechanisms whose justification evaporated with the idle-reap
removal or that never had a production consumer:

- turn-level generation pinning and the turn lease in
  AgentEnvironmentService: a mid-turn reconnect broadcast failed every
  later call of the turn instead of letting new calls ride the new
  connection; per-call approval-window generation checks stay
- process/read pull channel with per-process replay buffers, seq
  numbering, and the long-poll timeout exemption: no client consumed it
  (notifications only), and mid-session reconnect is a declared non-goal
- environment unit host's unit-level update, cross-unit provide, and the
  imports/local DI dimensions: never called in production; transactions
  shrink to prepare/commit
- registry idleness bookkeeping left over from the reap removal, the
  unreachable 'starting' write retry, the expired-id set and unknown-id
  disconnect (late responses are now discarded like codex does), the
  handwritten notification-params validation (the dispatch try/catch
  already contains malformed frames), and the tuning option bags (a
  plain exitedRetentionMs test seam stays for the retention tests)

The 7-field host fingerprint behind machineIdentityChanged stays: ACP
binds every session to a same-machine environment, so suppressing the
switch reminder there is the standard flow, not an edge case.

* refactor: simplify remote environment ownership and execution

* test(remote-exec): require native pty for terminal resize regression

* test: trim duplicated remote-environment test coverage

Remove redundant cases that repeat the same branch at multiple layers:
drop the second stub-wire undo harness in environmentBindingService tests,
the six permutations of the in-flight conflict guard, node-sdk cases that
replay kap-server REST scenarios one-to-one, factory-level executor
guidance cases already covered by connectGuidance tests, and repeated
fixtures/dialog navigation blocks. Merge single-assertion permutations
into their sibling cases; no behavior coverage is lost.

* fix(remote-exec): preserve complete directory listing semantics

* refactor(cli): share SDK host lifecycle in print mode

* refactor(remote-exec, agent-core-v2): simplify remote environments

- drop the periodic status ping and the control-call timeout category:
  ssh brings ServerAlive, docker/command bring EOF, and a stalled
  business call already fails on the unified request timeout
- shrink executor failure guidance to classification plus static
  per-launcher wording: no more remote uname probe, CDN manifest fetch,
  or generated install scripts (artifactLocator and the guidance
  plumbing are gone; the e2e driver inlines its own manifest fetch)
- drop the --environment startup announce flow: the first prompt simply
  waits for the lazy create like any other message; the background
  pre-create and the synthetic connecting slot stay
- drop project-level environment declarations end to end: the
  .kimi-code/environments.toml file, its trust gating and trust-prompt
  preview, the declare scope (global is the only write target), the
  provider's project file watch, and the registration wait

* refactor: reconnect remote environments without replacing identity

Drop EnvironmentUnitHost and reconnect by swapping the inner connection
on a stable environment object. Temporary connect environments can retry
in process. Remove unused environment/status, process/start arg0,
processFlow capability negotiation, and degraded/draining statuses.

* chore: consolidate changesets into one

* chore: restore changesets owned by main

* fix(remote-exec): forward captured fs to the current connection after reconnect

Program generations capture environment.fs once when the generation is
built. With identity-stable reconnects the captured RemoteFileSystem
pointed at the closed connection, so instruction, skill, profile, and
project-config reads kept failing after a reconnect. Hand out one stable
forwarding IHostFileSystem per managed environment that resolves the
current inner connection on every call.

* fix(remote-exec): allow empty process arguments after argv[0]

The local process service accepts empty argument strings, but the remote
executor rejected the whole argv, so configs such as an MCP command with
an empty argument worked locally and failed remotely. Only argv[0] must
be non-empty.

* fix(remote-exec): expire historical process groups

* refactor: fold remote-exec into agent-core-v2 as src/remote

The remote execution protocol, client, and standalone executor are an
implementation detail of the v2 engine rather than a public package:
keep them behind agent-core-v2's export map (./remote, ./remote/server)
so TypeScript types and module boundaries do the isolation a separate
package used to, without the release and workspace overhead.

* refactor(agent-core-v2): fix human-kernel import boundary violations

lint:imports flagged four violations where v2 code reached into human
implementation modules (or the reverse). Move the shared vocabulary to
the kernel side so the dependency direction stays human -> v2 only:

- promptDisplayTextFromContentParts joins origin.ts; the media path tag
  family and image caption extraction become llm/media vocabulary
  modules, re-exported by agent/media for existing consumers
- the history entry types and factories move from agent/turn to
  agent/historyEntry; turn re-exports them for the kernel internals
- errorStatusCode moves from llm/errors to llm/errorStatus

* fix(agent-core-v2,cli): open resumed remote sessions without waiting for the environment connect

* feat(cli): animate busy spinners in environment and resume dialogs

* fix(agent-core-v2): keep settled-result field name as reason under oxlint auto-fix

* test(agent-core-v2): regenerate tool-list snapshots for default-off environment tools

* fix(remote): keep exec-server to filesystem and piped processes

Interactive terminals stay local. The executor no longer allocates a pty, and the SEA build no longer packages or source-builds node-pty.

* chore: restore the node-pty permission script path

The resolve-path rewrite followed a temporary remote-exec package and is unrelated to remote execution.

* refactor: prune speculative layers and dead code from remote environments

Remove the InnerForwardingFileSystem forwarder and the PENDING_* fake
host/path/workspace placeholders (Environment.host/path/workspace are now
optional and pending environments return undefined), drop the dead
capabilities handshake field, ProcessFlowParams, ProcessManagerHost,
ProcessStartResult.processId echo, ConnectionCloseInfo.error, the
clientName/generation options nobody overrides, and the duplicated
describeEnvironmentEntry/environmentStatusAllows parameter/standalone
environment factory/inspectAgentEnvironment/get() accessor.

Consolidate the five copies of the environment error mapping in kap-server,
the triplicated environment temp-dir target helper, the duplicated
splitLinesKeepingTerminator and rgLocator helpers, the footer's hand-rolled
SpinnerTicker, and the TUI environment manager's identity mapper, dead
generation guard, and double options assembly.

* chore: match the node-pty permission script to main

The catch rename was an oxlint autofix, not part of remote execution.

* fix(tui): keep the current environment when /new starts a session

/new clears the conversation, not the workplace. Carry the live binding,
including an explicit switch back to local. A session-less /new still uses
--environment.

* refactor(remote-exec): share one connection per environment id

Drop the connection pool. Each environment id keeps one executor
process for the whole process; workspaces register views and the
last view closes it. connect() while ready is a no-op. Explicit
reconnect is disconnect then connect, process-wide for that id, and
does not change a view's generation. A different id stays up.
Temporary connect does not join the table.

* test(tui): type the createSession mock so call args are inspectable

* test(cli): align session mocks and exec-server handshake with current protocol

Session mocks gain getEnvironment/listEnvironments so /new can inherit
the live binding, and the handshake test drops the capabilities field
removed from InitializeResult.

* fix(tui): drop the remote environment disconnect transcript notice

The footer already shows the disconnected environment and its failure reason.

* fix(tui): show connecting feedback while /new waits on a remote environment

/new on a remote binding awaits the environment connect inside
createSession (the engine builds the controller on the remote root),
so a disconnected remote left the TUI silent for the whole handshake.
Mirror the startup pre-create treatment: a synthetic connecting
environment slot drives the footer spinner and a transcript status
names the target while creation is in flight, skipped when the slot
already shows the target as usable (a live pooled connection makes
creation fast). The real slot returns via refreshEnvironmentSlot once
the session exists; on failure the old session's slot is re-synced, or
dropped when session-less.

* fix: reduce remote session creation delays

* refactor: manage execution environments at app scope

* fix: align print and wire views with app environments

* fix: avoid repeated remote skill scans

* fix(agent-core-v2,cli): wait for the environment connect when resuming a remote session

A resumed remote-bound session previously opened on the local controller
while the connect was still in flight, so its skills, instructions, MCP,
and dirs came from the local environment for the whole session lifetime.
Resume now awaits the connect like /new does, falling back to a degraded
open with the binding kept when the target is unreachable.

* chore: drop the remote environments changeset

The removed runtime API shipped with the published SDK 0.20.0, so the
minor entry was wrong; versioning for the feature is handled outside
changesets.

* feat(agent-core-v2): drop the agent environment tools and subagent environment parameter

Remove the experimental change_environment/connect tools feature, the
system-prompt environments section, and the Agent tool's environment
parameter so subagents always inherit the caller binding.

* feat(agent-core-v2,acp-server): narrow the environment binding service to creation-time binding

Remove set/switch/connectAndSwitch/connectAndSwitchInTurn, the plan-mode
and in-flight guards, the undo participant, and the environment-switch-ask
permission policy. The remaining bind(id, cwd) serves creation-time binding
(ACP session bind); the EnvironmentSetBinding op stays durable and
replayable but is no longer undoable.

* feat(kap-server): drop the environment switch, reconnect, and declare routes

Keep the read-only GET environment binding and GET environments list
endpoints; phase 1 binds environments at session creation only.

* feat(node-sdk,klient): drop the environment switch, declare, and suggest surfaces

Keep the read-only getEnvironment/listEnvironments session APIs; phase 1
binds environments at session creation only. The klient wire contract
shrinks to agentEnvironmentBindingService.current.

* feat(kimi-code): drop the /environment manager and remote mention completion

Phase 1 binds environments at startup (--environment) or session creation;
the in-session manager, cwd/add dialogs, remote @ completion, and the
undo-time binding refresh move to the follow-up change phase.

* fix(agent-core-v2): repair the subagent spawn and swarm test after the binding narrowing

* test(agent-core-v2,kap-server): regenerate manifests and rebind environment tests at session creation

* docs(node-sdk): drop removed environment switch methods from the client overview

* refactor: prune dead environment code and simplify remote protocol

- remove phase-2 leftovers with no production callers: ephemeral connector,
  declare(), EnvironmentRegistry.replace(), agentEnvironment.reconnect(),
  MCP envVars, and fileHistory cross-environment capture
- simplify the remote protocol: exempt process/write from the per-request
  timeout and drop the writeId retry/dedup chain, merge process/terminate
  into process/signal with TERM->KILL escalation (keeping the
  terminate-before-start tombstone), drop the initialized notification and
  the client-side in-flight queue
- launch the docker executor via sh -c like ssh and delete the tilde home
  probe and its local-runner plumbing
- unify {environmentId,cwd} key encoding behind environmentBindingId
- fail session creation explicitly when the environment is unavailable
  instead of silently falling back to the local controller
- planService reuses environmentTempTarget with a local-only tmpdir fallback
- sync the remote README and affected docs

* refactor: simplify remote environment phase one

* refactor: prune unused environment surface and deduplicate helpers

- drop protocol fields no client sends (read/write followSymlinks, createdAtMs, pipeStdin) and their server branches
- remove product code only referenced by tests: Program.suggestFiles, Program.onDidChangeTrust, MCP originalsDir, kap-server resolveWorkspaceInstance, unused SlashCommandHost/KimiTUI members
- merge duplicated logic: connect+acquireWhenReady into EnvironmentRegistry, prompts/skills media targets into environmentMediaTargets, realpath-existing-prefix into one helper, decodeBase64 reuse, single rg target mapping, node-sdk declarations via IEnvironmentDeclarationService
- simplify fireAndForgetTrigger, sendWrite, inline launcherLabel and environmentEntryType, drop redundant exports

EnvironmentRegistry.acquireWhenReady now triggers connect like the agent-level path already did; the two providerFactory tests pin the immediate post-failure error via acquire() instead.

* fix: accept runtime_id as a deprecated alias for environment targeting

Released clients and mcp.json entries that only set runtime_id otherwise silently fall back to local after the runtime-to-environment rename. Cover MCP stdio config, terminal creation, and the session fs/search/suggest/download routes; environment_id wins when both keys are present.

* fix: validate local workspace roots and await provider attach before session use

ISessionManager.create again rejects a missing or non-directory workDir with fs.path_not_found for local bindings; remote bindings keep deferred root validation, and createOrTouch stays lenient.

SDKRpcClientV2 awaits the remote environment provider attach before create/resume/fork/reload and temporary resume, so declared or persisted remote environments no longer report unavailable or fall back to a local controller based on registration timing.

* refactor: persist environment binding in session meta

Cold resume reads the binding from state.json instead of scanning the
agent wire. An unregistered or unreachable remote binding fails the
resume instead of opening a local controller. Provider attach is part
of EnvironmentService.ready, so create and resume wait in one place.

* refactor: prune speculative environment surface and duplicate validation

* refactor: drop environment switch notification leftovers from the binding service

* fix(agent-core-v2): satisfy strict undefined check in compaction truncation

* fix(agent-core-v2): persist only declared environment bindings to session meta

* fix: keep MCP stdio executor rejection and the harness options type alias

* refactor: drop speculative scaffolding from remote environments phase 1

- remove task-output spill pinning/persistence (only meaningful once
  runtime rebinding lands)
- resolve the main-agent environment inside session lifecycle via a new
  ensureMainAgent create option instead of re-resolving declarations in
  the kap-server sessions route
- revert workspace trust onDidChange to a plain Emitter (no waitUntil
  consumer exists)
- drop unused TerminalSpawnOptions.env and the dead
  Program.sessionControllerGeneration getter
- inline single-use wrappers (suggestFiles helpers, originals/spill
  targets, locateSession options object)
- reuse environmentStatusSchema in the REST environment protocol
- simplify the exec-server entry's exit handling

* test: remove redundant and dead environment test coverage

- drop tests whose turn-event fixtures no longer reach the binding
  service (it never subscribes), and their duplicated mid-turn cases
- drop tautological replace-vs-timer races and tests fully covered by
  stronger pins elsewhere (guidance messages, pending-drain, initialize
  timeout, etag/range, node-walk fallback)
- merge parallel bashTool/globTool test files into the existing tool
  test files per repo convention
- collapse identical expensive e2e runs (argv spellings, transports)
- assert overlay resource grouping instead of lease.track call counts

* feat: add environment cwd and remote mention completion

* fix: harden remote environment compatibility and recovery

* fix: preserve surrogate pairs in compaction truncation

* fix: keep plan files local and report usable output paths

* fix: keep remote session artifacts local and readable

* feat: support trusted project remote environments

* feat: add protocol-level liveness ping for remote connections

* test: prune redundant remote-environment test cases

* fix(agent-core-v2): keep surrogate pairs intact in compaction tail truncation

* chore: trigger pkg.pr.new preview publish

* fix(tui): render welcome above startup progress rows and skip stale session-less notice

* fix(node-sdk): preserve environment ids in TOML config transform

* docs: fix --environment example to a working argument order

* test(agent-core-v2): add runtime.set_binding to the v1 wire vocabulary

* fix(vis): cover runtime.set_binding in wire record rendering

* fix(agent-core-v2): expand launcher remoteBin home via the remote shell $HOME

* fix(agent-core-v2): resolve ~ tool paths against the reconnected environment host

* fix(agent-core-v2): disable local file watchers for remote workspace bindings

* perf(agent-core-v2): scan remote frame newlines with indexOf and share one TextDecoder

* perf(agent-core-v2): concurrent lstat in fs list probes, offset window reads, folded head sample

* fix: address remote environment review findings

* test: update replay harness for environment preview

* fix: resolve remote skills and ripgrep across client platforms

* refactor(agent-core-v2): keep remote workdirs out of Program

- Program returns to one local generation per workspace; remote project
  content (fs, git, AGENTS.md, project skills/profiles) is built per session
  through a workdir factory and disposed with the session.
- SessionLifecycleService connects the target, validates the cwd, persists
  environmentId/environmentCwd in session meta at creation, and reads them
  back on resume; SessionManager only resolves the creation environment and
  routes to one controller per workspace.
- Remote environments expose fs/process facades that survive reconnects.
- Drop project-level .kimi-code/environments.toml with its trust gating,
  conflict detection, and environmentProject provenance; declarations come
  from the user [environments] config only.
- Agent environment binding keeps a single replayable state key and no
  longer writes session meta.

* refactor: serve session fs from the session workdir

- Seed each session with ISessionWorkdir (its environment and fs service);
  remote sessions get their session-owned workdir fs, local sessions the
  workspace fs. Remove createEnvironmentFs and its fabricated workspace
  context.
- kap-server session fs actions and downloads use the session's own
  environment; workspace and root suggest/search routes run locally through
  a private rooted fs. Drop the runtime_id / environment_id parameters from
  these routes.
- SDK suggestFiles takes a sessionId instead of an environment binding; the
  TUI completes remote @ mentions through the live session.
- kimi-inspect stops sending environment_id; docs updated.

* refactor: simplify remote environment state handling

* fix: correct AGENTS.md reload paths for remote sessions

* fix: fail fast on invalid environment configuration

* refactor: drop unused runtime compatibility

* fix(sdk): preserve lazy model binding for local sessions

* feat(agent-core-v2): append the executor invocation for command environments

Command environment args now only describe how to reach the target; the
launcher appends `<remoteBin> exec-server` (remoteBin defaults to
~/.kimi-code/bin/kimi) unless the args already invoke exec-server. The
remoteBin is part of the declaration fingerprint and the missing-executor
guidance names it for every launcher type.

* test(tui): stub editor replacement disposal in fullscreen hosts

* fix(agent-core-v2): expand remote additional dirs against the target home

* chore: drop the unused standalone executor build

* fix: reject bash when the approved environment generation changes

Keep KimiHarnessRuntimeOptions as a deprecated alias.

* refactor(agent-core-v2): seed every session from one workdir

Local sessions alias the shared generation. Remote sessions still open their own view, and both paths build that view through one constructor.

* fix(agent-core-v2): inherit the session environment when creating agents

* fix: keep local session cwd and remote shutdown compatible

Seed the test harness with the session workdir the agent lifecycle now requires, and keep an explicit local cwd, the user's GIT_TERMINAL_PROMPT, the remote status-line directory, and command-launcher PATH resolution.

* feat: add SSH password authentication fallback

* refactor(agent-core-v2): move remote environment declarations under remote/

The target-neutral environment layer imported the remote client's launcher
module, and the ssh/docker/command schema lived next to the Environment
contract. Move the declaration schema, the [environments] config section and
entry info into remote/declaration, fold launcher conversion into
remote/client/launchers, and enforce the direction in check-import-boundaries:
environment/ never imports remote/, and remote/declaration never imports the
remote client or executor.

* refactor(agent-core-v2): build every session workdir through one cached path

Local and remote sessions now acquire their project context through the
same Program workdir path, keyed by (environmentId, cwd) and shared by
reference count; the workspace root is one resident entry. Workdirs on
targets that cannot be watched refresh whenever a session acquires them,
and Program.reload refreshes every live workdir.

Project agent profiles register under their workdir key, so remote
sessions no longer see the launch directory's project agents, and they
are read only where workspace trust applies (local in phase 1). Only an
explicitly bound cwd is validated; the implicit workspace root keeps its
deferred validation.

* test: keep scoped filesystem parent metadata accurate

* fix: preserve host cwd for remote sessions

* refactor(agent-core-v2): move program workdir cache into ProgramWorkdirs

* fix: restore retry codes and reverse token scan after the main merge

The merge wrote a Set into the array-typed retry table and switched the
reverse token scan to codePointAt. Both parents kept the array and
charCodeAt. Print cleanup can dispose the test app scope, and the node
fallback grep probe rejects the cached rg binary.

* revert(agent-core-v2): drop out-of-scope human boundary refactor

Restore the human module and its import sites to the base revision; the import-boundary cleanup is unrelated to remote environments and will be handled separately.

* refactor(kimi-code): load the exec-server through the SDK

Add a light @moonshot-ai/kimi-code-sdk/exec-server subpath that re-exports the engine's remote/server entry, so the CLI keeps consuming core only through the SDK and the app-level exception is dropped.

* refactor(agent-core-v2): serve exec-server…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants