okami.mom/strata

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

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
8.2 KiB115 linesraw
1// The app's Load, headless, for the config snapshot.  node app_driver.mjs <world.json> <plain|models>
2//
3// The host's own createNativeControl runs the Load exactly as the app does.  Fake: the installer process (strata_mcp.py: catalog and hardware), Control's
4// model list, engine package, profile save and start (they record what the host hands over).  Real: Control's `drafting plan` and `drafting fetch`, run
5// through the Python shim on the same simulated machine, with the download replaced by a recorder.  No engine starts, nothing is downloaded, no network.
6import { EventEmitter } from 'node:events';
7import { existsSync, mkdirSync, readFileSync } from 'node:fs';
8import { join, dirname } from 'node:path';
9import { fileURLToPath, pathToFileURL } from 'node:url';
10
11const [worldFile, which] = process.argv.slice(2);
12const spec = JSON.parse(readFileSync(worldFile, 'utf8'));
13const root = spec.root;
14const repo = process.env.STRATA_SNAPSHOT_REPO;
15const python = process.env.STRATA_SNAPSHOT_PYTHON;
16const here = dirname(fileURLToPath(import.meta.url));
17
18// every per-user place the host or Control writes to is inside the scratch folder
19Object.assign(process.env, {
20  HOME: join(root, 'home'), USERPROFILE: join(root, 'home'), APPDATA: join(root, 'roaming'), LOCALAPPDATA: join(root, 'local'),
21  XDG_CONFIG_HOME: join(root, 'xdg-config'), XDG_STATE_HOME: join(root, 'state'), XDG_DATA_HOME: join(root, 'xdg-data'),
22  STRATA_SETTINGS_FILE: join(root, 'settings.json'), STRATA_COMPONENTS_DIR: join(root, 'components'), STRATA_INSTALL_DIR: join(root, 'install'),
23  STRATA_PROFILE_DIR: join(root, 'config', 'profiles'), STRATA_RUNTIME_DIR: join(root, 'runtime'), STRATA_SNAPSHOT_WORLD: worldFile,
24});
25for (const k of ['STRATA_API_KEY', 'STRATA_ENGINE_BACKEND', 'STRATA_UPDATE_FEED', 'STRATA_NATIVE_REPO']) delete process.env[k];
26mkdirSync(process.env.STRATA_COMPONENTS_DIR, { recursive: true });
27
28const { createNativeControl } = await import(pathToFileURL(join(repo, 'apps/host/server/native-control.mjs')).href);
29const { createControl } = await import(pathToFileURL(join(repo, 'apps/host/server/control-runtime.mjs')).href);
30
31// ---- the world: the facts the Python side wrote into world-info.json (nothing is retyped here)
32const info = JSON.parse(readFileSync(join(root, 'world-info.json'), 'utf8'));
33const { tag, family, modelName, model, configPath, hardware, sizeId, backend } = info;
34
35const calls = [];
36const real = createControl({ control: { dir: repo, python, cli: join(here, 'control_shim.py') } });
37const saved = [];
38const pick = (o, keys) => { const out = {}; for (const k of keys) if (o && k in o) out[k] = o[k]; return out; };
39const fake = {
40  ...real,
41  version: '0.2.12',
42  async installedModels() {
43    return { install_dir: join(root, 'install'), models: [{ id: tag, name: modelName, source_config: configPath, context_tokens: info.context, backend, component_status: 'present', missing: [], issue_codes: [] }] };
44  },
45  async engine() { return { usable: true, backend, components_dir: join(root, 'components'), engine: { version: '0.1.55', platform: info.platform, backend, exe: info.exe, root: dirname(info.exe) } }; },
46  async saveProfile(name, path) { calls.push(['saveProfile', name]); saved.push(JSON.parse(readFileSync(path, 'utf8'))); return {}; },
47  async start(name) { calls.push(['start', name]); return { ok: true, state: 'ready' }; },
48  async stop() { return { ok: true }; },
49  async status() { return { state: 'ready' }; },
50};
51const draftingPlan = real.draftingPlan.bind(real), draftingFetch = real.draftingFetch.bind(real);
52let probe = null;
53fake.draftingPlan = async (o = {}) => {
54  if (!o.configPath) { probe = draftingPlan(o); return probe; }     // the host's one-off "does this engine serve DFlash2" probe: awaited before the Load (below), not part of the Load's record
55  const r = await draftingPlan(o);
56  calls.push(['draftingPlan', { mode: o.mode ?? null, noSplit: !!o.noSplit, result: pick(r, ['needed', 'choice', 'drafter', 'gb', 'line', 'note', 'split', 'mtp_needed', 'mtp_here']) }]);
57  return r;
58};
59fake.draftingFetch = async (o = {}) => { const r = await draftingFetch(o); calls.push(['draftingFetch', { mode: o.mode ?? null, noSplit: !!o.noSplit }]); return r; };
60
61const catalog = { families: [{ family, title: info.title, about: 'x', images: true, experimental: false, sizes: [
62  { id: sizeId, model, download_gb: 75.8, ram_needed_gb: 60, about: 'x', on_this_pc: 'fits', installed: true, images: true, experimental: false }] }],
63  contexts: [8192, 32768, 131072], recommendation: { family, model, context: info.context }, context_note: '' };
64
65const spawnProcess = (command, argv) => {
66  if (!String(argv[0]).endsWith('strata_mcp.py')) throw new Error('no process but the installer may be started in packaged mode: ' + command + ' ' + argv.join(' '));
67  const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.exitCode = null;
68  child.kill = () => { child.exitCode = 0; queueMicrotask(() => child.emit('exit', 0)); return true; };
69  child.stdin = { write(line) {
70    const message = JSON.parse(line); if (!message.id) return;
71    let result;
72    if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' };
73    else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install', 'strata_remove'].map(name => ({ name })) };
74    else if (message.params.name === 'strata_models') result = { structuredContent: catalog };
75    else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: null, running: [], summary: 'x' } };
76    else result = { structuredContent: { summary: 'x', install: { running: false, exit_code: 0 } } };
77    queueMicrotask(() => child.stdout.emit('data', Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + '\n')));
78  } };
79  return child;
80};
81
82const directory = join(root, 'host-data');
83mkdirSync(directory, { recursive: true });
84const native = createNativeControl({
85  control: fake, directory, spawnProcess, fetcher: async () => Response.json({ status: 'ok', engine: {} }), requests: () => [], modelsDirectory: () => join(root, 'data', 'models'),
86  hardwareProbe: () => hardware.gpus.map(g => ({ index: g.index, vram_gb: g.vram_gb })),
87});
88
89const until = async (job) => {
90  for (let i = 0; i < 1500; i++) { const j = native.state().jobs.find(x => x.id === job.id); if (j && j.state !== 'running') return j; await new Promise(r => setTimeout(r, 20)); }
91  throw new Error('the Load did not finish');
92};
93let exitCode = 0;
94try {
95  await native.refresh(true);
96  native.state();
97  for (let i = 0; i < 100 && !probe; i++) await new Promise(r => setTimeout(r, 20));    // the host asks once, at its first state; the Load must start after the answer
98  if (probe) { await probe.catch(() => {}); await new Promise(r => setTimeout(r, 100)); }
99  // STRATA_SNAPSHOT_APP_ARGS (JSON): more of what the Models screen passes (resourceProfile, vision), for the tests that need it; the golden runs leave it unset
100  const extra = process.env.STRATA_SNAPSHOT_APP_ARGS ? JSON.parse(process.env.STRATA_SNAPSHOT_APP_ARGS) : {};
101  const args = { ...(which === 'models' ? { model: tag, values: { drafting: 'auto' } } : { model: tag }), ...extra };
102  const job = await until(native.operation('load', args));
103  if (job.state !== 'done') { console.error('Load ended in state ' + job.state + ': ' + (job.error ?? '')); exitCode = 3; }
104  const fetchLog = join(root, 'shim-fetches.jsonl');
105  const fetches = existsSync(fetchLog) ? readFileSync(fetchLog, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)) : [];
106  const result = {
107    command: which === 'models' ? `Models screen: Load ${tag} with Drafting = Auto` : `plain Load ${tag}`,
108    control_calls: calls.map(c => (c.length === 2 && typeof c[1] === 'object' ? { call: c[0], ...c[1] } : { call: c[0] })),
109    fetches, config_file: saved.length ? saved[saved.length - 1] : null,
110    job: { state: job.state, summary: job.summary ?? null, drafterNote: job.drafterNote ?? null },
111  };
112  console.log('SNAPSHOT-RESULT ' + JSON.stringify(result));
113} catch (error) { console.error(error?.stack ?? String(error)); exitCode = 2; }
114await native.close();
115process.exit(exitCode);