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

73 lines
3.5 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
const conflict = () => Object.assign(Error('agent_profile_conflict'), { code: 'agent_profile_conflict' });
const profileFile = /^local-agent-(?:[a-f0-9]{12}-)?[a-f0-9]{24}\.md$/;
const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
// Existing files are accepted only byte-for-byte. A profile edited by the user
// is never replaced. Optional ownership permits pruning retired private files.
export function ensureAgentProfiles({ directory, router, models, profiles, ownedFiles }) {
const requested = profiles ?? (models === undefined ? router.boundProfiles
: [...new Set(models)].map(model => ({ model })));
const entries = [...new Map(requested.map(({ model, role }) => {
const name = router.profileName(model, role);
if (!/^local-agent-[a-f0-9]{12}-[a-f0-9]{24}$/.test(name)) throw conflict();
return [name, { name, file: path.join(directory, name + '.md'), text: router.profileText(model, role) }];
})).values()];
const exists = entry => {
let stat;
try { stat = fs.lstatSync(entry.file); }
catch (error) { if (error.code === 'ENOENT') return false; throw error; }
if (!stat.isFile() || fs.readFileSync(entry.file, 'utf8') !== entry.text) throw conflict();
return true;
};
// Check every existing name before publishing any new profile.
const missing = entries.filter(entry => !exists(entry));
const obsolete = [];
const verifyOwned = name => {
const file = path.join(directory, name);
if (!fs.lstatSync(file).isFile() || digest(fs.readFileSync(file)) !== ownedFiles[name]) throw conflict();
};
if (ownedFiles !== undefined) {
if (!ownedFiles || typeof ownedFiles !== 'object' || Array.isArray(ownedFiles)
|| Object.entries(ownedFiles).some(([name, hash]) => !profileFile.test(name) || !/^[a-f0-9]{64}$/.test(hash))) {
throw conflict();
}
const wanted = new Set(entries.map(entry => path.basename(entry.file)));
for (const name of fs.existsSync(directory) ? fs.readdirSync(directory) : []) {
// Hidden metadata entries are never stat'd, read, hashed, deleted, or treated as conflicts.
if (name.startsWith('.')) continue;
// MUTATION profiles-ownership: unknown or edited files never become deletion authority.
if (Object.hasOwn(ownedFiles, name)) verifyOwned(name);
else if (!wanted.has(name)) throw conflict();
if (!wanted.has(name)) obsolete.push(name);
}
}
let changed = false;
if (missing.length) fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
for (const entry of missing) {
const staged = entry.file + '.' + process.pid + '.' + crypto.randomBytes(6).toString('hex') + '.tmp';
let created = false;
try {
fs.writeFileSync(staged, entry.text, { mode: 0o600, flag: 'wx' });
created = true;
// An exclusive link publishes a complete file without replacing one
// created or edited by another writer after the preflight check.
try { fs.linkSync(staged, entry.file); changed = true; }
catch (error) {
if (error.code !== 'EEXIST') throw error;
if (!exists(entry)) throw conflict();
}
} finally { if (created) fs.unlinkSync(staged); }
}
for (const name of obsolete) {
// Recheck bytes immediately before deleting an obsolete owned profile.
verifyOwned(name);
fs.unlinkSync(path.join(directory, name));
changed = true;
}
return { changed, names: entries.map(entry => entry.name) };
}