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.

39.5 KB
Raw Blame
import { execFile, type ExecFileException } from 'node:child_process'
import { heldPaneFormat } from './nativePaneHold.js'
import { patientDeadline, patientExec, type ExecDone } from './patientExec.js'
import type { TerminalBackend, TerminalBackendPrepared } from './terminalBackend.js'
import type { AgentEngine } from '../engines/types.js'
import {
  TERMINAL_ACTION_SUCCEEDED,
  terminalActionNotStarted,
  terminalActionPossiblyExecuted,
  terminalEnterWithheld,
  type SubmitOptions,
  type TerminalActionResult,
  type TerminalBackendCapabilities,
  type TerminalCaptureOptions,
  type TerminalCreateRequest,
  type TerminalCreateResult,
  type TerminalInventoryResult,
  type TerminalLogicalKey,
  type TerminalPaneInfo,
  type TerminalPaneRead,
  type TerminalProcessExpectation,
  type TerminalReadResult,
  type TerminalRespawnRequest,
  type TerminalStreamHandle,
  type TerminalStreamSink,
  type TerminalStreamSize,
  type TmuxRuntimeRef,
  type RuntimeValidation,
} from './terminalTypes.js'
import { inTmuxRoom } from './tmuxControlGate.js'
import { TmuxControlStream } from './tmuxStream.js'
import {
  captureTmuxPane,
  clearPaneRemainOnExit,
  ENGINE_EXIT_PANE_OPTION,
  listPaneTitles,
  sendKeyToTmux,
  sendLiteralToTmux,
  paneOptionScope,
  paneStyleArgs,
  sendToTmux,
  setPaneMouseOn,
  setPaneStyle,
  tmuxPaneInfo,
  tmuxPanePid,
  tmuxPaneState,
} from './tmux.js'
import { lookupPaneEngineProcess } from './paneEngineProcess.js'
import { LSTART_MARKER_RE } from './processTable.js'
import { env } from '../config/env.js'
import { HARNESS_OWNER_OPTION, harnessPaneOwner, ownerCommand } from './harnessSessionLabel.js'
import {
  TMUX_FEATURE_MIN,
  tmuxFeatures,
  tmuxSupportsSessionEnv,
  tmuxTooOldForEnv,
  tmuxTooOldForSessionEnv,
  type TmuxFeatures,
} from './tmuxVersion.js'

import { ensureTmuxOnPath, type TmuxPathOutcome } from './tmuxOnPath.js'
import { isHarnessdVariable } from './harnessdEnv.js'
import { isAgentSessionVariable } from './agentSessionEnv.js'
import { DEFAULT_HOST_THEME, windowStyleOf, type HostTheme } from './hostTheme.js'
import { machineNames } from './machineNames.js'
import { adoptLegacyHarnessSessions, isNoTmuxServerError, listTmuxPanes } from './tmuxAgentDiscovery.js'
import { sameProcessIdentity, terminalRouteKey } from './terminalRuntime.js'
import { TMUX_KEYS } from './terminalKeys.js'

// Every tmux call here: a held event loop must not turn a timeout into a failure, or into an empty
// answer that reads as a pane that was never made (patientExec.ts).
const run = patientExec(execFile)

/** Test seams for `prepare`: where tmux is looked for (`ensureTmuxOnPath`). */
export interface TmuxBackendPrepareSeams {
  ensureOnPath?: () => Promise<TmuxPathOutcome>
}

function legacyActionResult(ok: boolean, operation: string): TerminalActionResult {
  // The legacy helper has spawned tmux before it reports false, so execution cannot safely be ruled out.
  return ok ? TERMINAL_ACTION_SUCCEEDED : terminalActionPossiblyExecuted(`${operation} did not complete`)
}

/**
 * The argv for removing [names] from session [sessionId]'s environment.
 *
 * Exported so a spec can pin the exact command without a tmux server. `-u` REMOVES the variable;
 * the `-e VAR=` form that `respawn-pane` accepts would set it to an empty string instead, and an
 * engine handed an empty base URL does not fall back to its own login — it dials the empty string.
 */
export function clearEnvArgs(sessionId: string, names: readonly string[]): string[] {
  const args: string[] = []
  for (const name of names) {
    if (args.length) args.push(';')
    args.push('set-environment', '-t', sessionId, '-u', name)
  }
  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])
}

/**
 * [word] as one word of tmux's command syntax, the one `source-file` and `if-shell` parse: single-quoted,
 * each `'` closed, given in double quotes and reopened. A newline or carriage return goes as a double-quoted
 * escape: measured on tmux 3.7, a raw newline inside single quotes lost the next line when it began with `#`.
 */
export function tmuxWord(word: string): string {
  return `'${word.replace(/'/g, `'"'"'`).replace(/\n/g, `'"\\n"'`).replace(/\r/g, `'"\\r"'`)}'`
}

/** The tmux command list [args] (`;` separating its commands, as on a command line) as a `source-file` script. */
export function tmuxScript(args: readonly string[]): string {
  return `${args.map((word) => word === ';' ? ';' : tmuxWord(word)).join(' ')}\n`
}

/**
 * The target that names the session called [label] exactly, and its active pane (its only one when it has just
 * been made), or null when there is no such target: a session with no name, or one whose name tmux would read
 * as a window or pane separator.
 */
export function scriptTarget(label: string | undefined): string | null {
  return label && !/[:.]/.test(label) ? `=${label}:` : null
}

/**
 * The command line that runs a script given on stdin. `source-file` alone does not start a server ("no server
 * running"), so `start-server` comes first; a server it starts takes this as its title, with no value in it.
 */
export const SCRIPT_ON_STDIN = ['start-server', ';', 'source-file', '-'] as const

/**
 * Run the tmux command list [args] with none of its words on a command line: every account on the machine
 * reads every process's command line (`ps -axww`). `new-session -e KEY=VALUE` as argv showed a Team
 * account's relay token to every account on the Mac Studio for as long as the tmux server it started lived,
 * since a server keeps that command line as its title (audit M2, docs/security/2026-11-02-team-account-boundary.md);
 * and with a server running, the short-lived client still showed it to a loop of `ps`. The list goes on stdin,
 * which only its own account can read, and touches no disk, so a crash leaves nothing behind. `source-file -` is
 * tmux 3.1. The deadline is patientExec's, for the same held-loop reason; tmux answers exactly as on argv: a
 * failing command stops the rest of the list, with its message on stderr.
 */
function runScript(args: readonly string[], timeout: number, done: ExecDone): void {
  let finished = false
  let cancel = (): void => {}
  // A child this kills for its deadline is reported `killed`, which `create` reads as a timeout.
  const child = execFile('tmux', [...SCRIPT_ON_STDIN], { encoding: 'utf8' }, (error: ExecFileException | null, stdout: string, stderr: string) => {
    finished = true
    cancel()
    done(error, stdout ?? '', stderr ?? '')
  })
  // A tmux that cannot be started (ENOENT) closes its stdin; the error is the callback's to report, not a throw.
  child.stdin?.on('error', () => {})
  child.stdin?.end(tmuxScript(args))
  if (!finished) cancel = patientDeadline(timeout, () => child.kill('SIGTERM'))
}

export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
  readonly name = 'tmux' as const
  readonly instanceId = 'tmux:default'

  /** What each Harness pane's `window-style` was last set to, so a scan re-applies only changes. */
  private readonly styledPanes = new Map<string, string>()
  private readonly desiredStyles = new Map<string, string>()
  private readonly stylingPanes = new Set<string>()

  /**
   * [hostTheme] answers with the desktop's current pane colours (see `hostTheme.ts`); read at every
   * use rather than captured, so a theme the app sends later reaches sessions created after it.
   * [owner] is the tag this daemon's panes carry (`HARNESS_OWNER_OPTION`), read at every create for
   * the same reason as the theme: the data folder is the daemon's to move.
   * [observeMachineName] reads the machine's name as tmux titles the new pane with it (lib/machineNames.ts).
   */
  constructor(
    private readonly hostTheme: () => HostTheme = () => DEFAULT_HOST_THEME,
    private readonly owner: () => string = () => harnessPaneOwner(env.ADAPTER_DATA_DIR),
    private readonly observeMachineName: () => void = () => machineNames.observe(),
    /** What this machine's tmux can do (`tmuxVersion.ts`): a command an older tmux does not know fails
     *  the whole command list it is chained into, and every agent create with it. */
    private readonly features: () => Promise<TmuxFeatures> = tmuxFeatures,
    private readonly seams: TmuxBackendPrepareSeams = {},
  ) {}

  async prepare({ ownedPanes }: { ownedPanes: ReadonlyMap<string, AgentEngine> }): Promise<TerminalBackendPrepared> {
    // Before ANY tmux call: a daemon that came up outside a terminal (the usual shape after a reboot)
    // has a minimal PATH, and every `execFile('tmux', …)` below would ENOENT. Ask the user's own login
    // shell where tmux is and adopt that directory, the same way the engine launch already consults it.
    // The daemon starts this alongside its own login-shell capture (`warmLoginShellEnvironment`), so
    // their wall-clock cost overlaps instead of adding up.
    const tmuxPath = await (this.seams.ensureOnPath ?? (() => ensureTmuxOnPath()))()
    // Missing tmux is a STATE, not a reason to refuse to start. The daemon already models a machine
    // without it — no backend to make panes on whenever the config omits tmux, every caller tests it, and
    // the create/restart/resume paths answer `TMUX_UNAVAILABLE` — so it can still serve its status, the
    // local socket and the backend link, leave for an update, and say what is missing. Refusing instead left a
    // machine whose PATH lost tmux with a daemon that could not start and therefore could not be fixed.
    if (tmuxPath.state === 'absent') {
      console.error(`[tmux] unavailable: ${tmuxPath.reason} · install tmux and verify \`tmux -V\`,`
        + ' then restart — agents cannot be created or restored until then')
      return { state: 'unavailable', code: 'TMUX_UNAVAILABLE', reason: tmuxPath.reason }
    }
    if (tmuxPath.state === 'adopted') {
      console.log(`[tmux] not on the daemon PATH · adopted ${tmuxPath.path} · ${tmuxPath.from}`)
    }
    // Before the first inventory: sessions a pre-prefix build named `<engine>-<ts>` are renamed to
    // `harness-<engine>-<ts>` so discovery's whitelist sees the registry's own panes again.
    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, and one
    // started from an agent's shell that agent's session (lib/agentSessionEnv.ts).
    const forgotten = await this.unsetServerEnvironment((name) => isHarnessdVariable(name) || isAgentSessionVariable(name))
    if (forgotten.length) console.log(`[terminal] tmux: removed ${forgotten.join(', ')} from the environment new panes start with`)
    // A first inventory that cannot be read is said, not fatal: tmux is there, and the next scan asks again.
    const startup = await this.inventory()
    console.log(startup.state === 'available'
      ? '[terminal] tmux: available'
      : `[terminal] tmux: ${startup.state} (${startup.reason})`)
    return { state: 'ready' }
  }

  /** `sessionEnv`: whether `create` can be given an `env` — tmux 3.2 (`TMUX_SESSION_ENV_MIN`), probed once per process. */
  async capabilities(): Promise<TerminalBackendCapabilities> {
    return { sessionEnv: await tmuxSupportsSessionEnv() }
  }

  async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<TmuxRuntimeRef>> {
    // tmux titles the pane it is about to make with the machine's name as it is now, and an engine
    // that sets no title keeps it. Read here, that name is refused even if the machine has another
    // by the next title sweep: a name it had only between two sweeps would otherwise never be seen.
    this.observeMachineName()
    const features = await this.features()
    const variables = Object.entries(request.env ?? {})
    // `-e` (tmux 3.2+) puts these in the SESSION environment rather than the engine's argv, and a list
    // that carries them goes to tmux on stdin (`runScript`), never on tmux's own command line: either
    // would put a grid relay key in `ps` output. Callers refuse a grid or a
    // harness on an older tmux by name (`capabilities().sessionEnv`); whatever else reaches here with
    // variables on one is refused here, saying why, rather than handed to tmux to answer with its
    // usage text — and never moved into the argv, where a secret would show.
    if (variables.length && !features.sessionEnv) return terminalActionNotStarted(tmuxTooOldForEnv(TMUX_FEATURE_MIN.sessionEnv, 'a new session'))
    // On a command line, tmux gives the options chained after `new-session` to the session it just made.
    // From `source-file` it does not: they went to the session tmux takes as current, another one's pane
    // when the server had one, which took this daemon's tag and left the new pane with none, nor
    // `remain-on-exit`, nor `destroy-unattached off` (found in review of #2542, tmux 3.7 and 3.8). There each
    // option names the new session exactly (`=NAME:`), so the session needs a name that target can hold.
    const target = variables.length ? scriptTarget(request.label) : undefined
    if (target === null) return terminalActionNotStarted('a session with its own variables needs a name without ":" or "."')
    const option = target ? ['-t', target] : []
    const owner = this.owner()
    const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']
    if (request.cwd) args.push('-c', request.cwd)
    if (request.label) args.push('-s', request.label)
    for (const [key, value] of variables) args.push('-e', `${key}=${value}`)
    // Trailing args after this point become the session's shell-command. tmux execs them directly
    // (no shell interposed) when given as separate argv elements, so no quoting/escaping is needed.
    if (request.command?.length) args.push(...this.ownedCommand(features, owner, request.command))
    // Pane options where tmux has them, so these go with the pane wherever the person moves it and never
    // change the rest of a window of theirs; the agent's own new window before tmux 3.0.
    const scope = paneOptionScope(features)
    // Keep the pane when its process dies, so an engine that exits immediately (not logged in, bad
    // config) still has its error text readable afterwards instead of taking the whole session down
    // with it. Chained into THIS tmux invocation on purpose: an engine can exit in under a
    // millisecond, and a second `set-option` call loses that race — measured, the session was
    // already gone before the follow-up command could reach the server.
    // Whoever created the pane owns turning this back off; see `clearPaneRemainOnExit`.
    args.push(';', 'set-option', scope, ...option, 'remain-on-exit', 'on')
    // An agent's session never has a client attached, so a person's `set -g destroy-unattached on`
    // (in their ~/.tmux.conf, which this server loads) ended every agent the moment it was made, and
    // Harness could not run at all on their machine (found end to end, e2e/tmuxconf.e2e.ts). Turned
    // off for this session only, in this same invocation, before the server can act on it.
    args.push(';', 'set-option', ...option, 'destroy-unattached', 'off')
    // Same invocation, same reason: an engine asks its terminal for its colours (OSC 10/11) in its
    // first milliseconds and never again, so the style has to be there before the engine is.
    const style = windowStyleOf(this.hostTheme())
    args.push(';', ...paneStyleArgs(features, style, target))
    // Whose pane it is, from its first instant: another daemon on this tmux server scanning a moment
    // later must already see it is not its own. On the pane, which keeps it wherever the person moves
    // it (see HARNESS_OWNER_OPTION); before tmux 3.0, on the window, and in the start command.
    args.push(';', 'set-option', scope, ...option, HARNESS_OWNER_OPTION, owner)
    // `killed`/`signal` come from execFile's own error shape, which ErrnoException alone does not declare.
    type ExecError = NodeJS.ErrnoException & { killed?: boolean; signal?: NodeJS.Signals | null }
    // A new session is a notification to every control client: on a tmux before 3.7, not while one
    // attaches (tmuxControlGate.ts).
    const result = await inTmuxRoom('notify', () => new Promise<{ error: ExecError | null; stdout: string; stderr: string }>((resolve) => {
      if (request.current?.() === false) { resolve({ error: Object.assign(new Error('The harness changed before pane dispatch'), { code: 'HARNESS_CANCELLED' }), stdout: '', stderr: '' }); return }
      request.onDispatch?.()
      const done: ExecDone = (error, stdout, stderr) => resolve({ error: error as ExecError | null, stdout, stderr })
      if (variables.length) runScript(args, 5_000, done)
      else run('tmux', args, { timeout: 5_000 }, done)
    }), features)
    if (result.error) {
      if (result.error.code === 'HARNESS_CANCELLED') return terminalActionNotStarted(result.error.message)
      if (result.error.code === 'ENOENT') return terminalActionNotStarted('tmux is unavailable')
      // tmux says exactly why it refused — "duplicate session", "protocol version mismatch",
      // a .tmux.conf error, a directory it cannot enter. Dropping stderr here turned every one of
      // those into the same unactionable SPAWN_FAILED, diagnosable only by reading the daemon log
      // on the machine that failed, which does not have the reason either.
      const detail = result.stderr.trim().split('\n')[0]?.slice(0, 200)
        // execFile reports a timeout kill as SIGTERM with no stderr — the one failure whose cause
        // is not in tmux's own output.
        || (result.error.killed ? 'tmux did not answer within 5s' : result.error.message.slice(0, 200))
      return terminalActionPossiblyExecuted(`tmux session creation did not complete: ${detail}`)
    }
    // The first line: on stdin, a tmux that `start-server` just started prints its ~/.tmux.conf's errors to the
    // client after the pane id, where on a command line it shows them in the session instead.
    const paneId = result.stdout.trim().split('\n')[0]?.trim() ?? ''
    if (!/^%\d+$/.test(paneId)) {
      return terminalActionPossiblyExecuted('tmux created a session without returning its root pane')
    }
    await setPaneMouseOn(paneId)
    this.styledPanes.set(paneId, style)
    return { state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId } }
  }

  /**
   * [command] as this daemon starts it. Before tmux 3.0, through `ownerCommand`, so the pane's start
   * command carries the tag that a window option cannot keep once the person moves the pane. An empty
   * command is tmux's default shell, and stays that: `/usr/bin/env` with nothing to run would print the
   * environment and exit.
   */
  private ownedCommand(features: TmuxFeatures, owner: string, command: readonly string[] = []): string[] {
    return features.paneOptions || !command.length ? [...command] : ownerCommand(owner, command)
  }

  /**
   * Replace the process running in an existing pane, with a different environment.
   *
   * `-k` kills what is there first; without it tmux refuses a live pane. `remain-on-exit` is turned on
   * in the SAME invocation and for the same reason as in `create`: a respawned engine that dies
   * immediately (a rejected key, a model the grid does not serve) must leave its error on screen
   * instead of taking the pane down with it. Whoever calls this owns turning it back off.
   */
  /**
   * Why [respawn] would refuse this request on this machine's tmux, or null when it would try. Asked by a
   * restart BEFORE it stops the engine it replaces: a respawn refused after the kill left the agent with
   * a dead pane and no engine.
   */
  async respawnRefusal(request: Pick<TerminalRespawnRequest, 'env'>): Promise<string | null> {
    // `respawn-pane -e` is tmux 3.0, and the stdin its list goes on (`runScript`) 3.1; refused before, for
    // the reason `create` gives.
    return Object.keys(request.env ?? {}).length && !(await this.features()).respawnEnv ? tmuxTooOldForEnv(TMUX_FEATURE_MIN.respawnEnv, 'a respawned pane') : null
  }

  async respawn(runtime: TmuxRuntimeRef, request: TerminalRespawnRequest): Promise<TerminalActionResult> {
    const refused = await this.respawnRefusal(request)
    if (refused) return terminalActionNotStarted(refused)
    const features = await this.features()
    const variables = Object.entries(request.env ?? {})
    const scope = paneOptionScope(features)
    // The engine-exit marker is the pane's, and a respawned pane is a new launch: cleared here, in
    // the same invocation, or the new engine would read as exited the moment it started. A `-p` here
    // before tmux 3.0 failed the whole list, the respawn with it, so no agent could restart there.
    const setup = [
      ['set-option', scope, '-t', runtime.paneId, 'remain-on-exit', 'on'],
      ['set-option', scope, '-t', runtime.paneId, ENGINE_EXIT_PANE_OPTION, ''],
    ]
    const args = ['respawn-pane', '-k']
    if (request.cwd) args.push('-c', request.cwd)
    for (const [key, value] of variables) args.push('-e', `${key}=${value}`)
    // A respawn replaces the pane's start command, which carries its tag before tmux 3.0 (`create`).
    args.push('-t', runtime.paneId, ...this.ownedCommand(features, this.owner(), request.command))
    const commands = [...setup, args]
    if (request.expectedHeldToken && !/^[a-f0-9-]{36}$/.test(request.expectedHeldToken)) return terminalActionNotStarted('invalid waiting pane identity')
    const command = request.expectedHeldToken
      ? ['if-shell', '-F', '-t', runtime.paneId, heldPaneFormat(request.expectedHeldToken),
        commands.map(parts => parts.map(tmuxWord).join(' ')).join('; '), 'display-message -p adoption-mismatch']
      : commands.flatMap((parts, index) => index ? [';', ...parts] : parts)
    const result = await new Promise<{ error: NodeJS.ErrnoException | null; stderr: string }>((resolve) => {
      if (request.current?.() === false) { resolve({ error: Object.assign(new Error('The harness changed before pane dispatch'), { code: 'HARNESS_CANCELLED' }), stderr: '' }); return }
      request.onDispatch?.()
      const done: ExecDone = (error, stdout, stderr) => resolve({
        error: stdout.trim() === 'adoption-mismatch' ? Object.assign(new Error('The waiting pane changed'), { code: 'HARNESS_CANCELLED' }) : error as NodeJS.ErrnoException | null,
        stderr,
      })
      // With variables, on stdin, never on tmux's command line (`runScript`, as in `create`).
      if (variables.length) runScript(command, 5_000, done)
      else run('tmux', command, { timeout: 5_000 }, done)
    })
    if (!result.error) return TERMINAL_ACTION_SUCCEEDED
    if (result.error.code === 'HARNESS_CANCELLED') return terminalActionNotStarted(result.error.message)
    if (result.error.code === 'ENOENT') return terminalActionNotStarted('tmux is unavailable')
    // `-k` means the old process may already be gone even though the new one never started, so this
    // cannot be reported as "nothing happened".
    const detail = result.stderr.trim().split('\n')[0]?.slice(0, 200) || result.error.message.slice(0, 200)
    return terminalActionPossiblyExecuted(`tmux could not respawn the pane: ${detail}`)
  }

  /** Read only. The dispatch repeats this predicate inside tmux; this read grants no later write. */
  async isHeld(runtime: TmuxRuntimeRef, token: string): Promise<boolean | 'unknown'> {
    if (!/^%\d+$/.test(runtime.paneId) || !/^[a-f0-9-]{36}$/.test(token)) return 'unknown'
    return new Promise(resolve => run('tmux', ['display-message', '-p', '-t', runtime.paneId,
      heldPaneFormat(token)], { timeout: 2_000 }, (error, stdout) => {
      if (error) { resolve(isNoTmuxServerError(error.message) || /can't find pane: %\d+/.test(error.message) ? false : 'unknown'); return }
      resolve(stdout.trim() === '1' ? true : stdout.trim() === '0' ? false : 'unknown')
    }))
  }

  /** A pending adoption may close only its own inert shell, even after tmux recycled the pane ID. */
  async killHeld(runtime: TmuxRuntimeRef, token: string, current: () => boolean): Promise<TerminalActionResult> {
    if (!/^%\d+$/.test(runtime.paneId) || !/^[a-f0-9-]{36}$/.test(token)) return terminalActionNotStarted('invalid waiting pane identity')
    const result = await inTmuxRoom('notify', () => new Promise<{ error: Error | null; stdout: string }>(resolve => {
      if (!current()) { resolve({ error: new Error('Adoption changed before pane close'), stdout: '' }); return }
      // Evaluated inside the tmux server, in the same command that kills: no check/use gap for %N.
      run('tmux', ['if-shell', '-F', '-t', runtime.paneId, heldPaneFormat(token),
        `kill-pane -t ${runtime.paneId}`, 'display-message -p adoption-mismatch'], { timeout: 5_000 },
      (error, stdout) => resolve({ error, stdout }))
    }))
    if (!result.error && !result.stdout.trim() || result.error && (isNoTmuxServerError(result.error.message) || /can't find pane: %\d+/.test(result.error.message))) return TERMINAL_ACTION_SUCCEEDED
    // if-shell can evaluate against the active pane when its target has already gone. A mismatch
    // is an idempotent close only when an authoritative inventory confirms this exact pane is gone.
    if (await this.paneAbsent(runtime)) return TERMINAL_ACTION_SUCCEEDED
    return terminalActionNotStarted('The waiting pane no longer has this adoption identity')
  }

  async kill(runtime: TmuxRuntimeRef, current?: () => boolean): Promise<TerminalActionResult> {
    if (!/^%\d+$/.test(runtime.paneId)) return terminalActionNotStarted('invalid tmux pane identity')
    // Discovered harnesses can share a tmux session with unrelated work. The
    // canonical pane id is the entire target; never widen this to kill-session.
    // The last pane gone closes its session, a notification to every control client: on a tmux before
    // 3.7, not while one attaches (tmuxControlGate.ts).
    const ok = await inTmuxRoom('notify', () => new Promise<boolean | undefined>((resolve) => {
      if (current && !current()) { resolve(undefined); return }
      run('tmux', ['kill-pane', '-t', runtime.paneId], { timeout: 5_000 }, (error) => resolve(!error))
    }))
    if (ok === undefined) return terminalActionNotStarted('The harness changed before pane close')
    if (ok) return TERMINAL_ACTION_SUCCEEDED
    // The engine may have exited and removed its pane before the parallel PID
    // check completed. Only authoritative inventory makes that an idempotent success.
    // Use all panes here: discovery deliberately hides sessions that were renamed
    // or created elsewhere, and their absence from discovery is not proof of exit.
    if (await this.paneAbsent(runtime)) return TERMINAL_ACTION_SUCCEEDED
    return legacyActionResult(false, 'tmux pane close')
  }

  private paneAbsent(runtime: TmuxRuntimeRef): Promise<boolean> {
    return new Promise<boolean>(resolve => {
      run('tmux', ['list-panes', '-a', '-F', '#{pane_id}'], { timeout: 2_000 }, (error, stdout) => {
        if (error) { resolve(isNoTmuxServerError(error.message)); return }
        const ids = stdout.trim().split('\n').filter(Boolean)
        // A running server lists a pane at the least: an empty listing is a read that was lost, not proof.
        resolve(ids.length > 0 && ids.every(id => /^%\d+$/.test(id)) && !ids.includes(runtime.paneId))
      })
    })
  }

  /**
   * Remove [names] from the environment of the session that owns [runtime].
   *
   * A pane created by `new-session -e` put those variables in the SESSION environment, and
   * `respawn-pane` inherits it — so respawning with no `-e` flags would leave the old grid in place
   * while reporting a clean swap. This is what makes "back to your own login" actually true.
   */
  async clearEnv(runtime: TmuxRuntimeRef, names: readonly string[], current?: () => boolean): Promise<TerminalActionResult> {
    if (!names.length) return legacyActionResult(true, 'tmux clear environment')
    const sessionId = await this.resolveSessionId(runtime.paneId)
    if (current?.() === false) return terminalActionNotStarted('The harness changed before clearing its environment')
    if (!sessionId) return terminalActionNotStarted('tmux session could not be resolved from pane')
    const ok = await new Promise<boolean>((resolve) => {
      run('tmux', clearEnvArgs(sessionId, names), { timeout: 5_000 }, (error) => resolve(!error))
    })
    return legacyActionResult(ok, 'tmux clear environment')
  }

  /** The id of the session that owns [paneId], or null when tmux will not say. */
  private resolveSessionId(paneId: string): Promise<string | null> {
    return new Promise((resolve) => {
      run('tmux', ['display-message', '-p', '-t', paneId, '#{session_id}'], { timeout: 2_000 }, (error, stdout) => {
        const value = stdout.trim()
        resolve(!error && /^\$\d+$/.test(value) ? value : null)
      })
    })
  }

  /**
   * Re-arm `remain-on-exit` on an already-live pane, mirroring what `create()` does at spawn time.
   *
   * Restart must call this BEFORE killing the pane's engine process. `clearPaneRemainOnExit` turns
   * this off the moment an agent is first confirmed (see `cli.ts`'s `onCreateAgent`), so without
   * re-arming it here tmux destroys the pane — and, being its only pane, the whole session — the
   * instant the old process exits.
   */
  async holdOpen(runtime: TmuxRuntimeRef, current?: () => boolean): Promise<TerminalActionResult> {
    const scope = paneOptionScope(await this.features())
    if (current?.() === false) return terminalActionNotStarted('The harness changed before retaining its pane')
    const ok = await new Promise<boolean>((resolve) => {
      run('tmux', ['set-option', scope, '-t', runtime.paneId, 'remain-on-exit', 'on'], { timeout: 2_000 }, (error) => {
        resolve(!error)
      })
    })
    return legacyActionResult(ok, 'tmux remain-on-exit re-arm')
  }

  async titles(): Promise<TerminalReadResult<Map<string, string>>> {
    const titles = await listPaneTitles()
    return {
      state: 'succeeded',
      value: new Map([...titles].map(([paneId, title]) => [terminalRouteKey({ backend: 'tmux', paneId }), title])),
    }
  }

  /**
   * 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 }
    this.restyle(result.panes.map((pane) => pane.tmuxPane))
    return {
      state: 'available',
      roots: result.panes.map((pane) => ({
        runtime: { backend: 'tmux' as const, paneId: pane.tmuxPane },
        rootPid: pane.rootPid,
        cwd: pane.cwd,
      })),
    }
  }

  /**
   * Retroactive, on every scan: a pane from before this build, one that outlived a daemon restart,
   * or every pane after the app changed its palette. Fire-and-forget — a scan that misses one
   * because tmux was briefly slow catches it on the next pass. Panes that are gone are forgotten
   * so a reused pane id is styled afresh. Each pane on its own (`setPaneStyle`), never its window:
   * the person may have moved it into a window of theirs.
   */
  private restyle(panes: readonly string[]): void {
    const style = windowStyleOf(this.hostTheme())
    const live = new Set(panes)
    for (const pane of this.desiredStyles.keys()) {
      if (!live.has(pane)) this.desiredStyles.delete(pane)
    }
    for (const pane of this.styledPanes.keys()) {
      if (!live.has(pane)) this.styledPanes.delete(pane)
    }
    for (const pane of panes) {
      this.desiredStyles.set(pane, style)
      this.applyStyle(pane)
    }
  }

  private applyStyle(pane: string): void {
    const style = this.desiredStyles.get(pane)
    if (style === undefined || this.stylingPanes.has(pane) || this.styledPanes.get(pane) === style) return
    // Serialize writes per pane: scans can overlap a slow tmux command or a theme change.
    this.stylingPanes.add(pane)
    void setPaneStyle(pane, style).then((applied) => {
      if (applied && this.desiredStyles.has(pane)) this.styledPanes.set(pane, style)
    }).finally(() => {
      this.stylingPanes.delete(pane)
      // Apply a newer theme immediately, but retry a failed unchanged write on the next scan.
      if (this.desiredStyles.get(pane) !== style) this.applyStyle(pane)
    })
  }

  async validate(runtime: TmuxRuntimeRef, expected: TerminalProcessExpectation): Promise<RuntimeValidation> {
    try {
      const found = await lookupPaneEngineProcess(this, runtime, expected.engine)
      if (!found.ok) return { state: found.unknown ? 'unknown' : 'gone', reason: found.reason }
      const live = found.identity
      // A saved marker that is not a C-locale `lstart` stamp was written either by the pre-fix parser,
      // with its fields shifted, or by a `ps` that still inherited the user's LC_TIME (see psEnv in
      // lib/childLocale.ts). Either way it can never equal the corrected stamp for the same live
      // process, so comparing it would report a running engine as gone — once, on the upgrade that
      // fixed the reading. The pane still has a matching engine process; take it.
      //
      // Resume's checkSessionRuntime makes the same allowance. The coordinator passes persisted
      // identities directly here when validating or acquiring a terminal lease.
      if (expected.processIdentity && !LSTART_MARKER_RE.test(expected.processIdentity.startMarker)) {
        return { state: 'alive' }
      }
      if (expected.processIdentity && !sameProcessIdentity(expected.processIdentity, live)) {
        return { state: 'gone', reason: 'process changed under tmux pane', replaced: true }
      }
      return { state: 'alive' }
    } catch {
      return { state: 'unknown', reason: 'tmux runtime probe failed' }
    }
  }

  /** Hand the pane back to tmux's default disposal (`clearPaneRemainOnExit`). */
  releaseHold(runtime: TmuxRuntimeRef, current?: () => boolean): Promise<void> {
    return clearPaneRemainOnExit(runtime.paneId, current)
  }

  paneState(runtime: TmuxRuntimeRef): Promise<TerminalPaneRead> {
    return tmuxPaneState(runtime.paneId)
  }

  paneInfo(runtime: TmuxRuntimeRef): Promise<TerminalPaneInfo | null> {
    return tmuxPaneInfo(runtime.paneId)
  }

  rootProcess(runtime: TmuxRuntimeRef): Promise<number | 'missing' | null> {
    return tmuxPanePid(runtime.paneId)
  }

  async capture(runtime: TmuxRuntimeRef, options: TerminalCaptureOptions = {}): Promise<TerminalReadResult<string>> {
    const captured = await captureTmuxPane(runtime.paneId, options.historyLines, {
      visible: options.mode === 'visible',
      ansi: options.ansi,
    })
    return captured === null
      ? { state: 'failed', reason: 'tmux capture failed' }
      : { state: 'succeeded', value: captured }
  }

  async typeLiteral(runtime: TmuxRuntimeRef, text: string): Promise<TerminalActionResult> {
    return legacyActionResult(await sendLiteralToTmux(runtime.paneId, text), 'tmux literal input')
  }

  async submitText(runtime: TmuxRuntimeRef, text: string, options?: SubmitOptions): Promise<TerminalActionResult> {
    const sent = await sendToTmux(runtime.paneId, text, options?.beforeEnter, options?.allowed)
    if (typeof sent === 'boolean') return legacyActionResult(sent, 'tmux submission')
    if ('notPasted' in sent) return terminalActionNotStarted(sent.notPasted)
    return terminalEnterWithheld(sent.withheld)
  }

  async sendKey(runtime: TmuxRuntimeRef, key: TerminalLogicalKey): Promise<TerminalActionResult> {
    return legacyActionResult(await sendKeyToTmux(runtime.paneId, TMUX_KEYS[key]), 'tmux key input')
  }

  async setTitle(runtime: TmuxRuntimeRef, title: string): Promise<TerminalActionResult> {
    const ok = await new Promise<boolean>((resolve) => {
      run('tmux', ['select-pane', '-t', runtime.paneId, '-T', title.slice(0, 200)], { timeout: 2_000 }, (error) => {
        resolve(!error)
      })
    })
    return legacyActionResult(ok, 'tmux title update')
  }

  async notify(runtime: TmuxRuntimeRef, title: string, body: string): Promise<TerminalActionResult> {
    const message = `${title.slice(0, 200)}: ${body.slice(0, 1_000)}`
    const ok = await new Promise<boolean>((resolve) => {
      run('tmux', ['display-message', '-t', runtime.paneId, '--', message], { timeout: 2_000 }, (error) => {
        resolve(!error)
      })
    })
    return legacyActionResult(ok, 'tmux notification')
  }

  /**
   * Stream a pane's bytes. Deliberately NOT gated on identifying the engine process in it.
   *
   * Streaming and injection need different thresholds, and they used to share one. This path
   * addresses the PANE — `capture-pane -t %N` out, `send-keys -t %N` in — and a tmux pane id is
   * monotonic and never reused within a server, so the id alone is a safe address. Injection is the
   * one that types into whatever process owns the pane, and it keeps validating: see
   * `TerminalBackendCoordinator.validateLease` and the lease dispatch fallbacks. The reaper
   * (`coordinator.validate`) keeps validating too.
   *
   * Requiring a match here made the pane unviewable in exactly the situations where seeing it is the
   * whole point: an engine that crashed, one stopped at a first-run prompt under a process the
   * matcher does not cover, or a pane that has fallen back to a bare shell. The agent was listed, and
   * clicking it produced "TERMINAL FROZEN · no <engine> process under tmux pane" instead of the
   * screen that would have explained why. A pane that is genuinely gone still fails, one line later:
   * `TmuxControlStream.open` reads `paneMeta` first and refuses a missing pane and a multi-pane
   * window. Dropping the check also takes a whole-process-table `ps` scan off every terminal open.
   *
   * `expected` stays in the signature because `TerminalBackend` defines it; it is intentionally
   * unused here.
   */
  async openStream(
    runtime: TmuxRuntimeRef,
    expected: TerminalProcessExpectation,
    size: TerminalStreamSize,
    sink: TerminalStreamSink,
    readOnly?: boolean,
  ): Promise<TerminalReadResult<TerminalStreamHandle<TmuxRuntimeRef>>> {
    void expected
    return TmuxControlStream.open(runtime.paneId, size, sink, readOnly)
  }
}