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.

feat(cli): watch tmux and Herdr together, with nothing to configure

0xken158a06fc02e835
diff --git a/cli/.env.example b/cli/.env.example
index 100798220..f819972fa 100644
--- a/cli/.env.example
+++ b/cli/.env.example
@@ -22,8 +22,10 @@ PORT=18473
# DISABLE_HOOK_INSTALL=false
# Terminal backends are additive and ordered. tmux remains the default.
-# TERMINAL_BACKENDS=tmux # tmux | herdr | tmux,herdr
-# HERDR_SESSIONS=default # ordered configured local named sessions
+# Both are UNSET by default, and unset means auto: tmux plus Herdr whenever the herdr binary is on PATH,
+# adopting every running Herdr session. Set them only to pin.
+# TERMINAL_BACKENDS=tmux # pin the set: tmux | herdr | tmux,herdr (tmux turns Herdr off)
+# HERDR_SESSIONS=default # pin an allowlist of local named sessions
# HERDR_BIN=herdr # used only for non-sensitive session discovery/diagnostics
# TERMINAL_RECONCILE_INTERVAL_MS=5000 # minimum 5000; neutral replacement for the legacy name below
diff --git a/cli/README.md b/cli/README.md
index 676b11386..a5227aa9c 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -65,17 +65,21 @@ daemon on it, so `harness` on this computer means your code without publishing a
turned **off** in the command shim it writes (otherwise the published release overwrites your build within
the minute). See [`RELEASE.md`](RELEASE.md#local-install-no-upload).
-After joining, start each agent yourself in tmux or a configured Herdr session with its normal vendor command. Harness observes the
-process; it does not launch the CLI or choose its permission/trust flags:
+After joining, start each agent yourself in tmux or Herdr with its normal vendor command. Harness
+observes the process; it does not launch the CLI or choose its permission/trust flags:
```bash
tmux new
claude # or: codex, agent, opencode, pi, hermes, cmd, devin, muse, amp, kilo, grok
-# Or, after starting a named Herdr session through Herdr itself:
-TERMINAL_BACKENDS=herdr HERDR_SESSIONS=default harness join
+# Or the same engines under Herdr — nothing to configure, and both at once is fine:
+herdr
+claude
```
+Both multiplexers are watched by default, and a Herdr session started after the daemon is adopted on
+the next scan. There is no env var to set for either one.
+
Each supported top-level CLI process appears automatically. Exiting or deleting the agent stops only
the validated engine process; Harness never closes the user-owned tmux or Herdr pane.
@@ -122,10 +126,14 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.json
### Terminal backend behavior
-- `TERMINAL_BACKENDS` is a strict ordered list: `tmux`, `herdr`, or `tmux,herdr`. The default is `tmux`.
-- `HERDR_SESSIONS` is an ordered list of local named sessions. Harness never auto-starts a session and
- never connects to a socket supplied only by a hook. Herdr support is pinned to compatible 0.8.x,
- protocol 19.
+- **Unset means auto.** Every backend usable on the machine is watched: tmux always, Herdr whenever its
+ binary is on `PATH`. A machine without Herdr pays a few `PATH` lookups and never spawns anything.
+- `TERMINAL_BACKENDS` overrides that with a strict ordered list — `tmux`, `herdr`, or `tmux,herdr`.
+ `TERMINAL_BACKENDS=tmux` is how you turn Herdr off.
+- `HERDR_SESSIONS` unset means every session Herdr reports as **running** is adopted, so a session
+ started later needs no restart. Setting it makes a strict allowlist that discovery never widens.
+- Harness never auto-starts a session, and never connects to a socket supplied only by a hook. Herdr
+ support is pinned to compatible 0.8.x, protocol 19.
- The shared backend contract can create and close a tmux session or Herdr workspace when explicitly
invoked. This is lifecycle capability, not automatic startup behavior; normal discovery observes
user-owned sessions, and agent deletion still terminates only the validated engine process.
@@ -162,8 +170,8 @@ reported as such, not described as exercised.
| `CLAUDE_PROJECTS_DIR` | `~/.claude/projects` | where Claude writes session JSONL |
| `ADAPTER_DATA_DIR` | `~/.harness/cli/data` | registry + token persistence |
| `DISABLE_HOOK_INSTALL` | `false` | skip auto-installing the claude hooks |
-| `TERMINAL_BACKENDS` | `tmux` | strict ordered list: `tmux`, `herdr`, or `tmux,herdr` |
-| `HERDR_SESSIONS` | `default` | ordered configured local named Herdr sessions |
+| `TERMINAL_BACKENDS` | *(auto)* | pin the set: `tmux`, `herdr`, or `tmux,herdr`. Unset = every usable backend |
+| `HERDR_SESSIONS` | *(auto)* | pin an allowlist. Unset = every running Herdr session is adopted |
| `HERDR_BIN` | `herdr` | Herdr executable used only for session discovery/diagnostics |
| `TERMINAL_RECONCILE_INTERVAL_MS` | `5000` | backend-neutral discovery interval; minimum 5000 ms |
| `TMUX_REAP_INTERVAL_MS` | `5000` | process discovery interval (removal requires two confirmed misses) |
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 4cf40cdf5..ffb987e1b 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -33,7 +33,14 @@ import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'
import { findLiveSession } from './lib/sessionRepair.js'
import { TmuxBackend } from './lib/tmuxBackend.js'
import { HerdrBackend } from './lib/herdrBackend.js'
-import { listInstalledHerdrSessions, resolveConfiguredHerdrSessions } from './lib/herdrSessions.js'
+import {
+ discoverRunningHerdrSessions,
+ herdrHintSelects,
+ listInstalledHerdrSessions,
+ resolveConfiguredHerdrSessions,
+ type HerdrTargetResolution,
+} from './lib/herdrSessions.js'
+import { ALL_TERMINAL_BACKENDS } from './config/terminalConfig.js'
import { TerminalBackendCoordinator } from './lib/terminalBackendCoordinator.js'
import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'
import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'
@@ -453,13 +460,32 @@ async function runForeground(token: string): Promise<void> {
await registry.transaction(() => {
for (const session of registry.list()) registry.setActive(session.agentId, false)
})
- const terminalConfig = { backends: env.TERMINAL_BACKENDS, herdrSessions: env.HERDR_SESSIONS }
+ // Unset means AUTO: watch every backend usable on this machine, and adopt whatever Herdr sessions are
+ // running. That is what makes `herdr` then an engine behave exactly like `tmux new` then an engine —
+ // no env var to know about. An explicit value still pins the set, and an explicit HERDR_SESSIONS is
+ // still a strict allowlist that discovery never widens.
+ const backendsExplicit = env.TERMINAL_BACKENDS !== undefined
+ const herdrSessionsExplicit = env.HERDR_SESSIONS !== undefined
+ const terminalConfig = {
+ backends: env.TERMINAL_BACKENDS ?? ALL_TERMINAL_BACKENDS,
+ herdrSessions: env.HERDR_SESSIONS ?? [],
+ }
+ /** The names in play right now: the operator's allowlist, or whatever Herdr currently reports. */
+ let activeHerdrSessions: readonly string[] = terminalConfig.herdrSessions
+ const resolveHerdrTargets = async (): Promise<HerdrTargetResolution[]> => {
+ if (!terminalConfig.backends.includes('herdr')) return []
+ return herdrSessionsExplicit
+ ? resolveConfiguredHerdrSessions(terminalConfig.herdrSessions, () => listInstalledHerdrSessions(env.HERDR_BIN))
+ : discoverRunningHerdrSessions(env.HERDR_BIN)
+ }
const tmuxBackend = terminalConfig.backends.includes('tmux') ? new TmuxBackend() : null
- const herdrTargets = terminalConfig.backends.includes('herdr')
- ? await resolveConfiguredHerdrSessions(terminalConfig.herdrSessions, () => listInstalledHerdrSessions(env.HERDR_BIN))
- : []
+ const herdrTargets = await resolveHerdrTargets()
+ activeHerdrSessions = herdrTargets.map((target) => target.sessionName)
const resolvedHerdrPaths = herdrTargets.flatMap((target) => target.state === 'available' ? [target.endpoint.socketPath] : [])
- if (new Set(resolvedHerdrPaths).size !== resolvedHerdrPaths.length) {
+ // Only an operator-named pair of aliases is a configuration error worth refusing to start over.
+ // Discovery cannot produce one — resolveConfiguredHerdrSessions already downgrades aliased sessions to
+ // unavailable — and a machine that never asked for Herdr must not fail to start because of it.
+ if (herdrSessionsExplicit && new Set(resolvedHerdrPaths).size !== resolvedHerdrPaths.length) {
throw new Error('two configured Herdr session names resolve to the same canonical endpoint')
}
const herdrStartup = await Promise.all(herdrTargets.map(async (target) => {
@@ -478,21 +504,24 @@ async function runForeground(token: string): Promise<void> {
state: target.state,
...(target.state === 'available' ? {} : { reason: target.reason }),
}]))
- if (!tmuxBackend && herdrStartup.length > 0 && herdrStartup.every((target) => target.state === 'incompatible')) {
+ // Fatal only when the operator asked for these backends. Auto-detection must never let a Herdr this
+ // build does not speak (a newer protocol, say) take down a daemon whose user never mentioned Herdr.
+ if (backendsExplicit && !tmuxBackend && herdrStartup.length > 0
+ && herdrStartup.every((target) => target.state === 'incompatible')) {
throw new Error('every enabled terminal backend is protocol-incompatible')
}
const terminalBackends = [...(tmuxBackend ? [tmuxBackend] : []), ...herdrBackends]
const terminals = new TerminalBackendCoordinator(
terminalBackends,
terminalConfig.backends,
- terminalConfig.herdrSessions,
+ activeHerdrSessions,
)
const refreshHerdrTargets = async (): Promise<void> => {
if (!terminalConfig.backends.includes('herdr')) return
- const resolved = await resolveConfiguredHerdrSessions(
- terminalConfig.herdrSessions,
- () => listInstalledHerdrSessions(env.HERDR_BIN),
- )
+ const resolved = await resolveHerdrTargets()
+ // A session started after the daemon shows up here, on the next pass — which is the whole point:
+ // discovery, not configuration, decides what is watched.
+ activeHerdrSessions = resolved.map((target) => target.sessionName)
const available = resolved.filter((target): target is Extract<typeof target, { state: 'available' }> => target.state === 'available')
const aliased = new Set<string>()
const byPath = new Map<string, string>()
@@ -526,18 +555,19 @@ async function runForeground(token: string): Promise<void> {
recovered.set(target.sessionName, backend)
herdrTargetStates.set(target.sessionName, { state: 'available' })
}
- herdrBackends.splice(0, herdrBackends.length, ...terminalConfig.herdrSessions.flatMap((name) => {
+ herdrBackends.splice(0, herdrBackends.length, ...activeHerdrSessions.flatMap((name) => {
const backend = recovered.get(name)
return backend ? [backend] : []
}))
terminalBackends.splice(0, terminalBackends.length, ...(tmuxBackend ? [tmuxBackend] : []), ...herdrBackends)
terminals.replaceBackends(terminalBackends)
- if (herdrBackends.length === terminalConfig.herdrSessions.length) {
+ terminals.setHerdrSessionOrder(activeHerdrSessions)
+ if (herdrBackends.length === activeHerdrSessions.length) {
writeTerminalConfigSnapshot(env.ADAPTER_DATA_DIR, terminalConfig, herdrBackends.map((backend) => backend.endpoint))
}
}
const completeHerdrSnapshot = !terminalConfig.backends.includes('herdr')
- || herdrBackends.length === terminalConfig.herdrSessions.length
+ || herdrBackends.length === activeHerdrSessions.length
if (completeHerdrSnapshot) {
writeTerminalConfigSnapshot(
env.ADAPTER_DATA_DIR,
@@ -547,7 +577,7 @@ async function runForeground(token: string): Promise<void> {
} else {
const previous = readTerminalConfigSnapshot(env.ADAPTER_DATA_DIR)
const previousNames = previous?.herdrEndpoints.map((endpoint) => endpoint.sessionName) ?? []
- if (JSON.stringify(previousNames) !== JSON.stringify(terminalConfig.herdrSessions)
+ if (JSON.stringify(previousNames) !== JSON.stringify(activeHerdrSessions)
|| !previous?.backends.includes('herdr')) {
// The configured allowlist changed but cannot be resolved completely. Publish a fail-closed
// snapshot rather than leaving an old endpoint authorized for daemon-down hooks.
@@ -1550,9 +1580,7 @@ async function runForeground(token: string): Promise<void> {
if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId })
continue
}
- const backend = herdrBackends.find((candidate) =>
- candidate.endpoint.sessionName === hint.sessionName
- && (!hint.socketPath || candidate.endpoint.socketPath === hint.socketPath))
+ const backend = herdrBackends.find((candidate) => herdrHintSelects(candidate.endpoint, hint))
if (!backend) continue
const runtime = await backend.resolveRuntimeHint(hint.paneId)
if (runtime.state === 'succeeded') resolved.push(runtime.value)
@@ -1584,9 +1612,9 @@ async function runForeground(token: string): Promise<void> {
if (!candidates.size && runtimeHints?.some((hint) => hint.backend === 'herdr')) {
const configuredSessions = new Set(runtimeHints
.filter((hint): hint is Extract<HookTerminalHint, { backend: 'herdr' }> => hint.backend === 'herdr')
- .filter((hint) => herdrBackends.some((backend) => backend.endpoint.sessionName === hint.sessionName
- && (!hint.socketPath || backend.endpoint.socketPath === hint.socketPath)))
- .map((hint) => hint.sessionName))
+ .flatMap((hint) => herdrBackends
+ .filter((backend) => herdrHintSelects(backend.endpoint, hint))
+ .map((backend) => backend.endpoint.sessionName)))
for (const candidate of registry.list()) {
if (candidate.engine !== engine || !callerBelongsTo(candidate)) continue
if (candidate.runtimes.some((runtime) => runtime.backend === 'herdr' && configuredSessions.has(runtime.sessionName))) {
@@ -1751,10 +1779,14 @@ async function runForeground(token: string): Promise<void> {
config: {
watching: `${terminalConfig.backends.join(' + ')} terminals across all supported engines`,
terminalBackends: terminalConfig.backends,
- herdrSessions: terminalConfig.herdrSessions,
+ // What is watched NOW, not what was configured at boot: under auto-detection the session set is
+ // discovered per pass, so reporting the (empty) configured list would answer the wrong question
+ // for the one person most likely to ask it — someone checking why their pane is not showing up.
+ herdrSessions: activeHerdrSessions,
+ terminalSelection: backendsExplicit ? 'configured' : 'auto',
terminalTargets: [
...(tmuxBackend ? [{ backend: 'tmux', instance: 'default', state: 'configured' }] : []),
- ...terminalConfig.herdrSessions.map((sessionName) => ({
+ ...activeHerdrSessions.map((sessionName) => ({
backend: 'herdr',
sessionName,
...(herdrTargetStates.get(sessionName) ?? { state: 'unavailable', reason: 'not yet resolved' }),
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 9d8be330b..de4aa9fda 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -182,14 +182,21 @@ const envSchema = z.object({
// Set to 'true' to skip auto-installing lifecycle hooks for every supported engine.
DISABLE_HOOK_INSTALL: z.string().default('false').transform((v) => v === 'true'),
// Additive terminal capability. Order controls deterministic primary-route tie breaking.
- TERMINAL_BACKENDS: z.string().default('tmux').transform((value, context) => {
+ //
+ // UNSET MEANS AUTO — every backend that is actually usable here, which is what makes `herdr` then an
+ // engine behave like `tmux new` then an engine, with nothing to configure. Set it to pin: `tmux` is
+ // how you turn Herdr off. Validation is unchanged for a value that IS given.
+ TERMINAL_BACKENDS: z.string().optional().transform((value, context) => {
+ if (value === undefined || value === '') return undefined
try { return parseTerminalBackends(value) } catch (error) {
context.addIssue({ code: 'custom', message: error instanceof Error ? error.message : 'invalid terminal backends' })
return z.NEVER
}
}),
- // Configured Herdr named sessions only. Hook-supplied socket paths never expand this allowlist.
- HERDR_SESSIONS: z.string().default('default').transform((value, context) => {
+ // Named Herdr sessions. UNSET means "adopt the sessions Herdr reports as running"; a value is a strict
+ // allowlist that discovery never widens, and hook-supplied socket paths never expand it either.
+ HERDR_SESSIONS: z.string().optional().transform((value, context) => {
+ if (value === undefined || value === '') return undefined
try { return parseHerdrSessions(value) } catch (error) {
context.addIssue({ code: 'custom', message: error instanceof Error ? error.message : 'invalid Herdr sessions' })
return z.NEVER
diff --git a/cli/src/config/terminalConfig.spec.ts b/cli/src/config/terminalConfig.spec.ts
index 1b63cabcc..34ddea9a7 100644
--- a/cli/src/config/terminalConfig.spec.ts
+++ b/cli/src/config/terminalConfig.spec.ts
@@ -2,15 +2,40 @@ import { describe, expect, it } from 'vitest'
import { parseHerdrSessions, parseTerminalBackends, parseTerminalConfig } from './terminalConfig.js'
describe('terminal backend configuration', () => {
- it('defaults to tmux without requiring Herdr', () => {
- expect(parseTerminalConfig({})).toEqual({ backends: ['tmux'], herdrSessions: [] })
+ it('watches every backend when nothing is configured, and names no sessions', () => {
+ // Unset is AUTO, not tmux: a second multiplexer that only works for people who know an env var is
+ // not the same product as `tmux new` + engine. The empty session list is not "no Herdr" — it means
+ // the names come from discovery, so a session started later is adopted without a restart.
+ expect(parseTerminalConfig({})).toEqual({
+ backends: ['tmux', 'herdr'],
+ herdrSessions: [],
+ backendsExplicit: false,
+ herdrSessionsExplicit: false,
+ })
})
- it('preserves backend and named-session order for deterministic ranking', () => {
+ it('treats an explicit value as a pin, and an explicit session list as a strict allowlist', () => {
expect(parseTerminalConfig({
TERMINAL_BACKENDS: 'herdr,tmux',
HERDR_SESSIONS: 'work,default',
- })).toEqual({ backends: ['herdr', 'tmux'], herdrSessions: ['work', 'default'] })
+ })).toEqual({
+ backends: ['herdr', 'tmux'],
+ herdrSessions: ['work', 'default'],
+ backendsExplicit: true,
+ herdrSessionsExplicit: true,
+ })
+ // Turning Herdr off is still one variable, and it stays off whatever is running on the machine.
+ expect(parseTerminalConfig({ TERMINAL_BACKENDS: 'tmux' })).toMatchObject({
+ backends: ['tmux'],
+ herdrSessions: [],
+ backendsExplicit: true,
+ })
+ // An allowlist without a backend list still applies — auto-detects the backends, pins the sessions.
+ expect(parseTerminalConfig({ HERDR_SESSIONS: 'work' })).toMatchObject({
+ backends: ['tmux', 'herdr'],
+ herdrSessions: ['work'],
+ herdrSessionsExplicit: true,
+ })
})
it.each(['', ' ', 'tmux,', 'tmux,,herdr', 'tmux,tmux', 'screen'])('rejects invalid TERMINAL_BACKENDS=%j', (value) => {
diff --git a/cli/src/config/terminalConfig.ts b/cli/src/config/terminalConfig.ts
index da83bc067..b0d0e2551 100644
--- a/cli/src/config/terminalConfig.ts
+++ b/cli/src/config/terminalConfig.ts
@@ -2,11 +2,30 @@ import type { TerminalBackendName } from '../lib/terminalTypes.js'
const HERDR_SESSION_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
+/** Every backend the daemon knows how to drive. Absent configuration means "look for all of them". */
+export const ALL_TERMINAL_BACKENDS: readonly TerminalBackendName[] = ['tmux', 'herdr']
+
+/** What is watched right now. This is also the persisted snapshot shape — keep it serializable. */
export interface TerminalConfig {
backends: readonly TerminalBackendName[]
+ /** Empty under auto-detection: the session set comes from discovery, not from configuration. */
herdrSessions: readonly string[]
}
+export interface ResolvedTerminalConfig extends TerminalConfig {
+ /**
+ * Did the operator name the backends, or did we?
+ *
+ * It decides what happens when one of them turns out to be unusable. An explicitly configured backend
+ * that fails is a startup error — it was asked for, and silence would be a lie. An auto-detected one
+ * is simply absent, because nobody asked for it and a machine without Herdr must not be told about
+ * Herdr, still less refuse to start because of it.
+ */
+ backendsExplicit: boolean
+ /** Same distinction for the session list: a named allowlist is honoured verbatim, never widened. */
+ herdrSessionsExplicit: boolean
+}
+
function strictList(value: string, field: string): string[] {
const parts = value.split(',').map((part) => part.trim())
if (!parts.length || parts.some((part) => !part)) {
@@ -36,13 +55,32 @@ export function parseHerdrSessions(value = 'default'): string[] {
return values
}
+/**
+ * Unset means AUTO, not "tmux".
+ *
+ * The tmux flow has never asked for configuration — start a pane, run the engine, the agent appears —
+ * and a second multiplexer that only works for people who know an env var is not the same product. So
+ * an absent `TERMINAL_BACKENDS` means "watch every backend that is actually usable on this machine"
+ * (Herdr resolves only when its binary is on PATH, so a machine without it pays nothing), and an absent
+ * `HERDR_SESSIONS` means "adopt the sessions Herdr says are running" rather than a fixed name that
+ * happens to be `default`.
+ *
+ * Both remain overrides. Naming the backends pins them — `TERMINAL_BACKENDS=tmux` is how you turn Herdr
+ * off — and naming the sessions keeps today's strict allowlist, which discovery never widens.
+ */
export function parseTerminalConfig(input: {
TERMINAL_BACKENDS?: string
HERDR_SESSIONS?: string
-}): TerminalConfig {
- const backends = parseTerminalBackends(input.TERMINAL_BACKENDS)
+}): ResolvedTerminalConfig {
+ const backendsExplicit = input.TERMINAL_BACKENDS !== undefined && input.TERMINAL_BACKENDS !== ''
+ const backends = backendsExplicit ? parseTerminalBackends(input.TERMINAL_BACKENDS) : ALL_TERMINAL_BACKENDS
+ const herdrSessionsExplicit = input.HERDR_SESSIONS !== undefined && input.HERDR_SESSIONS !== ''
return {
backends,
- herdrSessions: backends.includes('herdr') ? parseHerdrSessions(input.HERDR_SESSIONS) : [],
+ herdrSessions: backends.includes('herdr') && herdrSessionsExplicit
+ ? parseHerdrSessions(input.HERDR_SESSIONS)
+ : [],
+ backendsExplicit,
+ herdrSessionsExplicit,
}
}
diff --git a/cli/src/lib/herdrSessions.spec.ts b/cli/src/lib/herdrSessions.spec.ts
index fe9ad86c5..c3e3888c7 100644
--- a/cli/src/lib/herdrSessions.spec.ts
+++ b/cli/src/lib/herdrSessions.spec.ts
@@ -1,5 +1,11 @@
-import { describe, expect, it } from 'vitest'
-import { parseHerdrSessionList, resolveConfiguredHerdrSessions } from './herdrSessions.js'
+import { describe, expect, it, vi } from 'vitest'
+import {
+ discoverRunningHerdrSessions,
+ herdrBinaryAvailable,
+ herdrHintSelects,
+ parseHerdrSessionList,
+ resolveConfiguredHerdrSessions,
+} from './herdrSessions.js'
describe('configured Herdr session bootstrap', () => {
it('parses bounded session-list output without treating pane content as CLI data', () => {
@@ -51,3 +57,77 @@ describe('configured Herdr session bootstrap', () => {
expect(() => parseHerdrSessionList('x'.repeat(512 * 1024 + 1))).toThrow('size limit')
})
})
+
+describe('Herdr auto-discovery (no configuration)', () => {
+ const endpoint = async ({ sessionName, socketPath }: { sessionName: string; socketPath: string }) => ({
+ sessionName, socketPath, endpointId: `id:${socketPath}`, generation: { device: 1, inode: 1 },
+ })
+
+ it('adopts every RUNNING session, whatever it is called', async () => {
+ // The point of auto-detection: the user starts a session with a name we were never told about, and
+ // its panes are watched on the next pass. A stopped session is not a target.
+ const result = await discoverRunningHerdrSessions(
+ 'herdr',
+ async () => [
+ { name: 'scratch', running: true, session_dir: '/a', socket_path: '/a/herdr.sock' },
+ { name: 'default', running: true, session_dir: '/b', socket_path: '/b/herdr.sock' },
+ { name: 'stopped', running: false, session_dir: '/c', socket_path: '/c/herdr.sock' },
+ ],
+ endpoint,
+ )
+ expect(result.map((target) => [target.sessionName, target.state])).toEqual([
+ ['scratch', 'available'],
+ ['default', 'available'],
+ ])
+ })
+
+ it('costs nothing on a machine without Herdr — no spawn, no targets', async () => {
+ const list = vi.fn()
+ await expect(discoverRunningHerdrSessions('herdr-does-not-exist-anywhere', list, endpoint)).resolves.toEqual([])
+ expect(list).not.toHaveBeenCalled()
+ expect(herdrBinaryAvailable('herdr-does-not-exist-anywhere')).toBe(false)
+ })
+
+ it('stays quiet when an installed Herdr cannot answer', async () => {
+ // Installed but broken, or a build whose `session list --json` shape moved. Nobody asked for Herdr,
+ // so there is nothing to report and nothing to adopt — never a startup failure.
+ await expect(discoverRunningHerdrSessions('herdr', async () => { throw new Error('exit 1') }, endpoint))
+ .resolves.toEqual([])
+ await expect(discoverRunningHerdrSessions('herdr', async () => [], endpoint)).resolves.toEqual([])
+ })
+
+ it('still refuses two discovered sessions that alias one endpoint', async () => {
+ // Discovery must not become a way around the alias rule the configured path enforces.
+ const result = await discoverRunningHerdrSessions(
+ 'herdr',
+ async () => [
+ { name: 'one', running: true, session_dir: '/same', socket_path: '/same/herdr.sock' },
+ { name: 'two', running: true, session_dir: '/same', socket_path: '/same/herdr.sock' },
+ ],
+ endpoint,
+ )
+ expect(result.every((target) => target.state === 'unavailable')).toBe(true)
+ })
+})
+
+describe('hook hint → endpoint selection', () => {
+ const endpoint = { sessionName: 'default', socketPath: '/config/default/herdr.sock' }
+
+ it('matches on the socket path alone, because herdr 0.8.0 exports no HERDR_SESSION', () => {
+ // The pane env measured on 0.8.0: HERDR_PANE_ID, HERDR_SOCKET_PATH, HERDR_ENV, HERDR_TAB_ID,
+ // HERDR_WORKSPACE_ID. Requiring a session name rejected every real hook, so nothing ever bound —
+ // a resumed session opened blank and a turn typed in the pane emitted no frames.
+ expect(herdrHintSelects(endpoint, { socketPath: '/config/default/herdr.sock' })).toBe(true)
+ expect(herdrHintSelects(endpoint, { sessionName: 'default' })).toBe(true)
+ expect(herdrHintSelects(endpoint, { sessionName: 'default', socketPath: '/config/default/herdr.sock' })).toBe(true)
+ })
+
+ it('refuses a hint that identifies nothing, or that disagrees', () => {
+ // A hint with no identifying field must never match "whatever backend is first" — that would let a
+ // pane in one session speak for an agent in another.
+ expect(herdrHintSelects(endpoint, {})).toBe(false)
+ expect(herdrHintSelects(endpoint, { sessionName: 'other' })).toBe(false)
+ expect(herdrHintSelects(endpoint, { socketPath: '/somewhere/else.sock' })).toBe(false)
+ expect(herdrHintSelects(endpoint, { sessionName: 'default', socketPath: '/somewhere/else.sock' })).toBe(false)
+ })
+})
diff --git a/cli/src/lib/herdrSessions.ts b/cli/src/lib/herdrSessions.ts
index fc09d4600..939aac4b9 100644
--- a/cli/src/lib/herdrSessions.ts
+++ b/cli/src/lib/herdrSessions.ts
@@ -1,4 +1,6 @@
import { execFile } from 'node:child_process'
+import { accessSync, constants, realpathSync } from 'node:fs'
+import { delimiter, join } from 'node:path'
import { promisify } from 'node:util'
import { HerdrEndpointError, resolveHerdrEndpoint, type HerdrEndpoint } from './herdrApiClient.js'
@@ -47,6 +49,92 @@ export async function listInstalledHerdrSessions(herdrBin = 'herdr'): Promise<He
return parseHerdrSessionList(result.stdout)
}
+/**
+ * Does a hook's terminal hint identify THIS already-resolved endpoint?
+ *
+ * Measured on herdr 0.8.0: a pane's environment carries `HERDR_PANE_ID`, `HERDR_SOCKET_PATH`,
+ * `HERDR_ENV`, `HERDR_TAB_ID` and `HERDR_WORKSPACE_ID` — and **no `HERDR_SESSION`**. Matching a backend
+ * by session name alone therefore rejected every real Herdr hook (`no_matching_engine_process`, 37 times
+ * in one afternoon here), so no session ever bound: a resumed session showed a blank conversation and a
+ * turn typed in the pane produced no frames at all.
+ *
+ * The socket path is the better key anyway — it is what the endpoint IS, while the session name is a
+ * label for it. Both are accepted, whichever the running Herdr exports, and a field that is present but
+ * disagrees disqualifies the match.
+ *
+ * This only ever SELECTS among endpoints already validated at discovery: a hook cannot introduce a
+ * socket, only point at one we resolved ourselves. Symlinked paths are compared canonically so a hook
+ * reporting `~/.config/...` still matches an endpoint resolved through `/System/Volumes/Data/...`.
+ */
+export function herdrHintSelects(
+ endpoint: Pick<HerdrEndpoint, 'sessionName' | 'socketPath'>,
+ hint: { sessionName?: string; socketPath?: string },
+): boolean {
+ const wantsName = !!hint.sessionName
+ const wantsPath = !!hint.socketPath
+ if (!wantsName && !wantsPath) return false
+ if (wantsName && endpoint.sessionName !== hint.sessionName) return false
+ if (wantsPath && !samePath(endpoint.socketPath, hint.socketPath!)) return false
+ return true
+}
+
+function samePath(left: string, right: string): boolean {
+ if (left === right) return true
+ try { return realpathSync(left) === realpathSync(right) } catch { return false }
+}
+
+/**
+ * Is a Herdr binary visible to this user, without spawning anything?
+ *
+ * Auto-detection runs before every reconcile pass, and the overwhelmingly common machine has no Herdr
+ * at all — so the negative case must cost nothing. A PATH walk with `accessSync(X_OK)` is a handful of
+ * stat calls (the same technique `engineBin.commandCandidates` uses to resolve vendor CLIs); spawning
+ * `herdr session list` only to watch it fail with ENOENT twelve times a minute is not acceptable as a
+ * default. An absolute `HERDR_BIN` is checked directly.
+ */
+export function herdrBinaryAvailable(herdrBin = 'herdr'): boolean {
+ const candidates = herdrBin.includes('/')
+ ? [herdrBin]
+ : (process.env.PATH ?? '').split(delimiter).filter(Boolean).map((entry) => join(entry, herdrBin))
+ for (const candidate of candidates) {
+ try {
+ accessSync(candidate, constants.X_OK)
+ return true
+ } catch { /* keep looking */ }
+ }
+ return false
+}
+
+/**
+ * Every Herdr session that is currently RUNNING, resolved the same way a configured one is.
+ *
+ * This is what "no configuration" means in practice: the names come from the user's own `herdr session
+ * list`, not from an env var they have to know about, so starting a session — with any name, at any
+ * time — makes its panes discoverable on the next pass. Nothing about the trust model changes: every
+ * endpoint still goes through `resolveHerdrEndpoint`'s canonical-path, owner, type, mode and
+ * socket-generation checks, and a hook-supplied socket path still never widens what is adopted here.
+ *
+ * Returns [] when Herdr is absent or reports nothing, which is the quiet path for a tmux-only machine.
+ */
+export async function discoverRunningHerdrSessions(
+ herdrBin = 'herdr',
+ list: () => Promise<HerdrSessionListRow[]> = () => listInstalledHerdrSessions(herdrBin),
+ resolveEndpoint: typeof resolveHerdrEndpoint = resolveHerdrEndpoint,
+): Promise<HerdrTargetResolution[]> {
+ if (!herdrBinaryAvailable(herdrBin)) return []
+ let rows: HerdrSessionListRow[]
+ try {
+ rows = await list()
+ } catch {
+ // Installed but unusable (a broken build, a version whose `session list --json` shape moved). Not an
+ // error the operator asked for, so it is simply nothing to adopt.
+ return []
+ }
+ const running = rows.filter((row) => row.running).map((row) => row.name)
+ if (!running.length) return []
+ return resolveConfiguredHerdrSessions(running, async () => rows, resolveEndpoint)
+}
+
export async function resolveConfiguredHerdrSessions(
sessionNames: readonly string[],
list: () => Promise<HerdrSessionListRow[]> = listInstalledHerdrSessions,
diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.ts
index 8721c82ef..676755c20 100644
--- a/cli/src/lib/terminalBackendCoordinator.ts
+++ b/cli/src/lib/terminalBackendCoordinator.ts
@@ -46,7 +46,7 @@ export class TerminalBackendCoordinator {
constructor(
backends: readonly TerminalBackend[],
private readonly backendOrder: readonly string[],
- private readonly herdrSessionOrder: readonly string[],
+ private herdrSessionOrder: readonly string[],
) {
this.replaceBackends(backends)
}
@@ -56,6 +56,14 @@ export class TerminalBackendCoordinator {
for (const backend of backends) this.byInstance.set(backend.instanceId, backend)
}
+ /**
+ * The session order is only a deterministic tie-break between two runtimes of the same backend, but it
+ * has to track discovery: with sessions adopted as they start, the set is no longer fixed at boot.
+ */
+ setHerdrSessionOrder(order: readonly string[]): void {
+ this.herdrSessionOrder = order
+ }
+
instances(): TerminalBackend[] {
return [...this.byInstance.values()]
}