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): honour payload.grid — launch a new agent on the grid the app picked
Dev jacob76e69db79d9e
diff --git a/cli/README.md b/cli/README.mdindex dbe2a328e..eafd9d0df 100644--- a/cli/README.md+++ b/cli/README.md@@ -124,6 +124,15 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.json- **Live agent sync** to web + device: discovery emits `agent_synced` immediately, even with no session;binding later emits session sync, and confirmed process exit emits one `agent_deleted`. A sessionlessagent returns an empty `sessions_list`, accepts input by `agentId`, and binds after the first turn.+- **A new agent can be pointed at a grid.** When the desktop app has a grid selected it sends+ `payload.grid` (relay base URL, a key minted for that launch, and optionally a model) on+ `agent_create`; the daemon turns it into the engine's own environment and gives the new tmux+ session that environment with `new-session -e`, so the credential never appears in the engine's+ argv. Only Claude Code is supported today (`ANTHROPIC_BASE_URL` / `ANTHROPIC_AUTH_TOKEN` /+ `ANTHROPIC_MODEL`) — every other engine is **refused** with `GRID_ENGINE_UNSUPPORTED` rather than+ quietly started on its own login, because the Codex CLI and friends are configured by a file+ rather than the environment. Needs tmux ≥ 3.2; an older one is refused as `TMUX_TOO_OLD_FOR_GRID`.+ See `src/lib/gridLaunch.ts`.- **Mirror-all**: every JSONL line streams up — prompts typed directly in the terminal render inthe web identically to web-sent ones (`turn_started`/`turn_ended` are derived from the file).- **Compaction (`/compact` or auto-compact):** claude does an **in-file** compact — the JSONL keepsdiff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 707a0e69f..a3d54924f 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -22,6 +22,7 @@ import { VERSION } from './version.js'import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'import { ENGINES, type AgentEngine } from './engines/types.js'import { listDir } from './lib/fsBrowse.js'+import { parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'import { routeVoiceTask } from './lib/voiceRouter.js'import { tailFile } from './lib/sessions.js'import { messagesToEvents, windowRawLines, subagentStatsFromRawLines, type SessionEvent } from './lib/normalize.js'@@ -293,7 +294,13 @@ export class BackendSocket {onDeleteAgent: ((sessionId: string) => void) | null = null/** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the* requested folder and returns its process-agent. Session metadata may bind later through hooks. */- onCreateAgent: ((input: { engine: AgentEngine; cwd: string; bypassPermission: boolean }) =>+ onCreateAgent: ((input: {+ engine: AgentEngine+ cwd: string+ bypassPermission: boolean+ /** A grid to point this agent at instead of the engine's own login; null when none was chosen. */+ grid: GridLaunchOverride | null+ }) =>Promise<{ ok: true; session: RegisteredSession } | { 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@@ -1281,7 +1288,17 @@ export class BackendSocket {if (!engine || !ENGINES.includes(engine)) { reply(type, requestId, { error: 'INVALID_ENGINE' }); return }if (!cwd || !isAbsolute(cwd)) { reply(type, requestId, { error: 'INVALID_CWD' }); return }if (!this.onCreateAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }- const result = await this.onCreateAgent({ engine, cwd, bypassPermission: payload.bypassPermission === true })+ // Absent is the ordinary case and stays indistinguishable from a client that predates grids;+ // present-but-malformed is refused here rather than half-applied at launch, because an agent+ // that quietly ran on the engine's own login would look like it worked.+ const grid = parseGridLaunchOverride(payload.grid)+ if (grid.state === 'invalid') { reply(type, requestId, { error: 'INVALID_GRID', detail: grid.reason }); return }+ const result = await this.onCreateAgent({+ engine,+ cwd,+ bypassPermission: payload.bypassPermission === true,+ grid: grid.state === 'ok' ? grid.override : null,+ })// `detail` carries the underlying cause (tmux's own message) so the person who clicked// Create can read it, rather than having to open a log on the machine that failed.if (!result.ok) {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 10c7e77f5..065d7aa81 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -43,6 +43,8 @@ import { renderLoginSuccessHtml } from './lib/loginPage.js'import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'+import { buildGridEngineEnv, describeGridLaunch } from './lib/gridLaunch.js'+import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'import { findLiveSession } from './lib/sessionRepair.js'@@ -2695,20 +2697,43 @@ async function runForeground(session: AuthSession): Promise<void> {* The freshly-exec'd engine process may not be visible to `ps` the instant tmux returns, so one probe* pass can miss it — retry `triggerHint` a few times with backoff before giving up.*/- backend.onCreateAgent = async ({ engine, cwd, bypassPermission }) => {+ backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid }) => {if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }try {if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }} catch {return { ok: false, error: 'CWD_NOT_FOUND' }}+ // A grid is the user's answer to "where should this run", so every way of not honouring it is a+ // refusal rather than a fallback — an agent silently started on the engine's own login spends the+ // wrong account and looks identical to one that worked.+ let gridEnv: Record<string, string> | undefined+ if (grid) {+ const built = buildGridEngineEnv(engine, grid)+ if (!built.ok) {+ console.warn(`[agent] create ${engine} refused · ${built.detail}`)+ return { ok: false, error: built.error, detail: built.detail }+ }+ if (!(await tmuxSupportsSessionEnv())) {+ const detail = `this machine's tmux is older than `+ + `${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, which is the first version that can `+ + `give a new session its own environment — so ${engine} could not have been pointed at grid `+ + `${grid.networkName}. Upgrade tmux, or create this agent without a grid selected.`+ console.warn(`[agent] create ${engine} refused · ${detail}`)+ return { ok: false, error: 'TMUX_TOO_OLD_FOR_GRID', detail }+ }+ gridEnv = built.env+ // Named in the log because the pane itself gives nothing away: the engine looks exactly like a+ // normally launched one. The key is never printed.+ console.log(describeGridLaunch(engine, grid))+ }// Harness-created sessions are easy to distinguish from a user's organic tmux sessions while// retaining the engine and a collision-resistant creation suffix for diagnostics.const label = `harness-${engine}-${Date.now()}`.replace(/[^A-Za-z0-9_-]/g, '-')const launchOptions = { bypassPermission }const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)- const spawned = await tmuxBackend.create({ cwd, label, command: argv })+ const spawned = await tmuxBackend.create({ cwd, label, command: argv, ...(gridEnv ? { env: gridEnv } : {}) })if (spawned.state !== 'succeeded') {console.warn(`[agent] create ${engine} failed · tmux could not open a pane · ${spawned.reason ?? ''}`)// `tmuxBackend` exists whenever the CONFIG lists tmux — it is never a probe of the binary. So adiff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.tsnew file mode 100644index 000000000..8c417cfad--- /dev/null+++ b/cli/src/lib/gridLaunch.spec.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from 'vitest'+import {+ GRID_ENGINE_ENV,+ anthropicBaseUrl,+ buildGridEngineEnv,+ describeGridLaunch,+ gridCapableEngines,+ parseGridLaunchOverride,+ type GridLaunchOverride,+} from './gridLaunch.js'+import { ENGINES } from '../engines/types.js'++/** The shape the desktop actually sends, with values read off the live control plane. */+const WIRE = {+ networkId: 'grid-3378218621364f16',+ networkName: 'autonomous.ai',+ baseUrl: 'https://grid.autonomous.ai/grid-3378218621364f16/relay/v1',+ apiKey: 'gridkey-abc123',+}++const OVERRIDE: GridLaunchOverride = { ...WIRE }++describe('parseGridLaunchOverride', () => {+ it('reads absent as absent, not as a failure', () => {+ // The whole no-regression promise rests on this: a client with no grid selected sends no field,+ // and must create agents exactly the way it did before grids existed.+ expect(parseGridLaunchOverride(undefined)).toEqual({ state: 'absent' })+ expect(parseGridLaunchOverride(null)).toEqual({ state: 'absent' })+ })++ it('accepts the desktop payload, with and without a model', () => {+ expect(parseGridLaunchOverride(WIRE)).toEqual({ state: 'ok', override: OVERRIDE })+ expect(parseGridLaunchOverride({ ...WIRE, model: 'glm-5.2' }))+ .toEqual({ state: 'ok', override: { ...OVERRIDE, model: 'glm-5.2' } })+ })++ it('names every missing field at once rather than one per round trip', () => {+ const result = parseGridLaunchOverride({ networkId: 'g1' })+ expect(result.state).toBe('invalid')+ expect(result).toMatchObject({ reason: 'grid is missing networkName, baseUrl, apiKey' })+ })++ it('refuses a baseUrl that is not an http(s) address', () => {+ for (const baseUrl of ['relay.example/v1', 'file:///etc/passwd', 'ws://relay.example/v1']) {+ expect(parseGridLaunchOverride({ ...WIRE, baseUrl }).state).toBe('invalid')+ }+ })++ it('refuses control characters, which would corrupt the environment silently', () => {+ expect(parseGridLaunchOverride({ ...WIRE, apiKey: 'abc\u0007def' }).state).toBe('invalid')+ expect(parseGridLaunchOverride({ ...WIRE, model: 'glm\n5.2' }).state).toBe('invalid')+ })++ it('refuses a present-but-empty model instead of quietly dropping the choice', () => {+ expect(parseGridLaunchOverride({ ...WIRE, model: ' ' }).state).toBe('invalid')+ })++ it('refuses a grid that is not an object', () => {+ expect(parseGridLaunchOverride('autonomous.ai').state).toBe('invalid')+ expect(parseGridLaunchOverride([WIRE]).state).toBe('invalid')+ })+})++describe('anthropicBaseUrl', () => {+ it('drops the /v1 that OpenAI clients need and Claude Code appends itself', () => {+ expect(anthropicBaseUrl(WIRE.baseUrl)).toBe('https://grid.autonomous.ai/grid-3378218621364f16/relay')+ })++ it('is idempotent and trailing-slash tolerant', () => {+ const relay = 'https://relay.example/relay'+ expect(anthropicBaseUrl(relay)).toBe(relay)+ expect(anthropicBaseUrl(`${relay}/v1/`)).toBe(relay)+ expect(anthropicBaseUrl(`${relay}//`)).toBe(relay)+ })++ it('leaves a path that merely ends in something like v1 alone', () => {+ expect(anthropicBaseUrl('https://relay.example/relay/av1')).toBe('https://relay.example/relay/av1')+ })+})++describe('buildGridEngineEnv', () => {+ it('points Claude Code at the relay with the bearer variable only', () => {+ const built = buildGridEngineEnv('claude', OVERRIDE)+ expect(built).toEqual({+ ok: true,+ env: {+ ANTHROPIC_BASE_URL: 'https://grid.autonomous.ai/grid-3378218621364f16/relay',+ ANTHROPIC_AUTH_TOKEN: WIRE.apiKey,+ },+ })+ // Setting it too makes Claude Code warn that auth may not work, and it decides nothing.+ expect(built).not.toHaveProperty('env.ANTHROPIC_API_KEY')+ })++ it('sets the model the user picked, and none when they picked none', () => {+ const chosen = buildGridEngineEnv('claude', { ...OVERRIDE, model: 'glm-5.2' })+ expect(chosen).toMatchObject({ ok: true, env: { ANTHROPIC_MODEL: 'glm-5.2' } })+ expect(buildGridEngineEnv('claude', OVERRIDE)).not.toHaveProperty('env.ANTHROPIC_MODEL')+ })++ it('refuses every engine with no verified environment contract, naming the grid and the way out', () => {+ for (const engine of ENGINES) {+ if (GRID_ENGINE_ENV[engine]) continue+ const built = buildGridEngineEnv(engine, OVERRIDE)+ expect(built.ok).toBe(false)+ expect(built).toMatchObject({ error: 'GRID_ENGINE_UNSUPPORTED' })+ if (built.ok) continue+ expect(built.detail).toContain(OVERRIDE.networkName)+ expect(built.detail).toContain('claude')+ }+ })++ it('declares an entry for every engine, so a new one cannot default into a guess', () => {+ expect(Object.keys(GRID_ENGINE_ENV).sort()).toEqual([...ENGINES].sort())+ expect(gridCapableEngines()).toEqual(['claude'])+ })+})++describe('describeGridLaunch', () => {+ it('names the grid and the model, and never the key', () => {+ const line = describeGridLaunch('claude', { ...OVERRIDE, model: 'glm-5.2' })+ expect(line).toContain('autonomous.ai')+ expect(line).toContain('glm-5.2')+ expect(line).not.toContain(WIRE.apiKey)+ expect(describeGridLaunch('claude', OVERRIDE)).not.toContain(WIRE.apiKey)+ })+})diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.tsnew file mode 100644index 000000000..47a5bcbe6--- /dev/null+++ b/cli/src/lib/gridLaunch.ts@@ -0,0 +1,193 @@+/**+ * Pointing a newly created agent at an Autonomous Grid instead of the engine's own login.+ *+ * The desktop app lets a user pick a grid (and optionally a model), mints a short-lived relay key for+ * it, and sends the result as `payload.grid` on `agent_create`. Nothing about that reaches an engine+ * by itself: this CLI is what spawns the engine, so this module turns that payload into the+ * environment the engine is launched with.+ *+ * ## The relay is OpenAI-compatible, and that is not enough+ *+ * Every engine here can in principle be pointed somewhere else, but only through the mechanism its+ * own vendor supports, and those genuinely differ — Claude Code reads environment variables, while+ * the Codex CLI needs a `[model_providers.*]` block in `~/.codex/config.toml` (verified in the grid+ * repo's `docs/codex-quickstart.md`; `wire_api = "responses"` is mandatory there and has no+ * environment-only spelling). Writing another tool's config file on a user's behalf is a side effect+ * that outlives the agent, so this module does not do it, and an engine whose contract we have not+ * verified is refused rather than guessed at — the same rule `BYPASS_PERMISSION_FLAGS` already+ * follows in `engineLaunch.ts`.+ *+ * Refusing is the point. Silently launching against the engine's own login would put the agent+ * somewhere other than where the user said, spend the wrong account, and look like it worked.+ */++import type { AgentEngine } from '../engines/types.js'++/** What the desktop sends, once validated. Mirrors `GridAgentOverride` in the desktop app. */+export interface GridLaunchOverride {+ networkId: string+ /** The grid's display name — for log lines and error text, never for routing. */+ networkName: string+ /**+ * The grid's OpenAI-compatible relay root, as the control plane reports it: `<grid>/relay/v1`.+ * Per-engine forms are derived from this; see `anthropicBaseUrl`.+ */+ baseUrl: string+ /** Short-lived, minted per launch. Never logged. */+ apiKey: string+ /** Absent means "whatever the engine asks for" — the relay's own default. */+ model?: string+}++export type GridOverrideParse =+ | { state: 'absent' }+ | { state: 'ok'; override: GridLaunchOverride }+ | { state: 'invalid'; reason: string }++/**+ * Control characters have no place in a URL, a token or a model id, and every one of these values+ * ends up in a process environment. Rejecting them keeps a malformed frame from producing an engine+ * whose environment is subtly not what either side thinks it is.+ */+const CONTROL_CHARS = /[\u0000-\u001F\u007F]/++function requiredString(raw: Record<string, unknown>, key: string): string | null {+ const value = raw[key]+ if (typeof value !== 'string') return null+ const trimmed = value.trim()+ if (!trimmed || CONTROL_CHARS.test(trimmed)) return null+ return trimmed+}++/**+ * `payload.grid` as a validated override, or the reason it is not one.+ *+ * Absent is a first-class answer, not a failure: a build with no grid selected sends no `grid` field+ * at all, and must create agents exactly the way it always did.+ */+export function parseGridLaunchOverride(raw: unknown): GridOverrideParse {+ if (raw === undefined || raw === null) return { state: 'absent' }+ if (typeof raw !== 'object' || Array.isArray(raw)) return { state: 'invalid', reason: 'grid must be an object' }+ const source = raw as Record<string, unknown>+ const networkId = requiredString(source, 'networkId')+ const networkName = requiredString(source, 'networkName')+ const baseUrl = requiredString(source, 'baseUrl')+ const apiKey = requiredString(source, 'apiKey')+ const missing = [+ networkId ? null : 'networkId',+ networkName ? null : 'networkName',+ baseUrl ? null : 'baseUrl',+ apiKey ? null : 'apiKey',+ ].filter((name): name is string => name !== null)+ if (missing.length) return { state: 'invalid', reason: `grid is missing ${missing.join(', ')}` }+ // An engine is about to be handed this as the address it talks to, so it has to be an address:+ // anything else (a `file:` URL, a bare hostname, a path) would fail inside the engine with an+ // error naming neither the grid nor this frame.+ let parsed: URL+ try {+ parsed = new URL(baseUrl as string)+ } catch {+ return { state: 'invalid', reason: 'grid baseUrl is not a URL' }+ }+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {+ return { state: 'invalid', reason: `grid baseUrl must be http(s), got ${parsed.protocol}` }+ }+ const hasModel = source.model !== undefined && source.model !== null+ const model = hasModel ? requiredString(source, 'model') : undefined+ if (hasModel && !model) return { state: 'invalid', reason: 'grid model must be a non-empty string' }+ return {+ state: 'ok',+ override: {+ networkId: networkId as string,+ networkName: networkName as string,+ baseUrl: baseUrl as string,+ apiKey: apiKey as string,+ ...(model ? { model } : {}),+ },+ }+}++/**+ * The relay root Claude Code wants, from the OpenAI-compatible one the control plane hands out.+ *+ * The app appends `/v1/messages` itself, so the `/v1` an OpenAI SDK needs would 404 every request+ * here — the same one-character difference that makes `grid launch claude --print-env` a separate+ * command from `grid info --env` in the grid CLI. Idempotent: a base that already lacks `/v1` comes+ * back unchanged.+ */+export function anthropicBaseUrl(baseUrl: string): string {+ const trimmed = baseUrl.replace(/\/+$/, '')+ return trimmed.endsWith('/v1') ? trimmed.slice(0, -'/v1'.length) : trimmed+}++/**+ * How each engine is pointed at a grid through its environment alone — `null` where no such+ * mechanism is confirmed to exist.+ *+ * `null` is a refusal, not a gap to be filled in later with a plausible guess; see the module+ * comment. The one entry here is the one the grid CLI itself ships as a launch target+ * (`autonomous-grid/shared/launch/claude.py`), so these variable names are the vendor's own contract+ * rather than this repo's reading of it.+ */+export const GRID_ENGINE_ENV: Readonly<+ Record<AgentEngine, ((override: GridLaunchOverride) => Record<string, string>) | null>+> = {+ claude: (override) => ({+ ANTHROPIC_BASE_URL: anthropicBaseUrl(override.baseUrl),+ // The bearer variable, and ONLY it. Claude Code warns when ANTHROPIC_AUTH_TOKEN and+ // ANTHROPIC_API_KEY are both set, and the relay prefers the Bearer header anyway — so+ // ANTHROPIC_API_KEY would decide nothing, while colliding with the variable a user's own+ // Anthropic key lives in.+ ANTHROPIC_AUTH_TOKEN: override.apiKey,+ // `grid launch claude` deliberately sets no model variable, on the grounds that a launcher has no+ // standing to choose a user's model. That reasoning does not carry here: the desktop app ASKED,+ // and this is the answer. Left unset when the user picked no model, which leaves the app's own+ // defaults, `settings.json` and `/model` in charge exactly as before.+ ...(override.model ? { ANTHROPIC_MODEL: override.model } : {}),+ }),+ // Config-file only: `[model_providers.grid]` with `wire_api = "responses"` in ~/.codex/config.toml.+ codex: null,+ // Unverified — do not guess an environment contract for a CLI we have not checked.+ cursor: null,+ opencode: null,+ pi: null,+ hermes: null,+ commandcode: null,+ devin: null,+ muse: null,+ amp: null,+ kilo: null,+ grok: null,+ agy: null,+ copilot: null,+}++/** Engines that can be pointed at a grid today, so error text can name what to pick instead. */+export function gridCapableEngines(): AgentEngine[] {+ return (Object.keys(GRID_ENGINE_ENV) as AgentEngine[]).filter((engine) => GRID_ENGINE_ENV[engine] !== null)+}++export type GridEnvResult =+ | { ok: true; env: Record<string, string> }+ | { ok: false; error: string; detail: string }++/** The environment `engine` must be launched with to reach `override`, or why it cannot be. */+export function buildGridEngineEnv(engine: AgentEngine, override: GridLaunchOverride): GridEnvResult {+ const build = GRID_ENGINE_ENV[engine]+ if (!build) {+ return {+ ok: false,+ error: 'GRID_ENGINE_UNSUPPORTED',+ detail: `${engine} cannot be pointed at a grid through its environment, so it would have run on `+ + `its own login instead of grid ${override.networkName}. `+ + `Engines that can: ${gridCapableEngines().join(', ')}.`,+ }+ }+ return { ok: true, env: build(override) }+}++/** One log line naming where an agent was sent — grid, model, engine. Never the key. */+export function describeGridLaunch(engine: AgentEngine, override: GridLaunchOverride): string {+ return `[grid] ${engine} -> ${override.networkName} (${override.networkId})`+ + ` · ${override.model ?? 'model chosen by the engine'}`+}diff --git a/cli/src/lib/herdrBackend.ts b/cli/src/lib/herdrBackend.tsindex 6aea7437e..ae6250cf7 100644--- a/cli/src/lib/herdrBackend.ts+++ b/cli/src/lib/herdrBackend.ts@@ -135,7 +135,7 @@ export class HerdrBackend implements TerminalBackend<HerdrRuntimeRef> {...(request.cwd ? { cwd: request.cwd } : {}),focus: false,...(request.label ? { label: request.label } : {}),- env: {},+ env: request.env ?? {},}, { mutation: 'other' })if (!result.ok) {if (result.dispatch === 'not_started') return terminalActionNotStarted(result.reason)diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex 0d6d95ccf..e4d3bc1ef 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -64,6 +64,13 @@ export interface TerminalCreateRequest {label?: string/** argv (binary first) to run instead of the backend's default shell, e.g. an engine CLI launch. */command?: string[]+ /**+ * Extra environment for the created terminal, layered over whatever it would otherwise inherit.+ *+ * Deliberately not part of `command`: these values are credentials (a grid relay key, see+ * `gridLaunch.ts`), and argv is world-readable through `ps` for as long as the process lives.+ */+ env?: Record<string, string>}export type TerminalCreateResult<Ref extends TerminalRuntimeRef = TerminalRuntimeRef> =diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.tsindex df1d1476f..4c07c3848 100644--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@ -102,4 +102,35 @@ printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"'display-message -t %7 -- Build status: Ready; touch /tmp/must-not-run',)})+ it('hands the session its own environment, before the command it launches', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-env-'))+ dirs.push(dir)+ const calls = join(dir, 'calls')+ const tmux = join(dir, 'tmux')+ writeFileSync(tmux, `#!/bin/sh+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"+printf '%%42\\n'+`)+ chmodSync(tmux, 0o700)+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ process.env.TMUX_BACKEND_CALLS = calls++ const created = await new TmuxBackend().create({+ cwd: '/tmp/work',+ label: 'harness-test',+ // A grid relay key. It goes here rather than into `command` precisely so it stays out of the+ // engine's argv, where `ps` would expose it for the life of the agent.+ env: { ANTHROPIC_BASE_URL: 'https://relay.example/relay', ANTHROPIC_AUTH_TOKEN: 'gridkey-abc123' },+ command: ['/bin/zsh', '-lic', 'exec "$@"', 'harness-engine', 'claude'],+ })++ expect(created.state).toBe('succeeded')+ // Order is load-bearing: everything after the first non-flag argument is the session's+ // shell-command, so an `-e` placed after `command` would be handed to the engine instead of tmux.+ expect(readFileSync(calls, 'utf8').trim().split('\n')[0]).toBe(+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test'+ + ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_AUTH_TOKEN=gridkey-abc123'+ + ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -w remain-on-exit on',+ )+ })})diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex b578a1a38..c5b0d80c0 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -76,6 +76,10 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']if (request.cwd) args.push('-c', request.cwd)if (request.label) args.push('-s', request.label)+ // `-e` (tmux 3.2+) puts these in the SESSION environment rather than the launch argv, so a grid+ // relay key never lands in `ps` output for the life of the agent. Callers gate on+ // `tmuxSupportsSessionEnv()`; an older tmux answers the flag with its usage text.+ for (const [key, value] of Object.entries(request.env ?? {})) args.push('-e', `${key}=${value}`)// Trailing args after this point become the session's shell-command. tmux execs them directly// (no shell interposed) when given as separate argv elements, so no quoting/escaping is needed.if (request.command?.length) args.push(...request.command)diff --git a/cli/src/lib/tmuxVersion.spec.ts b/cli/src/lib/tmuxVersion.spec.tsnew file mode 100644index 000000000..4993c2560--- /dev/null+++ b/cli/src/lib/tmuxVersion.spec.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest'+import { TMUX_SESSION_ENV_MIN, parseTmuxVersion, supportsSessionEnv } from './tmuxVersion.js'++describe('parseTmuxVersion', () => {+ it('reads the shapes tmux -V actually prints', () => {+ expect(parseTmuxVersion('tmux 3.5a\n')).toEqual({ major: 3, minor: 5 })+ expect(parseTmuxVersion('tmux 3.2\n')).toEqual({ major: 3, minor: 2 })+ expect(parseTmuxVersion('tmux next-3.6\n')).toEqual({ major: 3, minor: 6 })+ expect(parseTmuxVersion('tmux openbsd-7.4\n')).toEqual({ major: 7, minor: 4 })+ })++ it('has no answer for a build that prints no number', () => {+ expect(parseTmuxVersion('tmux master\n')).toBeNull()+ expect(parseTmuxVersion('')).toBeNull()+ })+})++describe('supportsSessionEnv', () => {+ it('draws the line at the release that added new-session -e', () => {+ expect(TMUX_SESSION_ENV_MIN).toEqual({ major: 3, minor: 2 })+ expect(supportsSessionEnv({ major: 3, minor: 1 })).toBe(false)+ expect(supportsSessionEnv({ major: 2, minor: 9 })).toBe(false)+ expect(supportsSessionEnv({ major: 3, minor: 2 })).toBe(true)+ expect(supportsSessionEnv({ major: 3, minor: 10 })).toBe(true)+ expect(supportsSessionEnv({ major: 4, minor: 0 })).toBe(true)+ })++ it('treats an unreadable version as capable, so a working tmux is never refused on a guess', () => {+ expect(supportsSessionEnv(null)).toBe(true)+ })+})diff --git a/cli/src/lib/tmuxVersion.ts b/cli/src/lib/tmuxVersion.tsnew file mode 100644index 000000000..f3a9b7f11--- /dev/null+++ b/cli/src/lib/tmuxVersion.ts@@ -0,0 +1,62 @@+/**+ * What this machine's tmux can do, for the one feature that is not universally available.+ *+ * `new-session -e VAR=value` arrived in tmux 3.2. Without a check, an older tmux answers a grid+ * launch with its own usage text — which the create path faithfully reports as `SPAWN_FAILED:+ * usage: new-session [-AdDEHPX] ...`, a dead end for anyone who did not already know the flag was+ * new. The version is worth one `tmux -V` so the refusal can name the actual cause.+ */++import { execFile } from 'node:child_process'++/** The first tmux that accepts `-e` on `new-session`. */+export const TMUX_SESSION_ENV_MIN = { major: 3, minor: 2 } as const++export interface TmuxVersion {+ major: number+ minor: number+}++/**+ * `tmux 3.5a` / `tmux next-3.6` / `tmux openbsd-7.4` → the numeric part; `null` when there is none.+ *+ * `null` means "cannot tell", not "too old" — `tmux master` reports no number at all and is newer+ * than every release, so callers treat an unparsed version as capable and let tmux itself answer.+ */+export function parseTmuxVersion(output: string): TmuxVersion | null {+ const match = /(\d+)\.(\d+)/.exec(output)+ if (!match) return null+ return { major: Number(match[1]), minor: Number(match[2]) }+}++export function supportsSessionEnv(version: TmuxVersion | null): boolean {+ if (!version) return true // see parseTmuxVersion — unknown is not old+ if (version.major !== TMUX_SESSION_ENV_MIN.major) return version.major > TMUX_SESSION_ENV_MIN.major+ return version.minor >= TMUX_SESSION_ENV_MIN.minor+}++let cached: Promise<TmuxVersion | null> | undefined++async function probe(): Promise<TmuxVersion | null> {+ return await new Promise((resolve) => {+ execFile('tmux', ['-V'], { timeout: 2_000 }, (error, stdout) => {+ // A tmux that cannot be run at all is not this check's problem: the create path already+ // reports `TMUX_UNAVAILABLE` for it, and answering "too old" here would name the wrong cause.+ resolve(error ? null : parseTmuxVersion(stdout))+ })+ })+}++/**+ * Can `TmuxBackend.create` be given an `env`? Probed once per process — tmux does not change under+ * a running daemon, and this sits in front of an interactive "create agent" click.+ */+export async function tmuxSupportsSessionEnv(): Promise<boolean> {+ cached ??= probe()+ return supportsSessionEnv(await cached)+}++/** Test seam: forget the cached probe so a spec can install its own tmux. */+export function resetTmuxVersionCache(): void {+ cached = undefined+}