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.

Core boundary, part 5: the new-pane watcher, adoption, create and fork become modules (#725)

Dee4b903923bba9
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 8c8babbe3..9c2734d75 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -192,6 +192,10 @@ import { createBinding } from './core/agents/bind.js'
import { createDiscoveryHandlers } from './core/agents/discovery.js'
import { createLaunchHelpers } from './core/agents/launch.js'
import { createCancel } from './core/turns/cancel.js'
+import { createPaneWatcher } from './core/agents/newPane.js'
+import { createAdoption } from './core/agents/adopt.js'
+import { createAgentCreator } from './core/agents/create.js'
+import { createAgentForker } from './core/agents/fork.js'
import { describeMasterStatus, readStatusFile, runMaster } from './harnessd/master.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from './harnessd/protocol.js'
import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'
@@ -384,10 +388,6 @@ const PROXY_BACKEND_TIMEOUT_MS = 20_000
* stalled control-plane connection cannot hold it open. */
const GRID_MINT_TIMEOUT_MS = 10_000
-/** How long creating a Model Manager waits for grid to be set up before its workspace asks grid which
- * grid is this account's. Short: the app gives the whole create 20s, and a first install takes minutes.
- * Past it the set-up carries on, and the agent's own `harness grid setup` waits for it. */
-const MODEL_MANAGER_GRID_WAIT_MS = 8_000
function usage(exitCode = 0): never {
@@ -1579,14 +1579,6 @@ async function restartDaemonForIdentity(): Promise<void> {
await launch(false) // prints the status block and exits
}
-/** The pane's session environment: the grid's or the profile's, with the DSH's layered on top. */
-function mergedLaunchEnv(
- base: Record<string, string> | undefined,
- dsh: Record<string, string> | undefined,
-): Record<string, string> | undefined {
- if (!base && !dsh) return undefined
- return { ...(base ?? {}), ...(dsh ?? {}) }
-}
/** Set by runForeground once the DSH companions exist; a frame projected before that carries none. */
let activityFrameContextRef: ((s: RegisteredSession) => ActivityFrame | null) | null = null
@@ -3828,536 +3820,60 @@ async function runForeground(session: AuthSession | null): Promise<void> {
* pass can miss it — retry `triggerHint` a few times with backoff before giving up.
*/
- /**
- * Watch a pane this daemon just opened until its engine process shows up (ready), dies (failed), or
- * ten minutes pass. Shared by create and fork: the two open panes the same way and wait the same way.
- */
- const watchNewPane = async (engine: AgentEngine, pending: RegisteredSession, spawned: { runtime: TmuxRuntimeRef }, command: string[], installIfMissing: ReturnType<typeof engineInstallRecipe> | undefined, budgetMs = 10 * 60_000): Promise<void> => {
- const startedAt = Date.now()
- let delayMs = 50
- try {
- while (Date.now() - startedAt < budgetMs) {
- if (!registry.byAgent(pending.agentId)) return
- const processIdentity = await resolvePaneEngineProcess(spawned.runtime.paneId, engine)
- if (processIdentity) {
- registry.updateProcessIdentity(pending.agentId, processIdentity)
- const ready = registry.setLaunch(pending.agentId, { state: 'ready' })
- await clearPaneRemainOnExit(spawned.runtime.paneId)
- if (ready) announceSession(ready)
- void agentReconciler.triggerHint(spawned.runtime, engine).catch((error) => {
- console.warn(`[agent] background bind failed · ${engine} · ${error instanceof Error ? error.message : error}`)
- })
- console.log(`[agent] create ready · ${engine} · agent ${pending.agentId} · ${Date.now() - startedAt}ms`)
- return
- }
- const paneState = await tmuxPaneState(spawned.runtime.paneId)
- if (!paneState) {
- registry.setTerminalAvailable(pending.agentId, false)
- announceSession(pending)
- return
- }
- if (paneState.dead) {
- const installed = await commandAvailableInInteractiveShell(command[0], undefined, installIfMissing)
- const error = installed ? 'ENGINE_DID_NOT_START' : 'ENGINE_NOT_INSTALLED'
- const detail = installed
- ? `${engine} exited before its engine process became ready. See the terminal output for details.`
- : `${engine} is not installed, or its automatic install failed. See the terminal output for details.`
- const failed = registry.setLaunch(pending.agentId, { state: 'failed', error, detail })
- if (failed) announceSession(failed)
- console.warn(`[agent] create failed · ${engine} · ${detail}`)
- return
- }
- // The engine started and was gone again before it was ever seen (a flag it refused, a
- // config it could not read): its wrapper has handed the pane to a shell with the engine's
- // own words on screen. That pane is a terminal, and the row says so — the person reads
- // the error where it was printed and types the command again, rather than being handed a
- // "Start failed" tile they cannot type into.
- if (paneState.engineExit !== null) {
- // Say what happened before the evidence goes. The pane is about to become an ordinary
- // terminal and `releaseEngine` rewrites the launch to `ready`, so after this point nothing
- // anywhere — frame, registry, archive — records that an engine was ever meant to be here
- // or why it left. openharness#285 was exactly this: opencode printed its help over a flag
- // it did not know, and the only trace was one line saying the pane had become a terminal.
- // `describeAgentCreateFailure` was written for this and had no caller.
- // `dead: true` describes the ENGINE, which is what the diagnosis is about, not the pane —
- // the pane is alive and about to become a terminal. That is the sentence this state
- // selects ("started and exited with status N"), and it is the true one here.
- const captured = await captureTerminal(pending.agentId, 40)
- console.warn(`[agent] create · ${engine} · agent ${sid(pending.agentId)} · `
- + describeAgentCreateFailure({
- state: { dead: true, exitStatus: paneState.engineExit, command: engine },
- output: summarizePaneOutput(captured ?? ''),
- engineBin: command[0],
- shellName: null,
- processes: [],
- elapsedMs: Date.now() - startedAt,
- }))
- await clearPaneRemainOnExit(spawned.runtime.paneId)
- // A hook may have bound a conversation while this watcher was awaiting its probe.
- // Archive the current row, not the pre-hook pending snapshot.
- const row = registry.byAgent(pending.agentId)
- if (row?.sessionId) retainExitedSession(row, true)
- else {
- const released = registry.releaseEngine(pending.agentId)
- if (released) announceSession(released)
- }
- console.warn(`[agent] create · ${engine} exited (${paneState.engineExit}) before ready · agent ${pending.agentId} kept as a terminal`)
- return
- }
- await new Promise<void>((resolve) => {
- const timer = setTimeout(resolve, delayMs)
- timer.unref?.()
- })
- delayMs = Math.min(delayMs * 2, 750)
- }
- const detail = `${engine} did not expose an engine process within ${Math.round(budgetMs / 60_000)} minutes. The terminal remains available.`
- const failed = registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT', detail })
- if (failed) announceSession(failed)
- console.warn(`[agent] create timed out · ${engine} · agent ${pending.agentId}`)
- } catch (error) {
- console.warn(`[agent] create watch failed · ${engine} · ${error instanceof Error ? error.message : error}`)
- }
- }
-
- /**
- * Whether a conversation Harness did not start can be opened here as a harness: one discovery found
- * (looked for again if it is new), on this engine, not already a harness, and not open in a running
- * process — a terminal or the engine's app that still has it would write it too.
- *
- * One open in a terminal can be taken over ([takeOver]): the terminal's process is stopped and the
- * conversation resumes here. Asked without it, the refusal says whether that process is mid-turn,
- * so the person can choose to wait for the turn to end or stop it now. An app's is never stopped.
- */
- const adoptableSession = async (sessionId: string, engine: AgentEngine, takeOver: 'idle' | 'now' | 'wait' | null): Promise<{ ok: true; cwd: string; title: string; owner: SessionOwner | null; busy: boolean; launchArgs: readonly string[] } | { ok: false; error: string; detail: string }> => {
- const held = (id: string) => !!registry.bySession(id) || stoppedAgents.list().some((s) => s.sessionId === id)
- if (held(sessionId)) {
- return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }
- }
- const found = externalSessions.get(sessionId) ?? (await externalSessions.scan(), externalSessions.get(sessionId))
- if (found && [found.sessionId, ...found.aliases ?? []].some(held)) {
- return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }
- }
- if (!found) return { ok: false, error: 'SESSION_NOT_FOUND', detail: 'This conversation is no longer on this machine.' }
- if (found.engine !== engine) return { ok: false, error: 'INVALID_ENGINE', detail: `This is a ${found.engine} conversation.` }
- // The Codex app keeps a thread in a folder of its own, which people tidy away. Checked before
- // anything is stopped: a take-over that then cannot open would only have closed it.
- if (!existsSync(found.cwd)) {
- return { ok: false, error: 'SESSION_FOLDER_GONE', detail: `The folder it ran in is gone: ${found.cwd}` }
- }
- const title = found.title || sessionSearch?.session(sessionId)?.title || ''
- const launchArgs = found.launchArgs ?? []
- const owner = await openSessions.owner(sessionId)
- if (!owner) return { ok: true, cwd: found.cwd, title, owner: null, busy: false, launchArgs }
- const engineName = engineLabel(engine)
- // A process in one of Harness's own panes is an agent the daemon is still binding: never stopped.
- if (owner.harness) return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }
- // Started on it, as its arguments say, and perhaps moved on since — or in a pane nobody could check
- // was not Harness's own: not opened twice, never stopped.
- if (owner.fromArgs || owner.unverified) {
- return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It may be open in ${engineName} in a terminal. Close it there, then open it here.` }
- }
- if (!owner.tty) {
- return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It is open in ${engineName}'s app or an editor. Close it there, then open it here.` }
- }
- const busy = await openSessions.busy(owner)
- if (busy && (takeOver === null || takeOver === 'idle')) {
- return { ok: false, error: 'SESSION_BUSY_IN_TERMINAL', detail: `${engineName} is working on it in a terminal.` }
- }
- if (takeOver === null) {
- return { ok: false, error: 'SESSION_OPEN_IN_TERMINAL', detail: `It is open in ${engineName} in a terminal. Moving it here quits it there.` }
- }
- return { ok: true, cwd: found.cwd, title, owner, busy, launchArgs }
- }
-
- /**
- * A conversation taken over when its turn ends (`takeOver: 'wait'`): its pane waits for the
- * terminal's process to go (engineLaunch `waitForPid`), and this stops that process once the turn
- * is over. It gives up when the harness does — closed, or Ctrl-C in its pane — and when the person
- * quits it in the terminal themselves, which is the pane's cue as well.
- */
- const takeOverWhenIdle = async (agentId: string, owner: SessionOwner, sessionId: string): Promise<void> => {
- for (;;) {
- await new Promise<void>((resolve) => { const timer = setTimeout(resolve, 1_000); timer.unref?.() })
- if (registry.byAgent(agentId)?.launch?.state !== 'starting' || !processAlive(owner.pid)) return
- // Moved on in that terminal (`/resume`, `/new`): its turn is another conversation's now, and it
- // is left alone. The pane still waits for it to quit, and then opens this one.
- if (await heldBy(sessionId, owner) !== 'same') {
- console.log(`[agent] take over ${sid(sessionId)} · pid ${owner.pid} moved on · left running`)
- return
- }
- if (await openSessions.busy(owner)) continue
- const stopped = await stopSessionOwner(owner)
- console.log(`[agent] take over ${sid(sessionId)} · turn ended · pid ${owner.pid} ${stopped ? 'stopped' : 'did not stop'}`)
- return
- }
- }
-
- /**
- * Who holds [sessionId] now, against the [owner] seen when the person chose: `same` (that process,
- * still a terminal's, by hard evidence, not one of Harness's own), `free` (nobody), or `other`.
- * Asked again right before anything is stopped: the terminal may have moved to other work since.
- */
- const heldBy = async (sessionId: string, owner: SessionOwner): Promise<'same' | 'free' | 'other'> => {
- const now = await openSessions.owner(sessionId)
- if (!now) return 'free'
- return now.pid === owner.pid && !!now.tty && !now.fromArgs && !now.harness && !now.unverified ? 'same' : 'other'
- }
+ // Watching a pane create or fork just opened until its engine is up, or why not (core/agents/newPane.ts).
+ const watchNewPane = createPaneWatcher({
+ registry,
+ announceSession,
+ triggerHint: (runtime, engine) => agentReconciler.triggerHint(runtime, engine),
+ captureTerminal,
+ retainExitedSession,
+ })
- backend.onCreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId, takeOver }) => {
- if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
- // A conversation Harness did not start opens in its own folder, under its own title — taken over
- // from the terminal that has it, when asked to.
- let owner: SessionOwner | null = null
- let ownerBusy = false
- let resumeArgs: readonly string[] = []
- if (resumeSessionId) {
- const adopted = await adoptableSession(resumeSessionId, engine, takeOver ?? null)
- if (!adopted.ok) return adopted
- cwd = adopted.cwd
- name = name ?? (adopted.title || null)
- owner = adopted.owner
- ownerBusy = adopted.busy
- resumeArgs = adopted.launchArgs
- }
- if (backend.purgeAgentService?.blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }
- try {
- if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
- } catch {
- return { ok: false, error: 'CWD_NOT_FOUND' }
- }
- // A harness can pin its permission mode (`dshPinnedPermissionMode`): the Grid harness starts model
- // servers, which Codex's sandbox would start without a GPU. Pinned before anything reads the mode,
- // and recorded on the row like a chosen one, so a relaunch keeps it.
- const pinnedDsh = dsh ? installedDsh(dsh) : null
- const pinnedMode = pinnedDsh ? dshPinnedPermissionMode(pinnedDsh.manifest) : null
- if (pinnedMode && permissionModeFlags(engine, pinnedMode)) {
- permissionMode = pinnedMode
- bypassPermission = permissionModeApproves(pinnedMode)
- }
- // An engine too old for the flag this permission mode launches it with prints its help and
- // exits; the wrapper then hands the pane to a shell, and what the person gets is a terminal
- // full of help text with nothing anywhere saying why (openharness#285, opencode without
- // `--auto`). Refuse before opening a pane — this is a launch somebody is waiting on, and Ask
- // works today. Codex has been checked this way since it gained `--approve-for-me`; every other
- // engine with a permission flag was not, and carried the same failure.
- const refusal = await refusePermissionFlagIfUnsupported(engine, { permissionMode, bypassPermission })
- if (refusal) {
- console.warn(`[agent] create refused · ${engine} · ${refusal.detail}`)
- return { ok: false, ...refusal }
- }
- // Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
- // retaining the engine and a collision-resistant creation suffix for diagnostics. Computed
- // before the grid block because a file-configured engine keys its config directory on it.
- // The `harness-` prefix is also discovery's whitelist (see `isHarnessSession` /
- // `TmuxBackend.inventory()`) — every pane outside it is invisible to the daemon.
- const label = buildHarnessSessionLabel(engine)
- // Prepare the harness workspace, then bind its session context to the selected engine.
- // Missing packages or invalid runtimes refuse the launch before the agent is started.
- let dshEnv: Record<string, string> | undefined
- let dshArgs: string[] = []
- /** A DSH's own name ("Blender"), which the agent is named after instead of its engine. */
- let dshLabel: string | undefined
- /** What the harness is told about the signed-in account (its private grid), not left to guess. */
- let dshAccount: DshAccount = {}
- if (dsh) {
- const installed = installedDsh(dsh)
- if (!installed) return { ok: false, error: 'INVALID_DSH', detail: `${dsh} is not installed on this machine` }
- if (installed.manifest.kind === 'viewer') return { ok: false, error: 'INVALID_DSH', detail: `${dsh} is a viewer package, not an agent` }
- const refusal = incompatibleHarnessEngine(dsh, installed.manifest, engine)
- if (refusal) {
- return { ok: false, error: 'INVALID_DSH', detail: refusal }
- }
- if (!(await tmuxSupportsSessionEnv())) {
- const detail = `this machine's tmux is older than ${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, `
- + `which is the first version that can give a new session its own environment — so ${installed.manifest.name} `
- + `could not tell ${engine} which harness it is. Upgrade tmux.`
- console.warn(`[agent] create ${dsh} refused · ${detail}`)
- return { ok: false, error: 'TMUX_TOO_OLD_FOR_DSH', detail }
- }
- // The Model Manager is grid in use, however it was made (the Store, New Harness, `harness new`, the
- // models picker): grid is set up before the workspace asks it which grid is this account's.
- const ensureGrid = backend.ensureGrid
- if (installed.id === MODEL_MANAGER_ID && ensureGrid) {
- const setUp = await setUpWithin(() => ensureGrid({ ownGrid: true }), MODEL_MANAGER_GRID_WAIT_MS)
- if (setUp === 'pending') console.log(`[dsh] ${dsh} · grid is still being set up; the agent waits for it with \`harness grid setup\``)
- }
- try {
- dshAccount = { privateGrid: await backend.privateGridName().catch(() => null) }
- // Asked BEFORE the template goes in: afterwards every folder has content.
- // Not there yet is empty; unreadable is not — trust is only ever granted on evidence.
- const emptyBefore = await readdir(cwd).then((names) => names.length === 0,
- (error: NodeJS.ErrnoException) => error.code === 'ENOENT')
- const materialized = await materializeWorkspace(installed, cwd, dshAccount, engine)
- for (const warning of materialized.warnings) console.warn(`[dsh] ${dsh} materialize · ${warning}`)
- console.log(`[dsh] ${dsh} materialized ${cwd} · created ${materialized.created.length} · kept ${materialized.kept.length}`)
- // The template just went into an EMPTY folder: everything in it is the harness's, and Claude Code
- // need not ask. Laid into a folder that already held something — a clone, the person's own repo —
- // it proves nothing about the rest, so trust stays the person's call (lib/claudeTrust.ts).
- if (emptyBefore && materialized.created.some((item) => item.startsWith('template'))) {
- try {
- if (engine === 'claude') preTrustClaudeProject(cwd)
- if (engine === 'codex') preTrustCodexProject(cwd)
- } catch (error) { console.warn(`[dsh] pre-trust ${cwd} · ${error instanceof Error ? error.message : error}`) }
- }
- } catch (error) {
- const detail = `could not prepare the workspace for ${dsh} · ${error instanceof Error ? error.message : error}`
- console.warn(`[agent] create ${dsh} refused · ${detail}`)
- return { ok: false, error: 'DSH_MATERIALIZE_FAILED', detail }
- }
- const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label, dshAccount, null))
- if (!prepared.ok) return prepared
- dshEnv = prepared.launch.env
- dshArgs = prepared.launch.args
- dshLabel = installed.manifest.name
- }
- // A grid is the user's answer to "where should this run", so every way of not honouring it is a
- // refusal rather than a fallback — an agent silently started on the engine's own login spends the
- // wrong account and looks identical to one that worked.
- let gridLaunch: { env: Record<string, string>; args: string[]; webSearch: GridWebSearchStatus } | undefined
- if (grid) {
- const built = buildGridEngineLaunch(engine, grid, gridLaunchMachine())
- if (!built.ok) {
- console.warn(`[agent] create ${engine} refused · ${built.detail}`)
- return { ok: false, error: built.error, detail: built.detail }
- }
- if (!(await tmuxSupportsSessionEnv())) {
- const detail = `this machine's tmux is older than `
- + `${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, which is the first version that can `
- + `give a new session its own environment — so ${engine} could not have been pointed at grid `
- + `${grid.networkName}. Upgrade tmux, or create this agent without a grid selected.`
- console.warn(`[agent] create ${engine} refused · ${detail}`)
- return { ok: false, error: 'TMUX_TOO_OLD_FOR_GRID', detail }
- }
- gridLaunch = { env: { ...built.launch.env }, args: built.launch.args, webSearch: built.launch.webSearch }
- // An engine whose provider lives in a file gets a directory this daemon owns, never the
- // user's own dotfiles. The label is unique per creation, so two agents never share one.
- if (built.launch.configDir) {
- const { envVar, files, pointAt, links } = built.launch.configDir
- try {
- const dir = await writeGridConfigDir(label, files, links)
- // Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.
- gridLaunch.env[envVar] = pointAt ? join(dir, pointAt) : dir
- } catch (error) {
- const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`
- console.warn(`[agent] create ${engine} refused · ${detail}`)
- return { ok: false, error: 'GRID_CONFIG_FAILED', detail }
- }
- }
- // Named in the log because the pane itself gives nothing away: the engine looks exactly like a
- // normally launched one. The key is never printed.
- console.log(describeGridLaunch(engine, grid, built.launch.webSearch))
- }
- // A Codex agent pointed at a profile OTHER than this machine's default reads hooks.json from
- // THAT folder, not the one `harness login` already installed into — without this, such an agent
- // fires no hook at all (no SessionStart/UserPromptSubmit/Stop) and never streams a single event.
- // Idempotent, so paying this on every create against an already-set-up profile is free.
- if (codexHome && !env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, codexHome)
- // OpenCode may have upgraded from 1.x to 2.x while this daemon was running. Its new TUI must
- // not discover our old server plugin; the cached version probe changes with the executable.
- if (engine === 'opencode' && !env.DISABLE_HOOK_INSTALL) installOpencodePlugin(hookPort)
- // Do not start a second interactive login shell merely to ask whether the engine is installed.
- // The pane's own shell performs the same check before exec, and installs only when necessary.
- // This removes ~1s of shell startup from the click-to-terminal critical path.
- const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)
- // Clearing the vendor credentials this launch does NOT set is part of pointing an agent at a
- // grid, not an extra. An engine chooses its provider from whatever it can see, and an inherited
- // key wins on its own terms — OpenCode picked Anthropic over a grid it had been handed, and said
- // only `invalid x-api-key`. Nothing is cleared when no grid is in play: an agent on its own login
- // is supposed to use exactly these variables.
- const clearEnv = [...(gridLaunch ? gridConflictingEnvToClear(gridLaunch) : []), ...harnessEnvToClear(dshEnv)]
- // The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it
- // from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was
- // checked for a contract at the wire (AGENT_UNSUPPORTED, opencode v2 included), so this cannot throw.
- const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, opencodeMajorVersion()) : []), ...resumeArgs]
- // The first prompt is a launch option only — never part of `extraArgs`, which the registry row
- // carries into a relaunch (engineLaunch.ts, `firstPrompt`).
- // Stopped mid-turn, the resumed conversation is told to carry on — by an engine that can open
- // with a message; any other resumes where it stopped and waits.
- const waitFor = owner && takeOver === 'wait' && ownerBusy ? owner : null
- const firstPrompt = prompt ?? (owner && !waitFor && ownerBusy && supportsFirstPrompt(engine) ? 'continue' : null)
- const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), ...(resumeSessionId ? { resumeSessionId } : {}), ...(waitFor ? { waitForPid: { pid: waitFor.pid, name: engineLabel(engine) } } : {}), terminalHint: { machineName: terminalHintMachineName() } }
- const command = buildEngineCommandArgv(engine, launchOptions)
- const argv = buildEngineLaunchArgv(engine, launchOptions)
- // The terminal's process goes last, once nothing here can refuse or fail the launch — the command
- // is built — stopped now, or, to wait for its turn, left running for the pane to wait on.
- if (owner && !waitFor && resumeSessionId) {
- const held = await heldBy(resumeSessionId, owner)
- if (held === 'other') {
- return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: 'It moved to another process just now. Close it there, then open it here.' }
- }
- // Quit in its terminal meanwhile: it is free, and nothing is stopped.
- if (held === 'same' && !await stopSessionOwner(owner)) {
- return { ok: false, error: 'SESSION_STOP_FAILED', detail: 'The terminal that has it did not quit. Close it there, then open it here.' }
- }
- if (held === 'same') console.log(`[agent] take over ${sid(resumeSessionId)} · pid ${owner.pid} stopped${ownerBusy ? ' mid-turn' : ''}`)
- }
- // A tmux route is enough to stream its screen. Register it before looking for a process so both
- // loopback and relayed Desktop clients can attach while the login shell/installer is still busy.
- // `tmuxBackend` exists whenever the CONFIG lists tmux — it is never a probe of the binary, so a
- // daemon that cannot resolve `tmux` at all (a login context whose PATH lacks Homebrew's bin, the
- // usual shape after a reboot) is reported as `TMUX_UNAVAILABLE` too, distinctly from a tmux that
- // answered and refused (`SPAWN_FAILED`) — see createAgentPane.ts. Registration itself is retried
- // there: a stale registry entry from a previous tmux-server generation occasionally collides with
- // a freshly-minted pane id, and that collision clears on its own on the very next pane.
- prepareApiTools(cwd, engine)
- // Mutually exclusive with a grid (backendSocket.ts refuses the two together): a chosen Codex
- // profile becomes the new session's CODEX_HOME, the same `-e` mechanism a grid's own env rides.
- const result = await createAndRegisterPane({
- tmuxBackend,
- registry,
- engine,
- cwd,
- sessionLabel: label,
- argv,
- env: freshHarnessEnvironment(engine, mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv), !!grid || !!resumeSessionId,
- permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')),
- grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
- gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
- codexHome,
- dsh,
- dshRuntime: dsh ? label : null,
- agent,
- bypassPermission,
- permissionMode,
- defaultName: name,
- label: dshLabel,
- })
- if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
- const { spawned, pending } = result
- // A terminal is ready the moment its pane is: there is no engine process to wait for, and the
- // shell exiting is the person closing it — so `remain-on-exit` comes off now, and the pane going
- // away is what removes the row (reconciler `onRemoved`), exactly as for an engine that quit.
- if (isTerminalEngine(engine)) {
- await clearPaneRemainOnExit(spawned.runtime.paneId)
- const ready = registry.setLaunch(pending.agentId, { state: 'ready' }) ?? pending
- announceSession(ready)
- console.log(`[agent] create terminal open · agent ${pending.agentId}`)
- return { ok: true, session: ready }
- }
- announceSession(pending)
- if (pending.dsh) attachDsh(pending)
+ // Opening a conversation Harness did not start, and taking it over from a terminal (core/agents/adopt.ts).
+ const adoption = createAdoption({
+ bySession: (sessionId) => registry.bySession(sessionId),
+ byAgent: (agentId) => registry.byAgent(agentId),
+ stoppedAgents,
+ externalSessions,
+ openSessions,
+ search: sessionSearch,
+ })
+ const adoptableSession = adoption.adoptableSession
+ const takeOverWhenIdle = adoption.takeOverWhenIdle
+ const heldBy = adoption.heldBy
- // A pane waiting out another terminal's turn may wait as long as that turn takes.
- void watchNewPane(engine, pending, spawned, command, installIfMissing, waitFor ? 24 * 60 * 60_000 : undefined)
- if (waitFor && resumeSessionId) void takeOverWhenIdle(pending.agentId, waitFor, resumeSessionId)
- console.log(`[agent] create pane open · ${engine} · agent ${pending.agentId}`)
- return { ok: true, session: pending }
- }
+ // Creating an agent (core/agents/create.ts).
+ backend.onCreateAgent = createAgentCreator({
+ tmuxBackend,
+ registry,
+ adoptableSession,
+ heldBy,
+ takeOverWhenIdle,
+ watchNewPane,
+ announceSession,
+ attachDsh,
+ prepareApiTools,
+ hookPort,
+ hooksDisabled: env.DISABLE_HOOK_INSTALL,
+ gridLaunchMachine,
+ terminalHintMachineName,
+ blocksFolder: (cwd) => backend.purgeAgentService?.blocksFolder(cwd),
+ gridSetup: () => backend.ensureGrid,
+ privateGridName: () => backend.privateGridName(),
+ })
- /**
- * Fork an agent (`agent_fork`): open a NEW pane whose engine starts with everything the source's
- * session has — `claude --resume <id> --fork-session`, `codex fork <id>` — or, for an engine that
- * cannot fork but takes a first prompt, a handoff message composed from what this daemon remembers
- * of the source (lib/forkAgent.ts). Same folder, same harness, same permission mode, same named
- * agent; a grid agent is refused rather than half-copied. The source is not touched — it is not even
- * paused — which is why it has to be IDLE: a fork taken mid-turn is a transcript cut in half.
- */
- backend.onForkAgent = async ({ agentId, name, prompt }) => {
- if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
- const source = registry.byAgent(agentId)
- if (!source) return { ok: false, error: 'AGENT_NOT_FOUND' }
- const sourceName = projectDisplayName(source)
- if (!source.cwd) return { ok: false, error: 'CWD_NOT_FOUND', detail: `${sourceName} has no working folder on record.` }
- try {
- if (!statSync(source.cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
- } catch {
- return { ok: false, error: 'CWD_NOT_FOUND' }
- }
- if (source.gridLaunch || source.grid) {
- return { ok: false, error: 'FORK_ON_GRID_UNSUPPORTED', detail: `${sourceName} runs on a grid; forking a grid agent is not supported.` }
- }
- if (source.sessionId && mirror.isBusy(source.sessionId)) {
- return { ok: false, error: 'AGENT_BUSY', detail: `${sourceName} is in the middle of a turn. Wait for it to finish, then fork.` }
- }
- const engine = source.engine
- const memory = {
- asks: source.sessionId ? mirror.recentAsks(source.sessionId) : [],
- recaps: source.sessionId ? mirror.recent(source.sessionId, 5).map((t) => t.recap || t.text) : [],
- lastAnswer: source.sessionId ? mirror.lastFullText(source.sessionId) : undefined,
- }
- const plan = planFork({ engine, sessionId: source.sessionId, name: sourceName, cwd: source.cwd }, memory, prompt)
- if (!plan.ok) return { ok: false, error: plan.error, detail: plan.detail }
-
- const label = buildHarnessSessionLabel(engine)
- // Fork the source's saved harness context. Workspace templates and init are not run again.
- let dshEnv: Record<string, string> | undefined
- let dshArgs: string[] = []
- let dshLabel: string | undefined
- if (source.dsh) {
- const installed = installedDsh(source.dsh)
- if (!installed) return { ok: false, error: 'INVALID_DSH', detail: `${source.dsh} is no longer installed on this machine` }
- // Narrowed above; a closure would lose that, so the checked values are named here.
- const cwd = source.cwd
- const sourceKey = forkRuntimeKey({ cwd, agentId: source.agentId, dshRuntime: source.dshRuntime })
- const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label,
- { privateGrid: backend.gridName() }, sourceKey))
- if (!prepared.ok) return prepared
- dshEnv = prepared.launch.env
- dshArgs = prepared.launch.args
- dshLabel = installed.manifest.name
- }
- const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)
- // Same guard as a relaunch (`buildLaunchOverrides`): an opencode agent recorded on v1 forks on v2
- // as a general session rather than handing the v2 TUI an `--agent` it exits on.
- const forkMajor = opencodeMajorVersion()
- const extraArgs = [...dshArgs, ...(source.agent && supportsNamedAgent(engine, forkMajor) ? namedAgentArgs(engine, source.agent, forkMajor) : [])]
- const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPrompt
- const launchOptions = {
- clearEnv: harnessEnvToClear(dshEnv),
- bypassPermission: source.bypassPermission ?? false,
- ...(source.permissionMode ? { permissionMode: source.permissionMode } : {}),
- extraArgs: extraArgs.length ? extraArgs : undefined,
- installIfMissing,
- cwd: source.cwd,
- harnessNode: source.dsh ? true : undefined,
- ...(plan.level === 'native' ? { forkSessionId: plan.forkSessionId } : {}),
- ...(firstPrompt ? { firstPrompt } : {}),
- }
- // Same refusal as create: the clone inherits the source's permission mode, and an engine that
- // has since been downgraded would hand back a pane of help text instead of a harness.
- const forkRefusal = await refusePermissionFlagIfUnsupported(engine, launchOptions)
- if (forkRefusal) {
- console.warn(`[agent] fork refused · ${engine} · ${forkRefusal.detail}`)
- return { ok: false, ...forkRefusal }
- }
- prepareApiTools(source.cwd, engine)
- const command = buildEngineCommandArgv(engine, launchOptions)
- const argv = buildEngineLaunchArgv(engine, launchOptions)
- const result = await createAndRegisterPane({
- tmuxBackend,
- registry,
- engine,
- cwd: source.cwd,
- sessionLabel: label,
- argv,
- env: mergedLaunchEnv(source.codexHome ? { CODEX_HOME: source.codexHome } : undefined, dshEnv),
- grid: null,
- gridLaunchRecord: null,
- codexHome: source.codexHome ?? null,
- dshRuntime: source.dsh ? label : null,
- dsh: source.dsh ?? null,
- agent: source.agent ?? null,
- bypassPermission: source.bypassPermission ?? false,
- permissionMode: source.permissionMode ?? null,
- defaultName: name ?? forkName(sourceName),
- label: dshLabel,
- // The session being forked from, so a Change agent right after the fork reads exactly that conversation.
- forkedFrom: {
- agentId: source.agentId, name: sourceName,
- ...(source.sessionId ? { sessionId: source.sessionId, ...(source.transcriptPath ? { transcriptPath: source.transcriptPath } : {}) } : {}),
- },
- })
- if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
- const { spawned, pending } = result
- // The new tile starts with the source's last recap on it, the way a native fork's pane starts with
- // the source's transcript: memory in both places, not one. Settled when the engine names its session.
- if (source.sessionId) pendingForkInherit.set(pending.agentId, source.sessionId)
- announceSession(pending)
- if (pending.dsh) attachDsh(pending)
- void watchNewPane(engine, pending, spawned, command, installIfMissing)
- console.log(`[agent] fork pane open · ${engine} · ${plan.level} · ${source.agentId} → ${pending.agentId}`)
- return { ok: true, session: pending, level: plan.level }
- }
+ // Forking an agent (core/agents/fork.ts).
+ backend.onForkAgent = createAgentForker({
+ tmuxBackend,
+ registry,
+ mirror,
+ pendingForkInherit,
+ watchNewPane,
+ announceSession,
+ attachDsh,
+ prepareApiTools,
+ gridName: () => backend.gridName(),
+ })
/**
* The dependencies a pane-process swap needs, for both callers that do one.
diff --git a/cli/src/core/agents/adopt.spec.ts b/cli/src/core/agents/adopt.spec.ts
new file mode 100644
index 000000000..77e9a5164
--- /dev/null
+++ b/cli/src/core/agents/adopt.spec.ts
@@ -0,0 +1,151 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { processAlive, stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'
+import { createAdoption, type AdoptDeps } from './adopt.js'
+
+vi.mock('../../lib/sessionSearch/external.js', async (real) => ({
+ ...await real<object>(),
+ processAlive: vi.fn(() => true),
+ stopSessionOwner: vi.fn(async () => true),
+}))
+
+const folder = mkdtempSync(join(tmpdir(), 'core-adopt-'))
+afterAll(() => rmSync(folder, { recursive: true, force: true }))
+
+const conversation = (over: Record<string, unknown> = {}) => ({ sessionId: 'c1', engine: 'claude', cwd: folder, title: 'Fix the build', ...over })
+const owner = (over: Partial<SessionOwner> = {}): SessionOwner =>
+ ({ pid: 7, engine: 'claude', tty: '/dev/ttys001', fromArgs: false, harness: false, unverified: false, ...over }) as SessionOwner
+
+function setup(over: Partial<AdoptDeps> = {}) {
+ const found = new Map<string, ReturnType<typeof conversation>>()
+ let starting = true
+ const deps: AdoptDeps = {
+ bySession: vi.fn(() => undefined),
+ byAgent: vi.fn(() => (starting ? { launch: { state: 'starting' } } : { launch: { state: 'ready' } }) as RegisteredSession),
+ stoppedAgents: { list: vi.fn(() => []) },
+ externalSessions: { get: vi.fn((id: string) => found.get(id) as never), scan: vi.fn(async () => []) },
+ openSessions: { owner: vi.fn(async () => null), busy: vi.fn(async () => false) },
+ search: null,
+ ...over,
+ }
+ return { deps, found, adoption: createAdoption(deps), launched: () => { starting = false } }
+}
+
+describe('whether a conversation can be opened here', () => {
+ it('refuses one that is already a harness, live, stopped, or under another of its names', async () => {
+ const live = setup({ bySession: vi.fn((id: string) => id === 'c1' ? ({} as RegisteredSession) : undefined) })
+ expect(await live.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ ok: false, error: 'SESSION_IN_HARNESS' })
+ const stopped = setup({ stoppedAgents: { list: vi.fn(() => [{ sessionId: 'c1' } as RegisteredSession]) } })
+ expect(await stopped.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_IN_HARNESS' })
+ const alias = setup({ bySession: vi.fn((id: string) => id === 'old-name' ? ({} as RegisteredSession) : undefined) })
+ alias.found.set('c1', conversation({ aliases: ['old-name'] }))
+ expect(await alias.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_IN_HARNESS' })
+ })
+
+ it('looks again for one it has not seen, and refuses one that is gone, of another engine, or whose folder went', async () => {
+ const run = setup()
+ expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_NOT_FOUND' })
+ expect(run.deps.externalSessions.scan).toHaveBeenCalled()
+ run.found.set('c1', conversation({ engine: 'codex' }))
+ expect(await run.adoption.adoptableSession('c1', 'claude', null)).toEqual({ ok: false, error: 'INVALID_ENGINE', detail: 'This is a codex conversation.' })
+ run.found.set('c1', conversation({ cwd: join(folder, 'gone') }))
+ expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_FOLDER_GONE' })
+ })
+
+ it('opens one nobody has open, under its own title, or search\'s, or none', async () => {
+ const run = setup({ search: { session: () => ({ title: 'From search' }) } })
+ run.found.set('c1', conversation({ launchArgs: ['--model', 'opus'] }))
+ expect(await run.adoption.adoptableSession('c1', 'claude', null)).toEqual({
+ ok: true, cwd: folder, title: 'Fix the build', owner: null, busy: false, launchArgs: ['--model', 'opus'],
+ })
+ run.found.set('c1', conversation({ title: '' }))
+ expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ title: 'From search', launchArgs: [] })
+ const bare = setup({ search: { session: () => undefined } })
+ bare.found.set('c1', conversation({ title: '' }))
+ expect(await bare.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ title: '' })
+ })
+
+ it('never takes one from Harness\'s own pane, an app, or a terminal it cannot be sure of', async () => {
+ const run = setup()
+ run.found.set('c1', conversation())
+ const asked = async (who: SessionOwner) => {
+ vi.mocked(run.deps.openSessions.owner).mockResolvedValueOnce(who)
+ return run.adoption.adoptableSession('c1', 'claude', 'now')
+ }
+ expect(await asked(owner({ harness: true }))).toMatchObject({ error: 'SESSION_IN_HARNESS' })
+ expect(await asked(owner({ fromArgs: true }))).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE', detail: expect.stringContaining('in a terminal') })
+ expect(await asked(owner({ unverified: true }))).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE' })
+ expect(await asked(owner({ tty: null } as Partial<SessionOwner>))).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE', detail: expect.stringContaining("Claude's app") })
+ })
+
+ it('takes one from a terminal only when asked, and says when that terminal is mid-turn', async () => {
+ const run = setup()
+ run.found.set('c1', conversation())
+ vi.mocked(run.deps.openSessions.owner).mockResolvedValue(owner())
+ expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_OPEN_IN_TERMINAL' })
+ expect(await run.adoption.adoptableSession('c1', 'claude', 'idle')).toMatchObject({ ok: true, busy: false })
+ vi.mocked(run.deps.openSessions.busy).mockResolvedValue(true)
+ expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_BUSY_IN_TERMINAL' })
+ expect(await run.adoption.adoptableSession('c1', 'claude', 'idle')).toMatchObject({ error: 'SESSION_BUSY_IN_TERMINAL' })
+ expect(await run.adoption.adoptableSession('c1', 'claude', 'now')).toMatchObject({ ok: true, busy: true })
+ expect(await run.adoption.adoptableSession('c1', 'claude', 'wait')).toMatchObject({ ok: true, busy: true })
+ })
+})
+
+describe('who holds a conversation now', () => {
+ it('is the same terminal process only on hard evidence', async () => {
+ const run = setup()
+ expect(await run.adoption.heldBy('c1', owner())).toBe('free')
+ vi.mocked(run.deps.openSessions.owner).mockResolvedValueOnce(owner())
+ expect(await run.adoption.heldBy('c1', owner())).toBe('same')
+ for (const changed of [{ pid: 8 }, { tty: null }, { fromArgs: true }, { harness: true }, { unverified: true }] as Array<Partial<SessionOwner>>) {
+ vi.mocked(run.deps.openSessions.owner).mockResolvedValueOnce(owner(changed))
+ expect(await run.adoption.heldBy('c1', owner()), JSON.stringify(changed)).toBe('other')
+ }
+ })
+})
+
+describe('taking a conversation over when its turn ends', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.mocked(processAlive).mockReset().mockReturnValue(true)
+ vi.mocked(stopSessionOwner).mockReset().mockResolvedValue(true)
+ })
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
+
+ it('waits for the turn to end, then stops the terminal\'s process', async () => {
+ const log = vi.mocked(console.log)
+ const run = setup()
+ vi.mocked(run.deps.openSessions.owner).mockResolvedValue(owner())
+ vi.mocked(run.deps.openSessions.busy).mockResolvedValueOnce(true).mockResolvedValueOnce(false)
+ const done = run.adoption.takeOverWhenIdle('a1', owner(), 'c1')
+ await vi.advanceTimersByTimeAsync(2_000)
+ await done
+ expect(stopSessionOwner).toHaveBeenCalledWith(owner())
+ expect(String(log.mock.calls[0][0])).toContain('turn ended · pid 7 stopped')
+ vi.mocked(stopSessionOwner).mockResolvedValueOnce(false)
+ const again = run.adoption.takeOverWhenIdle('a1', owner(), 'c1')
+ await vi.advanceTimersByTimeAsync(1_000)
+ await again
+ expect(String(log.mock.calls[1][0])).toContain('pid 7 did not stop')
+ })
+
+ it('gives up when the harness stops starting, the process is gone, or the terminal moved on', async () => {
+ const log = vi.mocked(console.log)
+ const run = setup()
+ run.launched()
+ await (async () => { const done = run.adoption.takeOverWhenIdle('a1', owner(), 'c1'); await vi.advanceTimersByTimeAsync(1_000); await done })()
+ const gone = setup()
+ vi.mocked(processAlive).mockReturnValueOnce(false)
+ await (async () => { const done = gone.adoption.takeOverWhenIdle('a1', owner(), 'c1'); await vi.advanceTimersByTimeAsync(1_000); await done })()
+ const moved = setup()
+ vi.mocked(moved.deps.openSessions.owner).mockResolvedValue(owner({ pid: 8 }))
+ await (async () => { const done = moved.adoption.takeOverWhenIdle('a1', owner(), 'c1'); await vi.advanceTimersByTimeAsync(1_000); await done })()
+ expect(stopSessionOwner).not.toHaveBeenCalled()
+ expect(String(log.mock.calls[0][0])).toContain('pid 7 moved on · left running')
+ })
+})
diff --git a/cli/src/core/agents/adopt.ts b/cli/src/core/agents/adopt.ts
new file mode 100644
index 000000000..1ec9789d7
--- /dev/null
+++ b/cli/src/core/agents/adopt.ts
@@ -0,0 +1,113 @@
+/**
+ * Adopting a conversation Harness did not start: whether one discovery found can be opened here as a
+ * harness, and taking it over from a terminal that has it open — now, or once its turn ends — never
+ * from an app, and never from a pane that is Harness's own.
+ *
+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).
+ */
+import { existsSync } from 'node:fs'
+import type { AgentEngine } from '../../engines/types.js'
+import { engineLabel } from '../../lib/agentNames.js'
+import { sid } from '../../lib/log.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { processAlive, stopSessionOwner, type ExternalSessions, type OpenSessions, type SessionOwner } from '../../lib/sessionSearch/external.js'
+import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'
+
+export interface AdoptDeps {
+ bySession: (sessionId: string) => RegisteredSession | undefined
+ byAgent: (agentId: string) => RegisteredSession | undefined
+ stoppedAgents: Pick<StoppedAgentStore, 'list'>
+ externalSessions: Pick<ExternalSessions, 'get' | 'scan'>
+ openSessions: Pick<OpenSessions, 'owner' | 'busy'>
+ /** Session search, when it is on: the title it indexed for a conversation. */
+ search: { session(sessionId: string): { title?: string } | undefined } | null | undefined
+}
+
+export function createAdoption({ bySession, byAgent, stoppedAgents, externalSessions, openSessions, search }: AdoptDeps) {
+ /**
+ * Whether a conversation Harness did not start can be opened here as a harness: one discovery found
+ * (looked for again if it is new), on this engine, not already a harness, and not open in a running
+ * process — a terminal or the engine's app that still has it would write it too.
+ *
+ * One open in a terminal can be taken over ([takeOver]): the terminal's process is stopped and the
+ * conversation resumes here. Asked without it, the refusal says whether that process is mid-turn,
+ * so the person can choose to wait for the turn to end or stop it now. An app's is never stopped.
+ */
+ const adoptableSession = async (sessionId: string, engine: AgentEngine, takeOver: 'idle' | 'now' | 'wait' | null): Promise<{ ok: true; cwd: string; title: string; owner: SessionOwner | null; busy: boolean; launchArgs: readonly string[] } | { ok: false; error: string; detail: string }> => {
+ const held = (id: string) => !!bySession(id) || stoppedAgents.list().some((s) => s.sessionId === id)
+ if (held(sessionId)) {
+ return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }
+ }
+ const found = externalSessions.get(sessionId) ?? (await externalSessions.scan(), externalSessions.get(sessionId))
+ if (found && [found.sessionId, ...found.aliases ?? []].some(held)) {
+ return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }
+ }
+ if (!found) return { ok: false, error: 'SESSION_NOT_FOUND', detail: 'This conversation is no longer on this machine.' }
+ if (found.engine !== engine) return { ok: false, error: 'INVALID_ENGINE', detail: `This is a ${found.engine} conversation.` }
+ // The Codex app keeps a thread in a folder of its own, which people tidy away. Checked before
+ // anything is stopped: a take-over that then cannot open would only have closed it.
+ if (!existsSync(found.cwd)) {
+ return { ok: false, error: 'SESSION_FOLDER_GONE', detail: `The folder it ran in is gone: ${found.cwd}` }
+ }
+ const title = found.title || search?.session(sessionId)?.title || ''
+ const launchArgs = found.launchArgs ?? []
+ const owner = await openSessions.owner(sessionId)
+ if (!owner) return { ok: true, cwd: found.cwd, title, owner: null, busy: false, launchArgs }
+ const engineName = engineLabel(engine)
+ // A process in one of Harness's own panes is an agent the daemon is still binding: never stopped.
+ if (owner.harness) return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }
+ // Started on it, as its arguments say, and perhaps moved on since — or in a pane nobody could check
+ // was not Harness's own: not opened twice, never stopped.
+ if (owner.fromArgs || owner.unverified) {
+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It may be open in ${engineName} in a terminal. Close it there, then open it here.` }
+ }
+ if (!owner.tty) {
+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It is open in ${engineName}'s app or an editor. Close it there, then open it here.` }
+ }
+ const busy = await openSessions.busy(owner)
+ if (busy && (takeOver === null || takeOver === 'idle')) {
+ return { ok: false, error: 'SESSION_BUSY_IN_TERMINAL', detail: `${engineName} is working on it in a terminal.` }
+ }
+ if (takeOver === null) {
+ return { ok: false, error: 'SESSION_OPEN_IN_TERMINAL', detail: `It is open in ${engineName} in a terminal. Moving it here quits it there.` }
+ }
+ return { ok: true, cwd: found.cwd, title, owner, busy, launchArgs }
+ }
+
+ /**
+ * A conversation taken over when its turn ends (`takeOver: 'wait'`): its pane waits for the
+ * terminal's process to go (engineLaunch `waitForPid`), and this stops that process once the turn
+ * is over. It gives up when the harness does — closed, or Ctrl-C in its pane — and when the person
+ * quits it in the terminal themselves, which is the pane's cue as well.
+ */
+ const takeOverWhenIdle = async (agentId: string, owner: SessionOwner, sessionId: string): Promise<void> => {
+ for (;;) {
+ await new Promise<void>((resolve) => { const timer = setTimeout(resolve, 1_000); timer.unref?.() })
+ if (byAgent(agentId)?.launch?.state !== 'starting' || !processAlive(owner.pid)) return
+ // Moved on in that terminal (`/resume`, `/new`): its turn is another conversation's now, and it
+ // is left alone. The pane still waits for it to quit, and then opens this one.
+ if (await heldBy(sessionId, owner) !== 'same') {
+ console.log(`[agent] take over ${sid(sessionId)} · pid ${owner.pid} moved on · left running`)
+ return
+ }
+ if (await openSessions.busy(owner)) continue
+ const stopped = await stopSessionOwner(owner)
+ console.log(`[agent] take over ${sid(sessionId)} · turn ended · pid ${owner.pid} ${stopped ? 'stopped' : 'did not stop'}`)
+ return
+ }
+ }
+
+ /**
+ * Who holds [sessionId] now, against the [owner] seen when the person chose: `same` (that process,
+ * still a terminal's, by hard evidence, not one of Harness's own), `free` (nobody), or `other`.
+ * Asked again right before anything is stopped: the terminal may have moved to other work since.
+ */
+ const heldBy = async (sessionId: string, owner: SessionOwner): Promise<'same' | 'free' | 'other'> => {
+ const now = await openSessions.owner(sessionId)
+ if (!now) return 'free'
+ return now.pid === owner.pid && !!now.tty && !now.fromArgs && !now.harness && !now.unverified ? 'same' : 'other'
+ }
+ return { adoptableSession, takeOverWhenIdle, heldBy }
+}
+
+export type Adoption = ReturnType<typeof createAdoption>
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
new file mode 100644
index 000000000..9e3643afd
--- /dev/null
+++ b/cli/src/core/agents/create.spec.ts
@@ -0,0 +1,358 @@
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { installedDsh } from '../../dsh/installed.js'
+import { dshPinnedPermissionMode } from '../../dsh/manifest.js'
+import { materializeWorkspace } from '../../dsh/materialize.js'
+import { harnessLaunchOrRefusal, incompatibleHarnessEngine } from '../../dsh/runtime.js'
+import { preTrustClaudeProject, preTrustCodexProject } from '../../lib/claudeTrust.js'
+import { createAndRegisterPane } from '../../lib/createAgentPane.js'
+import { enginePathOverride } from '../../lib/engineBin.js'
+import { buildEngineLaunchArgv, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt } from '../../lib/engineLaunch.js'
+import { setUpWithin } from '../../lib/gridAttach.js'
+import { writeGridConfigDir } from '../../lib/gridConfigDir.js'
+import { buildGridEngineLaunch } from '../../lib/gridLaunch.js'
+import { installCodexHooks, installOpencodePlugin } from '../../lib/hooks.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'
+import { clearPaneRemainOnExit } from '../../lib/tmux.js'
+import { tmuxSupportsSessionEnv } from '../../lib/tmuxVersion.js'
+import { createAgentCreator, type CreateAgentDeps } from './create.js'
+
+vi.mock('../../dsh/installed.js', () => ({ installedDsh: vi.fn(() => undefined) }))
+vi.mock('../../dsh/manifest.js', async (real) => ({ ...await real<object>(), dshPinnedPermissionMode: vi.fn(() => null) }))
+vi.mock('../../dsh/materialize.js', () => ({ materializeWorkspace: vi.fn(async () => ({ warnings: [], created: [], kept: [] })) }))
+vi.mock('../../dsh/runtime.js', async (real) => ({
+ ...await real<object>(),
+ harnessLaunchOrRefusal: vi.fn((prepare: () => unknown) => { prepare(); return { ok: true, launch: { env: { HARNESS_DSH: 'blender' }, args: ['--dsh'] } } }),
+ incompatibleHarnessEngine: vi.fn(() => null),
+ prepareHarnessLaunch: vi.fn(),
+}))
+vi.mock('../../dsh/launch.js', async (real) => ({ ...await real<object>(), harnessEnvToClear: vi.fn(() => ['HARNESS_OLD']) }))
+vi.mock('../../engines/opencode/version.js', () => ({ opencodeMajorVersion: vi.fn(() => 2) }))
+vi.mock('../../lib/claudeTrust.js', () => ({ preTrustClaudeProject: vi.fn(), preTrustCodexProject: vi.fn() }))
+vi.mock('../../lib/createAgentPane.js', () => ({ createAndRegisterPane: vi.fn() }))
+vi.mock('../../lib/engineBin.js', async (real) => ({ ...await real<object>(), enginePathOverride: vi.fn(() => null) }))
+vi.mock('../../lib/engineInstall.js', async (real) => ({ ...await real<object>(), engineInstallRecipe: vi.fn(() => ({ install: 'recipe' })) }))
+vi.mock('../../lib/engineLaunch.js', async (real) => ({
+ ...await real<object>(),
+ buildEngineCommandArgv: vi.fn(() => ['claude']),
+ buildEngineLaunchArgv: vi.fn(() => ['zsh', '-lc', 'claude']),
+ namedAgentArgs: vi.fn((_engine: string, agent: string) => ['--agent', agent]),
+ permissionModeApproves: vi.fn(() => true),
+ permissionModeFlags: vi.fn(() => ['--permission-mode']),
+ refusePermissionFlagIfUnsupported: vi.fn(async () => null),
+ supportsFirstPrompt: vi.fn(() => true),
+}))
+vi.mock('../../lib/gridAttach.js', async (real) => ({ ...await real<object>(), setUpWithin: vi.fn(async (run: () => Promise<unknown>) => { await run(); return 'done' }) }))
+vi.mock('../../lib/gridConfigDir.js', () => ({ writeGridConfigDir: vi.fn(async () => '/config/harness-claude') }))
+vi.mock('../../lib/gridLaunch.js', async (real) => ({
+ ...await real<object>(),
+ buildGridEngineLaunch: vi.fn(() => ({ ok: true, launch: { env: { GRID_KEY: 'k' }, args: ['--grid'], webSearch: 'off' } })),
+ describeGridLaunch: vi.fn(() => '[grid] claude on Home'),
+ gridConflictingEnvToClear: vi.fn(() => ['ANTHROPIC_API_KEY']),
+}))
+vi.mock('../../lib/hooks.js', async (real) => ({ ...await real<object>(), installCodexHooks: vi.fn(), installOpencodePlugin: vi.fn() }))
+vi.mock('../../lib/sessionSearch/external.js', async (real) => ({ ...await real<object>(), stopSessionOwner: vi.fn(async () => true) }))
+vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}) }))
+vi.mock('../../lib/tmuxVersion.js', async (real) => ({ ...await real<object>(), tmuxSupportsSessionEnv: vi.fn(async () => true) }))
+
+const root = mkdtempSync(join(tmpdir(), 'core-create-'))
+afterAll(() => rmSync(root, { recursive: true, force: true }))
+let folders = 0
+const folder = (files: string[] = []) => {
+ const dir = join(root, `f${folders++}`)
+ mkdirSync(dir)
+ for (const file of files) writeFileSync(join(dir, file), '')
+ return dir
+}
+
+const request = (over: Record<string, unknown> = {}) => ({
+ engine: 'claude', cwd: folder(), bypassPermission: false, permissionMode: null, grid: null, codexHome: null, dsh: null,
+ prompt: null, name: null, agent: null, resumeSessionId: null, takeOver: null, ...over,
+}) as unknown as Parameters<ReturnType<typeof createAgentCreator>>[0]
+
+const pending = { agentId: 'a1', sessionId: '', engine: 'claude' } as RegisteredSession
+const owner = { pid: 7, engine: 'claude' } as SessionOwner
+
+function setup(over: Partial<CreateAgentDeps> = {}) {
+ const deps: CreateAgentDeps = {
+ tmuxBackend: {} as CreateAgentDeps['tmuxBackend'],
+ registry: { setLaunch: vi.fn(() => ({ ...pending, launch: { state: 'ready' } })) } as unknown as CreateAgentDeps['registry'],
+ adoptableSession: vi.fn(async () => ({ ok: true, cwd: folder(), title: 'Adopted', owner: null, busy: false, launchArgs: [] })) as never,
+ heldBy: vi.fn(async () => 'same' as const),
+ takeOverWhenIdle: vi.fn(async () => {}),
+ watchNewPane: vi.fn(async () => {}),
+ announceSession: vi.fn(),
+ attachDsh: vi.fn(),
+ prepareApiTools: vi.fn(),
+ hookPort: 4242,
+ hooksDisabled: false,
+ gridLaunchMachine: vi.fn(() => ({}) as never),
+ terminalHintMachineName: () => 'this-mac',
+ blocksFolder: vi.fn(() => false),
+ gridSetup: vi.fn(() => vi.fn(async () => ({}))) as never,
+ privateGridName: vi.fn(async () => 'grid-me'),
+ ...over,
+ }
+ return { deps, create: createAgentCreator(deps) }
+}
+
+const installed = (over: Record<string, unknown> = {}) => ({ id: 'autonomous/blender', manifest: { name: 'Blender', kind: 'agent' }, ...over })
+
+describe('creating an agent', () => {
+ beforeEach(() => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(createAndRegisterPane).mockReset().mockResolvedValue({ ok: true, spawned: { runtime: { paneId: '%1' } }, pending } as never)
+ })
+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+
+ describe('refusals before any pane opens', () => {
+ it('without tmux, in a folder being purged, or in a folder that is not one', async () => {
+ expect(await setup({ tmuxBackend: null }).create(request())).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })
+ expect(await setup({ blocksFolder: () => true }).create(request())).toEqual({ ok: false, error: 'WORKTREE_BUSY' })
+ const { create } = setup()
+ const file = join(folder(['x']), 'x')
+ expect(await create(request({ cwd: file }))).toEqual({ ok: false, error: 'CWD_NOT_FOUND' })
+ expect(await create(request({ cwd: join(root, 'missing') }))).toEqual({ ok: false, error: 'CWD_NOT_FOUND' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+
+ it('for a permission flag the engine does not take', async () => {
+ vi.mocked(refusePermissionFlagIfUnsupported).mockResolvedValueOnce({ error: 'PERMISSION_MODE_UNSUPPORTED', detail: 'opencode has no --auto' } as never)
+ expect(await setup().create(request({ engine: 'opencode', permissionMode: 'auto' }))).toEqual({ ok: false, error: 'PERMISSION_MODE_UNSUPPORTED', detail: 'opencode has no --auto' })
+ })
+
+ it('for a DSH that is missing, a viewer, the wrong engine, or on a tmux too old to pass it on', async () => {
+ const { create } = setup()
+ expect(await create(request({ dsh: 'blender' }))).toMatchObject({ error: 'INVALID_DSH', detail: 'blender is not installed on this machine' })
+ vi.mocked(installedDsh).mockReturnValue(installed({ manifest: { name: 'Viewer', kind: 'viewer' } }) as never)
+ expect(await create(request({ dsh: 'viewer' }))).toMatchObject({ error: 'INVALID_DSH', detail: 'viewer is a viewer package, not an agent' })
+ vi.mocked(installedDsh).mockReturnValue(installed() as never)
+ vi.mocked(incompatibleHarnessEngine).mockReturnValueOnce('Blender runs on codex')
+ expect(await create(request({ dsh: 'blender' }))).toMatchObject({ error: 'INVALID_DSH', detail: 'Blender runs on codex' })
+ vi.mocked(tmuxSupportsSessionEnv).mockResolvedValueOnce(false)
+ expect(await create(request({ dsh: 'blender' }))).toMatchObject({ error: 'TMUX_TOO_OLD_FOR_DSH' })
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ })
+
+ it('for a DSH whose workspace cannot be prepared, or whose launch refuses', async () => {
+ vi.mocked(installedDsh).mockReturnValue(installed() as never)
+ const { create } = setup()
+ vi.mocked(materializeWorkspace).mockRejectedValueOnce(new Error('disk full')).mockRejectedValueOnce('worse')
+ expect(await create(request({ dsh: 'blender' }))).toMatchObject({ error: 'DSH_MATERIALIZE_FAILED', detail: 'could not prepare the workspace for blender · disk full' })
+ expect(await create(request({ dsh: 'blender' }))).toMatchObject({ detail: 'could not prepare the workspace for blender · worse' })
+ vi.mocked(harnessLaunchOrRefusal).mockReturnValueOnce({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime' } as never)
+ expect(await create(request({ dsh: 'blender' }))).toEqual({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime' })
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ })
+
+ it('for a grid it cannot honour: refused by the launch, a tmux too old, or a config it cannot write', async () => {
+ const grid = { networkId: 'g1', networkName: 'Home', baseUrl: 'http://g', model: null }
+ const { create } = setup()
+ vi.mocked(buildGridEngineLaunch).mockReturnValueOnce({ ok: false, error: 'GRID_ENGINE_UNSUPPORTED', detail: 'no grid for amp' } as never)
+ expect(await create(request({ grid }))).toEqual({ ok: false, error: 'GRID_ENGINE_UNSUPPORTED', detail: 'no grid for amp' })
+ vi.mocked(tmuxSupportsSessionEnv).mockResolvedValueOnce(false)
+ expect(await create(request({ grid }))).toMatchObject({ error: 'TMUX_TOO_OLD_FOR_GRID' })
+ const configured = { ok: true, launch: { env: {}, args: [], webSearch: 'off', configDir: { envVar: 'PI_CONFIG', files: {}, links: [] } } }
+ vi.mocked(buildGridEngineLaunch).mockReturnValueOnce(configured as never).mockReturnValueOnce(configured as never)
+ vi.mocked(writeGridConfigDir).mockRejectedValueOnce(new Error('read-only')).mockRejectedValueOnce('worse')
+ expect(await create(request({ grid }))).toMatchObject({ error: 'GRID_CONFIG_FAILED', detail: "could not write claude's grid configuration · read-only" })
+ expect(await create(request({ grid }))).toMatchObject({ detail: "could not write claude's grid configuration · worse" })
+ })
+
+ it('when opening a conversation that cannot be opened, or that moved or would not quit in its terminal', async () => {
+ const refused = setup({ adoptableSession: vi.fn(async () => ({ ok: false, error: 'SESSION_NOT_FOUND', detail: 'gone' })) as never })
+ expect(await refused.create(request({ resumeSessionId: 'c1' }))).toEqual({ ok: false, error: 'SESSION_NOT_FOUND', detail: 'gone' })
+ const adopted = vi.fn(async () => ({ ok: true, cwd: folder(), title: '', owner, busy: false, launchArgs: [] }))
+ const moved = setup({ adoptableSession: adopted as never, heldBy: vi.fn(async () => 'other' as const) })
+ expect(await moved.create(request({ resumeSessionId: 'c1', takeOver: 'now' }))).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE' })
+ vi.mocked(stopSessionOwner).mockResolvedValueOnce(false)
+ expect(await setup({ adoptableSession: adopted as never }).create(request({ resumeSessionId: 'c1', takeOver: 'now' }))).toMatchObject({ error: 'SESSION_STOP_FAILED' })
+ })
+
+ it('when the pane itself cannot be made', async () => {
+ vi.mocked(createAndRegisterPane).mockResolvedValueOnce({ ok: false, error: 'SPAWN_FAILED', detail: 'tmux said no' } as never)
+ expect(await setup().create(request())).toEqual({ ok: false, error: 'SPAWN_FAILED', detail: 'tmux said no' })
+ })
+ })
+
+ describe('a pane that opens', () => {
+ it('opens a plain session, announces it and watches it until its engine is up', async () => {
+ const { deps, create } = setup()
+ const result = await create(request())
+ expect(result).toEqual({ ok: true, session: pending })
+ expect(deps.prepareApiTools).toHaveBeenCalled()
+ expect(deps.announceSession).toHaveBeenCalledWith(pending)
+ expect(deps.attachDsh).not.toHaveBeenCalled()
+ expect(deps.watchNewPane).toHaveBeenCalledWith('claude', pending, { runtime: { paneId: '%1' } }, ['claude'], { install: 'recipe' }, undefined)
+ expect(deps.takeOverWhenIdle).not.toHaveBeenCalled()
+ const pane = vi.mocked(createAndRegisterPane).mock.calls[0][0]
+ expect(pane).toMatchObject({ engine: 'claude', sessionLabel: expect.any(String), grid: null, gridLaunchRecord: null, dsh: null, dshRuntime: null, defaultName: null })
+ })
+
+ it('starts an approving session in the default harness permission when no mode was named', async () => {
+ expect(await setup().create(request({ bypassPermission: true }))).toMatchObject({ ok: true })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ bypassPermission: true, permissionMode: null })
+ })
+
+ it('opens a terminal ready at once, with nothing to watch', async () => {
+ vi.mocked(createAndRegisterPane).mockResolvedValueOnce({ ok: true, spawned: { runtime: { paneId: '%2' } }, pending: { ...pending, engine: 'terminal' } } as never)
+ const { deps, create } = setup()
+ expect(await create(request({ engine: 'terminal' }))).toMatchObject({ ok: true, session: { launch: { state: 'ready' } } })
+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%2')
+ expect(deps.watchNewPane).not.toHaveBeenCalled()
+ vi.mocked(createAndRegisterPane).mockResolvedValueOnce({ ok: true, spawned: { runtime: { paneId: '%3' } }, pending: { ...pending, engine: 'terminal' } } as never)
+ vi.mocked(deps.registry.setLaunch).mockReturnValueOnce(null)
+ expect(await create(request({ engine: 'terminal' }))).toMatchObject({ ok: true, session: { engine: 'terminal' } })
+ })
+
+ it('as a DSH: its workspace prepared, trusted when it went into an empty folder, and its launch layered on', async () => {
+ vi.mocked(installedDsh).mockReturnValue(installed() as never)
+ vi.mocked(materializeWorkspace).mockResolvedValue({ warnings: ['kept AGENTS.md'], created: ['template/scene.blend'], kept: [] } as never)
+ vi.mocked(createAndRegisterPane).mockResolvedValue({ ok: true, spawned: { runtime: { paneId: '%1' } }, pending: { ...pending, dsh: 'blender' } } as never)
+ const { deps, create } = setup()
+ await create(request({ dsh: 'blender' }))
+ expect(preTrustClaudeProject).toHaveBeenCalled()
+ expect(deps.attachDsh).toHaveBeenCalled()
+ const pane = vi.mocked(createAndRegisterPane).mock.calls[0][0]
+ expect(pane).toMatchObject({ dsh: 'blender', dshRuntime: expect.any(String), label: 'Blender', env: expect.objectContaining({ HARNESS_DSH: 'blender' }) })
+ await create(request({ dsh: 'blender', engine: 'codex' }))
+ expect(preTrustCodexProject).toHaveBeenCalled()
+ // A folder that already held something, or could not be read: trust stays the person's call.
+ await create(request({ dsh: 'blender', cwd: folder(['README.md']) }))
+ await create(request({ dsh: 'blender', engine: 'pi' }))
+ expect(preTrustClaudeProject).toHaveBeenCalledTimes(1)
+ vi.mocked(preTrustClaudeProject).mockImplementationOnce(() => { throw new Error('settings locked') }).mockImplementationOnce(() => { throw 'worse' })
+ expect(await create(request({ dsh: 'blender' }))).toMatchObject({ ok: true })
+ expect(await create(request({ dsh: 'blender' }))).toMatchObject({ ok: true })
+ vi.mocked(materializeWorkspace).mockResolvedValueOnce({ warnings: [], created: ['AGENTS.md'], kept: [] } as never)
+ await create(request({ dsh: 'blender' }))
+ expect(preTrustClaudeProject).toHaveBeenCalledTimes(3)
+ // A folder it cannot read is not an empty one.
+ const unreadable = folder()
+ chmodSync(unreadable, 0o000)
+ try {
+ await create(request({ dsh: 'blender', cwd: unreadable }))
+ } finally { chmodSync(unreadable, 0o755) }
+ expect(preTrustClaudeProject).toHaveBeenCalledTimes(3)
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ vi.mocked(materializeWorkspace).mockReset().mockResolvedValue({ warnings: [], created: [], kept: [] } as never)
+ })
+
+ it('as the Model Manager: grid is set up first, waiting a while for it', async () => {
+ const log = vi.mocked(console.log)
+ vi.mocked(installedDsh).mockReturnValue(installed({ id: 'autonomous/autonomous-grid' }) as never)
+ const ensure = vi.fn(async () => ({}))
+ const { create } = setup({ gridSetup: () => ensure as never })
+ await create(request({ dsh: 'autonomous-grid' }))
+ expect(setUpWithin).toHaveBeenCalled()
+ expect(ensure).toHaveBeenCalledWith({ ownGrid: true })
+ vi.mocked(setUpWithin).mockResolvedValueOnce('pending' as never)
+ await create(request({ dsh: 'autonomous-grid' }))
+ expect(log.mock.calls.map(([line]) => String(line)).some((line) => line.includes('grid is still being set up'))).toBe(true)
+ // No grid set-up on this daemon: the harness starts anyway.
+ expect(await setup({ gridSetup: () => undefined as never }).create(request({ dsh: 'autonomous-grid' }))).toMatchObject({ ok: true })
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ })
+
+ it('pins a DSH\'s permission mode when the engine takes it, and tells the harness about the account it can', async () => {
+ vi.mocked(installedDsh).mockReturnValue(installed() as never)
+ vi.mocked(dshPinnedPermissionMode).mockReturnValue('auto' as never)
+ const { create } = setup({ privateGridName: vi.fn(async () => { throw new Error('signed out') }) })
+ await create(request({ dsh: 'blender' }))
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ permissionMode: 'auto', bypassPermission: true })
+ vi.mocked(permissionModeFlags).mockReturnValueOnce(null as never)
+ await create(request({ dsh: 'blender' }))
+ expect(vi.mocked(createAndRegisterPane).mock.calls[1][0]).toMatchObject({ permissionMode: null, bypassPermission: false })
+ vi.mocked(dshPinnedPermissionMode).mockReset().mockReturnValue(null)
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ })
+
+ it('on a grid: its environment, its argv and its config folder, and the vendor keys it must not see cleared', async () => {
+ const grid = { networkId: 'g1', networkName: 'Home', baseUrl: 'http://g', model: 'm1' }
+ const { create } = setup()
+ await create(request({ grid }))
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({
+ grid: { baseUrl: 'http://g', model: 'm1' }, gridLaunchRecord: { override: grid, webSearch: 'off' }, env: expect.objectContaining({ GRID_KEY: 'k' }),
+ })
+ const withFile = (pointAt?: string) => ({ ok: true, launch: { env: {}, args: [], webSearch: 'off', configDir: { envVar: 'OPENCODE_CONFIG', files: {}, links: [], pointAt } } })
+ vi.mocked(buildGridEngineLaunch).mockReturnValueOnce(withFile('opencode.json') as never).mockReturnValueOnce(withFile() as never)
+ await create(request({ grid: { ...grid, model: undefined } }))
+ await create(request({ grid }))
+ expect(vi.mocked(createAndRegisterPane).mock.calls[1][0]).toMatchObject({ grid: { model: null }, env: { OPENCODE_CONFIG: '/config/harness-claude/opencode.json' } })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[2][0]).toMatchObject({ env: { OPENCODE_CONFIG: '/config/harness-claude' } })
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({ clearEnv: ['ANTHROPIC_API_KEY', 'HARNESS_OLD'], extraArgs: ['--grid'] })
+ })
+
+ it('installs the hooks a Codex profile and a new OpenCode need, unless hooks are off', async () => {
+ const on = setup()
+ await on.create(request({ engine: 'codex', codexHome: '/codex-work' }))
+ await on.create(request({ engine: 'opencode' }))
+ expect(installCodexHooks).toHaveBeenCalledWith(4242, '/codex-work')
+ expect(installOpencodePlugin).toHaveBeenCalledWith(4242)
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ env: { CODEX_HOME: '/codex-work' }, codexHome: '/codex-work' })
+ const off = setup({ hooksDisabled: true })
+ await off.create(request({ engine: 'codex', codexHome: '/codex-work' }))
+ await off.create(request({ engine: 'opencode' }))
+ expect(installCodexHooks).toHaveBeenCalledTimes(1)
+ expect(installOpencodePlugin).toHaveBeenCalledTimes(1)
+ })
+
+ it('opens as a named agent, with a first prompt, and does not install an engine with a path override', async () => {
+ vi.mocked(enginePathOverride).mockReturnValueOnce('/opt/claude' as never)
+ const { deps, create } = setup()
+ await create(request({ agent: 'reviewer', prompt: 'review the diff', name: 'Reviewer' }))
+ const options = vi.mocked(buildEngineLaunchArgv).mock.calls[0][1] as Record<string, unknown>
+ expect(options).toMatchObject({ extraArgs: ['--agent', 'reviewer'], firstPrompt: 'review the diff', installIfMissing: undefined, cwd: expect.any(String) })
+ expect(options.terminalHint).toEqual({ machineName: 'this-mac' })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ agent: 'reviewer', defaultName: 'Reviewer' })
+ expect(deps.watchNewPane).toHaveBeenCalledWith('claude', pending, expect.anything(), ['claude'], undefined, undefined)
+ })
+
+ it('opens a conversation Harness did not start, in its folder and under its title, resuming it', async () => {
+ const cwd = folder()
+ const adopted = vi.fn(async () => ({ ok: true, cwd, title: 'Fix the build', owner: null, busy: false, launchArgs: ['--model', 'opus'] }))
+ const { create } = setup({ adoptableSession: adopted as never })
+ await create(request({ resumeSessionId: 'c1' }))
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ cwd, defaultName: 'Fix the build' })
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({ resumeSessionId: 'c1', extraArgs: ['--model', 'opus'] })
+ const untitled = vi.fn(async () => ({ ok: true, cwd, title: '', owner: null, busy: false, launchArgs: [] }))
+ await setup({ adoptableSession: untitled as never }).create(request({ resumeSessionId: 'c1' }))
+ expect(vi.mocked(createAndRegisterPane).mock.calls[1][0]).toMatchObject({ defaultName: null })
+ await setup({ adoptableSession: untitled as never }).create(request({ resumeSessionId: 'c1', name: 'Mine' }))
+ expect(vi.mocked(createAndRegisterPane).mock.calls[2][0]).toMatchObject({ defaultName: 'Mine' })
+ })
+
+ it('takes a conversation over from a terminal: stopped now (mid-turn: told to continue), or once its turn ends', async () => {
+ const log = vi.mocked(console.log)
+ const busyOwner = vi.fn(async () => ({ ok: true, cwd: folder(), title: '', owner, busy: true, launchArgs: [] }))
+ const now = setup({ adoptableSession: busyOwner as never })
+ await now.create(request({ resumeSessionId: 'c1', takeOver: 'now' }))
+ expect(stopSessionOwner).toHaveBeenCalledWith(owner)
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({ firstPrompt: 'continue' })
+ expect(log.mock.calls.map(([line]) => String(line)).some((line) => line.includes('pid 7 stopped mid-turn'))).toBe(true)
+ // An engine that cannot open with a message just resumes where it stopped.
+ vi.mocked(supportsFirstPrompt).mockReturnValueOnce(false)
+ await now.create(request({ resumeSessionId: 'c1', takeOver: 'now' }))
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[1][1]).not.toHaveProperty('firstPrompt')
+ const idleOwner = vi.fn(async () => ({ ok: true, cwd: folder(), title: '', owner, busy: false, launchArgs: [] }))
+ await setup({ adoptableSession: idleOwner as never }).create(request({ resumeSessionId: 'c1', takeOver: 'now' }))
+ expect(log.mock.calls.map(([line]) => String(line)).some((line) => line.endsWith('pid 7 stopped'))).toBe(true)
+ // Quit in its terminal meanwhile: nothing to stop.
+ const free = setup({ adoptableSession: idleOwner as never, heldBy: vi.fn(async () => 'free' as const) })
+ vi.mocked(stopSessionOwner).mockClear()
+ await free.create(request({ resumeSessionId: 'c1', takeOver: 'now' }))
+ expect(stopSessionOwner).not.toHaveBeenCalled()
+ // To wait for its turn: the pane waits on the process, and the watcher has a day.
+ const wait = setup({ adoptableSession: busyOwner as never })
+ await wait.create(request({ resumeSessionId: 'c1', takeOver: 'wait' }))
+ expect(stopSessionOwner).not.toHaveBeenCalled()
+ expect(vi.mocked(buildEngineLaunchArgv).mock.lastCall?.[1]).toMatchObject({ waitForPid: { pid: 7, name: 'Claude' } })
+ expect(wait.deps.watchNewPane).toHaveBeenCalledWith('claude', pending, expect.anything(), ['claude'], { install: 'recipe' }, 24 * 60 * 60_000)
+ expect(wait.deps.takeOverWhenIdle).toHaveBeenCalledWith('a1', owner, 'c1')
+ })
+ })
+})
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
new file mode 100644
index 000000000..aa647445d
--- /dev/null
+++ b/cli/src/core/agents/create.ts
@@ -0,0 +1,323 @@
+/**
+ * Creating an agent (`agent_create`): open a fresh pane running the chosen engine in the chosen
+ * folder, as a domain-specific harness or a plain session, on a grid or the engine's own login, opening
+ * a conversation Harness did not start when asked — and refuse, before any pane opens, every launch
+ * that would not do what was asked. The pane is then watched until its engine is up.
+ *
+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).
+ */
+import { statSync } from 'node:fs'
+import { readdir } from 'node:fs/promises'
+import { join } from 'node:path'
+import type { BackendSocket } from '../../backendSocket.js'
+import { MODEL_MANAGER_ID } from '../../dsh/builtins.js'
+import { installedDsh } from '../../dsh/installed.js'
+import { harnessEnvToClear, type DshAccount } from '../../dsh/launch.js'
+import { dshPinnedPermissionMode } from '../../dsh/manifest.js'
+import { materializeWorkspace } from '../../dsh/materialize.js'
+import { harnessLaunchOrRefusal, incompatibleHarnessEngine, prepareHarnessLaunch } from '../../dsh/runtime.js'
+import { opencodeMajorVersion } from '../../engines/opencode/version.js'
+import { isTerminalEngine } from '../../engines/types.js'
+import { engineLabel } from '../../lib/agentNames.js'
+import { preTrustClaudeProject, preTrustCodexProject } from '../../lib/claudeTrust.js'
+import { createAndRegisterPane } from '../../lib/createAgentPane.js'
+import { enginePathOverride } from '../../lib/engineBin.js'
+import { engineInstallRecipe } from '../../lib/engineInstall.js'
+import {
+ buildEngineCommandArgv, buildEngineLaunchArgv, namedAgentArgs, permissionModeApproves, permissionModeFlags,
+ refusePermissionFlagIfUnsupported, supportsFirstPrompt,
+} from '../../lib/engineLaunch.js'
+import { setUpWithin } from '../../lib/gridAttach.js'
+import { writeGridConfigDir } from '../../lib/gridConfigDir.js'
+import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, type GridLaunchMachine, type GridWebSearchStatus } from '../../lib/gridLaunch.js'
+import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../../lib/harnessDefaults.js'
+import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'
+import { installCodexHooks, installOpencodePlugin } from '../../lib/hooks.js'
+import { sid } from '../../lib/log.js'
+import type { registry, RegisteredSession } from '../../lib/registry.js'
+import { stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'
+import { clearPaneRemainOnExit } from '../../lib/tmux.js'
+import type { TmuxBackend } from '../../lib/tmuxBackend.js'
+import { TMUX_SESSION_ENV_MIN, tmuxSupportsSessionEnv } from '../../lib/tmuxVersion.js'
+import type { Adoption } from './adopt.js'
+import { mergedLaunchEnv } from './launchEnv.js'
+import type { createPaneWatcher } from './newPane.js'
+
+/** How long creating a Model Manager waits for grid to be set up before its workspace asks grid which
+ * grid is this account's. Short: the app gives the whole create 20s, and a first install takes minutes.
+ * Past it the set-up carries on, and the agent's own `harness grid setup` waits for it. */
+const MODEL_MANAGER_GRID_WAIT_MS = 8_000
+
+type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>
+
+export interface CreateAgentDeps {
+ /** The tmux backend; null where the configuration lists no tmux. */
+ tmuxBackend: TmuxBackend | null
+ registry: typeof registry
+ adoptableSession: Adoption['adoptableSession']
+ heldBy: Adoption['heldBy']
+ takeOverWhenIdle: Adoption['takeOverWhenIdle']
+ watchNewPane: ReturnType<typeof createPaneWatcher>
+ announceSession: (session: RegisteredSession) => void
+ attachDsh: (session: RegisteredSession) => void
+ prepareApiTools: (cwd: string | null | undefined, engine: string) => void
+ /** The hook server's port, which installed engine hooks post to. */
+ hookPort: number
+ /** Whether engine hooks are installed at all (DISABLE_HOOK_INSTALL). */
+ hooksDisabled: boolean
+ gridLaunchMachine: () => GridLaunchMachine
+ terminalHintMachineName: () => string
+ /** Whether a folder is being purged (PurgeAgentService.blocksFolder). */
+ blocksFolder: (cwd: string) => boolean | undefined
+ /** Grid set-up, when this daemon can do it (BackendSocket.ensureGrid). */
+ gridSetup: () => BackendSocket['ensureGrid']
+ privateGridName: () => Promise<string | null>
+}
+
+export function createAgentCreator({
+ tmuxBackend, registry, adoptableSession, heldBy, takeOverWhenIdle, watchNewPane, announceSession, attachDsh,
+ prepareApiTools, hookPort, hooksDisabled, gridLaunchMachine, terminalHintMachineName, blocksFolder, gridSetup,
+ privateGridName,
+}: CreateAgentDeps) {
+ const createAgent: CreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId, takeOver }) => {
+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
+ // A conversation Harness did not start opens in its own folder, under its own title — taken over
+ // from the terminal that has it, when asked to.
+ let owner: SessionOwner | null = null
+ let ownerBusy = false
+ let resumeArgs: readonly string[] = []
+ if (resumeSessionId) {
+ const adopted = await adoptableSession(resumeSessionId, engine, takeOver ?? null)
+ if (!adopted.ok) return adopted
+ cwd = adopted.cwd
+ name = name ?? (adopted.title || null)
+ owner = adopted.owner
+ ownerBusy = adopted.busy
+ resumeArgs = adopted.launchArgs
+ }
+ if (blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }
+ try {
+ if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
+ } catch {
+ return { ok: false, error: 'CWD_NOT_FOUND' }
+ }
+ // A harness can pin its permission mode (`dshPinnedPermissionMode`): the Grid harness starts model
+ // servers, which Codex's sandbox would start without a GPU. Pinned before anything reads the mode,
+ // and recorded on the row like a chosen one, so a relaunch keeps it.
+ const pinnedDsh = dsh ? installedDsh(dsh) : null
+ const pinnedMode = pinnedDsh ? dshPinnedPermissionMode(pinnedDsh.manifest) : null
+ if (pinnedMode && permissionModeFlags(engine, pinnedMode)) {
+ permissionMode = pinnedMode
+ bypassPermission = permissionModeApproves(pinnedMode)
+ }
+ // An engine too old for the flag this permission mode launches it with prints its help and
+ // exits; the wrapper then hands the pane to a shell, and what the person gets is a terminal
+ // full of help text with nothing anywhere saying why (openharness#285, opencode without
+ // `--auto`). Refuse before opening a pane — this is a launch somebody is waiting on, and Ask
+ // works today. Codex has been checked this way since it gained `--approve-for-me`; every other
+ // engine with a permission flag was not, and carried the same failure.
+ const refusal = await refusePermissionFlagIfUnsupported(engine, { permissionMode, bypassPermission })
+ if (refusal) {
+ console.warn(`[agent] create refused · ${engine} · ${refusal.detail}`)
+ return { ok: false, ...refusal }
+ }
+ // Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
+ // retaining the engine and a collision-resistant creation suffix for diagnostics. Computed
+ // before the grid block because a file-configured engine keys its config directory on it.
+ // The `harness-` prefix is also discovery's whitelist (see `isHarnessSession` /
+ // `TmuxBackend.inventory()`) — every pane outside it is invisible to the daemon.
+ const label = buildHarnessSessionLabel(engine)
+ // Prepare the harness workspace, then bind its session context to the selected engine.
+ // Missing packages or invalid runtimes refuse the launch before the agent is started.
+ let dshEnv: Record<string, string> | undefined
+ let dshArgs: string[] = []
+ /** A DSH's own name ("Blender"), which the agent is named after instead of its engine. */
+ let dshLabel: string | undefined
+ /** What the harness is told about the signed-in account (its private grid), not left to guess. */
+ let dshAccount: DshAccount = {}
+ if (dsh) {
+ const installed = installedDsh(dsh)
+ if (!installed) return { ok: false, error: 'INVALID_DSH', detail: `${dsh} is not installed on this machine` }
+ if (installed.manifest.kind === 'viewer') return { ok: false, error: 'INVALID_DSH', detail: `${dsh} is a viewer package, not an agent` }
+ const refusal = incompatibleHarnessEngine(dsh, installed.manifest, engine)
+ if (refusal) {
+ return { ok: false, error: 'INVALID_DSH', detail: refusal }
+ }
+ if (!(await tmuxSupportsSessionEnv())) {
+ const detail = `this machine's tmux is older than ${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, `
+ + `which is the first version that can give a new session its own environment — so ${installed.manifest.name} `
+ + `could not tell ${engine} which harness it is. Upgrade tmux.`
+ console.warn(`[agent] create ${dsh} refused · ${detail}`)
+ return { ok: false, error: 'TMUX_TOO_OLD_FOR_DSH', detail }
+ }
+ // The Model Manager is grid in use, however it was made (the Store, New Harness, `harness new`, the
+ // models picker): grid is set up before the workspace asks it which grid is this account's.
+ const ensureGrid = gridSetup()
+ if (installed.id === MODEL_MANAGER_ID && ensureGrid) {
+ const setUp = await setUpWithin(() => ensureGrid({ ownGrid: true }), MODEL_MANAGER_GRID_WAIT_MS)
+ if (setUp === 'pending') console.log(`[dsh] ${dsh} · grid is still being set up; the agent waits for it with \`harness grid setup\``)
+ }
+ try {
+ dshAccount = { privateGrid: await privateGridName().catch(() => null) }
+ // Asked BEFORE the template goes in: afterwards every folder has content.
+ // Not there yet is empty; unreadable is not — trust is only ever granted on evidence.
+ const emptyBefore = await readdir(cwd).then((names) => names.length === 0,
+ (error: NodeJS.ErrnoException) => error.code === 'ENOENT')
+ const materialized = await materializeWorkspace(installed, cwd, dshAccount, engine)
+ for (const warning of materialized.warnings) console.warn(`[dsh] ${dsh} materialize · ${warning}`)
+ console.log(`[dsh] ${dsh} materialized ${cwd} · created ${materialized.created.length} · kept ${materialized.kept.length}`)
+ // The template just went into an EMPTY folder: everything in it is the harness's, and Claude Code
+ // need not ask. Laid into a folder that already held something — a clone, the person's own repo —
+ // it proves nothing about the rest, so trust stays the person's call (lib/claudeTrust.ts).
+ if (emptyBefore && materialized.created.some((item) => item.startsWith('template'))) {
+ try {
+ if (engine === 'claude') preTrustClaudeProject(cwd)
+ if (engine === 'codex') preTrustCodexProject(cwd)
+ } catch (error) { console.warn(`[dsh] pre-trust ${cwd} · ${error instanceof Error ? error.message : error}`) }
+ }
+ } catch (error) {
+ const detail = `could not prepare the workspace for ${dsh} · ${error instanceof Error ? error.message : error}`
+ console.warn(`[agent] create ${dsh} refused · ${detail}`)
+ return { ok: false, error: 'DSH_MATERIALIZE_FAILED', detail }
+ }
+ const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label, dshAccount, null))
+ if (!prepared.ok) return prepared
+ dshEnv = prepared.launch.env
+ dshArgs = prepared.launch.args
+ dshLabel = installed.manifest.name
+ }
+ // A grid is the user's answer to "where should this run", so every way of not honouring it is a
+ // refusal rather than a fallback — an agent silently started on the engine's own login spends the
+ // wrong account and looks identical to one that worked.
+ let gridLaunch: { env: Record<string, string>; args: string[]; webSearch: GridWebSearchStatus } | undefined
+ if (grid) {
+ const built = buildGridEngineLaunch(engine, grid, gridLaunchMachine())
+ if (!built.ok) {
+ console.warn(`[agent] create ${engine} refused · ${built.detail}`)
+ return { ok: false, error: built.error, detail: built.detail }
+ }
+ if (!(await tmuxSupportsSessionEnv())) {
+ const detail = `this machine's tmux is older than `
+ + `${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, which is the first version that can `
+ + `give a new session its own environment — so ${engine} could not have been pointed at grid `
+ + `${grid.networkName}. Upgrade tmux, or create this agent without a grid selected.`
+ console.warn(`[agent] create ${engine} refused · ${detail}`)
+ return { ok: false, error: 'TMUX_TOO_OLD_FOR_GRID', detail }
+ }
+ gridLaunch = { env: { ...built.launch.env }, args: built.launch.args, webSearch: built.launch.webSearch }
+ // An engine whose provider lives in a file gets a directory this daemon owns, never the
+ // user's own dotfiles. The label is unique per creation, so two agents never share one.
+ if (built.launch.configDir) {
+ const { envVar, files, pointAt, links } = built.launch.configDir
+ try {
+ const dir = await writeGridConfigDir(label, files, links)
+ // Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.
+ gridLaunch.env[envVar] = pointAt ? join(dir, pointAt) : dir
+ } catch (error) {
+ const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`
+ console.warn(`[agent] create ${engine} refused · ${detail}`)
+ return { ok: false, error: 'GRID_CONFIG_FAILED', detail }
+ }
+ }
+ // Named in the log because the pane itself gives nothing away: the engine looks exactly like a
+ // normally launched one. The key is never printed.
+ console.log(describeGridLaunch(engine, grid, built.launch.webSearch))
+ }
+ // A Codex agent pointed at a profile OTHER than this machine's default reads hooks.json from
+ // THAT folder, not the one `harness login` already installed into — without this, such an agent
+ // fires no hook at all (no SessionStart/UserPromptSubmit/Stop) and never streams a single event.
+ // Idempotent, so paying this on every create against an already-set-up profile is free.
+ if (codexHome && !hooksDisabled) installCodexHooks(hookPort, codexHome)
+ // OpenCode may have upgraded from 1.x to 2.x while this daemon was running. Its new TUI must
+ // not discover our old server plugin; the cached version probe changes with the executable.
+ if (engine === 'opencode' && !hooksDisabled) installOpencodePlugin(hookPort)
+ // Do not start a second interactive login shell merely to ask whether the engine is installed.
+ // The pane's own shell performs the same check before exec, and installs only when necessary.
+ // This removes ~1s of shell startup from the click-to-terminal critical path.
+ const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)
+ // Clearing the vendor credentials this launch does NOT set is part of pointing an agent at a
+ // grid, not an extra. An engine chooses its provider from whatever it can see, and an inherited
+ // key wins on its own terms — OpenCode picked Anthropic over a grid it had been handed, and said
+ // only `invalid x-api-key`. Nothing is cleared when no grid is in play: an agent on its own login
+ // is supposed to use exactly these variables.
+ const clearEnv = [...(gridLaunch ? gridConflictingEnvToClear(gridLaunch) : []), ...harnessEnvToClear(dshEnv)]
+ // The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it
+ // from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was
+ // checked for a contract at the wire (AGENT_UNSUPPORTED, opencode v2 included), so this cannot throw.
+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, opencodeMajorVersion()) : []), ...resumeArgs]
+ // The first prompt is a launch option only — never part of `extraArgs`, which the registry row
+ // carries into a relaunch (engineLaunch.ts, `firstPrompt`).
+ // Stopped mid-turn, the resumed conversation is told to carry on — by an engine that can open
+ // with a message; any other resumes where it stopped and waits.
+ const waitFor = owner && takeOver === 'wait' && ownerBusy ? owner : null
+ const firstPrompt = prompt ?? (owner && !waitFor && ownerBusy && supportsFirstPrompt(engine) ? 'continue' : null)
+ const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), ...(resumeSessionId ? { resumeSessionId } : {}), ...(waitFor ? { waitForPid: { pid: waitFor.pid, name: engineLabel(engine) } } : {}), terminalHint: { machineName: terminalHintMachineName() } }
+ const command = buildEngineCommandArgv(engine, launchOptions)
+ const argv = buildEngineLaunchArgv(engine, launchOptions)
+ // The terminal's process goes last, once nothing here can refuse or fail the launch — the command
+ // is built — stopped now, or, to wait for its turn, left running for the pane to wait on.
+ if (owner && !waitFor && resumeSessionId) {
+ const held = await heldBy(resumeSessionId, owner)
+ if (held === 'other') {
+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: 'It moved to another process just now. Close it there, then open it here.' }
+ }
+ // Quit in its terminal meanwhile: it is free, and nothing is stopped.
+ if (held === 'same' && !await stopSessionOwner(owner)) {
+ return { ok: false, error: 'SESSION_STOP_FAILED', detail: 'The terminal that has it did not quit. Close it there, then open it here.' }
+ }
+ if (held === 'same') console.log(`[agent] take over ${sid(resumeSessionId)} · pid ${owner.pid} stopped${ownerBusy ? ' mid-turn' : ''}`)
+ }
+ // A tmux route is enough to stream its screen. Register it before looking for a process so both
+ // loopback and relayed Desktop clients can attach while the login shell/installer is still busy.
+ // `tmuxBackend` exists whenever the CONFIG lists tmux — it is never a probe of the binary, so a
+ // daemon that cannot resolve `tmux` at all (a login context whose PATH lacks Homebrew's bin, the
+ // usual shape after a reboot) is reported as `TMUX_UNAVAILABLE` too, distinctly from a tmux that
+ // answered and refused (`SPAWN_FAILED`) — see createAgentPane.ts. Registration itself is retried
+ // there: a stale registry entry from a previous tmux-server generation occasionally collides with
+ // a freshly-minted pane id, and that collision clears on its own on the very next pane.
+ prepareApiTools(cwd, engine)
+ // Mutually exclusive with a grid (backendSocket.ts refuses the two together): a chosen Codex
+ // profile becomes the new session's CODEX_HOME, the same `-e` mechanism a grid's own env rides.
+ const result = await createAndRegisterPane({
+ tmuxBackend,
+ registry,
+ engine,
+ cwd,
+ sessionLabel: label,
+ argv,
+ env: freshHarnessEnvironment(engine, mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv), !!grid || !!resumeSessionId,
+ permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')),
+ grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
+ gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
+ codexHome,
+ dsh,
+ dshRuntime: dsh ? label : null,
+ agent,
+ bypassPermission,
+ permissionMode,
+ defaultName: name,
+ label: dshLabel,
+ })
+ if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
+ const { spawned, pending } = result
+ // A terminal is ready the moment its pane is: there is no engine process to wait for, and the
+ // shell exiting is the person closing it — so `remain-on-exit` comes off now, and the pane going
+ // away is what removes the row (reconciler `onRemoved`), exactly as for an engine that quit.
+ if (isTerminalEngine(engine)) {
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ const ready = registry.setLaunch(pending.agentId, { state: 'ready' }) ?? pending
+ announceSession(ready)
+ console.log(`[agent] create terminal open · agent ${pending.agentId}`)
+ return { ok: true, session: ready }
+ }
+ announceSession(pending)
+ if (pending.dsh) attachDsh(pending)
+
+ // A pane waiting out another terminal's turn may wait as long as that turn takes.
+ void watchNewPane(engine, pending, spawned, command, installIfMissing, waitFor ? 24 * 60 * 60_000 : undefined)
+ if (waitFor && resumeSessionId) void takeOverWhenIdle(pending.agentId, waitFor, resumeSessionId)
+ console.log(`[agent] create pane open · ${engine} · agent ${pending.agentId}`)
+ return { ok: true, session: pending }
+ }
+ return createAgent
+}
diff --git a/cli/src/core/agents/fork.spec.ts b/cli/src/core/agents/fork.spec.ts
new file mode 100644
index 000000000..771f8e17d
--- /dev/null
+++ b/cli/src/core/agents/fork.spec.ts
@@ -0,0 +1,154 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { installedDsh } from '../../dsh/installed.js'
+import { harnessLaunchOrRefusal } from '../../dsh/runtime.js'
+import { createAndRegisterPane } from '../../lib/createAgentPane.js'
+import { enginePathOverride } from '../../lib/engineBin.js'
+import { buildEngineLaunchArgv, refusePermissionFlagIfUnsupported, supportsNamedAgent } from '../../lib/engineLaunch.js'
+import { planFork } from '../../lib/forkAgent.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { createAgentForker, type ForkAgentDeps } from './fork.js'
+
+vi.mock('../../dsh/installed.js', () => ({ installedDsh: vi.fn(() => undefined) }))
+vi.mock('../../dsh/runtime.js', async (real) => ({
+ ...await real<object>(),
+ forkRuntimeKey: vi.fn(() => 'source-key'),
+ harnessLaunchOrRefusal: vi.fn((prepare: () => unknown) => { prepare(); return { ok: true, launch: { env: { HARNESS_DSH: 'blender' }, args: ['--dsh'] } } }),
+ prepareHarnessLaunch: vi.fn(),
+}))
+vi.mock('../../engines/opencode/version.js', () => ({ opencodeMajorVersion: vi.fn(() => 2) }))
+vi.mock('../../lib/createAgentPane.js', () => ({ createAndRegisterPane: vi.fn() }))
+vi.mock('../../lib/engineBin.js', async (real) => ({ ...await real<object>(), enginePathOverride: vi.fn(() => null) }))
+vi.mock('../../lib/engineInstall.js', async (real) => ({ ...await real<object>(), engineInstallRecipe: vi.fn(() => ({ install: 'recipe' })) }))
+vi.mock('../../lib/engineLaunch.js', async (real) => ({
+ ...await real<object>(),
+ buildEngineCommandArgv: vi.fn(() => ['claude']),
+ buildEngineLaunchArgv: vi.fn(() => ['zsh', '-lc', 'claude']),
+ namedAgentArgs: vi.fn((_engine: string, agent: string) => ['--agent', agent]),
+ refusePermissionFlagIfUnsupported: vi.fn(async () => null),
+ supportsNamedAgent: vi.fn(() => true),
+}))
+vi.mock('../../lib/forkAgent.js', async (real) => ({ ...await real<object>(), planFork: vi.fn(() => ({ ok: true, level: 'native', forkSessionId: 's1' })) }))
+
+const root = mkdtempSync(join(tmpdir(), 'core-fork-'))
+afterAll(() => rmSync(root, { recursive: true, force: true }))
+const work = join(root, 'work')
+mkdirSync(work)
+writeFileSync(join(root, 'file'), '')
+
+const source = (over: Partial<RegisteredSession> = {}): RegisteredSession =>
+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: work, name: 'Builder', transcriptPath: '/t/s1.jsonl', ...over }) as RegisteredSession
+const pending = { agentId: 'f1', sessionId: '', engine: 'claude' } as RegisteredSession
+
+function setup(row: RegisteredSession | null = source(), over: Partial<ForkAgentDeps> = {}) {
+ const deps: ForkAgentDeps = {
+ tmuxBackend: {} as ForkAgentDeps['tmuxBackend'],
+ registry: { byAgent: vi.fn(() => row ?? undefined) } as unknown as ForkAgentDeps['registry'],
+ mirror: {
+ isBusy: vi.fn(() => false),
+ recentAsks: vi.fn(() => ['build it']),
+ recent: vi.fn(() => [{ recap: 'built', text: 'Built the app.' }, { recap: '', text: 'Ran the tests.' }]),
+ lastFullText: vi.fn(() => 'All green.'),
+ } as unknown as ForkAgentDeps['mirror'],
+ pendingForkInherit: new Map(),
+ watchNewPane: vi.fn(async () => {}),
+ announceSession: vi.fn(),
+ attachDsh: vi.fn(),
+ prepareApiTools: vi.fn(),
+ gridName: () => 'grid-me',
+ ...over,
+ }
+ return { deps, fork: createAgentForker(deps) }
+}
+
+describe('forking an agent', () => {
+ beforeEach(() => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(createAndRegisterPane).mockReset().mockResolvedValue({ ok: true, spawned: { runtime: { paneId: '%3' } }, pending } as never)
+ })
+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+
+ it('refuses without tmux, an agent, a folder, or with a grid or a turn in progress', async () => {
+ expect(await setup(source(), { tmuxBackend: null }).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })
+ expect(await setup(null).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })
+ expect(await setup(source({ cwd: undefined })).fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ error: 'CWD_NOT_FOUND', detail: expect.stringContaining('no working folder') })
+ expect(await setup(source({ cwd: join(root, 'file') })).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'CWD_NOT_FOUND' })
+ expect(await setup(source({ cwd: join(root, 'gone') })).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'CWD_NOT_FOUND' })
+ expect(await setup(source({ grid: { baseUrl: 'g', model: null } } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ error: 'FORK_ON_GRID_UNSUPPORTED' })
+ expect(await setup(source({ gridLaunch: { networkId: 'g' } } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ error: 'FORK_ON_GRID_UNSUPPORTED' })
+ const busy = setup()
+ vi.mocked(busy.deps.mirror.isBusy).mockReturnValue(true)
+ expect(await busy.fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ error: 'AGENT_BUSY' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+
+ it('refuses what the plan refuses, a harness no longer installed, a launch it refuses, and a pane it cannot make', async () => {
+ vi.mocked(planFork).mockReturnValueOnce({ ok: false, error: 'FORK_UNSUPPORTED', detail: 'amp cannot fork' } as never)
+ expect(await setup().fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'FORK_UNSUPPORTED', detail: 'amp cannot fork' })
+ expect(await setup(source({ dsh: 'blender' } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ error: 'INVALID_DSH' })
+ vi.mocked(installedDsh).mockReturnValue({ manifest: { name: 'Blender' } } as never)
+ vi.mocked(harnessLaunchOrRefusal).mockReturnValueOnce({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime' } as never)
+ expect(await setup(source({ dsh: 'blender' } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime' })
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ vi.mocked(refusePermissionFlagIfUnsupported).mockResolvedValueOnce({ error: 'PERMISSION_MODE_UNSUPPORTED', detail: 'no --auto' } as never)
+ expect(await setup().fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'PERMISSION_MODE_UNSUPPORTED', detail: 'no --auto' })
+ vi.mocked(createAndRegisterPane).mockResolvedValueOnce({ ok: false, error: 'SPAWN_FAILED', detail: 'tmux said no' } as never)
+ expect(await setup().fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'SPAWN_FAILED', detail: 'tmux said no' })
+ })
+
+ it('forks natively: the source\'s session, folder and permission, the source\'s recap waiting for the new tile', async () => {
+ const { deps, fork } = setup(source({ permissionMode: 'plan', bypassPermission: true, codexHome: '/codex' } as Partial<RegisteredSession>))
+ expect(await fork({ agentId: 'a1', name: null, prompt: 'try the other approach' })).toEqual({ ok: true, session: pending, level: 'native' })
+ expect(planFork).toHaveBeenCalledWith({ engine: 'claude', sessionId: 's1', name: expect.any(String), cwd: work },
+ { asks: ['build it'], recaps: ['built', 'Ran the tests.'], lastAnswer: 'All green.' }, 'try the other approach')
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({ forkSessionId: 's1', firstPrompt: 'try the other approach', permissionMode: 'plan', bypassPermission: true, cwd: work })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({
+ cwd: work, env: { CODEX_HOME: '/codex' }, codexHome: '/codex', permissionMode: 'plan', defaultName: expect.any(String),
+ forkedFrom: { agentId: 'a1', sessionId: 's1', transcriptPath: '/t/s1.jsonl' },
+ })
+ expect(deps.pendingForkInherit.get('f1')).toBe('s1')
+ expect(deps.prepareApiTools).toHaveBeenCalledWith(work, 'claude')
+ expect(deps.announceSession).toHaveBeenCalledWith(pending)
+ expect(deps.watchNewPane).toHaveBeenCalledWith('claude', pending, { runtime: { paneId: '%3' } }, ['claude'], { install: 'recipe' })
+ })
+
+ it('hands off what it remembers to an engine that cannot fork, and names the fork as asked', async () => {
+ vi.mocked(planFork).mockReturnValueOnce({ ok: true, level: 'handoff', firstPrompt: 'You are continuing…' } as never)
+ const { fork } = setup()
+ expect(await fork({ agentId: 'a1', name: 'Builder 2', prompt: null })).toMatchObject({ level: 'handoff' })
+ const options = vi.mocked(buildEngineLaunchArgv).mock.calls[0][1] as Record<string, unknown>
+ expect(options).toMatchObject({ firstPrompt: 'You are continuing…' })
+ expect(options).not.toHaveProperty('forkSessionId')
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ defaultName: 'Builder 2' })
+ })
+
+ it('forks an agent with no session from what little it has, and opens a native fork with no first prompt', async () => {
+ const { deps, fork } = setup(source({ sessionId: '', transcriptPath: undefined } as Partial<RegisteredSession>))
+ await fork({ agentId: 'a1', name: null, prompt: null })
+ expect(vi.mocked(planFork).mock.calls[0][1]).toEqual({ asks: [], recaps: [], lastAnswer: undefined })
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).not.toHaveProperty('firstPrompt')
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ forkedFrom: { agentId: 'a1' }, env: undefined, permissionMode: null, bypassPermission: false })
+ expect(deps.pendingForkInherit.size).toBe(0)
+ // A session without a transcript on record still forks from its session.
+ await setup(source({ transcriptPath: undefined } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[1][0]).toMatchObject({ forkedFrom: { agentId: 'a1', sessionId: 's1' } })
+ })
+
+ it('carries the harness and the named agent over, when the engine still takes it', async () => {
+ vi.mocked(installedDsh).mockReturnValue({ manifest: { name: 'Blender' } } as never)
+ vi.mocked(createAndRegisterPane).mockResolvedValue({ ok: true, spawned: { runtime: { paneId: '%3' } }, pending: { ...pending, dsh: 'blender' } } as never)
+ vi.mocked(enginePathOverride).mockReturnValueOnce('/opt/claude' as never)
+ const { deps, fork } = setup(source({ dsh: 'blender', dshRuntime: 'harness-claude-x', agent: 'reviewer' } as Partial<RegisteredSession>))
+ await fork({ agentId: 'a1', name: null, prompt: null })
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({ extraArgs: ['--dsh', '--agent', 'reviewer'], harnessNode: true, installIfMissing: undefined })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ dsh: 'blender', agent: 'reviewer', label: 'Blender', env: { HARNESS_DSH: 'blender' } })
+ expect(deps.attachDsh).toHaveBeenCalled()
+ vi.mocked(supportsNamedAgent).mockReturnValueOnce(false)
+ await setup(source({ agent: 'reviewer' } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[1][1]).toMatchObject({ extraArgs: undefined })
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ })
+})
diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.ts
new file mode 100644
index 000000000..091ce03ad
--- /dev/null
+++ b/cli/src/core/agents/fork.ts
@@ -0,0 +1,155 @@
+/**
+ * Forking an agent (`agent_fork`): open a NEW pane whose engine starts with everything the source's
+ * session has — `claude --resume <id> --fork-session`, `codex fork <id>` — or, for an engine that cannot
+ * fork but takes a first prompt, a handoff message composed from what this daemon remembers of the
+ * source (lib/forkAgent.ts). Same folder, same harness, same permission mode, same named agent; a grid
+ * agent is refused rather than half-copied. The source is not touched — it is not even paused — which is
+ * why it has to be IDLE: a fork taken mid-turn is a transcript cut in half.
+ *
+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).
+ */
+import { statSync } from 'node:fs'
+import type { BackendSocket } from '../../backendSocket.js'
+import { installedDsh } from '../../dsh/installed.js'
+import { harnessEnvToClear } from '../../dsh/launch.js'
+import { forkRuntimeKey, harnessLaunchOrRefusal, prepareHarnessLaunch } from '../../dsh/runtime.js'
+import { opencodeMajorVersion } from '../../engines/opencode/version.js'
+import type { CommanderMirror } from '../../lib/commander.js'
+import { createAndRegisterPane } from '../../lib/createAgentPane.js'
+import { enginePathOverride } from '../../lib/engineBin.js'
+import { engineInstallRecipe } from '../../lib/engineInstall.js'
+import { buildEngineCommandArgv, buildEngineLaunchArgv, namedAgentArgs, refusePermissionFlagIfUnsupported, supportsNamedAgent } from '../../lib/engineLaunch.js'
+import { forkName, planFork } from '../../lib/forkAgent.js'
+import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'
+import { projectDisplayName, type registry, type RegisteredSession } from '../../lib/registry.js'
+import type { TmuxBackend } from '../../lib/tmuxBackend.js'
+import { mergedLaunchEnv } from './launchEnv.js'
+import type { createPaneWatcher } from './newPane.js'
+
+type ForkAgent = NonNullable<BackendSocket['onForkAgent']>
+
+export interface ForkAgentDeps {
+ tmuxBackend: TmuxBackend | null
+ registry: typeof registry
+ mirror: Pick<CommanderMirror, 'isBusy' | 'recentAsks' | 'recent' | 'lastFullText'>
+ /** Forks whose session has not reported in yet, to the source session whose recap they inherit (bind.ts). */
+ pendingForkInherit: Map<string, string>
+ watchNewPane: ReturnType<typeof createPaneWatcher>
+ announceSession: (session: RegisteredSession) => void
+ attachDsh: (session: RegisteredSession) => void
+ prepareApiTools: (cwd: string | null | undefined, engine: string) => void
+ /** This account's private grid, as the socket knows it (BackendSocket.gridName). */
+ gridName: () => string | null
+}
+
+export function createAgentForker({
+ tmuxBackend, registry, mirror, pendingForkInherit, watchNewPane, announceSession, attachDsh, prepareApiTools, gridName,
+}: ForkAgentDeps) {
+ const forkAgent: ForkAgent = async ({ agentId, name, prompt }) => {
+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
+ const source = registry.byAgent(agentId)
+ if (!source) return { ok: false, error: 'AGENT_NOT_FOUND' }
+ const sourceName = projectDisplayName(source)
+ if (!source.cwd) return { ok: false, error: 'CWD_NOT_FOUND', detail: `${sourceName} has no working folder on record.` }
+ try {
+ if (!statSync(source.cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
+ } catch {
+ return { ok: false, error: 'CWD_NOT_FOUND' }
+ }
+ if (source.gridLaunch || source.grid) {
+ return { ok: false, error: 'FORK_ON_GRID_UNSUPPORTED', detail: `${sourceName} runs on a grid; forking a grid agent is not supported.` }
+ }
+ if (source.sessionId && mirror.isBusy(source.sessionId)) {
+ return { ok: false, error: 'AGENT_BUSY', detail: `${sourceName} is in the middle of a turn. Wait for it to finish, then fork.` }
+ }
+ const engine = source.engine
+ const memory = {
+ asks: source.sessionId ? mirror.recentAsks(source.sessionId) : [],
+ recaps: source.sessionId ? mirror.recent(source.sessionId, 5).map((t) => t.recap || t.text) : [],
+ lastAnswer: source.sessionId ? mirror.lastFullText(source.sessionId) : undefined,
+ }
+ const plan = planFork({ engine, sessionId: source.sessionId, name: sourceName, cwd: source.cwd }, memory, prompt)
+ if (!plan.ok) return { ok: false, error: plan.error, detail: plan.detail }
+
+ const label = buildHarnessSessionLabel(engine)
+ // Fork the source's saved harness context. Workspace templates and init are not run again.
+ let dshEnv: Record<string, string> | undefined
+ let dshArgs: string[] = []
+ let dshLabel: string | undefined
+ if (source.dsh) {
+ const installed = installedDsh(source.dsh)
+ if (!installed) return { ok: false, error: 'INVALID_DSH', detail: `${source.dsh} is no longer installed on this machine` }
+ // Narrowed above; a closure would lose that, so the checked values are named here.
+ const cwd = source.cwd
+ const sourceKey = forkRuntimeKey({ cwd, agentId: source.agentId, dshRuntime: source.dshRuntime })
+ const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label,
+ { privateGrid: gridName() }, sourceKey))
+ if (!prepared.ok) return prepared
+ dshEnv = prepared.launch.env
+ dshArgs = prepared.launch.args
+ dshLabel = installed.manifest.name
+ }
+ const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)
+ // Same guard as a relaunch (`buildLaunchOverrides`): an opencode agent recorded on v1 forks on v2
+ // as a general session rather than handing the v2 TUI an `--agent` it exits on.
+ const forkMajor = opencodeMajorVersion()
+ const extraArgs = [...dshArgs, ...(source.agent && supportsNamedAgent(engine, forkMajor) ? namedAgentArgs(engine, source.agent, forkMajor) : [])]
+ const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPrompt
+ const launchOptions = {
+ clearEnv: harnessEnvToClear(dshEnv),
+ bypassPermission: source.bypassPermission ?? false,
+ ...(source.permissionMode ? { permissionMode: source.permissionMode } : {}),
+ extraArgs: extraArgs.length ? extraArgs : undefined,
+ installIfMissing,
+ cwd: source.cwd,
+ harnessNode: source.dsh ? true : undefined,
+ ...(plan.level === 'native' ? { forkSessionId: plan.forkSessionId } : {}),
+ ...(firstPrompt ? { firstPrompt } : {}),
+ }
+ // Same refusal as create: the clone inherits the source's permission mode, and an engine that
+ // has since been downgraded would hand back a pane of help text instead of a harness.
+ const forkRefusal = await refusePermissionFlagIfUnsupported(engine, launchOptions)
+ if (forkRefusal) {
+ console.warn(`[agent] fork refused · ${engine} · ${forkRefusal.detail}`)
+ return { ok: false, ...forkRefusal }
+ }
+ prepareApiTools(source.cwd, engine)
+ const command = buildEngineCommandArgv(engine, launchOptions)
+ const argv = buildEngineLaunchArgv(engine, launchOptions)
+ const result = await createAndRegisterPane({
+ tmuxBackend,
+ registry,
+ engine,
+ cwd: source.cwd,
+ sessionLabel: label,
+ argv,
+ env: mergedLaunchEnv(source.codexHome ? { CODEX_HOME: source.codexHome } : undefined, dshEnv),
+ grid: null,
+ gridLaunchRecord: null,
+ codexHome: source.codexHome ?? null,
+ dshRuntime: source.dsh ? label : null,
+ dsh: source.dsh ?? null,
+ agent: source.agent ?? null,
+ bypassPermission: source.bypassPermission ?? false,
+ permissionMode: source.permissionMode ?? null,
+ defaultName: name ?? forkName(sourceName),
+ label: dshLabel,
+ // The session being forked from, so a Change agent right after the fork reads exactly that conversation.
+ forkedFrom: {
+ agentId: source.agentId, name: sourceName,
+ ...(source.sessionId ? { sessionId: source.sessionId, ...(source.transcriptPath ? { transcriptPath: source.transcriptPath } : {}) } : {}),
+ },
+ })
+ if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
+ const { spawned, pending } = result
+ // The new tile starts with the source's last recap on it, the way a native fork's pane starts with
+ // the source's transcript: memory in both places, not one. Settled when the engine names its session.
+ if (source.sessionId) pendingForkInherit.set(pending.agentId, source.sessionId)
+ announceSession(pending)
+ if (pending.dsh) attachDsh(pending)
+ void watchNewPane(engine, pending, spawned, command, installIfMissing)
+ console.log(`[agent] fork pane open · ${engine} · ${plan.level} · ${source.agentId} → ${pending.agentId}`)
+ return { ok: true, session: pending, level: plan.level }
+ }
+ return forkAgent
+}
diff --git a/cli/src/core/agents/launchEnv.ts b/cli/src/core/agents/launchEnv.ts
new file mode 100644
index 000000000..f96f54b08
--- /dev/null
+++ b/cli/src/core/agents/launchEnv.ts
@@ -0,0 +1,8 @@
+/** The pane's session environment: the grid's or the profile's, with the DSH's layered on top. */
+export function mergedLaunchEnv(
+ base: Record<string, string> | undefined,
+ dsh: Record<string, string> | undefined,
+): Record<string, string> | undefined {
+ if (!base && !dsh) return undefined
+ return { ...(base ?? {}), ...(dsh ?? {}) }
+}
diff --git a/cli/src/core/agents/newPane.spec.ts b/cli/src/core/agents/newPane.spec.ts
new file mode 100644
index 000000000..119f52241
--- /dev/null
+++ b/cli/src/core/agents/newPane.spec.ts
@@ -0,0 +1,163 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { commandAvailableInInteractiveShell } from '../../lib/engineLaunch.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { clearPaneRemainOnExit, resolvePaneEngineProcess, tmuxPaneState } from '../../lib/tmux.js'
+import { createPaneWatcher, type PaneWatcherDeps } from './newPane.js'
+
+vi.mock('../../lib/tmux.js', async (real) => ({
+ ...await real<object>(),
+ resolvePaneEngineProcess: vi.fn(async () => null),
+ clearPaneRemainOnExit: vi.fn(async () => {}),
+ tmuxPaneState: vi.fn(async () => ({ dead: false, engineExit: null })),
+}))
+vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), commandAvailableInInteractiveShell: vi.fn(async () => true) }))
+
+const pending = { agentId: 'a1', sessionId: '', engine: 'claude' } as RegisteredSession
+const runtime = { backend: 'tmux', paneId: '%7' }
+const spawned = { runtime } as never
+const identity = { pid: 99, startMarker: 'now' }
+
+function setup(over: Partial<PaneWatcherDeps> = {}) {
+ const rows = new Map<string, RegisteredSession>([['a1', pending]])
+ const deps: PaneWatcherDeps = {
+ registry: {
+ byAgent: vi.fn((agentId: string) => rows.get(agentId)),
+ updateProcessIdentity: vi.fn(),
+ setLaunch: vi.fn((_agentId: string, launch: { state: string }) => ({ ...pending, launch }) as RegisteredSession),
+ setTerminalAvailable: vi.fn(() => true),
+ releaseEngine: vi.fn(() => ({ ...pending, engine: 'terminal' }) as RegisteredSession),
+ } as unknown as PaneWatcherDeps['registry'],
+ announceSession: vi.fn(),
+ triggerHint: vi.fn(async () => {}),
+ captureTerminal: vi.fn(async () => 'error: unknown flag --plan'),
+ retainExitedSession: vi.fn(),
+ ...over,
+ }
+ return { deps, rows, watch: createPaneWatcher(deps) }
+}
+
+describe('watching a new pane', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(resolvePaneEngineProcess).mockReset().mockResolvedValue(null)
+ vi.mocked(tmuxPaneState).mockReset().mockResolvedValue({ dead: false, engineExit: null } as never)
+ vi.mocked(clearPaneRemainOnExit).mockClear()
+ vi.mocked(commandAvailableInInteractiveShell).mockReset().mockResolvedValue(true)
+ })
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
+
+ it('marks the agent ready once its engine process shows up, and asks discovery to bind it', async () => {
+ const { deps, watch } = setup()
+ vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(null).mockResolvedValueOnce(identity as never)
+ const done = watch('claude', pending, spawned, ['claude'], undefined)
+ await vi.advanceTimersByTimeAsync(50)
+ await done
+ expect(deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', identity)
+ expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', { state: 'ready' })
+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%7')
+ expect(deps.announceSession).toHaveBeenCalledWith(expect.objectContaining({ launch: { state: 'ready' } }))
+ expect(deps.triggerHint).toHaveBeenCalledWith(runtime, 'claude')
+ })
+
+ it('says so when the background bind fails, and announces nothing for a row the registry no longer has', async () => {
+ const warn = vi.mocked(console.warn)
+ const { deps, watch } = setup({ triggerHint: vi.fn(async () => { throw new Error('scan failed') }) })
+ vi.mocked(deps.registry.setLaunch).mockReturnValueOnce(null)
+ vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(identity as never)
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(deps.announceSession).not.toHaveBeenCalled()
+ const worse = setup({ triggerHint: vi.fn(async () => { throw 'worse' }) })
+ vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(identity as never)
+ await worse.watch('claude', pending, spawned, ['claude'], undefined)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(warn.mock.calls.map(([line]) => String(line)).filter((line) => line.includes('background bind failed'))).toEqual([
+ '[agent] background bind failed · claude · scan failed',
+ '[agent] background bind failed · claude · worse',
+ ])
+ })
+
+ it('stops watching an agent that was removed meanwhile', async () => {
+ const { deps, rows, watch } = setup()
+ rows.clear()
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ expect(resolvePaneEngineProcess).not.toHaveBeenCalled()
+ expect(deps.announceSession).not.toHaveBeenCalled()
+ })
+
+ it('marks the terminal unavailable when the pane is gone', async () => {
+ const { deps, watch } = setup()
+ vi.mocked(tmuxPaneState).mockResolvedValueOnce(null)
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ expect(deps.registry.setTerminalAvailable).toHaveBeenCalledWith('a1', false)
+ expect(deps.announceSession).toHaveBeenCalledWith(pending)
+ })
+
+ it('fails a launch whose pane died: not installed, or did not start', async () => {
+ const { deps, watch } = setup()
+ vi.mocked(tmuxPaneState).mockResolvedValue({ dead: true, engineExit: null } as never)
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ vi.mocked(commandAvailableInInteractiveShell).mockResolvedValueOnce(false)
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ expect(vi.mocked(deps.registry.setLaunch).mock.calls.map(([, launch]) => (launch as { error: string }).error)).toEqual(['ENGINE_DID_NOT_START', 'ENGINE_NOT_INSTALLED'])
+ expect(deps.announceSession).toHaveBeenCalledTimes(2)
+ vi.mocked(deps.registry.setLaunch).mockReturnValueOnce(null)
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ expect(deps.announceSession).toHaveBeenCalledTimes(2)
+ })
+
+ it('keeps a pane whose engine started and exited before it was seen as a terminal, saying why', async () => {
+ const warn = vi.mocked(console.warn)
+ const { deps, rows, watch } = setup()
+ vi.mocked(tmuxPaneState).mockResolvedValue({ dead: false, engineExit: 2 } as never)
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ expect(deps.registry.releaseEngine).toHaveBeenCalledWith('a1')
+ expect(deps.announceSession).toHaveBeenCalledWith(expect.objectContaining({ engine: 'terminal' }))
+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%7')
+ expect(warn.mock.calls.map(([line]) => String(line)).some((line) => line.includes('exited (2) before ready · agent a1 kept as a terminal'))).toBe(true)
+ // A hook bound a conversation meanwhile: that conversation is kept, the engine not released.
+ rows.set('a1', { ...pending, sessionId: 's1' } as RegisteredSession)
+ vi.mocked(deps.captureTerminal).mockResolvedValueOnce(null)
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ expect(deps.retainExitedSession).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 's1' }), true)
+ expect(deps.registry.releaseEngine).toHaveBeenCalledTimes(1)
+ // Released into nothing: nothing to announce.
+ rows.set('a1', pending)
+ vi.mocked(deps.registry.releaseEngine).mockReturnValueOnce(null)
+ vi.mocked(deps.announceSession).mockClear()
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ expect(deps.announceSession).not.toHaveBeenCalled()
+ })
+
+ it('backs off between looks, and gives up on a start that never shows, keeping the terminal', async () => {
+ const warn = vi.mocked(console.warn)
+ const { deps, watch } = setup()
+ const done = watch('claude', pending, spawned, ['claude'], undefined, 3_000)
+ await vi.advanceTimersByTimeAsync(3_000)
+ await done
+ // 50, 100, 200, 400, then every 750 ms.
+ expect(vi.mocked(resolvePaneEngineProcess).mock.calls.length).toBeGreaterThanOrEqual(6)
+ expect(vi.mocked(resolvePaneEngineProcess).mock.calls.length).toBeLessThanOrEqual(8)
+ expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', { state: 'failed', error: 'START_TIMEOUT', detail: expect.stringContaining('did not expose an engine process') })
+ expect(deps.announceSession).toHaveBeenCalled()
+ expect(warn.mock.calls.map(([line]) => String(line))).toContain('[agent] create timed out · claude · agent a1')
+ vi.mocked(deps.registry.setLaunch).mockReturnValueOnce(null)
+ vi.mocked(deps.announceSession).mockClear()
+ await watch('claude', pending, spawned, ['claude'], undefined, 0)
+ expect(deps.announceSession).not.toHaveBeenCalled()
+ })
+
+ it('reports a watch that fails', async () => {
+ const warn = vi.mocked(console.warn)
+ const { watch } = setup()
+ vi.mocked(resolvePaneEngineProcess).mockRejectedValueOnce(new Error('ps failed')).mockRejectedValueOnce('worse')
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ await watch('claude', pending, spawned, ['claude'], undefined)
+ expect(warn.mock.calls.map(([line]) => String(line))).toEqual([
+ '[agent] create watch failed · claude · ps failed',
+ '[agent] create watch failed · claude · worse',
+ ])
+ })
+})
diff --git a/cli/src/core/agents/newPane.ts b/cli/src/core/agents/newPane.ts
new file mode 100644
index 000000000..da52cd8ae
--- /dev/null
+++ b/cli/src/core/agents/newPane.ts
@@ -0,0 +1,119 @@
+/**
+ * The new-pane watcher: after create or fork opens a pane, watch it until its engine process shows up
+ * (ready), the pane dies (failed: not installed, or did not start), the engine starts and exits before
+ * it was ever seen (the pane is kept as a terminal, with the engine's words on screen), or the budget
+ * runs out (failed: start timeout; the terminal stays).
+ *
+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).
+ */
+import type { AgentEngine } from '../../engines/types.js'
+import { describeAgentCreateFailure, summarizePaneOutput } from '../../lib/agentCreateDiagnosis.js'
+import type { engineInstallRecipe } from '../../lib/engineInstall.js'
+import { commandAvailableInInteractiveShell } from '../../lib/engineLaunch.js'
+import { sid } from '../../lib/log.js'
+import type { registry, RegisteredSession } from '../../lib/registry.js'
+import type { TerminalRuntimeRef, TmuxRuntimeRef } from '../../lib/terminalTypes.js'
+import { clearPaneRemainOnExit, resolvePaneEngineProcess, tmuxPaneState } from '../../lib/tmux.js'
+
+export interface PaneWatcherDeps {
+ registry: Pick<typeof registry, 'byAgent' | 'updateProcessIdentity' | 'setLaunch' | 'setTerminalAvailable' | 'releaseEngine'>
+ announceSession: (session: RegisteredSession) => void
+ /** Ask the reconciler to bind what now runs in a pane (TerminalAgentReconciler.triggerHint). */
+ triggerHint: (runtime: TerminalRuntimeRef, engine: AgentEngine) => Promise<void>
+ captureTerminal: (target: string, historyLines?: number) => Promise<string | null>
+ retainExitedSession: (session: RegisteredSession, announce: boolean) => void
+}
+
+export function createPaneWatcher({ registry, announceSession, triggerHint, captureTerminal, retainExitedSession }: PaneWatcherDeps) {
+ /**
+ * Watch a pane this daemon just opened until its engine process shows up (ready), dies (failed), or
+ * ten minutes pass. Shared by create and fork: the two open panes the same way and wait the same way.
+ */
+ const watchNewPane = async (engine: AgentEngine, pending: RegisteredSession, spawned: { runtime: TmuxRuntimeRef }, command: string[], installIfMissing: ReturnType<typeof engineInstallRecipe> | undefined, budgetMs = 10 * 60_000): Promise<void> => {
+ const startedAt = Date.now()
+ let delayMs = 50
+ try {
+ while (Date.now() - startedAt < budgetMs) {
+ if (!registry.byAgent(pending.agentId)) return
+ const processIdentity = await resolvePaneEngineProcess(spawned.runtime.paneId, engine)
+ if (processIdentity) {
+ registry.updateProcessIdentity(pending.agentId, processIdentity)
+ const ready = registry.setLaunch(pending.agentId, { state: 'ready' })
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ if (ready) announceSession(ready)
+ void triggerHint(spawned.runtime, engine).catch((error) => {
+ console.warn(`[agent] background bind failed · ${engine} · ${error instanceof Error ? error.message : error}`)
+ })
+ console.log(`[agent] create ready · ${engine} · agent ${pending.agentId} · ${Date.now() - startedAt}ms`)
+ return
+ }
+ const paneState = await tmuxPaneState(spawned.runtime.paneId)
+ if (!paneState) {
+ registry.setTerminalAvailable(pending.agentId, false)
+ announceSession(pending)
+ return
+ }
+ if (paneState.dead) {
+ const installed = await commandAvailableInInteractiveShell(command[0], undefined, installIfMissing)
+ const error = installed ? 'ENGINE_DID_NOT_START' : 'ENGINE_NOT_INSTALLED'
+ const detail = installed
+ ? `${engine} exited before its engine process became ready. See the terminal output for details.`
+ : `${engine} is not installed, or its automatic install failed. See the terminal output for details.`
+ const failed = registry.setLaunch(pending.agentId, { state: 'failed', error, detail })
+ if (failed) announceSession(failed)
+ console.warn(`[agent] create failed · ${engine} · ${detail}`)
+ return
+ }
+ // The engine started and was gone again before it was ever seen (a flag it refused, a
+ // config it could not read): its wrapper has handed the pane to a shell with the engine's
+ // own words on screen. That pane is a terminal, and the row says so — the person reads
+ // the error where it was printed and types the command again, rather than being handed a
+ // "Start failed" tile they cannot type into.
+ if (paneState.engineExit !== null) {
+ // Say what happened before the evidence goes. The pane is about to become an ordinary
+ // terminal and `releaseEngine` rewrites the launch to `ready`, so after this point nothing
+ // anywhere — frame, registry, archive — records that an engine was ever meant to be here
+ // or why it left. openharness#285 was exactly this: opencode printed its help over a flag
+ // it did not know, and the only trace was one line saying the pane had become a terminal.
+ // `describeAgentCreateFailure` was written for this and had no caller.
+ // `dead: true` describes the ENGINE, which is what the diagnosis is about, not the pane —
+ // the pane is alive and about to become a terminal. That is the sentence this state
+ // selects ("started and exited with status N"), and it is the true one here.
+ const captured = await captureTerminal(pending.agentId, 40)
+ console.warn(`[agent] create · ${engine} · agent ${sid(pending.agentId)} · `
+ + describeAgentCreateFailure({
+ state: { dead: true, exitStatus: paneState.engineExit, command: engine },
+ output: summarizePaneOutput(captured ?? ''),
+ engineBin: command[0],
+ shellName: null,
+ processes: [],
+ elapsedMs: Date.now() - startedAt,
+ }))
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ // A hook may have bound a conversation while this watcher was awaiting its probe.
+ // Archive the current row, not the pre-hook pending snapshot.
+ const row = registry.byAgent(pending.agentId)
+ if (row?.sessionId) retainExitedSession(row, true)
+ else {
+ const released = registry.releaseEngine(pending.agentId)
+ if (released) announceSession(released)
+ }
+ console.warn(`[agent] create · ${engine} exited (${paneState.engineExit}) before ready · agent ${pending.agentId} kept as a terminal`)
+ return
+ }
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, delayMs)
+ timer.unref?.()
+ })
+ delayMs = Math.min(delayMs * 2, 750)
+ }
+ const detail = `${engine} did not expose an engine process within ${Math.round(budgetMs / 60_000)} minutes. The terminal remains available.`
+ const failed = registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT', detail })
+ if (failed) announceSession(failed)
+ console.warn(`[agent] create timed out · ${engine} · agent ${pending.agentId}`)
+ } catch (error) {
+ console.warn(`[agent] create watch failed · ${engine} · ${error instanceof Error ? error.message : error}`)
+ }
+ }
+ return watchNewPane
+}