Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(grid): support every engine that documents a way to change its endpoint

Dev jacoba6061d8fdb5b
diff --git a/cli/README.md b/cli/README.md
index eafd9d0df..6d171d275 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -128,11 +128,18 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.json
`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`.
+ argv. Six engines have a documented way to be pointed somewhere else and are supported through it:
+ **claude** (`ANTHROPIC_BASE_URL`), **codex** (`-c model_providers.grid.*`, key via `env_key`),
+ **opencode** and **hermes** (`OPENAI_BASE_URL`), **grok** (`GROK_MODELS_BASE_URL`) and **copilot**
+ (`COPILOT_PROVIDER_BASE_URL`). Every other engine is **refused** with `GRID_ENGINE_UNSUPPORTED`
+ and a reason specific to it — some talk only to their own service, some need a provider block
+ written into a dotfile this daemon will not edit — rather than quietly started on its own login.
+ Needs tmux ≥ 3.2; an older one is refused as `TMUX_TOO_OLD_FOR_GRID`. See `src/lib/gridLaunch.ts`.
+- **A running agent can be moved to a grid** (`agent_retarget`): `respawn-pane -k -e` re-execs the
+ pane's engine with the new launch and `--resume`, keeping the pane, its id and its scrollback, and
+ the new process is adopted onto the same agent record. A pane mid-turn is refused (`AGENT_BUSY`)
+ rather than interrupted. Which grid an agent is on is read off its live process
+ (`src/lib/gridAssignment.ts`), never bookkept.
- **Mirror-all**: every JSONL line streams up — prompts typed directly in the terminal render in
the 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 keeps
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index b33328713..f3d4cc285 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -43,7 +43,7 @@ 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 { buildGridEngineLaunch, 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'
@@ -2709,9 +2709,9 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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
+ let gridLaunch: { env: Record<string, string>; args: string[] } | undefined
if (grid) {
- const built = buildGridEngineEnv(engine, grid)
+ const built = buildGridEngineLaunch(engine, grid)
if (!built.ok) {
console.warn(`[agent] create ${engine} refused · ${built.detail}`)
return { ok: false, error: built.error, detail: built.detail }
@@ -2724,7 +2724,7 @@ async function runForeground(session: AuthSession): Promise<void> {
console.warn(`[agent] create ${engine} refused · ${detail}`)
return { ok: false, error: 'TMUX_TOO_OLD_FOR_GRID', detail }
}
- gridEnv = built.env
+ gridLaunch = built.launch
// 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))
@@ -2732,10 +2732,15 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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 launchOptions = { bypassPermission, extraArgs: gridLaunch?.args }
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
- const spawned = await tmuxBackend.create({ cwd, label, command: argv, ...(gridEnv ? { env: gridEnv } : {}) })
+ const spawned = await tmuxBackend.create({
+ cwd,
+ label,
+ command: argv,
+ ...(gridLaunch ? { env: gridLaunch.env } : {}),
+ })
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 a
@@ -2877,7 +2882,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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)
+ const built = buildGridEngineLaunch(session.engine, grid)
if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
if (!(await tmuxSupportsSessionEnv())) {
return {
@@ -2898,11 +2903,11 @@ async function runForeground(session: AuthSession): Promise<void> {
const release = acquireTerminalControl(session.agentId)
if (!release) return { ok: false, error: 'AGENT_BUSY' }
try {
- const launchOptions = { resumeSessionId: session.sessionId || null }
+ const launchOptions = { resumeSessionId: session.sessionId || null, extraArgs: built.launch.args }
const respawned = await tmuxBackend.respawn(pane, {
...(session.cwd ? { cwd: session.cwd } : {}),
command: buildEngineLaunchArgv(session.engine, launchOptions),
- env: built.env,
+ env: built.launch.env,
})
if (respawned.state !== 'succeeded') {
console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${respawned.reason}`)
@@ -2935,7 +2940,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// 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),
+ probeGridAssignment(identity, session.engine, identity.executable),
])
registry.updateProcessIdentity(session.agentId, identity, gateway.kind, assignment)
adopted = true
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index edd5770e6..cb7410497 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -51,6 +51,14 @@ export interface LaunchCommandOptions {
* flag could attach a DIFFERENT agent's conversation from the same folder.
*/
resumeSessionId?: string | null
+ /**
+ * Extra argv the caller has already composed, appended last.
+ *
+ * Exists for engines whose endpoint is configured on the command line rather than through the
+ * environment — Codex's `-c model_providers.*`, Grok's `-m`. See `gridLaunch.ts`; a credential
+ * never travels this way.
+ */
+ extraArgs?: readonly string[]
}
/** The executable argv, before the interactive-shell wrapper is applied. */
@@ -62,6 +70,7 @@ export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandO
}
const resumeFlag = opts.resumeSessionId ? RESUME_FLAGS[engine] : undefined
if (resumeFlag) argv.push(resumeFlag, opts.resumeSessionId as string)
+ if (opts.extraArgs?.length) argv.push(...opts.extraArgs)
return argv
}
diff --git a/cli/src/lib/gridAssignment.spec.ts b/cli/src/lib/gridAssignment.spec.ts
index 75376c441..1c895e7a2 100644
--- a/cli/src/lib/gridAssignment.spec.ts
+++ b/cli/src/lib/gridAssignment.spec.ts
@@ -1,68 +1,104 @@
import { describe, expect, it } from 'vitest'
import { assignmentMatches, classifyGridAssignment } from './gridAssignment.js'
+import { buildGridEngineLaunch, gridCapableEngines, type GridLaunchOverride } from './gridLaunch.js'
import { parsePsEnviron } from './processEnv.js'
-const RELAY = 'https://grid.autonomous.ai/grid-3378218621364f16/relay'
+const NETWORK_ID = 'grid-3378218621364f16'
+const RELAY = `https://grid.autonomous.ai/${NETWORK_ID}/relay`
+const RELAY_V1 = `${RELAY}/v1`
+
+const OVERRIDE: GridLaunchOverride = {
+ networkId: NETWORK_ID,
+ networkName: 'autonomous.ai',
+ baseUrl: RELAY_V1,
+ apiKey: 'gridkey-secret',
+ model: 'GLM-4.7-Flash',
+}
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('reads back what every supported engine was actually launched with', () => {
+ // The point of the round trip: the probe and the launcher must use the SAME knob per engine, or
+ // an agent that IS on a grid reports as being on none and gets pointlessly restarted.
+ for (const engine of gridCapableEngines()) {
+ const built = buildGridEngineLaunch(engine, OVERRIDE)
+ expect(built.ok).toBe(true)
+ if (!built.ok) continue
+ const assignment = classifyGridAssignment(engine, built.launch.env, built.launch.args.join(' '))
+ expect(assignment, engine).not.toBeNull()
+ expect(assignment?.baseUrl, engine).toContain(NETWORK_ID)
+ // opencode is the one engine with no verified model knob, so its model stays the app's own.
+ expect(assignment?.model, engine).toBe(engine === 'opencode' ? null : 'GLM-4.7-Flash')
+ }
})
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 })
+ for (const engine of gridCapableEngines()) {
+ const built = buildGridEngineLaunch(engine, OVERRIDE)
+ if (!built.ok) continue
+ const assignment = classifyGridAssignment(engine, built.launch.env, built.launch.args.join(' '))
+ expect(JSON.stringify(assignment), engine).not.toContain('gridkey-secret')
+ }
})
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()
+ expect(classifyGridAssignment('claude', { ANTHROPIC_BASE_URL: 'https://openrouter.ai/api' })).toBeNull()
+ expect(classifyGridAssignment('opencode', { OPENAI_BASE_URL: 'http://localhost:8080/v1' })).toBeNull()
+ expect(classifyGridAssignment('claude', {})).toBeNull()
+ expect(classifyGridAssignment('claude', { ANTHROPIC_BASE_URL: ' ' })).toBeNull()
+ expect(classifyGridAssignment('claude', { ANTHROPIC_BASE_URL: 'not a url' })).toBeNull()
+ })
+
+ it('reads Codex off its argv, where its endpoint actually lives', () => {
+ const args = `codex -c model_provider="grid" -c model_providers.grid.base_url="${RELAY_V1}" -m GLM-4.7-Flash`
+ expect(classifyGridAssignment('codex', { GRID_API_KEY: 'gridkey-secret' }, args))
+ .toEqual({ baseUrl: RELAY_V1, model: 'GLM-4.7-Flash' })
+ // Its environment alone says nothing — reading only env would report every codex agent as free.
+ expect(classifyGridAssignment('codex', { GRID_API_KEY: 'gridkey-secret' })).toBeNull()
+ })
+
+ it('does not confuse one engine\'s knob for another\'s', () => {
+ // A grok agent whose OPENAI_BASE_URL happens to be set by the user's shell is not on a grid.
+ expect(classifyGridAssignment('grok', { OPENAI_BASE_URL: RELAY_V1 })).toBeNull()
+ expect(classifyGridAssignment('copilot', { ANTHROPIC_BASE_URL: RELAY })).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)))
+ expect(classifyGridAssignment('claude', parsePsEnviron(line)))
.toEqual({ baseUrl: RELAY, model: 'GLM-4.7-Flash' })
})
+
+ it('has no answer for an engine that cannot be on a grid at all', () => {
+ expect(classifyGridAssignment('cursor', { ANTHROPIC_BASE_URL: RELAY })).toBeNull()
+ })
})
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)
+ expect(assignmentMatches(assignment, NETWORK_ID, '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)
+ expect(assignmentMatches(assignment, NETWORK_ID, 'DeepSeek-V4-Flash-0731')).toBe(false)
+ expect(assignmentMatches(assignment, NETWORK_ID, 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)
+ expect(assignmentMatches(null, NETWORK_ID, null)).toBe(false)
+ expect(assignmentMatches(undefined, NETWORK_ID, 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)
+ expect(assignmentMatches(unpinned, NETWORK_ID, null)).toBe(true)
+ expect(assignmentMatches(unpinned, NETWORK_ID, 'GLM-4.7-Flash')).toBe(false)
})
})
diff --git a/cli/src/lib/gridAssignment.ts b/cli/src/lib/gridAssignment.ts
index 6cea720b5..f1a50e230 100644
--- a/cli/src/lib/gridAssignment.ts
+++ b/cli/src/lib/gridAssignment.ts
@@ -2,34 +2,56 @@
* 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".
+ * existing one (`agent_retarget`). Both work by changing how the engine was launched, 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=… claude` in their own shell — which this product discovers and adopts —
+ * reports the truth rather than "none".
+ *
+ * Each engine is read through the same knob it was written through, so this table and
+ * `GRID_ENGINE_CONTRACTS` must stay in step: an engine written by environment is read from the
+ * environment, and Codex, which is written on the command line, is read from argv.
*
* **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 type { AgentEngine } from '../engines/types.js'
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. */
+ /** The relay root the engine was handed. The grid id is a path segment inside it. */
baseUrl: string
- /** `ANTHROPIC_MODEL`, when the launch pinned one. Null = the engine's own choice. */
+ /** The model the launch pinned. 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'
+/** The environment variable each engine's endpoint was written to, where it is one. */
+const BASE_URL_VAR: Partial<Record<AgentEngine, string>> = {
+ claude: 'ANTHROPIC_BASE_URL',
+ opencode: 'OPENAI_BASE_URL',
+ hermes: 'OPENAI_BASE_URL',
+ grok: 'GROK_MODELS_BASE_URL',
+ copilot: 'COPILOT_PROVIDER_BASE_URL',
+}
+
+/** The environment variable each engine's model was written to, where it is one. */
+const MODEL_VAR: Partial<Record<AgentEngine, string>> = {
+ claude: 'ANTHROPIC_MODEL',
+ hermes: 'HERMES_INFERENCE_MODEL',
+ copilot: 'COPILOT_MODEL',
+}
+
+/** Engines whose model was written into argv as `-m <model>` rather than an environment variable. */
+const MODEL_IN_ARGV = new Set<AgentEngine>(['codex', 'grok'])
+
+/** `-c model_providers.<name>.base_url="…"` — how Codex's endpoint is written, so how it is read. */
+const CODEX_BASE_URL = /model_providers\.[A-Za-z0-9_-]+\.base_url=(?:"([^"]+)"|(\S+))/
+const ARGV_MODEL = /(?:^|\s)-m\s+(\S+)/
/**
* A base URL that is not a grid is not an assignment.
@@ -49,11 +71,22 @@ function isGridUrl(value: string): boolean {
}
}
-/** 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()
+/** Classify an already-read environment and argv. Exported so a spec can pin the rules with no I/O. */
+export function classifyGridAssignment(
+ engine: AgentEngine,
+ processEnv: Record<string, string>,
+ args = '',
+): GridAssignment | null {
+ const urlVar = BASE_URL_VAR[engine]
+ const fromArgv = urlVar ? null : CODEX_BASE_URL.exec(args)
+ const baseUrl = (urlVar ? processEnv[urlVar] : (fromArgv?.[1] ?? fromArgv?.[2]))?.trim()
if (!baseUrl || !isGridUrl(baseUrl)) return null
- const model = processEnv[MODEL_VAR]?.trim()
+ const modelVar = MODEL_VAR[engine]
+ const model = modelVar
+ ? processEnv[modelVar]?.trim()
+ : MODEL_IN_ARGV.has(engine)
+ ? ARGV_MODEL.exec(args)?.[1]
+ : undefined
return { baseUrl, model: model || null }
}
@@ -65,12 +98,16 @@ export function classifyGridAssignment(processEnv: Record<string, string>): Grid
* 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> {
+export async function probeGridAssignment(
+ identity: ProcessIdentity,
+ engine: AgentEngine,
+ args = '',
+): Promise<GridAssignment | null> {
const processEnv = await readProcessEnv(identity)
- return processEnv ? classifyGridAssignment(processEnv) : null
+ return processEnv ? classifyGridAssignment(engine, processEnv, args) : null
}
-/** Is this agent already where `networkId` is served? */
+/** Is this agent already where `networkId` is served, on `model`? */
export function assignmentMatches(
assignment: GridAssignment | null | undefined,
networkId: string,
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index 8c417cfad..2fa350b4e 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -1,14 +1,14 @@
import { describe, expect, it } from 'vitest'
import {
- GRID_ENGINE_ENV,
anthropicBaseUrl,
- buildGridEngineEnv,
+ buildGridEngineLaunch,
describeGridLaunch,
gridCapableEngines,
parseGridLaunchOverride,
+ relayBaseUrl,
type GridLaunchOverride,
} from './gridLaunch.js'
-import { ENGINES } from '../engines/types.js'
+import { ENGINES, type AgentEngine } from '../engines/types.js'
/** The shape the desktop actually sends, with values read off the live control plane. */
const WIRE = {
@@ -17,8 +17,17 @@ const WIRE = {
baseUrl: 'https://grid.autonomous.ai/grid-3378218621364f16/relay/v1',
apiKey: 'gridkey-abc123',
}
+const RELAY_V1 = WIRE.baseUrl
+const RELAY = 'https://grid.autonomous.ai/grid-3378218621364f16/relay'
const OVERRIDE: GridLaunchOverride = { ...WIRE }
+const WITH_MODEL: GridLaunchOverride = { ...WIRE, model: 'GLM-4.7-Flash' }
+
+function launchOf(engine: AgentEngine, override = WITH_MODEL) {
+ const built = buildGridEngineLaunch(engine, override)
+ if (!built.ok) throw new Error(`${engine} was refused: ${built.detail}`)
+ return built.launch
+}
describe('parseGridLaunchOverride', () => {
it('reads absent as absent, not as a failure', () => {
@@ -46,7 +55,7 @@ describe('parseGridLaunchOverride', () => {
}
})
- it('refuses control characters, which would corrupt the environment silently', () => {
+ it('refuses control characters, which would corrupt an environment or an argv silently', () => {
expect(parseGridLaunchOverride({ ...WIRE, apiKey: 'abc\u0007def' }).state).toBe('invalid')
expect(parseGridLaunchOverride({ ...WIRE, model: 'glm\n5.2' }).state).toBe('invalid')
})
@@ -61,66 +70,121 @@ describe('parseGridLaunchOverride', () => {
})
})
-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)
+describe('relay base URLs', () => {
+ it('keeps the /v1 an OpenAI client needs and drops the one Claude Code appends itself', () => {
+ expect(relayBaseUrl(RELAY_V1)).toBe(RELAY_V1)
+ expect(relayBaseUrl(RELAY)).toBe(RELAY_V1)
+ 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')
+ it('is trailing-slash tolerant and leaves a lookalike path alone', () => {
+ expect(anthropicBaseUrl(`${RELAY}/v1/`)).toBe(RELAY)
+ expect(relayBaseUrl(`${RELAY}//`)).toBe(RELAY_V1)
+ expect(anthropicBaseUrl(`${RELAY}/av1`)).toBe(`${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,
+describe('the launch each engine gets', () => {
+ it('points Claude Code at the Messages root with the bearer variable only', () => {
+ expect(launchOf('claude')).toEqual({
env: {
- ANTHROPIC_BASE_URL: 'https://grid.autonomous.ai/grid-3378218621364f16/relay',
+ ANTHROPIC_BASE_URL: RELAY,
ANTHROPIC_AUTH_TOKEN: WIRE.apiKey,
+ ANTHROPIC_MODEL: 'GLM-4.7-Flash',
},
+ args: [],
})
// Setting it too makes Claude Code warn that auth may not work, and it decides nothing.
- expect(built).not.toHaveProperty('env.ANTHROPIC_API_KEY')
+ expect(launchOf('claude').env).not.toHaveProperty('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('configures Codex on its command line, keeping the key in the environment', () => {
+ const launch = launchOf('codex')
+ expect(launch.env).toEqual({ GRID_API_KEY: WIRE.apiKey })
+ expect(launch.args.join(' ')).toContain(`model_providers.grid.base_url="${RELAY_V1}"`)
+ expect(launch.args.join(' ')).toContain('model_providers.grid.env_key="GRID_API_KEY"')
+ // Codex speaks the Responses dialect and rejects `wire_api = "chat"`.
+ expect(launch.args.join(' ')).toContain('model_providers.grid.wire_api="responses"')
+ expect(launch.args).toContain('-m')
+ expect(launch.args).toContain('GLM-4.7-Flash')
})
- 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)
+ it('uses the OpenAI-compatible pair for opencode and Hermes', () => {
+ expect(launchOf('opencode').env).toEqual({
+ OPENAI_BASE_URL: RELAY_V1,
+ OPENAI_API_KEY: WIRE.apiKey,
+ })
+ expect(launchOf('hermes').env).toEqual({
+ OPENAI_BASE_URL: RELAY_V1,
+ OPENAI_API_KEY: WIRE.apiKey,
+ HERMES_INFERENCE_MODEL: 'GLM-4.7-Flash',
+ })
+ })
+
+ it('uses xAI\'s model-list base for Grok, with the model on the command line', () => {
+ const launch = launchOf('grok')
+ expect(launch.env).toEqual({ GROK_MODELS_BASE_URL: RELAY_V1, XAI_API_KEY: WIRE.apiKey })
+ expect(launch.args).toEqual(['-m', 'GLM-4.7-Flash'])
+ })
+
+ it('uses the documented BYOK trio for Copilot', () => {
+ expect(launchOf('copilot').env).toEqual({
+ COPILOT_PROVIDER_BASE_URL: RELAY_V1,
+ COPILOT_PROVIDER_API_KEY: WIRE.apiKey,
+ COPILOT_MODEL: 'GLM-4.7-Flash',
+ })
+ })
+
+ it('never puts the key in argv, for any engine', () => {
+ // `ps` is world-readable for the life of the process; the environment is not.
+ for (const engine of gridCapableEngines()) {
+ expect(launchOf(engine).args.join(' ')).not.toContain(WIRE.apiKey)
+ expect(Object.values(launchOf(engine).env)).toContain(WIRE.apiKey)
+ }
+ })
+
+ it('leaves the model to the engine when the user picked none', () => {
+ expect(launchOf('claude', OVERRIDE).env).not.toHaveProperty('ANTHROPIC_MODEL')
+ expect(launchOf('hermes', OVERRIDE).env).not.toHaveProperty('HERMES_INFERENCE_MODEL')
+ expect(launchOf('grok', OVERRIDE).args).toEqual([])
+ expect(launchOf('codex', OVERRIDE).args).not.toContain('-m')
+ })
+
+ it('refuses Copilot without a model rather than letting it fail inside the app', () => {
+ const built = buildGridEngineLaunch('copilot', OVERRIDE)
+ expect(built).toMatchObject({ ok: false, error: 'GRID_MODEL_REQUIRED' })
+ })
+})
+
+describe('the engines that cannot', () => {
+ it('refuses each one with a reason specific to that engine', () => {
+ const capable = new Set(gridCapableEngines())
+ const refused = ENGINES.filter((engine) => !capable.has(engine))
+ expect(refused.length).toBeGreaterThan(0)
+ for (const engine of refused) {
+ const built = buildGridEngineLaunch(engine, OVERRIDE)
expect(built.ok).toBe(false)
- expect(built).toMatchObject({ error: 'GRID_ENGINE_UNSUPPORTED' })
if (built.ok) continue
+ expect(built.error).toBe('GRID_ENGINE_UNSUPPORTED')
expect(built.detail).toContain(OVERRIDE.networkName)
- expect(built.detail).toContain('claude')
+ // "unsupported" alone tells nobody whether to wait, change a setting, or pick another engine.
+ expect(built.detail).not.toContain('it has no known way to change its endpoint')
+ expect(built.detail).toContain('Engines that can:')
}
})
- 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'])
+ it('lists exactly the engines with a verified vendor contract', () => {
+ expect([...gridCapableEngines()].sort())
+ .toEqual(['claude', 'codex', 'copilot', 'grok', 'hermes', 'opencode'])
})
})
describe('describeGridLaunch', () => {
it('names the grid and the model, and never the key', () => {
- const line = describeGridLaunch('claude', { ...OVERRIDE, model: 'glm-5.2' })
+ const line = describeGridLaunch('claude', WITH_MODEL)
expect(line).toContain('autonomous.ai')
- expect(line).toContain('glm-5.2')
+ expect(line).toContain('GLM-4.7-Flash')
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.ts
index 47a5bcbe6..a997ba0f0 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -1,21 +1,28 @@
/**
- * Pointing a newly created agent at an Autonomous Grid instead of the engine's own login.
+ * Pointing an 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.
+ * it, and sends the result as `payload.grid` on `agent_create` / `agent_retarget`. Nothing about that
+ * reaches an engine by itself: this CLI is what spawns the engine, so this module turns that payload
+ * into the launch — environment, and where the vendor demands it, argv.
*
- * ## The relay is OpenAI-compatible, and that is not enough
+ * ## Every entry here is the vendor's own documented contract
*
- * 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`.
+ * The relay speaks two dialects — Anthropic Messages at `<grid>/relay`, and OpenAI
+ * chat/completions + responses at `<grid>/relay/v1` — so an engine can be pointed at it only if the
+ * engine itself offers a way to change its endpoint. Those ways differ, and none of them is
+ * guessable: `ANTHROPIC_BASE_URL` for Claude Code, `-c model_providers.*` argv for Codex,
+ * `GROK_MODELS_BASE_URL` for Grok, `COPILOT_PROVIDER_BASE_URL` for Copilot. Each entry below cites
+ * where it was read from.
+ *
+ * An engine with no entry is REFUSED, and the refusal names why for that engine specifically. Two
+ * shapes of "no" appear repeatedly and are worth telling apart:
+ *
+ * * **Config-file only** (pi, kilo, agy's non-Gemini path): the provider block has to be written
+ * into the user's own dotfile. Editing another tool's configuration on someone's behalf is a
+ * side effect that outlives the agent, so this module does not do it.
+ * * **Vendor-bound** (cursor, amp, devin): the app talks to its own service and has no notion of
+ * an endpoint. There is nothing to set.
*
* 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.
@@ -30,10 +37,10 @@ export interface GridLaunchOverride {
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`.
+ * Per-engine forms are derived from this; see [relayBaseUrl] and [anthropicBaseUrl].
*/
baseUrl: string
- /** Short-lived, minted per launch. Never logged. */
+ /** Short-lived, minted per launch. Never logged, and never placed in argv. */
apiKey: string
/** Absent means "whatever the engine asks for" — the relay's own default. */
model?: string
@@ -46,8 +53,8 @@ export type GridOverrideParse =
/**
* 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.
+ * ends up in a process environment or an argv. Rejecting them keeps a malformed frame from producing
+ * an engine whose launch is subtly not what either side thinks it is.
*/
const CONTROL_CHARS = /[\u0000-\u001F\u007F]/
@@ -107,8 +114,14 @@ export function parseGridLaunchOverride(raw: unknown): GridOverrideParse {
}
}
+/** The OpenAI-compatible relay root — what every engine here wants except Claude Code. */
+export function relayBaseUrl(baseUrl: string): string {
+ const trimmed = baseUrl.replace(/\/+$/, '')
+ return trimmed.endsWith('/v1') ? trimmed : `${trimmed}/v1`
+}
+
/**
- * The relay root Claude Code wants, from the OpenAI-compatible one the control plane hands out.
+ * The relay root Claude Code wants.
*
* 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
@@ -120,70 +133,177 @@ export function anthropicBaseUrl(baseUrl: string): string {
return trimmed.endsWith('/v1') ? trimmed.slice(0, -'/v1'.length) : trimmed
}
+/** How one engine is launched against a grid. */
+export interface GridEngineLaunch {
+ /** Layered over the engine's inherited environment. This is where the key goes, always. */
+ env: Record<string, string>
+ /** Appended to the engine's argv. Never carries the key — `ps` is world-readable. */
+ args: string[]
+}
+
+interface GridEngineContract {
+ build: (override: GridLaunchOverride) => GridEngineLaunch
+ /** The engine cannot start against a grid without being told which model to ask for. */
+ requiresModel?: boolean
+}
+
+/** The variable Codex is told to read the key from — its own `env_key` indirection. */
+const CODEX_KEY_VAR = 'GRID_API_KEY'
+
+/**
+ * Every engine that can be pointed at a grid, and how.
+ *
+ * `undefined` is a refusal with a reason attached in [GRID_ENGINE_REFUSALS]; see the module comment
+ * for why a missing entry is never filled in with a plausible-looking guess.
+ */
+const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> = {
+ // The grid CLI's own launch target (`autonomous-grid/shared/launch/claude.py`), so these are the
+ // vendor's names as that team verified them rather than this repo's reading of them.
+ claude: {
+ build: (override) => ({
+ env: {
+ 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.
+ ...(override.model ? { ANTHROPIC_MODEL: override.model } : {}),
+ },
+ args: [],
+ }),
+ },
+
+ // Codex configures its provider entirely on the command line — `-c key=value` overrides anything
+ // `~/.codex/config.toml` would have said, which is how `ori codex` points it at OpenRouter without
+ // touching a dotfile (see `gatewayRuntime.ts`). Key names verified against the grid repo's
+ // `docs/codex-quickstart.md` and `-c` against codex-cli 0.144.6 on this machine.
+ //
+ // The key travels in the environment under `env_key`, never in argv.
+ codex: {
+ build: (override) => ({
+ env: { [CODEX_KEY_VAR]: override.apiKey },
+ args: [
+ '-c', 'model_provider="grid"',
+ '-c', 'model_providers.grid.name="Autonomous Grid"',
+ '-c', `model_providers.grid.base_url="${relayBaseUrl(override.baseUrl)}"`,
+ '-c', `model_providers.grid.env_key="${CODEX_KEY_VAR}"`,
+ // Mandatory: Codex speaks the Responses dialect and rejects `wire_api = "chat"`.
+ '-c', 'model_providers.grid.wire_api="responses"',
+ // The relay streams HTTP SSE, not WebSocket.
+ '-c', 'model_providers.grid.supports_websockets=false',
+ ...(override.model ? ['-m', override.model] : []),
+ ],
+ }),
+ },
+
+ // opencode's simplest documented custom provider: the OpenAI-compatible pair
+ // (https://opencode.ai/docs/providers). The model is left to the app — its `--model` wants a
+ // `provider/model` pair whose provider id is not documented for the env-var route, and inventing
+ // one would send it looking for a model that does not exist.
+ opencode: {
+ build: (override) => ({
+ env: {
+ OPENAI_BASE_URL: relayBaseUrl(override.baseUrl),
+ OPENAI_API_KEY: override.apiKey,
+ },
+ args: [],
+ }),
+ },
+
+ // Nous Research's documented trio for a custom OpenAI-compatible endpoint
+ // (hermes-agent/website/docs/reference/environment-variables.md).
+ hermes: {
+ build: (override) => ({
+ env: {
+ OPENAI_BASE_URL: relayBaseUrl(override.baseUrl),
+ OPENAI_API_KEY: override.apiKey,
+ ...(override.model ? { HERMES_INFERENCE_MODEL: override.model } : {}),
+ },
+ args: [],
+ }),
+ },
+
+ // xAI's own Grok CLI (the one this repo discovers under `~/.grok`, whose transcripts carry the
+ // `_x.ai/session/update` method). Its docs: "Grok fetches the model list from {base_url}/models",
+ // and "when you set models_base_url, Grok uses API key auth instead of session auth" — which is
+ // exactly the swap being asked for here. The model has no documented variable, so it goes in argv.
+ grok: {
+ build: (override) => ({
+ env: {
+ GROK_MODELS_BASE_URL: relayBaseUrl(override.baseUrl),
+ XAI_API_KEY: override.apiKey,
+ },
+ args: override.model ? ['-m', override.model] : [],
+ }),
+ },
+
+ // GitHub's documented BYOK path for Copilot CLI (docs.github.com … /use-byok-models). Copilot
+ // will not start against a custom provider without being told the model, so that is enforced
+ // here rather than left to fail inside the app.
+ copilot: {
+ requiresModel: true,
+ build: (override) => ({
+ env: {
+ COPILOT_PROVIDER_BASE_URL: relayBaseUrl(override.baseUrl),
+ COPILOT_PROVIDER_API_KEY: override.apiKey,
+ ...(override.model ? { COPILOT_MODEL: override.model } : {}),
+ },
+ args: [],
+ }),
+ },
+}
+
/**
- * How each engine is pointed at a grid through its environment alone — `null` where no such
- * mechanism is confirmed to exist.
+ * Why an engine cannot be pointed at a grid, in words the person who picked it can act on.
*
- * `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.
+ * Every engine without a contract has an entry: "unsupported" on its own tells a user nothing about
+ * whether to wait for a release, change a setting, or pick another engine.
*/
-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,
+const GRID_ENGINE_REFUSALS: Partial<Record<AgentEngine, string>> = {
+ cursor: 'Cursor Agent talks only to Cursor\'s own service — it has no endpoint setting',
+ amp: 'Amp talks only to its own service — it has no endpoint setting',
+ devin: 'Devin runs on its own hosted service — it has no endpoint setting',
+ pi: 'Pi needs a provider block written into ~/.pi/agent/models.json, which this will not edit for you',
+ kilo: 'the Kilo CLI has no OpenAI-compatible provider option yet (its own issues #5840, #6315)',
+ agy: 'Antigravity speaks the Gemini API, which this grid\'s relay does not serve',
+ muse: 'Muse Code documents no way to change its endpoint',
+ commandcode: 'Command Code documents no way to change its endpoint',
}
-/** Engines that can be pointed at a grid today, so error text can name what to pick instead. */
+/** Engines that can be pointed at a grid today, for error text that names what to pick instead. */
export function gridCapableEngines(): AgentEngine[] {
- return (Object.keys(GRID_ENGINE_ENV) as AgentEngine[]).filter((engine) => GRID_ENGINE_ENV[engine] !== null)
+ return Object.keys(GRID_ENGINE_CONTRACTS) as AgentEngine[]
}
-export type GridEnvResult =
- | { ok: true; env: Record<string, string> }
+export type GridLaunchResult =
+ | { ok: true; launch: GridEngineLaunch }
| { 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) {
+/** How `engine` must be launched to reach `override`, or why it cannot be. */
+export function buildGridEngineLaunch(engine: AgentEngine, override: GridLaunchOverride): GridLaunchResult {
+ const contract = GRID_ENGINE_CONTRACTS[engine]
+ if (!contract) {
+ const reason = GRID_ENGINE_REFUSALS[engine] ?? 'it has no known way to change its endpoint'
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(', ')}.`,
+ detail: `${engine} cannot run on grid ${override.networkName}: ${reason}. `
+ + `It would have run on its own login instead. Engines that can: ${gridCapableEngines().join(', ')}.`,
+ }
+ }
+ if (contract.requiresModel && !override.model) {
+ return {
+ ok: false,
+ error: 'GRID_MODEL_REQUIRED',
+ detail: `${engine} will not start against a grid without a model. `
+ + `Pick one for ${override.networkName} and try again.`,
}
}
- return { ok: true, env: build(override) }
+ return { ok: true, launch: contract.build(override) }
}
/** One log line naming where an agent was sent — grid, model, engine. Never the key. */
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
index f6fec3a45..31e9a5c90 100644
--- a/cli/src/lib/terminalAgentDiscovery.ts
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -244,7 +244,7 @@ export async function probeTerminalAgents(
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)
+ agent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)
}))
return { processTableAvailable: true, targets, ...discovered }
}
diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.ts
index 778ed4f1e..1da406c38 100644
--- a/cli/src/lib/tmuxAgentDiscovery.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.ts
@@ -238,7 +238,7 @@ export async function probeTmuxAgents(
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)
+ agent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)
}))
return probe
}