okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fcb0c2d0e
main
1/** 2* Locates and runs the pinned DeepSeek Harness (`dsh`) for the web profile. 3* 4* The Harness is a separate component, not part of the host: it is found through `STRATA_HARNESS_DIR` 5* (or `<components>/harness`), checked for the files a run needs, and started with the Strata profile 6* on a loopback port the OS picks. Nothing here downloads or installs anything. 7* 8* One process, one gateway, many sessions: every chat is a Harness session inside it, and cancelling 9* one chat never touches the process. Stopping the process is a lifecycle act (shutdown, or a model 10* route change while idle), never a way to implement Stop. 11*/ 12import { spawn , spawnSync } from 'node:child_process' ; 13import { existsSync , mkdirSync , readFileSync , rmSync , writeFileSync } from 'node:fs' ; 14import { join , resolve } from 'node:path' ; 15import { externalEnvironment } from '../external-env.mjs' ; 16import { utf8Script } from '../powershell-utf8.mjs' ; 17 18const URL_PATTERN = / http:\/\/127\.0\.0\.1: ( \d + ) \/\?token= ([ A - Za - z0 - 9_- ] + ) / ; 19 20/** Environment names that carry ambient credentials and must not reach the agent unless named. */ 21const SECRET_NAME = / ( KEY | TOKEN | SECRET | PASSWORD | PASSWD | CREDENTIAL | AUTH ) / i ; 22/** Names the agent and its shell tools need to behave like a normal user process. */ 23const KEEP = / ^ ( PATH | PATHEXT | SYSTEMROOT | WINDIR | COMSPEC | TEMP | TMP | TMPDIR | HOME | USERPROFILE | HOMEDRIVE | HOMEPATH | APPDATA | LOCALAPPDATA | PROGRAMDATA | PROGRAMFILES ( \(X86\) ) ?| PROGRAMW6432 | COMMONPROGRAMFILES ( \(X86\) ) ?| USERNAME | USERDOMAIN | COMPUTERNAME | OS | PROCESSOR_ARCHITECTURE | NUMBER_OF_PROCESSORS | LANG | LC_ALL | TERM | SHELL | USER | LOGNAME | XDG_. *| SYSTEMDRIVE | PSMODULEPATH ) $ / i ; 24 25/** The environment the agent gets: a filtered copy of the host's, plus exactly the names passed in `extra`. */ 26export function agentEnvironment ( base = process . env , extra = {}) { 27const out = {}; 28// The shell and tools the assistant runs for the person are the person's own programs: they get the environment the AppImage was 29// started from, never Strata's bundled libraries and GTK/GIO settings (external-env.mjs). Outside an AppImage this is `base`. 30for ( const [ k , v ] of Object . entries ( externalEnvironment ( base ))) { 31if ( v === undefined || ! KEEP . test ( k ) || SECRET_NAME . test ( k )) continue ; 32out [ k ] = v ; 33} 34// DSH_PERMISSION_MODE is the composition default for a session no chat mode has touched (a child agent, a 35// seeded session): the strictest sandbox, which matches the Manual preset, never the Harness's wider default. 36return { ...out , DSH_TELEMETRY_DISABLED :'1' , DSH_PERMISSION_MODE :'read-only' , NODE_USE_SYSTEM_CA :'1' , ...extra }; 37} 38 39/** 40* Find a usable Harness. Returns `{ ok:true, dir, bin, version }` or `{ ok:false, reason }`; the reason 41* is user-readable because it becomes the capability state shown in the app. 42*/ 43export function resolveHarness ({ env= process . env , componentsDir= null , bundledDir= null } = {}) { 44// Order: an explicit folder, the folder the installer ships next to the host, then the user's component folder. 45const candidates = [ env . STRATA_HARNESS_DIR , bundledDir , componentsDir ?join ( componentsDir , 'harness' ) :null ]. filter ( Boolean ); 46if ( ! candidates . length ) return { ok :false , reason :'The agent component (DeepSeek Harness) is not installed.' }; 47for ( const dir of candidates . map ( c => resolve ( c ))) { 48// A source checkout keeps the CLI in apps/cli; the installer's pruned production copy IS the CLI package. 49const nested = join ( dir , 'apps' , 'cli' , 'lib' , 'bin.js' ); 50const bin = existsSync ( nested ) ?nested :join ( dir , 'lib' , 'bin.js' ); 51if ( ! existsSync ( bin )) continue ; 52if ( ! existsSync ( join ( dir , 'node_modules' ))) return { ok :false , reason :`The agent component at ${ dir } has no installed dependencies.` }; 53let version = null ; 54try { version = JSON . parse ( readFileSync ( existsSync ( nested ) ?join ( dir , 'apps' , 'cli' , 'package.json' ) :join ( dir , 'package.json' ), 'utf8' )). version ?? null ; } catch { /* version is informational */ } 55return { ok :true , dir, bin, version}; 56} 57return { ok :false , reason :`The agent component was not found at ${ candidates . join ( ' or ' )} . Install or repair it.` }; 58} 59 60export class HarnessProcess { 61 #child= null ; 62/** @type { {baseUrl:string, token:string, port:number}|null } */ 63info = null ; 64exited = null ; 65 #onExit; 66 67constructor ({ harness, home, patchFile, cwd, env= {}, nodePath= process . execPath , logFile= null , pidFile= null , onExit= () => {} }) { 68Object . assign ( this , { harness, home, patchFile, cwd, extraEnv :env , nodePath, logFile, pidFile}); 69this . #onExit= onExit ; 70} 71 72get pid () { return this . #child?. pid ?? null ; } 73get running () { return this . #child!== null && this . exited === null ; } 74 75/** Start the agent and resolve with its loopback URL and launch token. */ 76async start ({ timeoutMs= 120_000 } = {}) { 77mkdirSync ( this . home , { recursive :true }); 78mkdirSync ( this . cwd , { recursive :true }); 79const args = [ this . harness . bin , '--profile' , 'web' , '--patch' , this . patchFile , '--port' , '0' , '--no-open' ]; 80const child = spawn ( this . nodePath , args , { 81cwd :this . cwd , windowsHide :true , stdio :[ 'ignore' , 'pipe' , 'pipe' ], 82env :agentEnvironment ( process . env , { ...this . extraEnv , DSH_HOME :this . home }), 83}); 84this . #child= child ; 85let text = '' ; 86const log = []; 87const keep = chunk => { log . push ( chunk . toString ()); if ( log . length > 200 ) log . shift (); }; 88child . on ( 'exit' , ( code , signal ) => { 89this . exited = { code, signal}; 90if ( this . logFile ) { try { writeFileSync ( this . logFile , redact ( log . join ( '' ), Object . values ( this . extraEnv ))); } catch { /* best effort */ } } 91this . #onExit( this . exited ); 92}); 93child . stderr . on ( 'data' , keep ); 94const info = await new Promise (( resolveInfo , reject ) => { 95const timer = setTimeout (() => reject ( new Error ( `the agent did not print its address within ${ Math . round ( timeoutMs / 1000 )} s` )), timeoutMs ); 96child . stdout . on ( 'data' , chunk => { 97keep ( chunk ); 98text += chunk . toString (); 99const m = URL_PATTERN . exec ( text ); 100if ( m ) { clearTimeout ( timer ); resolveInfo ({ port :Number ( m [ 1 ]), token :m [ 2 ], baseUrl :`http://127.0.0.1: ${ m [ 1 ]} ` }); } 101}); 102child . on ( 'exit' , code => { clearTimeout ( timer ); reject ( new Error ( `the agent exited during start (code ${ code } ): ${ redact ( log . join ( '' ). slice ( - 600 ), Object . values ( this . extraEnv ))} ` )); }); 103child . on ( 'error' , e => { clearTimeout ( timer ); reject ( e ); }); 104}). catch ( async error => { await this . stop (); throw error ; }); 105this . info = info ; 106if ( this . pidFile ) { try { writeFileSync ( this . pidFile , JSON . stringify ({ pid :child . pid , at :new Date (). toISOString () })); } catch { /* the record is a courtesy */ } } 107return info ; 108} 109 110/** Stop this process and its children. Only ever touches the PID this object started. */ 111async stop ({ graceMs= 3000 } = {}) { 112const child = this . #child; 113if ( ! child || this . exited ) return ; 114const done = new Promise ( r => child . once ( 'exit' , r )); 115if ( process . platform === 'win32' ) { 116// /T takes the shells and PTYs the agent started; /PID is this child only. 117spawnSync ( 'taskkill' , [ '/PID' , String ( child . pid ), '/T' , '/F' ], { windowsHide :true }); 118} else { 119child . kill ( 'SIGTERM' ); 120setTimeout (() => { if ( ! this . exited ) child . kill ( 'SIGKILL' ); }, graceMs ). unref (); 121} 122await Promise . race ([ done , new Promise ( r => setTimeout ( r , graceMs + 2000 ))]); 123if ( this . pidFile ) rmSync ( this . pidFile , { force :true }); 124} 125} 126 127/** The command line of a running process, or null. Used only to confirm a recorded PID is still our agent. */ 128function commandLineOf ( pid ) { 129if ( ! Number . isInteger ( pid ) || pid <= 0 ) return null ; 130if ( process . platform === 'win32' ) { 131const r = spawnSync ( 'powershell' , [ '-NoProfile' , '-NonInteractive' , '-Command' , utf8Script ( `(Get-CimInstance Win32_Process -Filter "ProcessId= ${ pid } ").CommandLine` )], { encoding :'utf8' , windowsHide :true , timeout :15000 }); 132return r . status === 0 && r . stdout . trim () ?r . stdout . trim () :null ; 133} 134const r = spawnSync ( 'ps' , [ '-p' , String ( pid ), '-o' , 'args=' ], { encoding :'utf8' }); 135return r . status === 0 && r . stdout . trim () ?r . stdout . trim () :null ; 136} 137 138/** 139* A host that died without stopping its agent leaves the agent running, still holding its sessions' 140* writer locks, so the next start could not resume a chat. The agent records its PID; at the next start 141* a recorded PID is stopped only when it is still a `dsh` web launch (never a reused PID). 142*/ 143export function stopStaleAgent ( pidFile ) { 144if ( ! existsSync ( pidFile )) return null ; 145let pid = null ; 146try { pid = Number ( JSON . parse ( readFileSync ( pidFile , 'utf8' )). pid ); } catch { /* unreadable record */ } 147rmSync ( pidFile , { force :true }); 148const cmd = commandLineOf ( pid ); 149if ( ! cmd || ! /lib [ \\ / ] bin\.js / . test ( cmd ) || ! /--profile web / . test ( cmd )) return null ; 150if ( process . platform === 'win32' ) spawnSync ( 'taskkill' , [ '/PID' , String ( pid ), '/T' , '/F' ], { windowsHide :true }); 151else { try { process . kill ( pid , 'SIGTERM' ); } catch { /* already gone */ } } 152return pid ; 153} 154 155/** Remove any occurrence of a secret value from text bound for a log. */ 156export function redact ( text , secrets ) { 157let out = String ( text ); 158for ( const s of secrets ) if ( typeof s === 'string' && s . length >= 6 ) out = out . split ( s ). join ( '[redacted]' ); 159return out . replace ( / token= [ A - Za - z0 - 9_- ] +/ g , 'token=[redacted]' ); 160}