okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f5ef26889
main
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 107directory, so `process.cwd()` was "host" in the sidebar and the agent could read and write the app): the person's own 108Documents\Strata\Workspace (the models folder is next to it, not in it), created on first use, unless STRATA_WORKSPACE names one. */ 109function defaultWorkspace () { 110if ( process . env . STRATA_WORKSPACE ) return resolve ( process . env . STRATA_WORKSPACE ); 111const user = process . env . USERPROFILE ?? process . env . HOME ?? homedir (); 112for ( const base of [ join ( user , 'Documents' ), user ]) { 113const dir = join ( base , 'Strata' , 'Workspace' ); 114try { mkdirSync ( dir , { recursive :true }); return dir ; } catch { /* try the next place */ } 115} 116return 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 () { 141const saved = readShellPrefs (); 142const desktop = !! shellNotifier ; 143return { 144 desktop, 145tray :desktop && process . platform !== 'linux' , 146port :PORT , defaultPort :DEFAULT_PORT , 147pinnedPort :saved . port || null , minimizeToTray :saved . tray , 148portNotice :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 ) { 164const engineOf = control . engine . bind ( control ); 165control . engine = async ( ...args ) => { 166const answer = await engineOf ( ...args ); 167return 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 172pinned component (STRATA_HARNESS_DIR), not part of this host, so its absence is a visible capability 173state 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 ) { 181const secrets = new Map ( modelProviders . withSecrets (). map ( c => [ c . id , c ])); 182const connections = ( list . connections ?? []). map ( c => ({ ...c , models :c . models . map ( m => { 183const asked = visionProbe . known ( c , m . id ); 184if (( 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). 186return { ...m , reads :readsPicturesByDefault ( m , asked ), thinks :m . reasoning ?? visionProbe . knownThinks ( c , m . id ) ?? null }; 187}) })); 188return { ...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 ) { 192if ( ! connection || ! model ) return 'This API model is no longer available. Choose another model in the chat picker.' ; 193if ( 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. 195if ( readsPicturesByDefault ( model , await visionProbe . check ( connection , model . id ))) return null ; 196const fix = `open Settings → Models, edit " ${ connection . name } " and turn on "Read pictures with this model"` ; 197return `" ${ 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 ({ 200tools :() => agentTools . profileView (), 201skillsDir :() => AGENT_SKILLS , 202onGoal :( 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. 204proxyBase :`http://127.0.0.1: ${ PORT } /api/internal/agent-llm` , 205expertSampling :() => 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. 207engineProgress :instanceId => engineProgressMark ( native . readyInstances (). find ( i => i . id === instanceId )), 208onPlan :( chatId , event , plan ) => hub . send ( 'plan' , { chatId, event, plan}), 209onQueue :( chatId , queue ) => hub . send ( 'queue' , { chatId, queue}), 210dataDir :store . DATA_DIR , 211componentsDir :componentsDirectory (), 212// The installer ships the Harness next to the host (<install>/host/server -> <install>/harness). 213bundledDir :resolve ( HERE , '..' , '..' , 'harness' ), 214defaultLocalId :() => native . defaultInstanceId (), 215localInstances :() => native . readyInstances (). map ( i => ({ 216id :i . id , label :i . label , baseUrl :`http://127.0.0.1: ${ i . port } /v1` , modelId :i . apiModelId , 217context :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. 219slots :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. 221mcpServers :i . mcpServers , 222})), 223connections :() => 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 })) })), 224log :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 ) => { 233if ( event === 'engine-status' ) rawSend ( 'engine-status' , payload ); 234else if ( event === 'engine-log' ) rawSend ( 'log' , payload ); 235else if ( event === 'models' && runtimeModels ){ 236runtimeModels . adopt ( payload . loaded ,{ beginner :store . get (). beginner , expert :engine . params (), extra :store . get (). configExtra ?? {}}); 237rawSend ( '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 => { 251if ( ! 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 });} 252rawSend ( '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 (){ 256if ( models . REAL ) runtimeModels . adopt ( models . library (). loaded ,{ beginner :store . get (). beginner , expert :engine . params (), extra :store . get (). configExtra ?? {}}); 257return 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 261GGUF 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 () { 275const s = store . get (); 276return { 277complete :!! s . setup . complete , 278dismissed :!! s . setup . dismissed , 279choices :s . setup . choices ?? {}, 280step :s . setup . step ?? 1 , 281flowVersion :2 , 282completedAt :s . setup . completedAt , 283history :s . setup . history ?? [], 284app :{ 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 () { 294const bundled = [ 295{ 296id :'commit-messages' , 297body :`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.` , 305name :'Commit messages' , 306description :'Writes conventional-commit messages from a diff, with a scope line and a why-paragraph.' , 307source :'bundled' , 308enabled :true , 309triggers :[ 'commit' , 'git message' , 'stage these changes' ], 310sizeKb :3.2 , 311}, 312{ 313id :'code-review' , 314body :`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.` , 322name :'Code review' , 323description :'Reviews a file or diff for correctness first, style second, and reports findings with line numbers.' , 324source :'bundled' , 325enabled :true , 326triggers :[ 'review this' , 'find bugs' , 'check my code' ], 327sizeKb :5.6 , 328}, 329{ 330id :'release-notes' , 331body :`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.` , 339name :'Release notes' , 340description :'Turns merged commits into user-facing release notes grouped by feature, fix and breaking change.' , 341source :'bundled' , 342enabled :false , 343triggers :[ 'release notes' , 'changelog' , 'what shipped' ], 344sizeKb :2.8 , 345}, 346{ 347id :'hardware-report' , 348body :`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.` , 357name :'Hardware report' , 358description :'Explains what this machine can run, in plain language, from the detected CPU, GPU and memory.' , 359source :'bundled' , 360enabled :true , 361triggers :[ 'can this run' , 'my hardware' , 'how fast' ], 362sizeKb :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. 368const extra = []; 369for ( const [ dir , source , prefix ] of [[ CREATED_SKILLS , 'created' , 'my-' ], [ join ( WORKSPACE , 'skills' ), 'workspace' , 'ws-' ]]) { 370if ( ! existsSync ( dir ) || ! statSync ( dir ). isDirectory ()) continue ; 371for ( const name of readdirSync ( dir )) { 372const full = join ( dir , name ); 373try { if ( ! statSync ( full ). isDirectory ()) continue ; } catch { continue ; } 374let text = '' , sizeKb = 1 ; 375const md = join ( full , 'SKILL.md' ); 376try { 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 */ } 377const parsed = parseSkillFile ( text ); 378extra . push ({ 379id :` ${ prefix } ${ name } ` , 380name :parsed . title ?? name . replace ( / - / g , ' ' ). replace ( / ^. / , c => c . toUpperCase ()), 381description :parsed . description ?? ( source === 'created' ?'A skill you wrote.' :`Workspace skill loaded from ${ name } /SKILL.md` ), 382 source, 383enabled :true , 384triggers :[ name . replace ( / - / g , ' ' )], 385body :parsed . body , 386sizeKb :Number ( sizeKb . toFixed ( 1 )), 387}); 388} 389} 390return [ ...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". 398enabled :store . get (). skillPreferences ?.[ s . id ]?. enabled ?? s . enabled , 399onlyIn :store . get (). skillPreferences ?.[ s . id ]?. onlyIn ?? null , 400useCount :0 , 401lastUsedAt :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 () { 409try { 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 ) { 422const hit = new Set ( selected . map ( s => s . id )); 423skillState = skillState . map (( s ) => { 424if ( ! hit . has ( s . id )) return s ; 425return { ...s , useCount :( s . useCount ?? 0 ) + 1 , lastUsedAt :new Date (). toISOString () }; 426}); 427if ( hit . size ) hub . send ( 'skills' , skillState ); 428} 429 430const execFileAsync = promisify ( execFile ); 431 432/* ---------------------------------------------------------------- prompt --- 433What Strata puts in front of every conversation. Counted so the context 434breakdown can show where the window actually goes rather than reporting a 435single 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 ) { 447const out = []; 448const walk = ( dir , at ) => { 449if ( at > depth || out . length > 60 ) return ; 450let entries ; 451try { 452entries = readdirSync ( dir , { withFileTypes :true }); 453} catch { 454return ; 455} 456for ( const e of entries ) { 457if ( out . length > 60 ) return ; 458if ( e . name . startsWith ( '.' ) || e . name === 'node_modules' ) continue ; 459const full = join ( dir , e . name ); 460const rel = full . slice ( root . length + 1 ); 461if ( e . isDirectory ()) walk ( full , at + 1 ); 462else if ( / \. ( md | txt | json | ts | tsx | mjs | js | css ) $ / . test ( e . name )) out . push ( rel ); 463} 464}; 465walk ( root , 0 ); 466return out ; 467} 468 469/* ------------------------------------------------------------- workspaces --- 470The host used to expose exactly one root, taken from the environment. A 471sidebar that offers "add a workspace" over a single-root host would be a lie, 472so the roots are now a small persisted registry. The original root is always 473first and cannot be removed, which keeps existing sessions and file paths 474valid. */ 475const WORKSPACES_FILE = join ( store . DATA_DIR , 'workspaces.json' ); 476 477function loadWorkspaces () { 478try { 479const parsed = JSON . parse ( readFileSync ( WORKSPACES_FILE , 'utf8' )); 480if ( 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. 482if ( 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 }; 483return parsed ; 484} 485} catch { 486/* first run */ 487} 488return [{ 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 () { 502try { 503mkdirSync ( store . DATA_DIR , { recursive :true }); 504writeFileSync ( WORKSPACES_FILE , JSON . stringify ( workspaces , null , 2 )); 505} catch ( err ) { 506console . 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 ) { 513const entries = []; 514const walk = ( dir , prefix = '' , depth = 0 ) => { 515if ( depth > 2 ) return ; 516let names = []; 517try { 518names = readdirSync ( dir ); 519} catch { 520return ; 521} 522for ( const name of names . slice ( 0 , 60 )) { 523if ( SKIP_DIRS . has ( name ) || name . startsWith ( '.DS' )) continue ; 524const full = join ( dir , name ); 525let st ; 526try { 527st = statSync ( full ); 528} catch { 529continue ; 530} 531const rel = prefix ?` ${ prefix } / ${ name } ` :name ; 532if ( st . isDirectory ()) { 533entries . push ({ path :rel , kind :'dir' }); 534walk ( full , rel , depth + 1 ); 535} else { 536entries . push ({ path :rel , kind :'file' , sizeKb :st . size / 1024 , updatedAt :st . mtime . toISOString () }); 537} 538} 539}; 540walk ( root ); 541entries . sort (( a , b ) => 542a . kind === b . kind ?a . path . localeCompare ( b . path ) :a . kind === 'dir' ?- 1 :1 , 543); 544return { path :root , entries}; 545} 546 547/* ----------------------------------------------------------------- chat io --- */ 548 549function clientName ( req ) { 550const ua = req . headers [ 'user-agent' ] ?? '' ; 551const header = req . headers [ 'x-strata-client' ]; 552if ( typeof header === 'string' && header ) return header ; 553if ( / curl / i . test ( ua )) return 'curl' ; 554if ( / python | httpx | requests / i . test ( ua )) return 'Python client' ; 555if ( / node | undici | axios / i . test ( ua )) return 'Node client' ; 556if ( / strata / i . test ( ua )) return 'Strata chat' ; 557return 'Local client' ; 558} 559 560async function runRemoteTurn ({ selection, message, history, images= [], thinking, onFrame, signal, workspaceId}) { 561const controller = new AbortController (); 562const requestSignal = signal ?AbortSignal . any ([ signal , controller . signal ]) :controller . signal ; 563let entry ; 564const started = Date . now (); 565try { 566const { connection, model} = modelProviders . resolve ( selection ); 567if ( connection . protocol === 'openai-chat' && model . reasoning == null ) await visionProbe . check ( connection , model . id ); 568const appliedSkills = selectSkills ( skillState , message , workspaceId ); 569entry = 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' )) }); 570serving . mark ( entry . id , { state :'generating' }); 571const 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 => { 572if ( frame . type === 'start' ) noteSkillUse ( appliedSkills ); 573if ( frame . type === 'done' ) serving . mark ( entry . id , { tokensIn :frame . tokensIn , tokensOut :frame . tokensOut , usageSource :frame . usageSource }); 574onFrame ({ ...frame , requestId :entry . id , model :model . name , contextMax :model . contextMax , remoteModel :true , ...( frame . type === 'start' ?{ skills :appliedSkills . map ( s => s . name ) } :{}) }); 575} }); 576serving . mark ( entry . id ,{ tps :result . tps ?? null }); 577serving . finish ( entry . id , { tokensOut :result . tokensOut , durationMs :Date . now () - started }); 578return result ; 579} catch ( err ) { 580const 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.' :'' ; 581const message = requestSignal . aborted ?'Request cancelled. Partial output is preserved.' :err . name === 'TimeoutError' ?'The model API timed out. Try again.' :err . message + refusedPicture ; 582if ( entry ) serving . finish ( entry . id , { durationMs :Date . now () - started , error :message }); 583onFrame ({ type :'error' , message, requestId :entry ?. id }); 584return { 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= [] }) { 590const write = frame => { if ( ! res . writableEnded && ! res . destroyed ) res . write ( ` ${ JSON . stringify ( frame )} \n` ); }; 591const cwd = chatFolders . get ( chatId ) ?? ( workspaceId ?workspaces . find ( w => w . id === workspaceId )?. path :null ) ?? WORKSPACE ; 592let choice , instance = null ; 593if ( body . remoteModel ) { 594choice = { 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. 596const own = modelProviders . withSecrets (). find ( c => c . id === choice . connectionId ); 597if ( own && own . protocol === 'openai-chat' ) await visionProbe . check ( own , choice . modelId ); 598} 599else { 600try { instance = native . resolveInstance ( body . nativeModelId ?? native . state (). defaultId ); } 601catch ( e ) { write ({ type :'error' , message :plainNoModel ( e . message ) }); return ; } 602choice = { instanceId :instance . id }; 603} 604const started = Date . now (); 605// A turn the engine is serving must be visible to the rest of the host (Serving, unload guards). 606const 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 ; 607if ( entry ) serving . mark ( entry . id , { state :'generating' }); 608const settle = ( tokensOut , error ) => { if ( entry ) serving . finish ( entry . id , { tokensOut, durationMs :Date . now () - started , ...( error ?{ error} :{}) }); }; 609try { 610// "/goal ..." is the Harness's goal command (set, show, pause, resume, clear); everything else is a message. 611const attached = chatAttachments . take ( chatId ); 612if ( attached . length && ! /^\/ / . test ( message . trim ())) message = withAttachments ( message , attached ); 613const goalLine = / ^\/goal (?: \s + ([ \s\S ] * )) ? $ / i . exec ( message . trim ()); 614const planLine = / ^\/plan (?: \s + ([ \s\S ] * )) ? $ / i . exec ( message . trim ()); 615const 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). 617const compactLine = / ^\/compact\s * $ / i . test ( message . trim ()); 618const 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 }; 619const 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 ); 624if ( result ?. detached ) void result . ended . then ( r => settle ( r ?. tokensOut ?? null ), () => settle ( null )); 625else settle ( result ?. tokensOut ?? null , result ?. error ?'The agent turn failed.' :undefined ); 626} catch ( err ) { 627const plain = plainTurnFailure ( err ); 628write ({ type :'error' , message :plain . message , ...( plain . details ?{ details :plain . details } :{}), code :plain . code }); 629settle ( 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 }) { 634if ( remoteModel ) return runRemoteTurn ({ selection :remoteModel , message, history, images, thinking, onFrame, signal, workspaceId}); 635if ( native . hasLive () || nativeModelId ){ 636let 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 (); 637const entry = serving . open ({ client :client ?? 'Strata chat' , endpoint :'/chat/completions' , model :instance . apiModelId , instanceId :instance . id , gpuIds :instance . gpus . map ( String ), cancel :() => cancel . abort ()}); 638try { 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} 640runtimeState (); 641let instance ; 642try { instance = runtimeModels . resolve ( runtimeModelId ,{ chatDefault :runtimeModelId === undefined });} 643catch ( err ){ onFrame ({ type :'error' , message :err . message }); return { error :err . message };} 644const v = variant ( instance . variantId ); 645 646if ( ! v ) { 647onFrame ({ type :'error' , message :'No model is loaded. Pick one in Models, then try again.' }); 648return ; 649} 650 651const controller = new AbortController (); 652const requestSignal = signal ?AbortSignal . any ([ signal , controller . signal ]) :controller . signal ; 653const 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' )) }); 654const started = Date . now (); 655let result = { tokensIn :null , tokensOut :null }; 656// Time to first token: the gap between asking and the first token arriving. 657let firstTokenMs = null ; 658 659try { 660onFrame ({ type :'queued' , requestId :entry . id }); 661await ( models . REAL ?requestQueue :runtimeModels . queue ( instance . id )). run ( requestSignal , async () => { 662requestSignal . throwIfAborted (); 663if ( ! runtimeModels . state (). instances . some ( i => i . id === instance . id )) throw new Error ( 'This model was unloaded before dispatch.' ); 664runtimeModels . 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. 667const appliedSkills = selectSkills ( skillState , message , workspaceId ); 668const systemPrompt = [ SYSTEM_PROMPT , skillInstructions ( appliedSkills )]. filter ( Boolean ). join ( '\n\n' ); 669serving . mark ( entry . id , { state :'generating' }); 670const contextMax = instance . memory . context ; 671const modelMonitor = models . REAL ?monitor :{ 672progressOutput :() => {}, 673beginReading :( total ) => runtimeModels . update ( instance . id ,{ phase :'reading' , prompt :{ done :0 , total, pct :0 }}), 674progressReading :( 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 }});}, 675beginGenerating :() => runtimeModels . update ( instance . id ,{ phase :'generating' }), 676beginThinking :() => runtimeModels . update ( instance . id ,{ phase :'thinking' }), 677}; 678try { 679result = await streamChat ({ 680 message, 681 history, 682 systemPrompt, 683modelLabel :v . label , 684candidates :readableCandidates (), 685onFrame :( frame ) => { 686if ( 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. 692if ( firstTokenMs === null && ( frame . type === 'delta' || frame . type === 'reasoning' )) { 693firstTokenMs = Date . now () - started ; 694} 695if ( frame . type === 'done' && typeof frame . ttftMs === 'number' ) firstTokenMs = frame . ttftMs ; 696if ( frame . type === 'start' ) { 697// Demo responses cannot demonstrate that instructions affected a model. 698if ( ! frame . demo ) noteSkillUse ( appliedSkills ); 699serving . mark ( entry . id , { tokensIn :frame . promptTokens ?? null , usageSource :frame . demo ?'demo' :'unavailable' }); 700} 701if ( frame . type === 'done' ) { 702serving . mark ( entry . id , { tokensIn :frame . tokensIn , tokensOut :frame . tokensOut , usageSource :frame . usageSource }); 703} 704onFrame ({ ...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}, 706signal :requestSignal , 707engine :{ 708variantId :v . id , 709beginReading :( tokens , id ) => modelMonitor . beginReading ( tokens , id ), 710progressReading :( done ) => modelMonitor . progressReading ( done ), 711beginGenerating :() => modelMonitor . beginGenerating (), 712beginThinking :() => modelMonitor . beginThinking (), 713}, 714}); 715requestSignal . throwIfAborted (); 716serving . 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 }); 717serving . finish ( entry . id , { 718tokensOut :result . tokensOut , 719durationMs :Date . now () - started , 720}); 721runtimeModels . 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 }}); 722if ( models . REAL ) monitor . record ({ 723tokensIn :result . tokensIn , 724tokensOut :result . tokensOut , 725durationMs :Date . now () - started , 726ttftMs :firstTokenMs ?? undefined , 727cachedTokens :result . cachedTokens , 728tps :result . tps , 729usageSource :result . usageSource , 730}); 731if ( models . REAL ){ monitor . setRecordedContext ({ ...result , requestId :entry . id , sessionId}); monitor . idle ();} 732} catch ( error ) { 733runtimeModels . update ( instance . id ,{ phase :'idle' }); 734if ( models . REAL ) monitor . idle ( requestSignal . aborted ?'Request cancelled' :'Last request failed' ); 735throw error ; 736} 737}); 738return result ; 739} catch ( err ) { 740const message = requestSignal . aborted ?'Request cancelled. Partial output is preserved.' :err . message ; 741serving . finish ( entry . id , { durationMs :Date . now () - started , error :message }); 742onFrame ({ type :'error' , message, requestId :entry . id }); 743return { 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 ) { 772const trial = trials . get ( run . id ); 773switch ( run . phase ) { 774case 'queued' :case 'checkpointing' :return { code :'reading-files' , text :'Reading your files…' }; 775case '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 } :{}) } } :{}) }; 776case 'checking' :return { code :'checking-result' , text :'Checking the result…' }; 777case 'decision' :return { code :'comparing' , text :'Comparing the two versions…' }; 778default :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 ) { 783const trial = trials . get ( id ); 784if ( ! trial ) return ; 785const timer = setInterval (() => { 786const run = timeskip . status ( id ); 787if ( ! run ) { clearInterval ( timer ); return ; } 788const activity = trialActivity ( run ); 789const key = JSON . stringify ([ run . phase , activity ]); 790if ( key !== trial . lastSent ) { trial . lastSent = key ; hub . send ( 'timeskip' , { id, phase :run . phase , activity}); } 791if ([ 'completed' , 'cancelled' , 'failed' , 'interrupted' ]. includes ( run . phase )) { clearInterval ( timer ); trials . delete ( id ); if ( trial . chatId ) trialByChat . delete ( trial . chatId ); } 792}, 2000 ); 793timer . unref ?.(); 794trial . 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 ) { 798const trial = trials . get ( id ); 799if ( trial ) { trial . controller ?. abort (); if ( trial . turnChat ) void agent . stop ( trial . turnChat ). catch (() => {}); } 800const stopped = await timeskip . stop ( id ); 801if ( trial ) { clearInterval ( trial . timer ); trials . delete ( id ); if ( trial . chatId ) trialByChat . delete ( trial . chatId ); } 802if ( stopped ) hub . send ( 'timeskip' , { id, phase :'cancelled' , activity :null }); 803return 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 } = {}) { 820const cli = join ( repoRoot , 'strata.py' ); 821const stateDir = () => tuningDir ( env ); 822 823function runCli ( args ) { 824return new Promise (( resolve ) => { 825const child = spawn ( python , [ ...pythonArgs , cli , ...args , '--output' , 'json' ], { 826cwd :repoRoot , windowsHide :true , env :{ ...env , PYTHONUTF8 :'1' , PYTHONIOENCODING :'utf-8' , STRATA_TUNE_DIR :stateDir () }, 827stdio :[ 'ignore' , 'pipe' , 'pipe' ], 828}); 829let out = '' , err = '' ; 830child . stdout . on ( 'data' , ( b ) => { out += b . toString (); }); 831child . stderr . on ( 'data' , ( b ) => { err += b . toString (); }); 832child . on ( 'error' , ( e ) => resolve ({ ok :false , error :e . message })); 833child . on ( 'close' , ( code ) => { 834let parsed = null ; 835try { parsed = JSON . parse ( out . trim (). split ( '\n' ). filter ( Boolean ). pop () ?? '' ); } catch { parsed = null ; } 836if ( ! parsed ) return resolve ({ ok :false , code, error :err . trim () || out . trim () || `exit ${ code } ` }); 837resolve ({ ok :Boolean ( parsed . ok ), code, envelope :parsed }); 838}); 839}); 840} 841 842return { 843 stateDir, 844/** The reviewable plan for one backend/engine pair. */ 845async plan ({ engine, backend, model, objective= 'generation' , trials= 16 , repeats= 3 }) { 846if ( ! engine || ! backend ) return { ok :false , code :2 , error :'engine and backend are required' }; 847const 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 )))]); 851return 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. */ 854jobs () { 855const root = stateDir (); 856if ( ! existsSync ( root )) return []; 857const out = []; 858for ( const entry of readdirSync ( root , { withFileTypes :true })) { 859if ( ! entry . isDirectory ()) continue ; 860const file = join ( root , entry . name , 'job.json' ); 861if ( ! existsSync ( file )) continue ; 862try { 863const data = JSON . parse ( readFileSync ( file , 'utf8' )); 864out . push ({ 865id :data . id , state :data . state , 866backend :data . plan ?. backend ?? null , objective :data . plan ?. objective ?? null , 867trials :data . report ?. trials_run ?? null , 868recommendation :data . report ?. recommendation_available === true , 869reason :data . report ?. reason ?? null , 870startedAt :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} 876return out ; 877}, 878job ( id ) { 879if ( ! /^ [ 0 - 9a - f ]{ 8 , 64 } $ / . test ( String ( id ?? '' ))) return null ; 880const file = join ( stateDir (), id , 'job.json' ); 881if ( ! existsSync ( file )) return null ; 882try { 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 ({ 892repoRoot :REPO_ROOT , 893python :TS_PYTHON , 894pythonArgs :PYTHON . args , 895env :{ ...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.) 901choice :() => { 902try { return { instanceId :native . resolveInstance ( native . state (). defaultId ). id }; } catch { /* no local model is ready */ } 903const [ connectionId , ...rest ] = String ( process . env . STRATA_TASK_REMOTE_MODEL ?? '' ). split ( ':' ); 904return connectionId && rest . length ?{ connectionId, modelId :rest . join ( ':' ) } :null ; 905}, 906}); 907const tasks = createTaskService ({ 908read :() => store . get (). tasks ?? [], 909write :records => store . update ({ tasks :records }), 910notify :task => hub . send ( 'task' , { id :task . id , title :task . title , status :task . status , attention :task . attention ?? null , error :task . error ?? null }), 911run :async ( task , signal ) => { 912if ( agent . status (). state !== 'unavailable' ) { const agentResult = await runAgentTask ( task , signal ); if ( agentResult ) return agentResult ; } 913let text = '' , failure = null , demo = ! models . REAL ; 914await runTurn ({ message :task . prompt , signal, client :`Task: ${ task . title } ` , onFrame :frame => { 915if ( frame . type === 'delta' ) text += frame . text ?? '' ; 916if ( frame . type === 'start' ) demo = !! frame . demo ; 917if ( frame . type === 'error' ) failure = frame . message ; 918}}); 919if ( failure ) throw new Error ( failure ); 920signal . throwIfAborted (); 921if ( ! text ) throw new Error ( 'The model returned no answer.' ); 922return { 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 ) => { 942const url = requestUrl ( req ); 943if ( ! url ) return badRequest ( res ); // #4397: a bad Host or request target is a 400, never an unhandled rejection 944const path = url . pathname ; 945const method = req . method ?? 'GET' ; 946 947res . setHeader ( 'access-control-allow-origin' , '*' ); 948res . setHeader ( 'access-control-allow-headers' , 'content-type, authorization, x-api-key, x-strata-client' ); 949res . setHeader ( 'access-control-allow-methods' , 'GET, POST, PATCH, DELETE, OPTIONS' ); 950if ( method === 'OPTIONS' ) { 951res . writeHead ( 204 ); 952res . end (); 953return ; 954} 955 956try { 957if ( path . startsWith ( '/api/' ) && req . headers . origin ) { 958const origin = new URL ( req . headers . origin ); 959if ( ! [ 'localhost' , '127.0.0.1' , '[::1]' ]. includes ( origin . hostname )) return error ( res , 403 , 'Open the local Strata app to use host controls.' ); 960} 961if ( path . startsWith ( '/api/' )) { 962const 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 ); 963if ( modelOperation ) modelOperations ++ ; 964try { return await api ( req , res , path , method , url ); } 965finally { if ( modelOperation ) modelOperations -- ; } 966} 967if ( path . startsWith ( '/v1/' )) { 968if ( storageChanging && method !== 'GET' ) return error ( res , 409 , 'Wait for the model folder check to finish.' ); 969return await openai ( req , res , apiPath ( path ), method ); 970} 971return await staticFile ( req , res , path ); 972} catch ( err ) { 973console . error ( '[strata]' , err ); 974if ( 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) 975error ( res , 500 , err . message ?? 'Internal error' ); 976} 977}); 978 979async function api ( req , res , path , method , url ) { 980if ( 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. 984const chatsRoute = / ^\/api\/chats (?: \/ ([ ^ / ] + )) ? $ / . exec ( path ); 985if ( chatsRoute ) { 986if ( ! req . headers [ 'x-strata-client' ]) return error ( res , 403 , 'Not allowed.' ); 987let id = null ; 988try { id = chatsRoute [ 1 ] ?decodeURIComponent ( chatsRoute [ 1 ]) :null ; } catch { return error ( res , 400 , 'That is not a chat id.' , { code :'bad-id' }); } 989const from = typeof req . headers [ 'x-strata-window' ] === 'string' ?req . headers [ 'x-strata-window' ]. slice ( 0 , 64 ) :null ; 990try { 991if ( ! id && method === 'GET' ) return json ( res , 200 , chatStore . list ()); 992if ( id === 'import' && method === 'POST' ) { 993const body = JSON . parse (( await readRaw ( req , 512 * 1024 * 1024 )). toString ( 'utf8' ) || '{}' ); 994const result = await chatStore . importMany ( body . sessions ); 995for ( const imported of result . imported ) hub . send ( 'chats' , { id :imported , rev :chatStore . rev ( imported ), from}); 996return json ( res , 200 , result ); 997} 998if ( id && method === 'GET' ) { 999const text = await chatStore . read ( id ); 1000if ( text === null ) return error ( res , 404 , 'No such chat.' , { code :'not-found' }); 1001res . writeHead ( 200 , { 'content-type' :'application/json; charset=utf-8' , 'content-length' :Buffer . byteLength ( text ), 'cache-control' :'no-store' }); 1002res . end ( text ); 1003return undefined ; 1004} 1005if ( id && method === 'PUT' ) { 1006const text = ( await readRaw ( req , 256 * 1024 * 1024 )). toString ( 'utf8' ); 1007const base = req . headers [ 'x-strata-base-rev' ]; 1008const saved = await chatStore . save ( id , text , { baseRev :typeof base === 'string' && / ^\d + $ / . test ( base ) ?Number ( base ) :null }); 1009hub . send ( 'chats' , { id, rev :saved . rev , from}); 1010return json ( res , 200 , saved ); 1011} 1012if ( id && method === 'DELETE' ) { 1013const removed = await chatStore . remove ( id ); 1014hub . send ( 'chats' , { id, deleted :true , from}); 1015return json ( res , 200 , removed ); 1016} 1017} catch ( e ) { 1018const failure = e instanceof SyntaxError ?{ status :400 , message :'The request must be JSON.' , code :'bad-json' } :storeFailure ( e ); 1019return error ( res , failure . status , failure . message , { code :failure . code }); 1020} 1021return error ( res , 405 , 'Method not allowed.' ); 1022} 1023if ( storageChanging && ! [ 'GET' , 'OPTIONS' ]. includes ( method )) return error ( res , 409 , 'Wait for the model folder check to finish.' ); 1024// --- events ------------------------------------------------------------- 1025if ( path === '/api/events' ) return hub . add ( res ); 1026if ( path . startsWith ( '/api/native' )){ try { 1027if ( path === '/api/native' && method === 'GET' ) return json ( res , 200 , await native . refresh ( url . searchParams . get ( 'refresh' ) === '1' )); 1028if ( path === '/api/native' && method === 'PATCH' ) return json ( res , 200 , await native . configure ( await readBody ( req ))); 1029if ( 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). */ 1031if ( path === '/api/native/models-folder/plan' && method === 'POST' ){ 1032const typed = await typedFolder (( await readBody ( req )). path ,{ isAbsolute}); 1033const picked = typed ?{ path :typed } :await chooseFolder ( 'Choose a folder for your models' ); 1034if ( picked . unavailable ){ const u = chooserUnavailable ( picked ); return error ( res , 501 , u . message ,{ code :u . code });} 1035if ( picked . cancelled ) return json ( res , 200 ,{ cancelled :true }); 1036return json ( res , 200 ,{ plan :await native . planModelsFolder ( picked . path )});} 1037if ( 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 );} 1038if ( path === '/api/native/models-folder/interrupted' && method === 'GET' ) return json ( res , 200 ,{ interrupted :await native . interruptedMove ()}); 1039if ( path === '/api/native/models-folder/resume' && method === 'POST' ){ const body = await readBody ( req ); return json ( res , 202 , await native . finishInterruptedMove ({ stopRunning :body . stopRunning === true }));} 1040if ( path === '/api/native/models-folder/leave' && method === 'POST' ) return json ( res , 200 , await native . leaveInterruptedMove ()); 1041if ( path === '/api/native/plan' && method === 'POST' ) return json ( res , 200 , await native . plan ( await readBody ( req ))); 1042if ( 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 ));} 1043if ( path === '/api/native/engine-restart/dismiss' && method === 'POST' ) return json ( res , 200 , native . dismissRestart ()); 1044if ( path === '/api/native/logs' && method === 'GET' ) return json ( res , 200 ,{ logs :native . logs ()}); 1045if ( 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. 1047Written to the user's Downloads folder (the window cannot save a download); the path is returned to show. */ 1048const NL = String . fromCharCode ( 10 ); 1049const lines = [ `Strata diagnostics ${ new Date (). toISOString ()} ` , `Version ${ native . state (). version ?? 'unknown' } ` , '' , '== Engine messages ==' ]; 1050for ( const l of native . logs ()) lines . push ( ` ${ l . at } ${ l . instanceId } : ${ l . line } ` ); 1051lines . 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 } ` : '' } ` ); 1052try { 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) */ } 1053try { 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 */ } 1054const folder = join ( process . env . USERPROFILE ?? process . env . HOME ?? homedir (), 'Downloads' ); mkdirSync ( folder ,{ recursive :true }); 1055const file = join ( folder , `strata-diagnostics- ${ new Date (). toISOString (). replace ( / [: . ] / g , '-' ). slice ( 0 , 19 )} .txt` ); writeFileSync ( file , lines . join ( NL ), 'utf8' ); 1056return json ( res , 200 ,{ path :file });} 1057if ( 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. */ 1059const typed = await typedFolder (( await readBody ( req )). path ,{ isAbsolute, fileType :/ \.gguf$ / i }); 1060const picked = typed ?{ path :typed } :await chooseFolder ( 'Choose the folder that holds your GGUF files' ); 1061if ( picked . unavailable ){ const u = chooserUnavailable ( picked ); return error ( res , 501 , u . message ,{ code :u . code });}; 1062if ( picked . cancelled ) return json ( res , 200 ,{ cancelled :true }); 1063return json ( res , 200 ,{ path :picked . path , preview :await native . localPreview ( picked . path )});} 1064if ( 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. */ 1066if ( 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 })); 1067if ( 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 })); 1068if ( 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 }));} 1069if ( path === '/api/native/tune/presets' && method === 'GET' ) return json ( res , 200 , await native . tunePresets . list ()); 1070if ( 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 }));} 1071const tunePreset = /^\/api\/native\/tune\/presets\/ ([ 0 - 9a - f ]{ 8 , 32 }) \/ ( apply | rename | delete | undo ) $ / . exec ( path ); 1072if ( tunePreset && method === 'POST' ) return json ( res , 200 , await native . tunePresets . action ( tunePreset [ 2 ], tunePreset [ 1 ], await readBody ( req ))); 1073const nativeOperation = /^\/api\/native\/operations\/ ([ a - z0 - 9- ] + ) \/cancel$ / . exec ( path ); 1074if ( nativeOperation && method === 'POST' ) return json ( res , 200 , await native . cancel ( nativeOperation [ 1 ])); 1075const nativeInstance = /^\/api\/native\/instances\/ ([ a - z0 - 9- ] + ) \/ ( unload | default ) $ / . exec ( path ); 1076if ( nativeInstance && method === 'POST' ) return json ( res , 200 , nativeInstance [ 2 ] === 'unload' ?await native . unload ( nativeInstance [ 1 ]) :native . setDefault ( nativeInstance [ 1 ])); 1077const 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). */ 1079if ( 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 ])});} 1080if ( nativeSettings && method === 'PATCH' ) return json ( res , 200 , native . save ( nativeSettings [ 1 ], await readBody ( req ))); 1081const nativeSettingsFile = /^\/api\/native\/models\/ ([ a - z0 - 9_.- ] + ) \/settings-file$ / . exec ( path ); 1082if ( nativeSettingsFile && method === 'GET' ) return json ( res , 200 , native . settingsFile ( nativeSettingsFile [ 1 ])); 1083if ( 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. 1086return 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 1088if ( path === '/api/model-providers' && method === 'GET' ) return json ( res , 200 , withPictureAnswers ( modelProviders . list ())); 1089if ( path === '/api/model-providers/discover' && method === 'POST' ) { 1090const body = await readBody ( req ); 1091const controller = new AbortController (); 1092res . on ( 'close' , () => { if ( ! res . writableEnded ) controller . abort (); }); 1093try { return json ( res , 200 , await modelProviders . discover ( body , controller . signal )); } 1094catch ( err ) { return error ( res , 400 , err . name === 'TimeoutError' ?'The model API timed out. Check the address and try again.' :err . message ); } 1095} 1096if ( path === '/api/model-providers' && method === 'POST' ) { 1097try { return json ( res , 200 , withPictureAnswers ( modelProviders . save ( await readBody ( req )))); } 1098catch ( err ) { return error ( res , 400 , err . message ); } 1099} 1100const providerMatch = / ^\/api\/model-providers\/ ([ a - zA - Z0 - 9- ] + ) $ / . exec ( path ); 1101if ( providerMatch && method === 'DELETE' ) return json ( res , 200 , withPictureAnswers ( modelProviders . remove ( providerMatch [ 1 ]))); 1102 1103if ( path === '/api/artifacts/open' && method === 'POST' ) { 1104const body = await readBody ( req , 30 * 1024 * 1024 ); 1105return 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. 1115if ( path === '/api/tune/plan' && method === 'POST' ) { 1116const body = await readBody ( req ); 1117const result = await tuning . plan ({ 1118engine :String ( body . engine ?? '' ). trim (), 1119backend :String ( body . backend ?? '' ). trim (), 1120model :body . model ?String ( body . model ) :undefined , 1121objective :body . objective , trials :body . trials , repeats :body . repeats , 1122}); 1123if ( ! result . ok ) return error ( res , result . code === 2 ?400 :502 , result . error ); 1124return json ( res , 200 , { plan :result . plan }); 1125} 1126if ( 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. 1130const status = supervisor . status (); 1131return json ( res , 200 , { 1132available :false , // the host starts no engine binary of its own (no llama-server) 1133path :null , 1134backend :status ?. backend ?? null , 1135running :Boolean ( status ?. running ), 1136}); 1137} 1138if ( path === '/api/tune/jobs' && method === 'GET' ) { 1139return json ( res , 200 , { jobs :tuning . jobs (), stateDir :tuning . stateDir () }); 1140} 1141if ( path === '/api/tune/job' && method === 'GET' ) { 1142const job = tuning . job ( url . searchParams . get ( 'id' )); 1143if ( ! job ) return error ( res , 404 , 'No such tuning job.' ); 1144return 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. 1152if ( path === '/api/timeskip' && method === 'GET' ) { 1153return json ( res , 200 , { runs :[ ...forkTs . list (), ...timeskip . list ()], stateDir :timeskip . stateDir () }); 1154} 1155if ( path === '/api/timeskip/status' && method === 'GET' ) { 1156const id = url . searchParams . get ( 'id' ); 1157if ( id && forkTs . has ( id )) return json ( res , 200 , { run :forkTs . status ( id ) }); 1158const run = id ?timeskip . status ( id ) :null ; 1159if ( ! run ) return error ( res , 404 , 'No such Time-skip run.' ); 1160return json ( res , 200 , { run :{ ...run , activity :trialActivity ( run ) } }); 1161} 1162if ( path === '/api/timeskip/start' && method === 'POST' ) { 1163const body = await readBody ( req ); 1164const workspaceId = typeof body . workspaceId === 'string' ?body . workspaceId :null ; 1165const workspace = String ( body . workspace ?? '' ). trim () || (( workspaceId ?workspaces . find ( w => w . id === workspaceId )?. path :null ) ?? WORKSPACE ); 1166const prompt = String ( body . prompt ?? '' ). trim (). slice ( 0 , 4000 ); 1167if ( body . legacy !== true ) { 1168if ( ! prompt ) return error ( res , 400 , 'Say what you want made or improved after /time-skip.' ); 1169if ( ! existsSync ( workspace )) return error ( res , 400 , 'Time-skip works on a folder of your own. Choose a folder for this chat, then try again.' ); 1170const cwd = chatFolders . get ( typeof body . sessionId === 'string' ?body . sessionId :'' ) ?? workspace ; 1171if ( 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.' ); 1172if ( 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.' ); 1173let choice , slots = 1 ; 1174if ( 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 ; } 1176else { 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.' ); } } 1177const chatId = typeof body . sessionId === 'string' && body . sessionId ?body . sessionId :null ; 1178if ( chatId && forkTs . byChat ( chatId )) return error ( res , 409 , 'A Time-skip is already running in this chat.' ); 1179const run = forkTs . start ({ prompt, workspace :cwd , chatId, choice, thinking :typeof body . thinking === 'string' ?body . thinking :'Low' , slots}); 1180return json ( res , 200 , { run, simulated :false }); 1181} 1182const 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. 1184if ( 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. 1186if ( existsSync ( workspace )) { 1187const size = measureFolder ( workspace ); 1188if ( 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} 1190const result = await timeskip . startDetached ({ 1191 workspace, prompt, 1192attempts :body . attempts ?? 1 , 1193 reviseCommand, 1194extraEnv :{ STRATA_HOST_URL :`http://127.0.0.1: ${ PORT } ` , STRATA_INTERNAL_SECRET :INTERNAL_SECRET }, 1195}); 1196if ( ! result . ok ) return error ( res , result . code === 2 ?400 :502 , result . error ); 1197const chatId = typeof body . sessionId === 'string' && body . sessionId ?body . sessionId :null ; 1198trials . set ( result . run . id , { chatId, turnChat :null , controller :null , step :null , lastSent :'' }); 1199if ( chatId ) trialByChat . set ( chatId , result . run . id ); 1200watchTrial ( result . run . id ); 1201if ( body . remoteModel ?. connectionId && body . remoteModel ?. modelId ) timeskipChoices . set ( result . run . id , { connectionId :String ( body . remoteModel . connectionId ), modelId :String ( body . remoteModel . modelId ) }); 1202return json ( res , 200 , { run :{ ...result . run , activity :trialActivity ( result . run ) }, simulated :false }); 1203} 1204if ( path === '/api/timeskip/files' && method === 'GET' ) { 1205const fid = url . searchParams . get ( 'id' ); 1206const found = forkTs . has ( fid ) ?forkTs . files ( fid ) :timeskip . files ( fid ); 1207if ( ! found ) return error ( res , 404 , 'No such Time-skip run.' ); 1208return 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. */ 1211if ( path === '/api/timeskip/file' && method === 'GET' ) { 1212const iid = url . searchParams . get ( 'id' ); 1213const 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' )); 1214if ( ! found ) return error ( res , 404 , 'No such picture in this Time-skip run.' ); 1215res . 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:" }); 1216createReadStream ( found . path ). pipe ( res ); 1217return ; 1218} 1219if ( path === '/api/timeskip/stop' && method === 'POST' ) { 1220const body = await readBody ( req ); 1221if ( forkTs . has ( String ( body . id ?? '' ))) return json ( res , 200 , { stopped :await forkTs . stop ( String ( body . id )) }); 1222return 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. 1225if ( path === '/api/internal/timeskip-revise' && method === 'POST' ) { 1226if ( ! sameSecret ( req . headers [ 'x-strata-internal' ], INTERNAL_SECRET )) return error ( res , 403 , 'Not allowed.' ); 1227const body = await readBody ( req ); 1228const cwd = String ( body . cwd ?? '' ); 1229// Only the job's own candidate folders may be worked in. 1230const root = resolve ( timeskip . stateDir ()); 1231if ( ! cwd || ! resolve ( cwd ). startsWith ( root + sep )) return error ( res , 400 , 'That folder is not part of a Time-skip run.' ); 1232const runId = resolve ( cwd ). slice ( root . length + 1 ). split ( sep )[ 0 ]; 1233const chosen = timeskipChoices . get ( runId ) ?? (() => { try { return { instanceId :native . resolveInstance ( native . state (). defaultId ). id }; } catch { return null ; } })(); 1234if ( ! chosen ) return error ( res , 503 , 'Load a model first, then try Time-skip again.' ); 1235const 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"). 1238res . writeHead ( 200 , { 'content-type' :'application/x-ndjson; charset=utf-8' , 'cache-control' :'no-cache, no-transform' }); 1239const write = frame => { if ( ! res . writableEnded && ! res . destroyed ) res . write ( ` ${ JSON . stringify ( frame )} \n` ); }; 1240write ({ type :'beat' }); 1241const beat = setInterval (() => write ({ type :'beat' }), 15_000 ); 1242const controller = new AbortController (); 1243const trial = trials . get ( runId ); 1244if ( trial ) { trial . turnChat = chatId ; trial . controller = controller ; } 1245res . on ( 'close' , () => { clearInterval ( beat ); if ( ! res . writableEnded ) { controller . abort (); void agent . stop ( chatId ). catch (() => {}); } }); 1246let text = '' , failure = null ; 1247try { 1248await agent . runTurn ({ chatId, message :timeskipRevisionMessage ( String ( body . prompt ?? '' )), workspacePath :cwd , choice :chosen , mode :'bypass' , thinking :'low' , history :[], signal :controller . signal , onFrame :frame => { 1249if ( frame . type === 'delta' ) text += frame . text ?? '' ; 1250else if ( frame . type === 'error' ) failure = frame . message ; 1251else 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 1253trial . 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 ; } 1257if ( controller . signal . aborted ) failure = failure ?? 'The trial was stopped.' ; 1258write ( failure ?{ type :'error' , message :failure } :{ type :'result' , text :text . slice ( - 600 ) }); 1259res . end (); 1260return undefined ; 1261} 1262if ( path === '/api/timeskip/apply' && method === 'POST' ) { 1263const body = await readBody ( req ); 1264if ( forkTs . has ( String ( body . id ?? '' ))) { 1265try { return json ( res , 200 , { apply :forkTs . apply ({ id :String ( body . id ), which :body . which === 'a' ?'a' :'b' , restore :Boolean ( body . restore ) }) }); } 1266catch ( e ) { return error ( res , 400 , e . message ); } 1267} 1268const result = await timeskip . apply ({ 1269id :body . id , workspace :body . workspace ?? null , 1270dryRun :Boolean ( body . dryRun ), restore :Boolean ( body . restore ), attempt :body . attempt ?? null , 1271}); 1272if ( ! result . ok ) { 1273// A concurrent user edit is a conflict the caller must see, not a server error to retry. 1274return json ( res , result . conflict ?409 :400 , { error :result . error , conflict :Boolean ( result . conflict ) }); 1275} 1276return json ( res , 200 , { apply :result . apply }); 1277} 1278if ( path === '/api/tasks' && method === 'GET' ) return json ( res , 200 , { tasks :tasks . list () }); 1279if ( path === '/api/tasks/draft' && method === 'POST' ) { 1280const body = await readBody ( req ); 1281const description = String ( body . description ?? '' ). trim (). slice ( 0 , 12000 ); 1282if ( ! description ) return error ( res , 400 , 'Describe the task first.' ); 1283let 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 }; 1284if ( models . REAL ) { 1285let text = '' , failure = null ; 1286await 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 ; } }); 1287if ( failure ) return error ( res , 400 , failure ); 1288try { draft = { ...draft , ...JSON . parse ( text . replace ( / ^``` (?: json ) ? \s *| \s * ```$ / g , '' ). trim ()), timeZone :body . timeZone ?? 'UTC' , enabled :true }; } 1289catch { return error ( res , 400 , 'The model did not return a usable draft. Try again or set up manually.' ); } 1290} 1291try { return json ( res , 200 , { draft :validateTask ( draft ), demo :! models . REAL }); } 1292catch ( e ) { return error ( res , 400 , e . message ); } 1293} 1294if ( path === '/api/tasks' && method === 'POST' ) { 1295try { return json ( res , 201 , tasks . put ( await readBody ( req ))); } catch ( e ) { return error ( res , 400 , e . message ); } 1296} 1297const taskRoute = path . match ( / ^\/api\/tasks\/ ([ ^ / ] + )(?: \/ ( run | stop )) ? $ / ); 1298if ( taskRoute ) { 1299const [, id , action ] = taskRoute ; 1300if ( ! tasks . list (). some ( t => t . id === id )) return error ( res , 404 , 'Task not found.' ); 1301try { 1302if ( method === 'PATCH' && ! action ) return json ( res , 200 , tasks . put ( await readBody ( req ), id )); 1303if ( 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 }); } 1304if ( 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 ----------------------------------------------------- 1309if ( path === '/api/health' ) { 1310return json ( res , 200 , { 1311ok :true , 1312uptimeSec :Math . round ( process . uptime ()), 1313backend :currentBackend (), 1314engine :supervisor . status (), 1315clients :hub . size , 1316}); 1317} 1318 1319// --- Strata Control: what the installed app runs on, and what it will not do --------------------- 1320if ( path === '/api/control/status' && method === 'GET' ) { 1321const 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" 1323if ( engine && ! engine . usable && ! bundledEngineSettled ) engine . notice = 'The engine that came with the app is being set up. This takes a minute the first time.' ; 1324return json ( res , 200 , { 1325packaged :process . env . STRATA_PACKAGED === '1' , 1326control :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, 1328engineSetup :! bundledEngineSettled , 1329componentsDir :componentsDirectory (), 1330acquisition :{ 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. 1334const fromShell = () => { 1335const token = process . env . STRATA_SHUTDOWN_TOKEN ?? '' ; 1336return 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. 1339if ( path === '/api/app/mode' && method === 'GET' ) return json ( res , 200 , appUi . state ()); 1340if ( 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). 1342if ( ! req . headers [ 'x-strata-client' ]) return error ( res , 403 , 'Not allowed.' ); 1343const verdict = appUi . quit (); 1344return 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. 1347if ( path === '/api/control/ui' && method === 'POST' ) { 1348if ( ! fromShell ()) return error ( res , 403 , 'Not allowed.' ); 1349const body = await readBody ( req ); 1350try { 1351if ( body . bridge ) appUi . setBridge ( body . bridge ); 1352if ( 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 })); 1353if ( body . open === true ) return json ( res , 200 , { ...appUi . state (), opened :await appUi . openPage ( `http://127.0.0.1: ${ PORT } /` ) }); 1354return 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. 1358if ( path === '/api/control/shutdown' && method === 'POST' ) { 1359if ( ! fromShell ()) return error ( res , 403 , 'Not allowed.' ); 1360json ( res , 202 , { stopping :true }); 1361setImmediate (() => void shutdown ()); 1362return ; 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). 1366if ( path === '/api/app/drop' && method === 'POST' ) { 1367if ( ! fromShell ()) return error ( res , 403 , 'Not allowed.' ); 1368try { return json ( res , 200 , { files :await nativeDrops . add (( await readBody ( req )). paths ) }); } catch ( err ) { return error ( res , 400 , err . message ); } 1369} 1370const dropGet = / ^\/api\/app\/drop\/ ([ 0 - 9a - f- ]{ 36 }) $ / . exec ( path ); 1371if ( dropGet && method === 'GET' ) { 1372const file = nativeDrops . take ( dropGet [ 1 ]); 1373if ( ! file ) return error ( res , 404 , 'That file is no longer available. Drop it again.' ); 1374res . 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 1377if ( path === '/api/setup' && method === 'GET' ) return json ( res , 200 , setupState ()); 1378if ( path === '/api/engine/first-run' && method === 'GET' ) { 1379if ( ! control ?. updateCheck ) return json ( res , 200 , { status :'unavailable' , gpus :[] }); 1380const info = await engineFirstRun ({ control, gpus :hardware . cachedHardware ()?. gpus ?? [] }); 1381try { 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 */ } 1382return json ( res , 200 , info ); 1383} 1384if ( path === '/api/engines' && method === 'GET' ) { 1385const { status, body} = await listEngines ( control ); 1386return json ( res , status , body ); 1387} 1388if (( path === '/api/engines/use' || path === '/api/engines/remove' ) && method === 'POST' ) { 1389const { status, body} = await changeEngine ( control , path . endsWith ( '/use' ) ?'use' :'remove' , await readBody ( req ), { modelsRunning :() => native . state (). instances . length > 0 }); 1390if ( status === 200 ) Promise . resolve ( native . refresh ?.( true )). catch (() => { /* the next poll reads it */ }); 1391return json ( res , status , body ); 1392} 1393if ( 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). 1395const kinds = [ 'update-engine' , 'install-engine-file' ]; 1396return json ( res , 200 , { job :native . state (). jobs . filter ( j => kinds . includes ( j . kind )). slice ( - 1 )[ 0 ] ?? null }); 1397} 1398if ( 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. 1400const name = String ( req . headers [ 'x-file-name' ] ?? 'engine.tar.gz' ). replace ( / [ ^ A - Za - z0 - 9._- ] / g , '_' ). slice ( - 120 ); 1401if ( ! /\. ( 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.' ); 1402const folder = join ( store . DATA_DIR , 'incoming-engine' ); 1403mkdirSync ( folder , { recursive :true , mode :0o700 }); 1404const target = join ( folder , name ); 1405await pipeline ( req , createWriteStream ( target , { mode :0o600 })); 1406return json ( res , 202 , native . operation ( 'install-engine-file' , { path :target })); 1407} 1408if ( path === '/api/updates/check' && method === 'GET' && control ?. updateCheck ) return json ( res , 200 , await checkComponentUpdates ({ control, appUpdater, appVersion :process . env . STRATA_APP_VERSION || null })); 1409if ( 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 1411if ( path === '/api/setup/step' && method === 'POST' ) { 1412const body = await readBody ( req ); 1413const s = store . get (); 1414const step = Math . max ( 1 , Math . min ( 4 , migrateSetup ({ step :body . step , flowVersion :body . flowVersion }). step )); 1415store . update ({ 1416setup :{ ...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}); 1418const next = setupState (); 1419hub . send ( 'setup' , next ); 1420return json ( res , 200 , next ); 1421} 1422 1423if ( path === '/api/setup/complete' && method === 'POST' ) { 1424const s = store . get (); 1425if ( ! models . library (). loaded &&! native . hasLive ()) return error ( res , 409 , 'Load a model before completing setup.' ); 1426store . update ({ setup :{ ...s . setup , dismissed :false , complete :true , flowVersion :2 , step :4 , completedAt :new Date (). toISOString () } }); 1427const next = setupState (); 1428hub . send ( 'setup' , next ); 1429return json ( res , 200 , next ); 1430} 1431 1432// --- hardware ----------------------------------------------------------- 1433if ( path === '/api/hardware' ) { 1434const force = url . searchParams . get ( 'reprobe' ) === '1' ; 1435const hw = await hardware . detect ({ force}); 1436if ( force ) monitor . init ( hub , hw ); 1437return json ( res , 200 , hw ); 1438} 1439 1440// --- models ------------------------------------------------------------- 1441if ( path === '/api/local-models/browse' && method === 'GET' ) { 1442const shortcuts = [{ name :'Model directory' , path :store . MODELS_DIR },{ name :'Home' , path :process . env . USERPROFILE ?? process . env . HOME }]. filter ( s => s . path ); 1443try { return json ( res , 200 , { ...browseLocalModels ( url . searchParams . get ( 'directory' ) ?? store . MODELS_DIR ), shortcuts}); } 1444catch ( err ) { return error ( res , 400 , err . message ); } 1445} 1446if ( path === '/api/local-models/inspect' && method === 'POST' ) { 1447try { const body = await readBody ( req ); return json ( res , 200 , inspectLocalModel ( body . path )); } 1448catch ( err ) { return error ( res , 400 , err . message ); } 1449} 1450if ( path === '/api/local-models' && method === 'POST' ) { 1451const body = await readBody ( req ); 1452if ( storageChanging ) return error ( res , 409 , 'Wait for the model folder check to finish.' ); 1453try { 1454const preview = inspectLocalModel ( body . path ), previous = variant ( preview . variant . id ); 1455if ( 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 } ` ;} 1456if ( 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.' ); 1457localModels . add ( preview ); 1458return json ( res , 200 ,{ library :runtimeModels . libraryState ( models . localModelAdded ()), variantId :preview . variant . id }); 1459} catch ( err ) { return error ( res , 400 , err . message ); } 1460} 1461if ( path === '/api/storage/models-directory' && method === 'POST' ) { 1462const body = await readBody ( req ); 1463let directory ; 1464try { directory = store . validateModelsDirectory ( body . directory ); } 1465catch ( err ) { return error ( res , 400 , err . message ); } 1466const changed = directory !== store . MODELS_DIR ; 1467const instances = runtimeState (). instances ; 1468if ( 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.' ); 1469if ( serving . state (). requests . some ( r => [ 'queued' , 'generating' ]. includes ( r . state ))) return error ( res , 409 , 'Finish or cancel model requests before changing the folder.' ); 1470if ( changed && instances . length && body . unload !== true ) return error ( res , 409 , 'Unload the current models before changing the folder.' ); 1471const nativePlan = nativeUnloadPlan ({ changed, unload :body . unload , instances :native . state (). instances }); 1472if ( nativePlan . refuse ) return error ( res , 409 , nativePlan . refuse ); 1473for ( const id of nativePlan . ids ) await native . unload ( id ); 1474storageChanging = true ; 1475try { 1476if ( changed ) { 1477if ( models . REAL ) await models . unload (); 1478else for ( const instance of instances ) runtimeModels . unload ( instance . id ); 1479store . changeModelsDirectory ( directory ); 1480engine . markStopped (); monitor . idle ( 'Model directory changed' ); 1481} 1482models . init ( hub ); 1483const images = await imageModels . rescan ( changed ); 1484const hw = await hardware . detect ({ force :true }); 1485const library = runtimeModels . libraryState ( models . library ()); 1486hub . send ( 'models' , library ); hub . send ( 'setup' , setupState ()); hub . send ( 'engine' , await engine . config ()); 1487return json ( res , 200 , { library, imageModels :images , runtime :runtimeState (), hardware :hw , setup :setupState () }); 1488} catch ( err ) { return error ( res , 400 , err . message ); } 1489finally { storageChanging = false ; hub . send ( 'models' , models . library ()); hub . send ( 'setup' , setupState ()); } 1490} 1491if ( path === '/api/image-models' && method === 'GET' ) return json ( res , 200 , imageModels . library ()); 1492if ( path === '/api/image-models' && method === 'PATCH' ) { 1493const body = await readBody ( req ); 1494return json ( res , 200 , imageModels . select ( body . selected )); 1495} 1496if ( path === '/api/image-models/apply' && method === 'POST' ) return json ( res , 200 , imageModels . apply ()); 1497const imageMatch = / ^\/api\/image-models\/ ( q4 | q5 | q6 | q8 ) \/ ( install | cancel ) $ / . exec ( path ); 1498if ( imageMatch && method === 'POST' ) { 1499const [, id , action ] = imageMatch ; 1500return json ( res , 200 , action === 'install' ?imageModels . install ( id ) :await imageModels . cancel ( id )); 1501} 1502if ( path === '/api/runtime' && method === 'GET' ) return json ( res , 200 , runtimeState ()); 1503if ( path === '/api/runtime/plan' && method === 'POST' ) return json ( res , 200 , runtimeModels . plan ( await readBody ( req ))); 1504if ( path === '/api/runtime/load' && method === 'POST' ){ 1505const body = await readBody ( req ); const checked = await engine . validate ({ ...body . config , variantId :body . variantId }); 1506if ( storageChanging ) return error ( res , 409 , 'Wait for the model folder check to finish.' ); 1507if ( ! checked . ok ) return error ( res , 400 , checked . issues . filter ( i => i . level === 'error' ). map ( i => i . message ). join ( ' ' )); 1508if ( models . REAL ) return error ( res , 409 , 'This native host supports one model on automatic GPU placement.' ); 1509try { 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} 1511const runtimeMatch = /^\/api\/runtime\/ ([ ^ / ] + ) \/ ( unload | default ) $ / . exec ( path ); 1512if ( runtimeMatch && method === 'POST' ){ 1513const [, id , action ] = runtimeMatch ; runtimeState (); 1514if ( models . REAL && action === 'unload' ){ 1515const instance = runtimeModels . state (). instances . find ( i => i . id === id ); 1516if ( ! instance ) return error ( res , 404 , 'This model is no longer loaded.' ); 1517if ( 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.' ); 1518await models . unload (); engine . markStopped (); hub . send ( 'engine' , await engine . config ()); runtimeState (); return json ( res , 200 , runtimeState ()); 1519} 1520try { return json ( res , 200 , action === 'unload' ?runtimeModels . unload ( id ) :runtimeModels . setDefault ( id ));} 1521catch ( err ){ return error ( res , 409 , err . message );} 1522} 1523if ( path === '/api/models' && method === 'GET' ) return json ( res , 200 , runtimeModels . libraryState ( models . library ())); 1524 1525const modelMatch = / ^\/api\/models\/ ([ ^ / ] + )(?: \/ ( install | cancel | load )) ? $ / . exec ( path ); 1526if ( modelMatch ) { 1527const [, id , action ] = modelMatch ; 1528if ( 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 )));} 1529if ( 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 ); } } 1530if ( method === 'POST' && action === 'cancel' ) return json ( res , 200 , runtimeModels . libraryState ( models . cancel ( id ))); 1531if ( method === 'POST' && action === 'load' ) { 1532const hw = await hardware . detect (); 1533if ( storageChanging ) return error ( res , 409 , 'Wait for the model folder check to finish.' ); 1534if ( ! models . REAL ){ 1535const config = { beginner :store . get (). beginner , expert :engine . params (), extra :store . get (). configExtra ?? {}}; 1536const gpuIds = config . expert . find ( p => p . id === 'gpu.layers' )?. value === 'CPU only' ?[] :hw . gpus . map ( g => g . id ?? ` ${ g . vendor } : ${ g . index } ` ); 1537try { 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 );} 1538catch ( err ){ return error ( res , 409 , err . message );} 1539await monitor . setModel ( id ); engine . markRunning ( hw . accelerator . backend ); hub . send ( 'engine' , await engine . config ()); 1540return 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 1543return 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 1547if ( path === '/api/models/unload' && method === 'POST' ) { 1548if ( ! models . REAL && runtimeModels . state (). defaultId ){ runtimeModels . unload ( runtimeModels . state (). defaultId ); return json ( res , 200 , runtimeModels . libraryState ( models . library ()));} 1549const lib = await models . unload ({ onPhase :() => monitor . idle ( 'Model unloaded' ) }); 1550engine . markStopped (); 1551hub . send ( 'engine' , await engine . config ()); 1552return json ( res , 200 , runtimeModels . libraryState ( lib )); 1553} 1554 1555// --- engine ------------------------------------------------------------- 1556if ( path === '/api/engine' && method === 'GET' ) return json ( res , 200 , await engine . config ()); 1557if ( path === '/api/engine' && method === 'PATCH' ) { 1558const body = await readBody ( req ); 1559const checked = await engine . validate ( body ); 1560if ( ! checked . ok ) return error ( res , 400 , checked . issues . filter ( i => i . level === 'error' ). map ( i => i . message ). join ( ' ' )); 1561const cfg = await engine . patch ( body ); 1562if ( body . beginner ?. contextLength ) { 1563monitor . setContextMax ( CONTEXT_TOKENS [ body . beginner . contextLength ] ?? 32768 ); 1564} 1565return json ( res , 200 , cfg ); 1566} 1567if ( path === '/api/engine/restart' && method === 'POST' ) { 1568monitor . idle ( 'Engine restarting' ); 1569const cfg = await engine . restart (); 1570monitor . setModel ( store . get (). loaded ); 1571return json ( res , 200 , cfg ); 1572} 1573if ( path === '/api/engine/reset' && method === 'POST' ) return json ( res , 200 , await engine . reset ()); 1574if ( path === '/api/engine/validate' && method === 'POST' ) { 1575const body = await readBody ( req ); 1576return json ( res , 200 , await engine . validate ( body ?? {})); 1577} 1578if ( path === '/api/engine/status' && method === 'GET' ) return json ( res , 200 , supervisor . status ()); 1579if ( path === '/api/engine/logs' && method === 'GET' ) { 1580return json ( res , 200 , { 1581logs :supervisor . logs ( Number ( url . searchParams . get ( 'limit' ) ?? 200 )), 1582status :supervisor . status (), 1583}); 1584} 1585if ( path === '/api/engine/stop' && method === 'POST' ) { 1586const status = await supervisor . stop (); 1587store . update ({ loaded :null }); 1588monitor . idle ( 'Model unloaded' ); 1589engine . markStopped (); 1590hub . send ( 'engine' , await engine . config ()); 1591hub . send ( 'models' , models . library ()); 1592return json ( res , 200 , status ); 1593} 1594if ( path === '/api/engine/binary' && method === 'GET' ) return json ( res , 200 , engineInstall . status ()); 1595if ( path === '/api/engine/binary' && method === 'POST' ) { 1596try { 1597const result = await engineInstall . install ({ force :url . searchParams . get ( 'force' ) === '1' }); 1598return json ( res , 200 , result ); 1599} catch ( err ) { 1600return error ( res , err . status ?? 500 , err . message , { ...engineInstall . status (), error :err . message }); 1601} 1602} 1603if ( path === '/api/engine/export' && method === 'GET' ) return json ( res , 200 , await engine . exportConfig ()); 1604 1605// --- serving ------------------------------------------------------------ 1606if ( path === '/api/serving/tunnel' && method === 'GET' ) return json ( res , 200 , await cloudflare . inspect ()); 1607if ( path === '/api/serving/tunnel' && method === 'POST' ) { 1608try { 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 ()); } 1609catch ( e ) { return error ( res , 400 , e . message ); } 1610} 1611if ( path === '/api/monitor/snapshot' && method === 'POST' ) { 1612try { const body = await readBody ( req , 25 * 1024 * 1024 ); return json ( res , 200 , await saveSnapshot ( body . data )); } 1613catch ( e ) { return error ( res , 400 , e . message ); } 1614} 1615if ( path === '/api/serving/share' && method === 'POST' ) { 1616try { const body = await readBody ( req ); if ( body . enabled === true ) await localShare . start (); else await localShare . stop (); return json ( res , 200 , serving . state ()); } 1617catch ( e ) { return error ( res , 400 , e . message ); } 1618} 1619if ( path === '/api/serving' && method === 'GET' ) return json ( res , 200 , serving . state ()); 1620if ( path === '/api/serving' && method === 'PATCH' ) { 1621const body = await readBody ( req ); 1622return json ( res , 200 , serving . patch ( body )); 1623} 1624const cancelMatch = / ^\/api\/serving\/requests\/ ([ ^ / ] + ) \/cancel$ / . exec ( path ); 1625if ( cancelMatch && method === 'POST' ) return json ( res , 200 , serving . cancel ( cancelMatch [ 1 ])); 1626 1627// --- monitor ------------------------------------------------------------ 1628if ( path === '/api/monitor' ) { monitor . watch (); if ( url . searchParams . get ( 'drives' ) === '1' ) monitor . watchDrives (); return json ( res , 200 , monitor . snapshot ()); } 1629 1630// --- skills / workspace ------------------------------------------------- 1631if ( path === '/api/skills' && method === 'GET' ) { 1632/* Re-scan rather than returning the array built at startup. 1633The screen offers a "Check again" action for a skill dropped into the 1634workspace while the app is open; returning the cached list made that 1635button a promise the host did not keep. Enabled state and usage counts 1636are carried across, since they belong to the skill's identity rather than 1637to the scan. */ 1638const known = new Map ( skillState . map (( s ) => [ s . id , s ])); 1639skillState = skills (). map (( s ) => { 1640const before = known . get ( s . id ); 1641return 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}); 1645syncAgentSkills (); 1646return 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. 1649if ( path === '/api/skills' && method === 'POST' ) { 1650const body = await readBody ( req ); 1651try { 1652const name = String ( body . name ?? '' ). trim (). slice ( 0 , 80 ); 1653const instructions = String ( body . body ?? '' ). trim (); 1654if ( ! name ) throw new Error ( 'Give the skill a name.' ); 1655if ( ! 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. 1657const triggers = body . triggers === undefined ?[] :skillEdit ({ triggers :body . triggers }). triggers ; 1658const id = writeCreatedSkill ( CREATED_SKILLS , { name, description :String ( body . description ?? '' ). trim (). slice ( 0 , 400 ), body :instructions . slice ( 0 , 40000 ) }); 1659const newId = `my- ${ id } ` , off = body . enabled === false ; 1660if ( off || triggers . length ) { 1661const saved = store . get (); 1662store . update ({ 1663 ...( off ?{ skillPreferences :{ ...saved . skillPreferences , [ newId ] :{ enabled :false , onlyIn :null } } } :{}), 1664 ...( triggers . length ?{ skillEdits :{ ...saved . skillEdits , [ newId ] :{ ...saved . skillEdits ?.[ newId ], triggers} } } :{}), 1665}); 1666} 1667const before = new Map ( skillState . map ( s => [ s . id , s ])); 1668skillState = 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 }); 1669syncAgentSkills (); 1670hub . send ( 'skills' , skillState ); 1671return json ( res , 201 , { id :newId , skills :skillState }); 1672} catch ( e ) { return error ( res , 400 , e . message ); } 1673} 1674const skillDelete = / ^\/api\/skills\/ ([ ^ / ] + ) $ / . exec ( path ); 1675if ( skillDelete && method === 'DELETE' ) { 1676const skill = skillState . find ( s => s . id === decodeURIComponent ( skillDelete [ 1 ])); 1677if ( ! skill ) return error ( res , 404 , 'Skill not found.' ); 1678if ( skill . source !== 'created' ) return error ( res , 400 , 'Only a skill you wrote here can be removed from this page.' ); 1679rmSync ( join ( CREATED_SKILLS , skill . id . replace ( / ^my- / , '' )), { recursive :true , force :true }); 1680skillState = skillState . filter ( s => s . id !== skill . id ); 1681syncAgentSkills (); 1682hub . send ( 'skills' , skillState ); 1683return json ( res , 200 , skillState ); 1684} 1685const skillMatch = / ^\/api\/skills\/ ([ ^ / ] + ) $ / . exec ( path ); 1686if ( skillMatch && method === 'PATCH' ) { 1687const body = await readBody ( req ); 1688const skillId = decodeURIComponent ( skillMatch [ 1 ]); 1689if ( ! skillState . some ( s => s . id === skillId )) return json ( res , 404 , { error :'Skill not found.' }); 1690let edit ; 1691try { edit = skillEdit ( body ); } catch ( error ) { return json ( res , 400 , { error :error . message }); } 1692if ( body . onlyIn != null && ! workspaces . some ( w => w . id === body . onlyIn )) return json ( res , 400 , { error :'Choose an available workspace.' }); 1693skillState = skillState . map (( s ) => 1694s . id === skillId 1695 ?{ 1696 ...s , 1697 ...edit , 1698enabled :body . enabled === undefined ?s . enabled :!! body . enabled , 1699// null clears the narrowing; a workspace id restricts to it. 1700onlyIn :body . onlyIn === undefined ?( s . onlyIn ?? null ) :( body . onlyIn || null ), 1701} 1702 :s , 1703); 1704store . 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 } } }); 1705syncAgentSkills (); 1706hub . send ( 'skills' , skillState ); 1707return json ( res , 200 , skillState ); 1708} 1709 1710if ( path === '/api/workspace' ) { 1711const root = url . searchParams . get ( 'root' ); 1712const 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. 1715return 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. 1721if ( path === '/api/workspace/file' ) { 1722const rootId = url . searchParams . get ( 'root' ); 1723const rel = url . searchParams . get ( 'path' ) ?? '' ; 1724const root = ( rootId ?workspaces . find (( w ) => w . id === rootId )?. path :null ) ?? WORKSPACE ; 1725const target = resolve ( root , rel ); 1726// A relative path may not escape its workspace. 1727if ( target !== resolve ( root ) && ! target . startsWith ( resolve ( root ) + '/' )) { 1728return error ( res , 400 , 'That file is outside the workspace.' ); 1729} 1730let st ; 1731try { 1732st = statSync ( target ); 1733} catch { 1734return error ( res , 404 , "That file doesn't exist any more." ); 1735} 1736if ( ! st . isFile ()) return error ( res , 400 , "That's a folder, not a file." ); 1737const LIMIT = 200 * 1024 ; 1738if ( st . size > LIMIT ) { 1739return json ( res , 200 , { path :rel , tooLarge :true , sizeKb :st . size / 1024 , text :'' }); 1740} 1741let text = '' ; 1742try { 1743text = readFileSync ( target , 'utf8' ); 1744} catch { 1745return 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. 1748if ( text . slice ( 0 , 1024 ). includes ( '\u0000' )) { 1749return json ( res , 200 , { path :rel , binary :true , sizeKb :st . size / 1024 , text :'' }); 1750} 1751return 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). 1755if ( path === '/api/chat/folder' && method === 'GET' ) { 1756const id = url . searchParams . get ( 'sessionId' ) ?? '' ; 1757return json ( res , 200 , { folder :chatFolders . info ( id ), default :workspaces [ 0 ]?. path ?? WORKSPACE }); 1758} 1759if ( path === '/api/chat/folder' && method === 'POST' ) { 1760const body = await readBody ( req ); 1761const id = String ( body . sessionId ?? '' ); 1762if ( ! id ) return error ( res , 400 , 'sessionId is required' ); 1763if ( agent . isRunning ( id )) return error ( res , 409 , 'This chat is still working. Stop it or wait for it to finish, then choose the folder.' ); 1764if ( body . path === null || body . path === '' ) { chatFolders . clear ( id ); return json ( res , 200 , { folder :null }); } 1765try { return json ( res , 200 , { folder :chatFolders . set ( id , body . path ) }); } catch ( e ) { return error ( res , 400 , e . message ); } 1766} 1767if ( path === '/api/files/open' && method === 'POST' ) { 1768const body = await readBody ( req ); 1769try { return json ( res , 200 , openFile ( chatRoot ( String ( body . sessionId ?? '' )), body . path , String ( body . how ?? 'app' ))); } 1770catch ( 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). */ 1773if ( path === '/api/chat/upload' && method === 'POST' ) { 1774const sid = url . searchParams . get ( 'sessionId' ) ?? '' ; 1775if ( ! sid ) return error ( res , 400 , 'sessionId is required' ); 1776try { const body = await readRaw ( req ); return json ( res , 200 , { files :uploads . accept ( sid , { body, contentType :req . headers [ 'content-type' ], name :url . searchParams . get ( 'name' ) }) }); } 1777catch ( e ) { return error ( res , e . code === 'too-big' ?413 :400 , e . message ); } 1778} 1779const uploadGet = / ^\/api\/chat\/upload\/ ([ 0 - 9a - f- ]{ 36 }) $ / . exec ( path ); 1780if ( uploadGet && method === 'GET' ) { 1781const img = uploads . image ( uploadGet [ 1 ]); 1782if ( ! img ) return error ( res , 404 , 'That picture is no longer available.' ); 1783res . 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} 1785if ( path === '/api/files/preview' && method === 'GET' ) { 1786const sid = url . searchParams . get ( 'sessionId' ) ?? '' ; 1787try { return json ( res , 200 , previewFile ( chatRoot ( sid ), url . searchParams . get ( 'path' ), sid )); } 1788catch ( e ) { return error ( res , e . code === 'outside' ?403 :400 , e . message ); } 1789} 1790if ( path === '/api/files/raw' && method === 'GET' ) { 1791try { 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 ; } 1792catch ( 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). */ 1795if ( path === '/api/chat/oversize' && method === 'POST' ) { 1796const body = await readBody ( req , 12 * 1024 * 1024 ); 1797const text = String ( body . text ?? '' ); 1798if ( ! text . trim ()) return error ( res , 400 , 'text is required' ); 1799let instance = null ; 1800try { instance = native . resolveInstance ( body . nativeModelId ?? native . state (). defaultId ); } catch { /* no local model: the length alone decides */ } 1801try { return json ( res , 200 , await prepareOversized ({ mode :body . mode === 'file' ?'file' :'preview' , text, root :chatRoot ( String ( body . sessionId ?? '' )), instance})); } 1802catch ( 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. */ 1805if ( path === '/api/chat/attachments' && method === 'GET' ) return json ( res , 200 , { files :chatAttachments . list ( url . searchParams . get ( 'sessionId' ) ?? '' ) }); 1806if ( path === '/api/chat/attachments' && method === 'POST' ) { 1807const body = await readBody ( req ); const id = String ( body . sessionId ?? '' ); 1808try { const file = resolveChatFile ( chatRoot ( id ), body . path ); return json ( res , 200 , { files :body . remove === true ?chatAttachments . remove ( id , file ) :chatAttachments . add ( id , file ) }); } 1809catch ( e ) { return error ( res , e . code === 'outside' ?403 :400 , e . message ); } 1810} 1811if ( path === '/api/files/path' && method === 'GET' ) { 1812try { const p = resolveChatFile ( chatRoot ( url . searchParams . get ( 'sessionId' ) ?? '' ), url . searchParams . get ( 'path' )); return json ( res , 200 , { path :p }); } 1813catch ( e ) { return error ( res , e . code === 'outside' ?403 :400 , e . message ); } 1814} 1815if ( path === '/api/workspaces' && method === 'GET' ) { 1816return json ( res , 200 , { workspaces}); 1817} 1818 1819if ( path === '/api/workspaces' && method === 'POST' ) { 1820const body = await readBody ( req ); 1821const target = resolve ( String ( body . path ?? '' ). trim (). replace ( / ^~ / , store . HOME )); 1822if ( ! target ) return error ( res , 400 , 'Choose a folder first.' ); 1823let st ; 1824try { 1825st = statSync ( target ); 1826} catch { 1827return error ( res , 400 , "That folder doesn't exist." ); 1828} 1829if ( ! st . isDirectory ()) return error ( res , 400 , "That's a file, not a folder." ); 1830if ( workspaces . some (( w ) => w . path === target )) { 1831return error ( res , 400 , 'That folder is already in your workspaces.' ); 1832} 1833const ws = { 1834id :`ws_ ${ Math . random (). toString ( 36 ). slice ( 2 , 8 )} ` , 1835name :basename ( target ) || target , 1836path :target , 1837}; 1838workspaces = [ ...workspaces , ws ]; 1839saveWorkspaces (); 1840return json ( res , 200 , ws ); 1841} 1842 1843/* A workspace's name is only what the sidebar shows; its folder stays. */ 1844if ( path . startsWith ( '/api/workspaces/' ) && method === 'PATCH' ) { 1845const id = path . split ( '/' )[ 3 ]; 1846const body = await readBody ( req ); 1847const name = String ( body . name ?? '' ). trim (). slice ( 0 , 80 ); 1848if ( ! name ) return error ( res , 400 , 'Type a name for this workspace.' ); 1849const at = workspaces . findIndex ( w => w . id === id ); 1850if ( at < 0 ) return error ( res , 404 , 'That workspace is not in your list.' ); 1851workspaces = workspaces . map (( w , i ) => ( i === at ?{ ...w , name} :w )); 1852saveWorkspaces (); 1853return json ( res , 200 , workspaces [ at ]); 1854} 1855 1856if ( path . startsWith ( '/api/workspaces/' ) && method === 'DELETE' ) { 1857const id = path . split ( '/' )[ 3 ]; 1858if ( id === workspaces [ 0 ]?. id ) { 1859return error ( res , 400 , 'The first workspace cannot be removed.' ); 1860} 1861workspaces = workspaces . filter (( w ) => w . id !== id ); 1862saveWorkspaces (); 1863return 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 1869search box instead — a button whose label and action had nothing to do with 1870each other. This does the thing the label says: choose a folder, check it 1871looks like a skill, copy it into the workspace's skills directory. */ 1872if ( path === '/api/skills/add' && method === 'POST' ) { 1873try { 1874// The dialog is the normal path; a typed `path` in the body stands in where none exists. 1875const typed = await typedFolder (( await readBody ( req )). path , { isAbsolute}); 1876const picked = typed ?{ path :typed } :await chooseFolder ( 'Choose a skill folder (it should contain SKILL.md)' ); 1877if ( picked . unavailable ) { const u = chooserUnavailable ( picked ); return error ( res , 501 , u . message ,{ code :u . code });}; 1878if ( picked . cancelled ) return json ( res , 200 , { cancelled :true }); 1879const chosen = picked . path ; 1880const base = basename ( chosen ); 1881const mdPath = join ( chosen , 'SKILL.md' ); 1882if ( ! existsSync ( mdPath )) { 1883return 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} 1885const dest = join ( WORKSPACE , 'skills' , base ); 1886if ( existsSync ( dest )) { 1887return error ( res , 400 , `A skill called " ${ base } " is already in this workspace. Rename the folder, or remove the existing one first.` ); 1888} 1889mkdirSync ( join ( WORKSPACE , 'skills' ), { recursive :true }); 1890cpSync ( chosen , dest , { recursive :true }); 1891return json ( res , 200 , { added :base }); 1892} catch ( e ) { 1893// Dismissing the dialog is { cancelled: true } above; anything thrown here is a real problem. 1894return error ( res , 400 , e . message ); 1895} 1896} 1897 1898if ( path === '/api/workspaces/pick' && method === 'POST' ) { 1899try { 1900const typed = await typedFolder (( await readBody ( req )). path , { isAbsolute}); 1901const picked = typed ?{ path :typed } :await chooseFolder ( 'Choose a folder for Strata' ); 1902if ( picked . unavailable ) { const u = chooserUnavailable ( picked ); return error ( res , 501 , u . message ,{ code :u . code });}; 1903if ( picked . cancelled ) return json ( res , 200 , { cancelled :true }); 1904return json ( res , 200 , { path :picked . path }); 1905} catch ( e ) { 1906return error ( res , 400 , e . message ); 1907} 1908} 1909 1910// --- agent -------------------------------------------------------------- 1911if ( 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. 1913const llmRoute = / ^\/api\/internal\/agent-llm\/ ([ A - Za - z0 - 9_.~- ] + )( \/. * ) $ / . exec ( path ); 1914if ( 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'}. 1916if ( path === '/api/goal' && method === 'GET' ) { 1917try { return json ( res , 200 , { goal :await agent . goalState ( url . searchParams . get ( 'chatId' ) ?? '' ) }); } catch ( e ) { return error ( res , 400 , e . message ); } 1918} 1919const goalAct = / ^\/api\/goal\/ ( pause | edit | clear ) $ / . exec ( path ); 1920if ( goalAct && method === 'POST' ) { 1921const body = await readBody ( req ); 1922try { 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. 1925if ( path === '/api/plan' && method === 'GET' ) return json ( res , 200 , { plan :agent . planState ( url . searchParams . get ( 'sessionId' ) ?? url . searchParams . get ( 'chatId' ) ?? '' ) }); 1926const planAct = / ^\/api\/plan\/ ( approve | edit | reject ) $ / . exec ( path ); 1927if ( planAct && method === 'POST' ) { 1928const body = await readBody ( req ); 1929try { 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 })); } 1930catch ( 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. 1933if ( path === '/api/chat/queue' && method === 'GET' ) return json ( res , 200 , agent . takeQueue ( url . searchParams . get ( 'sessionId' ) ?? '' , { release :url . searchParams . get ( 'release' ) === '1' })); 1934if ( path === '/api/chat/queue' && method === 'POST' ) { 1935const body = await readBody ( req ); 1936try { return json ( res , 200 , agent . queueMessage ({ chatId :String ( body . sessionId ?? '' ), text :body . message })); } 1937catch ( 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). 1940if ( path === '/api/chat/answer' && method === 'POST' ) { 1941const body = await readBody ( req ); 1942try { return json ( res , 200 , await agent . answerQuestion ({ chatId :String ( body . sessionId ?? '' ), callId :String ( body . callId ?? '' ), answers :body . answers , skip :body . skip === true })); } 1943catch ( e ) { return error ( res , e . code === 'question-gone' ?409 :400 , e . message ); } 1944} 1945// A message for one helper (#4749). 1946if ( path === '/api/chat/helper' && method === 'POST' ) { 1947const body = await readBody ( req ); 1948try { return json ( res , 200 , await agent . messageHelper ({ chatId :String ( body . sessionId ?? '' ), helperId :body . helperId , text :body . message , delivery :body . delivery })); } 1949catch ( e ) { return error ( res , e . code === 'helper-idle' || e . code === 'helper-refused' ?409 :400 , e . message ); } 1950} 1951if ( path === '/api/chat/queue/cancel' && method === 'POST' ) { 1952const body = await readBody ( req ); 1953try { return json ( res , 200 , agent . cancelQueued ({ chatId :String ( body . sessionId ?? '' ), id :String ( body . id ?? '' ) })); } 1954catch ( e ) { return error ( res , e . code === 'queue-gone' ?409 :400 , e . message ); } 1955} 1956if ( path === '/api/agent/tools' && method === 'GET' ) return json ( res , 200 , agentTools . view ()); 1957if ( path === '/api/agent/tools' && method === 'PUT' ) { 1958try { return json ( res , 200 , agentTools . update ( await readBody ( req ))); } catch ( e ) { return error ( res , 400 , e . message ); } 1959} 1960if ( path === '/api/agent/tools/custom' && method === 'POST' ) { 1961try { return json ( res , 200 , agentTools . addCustom ( await readBody ( req ))); } catch ( e ) { return error ( res , 400 , e . message ); } 1962} 1963const customToolRoute = / ^\/api\/agent\/tools\/custom\/ ([ A - Za - z0 - 9_- ] + ) $ / . exec ( path ); 1964if ( customToolRoute && method === 'PATCH' ) { 1965try { return json ( res , 200 , agentTools . editCustom ( customToolRoute [ 1 ], await readBody ( req ))); } catch ( e ) { return error ( res , 400 , e . message ); } 1966} 1967if ( customToolRoute && method === 'DELETE' ) { 1968try { return json ( res , 200 , agentTools . removeCustom ( customToolRoute [ 1 ])); } catch ( e ) { return error ( res , 400 , e . message ); } 1969} 1970if ( path === '/api/agent/pending' && method === 'GET' ) { 1971const 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). 1973if ( ! params . has ( 'chatId' )) return json ( res , 200 , { chats :agent . pendingAll () }); 1974return 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 1977that chat and call; a stale or foreign id is refused. */ 1978if ( path === '/api/chat/approval' && method === 'POST' ) { 1979const b = await readBody ( req ); 1980if ( 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' ); 1981try { return json ( res , 200 , await agent . approve ({ chatId :b . sessionId , callId :b . toolId , decision :b . decision })); } 1982catch ( 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. */ 1985if ( path === '/api/locale' && method === 'GET' ) return json ( res , 200 , systemLocale ()); 1986if ( path === '/api/shell' && method === 'GET' ) return json ( res , 200 , shellState ()); 1987if ( path === '/api/shell/prefs' && method === 'POST' ) { 1988const b = await readBody ( req ); 1989try { writeShellPrefs ( b ); } catch ( e ) { return error ( res , 400 , e . message ); } 1990return json ( res , 200 , shellState ()); 1991} 1992if ( path === '/api/shell/notify' && method === 'POST' ) { 1993const b = await readBody ( req ); 1994if ( ! shellNotifier || typeof b . title !== 'string' ) return json ( res , 200 , { shown :false }); 1995try { 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. */ 1998if ( path === '/api/chat/mode' && method === 'POST' ) { 1999const b = await readBody ( req ); 2000if ( typeof b . sessionId !== 'string' || ! [ 'manual' , 'plan' , 'bypass' ]. includes ( b . mode )) return error ( res , 400 , 'sessionId and mode (manual, plan or bypass) are required' ); 2001try { 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 2004of 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. */ 2006if ( path === '/api/chat/active' && method === 'GET' ) return json ( res , 200 , { turns :agent . runningTurns () }); 2007if ( path === '/api/chat/attach' && method === 'POST' ) { 2008const b = await readBody ( req ); 2009if ( typeof b . sessionId !== 'string' || ! b . sessionId ) return error ( res , 400 , 'sessionId is required' ); 2010const controller = new AbortController (); 2011res . on ( 'close' , () => { if ( ! res . writableEnded ) controller . abort (); }); 2012let started = false ; 2013const write = frame => { 2014if ( res . writableEnded || res . destroyed ) return ; 2015if ( ! 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 ); } 2016res . write ( ` ${ JSON . stringify ( frame )} 2017` ); 2018}; 2019const attached = agent . attach ({ chatId :b . sessionId , requestId :typeof b . requestId === 'string' ?b . requestId :null , onFrame :write , signal :controller . signal }); 2020if ( ! attached ) return error ( res , 404 , 'There is no turn to take over.' , { code :'no-turn' }); 2021await Promise . race ([ attached . ended , new Promise ( r => controller . signal . addEventListener ( 'abort' , r , { once :true }))]); 2022if ( ! res . writableEnded ) res . end (); 2023return undefined ; 2024} 2025/* Stop one chat's turn. Resolves once the turn has really ended, not when the cancel was admitted. */ 2026if ( path === '/api/chat/stop' && method === 'POST' ) { 2027const b = await readBody ( req ); 2028if ( 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). 2030const trialId = trialByChat . get ( b . sessionId ); 2031if ( trialId ) return json ( res , 200 , { stopped :await stopTrial ( trialId ), ended :'time-skip' }); 2032try { return json ( res , 200 , await agent . stop ( b . sessionId )); } catch ( e ) { return error ( res , 502 , e . message ); } 2033} 2034 2035// --- chat --------------------------------------------------------------- 2036if (( path === '/api/chat/stream' || path === '/api/plan/start-goal' ) && method === 'POST' ) { 2037const body = await readBody ( req , 12 * 1024 * 1024 ); 2038if ( path === '/api/plan/start-goal' ) { body . message = '/plan start' ; if ( typeof body . planId !== 'string' ) return error ( res , 400 , 'planId is required' ); } 2039let 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 );} 2040if ( 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 );} 2041else 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". 2043const message = body . goalAction === 'resume' ?'/goal resume' :String ( body . message ?? '' ). trim (); 2044if ( ! message ) return error ( res , 400 , 'message is required' ); 2045/* Which workspace the caller is in, so a skill narrowed to one project 2046does not fire in another. */ 2047const workspaceId = typeof body . workspaceId === 'string' ?body . workspaceId :null ; 2048 2049res . writeHead ( 200 , { 2050'content-type' :'application/x-ndjson; charset=utf-8' , 2051'cache-control' :'no-cache, no-transform' , 2052connection :'keep-alive' , 2053}); 2054keepStreamAlive ( res ); // #4878: a quiet turn stays open; the timer ends with the response 2055const controller = new AbortController (); 2056res . 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 2059detaches from the turn (it keeps running in the Harness); Stop is its own request. */ 2060const chatId = typeof body . sessionId === 'string' && body . sessionId ?body . sessionId :null ; 2061const 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 ; 2066if ( chatId && ! agentSkip ) { 2067const capability = agent . status (); 2068if ( capability . state !== 'unavailable' ) { 2069const skipped = mcpSkippedNotices ( capability . skippedServers ); 2070for ( const notice of skipped ) res . write ( ` ${ JSON . stringify ({ type : 'notice' , ... notice })} \n` ); 2071await runAgentTurn ({ res, controller, chatId, body, message, workspaceId, images}); 2072res . end (); 2073return undefined ; 2074} 2075res . 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' ) { 2077res . 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). 2081const plain = withPlainStatus ( frame => { if ( ! res . writableEnded && ! res . destroyed ) res . write ( ` ${ JSON . stringify ( frame )} \n` ); }); 2082res . on ( 'close' , () => plain . dispose ()); 2083await runTurn ({ 2084 message, 2085history :Array . isArray ( body . history ) ?body . history :[], 2086onFrame :plain , 2087signal :controller . signal , 2088 req, 2089client :'Strata chat' , 2090 workspaceId, 2091sessionId :typeof body . sessionId === 'string' ?body . sessionId :null , 2092remoteModel :body . remoteModel ?? null , 2093nativeModelId :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}); 2096res . end (); 2097return undefined ; 2098} 2099 2100return error ( res , 404 , `No route for ${ method } ${ path } ` ); 2101} 2102 2103/* -------------------------------------------------- OpenAI-compatible API --- */ 2104 2105async function openai ( req , res , path , method ) { 2106if ( ! serving . authorized ( req )) return error ( res , 401 , 'Invalid API key' ); 2107if ( native . state (). instances . length ){ 2108if ( 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 }}))}); 2109if ( 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} 2111if ( path === '/v1/responses' && method === 'POST' ) return error ( res , 503 , 'Load a native Strata model to use the Responses API.' ); 2112 2113if ( path === '/v1/models' && method === 'GET' ) { 2114const runtime = runtimeState (); 2115return 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 2118if (( path === '/v1/chat/completions' || path === '/v1/messages' ) && method === 'POST' ) { 2119if ( store . get (). serving ?. pauseServing ) return error ( res , 503 , 'New API requests are paused. Resume them in Serving.' ); 2120const body = await readBody ( req ); 2121const client = clientName ( req ); 2122const 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. 2125const workspaceId = typeof body . workspaceId === 'string' ?body . workspaceId :null ; 2126 2127const messages = anthropic 2128 ?[ 2129 ...( body . system ?[{ role :'system' , content :body . system }] :[]), 2130 ...( body . messages ?? []), 2131] 2132 :( body . messages ?? []); 2133const last = [ ...messages ]. reverse (). find (( m ) => m . role === 'user' ); 2134const text = 2135typeof last ?. content === 'string' 2136 ?last . content 2137 :Array . isArray ( last ?. content ) 2138 ?last . content . map (( c ) => c . text ?? '' ). join ( ' ' ) 2139 :'' ; 2140 2141if ( ! text ) return error ( res , 400 , 'No user message found' ); 2142 2143runtimeState (); 2144let loaded ; 2145try { loaded = runtimeModels . resolve ( body . model );} 2146catch ( err ){ return error ( res , 409 , err . message );} 2147loaded = { ...loaded , id :loaded . apiModelId }; 2148 2149const id = uid ( 'chatcmpl' ); 2150const created = Math . floor ( Date . now () / 1000 ); 2151const wantsStream = body . stream === true ; 2152const started = Date . now (); 2153const controller = new AbortController (); 2154res . on ( 'close' , () => { if ( ! res . writableEnded ) controller . abort (); }); 2155 2156if ( ! wantsStream ) { 2157let out = '' ; 2158let usage = { tokensIn :null , tokensOut :null }; 2159const result = await runTurn ({ 2160message :text , 2161runtimeModelId :loaded . apiModelId , 2162history :messages . slice ( 0 , - 1 ), 2163onFrame :( frame ) => { 2164if ( frame . type === 'delta' ) out += frame . text ; 2165if ( frame . type === 'done' ) usage = { tokensIn :frame . tokensIn , tokensOut :frame . tokensOut }; 2166}, 2167 client, 2168 req, 2169 workspaceId, 2170signal :controller . signal , 2171}); 2172if ( result ?. error ) return error ( res , 500 , result . error ); 2173return anthropic 2174 ?json ( res , 200 , { 2175 id, 2176type :'message' , 2177role :'assistant' , 2178model :loaded . id , 2179content :[{ type :'text' , text :out }], 2180usage :{ input_tokens :usage . tokensIn , output_tokens :usage . tokensOut }, 2181}) 2182 :json ( res , 200 , { 2183 id, 2184object :'chat.completion' , 2185 created, 2186model :loaded . id , 2187choices :[{ index :0 , message :{ role :'assistant' , content :out }, finish_reason :'stop' }], 2188usage :{ 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 2192res . writeHead ( 200 , { 2193'content-type' :'text/event-stream; charset=utf-8' , 2194'cache-control' :'no-cache, no-transform' , 2195connection :'keep-alive' , 2196}); 2197const write = ( payload ) => res . write ( `data: ${ JSON . stringify ( payload )} \n\n` ); 2198 2199if ( ! anthropic ) { 2200write ({ id, object :'chat.completion.chunk' , created, model :loaded . id , choices :[{ index :0 , delta :{ role :'assistant' }, finish_reason :null }] }); 2201} else { 2202res . write ( `event: message_start\ndata: ${ JSON . stringify ({ type : 'message_start' , message : { id , role : 'assistant' , model : loaded . id } })} \n\n` ); 2203} 2204 2205await runTurn ({ 2206message :text , 2207runtimeModelId :loaded . apiModelId , 2208history :messages . slice ( 0 , - 1 ), 2209 workspaceId, 2210onFrame :( frame ) => { 2211if ( frame . type === 'delta' ) { 2212if ( anthropic ) { 2213res . 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 { 2215write ({ id, object :'chat.completion.chunk' , created, model :loaded . id , choices :[{ index :0 , delta :{ content :frame . text }, finish_reason :null }] }); 2216} 2217} 2218if ( frame . type === 'done' && ! anthropic ) { 2219write ({ 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} 2221if ( frame . type === 'error' ) { 2222if ( anthropic ) res . write ( `event: error\ndata: ${ JSON . stringify ({ type : 'error' , error : { type : 'api_error' , message : frame . message } })} \n\n` ); 2223else write ({ error :{ message :frame . message , type :'server_error' } }); 2224} 2225}, 2226signal :controller . signal , 2227 client, 2228 req, 2229}); 2230 2231if ( anthropic ) { 2232res . write ( `event: message_stop\ndata: ${ JSON . stringify ({ type : 'message_stop' })} \n\n` ); 2233} else { 2234res . write ( 'data: [DONE]\n\n' ); 2235} 2236res . end (); 2237void started ; 2238return undefined ; 2239} 2240 2241return 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 ) { 2268if ( ! existsSync ( DIST )) { 2269res . writeHead ( 200 , { 'content-type' :'text/html; charset=utf-8' }); 2270res . 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> 2276For a single port run <code>npm run build:web && 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); 2281return ; 2282} 2283 2284const safe = normalize ( path ). replace ( / ^ ( \.\. [ / \\ ]) +/ , '' ); 2285let file = join ( DIST , safe ); 2286if ( ! file . startsWith ( DIST )) return error ( res , 403 , 'Forbidden' ); 2287 2288if ( ! existsSync ( file ) || statSync ( file ). isDirectory ()) { 2289if ( extname ( path )) return error ( res , 404 , 'Asset not found' ); 2290const index = join ( DIST , 'index.html' ); 2291if ( ! existsSync ( index )) return error ( res , 404 , 'Not found' ); 2292file = index ; 2293} 2294 2295const type = MIME [ extname ( file )] ?? 'application/octet-stream' ; 2296const size = statSync ( file ). size ; 2297const headers = { 'content-type' :type , 'cache-control' :file . endsWith ( 'index.html' ) ?'no-store' :'public, max-age=3600' , 'accept-ranges' :'bytes' }; 2298if ( req . headers . range ) { 2299const match = /^bytes= ( \d * ) - ( \d * ) $ / . exec ( req . headers . range ); 2300const start = match ?.[ 1 ] ?Number ( match [ 1 ]) :match ?.[ 2 ] ?Math . max ( 0 , size - Number ( match [ 2 ])) :NaN ; 2301const end = match ?.[ 1 ] && match [ 2 ] ?Math . min ( size - 1 , Number ( match [ 2 ])) :size - 1 ; 2302if ( ! Number . isSafeInteger ( start ) ||! Number . isSafeInteger ( end ) || start > end || start < 0 || start >= size ){ res . writeHead ( 416 ,{ 'content-range' :`bytes */ ${ size } ` }); res . end (); return ;} 2303res . writeHead ( 206 ,{ ...headers , 'content-range' :`bytes ${ start } - ${ end } / ${ size } ` , 'content-length' :end - start + 1 }); 2304if ( req . method === 'HEAD' ) res . end (); else createReadStream ( file ,{ start, end}). pipe ( res ); 2305return ; 2306} 2307res . writeHead ( 200 ,{ ...headers , 'content-length' :size }); 2308if ( req . method === 'HEAD' ) res . end (); else createReadStream ( file ). pipe ( res ); 2309} 2310 2311/* ------------------------------------------------------------------ start --- */ 2312 2313server . on ( 'error' , error => { 2314if ( server . listening ) { console . error ( `[strata] ${ error . message } ` ); return ; } 2315// a taken or Windows-reserved port: one plain sentence instead of a stack trace 2316console . error ( `[strata] ${ listenProblem ( error , PORT , HOST )} ` ); 2317process . exit ( 1 ); 2318}); 2319server . listen ( PORT , HOST , () => { 2320if ( 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. 2322if ( control && process . env . STRATA_PACKAGED === '1' ) control . cleanup (). catch (() => {}); 2323}); 2324 2325let stopping = false ; 2326const shutdown = async () => { 2327if ( stopping ) return ; stopping = true ; 2328clearInterval ( taskTimer ); tasks . close (); 2329const 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 2330server . close (); server . closeAllConnections ?.(); 2331await Promise . allSettled ([ localShare . stop (), cloudflare . stop (), native . close (), agent . close ()]); 2332process . 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' ) { 2339const parent = process . ppid ; 2340const gone = () => { 2341if ( process . ppid !== parent ) return true ; 2342try { process . kill ( parent , 0 ); return false ; } catch ( e ) { return e . code === 'ESRCH' ; } 2343}; 2344setInterval (() => { if ( gone ()) void shutdown (); }, 1000 ). unref (); 2345} 2346 2347export { server , VARIANTS };