diff --git a/packages/kimi-desktop/COMPATIBILITY.md b/packages/kimi-desktop/COMPATIBILITY.md index b5fe565..fb3be61 100644 --- a/packages/kimi-desktop/COMPATIBILITY.md +++ b/packages/kimi-desktop/COMPATIBILITY.md @@ -1,5 +1,13 @@ # macOS compatibility record +## Library upgrade 0.1.1 + +On Windows 11, Kimi 3.2.17.10, 2026-10-17: a disabled synthetic server placed in the ordinary desktop runtime's `runtime/kimi-code/home/mcp.json` appeared in the real authenticated `mcp.list` result. A synthetic skill placed in the ordinary desktop runtime's `skills` appeared in the real `skills.list` result. Both fixtures were removed and the original MCP bytes restored after the probe. No server command or skill was executed. + +An isolated synthetic Kimi configuration and upgraded adapter forwarded a shared instruction through the upgraded Work provider to the actual Work service using the existing desktop sign-in. The streamed response was HTTP 200, completed with `[DONE]`, and returned the exact marker present only in the shared instruction. This was a bridge request, not a desktop UI-submitted turn. Neither running Magpie nor Kimi was switched during the test. Fourteen agent tests passed, covering hot instruction changes/removal, unreadable instruction refusal, native directory links, preservation and existing bridge behavior. + +The same disabled MCP/skill discovery probe passed on macOS 26.6.2 arm64, ordinary Kimi 3.2.17 build 3.2.17.4, at 2026-10-17 04:37 UTC. Real `mcp.list` and `skills.list` both found their synthetic fixtures, then the original MCP bytes were restored and both fixtures removed. The 0.1.1 package created both directory symlinks in a temporary fixture; the 0.1.4 provider read the real desktop sign-in, returned `k3-agent` and `k2d8-preview`, and read one shared-allowance window. These calls did not execute an MCP command, invoke a skill or submit a desktop conversation. The earlier macOS inference record below remains the separate 0.1.0 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: diff --git a/packages/kimi-desktop/README.md b/packages/kimi-desktop/README.md index 1260664..e768e3b 100644 --- a/packages/kimi-desktop/README.md +++ b/packages/kimi-desktop/README.md @@ -10,6 +10,18 @@ Open and sign in to Kimi desktop. On Magpie's Agents page select **Kimi**, pick Disconnect Kimi in Magpie to restore its original model service address. Existing conversations, login credentials, unrelated settings, and native model entries are preserved. +## 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 with `instructions_unavailable` rather 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.json` to ordinary Kimi's `daimon-share/daimon/runtime/kimi-code/home/mcp.json`. The format is Kimi's `mcpServers` object. 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-skills` to ordinary Kimi's `daimon-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. diff --git a/packages/kimi-desktop/adapter.mjs b/packages/kimi-desktop/adapter.mjs index 62a0e29..e7614fb 100644 --- a/packages/kimi-desktop/adapter.mjs +++ b/packages/kimi-desktop/adapter.mjs @@ -6,6 +6,7 @@ import crypto from 'node:crypto'; import { once } from 'node:events'; import { rpc } from './rpc.mjs'; import { normalizeModels, mergeRuntimeModels, isMenuAlias } from './catalog.mjs'; +import { prepareLibrary, applyInstructions } from './library.mjs'; const PROVIDER = 'daimon-kimi-code'; const TOOL_ORIGIN = 'https://agent-gw.kimi.com'; @@ -69,6 +70,7 @@ export class KimiAdapter { 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.instructionsFile = path.join(this.stateDir, 'AGENTS.md'); this.catalog = []; Object.assign(this, { intervalMs, stabilityMs, rpcCall, fetchImpl, log }); this.ownerID = crypto.randomUUID(); @@ -83,6 +85,7 @@ export class KimiAdapter { bootstrap() { if (!fs.existsSync(this.configFile)) return false; fs.mkdirSync(this.stateDir, { recursive: true, mode: 0o700 }); + prepareLibrary(this.stateDir, this.kimiDir); if (!fs.existsSync(this.connectionFile)) { try { fs.writeFileSync(this.connectionFile, JSON.stringify({ schemaVersion: 1, enabled: false, @@ -211,6 +214,8 @@ export class KimiAdapter { catch { error(503, 'catalog_unavailable'); return; } if (!allowed.some(row => row.id === model)) { error(409, 'model_not_enabled_for_kimi'); return; } payload.model = model; + try { payload = applyInstructions(payload, this.instructionsFile); } + catch (failure) { error(failure.message === 'invalid_messages' ? 400 : 503, failure.message); return; } } const headers = { 'Content-Type': 'application/json', Authorization: inference ? 'Bearer ' + active.gatewayKey : req.headers.authorization }; @@ -391,6 +396,7 @@ export class KimiAdapter { this.report('connected', { model: desired.model }); } catch (error) { const codes = new Set(['invalid_gateway', 'invalid_connection', 'unsupported_kimi_config', + 'library_path_conflict', '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); diff --git a/packages/kimi-desktop/kimi-desktop.agent.js b/packages/kimi-desktop/kimi-desktop.agent.js index 78f5318..34b9471 100644 --- a/packages/kimi-desktop/kimi-desktop.agent.js +++ b/packages/kimi-desktop/kimi-desktop.agent.js @@ -6,6 +6,12 @@ export const agent = { format: 'json', model: 'model', dir: '~/.config/magpie-kimi', + library: { + instructions: '~/.config/magpie-kimi/AGENTS.md', + mcp: '~/.config/magpie-kimi/library-native/mcp.json', + mcpFormat: 'kimi', + skills: '~/.config/magpie-kimi/library-skills', + }, ua: ['Desktop Kimi Work'], notice: '接入普通 Kimi 桌面版的 Work。请先打开 Kimi,插件会在本地 Agent 就绪后连接;Chat 不受影响。', }; diff --git a/packages/kimi-desktop/kimi-desktop.test.mjs b/packages/kimi-desktop/kimi-desktop.test.mjs index 08603cc..180e330 100644 --- a/packages/kimi-desktop/kimi-desktop.test.mjs +++ b/packages/kimi-desktop/kimi-desktop.test.mjs @@ -8,11 +8,66 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import { KimiAdapter } from './adapter.mjs'; import { controlEndpoint } from './rpc.mjs'; import { agent, connect } from './kimi-desktop.agent.js'; +import { applyInstructions } from './library.mjs'; 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)); }; +test('Library uses ordinary Kimi native resources while keeping prior MCP and skills', async () => { + const f = await fixture(); + try { + const native = path.join(f.kimiDir || f.controller.kimiDir, 'runtime/kimi-code/home'); + const mcp = {mcpServers: {existing: {url: 'https://example.invalid/mcp'}}}; + write(path.join(native, 'mcp.json'), mcp); + const skill = path.join(f.controller.kimiDir, 'skills/existing/SKILL.md'); + fs.mkdirSync(path.dirname(skill), {recursive: true}); + fs.writeFileSync(skill, 'synthetic existing skill'); + f.controller.bootstrap(); + expect(read(path.join(f.controller.stateDir, 'library-native/mcp.json'))).toEqual(mcp); + expect(fs.readFileSync(path.join(f.controller.stateDir, 'library-skills/existing/SKILL.md'), 'utf8')).toBe('synthetic existing skill'); + expect(agent.library.mcpFormat).toBe('kimi'); + expect(agent.library.instructions).toEndWith('/AGENTS.md'); + fs.unlinkSync(path.join(f.controller.stateDir, 'library-native')); + fs.mkdirSync(path.join(f.controller.stateDir, 'library-native')); + expect(() => f.controller.bootstrap()).toThrow('library_path_conflict'); + expect(read(path.join(native, 'mcp.json'))).toEqual(mcp); + } finally { await f.cleanup(); } +}); + +test('shared instructions hot-update in existing conversations without replacing Kimi prompts or tools', async () => { + const f = await fixture(); + try { + await f.controller.tick(); + const original = {model: 'k2d8-preview', messages: [ + {role: 'system', content: 'Kimi native system prompt'}, + {role: 'user', content: [{type: 'text', text: 'synthetic history'}]}, + {role: 'assistant', tool_calls: [{id: 'synthetic-call', type: 'function', function: {name: 'Read', arguments: '{}'}}]}, + {role: 'tool', tool_call_id: 'synthetic-call', content: 'synthetic tool result'}, + ]}; + for (const text of ['synthetic rule one', 'synthetic rule two', '']) { + fs.writeFileSync(f.controller.instructionsFile, text); + const response = await fetch(f.controller.bridgeURL + '/chat/completions', {method: 'POST', + headers: {Authorization: 'Bearer synthetic-kimi-key'}, body: JSON.stringify(original)}); + expect(response.status).toBe(200); await response.text(); + const messages = f.requests.at(-1).body.messages; + expect(messages[0]).toEqual(original.messages[0]); + expect(messages.slice(text ? 2 : 1)).toEqual(original.messages.slice(1)); + expect(messages.filter(x => x.role === 'system')).toHaveLength(text ? 2 : 1); + if (text) expect(messages[1].content).toContain(text); + } + fs.writeFileSync(f.controller.instructionsFile, 'synthetic active rule'); + const once = applyInstructions(original, f.controller.instructionsFile); + expect(applyInstructions(once, f.controller.instructionsFile)).toEqual(once); + fs.writeFileSync(f.controller.instructionsFile, Buffer.from([0xff])); + const failed = await fetch(f.controller.bridgeURL + '/chat/completions', {method: 'POST', + headers: {Authorization: 'Bearer synthetic-kimi-key'}, body: JSON.stringify(original)}); + expect(failed.status).toBe(503); + expect((await failed.json()).error.code).toBe('instructions_unavailable'); + expect(f.requests).toHaveLength(3); + } finally { await f.cleanup(); } +}); + async function fixture() { const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'magpie-kimi-fixture-')); const kimiDir = path.join(directory, 'kimi'); @@ -260,7 +315,8 @@ test('reconnects retain only changed model fields, never a full credential backu 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'); + const saved = fs.readdirSync(f.controller.stateDir).filter(name => fs.lstatSync(path.join(f.controller.stateDir, name)).isFile()) + .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}); diff --git a/packages/kimi-desktop/library.mjs b/packages/kimi-desktop/library.mjs new file mode 100644 index 0000000..afd0387 --- /dev/null +++ b/packages/kimi-desktop/library.mjs @@ -0,0 +1,52 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +const BEGIN = ''; +const END = ''; +const LIMIT = 1024 * 1024; + +function linkDirectory(link, target) { + fs.mkdirSync(target, {recursive: true, mode: 0o700}); + let stat; + try { + stat = fs.lstatSync(link); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + // A directory junction needs no Windows developer-mode file-symlink privilege. + fs.symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir'); + return; + } + try { + if (!stat.isSymbolicLink() || fs.realpathSync(link) !== fs.realpathSync(target)) throw Error(); + } catch {throw Error('library_path_conflict');} +} + +export function prepareLibrary(stateDir, kimiDir) { + linkDirectory(path.join(stateDir, 'library-native'), path.join(kimiDir, 'runtime', 'kimi-code', 'home')); + linkDirectory(path.join(stateDir, 'library-skills'), path.join(kimiDir, 'skills')); +} + +export function applyInstructions(payload, file) { + if (!Array.isArray(payload.messages)) throw Error('invalid_messages'); + let text = ''; + try { + const stat = fs.statSync(file); + if (!stat.isFile() || stat.size > LIMIT) throw Error('instructions_unavailable'); + const bytes = fs.readFileSync(file); + if (bytes.length > LIMIT) throw Error('instructions_unavailable'); + text = new TextDecoder('utf-8', {fatal: true}).decode(bytes).replace(/^\uFEFF/, '').trim(); + } catch (error) { + if (error.code !== 'ENOENT') throw Error('instructions_unavailable'); + } + // Remove only our separate system message; leave Kimi's and the user's own + // instructions, tool messages, image parts and conversation history intact. + const messages = payload.messages.filter(message => !(message?.role === 'system' + && typeof message.content === 'string' && message.content.startsWith(BEGIN + '\n') + && message.content.endsWith('\n' + END))); + if (text) { + let at = 0; + while (['system', 'developer'].includes(messages[at]?.role)) at++; + messages.splice(at, 0, {role: 'system', content: BEGIN + '\n' + text + '\n' + END}); + } + return {...payload, messages}; +} diff --git a/packages/kimi-desktop/package.json b/packages/kimi-desktop/package.json index 8526fed..370db02 100644 --- a/packages/kimi-desktop/package.json +++ b/packages/kimi-desktop/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/agent-kimi-desktop", - "version": "0.1.0", + "version": "0.1.1", "description": "Kimi desktop Work as a Magpie agent, using the models configured in Magpie", "type": "module", "main": "./index.mjs", @@ -10,6 +10,7 @@ "adapter.mjs", "rpc.mjs", "catalog.mjs", + "library.mjs", "README.md", "COMPATIBILITY.md" ],