Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
host: Strata Control bridge (control-runtime, packaged native-control via owner runtime), acquisition.mjs gates the llama.cpp and cloudflared fetches, /api/control routes, acquire-spy tests
Niko12212622762f898c
diff --git a/apps/host/server/acquisition.mjs b/apps/host/server/acquisition.mjsnew file mode 100644index 000000000..060c88258--- /dev/null+++ b/apps/host/server/acquisition.mjs@@ -0,0 +1,31 @@+/**+ * The line between running the app and acquiring software, on the host side. It mirrors+ * strata_control/acquisition.py: starting a model, serving, and opening the app never download or install+ * an engine, a connector, a package or a compiler. Anything that would (the llama.cpp fetch, the cloudflared+ * fetch) calls `require()` first, and `require()` refuses where acquiring is forbidden.+ *+ * Forbidden means: STRATA_NO_ACQUIRE is 1/true/yes/on, or this is the packaged app (STRATA_PACKAGED=1).+ * The Tauri shell sets both for the host. Models the user chooses to download are a different, explicit action+ * with its own progress and consent and do not go through here.+ */++const TRUE = new Set(['1', 'true', 'yes', 'on']);++export class AcquisitionRefused extends Error {+ constructor(what, command = 'the Terminal command `strata install`') {+ super(`${what} is not installed here, and the app never downloads it while it runs. Install it from ${command}.`);+ this.name = 'AcquisitionRefused';+ this.code = 'acquisition_refused';+ this.status = 409;+ this.what = what;+ }+}++export function forbidden(env = process.env) {+ return TRUE.has(String(env.STRATA_NO_ACQUIRE ?? '').trim().toLowerCase()) || env.STRATA_PACKAGED === '1';+}++/** Call before any download or install. Throws AcquisitionRefused where acquiring is forbidden. */+export function require(what, command, env = process.env) {+ if (forbidden(env)) throw new AcquisitionRefused(what, command);+}diff --git a/apps/host/server/cloudflared-install.mjs b/apps/host/server/cloudflared-install.mjsindex 3c97ab8f1..fe45df562 100644--- a/apps/host/server/cloudflared-install.mjs+++ b/apps/host/server/cloudflared-install.mjs@@ -5,6 +5,7 @@ import { mkdir, mkdtemp, lstat, rename, rm, chmod, writeFile, access } from 'nodimport { constants } from 'node:fs';import { join } from 'node:path';import { promisify } from 'node:util';+import { require as requireAcquisition } from './acquisition.mjs';const run = promisify(execFile);const RELEASES = 'https://api.github.com/repos/cloudflare/cloudflared/releases/latest';@@ -24,16 +25,26 @@ export function verifyConnector(bytes, digest) {}}-export function createConnectorInstaller({ directory, platform = process.platform, arch = process.arch, fetchImpl = fetch }) {- const binary = join(directory, platform === 'win32' ? 'cloudflared.exe' : 'cloudflared');+/**+ * `componentDirectory` is where an optional, explicitly installed connector component would live (the local+ * component folder). A connector found there is used as it is; one that is not there is never fetched while the app+ * runs (acquisition.mjs), it is a notice.+ */+export function createConnectorInstaller({ directory, componentDirectory = null, platform = process.platform, arch = process.arch, fetchImpl = fetch }) {+ const name = platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';+ const binary = join(directory, name);let installing = null;async function locate() {- try { await access(binary, platform === 'win32' ? constants.F_OK : constants.X_OK); return binary; }- catch { return null; }+ for (const candidate of [binary, componentDirectory && join(componentDirectory, name)].filter(Boolean)) {+ try { await access(candidate, platform === 'win32' ? constants.F_OK : constants.X_OK); return candidate; }+ catch { /* try the next place */ }+ }+ return null;}async function install() {const existing = await locate();if (existing) return existing;+ requireAcquisition('The Cloudflare connector (cloudflared)', 'the optional connector component');const name = connectorAsset(platform, arch);await mkdir(directory, { recursive: true });const stage = await mkdtemp(join(directory, '.install-'));diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjsnew file mode 100644index 000000000..f9c1135ed--- /dev/null+++ b/apps/host/server/control-runtime.mjs@@ -0,0 +1,143 @@+/**+ * The App Host's bridge to Strata Control, the Python part of the product.+ *+ * In the installed app Control ships as a component next to the host (<install>/control): a pinned CPython with+ * hash-locked wheels, strata_control, strata_cli and the API server. The host never uses the user's Python, never runs+ * pip, git or a compiler, and never downloads anything to start a model: it asks Control, and Control starts the engine+ * under its owner runtime (loopback TCP + 256-bit token on Windows, a private socket elsewhere; a Job Object that ends+ * the server with its host; leases that stop a second owner).+ *+ * What lives here: where Control and the engine component folder are, a runner for the CLI (JSON in, JSON out, a+ * timeout, no shell), and the four operations the app needs: which engine this PC would use, which models are+ * installed, start a saved profile, stop it.+ */+import { spawn } from 'node:child_process';+import { existsSync, readFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { homedir } from 'node:os';++const HERE = dirname(fileURLToPath(import.meta.url));++export function bundledPython(dir, platform = process.platform) {+ return platform === 'win32' ? join(dir, 'python', 'python.exe') : join(dir, 'python', 'bin', 'python3');+}++/** The per-user component folder, the same rule as strata_control/engine_component.py components_dir(). */+export function componentsDirectory({ env = process.env, platform = process.platform, home = homedir() } = {}) {+ if (env.STRATA_COMPONENTS_DIR) return env.STRATA_COMPONENTS_DIR;+ if (platform === 'win32') return join(env.LOCALAPPDATA || join(home, 'AppData', 'Local'), 'Strata', 'components');+ return join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'strata', 'components');+}++/**+ * Is there a Control component to use? STRATA_CONTROL_DIR names it; otherwise it is the `control` folder beside+ * `host` in an installed app. Returns null in a source checkout (the host then keeps its older paths).+ */+export function findControl({ env = process.env, platform = process.platform, exists = existsSync, hostDir = resolve(HERE, '..') } = {}) {+ const candidates = [env.STRATA_CONTROL_DIR, join(hostDir, '..', 'control')].filter(Boolean).map(p => resolve(p));+ for (const dir of candidates) {+ const python = bundledPython(dir, platform);+ if (exists(python) && exists(join(dir, 'strata.py')) && exists(join(dir, 'strata_control'))) {+ let bundle = null;+ try { bundle = JSON.parse(readFileSync(join(dir, 'BUNDLE.json'), 'utf8').replace(/^/, '')); } catch { /* optional */ }+ return { dir, python, cli: join(dir, 'strata.py'), bundle };+ }+ }+ return null;+}++/** The environment Control runs in: nothing from the user's Python, and acquiring forbidden. */+export function controlEnvironment(control, { env = process.env, components = componentsDirectory({ env }) } = {}) {+ const next = { ...env };+ for (const key of ['PYTHONHOME', 'PYTHONPATH', 'PYTHONSTARTUP', 'VIRTUAL_ENV', 'STRATA_PYTHON', 'STRATA_NATIVE_PYTHON']) delete next[key];+ return {+ ...next,+ PYTHONNOUSERSITE: '1', PYTHONUTF8: '1', PYTHONUNBUFFERED: '1', PYTHONIOENCODING: 'utf-8',+ STRATA_NO_ACQUIRE: '1', STRATA_COMPONENTS_DIR: components, STRATA_API_KEY: '',+ ...(control?.dir ? { STRATA_CONTROL_DIR: control.dir } : {}),+ };+}++export class ControlError extends Error {+ constructor(message, { code = 'control_failed', exitCode = null, output = null } = {}) {+ super(message);+ this.name = 'ControlError';+ this.code = code;+ this.exitCode = exitCode;+ this.output = output;+ }+}++/** Run one CLI command of Control. Resolves { code, json, text, stderr }; rejects only if it cannot start or times out. */+export function runCli(control, args, { env = process.env, timeoutMs = 60_000, spawnProcess = spawn, components } = {}) {+ return new Promise((resolveRun, reject) => {+ const child = spawnProcess(control.python, [control.cli, ...args], {+ cwd: control.dir, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],+ env: controlEnvironment(control, { env, ...(components ? { components } : {}) }),+ });+ let out = '', err = '', done = false;+ const finish = (fn, value) => { if (done) return; done = true; clearTimeout(alarm); fn(value); };+ const alarm = setTimeout(() => {+ try { child.kill(); } catch { /* already gone */ }+ finish(reject, new ControlError(`Strata Control did not answer within ${Math.round(timeoutMs / 1000)} s (${args.slice(0, 2).join(' ')}).`, { code: 'control_timeout' }));+ }, timeoutMs);+ child.stdout.on('data', c => { out += c; if (out.length > 4_000_000) child.kill(); });+ child.stderr.on('data', c => { err += c; if (err.length > 200_000) err = err.slice(-100_000); });+ child.on('error', e => finish(reject, new ControlError(`Strata Control could not start: ${e.message}`, { code: 'control_missing' })));+ child.on('close', code => {+ let json = null;+ const text = out.trim();+ if (text) { try { json = JSON.parse(text.slice(text.indexOf('{'))); } catch { /* not JSON: caller reads text */ } }+ finish(resolveRun, { code, json, text, stderr: err.trim() });+ });+ });+}++const failure = (result, fallback) => new ControlError(+ result.json?.error?.message ?? result.json?.error ?? result.json?.notice ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || fallback),+ { exitCode: result.code, output: result.json });++/** Operations the app uses. `run` is injectable so the host's tests need no Python. */+export function createControl({ control = findControl(), env = process.env, run = null } = {}) {+ if (!control) return null;+ const call = run ?? ((args, options) => runCli(control, args, { env, ...options }));+ return {+ control,+ version: control.bundle?.version ?? null,+ async engine({ backend = null } = {}) {+ const result = await call(['components', 'engine', '--output', 'json', ...(backend ? ['--backend', backend] : [])], { timeoutMs: 30_000 });+ if (result.json) return result.json; // exit 5 still carries the report and the notice+ throw failure(result, 'The engine check failed.');+ },+ async installedModels({ installDir = null } = {}) {+ const result = await call(['models', 'list', '--installed', ...(installDir ? ['--install-dir', installDir] : []), '--output', 'json'], { timeoutMs: 60_000 });+ if (result.code !== 0 || !result.json) throw failure(result, 'The installed models could not be read.');+ return result.json;+ },+ async saveProfile(name, configPath) {+ const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 });+ const known = (listed.json?.profiles ?? []).some(p => p.id === name);+ const result = await call(known+ ? ['profile', 'use-config', name, '--from-config', configPath, '--output', 'json']+ : ['profile', 'create', name, '--from-config', configPath, '--output', 'json'], { timeoutMs: 30_000 });+ if (result.code !== 0) throw failure(result, 'The model profile could not be saved.');+ return result.json;+ },+ async start(name, { waitSeconds = 300 } = {}) {+ const result = await call(['runtime', 'start', '--profile', name, '--wait', String(waitSeconds), '--output', 'json'], { timeoutMs: (waitSeconds + 60) * 1000 });+ if (result.code !== 0 || !result.json?.ok) throw failure(result, 'The engine did not start.');+ return result.json;+ },+ async status(name) {+ const result = await call(['runtime', 'status', '--profile', name, '--output', 'json'], { timeoutMs: 30_000 });+ return result.json ?? { ok: false, state: 'unknown', error: result.stderr };+ },+ async stop(name, { waitSeconds = 120 } = {}) {+ const result = await call(['runtime', 'stop', '--profile', name, '--wait', String(waitSeconds), '--output', 'json'], { timeoutMs: (waitSeconds + 60) * 1000 });+ // an instance that is not running is already stopped+ 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.');+ return result.json;+ },+ };+}diff --git a/apps/host/server/engine-install.mjs b/apps/host/server/engine-install.mjsindex 97a1a8930..dd319bad9 100644--- a/apps/host/server/engine-install.mjs+++ b/apps/host/server/engine-install.mjs@@ -13,6 +13,7 @@ import { exec } from './util.mjs';import { HOME } from './store.mjs';import { tarBinary } from './platform-paths.mjs';import { nowIso } from './util.mjs';+import { require as requireAcquisition } from './acquisition.mjs';const ENGINE_DIR = join(HOME, 'engine');const RELEASES = 'https://api.github.com/repos/ggml-org/llama.cpp/releases?per_page=8';@@ -65,6 +66,7 @@ function assetMatcher() {}export async function findRelease() {+ requireAcquisition('The llama.cpp engine');state.status = 'checking';state.stage = 'Looking up the current llama.cpp build';emit();@@ -82,6 +84,7 @@ export async function findRelease() {}export async function install({ force = false } = {}) {+ requireAcquisition('The llama.cpp engine');if (running) return running;running = (async () => {diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex c75d9a860..ab7fbeedc 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -48,6 +48,9 @@ import { checkUpdates } from './updates.mjs';import { createImageModels } from './image-models.mjs';import { createRuntimeModels } from './runtime-models.mjs';import { createNativeControl } from './native-control.mjs';+import { findControl, createControl, componentsDirectory } from './control-runtime.mjs';+import { forbidden as acquisitionForbidden } from './acquisition.mjs';+import { timingSafeEqual } from 'node:crypto';import { nativeGateway } from './native-gateway.mjs';import { proxyCompletion } from './inference.mjs';import { validateChatImages } from './chat-images.mjs';@@ -74,7 +77,10 @@ const WORKSPACE = process.env.STRATA_WORKSPACE ?? process.cwd();const hub = new EventHub();const modelProviders = createModelProviders({ directory: store.DATA_DIR, changed: value => hub.send('providers', value) });const imageModels = createImageModels({ dataDir: store.DATA_DIR, modelsDir: () => store.MODELS_DIR, real: models.REAL, changed: value => hub.send('image-models', value) });-const native=createNativeControl({directory:store.DATA_DIR,modelsDirectory:()=>store.MODELS_DIR,nativeDataDirectory:store.nativeDataDirectory,beforeLoad:async()=>{if(models.REAL&&models.library().loaded){if(serving.state().requests.some(r=>runtimeModels.state().instances.some(i=>i.id===r.instanceId)&&["queued","generating"].includes(r.state)))throw new Error("Finish requests before switching engines.");await models.unload();runtimeState();}},requests:()=>serving.state().requests,changed:value=>hub.send('native',value)});+/* The installed app ships Strata Control (python + strata_control) next to the host; a source checkout has none and keeps its older paths. */+const CONTROL = findControl();+const control = createControl({ control: CONTROL });+const native=createNativeControl({control,directory:store.DATA_DIR,modelsDirectory:()=>store.MODELS_DIR,nativeDataDirectory:store.nativeDataDirectory,beforeLoad:async()=>{if(models.REAL&&models.library().loaded){if(serving.state().requests.some(r=>runtimeModels.state().instances.some(i=>i.id===r.instanceId)&&["queued","generating"].includes(r.state)))throw new Error("Finish requests before switching engines.");await models.unload();runtimeState();}},requests:()=>serving.state().requests,changed:value=>hub.send('native',value)});/* The agent: chats become DeepSeek Harness sessions when that component is installed. It is a separatepinned component (STRATA_HARNESS_DIR), not part of this host, so its absence is a visible capabilitystate and the chat falls back to the direct path with a notice, never silently to another model. */@@ -587,10 +593,10 @@ async function runTurn({ message, history = [], onFrame, signal, client, workspa}// `HERE` is apps/host/server, so the repository root is three levels up (server -> host -> apps).-const REPO_ROOT = resolve(HERE, '..', '..', '..');+const REPO_ROOT = CONTROL ? CONTROL.dir : resolve(HERE, '..', '..', '..');// The interpreter that drives the job is the same one the launcher would pick, named explicitly so// a packaged run uses the runtime the bundle carries rather than whatever `python3` resolves to.-const PYTHON = resolvePython({ repo: REPO_ROOT });+const PYTHON = resolvePython({ repo: REPO_ROOT, control: CONTROL });const TS_PYTHON = PYTHON.command;const REVISE_SCRIPT = resolve(REPO_ROOT, 'integrations', 'harness', 'revise_once.py');// A revision attempt is an agent turn, performed by the Harness through the pinned integration@@ -712,7 +718,7 @@ taskTimer.unref();const localShare = createLocalShare({ handle: openai, hasKey: () => !!store.get().serving?.apiKey, port: Number(process.env.STRATA_SHARE_PORT ?? PORT + 1), changed: () => serving.setSharing(localShare.state()) });const tunnelPort = Number(process.env.STRATA_TUNNEL_PORT ?? PORT + 2);const tunnelOrigin = createLocalShare({ handle: openai, hasKey: () => !!store.get().serving?.apiKey, host: '127.0.0.1', port: tunnelPort });-const connector = createConnectorInstaller({ directory: join(store.HOME, 'engine', 'cloudflare') });+const connector = createConnectorInstaller({ directory: join(store.HOME, 'engine', 'cloudflare'), componentDirectory: join(componentsDirectory(), 'cloudflared') });const cloudflare = createCloudflare({ origin: tunnelOrigin, originUrl: `http://127.0.0.1:${tunnelPort}`, hasKey: () => !!store.get().serving?.apiKey, changed: serving.setTunnel, locate: connector.locate, prepareConnector: connector.ensure });await cloudflare.inspect();@@ -919,6 +925,28 @@ async function api(req, res, path, method, url) {});}+ // --- Strata Control: what the installed app runs on, and what it will not do ---------------------+ if (path === '/api/control/status' && method === 'GET') {+ const engine = control ? await control.engine().catch(e => ({ usable: false, notice: e.message })) : null;+ return json(res, 200, {+ packaged: process.env.STRATA_PACKAGED === '1',+ control: CONTROL ? { dir: CONTROL.dir, python: CONTROL.python, version: control.version, bundle: CONTROL.bundle } : null,+ engine,+ componentsDir: componentsDirectory(),+ acquisition: { forbidden: acquisitionForbidden(), env: process.env.STRATA_NO_ACQUIRE ?? null },+ });+ }+ // The shell asks for a clean stop (engines this app started are stopped through Control) before it ends the process.+ if (path === '/api/control/shutdown' && method === 'POST') {+ const token = process.env.STRATA_SHUTDOWN_TOKEN ?? '';+ const given = String(req.headers['x-strata-shutdown'] ?? '');+ const same = token.length >= 32 && given.length === token.length && timingSafeEqual(Buffer.from(given), Buffer.from(token));+ if (!same) return error(res, 403, 'Not allowed.');+ json(res, 202, { stopping: true });+ setImmediate(() => void shutdown());+ return;+ }+if (path === '/api/setup' && method === 'GET') return json(res, 200, setupState());if (path === '/api/updates/check' && method === 'GET') return json(res, 200, await checkUpdates({ appVersion:native.state().version??setupState().app.version, engineVersion:native.state().available?(native.state().installed?.engine?.version??null):(await engine.config()).engine.version }));@@ -1123,7 +1151,7 @@ async function api(req, res, path, method, url) {const result = await engineInstall.install({ force: url.searchParams.get('force') === '1' });return json(res, 200, result);} catch (err) {- return error(res, 500, err.message, engineInstall.status());+ return error(res, err.status ?? 500, err.message, { ...engineInstall.status(), error: err.message });}}if (path === '/api/engine/export' && method === 'GET') return json(res, 200, await engine.exportConfig());@@ -1619,7 +1647,7 @@ let stopping=false;const shutdown = async () => {if(stopping)return;stopping=true;clearInterval(taskTimer);tasks.close();- const timeout=setTimeout(()=>process.exit(0),10000);timeout.unref();+ const timeout=setTimeout(()=>process.exit(0),control?75000:10000);timeout.unref(); // stopping an engine through Control can take a whileserver.close();server.closeAllConnections?.();await Promise.allSettled([localShare.stop(),cloudflare.stop(),native.close(),agent.close()]);process.exit(0);diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjsindex f5a0f5d8e..0b7c7c5ab 100644--- a/apps/host/server/native-control.mjs+++ b/apps/host/server/native-control.mjs@@ -1,151 +1,181 @@-/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */-import { spawn } from 'node:child_process';-import { randomBytes, randomUUID, createHash } from 'node:crypto';-import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs';-import { join, resolve, dirname, basename } from 'node:path';-import { fileURLToPath } from 'node:url';-import { createServer } from 'node:net';-import { NATIVE_FIELDS, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs';-import { resourceSettings } from './native-resources.mjs';-import { resolvePython, venvPython } from './python-resolver.mjs';-import { runtimeVision } from './native-vision.mjs';--const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..');-const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value);-const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state));-function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}}--export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){- mkdirSync(directory,{recursive:true});- const settingsPath=join(directory,'native-host.json');- let preferences=readJson(settingsPath,{repo:defaultRepo});- let child=null,seq=0,buffer='',pending=new Map(),definitions=[],refreshing=null,lastRead=0,connecting=null;- let snapshot={available:false,repo:preferences.repo,summary:'Connect a local Strata installation.',catalog:null,installed:null,hardware:null,error:null};- const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[];- const savedJobs=readJson(join(directory,'native-jobs.json'),[]);for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})});- let defaultId=null,timer=null,closing=false,polling=false;- const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);};- const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();};- function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}- function sourceText(){try{return readFileSync(join(preferences.repo,'serve/server.py'),'utf8');}catch{return '';}}- function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));}- function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}- function repo(){const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}- function python(){return resolvePython({repo:preferences.repo});}- function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});}- function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();}- async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;}- async function startClient(){- const folder=repo();- buffer='';const py0=python();const client=child=spawnProcess(py0.command,[...py0.args,join(folder,'tools/strata_mcp.py')],{cwd:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}});- client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}});- child.stderr.on('data',chunk=>append('control',chunk.toString()));- client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}});- client.on('exit',()=>{if(child===client){child=null;for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Strata control stopped. Python 3.10 or newer is required.'));}pending.clear();}});- await send('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'Strata UI',version:'0.1.0'}});- child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');- definitions=(await send('tools/list',{})).tools??[];- }- async function tool(name,args={}){await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;}- async function refresh(force=false){- if(closing)return state();- if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state();- refreshing=(async()=>{try{const [catalog,status]=await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:repo(),version:await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing;- }- function configure({repository}){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}- function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}- function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};}- function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};}- function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);}- function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}- async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));}- function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),confirm};}-- function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);}- async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}}- function externalRunning(){return Array.isArray(snapshot.external)?snapshot.external.filter(s=>![...instances.values()].some(i=>i.port===s.port)):[];}- async function install(job,args){if(job.state!=='running')return;if(externalRunning().length)throw new Error('Stop the native server running outside this UI before preparing files.');if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.');for(const id of [...instances.keys()])await unload(id);if(job.state!=='running')return;let result=await tool('strata_install',installArgs(args,true));job.summary=result.summary;job.result=result;emit();for(;;){if(job.state!=='running')return;await new Promise(resolve=>setTimeout(resolve,1500));result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(result.install&&!result.install.running){if(result.install.exit_code!==0)throw new Error(result.install.error??result.summary);await refresh(true);if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision});}return result;}}}- function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);}- async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});}- async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();}- async function loadEngine(job,args){- await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.');- if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.');- if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.');- const vision=runtimeVision(config,args.vision);- const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{};- const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile):null;- const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision};- if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');}- if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})};- for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.');- const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex');- const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement));- if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id};- const wasDefault=matching?.id===defaultId;- const id=matching?.id??randomUUID();let apiModelId=matching?.apiModelId??args.model,suffix=1;while(!matching&&[...instances.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${args.model}--${++suffix}`;- cfg.aliases=[...new Set([...(Array.isArray(cfg.aliases)?cfg.aliases:typeof cfg.aliases==='string'?cfg.aliases.split(',').map(s=>s.trim()).filter(Boolean):[]),apiModelId])];- const key=randomBytes(32).toString('hex');cfg.api_key=key;cfg.port=await freePort(args.port);- const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const configPath=join(work,`${id}.json`);- const py=venvPython(repo());if(!existsSync(py))throw new Error('The Strata Python environment is missing. Use Download / repair first.');- if(job.state!=='running')return;- await beforeLoad();if(job.state!=='running')return;- if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id);- if(job.state!=='running')return;- writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600});- const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};- const proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}});- instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id;- for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();});- proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit();- const deadline=Date.now()+300000;while(Date.now()<deadline&&job.state==='running'){- if(instance.status==='error')throw new Error(instance.error);- try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';if(resources||args.vision!==undefined)writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences});emit();ensurePoll();return {summary:`${instance.label} is ready.`,instanceId:id};}}catch{}- await new Promise(resolve=>setTimeout(resolve,1200));- }- if(job.state!=='running'){await unload(id);return;}- await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error);- }- async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');}- async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}}- function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();}- async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;}- function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;}- async function program(job,args){if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv;- if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];}- else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];}- else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];}- else if(job.kind==='update-strata'){const status=await execute('git',['status','--porcelain'],folder);if(status.trim())throw new Error('This Strata checkout has local edits. Save or commit them before updating.');const remote=await execute('git',['remote','get-url','origin'],folder);if(!/^https:\/\/github\.com\/Niko1221\/Strata(?:\.git)?\s*$/.test(remote))throw new Error('The native installation must use the official Strata repository to update here.');await execute('git',['pull','--ff-only'],folder);argv=[join(folder,'setup.py'),'--update'];}- else throw new Error('Unsupported native operation.');- return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});});- }- function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});}- function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);}- async function tune(job,args){- await refresh(true);if(job.state!=='running')return;- const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile);- if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.');- if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.');- if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.');- for(const id of [...instances.keys()])await unload(id);- if(job.state!=='running')return;- const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile);writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile});- if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);}- if(job.state!=='running')return;- const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile);- const next={...current.config,...values,ui_resource_profile:args.profile};- writeModelConfig(current.path,next);- job.summary='Applying your resource preference and loading the model…';emit();- const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:args.vision});- if(job.state!=='running'||!loaded?.instanceId)return;- job.summary='Checking your model’s speed…';emit();- const measured=await benchmark(job,{instanceId:loaded.instanceId});- return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile};- }- function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});}- async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();}- async function close(){closing=true;clearInterval(timer);const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true)));disconnect();}- // Remove nonserializable process references from public jobs.- const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,...job})=>job);return value;};- return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};-}+/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */+import { spawn } from 'node:child_process';+import { randomBytes, randomUUID, createHash } from 'node:crypto';+import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs';+import { join, resolve, dirname, basename } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createServer } from 'node:net';+import { NATIVE_FIELDS, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs';+import { resourceSettings } from './native-resources.mjs';+import { resolvePython, venvPython } from './python-resolver.mjs';+import os from 'node:os';+import { runtimeVision } from './native-vision.mjs';++const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..');+const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value);+const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state));+function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}}++export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},control=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){+ mkdirSync(directory,{recursive:true});+ const settingsPath=join(directory,'native-host.json');+ let preferences=readJson(settingsPath,{repo:defaultRepo});+ let child=null,seq=0,buffer='',pending=new Map(),definitions=[],refreshing=null,lastRead=0,connecting=null;+ let snapshot={available:false,repo:preferences.repo,summary:'Connect a local Strata installation.',catalog:null,installed:null,hardware:null,error:null};+ const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[];+ const savedJobs=readJson(join(directory,'native-jobs.json'),[]);for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})});+ /* Packaged mode: the app ships Strata Control (control-runtime.mjs). Models are run configs in an install folder, the engine+ comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed,+ updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */+ const packaged=!!control;+ const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.';+ let defaultId=null,timer=null,closing=false,polling=false;+ const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);};+ const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();};+ function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}+ function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}}+ function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));}+ function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}+ function repo(){if(packaged){const base=[preferences.installDir,snapshot.installDir].find(d=>d&&existsSync(d))??control.control.dir;return realpathSync(base);}const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}+ function python(){return resolvePython({repo:preferences.repo});}+ function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});}+ function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();}+ async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;}+ async function startClient(){+ const folder=repo();+ buffer='';const py0=python();const client=child=spawnProcess(py0.command,[...py0.args,join(folder,'tools/strata_mcp.py')],{cwd:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}});+ client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}});+ child.stderr.on('data',chunk=>append('control',chunk.toString()));+ client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}});+ client.on('exit',()=>{if(child===client){child=null;for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Strata control stopped. Python 3.10 or newer is required.'));}pending.clear();}});+ await send('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'Strata UI',version:'0.1.0'}});+ child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');+ definitions=(await send('tools/list',{})).tools??[];+ }+ async function controlTool(name){+ if(name==='strata_models')return {families:[],sizes:[],note:'Model files are installed from the Terminal; the app fetches nothing while it runs.'};+ if(name==='strata_status'){+ const [list,engine]=await Promise.all([control.installedModels({installDir:preferences.installDir}),control.engine()]);+ const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null}));+ const cores=os.cpus().length;+ return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'),+ installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir},+ installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models},+ hardware:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]},install:null,running:null};+ }+ if(name==='strata_install')throw new Error(NO_INSTALL);+ throw new Error(`Strata Control has no ${name}.`);+ }+ async function tool(name,args={}){if(packaged)return controlTool(name,args);await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;}+ async function refresh(force=false){+ if(closing)return state();+ if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state();+ refreshing=(async()=>{try{const [catalog,status]=await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing;+ }+ function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}+ function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}+ function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};}+ function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};}+ function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);}+ function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}+ async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));}+ function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),confirm};}++ function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);}+ async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}}+ function externalRunning(){return Array.isArray(snapshot.external)?snapshot.external.filter(s=>![...instances.values()].some(i=>i.port===s.port)):[];}+ async function install(job,args){if(job.state!=='running')return;if(externalRunning().length)throw new Error('Stop the native server running outside this UI before preparing files.');if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.');for(const id of [...instances.keys()])await unload(id);if(job.state!=='running')return;let result=await tool('strata_install',installArgs(args,true));job.summary=result.summary;job.result=result;emit();for(;;){if(job.state!=='running')return;await new Promise(resolve=>setTimeout(resolve,1500));result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(result.install&&!result.install.running){if(result.install.exit_code!==0)throw new Error(result.install.error??result.summary);await refresh(true);if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision});}return result;}}}+ function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);}+ async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});}+ async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();}+ async function loadEngine(job,args){+ await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.');+ if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.');+ if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.');+ const vision=runtimeVision(config,args.vision);+ const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{};+ const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile):null;+ const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision};+ if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');}+ if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})};+ for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.');+ const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex');+ const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement));+ if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id};+ const wasDefault=matching?.id===defaultId;+ const id=matching?.id??randomUUID();let apiModelId=matching?.apiModelId??args.model,suffix=1;while(!matching&&[...instances.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${args.model}--${++suffix}`;+ cfg.aliases=[...new Set([...(Array.isArray(cfg.aliases)?cfg.aliases:typeof cfg.aliases==='string'?cfg.aliases.split(',').map(s=>s.trim()).filter(Boolean):[]),apiModelId])];+ const key=randomBytes(32).toString('hex');cfg.api_key=key;cfg.port=await freePort(args.port);+ const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const configPath=join(work,`${id}.json`);+ const py=packaged?null:venvPython(repo());if(!packaged&&!existsSync(py))throw new Error('The Strata Python environment is missing. Use Download / repair first.');+ if(job.state!=='running')return;+ await beforeLoad();if(job.state!=='running')return;+ if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id);+ if(job.state!=='running')return;+ writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600});+ const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};+ let proc=null,started=null;+ if(packaged){+ /* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */+ const used=new Set([...instances.values()].map(i=>i.profile));let slot=1;while(used.has('app-'+slot))slot++;instance.profile='app-'+slot;+ instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit();+ started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300}));+ started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);});+ try{await started;}catch(error){instance.status='error';instance.error=error.message;emit();throw error;}+ } else {+ proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}});+ instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id;+ for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();});+ proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit();+ }+ const deadline=Date.now()+300000;while(Date.now()<deadline&&job.state==='running'){+ if(instance.status==='error')throw new Error(instance.error);+ try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';if(resources||args.vision!==undefined)writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences});emit();ensurePoll();return {summary:`${instance.label} is ready.`,instanceId:id};}}catch{}+ await new Promise(resolve=>setTimeout(resolve,1200));+ }+ if(job.state!=='running'){await unload(id);return;}+ if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error);+ }+ async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');}+ async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}}+ function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();}+ async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;}+ function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;}+ async function program(job,args){if(packaged)throw new Error(NO_INSTALL);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv;+ if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];}+ else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];}+ else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];}+ else if(job.kind==='update-strata'){const status=await execute('git',['status','--porcelain'],folder);if(status.trim())throw new Error('This Strata checkout has local edits. Save or commit them before updating.');const remote=await execute('git',['remote','get-url','origin'],folder);if(!/^https:\/\/github\.com\/Niko1221\/Strata(?:\.git)?\s*$/.test(remote))throw new Error('The native installation must use the official Strata repository to update here.');await execute('git',['pull','--ff-only'],folder);argv=[join(folder,'setup.py'),'--update'];}+ else throw new Error('Unsupported native operation.');+ return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});});+ }+ function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});}+ function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);}+ async function tune(job,args){+ await refresh(true);if(job.state!=='running')return;+ const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile);+ if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.');+ if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.');+ if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.');+ for(const id of [...instances.keys()])await unload(id);+ if(job.state!=='running')return;+ const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile);writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile});+ if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);}+ if(job.state!=='running')return;+ const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile);+ const next={...current.config,...values,ui_resource_profile:args.profile};+ writeModelConfig(current.path,next);+ job.summary='Applying your resource preference and loading the model…';emit();+ const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:args.vision});+ if(job.state!=='running'||!loaded?.instanceId)return;+ job.summary='Checking your model’s speed…';emit();+ const measured=await benchmark(job,{instanceId:loaded.instanceId});+ return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile};+ }+ function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});}+ async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();}+ async function close(){closing=true;clearInterval(timer);const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();}+ // Remove nonserializable process references from public jobs.+ const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,...job})=>job);return value;};+ return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};+}diff --git a/apps/host/server/python-resolver.mjs b/apps/host/server/python-resolver.mjsindex d2a3cbc5f..4d48d9ac9 100644--- a/apps/host/server/python-resolver.mjs+++ b/apps/host/server/python-resolver.mjs@@ -4,6 +4,8 @@** Order:* 1. STRATA_PYTHON, then STRATA_NATIVE_PYTHON (an explicit choice is never second-guessed)+ * 1b. the Control component's own interpreter, when the app ships one (control-runtime.mjs findControl):+ * the installed app never looks at the user's Python* 2. the repository's own venv: .venv\Scripts\python.exe on Windows, .venv/bin/python elsewhere* 3. Windows: `py -3` (the launcher), then python.exe; each one must actually start* (the Microsoft Store alias in WindowsApps exists on PATH but only opens the Store)@@ -28,12 +30,13 @@ export function pythonStarts(command, args = []) {const cache = new Map();-export function resolvePython({ repo = null, env = process.env, platform = process.platform, exists = existsSync, starts = pythonStarts, useCache = true } = {}) {- const key = JSON.stringify([repo, env.STRATA_PYTHON, env.STRATA_NATIVE_PYTHON, platform]);+export function resolvePython({ repo = null, control = null, env = process.env, platform = process.platform, exists = existsSync, starts = pythonStarts, useCache = true } = {}) {+ const key = JSON.stringify([repo, control?.python ?? null, env.STRATA_PYTHON, env.STRATA_NATIVE_PYTHON, platform]);if (useCache && cache.has(key)) return cache.get(key);const found = (() => {const explicit = env.STRATA_PYTHON || env.STRATA_NATIVE_PYTHON;if (explicit) return { command: explicit, args: [], source: 'environment' };+ if (control?.python) return { command: control.python, args: [], source: 'bundled' };if (repo) {const venv = venvPython(repo, platform);if (exists(venv)) return { command: venv, args: [], source: 'venv' };diff --git a/apps/host/tests/helpers/acquire-spy.mjs b/apps/host/tests/helpers/acquire-spy.mjsnew file mode 100644index 000000000..baf434bc7--- /dev/null+++ b/apps/host/tests/helpers/acquire-spy.mjs@@ -0,0 +1,77 @@+/**+ * A preload (`node --import acquire-spy.mjs server/index.mjs`) that watches a host process for anything that acquires+ * software, records each attempt as a JSON line in $ACQUIRE_SPY_LOG and blocks it:+ * - fetch / http(s) requests / sockets to anything but loopback;+ * - a child process that is a package manager, a compiler, git, a downloader or `python -m pip`.+ * The test that uses it fails if the log has a line. A host that was never allowed to acquire leaves it empty.+ */+import { appendFileSync } from 'node:fs';+import { basename } from 'node:path';+import childProcess from 'node:child_process';+import http from 'node:http';+import https from 'node:https';+import net from 'node:net';+import { syncBuiltinESMExports } from 'node:module';++const LOG = process.env.ACQUIRE_SPY_LOG;+const note = (kind, detail) => { try { appendFileSync(LOG, JSON.stringify({ kind, detail }) + '\n'); } catch { /* the test reads the log */ } };+const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1', '[::1]', '0.0.0.0', '']);+const FORBIDDEN = new Set(['pip', 'pip3', 'npm', 'npx', 'pnpm', 'yarn', 'git', 'curl', 'wget', 'cmake', 'ninja', 'cl', 'link', 'msbuild',+ 'winget', 'choco', 'scoop', 'apt', 'apt-get', 'dnf', 'pacman', 'brew', 'make', 'gcc', 'g++', 'cc', 'clang', 'rustup', 'cargo']);++const hostOf = value => {+ try { return new URL(typeof value === 'string' ? value : value?.url ?? String(value)).hostname.replace(/^\[|\]$/g, ''); } catch { return ''; }+};++const realFetch = globalThis.fetch;+globalThis.fetch = (input, init) => {+ const host = hostOf(input);+ if (!LOOPBACK.has(host)) { note('fetch', String(input?.url ?? input)); return Promise.reject(new TypeError('blocked by the acquisition spy')); }+ return realFetch(input, init);+};++for (const [module, label] of [[http, 'http'], [https, 'https']]) {+ for (const name of ['request', 'get']) {+ const original = module[name];+ module[name] = function patched(...args) {+ const first = args[0];+ const host = typeof first === 'string' || first instanceof URL ? hostOf(first) : (first?.hostname ?? first?.host ?? '').replace(/:\d+$/, '');+ if (!LOOPBACK.has(host)) { note(`${label}.${name}`, String(host)); throw new Error('blocked by the acquisition spy'); }+ return original.apply(this, args);+ };+ }+}++const originalConnect = net.Socket.prototype.connect;+net.Socket.prototype.connect = function patched(...args) {+ const first = args[0];+ const host = typeof first === 'object' && first ? (first.host ?? 'localhost') : (typeof args[1] === 'string' ? args[1] : 'localhost');+ if (typeof first === 'object' && first?.path) return originalConnect.apply(this, args);+ if (!LOOPBACK.has(String(host))) { note('socket', String(host)); throw new Error('blocked by the acquisition spy'); }+ return originalConnect.apply(this, args);+};++const looksLikeAcquisition = (command, args) => {+ const name = basename(String(command)).toLowerCase().replace(/\.(exe|cmd|bat)$/, '');+ if (FORBIDDEN.has(name)) return true;+ const list = (Array.isArray(args) ? args : []).map(String);+ if (/^python[\d.]*$|^py$/.test(name) && (list.includes('pip') || list.some(a => /(^|[\/])setup\.py$/.test(a)))) return true;+ return false;+};+for (const name of ['spawn', 'spawnSync', 'execFile', 'execFileSync']) {+ const original = childProcess[name];+ childProcess[name] = function patched(command, ...rest) {+ const args = Array.isArray(rest[0]) ? rest[0] : [];+ if (looksLikeAcquisition(command, args)) { note(name, [command, ...args].join(' ')); throw new Error('blocked by the acquisition spy'); }+ return original.call(this, command, ...rest);+ };+}+for (const name of ['exec', 'execSync']) {+ const original = childProcess[name];+ childProcess[name] = function patched(line, ...rest) {+ const first = String(line).trim().split(/\s+/)[0];+ if (looksLikeAcquisition(first, String(line).split(/\s+/).slice(1))) { note(name, String(line)); throw new Error('blocked by the acquisition spy'); }+ return original.call(this, line, ...rest);+ };+}+syncBuiltinESMExports();diff --git a/apps/host/tests/no-acquire.test.mjs b/apps/host/tests/no-acquire.test.mjsnew file mode 100644index 000000000..77982540e--- /dev/null+++ b/apps/host/tests/no-acquire.test.mjs@@ -0,0 +1,111 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createServer } from 'node:net';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { AcquisitionRefused, forbidden, require as requireAcquisition } from '../server/acquisition.mjs';+import * as engineInstall from '../server/engine-install.mjs';+import { createConnectorInstaller } from '../server/cloudflared-install.mjs';++const root = fileURLToPath(new URL('..', import.meta.url));+const spy = pathToFileURL(fileURLToPath(new URL('./helpers/acquire-spy.mjs', import.meta.url))).href;+const delay = ms => new Promise(r => setTimeout(r, ms));+async function freePort() { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }++test('the host-side switch: STRATA_NO_ACQUIRE or the packaged app forbids acquiring, nothing else does', () => {+ assert.equal(forbidden({}), false);+ for (const v of ['1', 'true', 'YES', 'on']) assert.equal(forbidden({ STRATA_NO_ACQUIRE: v }), true, v);+ for (const v of ['0', 'false', '', 'no']) assert.equal(forbidden({ STRATA_NO_ACQUIRE: v }), false, v);+ assert.equal(forbidden({ STRATA_PACKAGED: '1' }), true);+ assert.throws(() => requireAcquisition('the llama.cpp engine', undefined, { STRATA_NO_ACQUIRE: '1' }), AcquisitionRefused);+ assert.doesNotThrow(() => requireAcquisition('x', undefined, {}));+});++test('the llama.cpp and cloudflared fetches refuse before any request is made', async () => {+ const previous = process.env.STRATA_NO_ACQUIRE;+ process.env.STRATA_NO_ACQUIRE = '1';+ const realFetch = globalThis.fetch;+ let requests = 0;+ globalThis.fetch = async () => { requests++; throw new Error('network'); };+ const directory = await mkdtemp(join(tmpdir(), 'strata-no-acquire-'));+ try {+ await assert.rejects(engineInstall.install({ force: true }), err => err instanceof AcquisitionRefused && /llama\.cpp/.test(err.message) && err.status === 409);+ await assert.rejects(engineInstall.findRelease(), AcquisitionRefused);+ let connectorRequests = 0;+ const installer = createConnectorInstaller({ directory, platform: 'linux', arch: 'x64', fetchImpl: async () => { connectorRequests++; return { ok: false }; } });+ await assert.rejects(installer.ensure(), err => err instanceof AcquisitionRefused && /optional connector component/.test(err.message));+ assert.equal(requests + connectorRequests, 0, 'nothing was requested');+ assert.equal(existsSync(join(directory, '.install-')), false);+ } finally {+ globalThis.fetch = realFetch;+ if (previous === undefined) delete process.env.STRATA_NO_ACQUIRE; else process.env.STRATA_NO_ACQUIRE = previous;+ await rm(directory, { recursive: true, force: true });+ }+});++test('a connector placed in the component folder is used as it is; it is never fetched', async () => {+ const directory = await mkdtemp(join(tmpdir(), 'strata-connector-component-'));+ const components = join(directory, 'components', 'cloudflared');+ await mkdir(components, { recursive: true });+ const name = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';+ await writeFile(join(components, name), 'binary', { mode: 0o755 });+ try {+ const installer = createConnectorInstaller({ directory: join(directory, 'own'), componentDirectory: components, fetchImpl: async () => { throw new Error('no network'); } });+ assert.equal(await installer.locate(), join(components, name));+ assert.equal(await installer.ensure(), join(components, name));+ } finally { await rm(directory, { recursive: true, force: true }); }+});++async function runHost({ env, calls }) {+ const home = await mkdtemp(join(tmpdir(), 'strata-no-acquire-host-'));+ const log = join(home, 'spy.log');+ await writeFile(log, '');+ const port = await freePort(), base = `http://127.0.0.1:${port}`;+ const host = spawn(process.execPath, ['--import', spy, 'server/index.mjs'], {+ cwd: root, stdio: 'ignore',+ env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_REAL_ENGINE: '1', ACQUIRE_SPY_LOG: log, ...env },+ });+ const call = async (path, method = 'GET', body) => {+ const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });+ return { status: response.status, body: await response.json().catch(() => null) };+ };+ try {+ let up = false;+ for (let i = 0; i < 100 && !up; i++) { try { up = (await call('/api/health')).status === 200; } catch { await delay(100); } }+ assert.ok(up, 'host started');+ const results = await calls(call);+ await delay(300);+ const lines = (await readFile(log, 'utf8')).split('\n').filter(Boolean).map(l => JSON.parse(l));+ return { results, attempts: lines };+ } finally {+ host.kill();+ await new Promise(r => host.once('exit', r));+ await rm(home, { recursive: true, force: true });+ }+}++const probes = async call => ({+ health: await call('/api/health'),+ binary: await call('/api/engine/binary', 'POST'),+ tunnel: await call('/api/serving/tunnel', 'POST', { action: 'prepare' }),+ control: await call('/api/control/status'),+});++test('the packaged host serves, and every download/install route is refused without one attempt', { timeout: 60000 }, async () => {+ const { results, attempts } = await runHost({ env: { STRATA_PACKAGED: '1', STRATA_NO_ACQUIRE: '1' }, calls: probes });+ assert.equal(results.health.status, 200);+ assert.equal(results.binary.status, 409);+ assert.match(results.binary.body.error ?? results.binary.body.message ?? JSON.stringify(results.binary.body), /never downloads/);+ assert.ok(results.tunnel.status >= 400, 'preparing the connector is a refusal');+ assert.equal(results.control.body.acquisition.forbidden, true);+ assert.deepEqual(attempts, [], 'nothing tried to reach the internet or run an installer');+});++test('the spy is live: without the switch the same routes DO attempt to download (and are blocked)', { timeout: 60000 }, async () => {+ const { attempts } = await runHost({ env: { STRATA_PACKAGED: '', STRATA_NO_ACQUIRE: '' }, calls: async call => { await call('/api/engine/binary', 'POST'); await call('/api/serving/tunnel', 'POST', { action: 'prepare' }); } });+ assert.ok(attempts.some(a => a.kind === 'fetch' && /api\.github\.com\/repos\/ggml-org\/llama\.cpp/.test(a.detail)), JSON.stringify(attempts));+});diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjsnew file mode 100644index 000000000..0cffe83a7--- /dev/null+++ b/apps/host/tests/packaged-control.test.mjs@@ -0,0 +1,212 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { EventEmitter } from 'node:events';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs';+import { join, basename } from 'node:path';+import { tmpdir } from 'node:os';+import { bundledPython, componentsDirectory, controlEnvironment, createControl, findControl, runCli } from '../server/control-runtime.mjs';+import { resolvePython } from '../server/python-resolver.mjs';+import { createNativeControl } from '../server/native-control.mjs';++const isWin = process.platform === 'win32';++function fakeControlDir() {+ const dir = mkdtempSync(join(tmpdir(), 'strata-control-dir-'));+ mkdirSync(join(dir, 'python', ...(isWin ? [] : ['bin'])), { recursive: true });+ mkdirSync(join(dir, 'strata_control'), { recursive: true });+ mkdirSync(join(dir, 'serve'), { recursive: true });+ writeFileSync(bundledPython(dir), 'x');+ writeFileSync(join(dir, 'strata.py'), '# cli');+ writeFileSync(join(dir, 'serve', 'server.py'), 'port\nparallel\n/v1/responses');+ writeFileSync(join(dir, 'BUNDLE.json'), JSON.stringify({ version: '0.1.45', python: '3.12.15' }));+ return dir;+}++test('the Control component is found by STRATA_CONTROL_DIR or beside the host, and only if it is whole', () => {+ const dir = fakeControlDir();+ try {+ const found = findControl({ env: { STRATA_CONTROL_DIR: dir }, hostDir: join(dir, 'nowhere') });+ assert.equal(found.dir, dir);+ assert.equal(found.python, bundledPython(dir));+ assert.equal(found.bundle.python, '3.12.15');+ // beside the host: <install>/host + <install>/control+ const install = mkdtempSync(join(tmpdir(), 'strata-install-'));+ try {+ mkdirSync(join(install, 'host', 'server'), { recursive: true });+ assert.equal(findControl({ env: {}, hostDir: join(install, 'host') }), null, 'nothing beside the host yet');+ mkdirSync(join(install, 'control', 'python', ...(isWin ? [] : ['bin'])), { recursive: true });+ mkdirSync(join(install, 'control', 'strata_control'));+ writeFileSync(bundledPython(join(install, 'control')), 'x');+ writeFileSync(join(install, 'control', 'strata.py'), '#');+ assert.equal(findControl({ env: {}, hostDir: join(install, 'host') }).dir, join(install, 'control'));+ } finally { rmSync(install, { recursive: true, force: true }); }+ rmSync(join(dir, 'strata.py'));+ assert.equal(findControl({ env: { STRATA_CONTROL_DIR: dir }, hostDir: join(dir, 'x') }), null, 'a half component is not used');+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++test("Control runs on its own interpreter with nothing from the user's Python and acquiring forbidden", () => {+ const control = { dir: '/c', python: '/c/python/python3', cli: '/c/strata.py' };+ const env = controlEnvironment(control, { env: { PYTHONHOME: 'x', PYTHONPATH: 'y', VIRTUAL_ENV: 'z', STRATA_PYTHON: 'q', PATH: 'p', STRATA_API_KEY: 'secret' }, components: '/components' });+ assert.equal(env.PYTHONHOME, undefined);+ assert.equal(env.PYTHONPATH, undefined);+ assert.equal(env.VIRTUAL_ENV, undefined);+ assert.equal(env.STRATA_PYTHON, undefined);+ assert.equal(env.PYTHONNOUSERSITE, '1');+ assert.equal(env.STRATA_NO_ACQUIRE, '1');+ assert.equal(env.STRATA_COMPONENTS_DIR, '/components');+ assert.equal(env.STRATA_API_KEY, '', 'an inherited inference key never reaches the engine');+ assert.equal(env.PATH, 'p');+ // the resolver prefers the bundled interpreter over py -3 / PATH / a venv+ const python = resolvePython({ repo: '/repo', control, env: {}, exists: () => true, starts: () => { throw new Error('must not probe'); }, useCache: false });+ assert.deepEqual([python.command, python.source], ['/c/python/python3', 'bundled']);+ assert.equal(resolvePython({ control, env: { STRATA_PYTHON: '/mine' }, useCache: false }).command, '/mine', 'an explicit choice still wins');+ assert.equal(componentsDirectory({ env: { STRATA_COMPONENTS_DIR: '/x' } }), '/x');+ assert.match(componentsDirectory({ env: { LOCALAPPDATA: 'C:\\L' }, platform: 'win32', home: 'C:\\H' }), /Strata[\\/]components$/);+});++test('runCli passes the arguments untouched (no shell) and reads JSON', async () => {+ const seen = [];+ const spawnProcess = (command, args, options) => {+ seen.push({ command, args, options });+ const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.kill = () => {};+ queueMicrotask(() => { child.stdout.emit('data', '{"ok": true, "n": 1}\n'); child.emit('close', 0); });+ return child;+ };+ const control = { dir: '/c', python: '/c/python/python3', cli: '/c/strata.py' };+ const result = await runCli(control, ['models', 'list', '--installed', '--output', 'json'], { spawnProcess, env: {} });+ assert.deepEqual(result.json, { ok: true, n: 1 });+ assert.deepEqual(seen[0].args, ['/c/strata.py', 'models', 'list', '--installed', '--output', 'json']);+ assert.equal(seen[0].options.shell, undefined);+ assert.equal(seen[0].options.windowsHide, true);+ assert.equal(seen[0].options.env.STRATA_NO_ACQUIRE, '1');+});++// ---------------------------------------------------------------------------------- native-control in packaged mode++function packagedFixture({ engineUsable = true } = {}) {+ const root = mkdtempSync(join(tmpdir(), 'strata-packaged-test-'));+ const install = join(root, 'install'), data = join(root, 'data');+ mkdirSync(install, { recursive: true });+ const configs = ['iq2_xs', 'iq3_s'].map(id => {+ const path = join(install, `strata-${id}.json`);+ writeFileSync(path, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768'], model_name: `Qwen ${id}`, port: 8080 }));+ return { id, path };+ });+ const calls = [];+ const spawned = [];+ const control = {+ control: { dir: join(root, 'control') }, version: '0.1.45',+ async installedModels(options) { calls.push(['installedModels', options?.installDir ?? null]); return { install_dir: install, models: configs.map(c => ({ id: c.id, name: `Qwen ${c.id}`, source_config: c.path, component_status: 'present', context_tokens: 32768, backend: 'cuda' })) }; },+ async engine() {+ calls.push(['engine']);+ return engineUsable+ ? { usable: true, backend: 'cuda', components_dir: 'E:\\c', engine: { version: '0.1.45', platform: 'windows-x86_64', backend: 'cuda', exe: 'E:\\engine\\strata.exe', root: 'E:\\engine' } }+ : { usable: false, notice: 'No engine for this PC was found in E:\\c: the component folder holds no engine package. The app never downloads an engine while it starts or serves.', backend: 'cuda', engine: null, components_dir: 'E:\\c' };+ },+ async saveProfile(name, path) { calls.push(['saveProfile', name, basename(path)]); return {}; },+ async start(name, options) { calls.push(['start', name, options?.waitSeconds]); return { ok: true, state: 'ready' }; },+ async stop(name) { calls.push(['stop', name]); return { ok: true, state: 'stopped' }; },+ };+ const requests = [];+ const fetcher = async url => { calls.push(['fetch', url.replace(/:\d+/, ':PORT')]); return Response.json({ status: 'ok' }); };+ const native = createNativeControl({ control, directory: data, spawnProcess: (...args) => { spawned.push(args); throw new Error('no process may be started by the host in packaged mode'); }, fetcher, requests: () => requests });+ return { native, calls, spawned, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } };+}+const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); };++test('packaged: models come from Control, no python, git or engine process is started by the host', async () => {+ const f = packagedFixture();+ try {+ const state = await f.native.refresh(true);+ assert.equal(state.available, true, state.error);+ assert.deepEqual(state.installed.models.map(m => m.model), ['iq2_xs', 'iq3_s']);+ assert.equal(state.installed.models[0].ready, true);+ assert.equal(state.packaged, true);+ assert.match(state.summary, /engine 0\.1\.45/);+ assert.equal(state.version, '0.1.45');+ assert.equal(f.spawned.length, 0);+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: load = saved profile + runtime start under Control; unload = runtime stop; two models get two profiles', async () => {+ const f = packagedFixture();+ try {+ await f.native.refresh(true);+ const load = async args => { const job = await finish(f.native, f.native.operation('load', args).id); assert.equal(job.state, 'done', job.error); return job; };+ await load({ model: 'iq2_xs' });+ const first = f.native.state().instances[0];+ assert.equal(first.status, 'ready');+ const startCalls = f.calls.filter(c => ['saveProfile', 'start'].includes(c[0]));+ assert.deepEqual(startCalls.map(c => c.slice(0, 2)), [['saveProfile', 'app-1'], ['start', 'app-1']]);+ assert.equal(startCalls[1][2], 300);+ await load({ model: 'iq3_s', multiple: true });+ assert.deepEqual(f.calls.filter(c => c[0] === 'start').map(c => c[1]), ['app-1', 'app-2']);+ assert.equal(f.native.state().instances.length, 2);+ await f.native.unload(first.id);+ assert.deepEqual(f.calls.filter(c => c[0] === 'stop').at(-1), ['stop', 'app-1']);+ assert.equal(f.native.state().instances.length, 1);+ assert.equal(f.spawned.length, 0, 'the host never spawned anything itself');+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: no engine for this PC is the notice, and nothing is started', async () => {+ const f = packagedFixture({ engineUsable: false });+ try {+ await f.native.refresh(true);+ const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);+ assert.equal(job.state, 'error');+ assert.match(job.error, /No engine for this PC/);+ assert.match(job.error, /never downloads an engine/);+ assert.equal(f.calls.some(c => ['saveProfile', 'start'].includes(c[0])), false);+ assert.equal(f.spawned.length, 0);+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: install, update, rollback and calibration are refused with the Terminal notice and start nothing', async () => {+ const f = packagedFixture();+ try {+ await f.native.refresh(true);+ for (const [kind, args] of [['install', { family: 'qwen', model: 'IQ2_XS' }], ['update-engine', {}], ['update-strata', {}], ['rollback', {}], ['calibrate', { model: 'iq3_s' }]]) {+ const job = await finish(f.native, f.native.operation(kind, args).id);+ assert.equal(job.state, 'error', kind);+ assert.match(job.error, /Terminal|calibrates NVIDIA|No saved previous engine/, `${kind}: ${job.error}`);+ }+ assert.equal(f.spawned.length, 0);+ assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0);+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: the install folder can be chosen, and it is what Control is asked about', async () => {+ const f = packagedFixture();+ try {+ const other = join(f.root, 'other');+ mkdirSync(other);+ await f.native.configure({ repository: other });+ const saved = JSON.parse(readFileSync(join(f.root, 'data', 'native-host.json'), 'utf8'));+ assert.equal(saved.installDir.toLowerCase(), other.toLowerCase());+ assert.equal(f.calls.filter(c => c[0] === 'installedModels').at(-1)[1].toLowerCase(), other.toLowerCase());+ } finally { await f.native.close(); f.cleanup(); }+});++test('createControl asks the CLI for the engine, models and runtime and reads the notice of a missing engine', async () => {+ const seen = [];+ const control = createControl({+ control: { dir: '/c', python: '/p', cli: '/c/strata.py', bundle: { version: '9' } },+ run: async args => { seen.push(args.join(' ')); return args[0] === 'components' ? { code: 5, json: { ok: false, usable: false, notice: 'No engine for this PC' }, text: '', stderr: '' } : { code: 0, json: { ok: true, profiles: [] }, text: '', stderr: '' }; },+ });+ assert.equal((await control.engine()).notice, 'No engine for this PC');+ await control.installedModels({ installDir: 'D:\\Strata' });+ await control.saveProfile('app-1', 'C:\\x.json');+ await control.start('app-1');+ await control.stop('app-1');+ assert.deepEqual(seen, [+ 'components engine --output json',+ 'models list --installed --install-dir D:\\Strata --output json',+ 'profile list --output json',+ 'profile create app-1 --from-config C:\\x.json --output json',+ 'runtime start --profile app-1 --wait 300 --output json',+ 'runtime stop --profile app-1 --wait 120 --output json',+ ]);+ assert.equal(createControl({ control: null }), null);+});