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.

fix(grid): declare the grid as a provider for opencode, instead of moving its endpoint

bubu-dudude4f859e6a8e
diff --git a/cli/README.md b/cli/README.md
index ff5091494..1a7ffb3cf 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -130,9 +130,14 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.json
session that environment with `new-session -e`, so the credential never appears in the engine's
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`), **copilot**
- (`COPILOT_PROVIDER_BASE_URL`) and **pi** (a private config directory via `PI_CODING_AGENT_DIR`,
- so the user's own `~/.pi` is never touched). Every other engine is **refused** with `GRID_ENGINE_UNSUPPORTED`
+ **hermes** (`OPENAI_BASE_URL`), **grok** (`GROK_MODELS_BASE_URL`), **copilot**
+ (`COPILOT_PROVIDER_BASE_URL`), and two that need a provider DECLARED rather than an endpoint moved:
+ **pi** (a private config directory via `PI_CODING_AGENT_DIR`) and **opencode** (a private
+ `opencode.json` via `OPENCODE_CONFIG`) — so the user's own `~/.pi` and `~/.config/opencode` are
+ never touched. OpenCode is in that second group because pointing `OPENAI_BASE_URL` at a grid leaves
+ its compiled-in model catalogue in charge: the endpoint moves, the model names do not, and the
+ relay answers `503 · No providers available for this model`.
+ 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`.
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index e56fa6090..3af3d72e6 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -3042,9 +3042,11 @@ async function runForeground(session: AuthSession): Promise<void> {
// An engine whose provider lives in a file gets a directory this daemon owns, never the
// user's own dotfiles. The label is unique per creation, so two agents never share one.
if (built.launch.configDir) {
- const { envVar, files } = built.launch.configDir
+ const { envVar, files, pointAt } = built.launch.configDir
try {
- gridLaunch.env[envVar] = await writeGridConfigDir(label, files)
+ const dir = await writeGridConfigDir(label, files)
+ // Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.
+ gridLaunch.env[envVar] = pointAt ? join(dir, pointAt) : dir
} catch (error) {
const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`
console.warn(`[agent] create ${engine} refused · ${detail}`)
@@ -3424,9 +3426,11 @@ async function runForeground(session: AuthSession): Promise<void> {
if (built && built.ok && built.launch.configDir) {
// Keyed on the agent, so moving the same agent between grids rewrites one directory rather
// than leaving a trail of them.
- const { envVar, files } = built.launch.configDir
+ const { envVar, files, pointAt } = built.launch.configDir
try {
- gridEnv[envVar] = await writeGridConfigDir(session.agentId, files)
+ const dir = await writeGridConfigDir(session.agentId, files)
+ // Same split as create: a directory for Pi, the file itself for OpenCode.
+ gridEnv[envVar] = pointAt ? join(dir, pointAt) : dir
} catch (error) {
release()
const detail = `could not write ${session.engine}'s grid configuration · ${error instanceof Error ? error.message : error}`
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index f20298f2c..a59faf8a3 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -5,6 +5,7 @@ import {
describeGridLaunch,
gridCapableEngines,
gridConflictingEnvToClear,
+ gridProviderId,
gridEnvVarNames,
parseGridLaunchOverride,
relayBaseUrl,
@@ -112,11 +113,7 @@ describe('the launch each engine gets', () => {
expect(launch.args).toContain('GLM-4.7-Flash')
})
- 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,
- })
+ it('uses the OpenAI-compatible pair for Hermes, which honours the endpoint it is given', () => {
expect(launchOf('hermes').env).toEqual({
OPENAI_BASE_URL: RELAY_V1,
OPENAI_API_KEY: WIRE.apiKey,
@@ -124,6 +121,13 @@ describe('the launch each engine gets', () => {
})
})
+ it('does NOT use that pair for opencode, which would not honour it', () => {
+ // OpenCode reads the endpoint but keeps its compiled-in `openai` catalogue, so the pair produced
+ // an engine naming models the grid had never heard of. It declares a provider instead — see the
+ // `opencode declares the grid as a provider` block below.
+ expect(launchOf('opencode').env).toEqual({ GRID_API_KEY: WIRE.apiKey })
+ })
+
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 })
@@ -276,7 +280,12 @@ describe('gridConflictingEnvToClear', () => {
// The regression this exists for: OpenCode was given OPENAI_BASE_URL for a grid, found an
// inherited ANTHROPIC_API_KEY, and spent it on api.anthropic.com instead.
expect(clearedFor('opencode')).toContain('ANTHROPIC_API_KEY')
- expect(clearedFor('opencode')).not.toContain('OPENAI_BASE_URL')
+ // And OPENAI_* goes too, now that opencode brings its own provider: leaving the user's own
+ // OpenAI key in place would re-arm the built-in catalogue this launch exists to get away from.
+ expect(clearedFor('opencode')).toContain('OPENAI_BASE_URL')
+ expect(clearedFor('opencode')).toContain('OPENAI_API_KEY')
+ // Its own variable is the one thing kept.
+ expect(clearedFor('opencode')).not.toContain('GRID_API_KEY')
})
it('clears the personal Anthropic key even for Claude, whose grid uses the bearer variable', () => {
@@ -298,3 +307,73 @@ describe('gridConflictingEnvToClear', () => {
expect(cleared).toEqual(expect.arrayContaining(['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'OPENAI_BASE_URL']))
})
})
+
+describe('opencode declares the grid as a provider', () => {
+ const base: GridLaunchOverride = {
+ networkId: 'grid-x',
+ networkName: 'autonomous.ai',
+ baseUrl: 'https://grid.autonomous.ai/grid-x/relay/v1',
+ apiKey: 'RELAY-KEY',
+ }
+ const launch = (model?: string) => {
+ const built = buildGridEngineLaunch('opencode', model ? { ...base, model } : base)
+ if (!built.ok) throw new Error('opencode refused')
+ return built.launch
+ }
+ const config = (model?: string) => JSON.parse(launch(model).configDir!.files[0].content)
+
+ it('slugifies a grid name into something a person can type as <id>/<model>', () => {
+ expect(gridProviderId('autonomous.ai')).toBe('autonomous-ai')
+ expect(gridProviderId('private autonomous')).toBe('private-autonomous')
+ expect(gridProviderId('macOS')).toBe('macos')
+ // Nothing left to slug: an empty provider key would make the config unparseable.
+ expect(gridProviderId('...')).toBe('grid')
+ })
+
+ it('never writes a top-level `model`, which OpenCode validates against a closed enum', () => {
+ // A private grid's model is not in that enum, so this key would make OpenCode refuse the whole
+ // config at startup — arriving as a dead pane well after the launch looked fine.
+ expect(config('DeepSeek-V4-Flash-0731')).not.toHaveProperty('model')
+ expect(config()).not.toHaveProperty('model')
+ })
+
+ it('selects the model on argv instead, which is not schema-validated', () => {
+ expect(launch('DeepSeek-V4-Flash-0731').args).toEqual(['-m', 'autonomous-ai/DeepSeek-V4-Flash-0731'])
+ })
+
+ it("falls back to the grid's router when no model was chosen", () => {
+ expect(launch().args).toEqual(['-m', 'autonomous-ai/Auto'])
+ // And the router is not listed twice when it IS the selection.
+ expect(Object.keys(config().provider['autonomous-ai'].models)).toEqual(['Auto'])
+ })
+
+ it('keeps the key out of the file and references it from the environment', () => {
+ const written = launch('DeepSeek-V4-Flash-0731')
+ expect(written.configDir!.files[0].content).not.toContain('RELAY-KEY')
+ expect(written.env).toEqual({ GRID_API_KEY: 'RELAY-KEY' })
+ expect(config('DeepSeek-V4-Flash-0731').provider['autonomous-ai'].options.apiKey)
+ .toBe('{env:GRID_API_KEY}')
+ })
+
+ it('does not set OPENAI_* beside its own provider', () => {
+ // Those would re-arm OpenCode's built-in `openai` provider, whose compiled-in catalogue is what
+ // picked a model the grid answered 503 for.
+ expect(launch('DeepSeek-V4-Flash-0731').env).not.toHaveProperty('OPENAI_BASE_URL')
+ expect(launch('DeepSeek-V4-Flash-0731').env).not.toHaveProperty('OPENAI_API_KEY')
+ })
+
+ it('passes the relay root through verbatim — the SDK appends the path itself', () => {
+ expect(config().provider['autonomous-ai'].options.baseURL).toBe(base.baseUrl)
+ })
+
+ it('omits `limit` entirely rather than writing half of one', () => {
+ // OpenCode requires `context` and `output` together and rejects the config given only one.
+ const models = config('DeepSeek-V4-Flash-0731').provider['autonomous-ai'].models
+ for (const entry of Object.values(models)) expect(entry).not.toHaveProperty('limit')
+ })
+
+ it('points OPENCODE_CONFIG at the file, not at the directory holding it', () => {
+ expect(launch().configDir!.envVar).toBe('OPENCODE_CONFIG')
+ expect(launch().configDir!.pointAt).toBe('opencode.json')
+ })
+})
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index 61dc19af3..f23bff7e9 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -149,6 +149,88 @@ export function anthropicBaseUrl(baseUrl: string): string {
return trimmed.endsWith('/v1') ? trimmed.slice(0, -'/v1'.length) : trimmed
}
+/**
+ * The relay's routing strategy, used when the user picked no particular model.
+ *
+ * Not a model: send a request naming it and the grid chooses one. It is `owned_by: grid-router` in
+ * the relay's `/models`, and the relay answers it like any other id — which is what lets a provider
+ * block that must name SOMETHING name this.
+ */
+const GRID_ROUTER_MODEL = 'Auto'
+
+/** The file OpenCode's `OPENCODE_CONFIG` is pointed at. */
+const OPENCODE_CONFIG_FILE = 'opencode.json'
+
+/**
+ * A grid's name as an OpenCode provider id.
+ *
+ * The id is what a person types as `<id>/<model>`, so it has to survive being typed: lowercase, no
+ * spaces, no dots. Grid names carry all three — `autonomous.ai`, `private autonomous`, `macOS` — so
+ * this is a real transformation rather than a formality.
+ *
+ * autonomous.ai -> autonomous-ai
+ * private autonomous -> private-autonomous
+ * macOS -> macos
+ *
+ * A name that leaves nothing behind (punctuation only) falls back to `grid`, because an empty
+ * provider key would make the config unparseable rather than merely odd.
+ */
+export function gridProviderId(networkName: string): string {
+ const slug = networkName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
+ return slug || 'grid'
+}
+
+/**
+ * The provider block OpenCode reads, as JSON.
+ *
+ * Four things here are load-bearing, each of which breaks the engine differently when got wrong:
+ *
+ * 1. **No top-level `model` key.** OpenCode's schema `$ref`s a CLOSED enum of known public models
+ * with no wildcard branch, so naming a private grid's model there makes OpenCode refuse the
+ * whole config at startup — a failure that arrives as a dead pane, long after the launch looked
+ * fine. The model is selected on argv instead, which is not schema-validated.
+ * 2. **`baseURL` is the relay root verbatim.** It already ends in `/relay/v1`; the SDK appends
+ * `/chat/completions` itself, so any "normalising" here 404s every request.
+ * 3. **`apiKey` is `{env:…}`, not the key.** Nothing written to disk by this module may contain a
+ * credential. This diverges from the advice a person following OpenCode's own docs gets — there
+ * the literal is recommended, because an unset variable silently becomes an empty string and a
+ * human-launched OpenCode has no guarantee the variable is set. Here it IS guaranteed: the
+ * daemon puts it in the pane's environment with `tmux new-session -e` before the engine starts.
+ * 4. **No `limit` block.** OpenCode requires `context` and `output` TOGETHER and rejects the config
+ * if only one is present. The relay reports a context window per model but this module is not
+ * the thing that read it, and inventing one would be worse than the defaults OpenCode already
+ * uses.
+ */
+function opencodeGridConfig(
+ provider: string,
+ override: GridLaunchOverride,
+ model: string,
+): string {
+ const models: Record<string, { name: string }> = { [model]: { name: model } }
+ // The router is always offered, so the picker inside OpenCode can fall back to "let the grid
+ // choose" without the agent being recreated. Skipped when it IS the selection, so one id never
+ // appears twice.
+ if (model !== GRID_ROUTER_MODEL) {
+ models[GRID_ROUTER_MODEL] = { name: `${GRID_ROUTER_MODEL} (grid picks the model)` }
+ }
+ return `${JSON.stringify({
+ $schema: 'https://opencode.ai/config.json',
+ provider: {
+ [provider]: {
+ npm: '@ai-sdk/openai-compatible',
+ // The grid's name as written — this is what a person reads in the model picker, so it keeps
+ // its dots and its capitals while the id beside it does not.
+ name: override.networkName,
+ options: {
+ baseURL: relayBaseUrl(override.baseUrl),
+ apiKey: `{env:${GRID_KEY_VAR}}`,
+ },
+ models,
+ },
+ },
+ }, null, 2)}\n`
+}
+
/** One file to write into the per-agent config directory a launch is given. */
export interface GridConfigFile {
/** File name inside the directory. Never a path — this writes one flat directory. */
@@ -172,7 +254,18 @@ export interface GridEngineLaunch {
* exactly as they left it, and deleting the directory undoes everything. No file written here may
* contain the key; Pi's provider block references an environment variable instead.
*/
- configDir?: { envVar: string; files: GridConfigFile[] }
+ configDir?: {
+ envVar: string
+ files: GridConfigFile[]
+ /**
+ * Point [envVar] at ONE of the written files rather than at the directory holding them.
+ *
+ * Pi wants the directory (`PI_CODING_AGENT_DIR`); OpenCode's `OPENCODE_CONFIG` wants a config
+ * file. Same mechanism — a private directory this daemon owns — differing only in what the
+ * engine is handed, so it is a field rather than a second writer.
+ */
+ pointAt?: string
+ }
}
interface GridEngineContract {
@@ -349,14 +442,48 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// (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 is the one engine here that an endpoint variable alone cannot steer, and the reason is
+ // worth stating because `OPENAI_BASE_URL` looks like it should be enough — the grid CLI's own
+ // `grid info --env` exports exactly that pair, and it is enough for hermes.
+ //
+ // OpenCode's `openai` provider carries a COMPILED-IN model catalogue (49 entries: gpt-4o,
+ // gpt-5.6-terra-pro, …). It sends requests to `OPENAI_BASE_URL` but never asks that endpoint what
+ // it serves, so pointing it at a grid gives an engine that will only ever name models the grid has
+ // never heard of. Measured: it selected `gpt-5.6-terra-pro` and the relay answered
+ //
+ // 503 · No providers available for this model. This grid serves: DeepSeek-V4-Flash-0731, …
+ //
+ // and `-m openai/DeepSeek-V4-Flash-0731` — naming a real grid model under its built-in provider —
+ // made OpenCode's own server throw instead.
+ //
+ // So it takes the shape codex and pi take: DECLARE a provider. `OPENCODE_CONFIG` names a config
+ // file, this daemon writes one into a directory it owns, and the grid arrives as a provider whose
+ // models are the grid's own ids. The user's `~/.config/opencode/opencode.json` is never opened.
opencode: {
- build: (override) => ({
- env: {
- OPENAI_BASE_URL: relayBaseUrl(override.baseUrl),
- OPENAI_API_KEY: override.apiKey,
- },
- args: [],
- }),
+ build: (override) => {
+ const provider = gridProviderId(override.networkName)
+ // No model chosen means the grid routes — `Auto` is the router's own id, and the relay serves
+ // it (verified: 200). It is a real id to OpenCode either way, which is what matters: the
+ // provider block has to name something, and leaving the model out entirely puts OpenCode back
+ // on its own catalogue and the 503 above.
+ const model = override.model ?? GRID_ROUTER_MODEL
+ return {
+ // The key travels in the environment and is REFERENCED from the file, never written into it
+ // — the rule every config-file engine here follows.
+ env: { [GRID_KEY_VAR]: override.apiKey },
+ // Deliberately NOT `OPENAI_BASE_URL`/`OPENAI_API_KEY`. Setting them would re-arm the built-in
+ // `openai` provider beside ours, and its catalogue is what chose the model the grid refused.
+ args: ['-m', `${provider}/${model}`],
+ configDir: {
+ envVar: 'OPENCODE_CONFIG',
+ pointAt: OPENCODE_CONFIG_FILE,
+ files: [{
+ name: OPENCODE_CONFIG_FILE,
+ content: opencodeGridConfig(provider, override, model),
+ }],
+ },
+ }
+ },
},
// Nous Research's documented trio for a custom OpenAI-compatible endpoint