kimi-desktop 0.1.5: Retry-After is kept, and an owner record is never left half-written (#225)
Kimi Work's 429/503 through the desktop adapter now keep the upstream Retry-After (seconds and HTTP-date); no other upstream header is copied. The adapter's owner record is written whole to a temp file and published with an exclusive hard link, so a crash mid-write can no longer leave an empty adapter-owner.json that blocks every later host. A malformed record reports adapter_lock_invalid (and an access failure adapter_lock_unavailable) in status.json and the log, instead of failing silently; the README says how to recover. Review merge: main (kimi-desktop 0.1.4) merged in, package.json the only conflict, version 0.1.5. Run at 3f65c63 (HOME=$(mktemp -d)): - mote: bun test packages/kimi-desktop 36 pass, 0 fail. - Windows (xiaomi-gpu, win-run): 36 pass, 0 fail (hard links on NTFS). - Broken by hand, each reverted: Retry-After not forwarded -> its test red; the owner record written in place instead of linked -> 3 lock tests red; a malformed record silently returning false -> the malformed-record test red. Not tried with the real Kimi desktop app.
This commit is contained in:
@@ -28,6 +28,8 @@ The import-free `kimi-desktop.agent.js` registers the agent using Magpie's agent
|
||||
|
||||
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
|
||||
@@ -58,6 +60,8 @@ The 3.2.18 check includes real model requests, four background-control turns, an
|
||||
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
1. Close Kimi normally. In `~/.config/magpie-kimi/connection.json`, set `enabled` to `false` so the adapter does not reconnect when Magpie next starts.
|
||||
|
||||
@@ -114,20 +114,35 @@ export class KimiAdapter {
|
||||
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 before;
|
||||
try { before = fs.readFileSync(this.lockFile, 'utf8'); }
|
||||
catch (error) { if (error.code !== 'ENOENT') throw Error('adapter_lock_unavailable'); }
|
||||
if (before !== undefined) {
|
||||
let owner;
|
||||
try { owner = JSON.parse(before); } catch { throw Error('adapter_lock_invalid'); }
|
||||
if (!Number.isSafeInteger(owner?.pid) || owner.pid <= 0 || owner.pid > 2147483647
|
||||
|| typeof owner.ownerID !== 'string' || !owner.ownerID) throw Error('adapter_lock_invalid');
|
||||
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 {
|
||||
if (fs.readFileSync(this.lockFile, 'utf8') !== before) return false;
|
||||
fs.unlinkSync(this.lockFile);
|
||||
} catch (error) { if (error.code !== 'ENOENT') throw Error('adapter_lock_unavailable'); }
|
||||
}
|
||||
// Publish a complete record exclusively. A crash during the staging write
|
||||
// cannot leave a truncated owner record that blocks every future host.
|
||||
const staged = this.lockFile + '.' + process.pid + '.' + crypto.randomBytes(6).toString('hex') + '.tmp';
|
||||
try {
|
||||
fs.writeFileSync(this.lockFile, JSON.stringify({ pid: process.pid, ownerID: this.ownerID }), { flag: 'wx', mode: 0o600 });
|
||||
fs.writeFileSync(staged, JSON.stringify({ pid: process.pid, ownerID: this.ownerID }), { flag: 'wx', mode: 0o600 });
|
||||
fs.linkSync(staged, this.lockFile);
|
||||
this.locked = true;
|
||||
try { this.state = readJSON(this.stateFile); } catch { this.state = { active: false }; }
|
||||
return true;
|
||||
} catch { return false; }
|
||||
} catch (error) {
|
||||
if (error.code === 'EEXIST') return false;
|
||||
throw Error('adapter_lock_unavailable');
|
||||
} finally { try { fs.unlinkSync(staged); } catch { /* Never published, or already unlinked. */ } }
|
||||
}
|
||||
|
||||
releaseLock() {
|
||||
@@ -140,7 +155,7 @@ export class KimiAdapter {
|
||||
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);
|
||||
if (code.endsWith('_failed') || code.startsWith('adapter_lock_') || code === 'kimi_config_changed') this.log(code);
|
||||
}
|
||||
|
||||
saveState() { atomicJSON(this.stateFile, this.state); }
|
||||
@@ -240,8 +255,11 @@ export class KimiAdapter {
|
||||
: 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' });
|
||||
const responseHeaders = { 'Content-Type': upstream.headers.get('content-type') || 'application/json',
|
||||
'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' };
|
||||
const retryAfter = upstream.headers.get('retry-after');
|
||||
if (retryAfter !== null) responseHeaders['Retry-After'] = retryAfter;
|
||||
res.writeHead(upstream.status, responseHeaders);
|
||||
res.flushHeaders();
|
||||
if (upstream.body) for await (const chunk of upstream.body) {
|
||||
if (!res.write(chunk)) await once(res, 'drain', { signal: controller.signal });
|
||||
@@ -411,7 +429,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',
|
||||
'library_path_conflict', 'adapter_lock_invalid', 'adapter_lock_unavailable',
|
||||
'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);
|
||||
|
||||
@@ -206,6 +206,141 @@ test('Kimi menu aliases route independently and removed models fail closed', asy
|
||||
} finally {await f.cleanup();}
|
||||
});
|
||||
|
||||
test('rate-limit responses retain Retry-After, status and body without forwarding credentials', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
await f.controller.tick();
|
||||
const original = f.controller.fetchImpl;
|
||||
for (const [status, retry] of [[429, '17'], [503, 'Wed, 21 Oct 2037 07:28:00 GMT']]) {
|
||||
const body = JSON.stringify({error: {type: 'rate_limit_error', message: 'Synthetic upstream failure'}});
|
||||
f.controller.fetchImpl = async (url, options) => String(url).endsWith('/models')
|
||||
? original(url, options) : new Response(body, {status, headers: {
|
||||
'Content-Type': 'application/json', 'Retry-After': retry,
|
||||
'Set-Cookie': 'synthetic-cookie', Authorization: 'Bearer synthetic-secret',
|
||||
}});
|
||||
const response = await fetch(f.controller.bridgeURL + '/chat/completions', {method: 'POST',
|
||||
headers: {Authorization: 'Bearer synthetic-kimi-key'}, body: JSON.stringify({model: 'k2d8-preview', messages: []})});
|
||||
expect(response.status).toBe(status);
|
||||
expect(response.headers.get('retry-after')).toBe(retry);
|
||||
expect(await response.text()).toBe(body);
|
||||
expect(response.headers.get('authorization')).toBeNull();
|
||||
expect(response.headers.get('set-cookie')).toBeNull();
|
||||
}
|
||||
} finally { await f.cleanup(); }
|
||||
});
|
||||
|
||||
test('malformed owner records report a fixed error without taking an unknown lock', async () => {
|
||||
for (const contents of ['', '{"pid":', '{}', '{"pid":0,"ownerID":"synthetic"}', '{"pid":1}']) {
|
||||
const f = await fixture();
|
||||
try {
|
||||
fs.writeFileSync(f.controller.lockFile, contents);
|
||||
const logs = [];
|
||||
f.controller.log = code => logs.push(code);
|
||||
await f.controller.tick();
|
||||
await f.controller.tick();
|
||||
expect(f.controller.status.code).toBe('adapter_lock_invalid');
|
||||
expect(read(f.controller.statusFile).code).toBe('adapter_lock_invalid');
|
||||
expect(logs).toEqual(['adapter_lock_invalid']);
|
||||
expect(fs.readFileSync(f.controller.lockFile, 'utf8')).toBe(contents);
|
||||
expect(read(f.controller.configFile)).toEqual(f.doc);
|
||||
expect(f.controller.live).toBeNull();
|
||||
} finally { await f.cleanup(); }
|
||||
}
|
||||
});
|
||||
|
||||
test('owner records are fully written before exclusive atomic publication', async () => {
|
||||
const f = await fixture();
|
||||
const link = fs.linkSync;
|
||||
let published = false;
|
||||
try {
|
||||
fs.linkSync = (source, target) => {
|
||||
if (target === f.controller.lockFile) {
|
||||
expect(read(source)).toEqual({pid: process.pid, ownerID: f.controller.ownerID});
|
||||
expect(fs.existsSync(target)).toBe(false);
|
||||
published = true;
|
||||
}
|
||||
return link(source, target);
|
||||
};
|
||||
await f.controller.tick();
|
||||
expect(published).toBe(true);
|
||||
expect(f.controller.status.code).toBe('connected');
|
||||
expect(fs.readdirSync(f.controller.stateDir).filter(x => x.endsWith('.tmp'))).toEqual([]);
|
||||
} finally { fs.linkSync = link; await f.cleanup(); }
|
||||
});
|
||||
|
||||
test('failed owner publication leaves no partial lock or staged file', async () => {
|
||||
for (const phase of ['write', 'link']) {
|
||||
const f = await fixture();
|
||||
const link = fs.linkSync, writeFile = fs.writeFileSync;
|
||||
try {
|
||||
fs.writeFileSync = (file, data, options) => {
|
||||
if (phase === 'write' && String(file).startsWith(f.controller.lockFile + '.') && String(file).endsWith('.tmp')) {
|
||||
writeFile(file, '{"pid":', options);
|
||||
throw Object.assign(Error('synthetic interrupted staging write'), {code: 'EIO'});
|
||||
}
|
||||
return writeFile(file, data, options);
|
||||
};
|
||||
fs.linkSync = (source, target) => {
|
||||
if (phase === 'link' && target === f.controller.lockFile) throw Object.assign(Error('synthetic publication failure'), {code: 'EIO'});
|
||||
return link(source, target);
|
||||
};
|
||||
await f.controller.tick();
|
||||
expect(f.controller.status.code).toBe('adapter_lock_unavailable');
|
||||
expect(fs.existsSync(f.controller.lockFile)).toBe(false);
|
||||
expect(fs.readdirSync(f.controller.stateDir).filter(x => x.endsWith('.tmp'))).toEqual([]);
|
||||
expect(read(f.controller.configFile)).toEqual(f.doc);
|
||||
} finally { fs.linkSync = link; fs.writeFileSync = writeFile; await f.cleanup(); }
|
||||
}
|
||||
});
|
||||
|
||||
test('a competing exclusive publication keeps its complete owner record', async () => {
|
||||
const f = await fixture();
|
||||
const link = fs.linkSync;
|
||||
const other = {pid: process.pid, ownerID: 'synthetic-other-owner'};
|
||||
try {
|
||||
fs.linkSync = (source, target) => {
|
||||
if (target === f.controller.lockFile) write(target, other);
|
||||
return link(source, target);
|
||||
};
|
||||
await f.controller.tick();
|
||||
expect(read(f.controller.lockFile)).toEqual(other);
|
||||
expect(f.controller.locked).not.toBe(true);
|
||||
expect(f.controller.live).toBeNull();
|
||||
expect(fs.readdirSync(f.controller.stateDir).filter(x => x.endsWith('.tmp'))).toEqual([]);
|
||||
expect(read(f.controller.configFile)).toEqual(f.doc);
|
||||
} finally { fs.linkSync = link; await f.cleanup(); }
|
||||
});
|
||||
|
||||
test('a complete record belonging to an exited owner can still be reclaimed', async () => {
|
||||
const f = await fixture();
|
||||
const kill = process.kill;
|
||||
try {
|
||||
write(f.controller.lockFile, {pid: 2147483647, ownerID: 'synthetic-exited-owner'});
|
||||
process.kill = (pid, signal) => {
|
||||
if (pid === 2147483647 && signal === 0) throw Object.assign(Error('synthetic exited process'), {code: 'ESRCH'});
|
||||
return kill(pid, signal);
|
||||
};
|
||||
await f.controller.tick();
|
||||
expect(read(f.controller.lockFile)).toEqual({pid: process.pid, ownerID: f.controller.ownerID});
|
||||
expect(f.controller.status.code).toBe('connected');
|
||||
} finally { process.kill = kill; await f.cleanup(); }
|
||||
});
|
||||
|
||||
test('another adapter never replaces a valid live owner record', async () => {
|
||||
const f = await fixture();
|
||||
let second;
|
||||
try {
|
||||
await f.controller.tick();
|
||||
const before = fs.readFileSync(f.controller.lockFile);
|
||||
second = new KimiAdapter({stateDir: f.controller.stateDir, kimiDir: f.controller.kimiDir, stabilityMs: 0});
|
||||
await second.tick();
|
||||
expect(fs.readFileSync(f.controller.lockFile)).toEqual(before);
|
||||
expect(second.locked).not.toBe(true);
|
||||
expect(second.live).toBeNull();
|
||||
expect(f.controller.live).not.toBeNull();
|
||||
} finally { await second?.stop(); await f.cleanup(); }
|
||||
});
|
||||
|
||||
test('disconnect restores one address while retaining refreshed credentials and unrelated changes', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/agent-kimi-desktop",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.5",
|
||||
"description": "Kimi desktop Work as a Magpie agent, using the models configured in Magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user