okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-s5 dab63e9c3 (tuning presets on Models, effective values, outcome codes, apply_saved_tuning) into f-split-int0c165b48b

main
8.8 KiB141 linesraw
1/**
2 * The app's side of the auto-tuner. The tuner itself is Strata Control's (`strata tune auto`, `strata presets`): the same code and the
3 * same preset store the Terminal uses, so tuning in one place covers the other. This module only runs those commands, follows the
4 * status file the tuner rewrites at every step, and turns the answer into the sentence the app shows. It measures nothing itself.
5 */
6import { spawn } from 'node:child_process';
7import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
8import { join } from 'node:path';
9
10const MODES = new Set(['quick', 'thorough']);
11const USES = new Set(['chat', 'coding']);
12
13/** The one sentence a finished tune is reported with (plain words; the numbers are the tuner's own). */
14export function resultSentence(result) {
15  if (!result) return 'The tune did not finish.';
16  const name = result.preset?.name;
17  if (result.code === 'busy_pc') return 'Your PC was busy, so the measurements were not reliable. Nothing was changed. Try again when it is quiet.';
18  if (result.outcome === 'improved') {
19    const gain = Math.max(0, Math.round(result.gain_pct ?? 0));
20    return `+${gain}% faster answers${name ? `, saved as '${name}'` : ''}`;
21  }
22  if (result.outcome === 'default_confirmed') return `Your current settings are already the fastest we found${name ? `. Saved as '${name}' so it is not tuned again` : ''}`;
23  return result.message || 'Nothing was changed.';
24}
25
26export function createAutoTune({ launcher, workDir, spawnProcess = spawn, pollMs = 1500 }) {
27  mkdirSync(workDir, { recursive: true });
28
29  /** Run one CLI command and read its JSON. Rejects only when the command cannot start or times out. */
30  function run(args, { timeoutMs = 60_000 } = {}) {
31    const l = launcher();
32    return new Promise((resolve, reject) => {
33      const child = spawnProcess(l.command, [...(l.prefix ?? []), ...args], { cwd: l.cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: l.env });
34      let out = '', err = '', done = false;
35      const finish = (fn, v) => { if (done) return; done = true; clearTimeout(alarm); fn(v); };
36      const alarm = setTimeout(() => { try { child.kill(); } catch { /* gone */ } finish(reject, new Error('Strata did not answer in time.')); }, timeoutMs);
37      child.stdout?.on('data', c => { out += c; });
38      child.stderr?.on('data', c => { err += c; if (err.length > 100_000) err = err.slice(-50_000); });
39      child.on('error', e => finish(reject, new Error(`Strata could not start: ${e.message}`)));
40      child.on('close', code => {
41        let json = null;
42        const text = out.trim();
43        if (text) { try { json = JSON.parse(text.slice(text.indexOf('{'))); } catch { /* not JSON */ } }
44        finish(resolve, { code, json, text, stderr: err.trim() });
45      });
46    });
47  }
48  const need = (r, what) => {
49    if (r.json?.ok === false) throw new Error(r.json.error?.message ?? what);
50    if (r.code !== 0 && !r.json) throw new Error(r.stderr.split(/\r?\n/).filter(Boolean).pop() || what);
51    return r.json ?? {};
52  };
53
54  return {
55    run,
56    /** Which saved tuning these choices start with, and whether it is still valid (reads only). */
57    async status(configPath) { return need(await run(['presets', 'status', configPath, '--output', 'json'], { timeoutMs: 45_000 }), 'The saved tuning could not be read.'); },
58    /** What a start will really run: the saved tuning's values on top of the configuration (Expert mode shows these). */
59    async effective(configPath) { return need(await run(['presets', 'effective', configPath, '--output', 'json'], { timeoutMs: 45_000 }), 'The tuned values could not be read.'); },
60    /** Switch the saved tuning off for these choices (kept, can be switched on again with apply). */
61    async off(configPath) { return need(await run(['presets', 'off', configPath, '--output', 'json'], { timeoutMs: 45_000 }), 'The saved tuning could not be switched off.'); },
62    async list() { return need(await run(['presets', 'list', '--output', 'json'], { timeoutMs: 30_000 }), 'The saved tunings could not be read.'); },
63    async action(kind, id, extra = {}) {
64      if (!/^[0-9a-f]{8,32}$/.test(String(id ?? '')) && kind !== 'undo') throw new Error('Choose a saved tuning.');
65      const args = {
66        apply: ['presets', 'apply', id], delete: ['presets', 'delete', id], undo: ['presets', 'undo', id],
67        rename: ['presets', 'rename', id, String(extra.name ?? '').slice(0, 80)],
68      }[kind];
69      if (!args) throw new Error('Choose a supported action.');
70      return need(await run([...args, '--output', 'json'], { timeoutMs: 30_000 }), 'That did not work.');
71    },
72    /** Undo by configuration: back to the tuning that was active before (or the standard settings). */
73    async undoFor(configPath) { return need(await run(['presets', 'undo', 'x', '--config', configPath, '--output', 'json'], { timeoutMs: 45_000 }), 'There is nothing to undo.'); },
74
75    /**
76     * The long jobs: `tune auto` and `presets recheck`. `job` is a native-control job: `job.process` lets Stop end it,
77     * `job.progress` carries what the status file says (stage, minutes left, runs done) and `job.summary` the sentence.
78     */
79    async start(job, kind, opts, { onProgress = () => {} } = {}) {
80      const l = launcher();
81      const tag = job.id.slice(0, 8);
82      const statusFile = join(workDir, `tune-${tag}.status.json`);
83      const work = join(workDir, `tune-${tag}`);
84      rmSync(statusFile, { force: true });
85      let args;
86      if (kind === 'recheck') {
87        if (!opts.presetId) throw new Error('Choose a saved tuning to check.');
88        args = ['presets', 'recheck', opts.presetId, opts.configPath, '--output', 'json', '--status-file', statusFile, '--work-dir', work];
89      } else {
90        const mode = MODES.has(opts.mode) ? opts.mode : 'quick';
91        const use = USES.has(opts.use) ? opts.use : 'chat';
92        args = ['tune', 'auto', opts.configPath, '--mode', mode, '--use', use, '--output', 'json', '--status-file', statusFile, '--work-dir', work];
93        args.push('--goal', opts.goal === 'room' ? 'room' : 'speed');
94        if (opts.leaveRam) args.push('--leave-ram', String(Math.max(0, Math.min(50, Math.round(opts.leaveRam)))));
95        if (opts.allowSmallDifferences) args.push('--allow-small-differences');
96        // For headless checks on a PC where another engine runs: do not wait for it (the tuner would sit in its quiet check).
97        if (process.env.STRATA_TUNE_NO_QUIET_CHECK === '1') args.push('--no-quiet-check');
98        if (opts.name) args.push('--name', String(opts.name).slice(0, 80));
99      }
100      const child = spawnProcess(l.command, [...(l.prefix ?? []), ...args], { cwd: l.cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: l.env });
101      job.process = child;
102      let out = '', err = '';
103      child.stdout?.on('data', c => { out += c; });
104      child.stderr?.on('data', c => { err += c; if (err.length > 100_000) err = err.slice(-50_000); });
105      const poll = () => {
106        try {
107          const p = JSON.parse(readFileSync(statusFile, 'utf8'));
108          if (p && p.state !== 'done') { job.progress = { stage: p.stage, text: p.text ?? null, minutesLeft: p.minutes_left ?? null, runsDone: p.runs_done ?? 0, runsPlanned: p.runs_planned ?? 0, elapsedS: p.elapsed_s ?? 0, step: p.message ?? '', speeds: Array.isArray(p.speeds) ? p.speeds : [] }; onProgress(job.progress); }
109        } catch { /* not written yet */ }
110      };
111      const timer = setInterval(poll, pollMs);
112      try {
113        const code = await new Promise((resolve, reject) => { child.on('error', reject); child.on('close', resolve); });
114        clearInterval(timer);
115        let json = null;
116        const text = out.trim();
117        if (text) { try { json = JSON.parse(text.slice(text.indexOf('{'))); } catch { /* not JSON */ } }
118        if (job.state && job.state !== 'running') return null;      // stopped by the user
119        if (!json) throw new Error(err.split(/\r?\n/).filter(Boolean).pop() || `The tune stopped (exit ${code}).`);
120        if (json.ok === false) throw new Error(json.error?.message ?? 'The tune failed.');
121        const result = json.result ?? json;
122        if (kind === 'recheck') return { summary: json.verdict === 'keep' ? 'Still as fast as when it was saved.' : (json.reason ?? 'Checked.'), ...json };
123        return { summary: resultSentence(result), ...result };
124      } finally {
125        clearInterval(timer);
126        job.process = null;
127        rmSync(statusFile, { force: true });
128        try { rmSync(work, { recursive: true, force: true }); } catch { /* keep logs if busy */ }
129      }
130    },
131  };
132}
133
134export function writeTuneConfig(directory, model, cfg) {
135  const dir = join(directory, 'native-tune');
136  mkdirSync(dir, { recursive: true });
137  const path = join(dir, `${model}.json`);
138  const { api_key, port, ...rest } = cfg;            // the key and port belong to a running instance, not to the choices
139  writeFileSync(path, JSON.stringify(rest, null, 2), { mode: 0o600 });
140  return path;
141}