Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(browser): create private Windows known-folder layout
Seth Wilsonf8ce964f1a25
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e4104145..b6e20f66 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -100,12 +100,6 @@ jobs:bun-version: latest- run: npm ci# Uses an installed Chrome/Edge. No browser engine download or sandbox override.- - name: Diagnose Windows browser pipe startup- if: runner.os == 'Windows'- shell: bash- run: |- bun build scripts/diagnose-browser-startup.ts --target=node --outfile .browser-startup.mjs- node .browser-startup.mjs- run: npm test -- src/capabilities/browser/reader.integration.test.ts --maxWorkers=1env:MERCURY_TEST_BROWSER: '1'diff --git a/scripts/diagnose-browser-startup.ts b/scripts/diagnose-browser-startup.tsdeleted file mode 100644index 4e871588..00000000--- a/scripts/diagnose-browser-startup.ts+++ /dev/null@@ -1,88 +0,0 @@-// Temporary CI startup diagnostic: blank page only, production network guard,-// no credential inheritance, no debug listener and no sandbox override.-import { spawn, type ChildProcess } from 'node:child_process';-import { createServer } from 'node:http';-import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';-import { tmpdir } from 'node:os';-import { basename, join, win32 } from 'node:path';-import type { Readable, Writable } from 'node:stream';-import { browserArgs, browserEnvironment, findBrowser } from '../src/capabilities/browser/launch.js';--const pause = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));-function systemEnv(): NodeJS.ProcessEnv {- const selected: NodeJS.ProcessEnv = {};- for (const name of ['SystemRoot', 'WINDIR', 'SystemDrive', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432', 'CommonProgramFiles', 'CommonProgramFiles(x86)', 'CommonProgramW6432']) {- const entry = Object.entries(process.env).find(([key]) => key.toLowerCase() === name.toLowerCase());- if (entry?.[1]) selected[name] = entry[1];- }- const root = selected.SystemRoot ?? selected.WINDIR;- if (root) selected.PATH = win32.join(root, 'System32');- return selected;-}-function exited(child: ChildProcess): boolean { return !child.pid || child.exitCode !== null || child.signalCode !== null; }--async function probe(addSystemDirectories: boolean): Promise<void> {- const executable = await findBrowser();- const profile = await mkdtemp(join(tmpdir(), 'mercury-browser-probe-'));- const proxy = createServer((_req, res) => { res.writeHead(403, { Connection: 'close' }).end(); });- proxy.on('connect', (_req, socket) => socket.destroy());- proxy.on('upgrade', (_req, socket) => socket.destroy());- let child: ChildProcess | undefined;- let stderr = '';- let failure = '';- const replies: Array<{ id: number; ms: number; result?: unknown; error?: unknown }> = [];- const started = Date.now();- try {- await mkdir(join(profile, 'Default'));- await writeFile(join(profile, 'Default', 'Preferences'), JSON.stringify({ credentials_enable_service: false, profile: { password_manager_enabled: false, default_content_setting_values: { javascript: 2, notifications: 2, geolocation: 2, media_stream_mic: 2, media_stream_camera: 2, automatic_downloads: 2 } }, autofill: { profile_enabled: false, credit_card_enabled: false } }));- await new Promise<void>((resolve, reject) => { proxy.once('error', reject); proxy.listen(0, '127.0.0.1', resolve); });- const address = proxy.address();- if (!address || typeof address === 'string') throw new Error('proxy unavailable');- const env = { ...(addSystemDirectories ? systemEnv() : {}), ...browserEnvironment(profile) };- child = spawn(executable, [...browserArgs(profile, address.port), '--enable-logging=stderr'], { stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe'], env, windowsHide: true, detached: process.platform !== 'win32' });- child.stdout?.resume();- child.stderr?.setEncoding('utf8');- child.stderr?.on('data', (chunk: string) => { stderr = (stderr + chunk).slice(0, 8192); });- child.on('error', error => { failure = error.message; });- let buffer = '';- const output = child.stdio[4] as Readable;- output.setEncoding('utf8');- output.on('error', error => { failure = error.message; });- (child.stdio[3] as Writable).on('error', error => { failure = error.message; });- output.on('data', (chunk: string) => {- buffer += chunk;- if (buffer.length > 1_000_000) { failure = 'protocol limit exceeded'; buffer = ''; return; }- let at: number;- while ((at = buffer.indexOf('\0')) >= 0) {- const raw = buffer.slice(0, at); buffer = buffer.slice(at + 1);- try { const reply = JSON.parse(raw); if (reply.id) replies.push({ id: reply.id, ms: Date.now() - started, result: reply.result, error: reply.error }); }- catch { failure = 'invalid protocol JSON'; }- }- });- (child.stdio[3] as Writable).write(JSON.stringify({ id: 1, method: 'Browser.getVersion' }) + '\0');- (child.stdio[3] as Writable).write(JSON.stringify({ id: 2, method: 'Target.getTargets' }) + '\0');- while (Date.now() - started < 30_000 && replies.length < 2 && !failure && !exited(child)) await pause(100);- console.log(JSON.stringify({ probe: addSystemDirectories ? 'system-directory-env' : 'production-env', executable: basename(executable), platform: process.platform, runtime: process.version, envKeys: Object.keys(env).sort(), elapsedMs: Date.now() - started, exitCode: child.exitCode, signalCode: child.signalCode, failure, replies, stderr: stderr.split(profile).join('<profile>') }));- } finally {- if (child && !exited(child)) {- (child.stdio[3] as Writable).write(JSON.stringify({ id: 3, method: 'Browser.close' }) + '\0');- await pause(1000);- if (!exited(child)) {- if (process.platform === 'win32') {- const root = systemEnv().SystemRoot ?? systemEnv().WINDIR;- if (!root) throw new Error('Cannot safely resolve taskkill');- const killer = spawn(win32.join(root, 'System32', 'taskkill.exe'), ['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore', windowsHide: true });- await Promise.race([new Promise<void>(resolve => { killer.once('exit', () => resolve()); killer.once('error', () => resolve()); }), pause(3000)]);- } else { try { process.kill(-child.pid!, 'SIGKILL'); } catch { child.kill('SIGKILL'); } }- for (let i = 0; i < 30 && !exited(child); i++) await pause(100);- if (!exited(child)) throw new Error('Browser probe could not confirm process exit');- }- }- proxy.closeAllConnections();- await new Promise<void>(resolve => proxy.close(() => resolve()));- await rm(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });- }-}--await probe(false);-if (process.platform === 'win32') await probe(true);diff --git a/src/capabilities/browser/guards.test.ts b/src/capabilities/browser/guards.test.tsindex 8c3732ee..453b2314 100644--- a/src/capabilities/browser/guards.test.ts+++ b/src/capabilities/browser/guards.test.ts@@ -56,9 +56,21 @@ describe('installed browser launch contract', () => {});it('does not inherit provider credentials, real home, debugging variables or proxy settings', () => {- const env = browserEnvironment('/tmp/empty', { HOME: '/real', OPENAI_API_KEY: 'secret', SSH_AUTH_SOCK: '/agent', HTTPS_PROXY: 'http://proxy', NODE_OPTIONS: '--inspect', SystemRoot: 'C:\\Windows' });+ const env = browserEnvironment('/tmp/empty', { HOME: '/real', OPENAI_API_KEY: 'secret', SSH_AUTH_SOCK: '/agent', HTTPS_PROXY: 'http://proxy', NODE_OPTIONS: '--inspect', SystemRoot: 'C:\\Windows' }, 'linux');expect(env.HOME).toBe('/tmp/empty');expect(env.SystemRoot).toBe('C:\\Windows');for (const key of ['OPENAI_API_KEY', 'SSH_AUTH_SOCK', 'HTTPS_PROXY', 'NODE_OPTIONS']) expect(env[key]).toBeUndefined();});++ it('gives Windows known-folder APIs a private conventional home layout', () => {+ const env = browserEnvironment('C:\\Temp\\isolated', { USERPROFILE: 'C:\\Users\\Owner', LOCALAPPDATA: 'C:\\Users\\Owner\\AppData\\Local', OPENAI_API_KEY: 'secret', SystemRoot: 'C:\\Windows' }, 'win32');+ expect(env).toMatchObject({+ HOME: 'C:\\Temp\\isolated\\home', USERPROFILE: 'C:\\Temp\\isolated\\home',+ LOCALAPPDATA: 'C:\\Temp\\isolated\\home\\AppData\\Local',+ APPDATA: 'C:\\Temp\\isolated\\home\\AppData\\Roaming',+ TEMP: 'C:\\Temp\\isolated', SystemRoot: 'C:\\Windows',+ });+ expect(env.OPENAI_API_KEY).toBeUndefined();+ expect(Object.values(env).some((value) => value?.includes('Owner'))).toBe(false);+ });});diff --git a/src/capabilities/browser/launch.ts b/src/capabilities/browser/launch.tsindex 7f722e45..bcfb76c0 100644--- a/src/capabilities/browser/launch.ts+++ b/src/capabilities/browser/launch.ts@@ -32,11 +32,17 @@ export function browserArgs(profile: string, proxyPort: number): string[] {}/** No provider tokens, SSH agents, cloud credentials, or real profile/home env. */-export function browserEnvironment(profile: string, env = process.env): NodeJS.ProcessEnv {+export function browserEnvironment(profile: string, env = process.env, platform = process.platform): NodeJS.ProcessEnv {+ const home = platform === 'win32' ? win32.join(profile, 'home') : profile;return {...(env.SystemRoot ? { SystemRoot: env.SystemRoot } : {}),...(env.WINDIR ? { WINDIR: env.WINDIR } : {}),- HOME: profile, USERPROFILE: profile, LOCALAPPDATA: profile, APPDATA: profile,+ HOME: home, USERPROFILE: home,+ // Windows known-folder APIs expand AppData beneath USERPROFILE. A flat+ // empty home makes Chromium unable to resolve its default profile path,+ // so it refuses the debugging pipe even with an explicit user-data-dir.+ LOCALAPPDATA: platform === 'win32' ? win32.join(home, 'AppData', 'Local') : profile,+ APPDATA: platform === 'win32' ? win32.join(home, 'AppData', 'Roaming') : profile,TMPDIR: profile, TEMP: profile, TMP: profile, XDG_CONFIG_HOME: profile, XDG_CACHE_HOME: profile,LANG: 'C.UTF-8',};diff --git a/src/capabilities/browser/reader.integration.test.ts b/src/capabilities/browser/reader.integration.test.tsindex 52efa71a..67cf68b0 100644--- a/src/capabilities/browser/reader.integration.test.ts+++ b/src/capabilities/browser/reader.integration.test.ts@@ -1,7 +1,7 @@import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';import { createServer, type Server } from 'node:http';import { stat, mkdir, writeFile } from 'node:fs/promises';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { IsolatedBrowserReader } from './reader.js';import { BrowserPipe } from './pipe.js';import { browserUrl, requestPublicResource, type BrowserTransport } from './public-request.js';@@ -59,6 +59,7 @@ describe.skipIf(process.env.MERCURY_TEST_BROWSER !== '1')('installed browser agaexpect(child.exitCode !== null || child.signalCode !== null).toBe(true);const profile = child.spawnargs.find((arg) => arg.startsWith('--user-data-dir='))?.slice('--user-data-dir='.length);if (profile) await expect(stat(profile)).rejects.toMatchObject({ code: 'ENOENT' });+ if (profile && process.platform === 'win32') await expect(stat(dirname(profile))).rejects.toMatchObject({ code: 'ENOENT' });}hits.length = 0;transportedBytes = 0;diff --git a/src/capabilities/browser/reader.ts b/src/capabilities/browser/reader.tsindex bf42f03f..4c2ddbfd 100644--- a/src/capabilities/browser/reader.ts+++ b/src/capabilities/browser/reader.ts@@ -63,8 +63,15 @@ class ReaderPage {const executable = await findBrowser(this.options.executable);this.lifetime.signal.throwIfAborted();this.profile = await mkdtemp(join(tmpdir(), 'mercury-browser-'));- await mkdir(join(this.profile, 'Default'));- await writeFile(join(this.profile, 'Default', 'Preferences'), JSON.stringify({+ const env = browserEnvironment(this.profile);+ const browserProfile = process.platform === 'win32' ? join(this.profile, 'browser') : this.profile;+ await mkdir(join(browserProfile, 'Default'), { recursive: true });+ if (process.platform === 'win32') {+ // These must exist before Chromium calls SHGetFolderPath. The entire+ // home and the separate browser profile remain inside our temp root.+ await Promise.all([env.LOCALAPPDATA!, env.APPDATA!].map((dir) => mkdir(dir, { recursive: true })));+ }+ await writeFile(join(browserProfile, 'Default', 'Preferences'), JSON.stringify({credentials_enable_service: false, profile: { password_manager_enabled: false, default_content_setting_values: { javascript: 2, notifications: 2, geolocation: 2, media_stream_mic: 2, media_stream_camera: 2, automatic_downloads: 2 } },autofill: { profile_enabled: false, credit_card_enabled: false },}));@@ -81,17 +88,11 @@ class ReaderPage {const address = this.proxy.address();this.lifetime.signal.throwIfAborted();if (!address || typeof address === 'string') throw new Error('Browser network guard could not start.');- this.child = spawn(executable, browserArgs(this.profile, address.port), {- // Keep all five descriptors as pipes, including the standard streams,- // for Chromium's inherited-descriptor transport on Windows.- stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe'],- env: browserEnvironment(this.profile),+ this.child = spawn(executable, browserArgs(browserProfile, address.port), {+ stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'],+ env,detached: process.platform !== 'win32', windowsHide: true,});- // Browser logs never reach the model or the terminal. Drain both streams- // without collecting them so a full output pipe cannot block startup.- this.child.stdout?.resume();- this.child.stderr?.resume();this.pipe = new BrowserPipe(this.child);this.pipe.onFailure = () => this.closeInBackground();this.pipe.onEvent = (event) => { void this.handleEvent(event).catch(() => this.closeInBackground()); };