okami.mom/strata

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

Niko1221Merge f-0243-guifix into f-0243-rel9caf39495

main
13.0 KiB322 linesraw
1/**
2 * Hardware detection.
3 *
4 * Real probes, cross-platform, never fatal: if a command is missing we fall back
5 * to Node's os module and a CPU-only verdict. The onboarding wizard shows exactly
6 * what was found.
7 */
8import os from 'node:os';
9import { readFile } from 'node:fs/promises';
10import { parseCpuTopology, parseWindowsProcessors, parseNvidiaDevices, detectDrmGpus } from './device-probes.mjs';
11import { CONTEXT_TOKENS, VARIANTS, footprint } from './catalog.mjs';
12import { MODELS_DIR, diskFreeGb, diskTotalGb } from './store.mjs';
13import { probe, round } from './util.mjs';
14import { utf8Script } from './powershell-utf8.mjs';
15import { DX_ADAPTERS_SCRIPT, parseDxAdapters, windowsOtherGpus } from './windows-gpu.mjs';
16
17let cached = null;
18let cachedAt = 0;
19
20export function invalidate() {
21  cached = null;
22}
23
24/**
25 * The last detected hardware, synchronously.
26 *
27 * Callers that build config (the expert param list, for one) are synchronous and
28 * cannot await a detection pass, but they still need to know how many cores the
29 * machine has. Returns null before the first detection, so callers must have a
30 * sensible fallback rather than assuming a machine shape.
31 */
32export function cachedHardware() {
33  return cached ?? null;
34}
35
36function testHardware() {
37  const raw = process.env.STRATA_TEST_HARDWARE;
38  if (!raw) return null;
39  try { const value = JSON.parse(raw); return value && typeof value === 'object' ? value : null; } catch { return null; }
40}
41
42export async function detect({ force = false } = {}) {
43  if (!force && cached && Date.now() - cachedAt < 30_000) return cached;
44
45  const platform = process.platform;
46  const arch = process.arch;
47  // Tests only: STRATA_TEST_HARDWARE='{"totalGb":128,"freeGb":100,"gpus":[...]}' stands in for the probes, so a
48  // test about routing or lifecycle does not depend on how much memory the machine running it has.
49  const forced = testHardware();
50  const totalGb = forced?.totalGb ?? os.totalmem() / 1024 ** 3;
51  // os.freemem() ignores reclaimable pages, which reads as "0 GB free" on macOS.
52  const freeGb = forced?.freeGb ?? (await availableMemoryGb(platform)) ?? os.freemem() / 1024 ** 3;
53
54  const cpu = await detectCpu(platform);
55  const gpus = forced?.gpus ?? await detectGpus(platform, totalGb);
56  const accelerator = pickAccelerator(gpus, cpu, totalGb);
57
58  const hw = {
59    probedAt: new Date().toISOString(),
60    host: {
61      name: os.hostname().replace(/\.local$/, ''),
62      platform: platformLabel(platform),
63      release: os.release(),
64      arch,
65      app: process.version,
66    },
67    cpu,
68    processors: cpu.processors,
69    memory: {
70      totalGb: round(totalGb / 1, 1),
71      freeGb: round(freeGb / 1, 1),
72      usedGb: round(totalGb - freeGb, 1),
73      pressure: freeGb / totalGb > 0.35 ? 'low' : freeGb / totalGb > 0.18 ? 'medium' : 'high',
74    },
75    disk: {
76      path: MODELS_DIR,
77      totalGb: round(diskTotalGb(MODELS_DIR), 0),
78      freeGb: round(diskFreeGb(MODELS_DIR), 0),
79      modelsDir: MODELS_DIR,
80    },
81    gpus,
82    accelerator,
83    checks: [],
84    verdict: { ok: true, headline: '', detail: '' },
85    recommendedVariantId: '',
86  };
87
88  hw.checks = buildChecks(hw);
89  hw.verdict = buildVerdict(hw);
90  hw.recommendedVariantId = recommend(hw);
91
92  cached = hw;
93  cachedAt = Date.now();
94  return hw;
95}
96
97/** Reclaimable memory, not just the free list. */
98export async function availableMemoryGb(platform) {
99  if(platform==='linux') {
100    try { const raw=await readFile('/proc/meminfo','utf8'); const available=Number(/MemAvailable:\s+(\d+)/.exec(raw)?.[1]); return available>0?available/1024**2:null; } catch { return null; }
101  }
102  if (platform !== 'darwin') return null;
103  const out = await probe('vm_stat', []);
104  if (!out) return null;
105  const pageSize = Number(/page size of (\d+)/.exec(out)?.[1] ?? 4096);
106  const pages = (label) => Number(new RegExp(`Pages ${label}:\\s+(\\d+)`).exec(out)?.[1] ?? 0);
107  const reclaimable = pages('free') + pages('inactive') + pages('speculative') + pages('purgeable');
108  if (!reclaimable) return null;
109  return (reclaimable * pageSize) / 1024 ** 3;
110}
111
112async function detectCpu(platform) {
113  const logical = os.cpus(), threads = logical.length || 1;
114  let model = logical[0]?.model?.trim() ?? 'Unknown processor', ghz=round((logical[0]?.speed??0)/1000,2), processors=[];
115  if(platform==='darwin') {
116    const [brand,physical,threadCount,packages]=await Promise.all([
117      probe('sysctl',['-n','machdep.cpu.brand_string']),probe('sysctl',['-n','hw.physicalcpu']),probe('sysctl',['-n','hw.logicalcpu']),probe('sysctl',['-n','hw.packages'])
118    ]);
119    if(brand)model=brand;
120    const cores=Number(physical),count=Number(packages),totalThreads=Number(threadCount)||threads;
121    if(cores>0&&count>0&&cores%count===0&&totalThreads%count===0)processors=Array.from({length:count},(_,i)=>({id:`socket-${i}`,socket:String(i),model,cores:cores/count,threads:totalThreads/count,arch:process.arch,ghz,...(count===1?{logicalIds:logical.map((_,index)=>index)}:{})}));
122  } else if(platform==='linux') {
123    const raw=await probe('lscpu',['-b','-p=CPU,CORE,SOCKET']);
124    const names=new Map();
125    try { for(const block of (await readFile('/proc/cpuinfo','utf8')).split(/\n\s*\n/)) {
126      const fields=Object.fromEntries(block.split('\n').filter(l=>l.includes(':')).map(l=>{const i=l.indexOf(':');return [l.slice(0,i).trim(),l.slice(i+1).trim()];}));
127      if(fields['physical id']&&fields['model name'])names.set(fields['physical id'],fields['model name']);
128    }}catch{}
129    processors=parseCpuTopology(raw,model,process.arch,ghz,names);
130  } else if(platform==='win32') {
131    const raw=await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',utf8Script('Get-CimInstance Win32_Processor | Select-Object DeviceID,SocketDesignation,Name,NumberOfCores,NumberOfLogicalProcessors,MaxClockSpeed | ConvertTo-Json -Compress')]);
132    processors=parseWindowsProcessors(raw,process.arch);
133  }
134  const names=[...new Set(processors.map(p=>p.model))];
135  return {model:names.length===1?names[0]:names.length>1?names.join(' + '):model,cores:processors.length?processors.reduce((n,p)=>n+p.cores,0):threads,threads:processors.length?processors.reduce((n,p)=>n+p.threads,0):threads,arch:process.arch,ghz,processors,topologyKnown:!!processors.length};
136}
137
138async function detectGpus(platform, totalGb) {
139  const gpus = [];
140
141  if (platform === 'darwin') {
142    const raw = await probe('system_profiler', ['SPDisplaysDataType', '-json'], 8000);
143    if (raw) {
144      try {
145        const parsed = JSON.parse(raw);
146        const list = parsed?.SPDisplaysDataType ?? [];
147        list.forEach((g, i) => {
148          const name = g.sppci_model ?? g._name ?? 'Apple GPU';
149          if (!name || /display/i.test(name)) return;
150          const cores = Number(g.sppci_cores) || 0;
151          gpus.push({
152            id: `metal:${i}`,
153            index: i,
154            vendor: /apple/i.test(name) ? 'apple' : /amd|radeon/i.test(name) ? 'amd' : /intel/i.test(name) ? 'intel' : 'unknown',
155            name: cores ? `${name} (${cores}-core GPU)` : name,
156            // Apple silicon shares system memory; Metal's default wired limit is ~75%.
157            vramGb: /apple/i.test(name)&&process.arch==='arm64' ? round(totalGb * 0.75, 1) : (Number.parseFloat(String(g.sppci_vram??g.spdisplays_vram??'')) || 0) * (/MB/i.test(String(g.sppci_vram??g.spdisplays_vram??''))?1/1024:1),
158            unified: /apple/i.test(name)&&process.arch==='arm64',
159            backend: 'metal',
160          });
161        });
162      } catch {
163        /* fall through */
164      }
165    }
166    if (!gpus.length && process.arch === 'arm64') {
167      const chip = await probe('sysctl', ['-n', 'machdep.cpu.brand_string']);
168      gpus.push({
169        id: 'metal:0',
170        index: 0,
171        vendor: 'apple',
172        name: chip || 'Apple silicon GPU',
173        vramGb: round(totalGb * 0.75, 1),
174        unified: true,
175        backend: 'metal',
176      });
177    }
178  }
179
180  const smi = await probe('nvidia-smi', ['--query-gpu=index,uuid,pci.bus_id,name,memory.total,driver_version','--format=csv,noheader,nounits']);
181  gpus.push(...parseNvidiaDevices(smi));
182  if(platform==='linux') {
183    const drm=await detectDrmGpus();
184    for(const gpu of drm) {
185      const existing=gpus.find(g=>g.busId?.replace(/^00000000:/,'0000:')===gpu.busId);
186      if(existing)existing.sensorPath=gpu.sensorPath;else gpus.push(gpu);
187    }
188  }
189  if(platform==='win32') {
190    const raw=await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',utf8Script('Get-CimInstance Win32_VideoController | Select-Object Name,PNPDeviceID | ConvertTo-Json -Compress')]);
191    try {
192      const parsed=JSON.parse(raw);
193      const rows=(Array.isArray(parsed)?parsed:[parsed]).filter(row=>row?.Name&&!(/nvidia/i.test(row.Name)&&gpus.some(g=>g.vendor==='nvidia')));
194      const dx=rows.length?parseDxAdapters(await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',DX_ADAPTERS_SCRIPT],8000)):[];
195      for(const card of windowsOtherGpus(rows,dx))gpus.push({...card,index:gpus.length,unified:false,backend:'vulkan'});
196    }catch{}
197  }
198  gpus.forEach((g,i)=>{g.index=i;});
199
200  return gpus;
201}
202
203function pickAccelerator(gpus, cpu, totalGb) {
204  const best = [...gpus]
205    .filter((g) => g.backend !== 'cpu')
206    .sort((a, b) => b.vramGb - a.vramGb)[0];
207  if (best) {
208    return {
209      backend: best.backend,
210      label: best.name,
211      usableVramGb: best.vramGb,
212      unified: best.unified,
213    };
214  }
215  return {
216    backend: 'cpu',
217    label: `${cpu.model.split('@')[0].trim()} (CPU only)`,
218    usableVramGb: round(totalGb * 0.5, 1),
219    unified: true,
220  };
221}
222
223function buildChecks(hw) {
224  const checks = [];
225  const accel = hw.accelerator;
226
227  checks.push(
228    accel.backend === 'cpu'
229      ? {
230          id: 'gpu',
231          label: 'GPU and driver',
232          state: 'warn',
233          detail: 'No GPU accelerator found — Strata will run on the CPU',
234          value: accel.label,
235        }
236      : {
237          id: 'gpu',
238          label: 'GPU and driver',
239          state: 'pass',
240          detail: 'Compatible GPU found',
241          value: `${accel.label} · ${accel.backend}`,
242        },
243  );
244
245  const total = hw.memory.totalGb;
246  checks.push(
247    total >= 32
248      ? { id: 'memory', label: 'System memory', state: 'pass', detail: 'Enough for recommended model', value: `${Math.round(total)} GB` }
249      : total >= 16
250        ? { id: 'memory', label: 'System memory', state: 'pass', detail: 'Enough for the smallest model', value: `${Math.round(total)} GB` }
251        : { id: 'memory', label: 'System memory', state: 'fail', detail: 'Below the 16 GB minimum', value: `${Math.round(total)} GB` },
252  );
253
254  const cores = hw.cpu.cores;
255  checks.push(
256    cores >= 8
257      ? { id: 'cpu', label: 'CPU', state: 'pass', detail: 'Supported', value: `${cores} cores` }
258      : cores >= 4
259        ? { id: 'cpu', label: 'CPU', state: 'pass', detail: 'Supported, slower prompt reading', value: `${cores} cores` }
260        : { id: 'cpu', label: 'CPU', state: 'warn', detail: 'Few cores — expect slow prompt reading', value: `${cores} cores` },
261  );
262
263  const free = hw.disk.freeGb;
264  checks.push(
265    free >= 60
266      ? { id: 'storage', label: 'Free storage', state: 'pass', detail: 'Space available', value: `${Math.round(free)} GB free` }
267      : free >= 25
268        ? { id: 'storage', label: 'Free storage', state: 'pass', detail: 'Enough for one model', value: `${Math.round(free)} GB free` }
269        : { id: 'storage', label: 'Free storage', state: 'warn', detail: 'Tight — pick the smallest variant', value: `${Math.round(free)} GB free` },
270  );
271
272  return checks;
273}
274
275function buildVerdict(hw) {
276  const failed = hw.checks.filter((c) => c.state === 'fail');
277  const warned = hw.checks.filter((c) => c.state === 'warn');
278  if (failed.length) {
279    return {
280      ok: false,
281      headline: 'This computer is below the minimum.',
282      detail: `${failed.map((f) => f.label).join(' and ')} need attention before a model will fit.`,
283    };
284  }
285  if (warned.length) {
286    return {
287      ok: true,
288      headline: 'This computer can run Strata.',
289      detail: `${warned.map((w) => w.label).join(' and ')} ${warned.length > 1 ? 'are' : 'is'} a limit — Strata will pick a lighter model.`,
290    };
291  }
292  return {
293    ok: true,
294    headline: 'This computer can run Strata comfortably.',
295    detail: 'Everything needed for the recommended model is present.',
296  };
297}
298
299/**
300 * Recommend the heaviest variant that still fits fast memory at the default
301 * context, using the same footprint maths the tuning screen shows. When nothing
302 * fits, fall back to the smallest tier rather than the biggest.
303 */
304function recommend(hw) {
305  const usable = hw.accelerator.unified
306    ? hw.memory.totalGb * 0.72
307    : hw.accelerator.usableVramGb + hw.memory.totalGb * 0.35;
308  const ctx = CONTEXT_TOKENS.recommended;
309
310  const viable = VARIANTS.map((v) => ({ v, fp: footprint(v, ctx) }))
311    .filter(({ fp }) => fp.totalGb <= usable)
312    .sort((a, b) => b.fp.totalGb - a.fp.totalGb);
313
314  if (viable.length) return viable[0].v.id;
315
316  const smallest = [...VARIANTS].sort((a, b) => footprint(a, ctx).totalGb - footprint(b, ctx).totalGb)[0];
317  return smallest?.id ?? VARIANTS[0].id;
318}
319
320function platformLabel(platform) {
321  return platform === 'darwin' ? 'macOS' : platform === 'win32' ? 'Windows' : platform === 'linux' ? 'Linux' : platform;
322}