okami.mom/strata

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

Niko1221Merge f-023-int into f-023-guifcb0c2d0e

main
9.2 KiB160 linesraw
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 = {}) {
27  const 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`.
30  for (const [k, v] of Object.entries(externalEnvironment(base))) {
31    if (v === undefined || !KEEP.test(k) || SECRET_NAME.test(k)) continue;
32    out[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.
36  return { ...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.
45  const candidates = [env.STRATA_HARNESS_DIR, bundledDir, componentsDir ? join(componentsDir, 'harness') : null].filter(Boolean);
46  if (!candidates.length) return { ok: false, reason: 'The agent component (DeepSeek Harness) is not installed.' };
47  for (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.
49    const nested = join(dir, 'apps', 'cli', 'lib', 'bin.js');
50    const bin = existsSync(nested) ? nested : join(dir, 'lib', 'bin.js');
51    if (!existsSync(bin)) continue;
52    if (!existsSync(join(dir, 'node_modules'))) return { ok: false, reason: `The agent component at ${dir} has no installed dependencies.` };
53    let version = null;
54    try { version = JSON.parse(readFileSync(existsSync(nested) ? join(dir, 'apps', 'cli', 'package.json') : join(dir, 'package.json'), 'utf8')).version ?? null; } catch { /* version is informational */ }
55    return { ok: true, dir, bin, version };
56  }
57  return { 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} */
63  info = null;
64  exited = null;
65  #onExit;
66
67  constructor({ harness, home, patchFile, cwd, env = {}, nodePath = process.execPath, logFile = null, pidFile = null, onExit = () => {} }) {
68    Object.assign(this, { harness, home, patchFile, cwd, extraEnv: env, nodePath, logFile, pidFile });
69    this.#onExit = onExit;
70  }
71
72  get pid() { return this.#child?.pid ?? null; }
73  get running() { return this.#child !== null && this.exited === null; }
74
75  /** Start the agent and resolve with its loopback URL and launch token. */
76  async start({ timeoutMs = 120_000 } = {}) {
77    mkdirSync(this.home, { recursive: true });
78    mkdirSync(this.cwd, { recursive: true });
79    const args = [this.harness.bin, '--profile', 'web', '--patch', this.patchFile, '--port', '0', '--no-open'];
80    const child = spawn(this.nodePath, args, {
81      cwd: this.cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
82      env: agentEnvironment(process.env, { ...this.extraEnv, DSH_HOME: this.home }),
83    });
84    this.#child = child;
85    let text = '';
86    const log = [];
87    const keep = chunk => { log.push(chunk.toString()); if (log.length > 200) log.shift(); };
88    child.on('exit', (code, signal) => {
89      this.exited = { code, signal };
90      if (this.logFile) { try { writeFileSync(this.logFile, redact(log.join(''), Object.values(this.extraEnv))); } catch { /* best effort */ } }
91      this.#onExit(this.exited);
92    });
93    child.stderr.on('data', keep);
94    const info = await new Promise((resolveInfo, reject) => {
95      const timer = setTimeout(() => reject(new Error(`the agent did not print its address within ${Math.round(timeoutMs / 1000)}s`)), timeoutMs);
96      child.stdout.on('data', chunk => {
97        keep(chunk);
98        text += chunk.toString();
99        const m = URL_PATTERN.exec(text);
100        if (m) { clearTimeout(timer); resolveInfo({ port: Number(m[1]), token: m[2], baseUrl: `http://127.0.0.1:${m[1]}` }); }
101      });
102      child.on('exit', code => { clearTimeout(timer); reject(new Error(`the agent exited during start (code ${code}): ${redact(log.join('').slice(-600), Object.values(this.extraEnv))}`)); });
103      child.on('error', e => { clearTimeout(timer); reject(e); });
104    }).catch(async error => { await this.stop(); throw error; });
105    this.info = info;
106    if (this.pidFile) { try { writeFileSync(this.pidFile, JSON.stringify({ pid: child.pid, at: new Date().toISOString() })); } catch { /* the record is a courtesy */ } }
107    return info;
108  }
109
110  /** Stop this process and its children. Only ever touches the PID this object started. */
111  async stop({ graceMs = 3000 } = {}) {
112    const child = this.#child;
113    if (!child || this.exited) return;
114    const done = new Promise(r => child.once('exit', r));
115    if (process.platform === 'win32') {
116      // /T takes the shells and PTYs the agent started; /PID is this child only.
117      spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true });
118    } else {
119      child.kill('SIGTERM');
120      setTimeout(() => { if (!this.exited) child.kill('SIGKILL'); }, graceMs).unref();
121    }
122    await Promise.race([done, new Promise(r => setTimeout(r, graceMs + 2000))]);
123    if (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) {
129  if (!Number.isInteger(pid) || pid <= 0) return null;
130  if (process.platform === 'win32') {
131    const r = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', utf8Script(`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`)], { encoding: 'utf8', windowsHide: true, timeout: 15000 });
132    return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;
133  }
134  const r = spawnSync('ps', ['-p', String(pid), '-o', 'args='], { encoding: 'utf8' });
135  return 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) {
144  if (!existsSync(pidFile)) return null;
145  let pid = null;
146  try { pid = Number(JSON.parse(readFileSync(pidFile, 'utf8')).pid); } catch { /* unreadable record */ }
147  rmSync(pidFile, { force: true });
148  const cmd = commandLineOf(pid);
149  if (!cmd || !/lib[\\/]bin\.js/.test(cmd) || !/--profile web/.test(cmd)) return null;
150  if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true });
151  else { try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ } }
152  return pid;
153}
154
155/** Remove any occurrence of a secret value from text bound for a log. */
156export function redact(text, secrets) {
157  let out = String(text);
158  for (const s of secrets) if (typeof s === 'string' && s.length >= 6) out = out.split(s).join('[redacted]');
159  return out.replace(/token=[A-Za-z0-9_-]+/g, 'token=[redacted]');
160}