Files
Changtian Li bc5b8332ec kimi-desktop 0.1.6: per-role reasoning effort and context input budget (#813)
kimi-desktop 0.1.6: separate reasoning effort and an optional context input budget for the primary and secondary roles.

The change (f07e7f4a..1d14a185, since the round-6 approval):
- The settings page and API save `<role>ReasoningEffort` and `<role>ContextTokens` for each role. Only efforts and context limits the catalog publishes are offered; an unknown limit allows no custom budget.
- Inference drops Kimi's top-level `thinking`, `reasoning` and `reasoning_effort`, and sends the chosen effort, or none for the provider default. Kimi's native menu aliases no longer choose the model.
- A custom budget counts a copy of the request through magpie's `/v1/messages/count_tokens`. Over the budget gives 400 `context_length_exceeded`; a failed count gives fixed 503 `context_count_unavailable`. No generation is sent in either case. Without a budget, nothing extra is sent.
- Role-scoped worker profiles (`v2:[model, role]`) tell primary from secondary even on the same model. Older roleless profiles keep their binding and use defaults.
- 1d14a185 removes blank lines only.

Run at 1d14a1859f63fd4bb512d492d1de419ad3e6c79a on mote (macOS, Bun 1.4.2, HOME/TMPDIR/XDG in the run's own folder):
- `bun test` in packages/kimi-desktop: 626 pass, 0 fail, 29 files.
- `bun scripts/check.mjs kimi-desktop`: exit 0.
- 14 hand breaks, each red in the package suite:
  - drop `applyReasoningOptions`;
  - strip thinking fields only when an effort is set;
  - drop the budget check, or make it `>=`;
  - `useFresh` false, or without its model check;
  - a legacy roleless profile treated as primary;
  - a profile name without its role;
  - no `registerRoles`;
  - no `optionsMatch` in save;
  - no `refreshLiveModelOptions`;
  - count with `redirect: 'follow'`, or with no reply size limit;
  - a 131072 fallback for an unknown catalog context.
- CI at the head: test and on-npm pass. The PR merges onto main f379bf90+ with no conflicts.

Not blocking, left for a follow-up:
- Each inference now reads connection.json (adapter.mjs:547) with no fallback to the live connection. An unreadable file turns every request into 502, even without a budget.
- The comment above `applyReasoningOptions` ("Preserve the legacy connection untouched…") no longer matches the always-strip policy.
2026-11-09 10:07:07 +08:00

71 lines
3.2 KiB
JavaScript

import { execFile } from 'node:child_process';
import { constants } from 'node:fs';
import { access, readlink, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
import { promisify } from 'node:util';
const runFile = promisify(execFile);
const failure = code => Object.assign(new Error(code), { code });
async function executablePath(value) {
if (typeof value !== 'string' || !path.isAbsolute(value.trim())) return '';
try {
const resolved = await realpath(value.trim());
if (!(await stat(resolved)).isFile()) return '';
await access(resolved, constants.X_OK);
return resolved;
} catch { return ''; }
}
async function discoveredMagpiePath(value, platform) {
const names = platform === 'win32' ? /^magpie(?:\.exe)?$/i : /^magpie$/i;
const basename = value => (platform === 'win32' ? path.win32 : path).basename(value.trim());
if (typeof value !== 'string' || !names.test(basename(value))) return '';
const resolved = await executablePath(value);
// A magpie symlink must not turn an unrelated executable into the host.
return resolved && names.test(basename(resolved)) ? resolved : '';
}
// Use the running host's executable and environment so its normal agent setter
// owns the primary model, applied record and stash, including portable profiles.
export async function setPrimaryModel(model, { magpiePath, directory, env = process.env,
platform = process.platform, parentPID = process.ppid, run = runFile,
which = name => globalThis.Bun?.which?.(name) } = {}) {
let executable = '';
if (magpiePath !== undefined && magpiePath !== '') {
executable = await executablePath(magpiePath);
} else {
let parent = '';
try {
const validPID = Number.isSafeInteger(parentPID) && parentPID > 0;
const options = { cwd: directory || undefined, env,
timeout: 6000, encoding: 'utf8', windowsHide: true };
if (validPID && platform === 'darwin') {
const result = await run('/bin/ps', ['-ww', '-p', String(parentPID), '-o', 'comm='],
options);
parent = String(result.stdout || '').trim();
} else if (validPID && platform === 'linux') {
parent = await readlink(`/proc/${parentPID}/exe`);
} else if (validPID && platform === 'win32') {
const command = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; '
+ `(Get-CimInstance Win32_Process -Filter 'ProcessId=${parentPID}').ExecutablePath`;
const result = await run('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command], options);
parent = String(result.stdout || '').trim();
}
} catch { /* An explicit path or PATH may still name the host. */ }
executable = await discoveredMagpiePath(parent, platform);
if (!executable) {
try { executable = await discoveredMagpiePath(which('magpie'), platform); } catch { /* No PATH entry. */ }
}
}
if (!executable) throw failure('primary_model_unavailable');
try {
await run(executable, ['kimi-desktop', 'model', 'magpie/' + model], {
cwd: directory || undefined,
env: { ...env, MAGPIE_KIMI_SKIP_ADAPTER: '1' },
timeout: 60000,
windowsHide: true,
});
} catch { throw failure('primary_model_update_failed'); }
}