From 646776060f89d7d8ce1a059eca3df2a1babcd39a Mon Sep 17 00:00:00 2001 From: kupakupa <76491735+kupakupar@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:33:01 +0800 Subject: [PATCH] kimi-desktop: Kimi desktop Work as an agent, through its local runtime (#169) Adds agent-kimi-desktop 0.1.0 (kupakupar): Kimi desktop Work on magpie's Agents page. It moves the runtime's daimon-kimi-code baseUrl to a loopback bridge and back, through Kimi's local control API. Re-reviewed at dd8ed2c against the last review at 6c584bb: 1. menu-hook.cjs and selection.mjs are removed; no injected code ships. 2. No full config backup is written. Only before-menu-models.json (the model list and current choice) is kept, and it is removed on a clean disconnect. 3. providers.json and settings.json are never opened. The catalog comes from the gateway's /v1/models with the agent's key and its registered UA "Desktop Kimi Work". 4. No signal handlers and no process.exit. Restore runs on the 'exit' event, which fires when magpie closes the host's stdin (host.js rl.on("close") -> process.exit(0)). The README gives manual recovery after a SIGKILL. 5. macOS record: COMPATIBILITY.md (macOS 26.6.2 arm64, Kimi 3.2.17 build 3.2.17.4, magpie 0.1.1276, Bun 1.4.3). All four control methods succeeded, a streamed request returned 200, and a restore followed. The README says what happens when a private method fails. 6. Search and fetch pass Kimi's own request, with its own key, to Kimi's own origin, unchanged. This is the user's own account used by that user, the same rule as #171, so it is accepted. Run at dd8ed2c, and merged onto origin/main 2ea25b9 together with #171: - HOME=$(mktemp -d) bun test: 1660 pass, 0 fail (merged: 1668 pass, 0 fail). - bun test packages/kimi-desktop: 12 pass. - bun scripts/check.mjs: ok (it skips agent packages). - git diff --check, npm pack --dry-run (8 files), node scripts/dist.mjs (packs agent-kimi-desktop@0.1.0). - Broken by hand: re-adding a SIGTERM handler and a full config backup turns 3 tests red. - No CI ran on the PR. No real Kimi or credential was used. --- README.md | 1 + packages/kimi-desktop/COMPATIBILITY.md | 42 ++ packages/kimi-desktop/README.md | 51 +++ packages/kimi-desktop/adapter.mjs | 434 ++++++++++++++++++++ packages/kimi-desktop/catalog.mjs | 42 ++ packages/kimi-desktop/index.mjs | 19 + packages/kimi-desktop/kimi-desktop.agent.js | 19 + packages/kimi-desktop/kimi-desktop.test.mjs | 301 ++++++++++++++ packages/kimi-desktop/package.json | 32 ++ packages/kimi-desktop/rpc.mjs | 42 ++ registry.json | 3 +- 11 files changed, 985 insertions(+), 1 deletion(-) create mode 100644 packages/kimi-desktop/COMPATIBILITY.md create mode 100644 packages/kimi-desktop/README.md create mode 100644 packages/kimi-desktop/adapter.mjs create mode 100644 packages/kimi-desktop/catalog.mjs create mode 100644 packages/kimi-desktop/index.mjs create mode 100644 packages/kimi-desktop/kimi-desktop.agent.js create mode 100644 packages/kimi-desktop/kimi-desktop.test.mjs create mode 100644 packages/kimi-desktop/package.json create mode 100644 packages/kimi-desktop/rpc.mjs diff --git a/README.md b/README.md index 7f97cd4..04c2326 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ it off puts the config back. | Package | Agent | |---|---| | [aider](packages/aider) | [Aider](https://aider.chat): `~/.aider.conf.yml`, through litellm's `openai/` prefix | +| [kimi-desktop](packages/kimi-desktop) | Ordinary [Kimi desktop](https://www.kimi.com/) Work, through its authenticated local runtime; not Kimi Code CLI | | [type4me](packages/type4me) | [Type4Me](https://github.com/joewongjc/type4me), macOS voice input: `~/Library/Application Support/Type4Me/magpie-agent.json`, for its LLM post-processing | ```sh diff --git a/packages/kimi-desktop/COMPATIBILITY.md b/packages/kimi-desktop/COMPATIBILITY.md new file mode 100644 index 0000000..b5fe565 --- /dev/null +++ b/packages/kimi-desktop/COMPATIBILITY.md @@ -0,0 +1,42 @@ +# macOS compatibility record + +Observed at **2026-10-16 20:09 UTC** (2026-10-17 04:09 UTC+8): macOS 26.6.2 arm64; ordinary Kimi desktop **3.2.17, build 3.2.17.4** (`com.moonshot.kimichat`); official Magpie **0.1.1276**; Bun **1.4.3**. Agent runtime files were pinned to `dd3a8b889507f4c810e074acbb0dbf8a167ac99c` and checked against their Git blob SHA-256 values. + +The user signed in to ordinary Kimi desktop and opened Work. Its real configuration was found at: + +```text +~/Library/Application Support/kimi-desktop/daimon-share/daimon/config.json +``` + +The real runner was at `agents/main/runner.state.json` relative to that directory, reported `running`, and had no active turns. The fields `credentials.kimiCode.apiKey`, `credentials.kimiCode.baseUrl`, `credentials.kimiWeb.accessToken` and `credentials.kimiWeb.userId` were present and nonempty. All credential values and the local control token remained on the Mac and are omitted here. + +## What ran + +1. Started official Magpie in a separate temporary `XDG_CONFIG_HOME` on an unused loopback port, with the Kimi Work provider from PR #171. The real desktop sign-in was read using the normal macOS home. The existing Magpie process/profile was not restarted or replaced. +2. Instantiated the submitted `KimiAdapter` with a temporary `stateDir`, its default macOS Kimi path, and the submitted `rpc` implementation. Calls went to Kimi's real authenticated local WebSocket endpoint, not a fixture. The actual methods `models.current`, `conversations.setModel`, `conversations.getKimiModelList` and `conversations.updateKimiModelList` all succeeded. +3. Connected with selected model `kimi-work/k3-agent`. The adapter reported `connected` with no catalog error, wrote its owned loopback address, and added the gateway's catalog to the real runtime. There were initially two native Kimi models. +4. Sent a synthetic authenticated HTTP request to the adapter's `/v1/chat/completions`, using the real Kimi credential only on that loopback hop. The adapter used Magpie's credential for the gateway hop. Official Magpie then invoked the real Kimi Work provider and service. The response was HTTP 200 with a complete SSE stream and exactly `KIMI_WORK_MAC_OK`. Magpie's route record named agent `kimi-desktop`, provider `kimi-work`, requested model `kimi-work/k3-agent` and served model `k3-agent`. +5. Stopped the adapter, verified the restoration results below, and stopped only the temporary gateway. + +## Restoration observed + +```json +{ + "baseRestored": true, + "currentRestored": true, + "nativeCatalogRestored": true, + "credentialsUnchanged": true, + "unrelatedSettingsPreserved": true, + "noSyntheticModels": true, + "modelSnapshotRemoved": true, + "sandboxGatewayStopped": true +} +``` + +Configuration preservation here is a semantic comparison, not a claim about JSON whitespace. The credential-bearing document was held in memory for comparison only; it was never copied to a backup or uploaded. No app resources or model-menu injection patch were installed. + +## Limits + +The inference originated from a synthetic HTTP client at the bridge, **not a desktop UI-submitted Work conversation**. This proves the actual macOS control methods, configuration lifecycle and streamed adapter → official Magpie → real provider route; it does not prove desktop UI selection behavior. This run did not exercise Kimi search/fetch, SIGKILL, sleep/wake, natural token rotation or a future Kimi release. The Windows desktop UI observation is separate. + +The private API failure/rollback behavior and manual recovery are documented in README. The disclosed split routing of inference to Magpie and search/fetch to Kimi remains a separate maintainer review point; the subscription-provider decision in #171 is not presented as a desktop UI or search/fetch test. diff --git a/packages/kimi-desktop/README.md b/packages/kimi-desktop/README.md new file mode 100644 index 0000000..1260664 --- /dev/null +++ b/packages/kimi-desktop/README.md @@ -0,0 +1,51 @@ +# 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. + +```sh +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. The standard Kimi model menu continues to use the model selected 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. + +## 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. + +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 and connection ownership; no Kimi login credentials. +- `~/.config/magpie-kimi/before-menu-models.json`: one snapshot of the original model list/current choice, removed after a clean disconnect. No full configuration or credential backup is written. +- Kimi configuration: `kimi-desktop/daimon-share/daimon/config.json` under the platform's application-support directory. + +Verified with Windows 11, Kimi 3.2.17.10 and official Magpie 0.1.1275, including an actual Work request through Magpie. The [macOS record](COMPATIBILITY.md) verifies 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 macOS desktop UI-submitted Work turn remains unverified. The supported 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. + +```sh +bun test packages/kimi-desktop/kimi-desktop.test.mjs +``` + +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. + +## 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 the current address is still its own; restart Kimi to reload its runtime. An explicit disconnect while both apps are running additionally restores model selection/list through the control API. + +A forced kill, power loss or a broken private API can leave Kimi pointing at an inactive loopback bridge. To recover without starting Magpie: + +1. Close Kimi normally. In `~/.config/magpie-kimi/connection.json`, set `enabled` to `false` so the adapter does not reconnect when Magpie next starts. +2. Open Kimi's `config.json` at the application-support path above. Only if `model.providers["daimon-kimi-code"].baseUrl` equals `bridgeURL` in `adapter-state.json`, change that one field to the same state's `originalBase` (normally `https://agent-gw.kimi.com/coding/v1`). Leave `credentials` and all unrelated fields untouched; do not replace the whole document from an old backup. +3. If `model.current` starts with `magpie-local-`, set it to `current` from `before-menu-models.json` if that alias still exists in `model.models`; otherwise choose an existing native `daimon-kimi-code` alias, such as `k3-agent` or `k2d8-preview`. Remove only `model.models` keys beginning with `magpie-local-` if present. Reopen Kimi; it refreshes its native model catalog. + +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. diff --git a/packages/kimi-desktop/adapter.mjs b/packages/kimi-desktop/adapter.mjs new file mode 100644 index 0000000..62a0e29 --- /dev/null +++ b/packages/kimi-desktop/adapter.mjs @@ -0,0 +1,434 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import http from 'node:http'; +import crypto from 'node:crypto'; +import { once } from 'node:events'; +import { rpc } from './rpc.mjs'; +import { normalizeModels, mergeRuntimeModels, isMenuAlias } from './catalog.mjs'; + +const PROVIDER = 'daimon-kimi-code'; +const TOOL_ORIGIN = 'https://agent-gw.kimi.com'; +const BODY_LIMIT = 32 * 1024 * 1024; +const HEADERS = ['user-agent', 'x-msh-version', 'r-timezone', 'x-session-id', 'session_id']; +const readJSON = file => JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); +const sha = value => crypto.createHash('sha256').update(value).digest('hex'); +const baseURL = doc => doc?.model?.providers?.[PROVIDER]?.baseUrl; +const activeCount = value => Array.isArray(value) ? value.length : Number(value) || 0; +const busy = runner => activeCount(runner?.activeKernelTurns) + activeCount(runner?.activeKernelToolCalls) > 0; + +function atomicJSON(file, value) { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const temp = file + '.' + process.pid + '.' + crypto.randomBytes(6).toString('hex') + '.tmp'; + try { + fs.writeFileSync(temp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600, flag: 'wx' }); + fs.renameSync(temp, file); + } finally { try { fs.unlinkSync(temp); } catch { /* Renamed. */ } } +} + +function gatewayURL(value) { + let url; + try { url = new URL(value); } catch { throw Error('invalid_gateway'); } + if (!['http:', 'https:'].includes(url.protocol) || !['127.0.0.1', '[::1]'].includes(url.hostname) + || url.username || url.password || url.search || url.hash || !/^\/v1\/?$/.test(url.pathname)) { + throw Error('invalid_gateway'); + } + return url.href.replace(/\/$/, ''); +} + +function officialURL(value) { + let url; + try { url = new URL(value); } catch { throw Error('unsupported_kimi_config'); } + if (url.origin !== TOOL_ORIGIN || url.pathname !== '/coding/v1' + || url.username || url.password || url.search || url.hash) throw Error('unsupported_kimi_config'); + return url.href; +} + +function authenticated(actual, key) { + if (!key || typeof key !== 'string') return false; + const left = Buffer.from(actual || ''), right = Buffer.from('Bearer ' + key); + return left.length === right.length && crypto.timingSafeEqual(left, right); +} + +export function defaultKimiDirectory(home = os.homedir()) { + const support = process.platform === 'win32' ? process.env.APPDATA || path.join(home, 'AppData', 'Roaming') + : process.platform === 'darwin' ? path.join(home, 'Library', 'Application Support') : path.join(home, '.config'); + return path.join(support, 'kimi-desktop', 'daimon-share', 'daimon'); +} + +export class KimiAdapter { + constructor({ home = os.homedir(), stateDir, kimiDir, intervalMs = 1000, stabilityMs = 2000, + rpcCall = rpc, fetchImpl = globalThis.fetch, log = () => {} } = {}) { + this.stateDir = stateDir || path.join(home, '.config', 'magpie-kimi'); + this.kimiDir = kimiDir || defaultKimiDirectory(home); + this.configFile = path.join(this.kimiDir, 'config.json'); + this.runnerFile = path.join(this.kimiDir, 'agents', 'main', 'runner.state.json'); + this.connectionFile = path.join(this.stateDir, 'connection.json'); + this.stateFile = path.join(this.stateDir, 'adapter-state.json'); + this.lockFile = path.join(this.stateDir, 'adapter-owner.json'); + this.statusFile = path.join(this.stateDir, 'status.json'); + this.catalogFile = path.join(this.stateDir, 'menu-catalog.json'); + this.modelBackupFile = path.join(this.stateDir, 'before-menu-models.json'); + this.catalog = []; + Object.assign(this, { intervalMs, stabilityMs, rpcCall, fetchImpl, log }); + this.ownerID = crypto.randomUUID(); + this.status = {}; + this.running = false; + this.live = null; + this.stopping = false; + this.state = null; + this.inflight = new Set(); + } + + bootstrap() { + if (!fs.existsSync(this.configFile)) return false; + fs.mkdirSync(this.stateDir, { recursive: true, mode: 0o700 }); + if (!fs.existsSync(this.connectionFile)) { + try { + fs.writeFileSync(this.connectionFile, JSON.stringify({ schemaVersion: 1, enabled: false, + model: '', gateway: { url: '', key: '' } }, null, 2) + '\n', { mode: 0o600, flag: 'wx' }); + } catch (error) { if (error.code !== 'EEXIST') throw error; } + } + return true; + } + + ownLock() { + if (this.locked) { + try { return readJSON(this.lockFile).ownerID === this.ownerID; } catch { this.locked = false; } + } + try { + const before = fs.readFileSync(this.lockFile, 'utf8'), owner = JSON.parse(before); + let alive = true; + try { process.kill(owner.pid, 0); } catch (error) { alive = error.code !== 'ESRCH'; } + if (alive) return false; + if (fs.readFileSync(this.lockFile, 'utf8') !== before) return false; + fs.unlinkSync(this.lockFile); + } catch (error) { if (error.code !== 'ENOENT') return false; } + try { + fs.writeFileSync(this.lockFile, JSON.stringify({ pid: process.pid, ownerID: this.ownerID }), { flag: 'wx', mode: 0o600 }); + this.locked = true; + try { this.state = readJSON(this.stateFile); } catch { this.state = { active: false }; } + return true; + } catch { return false; } + } + + releaseLock() { + try { if (readJSON(this.lockFile).ownerID === this.ownerID) fs.unlinkSync(this.lockFile); } catch { /* Not ours. */ } + this.locked = false; + } + + report(code, details = {}) { + const next = { code, ...details }; + if (JSON.stringify(next) === JSON.stringify(this.status)) return; + this.status = next; + if (fs.existsSync(this.stateDir)) atomicJSON(this.statusFile, { ...next, at: new Date().toISOString() }); + if (code.endsWith('_failed') || code === 'kimi_config_changed') this.log(code); + } + + saveState() { atomicJSON(this.stateFile, this.state); } + + async gatewayCatalog(target, key) { + // Magpie applies this agent's visibility and model selection. The key + // and registered User-Agent identify it; no credential/config file read. + const response = await this.fetchImpl(target + '/models', {method: 'GET', headers: { + Accept: 'application/json', Authorization: 'Bearer ' + key, 'User-Agent': 'Desktop Kimi Work', + }, signal: AbortSignal.timeout(6000), redirect: 'error', proxy: ''}); + if (!response.ok || Number(response.headers.get('content-length') || 0) > 8 * 1024 * 1024) throw Error('catalog_unavailable'); + const text = await response.text(); + if (Buffer.byteLength(text) > 8 * 1024 * 1024) throw Error('catalog_unavailable'); + return normalizeModels(JSON.parse(text), {allowEmpty: true}); + } + + publishCatalog(desired) { + atomicJSON(this.catalogFile,{schemaVersion:1,enabled:true,exclusive:true,updatedAt:new Date().toISOString(), + selectedAlias:this.catalog.find(x=>x.id===desired.model)?.alias||'',models:this.catalog.map(x=>x.menu)}); + } + + // Change one field in the newest document; never restore stale login tokens. + changeBase(expected, replacement) { + const before = fs.readFileSync(this.configFile), doc = JSON.parse(before.toString('utf8').replace(/^\uFEFF/, '')); + if (baseURL(doc) !== expected) throw Error('kimi_config_changed'); + if (expected === replacement) return doc; + doc.model.providers[PROVIDER].baseUrl = replacement; + if (!fs.readFileSync(this.configFile).equals(before)) throw Error('kimi_config_changed'); + atomicJSON(this.configFile, doc); + return doc; + } + + async listen() { + if (this.server) return; + const server = http.createServer((req, res) => { void this.forward(req, res); }); + server.requestTimeout = 300000; + server.headersTimeout = 15000; + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + this.server = server; + this.bridgeURL = 'http://127.0.0.1:' + server.address().port + '/v1'; + } + + async forward(req, res) { + const error = (status, code) => { + if (!res.headersSent) res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { type: 'kimi_adapter_error', code, message: code } })); + }; + if (req.method !== 'POST' || !['/v1/chat/completions', '/v1/search', '/v1/fetch'].includes(req.url)) { + error(404, 'not_found'); return; + } + const active = this.live; + if (!active) { error(503, 'kimi_not_connected'); return; } + let doc; + try { doc = readJSON(this.configFile); } catch { error(503, 'kimi_config_unavailable'); return; } + if (!authenticated(req.headers.authorization, doc.credentials?.kimiCode?.apiKey)) { + error(401, 'unauthorized'); return; + } + if (req.headers.origin || req.headers['sec-fetch-site']) { error(403, 'browser_request_refused'); return; } + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 300000); + this.inflight.add(controller); + res.once('close', () => { if (!res.writableEnded) controller.abort(); }); + req.once('aborted', () => controller.abort()); + try { + let length = 0; + const chunks = []; + for await (const chunk of req) { + length += chunk.length; + if (length > BODY_LIMIT) { error(413, 'request_too_large'); return; } + chunks.push(chunk); + } + let payload; + try { payload = JSON.parse(Buffer.concat(chunks).toString('utf8')); } + catch { error(400, 'invalid_json'); return; } + if (!payload || Array.isArray(payload) || typeof payload !== 'object') { error(400, 'invalid_json'); return; } + const inference = req.url === '/v1/chat/completions'; + if (inference) { + const selected = this.catalog.find(x => x.alias === payload.model); + if (!selected && isMenuAlias(payload.model)) { error(409, 'model_no_longer_available'); return; } + const model=selected?.id||active.model; + let allowed; + try { allowed = await this.gatewayCatalog(active.gatewayURL, active.gatewayKey); } + catch { error(503, 'catalog_unavailable'); return; } + if (!allowed.some(row => row.id === model)) { error(409, 'model_not_enabled_for_kimi'); return; } + payload.model = model; + } + const headers = { 'Content-Type': 'application/json', + Authorization: inference ? 'Bearer ' + active.gatewayKey : req.headers.authorization }; + for (const name of HEADERS) if (typeof req.headers[name] === 'string') headers[name] = req.headers[name]; + if (!headers['user-agent']) headers['user-agent'] = 'Desktop Kimi Work'; + const url = inference ? active.gatewayURL + '/chat/completions' + : officialURL(active.originalBase) + req.url.slice('/v1'.length); + const upstream = await this.fetchImpl(url, { method: 'POST', headers, + body: JSON.stringify(payload), signal: controller.signal, redirect: 'error' }); + res.writeHead(upstream.status, { 'Content-Type': upstream.headers.get('content-type') || 'application/json', + 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' }); + res.flushHeaders(); + if (upstream.body) for await (const chunk of upstream.body) { + if (!res.write(chunk)) await once(res, 'drain', { signal: controller.signal }); + } + res.end(); + } catch { + if (res.headersSent) res.destroy(); + else error(controller.signal.aborted ? 499 : 502, controller.signal.aborted ? 'request_cancelled' : 'upstream_connection_failed'); + } finally { + clearTimeout(timeout); + this.inflight.delete(controller); + } + } + + async restore({ reload = true } = {}) { + if (!this.state?.active) return; + let doc = readJSON(this.configFile); + let modelsRestored = false; + if (reload && baseURL(doc) === this.state.bridgeURL) { + try { + const runner = readJSON(this.runnerFile); + const current = await this.rpcCall(runner, 'conversations.getKimiModelList'); + const native = (current?.models || []).filter(x => !isMenuAlias(x.model)); + if (native.length) { + if (isMenuAlias(doc.model.current)) { + let original; + try {original=readJSON(this.modelBackupFile).current;} catch {} + const alias=native.some(x => x.model === original) ? original : native[0].model; + await this.rpcCall(runner,'conversations.setModel',{modelAlias:alias}); + } + if (native.length !== current.models.length) await this.rpcCall(runner,'conversations.updateKimiModelList',{models:native}); + doc=readJSON(this.configFile); + modelsRestored = true; + } + } catch { this.report('restored_waiting_kimi'); } + } + let changed = false; + if (baseURL(doc) === this.state.bridgeURL) { + this.changeBase(this.state.bridgeURL, this.state.originalBase); + changed = true; + } + this.live = null; + if (fs.existsSync(this.catalogFile)) atomicJSON(this.catalogFile, {schemaVersion: 1, enabled: false, models: [], updatedAt: new Date().toISOString()}); + this.state.active = false; + this.saveState(); + if (changed && reload) { + try { + const current = readJSON(this.configFile); + await this.rpcCall(readJSON(this.runnerFile), 'conversations.setModel', { modelAlias: current.model.current }); + } catch { this.report('restored_waiting_kimi'); } + } + // Only model fields were saved, never the full credentials-bearing config. + if (modelsRestored) { + try { fs.unlinkSync(this.modelBackupFile); } catch (error) { if (error.code !== 'ENOENT') throw error; } + } + } + + async syncCatalog(runner, desired, target) { + if (Date.now() < (this.catalogAfter || 0)) return; + this.catalogAfter = Date.now() + 10000; + if (busy(runner)) { + // Long Work turns must retain their menu entries. Refresh the local + // liveness timestamp without changing models or reloading a busy runtime. + try { + const keep = new Set((await this.gatewayCatalog(target, desired.gateway.key)).map(x => x.id)); + this.catalog=this.catalog.filter(x=>keep.has(x.id)); + const saved=readJSON(this.catalogFile); + if(saved.enabled) this.publishCatalog(desired); + } catch { /* Initial connection waits until idle. */ } + return; + } + try { + const catalog = await this.gatewayCatalog(target, desired.gateway.key); + const current = await this.rpcCall(runner, 'conversations.getKimiModelList'); + if (!Array.isArray(current?.models)) throw Error('catalog_unavailable'); + const merged = mergeRuntimeModels(current.models, catalog); + const same = merged.length === current.models.length && catalog.every(wanted => { + const found = current.models.find(x => x.model === wanted.alias); + return found && Object.entries(wanted.runtime).every(([key,value]) => { + const left = Array.isArray(value) ? [...value].sort() : value; + const right = Array.isArray(found[key]) ? [...found[key]].sort() : found[key]; + return JSON.stringify(left) === JSON.stringify(right); + }); + }); + if (!same) { + if (!fs.existsSync(this.modelBackupFile)) { + atomicJSON(this.modelBackupFile, {models: current.models, current: readJSON(this.configFile).model.current}); + } + await this.rpcCall(runner, 'conversations.updateKimiModelList', {models: merged}); + } + this.catalog = catalog; + this.publishCatalog(desired); + this.catalogError = null; + } catch { this.catalogError = 'catalog_sync_failed'; } + } + + async tick() { + if (this.running || this.stopping) return; + this.running = true; + try { + if (!this.bootstrap()) return; + if (!this.ownLock()) return; + const desired = readJSON(this.connectionFile); + let runner; + try { runner = readJSON(this.runnerFile); } catch { /* Kimi isn't running yet. */ } + if (!desired.enabled || !desired.model) { + if (this.state.active && busy(runner)) { this.report('waiting_kimi_idle'); return; } + await this.restore(); + this.pausedSignature = null; + this.retryAfter = 0; + this.report('disconnected'); + return; + } + const target = gatewayURL(desired.gateway?.url); + if (typeof desired.gateway?.key !== 'string' || !desired.gateway.key + || typeof desired.model !== 'string' || !desired.model.includes('/') || desired.model.length > 1024) { + throw Error('invalid_connection'); + } + if (!runner || runner.lifecycleStatus !== 'running') { this.report('waiting_kimi'); return; } + const bytes = fs.readFileSync(this.configFile), doc = JSON.parse(bytes.toString('utf8').replace(/^\uFEFF/, '')); + const generation = sha(JSON.stringify([runner.daemonGeneration, runner.control?.endpoint?.url, + runner.control?.endpoint?.startedAt, runner.control?.endpoint?.pid])); + const signature = sha(JSON.stringify([desired.model, target, desired.gateway.key])); + const fingerprint = sha(bytes); + if (fingerprint !== this.fingerprint) { this.fingerprint = fingerprint; this.stableSince = Date.now(); } + const unchanged = this.state.active && this.state.generation === generation && this.state.signature === signature; + if (unchanged && baseURL(doc) === this.bridgeURL && this.live) { + await this.syncCatalog(runner, desired, target); + this.report('connected', { model: desired.model, models: this.catalog.length, ...(this.catalogError ? {catalog: this.catalogError} : {}) }); return; + } + if (this.pausedSignature === signature) { this.report('kimi_config_changed'); return; } + if (unchanged && this.live && baseURL(doc) !== this.bridgeURL) { + this.pausedSignature = signature; + this.live = null; + this.report('kimi_config_changed'); + return; + } + if (busy(runner)) { this.report('waiting_kimi_idle'); return; } + if (Date.now() - this.stableSince < this.stabilityMs) { this.report('waiting_kimi_ready'); return; } + if (Date.now() < (this.retryAfter || 0)) return; + this.retryAfter = Date.now() + 5000; + const oldBase = baseURL(doc); + const originalBase = this.state.active && oldBase === this.state.bridgeURL + ? officialURL(this.state.originalBase) : officialURL(oldBase); + if (!doc.model.models?.[doc.model.current] || typeof doc.credentials?.kimiCode?.apiKey !== 'string') { + throw Error('unsupported_kimi_config'); + } + await this.rpcCall(runner, 'models.current'); + await this.listen(); + if (!fs.readFileSync(this.configFile).equals(bytes)) throw Error('kimi_config_changed'); + const previous = this.state; + this.state = { active: true, originalBase, bridgeURL: this.bridgeURL, generation, signature, model: desired.model }; + // Persist recovery ownership before writing the Kimi file. + this.saveState(); + this.changeBase(oldBase, this.bridgeURL); + try { + await this.rpcCall(runner, 'conversations.setModel', { modelAlias: doc.model.current }); + } catch (error) { + this.changeBase(this.bridgeURL, oldBase); + this.state = previous; + this.saveState(); + throw error; + } + this.live = { model: desired.model, gatewayURL: target, gatewayKey: desired.gateway.key, originalBase }; + await this.syncCatalog(runner, desired, target); + this.pausedSignature = null; + this.report('connected', { model: desired.model }); + } catch (error) { + const codes = new Set(['invalid_gateway', 'invalid_connection', 'unsupported_kimi_config', + 'kimi_config_changed', 'kimi_control_unavailable', 'kimi_control_timeout', 'kimi_control_closed', 'kimi_control_rejected']); + const code = codes.has(error.message) ? error.message : 'adapter_failed'; + this.report(code); + } finally { this.running = false; } + } + + async start() { + await this.tick(); + this.timer = setInterval(() => { void this.tick(); }, this.intervalMs); + this.timer.unref?.(); + return this; + } + + async stop() { + clearInterval(this.timer); + this.stopping = true; + while (this.running) await new Promise(resolve => setTimeout(resolve, 20)); + if (this.locked) { + try { await this.restore(); } catch { /* Never write a changed third-party configuration. */ } + this.report('disconnected'); + this.releaseLock(); + } + for (const pending of this.inflight) pending.abort(); + if (this.server) { + this.server.closeAllConnections?.(); + await new Promise(resolve => this.server.close(resolve)); + this.server = null; + } + } + + restoreFileOnExit() { + if (!this.locked) return; + try { + if (this.state?.active && baseURL(readJSON(this.configFile)) === this.state.bridgeURL) { + this.changeBase(this.state.bridgeURL, this.state.originalBase); + } + } catch { /* Leave a changed configuration alone. */ } + try { atomicJSON(this.catalogFile, {schemaVersion:1, enabled:false, models:[], updatedAt:new Date().toISOString()}); } catch { /* Exiting. */ } + this.releaseLock(); + } +} diff --git a/packages/kimi-desktop/catalog.mjs b/packages/kimi-desktop/catalog.mjs new file mode 100644 index 0000000..1bc91ce --- /dev/null +++ b/packages/kimi-desktop/catalog.mjs @@ -0,0 +1,42 @@ +import crypto from 'node:crypto'; + +export const isMenuAlias = value => /^magpie-local-[a-f0-9]{24}$/.test(value || ''); +const clean = value => typeof value === 'string' && value.length <= 2048 && !/[\x00-\x1f]/.test(value) ? value.trim() : ''; +const positive = (value, fallback) => Number.isSafeInteger(value) && value > 0 ? value : fallback; +const effortNames = { none: '关闭', minimal: '极低', low: '低', medium: '中', high: '高', xhigh: '极高', max: '最高' }; + +export function normalizeModels(payload, {allowEmpty=false}={}) { + if (!Array.isArray(payload?.data) || payload.has_more || payload.data.length > 50000) throw Error('catalog_invalid'); + const models = new Map(); + for (const row of payload.data) { + const id = clean(row.id); + if (!id || !id.includes('/')) continue; + const alias = 'magpie-local-' + crypto.createHash('sha256').update(id).digest('hex').slice(0, 24); + const efforts = [...new Set((row.supported_reasoning_levels || []).map(x => clean(x.effort)).filter(x => x in effortNames))]; + const thinking = efforts.includes('high') ? 'high' : efforts.includes('medium') ? 'medium' : efforts[0] || ''; + const capabilities = ['dynamically_loaded_tools']; + if (row.modalities?.input?.includes('image')) capabilities.push('image_in'); + if (row.reasoning) capabilities.push('thinking'); + const runtime = { model: alias, maxContextSize: positive(row.context_window || row.context_length, 131072), + capabilities, ...(row.max_output_tokens ? {maxOutputSize: positive(row.max_output_tokens, 8192)} : {}), + ...(efforts.length ? {supportEfforts: efforts, defaultEffort: thinking} : {}) }; + const title = clean(row.magpie_label) || clean(row.display_name) || id; + models.set(id, { id, alias, runtime, menu: { + key: alias, modelId: alias, modelAlias: alias, displayName: title + ' · Magpie', description: id, + inputPlaceholder: '尽管问,或做个 Agent 任务…', label: [], scenario: 6, agentMode: 'TYPE_NORMAL', + kimiPlusId: 'ok-computer', switchableTo: [], + reasoningEffortOptions: efforts.map(e => ({effort: 'REASONING_EFFORT_' + e.toUpperCase(), + reasoningEffort: e, thinkingLevel: e, displayName: effortNames[e], description: ''})), + defaultReasoningEffort: thinking ? 'REASONING_EFFORT_' + thinking.toUpperCase() : 'REASONING_EFFORT_UNSPECIFIED', + defaultThinkingLevel: thinking, + daimonModelConfig: {maxContextSize: runtime.maxContextSize, capabilities, supportEfforts: efforts, + defaultEffort: thinking, protocol: '', betaApi: false, reasoningKey: ''}, + }}); + } + if (!models.size && !allowEmpty) throw Error('catalog_empty'); + return [...models.values()]; +} + +export function mergeRuntimeModels(existing, catalog) { + return [...existing.filter(x => !isMenuAlias(x.model)), ...catalog.map(x => x.runtime)]; +} diff --git a/packages/kimi-desktop/index.mjs b/packages/kimi-desktop/index.mjs new file mode 100644 index 0000000..061e3e8 --- /dev/null +++ b/packages/kimi-desktop/index.mjs @@ -0,0 +1,19 @@ +import { KimiAdapter } from './adapter.mjs'; + +const instance = Symbol.for('magpie.kimi-desktop.adapter.v1'); + +export default async function KimiDesktop(input) { + if (!globalThis[instance]) { + const log = code => { + try { + void input?.client?.app?.log?.({ body: { service: 'kimi-desktop', level: 'warn', message: code } })?.catch?.(() => {}); + } catch { /* No configuration, credentials or raw RPC errors in logs. */ } + }; + const adapter = await new KimiAdapter({ log }).start(); + globalThis[instance] = adapter; + // The shared host owns shutdown. Its normal exit path is synchronous; + // never install signal handlers or terminate a host shared with plugins. + process.once('exit', () => adapter.restoreFileOnExit()); + } + return {}; +} diff --git a/packages/kimi-desktop/kimi-desktop.agent.js b/packages/kimi-desktop/kimi-desktop.agent.js new file mode 100644 index 0000000..78f5318 --- /dev/null +++ b/packages/kimi-desktop/kimi-desktop.agent.js @@ -0,0 +1,19 @@ +export const agent = { + id: 'kimi-desktop', + name: 'Kimi', + icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAABwCAMAAADxPgR5AAACvlBMVEUAAAAAAAECAgMNDQ0BAQEdHR4BAQICAQGYmJgBAQEAAAAGBgVoaGhGRkYJCQgiIyJpaWkCAgWSkpIzNDMICQkDAwM4OTglJiWMjowwMTCKi4tDQ0JNTk56fHl7e3unqKd7fXwLCwsAAAB3d3dmZ2cAAAGXl5dqa2tISEgDAwKGiIYCAgQCAgJoaGh8fnxlZWVeXl4GBwbU1dTExsSpqamkpKSen56Pj48VFRURExKztLMwMTABAAUAAAIsLS2tr6q3vLp5e3m0tbWVlZUKCg7GyMgrLSsFBQUDAwQAAAEB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RehVjF/YDY3BHjwJkZG7DSKUFRMBmyZZvSwwPlagYQdm4XmheiiGFAI0pS2Uu5aM0F+CNGrlyeMYVy0V2I8dV7OOjzBHrTK3CPZFEKdG600CAB4mx9cwfmlWuuTwh8B0s25MuJPFCmgleCkb7g/fdLjphBbW44NX3cwg6iogKSraS1nkNpwj4p+0alpMHvu0MHBZYTqjUF91uyfcuqTGAXhxo+hRIurdy/iN2Zu6MaiPy4PpRq4Z0YiBUiiBxOFHwUTQVo0ZCwX4CWUsPs30MjUSdYVTSU0zBo1pK4Dq1qERySghQb+0TXkFRgSrekU6p+WZuebWstmM35o6ncSaKEWQZFeU4IbicJPIpNAUTUE1utSv1d9036WG734/g6RoaOCZuINCNC2XWxzHWUqQyxfoecK2rSUZLYlG9WG4bL1pia6eyviT9dv6AJ1uUVk6DCIVKg15jFp/Ox6rRAfFUqOD1z4kahHq7UQ3hkfGeh4S83fjBrvx1o2jl+0sFtvAMvmUiqxLpSRGzTfkTs682Yy/mLpouiN9O10stkGzjqDJasmbqGTf9V68H39de98Bi69LrzIfio1OAHPjd55XU5lwWe9iC47fYKpF59g6zHRf5a8lsJDC7DIsmzmF8XdT56ymAlXoRTUizjfaHYwsjL8uddLiF+96b2KdV93+lxR6wvV8/N2g2WrXqahFefnkcOPIvCNXACyhvg4BhSzqyK9a/DXuXzKX7JqOYM+v6/BwxtunX3Ve9j6F37zNNFKNFy96mSepj/hz1ysyl0ohAMLx8zlHjtgPHRrOfw2s63d5t9PUze0L5wzT/s/SpbMW7dk5Y8GOrVtWLO+n4523oTevM1Sl1ymYBpVGqelHNVDELz4mZQ0/dkemTZq0cv7kGWvXzVw/9w/H658B4/5FYKGK3+sAAAAASUVORK5CYII=", + config: '~/.config/magpie-kimi/connection.json', + format: 'json', + model: 'model', + dir: '~/.config/magpie-kimi', + ua: ['Desktop Kimi Work'], + notice: '接入普通 Kimi 桌面版的 Work。请先打开 Kimi,插件会在本地 Agent 就绪后连接;Chat 不受影响。', +}; + +export function connect({ gateway }) { + return { + enabled: true, + 'gateway.url': gateway.v1, + 'gateway.key': gateway.key, + }; +} diff --git a/packages/kimi-desktop/kimi-desktop.test.mjs b/packages/kimi-desktop/kimi-desktop.test.mjs new file mode 100644 index 0000000..08603cc --- /dev/null +++ b/packages/kimi-desktop/kimi-desktop.test.mjs @@ -0,0 +1,301 @@ +import { test, expect } from 'bun:test'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import http from 'node:http'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { KimiAdapter } from './adapter.mjs'; +import { controlEndpoint } from './rpc.mjs'; +import { agent, connect } from './kimi-desktop.agent.js'; + +const official = 'https://agent-gw.kimi.com/coding/v1'; +const read = file => JSON.parse(fs.readFileSync(file, 'utf8')); +const write = (file, value) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(value)); }; + +async function fixture() { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'magpie-kimi-fixture-')); + const kimiDir = path.join(directory, 'kimi'); + const requests = [], tools = [], calls = []; + const models = [{id:'original-provider/test-model',display_name:'First'}, {id:'other-provider/other-model',display_name:'Second'}]; + const gateway = http.createServer(async (req, res) => { + if (req.method === 'GET' && req.url === '/v1/models') { + if (req.headers.authorization !== 'Bearer synthetic-magpie-key' || req.headers['user-agent'] !== 'Desktop Kimi Work') { + res.writeHead(403); res.end(); return; + } + res.writeHead(200, {'Content-Type':'application/json'}); + res.end(JSON.stringify({data:models})); return; + } + let body = ''; for await (const chunk of req) body += chunk; + requests.push({ path: req.url, authorization: req.headers.authorization, body: JSON.parse(body) }); + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + res.write('data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_read","type":"function","function":{"name":"Read","arguments":"{}"}}]}}]}\n\n'); + res.end('data: [DONE]\n\n'); + }); + await new Promise(resolve => gateway.listen(0, '127.0.0.1', resolve)); + const controller = new KimiAdapter({ stateDir: path.join(directory, 'state'), kimiDir, + stabilityMs: 0, intervalMs: 100000, + rpcCall: async (_runner, method, params) => { calls.push({ method, params }); + if (method === 'conversations.getKimiModelList') return {models:[{model:'k2d8-preview'}]}; + return { current: 'k2d8-preview' }; }, + fetchImpl: async (url, options) => { + if (String(url).startsWith('https://agent-gw.kimi.com/')) { + tools.push({ url: String(url), authorization: options.headers.Authorization, body: JSON.parse(options.body) }); + return new Response('{"result":"official tool response"}', { headers: { 'Content-Type': 'application/json' } }); + } + return fetch(url, options); + }, + }); + const doc = { credentials: { kimiCode: { apiKey: 'synthetic-kimi-key', baseUrl: official, refreshToken: 'synthetic-refresh-before' } }, + model: { current: 'k2d8-preview', providers: { 'daimon-kimi-code': { type: 'kimi', baseUrl: official } }, + models: { 'k2d8-preview': { model: 'k2d8-preview', provider: 'daimon-kimi-code' } } }, + unrelated: { preserve: ['all', 'original', 'settings'] } }; + write(controller.configFile, doc); + write(controller.runnerFile, { lifecycleStatus: 'running', daemonGeneration: 'synthetic-generation-1', + activeKernelTurns: 0, activeKernelToolCalls: 0, control: { endpoint: { url: 'ws://127.0.0.1:3072/control', pid: 10, startedAt: 1 } } }); + controller.bootstrap(); + const connection = { schemaVersion: 1, enabled: true, model: 'original-provider/test-model', + gateway: { url: 'http://127.0.0.1:' + gateway.address().port + '/v1', key: 'synthetic-magpie-key' }, requestId: 1 }; + write(controller.connectionFile, connection); + return { directory, controller, doc, connection, requests, tools, calls, models, + cleanup: async () => { await controller.stop(); gateway.closeAllConnections(); await new Promise(resolve => gateway.close(resolve)); fs.rmSync(directory, { recursive: true, force: true }); } }; +} + +test('Work inference uses selected model and gateway auth; SSE tools survive; official fetch/search keep Kimi auth', async () => { + const f = await fixture(); + try { + await f.controller.tick(); + expect(f.controller.status.code).toBe('connected'); + const payload = { model: 'k2d8-preview', stream: true, + messages: [{ role: 'system', content: 'synthetic original instruction' }, { role: 'user', content: 'synthetic request' }], + tools: [{ type: 'function', function: { name: 'Read', parameters: { type: 'object' } } }] }; + const response = await fetch(f.controller.bridgeURL + '/chat/completions', { method: 'POST', + headers: { Authorization: 'Bearer synthetic-kimi-key', 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); + expect(response.status).toBe(200); + expect(response.headers.get('content-type')).toContain('text/event-stream'); + expect(await response.text()).toContain('"name":"Read"'); + expect(f.requests).toHaveLength(1); + expect(f.requests[0].authorization).toBe('Bearer synthetic-magpie-key'); + expect(f.requests[0].body).toEqual({ ...payload, model: 'original-provider/test-model' }); + for (const tool of ['fetch', 'search']) { + const response = await fetch(f.controller.bridgeURL + '/' + tool, { method: 'POST', headers: { + Authorization: 'Bearer synthetic-kimi-key', 'Content-Type': 'application/json' }, body: '{"query":"synthetic"}' }); + expect(response.status).toBe(200); await response.text(); + } + expect(f.tools.map(x => x.url)).toEqual(['https://agent-gw.kimi.com/coding/v1/fetch', 'https://agent-gw.kimi.com/coding/v1/search']); + expect(f.tools.every(x => x.authorization === 'Bearer synthetic-kimi-key')).toBe(true); + const current = read(f.controller.configFile); + expect(current.credentials).toEqual(f.doc.credentials); + expect(current.model.current).toBe('k2d8-preview'); + expect(current.unrelated).toEqual(f.doc.unrelated); + expect(f.calls.map(x => x.method)).toEqual(['models.current', 'conversations.setModel', 'conversations.getKimiModelList', 'conversations.updateKimiModelList']); + } finally { await f.cleanup(); } +}); + +test('Kimi menu aliases route independently and removed models fail closed', async () => { + const f = await fixture(); + try { + await f.controller.tick(); + expect(f.controller.catalog.length).toBe(2); + const menu = read(f.controller.catalogFile); + expect(menu.models[0].displayName).toBe('First · Magpie'); + expect(f.calls.find(x => x.method === 'conversations.updateKimiModelList').params.models[0].model).toBe('k2d8-preview'); + const chosen = f.controller.catalog.find(x => x.id === 'other-provider/other-model'); + const response = await fetch(f.controller.bridgeURL + '/chat/completions', {method:'POST', headers:{Authorization:'Bearer synthetic-kimi-key'}, + body:JSON.stringify({model:chosen.alias,messages:[{role:'user',content:'synthetic'}]})}); + await response.text(); + expect(f.requests[0].body.model).toBe('other-provider/other-model'); + expect(f.requests[0].authorization).toBe('Bearer synthetic-magpie-key'); + f.controller.catalog = f.controller.catalog.filter(x => x.alias !== chosen.alias); + const refused = await fetch(f.controller.bridgeURL + '/chat/completions', {method:'POST',headers:{Authorization:'Bearer synthetic-kimi-key'}, + body:JSON.stringify({model:chosen.alias,messages:[]})}); + expect(refused.status).toBe(409); + expect(f.requests.length).toBe(1); + } finally {await f.cleanup();} +}); + +test('disconnect restores one address while retaining refreshed credentials and unrelated changes', async () => { + const f = await fixture(); + try { + await f.controller.tick(); + const doc = read(f.controller.configFile); + doc.credentials.kimiCode.refreshToken = 'synthetic-refresh-rotated'; + doc.unrelated.newSetting = 'preserved'; + write(f.controller.configFile, doc); + write(f.controller.connectionFile, { ...f.connection, enabled: false }); + await f.controller.tick(); + expect(f.controller.status.code).toBe('disconnected'); + const after = read(f.controller.configFile); + expect(after.model.providers['daimon-kimi-code'].baseUrl).toBe(official); + expect(after.credentials.kimiCode.refreshToken).toBe('synthetic-refresh-rotated'); + expect(after.unrelated.newSetting).toBe('preserved'); + expect(f.calls.at(-1).method).toBe('conversations.setModel'); + expect(fs.existsSync(f.controller.modelBackupFile)).toBe(false); + expect(fs.existsSync(path.join(f.controller.stateDir, 'backups'))).toBe(false); + } finally { await f.cleanup(); } +}); + +test('disconnect returns a selected menu alias to the original model without losing native entries', async () => { + const f=await fixture(); + try { + await f.controller.tick(); + let models=f.calls.find(x=>x.method==='conversations.updateKimiModelList').params.models; + const base=f.controller.rpcCall; + f.controller.rpcCall=async(runner,method,params)=>{ + if(method==='conversations.getKimiModelList')return {models}; + if(method==='conversations.updateKimiModelList')models=params.models; + if(method==='conversations.setModel'){ + const doc=read(f.controller.configFile);doc.model.current=params.modelAlias;write(f.controller.configFile,doc); + } + return base(runner,method,params); + }; + const doc=read(f.controller.configFile);doc.model.current=f.controller.catalog[1].alias;write(f.controller.configFile,doc); + write(f.controller.connectionFile,{...f.connection,enabled:false}); + await f.controller.tick(); + expect(read(f.controller.configFile).model.current).toBe('k2d8-preview'); + expect(models).toEqual([{model:'k2d8-preview'}]); + expect(read(f.controller.configFile).credentials).toEqual(f.doc.credentials); + expect(read(f.controller.catalogFile).enabled).toBe(false); + }finally{await f.cleanup();} +}); + +test('long Work turns keep the native menu alive without reloading the busy runtime', async () => { + const f=await fixture(); + try { + await f.controller.tick(); + const calls=f.calls.length; + const catalog=read(f.controller.catalogFile); + write(f.controller.catalogFile,{...catalog,updatedAt:'2000-01-01T00:00:00Z'}); + write(f.controller.runnerFile,{...read(f.controller.runnerFile),activeKernelTurns:1}); + f.controller.catalogAfter=0; + await f.controller.tick(); + expect(Date.now()-Date.parse(read(f.controller.catalogFile).updatedAt)).toBeLessThan(5000); + expect(read(f.controller.catalogFile).models).toEqual(catalog.models); + expect(f.calls.length).toBe(calls); + }finally{await f.cleanup();} +}); + +test('requests without Kimi auth, browser requests and unknown paths never reach a supplier', async () => { + const f = await fixture(); + try { + await f.controller.tick(); + for (const [suffix, headers, status] of [ + ['/chat/completions', {}, 401], + ['/chat/completions', { Authorization: 'Bearer synthetic-kimi-key', Origin: 'https://example.invalid' }, 403], + ['/unknown', { Authorization: 'Bearer synthetic-kimi-key' }, 404], + ]) { + const response = await fetch(f.controller.bridgeURL + suffix, { method: 'POST', headers, body: '{}' }); + expect(response.status).toBe(status); await response.text(); + } + expect(f.requests).toHaveLength(0); + expect(f.tools).toHaveLength(0); + } finally { await f.cleanup(); } +}); + +test('waits for active Work tasks; pauses on outside config changes; explicit reconnect recovers', async () => { + const f = await fixture(); + try { + const runner = read(f.controller.runnerFile); + write(f.controller.runnerFile, { ...runner, activeKernelTurns: 1 }); + await f.controller.tick(); + expect(f.controller.status.code).toBe('waiting_kimi_idle'); + expect(f.calls).toHaveLength(0); + write(f.controller.runnerFile, runner); + await f.controller.tick(); + expect(f.controller.status.code).toBe('connected'); + const doc = read(f.controller.configFile); + doc.model.providers['daimon-kimi-code'].baseUrl = official; + write(f.controller.configFile, doc); + await f.controller.tick(); + expect(f.controller.status.code).toBe('kimi_config_changed'); + await f.controller.tick(); + expect(read(f.controller.configFile).model.providers['daimon-kimi-code'].baseUrl).toBe(official); + write(f.controller.connectionFile, { ...f.connection, enabled: false }); + await f.controller.tick(); + write(f.controller.connectionFile, f.connection); + await f.controller.tick(); + expect(f.controller.status.code).toBe('connected'); + } finally { await f.cleanup(); } +}); + +test('rejects remote gateway and control endpoints before changing Kimi', async () => { + const f = await fixture(); + try { + write(f.controller.connectionFile, { ...f.connection, gateway: { url: 'http://example.invalid/v1', key: 'synthetic' } }); + await f.controller.tick(); + expect(f.controller.status.code).toBe('invalid_gateway'); + expect(read(f.controller.configFile)).toEqual(f.doc); + expect(() => controlEndpoint({ control: { endpoint: { url: 'ws://example.invalid/control', auth: { token: 'synthetic' } } } })).toThrow(); + expect(agent.id).toBe('kimi-desktop'); + expect(connect({ gateway: { v1: 'http://127.0.0.1:3425/v1', key: 'synthetic' } })['gateway.key']).toBe('synthetic'); + } finally { await f.cleanup(); } +}); + +test('the identified gateway catalog updates visibility without opening Magpie files, even during an active turn',async()=>{ + const f=await fixture(); + try{ + await f.controller.tick(); + const removed=f.controller.catalog.find(x=>x.id==='other-provider/other-model'); + const magpieDir = path.join(f.directory, 'magpie'); + fs.mkdirSync(magpieDir); + fs.writeFileSync(path.join(magpieDir, 'providers.json'), 'not JSON: must never be opened'); + fs.writeFileSync(path.join(magpieDir, 'settings.json'), 'not JSON: policy belongs to gateway'); + f.models.splice(1); + const response=await fetch(f.controller.bridgeURL+'/chat/completions',{method:'POST',headers:{Authorization:'Bearer synthetic-kimi-key'}, + body:JSON.stringify({model:removed.alias,messages:[]})}); + expect(response.status).toBe(409);expect(f.requests).toHaveLength(0); + const runner=read(f.controller.runnerFile);runner.activeKernelTurns=['synthetic-turn'];write(f.controller.runnerFile,runner); + f.controller.catalogAfter=0;await f.controller.tick(); + expect(f.controller.catalog.map(x=>x.id)).toEqual(['original-provider/test-model']); + expect(read(f.controller.catalogFile)).toMatchObject({exclusive:true,enabled:true}); + expect(read(f.controller.catalogFile).models).toHaveLength(1); + }finally{await f.cleanup();} +}); + +test('reconnects retain only changed model fields, never a full credential backup', async () => { + const f = await fixture(); + try { + for (let i = 0; i < 2; i++) { + write(f.controller.connectionFile, f.connection); + f.controller.catalogAfter = 0; + await f.controller.tick(); + expect(f.controller.status.code).toBe('connected'); + const saved = fs.readdirSync(f.controller.stateDir).map(name => fs.readFileSync(path.join(f.controller.stateDir, name), 'utf8')).join('\n'); + expect(saved).not.toContain('synthetic-kimi-key'); + expect(saved).not.toContain('synthetic-refresh-before'); + write(f.controller.connectionFile, {...f.connection, enabled: false}); + await f.controller.tick(); + expect(fs.existsSync(f.controller.modelBackupFile)).toBe(false); + } + } finally { await f.cleanup(); } +}); + +test('disconnect restores the address even when Kimi removes a private catalog method', async () => { + const f = await fixture(); + try { + await f.controller.tick(); + f.controller.rpcCall = async () => {throw Error('kimi_control_rejected');}; + write(f.controller.connectionFile, {...f.connection, enabled: false}); + await f.controller.tick(); + expect(read(f.controller.configFile).model.providers['daimon-kimi-code'].baseUrl).toBe(official); + expect(read(f.controller.configFile).credentials).toEqual(f.doc.credentials); + expect(fs.existsSync(f.controller.modelBackupFile)).toBe(true); + expect(f.controller.state.active).toBe(false); + } finally {await f.cleanup();} +}); + +test('loading an agent never installs signal handlers in the shared plugin host', () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'kimi-empty-host-')); + const entry = pathToFileURL(fileURLToPath(new URL('./index.mjs', import.meta.url))).href; + try { + const child = spawnSync(process.execPath, ['--eval', ` + const before = ['SIGTERM','SIGINT'].map(s => process.listenerCount(s)); + const plugin = (await import(${JSON.stringify(entry)})).default; + await plugin({}); + if (['SIGTERM','SIGINT'].some((s,i) => process.listenerCount(s) !== before[i])) throw Error('shared signal handlers changed'); + console.log('host preserved'); + `], {env: {...process.env, HOME: home, USERPROFILE: home, APPDATA: home}, encoding: 'utf8', timeout: 10000}); + expect(child.status).toBe(0); + expect(child.stdout).toContain('host preserved'); + } finally { fs.rmSync(home, {recursive: true, force: true}); } +}); diff --git a/packages/kimi-desktop/package.json b/packages/kimi-desktop/package.json new file mode 100644 index 0000000..8526fed --- /dev/null +++ b/packages/kimi-desktop/package.json @@ -0,0 +1,32 @@ +{ + "name": "@magpie-community/agent-kimi-desktop", + "version": "0.1.0", + "description": "Kimi desktop Work as a Magpie agent, using the models configured in Magpie", + "type": "module", + "main": "./index.mjs", + "files": [ + "kimi-desktop.agent.js", + "index.mjs", + "adapter.mjs", + "rpc.mjs", + "catalog.mjs", + "README.md", + "COMPATIBILITY.md" + ], + "keywords": [ + "magpie", + "magpie-agent", + "kimi", + "kimi-work" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/kimi-desktop" + }, + "magpie": { + "agent": "./kimi-desktop.agent.js", + "icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAABwCAMAAADxPgR5AAACvlBMVEUAAAAAAAECAgMNDQ0BAQEdHR4BAQICAQGYmJgBAQEAAAAGBgVoaGhGRkYJCQgiIyJpaWkCAgWSkpIzNDMICQkDAwM4OTglJiWMjowwMTCKi4tDQ0JNTk56fHl7e3unqKd7fXwLCwsAAAB3d3dmZ2cAAAGXl5dqa2tISEgDAwKGiIYCAgQCAgJoaGh8fnxlZWVeXl4GBwbU1dTExsSpqamkpKSen56Pj48VFRURExKztLMwMTABAAUAAAIsLS2tr6q3vLp5e3m0tbWVlZUKCg7GyMgrLSsFBQUDAwQAAAEBAQP///8CAgECAwIEBAMFBQUHBwcGBwUICQgLCwsEAwcFBQMNDQ0KCgkFBQcMDQsXg/8QEBAICAoSEhMODg4KCQvf398jJCQPDhAzNDMlJSYLCw0fICAbHBxCQkJhYWEmJyciIiIeHh40NTQpKipAQUIgISEWFhUyMjFFRUUZGhoVFRU6OzsUFBMRERJISUg9Pj4XGBg5OTkoKCgODgxVVlUtLS3v7/BiY2I8PDwWFhdkZWRAQD81NTYd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0YiBUiiBxOFHwUTQVo0ZCwX4CWUsPs30MjUSdYVTSU0zBo1pK4Dq1qERySghQb+0TXkFRgSrekU6p+WZuebWstmM35o6ncSaKEWQZFeU4IbicJPIpNAUTUE1utSv1d9036WG734/g6RoaOCZuINCNC2XWxzHWUqQyxfoecK2rSUZLYlG9WG4bL1pia6eyviT9dv6AJ1uUVk6DCIVKg15jFp/Ox6rRAfFUqOD1z4kahHq7UQ3hkfGeh4S83fjBrvx1o2jl+0sFtvAMvmUiqxLpSRGzTfkTs682Yy/mLpouiN9O10stkGzjqDJasmbqGTf9V68H39de98Bi69LrzIfio1OAHPjd55XU5lwWe9iC47fYKpF59g6zHRf5a8lsJDC7DIsmzmF8XdT56ymAlXoRTUizjfaHYwsjL8uddLiF+96b2KdV93+lxR6wvV8/N2g2WrXqahFefnkcOPIvCNXACyhvg4BhSzqyK9a/DXuXzKX7JqOYM+v6/BwxtunX3Ve9j6F37zNNFKNFy96mSepj/hz1ysyl0ohAMLx8zlHjtgPHRrOfw2s63d5t9PUze0L5wzT/s/SpbMW7dk5Y8GOrVtWLO+n4523oTevM1Sl1ymYBpVGqelHNVDELz4mZQ0/dkemTZq0cv7kGWvXzVw/9w/H658B4/5FYKGK3+sAAAAASUVORK5CYII=" + } +} diff --git a/packages/kimi-desktop/rpc.mjs b/packages/kimi-desktop/rpc.mjs new file mode 100644 index 0000000..04174bd --- /dev/null +++ b/packages/kimi-desktop/rpc.mjs @@ -0,0 +1,42 @@ +export function controlEndpoint(state) { + const endpoint = state?.control?.endpoint; + let url; + try { url = new URL(endpoint?.url); } catch { throw Error('kimi_control_unavailable'); } + if (url.protocol !== 'ws:' || !['127.0.0.1', '[::1]'].includes(url.hostname) + || !url.port || url.pathname !== '/control' || url.username || url.password + || url.search || url.hash || typeof endpoint?.auth?.token !== 'string' + || !endpoint.auth.token) throw Error('kimi_control_unavailable'); + return endpoint; +} + +// Bun supplies the authenticated WebSocket client; no browser or Kimi Code CLI. +export async function rpc(state, method, params = {}, { timeout = 6000, Socket = globalThis.WebSocket } = {}) { + if (!['models.current', 'conversations.setModel', 'conversations.getKimiModelList', + 'conversations.updateKimiModelList'].includes(method)) throw Error('unsupported_control_method'); + const endpoint = controlEndpoint(state); + return new Promise((resolve, reject) => { + let socket, settled = false; + const finish = (error, value) => { + if (settled) return; + settled = true; + clearTimeout(timer); + try { socket?.close(); } catch { /* Already closed. */ } + error ? reject(Error(error)) : resolve(value); + }; + const timer = setTimeout(() => finish('kimi_control_timeout'), timeout); + try { + socket = new Socket(endpoint.url, { headers: { Authorization: 'Bearer ' + endpoint.auth.token } }); + socket.addEventListener('error', () => finish('kimi_control_unavailable')); + socket.addEventListener('close', () => finish('kimi_control_closed')); + socket.addEventListener('open', () => { + socket.send(JSON.stringify({ jsonrpc: '2.0', id: 1, method, params })); + }); + socket.addEventListener('message', event => { + let message; + try { message = JSON.parse(String(event.data)); } catch { return; } + if (message.id !== 1) return; + finish(message.error ? 'kimi_control_rejected' : null, message.result); + }); + } catch { finish('kimi_control_unavailable'); } + }); +} diff --git a/registry.json b/registry.json index 8c8dfce..ede12ee 100644 --- a/registry.json +++ b/registry.json @@ -59,6 +59,7 @@ { "package": "@magpie-community/tools-calc", "name": "Calc", "kind": "tools", "community": true, "summary": { "en": "Exact arithmetic, unit conversion and calendar date math as tools for every agent: no network, no key.", "zh": "给每个 agent 的精确计算、单位换算和日历日期计算工具:不联网,不需要 key。" } }, { "package": "@magpie-community/page-usage", "name": "Usage Glance", "kind": "page", "community": true, - "summary": { "en": "A page in magpie's window with calls, errors, tokens and cost for today, 7 or 30 days, and the models behind them. Reads only your usage summary.", "zh": "在 magpie 窗口里一眼看到今天、7 天或 30 天的调用、错误、token、费用和对应模型。只读取用量汇总。" } } + "summary": { "en": "A page in magpie's window with calls, errors, tokens and cost for today, 7 or 30 days, and the models behind them. Reads only your usage summary.", "zh": "在 magpie 窗口里一眼看到今天、7 天或 30 天的调用、错误、token、费用和对应模型。只读取用量汇总。" } }, + {"package": "@magpie-community/agent-kimi-desktop", "name": "Kimi", "kind": "agent", "community": true, "summary": {"en": "Kimi desktop Work on Magpie's Agents page: select a model from Magpie, then disconnect to restore the original service. Not Kimi Code CLI.", "zh": "把普通 Kimi 桌面版 Work 接入 Magpie Agent 页,使用已配置的模型;断开恢复原连接。不是 Kimi Code CLI。"}} ] }