okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
27.6 KiB386 linesraw
1/**
2 * The App Host's bridge to Strata Control, the Python part of the product.
3 *
4 * In the installed app Control ships as a component next to the host (<install>/control): a pinned CPython with
5 * hash-locked wheels, strata_control, strata_cli and the API server. The host never uses the user's Python, never runs
6 * pip, git or a compiler, and never downloads anything to start a model: it asks Control, and Control starts the engine
7 * under its owner runtime (loopback TCP + 256-bit token on Windows, a private socket elsewhere; a Job Object that ends
8 * the server with its host; leases that stop a second owner).
9 *
10 * What lives here: where Control and the engine component folder are, a runner for the CLI (JSON in, JSON out, a
11 * timeout, no shell), and the four operations the app needs: which engine this PC would use, which models are
12 * installed, start a saved profile, stop it.
13 */
14import { spawn } from 'node:child_process';
15import { existsSync, readFileSync } from 'node:fs';
16import { dirname, join, resolve } from 'node:path';
17import { fileURLToPath } from 'node:url';
18import { homedir } from 'node:os';
19
20const HERE = dirname(fileURLToPath(import.meta.url));
21
22export function bundledPython(dir, platform = process.platform) {
23  return platform === 'win32' ? join(dir, 'python', 'python.exe') : join(dir, 'python', 'bin', 'python3');
24}
25
26/** The per-user component folder, the same rule as strata_control/engine_component.py components_dir(). */
27export function componentsDirectory({ env = process.env, platform = process.platform, home = homedir() } = {}) {
28  if (env.STRATA_COMPONENTS_DIR) return env.STRATA_COMPONENTS_DIR;
29  if (platform === 'win32') return join(env.LOCALAPPDATA || join(home, 'AppData', 'Local'), 'Strata', 'components');
30  return join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'strata', 'components');
31}
32
33/**
34 * A Control that the component updater installed (`strata update` writes `<components>/control/active.json` after the new
35 * bundle ran once). Null when there is none.
36 */
37export function updatedControlDirectory({ env = process.env, platform = process.platform, components = null } = {}) {
38  try {
39    const base = components ?? componentsDirectory({ env, platform });
40    const pointer = JSON.parse(readFileSync(join(base, 'control', 'active.json'), 'utf8').replace(/^/, ''));
41    if (typeof pointer?.folder !== 'string' || !/^[\w.+-]+$/.test(pointer.folder)) return null;
42    return { dir: join(base, 'control', pointer.folder), version: typeof pointer.version === 'string' ? pointer.version : null };
43  } catch { return null; }
44}
45
46const versionKey = value => String(value ?? '').split('.').map(part => Number.parseInt(part, 10) || 0);
47function newer(a, b) {
48  for (let i = 0; i < Math.max(a.length, b.length); i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
49  return false;
50}
51
52/**
53 * Is there a Control component to use? STRATA_CONTROL_DIR names one (the Tauri shell sets it to the bundled one), the
54 * `control` folder beside `host` is the installed app's, and `<components>/control/active.json` is one the component
55 * updater installed. Each must be whole; the newest version wins, so an app update that ships a newer Control is never
56 * held back by an older updated one, and an updated Control is never lost to an older bundled one. A tie goes to the first
57 * in that order. Returns null in a source checkout (the host then keeps its older paths).
58 */
59export function findControl({ env = process.env, platform = process.platform, exists = existsSync, hostDir = resolve(HERE, '..'), components = null } = {}) {
60  const updated = updatedControlDirectory({ env, platform, components });
61  const candidates = [{ dir: env.STRATA_CONTROL_DIR }, { dir: join(hostDir, '..', 'control') }, ...(updated ? [updated] : [])]
62    .filter(c => c.dir).map(c => ({ ...c, dir: resolve(c.dir) }));
63  let best = null;
64  for (const candidate of candidates) {
65    const python = bundledPython(candidate.dir, platform);
66    if (!(exists(python) && exists(join(candidate.dir, 'strata.py')) && exists(join(candidate.dir, 'strata_control')))) continue;
67    let bundle = null;
68    try { bundle = JSON.parse(readFileSync(join(candidate.dir, 'BUNDLE.json'), 'utf8').replace(/^/, '')); } catch { /* optional */ }
69    const found = { dir: candidate.dir, python, cli: join(candidate.dir, 'strata.py'), bundle, key: versionKey(bundle?.version ?? candidate.version) };
70    if (!best || newer(found.key, best.key)) best = found;
71  }
72  if (!best) return null;
73  const { key, ...control } = best;
74  return control;
75}
76
77/**
78 * The environment of the server the host starts from a source checkout (#3851): the key travels in the run configuration, so a
79 * STRATA_API_KEY the host itself was started with is removed. Setting it to an empty string made serve/server.py stop with
80 * "an API key was given but it is empty".
81 */
82export function sourceServerEnvironment(env = process.env) {
83  const next = { ...env, PYTHONUNBUFFERED: '1', PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' };
84  delete next.STRATA_API_KEY;
85  return next;
86}
87
88/** The environment Control runs in: nothing from the user's Python, and acquiring forbidden. */
89export function controlEnvironment(control, { env = process.env, components = componentsDirectory({ env }), acquire = false } = {}) {
90  const next = { ...env };
91  for (const key of ['PYTHONHOME', 'PYTHONPATH', 'PYTHONSTARTUP', 'VIRTUAL_ENV', 'STRATA_PYTHON', 'STRATA_NATIVE_PYTHON', 'STRATA_API_KEY']) delete next[key];
92  const result = {
93    ...next,
94    PYTHONNOUSERSITE: '1', PYTHONUTF8: '1', PYTHONUNBUFFERED: '1', PYTHONIOENCODING: 'utf-8',
95    STRATA_NO_ACQUIRE: '1', STRATA_COMPONENTS_DIR: components,
96    // The app's own settings file, beside its components: Control and the installer never read or write the file an older
97    // command-line Strata keeps in %APPDATA% / ~/.config (its list of Strata folders), so an old install is never adopted.
98    ...(components ? { STRATA_SETTINGS_FILE: env.STRATA_SETTINGS_FILE || join(dirname(components), 'app-settings.json') } : {}),
99    ...(control?.dir ? { STRATA_CONTROL_DIR: control.dir } : {}),
100  };
101  // Only the explicit update step (`strata update`) may acquire; every other Control process keeps the switch on.
102  if (acquire) delete result.STRATA_NO_ACQUIRE;
103  return result;
104}
105
106/**
107 * The environment of the installer process (tools/strata_mcp.py): Control's, with acquiring still forbidden for the process
108 * itself. Only the install job it starts when the user asks to download a model lifts that for its own children.
109 */
110export function installerEnvironment(control, { env = process.env, installDir, components = componentsDirectory({ env }) } = {}) {
111  return { ...controlEnvironment(control, { env, components }), STRATA_CONTROL_INSTALL: '1', ...(installDir ? { STRATA_INSTALL_DIR: installDir } : {}) };
112}
113
114export class ControlError extends Error {
115  constructor(message, { code = 'control_failed', exitCode = null, output = null } = {}) {
116    super(message);
117    this.name = 'ControlError';
118    this.code = code;
119    this.exitCode = exitCode;
120    this.output = output;
121  }
122}
123
124/**
125 * Small Control programs that are a module of strata_control and not a `strata` command. They run on Control's interpreter with Control's folder first on the
126 * path (the folder is the working directory), so they work whatever the interpreter does with the script folder.
127 */
128const BOOT = {
129  pictures: 'import os,sys;sys.path.insert(0,os.getcwd());from strata_control import pictures;sys.exit(pictures.main(sys.argv[1:]))',
130};
131
132/** Run one CLI command of Control (or, with `boot`, one of its modules). Resolves { code, json, text, stderr }; rejects only if it cannot start or times out. */
133export function runCli(control, args, { env = process.env, timeoutMs = 60_000, spawnProcess = spawn, components, acquire = false, onLine = null, signal = null, boot = null } = {}) {
134  return new Promise((resolveRun, reject) => {
135    const child = spawnProcess(control.python, boot ? ['-c', BOOT[boot], ...args] : [control.cli, ...args], {
136      cwd: control.dir, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
137      env: controlEnvironment(control, { env, acquire, ...(components ? { components } : {}) }),
138    });
139    if (signal) {
140      if (signal.aborted) { try { child.kill(); } catch { /* gone */ } }
141      else signal.addEventListener('abort', () => { try { child.kill(); } catch { /* gone */ } }, { once: true });
142    }
143    let out = '', err = '', done = false, pending = '';
144    const finish = (fn, value) => { if (done) return; done = true; clearTimeout(alarm); fn(value); };
145    const alarm = setTimeout(() => {
146      try { child.kill(); } catch { /* already gone */ }
147      finish(reject, new ControlError(`Strata Control did not answer within ${Math.round(timeoutMs / 1000)} s (${args.slice(0, 2).join(' ')}).`, { code: 'control_timeout' }));
148    }, timeoutMs);
149    child.stdout.on('data', c => {
150      out += c; if (out.length > 4_000_000) child.kill();
151      if (onLine) {                                       // JSON lines (--output jsonl): each complete line is one event
152        pending += c;
153        let at;
154        while ((at = pending.indexOf('\n')) >= 0) {
155          const line = pending.slice(0, at).trim(); pending = pending.slice(at + 1);
156          if (!line.startsWith('{')) continue;
157          try { onLine(JSON.parse(line)); } catch { /* not an event */ }
158        }
159      }
160    });
161    child.stderr.on('data', c => { err += c; if (err.length > 200_000) err = err.slice(-100_000); });
162    child.on('error', e => finish(reject, new ControlError(`Strata Control could not start: ${e.message}`, { code: 'control_missing' })));
163    child.on('close', code => {
164      let json = null;
165      const text = out.trim();
166      if (onLine) {                                       // the last line is the result record
167        const last = text.split(/\r?\n/).filter(line => line.startsWith('{')).pop();
168        if (last) { try { json = JSON.parse(last); } catch { /* not JSON */ } }
169      } else if (text) { try { json = JSON.parse(text.slice(text.indexOf('{'))); } catch { /* not JSON: caller reads text */ } }
170      finish(resolveRun, { code, json, text, stderr: err.trim() });
171    });
172  });
173}
174
175/** Control's exit 7 means two things: an engine is serving, or another update holds the update lock (strata_control/updater.py update_lock). The lock is told by its text. */
176export const UPDATE_LOCK_HELD = /another update is already running/i;
177const failure = (result, fallback) => {
178  const message = result.json?.error?.message ?? result.json?.error ?? result.json?.notice ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || fallback);
179  return new ControlError(message, { exitCode: result.code, output: result.json, ...(UPDATE_LOCK_HELD.test(String(message)) ? { code: 'update_busy' } : {}) });
180};
181
182/** Operations the app uses. `run` is injectable so the host's tests need no Python. */
183export function createControl({ control = findControl(), env = process.env, run = null } = {}) {
184  if (!control) return null;
185  const call = run ?? ((args, options) => runCli(control, args, { env, ...options }));
186  const feedArgs = feed => (feed ? ['--feed', feed] : []);
187  return {
188    control,
189    version: control.bundle?.version ?? null,
190    /**
191     * Use the newest whole Control there is now (findControl again), after an update installed one: true when it changed. Every later call runs the new one.
192     * The caller makes sure nothing of the old one is running (native-control.mjs switchControl).
193     */
194    reload({ find = findControl } = {}) {
195      const next = find({ env });
196      if (!next || resolve(next.dir) === resolve(control.dir)) return false;
197      control = next;
198      this.control = next;
199      this.version = next.bundle?.version ?? null;
200      return true;
201    },
202    /**
203     * The explicit update step. These are the only calls that let Control reach the network: `acquire` removes
204     * STRATA_NO_ACQUIRE for that one process. Starting, serving, listing and rolling back never do.
205     */
206    async updateCheck({ feed = env.STRATA_UPDATE_FEED ?? null, appVersion = env.STRATA_APP_VERSION ?? null } = {}) {
207      const result = await call(['update', '--check', '--output', 'json', ...feedArgs(feed), ...(appVersion ? ['--app-version', appVersion] : [])], { timeoutMs: 90_000, acquire: true });
208      if (result.json?.ok) return result.json;
209      throw failure(result, 'The update check failed.');
210    },
211    async update({ feed = env.STRATA_UPDATE_FEED ?? null, engine = true, control: withControl = true, appVersion = env.STRATA_APP_VERSION ?? null, force = false, stopModel = false, onEvent = null, signal = null } = {}) {
212      const args = ['update', '--output', 'jsonl', ...feedArgs(feed), ...(engine ? [] : ['--no-engine']), ...(withControl ? [] : ['--no-control']),
213        ...(appVersion ? ['--app-version', appVersion] : []), ...(force ? ['--force'] : []), ...(stopModel ? ['--stop-model'] : [])];
214      const result = await call(args, { timeoutMs: 3 * 3600_000, acquire: true, onLine: onEvent ?? (() => {}), signal });
215      if (result.json?.ok) return result.json;
216      const failed = result.json?.results?.find?.(r => r.status === 'failed');
217      if (failed) throw Object.assign(new ControlError(failed.error, { exitCode: failed.exit_code ?? result.code, output: result.json }), { code: result.code === 7 && !UPDATE_LOCK_HELD.test(failed.error ?? '') ? 'engine_serving' : result.code === 7 ? 'update_busy' : 'update_failed' });
218      throw failure(result, 'The update failed.');
219    },
220    /** Install an engine package the person downloaded and chose (the offline path): no network; Control checks the package's own signature. */
221    async installEngineFile(path, { onEvent = null, signal = null } = {}) {
222      const result = await call(['components', 'install-file', path, '--output', 'jsonl'], { timeoutMs: 3600_000, onLine: onEvent ?? (() => {}), signal });
223      if (result.json?.ok) return { ok: true, results: [result.json] };
224      throw failure(result, 'This file could not be installed.');
225    },
226    async rollbackEngine() {
227      const result = await call(['components', 'rollback', '--output', 'json'], { timeoutMs: 120_000 });
228      if (result.json?.ok) return result.json;
229      throw failure(result, 'The engine could not be rolled back.');
230    },
231    /** The engines installed on this computer, by family (`strata components engines`): the one list the Terminal prints too. Reads files only. */
232    async engines() {
233      const result = await call(['components', 'engines', '--output', 'json'], { timeoutMs: 60_000 });
234      if (result.json?.ok) return result.json;
235      throw failure(result, 'The installed engines could not be read.');
236    },
237    /** Switch to an installed engine (`strata components use`): nothing is downloaded. `root` is kept for older callers. */
238    async useEngine({ family, folder }) {
239      const result = await call(['components', 'use', folder, '--family', family, '--output', 'json'], { timeoutMs: 600_000 });
240      if (result.json?.ok) return result.json;
241      throw failure(result, 'The engine could not be switched.');
242    },
243    /** Delete an installed engine (`strata components remove`); Control refuses the one in use. */
244    async removeEngine({ family, folder }) {
245      const result = await call(['components', 'remove', folder, '--family', family, '--output', 'json'], { timeoutMs: 600_000 });
246      if (result.json?.ok) return result.json;
247      throw failure(result, 'The engine could not be deleted.');
248    },
249    async engine({ backend = null } = {}) {
250      const result = await call(['components', 'engine', '--output', 'json', ...(backend ? ['--backend', backend] : [])], { timeoutMs: 30_000 });
251      if (result.json) return result.json;                  // exit 5 still carries the report and the notice
252      throw failure(result, 'The engine check failed.');
253    },
254    async installedModels({ installDir = null } = {}) {
255      const result = await call(['models', 'list', '--installed', ...(installDir ? ['--install-dir', installDir] : []), '--output', 'json'], { timeoutMs: 60_000 });
256      if (result.code !== 0 || !result.json) throw failure(result, 'The installed models could not be read.');
257      return result.json;
258    },
259    /** What a local GGUF folder or file holds, without touching it: the model it is, and why it cannot be used when it cannot. */
260    async importPlan(path) {
261      const result = await call(['models', 'import', path, '--plan', '--output', 'json'], { timeoutMs: 120_000 });
262      if (result.json && result.code === 0) return result.json.plan ?? result.json;
263      // A set that cannot be used is still a checked set: Control answers (exit 5, ok:false) with the plan and the reasons, and the page says them in
264      // words ("Strata can't run these files yet"). Only a check that could not run at all is a failure.
265      if (result.json?.plan && Array.isArray(result.json.plan.issues)) return result.json.plan;
266      throw failure(result, 'The files could not be checked.');
267    },
268    /** What picking `to` as the models folder means (sizes, free space, which choices are possible, why not): nothing is changed. */
269    async planModelsMove(from, to) {
270      const result = await call(['models', 'move', to, ...(from ? ['--from', from] : []), '--plan', '--output', 'json'], { timeoutMs: 120_000 });
271      if (result.json?.plan) return result.json.plan;
272      throw failure(result, 'The folder could not be checked.');
273    },
274    /**
275     * Move the model files to `to` (copied, checked, then the old copies removed). `onEvent` gets the progress lines; a file at `cancelFile` stops it
276     * safely. Resolves with the summary (done / stopped, what moved, what is left); a failure is a ControlError whose `output` carries the details.
277     */
278    async moveModels(from, to, { installDir = null, cancelFile = null, onEvent = null } = {}) {
279      const args = ['models', 'move', to, ...(from ? ['--from', from] : []), ...(installDir ? ['--install-dir', installDir] : []), ...(cancelFile ? ['--cancel-file', cancelFile] : []), '--output', 'jsonl'];
280      const result = await call(args, { timeoutMs: 24 * 3600_000, onLine: onEvent ?? (() => {}) });
281      if (result.json?.ok && result.json.event === 'result') return result.json;
282      const error = result.json?.error;
283      throw Object.assign(new ControlError(error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The models could not be moved.'), { exitCode: result.code, output: result.json }), { code: error?.code ?? 'move_failed', details: error?.details ?? '' });
284    },
285    /** A move of the models folder that the last run left unfinished (`strata models move --status`): null, or {state, from, to, bytes}. */
286    async interruptedModelsMove(dataFolder) {
287      const result = await call(['models', 'move', '--status', ...(dataFolder ? ['--from', dataFolder] : []), '--output', 'json'], { timeoutMs: 30_000 });
288      if (result.json?.ok) return result.json.interrupted ?? null;
289      throw failure(result, 'The models folder could not be checked.');
290    },
291    /** "Finish it": the same move again, from where it stopped. Same events and result as moveModels. */
292    async resumeModelsMove(dataFolder, { installDir = null, cancelFile = null, onEvent = null } = {}) {
293      const args = ['models', 'move', '--resume', ...(dataFolder ? ['--from', dataFolder] : []), ...(installDir ? ['--install-dir', installDir] : []), ...(cancelFile ? ['--cancel-file', cancelFile] : []), '--output', 'jsonl'];
294      const result = await call(args, { timeoutMs: 24 * 3600_000, onLine: onEvent ?? (() => {}) });
295      if (result.json?.ok && result.json.event === 'result') return result.json;
296      const error = result.json?.error;
297      throw Object.assign(new ControlError(error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The models could not be moved.'), { exitCode: result.code, output: result.json }), { code: error?.code ?? 'move_failed', details: error?.details ?? '' });
298    },
299    /** "Leave it": keep the old folder, remove the partial copies in the new one. */
300    async leaveModelsMove(dataFolder, { installDir = null } = {}) {
301      const result = await call(['models', 'move', '--leave', ...(dataFolder ? ['--from', dataFolder] : []), ...(installDir ? ['--install-dir', installDir] : []), '--output', 'json'], { timeoutMs: 24 * 3600_000 });
302      if (result.json?.ok) return result.json;
303      throw Object.assign(failure(result, 'The partial copies could not be removed.'), { code: result.json?.error?.code ?? 'leave_failed', details: result.json?.error?.details ?? '' });
304    },
305    /**
306     * The drafter for a model's run config and the drafting choice (`strata drafting plan`): { needed, tuned_needed, gb, drafter_gb, tuned, file, line, note, drafter, split, mtp_needed, mtp_gb }. `model` (with `family`) names a model that has no run config yet. Control decides
307     * (the table of strata_control/drafting.py and the all-cards split engine's rule, strata_control/split_engine.py: the same answer as the Terminal's); the app never reads
308     * it. Nothing is downloaded. `noSplit` asks as if the split engine will not take the start (only after the draft layer for the split could not be downloaded).
309     */
310    async draftingPlan({ configPath = null, mode = null, family = null, model = null, dataDir = null, noSplit = false, unloading = false } = {}) {
311      const result = await call(['drafting', 'plan', ...(configPath ? ['--config', configPath] : []), ...(mode ? ['--mode', mode] : []), ...(family ? ['--family', family] : []), ...(model && !configPath ? ['--model', model] : []), ...(dataDir ? ['--data-dir', dataDir] : []), ...(noSplit ? ['--no-split'] : []), ...(unloading ? ['--engines-unloading'] : []), '--output', 'json'], { timeoutMs: 30_000 });
312      if (result.json?.ok) return result.json;
313      throw failure(result, 'The drafter could not be checked.');
314    },
315    /** Fetch and pack the drafter when the choice would use it and it is not here (`strata drafting fetch --if-needed`); `onEvent` gets {step, done, total}. */
316    async draftingFetch({ configPath, mode = null, noSplit = false, unloading = false, throttle = false, onEvent = null, signal = null } = {}) {
317      const args = ['drafting', 'fetch', '--config', configPath, ...(mode ? ['--mode', mode] : []), ...(noSplit ? ['--no-split'] : []), ...(unloading ? ['--engines-unloading'] : []), '--if-needed', ...(throttle ? ['--throttle'] : []), '--output', 'jsonl'];
318      const result = await call(args, { timeoutMs: 3 * 3600_000, acquire: true, onLine: onEvent ?? (() => {}), signal });
319      if (result.json?.ok) return result.json;
320      throw Object.assign(new ControlError(result.json?.error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The DFlash2 drafter could not be downloaded.'), { exitCode: result.code, output: result.json }), { code: 'drafting_failed' });
321    },
322    /**
323     * The all-cards split engine for the run config the app is about to start (`strata split-engine apply`, the step `strata launch` does itself): Control checks the rule, the
324     * engine package and the draft layer on this computer and writes the split engine's run config to `outPath` when the answer is yes. Resolves { split, line, warn, reasons, cards, written };
325     * `configPath` is never changed, nothing is downloaded.
326     */
327    async splitEngine({ configPath, outPath } = {}) {
328      const result = await call(['split-engine', 'apply', '--config', configPath, '--out', outPath, '--output', 'json'], { timeoutMs: 60_000 });
329      if (result.json?.ok) return result.json;
330      throw failure(result, 'The all-cards split engine could not be checked.');
331    },
332    /**
333     * The picture files of an installed model that has none (strata_control/pictures.py): found or downloaded once (about 0.9 GB, shared), and the run
334     * config's `vision` section worked out for this engine. Nothing else of the model is touched and nothing is written to its run config: the caller does.
335     * Resolves { mmproj, vision, fetched, note, data_dir }; a failure is a ControlError whose `code` is offline | disk | failed | checksum | unsupported | no_reader.
336     * `onEvent` gets {step, done, total}. This is an explicit step that may reach the network (`acquire`), only for the Load the person pressed.
337     */
338    async picturesFetch({ configPath, engineDir, vision = 'yes', dataDir = null, family = null, hardware = null, onEvent = null, signal = null } = {}) {
339      const args = ['fetch', '--config', configPath, '--engine-dir', engineDir, '--vision', vision, ...(dataDir ? ['--data-dir', dataDir] : []), ...(family ? ['--family', family] : []),
340        ...(hardware?.vram_gb != null ? ['--vram-gb', String(hardware.vram_gb)] : []), ...(hardware?.make ? ['--make', String(hardware.make)] : []), ...(hardware?.arch != null ? ['--arch', String(hardware.arch)] : [])];
341      const result = await call(args, { timeoutMs: 3 * 3600_000, acquire: true, boot: 'pictures', onLine: onEvent ?? (() => {}), signal });
342      if (result.json?.ok) return result.json;
343      throw Object.assign(new ControlError(result.json?.error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The picture files could not be downloaded.'), { exitCode: result.code, output: result.json }), { code: result.json?.error?.code ?? 'failed' });
344    },
345    async saveProfile(name, configPath) {
346      const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 });
347      const known = (listed.json?.profiles ?? []).some(p => p.id === name);
348      const result = await call(known
349        ? ['profile', 'use-config', name, '--from-config', configPath, '--output', 'json']
350        : ['profile', 'create', name, '--from-config', configPath, '--output', 'json'], { timeoutMs: 30_000 });
351      if (result.code !== 0) throw failure(result, 'The model profile could not be saved.');
352      return result.json;
353    },
354    // The app owns the engines it starts: `--die-with-pid` makes the owner stop its engine (drained) when this host is
355    // gone, however the host ended (a crash, a kill, the shell's death). A Terminal's `runtime start` has no such tie.
356    async start(name, { waitSeconds = 300, dieWithPid = process.pid, drainSeconds = 15 } = {}) {
357      const result = await call(['runtime', 'start', '--profile', name, '--wait', String(waitSeconds), '--shutdown-timeout', String(drainSeconds), ...(dieWithPid ? ['--die-with-pid', String(dieWithPid)] : []), '--output', 'json'], { timeoutMs: (waitSeconds + 60) * 1000 });
358      if (result.code !== 0 || !result.json?.ok) throw failure(result, 'The engine did not start.');
359      return result.json;
360    },
361    /** Give the user back Strata files in their own folders that a run as administrator locked (`strata repair-access`). Never throws. */
362    async repairAccess() {
363      try {
364        const result = await call(['repair-access', '--output', 'json'], { timeoutMs: 60_000 });
365        return result.json ?? { ok: false, error: result.stderr };
366      } catch (error) {
367        return { ok: false, error: String(error?.message ?? error) };
368      }
369    },
370    /** End servers and engines Strata started whose owner is gone (each is re-checked by PID, start time and command line). */
371    async cleanup() {
372      const result = await call(['runtime', 'cleanup', '--output', 'json'], { timeoutMs: 120_000 });
373      return result.json ?? { ok: false, error: result.stderr };
374    },
375    async status(name) {
376      const result = await call(['runtime', 'status', '--profile', name, '--output', 'json'], { timeoutMs: 30_000 });
377      return result.json ?? { ok: false, state: 'unknown', error: result.stderr };
378    },
379    async stop(name, { waitSeconds = 120 } = {}) {
380      const result = await call(['runtime', 'stop', '--profile', name, '--wait', String(waitSeconds), '--output', 'json'], { timeoutMs: (waitSeconds + 60) * 1000 });
381      // an instance that is not running is already stopped
382      if (result.code !== 0 && !/not running|no owner|stopped|absent|no managed/i.test(JSON.stringify(result.json ?? result.stderr))) throw failure(result, 'The engine did not stop.');
383      return result.json;
384    },
385  };
386}