okami.mom/strata

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

Niko1221Merge f-027-gh-app: GitHub app and Terminal items for 0.2.73cabb9e3f

main
18.5 KiB320 linesraw
1/**
2 * The engine that ships inside the installer (<install>/engine-bundle/<package folder>, the same layout Strata Control's
3 * packaging/package_engine.py writes: engine-component.json, schema 2, SHA-256 and size for every file).
4 *
5 * On start, when this PC has no engine package for the bundle's platform and backend, or only an older one, the bundled
6 * package is checked against its own manifest and copied into the normal components folder (<components>/engine/<folder>),
7 * where Control and the "engine comes with the model" flow find it like any other installed engine. Nothing is downloaded.
8 * An installed engine of the same version or newer is never touched; a damaged copy of the very same package is repaired.
9 * The copy is made under a hidden temporary name and renamed into place, so an interrupted run leaves nothing half-installed
10 * (the next start removes the leftover and tries again).
11 */
12import { createReadStream, existsSync, readFileSync, readdirSync } from 'node:fs';
13import { execFileSync } from 'node:child_process';
14import { copyFile, mkdir, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
15import { createHash } from 'node:crypto';
16import { dirname, join, resolve, sep } from 'node:path';
17
18const MANIFEST = 'engine-component.json';
19
20const versionKey = value => String(value ?? '').split('.').map(part => Number.parseInt(part, 10) || 0);
21export function compareVersions(a, b) {
22  const x = versionKey(a), y = versionKey(b);
23  for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0) ? 1 : -1;
24  return 0;
25}
26
27async function readManifest(folder) {
28  try {
29    const data = JSON.parse((await readFile(join(folder, MANIFEST), 'utf8')).replace(/^/, ''));
30    if (!data || data.id !== 'strata-engine' || typeof data.version !== 'string' || typeof data.platform !== 'string' || typeof data.backend !== 'string') return null;
31    if (!Array.isArray(data.files) || !data.files.length || typeof data.entrypoint !== 'string') return null;
32    return data;
33  } catch { return null; }
34}
35
36function plainRelative(path) {
37  if (typeof path !== 'string' || !path || path.startsWith('/') || path.startsWith('\\') || /^[a-z]:/i.test(path)) return null;
38  const parts = path.split(/[\\/]/);
39  return parts.some(p => !p || p === '..' || p === '.') ? null : parts.join('/');
40}
41
42function sha256(path) {
43  return new Promise((resolveHash, reject) => {
44    const hash = createHash('sha256');
45    createReadStream(path).on('data', d => hash.update(d)).on('error', reject).on('end', () => resolveHash(hash.digest('hex')));
46  });
47}
48
49/**
50 * The NVIDIA driver version of this PC (the oldest when several cards disagree), or null when there is none or it cannot be read.
51 * Linux: the kernel module's own file; anywhere: nvidia-smi. Never throws.
52 */
53export function nvidiaDriverVersion() {
54  try {
55    const text = readFileSync('/proc/driver/nvidia/version', 'utf8');
56    const found = /Kernel Module\s+(\d+(?:\.\d+)+)/.exec(text);
57    if (found) return found[1];
58  } catch { /* not Linux, or no NVIDIA driver */ }
59  try {
60    const out = execFileSync('nvidia-smi', ['--query-gpu=driver_version', '--format=csv,noheader'], { encoding: 'utf8', timeout: 8000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
61    const versions = out.split(/\r?\n/).map(line => line.trim()).filter(line => /^\d+(\.\d+)+$/.test(line));
62    if (versions.length) return versions.sort(compareVersions)[0];
63  } catch { /* no nvidia-smi */ }
64  return null;
65}
66
67/** Where the builds are published; the wrong-make sentence points here. */
68export const RELEASES_URL = 'https://github.com/Niko1221/Strata/releases';
69
70/** The PCI vendor ids of the display adapters Windows reports as present right now (PowerShell, Win32_VideoController); empty when that cannot be read. */
71export function windowsPresentVendors({ platform = process.platform, run = execFileSync } = {}) {
72  const found = new Set();
73  if (platform !== 'win32') return found;
74  try {
75    const out = run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_VideoController | ForEach-Object { $_.PNPDeviceID }'], { encoding: 'utf8', timeout: 15000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
76    for (const match of String(out).matchAll(/VEN_([0-9A-F]{4})/gi)) found.add(match[1].toLowerCase());
77  } catch { /* no PowerShell or a limited account: the registry answer stands */ }
78  return found;
79}
80
81/**
82 * The PCI vendor ids (`10de`, `1002`, `8086`) of the Windows display adapters; empty off Windows or when the registry cannot be read.
83 * The registry keeps the entry of a card that was taken out (an NVIDIA card swapped for a Radeon, #3892): when NVIDIA and AMD are both
84 * listed, only the makes Windows reports as present now count, the same rule Strata Control uses (engine_component.windows_display_adapters).
85 */
86export function windowsDisplayVendors({ platform = process.platform, run = execFileSync, present = windowsPresentVendors } = {}) {
87  const found = new Set();
88  if (platform !== 'win32') return found;
89  try {
90    const out = run('reg', ['query', 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}', '/s', '/v', 'MatchingDeviceId'], { encoding: 'utf8', timeout: 8000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
91    for (const match of String(out).matchAll(/VEN_([0-9A-F]{4})/gi)) found.add(match[1].toLowerCase());
92  } catch { /* no registry access: the tools decide */ }
93  if (found.has('10de') && found.has('1002')) {
94    const now = present({ platform, run });
95    const kept = new Set([...found].filter(vendor => now.has(vendor)));
96    if (kept.size) return kept;
97  }
98  return found;
99}
100
101const BACKEND_OF_VENDOR = [['10de', 'cuda'], ['1002', 'hip'], ['8086', 'sycl']];
102
103/**
104 * Every engine family this PC's graphics cards can run, in the order NVIDIA, AMD, Intel; STRATA_ENGINE_BACKEND wins. A PC with two
105 * makes lists both, so a build for either make is accepted (recommend, never force).
106 */
107export function gpuBackendsHere(env = process.env, { vendors = windowsDisplayVendors() } = {}) {
108  const forced = String(env.STRATA_ENGINE_BACKEND ?? '').trim().toLowerCase();
109  if (forced) return ['cuda', 'hip', 'sycl'].includes(forced) ? [forced] : [];
110  if (vendors.size) {
111    const list = BACKEND_OF_VENDOR.filter(([vendor]) => vendors.has(vendor)).map(([, backend]) => backend);
112    if (list.length) return list;
113  }
114  if (nvidiaDriverVersion()) return ['cuda'];
115  try {
116    const base = '/sys/class/drm';
117    const seen = new Set();
118    for (const card of readdirSync(base)) {
119      if (!/^card\d+$/.test(card)) continue;
120      try { seen.add(readFileSync(`${base}/${card}/device/vendor`, 'utf8').trim().toLowerCase()); } catch { /* no vendor file */ }
121    }
122    const list = [['0x10de', 'cuda'], ['0x1002', 'hip'], ['0x8086', 'sycl']].filter(([vendor]) => seen.has(vendor)).map(([, backend]) => backend);
123    if (list.length) return list;
124  } catch { /* not Linux */ }
125  return [];
126}
127
128/**
129 * The engine family this PC's graphics card needs ('cuda', 'hip', 'sycl'), or null when it cannot be told. The same order as Control
130 * (NVIDIA first, then AMD, then Intel); STRATA_ENGINE_BACKEND wins. Reads only the driver and (Linux) the PCI vendor of the display adapters.
131 */
132export function gpuBackendHere(env = process.env, options = {}) {
133  return gpuBackendsHere(env, options)[0] ?? null;
134}
135
136const HIP_FAMILIES = [['RX 9000', ['gfx1200', 'gfx1201']], ['RX 7000', ['gfx1100', 'gfx1101', 'gfx1102']], ['RX 6000', ['gfx1030', 'gfx1031']], ['Ryzen AI Max', ['gfx1151']]];
137const MAKE_NAME = { cuda: 'NVIDIA', hip: 'AMD', sycl: 'Intel' };
138
139/** The plain sentence for a build made for another make of graphics card than this PC has. */
140export function wrongMakeNotice(manifest, here) {
141  const built = manifest.backend;
142  const families = [...new Set((manifest.archs ?? []).map(a => HIP_FAMILIES.find(([, list]) => list.includes(a))?.[0]).filter(Boolean))];
143  const builtFor = built === 'hip' && families.length ? `AMD ${families.join(' and ')}` : MAKE_NAME[built] ?? built;
144  return `This Strata is for ${builtFor} cards. Your PC has an ${MAKE_NAME[here] ?? here} card: download the ${MAKE_NAME[here] ?? here} version from ${RELEASES_URL}`;
145}
146
147/** One engine can ship as several builds of the same backend (CUDA 13 and CUDA 12 differ in the oldest driver they run on). */
148const variantOf = manifest => `${manifest.platform}/${manifest.backend}/${manifest.min_driver?.nvidia ?? ''}`;
149
150/** Does every file the manifest lists exist with its size (and, when `deep`, its SHA-256)? */
151export async function packageIsWhole(folder, manifest, { deep = false } = {}) {
152  for (const item of manifest.files) {
153    const rel = plainRelative(item?.path);
154    if (!rel || !/^[0-9a-f]{64}$/i.test(String(item.sha256 ?? '')) || !Number.isInteger(item.bytes)) return false;
155    const path = join(folder, ...rel.split('/'));
156    let info;
157    try { info = await stat(path); } catch { return false; }
158    if (!info.isFile() || info.size !== item.bytes) return false;
159    if (deep && (await sha256(path)).toLowerCase() !== String(item.sha256).toLowerCase()) return false;
160  }
161  return true;
162}
163
164/**
165 * Install the bundled engine when it is needed.
166 * Returns { action: 'installed' | 'repaired' | 'kept' | 'none' | 'refused', folder?, version?, reason? }; never throws.
167 */
168export async function installBundledEngine({ bundleDir, components, platform = null, log = () => {}, driver = undefined, backend = undefined } = {}) {
169  try {
170    if (!bundleDir || !components || !existsSync(bundleDir)) return { action: 'none' };
171    let packages = [];
172    for (const entry of await readdir(bundleDir, { withFileTypes: true })) {
173      if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
174      const manifest = await readManifest(join(bundleDir, entry.name));
175      if (manifest) packages.push({ name: entry.name, manifest });
176    }
177    if (platform) packages = packages.filter(p => p.manifest.platform === platform);
178    if (!packages.length) return { action: 'none' };
179    // A build for another make of graphics card than this PC has can never run here: it is not unpacked, and the caller says so in plain words.
180    // A PC with two makes (an AMD card for the model, an NVIDIA card for the desktop) accepts a build for either (#3892).
181    const wantedList = backend === undefined ? gpuBackendsHere() : (Array.isArray(backend) ? backend : backend ? [backend] : []);
182    const wanted = wantedList[0] ?? null;
183    if (wanted && ['cuda', 'hip', 'sycl'].includes(wanted)) {
184      const gpu = packages.filter(p => ['cuda', 'hip', 'sycl'].includes(p.manifest.backend));
185      const fits = packages.filter(p => !gpu.includes(p) || wantedList.includes(p.manifest.backend));
186      if (gpu.length && !fits.length) {
187        const first = gpu.sort((a, b) => compareVersions(b.manifest.version, a.manifest.version))[0].manifest;
188        return { action: 'wrong-make', built: first.backend, here: wanted, notice: wrongMakeNotice(first, wanted) };
189      }
190      packages = fits;
191    }
192    // The CUDA builds the NVIDIA driver here can run: all of them when the driver is unknown or fits several; when none fits, the one with the lowest
193    // requirement, so that Control can name the driver to install (copying the others would only waste disk).
194    const driverHere = driver === undefined ? nvidiaDriverVersion() : driver;
195    const need = item => item.manifest.min_driver?.nvidia ?? null;
196    if (driverHere) {
197      const cuda = packages.filter(p => need(p));
198      const fits = cuda.filter(p => compareVersions(driverHere, need(p)) >= 0);
199      if (cuda.length && !fits.length) {
200        const lowest = [...cuda].sort((a, b) => compareVersions(need(a), need(b)))[0];
201        packages = packages.filter(p => !need(p) || p === lowest);
202      } else {
203        packages = packages.filter(p => !need(p) || fits.includes(p));
204      }
205    }
206    // the newest bundled package of each platform/backend/driver requirement
207    packages.sort((a, b) => compareVersions(b.manifest.version, a.manifest.version));
208    const engineRoot = join(components, 'engine');
209    let last = { action: 'none' };
210    const done = new Set();
211    for (const { name, manifest } of packages) {
212      const key = variantOf(manifest);
213      if (done.has(key)) continue;
214      done.add(key);
215      if (!/^[\w.+-]+$/.test(name)) { last = { action: 'refused', reason: 'the package folder name is not plain' }; continue; }
216      // what is installed for the same platform and backend
217      let newestInstalled = null, sameFolder = null;
218      try {
219        for (const entry of await readdir(engineRoot, { withFileTypes: true })) {
220          if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
221          const installed = await readManifest(join(engineRoot, entry.name));
222          if (!installed || variantOf(installed) !== variantOf(manifest)) continue;
223          if (entry.name === name) sameFolder = installed;
224          if (!newestInstalled || compareVersions(installed.version, newestInstalled.version) > 0) newestInstalled = installed;
225        }
226      } catch { /* no engine folder yet */ }
227      let repair = false;
228      if (newestInstalled && compareVersions(newestInstalled.version, manifest.version) >= 0) {
229        // an engine of the same version or newer is already there; only a damaged copy of this very package is put right
230        if (sameFolder && !(await packageIsWhole(join(engineRoot, name), sameFolder))) repair = true;
231        else { last = { action: 'kept', version: newestInstalled.version }; continue; }
232      }
233      const source = join(bundleDir, name);
234      if (!(await packageIsWhole(source, manifest, { deep: true }))) {
235        last = { action: 'refused', reason: 'the engine inside the installer does not match its manifest' };
236        log(`bundled engine ${name}: ${last.reason}`);
237        continue;
238      }
239      await mkdir(engineRoot, { recursive: true });
240      const temp = join(engineRoot, `.bundle-${name}.tmp`);
241      await rm(temp, { recursive: true, force: true });
242      try {
243        await mkdir(temp, { recursive: true });
244        for (const item of [...manifest.files.map(f => f.path), MANIFEST]) {
245          const rel = plainRelative(item).split('/');
246          const target = join(temp, ...rel);
247          if (!resolve(target).startsWith(resolve(temp) + sep)) throw new Error('a path leaves the package');
248          await mkdir(dirname(target), { recursive: true });
249          await copyFile(join(source, ...rel), target);
250        }
251        if (!(await packageIsWhole(temp, manifest, { deep: true }))) throw new Error('the copy does not match the manifest');
252        const finalFolder = join(engineRoot, name);
253        if (repair) await rm(finalFolder, { recursive: true, force: true });
254        await rename(temp, finalFolder);
255      } catch (error) {
256        await rm(temp, { recursive: true, force: true }).catch(() => {});
257        last = { action: 'refused', reason: error?.message ?? String(error) };
258        log(`bundled engine ${name}: ${last.reason}`);
259        continue;
260      }
261      last = { action: repair ? 'repaired' : 'installed', folder: join(engineRoot, name), version: manifest.version };
262      log(`bundled engine ${name}: ${last.action}`);
263    }
264    return last;
265  } catch (error) {
266    return { action: 'refused', reason: error?.message ?? String(error) };
267  }
268}
269
270/**
271 * After an update from an installer that carried an engine (a per-GPU build), its `engine-bundle` folder is still in the install folder
272 * (about 570 MB) although the engine was copied to the engine store long ago. It is removed only when EVERY package in it exists complete in
273 * the store (every file there with the size and SHA-256 its manifest lists); otherwise it stays and one line says why.
274 * Returns { removed: bool, reason?: string, packages?: number }; never throws.
275 */
276export async function removeVerifiedBundle({ bundleDir, components, log = () => {} } = {}) {
277  try {
278    if (!bundleDir || !components || !existsSync(bundleDir)) return { removed: false, reason: 'no bundle' };
279    // Files inside a signed macOS app must stay intact after installation.
280    if (process.platform === 'darwin' && resolve(bundleDir).split(sep).some(part => part.toLowerCase().endsWith('.app'))) return keepBundle(log, 'macOS app bundles must remain unchanged after signing');
281    const packages = [];
282    for (const entry of await readdir(bundleDir, { withFileTypes: true })) {
283      if (!entry.isDirectory()) continue;
284      const folder = join(bundleDir, entry.name);
285      const manifest = await readManifest(folder);
286      packages.push({ folder, manifest, name: entry.name });
287    }
288    if (!packages.length) return { removed: false, reason: 'nothing in the bundle' };
289    const store = join(components, 'engine');
290    const stored = existsSync(store) ? (await readdir(store, { withFileTypes: true })).filter(e => e.isDirectory() && !e.name.startsWith('.')).map(e => join(store, e.name)) : [];
291    for (const pkg of packages) {
292      if (!pkg.manifest) return keepBundle(log, `${pkg.name} has no readable manifest`);
293      let found = false;
294      for (const candidate of stored) {
295        const theirs = await readManifest(candidate);
296        if (!theirs || theirs.version !== pkg.manifest.version || theirs.platform !== pkg.manifest.platform || theirs.backend !== pkg.manifest.backend
297          || (theirs.variant ?? '') !== (pkg.manifest.variant ?? '') || (theirs.build_id ?? '') !== (pkg.manifest.build_id ?? '')) continue;
298        if (await packageIsWhole(candidate, pkg.manifest, { deep: true })) { found = true; break; }
299      }
300      if (!found) return keepBundle(log, `${pkg.name} is not (or not completely) in the engine store`);
301    }
302    for (const pkg of packages) await rm(pkg.folder, { recursive: true, force: true });
303    log(`engine bundle: the copy that came with the installer (${packages.map(p => p.name).join(', ')}) was removed; the same engine is complete in the engine store`);
304    return { removed: true, packages: packages.length };
305  } catch (error) {
306    return keepBundle(log, `could not be checked (${error?.message ?? error})`);
307  }
308}
309function keepBundle(log, why) {
310  log(`engine bundle: kept in the install folder (${why})`);
311  return { removed: false, reason: why };
312}
313
314/**
315 * What the host does once its engine step has settled: for an engine that is (or was) there, look at the install folder's leftover bundle.
316 * The lines go to the host's output (console.log), which the desktop shell copies to its log file (`[host] engine bundle: ...`).
317 */
318export function cleanupAfterInstall(settled, { bundleDir, components, log = line => console.log(line) } = {}) {
319  return Promise.resolve(settled).then(result => (['installed', 'kept', 'repaired'].includes(result?.action) ? removeVerifiedBundle({ bundleDir, components, log }) : null), () => null);
320}