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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Core boundary, part 6: restart, retarget, stop, purge, resume and close become modules (#727)
Dee7996caa31596
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 9c2734d75..dd0336cda 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1,6 +1,6 @@#!/usr/bin/env nodeimport './config/loadEnv.js'-import { MODEL_MANAGER_ID, ensureBundledCoreHarnesses } from './dsh/builtins.js'+import { ensureBundledCoreHarnesses } from './dsh/builtins.js'import { runDevicesCommand } from './devices/client.js'import { createDeviceStore, deviceStoreAgents } from './lib/autonomous-device/storeRuntime.js'import { mutateDsh } from './dsh/service.js'@@ -27,17 +27,15 @@ import { AutonomousDeviceDirect } from './lib/autonomous-device/direct.js'*/import { readFileSync, readdirSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, statSync, renameSync } from 'fs'-import { dirname, join, resolve } from 'path'+import { join, resolve } from 'path'import { fileURLToPath } from 'url'-import { execFile as execFileCb, spawn } from 'child_process'+import { spawn } from 'child_process'import { createServer, type Server } from 'http'import { createInterface, emitKeypressEvents } from 'readline'import { homedir, hostname } from 'os'import { env } from './config/env.js'import { VERSION } from './version.js'import { sqlitePreflightMessage } from './lib/sqliteAvailability.js'-import { AttachTracker } from './lib/attachTracker.js'-import { binaryOnPath } from './lib/binaryOnPath.js'import { warmLoginShellEnvironment } from './lib/loginShellEnv.js'import { ensureUtf8Locale } from './lib/childLocale.js'import { DialLog } from './cable/dialLog.js'@@ -77,78 +75,57 @@ import { ensureHarnessGrid, type EnsureStatus } from './lib/gridEnsure.js'import { passThroughToGridLogout } from './lib/gridLogout.js'import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'import { warnIfGridSignInRemains } from './lib/gridCredentials.js'-import { reconcileGridAttach, gridNamesLocal, createGridAccess, setUpWithin } from './lib/gridAttach.js'+import { reconcileGridAttach, gridNamesLocal, createGridAccess } from './lib/gridAttach.js'import { signedInGridEmail, resetGridDeriveMemo } from './lib/gridDerive.js'import { forgetGridModels, gridAnnotation, keystrokePrewarm, observeMachineList, onGridModelsChanged, warmGridModels } from './lib/gridModels.js'import { gridAvailable, managedGridPath } from './lib/gridExec.js'-import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'-import { isTerminalEngine, type AgentEngine } from './engines/types.js'-import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from './lib/harnessDefaults.js'-import { probeEngines } from './lib/engineProbe.js'-import { randomUUID } from 'node:crypto'+import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, enginePathOverride } from './lib/engineBin.js'+import { isTerminalEngine } from './engines/types.js'import { engineInstallRecipe } from './lib/engineInstall.js'-import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, dropPermissionFlagIfUnsupported, namedAgentArgs, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'+import { buildEngineLaunchArgv } from './lib/engineLaunch.js'import { workspaceMissing } from './lib/workspaceCheck.js'-import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, isApiLaunch, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'+import { type GridLaunchMachine } from './lib/gridLaunch.js'import { HERMES_SYSTEM_MANAGED_DIR } from './lib/gridWebMcp.js'import { writeGridConfigDir } from './lib/gridConfigDir.js'-import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'+import { tmuxSupportsSessionEnv } from './lib/tmuxVersion.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'-import { terminateDeletedAgent, checkPidRuntime } from './lib/deleteAgentFallback.js'-import { AgentRestartCoordinator, bypassPermissionFor, restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'-import { claudeContinuation, claudeProcessSession, findLiveSession, findResumedTranscript } from './lib/sessionRepair.js'+import { claudeProcessSession, findLiveSession, findResumedTranscript } from './lib/sessionRepair.js'import { handoffProviderDeps } from './lib/handoffDiscovery.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from './lib/hostTheme.js'-import { describeAgentCreateFailure, summarizePaneOutput } from './lib/agentCreateDiagnosis.js'-import { createAndRegisterPane } from './lib/createAgentPane.js'-import { forkName, planFork } from './lib/forkAgent.js'import { restoreAgents } from './lib/restoreAgents.js'import { createRetainExitedSession } from './lib/retainExitedSession.js'-import { createSessionSync } from './lib/sessionSync.js'-import { CloseAgentService, inspectCloseActivity } from './lib/closeAgentService.js'import { OpenTabProtection } from './lib/openTabProtection.js'-import { PurgeAgentService } from './lib/purgeAgentService.js'import { sessionCheckpoints } from './lib/sessionCheckpoint.js'import { repairClaudeCwd } from './lib/cwdRepair.js'import { stoppedAgents } from './lib/stoppedAgents.js'import { prepareAgentHandoff } from './lib/agentHandoff.js'import { SessionSearchIndex, folderWords, type SearchSource } from './lib/sessionSearch/indexer.js'-import { ExternalSessions, OpenSessions, processAlive, stopSessionOwner, type SessionOwner } from './lib/sessionSearch/external.js'+import { ExternalSessions, OpenSessions } from './lib/sessionSearch/external.js'import { externalProviders } from './lib/sessionSearch/externals/index.js'-import { engineLabel } from './lib/agentNames.js'import { SessionSearchStore } from './lib/sessionSearch/store.js'import { SESSION_SEARCH_FILE, searchCommand } from './lib/sessionSearch/command.js'import { sweepWorktrees } from './lib/worktreeSweep.js'import { nameBranchAfterSession } from './lib/branchNaming.js'import { forgetAgentProject } from './lib/agentProject.js'-import { createStopAgentService } from './lib/stopAgentService.js'-import { createResumeAgentService } from './lib/resumeAgentService.js'-import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'-import { prepareCodexResume } from './engines/codex/portableHistory.js'+import { type LaunchOverridesDeps } from './lib/launchOverrides.js'import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'import { adoptLegacyHarnessSessions, listTmuxPanes } from './lib/tmuxAgentDiscovery.js'import { installedDsh } from './dsh/installed.js'-import { dshPinnedPermissionMode, dshVerdictPath, dshViewerName } from './dsh/manifest.js'+import { dshVerdictPath, dshViewerName } from './dsh/manifest.js'import { catalogEntry } from './dsh/catalog.js'import { removeDsh } from './dsh/install.js'-import { preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'-import { materializeWorkspace } from './dsh/materialize.js'-import { harnessEnvToClear, type DshAccount } from './dsh/launch.js'-import { forkRuntimeKey, harnessLaunchOrRefusal, incompatibleHarnessEngine, prepareHarnessLaunch } from './dsh/runtime.js'+import { prepareHarnessLaunch } from './dsh/runtime.js'import { DshViewerManager } from './dsh/viewer.js'import { ViewerLedger } from './dsh/viewerLedger.js'import { DshVerdictWatcher, type DshVerdict } from './dsh/verdict.js'import { dshCommand, dshUsage } from './dsh/command.js'-import { ApiConnectionError, ApiConnections } from './lib/apiConnections.js'-import { refreshApiLaunch, rememberSavedApis } from './lib/apiModels.js'+import { ApiConnections } from './lib/apiConnections.js'+import { rememberSavedApis } from './lib/apiModels.js'import { apiCommand, apiUsage } from './lib/apiCommand.js'import { prepareApiInstructions } from './lib/apiInstructions.js'import type { AgentDshContext } from './lib/agentFrame.js'-import { basename } from 'node:path'import {- bypassPermissionActive,- permissionModeFromArgv,clearPaneRemainOnExit,resolvePaneEngineProcess,tmuxPaneState,@@ -156,21 +133,18 @@ import {import { ALL_TERMINAL_BACKENDS } from './config/terminalConfig.js'import { TerminalBackendCoordinator } from './lib/terminalBackendCoordinator.js'import { TerminalStreamManager } from './lib/terminalStreamManager.js'-import { processIdentityKey, terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'+import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'-import { processRows, type DiscoveredTerminalAgent } from './lib/terminalAgentDiscovery.js'+import { processRows } from './lib/terminalAgentDiscovery.js'import { remoteCommand } from './remoteCommand.js'import { tuiCommand } from './tui/index.js'import { newCommand } from './lib/newCommand.js'import { gridSetupCommand } from './lib/gridSetupCommand.js'import { WebSocket as NewCommandSocket } from 'ws'import {- terminalActionNotStarted,- type TerminalActionResult,type TerminalRuntimeRef,- type TmuxRuntimeRef,} from './lib/terminalTypes.js'-import { Watcher, type HistoryEvent, type LineEvent, type RewrittenEvent, type TailHold } from './watcher/watcher.js'+import { Watcher } from './watcher/watcher.js'import { chooseHookAgent, startHookServer } from './hookServer.js'import { connectToMaster } from './harnessd/coreLink.js'import { createTerminalControl } from './core/terminals/control.js'@@ -196,6 +170,11 @@ 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 { createPaneSwap } from './core/agents/swap.js'+import { createAgentRetargeter } from './core/agents/retarget.js'+import { createAgentRestarter } from './core/agents/restart.js'+import { createAgentLifecycle } from './core/agents/lifecycle.js'+import { createAgentClosing } from './core/agents/close.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'@@ -212,18 +191,9 @@ import { WindowVisit } from './cable/windowVisit.js'import { WindowForm } from './cable/windowForm.js'import { RemoteRelayPool } from './lib/remoteRelay.js'import { TERMINAL_BINARY_VERSION } from './lib/terminalBinary.js'-import { foldTranscript, lastTurnTextFromRawLines, lineToEvents, newTurnState, selectClaudeRecapLine, TranscriptFold, type LiveEvent, type TurnState } from './lib/normalize.js'-import { attachTranscript, claudeAttachRules, codexAttachRules, type AttachRead } from './lib/attachTranscript.js'-import { tailFileUntil } from './lib/transcriptTail.js'-import { AskQuestionController, parseEngineQuestionPane, pollsQuestions, QuestionWatcher } from './lib/askQuestion.js'-import { teamWriteHold } from './teams/preflight.js'+import { type LiveEvent } from './lib/normalize.js'import { TeamError } from './teams/model.js'-import { CommanderMirror, SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from './lib/commander.js'-import { AgentNotifications } from './lib/agentNotifications.js'-import { deriveTurnSummary } from './lib/deviceRecap.js'-import type { CableAgent } from './cable/cableSession.js'import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'-import { tailFile } from './lib/sessions.js'import { E2eeStore, identitySpent, peekIdentityPub } from './lib/e2ee/store.js'import { confirmsRemoval, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceHistory, formatDeviceList, logOrder, removeConfirmation } from './lib/e2ee/deviceDisplay.js'import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'@@ -244,64 +214,38 @@ import { managedNodePath } from './lib/nodeRuntime.js'import { updateManagedTui } from './tui/manage.js'import { startTuiUpdater } from './tui/update.js'import { ensureHnLauncher, ensureLauncher, ensureManagedGrid, ensureManagedRuntime, startGridPinRecheck } from './lib/runtimeInstall.js'-import { readdir, stat } from 'fs/promises'-import { CodexNormalizer, codexTaskError } from './engines/codex/normalizer.js'-import { readLastCodexTurnText } from './engines/codex/lastTurn.js'-import { TurnActivity, type ActivityFrame } from './lib/turnActivity.js'-import { CodexActivityReader, RuntimeActivityReader, activityRuntimeKey } from './lib/runtimeActivity.js'-import { codexSubagentResolverFor } from './engines/codex/subagent.js'-import { CursorNormalizer, lastCursorTurnText } from './engines/cursor/normalizer.js'-import { CursorTranscriptDiscovery, findCursorTranscript } from './engines/cursor/discovery.js'+import { type ActivityFrame } from './lib/turnActivity.js'+import { CursorNormalizer } from './engines/cursor/normalizer.js'+import { CursorTranscriptDiscovery } from './engines/cursor/discovery.js'import { cursorConfigDir, cursorDataDir } from './engines/cursor/home.js'import { CursorSubagentManager } from './engines/cursor/subagent.js'import { CursorTaskHookQueue } from './engines/cursor/taskHookQueue.js'-import { loadCursorPendingTasks, removeCursorPendingTasks } from './engines/cursor/pendingTasks.js'-import { OpencodeReader, readOpencodeMessages } from './engines/opencode/reader.js'-import { applyOpencodeSessionModel, parseOpencodeModelId } from './engines/opencode/sessionModel.js'-import { isOpencodeV2, opencodeMajorVersion } from './engines/opencode/version.js'-import { lastOpencodeTurnText, opencodeMessagesToEvents } from './engines/opencode/normalizer.js'-import { KiloReader, readKiloMessages } from './engines/kilo/reader.js'-import { kiloMessagesToEvents, lastKiloTurnText } from './engines/kilo/normalizer.js'-import { MuseNormalizer, lastMuseTurnText, museMessagesToEvents } from './engines/muse/normalizer.js'-import { AmpNormalizer, lastAmpTurnText, ampMessagesToEvents } from './engines/amp/normalizer.js'-import { GrokNormalizer, lastGrokTurnText } from './engines/grok/normalizer.js'-import { findGrokTranscript } from './engines/grok/session.js'-import { AgyNormalizer, lastAgyTurnText } from './engines/agy/normalizer.js'-import { findAgyTranscript } from './engines/agy/session.js'-import { agyPaneIdle } from './engines/agy/runtimeProfile.js'-import { CopilotNormalizer, copilotHistoryTurnOpen, lastCopilotTurnText } from './engines/copilot/normalizer.js'-import { copilotSessionForPid, findCopilotTranscript } from './engines/copilot/session.js'-import { PiNormalizer, lastPiTurnText } from './engines/pi/normalizer.js'-import { HermesReader, readHermesMessages } from './engines/hermes/reader.js'+import { loadCursorPendingTasks } from './engines/cursor/pendingTasks.js'+import { readOpencodeMessages } from './engines/opencode/reader.js'+import { opencodeMajorVersion } from './engines/opencode/version.js'+import { opencodeMessagesToEvents } from './engines/opencode/normalizer.js'+import { readKiloMessages } from './engines/kilo/reader.js'+import { kiloMessagesToEvents } from './engines/kilo/normalizer.js'+import { readHermesMessages } from './engines/hermes/reader.js'import { hermesDbForSession } from './lib/hermesHome.js'-import { DevinReader, readDevinMessages } from './engines/devin/reader.js'-import { hermesMessagesToEvents, lastHermesTurnText } from './engines/hermes/normalizer.js'-import { devinMessagesToEvents, lastDevinTurnText } from './engines/devin/normalizer.js'-import {- CommandCodeNormalizer,- commandCodeRunError,- commandCodeRunErrorSummary,- lastCommandCodeTurnText,-} from './engines/commandcode/normalizer.js'-import { probeGatewayRuntime } from './lib/gatewayRuntime.js'-import { probeGridAssignment, sameGridAssignment } from './lib/gridAssignment.js'+import { readDevinMessages } from './engines/devin/reader.js'+import { hermesMessagesToEvents } from './engines/hermes/normalizer.js'+import { devinMessagesToEvents } from './engines/devin/normalizer.js'import { agentFrame, lastActivityAt, type AgentFrame } from './lib/agentFrame.js'import { agentTokenUsage } from './lib/agentTokenUsage.js'-import { SessionInputController } from './lib/sessionInput.js'import { DeviceResultJournal } from './lib/autonomous-device/resultJournal.js'-import { AutonomousDeviceInput, isDeviceInputBoundary } from './lib/autonomous-device/input.js'import { adaptSlashCommand } from './lib/goalCommand.js'-import { RuntimeProfileManager, parseRuntimeProfile, type RuntimeField } from './lib/runtimeProfile.js'-import { RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'-import { deviceErrorText } from './lib/deviceErrors.js'-import { correlateAgentEvent, turnHeartbeatFrame } from './lib/agentEvent.js'-import { transcriptIsFirstTurn } from './lib/firstTurnReplay.js'+import { RuntimeProfileManager } from './lib/runtimeProfile.js'+import { RuntimeProfileController } from './lib/runtimeProfileController.js'// Before ANY child is spawned: on Linux an absent locale makes tmux and ps mangle their output,// which silently costs the daemon every pane it would have discovered. See lib/childLocale.ts.ensureUtf8Locale()import {- installTimestampedConsole, sid, preview,- prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS,+ installTimestampedConsole,+ sid,+ prepareLogFile,+ trimLogFile,+ LOG_CHECK_INTERVAL_MS,} from './lib/log.js'@@ -1793,13 +1737,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Reading and writing panes through control leases (core/terminals/control.ts).const terminalControl = createTerminalControl({ resolve: (target) => registry.resolve(target), terminals })const pinnedControls = terminalControl.pinnedControls- const pinTerminalControl = terminalControl.pinTerminalControlconst invalidateTerminalControl = terminalControl.invalidateTerminalControlconst captureTerminal = terminalControl.captureTerminal- const submitTerminalAction = terminalControl.submitTerminalActionconst submitTerminal = terminalControl.submitTerminalconst typeTerminal = terminalControl.typeTerminal- const keyTerminalAction = terminalControl.keyTerminalActionconst keyTerminal = terminalControl.keyTerminalconst validateTerminal = terminalControl.validateTerminal// Persisted records are not trusted blindly. The process reconciler below adopts a matching live@@ -2142,19 +2083,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Each session's engine state, in one table (core/transcripts/normalizers.ts).const normalizers = createSessionNormalizers()- const turnStates = normalizers.turnStates- const codexNormalizers = normalizers.codexNormalizersconst cursorNormalizers = normalizers.cursorNormalizers- const opencodeReaders = normalizers.opencodeReaders- const kiloReaders = normalizers.kiloReaders- const piNormalizers = normalizers.piNormalizers- const museNormalizers = normalizers.museNormalizers- const ampNormalizers = normalizers.ampNormalizers- const grokNormalizers = normalizers.grokNormalizersconst agyNormalizers = normalizers.agyNormalizers- const copilotNormalizers = normalizers.copilotNormalizers- const hermesReaders = normalizers.hermesReaders- const devinReaders = normalizers.devinReadersconst commandcodeNormalizers = normalizers.commandcodeNormalizersconst sessionTurnState = normalizers.sessionTurnStateconst sessionTurnOpen = normalizers.sessionTurnOpen@@ -3875,489 +3805,97 @@ async function runForeground(session: AuthSession | null): Promise<void> {gridName: () => backend.gridName(),})- /**- * The dependencies a pane-process swap needs, for both callers that do one.- *- * Restart and retarget are the same mechanism pointed at different ends: kill the engine, respawn it- * in the pane it was already in, wait for the new process. They differ only in what the replacement- * is launched WITH — retarget adds the grid's environment and the argv that configures it — so that- * is the only thing this takes. Written once because two copies of a kill sequence drift, and the- * half that drifts is the half nobody ran today.- */- const restartJobs = new AgentRestartCoordinator()- const sameRestartTarget = (session: RegisteredSession): boolean => {- const current = registry.byAgent(session.agentId)- return !!current && current.registeredAt === session.registeredAt- && current.tmuxPane === session.tmuxPane && current.engine === session.engine- }-- const paneSwapDeps = (- session: RegisteredSession,- runtime: TmuxRuntimeRef,- launch: { env?: Record<string, string>; extraArgs?: readonly string[]; clearEnv?: readonly string[] } = {},- /** The mode this swap may actually ask for — the row's own, unless the engine on disk has since- * stopped taking its flag and the caller dropped it (`dropPermissionFlagIfUnsupported`). */- permissionMode: string | null = session.permissionMode ?? null,- ): RestartAgentDeps => ({- prepareResume: () => prepareSessionResume(session),- holdOpen: async () => {- const result = await tmuxBackend!.holdOpen(runtime)- return result.state === 'succeeded'- ? { ok: true }- : { ok: false, reason: 'reason' in result ? result.reason : 'could not re-arm remain-on-exit' }- },- terminate: (checkAfterMs) => terminateDeletedAgent(session, {- checkRuntime: checkPidRuntime,- kill: (pid, signal) => process.kill(pid, signal),- sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),- log: (message) => console.log(message),- }, checkAfterMs),- respawn: async (argv) => {- const result = await tmuxBackend!.respawn(runtime, {- command: argv,- cwd: homedir(),- ...(launch.env ? { env: launch.env } : {}),- })- return result.state === 'succeeded'- ? { ok: true }- : { ok: false, reason: 'reason' in result ? result.reason : 'tmux respawn-pane did not complete' }- },- waitForProcess: async () => {- // Mirrors onCreateAgent's own discovery budget/backoff shape for the same reason: the engine's- // interactive-login-shell startup, not the tmux call, is the slow half.- const SWAP_DISCOVERY_BUDGET_MS = 8_000- let delayMs = 150- let waited = 0- while (waited < SWAP_DISCOVERY_BUDGET_MS) {- await new Promise((resolve) => setTimeout(resolve, delayMs))- waited += delayMs- const found = await resolvePaneEngineProcess(runtime.paneId, session.engine)- if (found) return found- delayMs = Math.min(delayMs * 2, 750)- }- return null- },- buildArgv: (opts) => buildEngineLaunchArgv(session.engine, {- ...opts,- // The mode picked at create outranks what the live argv said: `bypassPermission` is a yes/no, and- // Plan or Accept edits would come back as Ask without it.- ...(permissionMode ? { permissionMode } : {}),- ...(session.cwd ? { cwd: session.cwd } : {}),- ...(launch.extraArgs?.length ? { extraArgs: launch.extraArgs } : {}),- // A pane swap onto a grid has to clear the same vendor credentials a fresh create does, for the- // same reason and against the same failure: an engine re-exec'd with the grid's variables still- // sees whatever else the pane inherited, and picks its provider from all of it. This was the- // gap — a create cleared them, then moving that agent onto a grid from the pane header put them- // straight back, so the engine came up on Anthropic with a grid selected above it.- //- // Named by the caller (`buildLaunchOverrides` derives it from what the grid launch provides), so- // a swap that sets no grid — back to the engine's own login, or a Codex profile's CODEX_HOME —- // clears nothing. There the user's own variables are the point.- ...(launch.clearEnv?.length ? { clearEnv: launch.clearEnv } : {}),- ...(launch.env?.HARNESS_DSH ? { harnessNode: true } : {}),- }),- log: (message) => console.log(message),+ // Swapping a pane's engine process, for restart and retarget (core/agents/swap.ts).+ const paneSwap = createPaneSwap({+ byAgent: (agentId) => registry.byAgent(agentId),+ tmuxBackend,+ prepareSessionResume,+ })+ const restartJobs = paneSwap.restartJobs+ const sameRestartTarget = paneSwap.sameRestartTarget+ const paneSwapDeps = paneSwap.paneSwapDeps+ const liveBypassPermission = paneSwap.liveBypassPermission++ // Moving a running agent onto a grid, or back to its own login (core/agents/retarget.ts).+ backend.onRetargetAgent = createAgentRetargeter({+ purgeBusy: (agentId) => backend.purgeAgentService?.busy(agentId),+ tmuxBackend,+ registry,+ runtimeProfiles,+ launchOverridesDeps,+ captureTerminal,+ acquireTerminalControl,+ relaunchOverrides,+ downgradedPermission,+ agentReconciler,+ restartJobs,+ paneSwapDeps,+ liveBypassPermission,+ announceSession,+ opencodeDb: OPENCODE_DB,})- /** The bypass-permission flag the LIVE process was launched with. The fallback behind- * `bypassPermissionFor` for a row that recorded neither a mode nor the flag (written before either- * was persisted, and not yet seen by a discovery scan); read before anything is signalled. */- const liveBypassPermission = async (session: RegisteredSession): Promise<boolean> => {- const identity = session.processIdentity- if (!identity) return false- const rows = await processRows()- const row = rows?.find((candidate) =>- candidate.pid === identity.pid && candidate.startMarker === identity.startMarker)- return row ? bypassPermissionActive(session.engine, row.args) : false- }-- /**- * Move a RUNNING agent onto a grid (`agent_retarget`).- *- * A process's environment is fixed at `execve`, so there is no way to re-point a live engine short of- * replacing the process. `respawn-pane -k` does exactly that and keeps the pane, which keeps the pane- * id, which keeps the agent's identity, its tile and its scrollback — the user sees their agent- * restart, not a new agent appear. `--resume` brings the conversation back.- *- * Every check below refuses instead of doing something partial, because a half-applied move is- * indistinguishable from a working one until the bill arrives.- */- backend.onRetargetAgent = async ({ agentId, grid }) => {- if (backend.purgeAgentService?.busy(agentId)) return { ok: false, error: 'AGENT_BUSY' }- if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }- const session = registry.resolve(agentId)- if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }- const pane = session.runtimes.find((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')- // Only tmux panes can be respawned. Saying so is better than a generic failure the user cannot act on.- if (!pane) return { ok: false, error: 'RETARGET_UNSUPPORTED_BACKEND', detail: `${session.engine} is not running in a tmux pane` }- // The swap kills a process it has validated by pid + start marker. Without one there is nothing to- // validate, and respawning over a pane whose occupant we cannot identify is how you replace- // something that was not ours.- if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }- // Leaving for a grid is the LAST moment this agent's own model is observable: once the pane is on- // the grid, the engine reports the grid's model and the previous choice exists nowhere. So it is- // read now and kept, and a later move back returns the person to it rather than to whatever- // default the engine would otherwise fall to. Read from the live engine, not from the row.- //- // Coming back reads what was kept. Not cleared on the way home: an agent bounced between a grid- // and its own login should land on the same model every time, not only the first.- // ⚠️ `selectedModel` answers an ENCODED runtime-profile id (`runtime-v1:…`), not a model name —- // handing that to an engine would point it at a model that does not exist. Decode it and take- // the model. For claude the decoded value is already the vendor's alias (`opus`), which is what- // ANTHROPIC_MODEL wants. Null when the daemon has not observed this pane's model yet, which is a- // real answer: there is then nothing to come back to and the engine decides, as it did before.- // ⚠️ The profile's OWN engine has to match, not just the session it was read under. A model is- // only meaningful to the engine that named it — `opencode/big-pickle` handed back as- // ANTHROPIC_MODEL is not a Claude model, and Claude Code says so ("It may not exist or you may- // not have access to it") on a pane the user never chose it for. The keying bug that let one- // agent read another's model is fixed at its source in RuntimeProfileManager; this is the second- // lock, because the cost of being wrong here is a pane that answers on nothing.- const profile = parseRuntimeProfile(runtimeProfiles.selectedModel(session))- const observed = profile && profile.engine === session.engine ? profile.model : null- const remembered = grid- // Two guards, and both come from watching this go wrong:- //- // * Capture only when the agent is on its OWN LOGIN. Moving grid→grid must not overwrite the- // memory with the first grid's model — the subscription choice has not changed, and the- // whole point is to still have it on the way home.- //- // * Never remember the model being moved TO. An engine can keep REPORTING a grid model after- // it has come back (Claude Code restores it from its own session file and says so), so a- // later move to that same grid would otherwise capture the grid's model as the- // "subscription" one and hand it straight back — teaching the bug to itself.- ? (!session.grid && observed !== grid.model ? observed : (session.subscriptionModel ?? null))- : (session.subscriptionModel ?? null)- // What this machine cannot do at all is said first, before the pane is even looked at.- const target: LaunchSource = {- gridLaunch: grid,- codexHome: session.codexHome,- ...(grid ? {} : { subscriptionModel: remembered }),- }- const valid = await validateLaunchOverrides(launchOverridesDeps, session.engine, target)- if (!valid.ok) return { ok: false, error: valid.error, detail: valid.detail }- // A resumed opencode session takes its model from its own rows in opencode.db, not from `-m`- // (see below), and those rows are written through the `sqlite3` CLI. Without it the respawn- // would land the right provider, key and argv on a pane that then answers on the OLD model —- // the failure this handler exists to refuse — so it is refused here, before the pane is touched.- // Only when the launch will name a model: a grid launch always does; a move home does only when- // the remembered model carries its provider (`subscriptionModel.ts`), and otherwise the engine- // decides, as it always did. v2 switches the model through OpenCode's own API instead and needs no- // sqlite3 (`applyOpencodeSessionModel`).- const rewritesOpencodeSession = session.engine === 'opencode' && !!session.sessionId- && (!!grid || !!remembered?.includes('/'))- const opencodeMajor = session.engine === 'opencode' ? opencodeMajorVersion() : null- if (rewritesOpencodeSession && !isOpencodeV2(opencodeMajor) && !binaryOnPath('sqlite3')) {- return {- ok: false,- error: 'OPENCODE_SQLITE_MISSING',- detail: 'the sqlite3 CLI is not on PATH, and a resumed opencode session keeps its model unless its store is rewritten — install sqlite3 and retry',- }- }- // The replacement enters the row's folder before it execs: a folder that is gone is refused here,- // with the other refusals, before the pane is touched or its control taken.- const missing = workspaceMissing(session.cwd)- if (missing) return missing- // Mid-turn is the one state where restarting costs real work: the conversation comes back but- // whatever the engine was doing does not. The app is told which agents these are so the user can- // move them once they are done, rather than being asked to choose between losing a turn and losing- // the grid.- const capture = await captureTerminal(session.agentId, 100)- if (!capture) return { ok: false, error: 'TMUX_FAILED' }- if (!inspectRuntimePane(session.engine, capture).idle) return { ok: false, error: 'AGENT_BUSY' }- // Nothing may type into the pane while it is being replaced.- if (restartJobs.busy(session.agentId)) return { ok: false, error: 'AGENT_BUSY' }- const release = acquireTerminalControl(session.agentId)- if (!release) return { ok: false, error: 'AGENT_BUSY' }- // The grid's env and argv, config directory written (keyed on the agent, so moving it between- // grids rewrites one directory) — or nothing at all for a move back to the engine's own login- // (clearing uses set-environment, which every supported tmux has). Built from the override the- // desktop just sent, never from the row: the row is what this call REPLACES. After the refusal- // guards, so a refused move leaves the live process's own configuration untouched.- const built = await relaunchOverrides(session, target)- if (!built.ok) {- release()- return { ok: false, error: built.error, detail: built.detail }- }-- // ⚠️ THE AGENT MUST ADOPT THE NEW PROCESS, OR IT STOPS BEING THE SAME AGENT.- //- // Identity in this daemon is keyed on the PROCESS, not the pane: the reconciler matches an existing- // record to an observation by pid + start marker (`currentProcessKey`), and its same-pane fallback- // only applies to an agent with no bound engine session. A respawn changes the pid, so left to- // discovery the new process is an unmatched observation — `onDiscovered` mints a NEW agent id, and- // the record the user was looking at becomes a ghost that the app still lists, still counts as "on- // an older target", and still offers to move. Moving it respawns the same pane again. Holding the- // route shuts the reconciler out for the duration; rebinding below is what ends the swap.- const routeKey = terminalRouteKey(pane)- agentReconciler.holdRoute(routeKey)- try {- // Back to the engine's own login. Nothing is built, because there is no launch to build. If this- // agent was launched onto a grid at creation, `new-session -e` wrote the grid's variables into- // the pane's SESSION environment, which a bare respawn-pane would inherit — clearing them first- // is what makes the env-less respawn below actually land on the engine's own login instead of- // silently keeping the old grid. If instead the agent was moved here by an earlier retarget,- // `respawn-pane -e` set those variables on that one process, not the session, so this clear is- // a harmless no-op and it is the env-less respawn itself that drops them. Either way the pane- // ends up clean. Run only after every refusal guard above: an early return with the pane- // already cleared but its live process untouched would leave that process still talking to the- // grid while the retarget reports failed — the exact half-applied state this handler exists to- // refuse.- //- // OpenCode's TUI drops `-m` when it RESUMES a session: it restores the model from the session's- // LAST USER MESSAGE (`data.model`), and its server falls back to the `session.model` column- // (measured on 1.18.31; upstream anomalyco/opencode #26901). Nothing else — config, model.json,- // `--fork` — changes a resumed session's model; the picker is the only writer opencode ships,- // and those two rows are what it writes. So they are written here, through SQL, before the- // respawn, with the exact `provider/model` the respawn's own `-m` names — and the TUI opens- // already on it, with nothing typed into the pane. Before the live process is touched, so a- // write that fails refuses the move with that process still on its old target. A session with- // no user message yet has nothing to restore from and takes `-m` on launch, so it is skipped.- //- // OpenCode 2.0 has no `-m` on its TUI, keeps sessions in tables the SQL above never reads (it- // used to answer SESSION_NOT_FOUND there, read as success, and then respawn with `-m` into- // `Unrecognized flag: -m` and a dead pane), and ships its own writer: the service's- // `session.switchModel`. `applyOpencodeSessionModel` picks per version, and on v2 every- // failure refuses the move — with the live process still untouched.- if (rewritesOpencodeSession) {- const model = built.overrides.sessionModel ? parseOpencodeModelId(built.overrides.sessionModel) : null- if (model) {- const written = await applyOpencodeSessionModel({- opencodeMajor, dbPath: OPENCODE_DB, sessionId: session.sessionId, model, cwd: session.cwd ?? undefined,- // (A model of opencode's own is looked for in its catalogue; a grid's provider lives in- // the pane's own config, which the service never reads.)- checkCatalog: !grid,- })- if (!written.ok) {- console.warn(`[grid] retarget ${sid(session.agentId)} refused · ${written.code} · ${written.detail}`)- return { ok: false, error: written.code, detail: written.detail }- }- }- }- if (!grid) {- const cleared = await tmuxBackend.clearEnv(pane, gridEnvVarNames(session.engine))- if (cleared.state !== 'succeeded') {- return { ok: false, error: 'GRID_CLEAR_FAILED', detail: 'reason' in cleared ? cleared.reason : 'tmux would not clear the pane environment' }- }- }- const retargetPermission = await downgradedPermission(session,- await bypassPermissionFor(session, () => liveBypassPermission(session)), 'retarget')- const outcome = await restartAgent(- { engine: session.engine, sessionId: session.sessionId },- retargetPermission.bypassPermission === true,- paneSwapDeps(session, pane, built.overrides, retargetPermission.permissionMode ?? null),- )- if (!outcome.ok) {- console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${outcome.detail}`)- return { ok: false, error: 'RESPAWN_FAILED', detail: outcome.detail }- }- // Both are read from the one cached environment of the new pid, so this costs no extra `ps`.- const [gateway, assignment] = await Promise.all([- probeGatewayRuntime(outcome.processIdentity),- probeGridAssignment(outcome.processIdentity, session.engine, outcome.processIdentity.executable),- ])- registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)- // The launch that just worked is the one a restart or a post-reboot restore must repeat — and- // what it decided about web search is what the app shows for this agent from now on. Null for- // a move home: the block, and the status with it, leave the frame together.- registry.setGridLaunch(session.agentId, built.overrides.gridLaunchRecord ?? null)- // Persisted only on the way OUT, and only once the move actually succeeded — a refused move- // must not overwrite the model the agent is still sitting on. Survives a daemon restart, so an- // agent left on a grid for a week still knows where it came from.- if (grid && remembered) registry.setSubscriptionModel(session.agentId, remembered)- registry.setActive(session.agentId, true)- await clearPaneRemainOnExit(pane.paneId)- const refreshed = registry.byAgent(session.agentId)- // The app decides whether to still offer a move from what it is told here, so a silent success- // would leave the banner up over an agent that had already been moved.- if (refreshed) announceSession(refreshed)- const how = outcome.resumed ? 'resumed' : 'fresh session'- const record = built.overrides.gridLaunchRecord- const where = record- ? describeGridLaunch(session.engine, record.override, record.webSearch)- : `${session.engine} on its own login`- console.log(`${where} · retargeted ${sid(session.agentId)} · ${how}`)- // Nothing is typed into the pane after the respawn. A resumed opencode session used to be put- // on its model through the `/models` picker here (MODEL_SELECT_FAILED); its store is rewritten- // before the respawn instead, see above.- return { ok: true }- } finally {- release()- agentReconciler.releaseRoute(routeKey)- }- }-- /**- * Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live- * registry entry, and closes only its exact tmux pane. Exact PID/start-marker validation guards the engine's- * SIGTERM/SIGKILL fallback. Engine conversation files, recaps and the Harness name remain on disk.- */- const stopJobs = new Map<string, Promise<void>>()- const stopAgent = createStopAgentService({- registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,- forgetSession, markDeleted, clearDeleted,+ // Stopping, purging and resuming an agent (core/agents/lifecycle.ts).+ const lifecycle = createAgentLifecycle({+ registry,+ stoppedAgents,+ restartJobs,+ tmuxBackend,+ agentReconciler,+ forgetSession,+ markDeleted,+ clearDeleted,+ sessionCheckpoints,+ mirror,+ sessionSearch,+ send: (frame) => backend.send(frame),+ pinnedControls,+ retainExitedSession,+ announceSession,+ relaunchOverrides,+ prepareSessionResume,+ refreshGridWebSearch,+ attachDsh,})+ const stopJobs = lifecycle.stopJobs+ const stopAgent = lifecycle.stopAgentbackend.onDeleteAgent = stopAgent- backend.purgeAgentService = new PurgeAgentService({- live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stoppedAgents.list()],- stopped: stoppedAgents, checkpoints: sessionCheckpoints, stop: stopAgent,- restarting: id => restartJobs.busy(id) || stopJobs.has(id),- deleted: s => {- if (s.sessionId) { mirror.deleteHistory(s.sessionId); sessionSearch?.deleteHistory(s.sessionId) }- registry.deleteSavedNames([s.agentId, s.sessionId].filter(Boolean))- backend.send({ type: 'agent_deleted', payload: { agentId: s.agentId, retained: false } })- },- })- backend.closeAgentService = new CloseAgentService({+ backend.purgeAgentService = lifecycle.purgeAgentService+ // Closing agents no window shows, and the cleanup preview (core/agents/close.ts).+ const closing = createAgentClosing({registry,- openTabs: cleanupTabs,- activity: async s => {- if (s.sessionId) await watcher.pollSession(s.sessionId)- const screen = await captureTerminal(s.agentId, 80)- return inspectCloseActivity(s, screen, sessionTurnState(s.sessionId), openQuestions.has(s.sessionId))- },- checkpoint: async (s, phase) => {- const captured = phase === 'before' ? await terminals.captureRetained(s, { historyLines: 2000 }) : null- await sessionCheckpoints.save(s, { screen: captured?.state === 'succeeded' ? captured.value : null })- },- stop: stopAgent,- changed: announceSession,+ cleanupTabs,+ watcher,+ captureTerminal,+ sessionTurnState,+ openQuestions,+ terminals,+ sessionCheckpoints,+ stopAgent,+ announceSession,})+ backend.closeAgentService = closing.closeAgentServicebackend.closeAgentService.start()- backend.cleanupPreview = async () => {- await cleanupTabs.refresh()- const sessions = registry.advertised()- const agents = []- for (const s of sessions) {- if (!cleanupTabs.isHidden(s)) continue- const target = { agentId: s.agentId, sessionId: s.sessionId, createdAt: new Date(s.registeredAt).toISOString() }- const inspected = await backend.closeAgentService!.request({ ...target, mode: 'inspect' })- if (inspected.error) continue // A changing session is never added to a reviewed batch.- agents.push({ ...target, name: projectDisplayName(s), engine: s.engine, activity: inspected.activity ?? 'unknown' })- }- return { version: 1, agents, kept: sessions.length - agents.length }- }-- const resumeAgent = createResumeAgentService({- registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,- retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,- refreshGridWebSearch, clearDeleted, attachDsh,- })- backend.onResumeAgent = (id, permissionMode) => backend.purgeAgentService?.busy(id) || backend.purgeAgentService?.blocksFolder(stoppedAgents.get(id)?.cwd)- ? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resumeAgent(id, permissionMode)-- /**- * Web or device restarted an agent (`agent_restart`): exit the live engine process and relaunch it in- * the SAME tmux pane, keeping the SAME agentId/session — restart must never look like delete+create to- * the registry or the UI. Two things guard that identity:- *- * - `remain-on-exit` is re-armed on the pane before the old process is killed (mirrors what- * `create()` does at spawn time), or tmux would tear the pane — and with it the whole one-pane- * session — down the instant that process exits.- * - the periodic reconciler is told to ignore this pane's ROUTE for the duration of the swap- * (`agentReconciler.holdRoute`/`releaseRoute`), or it would either flicker the agent dormant- * mid-kill, or — worse — mint a brand-new agent for the relaunched process the instant it appears,- * before this handler gets to rebind it.- *- * The permission mode comes from the registry row (`bypassPermissionFor`): what create recorded, or- * what discovery read off the live argv since — the live process is probed only for a row that has- * neither, and before anything is signalled. The sessionId to resume comes from the registry's- * live-synced field, not from the original launch argv (the user may have resumed/switched sessions- * from inside the engine's own terminal since launch).- */- backend.onRestartAgent = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {- if (backend.purgeAgentService?.busy(agentId) || stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }- const session = registry.resolve(agentId)- if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }- if (!session.tmuxPane || !tmuxBackend) return { ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' }- const target = { ...session }- const current = () => operationCurrent() && sameRestartTarget(target)- const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during restart.' } as const- if (!current()) return changed- // Both branches below `cd` into the row's folder before they exec, and both have already killed- // (or respawned over) the old process by the time that `cd` fails. Ask first, over a live agent.- const missing = workspaceMissing(session.cwd)- if (missing) return missing- const pane = session.tmuxPane- const engine = session.engine- const runtime: TmuxRuntimeRef = { backend: 'tmux', paneId: pane }- const routeKey = terminalRouteKey(runtime)- // Restarting a terminal is a fresh shell in the same pane — `respawn-pane -k` over whatever the- // old one was doing. There is no engine to wait for and no session to resume, so none of the- // process-swap choreography below applies. A terminal that ADOPTED an engine restarts the- // engine, like any agent: the tile said Restart about the engine it shows.- if (isTerminalEngine(engine)) {- agentReconciler.holdRoute(routeKey)- try {- // The same opening a fresh terminal tile prints (`onCreateAgent`'s `terminalHint`): a- // restarted tile is a fresh shell too, and should look like one.- const respawned = await tmuxBackend.respawn(runtime, {- command: buildEngineLaunchArgv(engine, {- ...(session.cwd ? { cwd: session.cwd } : {}),- terminalHint: { machineName: terminalHintMachineName() },- }),- cwd: homedir(),- })- if (!current()) return changed- if (respawned.state !== 'succeeded') return { ok: false, error: 'RESTART_FAILED', detail: respawned.reason }- await clearPaneRemainOnExit(pane)- if (!current()) return changed- registry.setActive(session.agentId, true)- const refreshed = registry.byAgent(session.agentId)- if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }- announceSession(refreshed)- console.log(`[restart] ${sid(session.agentId)} terminal · fresh shell`)- return { ok: true, session: refreshed, resumed: false }- } finally {- agentReconciler.releaseRoute(routeKey)- }- }- if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }-- // The replacement is launched WITH what the original was: its grid's env and argv (a bare- // respawn would inherit the tmux session's variables but never the codex `-c …` / pi `--model`- // half, and an agent moved here by a retarget has nothing in the session env at all), or its- // Codex profile. Refused before anything is killed, so a restart that cannot honour the grid- // leaves the running process alone.- const built = await relaunchOverrides(session)- if (!current()) return changed- if (!built.ok) return { ok: false, error: built.error, detail: built.detail }-- agentReconciler.holdRoute(routeKey)- try {- const restartPermission = await downgradedPermission(session,- await bypassPermissionFor(session, () => liveBypassPermission(session)), 'restart')- const outcome = await restartAgent(- { engine, sessionId: session.sessionId },- restartPermission.bypassPermission === true,- { ...paneSwapDeps(session, runtime, built.overrides, restartPermission.permissionMode ?? null), isCurrent: current },- )+ backend.cleanupPreview = closing.cleanupPreview+ backend.onResumeAgent = lifecycle.resumeAgent- if (!current()) return changed- if (!outcome.ok) return { ok: false, error: 'RESTART_FAILED', detail: outcome.detail }- refreshGridWebSearch(session.agentId, built.overrides)-- // Address the CANONICAL agentId from the resolved session, not the raw RPC input — `resolve()`- // accepts either an agentId or a bare sessionId, but `setActive`/`byAgent` only ever key on the- // real agentId. Gateway and grid are re-read off the new pid now (one cached env read) rather- // than left to the next scan, so the announce below already says where the engine came back.- const [gateway, assignment] = await Promise.all([- probeGatewayRuntime(outcome.processIdentity),- probeGridAssignment(outcome.processIdentity, engine, outcome.processIdentity.executable),- ])- if (!current()) return changed- registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)- registry.setActive(session.agentId, true)- await clearPaneRemainOnExit(pane)- if (!current()) return changed- const refreshed = registry.byAgent(session.agentId)- if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }- announceSession(refreshed)- console.log(`[restart] ${sid(session.agentId)} ${engine} · ${outcome.resumed ? 'resumed' : 'fresh session'}`- + (session.gridLaunch ? ` · grid ${session.gridLaunch.networkName}` : ''))- return { ok: true, session: refreshed, resumed: outcome.resumed }- } finally {- agentReconciler.releaseRoute(routeKey)- }+ // Restarting an agent in its own pane (core/agents/restart.ts).+ backend.onRestartAgent = createAgentRestarter({+ restartJobs,+ registry,+ purgeBusy: (agentId) => backend.purgeAgentService?.busy(agentId),+ stopJobs,+ pinnedControls,+ tmuxBackend,+ sameRestartTarget,+ agentReconciler,+ terminalHintMachineName,+ announceSession,+ relaunchOverrides,+ downgradedPermission,+ refreshGridWebSearch,+ liveBypassPermission,+ paneSwapDeps,})const submitAgent = inputs.submitAgentdiff --git a/cli/src/core/agents/close.spec.ts b/cli/src/core/agents/close.spec.tsnew file mode 100644index 000000000..0489d936d--- /dev/null+++ b/cli/src/core/agents/close.spec.ts@@ -0,0 +1,110 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { inspectCloseActivity, type CloseAgentServiceDeps } from '../../lib/closeAgentService.js'+import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'+import { createAgentClosing, type ClosingDeps } from './close.js'++// The real close service, recording what it was built with so its callbacks can be driven directly.+vi.mock('../../lib/closeAgentService.js', async (real) => {+ const actual = await real<typeof import('../../lib/closeAgentService.js')>()+ class RecordingCloseAgentService extends actual.CloseAgentService {+ constructor(readonly given: CloseAgentServiceDeps) { super(given) }+ }+ return { ...actual, CloseAgentService: RecordingCloseAgentService, inspectCloseActivity: vi.fn(() => 'idle') }+})++const row = (over: Partial<RegisteredSession> = {}) =>+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work/app', registeredAt: 0, ...over }) as RegisteredSession++function setup(over: Partial<ClosingDeps> = {}, advertised: RegisteredSession[] = []) {+ const deps: ClosingDeps = {+ registry: { advertised: vi.fn(() => advertised) } as unknown as ClosingDeps['registry'],+ cleanupTabs: { refresh: vi.fn(async () => {}), isHidden: vi.fn(() => true), assertHidden: vi.fn(async () => {}) },+ watcher: { pollSession: vi.fn(async () => {}) } as unknown as ClosingDeps['watcher'],+ captureTerminal: vi.fn(async () => 'screen'),+ sessionTurnState: vi.fn(() => false),+ openQuestions: { has: vi.fn(() => false) },+ terminals: { captureRetained: vi.fn(async () => ({ state: 'succeeded', value: 'scrollback' })) } as unknown as ClosingDeps['terminals'],+ sessionCheckpoints: { save: vi.fn(async () => {}) } as unknown as ClosingDeps['sessionCheckpoints'],+ stopAgent: vi.fn(async () => {}),+ announceSession: vi.fn(),+ ...over,+ }+ const closing = createAgentClosing(deps)+ const close = (closing.closeAgentService as unknown as { given: CloseAgentServiceDeps }).given+ return { deps, closing, close }+}++describe('closing agents no window shows', () => {+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })++ it('builds the close service on the registry and the open tabs, stopping and announcing as elsewhere', () => {+ const { deps, close } = setup()+ expect(close.registry).toBe(deps.registry)+ expect(close.openTabs).toBe(deps.cleanupTabs)+ expect(close.stop).toBe(deps.stopAgent)+ expect(close.changed).toBe(deps.announceSession)+ })++ describe('what an agent is doing', () => {+ it('reads its newest lines first, then its screen, its turn and whether it is asking', async () => {+ const { deps, close } = setup()+ expect(await close.activity(row())).toBe('idle')+ expect(deps.watcher.pollSession).toHaveBeenCalledWith('s1')+ expect(deps.captureTerminal).toHaveBeenCalledWith('a1', 80)+ expect(deps.sessionTurnState).toHaveBeenCalledWith('s1')+ expect(deps.openQuestions.has).toHaveBeenCalledWith('s1')+ expect(inspectCloseActivity).toHaveBeenCalledWith(row(), 'screen', false, false)+ })++ it('with no session yet, has no lines to read', async () => {+ const { deps, close } = setup()+ await close.activity(row({ sessionId: '' }))+ expect(deps.watcher.pollSession).not.toHaveBeenCalled()+ })+ })++ describe('the checkpoint around a close', () => {+ it('before: keeps two thousand lines of the pane with the conversation', async () => {+ const { deps, close } = setup()+ await close.checkpoint(row(), 'before')+ expect(deps.terminals.captureRetained).toHaveBeenCalledWith(row(), { historyLines: 2000 })+ expect(deps.sessionCheckpoints.save).toHaveBeenCalledWith(row(), { screen: 'scrollback' })+ })++ it('before, with a pane it cannot read, and after: keeps the conversation without a screen', async () => {+ const failing = setup({ terminals: { captureRetained: vi.fn(async () => ({ state: 'failed', reason: 'gone' })) } as never })+ await failing.close.checkpoint(row(), 'before')+ expect(failing.deps.sessionCheckpoints.save).toHaveBeenCalledWith(row(), { screen: null })+ const after = setup()+ await after.close.checkpoint(row(), 'after')+ expect(after.deps.terminals.captureRetained).not.toHaveBeenCalled()+ expect(after.deps.sessionCheckpoints.save).toHaveBeenCalledWith(row(), { screen: null })+ })+ })++ describe('the cleanup preview', () => {+ it('lists the hidden agents a close would take, as they are now, and counts the rest as kept', async () => {+ const shown = row({ agentId: 'shown' })+ const changing = row({ agentId: 'changing' })+ const quiet = row({ agentId: 'quiet', sessionId: 's2', registeredAt: 1_000 })+ const working = row({ agentId: 'working', sessionId: 's3' })+ const { deps, closing } = setup({}, [shown, changing, quiet, working])+ vi.mocked(deps.cleanupTabs.isHidden).mockImplementation((s) => s.agentId !== 'shown')+ const request = vi.spyOn(closing.closeAgentService, 'request')+ .mockResolvedValueOnce({ error: 'AGENT_CHANGED' })+ .mockResolvedValueOnce({})+ .mockResolvedValueOnce({ activity: 'working' })+ expect(await closing.cleanupPreview()).toEqual({+ version: 1,+ agents: [+ { agentId: 'quiet', sessionId: 's2', createdAt: new Date(1_000).toISOString(), name: projectDisplayName(quiet), engine: 'claude', activity: 'unknown' },+ { agentId: 'working', sessionId: 's3', createdAt: new Date(0).toISOString(), name: projectDisplayName(working), engine: 'claude', activity: 'working' },+ ],+ kept: 2,+ })+ expect(deps.cleanupTabs.refresh).toHaveBeenCalled()+ expect(request).toHaveBeenCalledWith({ agentId: 'changing', sessionId: 's1', createdAt: new Date(0).toISOString(), mode: 'inspect' })+ expect(request).toHaveBeenCalledTimes(3)+ })+ })+})diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.tsnew file mode 100644index 000000000..b6ee0a8f7--- /dev/null+++ b/cli/src/core/agents/close.ts@@ -0,0 +1,61 @@+/**+ * Closing agents that no window shows: the close service (now, once idle, after the task) and the+ * cleanup preview that lists what a close would take, each with what it is doing right now.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).+ */+import { CloseAgentService, inspectCloseActivity, type CloseAgentServiceDeps } from '../../lib/closeAgentService.js'+import type { OpenTabProtection } from '../../lib/openTabProtection.js'+import { projectDisplayName, type registry } from '../../lib/registry.js'+import type { SessionCheckpointStore } from '../../lib/sessionCheckpoint.js'+import type { TerminalBackendCoordinator } from '../../lib/terminalBackendCoordinator.js'+import type { Watcher } from '../../watcher/watcher.js'++export interface ClosingDeps {+ registry: typeof registry+ cleanupTabs: Pick<OpenTabProtection, 'refresh' | 'isHidden' | 'assertHidden'>+ watcher: Pick<Watcher, 'pollSession'>+ captureTerminal: (target: string, historyLines?: number) => Promise<string | null>+ sessionTurnState: (sessionId: string) => boolean | undefined+ /** What is still being asked, by session. */+ openQuestions: { has(sessionId: string): boolean }+ terminals: Pick<TerminalBackendCoordinator, 'captureRetained'>+ sessionCheckpoints: Pick<SessionCheckpointStore, 'save'>+ stopAgent: CloseAgentServiceDeps['stop']+ announceSession: CloseAgentServiceDeps['changed']+}++export function createAgentClosing({+ registry, cleanupTabs, watcher, captureTerminal, sessionTurnState, openQuestions, terminals, sessionCheckpoints,+ stopAgent, announceSession,+}: ClosingDeps) {+ const closeAgentService = new CloseAgentService({+ registry,+ openTabs: cleanupTabs,+ activity: async s => {+ if (s.sessionId) await watcher.pollSession(s.sessionId)+ const screen = await captureTerminal(s.agentId, 80)+ return inspectCloseActivity(s, screen, sessionTurnState(s.sessionId), openQuestions.has(s.sessionId))+ },+ checkpoint: async (s, phase) => {+ const captured = phase === 'before' ? await terminals.captureRetained(s, { historyLines: 2000 }) : null+ await sessionCheckpoints.save(s, { screen: captured?.state === 'succeeded' ? captured.value : null })+ },+ stop: stopAgent,+ changed: announceSession,+ })+ const cleanupPreview = async (): Promise<Record<string, unknown>> => {+ await cleanupTabs.refresh()+ const sessions = registry.advertised()+ const agents = []+ for (const s of sessions) {+ if (!cleanupTabs.isHidden(s)) continue+ const target = { agentId: s.agentId, sessionId: s.sessionId, createdAt: new Date(s.registeredAt).toISOString() }+ const inspected = await closeAgentService.request({ ...target, mode: 'inspect' })+ if (inspected.error) continue // A changing session is never added to a reviewed batch.+ agents.push({ ...target, name: projectDisplayName(s), engine: s.engine, activity: inspected.activity ?? 'unknown' })+ }+ return { version: 1, agents, kept: sessions.length - agents.length }+ }+ return { closeAgentService, cleanupPreview }+}diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.tsnew file mode 100644index 000000000..dce8309e9--- /dev/null+++ b/cli/src/core/agents/lifecycle.spec.ts@@ -0,0 +1,135 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { PurgeDeps } from '../../lib/purgeAgentService.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createResumeAgentService } from '../../lib/resumeAgentService.js'+import { createStopAgentService } from '../../lib/stopAgentService.js'+import { createAgentLifecycle, type LifecycleDeps } from './lifecycle.js'++vi.mock('../../lib/stopAgentService.js', async (real) => ({ ...await real<object>(), createStopAgentService: vi.fn(() => vi.fn(async () => {})) }))+vi.mock('../../lib/resumeAgentService.js', async (real) => ({+ ...await real<object>(),+ createResumeAgentService: vi.fn(() => vi.fn(async () => ({ ok: true }))),+}))+// The real purge service, recording what it was built with so its callbacks can be driven directly.+vi.mock('../../lib/purgeAgentService.js', async (real) => {+ const actual = await real<typeof import('../../lib/purgeAgentService.js')>()+ class RecordingPurgeAgentService extends actual.PurgeAgentService {+ constructor(readonly given: PurgeDeps) { super(given) }+ }+ return { ...actual, PurgeAgentService: RecordingPurgeAgentService }+})++const row = (over: Partial<RegisteredSession> = {}) => ({ agentId: 'a1', sessionId: 's1', cwd: '/work', ...over }) as RegisteredSession++function setup(over: Partial<LifecycleDeps> = {}) {+ const deps: LifecycleDeps = {+ registry: {+ byAgent: vi.fn(() => row()),+ list: vi.fn(() => [row()]),+ deleteSavedNames: vi.fn(),+ } as unknown as LifecycleDeps['registry'],+ stoppedAgents: { list: vi.fn(() => [row({ agentId: 'a2' })]), get: vi.fn(() => undefined) } as unknown as LifecycleDeps['stoppedAgents'],+ restartJobs: { busy: vi.fn(() => false) } as unknown as LifecycleDeps['restartJobs'],+ tmuxBackend: null,+ agentReconciler: {} as never,+ forgetSession: vi.fn(),+ markDeleted: vi.fn(),+ clearDeleted: vi.fn(),+ sessionCheckpoints: {} as never,+ mirror: { deleteHistory: vi.fn() },+ sessionSearch: { deleteHistory: vi.fn() },+ send: vi.fn(),+ pinnedControls: new Set<string>(),+ retainExitedSession: vi.fn(),+ announceSession: vi.fn(),+ relaunchOverrides: vi.fn() as never,+ prepareSessionResume: vi.fn(),+ refreshGridWebSearch: vi.fn(),+ attachDsh: vi.fn(),+ ...over,+ }+ const lifecycle = createAgentLifecycle(deps)+ const purge = (lifecycle.purgeAgentService as unknown as { given: PurgeDeps }).given+ return { deps, lifecycle, purge }+}++describe('stopping, purging and resuming an agent', () => {+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })++ it('builds stop on one map of stops in flight, which resume and the lifecycle share', () => {+ const { deps, lifecycle } = setup()+ expect(createStopAgentService).toHaveBeenCalledWith({+ registry: deps.registry, stoppedAgents: deps.stoppedAgents, restartJobs: deps.restartJobs, stopJobs: lifecycle.stopJobs,+ tmuxBackend: null, agentReconciler: deps.agentReconciler, forgetSession: deps.forgetSession,+ markDeleted: deps.markDeleted, clearDeleted: deps.clearDeleted,+ })+ expect(lifecycle.stopAgent).toBe(vi.mocked(createStopAgentService).mock.results[0].value)+ expect(createResumeAgentService).toHaveBeenCalledWith({+ registry: deps.registry, stoppedAgents: deps.stoppedAgents, tmuxBackend: null, restartJobs: deps.restartJobs,+ stopJobs: lifecycle.stopJobs, pinnedControls: deps.pinnedControls, retainExitedSession: deps.retainExitedSession,+ announceSession: deps.announceSession, relaunchOverrides: deps.relaunchOverrides, prepareSessionResume: deps.prepareSessionResume,+ refreshGridWebSearch: deps.refreshGridWebSearch, clearDeleted: deps.clearDeleted, attachDsh: deps.attachDsh,+ })+ })++ describe('purge', () => {+ it('sees live and stopped agents, stops through the stop service, and checkpoints where stop does', () => {+ const { deps, lifecycle, purge } = setup()+ expect(purge.live('a1')).toEqual(row())+ expect(deps.registry.byAgent).toHaveBeenCalledWith('a1')+ expect(purge.sessions()).toEqual([row(), row({ agentId: 'a2' })])+ expect(purge.stopped).toBe(deps.stoppedAgents)+ expect(purge.checkpoints).toBe(deps.sessionCheckpoints)+ expect(purge.stop).toBe(lifecycle.stopAgent)+ })++ it('waits on an agent that is restarting or stopping', () => {+ const restarting = setup({ restartJobs: { busy: vi.fn((id: string) => id === 'a1') } as never })+ expect(restarting.purge.restarting('a1')).toBe(true)+ const { lifecycle, purge } = setup()+ expect(purge.restarting('a1')).toBe(false)+ lifecycle.stopJobs.set('a1', Promise.resolve())+ expect(purge.restarting('a1')).toBe(true)+ })++ it('forgets a deleted conversation\'s lines, search entries and names, and tells every window', () => {+ const { deps, purge } = setup()+ purge.deleted(row())+ expect(deps.mirror.deleteHistory).toHaveBeenCalledWith('s1')+ expect(deps.sessionSearch?.deleteHistory).toHaveBeenCalledWith('s1')+ expect(deps.registry.deleteSavedNames).toHaveBeenCalledWith(['a1', 's1'])+ expect(deps.send).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 'a1', retained: false } })+ })++ it('with no session yet, or no search index, forgets only what there is', () => {+ const { deps, purge } = setup({ sessionSearch: null })+ purge.deleted(row())+ expect(deps.mirror.deleteHistory).toHaveBeenCalledWith('s1')+ purge.deleted(row({ sessionId: '' }))+ expect(deps.mirror.deleteHistory).toHaveBeenCalledTimes(1)+ expect(deps.registry.deleteSavedNames).toHaveBeenLastCalledWith(['a1'])+ })+ })++ describe('resume', () => {+ it('goes ahead for an agent no purge holds, with the mode asked for', async () => {+ const { deps, lifecycle } = setup()+ expect(await lifecycle.resumeAgent('a1', 'plan')).toEqual({ ok: true })+ const resume = vi.mocked(createResumeAgentService).mock.results[0].value+ expect(resume).toHaveBeenCalledWith('a1', 'plan')+ expect(deps.stoppedAgents.get).toHaveBeenCalledWith('a1')+ })++ it('waits while the agent is being purged, or while a purge holds its folder', async () => {+ const busy = setup()+ vi.spyOn(busy.lifecycle.purgeAgentService, 'busy').mockReturnValue(true)+ expect(await busy.lifecycle.resumeAgent('a1')).toEqual({ ok: false, error: 'AGENT_BUSY' })++ const folder = setup({ stoppedAgents: { list: () => [], get: vi.fn(() => row({ cwd: '/work/tree' })) } as never })+ const blocks = vi.spyOn(folder.lifecycle.purgeAgentService, 'blocksFolder').mockReturnValue(true)+ expect(await folder.lifecycle.resumeAgent('a1')).toEqual({ ok: false, error: 'AGENT_BUSY' })+ expect(blocks).toHaveBeenCalledWith('/work/tree')+ expect(vi.mocked(createResumeAgentService).mock.results[1].value).not.toHaveBeenCalled()+ })+ })+})diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.tsnew file mode 100644index 000000000..fa4cef08b--- /dev/null+++ b/cli/src/core/agents/lifecycle.ts@@ -0,0 +1,76 @@+/**+ * Stopping, purging and resuming an agent: the archive side of its lifecycle. Stop keeps the+ * conversation on disk to come back to; purge erases it; resume brings a stopped agent back.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).+ */+import type { BackendSocket } from '../../backendSocket.js'+import type { clearDeleted as clearDeletedFn, markDeleted as markDeletedFn } from '../../lib/deletedSessions.js'+import { PurgeAgentService } from '../../lib/purgeAgentService.js'+import type { registry } from '../../lib/registry.js'+import { createResumeAgentService, type ResumeAgentServiceDeps } from '../../lib/resumeAgentService.js'+import type { SessionCheckpointStore } from '../../lib/sessionCheckpoint.js'+import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'+import { createStopAgentService, type StopAgentServiceDeps } from '../../lib/stopAgentService.js'++type ResumeAgent = NonNullable<BackendSocket['onResumeAgent']>++export interface LifecycleDeps {+ registry: typeof registry+ stoppedAgents: StoppedAgentStore+ restartJobs: StopAgentServiceDeps['restartJobs']+ tmuxBackend: StopAgentServiceDeps['tmuxBackend'] & ResumeAgentServiceDeps['tmuxBackend']+ agentReconciler: StopAgentServiceDeps['agentReconciler']+ forgetSession: StopAgentServiceDeps['forgetSession']+ markDeleted: typeof markDeletedFn+ clearDeleted: typeof clearDeletedFn+ sessionCheckpoints: SessionCheckpointStore+ /** Where a purged conversation's lines and its search entries are dropped. */+ mirror: { deleteHistory(sessionId: string): void }+ sessionSearch: { deleteHistory(sessionId: string): void } | null+ /** To every connected window. */+ send: (frame: { type: string; payload: Record<string, unknown> }) => void+ pinnedControls: ResumeAgentServiceDeps['pinnedControls']+ retainExitedSession: ResumeAgentServiceDeps['retainExitedSession']+ announceSession: ResumeAgentServiceDeps['announceSession']+ relaunchOverrides: ResumeAgentServiceDeps['relaunchOverrides']+ prepareSessionResume: ResumeAgentServiceDeps['prepareSessionResume']+ refreshGridWebSearch: ResumeAgentServiceDeps['refreshGridWebSearch']+ attachDsh: ResumeAgentServiceDeps['attachDsh']+}++export function createAgentLifecycle({+ registry, stoppedAgents, restartJobs, tmuxBackend, agentReconciler, forgetSession, markDeleted, clearDeleted,+ sessionCheckpoints, mirror, sessionSearch, send, pinnedControls, retainExitedSession, announceSession,+ relaunchOverrides, prepareSessionResume, refreshGridWebSearch, attachDsh,+}: LifecycleDeps) {+ /**+ * Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live+ * registry entry, and closes only its exact tmux pane. Exact PID/start-marker validation guards the engine's+ * SIGTERM/SIGKILL fallback. Engine conversation files, recaps and the Harness name remain on disk.+ */+ const stopJobs = new Map<string, Promise<void>>()+ const stopAgent = createStopAgentService({+ registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,+ forgetSession, markDeleted, clearDeleted,+ })+ const purgeAgentService = new PurgeAgentService({+ live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stoppedAgents.list()],+ stopped: stoppedAgents, checkpoints: sessionCheckpoints, stop: stopAgent,+ restarting: id => restartJobs.busy(id) || stopJobs.has(id),+ deleted: s => {+ if (s.sessionId) { mirror.deleteHistory(s.sessionId); sessionSearch?.deleteHistory(s.sessionId) }+ registry.deleteSavedNames([s.agentId, s.sessionId].filter(Boolean))+ send({ type: 'agent_deleted', payload: { agentId: s.agentId, retained: false } })+ },+ })++ const resume = createResumeAgentService({+ registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,+ retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,+ refreshGridWebSearch, clearDeleted, attachDsh,+ })+ const resumeAgent: ResumeAgent = (id, permissionMode) => purgeAgentService.busy(id) || purgeAgentService.blocksFolder(stoppedAgents.get(id)?.cwd)+ ? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resume(id, permissionMode)+ return { stopJobs, stopAgent, purgeAgentService, resumeAgent }+}diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.tsnew file mode 100644index 000000000..a89464d91--- /dev/null+++ b/cli/src/core/agents/restart.spec.ts@@ -0,0 +1,251 @@+import { homedir } from 'node:os'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { buildEngineLaunchArgv } from '../../lib/engineLaunch.js'+import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'+import { probeGridAssignment } from '../../lib/gridAssignment.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { AgentRestartCoordinator, bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'+import { terminalRouteKey } from '../../lib/terminalRuntime.js'+import { clearPaneRemainOnExit } from '../../lib/tmux.js'+import { workspaceMissing } from '../../lib/workspaceCheck.js'+import { createAgentRestarter, type RestartDeps } from './restart.js'++vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), buildEngineLaunchArgv: vi.fn(() => ['zsh', '-l']) }))+vi.mock('../../lib/gatewayRuntime.js', async (real) => ({ ...await real<object>(), probeGatewayRuntime: vi.fn(async () => ({ kind: 'none' })) }))+vi.mock('../../lib/gridAssignment.js', async (real) => ({ ...await real<object>(), probeGridAssignment: vi.fn(async () => undefined) }))+vi.mock('../../lib/restartAgent.js', async (real) => ({+ ...await real<object>(),+ bypassPermissionFor: vi.fn(async (_s: unknown, live: () => Promise<boolean>) => live()),+ restartAgent: vi.fn(async () => ({ ok: true, resumed: true, processIdentity: { pid: 2, startMarker: 'new', executable: '/bin/claude' } })),+}))+vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}) }))+vi.mock('../../lib/workspaceCheck.js', () => ({ workspaceMissing: vi.fn(() => null) }))++const runtime = { backend: 'tmux', paneId: '%4' }+const routeKey = terminalRouteKey(runtime as never)+const newProcess = { pid: 2, startMarker: 'new', executable: '/bin/claude' }+const agent = (over: Partial<RegisteredSession> = {}): RegisteredSession => ({+ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work', tmuxPane: '%4', processIdentity: { pid: 1, startMarker: 'old' }, ...over,+}) as unknown as RegisteredSession+const terminal = (over: Partial<RegisteredSession> = {}) => agent({ engine: 'terminal', processIdentity: undefined, ...over } as Partial<RegisteredSession>)++/** `row` is what the registry resolves and reads back; `refreshed` is what it reads after the swap+ * (null: the row vanished mid-restart). `live` goes false to make the operation stale. */+function setup(row: RegisteredSession | null = agent(), over: Partial<RestartDeps> = {}, refreshed: RegisteredSession | null = row) {+ const state = { live: true }+ const tmuxBackend = { respawn: vi.fn(async () => ({ state: 'succeeded' })) }+ const deps: RestartDeps = {+ restartJobs: { run: vi.fn((_id: string, job: (current: () => boolean) => unknown) => job(() => state.live)) } as never,+ registry: {+ resolve: vi.fn(() => row ?? undefined),+ byAgent: vi.fn(() => refreshed ?? undefined),+ updateProcessIdentity: vi.fn(),+ setActive: vi.fn(),+ } as unknown as RestartDeps['registry'],+ purgeBusy: vi.fn(() => false),+ stopJobs: new Map(),+ pinnedControls: new Set(),+ tmuxBackend: tmuxBackend as unknown as RestartDeps['tmuxBackend'],+ sameRestartTarget: vi.fn(() => true),+ agentReconciler: { holdRoute: vi.fn(), releaseRoute: vi.fn() },+ terminalHintMachineName: () => 'studio',+ announceSession: vi.fn(),+ relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: { env: { GRID_KEY: 'k' } } })) as never,+ downgradedPermission: vi.fn(async (_s, bypass: boolean) => ({ bypassPermission: bypass, permissionMode: 'auto' })) as never,+ refreshGridWebSearch: vi.fn() as never,+ liveBypassPermission: vi.fn(async () => true),+ paneSwapDeps: vi.fn(() => ({ swap: true })) as never,+ ...over,+ }+ return { deps, state, tmuxBackend, restart: createAgentRestarter(deps) }+}++const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during restart.' }++describe('restarting an agent', () => {+ beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })++ describe('refusals before anything is touched', () => {+ it('for an agent being purged, stopped or answered, and for one that is not there', async () => {+ expect(await setup(agent(), { purgeBusy: () => true }).restart('a1')).toEqual({ ok: false, error: 'AGENT_BUSY' })+ expect(await setup(agent(), { stopJobs: new Map([['a1', Promise.resolve()]]) }).restart('a1')).toEqual({ ok: false, error: 'AGENT_BUSY' })+ expect(await setup(agent(), { pinnedControls: new Set(['a1']) }).restart('a1')).toEqual({ ok: false, error: 'AGENT_BUSY' })+ expect(await setup(null).restart('a1')).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })+ })++ it('for an agent with no tmux pane, or no tmux at all', async () => {+ expect(await setup(agent({ tmuxPane: undefined })).restart('a1')).toEqual({ ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' })+ expect(await setup(agent(), { tmuxBackend: null }).restart('a1')).toEqual({ ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' })+ })++ it('for an operation already overtaken, or an agent that is no longer the one asked about', async () => {+ const stale = setup()+ stale.state.live = false+ expect(await stale.restart('a1')).toEqual(changed)+ const replaced = setup(agent(), { sameRestartTarget: vi.fn(() => false) })+ expect(await replaced.restart('a1')).toEqual(changed)+ expect(replaced.deps.sameRestartTarget).toHaveBeenCalledWith(agent())+ expect(replaced.deps.agentReconciler.holdRoute).not.toHaveBeenCalled()+ })++ it('for a folder that is gone, before the old process is killed', async () => {+ vi.mocked(workspaceMissing).mockReturnValueOnce({ ok: false, error: 'CWD_NOT_FOUND', detail: 'gone' } as never)+ const run = setup()+ expect(await run.restart('a1')).toEqual({ ok: false, error: 'CWD_NOT_FOUND', detail: 'gone' })+ expect(workspaceMissing).toHaveBeenCalledWith('/work')+ expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()+ expect(restartAgent).not.toHaveBeenCalled()+ })++ it('for an engine with no process to replace, or a launch it cannot honour', async () => {+ expect(await setup(agent({ processIdentity: undefined } as Partial<RegisteredSession>)).restart('a1')).toEqual({ ok: false, error: 'NO_ACTIVE_PROCESS' })+ const refused = setup(agent(), { relaunchOverrides: vi.fn(async () => ({ ok: false, error: 'API_UNAVAILABLE', detail: 'removed' })) as never })+ expect(await refused.restart('a1')).toEqual({ ok: false, error: 'API_UNAVAILABLE', detail: 'removed' })+ expect(refused.deps.agentReconciler.holdRoute).not.toHaveBeenCalled()+ expect(restartAgent).not.toHaveBeenCalled()+ })+ })++ describe('one job per agent', () => {+ it('keyed by the agent a session id resolves to, or by the id as given when nothing resolves', async () => {+ const run = setup(agent())+ await run.restart('s1')+ expect(run.deps.restartJobs.run).toHaveBeenCalledWith('a1', expect.any(Function))+ const missing = setup(null)+ await missing.restart('ghost')+ expect(missing.deps.restartJobs.run).toHaveBeenCalledWith('ghost', expect.any(Function))+ })++ it('so a second restart of the same agent joins the first through the real coordinator', async () => {+ const restartJobs = new AgentRestartCoordinator()+ const run = setup(terminal(), { restartJobs })+ const [first, second] = await Promise.all([run.restart('a1'), run.restart('a1')])+ expect(second).toBe(first)+ expect(run.tmuxBackend.respawn).toHaveBeenCalledTimes(1)+ expect(restartJobs.busy('a1')).toBe(false)+ })+ })++ describe('a terminal', () => {+ it('restarts as a fresh shell in the same pane, opened like a new terminal tile', async () => {+ const run = setup(terminal())+ expect(await run.restart('a1')).toEqual({ ok: true, session: terminal(), resumed: false })+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('terminal', { cwd: '/work', terminalHint: { machineName: 'studio' } })+ expect(run.tmuxBackend.respawn).toHaveBeenCalledWith(runtime, { command: ['zsh', '-l'], cwd: homedir() })+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%4')+ expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)+ expect(run.deps.announceSession).toHaveBeenCalledWith(terminal())+ expect(console.log).toHaveBeenCalledWith('[restart] a1 terminal · fresh shell')+ expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(routeKey)+ expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)+ expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()+ })++ it('with no folder of its own, opens without one', async () => {+ await setup(terminal({ cwd: undefined })).restart('a1')+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('terminal', { terminalHint: { machineName: 'studio' } })+ })++ it('says why tmux would not respawn it, and lets the route go', async () => {+ const run = setup(terminal())+ run.tmuxBackend.respawn.mockResolvedValueOnce({ state: 'failed', reason: 'pane gone' } as never)+ expect(await run.restart('a1')).toEqual({ ok: false, error: 'RESTART_FAILED', detail: 'pane gone' })+ expect(clearPaneRemainOnExit).not.toHaveBeenCalled()+ expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)+ })++ it('stops at whichever step finds the operation overtaken', async () => {+ const respawned = setup(terminal())+ respawned.tmuxBackend.respawn.mockImplementationOnce(async () => { respawned.state.live = false; return { state: 'succeeded' } })+ expect(await respawned.restart('a1')).toEqual(changed)+ expect(clearPaneRemainOnExit).not.toHaveBeenCalled()+ expect(respawned.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)++ const cleared = setup(terminal())+ vi.mocked(clearPaneRemainOnExit).mockImplementationOnce(async () => { cleared.state.live = false })+ expect(await cleared.restart('a1')).toEqual(changed)+ expect(cleared.deps.registry.setActive).not.toHaveBeenCalled()+ })++ it('fails, without announcing, when the row vanished mid-restart', async () => {+ const run = setup(terminal(), {}, null)+ expect(await run.restart('a1')).toEqual({ ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' })+ expect(run.deps.announceSession).not.toHaveBeenCalled()+ })+ })++ describe('an engine', () => {+ it('comes back in the same pane with its launch, its permission and its conversation', async () => {+ const run = setup()+ expect(await run.restart('a1')).toEqual({ ok: true, session: agent(), resumed: true })+ expect(bypassPermissionFor).toHaveBeenCalledWith(agent(), expect.any(Function))+ expect(run.deps.liveBypassPermission).toHaveBeenCalledWith(agent())+ expect(run.deps.downgradedPermission).toHaveBeenCalledWith(agent(), true, 'restart')+ expect(run.deps.paneSwapDeps).toHaveBeenCalledWith(agent(), runtime, { env: { GRID_KEY: 'k' } }, 'auto')+ const [target, bypass, swapDeps] = vi.mocked(restartAgent).mock.calls[0]+ expect(target).toEqual({ engine: 'claude', sessionId: 's1' })+ expect(bypass).toBe(true)+ expect(swapDeps).toMatchObject({ swap: true })+ expect(swapDeps.isCurrent?.()).toBe(true)+ expect(run.deps.refreshGridWebSearch).toHaveBeenCalledWith('a1', { env: { GRID_KEY: 'k' } })+ expect(probeGatewayRuntime).toHaveBeenCalledWith(newProcess)+ expect(probeGridAssignment).toHaveBeenCalledWith(newProcess, 'claude', '/bin/claude')+ expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', newProcess, 'none', undefined)+ expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%4')+ expect(run.deps.announceSession).toHaveBeenCalledWith(agent())+ expect(console.log).toHaveBeenCalledWith('[restart] a1 claude · resumed')+ expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(routeKey)+ expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)+ })++ it('without a mode or a yes, launches with no mode and no bypass; a fresh session on a grid says both', async () => {+ const grid = agent({ gridLaunch: { networkName: 'Home' } } as Partial<RegisteredSession>)+ const run = setup(grid, { downgradedPermission: vi.fn(async () => ({ bypassPermission: false })) as never })+ vi.mocked(restartAgent).mockResolvedValueOnce({ ok: true, resumed: false, processIdentity: newProcess } as never)+ expect(await run.restart('a1')).toEqual({ ok: true, session: grid, resumed: false })+ expect(run.deps.paneSwapDeps).toHaveBeenCalledWith(grid, runtime, { env: { GRID_KEY: 'k' } }, null)+ expect(vi.mocked(restartAgent).mock.calls[0][1]).toBe(false)+ expect(console.log).toHaveBeenCalledWith('[restart] a1 claude · fresh session · grid Home')+ })++ it('says why the swap failed, and lets the route go', async () => {+ vi.mocked(restartAgent).mockResolvedValueOnce({ ok: false, detail: 'could not re-arm the pane' } as never)+ const run = setup()+ expect(await run.restart('a1')).toEqual({ ok: false, error: 'RESTART_FAILED', detail: 'could not re-arm the pane' })+ expect(run.deps.refreshGridWebSearch).not.toHaveBeenCalled()+ expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)+ })++ it('stops at whichever step finds the operation overtaken', async () => {+ const built = setup()+ vi.mocked(built.deps.relaunchOverrides).mockImplementationOnce(async () => { built.state.live = false; return { ok: true, overrides: {} } as never })+ expect(await built.restart('a1')).toEqual(changed)+ expect(built.deps.agentReconciler.holdRoute).not.toHaveBeenCalled()++ const swapped = setup()+ vi.mocked(restartAgent).mockImplementationOnce(async () => { swapped.state.live = false; return { ok: true, resumed: true, processIdentity: newProcess } as never })+ expect(await swapped.restart('a1')).toEqual(changed)+ expect(swapped.deps.refreshGridWebSearch).not.toHaveBeenCalled()+ expect(swapped.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)++ const probed = setup()+ vi.mocked(probeGatewayRuntime).mockImplementationOnce(async () => { probed.state.live = false; return { kind: 'none' } as never })+ expect(await probed.restart('a1')).toEqual(changed)+ expect(probed.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()++ const cleared = setup()+ vi.mocked(clearPaneRemainOnExit).mockImplementationOnce(async () => { cleared.state.live = false })+ expect(await cleared.restart('a1')).toEqual(changed)+ expect(cleared.deps.announceSession).not.toHaveBeenCalled()+ })++ it('fails, without announcing, when the row vanished mid-restart', async () => {+ const run = setup(agent(), {}, null)+ expect(await run.restart('a1')).toEqual({ ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' })+ expect(run.deps.announceSession).not.toHaveBeenCalled()+ expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)+ })+ })+})diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.tsnew file mode 100644index 000000000..fe8548040--- /dev/null+++ b/cli/src/core/agents/restart.ts@@ -0,0 +1,169 @@+/**+ * Restarting an agent in its own pane (`agent_restart`): same agentId, same session, same launch.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).+ */+import { homedir } from 'node:os'+import type { BackendSocket } from '../../backendSocket.js'+import { isTerminalEngine } from '../../engines/types.js'+import { buildEngineLaunchArgv } from '../../lib/engineLaunch.js'+import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'+import { probeGridAssignment } from '../../lib/gridAssignment.js'+import { sid } from '../../lib/log.js'+import type { registry, RegisteredSession } from '../../lib/registry.js'+import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'+import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'+import { terminalRouteKey } from '../../lib/terminalRuntime.js'+import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'+import { clearPaneRemainOnExit } from '../../lib/tmux.js'+import type { TmuxBackend } from '../../lib/tmuxBackend.js'+import { workspaceMissing } from '../../lib/workspaceCheck.js'+import type { createLaunchHelpers } from './launch.js'+import type { PaneSwap } from './swap.js'++type LaunchHelpers = ReturnType<typeof createLaunchHelpers>++type RestartAgentHandler = NonNullable<BackendSocket['onRestartAgent']>++export interface RestartDeps {+ restartJobs: PaneSwap['restartJobs']+ registry: typeof registry+ /** Whether a purge holds this agent (PurgeAgentService.busy). */+ purgeBusy: (agentId: string) => boolean | undefined+ /** Stops in flight, by agent (the stop service's own map). */+ stopJobs: Map<string, Promise<void>>+ /** Panes held for a multi-step answer (terminal control). */+ pinnedControls: Set<string>+ tmuxBackend: TmuxBackend | null+ sameRestartTarget: PaneSwap['sameRestartTarget']+ agentReconciler: Pick<TerminalAgentReconciler, 'holdRoute' | 'releaseRoute'>+ terminalHintMachineName: () => string+ announceSession: (session: RegisteredSession) => void+ relaunchOverrides: LaunchHelpers['relaunchOverrides']+ downgradedPermission: LaunchHelpers['downgradedPermission']+ refreshGridWebSearch: LaunchHelpers['refreshGridWebSearch']+ liveBypassPermission: PaneSwap['liveBypassPermission']+ paneSwapDeps: PaneSwap['paneSwapDeps']+}++export function createAgentRestarter({+ restartJobs, registry, purgeBusy, stopJobs, pinnedControls, tmuxBackend, sameRestartTarget, agentReconciler,+ terminalHintMachineName, announceSession, relaunchOverrides, downgradedPermission, refreshGridWebSearch,+ liveBypassPermission, paneSwapDeps,+}: RestartDeps) {+ /**+ * Web or device restarted an agent (`agent_restart`): exit the live engine process and relaunch it in+ * the SAME tmux pane, keeping the SAME agentId/session — restart must never look like delete+create to+ * the registry or the UI. Two things guard that identity:+ *+ * - `remain-on-exit` is re-armed on the pane before the old process is killed (mirrors what+ * `create()` does at spawn time), or tmux would tear the pane — and with it the whole one-pane+ * session — down the instant that process exits.+ * - the periodic reconciler is told to ignore this pane's ROUTE for the duration of the swap+ * (`agentReconciler.holdRoute`/`releaseRoute`), or it would either flicker the agent dormant+ * mid-kill, or — worse — mint a brand-new agent for the relaunched process the instant it appears,+ * before this handler gets to rebind it.+ *+ * The permission mode comes from the registry row (`bypassPermissionFor`): what create recorded, or+ * what discovery read off the live argv since — the live process is probed only for a row that has+ * neither, and before anything is signalled. The sessionId to resume comes from the registry's+ * live-synced field, not from the original launch argv (the user may have resumed/switched sessions+ * from inside the engine's own terminal since launch).+ */+ const restartAgentHandler: RestartAgentHandler = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {+ if (purgeBusy(agentId) || stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }+ const session = registry.resolve(agentId)+ if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }+ if (!session.tmuxPane || !tmuxBackend) return { ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' }+ const target = { ...session }+ const current = () => operationCurrent() && sameRestartTarget(target)+ const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during restart.' } as const+ if (!current()) return changed+ // Both branches below `cd` into the row's folder before they exec, and both have already killed+ // (or respawned over) the old process by the time that `cd` fails. Ask first, over a live agent.+ const missing = workspaceMissing(session.cwd)+ if (missing) return missing+ const pane = session.tmuxPane+ const engine = session.engine+ const runtime: TmuxRuntimeRef = { backend: 'tmux', paneId: pane }+ const routeKey = terminalRouteKey(runtime)+ // Restarting a terminal is a fresh shell in the same pane — `respawn-pane -k` over whatever the+ // old one was doing. There is no engine to wait for and no session to resume, so none of the+ // process-swap choreography below applies. A terminal that ADOPTED an engine restarts the+ // engine, like any agent: the tile said Restart about the engine it shows.+ if (isTerminalEngine(engine)) {+ agentReconciler.holdRoute(routeKey)+ try {+ // The same opening a fresh terminal tile prints (`onCreateAgent`'s `terminalHint`): a+ // restarted tile is a fresh shell too, and should look like one.+ const respawned = await tmuxBackend.respawn(runtime, {+ command: buildEngineLaunchArgv(engine, {+ ...(session.cwd ? { cwd: session.cwd } : {}),+ terminalHint: { machineName: terminalHintMachineName() },+ }),+ cwd: homedir(),+ })+ if (!current()) return changed+ if (respawned.state !== 'succeeded') return { ok: false, error: 'RESTART_FAILED', detail: respawned.reason }+ await clearPaneRemainOnExit(pane)+ if (!current()) return changed+ registry.setActive(session.agentId, true)+ const refreshed = registry.byAgent(session.agentId)+ if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }+ announceSession(refreshed)+ console.log(`[restart] ${sid(session.agentId)} terminal · fresh shell`)+ return { ok: true, session: refreshed, resumed: false }+ } finally {+ agentReconciler.releaseRoute(routeKey)+ }+ }+ if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }++ // The replacement is launched WITH what the original was: its grid's env and argv (a bare+ // respawn would inherit the tmux session's variables but never the codex `-c …` / pi `--model`+ // half, and an agent moved here by a retarget has nothing in the session env at all), or its+ // Codex profile. Refused before anything is killed, so a restart that cannot honour the grid+ // leaves the running process alone.+ const built = await relaunchOverrides(session)+ if (!current()) return changed+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }++ agentReconciler.holdRoute(routeKey)+ try {+ const restartPermission = await downgradedPermission(session,+ await bypassPermissionFor(session, () => liveBypassPermission(session)), 'restart')+ const outcome = await restartAgent(+ { engine, sessionId: session.sessionId },+ restartPermission.bypassPermission === true,+ { ...paneSwapDeps(session, runtime, built.overrides, restartPermission.permissionMode ?? null), isCurrent: current },+ )++ if (!current()) return changed+ if (!outcome.ok) return { ok: false, error: 'RESTART_FAILED', detail: outcome.detail }+ refreshGridWebSearch(session.agentId, built.overrides)++ // Address the CANONICAL agentId from the resolved session, not the raw RPC input — `resolve()`+ // accepts either an agentId or a bare sessionId, but `setActive`/`byAgent` only ever key on the+ // real agentId. Gateway and grid are re-read off the new pid now (one cached env read) rather+ // than left to the next scan, so the announce below already says where the engine came back.+ const [gateway, assignment] = await Promise.all([+ probeGatewayRuntime(outcome.processIdentity),+ probeGridAssignment(outcome.processIdentity, engine, outcome.processIdentity.executable),+ ])+ if (!current()) return changed+ registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)+ registry.setActive(session.agentId, true)+ await clearPaneRemainOnExit(pane)+ if (!current()) return changed+ const refreshed = registry.byAgent(session.agentId)+ if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }+ announceSession(refreshed)+ console.log(`[restart] ${sid(session.agentId)} ${engine} · ${outcome.resumed ? 'resumed' : 'fresh session'}`+ + (session.gridLaunch ? ` · grid ${session.gridLaunch.networkName}` : ''))+ return { ok: true, session: refreshed, resumed: outcome.resumed }+ } finally {+ agentReconciler.releaseRoute(routeKey)+ }+ })+ return restartAgentHandler+}diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.tsnew file mode 100644index 000000000..d6d757b1a--- /dev/null+++ b/cli/src/core/agents/retarget.spec.ts@@ -0,0 +1,212 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { applyOpencodeSessionModel, parseOpencodeModelId } from '../../engines/opencode/sessionModel.js'+import { isOpencodeV2 } from '../../engines/opencode/version.js'+import { binaryOnPath } from '../../lib/binaryOnPath.js'+import { validateLaunchOverrides } from '../../lib/launchOverrides.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'+import { parseRuntimeProfile } from '../../lib/runtimeProfile.js'+import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'+import { clearPaneRemainOnExit } from '../../lib/tmux.js'+import { workspaceMissing } from '../../lib/workspaceCheck.js'+import { createAgentRetargeter, type RetargetDeps } from './retarget.js'++vi.mock('../../engines/opencode/sessionModel.js', async (real) => ({+ ...await real<object>(),+ applyOpencodeSessionModel: vi.fn(async () => ({ ok: true })),+ parseOpencodeModelId: vi.fn((id: string) => ({ providerID: id.split('/')[0], modelID: id.split('/')[1] })),+}))+vi.mock('../../engines/opencode/version.js', () => ({ isOpencodeV2: vi.fn(() => false), opencodeMajorVersion: vi.fn(() => 1) }))+vi.mock('../../lib/binaryOnPath.js', () => ({ binaryOnPath: vi.fn(() => true) }))+vi.mock('../../lib/gatewayRuntime.js', async (real) => ({ ...await real<object>(), probeGatewayRuntime: vi.fn(async () => ({ kind: 'none' })) }))+vi.mock('../../lib/gridAssignment.js', async (real) => ({ ...await real<object>(), probeGridAssignment: vi.fn(async () => undefined) }))+vi.mock('../../lib/gridLaunch.js', async (real) => ({ ...await real<object>(), describeGridLaunch: vi.fn(() => 'claude on Home'), gridEnvVarNames: vi.fn(() => ['ANTHROPIC_BASE_URL']) }))+vi.mock('../../lib/launchOverrides.js', async (real) => ({ ...await real<object>(), validateLaunchOverrides: vi.fn(async () => ({ ok: true })) }))+vi.mock('../../lib/restartAgent.js', async (real) => ({+ ...await real<object>(),+ bypassPermissionFor: vi.fn(async (_s: unknown, live: () => Promise<boolean>) => live()),+ restartAgent: vi.fn(async () => ({ ok: true, resumed: true, processIdentity: { pid: 2, startMarker: 'new', executable: '/bin/claude' } })),+}))+vi.mock('../../lib/runtimeProfile.js', async (real) => ({ ...await real<object>(), parseRuntimeProfile: vi.fn(() => ({ engine: 'claude', model: 'opus' })) }))+vi.mock('../../lib/runtimeProfileController.js', async (real) => ({ ...await real<object>(), inspectRuntimePane: vi.fn(() => ({ idle: true })) }))+vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}) }))+vi.mock('../../lib/workspaceCheck.js', () => ({ workspaceMissing: vi.fn(() => null) }))++const pane = { backend: 'tmux', paneId: '%4' }+const grid = { networkId: 'g1', networkName: 'Home', baseUrl: 'http://g', model: 'big', apiKey: 'k' }+const agent = (over: Partial<RegisteredSession> = {}): RegisteredSession => ({+ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work', runtimes: [pane], processIdentity: { pid: 1, startMarker: 'old' }, ...over,+}) as unknown as RegisteredSession++function setup(row: RegisteredSession | null = agent(), over: Partial<RetargetDeps> = {}) {+ const release = vi.fn()+ const deps: RetargetDeps = {+ purgeBusy: vi.fn(() => false),+ tmuxBackend: { clearEnv: vi.fn(async () => ({ state: 'succeeded' })) } as unknown as RetargetDeps['tmuxBackend'],+ registry: {+ resolve: vi.fn(() => row ?? undefined),+ byAgent: vi.fn(() => row ?? undefined),+ updateProcessIdentity: vi.fn(),+ setGridLaunch: vi.fn(),+ setSubscriptionModel: vi.fn(),+ setActive: vi.fn(),+ } as unknown as RetargetDeps['registry'],+ runtimeProfiles: { selectedModel: vi.fn(() => 'runtime-v1:claude:opus') } as never,+ launchOverridesDeps: {} as never,+ captureTerminal: vi.fn(async () => 'idle pane'),+ acquireTerminalControl: vi.fn(() => release),+ relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: { gridLaunchRecord: { override: grid, webSearch: 'off' } } })) as never,+ downgradedPermission: vi.fn(async (_s, bypass: boolean) => ({ bypassPermission: bypass, permissionMode: null })) as never,+ agentReconciler: { holdRoute: vi.fn(), releaseRoute: vi.fn() },+ restartJobs: { busy: vi.fn(() => false) } as never,+ paneSwapDeps: vi.fn(() => ({})) as never,+ liveBypassPermission: vi.fn(async () => true),+ announceSession: vi.fn(),+ opencodeDb: '/db/opencode.db',+ ...over,+ }+ return { deps, release, retarget: createAgentRetargeter(deps) }+}++describe('retargeting an agent', () => {+ beforeEach(() => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ })+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })++ describe('refusals before anything is touched', () => {+ it('for an agent being purged, no tmux, no agent, no tmux pane or no process to validate', async () => {+ expect(await setup(agent(), { purgeBusy: () => true }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })+ expect(await setup(agent(), { tmuxBackend: null }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })+ expect(await setup(null).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })+ expect(await setup(agent({ runtimes: [] } as Partial<RegisteredSession>)).retarget({ agentId: 'a1', grid })).toMatchObject({ error: 'RETARGET_UNSUPPORTED_BACKEND' })+ expect(await setup(agent({ processIdentity: undefined } as Partial<RegisteredSession>)).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'NO_ACTIVE_PROCESS' })+ })++ it('for a launch this machine cannot do, an OpenCode store it cannot rewrite, or a folder that is gone', async () => {+ vi.mocked(validateLaunchOverrides).mockResolvedValueOnce({ ok: false, error: 'GRID_ENGINE_UNSUPPORTED', detail: 'no' } as never)+ expect(await setup().retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'GRID_ENGINE_UNSUPPORTED', detail: 'no' })+ vi.mocked(binaryOnPath).mockReturnValueOnce(false)+ expect(await setup(agent({ engine: 'opencode' } as Partial<RegisteredSession>)).retarget({ agentId: 'a1', grid })).toMatchObject({ error: 'OPENCODE_SQLITE_MISSING' })+ vi.mocked(workspaceMissing).mockReturnValueOnce({ ok: false, error: 'CWD_NOT_FOUND', detail: 'gone' } as never)+ expect(await setup().retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'CWD_NOT_FOUND', detail: 'gone' })+ })++ it('for a pane it cannot read, a turn in progress, a swap already running, or control it cannot take', async () => {+ expect(await setup(agent(), { captureTerminal: vi.fn(async () => null) }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'TMUX_FAILED' })+ vi.mocked(inspectRuntimePane).mockReturnValueOnce({ idle: false } as never)+ expect(await setup().retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })+ expect(await setup(agent(), { restartJobs: { busy: () => true } as never }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })+ expect(await setup(agent(), { acquireTerminalControl: () => null }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })+ })++ it('for overrides it cannot build, giving control back', async () => {+ const run = setup(agent(), { relaunchOverrides: vi.fn(async () => ({ ok: false, error: 'API_UNAVAILABLE', detail: 'removed' })) as never })+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'API_UNAVAILABLE', detail: 'removed' })+ expect(run.release).toHaveBeenCalled()+ expect(run.deps.agentReconciler.holdRoute).not.toHaveBeenCalled()+ })+ })++ describe('a move that goes ahead', () => {+ it('onto a grid: the pane respawned, the new process adopted, the launch and the model it left kept', async () => {+ const log = vi.mocked(console.log)+ const run = setup()+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })+ expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalled()+ expect(restartAgent).toHaveBeenCalledWith({ engine: 'claude', sessionId: 's1' }, true, {})+ expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', expect.objectContaining({ pid: 2 }), 'none', undefined)+ expect(run.deps.registry.setGridLaunch).toHaveBeenCalledWith('a1', { override: grid, webSearch: 'off' })+ expect(run.deps.registry.setSubscriptionModel).toHaveBeenCalledWith('a1', 'opus')+ expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%4')+ expect(run.deps.announceSession).toHaveBeenCalled()+ expect(run.release).toHaveBeenCalled()+ expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalled()+ expect(log.mock.calls.map(([line]) => String(line))).toContain('claude on Home · retargeted a1 · resumed')+ })++ it('remembers only the model of the agent\'s own login, never a grid\'s, never the one it moves to', async () => {+ const validated = () => vi.mocked(validateLaunchOverrides).mock.lastCall?.[2]+ // Grid to grid: the memory stays as it was.+ const fromGrid = setup(agent({ grid: { baseUrl: 'x' }, subscriptionModel: 'sonnet' } as Partial<RegisteredSession>))+ await fromGrid.retarget({ agentId: 'a1', grid })+ expect(fromGrid.deps.registry.setSubscriptionModel).toHaveBeenCalledWith('a1', 'sonnet')+ // The engine still reports the grid's model: that is not the one to remember.+ vi.mocked(parseRuntimeProfile).mockReturnValueOnce({ engine: 'claude', model: 'big' } as never)+ const reporting = setup(agent())+ await reporting.retarget({ agentId: 'a1', grid })+ expect(reporting.deps.registry.setSubscriptionModel).not.toHaveBeenCalled()+ // Another engine's model, or none observed: nothing to remember.+ vi.mocked(parseRuntimeProfile).mockReturnValueOnce({ engine: 'opencode', model: 'big-pickle' } as never).mockReturnValueOnce(null as never)+ await setup().retarget({ agentId: 'a1', grid })+ await setup().retarget({ agentId: 'a1', grid })+ expect(validated()).toEqual({ gridLaunch: grid, codexHome: undefined })+ })++ it('back home: the grid\'s variables cleared from the pane, on the remembered model, said plainly', async () => {+ const log = vi.mocked(console.log)+ const run = setup(agent({ grid: { baseUrl: 'x' }, subscriptionModel: 'opus' } as Partial<RegisteredSession>), {+ relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: {} })) as never,+ })+ vi.mocked(restartAgent).mockResolvedValueOnce({ ok: true, resumed: false, processIdentity: { pid: 2, startMarker: 'n' } } as never)+ expect(await run.retarget({ agentId: 'a1', grid: null })).toEqual({ ok: true })+ expect(vi.mocked(validateLaunchOverrides).mock.lastCall?.[2]).toEqual({ gridLaunch: null, codexHome: undefined, subscriptionModel: 'opus' })+ expect(run.deps.tmuxBackend!.clearEnv).toHaveBeenCalledWith(pane, ['ANTHROPIC_BASE_URL'])+ expect(run.deps.registry.setGridLaunch).toHaveBeenCalledWith('a1', null)+ expect(run.deps.registry.setSubscriptionModel).not.toHaveBeenCalled()+ expect(log.mock.calls.map(([line]) => String(line))).toContain('claude on its own login · retargeted a1 · fresh session')+ const none = setup(agent(), { relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: {} })) as never })+ await none.retarget({ agentId: 'a1', grid: null })+ expect(vi.mocked(validateLaunchOverrides).mock.lastCall?.[2]).toMatchObject({ subscriptionModel: null })+ })++ it('fails cleanly when the pane will not be cleared, or the respawn does not come up', async () => {+ const home = { relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: {} })) as never }+ const run = setup(agent(), home)+ vi.mocked(run.deps.tmuxBackend!.clearEnv).mockResolvedValueOnce({ state: 'failed', reason: 'no session' } as never).mockResolvedValueOnce({ state: 'unknown' } as never)+ expect(await run.retarget({ agentId: 'a1', grid: null })).toEqual({ ok: false, error: 'GRID_CLEAR_FAILED', detail: 'no session' })+ expect(await run.retarget({ agentId: 'a1', grid: null })).toEqual({ ok: false, error: 'GRID_CLEAR_FAILED', detail: 'tmux would not clear the pane environment' })+ vi.mocked(restartAgent).mockResolvedValueOnce({ ok: false, detail: 'no process' } as never)+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'RESPAWN_FAILED', detail: 'no process' })+ expect(run.release).toHaveBeenCalledTimes(3)+ expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledTimes(3)+ })++ it('rewrites a resumed OpenCode session\'s model before the respawn, and refuses if it cannot', async () => {+ const opencode = agent({ engine: 'opencode' } as Partial<RegisteredSession>)+ const withModel = { relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: { sessionModel: 'grid/big', gridLaunchRecord: null } })) as never }+ const run = setup(opencode, withModel)+ await run.retarget({ agentId: 'a1', grid })+ expect(applyOpencodeSessionModel).toHaveBeenCalledWith({ opencodeMajor: 1, dbPath: '/db/opencode.db', sessionId: 's1', model: { providerID: 'grid', modelID: 'big' }, cwd: '/work', checkCatalog: false })+ vi.mocked(applyOpencodeSessionModel).mockResolvedValueOnce({ ok: false, code: 'SESSION_NOT_FOUND', detail: 'no rows' } as never)+ expect(await setup(agent({ engine: 'opencode', cwd: undefined } as Partial<RegisteredSession>), withModel).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'SESSION_NOT_FOUND', detail: 'no rows' })+ // v2 needs no sqlite3; a model the overrides do not name, or one that does not parse, writes nothing.+ vi.mocked(isOpencodeV2).mockReturnValueOnce(true)+ vi.mocked(binaryOnPath).mockReturnValue(false)+ expect(await setup(opencode, { relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: {} })) as never }).retarget({ agentId: 'a1', grid })).toEqual({ ok: true })+ vi.mocked(binaryOnPath).mockReturnValue(true)+ vi.mocked(parseOpencodeModelId).mockReturnValueOnce(null as never)+ await setup(opencode, withModel).retarget({ agentId: 'a1', grid })+ expect(applyOpencodeSessionModel).toHaveBeenCalledTimes(2)+ // Home to a remembered model with its provider: checked against OpenCode's catalogue.+ await setup(agent({ engine: 'opencode', subscriptionModel: 'anthropic/claude' } as Partial<RegisteredSession>), withModel).retarget({ agentId: 'a1', grid: null })+ expect(vi.mocked(applyOpencodeSessionModel).mock.lastCall?.[0]).toMatchObject({ checkCatalog: true })+ // A remembered model without a provider, or an OpenCode agent with no session: no rewrite at all.+ vi.mocked(binaryOnPath).mockReturnValue(false)+ expect(await setup(agent({ engine: 'opencode', subscriptionModel: 'claude' } as Partial<RegisteredSession>), withModel).retarget({ agentId: 'a1', grid: null })).toEqual({ ok: true })+ expect(await setup(agent({ engine: 'opencode', sessionId: '' } as Partial<RegisteredSession>), withModel).retarget({ agentId: 'a1', grid })).toEqual({ ok: true })+ vi.mocked(binaryOnPath).mockReturnValue(true)+ })++ it('reads the live bypass flag only when the row recorded none, and announces nothing for a row gone meanwhile', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byAgent).mockReturnValue(undefined)+ await run.retarget({ agentId: 'a1', grid })+ expect(bypassPermissionFor).toHaveBeenCalled()+ expect(run.deps.liveBypassPermission).toHaveBeenCalled()+ expect(run.deps.announceSession).not.toHaveBeenCalled()+ })+ })+})diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.tsnew file mode 100644index 000000000..8e3f20df8--- /dev/null+++ b/cli/src/core/agents/retarget.ts@@ -0,0 +1,269 @@+/**+ * Moving a RUNNING agent onto a grid, or back to its engine's own login (`agent_retarget`).+ *+ * A process's environment is fixed at `execve`, so there is no way to re-point a live engine short of+ * replacing the process. `respawn-pane -k` does exactly that and keeps the pane, which keeps the pane+ * id, which keeps the agent's identity, its tile and its scrollback — the user sees their agent+ * restart, not a new agent appear. `--resume` brings the conversation back.+ *+ * Every check refuses instead of doing something partial, because a half-applied move is+ * indistinguishable from a working one until the bill arrives.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).+ */+import type { BackendSocket } from '../../backendSocket.js'+import { applyOpencodeSessionModel, parseOpencodeModelId } from '../../engines/opencode/sessionModel.js'+import { isOpencodeV2, opencodeMajorVersion } from '../../engines/opencode/version.js'+import { binaryOnPath } from '../../lib/binaryOnPath.js'+import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'+import { probeGridAssignment } from '../../lib/gridAssignment.js'+import { describeGridLaunch, gridEnvVarNames } from '../../lib/gridLaunch.js'+import { validateLaunchOverrides, type LaunchOverridesDeps, type LaunchSource } from '../../lib/launchOverrides.js'+import { sid } from '../../lib/log.js'+import type { registry, RegisteredSession } from '../../lib/registry.js'+import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'+import { parseRuntimeProfile, type RuntimeProfileManager } from '../../lib/runtimeProfile.js'+import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'+import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'+import { terminalRouteKey } from '../../lib/terminalRuntime.js'+import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'+import { clearPaneRemainOnExit } from '../../lib/tmux.js'+import type { TmuxBackend } from '../../lib/tmuxBackend.js'+import { workspaceMissing } from '../../lib/workspaceCheck.js'+import type { createLaunchHelpers } from './launch.js'+import type { PaneSwap } from './swap.js'++type LaunchHelpers = ReturnType<typeof createLaunchHelpers>++type RetargetAgent = NonNullable<BackendSocket['onRetargetAgent']>++export interface RetargetDeps {+ /** Whether a purge holds this agent (PurgeAgentService.busy). */+ purgeBusy: (agentId: string) => boolean | undefined+ tmuxBackend: TmuxBackend | null+ registry: typeof registry+ runtimeProfiles: Pick<RuntimeProfileManager, 'selectedModel'>+ launchOverridesDeps: LaunchOverridesDeps+ captureTerminal: (target: string, historyLines?: number) => Promise<string | null>+ acquireTerminalControl: (id: string, opts?: { forAnswer?: boolean }) => (() => void) | null+ relaunchOverrides: LaunchHelpers['relaunchOverrides']+ downgradedPermission: LaunchHelpers['downgradedPermission']+ agentReconciler: Pick<TerminalAgentReconciler, 'holdRoute' | 'releaseRoute'>+ restartJobs: PaneSwap['restartJobs']+ paneSwapDeps: PaneSwap['paneSwapDeps']+ liveBypassPermission: PaneSwap['liveBypassPermission']+ announceSession: (session: RegisteredSession) => void+ /** OpenCode's store, whose rows a resumed session takes its model from. */+ opencodeDb: string+}++export function createAgentRetargeter({+ purgeBusy, tmuxBackend, registry, runtimeProfiles, launchOverridesDeps, captureTerminal, acquireTerminalControl,+ relaunchOverrides, downgradedPermission, agentReconciler, restartJobs, paneSwapDeps, liveBypassPermission,+ announceSession, opencodeDb,+}: RetargetDeps) {+ const retargetAgent: RetargetAgent = async ({ agentId, grid }) => {+ if (purgeBusy(agentId)) return { ok: false, error: 'AGENT_BUSY' }+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }+ const session = registry.resolve(agentId)+ if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }+ const pane = session.runtimes.find((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')+ // Only tmux panes can be respawned. Saying so is better than a generic failure the user cannot act on.+ if (!pane) return { ok: false, error: 'RETARGET_UNSUPPORTED_BACKEND', detail: `${session.engine} is not running in a tmux pane` }+ // The swap kills a process it has validated by pid + start marker. Without one there is nothing to+ // validate, and respawning over a pane whose occupant we cannot identify is how you replace+ // something that was not ours.+ if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }+ // Leaving for a grid is the LAST moment this agent's own model is observable: once the pane is on+ // the grid, the engine reports the grid's model and the previous choice exists nowhere. So it is+ // read now and kept, and a later move back returns the person to it rather than to whatever+ // default the engine would otherwise fall to. Read from the live engine, not from the row.+ //+ // Coming back reads what was kept. Not cleared on the way home: an agent bounced between a grid+ // and its own login should land on the same model every time, not only the first.+ // ⚠️ `selectedModel` answers an ENCODED runtime-profile id (`runtime-v1:…`), not a model name —+ // handing that to an engine would point it at a model that does not exist. Decode it and take+ // the model. For claude the decoded value is already the vendor's alias (`opus`), which is what+ // ANTHROPIC_MODEL wants. Null when the daemon has not observed this pane's model yet, which is a+ // real answer: there is then nothing to come back to and the engine decides, as it did before.+ // ⚠️ The profile's OWN engine has to match, not just the session it was read under. A model is+ // only meaningful to the engine that named it — `opencode/big-pickle` handed back as+ // ANTHROPIC_MODEL is not a Claude model, and Claude Code says so ("It may not exist or you may+ // not have access to it") on a pane the user never chose it for. The keying bug that let one+ // agent read another's model is fixed at its source in RuntimeProfileManager; this is the second+ // lock, because the cost of being wrong here is a pane that answers on nothing.+ const profile = parseRuntimeProfile(runtimeProfiles.selectedModel(session))+ const observed = profile && profile.engine === session.engine ? profile.model : null+ const remembered = grid+ // Two guards, and both come from watching this go wrong:+ //+ // * Capture only when the agent is on its OWN LOGIN. Moving grid→grid must not overwrite the+ // memory with the first grid's model — the subscription choice has not changed, and the+ // whole point is to still have it on the way home.+ //+ // * Never remember the model being moved TO. An engine can keep REPORTING a grid model after+ // it has come back (Claude Code restores it from its own session file and says so), so a+ // later move to that same grid would otherwise capture the grid's model as the+ // "subscription" one and hand it straight back — teaching the bug to itself.+ ? (!session.grid && observed !== grid.model ? observed : (session.subscriptionModel ?? null))+ : (session.subscriptionModel ?? null)+ // What this machine cannot do at all is said first, before the pane is even looked at.+ const target: LaunchSource = {+ gridLaunch: grid,+ codexHome: session.codexHome,+ ...(grid ? {} : { subscriptionModel: remembered }),+ }+ const valid = await validateLaunchOverrides(launchOverridesDeps, session.engine, target)+ if (!valid.ok) return { ok: false, error: valid.error, detail: valid.detail }+ // A resumed opencode session takes its model from its own rows in opencode.db, not from `-m`+ // (see below), and those rows are written through the `sqlite3` CLI. Without it the respawn+ // would land the right provider, key and argv on a pane that then answers on the OLD model —+ // the failure this handler exists to refuse — so it is refused here, before the pane is touched.+ // Only when the launch will name a model: a grid launch always does; a move home does only when+ // the remembered model carries its provider (`subscriptionModel.ts`), and otherwise the engine+ // decides, as it always did. v2 switches the model through OpenCode's own API instead and needs no+ // sqlite3 (`applyOpencodeSessionModel`).+ const rewritesOpencodeSession = session.engine === 'opencode' && !!session.sessionId+ && (!!grid || !!remembered?.includes('/'))+ const opencodeMajor = session.engine === 'opencode' ? opencodeMajorVersion() : null+ if (rewritesOpencodeSession && !isOpencodeV2(opencodeMajor) && !binaryOnPath('sqlite3')) {+ return {+ ok: false,+ error: 'OPENCODE_SQLITE_MISSING',+ detail: 'the sqlite3 CLI is not on PATH, and a resumed opencode session keeps its model unless its store is rewritten — install sqlite3 and retry',+ }+ }+ // The replacement enters the row's folder before it execs: a folder that is gone is refused here,+ // with the other refusals, before the pane is touched or its control taken.+ const missing = workspaceMissing(session.cwd)+ if (missing) return missing+ // Mid-turn is the one state where restarting costs real work: the conversation comes back but+ // whatever the engine was doing does not. The app is told which agents these are so the user can+ // move them once they are done, rather than being asked to choose between losing a turn and losing+ // the grid.+ const capture = await captureTerminal(session.agentId, 100)+ if (!capture) return { ok: false, error: 'TMUX_FAILED' }+ if (!inspectRuntimePane(session.engine, capture).idle) return { ok: false, error: 'AGENT_BUSY' }+ // Nothing may type into the pane while it is being replaced.+ if (restartJobs.busy(session.agentId)) return { ok: false, error: 'AGENT_BUSY' }+ const release = acquireTerminalControl(session.agentId)+ if (!release) return { ok: false, error: 'AGENT_BUSY' }+ // The grid's env and argv, config directory written (keyed on the agent, so moving it between+ // grids rewrites one directory) — or nothing at all for a move back to the engine's own login+ // (clearing uses set-environment, which every supported tmux has). Built from the override the+ // desktop just sent, never from the row: the row is what this call REPLACES. After the refusal+ // guards, so a refused move leaves the live process's own configuration untouched.+ const built = await relaunchOverrides(session, target)+ if (!built.ok) {+ release()+ return { ok: false, error: built.error, detail: built.detail }+ }++ // ⚠️ THE AGENT MUST ADOPT THE NEW PROCESS, OR IT STOPS BEING THE SAME AGENT.+ //+ // Identity in this daemon is keyed on the PROCESS, not the pane: the reconciler matches an existing+ // record to an observation by pid + start marker (`currentProcessKey`), and its same-pane fallback+ // only applies to an agent with no bound engine session. A respawn changes the pid, so left to+ // discovery the new process is an unmatched observation — `onDiscovered` mints a NEW agent id, and+ // the record the user was looking at becomes a ghost that the app still lists, still counts as "on+ // an older target", and still offers to move. Moving it respawns the same pane again. Holding the+ // route shuts the reconciler out for the duration; rebinding below is what ends the swap.+ const routeKey = terminalRouteKey(pane)+ agentReconciler.holdRoute(routeKey)+ try {+ // Back to the engine's own login. Nothing is built, because there is no launch to build. If this+ // agent was launched onto a grid at creation, `new-session -e` wrote the grid's variables into+ // the pane's SESSION environment, which a bare respawn-pane would inherit — clearing them first+ // is what makes the env-less respawn below actually land on the engine's own login instead of+ // silently keeping the old grid. If instead the agent was moved here by an earlier retarget,+ // `respawn-pane -e` set those variables on that one process, not the session, so this clear is+ // a harmless no-op and it is the env-less respawn itself that drops them. Either way the pane+ // ends up clean. Run only after every refusal guard above: an early return with the pane+ // already cleared but its live process untouched would leave that process still talking to the+ // grid while the retarget reports failed — the exact half-applied state this handler exists to+ // refuse.+ //+ // OpenCode's TUI drops `-m` when it RESUMES a session: it restores the model from the session's+ // LAST USER MESSAGE (`data.model`), and its server falls back to the `session.model` column+ // (measured on 1.18.31; upstream anomalyco/opencode #26901). Nothing else — config, model.json,+ // `--fork` — changes a resumed session's model; the picker is the only writer opencode ships,+ // and those two rows are what it writes. So they are written here, through SQL, before the+ // respawn, with the exact `provider/model` the respawn's own `-m` names — and the TUI opens+ // already on it, with nothing typed into the pane. Before the live process is touched, so a+ // write that fails refuses the move with that process still on its old target. A session with+ // no user message yet has nothing to restore from and takes `-m` on launch, so it is skipped.+ //+ // OpenCode 2.0 has no `-m` on its TUI, keeps sessions in tables the SQL above never reads (it+ // used to answer SESSION_NOT_FOUND there, read as success, and then respawn with `-m` into+ // `Unrecognized flag: -m` and a dead pane), and ships its own writer: the service's+ // `session.switchModel`. `applyOpencodeSessionModel` picks per version, and on v2 every+ // failure refuses the move — with the live process still untouched.+ if (rewritesOpencodeSession) {+ const model = built.overrides.sessionModel ? parseOpencodeModelId(built.overrides.sessionModel) : null+ if (model) {+ const written = await applyOpencodeSessionModel({+ opencodeMajor, dbPath: opencodeDb, sessionId: session.sessionId, model, cwd: session.cwd ?? undefined,+ // (A model of opencode's own is looked for in its catalogue; a grid's provider lives in+ // the pane's own config, which the service never reads.)+ checkCatalog: !grid,+ })+ if (!written.ok) {+ console.warn(`[grid] retarget ${sid(session.agentId)} refused · ${written.code} · ${written.detail}`)+ return { ok: false, error: written.code, detail: written.detail }+ }+ }+ }+ if (!grid) {+ const cleared = await tmuxBackend.clearEnv(pane, gridEnvVarNames(session.engine))+ if (cleared.state !== 'succeeded') {+ return { ok: false, error: 'GRID_CLEAR_FAILED', detail: 'reason' in cleared ? cleared.reason : 'tmux would not clear the pane environment' }+ }+ }+ const retargetPermission = await downgradedPermission(session,+ await bypassPermissionFor(session, () => liveBypassPermission(session)), 'retarget')+ const outcome = await restartAgent(+ { engine: session.engine, sessionId: session.sessionId },+ retargetPermission.bypassPermission === true,+ paneSwapDeps(session, pane, built.overrides, retargetPermission.permissionMode ?? null),+ )+ if (!outcome.ok) {+ console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${outcome.detail}`)+ return { ok: false, error: 'RESPAWN_FAILED', detail: outcome.detail }+ }+ // Both are read from the one cached environment of the new pid, so this costs no extra `ps`.+ const [gateway, assignment] = await Promise.all([+ probeGatewayRuntime(outcome.processIdentity),+ probeGridAssignment(outcome.processIdentity, session.engine, outcome.processIdentity.executable),+ ])+ registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)+ // The launch that just worked is the one a restart or a post-reboot restore must repeat — and+ // what it decided about web search is what the app shows for this agent from now on. Null for+ // a move home: the block, and the status with it, leave the frame together.+ registry.setGridLaunch(session.agentId, built.overrides.gridLaunchRecord ?? null)+ // Persisted only on the way OUT, and only once the move actually succeeded — a refused move+ // must not overwrite the model the agent is still sitting on. Survives a daemon restart, so an+ // agent left on a grid for a week still knows where it came from.+ if (grid && remembered) registry.setSubscriptionModel(session.agentId, remembered)+ registry.setActive(session.agentId, true)+ await clearPaneRemainOnExit(pane.paneId)+ const refreshed = registry.byAgent(session.agentId)+ // The app decides whether to still offer a move from what it is told here, so a silent success+ // would leave the banner up over an agent that had already been moved.+ if (refreshed) announceSession(refreshed)+ const how = outcome.resumed ? 'resumed' : 'fresh session'+ const record = built.overrides.gridLaunchRecord+ const where = record+ ? describeGridLaunch(session.engine, record.override, record.webSearch)+ : `${session.engine} on its own login`+ console.log(`${where} · retargeted ${sid(session.agentId)} · ${how}`)+ // Nothing is typed into the pane after the respawn. A resumed opencode session used to be put+ // on its model through the `/models` picker here (MODEL_SELECT_FAILED); its store is rewritten+ // before the respawn instead, see above.+ return { ok: true }+ } finally {+ release()+ agentReconciler.releaseRoute(routeKey)+ }+ }+ return retargetAgent+}diff --git a/cli/src/core/agents/swap.spec.ts b/cli/src/core/agents/swap.spec.tsnew file mode 100644index 000000000..e8adf607e--- /dev/null+++ b/cli/src/core/agents/swap.spec.ts@@ -0,0 +1,125 @@+import { homedir } from 'node:os'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { checkPidRuntime, terminateDeletedAgent } from '../../lib/deleteAgentFallback.js'+import { buildEngineLaunchArgv } from '../../lib/engineLaunch.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { processRows } from '../../lib/terminalAgentDiscovery.js'+import { bypassPermissionActive, resolvePaneEngineProcess } from '../../lib/tmux.js'+import { createPaneSwap, type PaneSwapDeps } from './swap.js'++vi.mock('../../lib/deleteAgentFallback.js', async (real) => ({ ...await real<object>(), terminateDeletedAgent: vi.fn(async () => ({ ok: true })) }))+vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), buildEngineLaunchArgv: vi.fn(() => ['zsh', '-lc', 'claude']) }))+vi.mock('../../lib/terminalAgentDiscovery.js', async (real) => ({ ...await real<object>(), processRows: vi.fn(async () => null) }))+vi.mock('../../lib/tmux.js', async (real) => ({+ ...await real<object>(),+ bypassPermissionActive: vi.fn(() => true),+ resolvePaneEngineProcess: vi.fn(async () => null),+}))++const runtime = { backend: 'tmux', paneId: '%4' } as never+const session = (over: Partial<RegisteredSession> = {}): RegisteredSession =>+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', registeredAt: 100, tmuxPane: '%4', cwd: '/work', ...over }) as RegisteredSession++function setup(row: RegisteredSession | null = session()) {+ const tmuxBackend = {+ holdOpen: vi.fn(async () => ({ state: 'succeeded' })),+ respawn: vi.fn(async () => ({ state: 'succeeded' })),+ }+ const deps: PaneSwapDeps = {+ byAgent: vi.fn(() => row ?? undefined),+ tmuxBackend: tmuxBackend as unknown as PaneSwapDeps['tmuxBackend'],+ prepareSessionResume: vi.fn(),+ }+ return { deps, tmuxBackend, swap: createPaneSwap(deps) }+}++describe('the pane-process swap', () => {+ beforeEach(() => {+ vi.mocked(resolvePaneEngineProcess).mockReset().mockResolvedValue(null)+ vi.mocked(buildEngineLaunchArgv).mockClear()+ })+ afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() })++ it('restarts only the agent it was asked about: same registration, same pane, same engine', () => {+ expect(setup().swap.sameRestartTarget(session())).toBe(true)+ expect(setup(null).swap.sameRestartTarget(session())).toBe(false)+ for (const changed of [{ registeredAt: 101 }, { tmuxPane: '%5' }, { engine: 'codex' }] as Array<Partial<RegisteredSession>>) {+ expect(setup(session(changed)).swap.sameRestartTarget(session()), JSON.stringify(changed)).toBe(false)+ }+ expect(setup().swap.restartJobs).toBeDefined()+ })++ it('prepares the resume, holds the pane open and respawns it in the home folder, saying why when tmux will not', async () => {+ const { deps, tmuxBackend, swap } = setup()+ const swapDeps = swap.paneSwapDeps(session(), runtime, { env: { GRID_KEY: 'k' } })+ swapDeps.prepareResume?.()+ expect(deps.prepareSessionResume).toHaveBeenCalledWith(session())+ expect(await swapDeps.holdOpen()).toEqual({ ok: true })+ tmuxBackend.holdOpen.mockResolvedValueOnce({ state: 'failed', reason: 'pane gone' } as never).mockResolvedValueOnce({ state: 'unknown' } as never)+ expect(await swapDeps.holdOpen()).toEqual({ ok: false, reason: 'pane gone' })+ expect(await swapDeps.holdOpen()).toEqual({ ok: false, reason: 'could not re-arm remain-on-exit' })+ expect(await swapDeps.respawn(['claude', '--resume', 's1'])).toEqual({ ok: true })+ expect(tmuxBackend.respawn).toHaveBeenCalledWith(runtime, { command: ['claude', '--resume', 's1'], cwd: homedir(), env: { GRID_KEY: 'k' } })+ tmuxBackend.respawn.mockResolvedValueOnce({ state: 'failed', reason: 'busy' } as never).mockResolvedValueOnce({ state: 'unknown' } as never)+ expect(await swapDeps.respawn(['claude'])).toEqual({ ok: false, reason: 'busy' })+ expect(await swapDeps.respawn(['claude'])).toEqual({ ok: false, reason: 'tmux respawn-pane did not complete' })+ await swap.paneSwapDeps(session(), runtime).respawn(['claude'])+ expect(tmuxBackend.respawn).toHaveBeenLastCalledWith(runtime, { command: ['claude'], cwd: homedir() })+ })++ it('terminates the engine through the deleted-agent fallback, with real signals and sleeps', async () => {+ const { swap } = setup()+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true)+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ await swap.paneSwapDeps(session(), runtime).terminate(250)+ const [target, used, after] = vi.mocked(terminateDeletedAgent).mock.calls[0]+ expect(target).toEqual(session())+ expect(after).toBe(250)+ expect(used.checkRuntime).toBe(checkPidRuntime)+ used.kill?.(42, 'SIGTERM')+ expect(kill).toHaveBeenCalledWith(42, 'SIGTERM')+ await used.sleep?.(1)+ used.log?.('stopping')+ expect(log).toHaveBeenCalledWith('stopping')+ })++ it('waits for the new process with growing pauses, and gives up once eight seconds have passed', async () => {+ vi.useFakeTimers()+ const { swap } = setup()+ const found = { pid: 99, startMarker: 'now' }+ vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(null).mockResolvedValueOnce(found as never)+ const waiting = swap.paneSwapDeps(session(), runtime).waitForProcess()+ await vi.advanceTimersByTimeAsync(150 + 300)+ expect(await waiting).toEqual(found)+ const never = swap.paneSwapDeps(session(), runtime).waitForProcess()+ // 150, 300, 600, then 750 ms at a time: the budget is spent on the look that crosses 8 s.+ await vi.advanceTimersByTimeAsync(9_000)+ expect(await never).toBeNull()+ })++ it('builds the relaunch argv with the row\'s mode, folder, the caller\'s argv and the keys a grid must clear', () => {+ const { swap } = setup()+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const plain = swap.paneSwapDeps(session({ permissionMode: 'plan' } as Partial<RegisteredSession>), runtime)+ plain.buildArgv({ resumeSessionId: 's1' } as never)+ expect(buildEngineLaunchArgv).toHaveBeenLastCalledWith('claude', { resumeSessionId: 's1', permissionMode: 'plan', cwd: '/work' })+ const grid = swap.paneSwapDeps(session({ cwd: undefined }), runtime, { env: { HARNESS_DSH: 'blender' }, extraArgs: ['--grid'], clearEnv: ['ANTHROPIC_API_KEY'] }, null)+ grid.buildArgv({} as never)+ expect(buildEngineLaunchArgv).toHaveBeenLastCalledWith('claude', { extraArgs: ['--grid'], clearEnv: ['ANTHROPIC_API_KEY'], harnessNode: true })+ swap.paneSwapDeps(session(), runtime, { extraArgs: [], clearEnv: [] }).buildArgv({} as never)+ expect(buildEngineLaunchArgv).toHaveBeenLastCalledWith('claude', { cwd: '/work' })+ grid.log('swapped')+ expect(log).toHaveBeenCalledWith('swapped')+ })++ it('reads the live process\'s bypass flag, and says no when it cannot find the process', async () => {+ const { swap } = setup()+ expect(await swap.liveBypassPermission(session())).toBe(false)+ const identity = { pid: 42, startMarker: 'm1' }+ expect(await swap.liveBypassPermission(session({ processIdentity: identity } as Partial<RegisteredSession>))).toBe(false)+ vi.mocked(processRows).mockResolvedValue([{ pid: 42, startMarker: 'other', args: 'claude' }, { pid: 42, startMarker: 'm1', args: 'claude --dangerously-skip-permissions' }] as never)+ expect(await swap.liveBypassPermission(session({ processIdentity: identity } as Partial<RegisteredSession>))).toBe(true)+ expect(bypassPermissionActive).toHaveBeenCalledWith('claude', 'claude --dangerously-skip-permissions')+ expect(await swap.liveBypassPermission(session({ processIdentity: { pid: 43, startMarker: 'm1' } } as Partial<RegisteredSession>))).toBe(false)+ })+})diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.tsnew file mode 100644index 000000000..9135a5d3b--- /dev/null+++ b/cli/src/core/agents/swap.ts@@ -0,0 +1,124 @@+/**+ * The pane-process swap: kill an agent's engine, respawn it in the pane it was already in, and wait for+ * the new process — what restart and retarget both do, with the restart coordinator that keeps one swap+ * per agent at a time, and the bypass flag the live process was launched with.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).+ */+import { homedir } from 'node:os'+import { checkPidRuntime, terminateDeletedAgent } from '../../lib/deleteAgentFallback.js'+import { buildEngineLaunchArgv } from '../../lib/engineLaunch.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { AgentRestartCoordinator, type RestartAgentDeps } from '../../lib/restartAgent.js'+import { processRows } from '../../lib/terminalAgentDiscovery.js'+import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'+import { bypassPermissionActive, resolvePaneEngineProcess } from '../../lib/tmux.js'+import type { TmuxBackend } from '../../lib/tmuxBackend.js'++export interface PaneSwapDeps {+ byAgent: (agentId: string) => RegisteredSession | undefined+ /** The tmux backend; a swap only ever runs where there is one. */+ tmuxBackend: TmuxBackend | null+ prepareSessionResume: (session: RegisteredSession) => void+}++export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume }: PaneSwapDeps) {+ /**+ * The dependencies a pane-process swap needs, for both callers that do one.+ *+ * Restart and retarget are the same mechanism pointed at different ends: kill the engine, respawn it+ * in the pane it was already in, wait for the new process. They differ only in what the replacement+ * is launched WITH — retarget adds the grid's environment and the argv that configures it — so that+ * is the only thing this takes. Written once because two copies of a kill sequence drift, and the+ * half that drifts is the half nobody ran today.+ */+ const restartJobs = new AgentRestartCoordinator()+ const sameRestartTarget = (session: RegisteredSession): boolean => {+ const current = byAgent(session.agentId)+ return !!current && current.registeredAt === session.registeredAt+ && current.tmuxPane === session.tmuxPane && current.engine === session.engine+ }++ const paneSwapDeps = (+ session: RegisteredSession,+ runtime: TmuxRuntimeRef,+ launch: { env?: Record<string, string>; extraArgs?: readonly string[]; clearEnv?: readonly string[] } = {},+ /** The mode this swap may actually ask for — the row's own, unless the engine on disk has since+ * stopped taking its flag and the caller dropped it (`dropPermissionFlagIfUnsupported`). */+ permissionMode: string | null = session.permissionMode ?? null,+ ): RestartAgentDeps => ({+ prepareResume: () => prepareSessionResume(session),+ holdOpen: async () => {+ const result = await tmuxBackend!.holdOpen(runtime)+ return result.state === 'succeeded'+ ? { ok: true }+ : { ok: false, reason: 'reason' in result ? result.reason : 'could not re-arm remain-on-exit' }+ },+ terminate: (checkAfterMs) => terminateDeletedAgent(session, {+ checkRuntime: checkPidRuntime,+ kill: (pid, signal) => process.kill(pid, signal),+ sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),+ log: (message) => console.log(message),+ }, checkAfterMs),+ respawn: async (argv) => {+ const result = await tmuxBackend!.respawn(runtime, {+ command: argv,+ cwd: homedir(),+ ...(launch.env ? { env: launch.env } : {}),+ })+ return result.state === 'succeeded'+ ? { ok: true }+ : { ok: false, reason: 'reason' in result ? result.reason : 'tmux respawn-pane did not complete' }+ },+ waitForProcess: async () => {+ // Mirrors onCreateAgent's own discovery budget/backoff shape for the same reason: the engine's+ // interactive-login-shell startup, not the tmux call, is the slow half.+ const SWAP_DISCOVERY_BUDGET_MS = 8_000+ let delayMs = 150+ let waited = 0+ while (waited < SWAP_DISCOVERY_BUDGET_MS) {+ await new Promise((resolve) => setTimeout(resolve, delayMs))+ waited += delayMs+ const found = await resolvePaneEngineProcess(runtime.paneId, session.engine)+ if (found) return found+ delayMs = Math.min(delayMs * 2, 750)+ }+ return null+ },+ buildArgv: (opts) => buildEngineLaunchArgv(session.engine, {+ ...opts,+ // The mode picked at create outranks what the live argv said: `bypassPermission` is a yes/no, and+ // Plan or Accept edits would come back as Ask without it.+ ...(permissionMode ? { permissionMode } : {}),+ ...(session.cwd ? { cwd: session.cwd } : {}),+ ...(launch.extraArgs?.length ? { extraArgs: launch.extraArgs } : {}),+ // A pane swap onto a grid has to clear the same vendor credentials a fresh create does, for the+ // same reason and against the same failure: an engine re-exec'd with the grid's variables still+ // sees whatever else the pane inherited, and picks its provider from all of it. This was the+ // gap — a create cleared them, then moving that agent onto a grid from the pane header put them+ // straight back, so the engine came up on Anthropic with a grid selected above it.+ //+ // Named by the caller (`buildLaunchOverrides` derives it from what the grid launch provides), so+ // a swap that sets no grid — back to the engine's own login, or a Codex profile's CODEX_HOME —+ // clears nothing. There the user's own variables are the point.+ ...(launch.clearEnv?.length ? { clearEnv: launch.clearEnv } : {}),+ ...(launch.env?.HARNESS_DSH ? { harnessNode: true } : {}),+ }),+ log: (message) => console.log(message),+ })++ /** The bypass-permission flag the LIVE process was launched with. The fallback behind+ * `bypassPermissionFor` for a row that recorded neither a mode nor the flag (written before either+ * was persisted, and not yet seen by a discovery scan); read before anything is signalled. */+ const liveBypassPermission = async (session: RegisteredSession): Promise<boolean> => {+ const identity = session.processIdentity+ if (!identity) return false+ const rows = await processRows()+ const row = rows?.find((candidate) =>+ candidate.pid === identity.pid && candidate.startMarker === identity.startMarker)+ return row ? bypassPermissionActive(session.engine, row.args) : false+ }+ return { restartJobs, sameRestartTarget, paneSwapDeps, liveBypassPermission }+}++export type PaneSwap = ReturnType<typeof createPaneSwap>diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex 052654e42..ce41929c3 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -391,6 +391,13 @@ Done so far:that passed its canary but crashed the core restarted every machine on it once a minute. Testedend to end on real release bundles served from a local manifest (`e2e/update.e2e.ts`): one kept,one rolled back and left alone, then a newer one kept.+- **The core boundary, steps 1 to 11** (#716, #717, #721, #723, #725 and part 6): `runForeground`+ is down from 5,306 lines to 2,880. 29 modules under `cli/src/core` hold terminal control, session+ events, the normalizer table, input, questions, the turns (activity, heartbeats, recaps, the event+ funnel, stop hooks, the agy backstop, cancel), the transcripts (attach, ingest, last turn) and the+ agent lifecycle (forget, bind, discovery, launch, new panes, adoption, create, fork, the pane swap,+ retarget, restart, stop, purge, resume, close). Each file is held to 100% by `npm run test:core`,+ which CI runs; the unit and e2e suites pass at every step. Steps 12 to 14 remain.Next, in order: