Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into ethie/pm-clean

ethernet25b859a3ad44
diff --cc apps/desktop/electron/backend-env.test.ts
index c245c23ad49,36fcda19924..5ee4de5296d
--- a/apps/desktop/electron/backend-env.test.ts
+++ b/apps/desktop/electron/backend-env.test.ts
@@@ -6,37 -8,86 +8,38 @@@ import { test } from 'vitest
import {
appendUniquePathEntries,
buildDesktopBackendEnv,
- buildDesktopBackendPath,
- hermesManagedNodePathEntries,
normalizeHermesHomeRoot,
pathEnvKey,
- POSIX_SANE_PATH_ENTRIES
+ POSIX_SANE_PATH_ENTRIES,
+ profileBackendParentEnv
} from './backend-env'
-test('desktop backend PATH adds Hermes-managed bins and missing POSIX sane entries', () => {
- const result = buildDesktopBackendPath({
- hermesHome: '/Users/test/.hermes',
- venvRoot: '/Users/test/.hermes/hermes-agent/venv',
- currentPath: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
- platform: 'darwin',
- pathModule: path.posix
+test('backend env scrubs PYTHONPATH and PYTHONHOME', () => {
+ const env = buildDesktopBackendEnv({
+ currentEnv: {
+ PATH: '/usr/bin:/bin',
+ PYTHONPATH: '/leaked/other/checkout',
+ PYTHONHOME: '/leaked/python'
+ },
+ platform: 'darwin'
})
- const entries = result.split(':')
- // Both managed-Node layouts lead, POSIX-native shape first, then the venv.
- assert.deepEqual(entries.slice(0, 3), [
- '/Users/test/.hermes/node/bin',
- '/Users/test/.hermes/node',
- '/Users/test/.hermes/hermes-agent/venv/bin'
- ])
- assert.ok(entries.includes('/opt/homebrew/bin'), 'Apple Silicon Homebrew bin is added')
- assert.ok(entries.includes('/opt/homebrew/sbin'), 'Apple Silicon Homebrew sbin is added')
- assert.ok(entries.includes('/usr/local/sbin'), 'missing standard sbin is added')
-
- for (const expected of POSIX_SANE_PATH_ENTRIES) {
- assert.ok(entries.includes(expected), `${expected} should be present`)
- }
+ assert.equal(env.PYTHONPATH, '')
+ assert.equal(env.PYTHONHOME, '')
})
-test('managed Node dirs lead with the platform-native layout but always offer both', () => {
- const posix = hermesManagedNodePathEntries('/Users/test/.hermes', {
- platform: 'darwin',
- pathModule: path.posix
- })
-
- const windows = hermesManagedNodePathEntries('C:\\Users\\test\\AppData\\Local\\hermes', {
- platform: 'win32',
- pathModule: path.win32
+test('POSIX backend PATH keeps the inherited PATH first and appends missing sane entries', () => {
+ const env = buildDesktopBackendEnv({
+ currentEnv: { PATH: '/opt/homebrew/bin:/usr/bin:/bin' },
+ platform: 'darwin'
})
- // install.sh uses node/bin; install.ps1 unpacks node.exe into node\ itself.
- // Both shapes are always emitted so migrated installs keep resolving.
- assert.deepEqual(posix, ['/Users/test/.hermes/node/bin', '/Users/test/.hermes/node'])
- assert.deepEqual(windows, [
- 'C:\\Users\\test\\AppData\\Local\\hermes\\node',
- 'C:\\Users\\test\\AppData\\Local\\hermes\\node\\bin'
- ])
-})
-
-test('managed Node dirs are empty without a Hermes home', () => {
- assert.deepEqual(hermesManagedNodePathEntries(undefined, { platform: 'darwin', pathModule: path.posix }), [])
- assert.deepEqual(hermesManagedNodePathEntries('', { platform: 'win32', pathModule: path.win32 }), [])
-})
+ const entries = env.PATH.split(':')
+ assert.equal(entries[0], '/opt/homebrew/bin', 'inherited PATH keeps precedence')
+ assert.equal(entries.filter(entry => entry === '/opt/homebrew/bin').length, 1, 'no duplicates')
-test('every managed Node dir outranks the inherited PATH on both platforms', () => {
- for (const [platform, pathModule, home, inherited, delimiter] of [
- ['darwin', path.posix, '/Users/test/.hermes', '/usr/local/bin:/usr/bin', ':'],
- ['win32', path.win32, 'C:\\hermes', 'C:\\Program Files\\nodejs;C:\\Windows\\System32', ';']
- ] as const) {
- const entries = buildDesktopBackendPath({
- hermesHome: home,
- venvRoot: null,
- currentPath: inherited,
- platform,
- pathModule
- }).split(delimiter)
-
- const managed = hermesManagedNodePathEntries(home, { platform, pathModule })
- const firstInherited = Math.min(...inherited.split(delimiter).map(entry => entries.indexOf(entry)))
-
- for (const dir of managed) {
- assert.ok(
- entries.indexOf(dir) >= 0 && entries.indexOf(dir) < firstInherited,
- `${dir} must precede the inherited PATH on ${platform}`
- )
- }
+ for (const expected of POSIX_SANE_PATH_ENTRIES) {
+ assert.ok(entries.includes(expected), `${expected} should be present`)
}
})
@@@ -94,13 -178,150 +97,130 @@@ test('normalizeHermesHomeRoot maps prof
assert.equal(normalizeHermesHomeRoot('/Users/test/.hermes', { pathModule: path.posix }), '/Users/test/.hermes')
})
-test('Windows PATH casing and delimiter are preserved without POSIX sane entries', () => {
- const env = buildDesktopBackendEnv({
- hermesHome: 'C:\\Users\\test\\AppData\\Local\\hermes',
- pythonPathEntries: ['C:\\repo\\hermes-agent'],
- venvRoot: 'C:\\Users\\test\\AppData\\Local\\hermes\\hermes-agent\\venv',
- currentEnv: {
- Path: 'C:\\Windows\\System32;C:\\Windows',
- PYTHONPATH: 'C:\\existing\\pythonpath'
- },
- platform: 'win32',
- pathModule: path.win32
- })
-
+test('pathEnvKey finds the platform-cased PATH key', () => {
assert.equal(pathEnvKey({ Path: 'x' }, 'win32'), 'Path')
- assert.equal(env.PATH, undefined)
- // Windows leads with the portable layout (install.ps1 unpacks node.exe
- // straight into node\, no bin\), then the POSIX shape for migrated installs.
- assert.ok(
- env.Path.startsWith(
- 'C:\\Users\\test\\AppData\\Local\\hermes\\node;C:\\Users\\test\\AppData\\Local\\hermes\\node\\bin;'
- )
- )
- assert.ok(env.Path.includes('\\venv\\Scripts;'))
- assert.ok(env.Path.includes(';C:\\Windows\\System32;C:\\Windows'))
- assert.equal(env.Path.includes('/opt/homebrew/bin'), false)
+ assert.equal(pathEnvKey({ PATH: 'x' }, 'win32'), 'PATH')
+ assert.equal(pathEnvKey({}, 'win32'), 'PATH')
+ assert.equal(pathEnvKey({ Path: 'x' }, 'darwin'), 'PATH')
})
-test('appendUniquePathEntries drops empty entries and keeps first occurrence', () => {
- assert.equal(appendUniquePathEntries([':/a::/b', ['/a', '/c']], { delimiter: ':' }), '/a:/b:/c')
+test('appendUniquePathEntries flattens, dedupes, and preserves first occurrence', () => {
+ assert.equal(appendUniquePathEntries(['/a:/b', ['/b', '/c'], '', null], { delimiter: ':' }), '/a:/b:/c')
})
+
+ // `hermes desktop` loads its launch profile's .env/.op.env into os.environ and
+ // hands that env to Electron; these cover what a profile backend inherits (#68367).
+ function withHermesRoot(files: Record<string, string>, run: (root: string) => void) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-profile-env-'))
+
+ try {
+ for (const [rel, contents] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true })
+ fs.writeFileSync(path.join(root, rel), contents)
+ }
+
+ run(root)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ }
+
+ const ROOT_SCOPE_FILES = {
+ '.env': '\uFEFFTLON_SHIP_URL=https://moon.invalid\nexport TLON_SHIP_CODE = "root-code" # moon\nPATH=/root/bin\n',
+ '.op.env': 'OP_SERVICE_ACCOUNT_TOKEN=root-op\n',
+ 'profiles/urbot/.env': 'ANTHROPIC_API_KEY=urbot-key\n'
+ }
+
+ const ROOT_LAUNCHED_ENV = {
+ HOME: '/Users/test',
+ PATH: '/usr/bin:/bin',
+ TLON_SHIP_URL: 'https://moon.invalid',
+ TLON_SHIP_CODE: 'root-code',
+ OP_SERVICE_ACCOUNT_TOKEN: 'root-op',
+ OPENROUTER_API_KEY: 'shell-key'
+ }
+
+ test('a named profile backend does not inherit secrets the root .env/.op.env loaded into Desktop', () => {
+ withHermesRoot(ROOT_SCOPE_FILES, root => {
+ const env = profileBackendParentEnv({
+ hermesHome: root,
+ profile: 'urbot',
+ currentEnv: ROOT_LAUNCHED_ENV,
+ platform: 'linux'
+ })
+
+ // Shell exports the root dotenv never declared, and OS names, still reach the child.
+ assert.deepEqual(env, { HOME: '/Users/test', PATH: '/usr/bin:/bin', OPENROUTER_API_KEY: 'shell-key' })
+ })
+ })
+
+ test('the launch profile backend inherits the Desktop env unchanged', () => {
+ withHermesRoot(ROOT_SCOPE_FILES, root => {
+ for (const profile of ['default', null, undefined]) {
+ assert.deepEqual(
+ profileBackendParentEnv({ hermesHome: root, profile, currentEnv: ROOT_LAUNCHED_ENV, platform: 'linux' }),
+ ROOT_LAUNCHED_ENV
+ )
+ }
+ })
+ })
+
+ test('a primary backend without an explicit profile follows the sticky active_profile', () => {
+ withHermesRoot({ ...ROOT_SCOPE_FILES, active_profile: 'urbot\n' }, root => {
+ const env = profileBackendParentEnv({ hermesHome: root, profile: null, currentEnv: ROOT_LAUNCHED_ENV })
+
+ assert.equal(env.TLON_SHIP_CODE, undefined)
+ assert.equal(env.OP_SERVICE_ACCOUNT_TOKEN, undefined)
+ assert.equal(env.OPENROUTER_API_KEY, 'shell-key')
+ })
+ })
+
+ test('Desktop launched from a named profile keeps that profile out of the default backend', () => {
+ withHermesRoot(
+ {
+ '.env': 'OPENAI_API_KEY=root-key\n',
+ 'profiles/work/.env': 'TLON_SHIP_CODE=work-code\nOP_SERVICE_ACCOUNT_TOKEN=work-op\n'
+ },
+ root => {
+ const currentEnv = {
+ HERMES_HOME: path.join(root, 'profiles', 'work'),
+ TLON_SHIP_CODE: 'work-code',
+ OP_SERVICE_ACCOUNT_TOKEN: 'work-op',
+ OPENAI_API_KEY: 'shell-key'
+ }
+
+ assert.deepEqual(profileBackendParentEnv({ hermesHome: root, profile: 'default', currentEnv }), {
+ HERMES_HOME: currentEnv.HERMES_HOME,
+ OPENAI_API_KEY: 'shell-key'
+ })
+ assert.deepEqual(profileBackendParentEnv({ hermesHome: root, profile: 'work', currentEnv }), currentEnv)
+ }
+ )
+ })
+
+ test('Windows matches profile homes and dotenv names case-insensitively', () => {
+ const root = 'C:\\Users\\test\\AppData\\Local\\hermes'
+ const files = { [`${root}\\.env`]: 'TELEGRAM_BOT_TOKEN=root-token\r\n' }
+
+ const fsModule = {
+ readFileSync: file => {
+ if (!(file in files)) {
+ throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
+ }
+
+ return files[file]
+ }
+ }
+
+ const currentEnv = {
+ HERMES_HOME: 'c:\\users\\test\\appdata\\local\\HERMES',
+ Path: 'C:\\Windows',
+ Telegram_Bot_Token: 'root-token'
+ }
+
+ const scoped = (profile: string) =>
+ profileBackendParentEnv({ hermesHome: root, profile, currentEnv, platform: 'win32', fsModule })
+
+ assert.deepEqual(scoped('default'), currentEnv)
+ assert.deepEqual(scoped('urbot'), { HERMES_HOME: currentEnv.HERMES_HOME, Path: 'C:\\Windows' })
+ })
diff --cc apps/desktop/electron/backend-env.ts
index 0c0bec9a069,2ed1d67e9a0..a9ce8cda972
--- a/apps/desktop/electron/backend-env.ts
+++ b/apps/desktop/electron/backend-env.ts
@@@ -56,6 -62,65 +57,22 @@@ function appendUniquePathEntries(entrie
return ordered.join(delimiter)
}
-/**
- * Hermes-managed Node.js directories, in preferred lookup order.
- *
- * There are two on-disk layouts. `scripts/install.ps1` unpacks portable Node
- * straight into `%LOCALAPPDATA%\hermes\node` (node.exe at the root, no `bin\`);
- * `scripts/install.sh` and the node-bootstrap helper use the POSIX
- * `$HERMES_HOME/node/bin`. Emit BOTH on every platform so mixed and migrated
- * installs resolve, leading with the layout native to the current platform.
- *
- * This is the single source of truth for the ordering rule on the Node side —
- * `main.ts` imports it rather than keeping its own copy. Mirrors
- * `iter_hermes_node_dirs()` in hermes_constants.py, which the Electron main
- * process cannot import.
- */
-function hermesManagedNodePathEntries(
- hermesHome,
- { platform = process.platform, pathModule = pathModuleForPlatform(platform) }: any = {}
-) {
- if (!hermesHome) {
- return []
- }
-
- const root = pathModule.join(hermesHome, 'node')
- const bin = pathModule.join(root, 'bin')
-
- return platform === 'win32' ? [root, bin] : [bin, root]
-}
-
-function buildDesktopBackendPath({
- hermesHome,
- venvRoot,
- currentPath = '',
- platform = process.platform,
- pathModule = pathModuleForPlatform(platform)
-}: any = {}) {
- const delimiter = delimiterForPlatform(platform)
- const hermesNodeDirs = hermesManagedNodePathEntries(hermesHome, { platform, pathModule })
- const venvBin = venvRoot ? pathModule.join(venvRoot, platform === 'win32' ? 'Scripts' : 'bin') : null
- const saneEntries = platform === 'win32' ? [] : POSIX_SANE_PATH_ENTRIES
-
- return appendUniquePathEntries([hermesNodeDirs, venvBin, currentPath, saneEntries], { delimiter })
-}
-
+ function resolveHermesHomePath(hermesHome, { pathModule, homedir = os.homedir() }: any) {
+ // fish (and any shell when the value is quoted) hands a literal `~` through; path.resolve()
+ // would pin it under cwd and the Python backend inherits that absolute path via HERMES_HOME.
+ let raw = String(hermesHome)
+
+ if (raw === '~' || raw.startsWith('~/') || (pathModule === path.win32 && raw.startsWith('~\\'))) {
+ raw = pathModule.join(homedir, raw.slice(1))
+ }
+
+ return pathModule.resolve(raw)
+ }
+
+ function isProfileHome(resolved, pathModule) {
+ return pathModule.basename(pathModule.dirname(resolved)).toLowerCase() === 'profiles'
+ }
+
function normalizeHermesHomeRoot(
hermesHome,
{ pathModule = pathModuleForPlatform(process.platform), homedir = os.homedir() }: any = {}
@@@ -64,39 -129,120 +81,121 @@@
return hermesHome
}
- // fish (and any shell when the value is quoted) hands a literal `~` through; path.resolve()
- // would pin it under cwd and the Python backend inherits that absolute path via HERMES_HOME.
- let raw = String(hermesHome)
+ const resolved = resolveHermesHomePath(hermesHome, { pathModule, homedir })
- if (raw === '~' || raw.startsWith('~/') || (pathModule === path.win32 && raw.startsWith('~\\'))) {
- raw = pathModule.join(homedir, raw.slice(1))
+ return isProfileHome(resolved, pathModule) ? pathModule.dirname(pathModule.dirname(resolved)) : resolved
+ }
+
+ // OS/interpreter names a dotenv may redeclare that no child can run without.
+ const PROCESS_ENV_NAMES = new Set([
+ 'APPDATA',
+ 'COMSPEC',
+ 'HERMES_HOME',
+ 'HOME',
+ 'LANG',
+ 'LC_ALL',
+ 'LOCALAPPDATA',
+ 'PATH',
+ 'PWD',
+ 'PYTHONPATH',
+ 'SHELL',
+ 'SSL_CERT_FILE',
+ 'SYSTEMROOT',
+ 'TEMP',
+ 'TMP',
+ 'TMPDIR',
+ 'TZ',
+ 'USER',
+ 'USERPROFILE',
+ 'VIRTUAL_ENV'
+ ])
+
+ function dotenvKeyNames(contents = '') {
+ return String(contents)
+ .replace(/^\uFEFF/, '')
+ .split(/\r?\n/)
+ .flatMap(line => line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.slice(1, 2) ?? [])
+ }
+
+ function readTextOrEmpty(fsModule, file) {
+ try {
+ return String(fsModule.readFileSync(file, 'utf8'))
+ } catch {
+ return ''
}
+ }
- const resolved = pathModule.resolve(raw)
- const parent = pathModule.dirname(resolved)
+ /**
+ * Parent env for a local `hermes serve` child of `profile` (#68367).
+ *
+ * `hermes desktop` loads its launch profile's `.env`/`.op.env` into os.environ
+ * before exec'ing Electron, so `process.env` carries that profile's platform
+ * credentials. A child for ANOTHER profile would inherit them ahead of its own
+ * dotenv (`.op.env` is even skipped once OP_SERVICE_ACCOUNT_TOKEN is set) and,
+ * e.g., connect the same Tlon ship as the default gateway. Drop every name the
+ * launch profile's dotenv declares, as `_profile_action_environment` does for
+ * dashboard actions; the child reloads its own scope. The launch profile's own
+ * backend keeps the env unchanged, and shell exports the launch dotenv never
+ * declared pass through everywhere.
+ *
+ * `profile` null/empty means no `--profile` flag: the child follows the sticky
+ * `active_profile` like a bare `hermes serve` (`_apply_profile_override`).
+ */
+ function profileBackendParentEnv({
+ hermesHome,
+ profile,
+ currentEnv = process.env,
+ platform = process.platform,
+ fsModule = fs,
+ pathModule = pathModuleForPlatform(platform)
+ }: any = {}) {
+ const env = { ...(currentEnv || {}) }
- if (pathModule.basename(parent).toLowerCase() === 'profiles') {
- return pathModule.dirname(parent)
+ if (!hermesHome) {
+ return env
+ }
+
+ const fold = platform === 'win32' ? (value: string) => value.toUpperCase() : (value: string) => value
+ const inheritedHome = currentEnv?.HERMES_HOME ? resolveHermesHomePath(currentEnv.HERMES_HOME, { pathModule }) : null
+ const launchHome = inheritedHome && isProfileHome(inheritedHome, pathModule) ? inheritedHome : hermesHome
+ const name = profile || readTextOrEmpty(fsModule, pathModule.join(hermesHome, 'active_profile')).trim()
+ const targetHome = !name || name === 'default' ? hermesHome : pathModule.join(hermesHome, 'profiles', name)
+
+ if (fold(pathModule.resolve(launchHome)) === fold(pathModule.resolve(targetHome))) {
+ return env
+ }
+
+ const launchOwned = new Set(
+ ['.env', '.op.env']
+ .flatMap(file => dotenvKeyNames(readTextOrEmpty(fsModule, pathModule.join(launchHome, file))))
+ .filter(key => !PROCESS_ENV_NAMES.has(key.toUpperCase()))
+ .map(fold)
+ )
+
+ for (const key of Object.keys(env)) {
+ if (launchOwned.has(fold(key))) {
+ delete env[key]
+ }
}
- return resolved
+ return env
}
-function buildDesktopBackendEnv({
- hermesHome,
- pythonPathEntries = [],
- venvRoot,
- currentEnv = process.env,
- platform = process.platform,
- pathModule = pathModuleForPlatform(platform)
-}: any = {}) {
+/**
+ * The environment for the spawned Python backend. Electron knows ONE thing:
+ * where the interpreter is (by convention). Everything else — managed tool
+ * PATHs, browser paths, node — is composed in-process by pm when the backend
+ * spawns tools. PYTHONPATH/PYTHONHOME are scrubbed so an inherited value
+ * can't make the backend import modules from another checkout.
+ */
+function buildDesktopBackendEnv({ currentEnv = process.env, platform = process.platform }: any = {}) {
const delimiter = delimiterForPlatform(platform)
- const currentPythonPath = currentEnv?.PYTHONPATH || ''
const key = pathEnvKey(currentEnv, platform)
+ const saneEntries = platform === 'win32' ? [] : POSIX_SANE_PATH_ENTRIES
return {
- PYTHONPATH: appendUniquePathEntries([...pythonPathEntries, currentPythonPath], { delimiter }),
+ PYTHONPATH: '',
+ PYTHONHOME: '',
// Force PEP 540 UTF-8 mode in the spawned Python backend so its stdio and
// subprocess defaults are UTF-8 even on non-UTF-8 Windows locales (GBK,
// cp1252, ...). hermes_bootstrap sets this inside the child too, but only
@@@ -111,8 -263,11 +210,9 @@@
export {
appendUniquePathEntries,
buildDesktopBackendEnv,
- buildDesktopBackendPath,
delimiterForPlatform,
- hermesManagedNodePathEntries,
normalizeHermesHomeRoot,
pathEnvKey,
- POSIX_SANE_PATH_ENTRIES
+ POSIX_SANE_PATH_ENTRIES,
+ profileBackendParentEnv
}
diff --cc apps/desktop/electron/main.ts
index 2a11b4dede4,2820a547ca6..9d2e85f91f0
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -65,15 -64,15 +65,15 @@@ import
import { dashboardFallbackArgs } from './backend-command'
import { createBackendConnectionState } from './backend-connection-state'
import { BackendDialClaims } from './backend-dial-claim'
- import { buildDesktopBackendEnv } from './backend-env'
-import {
- buildDesktopBackendEnv,
- hermesManagedNodePathEntries,
- normalizeHermesHomeRoot,
- profileBackendParentEnv
-} from './backend-env'
++import { buildDesktopBackendEnv, profileBackendParentEnv } from './backend-env'
import { createBackendExitRecoveryLatch } from './backend-exit-recovery'
import { isReauthRequiredError, waitForHermesReady } from './backend-health'
-import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'
+import {
+ backendCommandMatches,
+ type BackendOwnershipEntry,
+ createBackendOwnership,
+ createBackendShutdownCoordinator
+} from './backend-ownership'
import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes'
import { waitForDashboardPortAnnouncement } from './backend-ready'
import { recycleOwnedBackend } from './backend-recycle'