okami.mom/strata

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

Niko1221Merge f-no-llama-server: the packaged app loads only through the Strata engine; a llama-server on PATH or in STRATA_LLAMA_SERVER is never started (Load and autostart)f5ef26889

main
147.3 KiB2347 linesraw
1#!/usr/bin/env node
2import { engineProgressMark } from './agent/engine-progress.mjs';
3import './system-ca.mjs';        // #3722: the operating system's certificates, before any HTTPS request
4import { createCloudflare } from './cloudflare.mjs';
5import { createConnectorInstaller } from './cloudflared-install.mjs';
6import { findRunningConnector } from './cloudflared-find.mjs';
7import { openArtifact } from './artifacts.mjs';
8import { saveSnapshot } from './snapshot.mjs';
9import { resolvePython, shellPrefix } from './python-resolver.mjs';
10import { chooseFolder, chooserUnavailable, typedFolder } from './folder-dialog.mjs';
11import { createLocalShare } from './local-share.mjs';
12import { createTaskService, validateTask } from './tasks.mjs';
13import { createAgentTaskRunner } from './agent/task-run.mjs';
14import { migrateSetup } from './setup.mjs';
15import { skillEdit } from './skill-edits.mjs';
16import { materializeSkills, parseSkillFile, skillSlug, writeCreatedSkill } from './skill-files.mjs';
17import { systemFonts } from './fonts.mjs';
18import { tuningDir } from './platform-paths.mjs';
19import { createAgentBridge, plainTurnFailure } from './agent/agent-bridge.mjs';
20import { mcpSkippedNotices } from './agent/profile.mjs';
21import { createAgentTools } from './agent/tools-settings.mjs';
22import { withPlainStatus } from './agent/status.mjs';
23import { findBrowser, findPlaywrightMcp } from './agent/browser-probe.mjs';
24/**
25 * Strata engine host.
26 *
27 *   node server/index.mjs                 # API only (use with `npm run dev`)
28 *   node server/index.mjs --dist dist     # API + the built web app on one port
29 *
30 * Owns hardware detection, the model library, engine tuning, the serving log,
31 * live metrics and the local inference API. No runtime dependencies.
32 */
33import http from 'node:http';
34import { homedir } from 'node:os';
35import { statfsSync, cpSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
36import { pipeline } from 'node:stream/promises';
37import { spawn } from 'node:child_process';
38import { execFile } from 'node:child_process';
39import { promisify } from 'node:util';
40import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
41import { fileURLToPath } from 'node:url';
42
43import * as hardware from './hardware.mjs';
44import * as models from './models.mjs';
45import * as engine from './engine.mjs';
46import * as monitor from './monitor.mjs';
47import * as serving from './serving.mjs';
48import * as store from './store.mjs';
49import { createChatStore, storeFailure } from './chat-store.mjs';
50import { makePrivateDir } from './private-file.mjs';
51import * as supervisor from './supervisor.mjs';
52import * as engineInstall from './engine-install.mjs';
53import { detectBackend, currentBackend, streamChat, inferenceLine } from './inference.mjs';
54import { CONTEXT_TOKENS, VARIANTS, localModels, variant } from './catalog.mjs';
55import { browseLocalModels, inspectLocalModel } from './local-models.mjs';
56import { keepStreamAlive } from './stream-beat.mjs';
57import { EventHub, badRequest, error, json, readBody, readRaw, requestUrl, sameSecret, uid } from './util.mjs';
58import { createUploads } from './chat-uploads.mjs';
59import { createNativeDrops } from './native-drop.mjs';
60import { createVisionProbe, effectiveVision, readsPicturesByDefault } from './vision-probe.mjs';
61import { RequestQueue } from './request-queue.mjs';
62import { selectSkills, skillInstructions } from './skill-selection.mjs';
63import { createModelProviders } from './model-providers.mjs';
64import { createForkTimeskip } from './timeskip-fork.mjs';
65import { prepareOversized } from './oversize.mjs';
66import { createChatFolders, chatRootOf, openFile, resolveChatFile, previewFile, rawFile, createAttachments, withAttachments } from './chat-files.mjs';
67import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs';
68import { checkUpdates, checkComponentUpdates, engineFirstRun } from './updates.mjs';
69import { plainNoModel } from './no-model-text.mjs';
70import { createAppUi } from './app-ui.mjs';
71import { appVersionFrom, appVersionToShow } from './app-version.mjs';
72import { createImageModels } from './image-models.mjs';
73import { createRuntimeModels } from './runtime-models.mjs';
74import { createNativeControl } from './native-control.mjs';
75import { nativeUnloadPlan } from './storage-check.mjs';
76import { installBundledEngine, cleanupAfterInstall } from './bundled-engine.mjs';
77import { systemLocale } from './region.mjs';
78import { createShellNotifier, DEFAULT_PORT, parsePortNotice, readShellPrefs, writeShellPrefs } from './shell-prefs.mjs';
79import { findControl, createControl, componentsDirectory } from './control-runtime.mjs';
80import { listEngines, changeEngine } from './engine-library.mjs';
81import { forbidden as acquisitionForbidden } from './acquisition.mjs';
82import { randomBytes, timingSafeEqual } from 'node:crypto';
83import { nativeGateway } from './native-gateway.mjs';
84import { proxyCompletion } from './inference.mjs';
85import { apiPath } from './api-paths.mjs';
86import { findFreePort, listenProblem } from './ports.mjs';
87import { validateChatImages } from './chat-images.mjs';
88import { createTimeSkip, measureFolder, timeskipRevisionMessage, imageTypeOf } from './timeskip.mjs';
89
90const HERE = fileURLToPath(new URL('.', import.meta.url));
91const ROOT = resolve(HERE, '..');
92const argv = process.argv.slice(2);
93const distFlag = argv.indexOf('--dist');
94// `STRATA_DIST` exists for carriers that load this module directly rather than starting it as its
95// own process (the Electron app does that). Such a carrier cannot rely on `--dist`: when the host
96// runs as the Electron main process, `process.argv` is Chromium's switch list and the host's own
97// flags are not reliably present. An explicit environment variable is unambiguous, and the CLI
98// `--dist` form keeps working unchanged.
99const DIST = process.env.STRATA_DIST
100  ? resolve(process.env.STRATA_DIST)
101  : distFlag >= 0
102    ? resolve(argv[distFlag + 1] ?? join(ROOT, 'dist'))
103    : join(ROOT, 'dist');
104const PORT = Number(process.env.STRATA_PORT ?? 8791);
105const HOST = process.env.STRATA_BIND ?? '127.0.0.1';
106/* The folder chats work in when nothing else is chosen. It is never the app's own folder (the host is started inside its install
107   directory, so `process.cwd()` was "host" in the sidebar and the agent could read and write the app): the person's own
108   Documents\Strata\Workspace (the models folder is next to it, not in it), created on first use, unless STRATA_WORKSPACE names one. */
109function defaultWorkspace() {
110  if (process.env.STRATA_WORKSPACE) return resolve(process.env.STRATA_WORKSPACE);
111  const user = process.env.USERPROFILE ?? process.env.HOME ?? homedir();
112  for (const base of [join(user, 'Documents'), user]) {
113    const dir = join(base, 'Strata', 'Workspace');
114    try { mkdirSync(dir, { recursive: true }); return dir; } catch { /* try the next place */ }
115  }
116  return user;
117}
118const WORKSPACE = defaultWorkspace();
119const WORKSPACE_NAME = process.env.STRATA_WORKSPACE ? basename(WORKSPACE) : 'Strata';
120/** True for the app's own install/source folder or anything inside it. */
121const insideApp = path => { const rel = relative(ROOT, resolve(path)); return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); };
122
123const hub = new EventHub();
124/** The chats, as files in the profile's data folder (chat-store.mjs). */
125const chatStore = createChatStore({ dir: store.DATA_DIR, privateDir: makePrivateDir });
126const modelProviders = createModelProviders({ directory: store.DATA_DIR, knownThinks: (connection, modelId) => visionProbe.knownThinks(connection, modelId), changed: value => hub.send('providers', withPictureAnswers(value)) });
127const imageModels = createImageModels({ dataDir: store.DATA_DIR, modelsDir: () => store.MODELS_DIR, real: models.REAL, changed: value => hub.send('image-models', value) });
128/* The installed app ships Strata Control (python + strata_control) next to the host; a source checkout has none and keeps its older paths. */
129const CONTROL = findControl();
130const control = createControl({ control: CONTROL });
131// Files a run as administrator made in Strata's own folders (owner Administrators) are given back to the user at every start; best effort, never blocks.
132if (control && process.platform === 'win32' && !process.env.STRATA_NO_REPAIR_ACCESS) void control.repairAccess().catch(() => {});
133/* Which window shows the page (the app window or, when that cannot run, a browser tab) and what only the app window can do: app-ui.mjs. */
134const appUi = createAppUi({ shutdown: () => shutdown() });
135/* The app's version has one source: the desktop shell passes it (STRATA_APP_VERSION, from apps/desktop/src-tauri/Cargo.toml). Outside the app it is read from the same file in a checkout, else 'dev'. */
136function appVersion() { return appVersionFrom({ env: process.env, here: HERE }); }
137const appUpdater = appUi.updater;
138const shellNotifier = createShellNotifier();
139/** What the page needs for the desktop settings: whether this is the desktop app, the port in use, the saved choices and a busy-port notice. */
140function shellState() {
141  const saved = readShellPrefs();
142  const desktop = !!shellNotifier;
143  return {
144    desktop,
145    tray: desktop && process.platform !== 'linux',
146    port: PORT, defaultPort: DEFAULT_PORT,
147    pinnedPort: saved.port || null, minimizeToTray: saved.tray,
148    portNotice: parsePortNotice(process.env.STRATA_PORT_NOTICE),
149  };
150}
151/* The engine that ships inside the installer is put in the components folder when this PC has none (or an older one); no network, hashes checked. The model list waits for it. */
152const bundledEngine = control && !process.env.STRATA_NO_BUNDLED_ENGINE
153  ? installBundledEngine({ bundleDir: process.env.STRATA_ENGINE_BUNDLE_DIR || resolve(HERE, '..', '..', 'engine-bundle'), components: componentsDirectory(), log: line => console.log(line) })
154  : Promise.resolve({ action: 'none' });
155const engineBundleDir = process.env.STRATA_ENGINE_BUNDLE_DIR || resolve(HERE, '..', '..', 'engine-bundle');
156/* An update from a per-GPU installer leaves its engine-bundle behind; it goes only when the same engine is complete in the store (sizes and hashes). */
157cleanupAfterInstall(bundledEngine, { bundleDir: engineBundleDir, components: componentsDirectory() });
158let bundledEngineSettled = !(control && !process.env.STRATA_NO_BUNDLED_ENGINE);
159bundledEngine.then(() => { bundledEngineSettled = true; }, () => { bundledEngineSettled = true; });
160/* A build made for another make of graphics card is not unpacked; Control's answer then carries the plain sentence (with the right download) instead of its own. */
161let bundledWrongMake = null;
162bundledEngine.then(result => { if (result?.action === 'wrong-make') { bundledWrongMake = result.notice; console.log(result.notice); } }, () => {});
163if (control) {
164  const engineOf = control.engine.bind(control);
165  control.engine = async (...args) => {
166    const answer = await engineOf(...args);
167    return answer && !answer.usable && bundledWrongMake ? { ...answer, notice: bundledWrongMake, wrongMake: true } : answer;
168  };
169}
170const native=createNativeControl({control,ready:bundledEngine,appUpdater,hardwareProbe:()=>(hardware.cachedHardware()?.gpus??[]).map((g,n)=>({index:g.index??n,vram_gb:g.vramGb})),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)});
171/* The agent: chats become DeepSeek Harness sessions when that component is installed. It is a separate
172   pinned component (STRATA_HARNESS_DIR), not part of this host, so its absence is a visible capability
173   state and the chat falls back to the direct path with a notice, never silently to another model. */
174// What the person chose in Settings -> Tools (tool groups, web search service and key, the browser, their own tools).
175const llmProxy = createLlmProxy({ targetOf: key => agent.llmTarget(key), samplingNow: () => samplingFromExpert(store.get().expert) });
176const agentTools = createAgentTools({ read: () => store.get().agentTools, write: value => store.update({ agentTools: value }), dataDir: store.DATA_DIR, browser: () => ({ ...findBrowser(), cli: findPlaywrightMcp(agent.harnessDir()) }) });
177agentTools.ensureFile();
178const visionProbe = createVisionProbe();
179/** The model APIs as the chat picker sees them: each model says whether it reads pictures (what the person ticked, else what the server answered). Unanswered models are asked in the background. */
180function withPictureAnswers(list) {
181  const secrets = new Map(modelProviders.withSecrets().map(c => [c.id, c]));
182  const connections = (list.connections ?? []).map(c => ({ ...c, models: c.models.map(m => {
183    const asked = visionProbe.known(c, m.id);
184    if ((m.vision == null || m.reasoning == null) && asked === undefined && c.protocol === 'openai-chat' && secrets.has(c.id)) void visionProbe.check(secrets.get(c.id), m.id).catch(() => {});
185    // Pictures are on unless the person or the server says no; a model that thinks says so too (OpenRouter's supported_parameters).
186    return { ...m, reads: readsPicturesByDefault(m, asked), thinks: m.reasoning ?? visionProbe.knownThinks(c, m.id) ?? null };
187  }) }));
188  return { ...list, connections };
189}
190/** Why a picture cannot go to this API model, in plain words and with the way to fix it; null when it can. */
191async function pictureRefusal(connection, model) {
192  if (!connection || !model) return 'This API model is no longer available. Choose another model in the chat picker.';
193  if (connection.protocol !== 'openai-chat') return `Pictures can only be sent to model APIs that use the OpenAI chat style. "${connection.name}" uses a different style, so the picture stays in the preview. Add the model through an OpenAI-compatible address (a /v1 address) to send pictures.`;
194  // Pictures are on by default: only an explicit no (the person's switch, or the server's own list) stops one.
195  if (readsPicturesByDefault(model, await visionProbe.check(connection, model.id))) return null;
196  const fix = `open Settings → Models, edit "${connection.name}" and turn on "Read pictures with this model"`;
197  return `"${model.name}" is set not to read pictures (or its server says it cannot: a llama-server started without --mmproj, or a text-only model). If that is wrong, ${fix}. Otherwise choose a model that reads pictures.`;
198}
199const agent = createAgentBridge({
200  tools: () => agentTools.profileView(),
201  skillsDir: () => AGENT_SKILLS,
202  onGoal: (chatId, goal) => hub.send('goal', { chatId, goal }),
203  // The person's Response settings (thinking budget, Expert sampling) reach the agent's model through this host's own forwarding endpoint.
204  proxyBase: `http://127.0.0.1:${PORT}/api/internal/agent-llm`,
205  expertSampling: () => samplingFromExpert(store.get().expert),
206  // How far a local engine has got (the 2 s /metrics poll), for the agent's stall watchdog: it moves while a long prompt is read.
207  engineProgress: instanceId => engineProgressMark(native.readyInstances().find(i => i.id === instanceId)),
208  onPlan: (chatId, event, plan) => hub.send('plan', { chatId, event, plan }),
209  onQueue: (chatId, queue) => hub.send('queue', { chatId, queue }),
210  dataDir: store.DATA_DIR,
211  componentsDir: componentsDirectory(),
212  // The installer ships the Harness next to the host (<install>/host/server -> <install>/harness).
213  bundledDir: resolve(HERE, '..', '..', 'harness'),
214  defaultLocalId: () => native.defaultInstanceId(),
215  localInstances: () => native.readyInstances().map(i => ({
216    id: i.id, label: i.label, baseUrl: `http://127.0.0.1:${i.port}/v1`, modelId: i.apiModelId,
217    context: i.metrics?.engine?.max_context ?? i.context ?? undefined, key: i.key, vision: i.vision,
218    // The engine's request slots: helper agents never outnumber them.
219    slots: i.metrics?.live?.slots?.length || i.parallel || 1,
220    // The tool servers set up for this model (Settings, Tools): the agent connects to the same ones.
221    mcpServers: i.mcpServers,
222  })),
223  connections: () => modelProviders.withSecrets().map(c => ({ ...c, models: c.models.map(m => ({ ...m, vision: readsPicturesByDefault(m, visionProbe.known(c, m.id)), reasoning: m.reasoning ?? visionProbe.knownThinks(c, m.id) ?? null })) })),
224  log: line => console.log(line),
225});
226let storageChanging = false;
227let modelOperations = 0;
228const requestQueue = new RequestQueue(n => monitor.queueWaiting(n));
229// The supervisor raises its own event names; surface them on the client stream.
230let runtimeModels;
231const rawSend = hub.send.bind(hub);
232hub.send = (event, payload) => {
233  if (event === 'engine-status') rawSend('engine-status', payload);
234  else if (event === 'engine-log') rawSend('log', payload);
235  else if(event==='models' && runtimeModels){
236    runtimeModels.adopt(payload.loaded,{beginner:store.get().beginner,expert:engine.params(),extra:store.get().configExtra??{}});
237    rawSend('runtime',runtimeModels.state());rawSend(event,runtimeModels.libraryState(payload));
238  } else rawSend(event, payload);
239};
240
241/* ------------------------------------------------------------------- boot --- */
242
243const boot = await hardware.detect({ force: true });
244models.init(hub);
245engine.init(hub);
246engineInstall.init(hub);
247monitor.init(hub, boot);
248monitor.setLiveProbe(() => native.hasLive());
249serving.init(hub, { port: PORT, host: HOST });
250runtimeModels=createRuntimeModels({hardware:()=>hardware.cachedHardware()??boot,library:()=>models.library(),requests:()=>serving.state().requests,real:models.REAL,changed:value=>{
251  if(!models.REAL){const primary=value.instances.find(i=>i.id===value.defaultId);if(store.get().loaded!==(primary?.variantId??null))store.update({loaded:primary?.variantId??null});}
252  rawSend('runtime',value);rawSend('models',runtimeModels.libraryState(models.library()));
253}});
254runtimeModels.adopt(models.library().loaded,{beginner:store.get().beginner,expert:engine.params(),extra:store.get().configExtra??{}});
255function runtimeState(){
256  if(models.REAL)runtimeModels.adopt(models.library().loaded,{beginner:store.get().beginner,expert:engine.params(),extra:store.get().configExtra??{}});
257  return runtimeModels.state();
258}
259
260/* No start-up load: the remembered model of the real-engine mode was loaded through a llama.cpp llama-server (0.2.14, also for an imported
261   GGUF nobody had loaded). Models run on the Strata engine, whose own start does not come through here. */
262const backend = await detectBackend({ force: true });
263
264console.log(`strata host  ·  http://${HOST}:${PORT}`);
265console.log(`hardware     ·  ${boot.accelerator.label} / ${boot.accelerator.backend} / ${boot.cpu.cores} cores / ${Math.round(boot.memory.totalGb)} GB`);
266const printInference = engine => console.log(`inference    ·  ${models.REAL ? inferenceLine({ backend, engine, settled: bundledEngineSettled }) : 'simulated (design iteration) — set STRATA_REAL_ENGINE=1 for a real engine'}`);
267if (models.REAL && control && backend.kind === 'unavailable' && bundledEngineSettled) void control.engine().catch(() => null).then(printInference);
268else printInference(null);
269console.log(`models dir   ·  ${store.MODELS_DIR}`);
270console.log(`workspace    ·  ${WORKSPACE}`);
271
272/* ------------------------------------------------------------------- data --- */
273
274function setupState() {
275  const s = store.get();
276  return {
277    complete: !!s.setup.complete,
278    dismissed: !!s.setup.dismissed,
279    choices: s.setup.choices ?? {},
280    step: s.setup.step ?? 1,
281    flowVersion: 2,
282    completedAt: s.setup.completedAt,
283    history: s.setup.history ?? [],
284    app: { version: appVersion(), modelsDir: store.MODELS_DIR, dataDir: store.DATA_DIR, modelsDirNotice: store.MODELS_DIR_NOTICE },
285  };
286}
287
288/** Skills written in the Skills page live here (one folder each, SKILL.md inside). */
289const CREATED_SKILLS = join(store.DATA_DIR, 'skills');
290/** What the agent scans: the whole current list, written out by syncAgentSkills (the Harness watches it, so no restart). */
291const AGENT_SKILLS = join(store.DATA_DIR, 'agent', 'skills-live');
292
293function skills() {
294  const bundled = [
295    {
296      id: 'commit-messages',
297      body: `Write the commit message for the staged change.
298
299Subject line: conventional commits, imperative mood, at most 72 characters.
300Body: one paragraph explaining why the change was made, not what changed —
301the diff already says what changed. Wrap at 72 columns.
302
303If the diff contains more than one unrelated change, say so instead of
304inventing a single narrative for it.`,
305      name: 'Commit messages',
306      description: 'Writes conventional-commit messages from a diff, with a scope line and a why-paragraph.',
307      source: 'bundled',
308      enabled: true,
309      triggers: ['commit', 'git message', 'stage these changes'],
310      sizeKb: 3.2,
311    },
312    {
313      id: 'code-review',
314      body: `Review the code that follows and report findings.
315
316Correctness first: wrong results, unhandled cases, races, resource leaks.
317Then security. Then clarity. Style last, and only where it hides a bug.
318
319For each finding give the line, what is wrong, and what would fix it. If the
320code is fine, say that plainly rather than inventing minor notes to seem
321useful. Never restate what the code does.`,
322      name: 'Code review',
323      description: 'Reviews a file or diff for correctness first, style second, and reports findings with line numbers.',
324      source: 'bundled',
325      enabled: true,
326      triggers: ['review this', 'find bugs', 'check my code'],
327      sizeKb: 5.6,
328    },
329    {
330      id: 'release-notes',
331      body: `Turn the merged commits into release notes a user would understand.
332
333Group by Feature, Fix, and Breaking change. Write for someone who uses the
334product, not someone who wrote it: no commit hashes, no internal file names,
335no "refactored X".
336
337Omit anything with no user-visible effect. If nothing user-visible shipped,
338say so in one line rather than padding.`,
339      name: 'Release notes',
340      description: 'Turns merged commits into user-facing release notes grouped by feature, fix and breaking change.',
341      source: 'bundled',
342      enabled: false,
343      triggers: ['release notes', 'changelog', 'what shipped'],
344      sizeKb: 2.8,
345    },
346    {
347      id: 'hardware-report',
348      body: `Explain what this machine can run, in plain language.
349
350Lead with the verdict: which model classes will run comfortably, which will be
351tight, which will not fit. Then the evidence — CPU, accelerator, memory — in
352that order of importance to the reader.
353
354Avoid jargon a non-technical person would not know: "unified memory", not
355"UMA"; "graphics memory", not "VRAM". Give sizes in GB and say what they mean
356for the choice being made.`,
357      name: 'Hardware report',
358      description: 'Explains what this machine can run, in plain language, from the detected CPU, GPU and memory.',
359      source: 'bundled',
360      enabled: true,
361      triggers: ['can this run', 'my hardware', 'how fast'],
362      sizeKb: 2.1,
363    },
364  ];
365
366  // Two places hold skills a person brought or wrote: the app's own folder (written in the Skills page) and the workspace's skills folder (added
367  // with "Add skill"). Both are plain `<name>/SKILL.md` folders; the frontmatter (name, description) is optional.
368  const extra = [];
369  for (const [dir, source, prefix] of [[CREATED_SKILLS, 'created', 'my-'], [join(WORKSPACE, 'skills'), 'workspace', 'ws-']]) {
370    if (!existsSync(dir) || !statSync(dir).isDirectory()) continue;
371    for (const name of readdirSync(dir)) {
372      const full = join(dir, name);
373      try { if (!statSync(full).isDirectory()) continue; } catch { continue; }
374      let text = '', sizeKb = 1;
375      const md = join(full, 'SKILL.md');
376      try { text = readFileSync(md, 'utf8'); sizeKb = Math.max(0.1, statSync(md).size / 1024); } catch { /* a folder with no SKILL.md is listed but has nothing to show */ }
377      const parsed = parseSkillFile(text);
378      extra.push({
379        id: `${prefix}${name}`,
380        name: parsed.title ?? name.replace(/-/g, ' ').replace(/^./, c => c.toUpperCase()),
381        description: parsed.description ?? (source === 'created' ? 'A skill you wrote.' : `Workspace skill loaded from ${name}/SKILL.md`),
382        source,
383        enabled: true,
384        triggers: [name.replace(/-/g, ' ')],
385        body: parsed.body,
386        sizeKb: Number(sizeKb.toFixed(1)),
387      });
388    }
389  }
390  return [...bundled, ...extra].map(s => ({ ...s, ...store.get().skillEdits?.[s.id] }));
391}
392
393let skillState = skills().map((s) => ({
394  ...s,
395  // `enabled` is the standing answer; `onlyIn` narrows it to one workspace.
396  // A skill written for one project is noise in another, and a plain on/off
397  // switch cannot express "here but not there".
398  enabled: store.get().skillPreferences?.[s.id]?.enabled ?? s.enabled,
399  onlyIn: store.get().skillPreferences?.[s.id]?.onlyIn ?? null,
400  useCount: 0,
401  lastUsedAt: null,
402}));
403
404/**
405 * Write the skills the agent may use into its folder. A skill narrowed to one workspace is left out (the agent has no such scope), a skill
406 * switched off is written as hidden. Called after every change to the list.
407 */
408function syncAgentSkills() {
409  try { materializeSkills(AGENT_SKILLS, skillState.filter(s => !s.onlyIn)); } catch (e) { console.warn('skills · could not write the agent skills folder:', e.message); }
410}
411syncAgentSkills();
412
413/** Whether a skill applies, given where the reader is. */
414/**
415 * Records which enabled skills a prompt actually triggered.
416 *
417 * The triggers were decorative: nothing consulted them, so a skill's list was a
418 * claim the product could not back up. Matching them here is what makes "used in
419 * N conversations" possible rather than invented.
420 */
421function noteSkillUse(selected) {
422  const hit = new Set(selected.map(s => s.id));
423  skillState = skillState.map((s) => {
424    if (!hit.has(s.id)) return s;
425    return { ...s, useCount: (s.useCount ?? 0) + 1, lastUsedAt: new Date().toISOString() };
426  });
427  if (hit.size) hub.send('skills', skillState);
428}
429
430const execFileAsync = promisify(execFile);
431
432/* ---------------------------------------------------------------- prompt ---
433   What Strata puts in front of every conversation. Counted so the context
434   breakdown can show where the window actually goes rather than reporting a
435   single opaque total. */
436const SYSTEM_PROMPT = `You are Strata, a local inference assistant running entirely on this computer.
437Answer plainly and briefly. Use only tools actually offered to you. Ask for file content when no file tool is available.
438Say when you do not know. Never claim to have done something you have not done.`;
439
440/**
441 * Files a tool proposal could plausibly name.
442 *
443 * Scanned from the workspace so the demo proposes something that exists — it
444 * used to name `README.md` unconditionally, including on machines with none.
445 */
446function readableCandidates(root = WORKSPACE, depth = 3) {
447  const out = [];
448  const walk = (dir, at) => {
449    if (at > depth || out.length > 60) return;
450    let entries;
451    try {
452      entries = readdirSync(dir, { withFileTypes: true });
453    } catch {
454      return;
455    }
456    for (const e of entries) {
457      if (out.length > 60) return;
458      if (e.name.startsWith('.') || e.name === 'node_modules') continue;
459      const full = join(dir, e.name);
460      const rel = full.slice(root.length + 1);
461      if (e.isDirectory()) walk(full, at + 1);
462      else if (/\.(md|txt|json|ts|tsx|mjs|js|css)$/.test(e.name)) out.push(rel);
463    }
464  };
465  walk(root, 0);
466  return out;
467}
468
469/* ------------------------------------------------------------- workspaces ---
470   The host used to expose exactly one root, taken from the environment. A
471   sidebar that offers "add a workspace" over a single-root host would be a lie,
472   so the roots are now a small persisted registry. The original root is always
473   first and cannot be removed, which keeps existing sessions and file paths
474   valid. */
475const WORKSPACES_FILE = join(store.DATA_DIR, 'workspaces.json');
476
477function loadWorkspaces() {
478  try {
479    const parsed = JSON.parse(readFileSync(WORKSPACES_FILE, 'utf8'));
480    if (Array.isArray(parsed) && parsed.length) {
481      // An earlier version saved the app's own folder as the first workspace. The first entry keeps its id (chats point at it) and moves to the default folder.
482      if (parsed[0]?.id === 'root' && typeof parsed[0].path === 'string' && insideApp(parsed[0].path)) parsed[0] = { ...parsed[0], aliases: [...new Set([...(parsed[0].aliases ?? []), parsed[0].path])], path: WORKSPACE, name: WORKSPACE_NAME };
483      return parsed;
484    }
485  } catch {
486    /* first run */
487  }
488  return [{ id: 'root', name: WORKSPACE_NAME, path: WORKSPACE }];
489}
490
491let workspaces = loadWorkspaces();
492/* The folder each chat works in ("Select a folder"): the agent's working folder and sandbox for that chat. */
493const chatAttachments = createAttachments();
494const nativeDrops = createNativeDrops();
495const uploads = createUploads({ dir: join(store.DATA_DIR, 'uploads'), folderOf: chatId => chatRoot(chatId), attachments: chatAttachments });
496try { uploads.sweep(); } catch { /* best effort */ }
497const chatFolders = createChatFolders({ file: join(store.DATA_DIR, 'chat-folders.json') });
498/** Where a chat's files are: its chosen folder, else the folder its agent worked in, else the default workspace (chat-files.mjs). One source for every file route. */
499const chatRoot = chatId => chatRootOf({ chosen: chatFolders.get(chatId), used: agent.workingFolder?.(chatId), fallback: workspaces[0]?.path ?? WORKSPACE });
500
501function saveWorkspaces() {
502  try {
503    mkdirSync(store.DATA_DIR, { recursive: true });
504    writeFileSync(WORKSPACES_FILE, JSON.stringify(workspaces, null, 2));
505  } catch (err) {
506    console.warn('workspaces · could not persist', err.message);
507  }
508}
509
510const SKIP_DIRS = new Set(['node_modules', '.git', '.npm-cache', '.strata', '.shots', 'dist', '.vite', '__pycache__', '.cache']);
511
512function workspaceListing(root = WORKSPACE) {
513  const entries = [];
514  const walk = (dir, prefix = '', depth = 0) => {
515    if (depth > 2) return;
516    let names = [];
517    try {
518      names = readdirSync(dir);
519    } catch {
520      return;
521    }
522    for (const name of names.slice(0, 60)) {
523      if (SKIP_DIRS.has(name) || name.startsWith('.DS')) continue;
524      const full = join(dir, name);
525      let st;
526      try {
527        st = statSync(full);
528      } catch {
529        continue;
530      }
531      const rel = prefix ? `${prefix}/${name}` : name;
532      if (st.isDirectory()) {
533        entries.push({ path: rel, kind: 'dir' });
534        walk(full, rel, depth + 1);
535      } else {
536        entries.push({ path: rel, kind: 'file', sizeKb: st.size / 1024, updatedAt: st.mtime.toISOString() });
537      }
538    }
539  };
540  walk(root);
541  entries.sort((a, b) =>
542    a.kind === b.kind ? a.path.localeCompare(b.path) : a.kind === 'dir' ? -1 : 1,
543  );
544  return { path: root, entries };
545}
546
547/* ----------------------------------------------------------------- chat io --- */
548
549function clientName(req) {
550  const ua = req.headers['user-agent'] ?? '';
551  const header = req.headers['x-strata-client'];
552  if (typeof header === 'string' && header) return header;
553  if (/curl/i.test(ua)) return 'curl';
554  if (/python|httpx|requests/i.test(ua)) return 'Python client';
555  if (/node|undici|axios/i.test(ua)) return 'Node client';
556  if (/strata/i.test(ua)) return 'Strata chat';
557  return 'Local client';
558}
559
560async function runRemoteTurn({ selection, message, history, images = [], thinking, onFrame, signal, workspaceId }) {
561  const controller = new AbortController();
562  const requestSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
563  let entry;
564  const started = Date.now();
565  try {
566    const { connection, model } = modelProviders.resolve(selection);
567    if (connection.protocol === 'openai-chat' && model.reasoning == null) await visionProbe.check(connection, model.id);
568    const appliedSkills = selectSkills(skillState, message, workspaceId);
569    entry = serving.open({ client: 'Strata chat', endpoint: connection.protocol === 'anthropic' ? '/messages' : connection.protocol === 'openai-responses' ? '/responses' : '/chat/completions', model: `${connection.name} · ${model.name}`, cancel: () => controller.abort(new DOMException('Cancelled by the user', 'AbortError')) });
570    serving.mark(entry.id, { state: 'generating' });
571    const result = await modelProviders.stream({ selection, message, history, images, thinking, signal: requestSignal, systemPrompt: ['You are Strata, a helpful assistant. Answer clearly. Do not claim to have read files or performed actions unless their results are included in the conversation.', skillInstructions(appliedSkills)].filter(Boolean).join('\n\n'), onFrame: frame => {
572      if (frame.type === 'start') noteSkillUse(appliedSkills);
573      if (frame.type === 'done') serving.mark(entry.id, { tokensIn: frame.tokensIn, tokensOut: frame.tokensOut, usageSource: frame.usageSource });
574      onFrame({ ...frame, requestId: entry.id, model: model.name, contextMax: model.contextMax, remoteModel: true, ...(frame.type === 'start' ? { skills: appliedSkills.map(s => s.name) } : {}) });
575    } });
576    serving.mark(entry.id,{tps:result.tps??null});
577    serving.finish(entry.id, { tokensOut: result.tokensOut, durationMs: Date.now() - started });
578    return result;
579  } catch (err) {
580    const refusedPicture = images.length && /HTTP [45]\d\d/.test(String(err.message)) ? ' If this model does not read pictures, turn off "Read pictures with this model" in Settings → Models (edit this connection), or choose a model that does.' : '';
581    const message = requestSignal.aborted ? 'Request cancelled. Partial output is preserved.' : err.name === 'TimeoutError' ? 'The model API timed out. Try again.' : err.message + refusedPicture;
582    if (entry) serving.finish(entry.id, { durationMs: Date.now() - started, error: message });
583    onFrame({ type: 'error', message, requestId: entry?.id });
584    return { error: message };
585  }
586}
587
588/** One agent turn for a chat, streamed to the caller as the NDJSON frames the chat already renders. */
589async function runAgentTurn({ res, controller, chatId, body, message, workspaceId, images = [] }) {
590  const write = frame => { if (!res.writableEnded && !res.destroyed) res.write(`${JSON.stringify(frame)}\n`); };
591  const cwd = chatFolders.get(chatId) ?? (workspaceId ? workspaces.find(w => w.id === workspaceId)?.path : null) ?? WORKSPACE;
592  let choice, instance = null;
593  if (body.remoteModel) {
594    choice = { connectionId: String(body.remoteModel.connectionId), modelId: String(body.remoteModel.modelId) };
595    // Does this server read pictures? Asked before the agent is built, so a picture is never sent to one that cannot.
596    const own = modelProviders.withSecrets().find(c => c.id === choice.connectionId);
597    if (own && own.protocol === 'openai-chat') await visionProbe.check(own, choice.modelId);
598  }
599  else {
600    try { instance = native.resolveInstance(body.nativeModelId ?? native.state().defaultId); }
601    catch (e) { write({ type: 'error', message: plainNoModel(e.message) }); return; }
602    choice = { instanceId: instance.id };
603  }
604  const started = Date.now();
605  // A turn the engine is serving must be visible to the rest of the host (Serving, unload guards).
606  const entry = instance ? serving.open({ client: 'Strata chat', endpoint: '/agent', model: instance.apiModelId, instanceId: instance.id, gpuIds: instance.gpus.map(String), cancel: () => { void agent.stop(chatId); } }) : null;
607  if (entry) serving.mark(entry.id, { state: 'generating' });
608  const settle = (tokensOut, error) => { if (entry) serving.finish(entry.id, { tokensOut, durationMs: Date.now() - started, ...(error ? { error } : {}) }); };
609  try {
610    // "/goal ..." is the Harness's goal command (set, show, pause, resume, clear); everything else is a message.
611    const attached = chatAttachments.take(chatId);
612    if (attached.length && !/^\//.test(message.trim())) message = withAttachments(message, attached);
613    const goalLine = /^\/goal(?:\s+([\s\S]*))?$/i.exec(message.trim());
614    const planLine = /^\/plan(?:\s+([\s\S]*))?$/i.exec(message.trim());
615    const researchLine = /^\/research(?:\s+([\s\S]*))?$/i.exec(message.trim());
616    // "/compact" summarises the older messages of this chat now (it used to go to the model as text, which answered it as a question).
617    const compactLine = /^\/compact\s*$/i.test(message.trim());
618    const turnOptions = { chatId, message, workspacePath: cwd, choice, images, mode: typeof body.mode === 'string' ? body.mode : null, thinking: typeof body.thinking === 'string' ? body.thinking : null, thinkingBudget: Number.isFinite(body.thinkingBudget) ? body.thinkingBudget : 0, history: Array.isArray(body.history) ? body.history : [], onFrame: write, signal: controller.signal };
619    const result = typeof body.planId === 'string' && body.message === '/plan start' ? await agent.planGoal({ ...turnOptions, planId: body.planId })
620      : compactLine ? await agent.compactCommand(turnOptions)
621      : researchLine ? await agent.researchCommand({ ...turnOptions, line: researchLine[1] ?? '' })
622      : planLine ? await agent.planCommand({ ...turnOptions, line: planLine[1] ?? '' })
623      : goalLine ? await agent.goalCommand({ ...turnOptions, line: goalLine[1] ?? '' }) : await agent.runTurn(turnOptions);
624    if (result?.detached) void result.ended.then(r => settle(r?.tokensOut ?? null), () => settle(null));
625    else settle(result?.tokensOut ?? null, result?.error ? 'The agent turn failed.' : undefined);
626  } catch (err) {
627    const plain = plainTurnFailure(err);
628    write({ type: 'error', message: plain.message, ...(plain.details ? { details: plain.details } : {}), code: plain.code });
629    settle(null, plain.message);
630  }
631}
632
633async function runTurn({ message, history = [], onFrame, signal, client, workspaceId = null, sessionId = null, remoteModel = null, runtimeModelId = undefined, nativeModelId, images=[], useTools=false, thinking='medium', thinkingBudget=0 }) {
634  if (remoteModel) return runRemoteTurn({ selection: remoteModel, message, history, images, thinking, onFrame, signal, workspaceId });
635  if(native.hasLive()||nativeModelId){
636    let instance;try{instance=native.resolveInstance(nativeModelId??native.state().defaultId);}catch(e){const message=plainNoModel(e.message);onFrame({type:'error',message});return {error:message};}const started=Date.now(),cancel=new AbortController();
637    const entry=serving.open({client:client??'Strata chat',endpoint:'/chat/completions',model:instance.apiModelId,instanceId:instance.id,gpuIds:instance.gpus.map(String),cancel:()=>cancel.abort()});
638    try{serving.mark(entry.id,{state:'generating'});const applied=selectSkills(skillState,message,workspaceId);const result=await proxyCompletion({baseUrl:`http://127.0.0.1:${instance.port}/v1`,modelId:instance.apiModelId,authorization:instance.key,message,history,images,extra:{strata_mcp:useTools===true,...(thinkingBudget>0&&String(thinking).toLowerCase()!=='off'?{reasoning_budget_tokens:thinkingBudget}:{}),reasoning_effort:({off:'none',max:'high'}[String(thinking).toLowerCase()]??String(thinking).toLowerCase())},systemPrompt:[SYSTEM_PROMPT,skillInstructions(applied)].filter(Boolean).join('\n\n'),signal:signal?AbortSignal.any([signal,cancel.signal]):cancel.signal,onFrame:frame=>onFrame({...frame,requestId:entry.id,model:instance.label,contextMax:instance.metrics?.engine?.max_context??instance.context,skills:applied.map(s=>s.name)})});serving.mark(entry.id,{...result,usageSource:result.usageSource});serving.finish(entry.id,{tokensOut:result.tokensOut,durationMs:Date.now()-started});return result;}catch(e){serving.finish(entry.id,{durationMs:Date.now()-started,error:e.message});onFrame({type:'error',message:e.message,requestId:entry.id});return {error:e.message};}
639  }
640  runtimeState();
641  let instance;
642  try{instance=runtimeModels.resolve(runtimeModelId,{chatDefault:runtimeModelId===undefined});}
643  catch(err){onFrame({type:'error',message:err.message});return {error:err.message};}
644  const v = variant(instance.variantId);
645
646  if (!v) {
647    onFrame({ type: 'error', message: 'No model is loaded. Pick one in Models, then try again.' });
648    return;
649  }
650
651  const controller = new AbortController();
652  const requestSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
653  const entry = serving.open({ client: client ?? 'Strata chat', endpoint: '/chat/completions', model: instance.apiModelId, instanceId:instance.id, gpuIds:instance.gpuIds, cancel: () => controller.abort(new DOMException('Cancelled by the user', 'AbortError')) });
654  const started = Date.now();
655  let result = { tokensIn: null, tokensOut: null };
656  // Time to first token: the gap between asking and the first token arriving.
657  let firstTokenMs = null;
658
659  try {
660    onFrame({ type: 'queued', requestId: entry.id });
661    await (models.REAL?requestQueue:runtimeModels.queue(instance.id)).run(requestSignal, async () => {
662      requestSignal.throwIfAborted();
663      if(!runtimeModels.state().instances.some(i=>i.id===instance.id))throw new Error('This model was unloaded before dispatch.');
664      runtimeModels.update(instance.id,{phase:'reading'});
665      // Scope is resolved again at dispatch: a disabled skill never stays active
666      // merely because the request waited in the queue.
667      const appliedSkills = selectSkills(skillState, message, workspaceId);
668      const systemPrompt = [SYSTEM_PROMPT, skillInstructions(appliedSkills)].filter(Boolean).join('\n\n');
669      serving.mark(entry.id, { state: 'generating' });
670      const contextMax = instance.memory.context;
671      const modelMonitor=models.REAL?monitor:{
672        progressOutput:()=>{},
673        beginReading:(total)=>runtimeModels.update(instance.id,{phase:'reading',prompt:{done:0,total,pct:0}}),
674        progressReading:(done)=>{const total=runtimeModels.state().instances.find(i=>i.id===instance.id)?.prompt.total??0;runtimeModels.update(instance.id,{prompt:{done,total,pct:total?done/total*100:0}});},
675        beginGenerating:()=>runtimeModels.update(instance.id,{phase:'generating'}),
676        beginThinking:()=>runtimeModels.update(instance.id,{phase:'thinking'}),
677      };
678      try {
679        result = await streamChat({
680          message,
681          history,
682          systemPrompt,
683          modelLabel: v.label,
684          candidates: readableCandidates(),
685          onFrame: (frame) => {
686            if(frame.type==='stats'||frame.type==='done')modelMonitor.progressOutput(frame.tokensOut);
687            // Time to first *token*. A `tool` frame is a proposal, not generated
688            // output, and it arrives before the prompt is even read — counting it
689            // reported a 0ms first token. The stream emits `delta` for both
690            // reasoning and content; the real-engine path also reports ttftMs
691            // itself on the done frame.
692            if (firstTokenMs === null && (frame.type === 'delta' || frame.type === 'reasoning')) {
693              firstTokenMs = Date.now() - started;
694            }
695            if (frame.type === 'done' && typeof frame.ttftMs === 'number') firstTokenMs = frame.ttftMs;
696            if (frame.type === 'start') {
697              // Demo responses cannot demonstrate that instructions affected a model.
698              if (!frame.demo) noteSkillUse(appliedSkills);
699              serving.mark(entry.id, { tokensIn: frame.promptTokens ?? null, usageSource: frame.demo ? 'demo' : 'unavailable' });
700            }
701            if (frame.type === 'done') {
702              serving.mark(entry.id, { tokensIn: frame.tokensIn, tokensOut: frame.tokensOut, usageSource: frame.usageSource });
703            }
704            onFrame({ ...frame, ...(frame.type==='done'?{ttftMs:firstTokenMs}:{}), requestId: entry.id, model: v.label, contextMax, ...(frame.type === 'start' ? { skills: frame.demo ? [] : appliedSkills.map(s => s.name) } : {}) });
705          },
706          signal: requestSignal,
707          engine: {
708            variantId: v.id,
709            beginReading: (tokens, id) => modelMonitor.beginReading(tokens, id),
710            progressReading: (done) => modelMonitor.progressReading(done),
711            beginGenerating: () => modelMonitor.beginGenerating(),
712            beginThinking: () => modelMonitor.beginThinking(),
713          },
714        });
715        requestSignal.throwIfAborted();
716        serving.mark(entry.id,{cachedTokens:result.cachedTokens??null,tps:result.tps??null,promptTps:result.promptTps??null,hitRate:result.hitRate??null,pcieShare:result.pcieShare??null,finishReason:result.finishReason??null});
717        serving.finish(entry.id, {
718          tokensOut: result.tokensOut,
719          durationMs: Date.now() - started,
720        });
721        runtimeModels.update(instance.id,{phase:'idle',outputTps:result.tps??0,promptTps:result.promptTps??0,context:{usedTokens:(result.tokensIn??0)+(result.tokensOut??0),maxTokens:contextMax,pct:((result.tokensIn??0)+(result.tokensOut??0))/contextMax*100}});
722        if(models.REAL)monitor.record({
723          tokensIn: result.tokensIn,
724          tokensOut: result.tokensOut,
725          durationMs: Date.now() - started,
726          ttftMs: firstTokenMs ?? undefined,
727          cachedTokens: result.cachedTokens,
728          tps: result.tps,
729          usageSource: result.usageSource,
730        });
731        if(models.REAL){monitor.setRecordedContext({ ...result, requestId: entry.id, sessionId });monitor.idle();}
732      } catch (error) {
733        runtimeModels.update(instance.id,{phase:'idle'});
734        if(models.REAL)monitor.idle(requestSignal.aborted ? 'Request cancelled' : 'Last request failed');
735        throw error;
736      }
737    });
738    return result;
739  } catch (err) {
740    const message = requestSignal.aborted ? 'Request cancelled. Partial output is preserved.' : err.message;
741    serving.finish(entry.id, { durationMs: Date.now() - started, error: message });
742    onFrame({ type: 'error', message, requestId: entry.id });
743    return { error: message };
744  }
745}
746
747// `HERE` is apps/host/server, so the repository root is three levels up (server -> host -> apps).
748const REPO_ROOT = CONTROL ? CONTROL.dir : resolve(HERE, '..', '..', '..');
749// The interpreter that drives the job is the same one the launcher would pick, named explicitly so
750// a packaged run uses the runtime the bundle carries rather than whatever `python3` resolves to.
751const PYTHON = resolvePython({ repo: REPO_ROOT, control: CONTROL });
752const TS_PYTHON = PYTHON.command;
753const REVISE_SCRIPT = resolve(REPO_ROOT, 'integrations', 'harness', 'revise_once.py');
754// A revision attempt is an agent turn, performed by the Harness through the pinned integration
755// script — which is a *Python* program, so it is invoked with the interpreter, not with Node.
756// This is a configured path, never a value an HTTP caller supplies: accepting one would hand a
757// remote caller command execution on the user's machine.
758// The default revision step is the app's own assistant (server/timeskip-revise.mjs, run by Node), not the Harness's Python bridge, which
759// needs a Harness build next to the checkout that the installed app does not have.
760const REVISE_NODE_SCRIPT = resolve(HERE, 'timeskip-revise.mjs');
761const TIMESKIP_REVISE = process.env.STRATA_TIMESKIP_REVISE
762  ?? `"${process.execPath}" "${REVISE_NODE_SCRIPT}"`;
763/** Proves a revision request comes from a job this host started, not from some other program on this PC. */
764const INTERNAL_SECRET = randomBytes(24).toString('hex');
765/** The model a trial runs on, by run id: the chat's saved API model when it uses one, else the loaded local model. */
766const timeskipChoices = new Map();
767/** Trials this host is driving: run id -> { chatId (the chat that asked), turnChat (the assistant's own chat id), controller, step (the assistant's current status), lastSent }. */
768const trials = new Map();
769const trialByChat = new Map();
770/** What the job is doing, in the person's words, from its phase and the assistant's own current step (notes-split-agent3.md). */
771function trialActivity(run) {
772  const trial = trials.get(run.id);
773  switch (run.phase) {
774    case 'queued': case 'checkpointing': return { code: 'reading-files', text: 'Reading your files…' };
775    case 'generating': return { code: 'trying-version', text: 'Trying an improved version…', ...(trial?.step ? { args: { step: trial.step.text, stepCode: trial.step.code, ...(trial.step.args ? { stepArgs: trial.step.args } : {}) } } : {}) };
776    case 'checking': return { code: 'checking-result', text: 'Checking the result…' };
777    case 'decision': return { code: 'comparing', text: 'Comparing the two versions…' };
778    default: return null;
779  }
780}
781/** Tell the page when the job's phase or the assistant's step changed (SSE `timeskip`), at most every 2 s. */
782function watchTrial(id) {
783  const trial = trials.get(id);
784  if (!trial) return;
785  const timer = setInterval(() => {
786    const run = timeskip.status(id);
787    if (!run) { clearInterval(timer); return; }
788    const activity = trialActivity(run);
789    const key = JSON.stringify([run.phase, activity]);
790    if (key !== trial.lastSent) { trial.lastSent = key; hub.send('timeskip', { id, phase: run.phase, activity }); }
791    if (['completed', 'cancelled', 'failed', 'interrupted'].includes(run.phase)) { clearInterval(timer); trials.delete(id); if (trial.chatId) trialByChat.delete(trial.chatId); }
792  }, 2000);
793  timer.unref?.();
794  trial.timer = timer;
795}
796/** Stop a trial the person stopped: the assistant's turn, the job and its processes, and the copies. */
797async function stopTrial(id) {
798  const trial = trials.get(id);
799  if (trial) { trial.controller?.abort(); if (trial.turnChat) void agent.stop(trial.turnChat).catch(() => {}); }
800  const stopped = await timeskip.stop(id);
801  if (trial) { clearInterval(trial.timer); trials.delete(id); if (trial.chatId) trialByChat.delete(trial.chatId); }
802  if (stopped) hub.send('timeskip', { id, phase: 'cancelled', activity: null });
803  return stopped;
804}
805/**
806 * Tuning, from the App Host.
807 *
808 * The job contract is Strata Control's (`strata_control/tuning.py`) and is driven through
809 * `strata tune`. Two things the UI needs and neither is computable here:
810 *
811 *   * **what a sweep would search, and why the rest was excluded** — that depends on the selected
812 *     engine binary's own flag list, so it is asked of the CLI rather than guessed;
813 *   * **recorded jobs and their reports** — read from the job's durable `job.json`.
814 *
815 * There is deliberately no "run a sweep" route yet. A sweep needs a measurement harness that boots
816 * the engine with each candidate, and inventing measurements is exactly what the handoff forbids.
817 * The plan and the report are real; the sweep is gated on that harness.
818 */
819function createTuning({ repoRoot, python, pythonArgs = [], env = process.env } = {}) {
820  const cli = join(repoRoot, 'strata.py');
821  const stateDir = () => tuningDir(env);
822
823  function runCli(args) {
824    return new Promise((resolve) => {
825      const child = spawn(python, [...pythonArgs, cli, ...args, '--output', 'json'], {
826        cwd: repoRoot, windowsHide: true, env: { ...env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8', STRATA_TUNE_DIR: stateDir() },
827        stdio: ['ignore', 'pipe', 'pipe'],
828      });
829      let out = '', err = '';
830      child.stdout.on('data', (b) => { out += b.toString(); });
831      child.stderr.on('data', (b) => { err += b.toString(); });
832      child.on('error', (e) => resolve({ ok: false, error: e.message }));
833      child.on('close', (code) => {
834        let parsed = null;
835        try { parsed = JSON.parse(out.trim().split('\n').filter(Boolean).pop() ?? ''); } catch { parsed = null; }
836        if (!parsed) return resolve({ ok: false, code, error: err.trim() || out.trim() || `exit ${code}` });
837        resolve({ ok: Boolean(parsed.ok), code, envelope: parsed });
838      });
839    });
840  }
841
842  return {
843    stateDir,
844    /** The reviewable plan for one backend/engine pair. */
845    async plan({ engine, backend, model, objective = 'generation', trials = 16, repeats = 3 }) {
846      if (!engine || !backend) return { ok: false, code: 2, error: 'engine and backend are required' };
847      const r = await runCli(['tune', 'plan', '--engine', engine, '--backend', backend,
848        '--model', model ?? 'unknown', '--objective', objective,
849        '--trials', String(Math.max(0, Math.min(512, Number(trials) || 16))),
850        '--repeats', String(Math.max(1, Math.min(10, Number(repeats) || 3)))]);
851      return r.ok ? { ok: true, plan: r.envelope.plan } : { ok: false, code: r.code, error: r.error };
852    },
853    /** Recorded jobs, newest state only: the durable record is the authority. */
854    jobs() {
855      const root = stateDir();
856      if (!existsSync(root)) return [];
857      const out = [];
858      for (const entry of readdirSync(root, { withFileTypes: true })) {
859        if (!entry.isDirectory()) continue;
860        const file = join(root, entry.name, 'job.json');
861        if (!existsSync(file)) continue;
862        try {
863          const data = JSON.parse(readFileSync(file, 'utf8'));
864          out.push({
865            id: data.id, state: data.state,
866            backend: data.plan?.backend ?? null, objective: data.plan?.objective ?? null,
867            trials: data.report?.trials_run ?? null,
868            recommendation: data.report?.recommendation_available === true,
869            reason: data.report?.reason ?? null,
870            startedAt: data.started_at ?? null, finishedAt: data.finished_at ?? null,
871          });
872        } catch {
873          // A partially written record is skipped rather than reported as an empty job.
874        }
875      }
876      return out;
877    },
878    job(id) {
879      if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return null;
880      const file = join(stateDir(), id, 'job.json');
881      if (!existsSync(file)) return null;
882      try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; }
883    },
884  };
885}
886
887const tuning = createTuning({ repoRoot: REPO_ROOT, python: TS_PYTHON, pythonArgs: PYTHON.args });
888
889/* Time-skip: plan, lever, A all the way, B forked at the lever (notes-split-agent8.md). The older revise-the-draft job above stays reachable with legacy:true. */
890const forkTs = createForkTimeskip({ agent, dir: join(store.DATA_DIR, 'timeskip-fork'), notify: (type, data) => hub.send(type, data) });
891const timeskip = createTimeSkip({
892  repoRoot: REPO_ROOT,
893  python: TS_PYTHON,
894  pythonArgs: PYTHON.args,
895  env: { ...process.env, STRATA_TIMESKIP_DIR: process.env.STRATA_TIMESKIP_DIR ?? '' },
896});
897
898const runAgentTask = createAgentTaskRunner({
899  agent, workspace: WORKSPACE,
900  // The loaded local model. (STRATA_TASK_REMOTE_MODEL="<connection id>:<model id>" lets a developer or an API-only setup name a saved API model instead.)
901  choice: () => {
902    try { return { instanceId: native.resolveInstance(native.state().defaultId).id }; } catch { /* no local model is ready */ }
903    const [connectionId, ...rest] = String(process.env.STRATA_TASK_REMOTE_MODEL ?? '').split(':');
904    return connectionId && rest.length ? { connectionId, modelId: rest.join(':') } : null;
905  },
906});
907const tasks = createTaskService({
908  read: () => store.get().tasks ?? [],
909  write: records => store.update({ tasks: records }),
910  notify: task => hub.send('task', { id: task.id, title: task.title, status: task.status, attention: task.attention ?? null, error: task.error ?? null }),
911  run: async (task, signal) => {
912    if (agent.status().state !== 'unavailable') { const agentResult = await runAgentTask(task, signal); if (agentResult) return agentResult; }
913    let text = '', failure = null, demo = !models.REAL;
914    await runTurn({ message: task.prompt, signal, client: `Task: ${task.title}`, onFrame: frame => {
915      if (frame.type === 'delta') text += frame.text ?? '';
916      if (frame.type === 'start') demo = !!frame.demo;
917      if (frame.type === 'error') failure = frame.message;
918    }});
919    if (failure) throw new Error(failure);
920    signal.throwIfAborted();
921    if (!text) throw new Error('The model returned no answer.');
922    return { text, demo };
923  },
924});
925const taskTimer = setInterval(() => tasks.tick(), 15000);
926taskTimer.unref();
927
928// The share and tunnel listeners take a free port (the next ones above the host's own) instead of a fixed PORT+1 / PORT+2 that Docker, WSL or Hyper-V may hold or reserve.
929// The probe listens on the loopback address only: a probe on 0.0.0.0 made Windows Defender Firewall ask "Allow Node.js to communicate on these networks?" on the
930// first start of every new install path (QA 0213). Reserved or taken ports are caught on any address; the share listener itself binds 0.0.0.0 only when the person turns sharing on.
931const sharePort = await findFreePort(Number(process.env.STRATA_SHARE_PORT ?? PORT + 1), '127.0.0.1', { skip: [PORT] });
932const localShare = createLocalShare({ handle: openai, hasKey: () => !!store.get().serving?.apiKey, port: sharePort, changed: () => serving.setSharing(localShare.state()) });
933const tunnelPort = await findFreePort(Number(process.env.STRATA_TUNNEL_PORT ?? PORT + 2), '127.0.0.1', { skip: [PORT, sharePort] });
934const tunnelOrigin = createLocalShare({ handle: openai, hasKey: () => !!store.get().serving?.apiKey, host: '127.0.0.1', port: tunnelPort });
935const connector = createConnectorInstaller({ directory: join(store.HOME, 'engine', 'cloudflare'), componentDirectory: join(componentsDirectory(), 'cloudflared') });
936const 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, connectorInfo: connector.connector, findRunning: findRunningConnector });
937await cloudflare.inspect();
938
939/* --------------------------------------------------------------- routing --- */
940
941const server = http.createServer(async (req, res) => {
942  const url = requestUrl(req);
943  if (!url) return badRequest(res);   // #4397: a bad Host or request target is a 400, never an unhandled rejection
944  const path = url.pathname;
945  const method = req.method ?? 'GET';
946
947  res.setHeader('access-control-allow-origin', '*');
948  res.setHeader('access-control-allow-headers', 'content-type, authorization, x-api-key, x-strata-client');
949  res.setHeader('access-control-allow-methods', 'GET, POST, PATCH, DELETE, OPTIONS');
950  if (method === 'OPTIONS') {
951    res.writeHead(204);
952    res.end();
953    return;
954  }
955
956  try {
957    if (path.startsWith('/api/') && req.headers.origin) {
958      const origin = new URL(req.headers.origin);
959      if (!['localhost', '127.0.0.1', '[::1]'].includes(origin.hostname)) return error(res, 403, 'Open the local Strata app to use host controls.');
960    }
961    if (path.startsWith('/api/')) {
962      const modelOperation = !['GET', 'OPTIONS'].includes(method) && /^\/api\/(models|local-models|runtime|image-models|engine|native)(\/|$)/.test(path) && !['/api/runtime/plan', '/api/engine/validate', '/api/local-models/inspect'].includes(path);
963      if (modelOperation) modelOperations++;
964      try { return await api(req, res, path, method, url); }
965      finally { if (modelOperation) modelOperations--; }
966    }
967    if (path.startsWith('/v1/')) {
968      if (storageChanging && method !== 'GET') return error(res, 409, 'Wait for the model folder check to finish.');
969      return await openai(req, res, apiPath(path), method);
970    }
971    return await staticFile(req, res, path);
972  } catch (err) {
973    console.error('[strata]', err);
974    if (res.headersSent) { res.end(); return; }   // a stream already began: it ends here (a second writeHead would throw out of this handler and end the process)
975    error(res, 500, err.message ?? 'Internal error');
976  }
977});
978
979async function api(req, res, path, method, url) {
980  if(path==='/api/fonts'&&method==='GET')return json(res,200,await systemFonts());
981  // --- chats: one file each in the data folder -----------------------------
982  // Not held back by a model folder move: saving a chat has nothing to do with the models. A page must name itself (x-strata-client), which
983  // a web page from another site cannot do without the browser asking the host first.
984  const chatsRoute = /^\/api\/chats(?:\/([^/]+))?$/.exec(path);
985  if (chatsRoute) {
986    if (!req.headers['x-strata-client']) return error(res, 403, 'Not allowed.');
987    let id = null;
988    try { id = chatsRoute[1] ? decodeURIComponent(chatsRoute[1]) : null; } catch { return error(res, 400, 'That is not a chat id.', { code: 'bad-id' }); }
989    const from = typeof req.headers['x-strata-window'] === 'string' ? req.headers['x-strata-window'].slice(0, 64) : null;
990    try {
991      if (!id && method === 'GET') return json(res, 200, chatStore.list());
992      if (id === 'import' && method === 'POST') {
993        const body = JSON.parse((await readRaw(req, 512 * 1024 * 1024)).toString('utf8') || '{}');
994        const result = await chatStore.importMany(body.sessions);
995        for (const imported of result.imported) hub.send('chats', { id: imported, rev: chatStore.rev(imported), from });
996        return json(res, 200, result);
997      }
998      if (id && method === 'GET') {
999        const text = await chatStore.read(id);
1000        if (text === null) return error(res, 404, 'No such chat.', { code: 'not-found' });
1001        res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(text), 'cache-control': 'no-store' });
1002        res.end(text);
1003        return undefined;
1004      }
1005      if (id && method === 'PUT') {
1006        const text = (await readRaw(req, 256 * 1024 * 1024)).toString('utf8');
1007        const base = req.headers['x-strata-base-rev'];
1008        const saved = await chatStore.save(id, text, { baseRev: typeof base === 'string' && /^\d+$/.test(base) ? Number(base) : null });
1009        hub.send('chats', { id, rev: saved.rev, from });
1010        return json(res, 200, saved);
1011      }
1012      if (id && method === 'DELETE') {
1013        const removed = await chatStore.remove(id);
1014        hub.send('chats', { id, deleted: true, from });
1015        return json(res, 200, removed);
1016      }
1017    } catch (e) {
1018      const failure = e instanceof SyntaxError ? { status: 400, message: 'The request must be JSON.', code: 'bad-json' } : storeFailure(e);
1019      return error(res, failure.status, failure.message, { code: failure.code });
1020    }
1021    return error(res, 405, 'Method not allowed.');
1022  }
1023  if (storageChanging && !['GET', 'OPTIONS'].includes(method)) return error(res, 409, 'Wait for the model folder check to finish.');
1024  // --- events -------------------------------------------------------------
1025  if (path === '/api/events') return hub.add(res);
1026  if(path.startsWith('/api/native')){try{
1027  if(path==='/api/native'&&method==='GET')return json(res,200,await native.refresh(url.searchParams.get('refresh')==='1'));
1028  if(path==='/api/native'&&method==='PATCH')return json(res,200,await native.configure(await readBody(req)));
1029  if(path==='/api/native/directory'&&method==='POST')return json(res,200,native.setDownloadDirectory((await readBody(req)).directory));
1030  /* Settings > Storage > Models folder: pick (or type) a folder, say what it means, then start the choice. Copying is Control's (strata models move). */
1031  if(path==='/api/native/models-folder/plan'&&method==='POST'){
1032   const typed=await typedFolder((await readBody(req)).path,{isAbsolute});
1033   const picked=typed?{path:typed}:await chooseFolder('Choose a folder for your models');
1034   if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});}
1035   if(picked.cancelled)return json(res,200,{cancelled:true});
1036   return json(res,200,{plan:await native.planModelsFolder(picked.path)});}
1037  if(path==='/api/native/models-folder/start'&&method==='POST'){const body=await readBody(req);const result=await native.startModelsFolder({folder:body.path,choice:body.choice,stopRunning:body.stopRunning===true});return json(res,result.id?202:200,result);}
1038  if(path==='/api/native/models-folder/interrupted'&&method==='GET')return json(res,200,{interrupted:await native.interruptedMove()});
1039  if(path==='/api/native/models-folder/resume'&&method==='POST'){const body=await readBody(req);return json(res,202,await native.finishInterruptedMove({stopRunning:body.stopRunning===true}));}
1040  if(path==='/api/native/models-folder/leave'&&method==='POST')return json(res,200,await native.leaveInterruptedMove());
1041  if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req)));
1042  if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));}
1043  if(path==='/api/native/engine-restart/dismiss'&&method==='POST')return json(res,200,native.dismissRestart());
1044  if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()});
1045  if(path==='/api/native/logs/save'&&method==='POST'){
1046   /* Diagnostics to a file: the engine messages the app kept, failed operations, and the tail of each model's server log under Control.
1047      Written to the user's Downloads folder (the window cannot save a download); the path is returned to show. */
1048   const NL=String.fromCharCode(10);
1049   const lines=[`Strata diagnostics ${new Date().toISOString()}`,`Version ${native.state().version??'unknown'}`,'','== Engine messages =='];
1050   for(const l of native.logs())lines.push(`${l.at} ${l.instanceId}: ${l.line}`);
1051   lines.push('','== Operations ==');for(const j of native.state().jobs)lines.push(`${j.startedAt} ${j.kind} ${j.state}${j.error?`: ${j.error}`:''}${j.details?`${NL}  ${j.details}`:''}`);
1052   try{const logs=join(dirname(componentsDirectory()),'logs');const names=readdirSync(logs).filter(n=>/^desktop-.*\.log$/.test(n)).sort();const crash=names.filter(n=>n.startsWith('desktop-crash-')).slice(-3).reverse();const runs=names.filter(n=>!n.startsWith('desktop-crash-')).slice(-2).reverse();lines.push('',`== Desktop shell: window crash logs (${crash.length} newest) ==`);for(const n of crash)lines.push('',`-- ${n}`,readFileSync(join(logs,n),'utf8'));lines.push('',`== Desktop shell: last lines of the newest ${runs.length} run logs ==`);for(const n of runs)lines.push('',`-- ${n}`,...readFileSync(join(logs,n),'utf8').split(NL).slice(-300));}catch{/* no desktop logs (not the Linux app, or no crash) */}
1053   try{const runtime=process.env.STRATA_RUNTIME_DIR??join(dirname(componentsDirectory()),'runtime');for(const name of readdirSync(runtime).filter(n=>n.endsWith('.server.log'))){lines.push('',`== ${name} (last lines) ==`,...readFileSync(join(runtime,name),'utf8').split(NL).slice(-200));}}catch{/* no server logs yet */}
1054   const folder=join(process.env.USERPROFILE??process.env.HOME??homedir(),'Downloads');mkdirSync(folder,{recursive:true});
1055   const file=join(folder,`strata-diagnostics-${new Date().toISOString().replace(/[:.]/g,'-').slice(0,19)}.txt`);writeFileSync(file,lines.join(NL),'utf8');
1056   return json(res,200,{path:file});}
1057  if(path==='/api/native/local/preview'&&method==='POST'){
1058   /* "Use a local GGUF": pick (or type) the folder, and Control says what is in it. Nothing is copied or changed. */
1059   const typed=await typedFolder((await readBody(req)).path,{isAbsolute,fileType:/\.gguf$/i});
1060   const picked=typed?{path:typed}:await chooseFolder('Choose the folder that holds your GGUF files');
1061   if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});};
1062   if(picked.cancelled)return json(res,200,{cancelled:true});
1063   return json(res,200,{path:picked.path,preview:await native.localPreview(picked.path)});}
1064  if(path==='/api/native/benchmark'&&method==='GET')return json(res,200,native.benchmarkReport());
1065  /* The auto-tuner's saved tunings (Strata Control's presets, shared with the Terminal). Starting a tune or a re-check is POST /api/native/operations with kind autotune / recheck. */
1066  if(path==='/api/native/tune/status'&&method==='GET')return json(res,200,await native.tuneStatus({model:url.searchParams.get('model'),resourceProfile:url.searchParams.get('resourceProfile')||undefined,vision:url.searchParams.get('vision')||undefined}));
1067  if(path==='/api/native/tune/effective'&&method==='GET')return json(res,200,await native.tuneEffective({model:url.searchParams.get('model'),resourceProfile:url.searchParams.get('resourceProfile')||undefined,vision:url.searchParams.get('vision')||undefined}));
1068  if(path==='/api/native/tune/off'&&method==='POST'){const body=await readBody(req);return json(res,200,await native.tuneOff({model:body.model,resourceProfile:body.resourceProfile,vision:body.vision}));}
1069  if(path==='/api/native/tune/presets'&&method==='GET')return json(res,200,await native.tunePresets.list());
1070  if(path==='/api/native/tune/undo'&&method==='POST'){const body=await readBody(req);return json(res,200,await native.tunePresets.undoFor({model:body.model,resourceProfile:body.resourceProfile,vision:body.vision}));}
1071  const tunePreset=/^\/api\/native\/tune\/presets\/([0-9a-f]{8,32})\/(apply|rename|delete|undo)$/.exec(path);
1072  if(tunePreset&&method==='POST')return json(res,200,await native.tunePresets.action(tunePreset[2],tunePreset[1],await readBody(req)));
1073  const nativeOperation=/^\/api\/native\/operations\/([a-z0-9-]+)\/cancel$/.exec(path);
1074  if(nativeOperation&&method==='POST')return json(res,200,await native.cancel(nativeOperation[1]));
1075  const nativeInstance=/^\/api\/native\/instances\/([a-z0-9-]+)\/(unload|default)$/.exec(path);
1076  if(nativeInstance&&method==='POST')return json(res,200,nativeInstance[2]==='unload'?await native.unload(nativeInstance[1]):native.setDefault(nativeInstance[1]));
1077  const nativeSettings=/^\/api\/native\/models\/([a-z0-9_.-]+)\/settings$/.exec(path);
1078  /* Expert mode shows what will actually run: the saved tuning's values come with the settings (null when none applies or unreadable). */
1079  if(nativeSettings&&method==='GET'){const settings=native.settings(nativeSettings[1]);let tuned=null;try{const t=await native.tuneEffective({model:nativeSettings[1],resourceProfile:url.searchParams.get('resourceProfile')||undefined,vision:url.searchParams.get('vision')||undefined});tuned=t.applied?t:null;}catch{tuned=null;}return json(res,200,{...settings,tuned,hints:await native.settingsHints?.(nativeSettings[1])});}
1080  if(nativeSettings&&method==='PATCH')return json(res,200,native.save(nativeSettings[1],await readBody(req)));
1081  const nativeSettingsFile=/^\/api\/native\/models\/([a-z0-9_.-]+)\/settings-file$/.exec(path);
1082  if(nativeSettingsFile&&method==='GET')return json(res,200,native.settingsFile(nativeSettingsFile[1]));
1083  if(nativeSettingsFile&&method==='POST')return json(res,200,await native.openSettingsFile(nativeSettingsFile[1]));
1084
1085  // Credentials are handled only on the host. Responses and events expose a key-set flag.
1086  return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message,{...(e.code&&typeof e.code==='string'?{code:e.code}:{}),...(e.details?{details:String(e.details)}:{})});}}
1087
1088  if (path === '/api/model-providers' && method === 'GET') return json(res, 200, withPictureAnswers(modelProviders.list()));
1089  if (path === '/api/model-providers/discover' && method === 'POST') {
1090    const body = await readBody(req);
1091    const controller = new AbortController();
1092    res.on('close', () => { if (!res.writableEnded) controller.abort(); });
1093    try { return json(res, 200, await modelProviders.discover(body, controller.signal)); }
1094    catch (err) { return error(res, 400, err.name === 'TimeoutError' ? 'The model API timed out. Check the address and try again.' : err.message); }
1095  }
1096  if (path === '/api/model-providers' && method === 'POST') {
1097    try { return json(res, 200, withPictureAnswers(modelProviders.save(await readBody(req)))); }
1098    catch (err) { return error(res, 400, err.message); }
1099  }
1100  const providerMatch = /^\/api\/model-providers\/([a-zA-Z0-9-]+)$/.exec(path);
1101  if (providerMatch && method === 'DELETE') return json(res, 200, withPictureAnswers(modelProviders.remove(providerMatch[1])));
1102
1103  if(path === '/api/artifacts/open' && method === 'POST') {
1104    const body=await readBody(req, 30*1024*1024);
1105    return json(res,200,await openArtifact(body,{examplesDir:join(ROOT,'public','examples'),previewsDir:join(store.HOME,'previews')}));
1106  }
1107
1108  // Host-owned recurring prompts. Creating a draft never enables a schedule.
1109  // ------------------------------------------------------------------- Tuning
1110  //
1111  // The review surface and the recorded reports. Both are real: the plan is computed from the
1112  // selected engine binary's own flag list, and a report is read from the job's durable record.
1113  // There is no run route, because a sweep needs a measurement harness that does not exist yet and
1114  // a fabricated measurement is worse than no measurement.
1115  if (path === '/api/tune/plan' && method === 'POST') {
1116    const body = await readBody(req);
1117    const result = await tuning.plan({
1118      engine: String(body.engine ?? '').trim(),
1119      backend: String(body.backend ?? '').trim(),
1120      model: body.model ? String(body.model) : undefined,
1121      objective: body.objective, trials: body.trials, repeats: body.repeats,
1122    });
1123    if (!result.ok) return error(res, result.code === 2 ? 400 : 502, result.error);
1124    return json(res, 200, { plan: result.plan });
1125  }
1126  if (path === '/api/tune/engine' && method === 'GET') {
1127    // The plan is only meaningful for a real engine binary, so the panel asks rather than guessing.
1128    // `available` is false when nothing is installed, which is a state the panel must show honestly
1129    // instead of offering a plan that cannot be computed.
1130    const status = supervisor.status();
1131    return json(res, 200, {
1132      available: false,   // the host starts no engine binary of its own (no llama-server)
1133      path: null,
1134      backend: status?.backend ?? null,
1135      running: Boolean(status?.running),
1136    });
1137  }
1138  if (path === '/api/tune/jobs' && method === 'GET') {
1139    return json(res, 200, { jobs: tuning.jobs(), stateDir: tuning.stateDir() });
1140  }
1141  if (path === '/api/tune/job' && method === 'GET') {
1142    const job = tuning.job(url.searchParams.get('id'));
1143    if (!job) return error(res, 404, 'No such tuning job.');
1144    return json(res, 200, { job });
1145  }
1146
1147  // ---------------------------------------------------------------- Time-skip
1148  //
1149  // The job lives in Strata Control (`strata_control/time_skip.py`) and is driven through its CLI.
1150  // These routes only start it, follow it and apply its result; they never compute a status or a
1151  // score of their own, so the UI cannot show progress the job did not report.
1152  if (path === '/api/timeskip' && method === 'GET') {
1153    return json(res, 200, { runs: [...forkTs.list(), ...timeskip.list()], stateDir: timeskip.stateDir() });
1154  }
1155  if (path === '/api/timeskip/status' && method === 'GET') {
1156    const id = url.searchParams.get('id');
1157    if (id && forkTs.has(id)) return json(res, 200, { run: forkTs.status(id) });
1158    const run = id ? timeskip.status(id) : null;
1159    if (!run) return error(res, 404, 'No such Time-skip run.');
1160    return json(res, 200, { run: { ...run, activity: trialActivity(run) } });
1161  }
1162  if (path === '/api/timeskip/start' && method === 'POST') {
1163    const body = await readBody(req);
1164    const workspaceId = typeof body.workspaceId === 'string' ? body.workspaceId : null;
1165    const workspace = String(body.workspace ?? '').trim() || ((workspaceId ? workspaces.find(w => w.id === workspaceId)?.path : null) ?? WORKSPACE);
1166    const prompt = String(body.prompt ?? '').trim().slice(0, 4000);
1167    if (body.legacy !== true) {
1168      if (!prompt) return error(res, 400, 'Say what you want made or improved after /time-skip.');
1169      if (!existsSync(workspace)) return error(res, 400, 'Time-skip works on a folder of your own. Choose a folder for this chat, then try again.');
1170      const cwd = chatFolders.get(typeof body.sessionId === 'string' ? body.sessionId : '') ?? workspace;
1171      if (resolve(cwd) === resolve(ROOT) || resolve(cwd).startsWith(resolve(ROOT) + sep)) return error(res, 400, 'Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.');
1172      if (measureFolder(cwd).tooBig) return error(res, 400, 'This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.');
1173      let choice, slots = 1;
1174      if (body.remoteModel?.connectionId && body.remoteModel?.modelId) { choice = { connectionId: String(body.remoteModel.connectionId), modelId: String(body.remoteModel.modelId) };
1175        { const own = modelProviders.withSecrets().find(c => c.id === choice.connectionId); if (own && own.protocol === 'openai-chat') await visionProbe.check(own, choice.modelId); } slots = Number(body.slots) >= 1 ? Math.floor(Number(body.slots)) : 1; }
1176      else { try { const inst = native.resolveInstance(native.state().defaultId); choice = { instanceId: inst.id }; slots = inst.metrics?.live?.slots?.length || inst.parallel || 1; } catch { return error(res, 503, 'Load a model first, then try Time-skip again.'); } }
1177      const chatId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId : null;
1178      if (chatId && forkTs.byChat(chatId)) return error(res, 409, 'A Time-skip is already running in this chat.');
1179      const run = forkTs.start({ prompt, workspace: cwd, chatId, choice, thinking: typeof body.thinking === 'string' ? body.thinking : 'Low', slots });
1180      return json(res, 200, { run, simulated: false });
1181    }
1182    const reviseCommand = body.useAgent === false ? null : TIMESKIP_REVISE;
1183    // The folder of the app itself is never a person's work: "Keep the update" would write into the installation.
1184    if (resolve(workspace) === resolve(ROOT) || resolve(workspace).startsWith(resolve(ROOT) + sep)) return error(res, 400, 'Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.');
1185    // A trial copies the folder (twice), so a huge folder is refused in plain words instead of filling the disk.
1186    if (existsSync(workspace)) {
1187      const size = measureFolder(workspace);
1188      if (size.tooBig) return error(res, 400, 'This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.');
1189    }
1190    const result = await timeskip.startDetached({
1191      workspace, prompt,
1192      attempts: body.attempts ?? 1,
1193      reviseCommand,
1194      extraEnv: { STRATA_HOST_URL: `http://127.0.0.1:${PORT}`, STRATA_INTERNAL_SECRET: INTERNAL_SECRET },
1195    });
1196    if (!result.ok) return error(res, result.code === 2 ? 400 : 502, result.error);
1197    const chatId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId : null;
1198    trials.set(result.run.id, { chatId, turnChat: null, controller: null, step: null, lastSent: '' });
1199    if (chatId) trialByChat.set(chatId, result.run.id);
1200    watchTrial(result.run.id);
1201    if (body.remoteModel?.connectionId && body.remoteModel?.modelId) timeskipChoices.set(result.run.id, { connectionId: String(body.remoteModel.connectionId), modelId: String(body.remoteModel.modelId) });
1202    return json(res, 200, { run: { ...result.run, activity: trialActivity(result.run) }, simulated: false });
1203  }
1204  if (path === '/api/timeskip/files' && method === 'GET') {
1205    const fid = url.searchParams.get('id');
1206    const found = forkTs.has(fid) ? forkTs.files(fid) : timeskip.files(fid);
1207    if (!found) return error(res, 404, 'No such Time-skip run.');
1208    return json(res, 200, found);
1209  }
1210  /* One picture of a run, original or updated, for the Compare view. Only pictures inside the run's own folders; served as an image and nothing else. */
1211  if (path === '/api/timeskip/file' && method === 'GET') {
1212    const iid = url.searchParams.get('id');
1213    const found = forkTs.has(iid) ? (() => { const p = forkTs.image(iid, url.searchParams.get('path'), url.searchParams.get('version')); return p ? { path: p, type: imageTypeOf(p) } : null; })() : timeskip.image(iid, url.searchParams.get('path'), url.searchParams.get('version'));
1214    if (!found) return error(res, 404, 'No such picture in this Time-skip run.');
1215    res.writeHead(200, { 'content-type': found.type, 'cache-control': 'private, max-age=300', 'x-content-type-options': 'nosniff', 'content-security-policy': "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:" });
1216    createReadStream(found.path).pipe(res);
1217    return;
1218  }
1219  if (path === '/api/timeskip/stop' && method === 'POST') {
1220    const body = await readBody(req);
1221    if (forkTs.has(String(body.id ?? ''))) return json(res, 200, { stopped: await forkTs.stop(String(body.id)) });
1222    return json(res, 200, { stopped: await stopTrial(String(body.id ?? '')) });
1223  }
1224  // One revision attempt for a job this host started: the app's assistant works inside the candidate folder.
1225  if (path === '/api/internal/timeskip-revise' && method === 'POST') {
1226    if (!sameSecret(req.headers['x-strata-internal'], INTERNAL_SECRET)) return error(res, 403, 'Not allowed.');
1227    const body = await readBody(req);
1228    const cwd = String(body.cwd ?? '');
1229    // Only the job's own candidate folders may be worked in.
1230    const root = resolve(timeskip.stateDir());
1231    if (!cwd || !resolve(cwd).startsWith(root + sep)) return error(res, 400, 'That folder is not part of a Time-skip run.');
1232    const runId = resolve(cwd).slice(root.length + 1).split(sep)[0];
1233    const chosen = timeskipChoices.get(runId) ?? (() => { try { return { instanceId: native.resolveInstance(native.state().defaultId).id }; } catch { return null; } })();
1234    if (!chosen) return error(res, 503, 'Load a model first, then try Time-skip again.');
1235    const chatId = `timeskip:${randomBytes(6).toString('hex')}`;
1236    // The answer is a stream that starts at once and carries a beat every 15 s: a turn on a slow computer can run for many minutes with
1237    // nothing to say, and a caller that hears no byte for five minutes gives up (that was "The assistant could not be reached").
1238    res.writeHead(200, { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-cache, no-transform' });
1239    const write = frame => { if (!res.writableEnded && !res.destroyed) res.write(`${JSON.stringify(frame)}\n`); };
1240    write({ type: 'beat' });
1241    const beat = setInterval(() => write({ type: 'beat' }), 15_000);
1242    const controller = new AbortController();
1243    const trial = trials.get(runId);
1244    if (trial) { trial.turnChat = chatId; trial.controller = controller; }
1245    res.on('close', () => { clearInterval(beat); if (!res.writableEnded) { controller.abort(); void agent.stop(chatId).catch(() => {}); } });
1246    let text = '', failure = null;
1247    try {
1248      await agent.runTurn({ chatId, message: timeskipRevisionMessage(String(body.prompt ?? '')), workspacePath: cwd, choice: chosen, mode: 'bypass', thinking: 'low', history: [], signal: controller.signal, onFrame: frame => {
1249        if (frame.type === 'delta') text += frame.text ?? '';
1250        else if (frame.type === 'error') failure = frame.message;
1251        else if (frame.type === 'status' && trial) {
1252          // the assistant's own current step (what it is writing or running) rides along with the job's phase
1253          trial.step = frame.phase === 'idle' ? null : { code: frame.code, text: frame.text, args: frame.args };
1254        }
1255      } });
1256    } catch (e) { failure = failure ?? e.message; } finally { agent.forget(chatId); clearInterval(beat); if (trial) trial.step = null; }
1257    if (controller.signal.aborted) failure = failure ?? 'The trial was stopped.';
1258    write(failure ? { type: 'error', message: failure } : { type: 'result', text: text.slice(-600) });
1259    res.end();
1260    return undefined;
1261  }
1262  if (path === '/api/timeskip/apply' && method === 'POST') {
1263    const body = await readBody(req);
1264    if (forkTs.has(String(body.id ?? ''))) {
1265      try { return json(res, 200, { apply: forkTs.apply({ id: String(body.id), which: body.which === 'a' ? 'a' : 'b', restore: Boolean(body.restore) }) }); }
1266      catch (e) { return error(res, 400, e.message); }
1267    }
1268    const result = await timeskip.apply({
1269      id: body.id, workspace: body.workspace ?? null,
1270      dryRun: Boolean(body.dryRun), restore: Boolean(body.restore), attempt: body.attempt ?? null,
1271    });
1272    if (!result.ok) {
1273      // A concurrent user edit is a conflict the caller must see, not a server error to retry.
1274      return json(res, result.conflict ? 409 : 400, { error: result.error, conflict: Boolean(result.conflict) });
1275    }
1276    return json(res, 200, { apply: result.apply });
1277  }
1278  if (path === '/api/tasks' && method === 'GET') return json(res, 200, { tasks: tasks.list() });
1279  if (path === '/api/tasks/draft' && method === 'POST') {
1280    const body = await readBody(req);
1281    const description = String(body.description ?? '').trim().slice(0, 12000);
1282    if (!description) return error(res, 400, 'Describe the task first.');
1283    let draft = { title: description.slice(0, 70), prompt: description, frequency: /week/i.test(description) ? 'weekly' : /hour/i.test(description) ? 'hourly' : 'daily', at: '09:00', weekday: 1, timeZone: body.timeZone ?? 'UTC', enabled: true };
1284    if (models.REAL) {
1285      let text = '', failure = null;
1286      await runTurn({ message: 'Draft a recurring prompt task from the description below. Return only JSON with title (short), prompt (self-contained; text reasoning only, no file, web, email or external tools), frequency (hourly/daily/weekdays/weekly), at (HH:MM), weekday (0 Sunday to 6 Saturday). Do not claim to execute it. Description: ' + description, signal: AbortSignal.timeout(120000), client: 'Task drafting', onFrame: frame => { if (frame.type === 'delta') text += frame.text ?? ''; if (frame.type === 'error') failure = frame.message; } });
1287      if (failure) return error(res, 400, failure);
1288      try { draft = { ...draft, ...JSON.parse(text.replace(/^```(?:json)?\s*|\s*```$/g, '').trim()), timeZone: body.timeZone ?? 'UTC', enabled: true }; }
1289      catch { return error(res, 400, 'The model did not return a usable draft. Try again or set up manually.'); }
1290    }
1291    try { return json(res, 200, { draft: validateTask(draft), demo: !models.REAL }); }
1292    catch (e) { return error(res, 400, e.message); }
1293  }
1294  if (path === '/api/tasks' && method === 'POST') {
1295    try { return json(res, 201, tasks.put(await readBody(req))); } catch(e) { return error(res, 400, e.message); }
1296  }
1297  const taskRoute = path.match(/^\/api\/tasks\/([^/]+)(?:\/(run|stop))?$/);
1298  if (taskRoute) {
1299    const [, id, action] = taskRoute;
1300    if (!tasks.list().some(t => t.id === id)) return error(res, 404, 'Task not found.');
1301    try {
1302      if (method === 'PATCH' && !action) return json(res, 200, tasks.put(await readBody(req), id));
1303      if (method === 'POST' && action === 'run') { if (tasks.list().find(t => t.id === id)?.archived) return error(res, 400, 'Restore this task first.'); void tasks.execute(id); return json(res, 202, { accepted:true }); }
1304      if (method === 'POST' && action === 'stop') { tasks.stop(id); return json(res, 200, { stopped:true }); }
1305    } catch (e) { return error(res, 400, e.message); }
1306  }
1307
1308  // --- health / setup -----------------------------------------------------
1309  if (path === '/api/health') {
1310    return json(res, 200, {
1311      ok: true,
1312      uptimeSec: Math.round(process.uptime()),
1313      backend: currentBackend(),
1314      engine: supervisor.status(),
1315      clients: hub.size,
1316    });
1317  }
1318
1319  // --- Strata Control: what the installed app runs on, and what it will not do ---------------------
1320  if (path === '/api/control/status' && method === 'GET') {
1321    const engine = control ? await control.engine().catch(e => ({ usable: false, notice: e.message })) : null;
1322    // the first start copies the engine that came with the app (about a minute): say so instead of "no engine"
1323    if (engine && !engine.usable && !bundledEngineSettled) engine.notice = 'The engine that came with the app is being set up. This takes a minute the first time.';
1324    return json(res, 200, {
1325      packaged: process.env.STRATA_PACKAGED === '1',
1326      control: control ? { dir: control.control.dir, python: control.control.python, version: control.version, bundle: control.control.bundle } : null,   // control.control: the Control in use now (a first-run update can switch it)
1327      engine,
1328      engineSetup: !bundledEngineSettled,
1329      componentsDir: componentsDirectory(),
1330      acquisition: { forbidden: acquisitionForbidden(), env: process.env.STRATA_NO_ACQUIRE ?? null },
1331    });
1332  }
1333  // The shell (and nothing else) holds the secret that lets it end the host or tell it which window is in use.
1334  const fromShell = () => {
1335    const token = process.env.STRATA_SHUTDOWN_TOKEN ?? '';
1336    return token.length >= 32 && sameSecret(req.headers['x-strata-shutdown'], token);
1337  };
1338  // Which window the person is using: the page shows "Quit Strata" in browser mode only.
1339  if (path === '/api/app/mode' && method === 'GET') return json(res, 200, appUi.state());
1340  if (path === '/api/app/quit' && method === 'POST') {
1341    // A web page cannot send this header without the browser asking the host first, and the host refuses pages that are not local (above).
1342    if (!req.headers['x-strata-client']) return error(res, 403, 'Not allowed.');
1343    const verdict = appUi.quit();
1344    return verdict.ok ? json(res, verdict.status, { stopping: true }) : error(res, verdict.status, verdict.error);
1345  }
1346  // The shell: the window process registers its updater; or the window could not run and everything moves to a browser tab.
1347  if (path === '/api/control/ui' && method === 'POST') {
1348    if (!fromShell()) return error(res, 403, 'Not allowed.');
1349    const body = await readBody(req);
1350    try {
1351      if (body.bridge) appUi.setBridge(body.bridge);
1352      if (body.mode === 'browser') return json(res, 200, await appUi.switchToBrowser({ url: `http://127.0.0.1:${PORT}/`, reason: body.reason, notice: typeof body.notice === 'string' ? body.notice.slice(0, 300) : '', openPage: body.open !== false }));
1353      if (body.open === true) return json(res, 200, { ...appUi.state(), opened: await appUi.openPage(`http://127.0.0.1:${PORT}/`) });
1354      return json(res, 200, appUi.state());
1355    } catch (err) { return error(res, 400, err.message); }
1356  }
1357  // The shell asks for a clean stop (engines this app started are stopped through Control) before it ends the process.
1358  if (path === '/api/control/shutdown' && method === 'POST') {
1359    if (!fromShell()) return error(res, 403, 'Not allowed.');
1360    json(res, 202, { stopping: true });
1361    setImmediate(() => void shutdown());
1362    return;
1363  }
1364
1365  // Files dropped on the app window (Linux, macOS): the shell hands over the paths, the page fetches each file once (native-drop.mjs).
1366  if (path === '/api/app/drop' && method === 'POST') {
1367    if (!fromShell()) return error(res, 403, 'Not allowed.');
1368    try { return json(res, 200, { files: await nativeDrops.add((await readBody(req)).paths) }); } catch (err) { return error(res, 400, err.message); }
1369  }
1370  const dropGet = /^\/api\/app\/drop\/([0-9a-f-]{36})$/.exec(path);
1371  if (dropGet && method === 'GET') {
1372    const file = nativeDrops.take(dropGet[1]);
1373    if (!file) return error(res, 404, 'That file is no longer available. Drop it again.');
1374    res.writeHead(200, { 'content-type': file.type, 'content-length': file.bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(file.bytes); return undefined;
1375  }
1376
1377  if (path === '/api/setup' && method === 'GET') return json(res, 200, setupState());
1378  if (path === '/api/engine/first-run' && method === 'GET') {
1379    if (!control?.updateCheck) return json(res, 200, { status: 'unavailable', gpus: [] });
1380    const info = await engineFirstRun({ control, gpus: hardware.cachedHardware()?.gpus ?? [] });
1381    try { let at = componentsDirectory(); while (at && !existsSync(at) && dirname(at) !== at) at = dirname(at); const f = statfsSync(at); info.freeBytes = Number(f.bavail) * Number(f.bsize); } catch { /* unknown: no warning */ }
1382    return json(res, 200, info);
1383  }
1384  if (path === '/api/engines' && method === 'GET') {
1385    const { status, body } = await listEngines(control);
1386    return json(res, status, body);
1387  }
1388  if ((path === '/api/engines/use' || path === '/api/engines/remove') && method === 'POST') {
1389    const { status, body } = await changeEngine(control, path.endsWith('/use') ? 'use' : 'remove', await readBody(req), { modelsRunning: () => native.state().instances.length > 0 });
1390    if (status === 200) Promise.resolve(native.refresh?.(true)).catch(() => { /* the next poll reads it */ });
1391    return json(res, status, body);
1392  }
1393  if (path === '/api/engine/job' && method === 'GET') {
1394    // The newest engine download / file install, read without waiting for the native snapshot to connect (the first-run card needs it before that).
1395    const kinds = ['update-engine', 'install-engine-file'];
1396    return json(res, 200, { job: native.state().jobs.filter(j => kinds.includes(j.kind)).slice(-1)[0] ?? null });
1397  }
1398  if (path === '/api/engine/from-file' && method === 'POST') {
1399    // The person chose an engine package in the page (the offline path). The bytes come here; Control checks and installs them.
1400    const name = String(req.headers['x-file-name'] ?? 'engine.tar.gz').replace(/[^A-Za-z0-9._-]/g, '_').slice(-120);
1401    if (!/\.(tar\.gz|tgz|tar\.xz|zip)$/i.test(name)) return error(res, 400, 'This is not a Strata engine package. Choose the .tar.gz or .zip file from the release page.');
1402    const folder = join(store.DATA_DIR, 'incoming-engine');
1403    mkdirSync(folder, { recursive: true, mode: 0o700 });
1404    const target = join(folder, name);
1405    await pipeline(req, createWriteStream(target, { mode: 0o600 }));
1406    return json(res, 202, native.operation('install-engine-file', { path: target }));
1407  }
1408  if (path === '/api/updates/check' && method === 'GET' && control?.updateCheck) return json(res, 200, await checkComponentUpdates({ control, appUpdater, appVersion: process.env.STRATA_APP_VERSION || null }));
1409  if (path === '/api/updates/check' && method === 'GET') return json(res, 200, await checkUpdates({ appVersion:appVersionToShow(setupState().app.version,native.state().version), engineVersion:native.state().available?(native.state().installed?.engine?.version??null):(await engine.config()).engine.version }));
1410
1411  if (path === '/api/setup/step' && method === 'POST') {
1412    const body = await readBody(req);
1413    const s = store.get();
1414    const step = Math.max(1, Math.min(4, migrateSetup({ step: body.step, flowVersion: body.flowVersion }).step));
1415    store.update({
1416      setup: { ...s.setup, flowVersion: 2, complete: false, step, dismissed: !!body.dismissed, choices: { ...s.setup.choices, ...body.choices }, history: [...(s.setup.history ?? []), { step, at: new Date().toISOString() }] },
1417    });
1418    const next = setupState();
1419    hub.send('setup', next);
1420    return json(res, 200, next);
1421  }
1422
1423  if (path === '/api/setup/complete' && method === 'POST') {
1424    const s = store.get();
1425    if (!models.library().loaded&&!native.hasLive()) return error(res, 409, 'Load a model before completing setup.');
1426    store.update({ setup: { ...s.setup, dismissed: false, complete: true, flowVersion: 2, step: 4, completedAt: new Date().toISOString() } });
1427    const next = setupState();
1428    hub.send('setup', next);
1429    return json(res, 200, next);
1430  }
1431
1432  // --- hardware -----------------------------------------------------------
1433  if (path === '/api/hardware') {
1434    const force = url.searchParams.get('reprobe') === '1';
1435    const hw = await hardware.detect({ force });
1436    if (force) monitor.init(hub, hw);
1437    return json(res, 200, hw);
1438  }
1439
1440  // --- models -------------------------------------------------------------
1441  if (path === '/api/local-models/browse' && method === 'GET') {
1442    const shortcuts = [{name:'Model directory',path:store.MODELS_DIR},{name:'Home',path:process.env.USERPROFILE??process.env.HOME}].filter(s=>s.path);
1443    try { return json(res, 200, { ...browseLocalModels(url.searchParams.get('directory') ?? store.MODELS_DIR), shortcuts }); }
1444    catch (err) { return error(res, 400, err.message); }
1445  }
1446  if (path === '/api/local-models/inspect' && method === 'POST') {
1447    try { const body=await readBody(req); return json(res,200,inspectLocalModel(body.path)); }
1448    catch (err) { return error(res,400,err.message); }
1449  }
1450  if (path === '/api/local-models' && method === 'POST') {
1451    const body=await readBody(req);
1452    if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');
1453    try {
1454      const preview=inspectLocalModel(body.path),previous=variant(preview.variant.id);
1455      if(body.name!==undefined){if(typeof body.name!=='string'||!body.name.trim()||body.name.length>160)return error(res,400,'Enter a display name up to 160 characters.');preview.variant.name=body.name.replace(/[\x00-\x1f\x7f]/g,' ').trim();if(!preview.variant.name)return error(res,400,'Enter a display name.');preview.variant.label=`${preview.variant.name} · ${preview.variant.quant}`;}
1456      if(previous && runtimeModels.hasVariant(previous.id) && JSON.stringify(previous.local)!==JSON.stringify(preview.variant.local))return error(res,409,'Unload this local model before replacing its file reference.');
1457      localModels.add(preview);
1458      return json(res,200,{library:runtimeModels.libraryState(models.localModelAdded()),variantId:preview.variant.id});
1459    } catch (err) { return error(res,400,err.message); }
1460  }
1461  if (path === '/api/storage/models-directory' && method === 'POST') {
1462    const body = await readBody(req);
1463    let directory;
1464    try { directory = store.validateModelsDirectory(body.directory); }
1465    catch (err) { return error(res, 400, err.message); }
1466    const changed = directory !== store.MODELS_DIR;
1467    const instances = runtimeState().instances;
1468    if (storageChanging || modelOperations || models.directoryBusy() || imageModels.busy()||native.state().jobs.some(j=>j.state==='running')) return error(res, 409, 'Finish or cancel model downloads and loading before changing the folder.');
1469    if (serving.state().requests.some(r => ['queued', 'generating'].includes(r.state))) return error(res, 409, 'Finish or cancel model requests before changing the folder.');
1470    if (changed && instances.length && body.unload !== true) return error(res, 409, 'Unload the current models before changing the folder.');
1471    const nativePlan=nativeUnloadPlan({changed,unload:body.unload,instances:native.state().instances});
1472    if(nativePlan.refuse)return error(res,409,nativePlan.refuse);
1473    for(const id of nativePlan.ids)await native.unload(id);
1474    storageChanging = true;
1475    try {
1476      if (changed) {
1477        if (models.REAL) await models.unload();
1478        else for (const instance of instances) runtimeModels.unload(instance.id);
1479        store.changeModelsDirectory(directory);
1480        engine.markStopped(); monitor.idle('Model directory changed');
1481      }
1482      models.init(hub);
1483      const images = await imageModels.rescan(changed);
1484      const hw = await hardware.detect({ force: true });
1485      const library = runtimeModels.libraryState(models.library());
1486      hub.send('models', library); hub.send('setup', setupState()); hub.send('engine', await engine.config());
1487      return json(res, 200, { library, imageModels: images, runtime: runtimeState(), hardware: hw, setup: setupState() });
1488    } catch (err) { return error(res, 400, err.message); }
1489    finally { storageChanging = false; hub.send('models', models.library()); hub.send('setup', setupState()); }
1490  }
1491  if (path === '/api/image-models' && method === 'GET') return json(res, 200, imageModels.library());
1492  if (path === '/api/image-models' && method === 'PATCH') {
1493    const body = await readBody(req);
1494    return json(res, 200, imageModels.select(body.selected));
1495  }
1496  if (path === '/api/image-models/apply' && method === 'POST') return json(res, 200, imageModels.apply());
1497  const imageMatch = /^\/api\/image-models\/(q4|q5|q6|q8)\/(install|cancel)$/.exec(path);
1498  if (imageMatch && method === 'POST') {
1499    const [, id, action] = imageMatch;
1500    return json(res, 200, action === 'install' ? imageModels.install(id) : await imageModels.cancel(id));
1501  }
1502  if(path==='/api/runtime' && method==='GET')return json(res,200,runtimeState());
1503  if(path==='/api/runtime/plan' && method==='POST')return json(res,200,runtimeModels.plan(await readBody(req)));
1504  if(path==='/api/runtime/load' && method==='POST'){
1505    const body=await readBody(req);const checked=await engine.validate({...body.config,variantId:body.variantId});
1506    if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');
1507    if(!checked.ok)return error(res,400,checked.issues.filter(i=>i.level==='error').map(i=>i.message).join(' '));
1508    if(models.REAL)return error(res,409,'This native host supports one model on automatic GPU placement.');
1509    try{const plan=runtimeModels.plan(body);if(!plan.allowed)return error(res,409,'This model does not fit the selected setup.');for(const instance of native.state().instances)await native.unload(instance.id);return json(res,200,runtimeModels.load(body));}catch(err){return error(res,409,err.message);}
1510  }
1511  const runtimeMatch=/^\/api\/runtime\/([^/]+)\/(unload|default)$/.exec(path);
1512  if(runtimeMatch && method==='POST'){
1513    const [,id,action]=runtimeMatch;runtimeState();
1514    if(models.REAL && action==='unload'){
1515      const instance=runtimeModels.state().instances.find(i=>i.id===id);
1516      if(!instance)return error(res,404,'This model is no longer loaded.');
1517      if(serving.state().requests.some(r=>r.instanceId===id && ['queued','generating'].includes(r.state)))return error(res,409,'Finish or cancel this model’s requests first.');
1518      await models.unload();engine.markStopped();hub.send('engine',await engine.config());runtimeState();return json(res,200,runtimeState());
1519    }
1520    try{return json(res,200,action==='unload'?runtimeModels.unload(id):runtimeModels.setDefault(id));}
1521    catch(err){return error(res,409,err.message);}
1522  }
1523  if (path === '/api/models' && method === 'GET') return json(res, 200, runtimeModels.libraryState(models.library()));
1524
1525  const modelMatch = /^\/api\/models\/([^/]+)(?:\/(install|cancel|load))?$/.exec(path);
1526  if (modelMatch) {
1527    const [, id, action] = modelMatch;
1528    if (method === 'DELETE') {if(runtimeModels.hasVariant(id))return error(res,409,'Unload every instance of this model before deleting its files.');return json(res, 200, runtimeModels.libraryState(models.remove(id)));}
1529    if (method === 'POST' && action === 'install') { try { return json(res, 200, runtimeModels.libraryState(await models.install(id))); } catch (err) { return error(res, err.status ?? 500, err.message); } }
1530    if (method === 'POST' && action === 'cancel') return json(res, 200, runtimeModels.libraryState(models.cancel(id)));
1531    if (method === 'POST' && action === 'load') {
1532      const hw = await hardware.detect();
1533      if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');
1534      if(!models.REAL){
1535        const config={beginner:store.get().beginner,expert:engine.params(),extra:store.get().configExtra??{}};
1536        const gpuIds=config.expert.find(p=>p.id==='gpu.layers')?.value==='CPU only'?[]:hw.gpus.map(g=>g.id??`${g.vendor}:${g.index}`);
1537        try{const choice={variantId:id,gpuIds,config,executionMode:'single'};const plan=runtimeModels.plan(choice);if(!plan.allowed)throw new Error('This model does not fit the selected setup.');for(const instance of native.state().instances)await native.unload(instance.id);runtimeModels.load(choice);}
1538        catch(err){return error(res,409,err.message);}
1539        await monitor.setModel(id);engine.markRunning(hw.accelerator.backend);hub.send('engine',await engine.config());
1540        return json(res,200,runtimeModels.libraryState(models.library()));
1541      }
1542      // Strata's own engine only: 0.2.14 started a llama.cpp llama-server here (an imported GGUF, the starter list) in the real-engine mode
1543      return error(res,409,'Strata runs models only on its own engine, so this model can\'t load here. Open Models and choose a model there, or use "Use a local GGUF…" for a file you already have.');
1544    }
1545  }
1546
1547  if (path === '/api/models/unload' && method === 'POST') {
1548    if(!models.REAL && runtimeModels.state().defaultId){runtimeModels.unload(runtimeModels.state().defaultId);return json(res,200,runtimeModels.libraryState(models.library()));}
1549    const lib = await models.unload({ onPhase: () => monitor.idle('Model unloaded') });
1550    engine.markStopped();
1551    hub.send('engine', await engine.config());
1552    return json(res, 200, runtimeModels.libraryState(lib));
1553  }
1554
1555  // --- engine -------------------------------------------------------------
1556  if (path === '/api/engine' && method === 'GET') return json(res, 200, await engine.config());
1557  if (path === '/api/engine' && method === 'PATCH') {
1558    const body = await readBody(req);
1559    const checked = await engine.validate(body);
1560    if (!checked.ok) return error(res, 400, checked.issues.filter(i => i.level === 'error').map(i => i.message).join(' '));
1561    const cfg = await engine.patch(body);
1562    if (body.beginner?.contextLength) {
1563      monitor.setContextMax(CONTEXT_TOKENS[body.beginner.contextLength] ?? 32768);
1564    }
1565    return json(res, 200, cfg);
1566  }
1567  if (path === '/api/engine/restart' && method === 'POST') {
1568    monitor.idle('Engine restarting');
1569    const cfg = await engine.restart();
1570    monitor.setModel(store.get().loaded);
1571    return json(res, 200, cfg);
1572  }
1573  if (path === '/api/engine/reset' && method === 'POST') return json(res, 200, await engine.reset());
1574  if (path === '/api/engine/validate' && method === 'POST') {
1575    const body = await readBody(req);
1576    return json(res, 200, await engine.validate(body ?? {}));
1577  }
1578  if (path === '/api/engine/status' && method === 'GET') return json(res, 200, supervisor.status());
1579  if (path === '/api/engine/logs' && method === 'GET') {
1580    return json(res, 200, {
1581      logs: supervisor.logs(Number(url.searchParams.get('limit') ?? 200)),
1582      status: supervisor.status(),
1583    });
1584  }
1585  if (path === '/api/engine/stop' && method === 'POST') {
1586    const status = await supervisor.stop();
1587    store.update({ loaded: null });
1588    monitor.idle('Model unloaded');
1589    engine.markStopped();
1590    hub.send('engine', await engine.config());
1591    hub.send('models', models.library());
1592    return json(res, 200, status);
1593  }
1594  if (path === '/api/engine/binary' && method === 'GET') return json(res, 200, engineInstall.status());
1595  if (path === '/api/engine/binary' && method === 'POST') {
1596    try {
1597      const result = await engineInstall.install({ force: url.searchParams.get('force') === '1' });
1598      return json(res, 200, result);
1599    } catch (err) {
1600      return error(res, err.status ?? 500, err.message, { ...engineInstall.status(), error: err.message });
1601    }
1602  }
1603  if (path === '/api/engine/export' && method === 'GET') return json(res, 200, await engine.exportConfig());
1604
1605  // --- serving ------------------------------------------------------------
1606  if (path === '/api/serving/tunnel' && method === 'GET') return json(res, 200, await cloudflare.inspect());
1607  if (path === '/api/serving/tunnel' && method === 'POST') {
1608    try { const body = await readBody(req); if (body.action === 'stop') await cloudflare.stop(); else if (body.action === 'start') await cloudflare.start(body); else if (body.action === 'prepare') await cloudflare.prepare(); else throw new Error('Unknown tunnel action.'); return json(res, 200, serving.state()); }
1609    catch(e) { return error(res, 400, e.message); }
1610  }
1611  if (path === '/api/monitor/snapshot' && method === 'POST') {
1612    try { const body = await readBody(req, 25 * 1024 * 1024); return json(res, 200, await saveSnapshot(body.data)); }
1613    catch(e) { return error(res, 400, e.message); }
1614  }
1615  if (path === '/api/serving/share' && method === 'POST') {
1616    try { const body = await readBody(req); if (body.enabled === true) await localShare.start(); else await localShare.stop(); return json(res, 200, serving.state()); }
1617    catch(e) { return error(res, 400, e.message); }
1618  }
1619  if (path === '/api/serving' && method === 'GET') return json(res, 200, serving.state());
1620  if (path === '/api/serving' && method === 'PATCH') {
1621    const body = await readBody(req);
1622    return json(res, 200, serving.patch(body));
1623  }
1624  const cancelMatch = /^\/api\/serving\/requests\/([^/]+)\/cancel$/.exec(path);
1625  if (cancelMatch && method === 'POST') return json(res, 200, serving.cancel(cancelMatch[1]));
1626
1627  // --- monitor ------------------------------------------------------------
1628  if (path === '/api/monitor') { monitor.watch(); if (url.searchParams.get('drives') === '1') monitor.watchDrives(); return json(res, 200, monitor.snapshot()); }
1629
1630  // --- skills / workspace -------------------------------------------------
1631  if (path === '/api/skills' && method === 'GET') {
1632    /* Re-scan rather than returning the array built at startup.
1633       The screen offers a "Check again" action for a skill dropped into the
1634       workspace while the app is open; returning the cached list made that
1635       button a promise the host did not keep. Enabled state and usage counts
1636       are carried across, since they belong to the skill's identity rather than
1637       to the scan. */
1638    const known = new Map(skillState.map((s) => [s.id, s]));
1639    skillState = skills().map((s) => {
1640      const before = known.get(s.id);
1641      return before
1642        ? { ...s, enabled: before.enabled, onlyIn: before.onlyIn ?? null, useCount: before.useCount, lastUsedAt: before.lastUsedAt }
1643        : { ...s, onlyIn: null, useCount: 0, lastUsedAt: null };
1644    });
1645    syncAgentSkills();
1646    return json(res, 200, skillState);
1647  }
1648  // A skill written in the app: a name, what it is for, and the instructions. Saved as a folder the agent can read; no restart.
1649  if (path === '/api/skills' && method === 'POST') {
1650    const body = await readBody(req);
1651    try {
1652      const name = String(body.name ?? '').trim().slice(0, 80);
1653      const instructions = String(body.body ?? '').trim();
1654      if (!name) throw new Error('Give the skill a name.');
1655      if (!instructions) throw new Error('Write the instructions the assistant should follow.');
1656      // The form's own choices are kept: a skill created with "Skill enabled" off stays off (QA F04), and its trigger phrases are saved with it.
1657      const triggers = body.triggers === undefined ? [] : skillEdit({ triggers: body.triggers }).triggers;
1658      const id = writeCreatedSkill(CREATED_SKILLS, { name, description: String(body.description ?? '').trim().slice(0, 400), body: instructions.slice(0, 40000) });
1659      const newId = `my-${id}`, off = body.enabled === false;
1660      if (off || triggers.length) {
1661        const saved = store.get();
1662        store.update({
1663          ...(off ? { skillPreferences: { ...saved.skillPreferences, [newId]: { enabled: false, onlyIn: null } } } : {}),
1664          ...(triggers.length ? { skillEdits: { ...saved.skillEdits, [newId]: { ...saved.skillEdits?.[newId], triggers } } } : {}),
1665        });
1666      }
1667      const before = new Map(skillState.map(s => [s.id, s]));
1668      skillState = skills().map(s => before.has(s.id) ? { ...s, enabled: before.get(s.id).enabled, onlyIn: before.get(s.id).onlyIn ?? null, useCount: before.get(s.id).useCount, lastUsedAt: before.get(s.id).lastUsedAt } : { ...s, enabled: s.id === newId && off ? false : s.enabled, onlyIn: null, useCount: 0, lastUsedAt: null });
1669      syncAgentSkills();
1670      hub.send('skills', skillState);
1671      return json(res, 201, { id: newId, skills: skillState });
1672    } catch (e) { return error(res, 400, e.message); }
1673  }
1674  const skillDelete = /^\/api\/skills\/([^/]+)$/.exec(path);
1675  if (skillDelete && method === 'DELETE') {
1676    const skill = skillState.find(s => s.id === decodeURIComponent(skillDelete[1]));
1677    if (!skill) return error(res, 404, 'Skill not found.');
1678    if (skill.source !== 'created') return error(res, 400, 'Only a skill you wrote here can be removed from this page.');
1679    rmSync(join(CREATED_SKILLS, skill.id.replace(/^my-/, '')), { recursive: true, force: true });
1680    skillState = skillState.filter(s => s.id !== skill.id);
1681    syncAgentSkills();
1682    hub.send('skills', skillState);
1683    return json(res, 200, skillState);
1684  }
1685  const skillMatch = /^\/api\/skills\/([^/]+)$/.exec(path);
1686  if (skillMatch && method === 'PATCH') {
1687    const body = await readBody(req);
1688    const skillId = decodeURIComponent(skillMatch[1]);
1689    if (!skillState.some(s => s.id === skillId)) return json(res, 404, { error: 'Skill not found.' });
1690    let edit;
1691    try { edit = skillEdit(body); } catch (error) { return json(res, 400, { error: error.message }); }
1692    if (body.onlyIn != null && !workspaces.some(w => w.id === body.onlyIn)) return json(res, 400, { error: 'Choose an available workspace.' });
1693    skillState = skillState.map((s) =>
1694      s.id === skillId
1695        ? {
1696            ...s,
1697            ...edit,
1698            enabled: body.enabled === undefined ? s.enabled : !!body.enabled,
1699            // null clears the narrowing; a workspace id restricts to it.
1700            onlyIn: body.onlyIn === undefined ? (s.onlyIn ?? null) : (body.onlyIn || null),
1701          }
1702        : s,
1703    );
1704    store.update({ skillPreferences: Object.fromEntries(skillState.map(s => [s.id, { enabled: s.enabled, onlyIn: s.onlyIn }])), skillEdits: { ...store.get().skillEdits, [skillId]: { ...store.get().skillEdits?.[skillId], ...edit } } });
1705    syncAgentSkills();
1706    hub.send('skills', skillState);
1707    return json(res, 200, skillState);
1708  }
1709
1710  if (path === '/api/workspace') {
1711    const root = url.searchParams.get('root');
1712    const found = root ? workspaces.find((w) => w.id === root) : null;
1713    // A stale id from a saved session falls back to the primary root rather than
1714    // erroring, so a removed folder cannot break the app.
1715    return json(res, 200, workspaceListing(found?.path ?? WORKSPACE));
1716  }
1717
1718  // --- workspaces ---------------------------------------------------------
1719  // Read one file for the preview pane. Bounded deliberately: only inside a
1720  // registered workspace, only text, only up to a size that can be shown.
1721  if (path === '/api/workspace/file') {
1722    const rootId = url.searchParams.get('root');
1723    const rel = url.searchParams.get('path') ?? '';
1724    const root = (rootId ? workspaces.find((w) => w.id === rootId)?.path : null) ?? WORKSPACE;
1725    const target = resolve(root, rel);
1726    // A relative path may not escape its workspace.
1727    if (target !== resolve(root) && !target.startsWith(resolve(root) + '/')) {
1728      return error(res, 400, 'That file is outside the workspace.');
1729    }
1730    let st;
1731    try {
1732      st = statSync(target);
1733    } catch {
1734      return error(res, 404, "That file doesn't exist any more.");
1735    }
1736    if (!st.isFile()) return error(res, 400, "That's a folder, not a file.");
1737    const LIMIT = 200 * 1024;
1738    if (st.size > LIMIT) {
1739      return json(res, 200, { path: rel, tooLarge: true, sizeKb: st.size / 1024, text: '' });
1740    }
1741    let text = '';
1742    try {
1743      text = readFileSync(target, 'utf8');
1744    } catch {
1745      return json(res, 200, { path: rel, binary: true, sizeKb: st.size / 1024, text: '' });
1746    }
1747    // A NUL byte in the first block is the usual signal for a binary file.
1748    if (text.slice(0, 1024).includes('\u0000')) {
1749      return json(res, 200, { path: rel, binary: true, sizeKb: st.size / 1024, text: '' });
1750    }
1751    return json(res, 200, { path: rel, text, sizeKb: st.size / 1024, updatedAt: st.mtime.toISOString() });
1752  }
1753
1754  // The folder a chat works in, and opening its files by path (notes-split-agent8.md).
1755  if (path === '/api/chat/folder' && method === 'GET') {
1756    const id = url.searchParams.get('sessionId') ?? '';
1757    return json(res, 200, { folder: chatFolders.info(id), default: workspaces[0]?.path ?? WORKSPACE });
1758  }
1759  if (path === '/api/chat/folder' && method === 'POST') {
1760    const body = await readBody(req);
1761    const id = String(body.sessionId ?? '');
1762    if (!id) return error(res, 400, 'sessionId is required');
1763    if (agent.isRunning(id)) return error(res, 409, 'This chat is still working. Stop it or wait for it to finish, then choose the folder.');
1764    if (body.path === null || body.path === '') { chatFolders.clear(id); return json(res, 200, { folder: null }); }
1765    try { return json(res, 200, { folder: chatFolders.set(id, body.path) }); } catch (e) { return error(res, 400, e.message); }
1766  }
1767  if (path === '/api/files/open' && method === 'POST') {
1768    const body = await readBody(req);
1769    try { return json(res, 200, openFile(chatRoot(String(body.sessionId ?? '')), body.path, String(body.how ?? 'app'))); }
1770    catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
1771  }
1772  /* Files and pictures dropped or pasted into a chat: multipart, a JSON data address, or raw bytes. A picture comes back with an id the next message names (imageIds). */
1773  if (path === '/api/chat/upload' && method === 'POST') {
1774    const sid = url.searchParams.get('sessionId') ?? '';
1775    if (!sid) return error(res, 400, 'sessionId is required');
1776    try { const body = await readRaw(req); return json(res, 200, { files: uploads.accept(sid, { body, contentType: req.headers['content-type'], name: url.searchParams.get('name') }) }); }
1777    catch (e) { return error(res, e.code === 'too-big' ? 413 : 400, e.message); }
1778  }
1779  const uploadGet = /^\/api\/chat\/upload\/([0-9a-f-]{36})$/.exec(path);
1780  if (uploadGet && method === 'GET') {
1781    const img = uploads.image(uploadGet[1]);
1782    if (!img) return error(res, 404, 'That picture is no longer available.');
1783    res.writeHead(200, { 'content-type': img.type, 'content-length': img.bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(img.bytes); return undefined;
1784  }
1785  if (path === '/api/files/preview' && method === 'GET') {
1786    const sid = url.searchParams.get('sessionId') ?? '';
1787    try { return json(res, 200, previewFile(chatRoot(sid), url.searchParams.get('path'), sid)); }
1788    catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
1789  }
1790  if (path === '/api/files/raw' && method === 'GET') {
1791    try { const f = rawFile(chatRoot(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); res.writeHead(200, { 'content-type': f.mime, 'content-length': f.bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(f.bytes); return undefined; }
1792    catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
1793  }
1794  /* A message too large for the model's window, made small enough to send: its text as a file in the chat's folder, or a shortened preview (oversize.mjs). */
1795  if (path === '/api/chat/oversize' && method === 'POST') {
1796    const body = await readBody(req, 12 * 1024 * 1024);
1797    const text = String(body.text ?? '');
1798    if (!text.trim()) return error(res, 400, 'text is required');
1799    let instance = null;
1800    try { instance = native.resolveInstance(body.nativeModelId ?? native.state().defaultId); } catch { /* no local model: the length alone decides */ }
1801    try { return json(res, 200, await prepareOversized({ mode: body.mode === 'file' ? 'file' : 'preview', text, root: chatRoot(String(body.sessionId ?? '')), instance })); }
1802    catch (e) { return error(res, 400, 'The message could not be prepared. Try a shorter message.'); }
1803  }
1804  /* "Attach as context": the file is named in the next message of the chat, so the assistant reads it again. */
1805  if (path === '/api/chat/attachments' && method === 'GET') return json(res, 200, { files: chatAttachments.list(url.searchParams.get('sessionId') ?? '') });
1806  if (path === '/api/chat/attachments' && method === 'POST') {
1807    const body = await readBody(req); const id = String(body.sessionId ?? '');
1808    try { const file = resolveChatFile(chatRoot(id), body.path); return json(res, 200, { files: body.remove === true ? chatAttachments.remove(id, file) : chatAttachments.add(id, file) }); }
1809    catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
1810  }
1811  if (path === '/api/files/path' && method === 'GET') {
1812    try { const p = resolveChatFile(chatRoot(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); return json(res, 200, { path: p }); }
1813    catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
1814  }
1815  if (path === '/api/workspaces' && method === 'GET') {
1816    return json(res, 200, { workspaces });
1817  }
1818
1819  if (path === '/api/workspaces' && method === 'POST') {
1820    const body = await readBody(req);
1821    const target = resolve(String(body.path ?? '').trim().replace(/^~/, store.HOME));
1822    if (!target) return error(res, 400, 'Choose a folder first.');
1823    let st;
1824    try {
1825      st = statSync(target);
1826    } catch {
1827      return error(res, 400, "That folder doesn't exist.");
1828    }
1829    if (!st.isDirectory()) return error(res, 400, "That's a file, not a folder.");
1830    if (workspaces.some((w) => w.path === target)) {
1831      return error(res, 400, 'That folder is already in your workspaces.');
1832    }
1833    const ws = {
1834      id: `ws_${Math.random().toString(36).slice(2, 8)}`,
1835      name: basename(target) || target,
1836      path: target,
1837    };
1838    workspaces = [...workspaces, ws];
1839    saveWorkspaces();
1840    return json(res, 200, ws);
1841  }
1842
1843  /* A workspace's name is only what the sidebar shows; its folder stays. */
1844  if (path.startsWith('/api/workspaces/') && method === 'PATCH') {
1845    const id = path.split('/')[3];
1846    const body = await readBody(req);
1847    const name = String(body.name ?? '').trim().slice(0, 80);
1848    if (!name) return error(res, 400, 'Type a name for this workspace.');
1849    const at = workspaces.findIndex(w => w.id === id);
1850    if (at < 0) return error(res, 404, 'That workspace is not in your list.');
1851    workspaces = workspaces.map((w, i) => (i === at ? { ...w, name } : w));
1852    saveWorkspaces();
1853    return json(res, 200, workspaces[at]);
1854  }
1855
1856  if (path.startsWith('/api/workspaces/') && method === 'DELETE') {
1857    const id = path.split('/')[3];
1858    if (id === workspaces[0]?.id) {
1859      return error(res, 400, 'The first workspace cannot be removed.');
1860    }
1861    workspaces = workspaces.filter((w) => w.id !== id);
1862    saveWorkspaces();
1863    return json(res, 200, { ok: true });
1864  }
1865
1866  // A native folder chooser. Asking someone who finds computers daunting to type
1867  // an absolute path is not a real option, so this borrows the system dialog.
1868  /* "Add from folder" promised to install a skill and, until now, cleared the
1869     search box instead — a button whose label and action had nothing to do with
1870     each other. This does the thing the label says: choose a folder, check it
1871     looks like a skill, copy it into the workspace's skills directory. */
1872  if (path === '/api/skills/add' && method === 'POST') {
1873    try {
1874      // The dialog is the normal path; a typed `path` in the body stands in where none exists.
1875      const typed = await typedFolder((await readBody(req)).path, { isAbsolute });
1876      const picked = typed ? { path: typed } : await chooseFolder('Choose a skill folder (it should contain SKILL.md)');
1877      if (picked.unavailable) {const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});};
1878      if (picked.cancelled) return json(res, 200, { cancelled: true });
1879      const chosen = picked.path;
1880      const base = basename(chosen);
1881      const mdPath = join(chosen, 'SKILL.md');
1882      if (!existsSync(mdPath)) {
1883        return error(res, 400, `That folder has no SKILL.md, so there is nothing for the model to read. A skill folder holds a SKILL.md with its instructions.`);
1884      }
1885      const dest = join(WORKSPACE, 'skills', base);
1886      if (existsSync(dest)) {
1887        return error(res, 400, `A skill called "${base}" is already in this workspace. Rename the folder, or remove the existing one first.`);
1888      }
1889      mkdirSync(join(WORKSPACE, 'skills'), { recursive: true });
1890      cpSync(chosen, dest, { recursive: true });
1891      return json(res, 200, { added: base });
1892    } catch (e) {
1893      // Dismissing the dialog is { cancelled: true } above; anything thrown here is a real problem.
1894      return error(res, 400, e.message);
1895    }
1896  }
1897
1898  if (path === '/api/workspaces/pick' && method === 'POST') {
1899    try {
1900      const typed = await typedFolder((await readBody(req)).path, { isAbsolute });
1901      const picked = typed ? { path: typed } : await chooseFolder('Choose a folder for Strata');
1902      if (picked.unavailable) {const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});};
1903      if (picked.cancelled) return json(res, 200, { cancelled: true });
1904      return json(res, 200, { path: picked.path });
1905    } catch (e) {
1906      return error(res, 400, e.message);
1907    }
1908  }
1909
1910  // --- agent --------------------------------------------------------------
1911  if (path === '/api/agent/status' && method === 'GET') return json(res, 200, agent.status());
1912  // The assistant's model requests, with the person's Response settings added (llm-shape.mjs). This computer only.
1913  const llmRoute = /^\/api\/internal\/agent-llm\/([A-Za-z0-9_.~-]+)(\/.*)$/.exec(path);
1914  if (llmRoute) { llmProxy(req, res, llmRoute[1], llmRoute[2] + (url.search ?? '')); return undefined; }
1915  // The goal bar (notes-split-agent3.md): the state, and the instant actions. Resume runs rounds, so it is a chat stream with {goalAction:'resume'}.
1916  if (path === '/api/goal' && method === 'GET') {
1917    try { return json(res, 200, { goal: await agent.goalState(url.searchParams.get('chatId') ?? '') }); } catch (e) { return error(res, 400, e.message); }
1918  }
1919  const goalAct = /^\/api\/goal\/(pause|edit|clear)$/.exec(path);
1920  if (goalAct && method === 'POST') {
1921    const body = await readBody(req);
1922    try { return json(res, 200, await agent.goalControl({ chatId: String(body.chatId ?? body.sessionId ?? ''), action: goalAct[1], text: body.text })); } catch (e) { return error(res, 400, e.message); }
1923  }
1924  // Plans (notes-split-agent6.md): the plan of a chat, and the instant actions. "Start as goal" streams, so it is /api/plan/start-goal below.
1925  if (path === '/api/plan' && method === 'GET') return json(res, 200, { plan: agent.planState(url.searchParams.get('sessionId') ?? url.searchParams.get('chatId') ?? '') });
1926  const planAct = /^\/api\/plan\/(approve|edit|reject)$/.exec(path);
1927  if (planAct && method === 'POST') {
1928    const body = await readBody(req);
1929    try { return json(res, 200, agent.planControl({ chatId: String(body.sessionId ?? body.chatId ?? ''), planId: typeof body.planId === 'string' ? body.planId : null, action: planAct[1], steps: body.steps, title: body.title })); }
1930    catch (e) { return error(res, e.code === 'plan-gone' || e.code === 'plan-used' ? 409 : 400, e.message); }
1931  }
1932  // Messages typed while a goal runs: queued (shown as queued), taken back, or listed.
1933  if (path === '/api/chat/queue' && method === 'GET') return json(res, 200, agent.takeQueue(url.searchParams.get('sessionId') ?? '', { release: url.searchParams.get('release') === '1' }));
1934  if (path === '/api/chat/queue' && method === 'POST') {
1935    const body = await readBody(req);
1936    try { return json(res, 200, agent.queueMessage({ chatId: String(body.sessionId ?? ''), text: body.message })); }
1937    catch (e) { return error(res, e.code === 'queue-idle' ? 409 : 400, e.message); }
1938  }
1939  // The person's answer to a question the agent asked, or a skip (#4244).
1940  if (path === '/api/chat/answer' && method === 'POST') {
1941    const body = await readBody(req);
1942    try { return json(res, 200, await agent.answerQuestion({ chatId: String(body.sessionId ?? ''), callId: String(body.callId ?? ''), answers: body.answers, skip: body.skip === true })); }
1943    catch (e) { return error(res, e.code === 'question-gone' ? 409 : 400, e.message); }
1944  }
1945  // A message for one helper (#4749).
1946  if (path === '/api/chat/helper' && method === 'POST') {
1947    const body = await readBody(req);
1948    try { return json(res, 200, await agent.messageHelper({ chatId: String(body.sessionId ?? ''), helperId: body.helperId, text: body.message, delivery: body.delivery })); }
1949    catch (e) { return error(res, e.code === 'helper-idle' || e.code === 'helper-refused' ? 409 : 400, e.message); }
1950  }
1951  if (path === '/api/chat/queue/cancel' && method === 'POST') {
1952    const body = await readBody(req);
1953    try { return json(res, 200, agent.cancelQueued({ chatId: String(body.sessionId ?? ''), id: String(body.id ?? '') })); }
1954    catch (e) { return error(res, e.code === 'queue-gone' ? 409 : 400, e.message); }
1955  }
1956  if (path === '/api/agent/tools' && method === 'GET') return json(res, 200, agentTools.view());
1957  if (path === '/api/agent/tools' && method === 'PUT') {
1958    try { return json(res, 200, agentTools.update(await readBody(req))); } catch (e) { return error(res, 400, e.message); }
1959  }
1960  if (path === '/api/agent/tools/custom' && method === 'POST') {
1961    try { return json(res, 200, agentTools.addCustom(await readBody(req))); } catch (e) { return error(res, 400, e.message); }
1962  }
1963  const customToolRoute = /^\/api\/agent\/tools\/custom\/([A-Za-z0-9_-]+)$/.exec(path);
1964  if (customToolRoute && method === 'PATCH') {
1965    try { return json(res, 200, agentTools.editCustom(customToolRoute[1], await readBody(req))); } catch (e) { return error(res, 400, e.message); }
1966  }
1967  if (customToolRoute && method === 'DELETE') {
1968    try { return json(res, 200, agentTools.removeCustom(customToolRoute[1])); } catch (e) { return error(res, 400, e.message); }
1969  }
1970  if (path === '/api/agent/pending' && method === 'GET') {
1971    const params = new URL(req.url, 'http://x').searchParams;
1972    // No chat named: every chat with an approval waiting (the task board lists them without opening each chat).
1973    if (!params.has('chatId')) return json(res, 200, { chats: agent.pendingAll() });
1974    return json(res, 200, { pending: agent.pendingFor(params.get('chatId') ?? '') });
1975  }
1976  /* Approve / Deny a tool the agent asked about. The answer reaches the Harness approval for exactly
1977     that chat and call; a stale or foreign id is refused. */
1978  if (path === '/api/chat/approval' && method === 'POST') {
1979    const b = await readBody(req);
1980    if (typeof b.sessionId !== 'string' || typeof b.toolId !== 'string' || !['approve', 'deny'].includes(b.decision)) return error(res, 400, 'sessionId, toolId and decision (approve or deny) are required');
1981    try { return json(res, 200, await agent.approve({ chatId: b.sessionId, callId: b.toolId, decision: b.decision })); }
1982    catch (e) { return error(res, e.code === 'approval-gone' ? 409 : 400, e.message); }
1983  }
1984  /* The desktop shell's own choices (#3402, #3477): the port it asks for, the tray, and a desktop notification through the shell. */
1985  if (path === '/api/locale' && method === 'GET') return json(res, 200, systemLocale());
1986  if (path === '/api/shell' && method === 'GET') return json(res, 200, shellState());
1987  if (path === '/api/shell/prefs' && method === 'POST') {
1988    const b = await readBody(req);
1989    try { writeShellPrefs(b); } catch (e) { return error(res, 400, e.message); }
1990    return json(res, 200, shellState());
1991  }
1992  if (path === '/api/shell/notify' && method === 'POST') {
1993    const b = await readBody(req);
1994    if (!shellNotifier || typeof b.title !== 'string') return json(res, 200, { shown: false });
1995    try { return json(res, 200, await shellNotifier.notify({ title: b.title, body: String(b.body ?? '') })); } catch { return json(res, 200, { shown: false }); }
1996  }
1997  /* The person changed the chat's mode while a turn runs: it applies to the next tool call, goal and helpers included. */
1998  if (path === '/api/chat/mode' && method === 'POST') {
1999    const b = await readBody(req);
2000    if (typeof b.sessionId !== 'string' || !['manual', 'plan', 'bypass'].includes(b.mode)) return error(res, 400, 'sessionId and mode (manual, plan or bypass) are required');
2001    try { return json(res, 200, await agent.setMode(b.sessionId, b.mode)); } catch (e) { return error(res, e.code === 'mode-unavailable' ? 409 : 502, e.message); }
2002  }
2003  /* A page that has just loaded asks which chats have a turn running (a reload does not stop a turn), and takes one over again: the catch-up
2004     of what was said while no page was there, then the live frames, as on /api/chat/stream. A turn that ended while the page was away
2005     (the page names it by requestId) is sent once, whole. 404 when there is nothing to take over. */
2006  if (path === '/api/chat/active' && method === 'GET') return json(res, 200, { turns: agent.runningTurns() });
2007  if (path === '/api/chat/attach' && method === 'POST') {
2008    const b = await readBody(req);
2009    if (typeof b.sessionId !== 'string' || !b.sessionId) return error(res, 400, 'sessionId is required');
2010    const controller = new AbortController();
2011    res.on('close', () => { if (!res.writableEnded) controller.abort(); });
2012    let started = false;
2013    const write = frame => {
2014      if (res.writableEnded || res.destroyed) return;
2015      if (!started) { started = true; res.writeHead(200, { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-cache, no-transform', connection: 'keep-alive' }); keepStreamAlive(res); }
2016      res.write(`${JSON.stringify(frame)}
2017`);
2018    };
2019    const attached = agent.attach({ chatId: b.sessionId, requestId: typeof b.requestId === 'string' ? b.requestId : null, onFrame: write, signal: controller.signal });
2020    if (!attached) return error(res, 404, 'There is no turn to take over.', { code: 'no-turn' });
2021    await Promise.race([attached.ended, new Promise(r => controller.signal.addEventListener('abort', r, { once: true }))]);
2022    if (!res.writableEnded) res.end();
2023    return undefined;
2024  }
2025  /* Stop one chat's turn. Resolves once the turn has really ended, not when the cancel was admitted. */
2026  if (path === '/api/chat/stop' && method === 'POST') {
2027    const b = await readBody(req);
2028    if (typeof b.sessionId !== 'string') return error(res, 400, 'sessionId is required');
2029    // A Time-skip trial of this chat is stopped by the same Stop button (and cleans up its copies).
2030    const trialId = trialByChat.get(b.sessionId);
2031    if (trialId) return json(res, 200, { stopped: await stopTrial(trialId), ended: 'time-skip' });
2032    try { return json(res, 200, await agent.stop(b.sessionId)); } catch (e) { return error(res, 502, e.message); }
2033  }
2034
2035  // --- chat ---------------------------------------------------------------
2036  if ((path === '/api/chat/stream' || path === '/api/plan/start-goal') && method === 'POST') {
2037    const body = await readBody(req,12*1024*1024);
2038    if (path === '/api/plan/start-goal') { body.message = '/plan start'; if (typeof body.planId !== 'string') return error(res, 400, 'planId is required'); }
2039    let images;try{const named=Array.isArray(body.imageIds)&&body.imageIds.length?uploads.dataUrls(typeof body.sessionId==='string'?body.sessionId:'',body.imageIds):[];images=validateChatImages([...(Array.isArray(body.images)?body.images:[]),...named]);}catch(e){return error(res,400,e.message);}
2040    if(images.length&&body.remoteModel){const own=modelProviders.withSecrets().find(c=>c.id===body.remoteModel.connectionId);const row=own?.models.find(m=>m.id===body.remoteModel.modelId);const refused=await pictureRefusal(own,row);if(refused)return error(res,409,refused);}
2041    else if(images.length){let selected;try{selected=native.resolveInstance(body.nativeModelId??native.state().defaultId);}catch(e){return error(res,409,e.message);}if(!selected.vision)return error(res,409,'This model was started without picture reading. Open Models, turn on Read pictures and load it again, or choose a model that reads pictures.');}
2042    // The goal bar's Resume has no words of its own: it is the same turn as "/goal resume".
2043    const message = body.goalAction === 'resume' ? '/goal resume' : String(body.message ?? '').trim();
2044    if (!message) return error(res, 400, 'message is required');
2045    /* Which workspace the caller is in, so a skill narrowed to one project
2046       does not fire in another. */
2047    const workspaceId = typeof body.workspaceId === 'string' ? body.workspaceId : null;
2048
2049    res.writeHead(200, {
2050      'content-type': 'application/x-ndjson; charset=utf-8',
2051      'cache-control': 'no-cache, no-transform',
2052      connection: 'keep-alive',
2053    });
2054    keepStreamAlive(res);   // #4878: a quiet turn stays open; the timer ends with the response
2055    const controller = new AbortController();
2056    res.on('close', () => { if (!res.writableEnded) controller.abort(); });
2057
2058    /* Agent turn, when the component is there and this request can use it. A client that disappears
2059       detaches from the turn (it keeps running in the Harness); Stop is its own request. */
2060    const chatId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId : null;
2061    const agentSkip = process.env.STRATA_AGENT === 'off' ? 'The agent is turned off (STRATA_AGENT=off).'
2062      : body.agent === false || body.tools === false ? 'This chat runs without the agent.'
2063      : !chatId ? 'This request did not name a chat.'
2064      : !(body.remoteModel || native.hasLive()) ? 'The agent needs a loaded Strata model or an API model.'
2065      : null;
2066    if (chatId && !agentSkip) {
2067      const capability = agent.status();
2068      if (capability.state !== 'unavailable') {
2069        const skipped = mcpSkippedNotices(capability.skippedServers);
2070        for (const notice of skipped) res.write(`${JSON.stringify({ type: 'notice', ...notice })}\n`);
2071        await runAgentTurn({ res, controller, chatId, body, message, workspaceId, images });
2072        res.end();
2073        return undefined;
2074      }
2075      res.write(`${JSON.stringify({ type: 'notice', code: 'agent-unavailable', message: `${capability.reason}`, ...(capability.detail ? { details: capability.detail } : {}) })}\n`);
2076    } else if (agentSkip && chatId && body.agent !== false && body.tools !== false && process.env.STRATA_AGENT !== 'off') {
2077      res.write(`${JSON.stringify({ type: 'notice', code: 'agent-skipped', message: agentSkip })}\n`);
2078    }
2079
2080    // A plain chat turn says what it is doing too (reading the message, thinking with a token count, writing).
2081    const plain = withPlainStatus(frame => { if (!res.writableEnded && !res.destroyed) res.write(`${JSON.stringify(frame)}\n`); });
2082    res.on('close', () => plain.dispose());
2083    await runTurn({
2084      message,
2085      history: Array.isArray(body.history) ? body.history : [],
2086      onFrame: plain,
2087      signal: controller.signal,
2088      req,
2089      client: 'Strata chat',
2090      workspaceId,
2091      sessionId: typeof body.sessionId === 'string' ? body.sessionId : null,
2092      remoteModel: body.remoteModel ?? null,
2093      nativeModelId:body.nativeModelId,
2094      images,useTools:body.useTools===true,thinking:body.thinking??'high',thinkingBudget:Number.isInteger(body.thinkingBudget)&&body.thinkingBudget>0?Math.min(body.thinkingBudget,262144):0,
2095    });
2096    res.end();
2097    return undefined;
2098  }
2099
2100  return error(res, 404, `No route for ${method} ${path}`);
2101}
2102
2103/* -------------------------------------------------- OpenAI-compatible API --- */
2104
2105async function openai(req, res, path, method) {
2106  if (!serving.authorized(req)) return error(res, 401, 'Invalid API key');
2107  if(native.state().instances.length){
2108    if(path==='/v1/models'&&method==='GET')return json(res,200,{object:'list',data:native.state().instances.filter(i=>i.status==='ready').map(i=>({id:i.apiModelId,object:'model',owned_by:'strata',meta:{instanceId:i.id,gpus:i.gpus,label:i.label,aliases:i.aliases}}))});
2109    if(method==='POST'&&['/v1/chat/completions','/v1/messages','/v1/responses'].includes(path)){if(store.get().serving?.pauseServing)return error(res,503,'New API requests are paused.');if(path==='/v1/responses'&&!native.state().capabilities.responses)return error(res,501,'Update the native Strata installation to use the Responses API.');return nativeGateway({req,res,path,body:await readBody(req,12*1024*1024),control:native,serving});}
2110  }
2111  if(path==='/v1/responses'&&method==='POST')return error(res,503,'Load a native Strata model to use the Responses API.');
2112
2113  if (path === '/v1/models' && method === 'GET') {
2114    const runtime=runtimeState();
2115    return json(res,200,{object:'list',data:runtime.instances.map(i=>({id:i.apiModelId,object:'model',created:Math.floor(new Date(i.loadedAt).getTime()/1000),owned_by:'strata',meta:{label:i.family,context:i.memory.context,instanceId:i.id,gpuIds:i.gpuIds,mode:runtime.mode}}))});
2116  }
2117
2118  if ((path === '/v1/chat/completions' || path === '/v1/messages') && method === 'POST') {
2119    if (store.get().serving?.pauseServing) return error(res, 503, 'New API requests are paused. Resume them in Serving.');
2120    const body = await readBody(req);
2121    const client = clientName(req);
2122    const anthropic = path === '/v1/messages';
2123    // An API client can say which workspace it is acting for; without it, a
2124    // skill narrowed to one project does not fire.
2125    const workspaceId = typeof body.workspaceId === 'string' ? body.workspaceId : null;
2126
2127    const messages = anthropic
2128      ? [
2129          ...(body.system ? [{ role: 'system', content: body.system }] : []),
2130          ...(body.messages ?? []),
2131        ]
2132      : (body.messages ?? []);
2133    const last = [...messages].reverse().find((m) => m.role === 'user');
2134    const text =
2135      typeof last?.content === 'string'
2136        ? last.content
2137        : Array.isArray(last?.content)
2138          ? last.content.map((c) => c.text ?? '').join(' ')
2139          : '';
2140
2141    if (!text) return error(res, 400, 'No user message found');
2142
2143    runtimeState();
2144    let loaded;
2145    try{loaded=runtimeModels.resolve(body.model);}
2146    catch(err){return error(res,409,err.message);}
2147    loaded={...loaded,id:loaded.apiModelId};
2148
2149    const id = uid('chatcmpl');
2150    const created = Math.floor(Date.now() / 1000);
2151    const wantsStream = body.stream === true;
2152    const started = Date.now();
2153    const controller = new AbortController();
2154    res.on('close', () => { if (!res.writableEnded) controller.abort(); });
2155
2156    if (!wantsStream) {
2157      let out = '';
2158      let usage = { tokensIn: null, tokensOut: null };
2159      const result = await runTurn({
2160        message: text,
2161        runtimeModelId:loaded.apiModelId,
2162        history: messages.slice(0, -1),
2163        onFrame: (frame) => {
2164          if (frame.type === 'delta') out += frame.text;
2165          if (frame.type === 'done') usage = { tokensIn: frame.tokensIn, tokensOut: frame.tokensOut };
2166        },
2167        client,
2168        req,
2169        workspaceId,
2170        signal: controller.signal,
2171      });
2172      if (result?.error) return error(res, 500, result.error);
2173      return anthropic
2174        ? json(res, 200, {
2175            id,
2176            type: 'message',
2177            role: 'assistant',
2178            model: loaded.id,
2179            content: [{ type: 'text', text: out }],
2180            usage: { input_tokens: usage.tokensIn, output_tokens: usage.tokensOut },
2181          })
2182        : json(res, 200, {
2183            id,
2184            object: 'chat.completion',
2185            created,
2186            model: loaded.id,
2187            choices: [{ index: 0, message: { role: 'assistant', content: out }, finish_reason: 'stop' }],
2188            usage: { prompt_tokens: usage.tokensIn, completion_tokens: usage.tokensOut, total_tokens: Number.isFinite(usage.tokensIn) && Number.isFinite(usage.tokensOut) ? usage.tokensIn + usage.tokensOut : null },
2189          });
2190    }
2191
2192    res.writeHead(200, {
2193      'content-type': 'text/event-stream; charset=utf-8',
2194      'cache-control': 'no-cache, no-transform',
2195      connection: 'keep-alive',
2196    });
2197    const write = (payload) => res.write(`data: ${JSON.stringify(payload)}\n\n`);
2198
2199    if (!anthropic) {
2200      write({ id, object: 'chat.completion.chunk', created, model: loaded.id, choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] });
2201    } else {
2202      res.write(`event: message_start\ndata: ${JSON.stringify({ type: 'message_start', message: { id, role: 'assistant', model: loaded.id } })}\n\n`);
2203    }
2204
2205    await runTurn({
2206      message: text,
2207      runtimeModelId:loaded.apiModelId,
2208      history: messages.slice(0, -1),
2209      workspaceId,
2210      onFrame: (frame) => {
2211        if (frame.type === 'delta') {
2212          if (anthropic) {
2213            res.write(`event: content_block_delta\ndata: ${JSON.stringify({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: frame.text } })}\n\n`);
2214          } else {
2215            write({ id, object: 'chat.completion.chunk', created, model: loaded.id, choices: [{ index: 0, delta: { content: frame.text }, finish_reason: null }] });
2216          }
2217        }
2218        if (frame.type === 'done' && !anthropic) {
2219          write({ id, object: 'chat.completion.chunk', created, model: loaded.id, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: frame.tokensIn, completion_tokens: frame.tokensOut } });
2220        }
2221        if (frame.type === 'error') {
2222          if (anthropic) res.write(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: 'api_error', message: frame.message } })}\n\n`);
2223          else write({ error: { message: frame.message, type: 'server_error' } });
2224        }
2225      },
2226      signal: controller.signal,
2227      client,
2228      req,
2229    });
2230
2231    if (anthropic) {
2232      res.write(`event: message_stop\ndata: ${JSON.stringify({ type: 'message_stop' })}\n\n`);
2233    } else {
2234      res.write('data: [DONE]\n\n');
2235    }
2236    res.end();
2237    void started;
2238    return undefined;
2239  }
2240
2241  return error(res, 404, `No route for ${method} ${path}`);
2242}
2243
2244/* ---------------------------------------------------------------- static --- */
2245
2246const MIME = {
2247  '.html': 'text/html; charset=utf-8',
2248  '.js': 'text/javascript; charset=utf-8',
2249  '.mjs': 'text/javascript; charset=utf-8',
2250  '.css': 'text/css; charset=utf-8',
2251  '.json': 'application/json; charset=utf-8',
2252  '.webmanifest': 'application/manifest+json; charset=utf-8',
2253  '.svg': 'image/svg+xml',
2254  '.woff2': 'font/woff2',
2255  '.png': 'image/png',
2256  '.jpg': 'image/jpeg',
2257  '.webp': 'image/webp',
2258  '.gif': 'image/gif',
2259  '.mp4': 'video/mp4',
2260  '.webm': 'video/webm',
2261  '.ico': 'image/x-icon',
2262  '.map': 'application/json; charset=utf-8',
2263  '.pdf': 'application/pdf',
2264  '.md': 'text/markdown; charset=utf-8',
2265};
2266
2267async function staticFile(req, res, path) {
2268  if (!existsSync(DIST)) {
2269    res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
2270    res.end(
2271      `<!doctype html><meta charset="utf-8"><title>Strata</title>
2272       <body style="font:16px/1.6 -apple-system,system-ui;background:#0e1113;color:#eef1f3;padding:48px">
2273       <h1 style="margin:0 0 8px">Strata host is running</h1>
2274       <p style="color:#8e979f">No built web app found at <code>${DIST}</code>.</p>
2275       <p>For development run <code>npm run dev</code> (Vite on :5199 proxies /api here).<br>
2276       For a single port run <code>npm run build:web &amp;&amp; npm run serve</code>.</p>
2277       <p style="color:#8e979f">API: <a style="color:#4ade80" href="/api/health">/api/health</a> ·
2278       <a style="color:#4ade80" href="/api/hardware">/api/hardware</a> ·
2279       <a style="color:#4ade80" href="/v1/models">/v1/models</a></p></body>`,
2280    );
2281    return;
2282  }
2283
2284  const safe = normalize(path).replace(/^(\.\.[/\\])+/, '');
2285  let file = join(DIST, safe);
2286  if (!file.startsWith(DIST)) return error(res, 403, 'Forbidden');
2287
2288  if (!existsSync(file) || statSync(file).isDirectory()) {
2289    if (extname(path)) return error(res, 404, 'Asset not found');
2290    const index = join(DIST, 'index.html');
2291    if (!existsSync(index)) return error(res, 404, 'Not found');
2292    file = index;
2293  }
2294
2295  const type = MIME[extname(file)] ?? 'application/octet-stream';
2296  const size=statSync(file).size;
2297  const headers={'content-type':type,'cache-control':file.endsWith('index.html')?'no-store':'public, max-age=3600','accept-ranges':'bytes'};
2298  if(req.headers.range) {
2299    const match=/^bytes=(\d*)-(\d*)$/.exec(req.headers.range);
2300    const start=match?.[1]?Number(match[1]):match?.[2]?Math.max(0,size-Number(match[2])):NaN;
2301    const end=match?.[1]&&match[2]?Math.min(size-1,Number(match[2])):size-1;
2302    if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start>end||start<0||start>=size){res.writeHead(416,{'content-range':`bytes */${size}`});res.end();return;}
2303    res.writeHead(206,{...headers,'content-range':`bytes ${start}-${end}/${size}`,'content-length':end-start+1});
2304    if(req.method==='HEAD')res.end();else createReadStream(file,{start,end}).pipe(res);
2305    return;
2306  }
2307  res.writeHead(200,{...headers,'content-length':size});
2308  if(req.method==='HEAD')res.end();else createReadStream(file).pipe(res);
2309}
2310
2311/* ------------------------------------------------------------------ start --- */
2312
2313server.on('error', error => {
2314  if (server.listening) { console.error(`[strata] ${error.message}`); return; }
2315  // a taken or Windows-reserved port: one plain sentence instead of a stack trace
2316  console.error(`[strata] ${listenProblem(error, PORT, HOST)}`);
2317  process.exit(1);
2318});
2319server.listen(PORT, HOST, () => {
2320  if (process.send) process.send({ type: 'strata-ready', port: PORT });
2321  // Engines a lost owner left behind (an earlier crash, an older version): ended after a PID + start time + command-line check.
2322  if (control && process.env.STRATA_PACKAGED === '1') control.cleanup().catch(() => {});
2323});
2324
2325let stopping=false;
2326const shutdown = async () => {
2327  if(stopping)return;stopping=true;
2328  clearInterval(taskTimer);tasks.close();
2329  const timeout=setTimeout(()=>process.exit(0),control?45000:10000);timeout.unref();   // stopping an engine through Control: drained (15 s), then ended; the shell's deadline is longer
2330  server.close();server.closeAllConnections?.();
2331  await Promise.allSettled([localShare.stop(),cloudflare.stop(),native.close(),agent.close()]);
2332  process.exit(0);
2333};
2334// Every ordinary way of being told to stop takes the clean path: Ctrl+C, kill, the terminal closing (SIGHUP), Ctrl+Break.
2335for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK']) { try { process.on(signal, shutdown); } catch { /* not on this platform */ } }
2336// Started by the desktop shell: when the shell is gone (killed, crashed, logged off) stop what this app started and leave.
2337// POSIX re-parents us (ppid changes); Windows keeps the old ppid, so the pid is probed (signal 0 never signals).
2338if (process.env.STRATA_EXIT_WITH_PARENT === '1') {
2339  const parent = process.ppid;
2340  const gone = () => {
2341    if (process.ppid !== parent) return true;
2342    try { process.kill(parent, 0); return false; } catch (e) { return e.code === 'ESRCH'; }
2343  };
2344  setInterval(() => { if (gone()) void shutdown(); }, 1000).unref();
2345}
2346
2347export { server, VARIANTS };