kimi-desktop 0.1.6: separate reasoning effort and an optional context input budget for the primary and secondary roles.
The change (f07e7f4a..1d14a185, since the round-6 approval):
- The settings page and API save `<role>ReasoningEffort` and `<role>ContextTokens` for each role. Only efforts and context limits the catalog publishes are offered; an unknown limit allows no custom budget.
- Inference drops Kimi's top-level `thinking`, `reasoning` and `reasoning_effort`, and sends the chosen effort, or none for the provider default. Kimi's native menu aliases no longer choose the model.
- A custom budget counts a copy of the request through magpie's `/v1/messages/count_tokens`. Over the budget gives 400 `context_length_exceeded`; a failed count gives fixed 503 `context_count_unavailable`. No generation is sent in either case. Without a budget, nothing extra is sent.
- Role-scoped worker profiles (`v2:[model, role]`) tell primary from secondary even on the same model. Older roleless profiles keep their binding and use defaults.
- 1d14a185 removes blank lines only.
Run at 1d14a1859f63fd4bb512d492d1de419ad3e6c79a on mote (macOS, Bun 1.4.2, HOME/TMPDIR/XDG in the run's own folder):
- `bun test` in packages/kimi-desktop: 626 pass, 0 fail, 29 files.
- `bun scripts/check.mjs kimi-desktop`: exit 0.
- 14 hand breaks, each red in the package suite:
- drop `applyReasoningOptions`;
- strip thinking fields only when an effort is set;
- drop the budget check, or make it `>=`;
- `useFresh` false, or without its model check;
- a legacy roleless profile treated as primary;
- a profile name without its role;
- no `registerRoles`;
- no `optionsMatch` in save;
- no `refreshLiveModelOptions`;
- count with `redirect: 'follow'`, or with no reply size limit;
- a 131072 fallback for an unknown catalog context.
- CI at the head: test and on-npm pass. The PR merges onto main f379bf90+ with no conflicts.
Not blocking, left for a follow-up:
- Each inference now reads connection.json (adapter.mjs:547) with no fallback to the live connection. An unreadable file turns every request into 502, even without a budget.
- The comment above `applyReasoningOptions` ("Preserve the legacy connection untouched…") no longer matches the always-strip policy.
33 KiB
Kimi desktop Work agent
Use the ordinary Kimi desktop application's local Work agent with a model selected in Magpie. This is not Kimi Code CLI, a Kimi subscription provider, or a way to spend Kimi Work subscription credits in other agents.
magpie plugin add @magpie-community/agent-kimi-desktop
Open and sign in to Kimi desktop. On Magpie's Agents page select Kimi, pick a model, and connect. The adapter waits for the local Work runtime to be ready and idle, then applies the connection without restarting either application. Use Kimi's Work page. Chat and cloud Claw are outside its scope. Kimi's native model menu remains visible; its selections do not choose the external inference model or reasoning effort. Configure those in Magpie. This package does not modify Kimi's application resources or install a custom model-menu patch.
Disconnect Kimi in Magpie to restore its original model service address. Existing conversations, login credentials, unrelated settings, and native model entries are preserved.
Primary and secondary models
Open the plugin's embedded Kimi Work models / Kimi Work 模型 page to choose the primary model. Selecting a secondary model opts in to role routing for new Agent tasks. An empty or absent secondary preference keeps native subagent behavior: the adapter does not install or enable the companion plugin or reload sessions for role routing, and native Agent schemas, history auditing and response calls pass through unchanged. Normal neutral alias cleanup still applies. The page shows saved preferences separately from their application status. Apply changes while Kimi is idle. Magpie's Agents → Kimi picker uses the same primary selection.
Only while a secondary model is selected and its profiles are ready, the bridge adds an optional model selector to the Agent tool declaration sent to the model:
primary: create an ordinary Work worker profile bound to the configured primary model.secondary: create an ordinary Work worker profile bound to the configured secondary model. This is the default only when bothmodelandsubagent_typeare omitted.native: keep the requested nativesubagent_typeand its specialized behavior.
For example:
请新建一个子代理处理资料整理,使用已配置的副模型,由主代理综合结果。
请让这个新建子代理使用已配置的主模型。
The actual tool argument selects the role; a prompt alone does not bind an arbitrary model ID. For new primary or secondary tasks, the bridge removes its model argument and replaces subagent_type with the selected ordinary worker profile, preserving the prompt, paths and other arguments. An explicit native subagent_type without model retains that profile and its restrictions. native removes only the selector and preserves the original type. Resume or fork retains an existing authenticated profile and model binding rather than selecting a new target.
Authenticated opaque call IDs retain the original selector for history auditing: the bridge restores explicit role choices only in its own verified assistant Agent history and leaves an omitted default omitted. The ID preserves native tool-result linkage and never selects the route; the role profile remains the model binding.
These ordinary workers declare general native tools (tools: ["*"]), disable Agent and AgentSwarm, and declare no subagents. They inherit the parent's native permission mode, and user-registered tools remain gated by their availability to the parent. Kimi's native permission guards still apply. The generated workers do not copy the specialized restrictions of coder, explore or plan; request a native type without model, or use model="native", to keep its native profile.
The role prompt contains an opaque random token authenticated by a local MAC. The token-to-model mapping and signing secret stay in adapter-state.json; generated profile text and role instructions contain neither the application brand, target model ID nor a reversible encoding of it. Binding state must be successfully persisted before profiles are published or plugin-control calls are sent. Profile names use a key-specific namespace, so rebuilding a key does not reuse another key's agent names. Only an authenticated section in system/developer text selects a binding and is removed before forwarding. Invalid, malformed or unknown identity there still fails with HTTP 409 agent_profile_unbound. With a saved routing key, quoted markers in user/assistant text, tool arguments/results and other fields are neutralized by removing the opening bracket from the reserved opening/closing tag prefixes; they never select a model or poison later requests. Shared instructions are refreshed and neutralized before profile authentication, so an AGENTS.md quotation cannot become a binding. A connection without a routing key performs no marker checks or neutralization; quoted content and the existing neutral alias cleanup retain their earlier behavior. Model routing and top-level thinking controls follow the plugin settings described below. The protocol's model field still names the selected model; user-authored brand or model text is not otherwise redacted. Every inference checks a bound target against the current gateway catalog; a temporarily missing or disabled target is refused without falling back to the primary.
Previously authenticated workers can retain their original allowed binding across model-preference changes while the native runtime has their profile. Clearing secondary schedules registration removal; a busy turn keeps its current confirmed schema until idle cleanup completes, then new role-tool translation is off. This does not promise that Kimi can resume a profile after its plugin has been disabled or its registration removed. Full native child compaction, fork and those resume boundaries have not been tested in this review revision.
The secondary preference is the optional secondaryModel field in ~/.config/magpie-kimi/connection.json. The primary model and gateway fields remain owned by Magpie's normal agent connection. Saving a changed primary runs the current host's official magpie kimi-desktop model magpie/<provider/model> command, preserving the host's selected model and disconnect bookkeeping. The command inherits the host environment; a plugin-private flag prevents that command's extra plugin host from starting another Kimi adapter. Automatic discovery checks the parent executable (ps on macOS, /proc on Linux, PowerShell CIM on Windows), then PATH. Discovered paths and their resolved targets must have the case-insensitive basename magpie (magpie.exe is also accepted on Windows); a shell or magpie-bun is not used. If discovery fails, including on Windows, set plugin option magpiePath to the current Magpie executable. An explicitly configured path permits a custom executable name. Connect Kimi in Magpie before using the model page.
When both selections change, the primary is saved first, then the secondary preference is merged into the fresh connection. A secondary save failure after a successful primary change is reported as a partial save; refresh the page to check the applied state and retry. The settings service listens on 127.0.0.1:3491; plugin option settingsPort can change that port. It uses a separate page-session credential and never sends the gateway or Kimi credential to the page.
If the configured settings port is temporarily unavailable, the existing adapter tick retries it without restarting the primary bridge or changing the selected models. Stable ticks keep the same settings service and page session. The launcher tries at 0, 3 and 6 seconds; if navigation still has not opened the service after 9 seconds, it shows a localized error and an in-page Retry button. Stopping the adapter waits for pending settings initialization and closes its listener.
When opted in, the package generates a companion plugin containing only kimi.plugin.json and agent Markdown files under ~/.config/magpie-kimi/native-model-roles. Its neutral ID is local-work-model-roles-<hash>. Kimi's existing local installPlugin / updatePlugin API receives {source}, copies it to <KIMI_HOME>/plugins/managed/<id> and registers it. The adapter enables it through setPluginEnabled and checks the cached, idle-session reload acknowledgements. Stable getPluginInfo probes are at least 30 seconds apart and skipped while busy. A transient or ambiguous failure keeps the last confirmed role schema; an idle confirmation of a missing or disabled plugin changes readiness. The manifest stays at 1.0.0, including local same-version updates.
Previously bound models have a retirement grace period: their bindings are deleted only after three consecutive successful catalog synchronizations report them absent and at least ten minutes have elapsed since the first absence. Failed fetches and cached ticks do not count. Absence counts and their start times are persisted with bindings in adapter-state.json, including across restarts. Actual retirement waits for an idle role-profile synchronization with verifiable registry provenance and unchanged owned source/managed snapshots, so token revocation and owned-profile cleanup stay consistent. A detected conflict defers deletion until it is resolved. A cleared secondary keeps its inactive cached bindings until the next valid opt-in; successful observations still update the absence record, without reinstalling the companion. A returning model clears its absence record and can use its original token again before retirement. During absence, requests for that binding still receive 409. Generated profile pruning uses the resulting retained binding set and requires matching ownership evidence; it does not grow indefinitely with every past model selection. Dot-prefixed entries in either source or managed agents directory are ignored, are not hashed or pruned, and do not cause conflicts. Other unknown files and edited generated files are preserved and report agent_profile_conflict. Registry ownership requires local-source, managed-root and exact declarative-manifest checks. Equivalent directory paths, including a parent symlink or junction, are compared by canonical real paths for existing directories rather than by an installation-drive assumption; the existing checks against a symlinked registry file or replaced managed root remain. Before enabling roles, another key's role-plugin ID or a foreign prefix-matching registration reports agent_profile_conflict without plugin RPCs or registry changes; it cannot silently coexist. The adapter leaves native profiles, application resources, Magpie core and SQLite untouched.
Normal cleanup for clearing secondary, disconnecting, or calling stop() verifies the saved companion's ownership, disables it with setPluginEnabled(false), waits for explicit session-reload acknowledgement, rechecks provenance, then calls removePlugin to remove its installed registration. Busy sessions, missing or failed acknowledgements and incomplete removal leave a persisted recovery obligation for the next idle tick or start. A lost removal reply is retried; a fixed native-not-found reply still requires reload confirmation before recovery completes. Reconnecting with secondary selected installs the source again when the registration is missing, even if a byte-identical managed cache remains.
Registration removal retains the managed cache, generated source profiles and adapter binding state. The inspected native removal chain removes the installed record and reloads contributions; it does not delete all generated files or uninstall the Magpie package. Catalog pruning remains the separate ownership-checked policy above. A missing disk record alone does not prove native removal: recovery checks native presence and saved source/cache ownership. Ambiguous or malformed replies keep recovery pending.
The synchronous exit handler cannot send RPC or remove the registration. It writes only the saved, verified companion registration's enabled field to false in <KIMI_HOME>/plugins/installed.json, using original-byte comparison and a private temporary file followed by rename. Unrelated entries and fields are preserved; conflicts are left untouched. Native-source inspection found no registry watcher, so disk false neither removes the registration nor immediately removes profiles already loaded in Kimi's memory. The plugin identity and pending phase remain in adapter state even when the helper fails or disk is already false. At the next idle recovery, a present plugin still receives setPluginEnabled(false), followed by checked session reload and registration removal. Only a fixed native-not-found reply plus reload confirmation can finish an already-removed obligation. This follow-up has native evidence for disable and registration removal; resume after either operation remains untested. Synchronous-exit and restart observations are separately listed in the compatibility record.
The adapter does not add native model definitions or secondary_model pools, and does not rewrite them in the background. An earlier Kimi 3.2.25 observation found queue dispatch rebuilding those definitions and dropping an added pool. The earlier review revisions were unreleased but had been run locally: existing state.secondary and state.secondaryPool snapshots therefore carry real restore obligations. Their ownership-recorded restoration path remains so removing the code does not strand old aliases or owned fields. A native TOML file this adapter never wrote does not acquire ownership or trigger a secondary reload. In-memory foreign snapshots protect values only around the adapter's own primary/menu RPCs. A byte-comparison conflict during restoration preserves the external edit and reports fixed kimi_config_changed, while allowing other primary-restoration work to finish. Later ticks retain that warning instead of replacing it with connected. Owned restoration does not save model/provider definitions or credentials. Legacy alias recognition and scoped historical Agent metadata cleanup support these recorded local review states.
Secondary profiles require a recognized native V2 kernel family; support is not pinned to a Kimi application version. A legacy or unknown family keeps the primary bridge available but reports secondary_model_unsupported_runtime for an explicit secondary preference. This follow-up was exercised in native Kimi 3.2.25 / build 3.2.25.22 with real Read calls, three child-role routes, clearing and disconnect/reconnect. The compatibility record distinguishes those results from the incomplete host-offline exit/restart confirmation, records the Magpie version change during that attempt, and lists source/protocol evidence and remaining native boundaries. Supplier arguments in native history are already translated, so they are not a raw pre-translation capture. Settings failure cases still use a VM. The cc9a023 turns and older pool/runtime results are historical records.
Reasoning effort and context input budgets
On the embedded Kimi Work models page, choose reasoning effort and an optional context input budget (counted/estimated) separately for the primary and secondary model, then save. Selecting the same model for both roles still permits different parameters. A blank reasoning choice uses Magpie/provider defaults; only efforts explicitly published by the model catalog are selectable. Fixed reasoning policies in Magpie's routing configuration take precedence. Unknown capabilities are not inferred from model names, and the historical 131072-token fallback is not presented as a known limit.
Kimi's top-level thinking, reasoning and reasoning_effort controls are removed from inference requests, including existing connections that have not saved these new preferences. The plugin sends the selected effort, or no effort override for Magpie/provider defaults. It preserves message content, reasoning history and tool calls/results. Native menu aliases cannot override the connected primary; only authenticated worker profiles select a child target. New role-scoped profiles distinguish primary from secondary even when their target IDs are identical. Older authenticated profiles without a role keep their model binding and use provider defaults with no additional input budget; create a new child to adopt independent role parameters. Native and resumed/forked profiles retain their existing behavior and binding.
No additional input budget is the default. A custom budget must be a positive integer no greater than the model catalog's published context limit; an unknown limit disables custom budgeting. Before generation, the bridge converts the final routed request into a count-only copy containing its system/developer text, supported text/images, reasoning text, tool schemas, calls and results. It calls Magpie's existing POST /v1/messages/count_tokens with the same gateway credential and permitted caller-identity headers. Magpie may return a provider count or an estimate. If that number exceeds the budget, generation is refused with context_length_exceeded; if counting fails or the message format cannot be represented, generation is refused with fixed context_count_unavailable. No generation request is sent in either case. Only a custom budget adds this counting request; it can add latency and consume the model service's request allowance. No new local port, network endpoint or native RPC method is added.
This is an input-budget check, not a setting for Kimi's native compaction window or an output-token limit. It does not change max_tokens, invent token usage or directly trim history. Kimi may attempt native compaction after a context error, preserving the worker's authenticated system prompt; its summary requests are checked against the same role budget. Recovery is not guaranteed: fixed system/tool overhead or a large remaining message can still exceed the budget. Raise/remove the budget, shorten the input or start a new conversation if recovery fails. Native compaction can reduce earlier details available to subsequent inference, and raising the budget does not expand Kimi's native window.
Preferences are bound to their selected model. While a model or gateway change waits for application, active requests retain the previous role rules in memory. After a confirmed switch, an older resumed model binding does not inherit another model's parameters. Saving a partial patch merges it into the latest connection document; unavailable values remain visible so they can be explicitly replaced or reset. Kimi login, other native plugins, paid-data authorizations, billing and service paths are unchanged. Financial database results remain ordinary tool input to the selected model; the plugin does not call their paid query APIs for counting.
中文说明
在内嵌的 Kimi Work 模型页面中,分别选择主、副模型的思考强度与可选的上下文输入预算(计数/估算),然后保存。主、副使用同一模型也能设置不同参数。默认思考选项交给 Magpie/供应方决定;只有模型目录明确公布的强度可以选择,Magpie 路由中固定的思考强度优先。插件不按模型名称猜测能力,也不会把旧的 131072-token 回退值当作已知上限显示。
推理请求中的 Kimi 顶层 thinking、reasoning 和 reasoning_effort 会被移除,尚未保存新偏好的已有连接也适用。插件发送选定强度,默认时不指定强度,让 Magpie/供应方决定。消息正文、推理历史、工具调用与结果保持完整。Kimi 菜单别名不能覆盖已接入的主模型,子任务只能由认证的 worker profile 选择目标。新的角色 profile 能区分指向同一模型的主、副角色。旧的无角色认证 profile 保留原模型绑定,使用供应方默认值且不增加输入预算;新建子代理才能采用独立角色参数。原生类型及恢复/分叉任务保留原行为和绑定。
默认不额外限制输入。自定义预算必须是正整数,且不能超过模型目录公布的上下文上限;上限未知时不能自定义。生成回答前,桥接将完成路由后的请求转换为仅供计数的副本,包含 system/developer 文本、支持的文本与图片、推理文本、工具 schema、调用及结果,并以相同网关凭据和允许的调用身份头请求 Magpie 已有的 POST /v1/messages/count_tokens。Magpie 可能返回供应方计数,也可能返回估算。结果超过预算时返回 context_length_exceeded;计数失败或无法表示消息格式时返回固定的 context_count_unavailable,两种情况下都不会发送生成请求。只有自定义预算会增加这次计数请求,可能增加延迟并占用模型服务的请求额度。插件不新增本地端口、网络端点或原生 RPC 方法。
这是输入预算检查,不设置 Kimi 原生压缩窗口,也不设置输出长度。插件不改 max_tokens、不伪造 usage,也不直接裁剪历史。Kimi 遇到上下文错误后可能尝试原生压缩,并保留 worker 的认证 system prompt;摘要请求仍按同一角色预算检查。恢复不保证成功:固定 system/工具开销或剩余的大消息仍可能超预算。失败时可调高或取消预算、缩短输入或新建会话。原生压缩可能减少后续推理能看到的早期细节,提高预算也不会扩大 Kimi 原生窗口。
偏好与所选模型绑定。模型或网关切换等待应用时,当前请求继续使用内存中的旧角色规则;确认切换后,恢复的旧模型绑定不会套用另一模型的参数。部分字段保存会合并最新连接文档;不可用值仍保留显示,允许明确替换或恢复默认。Kimi 登录、其他原生插件、付费数据授权、计费及服务通路保持不变。金融数据库结果仍作为普通工具输入交给选定模型,计数不会调用金融数据库的付费查询 API。
Library: instructions, MCP and skills
Version 0.1.1 registers ordinary Kimi as a target on all three Library pages. This is separate from Kimi Code. Existing assignments stay unchanged; select Kimi on the resources you want to share.
- Shared instructions are written by Magpie to
~/.config/magpie-kimi/AGENTS.md. While connected, the adapter reads this file before each inference and inserts one separate system message, preserving Kimi's original prompts, tool calls and history. Changes also apply to existing Work conversations on their next request. Removing the assignment removes Magpie's managed block; other text in that file remains the user's own instructions. An unreadable/invalid file fails withinstructions_unavailablerather than silently omitting active rules. These instructions do not apply when disconnected, to Chat, or to cloud Claw. - MCP points through
~/.config/magpie-kimi/library-native/mcp.jsonto ordinary Kimi'sdaimon-share/daimon/runtime/kimi-code/home/mcp.json. The format is Kimi'smcpServersobject. Existing server entries are retained by Magpie's normal Library merge; new conversations load changed MCP settings. Existing conversations can use Kimi's own reconnect controls. - Skills point through
~/.config/magpie-kimi/library-skillsto ordinary Kimi'sdaimon-share/daimon/skills. This exposes existing native skills as well as Library assignments. Bundled/user skills are not deleted or replaced by the adapter. Conflicts use Magpie's normal keep-own/use-library choice. Start a new Work conversation to load changed skills.
The two directory links are Windows junctions or macOS directory symlinks; no administrator authorization or app modification is needed. An existing different object at either link path is left intact and reports library_path_conflict. Resource files remain in Kimi when the model bridge disconnects. The adapter does not enable all resources or change another agent's assignments.
The Work provider carries an agent's messages unchanged; a provider is not a separate instruction target. Give shared instructions to the agent making the request. Using Kimi Work in Codex therefore uses Codex's instructions, while ordinary Kimi uses the Kimi assignment above.
How it works
The import-free kimi-desktop.agent.js registers the agent using Magpie's agent interface. The Bun entry index.mjs is also necessary: Kimi's actual configuration belongs to its running local runtime, so changing a file alone does not reliably apply a model. It runs a loopback adapter and uses Kimi's authenticated local control API to reload the selected model.
Inference goes to Magpie using Magpie's agent credential. Kimi's web search/fetch tools continue through Kimi's original agent-gw.kimi.com service with Kimi's own credential. Kimi login credentials are never forwarded to Magpie or a third-party model provider. Requests to unknown paths and requests without Kimi authentication are rejected; no system proxy, certificate or firewall settings are changed.
Rate-limit and temporary-service responses retain the upstream status, body and Retry-After header, including both delay-seconds and HTTP-date values. Other upstream headers are not copied wholesale.
The adapter does not reload a busy Work runtime. If Kimi independently changes its service configuration while connected, adaptation pauses instead of repeatedly overwriting it; disconnect and reconnect in Magpie to retry.
Local files and compatibility
~/.config/magpie-kimi/connection.json: Magpie's selected model and connection.~/.config/magpie-kimi/status.json: fixed status categories, without credentials.~/.config/magpie-kimi/adapter-state.json: original service address, recovery ownership, local role-signing secret, opaque token-to-model bindings, companion-plugin state and pending disable/reload IDs; no Kimi login credentials.~/.config/magpie-kimi/native-model-roles: generated companion-plugin source; Kimi owns its installed managed copy.~/.config/magpie-kimi/before-menu-models.json: an earlier adapter's original model-list/current-choice snapshot, retained until acknowledged menu/runtime restoration. No full configuration or credential backup is written.- Kimi configuration:
daimon/config.jsonin Kimi'sdaimon-sharefolder: wherekimi-desktop/daimon-storage.jsonpoints (shareDir; Kimi 3.2.21 on Windows writes it when installed on another drive, e.g.D:\KimiData\daimon-share, and on any system when its storage is moved), elsekimi-desktop/daimon-share, under the platform's application-support directory (%APPDATA%,~/Library/Application Support,~/.config).
Earlier primary-bridge revisions were verified with Windows 11, Kimi 3.2.17.10 and official Magpie 0.1.1275, including an actual Work request through Magpie. The historical macOS record covers real control methods, connect/disconnect restoration and a real streamed bridge request on macOS 26.6.2 arm64, Kimi 3.2.17 build 3.2.17.4 and official Magpie 0.1.1276. That request was initiated by an HTTP test client. A later macOS desktop UI-submitted Work turn was verified on 2026-11-06 with a non-Kimi model selected in Magpie; see the macOS desktop UI turn record. These older results do not validate the current role-profile candidate. The required runtime has provider daimon-kimi-code with original service https://agent-gw.kimi.com/coding/v1; other layouts stop with unsupported_kimi_config.
The private control API is undocumented. Before connecting, the adapter probes models.current; a refused/missing method stops connection without changing the service address. A failed conversations.setModel rolls back that address. Failures of conversations.getKimiModelList or conversations.updateKimiModelList report catalog_sync_failed and preserve the existing catalog rather than inventing a different protocol. In that case the selected-model bridge may remain connected; disconnect it to return to Kimi's service. No vendor app files are patched, and no automatic upgrade to an unknown protocol is attempted.
No Kimi binaries, personal configuration, prompts, account identifiers or credentials are included. There are no runtime dependencies. Tests use isolated temporary directories and synthetic credentials.
bun test packages/kimi-desktop
The model catalog is fetched from Magpie's /v1/models with this agent's credential and registered User-Agent. Magpie owns its visibility, picked/hidden models, disables and ordering. The adapter never opens Magpie's providers.json or settings.json. It rechecks the gateway catalog before every inference; removed selections are refused even during a running turn, and an unavailable catalog returns a fixed error instead of falling back to an unrestricted list. This package includes no Electron injection hook or model-menu patch. The icon is Kimi's desktop application icon.
Inference thinking fields now follow the plugin-page policy above. The historical 3.2.18 compatibility check covers the earlier runtime/menu registration path's always_thinking handling, real model requests, background-control turns and signed-in UI submissions in a separate official desktop profile. It does not establish thinking behavior or native acceptance for the current role-profile implementation.
Shutdown and manual recovery
The shared plugin host owns process shutdown. This plugin installs no SIGTERM/SIGINT handler and never calls process.exit. On the host's normal exit event it synchronously restores the original address if still owned and attempts the owned plugin-registry disable described above. This leaves a pending native memory/session refresh; a disk false alone is not that acknowledgement. An explicit disconnect while both apps are running also restores model selection/list through the control API.
The adapter's explicit stop() closes its settings service and uses normal restoration for owned primary/menu state, earlier owned secondary fields and companion-plugin disable/reload acknowledgement followed by registration removal. Busy or unacknowledged recovery remains pending. Changing settingsPort recreates the page service when plugin options are loaded again.
If a primary/menu control call fails or loses its reply, recovery ownership and the model backup remain until the menu and final runtime reload are acknowledged. A subsequent start can finish restoration even when the address is already official and the connection is disabled. A failed secondary write retains its previous owned binding so retries, stopping and crash recovery do not mistake it for another writer's configuration.
Owner records are fully written to a temporary file and published with an exclusive hard link, so interruption during the write cannot publish an empty/partial adapter-owner.json. An existing live owner is left alone. A malformed legacy owner record reports adapter_lock_invalid in status.json and the plugin log; a file access/publication failure reports adapter_lock_unavailable. The plugin does not guess who owns a malformed record or automatically remove it. To recover from adapter_lock_invalid, close all Magpie instances first, remove only ~/.config/magpie-kimi/adapter-owner.json, then reopen Magpie. Leave connection.json, the other state files and Kimi's credentials intact.
A forced kill, power loss or a broken private API can leave Kimi pointing at an inactive loopback bridge. To recover without starting Magpie:
- Close Kimi normally. In
~/.config/magpie-kimi/connection.json, setenabledtofalseso the adapter does not reconnect when Magpie next starts. - Open Kimi's
config.jsonat the application-support path above. Only ifmodel.providers["daimon-kimi-code"].baseUrlequalsbridgeURLinadapter-state.json, change that one field to the same state'soriginalBase(normallyhttps://agent-gw.kimi.com/coding/v1). Leavecredentialsand all unrelated fields untouched; do not replace the whole document from an old backup. - If an earlier adapter left
model.currentstarting withmagpie-local-orlocal-model-, set it tocurrentfrombefore-menu-models.jsonif that alias still exists inmodel.models; otherwise choose an existing nativedaimon-kimi-codealias, such ask3-agentork2d8-preview. Remove only those adapter alias keys frommodel.modelsif present. Reopen Kimi; it refreshes its native model catalog. - If a forced termination left a
local-work-model-roles-*companion enabled, use Kimi's native plugin management to disable or remove that entry before continuing without the bridge. Registration removal can leave generated files on disk; resume after disable or removal is not established by this review.
Older experimental packages created full backups/before-connect-*.json copies, which can contain Kimi credentials. This package creates no such files and does not silently delete existing user backups. After recovery, users can remove those older copies locally. Do not upload them in an issue or PR.