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.

94.4 KB
Raw Blame
import { LAUNCH_LOCATION_VARIABLES } from '../engines/kit/nativeLocations.js'
import type { NativeLaunch } from '../engines/nativeLaunch.js'
import { nativeLaunchGuard } from '../engines/kit/nativeLaunchGuard.js'
import { nativePaneHold, NATIVE_LAUNCH_MARKER } from './nativePaneHold.js'
import { execFile } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { isAbsolute, basename, dirname, join } from 'node:path'
import { baseNode } from '../harnessd/baseNode.js'
import { env } from '../config/env.js'
import { launchContract, launchField } from '../engines/launches.js'
import { startupFunctions, startupNeedsScript, startupRuns } from '../engines/kit/launchStartup.js'
import { screenArgs, screenEnvPrefix, screenPrelude, screenVariables } from '../engines/kit/launchScreen.js'
import { isTerminalEngine, PROCESS_ENGINES, type AgentEngine } from '../engines/types.js'
import { isOpencodeV2 } from '../engines/opencode/contract.js'
import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'
import { windowsEngineArgv } from './windows/launch.js'
import { nativeLaunchConfirmed, windowsHeldPaneArgv, windowsStartupArgs } from './windows/engineStart.js'
import { defaultWindowsShell } from './windows/shell.js'
import { engineBin } from './engineBin.js'
import { launchModelArgs, type LaunchModel } from './launchModel.js'
import { engineInstallPaths, engineInstallRecipe, npmEnginePrefix, type EngineInstallRecipe } from './engineInstall.js'
import { engineLabel } from './agentNames.js'
import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath } from './gridBinary.js'
import { loginShellEnvironment } from './loginShellEnv.js'
import { managedNodePath } from './nodeRuntime.js'
import { RAISE_OPEN_FILES_SH } from './openFiles.js'
import { ENGINE_EXIT_PANE_OPTION } from './engineExitOption.js'
import { shellSingleQuote } from './shellQuote.js'
import { browserPrelude } from './browserShim.js'
import { currentUserShell } from './userShell.js'
import { harnessPaneOwner } from './harnessSessionLabel.js'

export { shellSingleQuote }

/**
 * Best-effort "skip permission prompts" flag per engine, confirmed against each vendor's own docs.
 * `null` = no known/safe flag — callers must hide the option rather than guess one.
 */
export const BYPASS_PERMISSION_FLAGS: Readonly<Record<AgentEngine, string[] | null>> = {
  ...launchField('bypassPermission'),
  cursor: ['--force'],
  opencode: ['--auto'],
  // No permission-prompt system to bypass (pi), or config-file based rather than a flag (hermes).
  pi: null,
  omp: null,
  hermes: null,
  // Unconfirmed — do not guess a flag for a CLI we haven't verified.
  commandcode: null,
  devin: null,
  muse: null,
  amp: null,
  kilo: null,
  grok: null,
  agy: null,
  copilot: null,
  // A shell has no permissions to bypass.
  terminal: null,
}

/**
 * The permission modes a person can pick for a new agent (New Harness ▸ Advanced), per engine, and the
 * argv each one launches with. `auto` is the default and is exactly [BYPASS_PERMISSION_FLAGS]; `ask`
 * adds nothing, so the engine behaves as its own settings say, except Claude Code's, which names its asking
 * mode (claude/launch.ts: given none, 2.1.296 started in auto); the rest are the engines' documented
 * modes (`claude --help`: `--permission-mode acceptEdits|plan`; `codex --help`: `--sandbox read-only`,
 * `--dangerously-bypass-approvals-and-sandbox`). An engine absent here offers no choice.
 *
 * The desktop mirrors this table in `lib/core/permission_modes.dart` — keep both in step.
 */
export const PERMISSION_MODES: Readonly<Partial<Record<AgentEngine, Readonly<Record<string, readonly string[]>>>>> = {
  ...launchField('permissionModes'),
  cursor: { auto: ['--force'], ask: [] },
  opencode: { auto: ['--auto'], ask: [] },
}

/** Modes a relaunch never trades for the engine's own default when the engine on disk lacks their flag: Team-written work,
 *  whose default would read the branch's own settings (audit H2). The relaunch is held. A Buddy's were kept too, until a
 *  Buddy ran in full mode like its owner's own session (task #2832). */
const KEPT_PERMISSION_MODES: ReadonlySet<string> = new Set(['teamWritten'])

/** The argv of [mode] for [engine], or null when the engine has no such mode. */
export function permissionModeFlags(engine: AgentEngine, mode: string): readonly string[] | null {
  const modes = PERMISSION_MODES[engine]
  return modes && Object.hasOwn(modes, mode) ? modes[mode] : null
}

/** Whether [mode] lets the agent act without stopping to ask — what `bypassPermission` records. */
export function permissionModeApproves(mode: string): boolean {
  return mode === 'auto' || mode === 'full'
}

/**
 * How each engine takes a FIRST prompt on launch: the interactive session opens with that message
 * already submitted, so the pane's first visible thing is the agent's answer rather than an empty
 * input waiting for one. `null` = no documented mechanism; the caller refuses (`PROMPT_UNSUPPORTED`)
 * rather than guess, the way `gridLaunch.ts` refuses an engine with no endpoint contract.
 *
 * An entry is the argv placed BEFORE the text: a flag (`['--prompt']`) or nothing at all for an
 * engine that reads a bare positional. Each entry cites where it was read from.
 */
export const FIRST_PROMPT_ARGS: Readonly<Record<AgentEngine, readonly string[] | null>> = {
  ...launchField('firstPromptArgs'),
  // `opencode --help`: `--prompt  prompt to use`, a TUI flag — the interactive session starts with
  // the message submitted. A flag rather than a positional because opencode's own positional is
  // `[project]`, a directory: handed the text bare, it would try to open a folder by that name.
  opencode: ['--prompt'],
  // No documented first-prompt argument for an interactive launch. Not guessed.
  cursor: null,
  pi: null,
  // `omp --help`: ARGUMENTS MESSAGES. A bare positional starts the turn.
  omp: [],
  // `hermes chat --help`: "-q, --query QUERY  Query to run. On a real TTY the prompt seeds an
  // interactive session (first turn)". Measured on a live pane: the prompt is answered and the TUI
  // stays open for the next turn, which is also what lets a fork of a Hermes agent hand off.
  hermes: ['chat', '-q'],
  commandcode: null,
  devin: null,
  muse: null,
  amp: null,
  kilo: null,
  grok: null,
  agy: null,
  copilot: null,
  terminal: null,
}

/** A first prompt is a message, not a document. Enforced at the wire (`agent_create`) before any pane
 *  exists, so an over-long one is refused rather than truncated into something the agent was not asked. */
export const MAX_FIRST_PROMPT_CHARS = 2000

/** The refusal for an engine with no entry in [FIRST_PROMPT_ARGS]. `code` is the wire error. */
export class FirstPromptUnsupportedError extends Error {
  readonly code = 'PROMPT_UNSUPPORTED' as const
  constructor(readonly engine: AgentEngine) {
    // What to do instead, not only what is missing (prompt_unsupported, Oct 21–27).
    const takers = PROCESS_ENGINES.filter(supportsFirstPrompt).map(engineLabel)
    super(`${engineLabel(engine)} cannot start with a first message. Start it without one and type the message once it opens, `
      + `or choose ${takers.slice(0, -1).join(', ')} or ${takers.at(-1)} to start with one.`)
    this.name = 'FirstPromptUnsupportedError'
  }
}

export function supportsFirstPrompt(engine: AgentEngine): boolean {
  return FIRST_PROMPT_ARGS[engine] !== null
}

/** The argv that hands `prompt` to `engine` as its first message. Throws [FirstPromptUnsupportedError]
 *  for an engine with no contract, so a caller cannot build an argv that silently drops the prompt. */
export function firstPromptArgs(engine: AgentEngine, prompt: string): string[] {
  const lead = FIRST_PROMPT_ARGS[engine]
  if (lead === null) throw new FirstPromptUnsupportedError(engine)
  return [...lead, prompt]
}

/**
 * How each engine opens AS one of its named agents — its own name in the footer, its own system
 * prompt — rather than as a general session. `null` = no documented mechanism; the caller refuses
 * (`AGENT_UNSUPPORTED`) before a pane exists, the way [FIRST_PROMPT_ARGS] does for a prompt.
 *
 * An entry is the argv placed BEFORE the name. Unlike a first prompt, the agent IS part of the
 * relaunch record (`RegisteredSession.agent`, carried by `launchOverrides.ts`): a pane opened as
 * `harness-compute` comes back as `harness-compute`.
 */
export const NAMED_AGENT_ARGS: Readonly<Record<AgentEngine, readonly string[] | null>> = {
  // `opencode --help`: `--agent  agent to use`. The name is one of opencode's own agents
  // (`~/.config/opencode/agents/<name>.md`, `mode: primary`).
  opencode: ['--agent'],
  // No documented "open as this named agent" argument for an interactive launch. Not guessed.
  claude: null,
  codex: null,
  cursor: null,
  pi: null,
  omp: null,
  hermes: null,
  commandcode: null,
  devin: null,
  muse: null,
  amp: null,
  kilo: null,
  grok: null,
  agy: null,
  copilot: null,
  terminal: null,
}

/** An agent name is an identifier the engine looks a file up by — never a path, never prose. */
export const AGENT_NAME_RE = /^[A-Za-z0-9_-]{1,64}$/

/** The refusal for an engine with no entry in [NAMED_AGENT_ARGS]. `code` is the wire error. */
export class NamedAgentUnsupportedError extends Error {
  readonly code = 'AGENT_UNSUPPORTED' as const
  constructor(readonly engine: AgentEngine) {
    super(`${engine} has no documented way to open as a named agent, so the agent was not created.`)
    this.name = 'NamedAgentUnsupportedError'
  }
}

/**
 * `opencodeMajor` is the installed OpenCode's major version (`engines/opencode/version.ts`), absent
 * meaning v1. v2 moved `--agent` to `opencode run`; its TUI exits 1 on the flag, so v2 has no entry.
 */
export function supportsNamedAgent(engine: AgentEngine, opencodeMajor: number | null = null): boolean {
  if (engine === 'opencode' && isOpencodeV2(opencodeMajor)) return false
  return NAMED_AGENT_ARGS[engine] !== null
}

/** The argv that opens `engine` as its named agent `agent`. Throws [NamedAgentUnsupportedError] for
 *  an engine with no contract, so a caller cannot build an argv that silently drops the name. */
export function namedAgentArgs(engine: AgentEngine, agent: string, opencodeMajor: number | null = null): string[] {
  const lead = NAMED_AGENT_ARGS[engine]
  if (lead === null || !supportsNamedAgent(engine, opencodeMajor)) throw new NamedAgentUnsupportedError(engine)
  return [...lead, agent]
}

export interface LaunchCommandOptions {
  /** One executable and its prepared settings, retained through every launch fact. */
  native?: NativeLaunch
  bypassPermission?: boolean
  /** A mode from [PERMISSION_MODES]; when the engine has it, it decides the flags and
   *  `bypassPermission` is ignored. */
  permissionMode?: string
  /** Resume this engine session id on launch, when a launch-resume flag is known for the engine. */
  resumeSessionId?: string
  /** FORK this engine session id on launch — a new session that starts with its history, the source
   *  untouched ([LAUNCH_FORK_FLAG]). Takes precedence over `resumeSessionId`. */
  forkSessionId?: string
  /**
   * The message the session opens with, already submitted — see [FIRST_PROMPT_ARGS]. Appended LAST,
   * after every flag, because two of the three engines take it positionally and a positional is only
   * unambiguous once the options are exhausted.
   *
   * A launch option and nothing more: it is never written to the registry row, so a relaunch (which
   * resumes a session that already has its first turn) never repeats it. Never logged either — it is
   * what the user typed.
   */
  firstPrompt?: string
  /**
   * The model and effort this session runs on, as flags of that session alone (lib/launchModel.ts). A launch option
   * like `firstPrompt`: never written to the registry row, so a relaunch is the engine's own again.
   */
  launchModel?: LaunchModel
  /**
   * Terminal only: print the tile's banner before the first prompt — the wordmark, where this pane
   * is, that an agent typed here becomes the tile, and `harness remote`. Every NEW terminal tile
   * gets it (`agent_create`); a pane rebuilt by restore or restart is not a new tile and names
   * nothing here.
   */
  terminalHint?: { machineName: string }
  /**
   * Extra argv the caller has already composed, appended last.
   *
   * Exists for engines whose endpoint is configured on the command line rather than through the
   * environment — Codex's `-c model_providers.*`, Grok's `-m`. See `gridLaunch.ts`; a credential
   * never travels this way.
   */
  extraArgs?: readonly string[]
  /**
   * The words the machine's owner added to this agent (`registry` `launchArgs`), appended after everything else: the
   * extra arguments, the model and the first prompt. Last, so a trailing flag that takes a value fails loudly at
   * startup instead of swallowing an argument Harness itself added, and a flag of theirs cannot be read as a value of
   * Harness's. Checked by `checkLaunchWords` before they get here.
   */
  ownerArgs?: readonly string[]
  /**
   * A shell line to run in the pane BEFORE the engine, from `engineInstall.ts` — the engine is not on
   * this machine yet and the user agreed to fetch it.
   *
   * It runs inside the same interactive shell the engine is about to be exec'd into, which is the
   * only context where installing helps: `npm`, `node` and `curl` routinely arrive through
   * `.zshrc`/`.bashrc` (nvm, asdf, vendor installers), and a prefix chosen by the daemon's PATH would
   * either not find npm or install into a prefix the engine's own shell cannot then see. The second
   * failure is the dangerous one — it looks like success and leaves the engine still missing.
   *
   * Ignored when there is no interactive shell to wrap with: without one there is no launch script to
   * put it in, and running an installer through a bare `execFile` would use the daemon's PATH, which
   * is the case above.
   */
  installFirst?: string
  /** Install only when command[0] is absent, checked inside the pane's already-started shell. */
  installIfMissing?: EngineInstallRecipe
  /**
   * Environment variables to clear in the pane before the engine starts — the vendor credentials a
   * grid launch must not leave lying around. See `gridConflictingEnvToClear` in `gridLaunch.ts`,
   * which is the only caller and which computes them from what the launch itself sets.
   *
   * It has to happen HERE rather than through tmux, because `tmux new-session -e` can only set a
   * variable, never remove one — and the value being removed was inherited from the tmux server, the
   * daemon, or the terminal that started the app, none of which this process can reach back into.
   *
   * Scoped to the engine's own process. Nothing on disk changes, and a plain shell on the same
   * machine keeps everything it had.
   */
  clearEnv?: readonly string[]
  /**
   * A DSH agent: when the pane's shell, rc files and all, has no `node`, the Node this daemon runs on
   * joins the END of its PATH before the engine starts, so the agent's own tool calls can run what the
   * harness's skills tell them to (`node "$MARP_TOOLCHAIN/check.mjs"`, a package's tscircuit CLI). A
   * machine with no node on PATH is the normal case since the runtime went private; a plain engine
   * launch is left exactly as it was.
   */
  harnessNode?: boolean
  /** Workspace entered after interactive-shell startup, not before it. */
  cwd?: string
  /**
   * A conversation taken over from the terminal that has it, once its turn ends (`agent_create`
   * `takeOver: 'wait'`): the pane says it is waiting and starts the engine when that process is
   * gone — the daemon stops it when the turn ends. Ctrl-C gives up and leaves it where it was.
   * Ignored without an interactive shell, like `installFirst`: there is no script to wait in.
   */
  waitForPid?: { pid: number; name: string }
}

/**
 * Best-known "resume this session id" launch flag per engine — kept SEPARATE from tmux.ts's
 * `RESUME_ARGS` (parsing-only, reverse-engineered from an already-running process's argv, never proven
 * as a launch argument). `claude` and `codex` are populated here from confirmed real invocations (see
 * the `resumeSessionId` test fixtures in tmux.spec.ts: `'claude --resume <id>'`, `'codex resume <id>'`)
 * even though `RESUME_ARGS` has no entry for either — that map's silence reflects that neither engine
 * ever needed argv-based repair (both fire their own SessionStart hook on resume), not an absent flag.
 * `amp` needs its full subcommand chain (`amp threads continue <id>`, confirmed by the same fixture
 * file) rather than the bare `continue` alternative `RESUME_ARGS` also accepts for parsing purposes.
 *
 * A wrong or unsupported entry here is not fatal: restart (cli.ts's `onRestartAgent`) falls back to a
 * fresh, no-resume relaunch automatically if the flagged relaunch doesn't produce a recognizable
 * process within budget — a working agent under a fresh session beats a dead pane.
 *
 * Moving a running agent to a grid re-execs it through the same path, and relies on the same table for
 * the same reason: an engine that came back with no way to resume would have thrown away the
 * conversation the user was in the middle of.
 *
 * A leading token that does NOT start with `-` is a SUBCOMMAND (`resume`, `threads continue`) and must
 * be the first argv after the binary, ahead of any other flag — `buildEngineCommandArgv` branches on
 * this. `devin --resume <id>` is documented since Devin CLI 2026.4.17 (docs.devin.ai/cli, "Essential
 * commands"); it must run in the session's own folder, or Devin asks which folder to use.
 */
export const LAUNCH_RESUME_FLAG: Readonly<Partial<Record<AgentEngine, string[]>>> = {
  ...launchField('resumeArgs'),
  cursor: ['--resume'],
  opencode: ['--session'],
  kilo: ['--session'],
  // Not `--session`: Pi writes a session's file only once its first reply lands, and `--session <id>`
  // with no file answers "No session found matching" and exits, so a Pi nobody had written to yet died
  // on a model switch or a restart. `--session-id` opens that project's session when it exists and
  // creates it under the same id when it does not (Pi 1.0 `createSessionManager`).
  pi: ['--session-id'],
  hermes: ['--resume'],
  commandcode: ['--resume'],
  muse: ['resume'],
  amp: ['threads', 'continue'],
  grok: ['--resume'],
  agy: ['--conversation'],
  copilot: ['--resume'],
  devin: ['--resume'],
}

/**
 * "Open a NEW session that starts with everything session <id> has" — a fork, per engine. Confirmed
 * against each CLI's own `--help` (2026-09-18): `claude --resume <id> --fork-session` ("When resuming,
 * create a new session ID") and `codex fork <id>` ("Fork a previous interactive session"). The source
 * session is left exactly as it was; the two then diverge.
 *
 * Same shape rule as [LAUNCH_RESUME_FLAG]: a leading token that does not start with `-` is a
 * subcommand and goes first. `after` is appended once the id is in place. An engine absent here has no
 * native fork; `forkAgent.ts` falls back to a handoff (a composed first prompt) where the engine takes
 * one, and refuses otherwise — never a plain `--resume`, which would put two processes on ONE session.
 */
export const LAUNCH_FORK_FLAG: Readonly<Partial<Record<AgentEngine, { lead: string[]; after?: string[] }>>> = {
  ...launchField('forkArgs'),
}

/** Whether a relaunch can reopen this engine's previous conversation — see [LAUNCH_RESUME_FLAG].
 *  `lib/resumeCapability.ts` turns this into what Pause/Resume may promise a person. */
export function supportsLaunchResume(engine: AgentEngine): boolean {
  return LAUNCH_RESUME_FLAG[engine] !== undefined
}

export function supportsNativeFork(engine: AgentEngine): boolean {
  return LAUNCH_FORK_FLAG[engine] !== undefined
}

/** The executable argv, before the interactive-shell wrapper is applied. */
export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandOptions = {}): string[] {
  // Windows: the flags its declared startup puts first (Codex's `--no-daemon`), which a launch script probes for elsewhere.
  const argv = [opts.native?.executable?.command ?? engineBin(engine), ...(process.platform === 'win32' ? windowsStartupArgs(engine, opts.native) : [])]
  // A fork is a resume that leaves the source alone; the two are exclusive, and the fork wins.
  const fork = opts.forkSessionId ? LAUNCH_FORK_FLAG[engine] : undefined
  const resumeFlag = fork ? fork.lead : opts.resumeSessionId ? LAUNCH_RESUME_FLAG[engine] : undefined
  const sessionArg = fork ? opts.forkSessionId : opts.resumeSessionId
  const resumeIsSubcommand = !!resumeFlag?.length && !resumeFlag[0].startsWith('-')
  // Subcommand-style resume (`codex resume <id>`, `amp threads continue <id>`, `muse resume <id>`) is
  // parsed positionally and must be the first argv after the binary, ahead of any other flag.
  if (resumeIsSubcommand && resumeFlag && sessionArg) {
    argv.push(...resumeFlag, sessionArg, ...(fork?.after ?? []))
  }
  const modeFlags = opts.permissionMode ? permissionModeFlags(engine, opts.permissionMode) : null
  if (modeFlags) {
    argv.push(...modeFlags)
  } else if (opts.bypassPermission) {
    const flags = BYPASS_PERMISSION_FLAGS[engine]
    if (flags) argv.push(...flags)
  }
  if (!resumeIsSubcommand && resumeFlag && sessionArg) {
    argv.push(...resumeFlag, sessionArg, ...(fork?.after ?? []))
  }
  // Ahead of the extra arguments, so a grid's or a harness's own value for the same key is the one that holds.
  argv.push(...screenArgs(launchContract(engine)))
  if (opts.extraArgs?.length) argv.push(...opts.extraArgs)
  if (opts.launchModel) argv.push(...launchModelArgs(engine, opts.launchModel))
  if (opts.firstPrompt) argv.push(...firstPromptArgs(engine, opts.firstPrompt))
  if (opts.ownerArgs?.length) argv.push(...opts.ownerArgs)
  // Windows: the engine's .exe, or the node script its npm shim runs; never the .ps1 PowerShell would pick, and never
  // a batch file cmd.exe would read the first message through (lib/windows/launch.ts).
  return windowsEngineArgv(engine, argv)
}

export interface InteractiveEngineShell {
  path: string
  args: readonly string[]
  label: string
}

/**
 * The shell users get in a terminal is not the detached daemon's environment.
 *
 * zsh needs its login files as well as .zshrc; Ubuntu's usual bash setup puts
 * nvm/asdf and vendor PATH edits in .bashrc, so it must be interactive but not
 * login.  Other POSIX-like shells get the portable interactive form.
 */
/**
 * The shells that speak the POSIX shell language every launch script here is written in. Any other
 * login shell (fish, tcsh, csh, nushell, xonsh) cannot run one: handed the script with `-c`, it fails
 * on the first `if … then` or `"$@"`, and the engine never starts. tcsh ships with macOS and stands
 * in for all of them: before this, no agent started at all for a person whose shell was not POSIX,
 * and no terminal tile either (e2e/shells.e2e.ts).
 */
const POSIX_SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'oksh', 'pdksh', 'ash', 'yash', 'posh', 'busybox'])
/** Shells that are not POSIX but take `-i` to load the person's interactive startup files. */
const INTERACTIVE_FLAG_SHELLS = new Set(['fish', 'tcsh', 'csh', 'xonsh'])

export function isPosixShell(path: string): boolean {
  return POSIX_SHELLS.has(basename(path).toLowerCase())
}

export function interactiveEngineShell(shell: string | undefined = undefined): InteractiveEngineShell | null {
  // Windows has no shell that runs these scripts. Its SHELL, where one is set at all, is not one: OpenSSH for Windows
  // sets `c:\windows\system32\cmd.exe`, and every launch, probe and environment read went to `cmd.exe -c`, which
  // reads `-c` as nothing and the script as a command (measured on the Windows 11 VM, 2026-10-15). So never one there:
  // each caller has its no-shell path (lib/windows/engineStart.ts).
  if (process.platform === 'win32') return null
  const candidate = shell === undefined ? currentUserShell() : shell
  if (!candidate || !isAbsolute(candidate)) return null
  const name = basename(candidate).toLowerCase()
  switch (name) {
    case 'zsh': return { path: candidate, args: ['-lic'], label: 'zsh login shell' }
    case 'bash': return { path: candidate, args: ['-ic'], label: 'bash interactive shell' }
    default: return isPosixShell(candidate)
      ? { path: candidate, args: ['-ic'], label: `${name} interactive shell` }
      // Separate flags: not every one of these reads them combined.
      : { path: candidate, args: INTERACTIVE_FLAG_SHELLS.has(name) ? ['-i', '-c'] : ['-c'], label: `${name} shell` }
  }
}

/** Automated zsh launches must set this BEFORE rc files run. Oh My Zsh otherwise waits for an
 * update answer before the engine exists, while an agent switch is still showing the old pane.
 * DISABLE_UPDATE_PROMPT would auto-update instead; DISABLE_AUTO_UPDATE skips that work entirely.
 * Keep ordinary terminal launches unchanged, and keep loading rc files for PATH/version managers. */
export function engineShellArgv(shell: InteractiveEngineShell, args: readonly string[]): string[] {
  if (!isPosixShell(shell.path)) return throughPosixShell(shell, args)
  const prefix = basename(shell.path).toLowerCase() === 'zsh'
    ? ['/usr/bin/env', 'DISABLE_AUTO_UPDATE=true', ...zshNewUserGuard()]
    : []
  return [...prefix, shell.path, ...shell.args, ...args]
}

/** The startup files zsh's new-user module looks for (zshmodules(1), zsh/newuser). */
const ZSH_STARTUP_FILES = ['.zshenv', '.zprofile', '.zshrc', '.zlogin'] as const

/** The .zshenv in Harness's own ZDOTDIR (`zshNewUserGuard`): the person's ZDOTDIR back as it was, or unset,
 *  before anything of theirs is read; zsh then reads .zprofile, .zshrc and .zlogin from theirs. */
export const ZSH_GUARD_ZSHENV = `# Written by Harness (engineLaunch.ts zshNewUserGuard): keeps zsh's new-user menu out of an agent's pane.
if (( \${+HARNESS_ZDOTDIR} )); then ZDOTDIR="\$HARNESS_ZDOTDIR"; unset HARNESS_ZDOTDIR; else unset ZDOTDIR; fi
[[ -r "\${ZDOTDIR:-\$HOME}/.zshenv" ]] && builtin source "\${ZDOTDIR:-\$HOME}/.zshenv"
`

/**
 * Keeps zsh's new-user menu out of an engine's pane. Debian, Ubuntu, Fedora and Arch ship zsh's
 * `zsh/newuser` module: on a terminal, for someone with none of the four startup files in $ZDOTDIR (else
 * $HOME), it runs a full-screen menu that waits for a key, so every agent's pane showed it and no engine
 * started (the end-to-end suite's first Linux runs, 2026-10-06; macOS's zsh has no such module). The
 * module looks only there, right after the global zshenv: for such a person ZDOTDIR points at a folder of
 * Harness's whose .zshenv puts theirs back (`HARNESS_ZDOTDIR`; absent means unset). Anyone with a startup
 * file of their own starts exactly as before.
 */
export function zshNewUserGuard(environment: NodeJS.ProcessEnv = process.env): string[] {
  const dotdir = environment.ZDOTDIR || environment.HOME
  if (!dotdir || ZSH_STARTUP_FILES.some((name) => existsSync(join(dotdir, name)))) return []
  const folder = join(env.ADAPTER_DATA_DIR, 'zsh-startup')
  try {
    mkdirSync(folder, { recursive: true, mode: 0o700 })
    const file = join(folder, '.zshenv')
    let current: string | null = null
    try { current = readFileSync(file, 'utf8') } catch { /* not written yet */ }
    if (current !== ZSH_GUARD_ZSHENV) writeFileSync(file, ZSH_GUARD_ZSHENV, { mode: 0o600 })
  } catch {
    // A ZDOTDIR without its .zshenv would leave the person's own ZDOTDIR unrestored: launch as before.
    return []
  }
  return [`ZDOTDIR=${folder}`, ...(environment.ZDOTDIR !== undefined ? [`HARNESS_ZDOTDIR=${environment.ZDOTDIR}`] : [])]
}

/**
 * For a shell that is not POSIX: it loads the person's environment (their PATH, their version
 * managers), then hands the script to a POSIX shell (`posixRunner`). The script and its arguments go
 * in a one-time file (`launchFile`), so all the person's shell parses is `exec /bin/dash '<file>'`,
 * which fish, tcsh, nushell and xonsh read alike. `args` is what a POSIX shell would take after
 * `-c`: the script, `$0`, then the arguments.
 */
function throughPosixShell(shell: InteractiveEngineShell, args: readonly string[]): string[] {
  const [script = '', , ...positional] = args
  const file = launchFile((path) => `rm -f -- ${shellSingleQuote(path)}\nset -- ${positional.map(shellSingleQuote).join(' ')}\n${script}`)
  return [shell.path, ...shell.args, `exec ${posixRunner()} ${shellSingleQuote(file)}`]
}

/**
 * The POSIX shell that runs a launch no login shell takes: dash where there is one (macOS ships it,
 * and it is Debian's and Ubuntu's /bin/sh), else /bin/sh. Run non-interactive, dash resumes an engine
 * that stopped like the rest (`STOP_PROOF_FUNCTIONS`), and so does Linux's bash 5; the bash 3.2 that
 * is macOS's /bin/sh never sees the stop, and the engine would wait, stopped, for good.
 */
function posixRunner(): string {
  return existsSync('/bin/dash') ? '/bin/dash' : '/bin/sh'
}

/**
 * A one-time file in the daemon's own data folder holding a launch script, which removes itself as it
 * starts. Private to this user, and no secret: those reach the pane through the session's environment,
 * never its command. One that never ran (a pane tmux would not make) is swept an hour on.
 *
 * Why a file: the launch goes to tmux as one `new-session` command, which tmux refuses past 16KiB
 * ("command too long", measured with tmux 3.7c), and the script is most of it. With a first prompt of
 * 2,000 three-byte characters, a grid's arguments and environment and a resume id, a Codex launch
 * written out on the command line came to 17.9KB. Named by a file, no launch comes near the limit.
 */
function launchFile(content: (path: string) => string): string {
  const directory = join(env.ADAPTER_DATA_DIR, 'launch')
  mkdirSync(directory, { recursive: true, mode: 0o700 })
  sweepLaunchFiles(directory)
  const file = join(directory, `${randomUUID()}.sh`)
  writeFileSync(file, content(file), { mode: 0o600 })
  return file
}

const LAUNCH_FILE_TTL_MS = 60 * 60_000

function sweepLaunchFiles(directory: string): void {
  try {
    for (const name of readdirSync(directory)) {
      if (!name.endsWith('.sh')) continue
      const path = join(directory, name)
      try { if (Date.now() - statSync(path).mtimeMs > LAUNCH_FILE_TTL_MS) rmSync(path, { force: true }) } catch { /* gone already */ }
    }
  } catch { /* nothing to sweep */ }
}

/**
 * The `-c` a POSIX login shell is given: `. '<file>'`, the launch script read from a one-time file
 * (`launchFile`) by the shell itself. Sourced, its commands are the shell's own top level, where a
 * stop is safe (`STOP_PROOF_FUNCTIONS`; measured the same as an inline script in zsh, bash, sh and
 * dash), and they keep the shell's positional parameters. Without a data folder to write in, the
 * script goes on the command line as it used to.
 */
function sourcedOnce(script: string): string {
  try {
    return `. ${shellSingleQuote(launchFile((path) => `rm -f -- ${shellSingleQuote(path)}\n${script}`))}`
  } catch {
    return script
  }
}

/**
 * Full argv for a fresh tmux pane. `exec` replaces the shell with the engine,
 * preserving process discovery while loading the same startup files a user
 * gets in Terminal/iTerm/Ubuntu Terminal. Arguments are positional, not a
 * shell command string, so engine paths and flags cannot be interpolated.
 */
export function buildEngineLaunchArgv(
  engine: AgentEngine,
  opts: LaunchCommandOptions = {},
  shell: string | undefined = undefined,
  runtimeNode: string = managedNodePath(),
  gridBinary: string = gridBinaryPath(),
  tmuxBinary: string | null = resolveBinaryOnPath('tmux'),
): string[] {
  if (isTerminalEngine(engine)) return buildTerminalLaunchArgv(opts, shell)
  const command = buildEngineCommandArgv(engine, opts)
  // Windows has no POSIX shell to run the launch script in: the engine is the pane's command, and what the script does
  // around it is the daemon's and the pty host's (lib/windows/engineStart.ts). A native launch whose prepared
  // executable or settings changed since they were confirmed waits in a held pane instead, as the guard below does.
  if (process.platform === 'win32') {
    return opts.native?.executable && !nativeLaunchConfirmed(opts.native)
      ? windowsHeldPaneArgv('Waiting for native launch preparation to be confirmed.', opts.native.token)
      : command
  }
  // An engine whose declared startup runs in the script gets one even where the daemon has no login shell.
  const interactive = interactiveEngineShell(shell)
    ?? (opts.native || startupNeedsScript(launchContract(engine)) ? { path: posixRunner(), args: ['-c'], label: 'shell' } : null)
  // No shell to run a script in (no SHELL, and the account's own shell is not an absolute path): the screen's
  // variables still reach the engine, through env.
  if (!interactive) return [...screenEnvPrefix(launchContract(engine)), ...command]
  const enginePrelude = engineFallbackPrelude(engine, interactive.path, tmuxBinary)
  // The clear comes FIRST, before the install as well as before the engine. An installer is a child
  // of this shell and inherits what it inherits: `npm` is not going to spend someone's Anthropic key,
  // but an install script that probes for credentials to configure itself would, and the whole point
  // of this launch is that the agent's environment is the one the user asked for.
  // Then the grid's PATH entry at the FRONT (its dir holds only `grid`), and — for a DSH agent — Harness's
  // Node at the END, only when the shell found none. The two never meet: one prepends, one appends.
  const nativeEnv = Object.entries(opts.native?.environment ?? {}).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}\n`).join('')
  // The screen's variables come after the rc files and the native ones, so neither a profile nor an adopted
  // environment chooses the other screen (facets/launch.ts `ScreenContract`). The shell the pane falls back to keeps
  // them, so an engine typed there afterwards runs on the same screen.
  const prelude = enginePrelude + clearEnvPrelude(opts.clearEnv) + clearEnvPrelude(opts.native?.clearEnvironment) + nativeEnv
    + screenPrelude(launchContract(engine)) + gridPanePrelude(gridBinary) + browserPrelude() + noDevtoolsPrelude() + (opts.harnessNode ? harnessNodePrelude(runtimeNode) : '')
  // rc files (notably nvm) call getcwd() before running this command. Start the shell in a safe
  // directory and enter the selected workspace only after those files have loaded: an IDE can replace
  // a workspace inode between the desktop picker resolving it and tmux spawning the pane.
  const cwdPrelude = opts.cwd
    ? `if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; exit 1; fi\n`
      + unreadableCwdGuard()
      + 'shift\n'
    : ''
  // The engine is found (or installed first), then run at the script's top level (`engineRunScript`).
  const engineFound = opts.native ? 'harness_engine_bin=$1\n' : opts.installIfMissing
    ? installIfMissingScript(opts.installIfMissing, runtimeNode, { engine, messageWaiting: Boolean(opts.firstPrompt) })
    : opts.installFirst
      ? installFirstScript(opts.installFirst)
      : 'harness_engine_bin=$1\n'
  const heldCommand = `/bin/sh -c ${shellSingleQuote('trap \'\' INT QUIT TSTP; printf \'%s\\n\' \"$1\"; while :; do sleep 3600; done')} harness-held ${shellSingleQuote('Waiting for native launch preparation to be confirmed.')} ${shellSingleQuote(opts.native?.token ?? '')}`
  // tmux retains pane_start_command across exec. Transition this pane to the
  // inert command so core can recognize its exact token after a crash, using the
  // same server-side predicate as every other held launch. No engine has run.
  const waiting = nativePaneHold(opts.native?.token ?? '', tmuxBinary, heldCommand, runtimeNode, harnessPaneOwner(env.ADAPTER_DATA_DIR))
  const guard = opts.native ? nativeLaunchGuard(opts.native, runtimeNode, waiting) : ''
  const body = `${JOB_CONTROL}${SIGNAL_GUARD}${engineFound}shift\n${guard}${engineRunScript(engine, tmuxBinary)}`
  // The open-files raise goes ahead of everything, the installer included: a pane inherits the tmux
  // SERVER's soft limit, which is launchd's 256 whenever the desktop app started the daemon that
  // started the server, and an engine (Claude Code refuses outright) or an npm install under 256 is
  // the failure the person then reads in the pane. See openFiles.ts.
  const wait = opts.waitForPid ? waitForPidScript(opts.waitForPid) : ''
  const script = RAISE_OPEN_FILES_SH + prelude + cwdPrelude + wait + body
  const argv = engineShellArgv(interactive, [isPosixShell(interactive.path) ? sourcedOnce(script) : script, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command])
  // Keep the nonce outside the one-time file, including non-POSIX and inline
  // launches. It is tmux's original launch identity, never a post-rc environment fact.
  return opts.native ? ['/usr/bin/env', `${NATIVE_LAUNCH_MARKER}=${opts.native.token}`, ...argv] : argv
}

/**
 * The variables a launch sets around its engine on Windows, which has no `/usr/bin/env` to put in front of the argv
 * (`buildEngineLaunchArgv` leaves it out there): the screen's (engines/kit/launchScreen.ts) and a native launch's
 * marker. The caller sends them with the pane's env (the pty host's create and respawn env), which the engine
 * inherits, after the launch's own so they win as the prefix did. None elsewhere, where they are in the argv. A screen's
 * cleared variables cannot ride an env; no engine declares any (facets/launch.ts `clearEnvironment`).
 */
export function engineLaunchEnv(engine: AgentEngine, native?: Pick<NativeLaunch, 'token'>, platform: NodeJS.Platform = process.platform): Record<string, string> | undefined {
  if (platform !== 'win32') return undefined
  // As the prefix wrote it: `${token}`, which a native launch always has (nativeLaunch.ts).
  const variables = { ...screenVariables(launchContract(engine)), ...(native ? { [NATIVE_LAUNCH_MARKER]: `${native.token}` } : {}) }
  return Object.keys(variables).length ? variables : undefined
}

/**
 * Job control, before the install and the engine: a pane's interactive shell has it already, the
 * hand-off's non-interactive one (`throughPosixShell`) gets it here (`STOP_PROOF_FUNCTIONS`), and
 * without a terminal (the specs) a shell goes on without it. zsh is asked by its own option: a
 * `set -m` that fails ends a zsh script, `|| :` or not.
 */
const JOB_CONTROL = 'if [ -n "${ZSH_VERSION:-}" ]; then setopt monitor 2>/dev/null || :; else set -m 2>/dev/null || :; fi\n'

/**
 * An engine that dies of SIGINT or SIGQUIT must not take the script with it. zsh, seeing its
 * foreground job killed by one of those, gives up the rest of the script as if it had been interrupted
 * itself; dash run interactive drops to its prompt; bash run without a terminal of its own (as the
 * hand-off's /bin/sh) exits: the exit handling never ran and the pane closed, or sat in a bare shell,
 * instead of turning into the person's shell (measured on main with zsh 5.9, dash and bash 5.3). npm's
 * Codex is a Node wrapper that re-raises the signal its native engine died of, and one it does not
 * listen for itself (QUIT) ends the job that way. With a trap they all go on; interactive bash and sh
 * went on anyway. The non-interactive bash then reports a job killed by INT as a success (status 0),
 * which still turns the pane into a shell. The trap does nothing else: the engine still gets the
 * signals itself, since a caught signal is reset for a child. Set after a take-over's wait, which has
 * a trap of its own.
 */
const SIGNAL_GUARD = 'trap : INT QUIT\n'

/** Waits in the pane for [wait]'s process to end before the engine starts: see `waitForPid`. Its
 *  second's sleep runs in a command substitution, out of a Ctrl+Z's reach (`STOP_PROOF_FUNCTIONS`):
 *  zsh would take a stopped `sleep` for the end of the script, and bash would leave the loop and
 *  start the engine while the terminal's still has the conversation. */
function waitForPidScript(wait: { pid: number; name: string }): string {
  const pid = Math.trunc(wait.pid)
  const name = wait.name.replace(/[^A-Za-z0-9 ._-]/g, '')
  return `printf '%s\\n' 'Waiting for the ${name} in your terminal to finish its turn.' 'It moves here when the turn ends. Ctrl-C leaves it there.'\n`
    + `trap 'printf "\\n%s\\n" "It stays in your terminal."; exit 130' INT\n`
    + `while kill -0 ${pid} 2>/dev/null; do harness_waited=$(sleep 1) || :; done\n`
    + `trap - INT\n`
    + `printf '\\033[H\\033[2J'\n`
}

/**
 * Discards what reached the pane's terminal for the engine that just left, before a shell can read it.
 *
 * An engine does not leave the moment it is told to: Claude Code runs its SessionEnd hooks first, and
 * reads no more input meanwhile. A message the daemon typed in that window (it checked the engine was
 * there just before) sat in the terminal's input, and the shell handed over next ran it as a command:
 * end to end, a message sent right behind `/exit` became a shell command one run in four once the fake
 * engines ran the real hooks (e2e/input-safety.e2e.ts). Everything waiting is read and dropped, until
 * nothing more comes for 0.3 s; it was typed for the engine, and is nobody's to run. The terminal's
 * settings are put back as they were. Without `stty` (no terminal) nothing is touched.
 */
export const ENGINE_INPUT_DRAIN_SH = '  if harness_tty=$(stty -g 2>/dev/null) && stty -icanon -echo min 0 time 3 2>/dev/null; then\n'
  + '    while harness_waiting=$(dd bs=65536 count=1 2>/dev/null | wc -c) && [ "$((harness_waiting))" -gt 0 ]; do :; done\n'
  + '    stty "$harness_tty" 2>/dev/null || true\n'
  + '  fi\n'

/**
 * The shell functions every engine launch runs its engine with, instead of a bare `exec`.
 *
 * The engine is a CHILD of the pane's shell, and when it exits — `/exit`, Ctrl-C, a crash — the
 * pane does not die with it: `harness_after` records the exit status on the pane (`ENGINE_EXIT_PANE_OPTION`,
 * which is how the daemon tells "the engine left" from "the install is still running") and `exec`s
 * the user's interactive shell in its place, exactly as a terminal opened with ⌘⇧T is. The daemon
 * then turns the row back into a terminal (`registry.releaseEngine`) rather than deleting it, and
 * typing the engine's name into that shell adopts it again (`adoptEngine`). A 127 is the one exit
 * that still ends the pane: the command was not found at all, and "not installed" needs to stay
 * a failure the app can name rather than a prompt with an error above it.
 *
 * `tmuxBinary` is the daemon's own tmux, quoted into the script, because the pane's shell may not
 * have it on PATH (the managed runtime never is). Without one the marker is skipped and the fallback
 * still happens — only a failure at launch then takes the daemon's full wait to notice.
 *
 * Without a terminal on stdin there is nobody to hand a shell to, so `harness_after` exits with the
 * engine's status instead — which is also what keeps the specs that run these scripts honest.
 *
 * A stop is not an exit: `harness_resume` continues a stopped engine, so only its real exit reaches
 * `harness_after` (`STOP_PROOF_FUNCTIONS`). The engine's run itself is `engineRunScript`'s, at the
 * script's top level. An engine's declared startup adds its own functions here: Codex's probe for its
 * owned-process flag and its runs again after a failed startup (engines/kit/launchStartup.ts).
 */
export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tmuxBinary: string | null): string {
  const loginArgs = basename(shellPath).toLowerCase() === 'zsh' ? ' -l' : ''
  // Named by the command a person would type (`cursor-agent`, `cmd`), not the engine id.
  const command = basename(engineBin(engine)) || engine
  // The pane's own option; a tmux before 3.0 has no pane options and refuses `-p`, so there the mark
  // goes on the pane's window, where `tmuxPaneState` reads it just the same. Without the second try
  // the mark was never made on such a tmux, and an engine that left read as still starting.
  const tmux = tmuxBinary && isAbsolute(tmuxBinary) ? shellSingleQuote(tmuxBinary) : null
  const mark = tmux
    ? `  [ -n "\${TMUX_PANE:-}" ] && { ${tmux} set-option -p -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1`
      + ` || ${tmux} set-option -w -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1; } || true\n`
    : ''
  return STOP_PROOF_FUNCTIONS
    + 'harness_after() {\n'
    + '  if [ "$harness_status" -eq 127 ]; then exit 127; fi\n'
    + mark
    // Only a pane — something with a terminal on stdin — gets a shell to type into. Run without one
    // (a spec exercising the script, a wrapper piped somewhere) the engine's own status is the answer.
    + '  if ! [ -t 0 ]; then exit "$harness_status"; fi\n'
    + ENGINE_INPUT_DRAIN_SH
    // The person's own shell gets back the developer folder they had (`noDevtoolsPrelude`).
    + '  if [ "${HARNESS_DEVELOPER_DIR:-}" = 1 ]; then unset DEVELOPER_DIR HARNESS_DEVELOPER_DIR; fi\n'
    + `  printf '\\n%s\\n' ${shellSingleQuote(`harness: ${command} exited ($harness_status). This pane is a shell now — run ${command} again, or stop the pane.`).replace('($harness_status)', `('"$harness_status"')`)}\n`
    + `  exec ${shellSingleQuote(shellPath)}${loginArgs}\n`
    + '}\n'
    + startupFunctions(engine, launchContract(engine), tmuxBinary, baseNode(process.execPath))
}

/**
 * A stopped engine is continued, never taken for one that exited: Ctrl+Z, which Claude Code and Codex
 * both answer by suspending themselves (they give the terminal back and stop their whole process
 * group, "Run `fg` to bring Claude Code back"), or a SIGSTOP from outside. tmux does this for a pane's
 * own process (server_child_stopped continues it at once), but the engine is the pane shell's child,
 * and an agent's pane has no prompt to type `fg` into.
 *
 * The pane shell has job control: the engine runs as its foreground job, in a process group of its own
 * that holds the terminal. Seeing that job stop, the shell used to carry on to the end of the launch
 * script (bash, sh) or give the script up at once (zsh), and exit, hanging up the stopped engine: the
 * pane closed and the agent was gone. Now `harness_resume` puts a stopped engine back in the
 * foreground with `fg`, as often as it stops, until it really exits, and keeps that exit status.
 * Measured in tmux with zsh 5.9, bash 3.2 and 5.3, sh and dash, each its own way:
 *
 *  - zsh gives up the whole script when a foreground job stops inside a function, an `if`, a loop or
 *    an `eval`, and carries on only after one at the top level; a stop seen by `fg` is fine anywhere.
 *    So the engine, and an install, run at the script's top level (`engineRunScript`). zsh prints its
 *    "suspended" and "continued" lines as they happen, as it would in a terminal.
 *  - bash breaks out of every loop around a job that stops, wherever the loop is, so there (and in
 *    sh and dash) the resume calls itself instead of looping; zsh's loops, which keeps it clear of
 *    zsh's limit on nested calls.
 *  - `fg` keeps its standard error. Run without a terminal of its own, bash takes standard error for
 *    the terminal, so a `fg 2>/dev/null` there never handed the terminal over: the engine stopped
 *    again on its first write to it, at once and for ever, until the recursion overflowed (bash 5.3
 *    as Fedora's /bin/sh, the hand-off of a fish or tcsh login).
 *  - A stop that comes back within a second of its resume, three times running, is resumed only after
 *    a second's pause, so nothing can spin; one that cannot take the terminal (TTIN, TTOU) five times
 *    running, or the thousandth stop of one run where the resume recurses, ends the engine instead
 *    (SIGKILL, status 137), and the pane turns into a shell as after any exit.
 *  - bash puts the terminal back in its own modes when a job stops and does not restore the job's on
 *    `fg` (zsh does; dash leaves them alone). Neither Claude Code nor Codex takes raw mode again on a
 *    plain SIGCONT, only after a stop of its own, so one stopped from outside under bash comes back
 *    to a line-mode terminal until it sets its modes again: accepted, and the e2e shows it. Ctrl+Z is
 *    not affected: the engine gave the terminal back and takes it again itself.
 *  - A stop of a process below the engine's own is seen by no shell, as one below a pane's process
 *    is seen by no tmux: npm's Codex is a Node wrapper with the native engine as its child, and a
 *    SIGSTOP of that child alone leaves it stopped. Its Ctrl+Z stops the whole group, wrapper too.
 *  - ksh93 stops the whole `... || harness_status=$?` list with the job and goes on with a status of
 *    0, so there a stop still reads as the engine's exit, as it did everywhere before.
 *
 * Only a job that stopped is resumed, told by its status — 128 plus STOP, TSTP, TTIN or TTOU, by name,
 * since the numbers differ between macOS and Linux — and not by `%%` alone, which could be a job a rc
 * file left running.
 *
 * Every other command the script waits on — a probe, a backoff, the wait for a take-over — runs in a
 * command substitution. That keeps it in the pane shell's own process group, which has no parent in
 * its session (tmux is outside it), and the kernel discards a terminal stop sent to such a group: a
 * Ctrl+Z at that moment is ignored rather than stopping a helper in a function, which zsh would again
 * take for the end of the script.
 */
const STOP_PROOF_FUNCTIONS = [
  'harness_stopped() {',
  '  [ "$harness_status" -gt 128 ] 2>/dev/null || return 1',
  '  harness_signal=$(kill -l "$harness_status" 2>/dev/null) || return 1',
  '  case $harness_signal in',
  '    STOP|TSTP|TTIN|TTOU|SIGSTOP|SIGTSTP|SIGTTIN|SIGTTOU) jobs %% >/dev/null 2>&1 ;;',
  '    *) return 1 ;;',
  '  esac',
  '}',
  'harness_fg() {',
  '  harness_now=$(date +%s 2>/dev/null) || harness_now=0',
  '  if [ $((harness_now - harness_resumed)) -le 1 ]; then harness_quick=$((harness_quick + 1)); else harness_quick=0; fi',
  '  harness_resumes=$((harness_resumes + 1))',
  '  case $harness_signal in *TTIN|*TTOU) harness_stuck=$harness_quick ;; *) harness_stuck=0 ;; esac',
  '  if [ "$harness_stuck" -ge 5 ] || { [ -z "${ZSH_VERSION:-}" ] && [ "$harness_resumes" -ge 1000 ]; }; then',
  '    kill -9 %% 2>/dev/null',
  '    harness_status=137',
  '    return 0',
  '  fi',
  '  if [ "$harness_quick" -ge 3 ]; then harness_waited=$(sleep 1) || :; fi',
  '  harness_resumed=$(date +%s 2>/dev/null) || harness_resumed=0',
  '  harness_status=0',
  '  fg >/dev/null || harness_status=$?',
  '}',
  'harness_resume() {',
  '  if [ -n "${ZSH_VERSION:-}" ]; then',
  '    while harness_stopped; do harness_fg; done',
  '    return 0',
  '  fi',
  '  harness_stopped || return 0',
  '  harness_fg',
  '  harness_resume',
  '}',
  'harness_resumed=0',
  'harness_quick=0',
  'harness_resumes=0',
  '',
].join('\n')

/**
 * The engine's run, then `harness_after`, at the script's top level: the one place a stop is safe in
 * every shell (`STOP_PROOF_FUNCTIONS`). `$harness_engine_bin` is the engine and `"$@"` its arguments.
 * An engine's declared startup decides how it is run: Codex's with its probed flag, and once more after a
 * startup that never opened its conversation (engines/kit/launchStartup.ts).
 */
function engineRunScript(engine: AgentEngine, tmuxBinary: string | null): string {
  return startupRuns(engine, launchContract(engine), tmuxBinary)
}

/**
 * The wordmark, as `cli/scripts/install.sh` prints it when an install is done (its `print_logo`);
 * `engineLaunch.spec.ts` holds the two to the same five lines. Printed through `printf '%s\n'` with
 * every line single-quoted, so the backslashes and the backtick reach the pane as drawn.
 */
export const HARNESS_WORDMARK_LINES: readonly string[] = [
  '    _',
  '   | |__   __ _ _ __ _ __   ___  ___ ___',
  "   | '_ \\ / _` | '__| '_ \\ / _ \\/ __/ __|",
  '   | | | | (_| | |  | | | |  __/\\__ \\__ \\',
  '   |_| |_|\\__,_|_|  |_| |_|\\___||___/___/',
]

/**
 * What a new terminal tile says before its prompt, every time one is opened — the installer's
 * finale, in the tile: the wordmark, where this pane is, and three things to type, each explained
 * in a column. An agent typed here becomes the tile (and the shell is back when it exits);
 * `harness remote` is the one thing only a tile can act on, since it swaps the tile it is typed in.
 * Every line stays under 78 columns — a pane is 80 wide when it prints them, before the app has
 * sized it, and a wrapped line stays wrapped in the scrollback. The block ends on a blank line, so
 * the prompt does not sit against it.
 */
export function terminalHintLines(machineName: string): string[] {
  // A hostname can be long (a cloud VM's FQDN runs to 50 characters); past the width the line has
  // left it is cut with an ellipsis rather than wrapped, which is the one thing the block promises.
  const name = machineName.trim() || 'this machine'
  const where = name.length > 62 ? `${name.slice(0, 61)}…` : name
  const row = (command: string, what: string): string => `    ${command.padEnd(29)}  ${what}`
  return [
    '',
    ...HARNESS_WORDMARK_LINES,
    '',
    `  Terminal on ${where}`,
    '',
    row('claude · codex · opencode …', 'run an agent here — this tile becomes it'),
    row('harness remote', 'open a terminal on another machine'),
    row('harness --help', 'everything else'),
    '',
  ]
}

/**
 * Full argv for a plain terminal pane: the user's login shell, nothing exec'd over it.
 *
 * The outer `-c` shell is non-interactive on purpose — it loads no rc files, only raises the
 * open-files limit (a `claude` typed into this terminal later would otherwise refuse under
 * launchd's 256, exactly as a launched engine would) and enters the workspace — then `exec`s the
 * interactive shell, which loads the user's startup files once, the way Terminal.app would. zsh
 * gets `-l` so its login files run; bash reads .bashrc on an interactive non-login start, which is
 * where Ubuntu keeps nvm and vendor PATH edits, so it gets no flag (same reasoning as
 * `interactiveEngineShell`). Without a resolvable shell the pane runs `/bin/sh`, which at least
 * gives the person a prompt.
 */
export function buildTerminalLaunchArgv(
  opts: Pick<LaunchCommandOptions, 'cwd' | 'terminalHint' | 'clearEnv'> = {},
  shell: string | undefined = undefined,
): string[] {
  // Windows: the shell a pane gets by default, started in the workspace (lib/windows/engineStart.ts `windowsPaneLaunch`).
  // The banner needs a script to print it, and is left out.
  if (process.platform === 'win32') return defaultWindowsShell()
  const candidate = shell === undefined ? currentUserShell() : shell
  const path = candidate && isAbsolute(candidate) ? candidate : '/bin/sh'
  const loginArgs = basename(path).toLowerCase() === 'zsh' ? ['-l'] : []
  const cwdPrelude = opts.cwd
    ? `if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; fi\n`
    : ''
  const hintPrelude = opts.terminalHint && process.env.HARNESS_OS !== '1'
    ? `printf '%s\\n' ${terminalHintLines(opts.terminalHint.machineName).map(shellSingleQuote).join(' ')}\n`
    : ''
  // The prelude is a POSIX script. For a shell that is not POSIX, /bin/sh runs it and then execs the
  // person's shell, which loads its own startup files as it always does.
  const interpreter = isPosixShell(path) ? path : '/bin/sh'
  return [interpreter, '-c', RAISE_OPEN_FILES_SH + clearEnvPrelude(opts.clearEnv) + browserPrelude() + cwdPrelude + hintPrelude + 'shift\nexec "$@"', 'harness-terminal', opts.cwd ?? '', path, ...loginArgs]
}

/**
 * Refuse a workspace the shell could enter but cannot read, and say why — before the engine finds
 * out on its own terms.
 *
 * `cd` succeeding proves only the search bit. macOS privacy protection (TCC) leaves exactly that:
 * a process whose responsible app was never granted Documents, Desktop or Downloads may enter the
 * folder and is refused its first readdir with EPERM. The engine then dies with nothing to go on —
 * Claude Code printed "An unknown error occurred (Unexpected)" on a machine whose tmux server had
 * been started by a terminal app without Documents access, and every pane the daemon opened on
 * that server inherited the refusal — so the check is made here, where the reason can be given.
 * `[ -r . ]` is `access(2)`, which TCC answers the same way as the readdir would.
 *
 * The hint names the fix for the platform this daemon generates the script on, which is the one
 * the pane runs on. `$PWD` is left to the shell so the message names the folder as entered. Short
 * lines, the action first: a dialog that relays the pane's last lines keeps about 180 characters
 * (agentCreateDiagnosis.ts), and the folder path alone can take half of that.
 */
export function unreadableCwdGuard(platform: NodeJS.Platform = process.platform): string {
  const hints = platform === 'darwin'
    ? [
        'harness: on macOS, grant Full Disk Access to the app that started tmux (and to Harness), then run: tmux kill-server',
        'harness: or pick a folder outside Documents, Desktop and Downloads (System Settings › Privacy & Security).',
      ]
    : ['harness: check the folder\'s permissions for this user.']
  return `if ! [ -r . ]; then printf '%s\\n' "harness: cannot read $PWD — the agent was not started." `
    + `${hints.map(shellSingleQuote).join(' ')} >&2; exit 1; fi\n`
}

/** Harness's Node at the end of PATH when the shell found none — see `LaunchCommandOptions.harnessNode`. */
export function harnessNodePrelude(runtimeNode: string = managedNodePath()): string {
  return `if ! command -v node >/dev/null 2>&1; then PATH="\${PATH:+$PATH:}"${shellSingleQuote(dirname(runtimeNode))}; export PATH; fi\n`
}

/**
 * `unset` for the variables a grid launch must not let through, or nothing at all.
 *
 * Names only — never values — and each is validated against a strict shell-identifier shape before it
 * reaches the script. The list is a constant in our own source today, so this is a guard against a
 * future caller rather than against anything on the wire; it is here because the day that changes is
 * the day nobody re-reads this function.
 */
function clearEnvPrelude(names: readonly string[] | undefined): string {
  const safe = (names ?? []).filter((name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
  return safe.length ? `unset ${safe.join(' ')}\n` : ''
}

/**
 * Install, then start the engine — or say why not, and stop.
 *
 * Three things this script gets right, each of which was a way to lose:
 *
 *  * **The engine only on success.** Running the engine after a failed install reproduces the exact
 *    `command not found` this feature exists to replace, with a screenful of npm output above it to
 *    bury the cause.
 *  * **The install line is not interpolated into a command.** It is the vendor's own published line
 *    from `engineInstall.ts` — a constant in our source, never anything a user or a peer supplied —
 *    and it is `eval`ed as the shell line it is written as, because `curl … | bash` is one of them.
 *    Nothing from the wire reaches here; if that ever changes, this is the line that must not.
 *  * **`"$@"` still carries the engine argv positionally**, so engine paths and flags are never
 *    re-parsed by the shell. That property is what the plain `exec "$@"` had and it is preserved.
 *
 * The install runs in a subshell at the script's top level, like the engine, so a Ctrl+Z in the
 * middle of it is resumed rather than ending the pane (`STOP_PROOF_FUNCTIONS`).
 *
 * The banner matters more than it looks. A pane that sits silent for forty seconds of `npm install`
 * reads as a hung agent, and the person's next move is to kill it.
 */
function installFirstScript(install: string): string {
  return [
    `printf '%s\\n' 'harness: installing the engine — this pane becomes the agent when it finishes' 'harness: $ ${install.replace(/'/g, "'\\''")}' ''`,
    'harness_status=0',
    `(eval ${JSON.stringify(install)}) || harness_status=$?`,
    'harness_resume',
    `if [ "$harness_status" -ne 0 ]; then printf '\\n%s\\n' 'harness: the install failed, so the agent was not started. The command is above; fix it and create the agent again.'; exit 1; fi`,
    'harness_engine_bin=$1',
    '',
  ].join('\n')
}

/**
 * Make npm recipes work on machines where Harness owns Node instead of installing it system-wide.
 *
 * The verified Node archive provisioned by `harness start` includes npm, but the daemon deliberately
 * does not mutate the user's PATH. A tmux login shell can therefore have neither `node` nor `npm`
 * even though the runtime executing Harness has both. Prefer any npm the user already configured;
 * otherwise prepend the managed runtime's bin directory for this pane only. This is portable across
 * macOS and Linux and avoids an interactive/root package-manager install in an agent launch.
 */
/** Harness's own Node folders. An npm engine run through them (`npm install -g` without a prefix) lands here. */
export function npmRuntimeBins(runtimeNode: string = managedNodePath()): string[] {
  return [...new Set([dirname(runtimeNode), dirname(baseNode(process.execPath))])]
}

function npmRuntimePrelude(recipe: EngineInstallRecipe, runtimeNode: string): string {
  if (!recipe.executable.npmGlobal) return ''
  const bins = npmRuntimeBins(runtimeNode)
    .map(shellSingleQuote)
    .join(' ')
  return [
    'if ! command -v node >/dev/null 2>&1 || ! command -v npm >/dev/null 2>&1; then',
    `  for harness_node_bin in ${bins}; do`,
    '    if [ -x "$harness_node_bin/node" ] && [ -x "$harness_node_bin/npm" ]; then',
    '      PATH="$harness_node_bin${PATH:+:$PATH}"',
    '      export PATH',
    '      hash -r 2>/dev/null || true',
    '      break',
    '    fi',
    '  done',
    'fi',
  ].join('\n')
}

/**
 * The `grid` this pane's agent gets is the one the daemon resolved — and stays it.
 *
 * `grid` is not only the daemon's subprocess: the Harness Compute skill has the AGENT run it, in
 * this pane, by name. A managed grid under `~/.harness/runtime` is invisible to a shell's PATH, and
 * a login file that puts `~/.local/bin` first is ordinary — which is where grid's own installer
 * (uv, on a Mac) leaves a `grid` of some other version. So the prepend is made HERE, after those
 * files have run, the way [npmRuntimePrelude] does for the managed Node — never by a symlink in
 * `~/.local/bin`, which would fight the installer for one file. Two versions of `grid` writing one
 * `~/.grid` is the outcome this exists to prevent.
 *
 * Without an absolute path to prepend — the bare name of the PATH fallback, or an override that is
 * not one — PATH is left alone. Either way grid's update check is off for the pane —
 * [GRID_NO_UPDATE_CHECK_VAR]: the agent is the process most likely to read "run `grid update`" and
 * do it, and under a managed runtime that overwrites the pin.
 *
 * Interactive shells only, like the npm prelude: a direct launch has no script to carry this.
 */
export function gridPanePrelude(binary: string): string {
  const onPath = isAbsolute(binary)
    ? [`PATH=${shellSingleQuote(dirname(binary))}"\${PATH:+:$PATH}"`, 'export PATH', 'hash -r 2>/dev/null || true']
    : []
  return [...onPath, `${GRID_NO_UPDATE_CHECK_VAR}=1`, `export ${GRID_NO_UPDATE_CHECK_VAR}`, ''].join('\n')
}

/** Where the developer tools are looked for; the specs point these at folders of their own. */
export interface DevtoolsPlaces {
  xcodeSelect: string
  /** Where Apple's command line developer tools install. */
  commandLineTools: string
  selectLink: string
}

const MAC_DEVTOOLS: DevtoolsPlaces = {
  xcodeSelect: '/usr/bin/xcode-select',
  commandLineTools: '/Library/Developer/CommandLineTools',
  selectLink: '/var/db/xcode_select_link',
}

/**
 * Keeps an agent from bringing up Apple's "Install Command Line Developer Tools" dialog.
 *
 * On a Mac without the developer tools, `/usr/bin/git`, `python3`, `make`, `cc`, `xcrun`, `xcodebuild`
 * and the rest are stubs that open that dialog and fail. Agents run them unasked: on a fresh Mac (the
 * activation VM, 2026-10-09) OpenCode ran `python3` for the first workspace's starter task, and a real
 * Claude Code and Codex pair brought it up too, over the person's first session. Given a
 * `DEVELOPER_DIR` that does not exist, every stub fails at once with "xcrun: error: missing
 * DEVELOPER_DIR path" instead, and no dialog (measured on that VM). It is the folder the tools
 * install to, so once they are installed they work, in a pane already open too. An environment
 * variable reaches what PATH could not: the login shells agents run commands in (`path_helper` puts
 * /usr/bin first again; stand-ins on PATH were bypassed that way, and raced when panes opened
 * together) and absolute `/usr/bin/…` calls.
 *
 * A Mac with the tools or Xcode, and every other system, only pays for `[ -x ]`, `[ -d ]` and `[ -e ]`
 * tests: `xcode-select -p` (which answers without a dialog) runs only when none of the usual places
 * exists, in a command substitution, out of a Ctrl+Z's reach (`STOP_PROOF_FUNCTIONS`). A
 * `DEVELOPER_DIR` already set is the person's own choice and stays.
 *
 * `HARNESS_DEVELOPER_DIR=1` marks the one set here. A launch that inherits it (a daemon restarted from
 * such a pane) decides again, and a pane that turns into the person's shell after its engine
 * (`harness_after`) drops both: Xcode installed meanwhile would otherwise fail there. An explicit
 * `xcode-select --install` still opens Apple's installer with it set (measured on the VM).
 */
export function noDevtoolsPrelude(places: DevtoolsPlaces = MAC_DEVTOOLS): string {
  const xcodeSelect = shellSingleQuote(places.xcodeSelect)
  return [
    'if [ "${HARNESS_DEVELOPER_DIR:-}" = 1 ]; then unset DEVELOPER_DIR HARNESS_DEVELOPER_DIR; fi',
    `if [ -x ${xcodeSelect} ] && [ -z "\${DEVELOPER_DIR:-}" ] && [ ! -d ${shellSingleQuote(`${places.commandLineTools}/usr/bin`)} ] && [ ! -e ${shellSingleQuote(places.selectLink)} ] && ! harness_devtools=$(${xcodeSelect} -p 2>/dev/null); then`,
    `  DEVELOPER_DIR=${shellSingleQuote(places.commandLineTools)}`,
    '  HARNESS_DEVELOPER_DIR=1',
    '  export DEVELOPER_DIR HARNESS_DEVELOPER_DIR',
    'fi',
    '',
  ].join('\n')
}

/** Install if needed, then run an exact native argv from an existing interactive prompt.
 * The parent shell keeps its helpers and environment when the agent exits. */
export function shellAgentArgv(binary: string, args: string[], recipe: EngineInstallRecipe,
  runtimeNode: string = managedNodePath()): string[] {
  return ['/bin/sh', '-c', RAISE_OPEN_FILES_SH + STOP_PROOF_FUNCTIONS
    + installIfMissingScript(recipe, runtimeNode) + 'shift\nexec "$harness_engine_bin" "$@"\n',
    'harness-shell-agent', binary, ...args]
}

/**
 * Install-if-missing has to resolve twice: before installing, and again after it returns.
 *
 * A `curl | bash` installer cannot export PATH back into its parent shell. Several supported
 * vendors correctly put their binary under ~/.local/bin and update a profile for the NEXT shell,
 * which previously made this very pane print `command not found` after a successful install. The
 * source-owned candidate paths below bridge that one-shell gap without sourcing arbitrary profile
 * files a second time. npm installs also get their active global prefix as a fallback.
 */
/**
 * How a pane says it is installing its agent. The installer's own output (the command, npm's notices,
 * "engine is missing") read as an error to the people it was for: the owner, reviewing a fresh-Mac
 * run, "we don't want to show scary text on the terminal" (2026-10-08). So the pane shows three plain
 * lines and a bar that moves with time (installers report no progress), and the installer's output
 * goes to a log under ~/.harness/logs, shown only when the install fails. It runs through Harness's
 * own Node, so where that is missing (an install without the managed runtime) the pane shows the
 * installer as before. Typical times are measured on a fresh Mac (VM, 2026-10-08).
 */
export interface FriendlyInstall {
  engine: string
  /** A first message is waiting to go to the agent once it starts. */
  messageWaiting: boolean
}

const TYPICAL_INSTALL_SECONDS: Readonly<Record<string, number>> = { opencode: 10, claude: 12, pi: 12, codex: 20 }

/** The progress shown while the installer's output streams into the log (argv: label, seconds, log, waiting). */
const INSTALL_PROGRESS_JS = [
  'const fs=require("fs");const [label,sec,log,waiting]=process.argv.slice(1);const E=Number(sec)*1000;const t0=Date.now();',
  'const out=fs.openSync(log,"a");fs.writeSync(out,"\\n--- "+new Date().toISOString()+" installing "+label+"\\n");',
  'process.stdin.on("data",(d)=>fs.writeSync(out,d));',
  'const rows=waiting==="1"?3:2;let drawn=false;',
  'const draw=()=>{const t=Date.now()-t0;const f=Math.min(0.97,Math.max(0.04,1-1/(1+2.4*t/E)));const n=Math.round(f*24);',
  'const left=Math.round((E-t)/1000);const when=t>3*E?"still working, this can take a while":left>3?"about "+left+" s":"almost there";',
  'const lines=["Installing "+label+"…  "+when,"█".repeat(n)+"░".repeat(24-n)].concat(waiting==="1"?["Your message goes as soon as it starts."]:[]);',
  'let text=drawn?"\\x1b["+rows+"F":"";for(const l of lines)text+="\\r\\x1b[2K"+l+"\\n";drawn=true;process.stdout.write(text);};',
  'draw();const tick=setInterval(draw,500);',
  'process.stdin.on("end",()=>{clearInterval(tick);fs.closeSync(out);});',
].join('')

function installIfMissingScript(recipe: EngineInstallRecipe, runtimeNode: string, friendly?: FriendlyInstall, home?: string, downloadEngine = friendly?.engine): string {
  const install = recipe.command
  const label = downloadEngine ? (downloadEngine === 'claude' ? 'Claude Code' : engineLabel(downloadEngine)) : ''
  const seconds = friendly ? (TYPICAL_INSTALL_SECONDS[friendly.engine] ?? 15) : 0
  const names = recipe.executable.names.map(shellSingleQuote).join(' ')
  const paths = engineInstallPaths(recipe, home).map(shellSingleQuote).join(' ')
  const prefix = home ? join(home, '.local') : npmEnginePrefix()
  // Scope both npm env spellings to the installer subprocess. Do not rewrite .npmrc or install
  // into a different OS user's shared prefix, and do not tie the engine to a versioned Node folder.
  // Either way a subshell, run at the top level where a stop is resumed (STOP_PROOF_FUNCTIONS).
  const run = (line: string) => recipe.executable.npmGlobal
    ? `(export npm_config_prefix=${shellSingleQuote(prefix)} NPM_CONFIG_PREFIX=${shellSingleQuote(prefix)}; eval ${shellSingleQuote(line)})`
    : `(eval ${shellSingleQuote(line)})`
  const installCommand = run(install)
  // The same line, its output into the log and the progress on the screen. Its status is the
  // installer's, written by the inner subshell; no file means the subshell itself was ended (Ctrl-C),
  // which counts as 130 so no fallback follows.
  const quiet = (line: string) => '( ( ' + run(line) + '; printf %s $? >"$harness_install_rc" ) 2>&1 | '
    + `${shellSingleQuote(runtimeNode)} -e ${shellSingleQuote(INSTALL_PROGRESS_JS)} ${shellSingleQuote(label)} ${seconds} "$harness_install_log" ${friendly?.messageWaiting ? 1 : 0}`
    + '; harness_rc="$(cat "$harness_install_rc" 2>/dev/null || echo 130)"; rm -f "$harness_install_rc"; exit "$harness_rc" )'
  const candidates = [names, paths].filter(Boolean).join(' ')
  // `curl … | bash` exits 0 when curl itself fails (bash ran an empty script), so the fallback is
  // decided by whether an executable exists afterwards, not by the first line's status.
  // Decided first, then run as a top-level command like the first install line: a Ctrl+Z inside a
  // compound `if` makes zsh drop the rest of it (STOP_PROOF_FUNCTIONS). An install the person ended
  // with Ctrl-C (130) is not followed by another one.
  const fallback = recipe.fallback ? [
    'harness_try_fallback=0',
    'if [ -z "$harness_engine_bin" ] && [ "$harness_status" -ne 130 ]; then',
    '  hash -r 2>/dev/null || true',
    '  if ! harness_find_engine "$1"; then',
    '    harness_try_fallback=1',
    '    harness_status=0',
    `    [ "$harness_quiet" -eq 1 ] || printf '\\n%s\\n' 'harness: that install did not finish; trying the npm package instead' 'harness: $ ${recipe.fallback.replace(/'/g, "'\\''")}' ''`,
    // The friendly view keeps it in the log, which a failure shows the end of.
    ...(friendly ? [`    [ "$harness_quiet" -eq 0 ] || printf '%s\\n' 'harness: that install did not finish; trying the npm package instead' >>"$harness_install_log"`] : []),
    '  fi',
    'fi',
    `[ "$harness_try_fallback" -eq 0 ] || [ "$harness_quiet" -eq 1 ] || ${run(recipe.fallback)} || harness_status=$?`,
    ...(friendly ? [`[ "$harness_try_fallback" -eq 0 ] || [ "$harness_quiet" -eq 0 ] || ${quiet(recipe.fallback)} || harness_status=$?`] : []),
    'harness_resume',
  ] : []
  return [
    'resolve_engine() {',
    '  candidate="$1"',
    '  resolved=""',
    '  case "$candidate" in',
    '    */*) resolved="$candidate" ;;',
    '    *) resolved="$(command -v "$candidate" 2>/dev/null)" || true ;;',
    '  esac',
    '  [ -n "$resolved" ] && [ -f "$resolved" ] && [ -x "$resolved" ]',
    '}',
    // The first of these that is there becomes `harness_engine_bin`. Loops are fine here: nothing in
    // them can stop the way the engine can.
    'harness_find_engine() {',
    '  harness_engine_bin=',
    `  for candidate in "$1"${candidates ? ` ${candidates}` : ''}; do`,
    '    if resolve_engine "$candidate"; then harness_engine_bin="$resolved"; return 0; fi',
    '  done',
    ...(recipe.executable.npmGlobal ? [
      '  npm_prefix="$(npm prefix -g 2>/dev/null)" || true',
      '  if [ -n "$npm_prefix" ]; then',
      `    for bin in ${names}; do`,
      '      if resolve_engine "$npm_prefix/bin/$bin"; then harness_engine_bin="$resolved"; return 0; fi',
      '    done',
      '  fi',
    ] : []),
    '  return 1',
    '}',
    // A previously installed npm launcher also needs Node. Resolve the runtime before executing
    // it, not just before installing it; fresh users often have no system node on PATH.
    npmRuntimePrelude(recipe, runtimeNode),
    // Desktop Harness downloads OpenCode, Codex and Claude Code beside a fresh computer's setup and
    // names the downloading process in `~/.harness/run/downloading-<engine>`. A pane that opens
    // meanwhile waits for that download, under the same line and bar, rather than starting a second
    // install into the folder it is writing (two npm installs into one prefix can break both). A
    // marker whose process is gone, or is not that download, is ignored. At most ten minutes.
    // The waiting runs in command substitutions, out of a Ctrl+Z's reach (STOP_PROOF_FUNCTIONS), with
    // the bar sent to the terminal through standard error. A wait ended early (Ctrl-C, the ten
    // minutes) while the download still runs ends the pane rather than starting a second install.
    ...(downloadEngine ? [
      'harness_wait_download() {',
      '  harness_dl_pid=$(cat "$HOME/.harness/run/downloading-$1" 2>/dev/null) || return 0',
      "  case \"$harness_dl_pid\" in ''|*[!0-9]*) return 0 ;; esac",
      '  kill -0 "$harness_dl_pid" 2>/dev/null || return 0',
      '  ps -p "$harness_dl_pid" -o command= 2>/dev/null | grep -q harness-download || return 0',
      '  if [ "$harness_quiet" -eq 1 ]; then',
      '    harness_dl_w=$( ( harness_dl_i=0; while kill -0 "$harness_dl_pid" 2>/dev/null && [ "$harness_dl_i" -lt 1200 ]; do sleep 0.5; harness_dl_i=$((harness_dl_i + 1)); done ) | '
        + `${shellSingleQuote(runtimeNode)} -e ${shellSingleQuote(INSTALL_PROGRESS_JS)} ${shellSingleQuote(label)} ${seconds} "$harness_install_log" ${friendly?.messageWaiting ? 1 : 0} >&2 ) || :`,
      '  else',
      `    printf '%s\\n' ${shellSingleQuote(`harness: ${label} is downloading in the background; waiting for it`)}`,
      '    harness_dl_i=0; while kill -0 "$harness_dl_pid" 2>/dev/null && [ "$harness_dl_i" -lt 1200 ]; do harness_dl_w=$(sleep 0.5) || :; harness_dl_i=$((harness_dl_i + 1)); done',
      '  fi',
      `  if kill -0 "$harness_dl_pid" 2>/dev/null; then printf '\\n%s\\n' ${shellSingleQuote(`${label} is still downloading. Try again in a minute.`)}; exit 1; fi`,
      '  hash -r 2>/dev/null || true',
      '}',
    ] : []),
    'harness_quiet=0',
    ...(friendly ? [
      'harness_install_log="$HOME/.harness/logs/install-' + friendly.engine.replace(/[^a-z0-9-]/g, '') + '.log"',
      // Beside the log rather than in a temporary folder: nothing machine-specific in the script.
      'harness_install_rc="$HOME/.harness/logs/install-' + friendly.engine.replace(/[^a-z0-9-]/g, '') + '-$$.rc"',
      `[ -x ${shellSingleQuote(runtimeNode)} ] && mkdir -p "$HOME/.harness/logs" 2>/dev/null && harness_quiet=1`,
    ] : []),
    ...(downloadEngine ? [`harness_find_engine "$1" || harness_wait_download ${shellSingleQuote(downloadEngine.replace(/[^a-z0-9-]/g, ''))}`] : []),
    'if ! harness_find_engine "$1"; then',
    ...(recipe.executable.npmGlobal ? [
      '  if ! command -v npm >/dev/null 2>&1; then',
      `    printf '%s\\n' 'harness: npm is unavailable and the managed Node.js/npm runtime could not be used.'`,
      '    exit 1',
      '  fi',
    ] : []),
    `  [ "$harness_quiet" -eq 1 ] || printf '%s\\n' 'harness: engine is missing — installing it in this terminal' 'harness: $ ${install.replace(/'/g, "'\\''")}' ''`,
    ...(recipe.executable.npmGlobal ? [`  [ "$harness_quiet" -eq 1 ] || printf '%s\\n' ${shellSingleQuote(`harness: installing for this user in ${npmEnginePrefix()}`)}`] : []),
    'fi',
    'harness_status=0',
    `[ -n "$harness_engine_bin" ] || [ "$harness_quiet" -eq 1 ] || ${installCommand} || harness_status=$?`,
    ...(friendly ? [`[ -n "$harness_engine_bin" ] || [ "$harness_quiet" -eq 0 ] || ${quiet(install)} || harness_status=$?`] : []),
    'harness_resume',
    ...fallback,
    'if [ -z "$harness_engine_bin" ]; then',
    ...(friendly ? [
      `  if [ "$harness_status" -ne 0 ] && [ "$harness_quiet" -eq 1 ]; then printf '\\n%s\\n\\n' ${shellSingleQuote(`${label} could not be installed.`)}; tail -n 12 "$harness_install_log"; printf '\\n%s\\n' "Full details: $harness_install_log"; exit 1; fi`,
    ] : []),
    `  if [ "$harness_status" -ne 0 ]; then printf '\\n%s\\n' 'harness: the install failed, so the agent was not started. The command is above; fix it and create the agent again.'; exit 1; fi`,
    '  hash -r 2>/dev/null || true',
    ...(friendly ? [
      `  if [ "$harness_quiet" -eq 1 ] && ! harness_find_engine "$1"; then printf '\\n%s\\n' ${shellSingleQuote(`${label} was installed but could not be started.`)} "Full details: $harness_install_log"; exit 1; fi`,
    ] : []),
    `  if ! harness_find_engine "$1"; then printf '\\n%s\\n' 'harness: the install completed, but its executable could not be found. Check the installer output and PATH above.'; exit 1; fi`,
    'fi',
    '',
  ].filter(Boolean).join('\n') + '\n'
}

/** An installation dependency only. Core must rebuild a launch after this exits;
 * no engine argv or first prompt is carried into the installer. */
export function buildEngineInstallationArgv(engine: AgentEngine, recipe: EngineInstallRecipe,
  environment: Record<string, string>, runtimeNode: string = managedNodePath()): string[] {
  // The installers are POSIX shell lines (`curl … | bash`, npm under a POSIX prelude): there is nothing to run them in.
  if (process.platform === 'win32') throw new Error(`The POSIX installer of ${engine} does not run on Windows (engines/kit/windowsInstall.ts does).`)
  const shell = interactiveEngineShell(environment.SHELL) ?? { path: posixRunner(), args: ['-c'], label: 'shell' }
  if (Object.keys(environment).some(key => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))) throw new Error('Invalid installation environment name')
  const locations = Object.entries(environment).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}\n`).join('')
  // A detached dependency has no foreground terminal job. Keep descendants in
  // its one process group so a deadline also ends stopped installer children.
  const body = RAISE_OPEN_FILES_SH + clearEnvPrelude(LAUNCH_LOCATION_VARIABLES.filter(key => !(key in environment))) + locations + 'set +m 2>/dev/null || :\n' + STOP_PROOF_FUNCTIONS
    + installIfMissingScript(recipe, runtimeNode, undefined, environment.HOME, engine) + 'exit 0\n'
  return engineShellArgv(shell, [body, 'harness-native-install', engineBin(engine)])
}

function availabilityScript(recipe: EngineInstallRecipe | undefined): string {
  const names = recipe?.executable.names.map(shellSingleQuote).join(' ') ?? ''
  const paths = recipe ? engineInstallPaths(recipe).map(shellSingleQuote).join(' ') : ''
  const candidates = [names, paths].filter(Boolean).join(' ')
  return [
    ...(recipe ? [npmRuntimePrelude(recipe, managedNodePath())] : []),
    `for candidate in "$@" ${candidates}; do`,
    '  case "$candidate" in',
    '    */*) resolved="$candidate" ;;',
    '    *) resolved="$(command -v "$candidate" 2>/dev/null)" || true ;;',
    '  esac',
    '  if [ -n "$resolved" ] && [ -f "$resolved" ] && [ -x "$resolved" ]; then exit 0; fi',
    'done',
    ...(recipe?.executable.npmGlobal ? [
      'npm_prefix="$(npm prefix -g 2>/dev/null)" || true',
      'if [ -n "$npm_prefix" ]; then',
      `  for bin in ${names}; do [ -f "$npm_prefix/bin/$bin" ] && [ -x "$npm_prefix/bin/$bin" ] && exit 0; done`,
      'fi',
    ] : []),
    // An ordinary shell/profile failure may also exit 1. Only this value proves the probe ran to completion and found nothing.
    'exit 42',
  ].join('\n')
}

export type CommandAvailability = { status: 'available' | 'missing' | 'unverified'; detail?: string }
/**
 * Does the same interactive shell that launches a new agent resolve this CLI?
 *
 * The fallback is intentionally the daemon PATH: without a usable absolute
 * SHELL there is no safer context to consult and direct launch is used too.
 */
export function commandAvailableInInteractiveShell(command: string, shell: string | undefined, recipe: EngineInstallRecipe | undefined, detailed: true): Promise<CommandAvailability>
export function commandAvailableInInteractiveShell(command: string, shell?: string, recipe?: EngineInstallRecipe): Promise<boolean>
export async function commandAvailableInInteractiveShell(
  command: string,
  shell: string | undefined = undefined,
  recipe: EngineInstallRecipe | undefined = undefined,
  detailed = false,
): Promise<boolean | CommandAvailability> {
  const interactive = interactiveEngineShell(shell)
  if (!interactive) {
    const found = binaryOnPath(command) || (recipe ? engineInstallPaths(recipe).some((candidate) => binaryOnPath(candidate)) : false)
    return detailed ? { status: found ? 'available' : 'missing' } : found
  }
  const [file, ...args] = engineShellArgv(interactive, [availabilityScript(recipe), 'harness-engine-probe', command])
  const result = await new Promise<CommandAvailability>((resolve) => {
    execFile(
      file,
      args,
      { timeout: 5_000 },
      (error) => {
        if (!error) return resolve({ status: 'available' })
        if (Number(error.code) === 42) return resolve({ status: 'missing' })
        if (error.killed) return resolve({ status: 'unverified', detail: 'Interactive shell tool probe timed out after 5 seconds.' })
        resolve({ status: 'unverified', detail: `Interactive shell tool probe failed (${String(error.code ?? error.signal ?? 'unknown error')}).` })
      },
    )
  })
  return detailed ? result : result.status === 'available'
}

export type CommandFlagSupport = 'supported' | 'unsupported' | 'unknown'

/**
 * The probe's one "help ran, the flag is not in it" exit. Not 1: that is what a shell exits with
 * for its own failures (the zsh `status` bug was one), and each of them would be a false refusal.
 * Shells fail with 1, 2, 126, 127 or 128+n, never this.
 */
const FLAG_UNSUPPORTED_EXIT = 64

/**
 * The pairs this probe has seen the engine SUPPORT, each with the engine file it saw (`engineFileStamp`).
 *
 * Every relaunch asks, and a post-reboot restore asks once per agent, so the working case — which
 * is nearly every case — is worth answering from memory instead of spawning `--help` again.
 *
 * Only `supported` is kept, deliberately. The remedy for the other two answers is to change the
 * engine on disk: openharness#285 was closed by its reporter upgrading opencode until it had
 * `--auto`. A cached `unsupported` would go on refusing that upgraded engine until the daemon
 * happened to restart, which is the one outcome worth more than the spawn it saves. `unknown` is
 * not kept for the same reason at shorter range: one slow `--help` would turn Auto off machine-wide.
 *
 * ⚠️ And a kept `supported` is only good for the file it was read from. An update can drop a flag as
 * well as add one, and remembered by name alone the answer outlived it: measured end to end
 * (`e2e/updates.e2e.ts`), an engine updated to a build without its permission flag was still
 * launched with it, and refused it at once — the row went ready, then stopped, with no reason given —
 * where a daemon restarted after the update refused the create and said why.
 */
const flagSupportCache = new Map<string, string>()

/**
 * Which file a command name runs, as a stamp that changes when an update replaces or rewrites it:
 * its real path (a Homebrew or native install points at a new version's folder), inode, size and
 * modification time. Resolved on the login shell's PATH, the one a launch resolves it on, then the
 * daemon's own. '' when neither finds it — remembered by name alone then, as before.
 */
function engineFileStamp(command: string): string {
  const path = resolveBinaryOnPath(command, { PATH: loginShellEnvironment().PATH })
    ?? resolveBinaryOnPath(command)
  if (!path) return ''
  try {
    const stat = statSync(path, { bigint: true })
    return [realpathSync(path), stat.ino, stat.size, stat.mtimeNs].join('\u0000')
  } catch {
    return ''
  }
}

/** Test seam, and for a machine where the engine was just upgraded. */
export function resetCommandFlagSupportCache(): void { flagSupportCache.clear() }

/**
 * Checks a CLI's own help from the same interactive shell that would launch
 * it. `unknown` is deliberately non-blocking: a broken or unusually slow help
 * command must not turn an otherwise usable engine into a false refusal.
 */
export async function commandSupportsFlagInInteractiveShell(
  command: string,
  flag: string,
  shell: string | undefined = undefined,
): Promise<CommandFlagSupport> {
  const key = `${command}\u0000${flag}\u0000${shell ?? ''}`
  const stamp = engineFileStamp(command)
  if (flagSupportCache.get(key) === stamp) return 'supported'
  const interactive = interactiveEngineShell(shell)
  if (!interactive) return 'unknown'
  // `harness_help_status`, not `status`: in zsh `status` is a read-only special parameter (an alias
  // of `$?`), so `status=$?` is a fatal error there and the shell dies with exit 1 — which this
  // function would read as `unsupported` and refuse an engine that does support the flag. macOS
  // defaults $SHELL to zsh, so the bare name made every Auto-approval probe on a Mac a false
  // refusal. Same reason `engineFallbackPrelude` namespaces its own `harness_status`.
  const script = [
    'help="$("$1" --help 2>&1)"',
    'harness_help_status=$?',
    '[ "$harness_help_status" -eq 0 ] || exit 2',
    // The flag, not a longer one that starts with it. A plain `*"$2"*` reads `--auto-update` in
    // opencode's help as support for `--auto` — and then launches the very pane openharness#285
    // reported, full of help text. So: followed by something that cannot continue a flag, or
    // ending the help. `[!…]` is POSIX and behaves the same in sh, bash and zsh (measured).
    `case "$help" in *"$2"[!A-Za-z0-9-]*|*"$2") exit 0 ;; *) exit ${FLAG_UNSUPPORTED_EXIT} ;; esac`,
  ].join('\n')
  const [file, ...args] = engineShellArgv(interactive, [script, 'harness-engine-capability', command, flag])
  return await new Promise((resolve) => {
    execFile(
      file,
      args,
      { timeout: 5_000 },
      (error) => {
        const answer: CommandFlagSupport = !error
          ? 'supported'
          : Number((error as { code?: number | string }).code) === FLAG_UNSUPPORTED_EXIT ? 'unsupported' : 'unknown'
        if (answer === 'supported') flagSupportCache.set(key, stamp)
        resolve(answer)
      },
    )
  })
}

/** What a launch would add for its permission mode, and whether the engine on disk knows it. */
export interface PermissionLaunchChoice {
  permissionMode?: string | null
  bypassPermission?: boolean
}

/**
 * The flag whose support decides whether this launch can keep its permission mode, or null when the
 * launch adds none — an `ask` mode, an engine with no entry in the tables, a terminal.
 *
 * Only the flag TOKEN, never its value. `permissionModeFlags('claude', 'auto')` is a pair,
 * `['--permission-mode', 'auto']`, and so is codex's `readOnly`; no `--help` prints a pair
 * literally, so a build that lists `--permission-mode` but no longer accepts `auto` is not caught
 * here. The single-token modes — `opencode --auto`, `cursor --force`, `codex --approve-for-me` —
 * are answered exactly, and the first of those is what openharness#285 was about.
 */
export function permissionFlagToVerify(engine: AgentEngine, choice: PermissionLaunchChoice): string | null {
  const flags = choice.permissionMode
    ? permissionModeFlags(engine, choice.permissionMode)
    : choice.bypassPermission ? BYPASS_PERMISSION_FLAGS[engine] : null
  return flags?.find((token) => token.startsWith('--')) ?? null
}

/**
 * Ask the engine on disk whether it knows the flag this launch would pass it.
 *
 * `null` means "launch as asked": either nothing is being added, or the engine takes it, or the
 * probe could not tell (`unknown` never refuses — see `commandSupportsFlagInInteractiveShell`).
 *
 * Best-effort by construction, and that is the right way round. The probe needs an interactive
 * shell to resolve the engine the way a launch will, so a machine that offers none answers
 * `unknown` and nothing is refused. A daemon started by systemd or in a container has no `SHELL`
 * in its environment — measured on a Linux container here — but `currentUserShell` falls back to
 * the passwd entry, which on a normal account is a real shell, so the check does reach the boxes
 * openharness#285 came from.
 */
async function unsupportedPermissionFlag(
  engine: AgentEngine,
  choice: PermissionLaunchChoice,
  shell: string | undefined,
): Promise<string | null> {
  const flag = permissionFlagToVerify(engine, choice)
  if (!flag) return null
  const support = await commandSupportsFlagInInteractiveShell(engineBin(engine), flag, shell)
  return support === 'unsupported' ? flag : null
}

/**
 * The first flag of a launch model (lib/launchModel.ts) that the engine on disk does not list in its `--help`, or null.
 * It reads the help the way the permission gate does, through the same probe and cache, so a Claude Code too old for
 * `--model` or `--effort` is refused before a pane exists instead of printing its help in one. `unknown` never refuses.
 */
export async function unsupportedLaunchModelFlag(engine: AgentEngine, launchModel: LaunchModel, shell: string | undefined = undefined): Promise<string | null> {
  for (const flag of launchModelArgs(engine, launchModel).filter((arg) => arg.startsWith('--'))) {
    if (await commandSupportsFlagInInteractiveShell(engineBin(engine), flag, shell) === 'unsupported') return flag
  }
  return null
}

/** The line that updates [engine]: its install line, which fetches the latest. Those are POSIX shell lines, so on
 *  Windows only an npm one, which PowerShell runs as written, is named. */
export function engineUpdateCommand(engine: AgentEngine, platform: NodeJS.Platform = process.platform): string | null {
  const command = engineInstallRecipe(engine)?.command
  return command && (platform !== 'win32' || command.startsWith('npm ')) ? command : null
}

/**
 * For a launch somebody is waiting on — create, fork. Refusing is kinder than opening a pane that
 * the engine will fill with its own help text and leave: the person is here, and Ask works today.
 *
 * The wire code is `CODEX_CLI_TOO_OLD` for every engine. The name is historical — this began as a
 * codex-only check — and it stays because clients key on it: a code missing from the desktop's
 * `refusedBeforeLaunch` set is not merely unlabelled there, it leaves the New Harness dialog saying
 * the machine "has not confirmed the new harness yet". The daemon self-updates and the app does
 * not, so the detail below is what an older app shows, and it names the engine itself.
 */
export async function refusePermissionFlagIfUnsupported(
  engine: AgentEngine,
  choice: PermissionLaunchChoice,
  shell: string | undefined = undefined,
  native?: NativeLaunch,
): Promise<{ error: string; detail: string; unavailable?: string } | null> {
  if (native) {
    const support = await native.permission(choice)
    if (support === 'unknown') return { error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting to confirm the selected executable’s permission flags.' }
    if (support === 'supported') return null
  }
  const flag = native ? permissionFlagToVerify(engine, choice) : await unsupportedPermissionFlag(engine, choice, shell)
  if (!flag) return null
  const update = engineUpdateCommand(engine)
  return {
    error: 'CODEX_CLI_TOO_OLD',
    detail: `The ${engine} CLI on this machine does not support ${flag}, which Harness uses for this permission mode. `
      // How to update, not only that it is needed (codex_cli_too_old, 2–4 a day).
      + `Update ${engine}${update ? ` by running ${update}, then try again` : ' and try again'}`
      + `${choice.permissionMode === 'ask' ? '.' : ', or choose Ask permissions for this harness.'}`,
  }
}

/**
 * For a launch nobody is waiting on — restore after a reboot, resume, restart, retarget. Here a
 * refusal costs the whole harness, pane and scrollback included, to save a permission mode; so the
 * flag is dropped and the launch goes ahead in Ask. The caller records that on the row, because a
 * row that goes on claiming Auto while running without it is the more expensive lie.
 */
export async function dropPermissionFlagIfUnsupported<T extends PermissionLaunchChoice>(
  engine: AgentEngine,
  choice: T,
  shell: string | undefined = undefined,
  native?: NativeLaunch,
): Promise<{ choice: T; droppedFlag: string | null; nativeHold?: string }> {
  const support = native ? await native.permission(choice) : null
  if (support === 'unknown') return { choice, droppedFlag: null, nativeHold: 'Waiting to confirm the selected executable’s permission flags.' }
  const droppedFlag = support === 'supported' ? null : native ? permissionFlagToVerify(engine, choice) : await unsupportedPermissionFlag(engine, choice, shell)
  if (!droppedFlag) return { choice, droppedFlag: null }
  if (choice.permissionMode && KEPT_PERMISSION_MODES.has(choice.permissionMode)) {
    const update = engineUpdateCommand(engine)
    return { choice, droppedFlag: null, nativeHold: `The ${engine} CLI on this machine does not support ${droppedFlag}, which this harness's `
      + `permission mode needs. It stays stopped until ${engine} is updated${update ? ` (${update})` : ''}.` }
  }
  // Ask in its place, launched with no flag at all: Claude Code's Ask names its mode with the very flag a build
  // this old may lack, so it goes as the engine's own default, which asked before auto mode existed.
  return { choice: { ...choice, permissionMode: permissionModeFlags(engine, 'ask')?.length ? null : 'ask', bypassPermission: false }, droppedFlag }
}