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
feat(grid): move a RUNNING agent onto the picked grid, keeping the agent
Dev jacob26cf7c55b18f
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex a3d54924f..f4feb7a95 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -302,6 +302,15 @@ export class BackendSocket {grid: GridLaunchOverride | null}) =>Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null+ /**+ * Called on `agent_retarget` — cli.ts re-execs an EXISTING agent's pane against a different grid.+ *+ * Separate from `onCreateAgent` because it is a different promise: the pane, its id and its+ * scrollback survive, and only the process is replaced. A running process's environment cannot be+ * edited, so there is no gentler way to move an agent that is already up.+ */+ onRetargetAgent: ((input: { agentId: string; grid: GridLaunchOverride }) =>+ Promise<{ ok: true } | { ok: false; error: string; detail?: string }>) | null = null/** Called when the web/device sends chat input to an agent terminal. */onMessage: ((sessionId: string, content: string) => void) | null = null/** Best-effort terminal-native title sync after a user renames an agent. */@@ -1309,6 +1318,32 @@ export class BackendSocket {return}+ // Move a RUNNING agent onto a grid. The pane survives; its process is re-exec'd with the+ // engine's grid environment and, when one is bound, `--resume <session>` so the conversation+ // comes back. Refused rather than half-applied: see cli.ts for what it checks first.+ case 'agent_retarget': {+ const agentId = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)+ if (!agentId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }+ if (!this.onRetargetAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }+ const target = parseGridLaunchOverride(payload.grid)+ // Unlike agent_create, an absent grid is meaningless here: this frame exists only to move an+ // agent somewhere, so nowhere is a malformed request rather than "leave it alone".+ if (target.state !== 'ok') {+ reply(type, requestId, {+ error: 'INVALID_GRID',+ detail: target.state === 'invalid' ? target.reason : 'grid is required',+ })+ return+ }+ const moved = await this.onRetargetAgent({ agentId, grid: target.override })+ if (!moved.ok) {+ reply(type, requestId, moved.detail ? { error: moved.error, detail: moved.detail } : { error: moved.error })+ return+ }+ reply(type, requestId, { retargeted: true })+ return+ }+// Delete an agent: signal its validated engine process and drop it from the list. Idempotent — an already// gone target still acks + re-emits agent_deleted so the web/device converge. E2EE-gated (the// frame arrived decrypted). Keeps the persisted recap + agent name for a later resume.@@ -1423,6 +1458,7 @@ export class BackendSocket {private async toProject(s: RegisteredSession): Promise<{id: string; sessionId: string; userId: string; name: string; status: stringcreatedAt: string; updatedAt: string; tmuxPane: string | null; terminal: { available: boolean; primary: string; runtimes: RegisteredSession['runtimes'] }; engine: RegisteredSession['engine']; selectedModel: string | null+ grid: { baseUrl: string; model: string | null } | null}> {const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : nullreturn {@@ -1437,6 +1473,9 @@ export class BackendSocket {terminal: { available: registry.terminalAvailable(s.agentId), primary: s.primaryRuntimeKey, runtimes: s.runtimes },engine: s.engine,selectedModel: this.runtimeProfileProvider?.(s) ?? null,+ // Where this agent's inference actually goes, so the app can tell which agents a newly picked+ // grid has left behind. Read off the live process by discovery; carries no credential.+ grid: s.grid ?? null,}}}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 065d7aa81..b33328713 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -66,7 +66,7 @@ import { TerminalStreamManager } from './lib/terminalStreamManager.js'import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'import { processRows, type DiscoveredTerminalAgent } from './lib/terminalAgentDiscovery.js'-import { terminalActionNotStarted, type HookTerminalHint, type TerminalActionResult, type TerminalRuntimeRef } from './lib/terminalTypes.js'+import { terminalActionNotStarted, type HookTerminalHint, type TerminalActionResult, type TerminalRuntimeRef, type TmuxRuntimeRef } from './lib/terminalTypes.js'import { readTerminalConfigSnapshot, writeTerminalConfigSnapshot } from './lib/terminalConfigSnapshot.js'import { Watcher, type LineEvent } from './watcher/watcher.js'import { chooseHookAgent, startHookServer } from './hookServer.js'@@ -128,10 +128,11 @@ import {lastCommandCodeTurnText,} from './engines/commandcode/normalizer.js'import { probeGatewayRuntime } from './lib/gatewayRuntime.js'+import { probeGridAssignment } from './lib/gridAssignment.js'import { SessionInputController } from './lib/sessionInput.js'import { adaptSlashCommand } from './lib/goalCommand.js'import { RuntimeProfileManager } from './lib/runtimeProfile.js'-import { RuntimeProfileController } from './lib/runtimeProfileController.js'+import { RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'import { deviceErrorText } from './lib/deviceErrors.js'import { correlateAgentEvent, turnHeartbeatFrame } from './lib/agentEvent.js'@@ -1998,6 +1999,7 @@ async function runForeground(session: AuthSession): Promise<void> {cwd: observed.cwd,processIdentity: observed.processIdentity,gateway: observed.gateway,+ grid: observed.grid,})if (!opened) returnif (opened.evicted) console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted)}`)@@ -2010,7 +2012,7 @@ async function runForeground(session: AuthSession): Promise<void> {onObserved: async (observed, current) => {const wasDormant = !current.activeregistry.updateRuntimes(current.agentId, observed.runtimes, observed.primaryRuntimeKey)- registry.updateProcessIdentity(current.agentId, observed.processIdentity, observed.gateway)+ registry.updateProcessIdentity(current.agentId, observed.processIdentity, observed.gateway, observed.grid)await bindObservedAgent(observed)if (wasDormant) {const active = registry.byAgent(current.agentId)@@ -2856,6 +2858,102 @@ async function runForeground(session: AuthSession): Promise<void> {return { ok: false, error: 'ENGINE_DID_NOT_START', detail }}+ /**+ * 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 (!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. A Herdr-hosted agent has no equivalent, and 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` }+ const built = buildGridEngineEnv(session.engine, grid)+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }+ if (!(await tmuxSupportsSessionEnv())) {+ return {+ ok: false,+ error: 'TMUX_TOO_OLD_FOR_GRID',+ detail: `this machine's tmux is older than ${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, `+ + 'which is the first version that can give a respawned pane its own environment.',+ }+ }+ // 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.+ const release = acquireTerminalControl(session.agentId)+ if (!release) return { ok: false, error: 'AGENT_BUSY' }+ try {+ const launchOptions = { resumeSessionId: session.sessionId || null }+ const respawned = await tmuxBackend.respawn(pane, {+ ...(session.cwd ? { cwd: session.cwd } : {}),+ command: buildEngineLaunchArgv(session.engine, launchOptions),+ env: built.env,+ })+ if (respawned.state !== 'succeeded') {+ console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${respawned.reason}`)+ return { ok: false, error: 'RESPAWN_FAILED', detail: respawned.reason }+ }+ console.log(`${describeGridLaunch(session.engine, grid)} · retargeted ${sid(session.agentId)}`)+ } finally {+ release()+ }+ // ⚠️ 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. That loop is what this adoption prevents.+ //+ // The wait is the same one `onCreateAgent` measured: a freshly exec'd engine is not in `ps` the+ // instant tmux returns, because the user's interactive login shell runs first.+ const previousPid = session.processIdentity?.pid+ const deadline = Date.now() + 8_000+ let delayMs = 150+ let adopted = false+ while (!adopted && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, delayMs))+ const identity = await resolvePaneEngineProcess(pane.paneId, session.engine)+ if (identity && identity.pid !== previousPid) {+ // 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(identity),+ probeGridAssignment(identity),+ ])+ registry.updateProcessIdentity(session.agentId, identity, gateway.kind, assignment)+ adopted = true+ break+ }+ delayMs = Math.min(delayMs * 2, 750)+ }+ if (!adopted) {+ // The respawn itself succeeded — only the adoption ran out of patience, and the periodic+ // reconcile will pick the pane up. Reporting a failure would send the user to redo something+ // that already happened.+ console.warn(`[grid] retarget ${sid(session.agentId)} · respawned, but its new process was not adopted in time`)+ }+ await agentReconciler.triggerHint({ backend: 'tmux', paneId: pane.paneId }, session.engine)+ await clearPaneRemainOnExit(pane.paneId)+ return { ok: true }+ }+/*** Web or device deleted an agent (`agent_delete`): end the AGENT, not the user's window.*diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex 5a4f08296..edd5770e6 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -28,8 +28,29 @@ export const BYPASS_PERMISSION_FLAGS: Readonly<Record<AgentEngine, string[] | nucopilot: null,}+/**+ * How to name an existing session on the command line, for the engines that need it here.+ *+ * Deliberately separate from `RESUME_ARGS` in `tmux.ts`, which reads argv the other way round to+ * recover an id and omits claude on purpose. This table is for WRITING a launch, and it exists for+ * one caller: moving a running agent to a grid re-execs it, and an engine that came back empty would+ * have thrown away the conversation the user was in the middle of. Only engines that can be pointed+ * at a grid at all need an entry — see `GRID_ENGINE_ENV` in `gridLaunch.ts`.+ */+export const RESUME_FLAGS: Partial<Record<AgentEngine, string>> = {+ claude: '--resume',+}+export interface LaunchCommandOptions {bypassPermission?: boolean+ /**+ * Resume this engine session instead of starting a new conversation.+ *+ * Ignored when the engine has no entry in [RESUME_FLAGS], and callers pass null for an agent that+ * has not bound a session yet — there is nothing to resume, and guessing with a `--continue` style+ * flag could attach a DIFFERENT agent's conversation from the same folder.+ */+ resumeSessionId?: string | null}/** The executable argv, before the interactive-shell wrapper is applied. */@@ -39,6 +60,8 @@ export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandOconst flags = BYPASS_PERMISSION_FLAGS[engine]if (flags) argv.push(...flags)}+ const resumeFlag = opts.resumeSessionId ? RESUME_FLAGS[engine] : undefined+ if (resumeFlag) argv.push(resumeFlag, opts.resumeSessionId as string)return argv}diff --git a/cli/src/lib/gatewayRuntime.ts b/cli/src/lib/gatewayRuntime.tsindex bc3359643..fcc8f9b22 100644--- a/cli/src/lib/gatewayRuntime.ts+++ b/cli/src/lib/gatewayRuntime.ts@@ -17,10 +17,13 @@* The key is held in memory only: never written to the registry, never logged, never sent to the backend.*/-import { execFile } from 'node:child_process'-import { readFile } from 'node:fs/promises'+import { readProcessEnv } from './processEnv.js'import type { ProcessIdentity } from './registry.js'+// Moved to processEnv.ts once the grid probe needed the same read; re-exported so the callers and+// specs that already knew them here keep working.+export { parseEnviron, parsePsEnviron } from './processEnv.js'+export interface GatewayRuntime {/** 'ori' ⇔ an OpenRouter endpoint is in play. null = a normal vendor login, or we could not look. */kind: 'ori' | null@@ -90,48 +93,6 @@ export function argvNamesOpenRouterProvider(args: string): boolean {|| /model_providers\.openrouter\./.test(args)}-/** NUL-separated `/proc/<pid>/environ`. */-export function parseEnviron(blob: string): Record<string, string> {- const out: Record<string, string> = {}- for (const entry of blob.split('\0')) {- const eq = entry.indexOf('=')- if (eq > 0) out[entry.slice(0, eq)] = entry.slice(eq + 1)- }- return out-}--/**- * macOS `ps eww -p <pid> -o command=`: argv first, then `KEY=VALUE` pairs, all space-separated with no- * quoting. A value containing spaces is therefore only recoverable by reading up to the next token that- * starts a new variable — which is exactly what this does. Leading argv is skipped by the same rule- * (`--flag=x` cannot start a variable), and the keys we care about never carry spaces anyway.- */-export function parsePsEnviron(line: string): Record<string, string> {- const out: Record<string, string> = {}- let key: string | null = null- for (const token of line.trim().split(/\s+/)) {- const eq = token.indexOf('=')- if (eq > 0 && /^[A-Za-z_][A-Za-z0-9_]*$/.test(token.slice(0, eq))) {- key = token.slice(0, eq)- out[key] = token.slice(eq + 1)- } else if (key) {- out[key] += ` ${token}`- }- }- return out-}--function readProcessEnv(pid: number): Promise<Record<string, string> | null> {- if (process.platform === 'linux') {- return readFile(`/proc/${pid}/environ`, 'utf8').then(parseEnviron).catch(() => null)- }- return new Promise((resolve) => {- execFile('ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {- resolve(err && !stdout ? null : parsePsEnviron(stdout))- })- })-}-/** Classify an already-read env + argv. Exported for fixtures; the probe below adds I/O and caching. */export function classifyGatewayRuntime(processEnv: Record<string, string>, args = ''): GatewayRuntime {const routed = BASE_URL_VARS.some((name) => isOpenRouterUrl(processEnv[name]))@@ -151,7 +112,7 @@ export async function probeGatewayRuntime(identity: ProcessIdentity, args = ''):const hit = cache.get(key)if (hit && (hit.runtime.kind !== null || Date.now() - hit.at < NEGATIVE_TTL_MS)) return hit.runtime- const processEnv = await readProcessEnv(identity.pid)+ const processEnv = await readProcessEnv(identity)if (!processEnv) return argvNamesOpenRouterProvider(args) ? { kind: 'ori' } : NONEconst runtime = classifyGatewayRuntime(processEnv, args)diff --git a/cli/src/lib/gridAssignment.spec.ts b/cli/src/lib/gridAssignment.spec.tsnew file mode 100644index 000000000..75376c441--- /dev/null+++ b/cli/src/lib/gridAssignment.spec.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest'+import { assignmentMatches, classifyGridAssignment } from './gridAssignment.js'+import { parsePsEnviron } from './processEnv.js'++const RELAY = 'https://grid.autonomous.ai/grid-3378218621364f16/relay'++describe('classifyGridAssignment', () => {+ it('reads the endpoint and the pinned model off the process', () => {+ expect(classifyGridAssignment({+ ANTHROPIC_BASE_URL: RELAY,+ ANTHROPIC_MODEL: 'DeepSeek-V4-Flash-0731',+ ANTHROPIC_AUTH_TOKEN: 'gridkey-secret',+ })).toEqual({ baseUrl: RELAY, model: 'DeepSeek-V4-Flash-0731' })+ })++ it('never carries the credential out of the process', () => {+ const assignment = classifyGridAssignment({+ ANTHROPIC_BASE_URL: RELAY,+ ANTHROPIC_AUTH_TOKEN: 'gridkey-secret',+ })+ expect(JSON.stringify(assignment)).not.toContain('gridkey-secret')+ expect(assignment).toEqual({ baseUrl: RELAY, model: null })+ })++ it('leaves an agent the user pointed somewhere else alone', () => {+ // Offering to "move" these away from where they were deliberately sent would be the app+ // overruling a choice it did not make.+ expect(classifyGridAssignment({ ANTHROPIC_BASE_URL: 'https://openrouter.ai/api' })).toBeNull()+ expect(classifyGridAssignment({ ANTHROPIC_BASE_URL: 'http://localhost:8080/v1' })).toBeNull()+ expect(classifyGridAssignment({})).toBeNull()+ expect(classifyGridAssignment({ ANTHROPIC_BASE_URL: ' ' })).toBeNull()+ expect(classifyGridAssignment({ ANTHROPIC_BASE_URL: 'not a url' })).toBeNull()+ })++ it('reads a real macOS `ps eww` line, which is how this actually arrives', () => {+ const line = `/Users/u/.local/bin/claude --resume abc ANTHROPIC_BASE_URL=${RELAY}`+ + ' ANTHROPIC_AUTH_TOKEN=gridkey-secret ANTHROPIC_MODEL=GLM-4.7-Flash HOME=/Users/u'+ expect(classifyGridAssignment(parsePsEnviron(line)))+ .toEqual({ baseUrl: RELAY, model: 'GLM-4.7-Flash' })+ })+})++describe('assignmentMatches', () => {+ const assignment = { baseUrl: RELAY, model: 'GLM-4.7-Flash' }++ it('matches the grid and the model the user picked', () => {+ expect(assignmentMatches(assignment, 'grid-3378218621364f16', 'GLM-4.7-Flash')).toBe(true)+ })++ it('does not match a different grid, or the same grid on a different model', () => {+ expect(assignmentMatches(assignment, 'grid-e3b210eacc5b4cdf', 'GLM-4.7-Flash')).toBe(false)+ expect(assignmentMatches(assignment, 'grid-3378218621364f16', 'DeepSeek-V4-Flash-0731')).toBe(false)+ expect(assignmentMatches(assignment, 'grid-3378218621364f16', null)).toBe(false)+ })++ it('treats an unknown assignment as not matching, never as fine', () => {+ // The whole point: "we could not tell" must cost a needless move offer, never a silent claim that+ // an agent is already where the user asked for.+ expect(assignmentMatches(null, 'grid-3378218621364f16', null)).toBe(false)+ expect(assignmentMatches(undefined, 'grid-3378218621364f16', null)).toBe(false)+ })++ it('matches an unpinned model only against an unpinned choice', () => {+ const unpinned = { baseUrl: RELAY, model: null }+ expect(assignmentMatches(unpinned, 'grid-3378218621364f16', null)).toBe(true)+ expect(assignmentMatches(unpinned, 'grid-3378218621364f16', 'GLM-4.7-Flash')).toBe(false)+ })+})diff --git a/cli/src/lib/gridAssignment.ts b/cli/src/lib/gridAssignment.tsnew file mode 100644index 000000000..6cea720b5--- /dev/null+++ b/cli/src/lib/gridAssignment.ts@@ -0,0 +1,86 @@+/**+ * Which grid is a running agent ACTUALLY on?+ *+ * The desktop app can point an agent at a grid when it is created (`gridLaunch.ts`), and can move an+ * existing one (`agent_retarget`). Both work by setting the engine's environment, which means the+ * answer is not in any record this daemon keeps — it is in the process. So it is read from the process,+ * the same way `gatewayRuntime.ts` reads which endpoint a pane is talking to, and for the same reason:+ * a bookkeeping map drifts the moment anything happens that the bookkeeper did not do, and plenty does.+ * A daemon restart forgets nothing. An agent the user started themselves with `ANTHROPIC_BASE_URL=…`+ * in their own shell — which this product discovers and adopts — reports the truth rather than "none".+ *+ * **The key is never read.** The pane's credential is the pane's business; what leaves here is the+ * endpoint and the model, both of which the app already knows because it chose them.+ */++import { readProcessEnv } from './processEnv.js'+import type { ProcessIdentity } from './registry.js'++/** Where an agent's inference goes, as far as anyone outside the pane needs to know. */+export interface GridAssignment {+ /** `ANTHROPIC_BASE_URL` verbatim — the grid id is a path segment inside it. */+ baseUrl: string+ /** `ANTHROPIC_MODEL`, when the launch pinned one. Null = the engine's own choice. */+ model: string | null+}++/**+ * Only Claude Code can be pointed at a grid today (see `GRID_ENGINE_ENV`), so only its variables are+ * read. An engine that gains an environment contract gets its variables added here at the same time.+ */+const BASE_URL_VAR = 'ANTHROPIC_BASE_URL'+const MODEL_VAR = 'ANTHROPIC_MODEL'++/**+ * A base URL that is not a grid is not an assignment.+ *+ * An agent can be pointed somewhere else entirely — OpenRouter through `ori`, a corporate proxy, a+ * local llama server — and reporting those as "on a grid" would make the app offer to move an agent+ * away from a place the user deliberately sent it.+ */+function isGridUrl(value: string): boolean {+ try {+ // The relay always lives under `/relay`, whatever host serves it — that is the one part of the+ // shape the control plane and both CLIs agree on (`<grid>/relay` for Messages, `/relay/v1` for+ // OpenAI clients). Matching on the host would pin this to one deployment.+ return new URL(value).pathname.split('/').includes('relay')+ } catch {+ return false+ }+}++/** Classify an already-read environment. Exported so a spec can pin the rules without any I/O. */+export function classifyGridAssignment(processEnv: Record<string, string>): GridAssignment | null {+ const baseUrl = processEnv[BASE_URL_VAR]?.trim()+ if (!baseUrl || !isGridUrl(baseUrl)) return null+ const model = processEnv[MODEL_VAR]?.trim()+ return { baseUrl, model: model || null }+}++/**+ * Read one live engine process's grid.+ *+ * Null covers both "not on a grid" and "could not look", deliberately: the caller renders an agent+ * whose assignment is unknown the same as one with none, which at worst offers a move that turns out+ * to be a no-op. The opposite error — claiming an agent is already on the right grid when nobody+ * checked — would leave it quietly running somewhere else.+ */+export async function probeGridAssignment(identity: ProcessIdentity): Promise<GridAssignment | null> {+ const processEnv = await readProcessEnv(identity)+ return processEnv ? classifyGridAssignment(processEnv) : null+}++/** Is this agent already where `networkId` is served? */+export function assignmentMatches(+ assignment: GridAssignment | null | undefined,+ networkId: string,+ model: string | null,+): boolean {+ if (!assignment) return false+ // Containment rather than a parsed id: the grid id IS a path segment of the relay URL today, and+ // asking "does this endpoint name the grid I picked" survives a control plane that rearranges the+ // rest of the path. A false negative costs one needless move; a false positive would leave an agent+ // somewhere the user did not choose and say it was fine.+ if (!assignment.baseUrl.includes(networkId)) return false+ return (assignment.model ?? null) === (model ?? null)+}diff --git a/cli/src/lib/processEnv.ts b/cli/src/lib/processEnv.tsnew file mode 100644index 000000000..7d00ef811--- /dev/null+++ b/cli/src/lib/processEnv.ts@@ -0,0 +1,93 @@+/**+ * Reading the environment of a live engine process.+ *+ * Two things about a pane are decided at `execve` and readable nowhere else: which endpoint the engine+ * talks to (`gatewayRuntime.ts`) and which grid it was pointed at (`gridAssignment.ts`). Both are+ * questions about the SAME process, so the read lives here and both ask through it — one `ps` per+ * agent, not one per question.+ *+ * Nothing here interprets or stores what it reads. A process environment is the user's business: the+ * callers pick out the handful of variables they have a reason to look at, and the rest is passed+ * through and dropped.+ */++import { execFile } from 'node:child_process'+import { readFile } from 'node:fs/promises'+import type { ProcessIdentity } from './registry.js'++/** NUL-separated `/proc/<pid>/environ`. */+export function parseEnviron(blob: string): Record<string, string> {+ const out: Record<string, string> = {}+ for (const entry of blob.split('\0')) {+ const eq = entry.indexOf('=')+ if (eq > 0) out[entry.slice(0, eq)] = entry.slice(eq + 1)+ }+ return out+}++/**+ * macOS `ps eww -p <pid> -o command=`: argv first, then `KEY=VALUE` pairs, all space-separated with no+ * quoting. A value containing spaces is therefore only recoverable by reading up to the next token that+ * starts a new variable — which is exactly what this does. Leading argv is skipped by the same rule+ * (`--flag=x` cannot start a variable), and the keys we care about never carry spaces anyway.+ */+export function parsePsEnviron(line: string): Record<string, string> {+ const out: Record<string, string> = {}+ let key: string | null = null+ for (const token of line.trim().split(/\s+/)) {+ const eq = token.indexOf('=')+ if (eq > 0 && /^[A-Za-z_][A-Za-z0-9_]*$/.test(token.slice(0, eq))) {+ key = token.slice(0, eq)+ out[key] = token.slice(eq + 1)+ } else if (key) {+ out[key] += ` ${token}`+ }+ }+ return out+}++function read(pid: number): Promise<Record<string, string> | null> {+ if (process.platform === 'linux') {+ return readFile(`/proc/${pid}/environ`, 'utf8').then(parseEnviron).catch(() => null)+ }+ return new Promise((resolve) => {+ execFile('ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {+ resolve(err && !stdout ? null : parsePsEnviron(stdout))+ })+ })+}++/**+ * A process's environment cannot change under it, so a read is permanent — for that process.+ *+ * The TTL is not about the environment changing. It is about having read the WRONG process: a launcher+ * like `ori claude` is discoverable for the ~100ms before it `execve`s the vendor binary away, and on+ * macOS `comm` truncates to 16 characters, so `~/.local/bin/ori` and `~/.local/bin/claude` are the same+ * cache key and the exec is invisible. Expiring the entry closes that window — and every other one like+ * it — for one extra `ps` per agent per minute. See `gatewayRuntime.ts`, where this was measured.+ *+ * A failed read is never cached: "we could not look" must not harden into an answer.+ */+const cache = new Map<string, { env: Record<string, string>; at: number }>()+const CACHE_LIMIT = 256+const TTL_MS = 60_000++export function processEnvCacheKey(identity: ProcessIdentity): string {+ return `${identity.pid}\u0000${identity.startMarker}\u0000${identity.executable}`+}++export function clearProcessEnvCache(): void {+ cache.clear()+}++/** The live environment of `identity`, or null when it could not be read. */+export async function readProcessEnv(identity: ProcessIdentity): Promise<Record<string, string> | null> {+ const key = processEnvCacheKey(identity)+ const hit = cache.get(key)+ if (hit && Date.now() - hit.at < TTL_MS) return hit.env+ const env = await read(identity.pid)+ if (!env) return null+ if (cache.size >= CACHE_LIMIT) cache.clear()+ cache.set(key, { env, at: Date.now() })+ return env+}diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 7fb2d5f9f..1d5e45357 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -36,6 +36,7 @@ import { uptime } from 'os'import { env } from '../config/env.js'import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'import { ENGINES, type AgentEngine } from '../engines/types.js'+import type { GridAssignment } from './gridAssignment.js'import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'import { agyTranscriptPath } from '../engines/agy/session.js'import { copilotTranscriptPath } from '../engines/copilot/session.js'@@ -85,6 +86,11 @@ export interface RegisteredSession {* discovery, so a pane restarted without the wrapper drops it on the next scan.*/gateway?: 'ori' | null+ /**+ * The grid this pane's engine is pointed at, if any — read off the live process on every discovery+ * exactly like `gateway`, never declared. See `gridAssignment.ts`. Carries no credential.+ */+ grid?: GridAssignment | null/** Legacy launcher-owned snapshots may still contain this field. New records never write it. */launcherId?: stringtranscriptPath: string | null@@ -787,6 +793,7 @@ class Registry {cwd?: string | nullprocessIdentity: ProcessIdentitygateway?: 'ori' | null+ grid?: GridAssignment | null}):{ entry: RegisteredSession; isNew: boolean; evicted: string | null } | null {if (this.writeBlocked) return null@@ -820,6 +827,7 @@ class Registry {// Only a successful read speaks: an undefined probe (ps failed, /proc unreadable) keeps whatever// the last good one said rather than silently downgrading a gateway agent to a vendor one.if (input.gateway !== undefined) existing.gateway = input.gateway+ if (input.grid !== undefined) existing.grid = input.gridexisting.updatedAt = Date.now()this.index(existing)this.terminalAvailableAgents.add(existing.agentId)@@ -851,6 +859,7 @@ class Registry {boundAt: null,engine,gateway: input.gateway ?? null,+ grid: input.grid ?? null,transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,@@ -1091,7 +1100,12 @@ class Registry {return this.bySession(sessionId)}- updateProcessIdentity(sessionId: string, processIdentity: ProcessIdentity, gateway?: 'ori' | null): boolean {+ updateProcessIdentity(+ sessionId: string,+ processIdentity: ProcessIdentity,+ gateway?: 'ori' | null,+ grid?: GridAssignment | null,+ ): boolean {const session = this.resolve(sessionId)if (!session || !validProcessIdentity(processIdentity)) return falsethis.drop(session)@@ -1099,6 +1113,9 @@ class Registry {// A record written before gateways existed, or by a pass whose probe failed, learns it here — the// env cannot change under a running process, so a successful read is always the truth for this pid.if (gateway !== undefined) session.gateway = gateway+ // The grid is read from the same environment and follows the same rule. It matters most right+ // after a retarget: the respawned pane is a new pid, and this is where its new grid lands.+ if (grid !== undefined) session.grid = gridsession.updatedAt = Date.now()this.index(session)this.save()diff --git a/cli/src/lib/terminalAgentDiscovery.grid.spec.ts b/cli/src/lib/terminalAgentDiscovery.grid.spec.tsnew file mode 100644index 000000000..22a67dce5--- /dev/null+++ b/cli/src/lib/terminalAgentDiscovery.grid.spec.ts@@ -0,0 +1,104 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { ProcessRow } from './tmux.js'+import type { TerminalBackend } from './terminalBackend.js'+import type { TerminalRootObservation, TerminalRuntimeRef } from './terminalTypes.js'++/**+ * The grid an agent is on has to ride the LIVE discovery path, exactly like `gateway` before it.+ *+ * This repo has already paid for this once: a probe wired onto `probeTmuxAgents` kept its own tests+ * green while the reconciler had moved to `probeTerminalAgents`, and every agent silently arrived+ * with the field undefined (see `terminalAgentDiscovery.gateway.spec.ts`). Nothing would go red here+ * either — the app would simply believe every agent is on no grid, offer to move ones that are+ * already right, and restart them for nothing. So the wiring is pinned, not the classifier+ * (`gridAssignment.spec.ts` covers that).+ */++const probeGatewayRuntime = vi.hoisted(() => vi.fn())+const probeGridAssignment = vi.hoisted(() => vi.fn())+const processRows = vi.hoisted(() => vi.fn())++vi.mock('./gatewayRuntime.js', () => ({ probeGatewayRuntime }))+vi.mock('./gridAssignment.js', () => ({ probeGridAssignment }))+vi.mock('./tmux.js', async (importOriginal) => ({+ ...await importOriginal<typeof import('./tmux.js')>(),+ processRows,+}))++const { probeTerminalAgents } = await import('./terminalAgentDiscovery.js')++const START = 'Sat Aug 15 10:00:00 2026'+const row = (pid: number, parentPid: number, executable: string, args = executable): ProcessRow =>+ ({ pid, parentPid, executable, startMarker: START, args })++const TMUX_RUNTIME: TerminalRuntimeRef = { backend: 'tmux', paneId: '%1' }+const HERDR_RUNTIME: TerminalRuntimeRef = {+ backend: 'herdr', endpointId: 'endpoint-a', sessionName: 'default', terminalId: 'terminal-a', paneId: 'w1:p1',+}+const ASSIGNMENT = { baseUrl: 'https://grid.autonomous.ai/grid-3378218621364f16/relay', model: 'GLM-4.7-Flash' }++function backendWith(name: 'tmux' | 'herdr', instanceId: string, roots: TerminalRootObservation[]): TerminalBackend {+ return {+ name,+ instanceId,+ inventory: async () => ({ state: 'available', roots }),+ } as unknown as TerminalBackend+}++beforeEach(() => {+ probeGatewayRuntime.mockReset()+ probeGatewayRuntime.mockResolvedValue({ kind: null })+ probeGridAssignment.mockReset()+ processRows.mockReset()+})++describe('grid assignment on the live terminal discovery path', () => {+ it('reports the grid under EITHER backend, from the process rather than the pane', async () => {+ processRows.mockResolvedValue([+ row(10, 1, 'bash'), row(30, 10, 'claude'),+ row(20, 1, 'bash'), row(40, 20, 'codex'),+ ])+ probeGridAssignment.mockResolvedValue(ASSIGNMENT)++ const probe = await probeTerminalAgents(+ [+ backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }]),+ backendWith('herdr', 'herdr:endpoint-a', [{ runtime: HERDR_RUNTIME, rootPid: 20, cwd: '/work' }]),+ ],+ ['tmux', 'herdr'],+ ['default'],+ 999,+ )++ expect(probe.agents).toHaveLength(2)+ expect(probe.agents.every((agent) => agent.grid === ASSIGNMENT)).toBe(true)+ expect(probeGridAssignment).toHaveBeenCalledTimes(2)+ for (const [identity] of probeGridAssignment.mock.calls) {+ expect(identity).toMatchObject({ startMarker: START })+ }+ })++ it('reports null for an agent on its own login', async () => {+ processRows.mockResolvedValue([row(10, 1, 'bash'), row(30, 10, 'claude')])+ probeGridAssignment.mockResolvedValue(null)+ const probe = await probeTerminalAgents(+ [backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])],+ ['tmux'],+ [],+ 999,+ )+ expect(probe.agents[0].grid).toBeNull()+ })++ it('does not probe when the process table is unavailable', async () => {+ processRows.mockResolvedValue(null)+ const probe = await probeTerminalAgents(+ [backendWith('tmux', 'tmux', [{ runtime: TMUX_RUNTIME, rootPid: 10, cwd: '/work' }])],+ ['tmux'],+ [],+ 999,+ )+ expect(probe.processTableAvailable).toBe(false)+ expect(probeGridAssignment).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.tsindex 442f32f83..f6fec3a45 100644--- a/cli/src/lib/terminalAgentDiscovery.ts+++ b/cli/src/lib/terminalAgentDiscovery.ts@@ -6,6 +6,7 @@ import {type AgentCommandOwnershipSnapshot,} from './engineBin.js'import { probeGatewayRuntime } from './gatewayRuntime.js'+import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'import type { TerminalBackend } from './terminalBackend.js'import {ambiguousAgentProcess,@@ -43,6 +44,13 @@ export interface DiscoveredTerminalAgent {* gateway launch is recognized identically under tmux and under Herdr.*/gateway?: 'ori' | null+ /**+ * The grid this engine process is pointed at, read from the same environment. null = a vendor login+ * or an unreadable probe — `gridAssignment.ts` explains why those share an answer.+ *+ * Backend-agnostic for the same reason `gateway` is: it is a fact about the process, not the pane.+ */+ grid?: GridAssignment | null}export interface TerminalTargetProbe {@@ -235,6 +243,8 @@ export async function probeTerminalAgents(await Promise.all(discovered.agents.map(async (agent) => {const runtime = await probeGatewayRuntime(agent.processIdentity, agent.args)agent.gateway = runtime.kind+ // Same process, same cached read — the grid costs no extra `ps`.+ agent.grid = await probeGridAssignment(agent.processIdentity)}))return { processTableAvailable: true, targets, ...discovered }}diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex e4d3bc1ef..6be90ea33 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -73,6 +73,19 @@ export interface TerminalCreateRequest {env?: Record<string, string>}+/**+ * Re-exec an EXISTING terminal's process, keeping the terminal itself.+ *+ * The pane, its id and its scrollback survive, which is the whole point: moving a running agent to a+ * grid must not look to the user like the agent was replaced. Only the process is replaced, because+ * its environment is the thing being changed and a process's environment cannot be edited in place.+ */+export interface TerminalRespawnRequest {+ cwd?: string+ command: string[]+ env?: Record<string, string>+}+export type TerminalCreateResult<Ref extends TerminalRuntimeRef = TerminalRuntimeRef> =| { state: 'succeeded'; dispatch: 'executed'; runtime: Ref }| { state: 'failed'; dispatch: 'not_started' | 'rejected'; reason: string }diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsindex 3385d0d07..778ed4f1e 100644--- a/cli/src/lib/tmuxAgentDiscovery.ts+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -15,6 +15,7 @@ import {} from './engineBin.js'import type { AgentEngine } from '../engines/types.js'import { probeGatewayRuntime } from './gatewayRuntime.js'+import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'import type { ProcessIdentity, RegisteredSession } from './registry.js'import {ambiguousAgentProcess,@@ -46,6 +47,11 @@ export interface DiscoveredTmuxAgent {* could not read the process; the registry then keeps whatever it already knew.*/gateway?: 'ori' | null+ /**+ * The grid this pane's engine is actually talking to, read off the same environment. null = a normal+ * vendor login, or the read failed; see `gridAssignment.ts` for why those share an answer.+ */+ grid?: GridAssignment | null}export type TmuxAgentProbe =@@ -226,11 +232,13 @@ export async function probeTmuxAgents(agentCommandOwnershipSnapshot(),hints,)- // Which endpoint each agent is pointed at. Cached per live process, so this is one read per agent for- // its whole life, not one per pass — and a failed read leaves `gateway` undefined rather than false.+ // Which endpoint each agent is pointed at, and which grid. Both read the same process environment+ // through the same cache, so this stays one read per agent for its whole life rather than one per+ // pass — and a failed read leaves `gateway` undefined rather than false.await Promise.all(probe.agents.map(async (agent) => {const runtime = await probeGatewayRuntime(agent.processIdentity, agent.args)agent.gateway = runtime.kind+ agent.grid = await probeGridAssignment(agent.processIdentity)}))return probe}diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.tsindex 4c07c3848..a860f7120 100644--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@ -133,4 +133,48 @@ printf '%%42\\n'+ ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -w remain-on-exit on',)})+ it('respawns a pane in place with a new environment, keeping the pane id', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-respawn-'))+ dirs.push(dir)+ const calls = join(dir, 'calls')+ const tmux = join(dir, 'tmux')+ writeFileSync(tmux, `#!/bin/sh+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"+`)+ chmodSync(tmux, 0o700)+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ process.env.TMUX_BACKEND_CALLS = calls++ const moved = await new TmuxBackend().respawn({ backend: 'tmux', paneId: '%42' }, {+ cwd: '/tmp/work',+ env: { ANTHROPIC_BASE_URL: 'https://relay.example/relay', ANTHROPIC_MODEL: 'GLM-4.7-Flash' },+ command: ['/bin/zsh', '-lic', 'exec "$@"', 'harness-engine', 'claude', '--resume', 'sess-1'],+ })++ expect(moved).toEqual({ state: 'succeeded', dispatch: 'executed' })+ // `remain-on-exit` is chained BEFORE the respawn, not after: an engine handed a rejected key can+ // exit before a follow-up call lands, taking its own error message down with it.+ expect(readFileSync(calls, 'utf8').trim()).toBe(+ 'set-option -w -t %42 remain-on-exit on ; respawn-pane -k -c /tmp/work'+ + ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_MODEL=GLM-4.7-Flash'+ + ' -t %42 /bin/zsh -lic exec "$@" harness-engine claude --resume sess-1',+ )+ })++ it('never reports a failed respawn as untouched, because -k already killed the old process', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-respawn-fail-'))+ dirs.push(dir)+ const tmux = join(dir, 'tmux')+ writeFileSync(tmux, `#!/bin/sh+printf 'no such pane: %%99\\n' >&2+exit 1+`)+ chmodSync(tmux, 0o700)+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`++ const moved = await new TmuxBackend().respawn({ backend: 'tmux', paneId: '%99' }, { command: ['claude'] })+ expect(moved.state).toBe('unknown')+ expect(moved).toMatchObject({ dispatch: 'possibly_executed' })+ if (moved.state === 'unknown') expect(moved.reason).toContain('no such pane')+ })})diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex c5b0d80c0..3eb87e715 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -12,6 +12,7 @@ import {type TerminalLogicalKey,type TerminalProcessExpectation,type TerminalReadResult,+ type TerminalRespawnRequest,type TerminalStreamHandle,type TerminalStreamSink,type TerminalStreamSize,@@ -119,6 +120,33 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {return { state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId } }}+ /**+ * Replace the process running in an existing pane, with a different environment.+ *+ * `-k` kills what is there first; without it tmux refuses a live pane. `remain-on-exit` is turned on+ * in the SAME invocation and for the same reason as in `create`: a respawned engine that dies+ * immediately (a rejected key, a model the grid does not serve) must leave its error on screen+ * instead of taking the pane down with it. Whoever calls this owns turning it back off.+ */+ async respawn(runtime: TmuxRuntimeRef, request: TerminalRespawnRequest): Promise<TerminalActionResult> {+ const args = ['set-option', '-w', '-t', runtime.paneId, 'remain-on-exit', 'on', ';', 'respawn-pane', '-k']+ if (request.cwd) args.push('-c', request.cwd)+ for (const [key, value] of Object.entries(request.env ?? {})) args.push('-e', `${key}=${value}`)+ args.push('-t', runtime.paneId, ...request.command)+ const result = await new Promise<{ error: NodeJS.ErrnoException | null; stderr: string }>((resolve) => {+ execFile('tmux', args, { timeout: 5_000 }, (error, _stdout, stderr) => resolve({+ error: error as NodeJS.ErrnoException | null,+ stderr,+ }))+ })+ if (!result.error) return TERMINAL_ACTION_SUCCEEDED+ if (result.error.code === 'ENOENT') return terminalActionNotStarted('tmux is unavailable')+ // `-k` means the old process may already be gone even though the new one never started, so this+ // cannot be reported as "nothing happened".+ const detail = result.stderr.trim().split('\n')[0]?.slice(0, 200) || result.error.message.slice(0, 200)+ return terminalActionPossiblyExecuted(`tmux could not respawn the pane: ${detail}`)+ }+async kill(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {const sessionId = await new Promise<string | null>((resolve) => {execFile('tmux', ['display-message', '-p', '-t', runtime.paneId, '#{session_id}'], { timeout: 2_000 }, (error, stdout) => {