Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Panes no longer inherit the daemon's internal HARNESSD_* environment (#1181)

Deebb0027298417
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 94dd042e4..8dc30e9cb 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -25,8 +25,9 @@
// (Claude Code) works on after its first stop because the /goal hook refused it (`!goalpause <condition>`:
// refused, and the goal paused with no further output), `!compactmid` compacts in the
// middle of a turn as an automatic compaction does, `!version` answers with the version this
-// process is, `!goal` and `!goal done` (Codex) start and achieve a goal the way Codex 0.160 shows one
-// under its composer, `!browse` (Codex) leaves Codex browsing its transcript in its default fullscreen
+// process is, `!env <prefix>` with the names of the variables in its environment that start with the
+// prefix (never their values), as an agent that reads its own environment can, `!goal` and `!goal done`
+// (Codex) start and achieve a goal the way Codex 0.160 shows one under its composer, `!browse` (Codex) leaves Codex browsing its transcript in its default fullscreen
// mode, and `!browse scrollback` in its scrollback mode, `!transcript` (Claude Code) leaves it in its
// transcript view, as ctrl+o does, `!overlay` (Codex) in its transcript overlay, as ctrl+t does in its
// scrollback mode, `!search` searching its prompt history, as ctrl+r does, `!config` (Claude Code) in its
@@ -1450,6 +1451,11 @@ export async function run(engine, config = {}, { native = false } = {}) {
return
}
if (directive?.[1] === 'version') { await finish(versionLine); return }
+ if (directive?.[1] === 'env') {
+ const names = Object.keys(process.env).filter((name) => name.startsWith(directive[2])).sort()
+ await finish(`env ${directive[2]}: ${names.join(',') || '(none)'}`)
+ return
+ }
if (engine === 'codex' && directive?.[1] === 'goal') {
bottom = goalBottom(directive[2] === 'done' ? 'Goal achieved (1m)' : 'Pursuing goal (1m)')
await finish(`answer ${turn}: ${prompt}`)
diff --git a/cli/e2e/paneEnv.e2e.ts b/cli/e2e/paneEnv.e2e.ts
new file mode 100644
index 000000000..cd6a6496c
--- /dev/null
+++ b/cli/e2e/paneEnv.e2e.ts
@@ -0,0 +1,112 @@
+/**
+ * What a pane is started with, end to end: never harnessd's own variables. The master gives the core and
+ * each service the `HARNESSD_*` they run by, the service token among them. The tmux server the core
+ * started copied them into every pane it made, so every agent, terminal tile and hook had them all (found
+ * 2026-10-11: `env` in an agent's pane listed every one). The core now takes them out of its
+ * environment before it starts anything (lib/harnessdEnv.ts), and a tmux server an earlier boot started
+ * with them is told to forget them as the core takes it over (TmuxBackend `unsetServerEnvironment`).
+ */
+import { execFile } from 'node:child_process'
+import { existsSync, mkdirSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { promisify } from 'node:util'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+const exec = promisify(execFile)
+type Engine = 'claude' | 'codex'
+type Row = Record<string, any>
+
+/** What an earlier boot's master gave its core, as an owner's machine showed them in a pane: made-up values. */
+const EARLIER_BOOT = {
+ HARNESSD_SERVICE_TOKEN: 'earlier-boot-token', HARNESSD_SERVICES: 'search,viewers', HARNESSD_SERVICE_PROCESSES: 'search,viewers',
+ HARNESSD_SUPERVISED: '1', HARNESSD_WATCHDOG_MS: '30000', HARNESSD_RESTARTS: '0', HARNESSD_JUDGES_SUPERSEDED: '1',
+}
+
+const row = async (client: LocalClient, agentId: string): Promise<Row | undefined> =>
+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents.find((agent) => agent.id === agentId)
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+
+async function create(d: IsolatedDaemon, client: LocalClient, engine: Engine | 'terminal', folder: string): Promise<Row> {
+ const cwd = join(d.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, ...(engine === 'terminal' ? {} : { bypassPermission: true }) }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to start`, async () => {
+ const agent = await row(client, created.agent.id)
+ if (engine === 'terminal') return agent?.tmuxPane ? agent : null
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+}
+
+/** The `HARNESSD_*` names an agent's engine has, asked as an agent reads its environment (fakeEngine `!env`). */
+async function engineHas(client: LocalClient, agentId: string): Promise<string> {
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, 'turn_ended (!env)')
+ client.send('message', { agentId, content: '!env HARNESSD_' })
+ await ended
+ const { sessionId } = (await row(client, agentId))!
+ return until('the !env answer in the thread', async () => {
+ const page = await client.request<{ events?: Array<{ type: string; payload: Record<string, any> }> }>('session_get', { sessionId, limit: 200 }, 30_000)
+ const answer = (page.events ?? []).filter((event) => event.type === 'text_delta').map((event) => String(event.payload.content))
+ .find((text) => text.startsWith('env HARNESSD_: '))
+ return answer?.slice('env HARNESSD_: '.length) ?? null
+ }, 15_000, 250)
+}
+
+/** The `HARNESSD_*` names in the environment of the shell a pane runs, written to a file by that shell. */
+async function shellHas(d: IsolatedDaemon, pane: string, name: string): Promise<string[]> {
+ const file = join(d.root, `${name}.env`)
+ await d.tmux.run('send-keys', '-t', pane, `env > ${file}.tmp && mv ${file}.tmp ${file}`, 'Enter')
+ await until(`${name}'s shell to write its environment`, () => existsSync(file) || null, 20_000, 100)
+ return names(readFileSync(file, 'utf8'))
+}
+const names = (env: string): string[] => env.split('\n').map((line) => line.split('=')[0]).filter((name) => name.startsWith('HARNESSD_')).sort()
+
+describe('a pane\'s environment', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+ const created = async (): Promise<IsolatedDaemon> => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ return d
+ }
+
+ /** Every kind of pane the daemon makes: Claude Code, Codex and a terminal tile, each without harnessd's variables. */
+ const expectNoneIn = async (d: IsolatedDaemon, client: LocalClient): Promise<void> => {
+ for (const engine of ['claude', 'codex'] as const) {
+ const agent = await create(d, client, engine, `pane-${engine}`)
+ expect(await engineHas(client, agent.id), engine).toBe('(none)')
+ }
+ const tile = await create(d, client, 'terminal', 'pane-terminal')
+ expect(await shellHas(d, tile.tmuxPane, 'terminal')).toEqual([])
+ }
+
+ it('has none of harnessd\'s variables when the daemon started the tmux server, under a master that gave the core them', async () => {
+ const d = await created()
+ await d.start()
+ // Under a master, as on every machine: the core was given the token, and its services connected with it.
+ expect(d.log()).toMatch(/\[harnessd\] core started/)
+ const client = await LocalClient.connect(d)
+ await expectNoneIn(d, client)
+ client.close()
+ }, 300_000)
+
+ it('has none of them when the tmux server was started before the daemon, by an earlier boot that gave it them', async () => {
+ const d = await created()
+ // The server as an earlier core left it: started from an environment with that boot's HARNESSD_*, and a
+ // pane of that boot's still in it, which keeps what it was started with.
+ const earlier = join(d.root, 'earlier.env')
+ await exec('tmux', ['-S', d.tmux.socket, 'new-session', '-d', '-s', 'earlier-boot', '/bin/sh', '-c', `env > ${earlier}; sleep 600`],
+ { env: { ...d.env, ...EARLIER_BOOT }, timeout: 10_000 })
+ await until('the earlier boot\'s pane to write its environment', () => existsSync(earlier) || null, 10_000, 50)
+ expect(names(readFileSync(earlier, 'utf8'))).toEqual(Object.keys(EARLIER_BOOT).sort())
+ await d.start()
+ expect(d.log()).toContain(`[terminal] tmux: removed ${Object.keys(EARLIER_BOOT).sort().join(', ')} from the environment new panes start with`)
+ const client = await LocalClient.connect(d)
+ await expectNoneIn(d, client)
+ client.close()
+ }, 300_000)
+})
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 5620fa62b..19cb45a8c 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -56,6 +56,7 @@ import { clearSafeModeMarker, safeModeDisposition, safeModeStatusBody, SafeModeR
import { awakeTimeout } from '../lib/sleepAware.js'
import { removePidFileIf, onError } from '../lib/daemonLaunch.js'
import { ensureTmuxOnPath } from '../lib/tmuxOnPath.js'
+import { harnessdEnv, holdHarnessdEnv, isHarnessdVariable } from '../lib/harnessdEnv.js'
import { AUTH_DIR, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'
import { ENGINES, enginePathOverride } from '../lib/engineBin.js'
import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
@@ -286,7 +287,8 @@ let SCRIPT_PATH = ''
* whose core would lose to this one's and roll the update back. Not `harness start`'s `spawnDaemon`, which
* finds THIS daemon in the pid file and exits. The managed Node is re-read, so a runtime provisioned while
* this ran is the master's. `ADAPTER_UPDATED_TO` (an older build's handoff) and `HARNESSD_SAFE_MODE` (a
- * master's word to its own core) are not for the master to pass to every core it starts.
+ * master's word to its own core) are not for the master to pass to every core it starts. The rest of what
+ * this core was started with is, its `HARNESSD_*` included (lib/harnessdEnv.ts): the master is harnessd's.
*/
function startMasterHere(): void {
// A log that cannot be opened (a full disk) costs the master's lines, never the handoff.
@@ -295,7 +297,7 @@ function startMasterHere(): void {
prepareLogFile(LOG_FILE, LEGACY_LOG_FILE)
log = openSync(LOG_FILE, 'a')
} catch (e) { console.error('[update] the master starts without the log:', e instanceof Error ? e.message : e) }
- const { ADAPTER_UPDATED_TO: _handedOver, HARNESSD_SAFE_MODE: _safeMode, ...inherited } = process.env
+ const { ADAPTER_UPDATED_TO: _handedOver, HARNESSD_SAFE_MODE: _safeMode, ...inherited } = harnessdEnv()
const master = spawn(managedNodePath(), [SCRIPT_PATH, '__harnessd'], { detached: true, env: inherited, stdio: ['ignore', log, log] })
// A spawn failure (e.g. EMFILE) emits 'error' on the child; with no listener that is an
// uncaughtException. This core is leaving either way, and the next `harness start` starts the daemon.
@@ -324,7 +326,7 @@ function startMasterHere(): void {
const coreLink = connectToMaster()
/** When the devices' process starts: once there is a device, a dial's port, a Wi-Fi device or a request for one
* (core/devicesWake.ts). Asked of the master through the channel above. */
-const devicesWake = createDevicesWake({ want: (service) => coreLink.want(service), dataDir: env.ADAPTER_DATA_DIR, cableDisabled: env.CABLE_DISABLE, testDialPort: process.env.HARNESSD_TEST_DIAL_PORT })
+const devicesWake = createDevicesWake({ want: (service) => coreLink.want(service), dataDir: env.ADAPTER_DATA_DIR, cableDisabled: env.CABLE_DISABLE, testDialPort: harnessdEnv().HARNESSD_TEST_DIAL_PORT })
const daemonBoot: {
/** Stops the updater this core runs beside itself under a master too old to run it (core/updaterBeside.ts). */
@@ -426,6 +428,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// move (it tears down two dozen subsystems declared further down). Until it is ready, a staged update is
// applied by `bootHandoff`, which hands the machine over without finishing start-up.
coreLink.onUpdate((version) => { void daemonBoot.applyStagedUpdate(version) })
+ // What the master told this core, read from here: runCore took it out of process.env before anything
+ // could hand it to a child (lib/harnessdEnv.ts).
+ const harnessd = harnessdEnv()
// Agents held until the service their launch asks is ready, and the passes that launch them
// (core/agents/heldLaunches.ts): the boot's restore of only those agents, set where tmux is there to restore into.
const restorePanes = createPaneOperations()
@@ -442,14 +447,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
restore: (only, current) => restoreOnly?.(only, current) ?? Promise.resolve({ restored: [], skipped: [], failed: [], held: [], unsurveyed: [] }),
log: (line) => console.log(line),
})
- wakeGateway({ outOfProcess: servicesTheMasterRuns(process.env, KNOWN_SERVICES), signedIn: !!session, dataDir: env.ADAPTER_DATA_DIR, want: (service) => coreLink.want(service) })
+ wakeGateway({ outOfProcess: servicesTheMasterRuns(harnessd, KNOWN_SERVICES), signedIn: !!session, dataDir: env.ADAPTER_DATA_DIR, want: (service) => coreLink.want(service) })
// …or, under a master too old to run the updater, from the updater this core runs beside itself
// (core/updaterBeside.ts), in a process of its own: the core downloads no build either way.
- if (needsUpdaterBeside(process.env, coreLink.supervised, isInstalledCopy(SCRIPT_PATH, env.ADAPTER_CLI_DIR), env.ADAPTER_UPDATE_DISABLE)) {
+ if (needsUpdaterBeside(harnessd, coreLink.supervised, isInstalledCopy(SCRIPT_PATH, env.ADAPTER_CLI_DIR), env.ADAPTER_UPDATE_DISABLE)) {
daemonBoot.updaterBeside = startUpdaterBeside({
spawn: () => {
+ // Harnessd's own process: handed what this core's master said (HARNESSD_JUDGES_SUPERSEDED) explicitly.
const updater = spawn(managedNodePath(), [SCRIPT_PATH, '__service', 'updater'], {
- env: { ...process.env, HARNESSD_SERVICE: 'updater', HARNESSD_UPDATER_BESIDE_CORE: '1' }, stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
+ env: { ...harnessdEnv(), HARNESSD_SERVICE: 'updater', HARNESSD_UPDATER_BESIDE_CORE: '1' }, stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
})
updater.on('error', (e) => console.error('[update] the updater could not start:', e instanceof Error ? e.message : e))
return { onMessage: (listener) => { updater.on('message', listener) }, onExit: (listener) => { updater.on('exit', listener) }, kill: () => { updater.kill() } }
@@ -464,7 +470,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
version: VERSION, supervised: coreLink.supervised, exitForUpdate: () => process.exit(CORE_EXIT_UPDATE),
// A core on its own that an older release started: its master must answer its probe, as a master asks
// before it re-executes on a bundle; then the master takes the machine, and runs the updater.
- probeMaster: () => probeStagedMaster((done) => execFile(managedNodePath(), [SCRIPT_PATH, PROBE_COMMAND], { encoding: 'utf8' }, (error, stdout) => done(error, stdout))),
+ probeMaster: () => probeStagedMaster((done) => execFile(managedNodePath(), [SCRIPT_PATH, PROBE_COMMAND], { encoding: 'utf8', env: harnessdEnv() }, (error, stdout) => done(error, stdout))),
handOff: () => { startMasterHere(); process.exit(0) },
log: (line) => console.log(line), error: (line) => console.error(line),
})
@@ -476,7 +482,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// harnessd's master saw this core crash again and again: start nothing that could do it again. The
// master's updater runs on, and a published fix still lands (`enterSafeMode`).
- if (process.env.HARNESSD_SAFE_MODE) throw new SafeModeRequest(process.env.HARNESSD_SAFE_MODE)
+ if (harnessd.HARNESSD_SAFE_MODE) throw new SafeModeRequest(harnessd.HARNESSD_SAFE_MODE)
const savedApis = new ApiConnectionMetadata(env.ADAPTER_DATA_DIR)
// Instructions read metadata locally; a models outage must not change a workspace's tool instructions.
@@ -550,6 +556,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
for (const adopted of await adoptLegacyHarnessSessions(ownedPanes)) {
console.log(`[terminal] renamed tmux session ${adopted.from} → ${adopted.to} (pane ${adopted.paneId}) · named by a build before the harness- prefix`)
}
+ // Before the first pane this boot makes or restarts: a server an earlier core started still has that
+ // core's HARNESSD_* (the service token among them) in the environment it gives every new pane.
+ const forgotten = await tmuxBackend.unsetServerEnvironment(isHarnessdVariable)
+ if (forgotten.length) console.log(`[terminal] tmux: removed ${forgotten.join(', ')} from the environment new panes start with`)
const tmuxStartup = await tmuxBackend.inventory()
console.log(tmuxStartup.state === 'available'
? '[terminal] tmux: available'
@@ -593,20 +603,20 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const syncRecapPool = (): void => {
ports.devices?.engines(registry.active().map((session) => session.engine))
}
- const outOfProcess = servicesTheMasterRuns(process.env, KNOWN_SERVICES)
- const liveHosted = masterRunsLiveEngines(process.env, process.ppid)
- const runtimeHosted = liveHosted && masterRunsEngineRuntime(process.env, process.ppid)
+ const outOfProcess = servicesTheMasterRuns(harnessd, KNOWN_SERVICES)
+ const liveHosted = masterRunsLiveEngines(harnessd, process.ppid)
+ const runtimeHosted = liveHosted && masterRunsEngineRuntime(harnessd, process.ppid)
// An older master's explicit capability report selects compatibility. A failed worker never does.
const isolatedLive = (engine: string): boolean => liveHosted
&& readerEngine(engine) && outOfProcess.has(READER_SERVICES[engine])
- const questionControlHosted = masterRunsEngineQuestionControl(process.env, process.ppid)
+ const questionControlHosted = masterRunsEngineQuestionControl(harnessd, process.ppid)
const isolatedQuestionControl = (engine: string): boolean => questionControlHosted && isolatedLive(engine)
- const modelControlHosted = masterRunsEngineModelControl(process.env, process.ppid)
+ const modelControlHosted = masterRunsEngineModelControl(harnessd, process.ppid)
const isolatedModelControl = (engine: string): boolean => modelControlHosted && isolatedLive(engine)
- const screenHosted = masterRunsEngineScreen(process.env, process.ppid)
+ const screenHosted = masterRunsEngineScreen(harnessd, process.ppid)
const isolatedScreen = (engine: string): boolean => screenHosted && isolatedLive(engine)
- const submissionHosted = masterRunsEngineSubmission(process.env, process.ppid)
- const nativeControlHosted = masterRunsEngineNativeControl(process.env, process.ppid)
+ const submissionHosted = masterRunsEngineSubmission(harnessd, process.ppid)
+ const nativeControlHosted = masterRunsEngineNativeControl(harnessd, process.ppid)
const isolatedNativeControl = (engine: string): boolean => nativeControlHosted && isolatedLive(engine)
const isolatedSubmission = (engine: string): boolean => submissionHosted && isolatedLive(engine)
const isolatedRuntime = (engine: string): boolean => runtimeHosted && isolatedLive(engine)
@@ -840,7 +850,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
// Each service starts and is called through the host, so one that fails is logged and left off and
// the core carries on without it (core/serviceHost.ts).
- const serviceHost = createServiceHost(ports, { faults: testFaults(process.env.HARNESSD_TEST_FAULTS) })
+ const serviceHost = createServiceHost(ports, { faults: testFaults(harnessd.HARNESSD_TEST_FAULTS) })
// The DSH companions: each harness agent's viewer and verdict watch (services/viewers.ts), started below.
dshFrameContextRef = (s) => ports.viewers?.frameContext(s) ?? null
// Models (services/models.ts), started below: what an agent's frame says of its grid, from memory.
@@ -899,7 +909,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The services harnessd's master runs in their own processes (harnessd/services.ts, `HARNESSD_SERVICES`):
// only under a master, which is what gives this core the token they connect with. Their requests are
// routed to them, and answered SERVICE_UNAVAILABLE while they are down (core/serviceLinks.ts).
- const serviceToken = process.env.HARNESSD_SUPERVISED === '1' ? process.env.HARNESSD_SERVICE_TOKEN : undefined
+ const serviceToken = harnessd.HARNESSD_SUPERVISED === '1' ? harnessd.HARNESSD_SERVICE_TOKEN : undefined
const liveFor: LiveFor = (engine) => isolatedLive(engine) ? undefined : inline?.liveFor(engine)
// The relay and its E2EE (gateway/): the backend link, the sessions and the keys, which every remote
// client's frames go through, held at the same gate. In its own process by default (core/gatewayLink.ts),
@@ -1577,7 +1587,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// HARNESSD_TEST_SLOW_PROBE_MS holds each discovery probe for up to that long, at random, before it is
// applied: some scans land at once and some straddle an agent's start, as on a loaded machine. The
// end-to-end suite uses it to put a scan across an engine's start on purpose (e2e/core.e2e.ts).
- const slowProbeMs = Number(process.env.HARNESSD_TEST_SLOW_PROBE_MS) || 0
+ const slowProbeMs = Number(harnessd.HARNESSD_TEST_SLOW_PROBE_MS) || 0
const gridAssignments = createGridAssignments({ models: () => ports.models ?? MODELS_OFF, registry,
revision: (id) => restartJobs.revision(id), announce: announceSession })
const agentReconciler = new TerminalAgentReconciler({
@@ -1745,7 +1755,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onToolStart: turnHooks.onToolStart,
onTurnStop: turnHooks.onTurnStop,
onPromptHook: turnHooks.onPromptHook,
- stopHookDelayMs: Number(process.env.HARNESSD_TEST_STOP_HOOK_DELAY_MS) || 0,
+ stopHookDelayMs: Number(harnessd.HARNESSD_TEST_STOP_HOOK_DELAY_MS) || 0,
// `harness pair`, `unpair`, `remote-password`, `link connect`, `group` and `devices`: the keys are the
// gateway's, and so are these answers (gateway/start.ts).
onPair: (code) => gatewayOps.pair(code),
@@ -2615,9 +2625,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (outOfProcess.has('devices')) ports.devices = devicesLink.port
else {
serviceHost.start('devices', (core, started) => inline!.startDevices(core, started, {
- logsDir: env.HARNESS_LOGS_DIR, testDialPort: process.env.HARNESSD_TEST_DIAL_PORT,
+ logsDir: env.HARNESS_LOGS_DIR, testDialPort: harnessd.HARNESSD_TEST_DIAL_PORT,
dialSerials: process.env.HARNESS_DIAL_SERIALS?.split(',').map((serial) => serial.trim()).filter(Boolean),
- cableDisabled: env.CABLE_DISABLE, faults: testFaults(process.env.HARNESSD_TEST_FAULTS),
+ cableDisabled: env.CABLE_DISABLE, faults: testFaults(harnessd.HARNESSD_TEST_FAULTS),
}), coreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS)
// Everything the windows said while the devices were being built, and what the machine runs.
if (ports.devices) devicesLink.started(ports.devices)
@@ -2634,7 +2644,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Worktrees Harness made that no live or stopped harness uses and nothing would miss
// (services/workspaces.ts): a few minutes after start, once restored agents are back in the
// registry, then twice a day. Only the end-to-end harness shortens the first wait.
- setTimeout(() => ports.workspaces?.sweepUnused(), Number(process.env.HARNESSD_TEST_SWEEP_AFTER_MS) || 5 * 60_000).unref()
+ setTimeout(() => ports.workspaces?.sweepUnused(), Number(harnessd.HARNESSD_TEST_SWEEP_AFTER_MS) || 5 * 60_000).unref()
setInterval(() => ports.workspaces?.sweepUnused(), 12 * 3600_000).unref()
@@ -2658,7 +2668,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// starting — a client reconnecting the moment the port answered, the backend's first frames — are
// answered now, in order, by the handlers meant to answer them (see BackendSocket.openRequests).
// Only the end-to-end harness sets this: a start-up that hangs after binding, for the master's deadline.
- if (process.env.HARNESSD_TEST_HOLD_READY === '1') await new Promise<never>(() => {})
+ if (harnessd.HARNESSD_TEST_HOLD_READY === '1') await new Promise<never>(() => {})
backend.openRequests()
daemonBoot.openRequests = null
coreLink.ready()
@@ -2758,15 +2768,19 @@ const enterSafeMode = (err: unknown): void => {
/** `harness __run`: the core, as harnessd's master (or `harness start` without one) spawns it. */
export function runCore(scriptPath: string): void {
+ // First, before anything this core starts can inherit them: a tmux server, an engine, a shell
+ // (lib/harnessdEnv.ts).
+ holdHarnessdEnv()
SCRIPT_PATH = scriptPath
// Inert unless the end-to-end suite asks for its event loop to be held (core/stall.ts).
- startStalls(testFaults(process.env.HARNESSD_TEST_FAULTS))
+ startStalls(testFaults(harnessdEnv().HARNESSD_TEST_FAULTS))
// NOT `onError`: a daemon that dies here can never be updated. See `enterSafeMode`.
runForeground(readAuthSession()).catch(enterSafeMode)
}
/** `harness start -f` with `HARNESS_NO_MASTER=1`, and a start under tsx: the core alone, in the process of the command that asked for it. */
export function runCoreInForeground(session: AuthSession | null, scriptPath: string): Promise<void> {
+ holdHarnessdEnv()
SCRIPT_PATH = scriptPath
return runForeground(session)
}
diff --git a/cli/src/harnessd/AGENTS.md b/cli/src/harnessd/AGENTS.md
index 1b00acb9b..05aaca4a4 100644
--- a/cli/src/harnessd/AGENTS.md
+++ b/cli/src/harnessd/AGENTS.md
@@ -52,3 +52,11 @@ It keeps the core and the services running, and nothing else.
as that core binds. Making a process on demand bumps `HARNESSD_PROTOCOL` and sets `askedSince` to it.
A `want` is heard before the core binds too: a core signed in asks for the gateway as it starts, so the
relay comes up beside it.
+11. **`HARNESSD_*` are for harnessd's processes alone, never a child's.** What the master tells the core and
+ each service (the service token among them) leaves process.env first thing in those processes
+ (`../lib/harnessdEnv.ts` `holdHarnessdEnv`), and is read through `harnessdEnv()`, never
+ `process.env.HARNESSD_*`. Left in, every child inherited it: the tmux server the core starts copies its
+ environment into every pane, and every agent and terminal had them (found 2026-10-11). A harnessd
+ process the core starts (the updater beside it, a master it hands over to, the master's probe) is given
+ it explicitly. The core also unsets them from a tmux server an earlier boot started
+ (`TmuxBackend.unsetServerEnvironment`).
diff --git a/cli/src/lib/harnessdEnv.spec.ts b/cli/src/lib/harnessdEnv.spec.ts
new file mode 100644
index 000000000..cfc0099ac
--- /dev/null
+++ b/cli/src/lib/harnessdEnv.spec.ts
@@ -0,0 +1,76 @@
+import { execFileSync } from 'node:child_process'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+// The store is the process's: each test gets a fresh one, and never touches the runner's own process.env.
+let harnessd: typeof import('./harnessdEnv.js')
+beforeEach(async () => {
+ vi.resetModules()
+ harnessd = await import('./harnessdEnv.js')
+})
+
+/** What a master starts a core with, beside the person's own variables. */
+const started = (): NodeJS.ProcessEnv => ({
+ HOME: '/home/someone', PATH: '/usr/bin:/bin',
+ HARNESSD_SERVICE_TOKEN: 'fixture-token', HARNESSD_SUPERVISED: '1', HARNESSD_SERVICES: 'search,viewers',
+ HARNESSD_WATCHDOG_MS: '30000', HARNESSD_TEST_FAULTS: 'search.crash',
+ // Named like one, but not harnessd's: only the prefix counts.
+ HARNESS_PORT: '18473', MY_HARNESSD_NOTE: 'kept',
+})
+
+describe('harnessd\'s variables', () => {
+ it('are the HARNESSD_* ones and no others', () => {
+ expect(harnessd.isHarnessdVariable('HARNESSD_SERVICE_TOKEN')).toBe(true)
+ expect(harnessd.isHarnessdVariable('HARNESSD_TEST_FAULTS')).toBe(true)
+ expect(harnessd.isHarnessdVariable('HARNESS_PORT')).toBe(false)
+ expect(harnessd.isHarnessdVariable('MY_HARNESSD_NOTE')).toBe(false)
+ expect(harnessd.isHarnessdVariable('harnessd_service_token')).toBe(false)
+ })
+
+ it('leave the environment once held, and are still read through harnessdEnv()', () => {
+ const env = started()
+ harnessd.holdHarnessdEnv(env)
+ expect(env).toEqual({ HOME: '/home/someone', PATH: '/usr/bin:/bin', HARNESS_PORT: '18473', MY_HARNESSD_NOTE: 'kept' })
+ expect(harnessd.harnessdEnv(env)).toEqual(started())
+ })
+
+ it('are put back over what the environment has now, which changes on its own (a PATH tmux was found on)', () => {
+ const env = started()
+ harnessd.holdHarnessdEnv(env)
+ env.PATH = '/opt/homebrew/bin:/usr/bin:/bin'
+ const read = harnessd.harnessdEnv(env)
+ expect(read.PATH).toBe('/opt/homebrew/bin:/usr/bin:/bin')
+ expect(read.HARNESSD_SERVICE_TOKEN).toBe('fixture-token')
+ // A copy: what a reader does with it changes neither.
+ read.HARNESSD_SERVICE_TOKEN = 'changed'
+ expect(harnessd.harnessdEnv(env).HARNESSD_SERVICE_TOKEN).toBe('fixture-token')
+ expect(env.HARNESSD_SERVICE_TOKEN).toBeUndefined()
+ })
+
+ it('read as the environment itself before anything is held, as in a process that holds none', () => {
+ expect(harnessd.harnessdEnv(started())).toEqual(started())
+ })
+
+ it('held twice keep what the first hold took', () => {
+ const env = started()
+ harnessd.holdHarnessdEnv(env)
+ harnessd.holdHarnessdEnv(env)
+ expect(harnessd.harnessdEnv(env).HARNESSD_SERVICES).toBe('search,viewers')
+ })
+
+ it('are held from process.env when no environment is named, and a child started after it has none of them', () => {
+ const original = { ...process.env }
+ process.env.HARNESSD_SERVICE_TOKEN = 'fixture-token'
+ process.env.HARNESSD_SUPERVISED = '1'
+ try {
+ harnessd.holdHarnessdEnv()
+ expect(process.env.HARNESSD_SERVICE_TOKEN).toBeUndefined()
+ expect(harnessd.harnessdEnv().HARNESSD_SERVICE_TOKEN).toBe('fixture-token')
+ // What a child process is given when it is given nothing: process.env, as it is now.
+ const child = execFileSync(process.execPath, ['-e', 'process.stdout.write(Object.keys(process.env).filter((name) => name.startsWith("HARNESSD_")).join(","))'], { encoding: 'utf8' })
+ expect(child).toBe('')
+ } finally {
+ for (const name of Object.keys(process.env)) if (!(name in original)) delete process.env[name]
+ Object.assign(process.env, original)
+ }
+ })
+})
diff --git a/cli/src/lib/harnessdEnv.ts b/cli/src/lib/harnessdEnv.ts
new file mode 100644
index 000000000..47b155145
--- /dev/null
+++ b/cli/src/lib/harnessdEnv.ts
@@ -0,0 +1,45 @@
+/**
+ * The `HARNESSD_*` variables: what harnessd's master tells the core and each service process it starts
+ * (harnessd/supervisor.ts, harnessd/services.ts, harnessd/master.ts), among them the service token
+ * that admits a connection as one of this boot's services (localWsServer.ts, `role: 'service'`).
+ *
+ * They are for those processes alone. Left in process.env, every child inherited them: the tmux server
+ * the core starts copies the environment it starts with into the one every new pane gets, so every
+ * agent, every terminal tile and every hook they ran had them all (found 2026-10-11: `env` in an agent's
+ * pane listed every one). So the core and each service process take them out of process.env first thing
+ * (`holdHarnessdEnv`), and read them through `harnessdEnv()` instead. What harnessd's own processes
+ * need of them (the updater beside a core, a master a core hands over to, the master's probe) is passed
+ * to them explicitly.
+ */
+
+const PREFIX = 'HARNESSD_'
+
+/** What this process took out of process.env: what `harnessdEnv()` puts back for its own readers. */
+const held: Record<string, string> = {}
+
+/** Whether [name] is one of harnessd's own variables, never for a pane or anything else a process starts. */
+export function isHarnessdVariable(name: string): boolean {
+ return name.startsWith(PREFIX)
+}
+
+/**
+ * Take every `HARNESSD_*` out of [env], this process's own by default, and keep it for `harnessdEnv()`.
+ * Called before the process starts anything: a child started before it has them for good, and a tmux
+ * server started before it hands them to every pane until it is told otherwise (TmuxBackend
+ * `unsetServerEnvironment`).
+ */
+export function holdHarnessdEnv(env: NodeJS.ProcessEnv = process.env): void {
+ for (const name of Object.keys(env).filter(isHarnessdVariable)) {
+ held[name] = env[name]!
+ delete env[name]
+ }
+}
+
+/**
+ * The environment this process was started with: [env] (process.env by default) with the `HARNESSD_*`
+ * it holds back put in again. A copy, for reading what the master said, and the base of the environment
+ * of harnessd's own processes; never of anything else.
+ */
+export function harnessdEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
+ return { ...env, ...held }
+}
diff --git a/cli/src/lib/machineNames.ts b/cli/src/lib/machineNames.ts
index b536f2b59..06ee99324 100644
--- a/cli/src/lib/machineNames.ts
+++ b/cli/src/lib/machineNames.ts
@@ -17,6 +17,7 @@
*/
import { readFileSync } from 'node:fs'
import { hostname } from 'node:os'
+import { harnessdEnv } from './harnessdEnv.js'
export const MACHINE_NAMES_KEPT = 16
@@ -85,4 +86,4 @@ export function hostnameReader(file: string | undefined): () => string {
}
/** The daemon's: what its title sweep and its tmux panes read, and what titles are refused as. */
-export const machineNames = createMachineNames(hostnameReader(process.env.HARNESSD_TEST_HOSTNAME_FILE))
+export const machineNames = createMachineNames(hostnameReader(harnessdEnv().HARNESSD_TEST_HOSTNAME_FILE))
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index 6eba170ef..8f2a4c3f7 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -3,10 +3,13 @@ import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ExecFileException } from 'node:child_process'
-import { TmuxBackend, clearEnvArgs } from './tmuxBackend.js'
+import { TmuxBackend, clearEnvArgs, serverVariables, unsetServerEnvArgs } from './tmuxBackend.js'
import { clearPaneRemainOnExit, forgetTmuxServer } from './tmux.js'
import { tmuxControlGate } from './tmuxControlGate.js'
import { assumeTmuxVersion, resetTmuxVersionCache } from './tmuxVersion.js'
+import { isHarnessdVariable } from './harnessdEnv.js'
+import { resolveBinaryOnPath } from './binaryOnPath.js'
+import { isolatedTmux } from '../testing/isolatedTmux.js'
/**
* The fake tmux in these specs is a real `/bin/sh` script, and on a loaded machine one takes seconds to
@@ -736,3 +739,89 @@ describe('clearEnv command shape', () => {
expect(clearEnvArgs('$3', [])).toEqual([])
})
})
+
+// A tmux server copies the environment it was started with into every pane it makes. One started by a core
+// before it held harnessd's variables back (lib/harnessdEnv.ts) gave them to every agent and terminal, the
+// service token among them (found 2026-10-11: `env` in an agent's pane listed every one).
+describe('harnessd\'s variables in the tmux server\'s environment', () => {
+ const LISTING = 'HOME=/home/someone\nHARNESSD_SERVICE_TOKEN=fixture-token\n-HARNESSD_RESTARTS\nHARNESSD_SUPERVISED=1\nMY_HARNESSD_NOTE=kept\nHARNESSD_SUPERVISED=1\n'
+
+ it('are the ones the server lists with a value, once each, and none it already removes', () => {
+ expect(serverVariables(LISTING, isHarnessdVariable)).toEqual(['HARNESSD_SERVICE_TOKEN', 'HARNESSD_SUPERVISED'])
+ expect(serverVariables('', isHarnessdVariable)).toEqual([])
+ // A value with a newline in it: what follows is not a name.
+ expect(serverVariables('NOTE=one\n two=HARNESSD_X\n', isHarnessdVariable)).toEqual([])
+ })
+
+ it('are removed from the global environment in one invocation', () => {
+ expect(unsetServerEnvArgs(['HARNESSD_SERVICE_TOKEN', 'HARNESSD_SUPERVISED'])).toEqual([
+ 'set-environment', '-g', '-u', 'HARNESSD_SERVICE_TOKEN', ';', 'set-environment', '-g', '-u', 'HARNESSD_SUPERVISED',
+ ])
+ })
+
+ /** A tmux that lists [listing] for the global environment, or answers as one with no server; and records each call. */
+ const fakeTmux = (script: string): () => string[] => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-env-'))
+ dirs.push(dir)
+ const calls = join(dir, 'calls')
+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh\nprintf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"\n${script}\n`, { mode: 0o700 })
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ process.env.TMUX_BACKEND_CALLS = calls
+ return () => existsSync(calls) ? readFileSync(calls, 'utf8').trim().split('\n') : []
+ }
+
+ it('are unset, and named, when the server has them', async () => {
+ const calls = fakeTmux(`[ "$1" = show-environment ] && printf '${LISTING.replace(/\n/g, '\\n')}'\nexit 0`)
+ await expect(new TmuxBackend().unsetServerEnvironment(isHarnessdVariable)).resolves.toEqual(['HARNESSD_SERVICE_TOKEN', 'HARNESSD_SUPERVISED'])
+ expect(calls()).toEqual([
+ 'show-environment -g',
+ 'set-environment -g -u HARNESSD_SERVICE_TOKEN ; set-environment -g -u HARNESSD_SUPERVISED',
+ ])
+ })
+
+ it('cost one call when the server has none, and one when there is no server: the next starts without them', async () => {
+ const none = fakeTmux(`[ "$1" = show-environment ] && printf 'HOME=/home/someone\\n'\nexit 0`)
+ await expect(new TmuxBackend().unsetServerEnvironment(isHarnessdVariable)).resolves.toEqual([])
+ expect(none()).toEqual(['show-environment -g'])
+ const noServer = fakeTmux(`echo 'no server running on /tmp/tmux-501/default' >&2\nexit 1`)
+ await expect(new TmuxBackend().unsetServerEnvironment(isHarnessdVariable)).resolves.toEqual([])
+ expect(noServer()).toEqual(['show-environment -g'])
+ })
+
+ it('are named as removed only when tmux removed them', async () => {
+ const calls = fakeTmux(`[ "$1" = show-environment ] && { printf 'HARNESSD_SERVICE_TOKEN=fixture-token\\n'; exit 0; }\nexit 1`)
+ await expect(new TmuxBackend().unsetServerEnvironment(isHarnessdVariable)).resolves.toEqual([])
+ expect(calls()).toEqual(['show-environment -g', 'set-environment -g -u HARNESSD_SERVICE_TOKEN'])
+ })
+
+ it.skipIf(!resolveBinaryOnPath('tmux'))('reach no pane a real server makes once they are unset, though the panes before have them', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'tmux-backend-env-home-'))
+ dirs.push(home)
+ // The server starts as one an earlier core started did: from an environment with harnessd's variables.
+ const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => !isHarnessdVariable(name)))
+ const tmux = await isolatedTmux({ ...inherited, HOME: home, ZDOTDIR: home, HISTFILE: join(home, 'history'),
+ HARNESSD_SERVICE_TOKEN: 'fixture-token', HARNESSD_SUPERVISED: '1', HARNESSD_WATCHDOG_MS: '30000' })
+ // The backend's own bare `tmux` reaches this private server and no other.
+ vi.stubEnv('TMUX', undefined)
+ vi.stubEnv('TMUX_PANE', undefined)
+ vi.stubEnv('TMUX_TMPDIR', tmux.root)
+ const harnessdIn = async (session: string): Promise<string[]> => {
+ const file = join(home, `${session}.env`)
+ await tmux.run('new-session', '-d', '-s', session, '/bin/sh', '-c', `env > ${file}.tmp && mv ${file}.tmp ${file}; sleep 60`)
+ for (let i = 0; i < 200 && !existsSync(file); i++) await new Promise((resolve) => setTimeout(resolve, 25))
+ return readFileSync(file, 'utf8').split('\n').map((line) => line.split('=')[0]).filter(isHarnessdVariable).sort()
+ }
+ try {
+ expect(await harnessdIn('before')).toEqual(['HARNESSD_SERVICE_TOKEN', 'HARNESSD_SUPERVISED', 'HARNESSD_WATCHDOG_MS'])
+ await expect(new TmuxBackend().unsetServerEnvironment(isHarnessdVariable)).resolves.toEqual(['HARNESSD_SERVICE_TOKEN', 'HARNESSD_SUPERVISED', 'HARNESSD_WATCHDOG_MS'])
+ // The client that asks for a pane still has them: tmux gives a new pane none of the client's own but
+ // those `update-environment` names, so the pane has none.
+ expect(await harnessdIn('after')).toEqual([])
+ // And a second core finds nothing left to remove.
+ await expect(new TmuxBackend().unsetServerEnvironment(isHarnessdVariable)).resolves.toEqual([])
+ } finally {
+ vi.unstubAllEnvs()
+ await tmux.close()
+ }
+ })
+})
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 484b14480..b494d3ee6 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -110,6 +110,19 @@ export function clearEnvArgs(sessionId: string, names: readonly string[]): strin
return args
}
+/**
+ * The names `tmux show-environment -g` lists [listing] with a value that [matches] names. A `-NAME` line
+ * is one already marked for removal, which tmux keeps out of every new pane itself.
+ */
+export function serverVariables(listing: string, matches: (name: string) => boolean): string[] {
+ return [...new Set(listing.split('\n').map((line) => /^([^-=\s][^=\s]*)=/.exec(line)?.[1]).filter((name): name is string => !!name && matches(name)))]
+}
+
+/** The argv for removing [names] from the tmux server's global environment, which every new pane starts from. */
+export function unsetServerEnvArgs(names: readonly string[]): string[] {
+ return names.flatMap((name, i) => [...(i ? [';'] : []), 'set-environment', '-g', '-u', name])
+}
+
export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
readonly name = 'tmux' as const
readonly instanceId = 'tmux:default'
@@ -394,6 +407,25 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
}
}
+ /**
+ * Remove every variable [matches] names from the tmux server's global environment, and say which.
+ *
+ * A tmux server keeps the environment it was started with as its global environment, and builds every
+ * new pane's from it (with the session's own on top). A server a core started before that core held
+ * harnessd's variables back (lib/harnessdEnv.ts), an earlier boot's or an older build's, hands them to
+ * every pane it makes until it is told to forget them, and it outlives the core. Nothing to do with no
+ * server: the next one starts from this core's environment, which no longer has them. Asked once, as
+ * the core takes the server over at start; a failure costs only this, never the start.
+ */
+ async unsetServerEnvironment(matches: (name: string) => boolean): Promise<string[]> {
+ const ask = (args: string[]) => new Promise<string | null>((resolve) => {
+ run('tmux', args, { timeout: 5_000 }, (error, stdout) => resolve(error ? null : stdout))
+ })
+ const names = serverVariables(await ask(['show-environment', '-g']) ?? '', matches)
+ if (!names.length) return []
+ return await ask(unsetServerEnvArgs(names)) === null ? [] : names
+ }
+
async inventory(): Promise<TerminalInventoryResult> {
const result = await listTmuxPanes(this.owner())
if (!result.ok) return { state: 'unavailable', reason: result.error }
diff --git a/cli/src/serviceProcess.spec.ts b/cli/src/serviceProcess.spec.ts
index a18bee3a2..21bfa129e 100644
--- a/cli/src/serviceProcess.spec.ts
+++ b/cli/src/serviceProcess.spec.ts
@@ -8,10 +8,26 @@ vi.mock('./lib/localSocket.js', async (real) => ({ ...await real<object>(), loca
// The test's own console stays as it is: it is shared with every other test in this worker.
const stamped = vi.hoisted(() => ({ times: 0 }))
vi.mock('./lib/log.js', async (real) => ({ ...await real<object>(), installTimestampedConsole: () => { stamped.times++ } }))
+// What the master said leaves process.env as the process starts (lib/harnessdEnv.ts): held here, as there,
+// but in a store each test starts empty, since the process is every test's in this worker.
+const harnessd = vi.hoisted(() => ({ held: {} as Record<string, string> }))
+vi.mock('./lib/harnessdEnv.js', async (real) => {
+ const actual = await real<typeof import('./lib/harnessdEnv.js')>()
+ return {
+ ...actual,
+ holdHarnessdEnv: () => {
+ for (const name of Object.keys(process.env).filter(actual.isHarnessdVariable)) {
+ harnessd.held[name] = process.env[name]!
+ delete process.env[name]
+ }
+ },
+ harnessdEnv: () => ({ ...process.env, ...harnessd.held }),
+ }
+})
describe('a service in its own process', () => {
const title = process.title
- afterEach(() => { process.title = title; local.socket = '/data/daemon-18473.sock'; vi.restoreAllMocks() })
+ afterEach(() => { process.title = title; local.socket = '/data/daemon-18473.sock'; harnessd.held = {}; vi.restoreAllMocks() })
it('can run every service the master knows, and the updater it runs beside them, and loads each one\'s runner on its own', async () => {
expect([...SERVICE_RUNNERS.keys()].sort()).toEqual([...KNOWN_SERVICES, ...UPDATER_HOST.services].sort())
@@ -34,8 +50,10 @@ describe('a service in its own process', () => {
const seen: ServiceProcessOptions[] = []
const handle = { stop: vi.fn() }
const loaded: string[] = []
+ // What a service would hand anything it starts (a viewer's server, an engine), as it loads.
+ const inherited: Array<string | undefined> = []
const runners = new Map([
- ['search', async () => { loaded.push('search'); return (options: ServiceProcessOptions) => { seen.push(options); return handle } }],
+ ['search', async () => { loaded.push('search'); inherited.push(process.env.HARNESSD_SERVICE_TOKEN); return (options: ServiceProcessOptions) => { seen.push(options); return handle } }],
['viewers', async () => { loaded.push('viewers'); return () => handle }],
])
const { host, hosted } = fakeHost()
@@ -44,6 +62,8 @@ describe('a service in its own process', () => {
await startServiceProcess('search', { runners, host })
} finally { delete process.env.HARNESSD_SERVICE_TOKEN }
expect(loaded).toEqual(['search'])
+ // The token is the service's to connect with, and no child's: out of process.env before any service loads.
+ expect(inherited).toEqual([undefined])
expect(process.title).toBe('harnessd-search')
// Its lines are stamped like the core's and the master's in the log they share.
expect(stamped.times).toBe(1)
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 17e5acdc4..f41897560 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -10,6 +10,7 @@
*/
import { env } from './config/env.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
+import { harnessdEnv, holdHarnessdEnv } from './lib/harnessdEnv.js'
import { readOrMintComputerId } from './lib/computerIdentity.js'
import { localSocketPath } from './lib/localSocket.js'
import { ignoreLogWriteErrors, installTimestampedConsole } from './lib/log.js'
@@ -70,6 +71,9 @@ const describe = (error: unknown): string => (error instanceof Error ? error.mes
* always did: the process ends, and the master decides whether to try again.
*/
export async function startServiceProcess(named: string | undefined, deps: ServiceProcessDeps = {}): Promise<ServiceProcess> {
+ // First, before any service starts a child that would inherit them: the viewers' servers, an engine's
+ // app-server, a one-shot engine run (lib/harnessdEnv.ts). Read through `harnessdEnv()` from here on.
+ holdHarnessdEnv()
const runners = deps.runners ?? SERVICE_RUNNERS
const exit = deps.exit ?? ((code: number) => process.exit(code))
const names = [...new Set((named ?? '').split(',').map((name) => name.trim()).filter(Boolean))]
@@ -88,7 +92,7 @@ export async function startServiceProcess(named: string | undefined, deps: Servi
// The master names the process (`edge` for the services it shares); a process started by hand is named
// for what it runs. The same name as the hard link it was exec'd through (harnessd/processName.ts): one
// name in ps and Activity Monitor.
- const title = process.env.HARNESSD_SERVICE || names.join(',')
+ const title = harnessdEnv().HARNESSD_SERVICE || names.join(',')
process.title = `harnessd-${title}`
// Its lines share the daemon's log with the master's: a write a full disk refuses is dropped, not fatal.
ignoreLogWriteErrors()
@@ -102,7 +106,7 @@ export async function startServiceProcess(named: string | undefined, deps: Servi
dataDir: env.ADAPTER_DATA_DIR,
socketPath: socketPath ?? '',
machineId: readOrMintComputerId(env.ADAPTER_COMPUTER_ID_FILE, env.ADAPTER_COMPUTER_ID),
- token: process.env.HARNESSD_SERVICE_TOKEN ?? '',
+ token: harnessdEnv().HARNESSD_SERVICE_TOKEN ?? '',
}
const running: ServiceProcess[] = []
let failure: unknown = null
diff --git a/cli/src/services/devicesProcess.ts b/cli/src/services/devicesProcess.ts
index 7476b678b..21bd25cb8 100644
--- a/cli/src/services/devicesProcess.ts
+++ b/cli/src/services/devicesProcess.ts
@@ -26,6 +26,7 @@ import { accountLink } from './accountLink.js'
import { startDevices, type DevicesDeps } from './devices.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess, type ServiceProcessOptions } from './process.js'
import { processCoreApi } from './processCoreApi.js'
+import { harnessdEnv } from '../lib/harnessdEnv.js'
/** An agent as the core lists it for the dial: with the name the apps show and the model it runs. */
type Viewed = RegisteredSession & { displayName?: string; runtimeProfile?: string | null }
@@ -72,7 +73,7 @@ function faultsOf(value: string | undefined): ReadonlySet<string> {
}
export function runDevicesService(options: DevicesServiceOptions): ServiceProcess {
- const processEnv = options.processEnv ?? process.env
+ const processEnv = options.processEnv ?? harnessdEnv()
let core: CoreConnection | null = null
/** Whether a dial watches, as the cable last said: told again to every core this process connects to.
* A dial says hello as soon as its port opens, which is often before a core that just started has
diff --git a/cli/src/services/process.ts b/cli/src/services/process.ts
index 8b3431556..9dc2855d5 100644
--- a/cli/src/services/process.ts
+++ b/cli/src/services/process.ts
@@ -15,6 +15,7 @@ import { existsSync } from 'node:fs'
import WebSocket from 'ws'
import type { Asker, ServiceRequests } from '../core/api.js'
import { heartbeatInterval, processLoopDelay, type LoopDelay, type MasterChannel } from '../harnessd/coreLink.js'
+import { harnessdEnv } from '../lib/harnessdEnv.js'
type Payload = Record<string, unknown>
@@ -125,7 +126,7 @@ export const LEAVE_GRACE_MS = 5_000
/** The process the services run in: alive to the master, and gone with it. */
export function hostServices(options: ServiceHostOptions): ServiceHost {
const channel: MasterChannel = options.channel ?? (process as unknown as MasterChannel)
- const env = options.env ?? process.env
+ const env = options.env ?? harnessdEnv()
const exit = options.exit ?? ((code: number) => process.exit(code))
const faults = [options.name, ...options.services].map((name) => serviceFaults(env, name))
const services: ServiceProcess[] = []
@@ -181,7 +182,7 @@ const HELD_OFF_POLL_MS = 200
/** One service in its process: its own link to the core, answering what the core routes to it. */
export function runServiceProcess(options: ServiceProcessOptions): ServiceProcess {
- const env = options.env ?? process.env
+ const env = options.env ?? harnessdEnv()
const faults = serviceFaults(env, options.name)
// As a service whose start throws: it is not run, and, alone in its process, the process ends and the
// master decides whether to try again.
diff --git a/cli/src/services/updaterProcess.ts b/cli/src/services/updaterProcess.ts
index b87243bc2..519fd2d88 100644
--- a/cli/src/services/updaterProcess.ts
+++ b/cli/src/services/updaterProcess.ts
@@ -19,6 +19,7 @@ import { describeSpawnLockOwner, withSpawnLock } from '../lib/daemonSpawnLock.js
import { DOWNLOAD_LIMITS, startSelfUpdater } from '../lib/selfUpdate.js'
import { startTuiUpdater } from '../tui/update.js'
import { VERSION } from '../version.js'
+import { harnessdEnv } from '../lib/harnessdEnv.js'
import type { ServiceProcess } from './process.js'
export interface UpdaterServiceDeps {
@@ -43,6 +44,8 @@ export const processUpdaterDeps = (): UpdaterServiceDeps => ({
})
export function runUpdaterService(_options?: unknown, deps: UpdaterServiceDeps = processUpdaterDeps()): ServiceProcess {
+ // What its master, or the core it runs beside, said: held out of process.env (lib/harnessdEnv.ts).
+ const harnessd = harnessdEnv()
const cli = deps.startCli({
currentVersion: VERSION,
url: env.ADAPTER_UPDATE_URL,
@@ -65,7 +68,7 @@ export function runUpdaterService(_options?: unknown, deps: UpdaterServiceDeps =
// A master judges a build staged while the one before is on probation (#807). Beside a core, under a
// master too old to run the updater (core/updaterBeside.ts), only one that says so: one from before
// rolled the newer build back with the one it judged.
- stageWhileJudged: process.env.HARNESSD_UPDATER_BESIDE_CORE !== '1' || process.env.HARNESSD_JUDGES_SUPERSEDED === '1',
+ stageWhileJudged: harnessd.HARNESSD_UPDATER_BESIDE_CORE !== '1' || harnessd.HARNESSD_JUDGES_SUPERSEDED === '1',
})
// hn is an independent, optional download: its failure never holds up the CLI's fix.
const hn = deps.startHn({
diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.ts
index ec0afd589..d6c0010ed 100644
--- a/cli/src/startupOrder.spec.ts
+++ b/cli/src/startupOrder.spec.ts
@@ -208,7 +208,7 @@ describe('the core\'s start-up order (core/main.ts)', () => {
const BINDING = /\bbackend\.(?:ownerCommands\.)?(?:[A-Za-z_$][\w$]*\s*=(?!=)|set[A-Z][\w$]*\()/g
/** The test-only hold the end-to-end harness uses for a start-up that hangs after binding. */
-const TEST_HOLD = "if (process.env.HARNESSD_TEST_HOLD_READY === '1') await new Promise<never>(() => {})"
+const TEST_HOLD = "if (harnessd.HARNESSD_TEST_HOLD_READY === '1') await new Promise<never>(() => {})"
describe('the core\'s request gate (core/main.ts)', () => {
const source = code(SOURCE)