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
fix(grid): clear the vendor credentials a grid launch does not set
bubu-dudu382c3ff67f88
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex f32d7d547..7a8871161 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -48,7 +48,7 @@ import { ENGINE_CLI_COMMANDS, ENGINES, engineBin } from './lib/engineBin.js'import type { AgentEngine } from './engines/types.js'import { engineInstallRecipe } from './lib/engineInstall.js'import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'-import { buildGridEngineLaunch, describeGridLaunch, gridEnvVarNames } from './lib/gridLaunch.js'+import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames } from './lib/gridLaunch.js'import { writeGridConfigDir } from './lib/gridConfigDir.js'import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'@@ -3073,7 +3073,13 @@ async function runForeground(session: AuthSession): Promise<void> {}return recipe.command})()- const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args, installFirst }+ // Clearing the vendor credentials this launch does NOT set is part of pointing an agent at a+ // grid, not an extra. An engine chooses its provider from whatever it can see, and an inherited+ // key wins on its own terms — OpenCode picked Anthropic over a grid it had been handed, and said+ // only `invalid x-api-key`. Nothing is cleared when no grid is in play: an agent on its own login+ // is supposed to use exactly these variables.+ const clearEnv = gridLaunch ? gridConflictingEnvToClear(gridLaunch) : undefined+ const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args, installFirst, clearEnv }const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)if (installFirst) console.log(`[agent] create ${engine} · installing first · ${installFirst}`)diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex 1678374cc..1c8db6c63 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -55,6 +55,19 @@ export interface LaunchCommandOptions {* is the case above.*/installFirst?: string+ /**+ * Environment variables to clear in the pane before the engine starts — the vendor credentials a+ * grid launch must not leave lying around. See `gridConflictingEnvToClear` in `gridLaunch.ts`,+ * which is the only caller and which computes them from what the launch itself sets.+ *+ * It has to happen HERE rather than through tmux, because `tmux new-session -e` can only set a+ * variable, never remove one — and the value being removed was inherited from the tmux server, the+ * daemon, or the terminal that started the app, none of which this process can reach back into.+ *+ * Scoped to the engine's own process. Nothing on disk changes, and a plain shell on the same+ * machine keeps everything it had.+ */+ clearEnv?: readonly string[]}/**@@ -164,10 +177,28 @@ export function buildEngineLaunchArgv(const command = buildEngineCommandArgv(engine, opts)const interactive = interactiveEngineShell(shell)if (!interactive) return command- const script = opts.installFirst+ // The clear comes FIRST, before the install as well as before the engine. An installer is a child+ // of this shell and inherits what it inherits: `npm` is not going to spend someone's Anthropic key,+ // but an install script that probes for credentials to configure itself would, and the whole point+ // of this launch is that the agent's environment is the one the user asked for.+ const prelude = clearEnvPrelude(opts.clearEnv)+ const body = opts.installFirst? installThenExecScript(opts.installFirst): 'exec "$@"'- return [interactive.path, ...interactive.args, script, 'harness-engine', ...command]+ return [interactive.path, ...interactive.args, prelude + body, 'harness-engine', ...command]+}++/**+ * `unset` for the variables a grid launch must not let through, or nothing at all.+ *+ * Names only — never values — and each is validated against a strict shell-identifier shape before it+ * reaches the script. The list is a constant in our own source today, so this is a guard against a+ * future caller rather than against anything on the wire; it is here because the day that changes is+ * the day nobody re-reads this function.+ */+function clearEnvPrelude(names: readonly string[] | undefined): string {+ const safe = (names ?? []).filter((name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name))+ return safe.length ? `unset ${safe.join(' ')}\n` : ''}/**diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.tsindex 0d3b762ed..f20298f2c 100644--- a/cli/src/lib/gridLaunch.spec.ts+++ b/cli/src/lib/gridLaunch.spec.ts@@ -4,6 +4,7 @@ import {buildGridEngineLaunch,describeGridLaunch,gridCapableEngines,+ gridConflictingEnvToClear,gridEnvVarNames,parseGridLaunchOverride,relayBaseUrl,@@ -245,3 +246,55 @@ describe('gridEnvVarNames', () => {expect(gridEnvVarNames('amp')).toEqual([])})})++describe('gridConflictingEnvToClear', () => {+ const override = {+ networkId: 'grid-x',+ networkName: 'autonomous.ai',+ baseUrl: 'https://grid.autonomous.ai/grid-x/relay/v1',+ apiKey: 'RELAY-KEY',+ }+ const clearedFor = (engine: AgentEngine, model?: string): string[] => {+ const built = buildGridEngineLaunch(engine, model ? { ...override, model } : override)+ if (!built.ok) throw new Error(`${engine} refused: ${JSON.stringify(built)}`)+ return gridConflictingEnvToClear(built.launch)+ }++ it('never clears a variable the same launch sets', () => {+ for (const engine of ['claude', 'codex', 'opencode', 'hermes', 'grok', 'copilot', 'pi'] as const) {+ const built = buildGridEngineLaunch(engine, { ...override, model: 'a-model' })+ if (!built.ok) throw new Error(`${engine} refused`)+ const set = new Set(Object.keys(built.launch.env))+ if (built.launch.configDir) set.add(built.launch.configDir.envVar)+ for (const name of gridConflictingEnvToClear(built.launch)) {+ expect(set.has(name), `${engine} both sets and clears ${name}`).toBe(false)+ }+ }+ })++ it("clears the key that redirected OpenCode away from the grid it was handed", () => {+ // 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')+ })++ it('clears the personal Anthropic key even for Claude, whose grid uses the bearer variable', () => {+ // Claude Code warns when both are set and the relay wants the Bearer; leaving the API key behind+ // is what let a dotfile decide which one won.+ expect(clearedFor('claude')).toContain('ANTHROPIC_API_KEY')+ expect(clearedFor('claude')).not.toContain('ANTHROPIC_AUTH_TOKEN')+ expect(clearedFor('claude')).not.toContain('ANTHROPIC_BASE_URL')+ })++ it('keeps ANTHROPIC_MODEL only when the launch pins one', () => {+ expect(clearedFor('claude')).toContain('ANTHROPIC_MODEL')+ expect(clearedFor('claude', 'DeepSeek-V4-Flash-0731')).not.toContain('ANTHROPIC_MODEL')+ })++ it('leaves codex its GRID_API_KEY and clears every vendor variable around it', () => {+ const cleared = clearedFor('codex')+ expect(cleared).not.toContain('GRID_API_KEY')+ expect(cleared).toEqual(expect.arrayContaining(['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'OPENAI_BASE_URL']))+ })+})diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.tsindex f803f7874..61dc19af3 100644--- a/cli/src/lib/gridLaunch.ts+++ b/cli/src/lib/gridLaunch.ts@@ -192,6 +192,63 @@ const GRID_KEY_VAR = 'GRID_API_KEY'/** The provider id our generated config declares. Pi selects it as `--model <id>/<model>`. */const GRID_PROVIDER_ID = 'grid'+/**+ * Every variable any contract in this file uses to point an engine somewhere.+ *+ * A grid launch has to CLEAR the ones it does not itself set, because setting the right variable is+ * not enough to decide where an engine goes: an engine picks a provider from whatever credentials it+ * can see, and a stray one wins on its own terms. Measured, twice, on one machine:+ *+ * * OpenCode, handed `OPENAI_BASE_URL` for a grid, found an inherited `ANTHROPIC_API_KEY` and chose+ * Claude Sonnet at api.anthropic.com — reporting `invalid x-api-key`, a sentence that names+ * neither the grid nor the variable that redirected it.+ * * Claude Code, on the same machine, had its `ANTHROPIC_BASE_URL` deleted by a line in `.zshrc` and+ * fell back to the same key, with the same unreadable result.+ *+ * The inherited value arrives from further away than a user can reasonably audit. On that machine it+ * came from `.zshrc`, and then — after that was fixed — from a VS Code setting+ * (`claudeCode.environmentVariables`) that seeded the terminal the desktop app was launched from,+ * whose environment the app passed to the daemon, which passed it to the tmux server, which gave it+ * to every pane. Four layers, none visible from the failure.+ *+ * So the launch is the place to settle it: it is the only point that knows the user asked for a grid.+ * Unset here is scoped to the engine's own process and touches nothing on disk — a plain terminal on+ * the same machine keeps every variable it had.+ *+ * The list is deliberately OUR OWN vars rather than a survey of every provider an engine supports.+ * Enumerating those is unbounded and would go stale silently; these are the ones this file uses, so+ * this file can be right about them.+ */+export const GRID_CONFLICTING_ENV_VARS: readonly string[] = [+ 'ANTHROPIC_API_KEY',+ 'ANTHROPIC_AUTH_TOKEN',+ 'ANTHROPIC_BASE_URL',+ 'ANTHROPIC_MODEL',+ 'OPENAI_API_KEY',+ 'OPENAI_BASE_URL',+ 'XAI_API_KEY',+ 'GROK_MODELS_BASE_URL',+ 'COPILOT_PROVIDER_API_KEY',+ 'COPILOT_PROVIDER_BASE_URL',+ 'COPILOT_MODEL',+ 'HERMES_INFERENCE_MODEL',+ GRID_KEY_VAR,+]++/**+ * The variables this launch must clear: everything in [GRID_CONFLICTING_ENV_VARS] the launch does not+ * itself set.+ *+ * Set-then-unset would be a bug, so the two sets are computed from one another rather than listed+ * twice — a contract that gains a variable stops clearing it in the same edit.+ */+export function gridConflictingEnvToClear(launch: GridEngineLaunch): string[] {+ const provided = new Set(Object.keys(launch.env))+ if (launch.configDir) provided.add(launch.configDir.envVar)+ return GRID_CONFLICTING_ENV_VARS.filter((name) => !provided.has(name))+}++/*** Pi's provider block, as the Grid app shipped and unit-tested it* (`autonomous-grid-app`, `pi_grid_config.dart` at 36d00c95, before Pi was dropped from that app for