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(cli): one sign-in, one sign-out, and the grid's models

bitcoinbuilder7c5a287cb1fd
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.ts
index ef7d738f2..48bd1db33 100644
--- a/cli/src/authCommand.spec.ts
+++ b/cli/src/authCommand.spec.ts
@@ -151,7 +151,16 @@ describe('harness login --json', () => {
const result = await runAsync(root, ['login', '--json'], base)
expect(result.status).toBe(0)
const lines = result.stdout.trim().split('\n').map((l) => JSON.parse(l))
- expect(lines).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true }])
+ // The sign-in now also hands its token to `grid` and makes sure the account's private grid
+ // exists — best-effort, reported on this line rather than allowed to change its status. There is
+ // no `grid` on PATH in this test, so it reports the attempt and the harness sign-in still
+ // succeeds, which is the property worth pinning.
+ expect(lines).toEqual([{
+ type: 'result',
+ status: 'success',
+ alreadySignedIn: true,
+ grid: { signedIn: false, code: expect.any(String) },
+ }])
})
it('emits a BACKEND_ERROR result line (not a stack trace) when authorize-native is unreachable', async () => {
@@ -200,6 +209,12 @@ describe('harness login --json', () => {
expect(exitCode).toBe(0)
// Drain any trailing buffered line after exit.
if (stdout.trim()) lines.push(JSON.parse(stdout.trim()))
- expect(lines[1]).toEqual({ type: 'result', status: 'success' })
+ // Same contract as the already-signed-in line: the grid hand-off is reported here, and its
+ // failure (no `grid` on PATH in this test) never changes `status`.
+ expect(lines[1]).toEqual({
+ type: 'result',
+ status: 'success',
+ grid: { signedIn: false, code: expect.any(String) },
+ })
}, 15_000)
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 39b3776ab..d3f840616 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -26,6 +26,7 @@ import { ENGINES, type AgentEngine } from './engines/types.js'
import { listDir } from './lib/fsBrowse.js'
import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'
import { parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
+import { listGridModels, resolveGridTarget } from './lib/gridModels.js'
import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'
import { probeEngines } from './lib/engineProbe.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
@@ -544,6 +545,13 @@ export class BackendSocket {
return this.e2ee.remotePasswordStatus()
}
+ /** The account's private harness grid name, as the backend last reported it. Null until the first
+ * `machine_meta` lands, or when this account has none yet. */
+ private harnessGridName: string | null = null
+
+ /** Which grid this machine's agents can be pointed at — for `harness status` and the models RPC. */
+ gridName(): string | null { return this.harnessGridName }
+
connect(): void {
if (this.closed || this.ws || this.connecting) return
this.connecting = true
@@ -1109,7 +1117,12 @@ export class BackendSocket {
// Machine display name (seed on connect + web renames) — mirrored locally for `harness status`.
if (type === 'machine_meta') {
- const name = (frame.payload as { name?: unknown } | undefined)?.name
+ const meta = frame.payload as { name?: unknown; gridName?: unknown } | undefined
+ const name = meta?.name
+ // The account's private grid, pushed on every connect. Held in memory only: it is the
+ // backend's value, and a daemon that cached it on disk would keep answering with a stale one
+ // after the account's grid changed.
+ this.harnessGridName = typeof meta?.gridName === 'string' && meta.gridName.trim() ? meta.gridName.trim() : null
this.onMachineMeta?.(typeof name === 'string' && name.trim() ? name.trim() : null)
return
}
@@ -1409,6 +1422,16 @@ export class BackendSocket {
return
}
+ case 'grid_models_list': {
+ // Only the account's OWN private grid: the picker is "models my machines serve", not a
+ // catalogue of every grid this computer's `grid` CLI happens to be signed into.
+ reply(type, requestId, {
+ gridName: this.harnessGridName,
+ models: await listGridModels(this.harnessGridName),
+ })
+ return
+ }
+
case 'models_list': {
const sessionId = typeof payload.agentId === 'string' && payload.agentId
? payload.agentId
@@ -1594,6 +1617,19 @@ export class BackendSocket {
if (!agentId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
if (!this.onRetargetAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
const clear = payload.clearGrid === true
+ // `gridModel` is the header picker's frame: a model id and nothing else. The endpoint and
+ // the credential are resolved HERE, from this machine's own signed-in `grid`, so neither
+ // ever crosses the relay and the app cannot be the source of truth for an address it does
+ // not know. A client that sends the full `grid` object still works unchanged.
+ const picked = typeof payload.gridModel === 'string' ? payload.gridModel : ''
+ if (picked && payload.grid === undefined && !clear) {
+ const resolved = await resolveGridTarget(this.harnessGridName, picked)
+ if (!resolved) {
+ reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: 'Could not read this machine\'s grid endpoint.' })
+ return
+ }
+ payload.grid = resolved
+ }
const target = parseGridLaunchOverride(payload.grid)
// Exactly one, and `clearGrid` is a separate field rather than `grid: null` on purpose:
// parseGridLaunchOverride already answers `absent` for both undefined and null, so
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index dcdf41e76..17cb264a5 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -49,6 +49,7 @@ import { readOrMintComputerId } from './lib/computerIdentity.js'
import { renderLoginSuccessHtml } from './lib/loginPage.js'
import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'
import { handOffToGrid } from './lib/gridHandoff.js'
+import { ensureHarnessGrid } from './lib/gridEnsure.js'
import { passThroughToGridLogout } from './lib/gridLogout.js'
import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
import { ENGINE_CLI_COMMANDS, ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'
@@ -484,6 +485,42 @@ type SignInOutcome =
/** Refused. Under `--json` its own coded result line has already been emitted. */
| { signedIn: false }
+/**
+ * Sign this computer in to its grid too, and make sure the account's private harness grid exists.
+ *
+ * ⚠️ **Best-effort, always.** A machine with no `grid`, one too old for `--harness`, a grid sign-in
+ * that fails, a backend that predates `POST /api/grid/name` — every one of them is a sentence on
+ * stderr and a harness sign-in that still succeeds. The harness is what the person asked for; the
+ * grid is what it can usually also arrange. `harness grid login` stays the explicit path, where the
+ * same failure IS the command's failure and exits non-zero.
+ *
+ * Returns what happened, so `--json` callers can carry it on their own result line.
+ */
+async function attachGridToSignIn(token: string, json: boolean): Promise<Record<string, unknown>> {
+ const note = (line: string): void => { if (!json) console.error(` · ${line}`) }
+ const handoff = await handOffToGrid(token, { json: true })
+ if (handoff.code !== 'OK') {
+ note(handoff.message)
+ return { grid: { signedIn: false, code: handoff.code } }
+ }
+ // The name is the backend's to mint and remember — this CLI holds neither the account's email nor
+ // its id (see backend/src/routes/grid.ts). A backend without the route is simply an older backend:
+ // no grid is ensured, nothing fails, and the next sign-in after it ships picks this up.
+ let gridName: string | null = null
+ try {
+ const { headers } = await controlPlaneAuth()
+ gridName = (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers)).gridName ?? null
+ } catch (err) {
+ note(`Could not read this account's grid name (${(err as Error).message}); skipping grid setup.`)
+ return { grid: { signedIn: true, ensured: 'skipped' } }
+ }
+ if (!gridName) return { grid: { signedIn: true, ensured: 'skipped' } }
+ const ensured = await ensureHarnessGrid(gridName)
+ if (ensured.status === 'failed' || ensured.status === 'skipped') note(ensured.message)
+ else if (ensured.status === 'created') note(`Created your private grid '${gridName}'.`)
+ return { grid: { signedIn: true, ensured: ensured.status, name: gridName } }
+}
+
async function loginCommand(
foreground: boolean,
force: boolean,
@@ -492,9 +529,21 @@ async function loginCommand(
): Promise<SignInOutcome> {
if (foreground) throw new Error('`harness login` does not run the adapter. Use `harness start -f`.')
const emit = (line: Record<string, unknown>): void => { if (json) console.log(JSON.stringify(line)) }
- const succeed = (alreadySignedIn: boolean): SignInOutcome => {
+ const succeed = async (alreadySignedIn: boolean): Promise<SignInOutcome> => {
+ // `chained` is `harness grid login`, which runs the hand-off itself and reports it as its own
+ // result — doing it here too would sign in to the grid twice and print two answers for one act.
+ let grid: Record<string, unknown> = {}
+ if (!opts.chained) {
+ try {
+ grid = await attachGridToSignIn(await new AuthSessionManager(backendHttpBase()).accessToken(), json)
+ } catch {
+ // The harness session is already saved and valid; a grid step that throws is still only a
+ // grid step. Never let it turn a completed sign-in into a failure.
+ grid = {}
+ }
+ }
if (opts.chained) return { signedIn: true, alreadySignedIn }
- if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true } : { type: 'result', status: 'success' })
+ if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true, ...grid } : { type: 'result', status: 'success', ...grid })
else if (alreadySignedIn) console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')
else console.log('\n ✓ Signed in. Run `harness start` to connect this computer.\n')
return { signedIn: true, alreadySignedIn }
@@ -517,7 +566,7 @@ async function loginCommand(
}
throw err
}
- return succeed(true)
+ return await succeed(true)
}
// A forced login may intentionally switch SSO accounts. The old daemon must not keep streaming
// under its existing socket while this process replaces the durable session.
@@ -610,7 +659,7 @@ async function loginCommand(
if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }
throw err
}
- return succeed(false)
+ return await succeed(false)
} finally {
await new Promise<void>((resolve) => callback.close(() => resolve()))
}
@@ -925,23 +974,33 @@ async function updateCommand(force: boolean): Promise<void> {
/**
* Stop the local adapter and discard this computer's SSO session — local, and unable to fail.
*
- * ⚠️ **This never touches the grid credential store, and must not learn to.** Two reasons, and both
- * matter: `grid logout` can refuse and exit non-zero over a serve child it cannot confirm stopped,
- * so cascading would let a grid condition block a harness sign-out for a reason that has nothing to
- * do with the harness; and the store may predate the harness entirely, having been written by a
- * browser sign-in this CLI knows nothing about. All that is owed is the sentence below, so that a
- * long-lived credential is not left behind in silence.
+ * **This DOES sign the grid out too, as of the one-sign-in flow.** That reverses the rule this
+ * comment used to state, so the reversal is written down rather than left to be rediscovered: one
+ * sign-in creates the grid session, so one sign-out ends it. The two objections that rule was built
+ * on are both answered rather than ignored —
+ *
+ * * `grid logout` can refuse and exit non-zero over a serve child it cannot confirm stopped. So
+ * its refusal is REPORTED, never propagated: a grid condition must not block a harness sign-out.
+ * * the grid store may predate the harness, written by a browser sign-in this CLI knows nothing
+ * about. Ending that session is now the intended behaviour, not an overreach — and when no
+ * `grid` can be run at all, the old sentence is still printed so nothing is left behind silently.
+ *
+ * It runs BEFORE the harness session is cleared, because `grid logout` tears down every serve child
+ * on this box first, while the token that makes their deregistration authoritative still exists.
*/
async function logout(): Promise<void> {
// Through the lock-taking stop, not an inline kill: a logout that lands mid-handoff would otherwise
// SIGTERM the OLD daemon, leave the new one coming up, and then delete the session under it.
await stopDaemonProcess()
+ // Before clearAuthSession: see the note above on serve children. Its exit code is deliberately
+ // dropped — this command cannot fail — and its own words have already reached the terminal.
+ const gridOut = await passThroughToGridLogout([])
clearAuthSession()
rmSync(MACHINE_NAME_FILE, { force: true })
console.log('Signed out. Run `harness login`, then `harness start`, to reconnect this computer.')
- // Existence is the whole of the test — nothing is read out of the store, and nothing is written
- // into it. On stderr, so a script reading this command's output is unaffected by it.
- warnIfGridSignInRemains()
+ // Only when there was no `grid` to run at all. A child that ran has already said what it did, and
+ // repeating "your grid sign-in is still here" after a successful sign-out would be false.
+ if (!gridOut.ran) warnIfGridSignInRemains()
process.exit(0)
}
diff --git a/cli/src/gridCommand.spec.ts b/cli/src/gridCommand.spec.ts
index f4811a828..69aae8e6b 100644
--- a/cli/src/gridCommand.spec.ts
+++ b/cli/src/gridCommand.spec.ts
@@ -573,8 +573,8 @@ function seedGridCredentials(dir: string): string {
* never wrote, and the SILENT case would then pass for entirely the wrong reason. Passing
* `undefined` drops the variable from the child's environment altogether, which is the state the
* `~/.grid` default is for. */
-function runLogout(root: string, gridHome?: string): Promise<Run> {
- return run(root, ['logout'], 'http://127.0.0.1:1', { GRID_HOME: gridHome })
+function runLogout(root: string, gridHome?: string, grid: GridOnPath = 'runnable'): Promise<Run> {
+ return run(root, ['logout'], 'http://127.0.0.1:1', { GRID_HOME: gridHome }, grid)
}
describe('harness grid logout', () => {
@@ -688,32 +688,64 @@ describe('harness grid logout', () => {
}, 20_000)
})
-describe('harness logout — the grid credential it will not touch', () => {
- it('warns, naming `harness grid logout`, when a grid sign-in is still on this machine', async () => {
+describe('harness logout — the grid sign-out it now performs', () => {
+ // ⚠️ This suite used to be named "the grid credential it will not touch" and asserted the
+ // OPPOSITE: that `harness logout` only ever printed a sentence about the grid. The one-sign-in
+ // flow reversed that decision deliberately — one sign-in creates the grid session, so one
+ // sign-out ends it — and these tests are what stop it being reverted by someone reading the old
+ // rule. The two objections the old rule was built on are each pinned below rather than dropped.
+
+ it('runs `grid logout` as part of signing out', async () => {
const root = tempRoot()
seedSession(root)
- seedGridCredentials(join(root, '.grid'))
const result = await runLogout(root)
- // Local, and unable to fail: the warning is a sentence, never a condition.
expect(result.status).toBe(0)
expect(result.stdout).toContain('Signed out.')
- expect(result.stderr).toContain('harness grid logout')
+ expect(readRecord(root).args).toEqual(['logout'])
}, 20_000)
- it('stays silent when there are no grid credentials', async () => {
+ it('completes the harness sign-out even when the grid refuses', async () => {
const root = tempRoot()
seedSession(root)
+ // `grid logout` refuses over a serve child it cannot confirm stopped. That must be reported and
+ // never propagated: a grid condition cannot block a harness sign-out.
+ const result = await run(root, ['logout'], 'http://127.0.0.1:1', {
+ FAKE_GRID_EXIT: '1',
+ FAKE_GRID_STDERR: 'dt-edge: still serving on pid 4242. Stop it, or sign out with --force.\n',
+ })
- const result = await runLogout(root)
+ expect(result.status).toBe(0)
+ expect(result.stdout).toContain('Signed out.')
+ expect(result.stderr).toContain('still serving on pid 4242')
+ }, 20_000)
+
+ it('falls back to the old sentence when there is no `grid` to run at all', async () => {
+ const root = tempRoot()
+ seedSession(root)
+ seedGridCredentials(join(root, '.grid'))
+ const result = await runLogout(root, undefined, 'absent')
+
+ // Nothing ran, so a credential really is being left behind — which is the one case the warning
+ // was written for, and the only one where it is still true.
expect(result.status).toBe(0)
expect(result.stdout).toContain('Signed out.')
+ expect(result.stderr).toContain('harness grid logout')
+ }, 20_000)
+
+ it('says nothing about the grid when nothing ran and there was no credential either', async () => {
+ const root = tempRoot()
+ seedSession(root)
+
+ const result = await runLogout(root, undefined, 'absent')
+
+ expect(result.status).toBe(0)
expect(result.stderr).not.toContain('grid logout')
}, 20_000)
- it('never removes the grid credential file', async () => {
+ it('never deletes the grid credential file itself', async () => {
const root = tempRoot()
seedSession(root)
const credentials = seedGridCredentials(join(root, '.grid'))
@@ -721,8 +753,8 @@ describe('harness logout — the grid credential it will not touch', () => {
await runLogout(root)
- // The store may predate the harness entirely — a browser sign-in it knows nothing about — so
- // the warning is the whole of what this command is entitled to do about it.
+ // Deleting credentials is `grid logout`'s own job, done in its own order (serve children first).
+ // The harness spawns it and reads nothing out of the store.
expect(existsSync(credentials)).toBe(true)
expect(readFileSync(credentials, 'utf8')).toBe(before)
}, 20_000)
@@ -733,7 +765,9 @@ describe('harness logout — the grid credential it will not touch', () => {
const elsewhere = join(root, 'grid-home')
seedGridCredentials(elsewhere)
- const result = await runLogout(root, elsewhere)
+ // With no `grid` on PATH the fallback sentence fires, which is what makes the path resolution
+ // observable at all — the cascade itself never reads the store.
+ const result = await runLogout(root, elsewhere, 'absent')
expect(result.stderr).toContain('harness grid logout')
}, 20_000)
@@ -741,31 +775,14 @@ describe('harness logout — the grid credential it will not touch', () => {
it('expands a leading ~ in GRID_HOME, because `grid` does', async () => {
const root = tempRoot()
seedSession(root)
+ // `envFor` sets HOME to the temp root, so `~` inside the child expands to there — seeding at
+ // the TEST process's home would be a different directory entirely.
seedGridCredentials(join(root, 'grid-state'))
- // A shell expands `~` at assignment; a systemd unit, a Docker ENV or a .env file does not. There
- // `grid`'s own `expanduser()` still resolves it, so a literal value taken verbatim here would
- // look for a directory named `~` and go silent about a credential that is definitely present.
- const result = await runLogout(root, '~/grid-state')
+ const result = await runLogout(root, '~/grid-state', 'absent')
expect(result.stderr).toContain('harness grid logout')
}, 20_000)
-
- it('does not warn about a store GRID_HOME points away from', async () => {
- const root = tempRoot()
- seedSession(root)
- // Credentials at the DEFAULT location, and a GRID_HOME aimed at an empty directory. Without the
- // override being read, the check would find the default store and warn — so this is the negative
- // control that makes the case above mean "it read GRID_HOME" rather than "it found something".
- seedGridCredentials(join(root, '.grid'))
- const empty = join(root, 'grid-home-empty')
- mkdirSync(empty, { recursive: true })
-
- const result = await runLogout(root, empty)
-
- expect(result.status).toBe(0)
- expect(result.stderr).not.toContain('grid logout')
- }, 20_000)
})
describe('harness reset — the second door onto the same sign-out', () => {
diff --git a/cli/src/lib/gridEnsure.spec.ts b/cli/src/lib/gridEnsure.spec.ts
new file mode 100644
index 000000000..bd6352778
--- /dev/null
+++ b/cli/src/lib/gridEnsure.spec.ts
@@ -0,0 +1,148 @@
+/**
+ * `ensureHarnessGrid` against a fake `grid` first on PATH — the same seam `gridCommand.spec.ts`
+ * uses, for the same reason: the real binary talks to a control plane, and the questions worth
+ * asking here are all about which argv this module sends and what it believes about the answer.
+ */
+import { afterEach, describe, expect, it } from 'vitest'
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+const dirs: string[] = []
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ delete process.env.HARNESS_GRID_BIN
+})
+
+/**
+ * A `grid` whose behaviour is data: a JSON script the test writes beside it decides what each verb
+ * answers, and every invocation is appended to a log the test reads back.
+ */
+const FAKE_GRID = `#!/usr/bin/env node
+const fs = require('fs')
+const log = process.env.FAKE_GRID_LOG
+const plan = JSON.parse(fs.readFileSync(process.env.FAKE_GRID_PLAN, 'utf8'))
+const args = process.argv.slice(2).filter((a) => a !== '--remote')
+const verb = args[0] || ''
+const calls = fs.existsSync(log) ? JSON.parse(fs.readFileSync(log, 'utf8')) : []
+calls.push(process.argv.slice(2))
+fs.writeFileSync(log, JSON.stringify(calls))
+const step = plan[verb]
+if (!step) { process.exit(0) }
+// \`ls\` may answer differently before and after a create, so its answer can be a LIST of turns.
+const turn = Array.isArray(step) ? (step[calls.filter((c) => c.includes(verb)).length - 1] ?? step[step.length - 1]) : step
+if (turn.stdout) process.stdout.write(turn.stdout)
+if (turn.stderr) process.stderr.write(turn.stderr)
+process.exit(turn.exit ?? 0)
+`
+
+interface Turn { stdout?: string; stderr?: string; exit?: number }
+
+function fakeGrid(plan: Record<string, Turn | Turn[]>): { calls: () => string[][] } {
+ const root = mkdtempSync(join(tmpdir(), 'grid-ensure-'))
+ dirs.push(root)
+ const bin = join(root, 'grid')
+ writeFileSync(bin, FAKE_GRID)
+ chmodSync(bin, 0o755)
+ const planFile = join(root, 'plan.json')
+ writeFileSync(planFile, JSON.stringify(plan))
+ const log = join(root, 'calls.json')
+ process.env.HARNESS_GRID_BIN = bin
+ process.env.FAKE_GRID_PLAN = planFile
+ process.env.FAKE_GRID_LOG = log
+ return {
+ calls: () => JSON.parse(readFileSync(log, 'utf8')) as string[][],
+ }
+}
+
+const VERSION_OK: Turn = { stdout: 'grid 0.3.46\n' }
+const rows = (...names: string[]): string =>
+ JSON.stringify(names.map((n) => ({ grid: n, type: 'permissioned-public', id: `grid-${n}` })))
+
+async function ensure(name = 'someone-7f3a91c4') {
+ const { ensureHarnessGrid } = await import('./gridEnsure.js')
+ return ensureHarnessGrid(name)
+}
+
+describe('ensureHarnessGrid', () => {
+ it('creates the grid when the account has none, as a private permissioned-public one', async () => {
+ const fake = fakeGrid({
+ version: VERSION_OK,
+ sync: {},
+ ls: { stdout: rows('something-else') },
+ start: {},
+ })
+ expect(await ensure()).toEqual({ status: 'created', message: '' })
+ const start = fake.calls().find((c) => c.includes('start'))
+ // The type is the whole safety property: `permissioned-providers` would open the grid to
+ // strangers and switch billing on.
+ expect(start).toEqual(['--remote', 'start', 'someone-7f3a91c4', '--type', 'permissioned-public'])
+ })
+
+ it('syncs AGAIN after creating, so the new grid has its access token', async () => {
+ // A just-created grid has no per-grid token locally; `grid info --env` and `grid join` both
+ // refuse until a refresh. Measured against the real control plane.
+ const fake = fakeGrid({ version: VERSION_OK, sync: {}, ls: { stdout: rows() }, start: {} })
+ expect((await ensure()).status).toBe('created')
+ const verbs = fake.calls().map((c) => c.find((a) => a !== '--remote'))
+ expect(verbs.filter((v) => v === 'sync').length).toBe(2)
+ expect(verbs.lastIndexOf('sync')).toBeGreaterThan(verbs.indexOf('start'))
+ })
+
+ it('does nothing when the grid is already there', async () => {
+ const fake = fakeGrid({ version: VERSION_OK, sync: {}, ls: { stdout: rows('someone-7f3a91c4') } })
+ expect(await ensure()).toEqual({ status: 'existed', message: '' })
+ expect(fake.calls().some((c) => c.includes('start'))).toBe(false)
+ })
+
+ it('syncs BEFORE looking, so a grid another machine made is seen', async () => {
+ const fake = fakeGrid({ version: VERSION_OK, sync: {}, ls: { stdout: rows('someone-7f3a91c4') } })
+ await ensure()
+ const order = fake.calls().map((c) => c.find((a) => a !== '--remote'))
+ expect(order.indexOf('sync')).toBeLessThan(order.indexOf('ls'))
+ })
+
+ it('adopts rather than duplicating when another machine won the create race', async () => {
+ // The control plane rejects a duplicate name, and the refusal is prose — so this is resolved by
+ // looking again, not by reading the error.
+ const fake = fakeGrid({
+ version: VERSION_OK,
+ sync: {},
+ ls: [{ stdout: rows() }, { stdout: rows('someone-7f3a91c4') }],
+ start: { exit: 1, stderr: 'POST …/managed-networks failed (409): name already taken\n' },
+ })
+ expect(await ensure()).toEqual({ status: 'adopted', message: '' })
+ expect(fake.calls().filter((c) => c.includes('sync')).length).toBe(2)
+ })
+
+ it('reports grid’s own words when the create really failed', async () => {
+ fakeGrid({
+ version: VERSION_OK,
+ sync: {},
+ ls: { stdout: rows() },
+ start: { exit: 1, stderr: 'the control plane is unreachable\n' },
+ })
+ const result = await ensure()
+ expect(result.status).toBe('failed')
+ expect(result.message).toContain('control plane is unreachable')
+ })
+
+ it('skips, without touching the grid, when the binary is older than the floor', async () => {
+ const fake = fakeGrid({ version: { stdout: 'grid 0.3.34\n' } })
+ const result = await ensure()
+ expect(result.status).toBe('skipped')
+ expect(result.message).toContain('0.3.36')
+ expect(fake.calls().some((c) => c.includes('start'))).toBe(false)
+ })
+
+ it('skips when there is no grid at all, and never throws', async () => {
+ process.env.HARNESS_GRID_BIN = join(tmpdir(), 'definitely-not-a-grid-binary')
+ const result = await ensure()
+ expect(result.status).toBe('skipped')
+ })
+
+ it('refuses an empty name rather than creating a grid called nothing', async () => {
+ fakeGrid({ version: VERSION_OK })
+ expect((await ensure(' ')).status).toBe('skipped')
+ })
+})
diff --git a/cli/src/lib/gridEnsure.ts b/cli/src/lib/gridEnsure.ts
new file mode 100644
index 000000000..1f7511d00
--- /dev/null
+++ b/cli/src/lib/gridEnsure.ts
@@ -0,0 +1,117 @@
+/**
+ * The user's private harness grid exists.
+ *
+ * Runs once, right after a successful sign-in hand-off — creating a grid is not something a daemon
+ * should do on a timer. Everything here is best-effort by construction: a machine with no `grid`, an
+ * old one, or a control plane having a bad minute must leave the harness sign-in itself untouched.
+ *
+ * **The name is not ours to invent.** It is minted and remembered by the backend, which is the only
+ * party holding both inputs (the account's email and id) and the only one that can referee two
+ * machines signing in at once. This module is handed the answer. See the plan's Change 7.
+ *
+ * **Every call is `--remote`.** Local mode is out of scope for the harness, and a one-shot override
+ * is cheaper than depending on the mode a user may have switched for their own reasons —
+ * `resolve_override` in autonomous-grid strips it from any position.
+ */
+import { gridExec, gridJson, gridVersion, meetsVersionFloor, GRID_VERSION_FLOOR } from './gridExec.js'
+
+/** What `grid ls --json` answers: one row per grid the sign-in fetched. */
+interface GridRow {
+ grid?: unknown
+ type?: unknown
+ id?: unknown
+}
+
+/**
+ * The network type for a grid that is one person's own machines.
+ *
+ * ⚠️ The name reads backwards and the mistake is expensive. "public" here means *not keyed to an
+ * email domain*, NOT *open to anyone*: a `permissioned-public` grid admits exactly the accounts on
+ * its allowlist roster, and `create_network` writes the creator one. The other choice,
+ * `permissioned-providers`, is the OPEN-consumer type — it is the only type the denylist governs and
+ * the only one billing switches on for. Picking it here would put a stranger's requests on the
+ * user's own GPU and start charging for it.
+ */
+export const HARNESS_GRID_TYPE = 'permissioned-public'
+
+export type EnsureStatus =
+ /** The grid was not there and this machine created it. */
+ | 'created'
+ /** It was already there — the ordinary answer on every machine after the first. */
+ | 'existed'
+ /** A create failed, but the grid turned out to exist anyway: another machine won the race. */
+ | 'adopted'
+ /** Nothing was attempted. The harness sign-in is unaffected; `message` says why. */
+ | 'skipped'
+ /** Something was attempted and did not work. `message` carries grid's own words. */
+ | 'failed'
+
+export interface EnsureResult {
+ status: EnsureStatus
+ /** Empty when there is nothing a person would need to read. Never contains a credential. */
+ message: string
+}
+
+const REMOTE = '--remote'
+
+function rowNames(rows: GridRow[] | null): string[] {
+ if (!Array.isArray(rows)) return []
+ return rows.map((row) => (typeof row.grid === 'string' ? row.grid : '')).filter(Boolean)
+}
+
+/** Does the account hold a grid by this name, as far as the locally stored registry knows? */
+async function gridExists(name: string): Promise<boolean> {
+ const { value } = await gridJson<GridRow[]>([REMOTE, 'ls'])
+ return rowNames(value).includes(name)
+}
+
+/**
+ * Make sure `name` exists as a remote grid, and say what had to happen.
+ *
+ * @param name the backend-minted grid name; nothing here derives or guesses one.
+ */
+export async function ensureHarnessGrid(name: string): Promise<EnsureResult> {
+ if (!name.trim()) return { status: 'skipped', message: 'No grid name was issued for this account.' }
+
+ // Ask the version once, up front. Every failure below would otherwise have to guess whether it was
+ // caused by an old binary, and "update grid" said once is worth more than three different refusals.
+ const version = await gridVersion()
+ if (!meetsVersionFloor(version)) {
+ return {
+ status: 'skipped',
+ message: version
+ ? `This machine's grid is ${version}; ${GRID_VERSION_FLOOR} or newer is needed. Update it and sign in again.`
+ : 'No usable `grid` on this machine, so no harness grid was set up.',
+ }
+ }
+
+ // Pull the account's grids before looking. `grid ls` reads a LOCAL registry and makes no network
+ // call, so without this a machine that has not synced since another one created the grid sees
+ // nothing and tries to create a second. Failure is not fatal — the create path below re-checks.
+ await gridExec([REMOTE, 'sync'])
+
+ if (await gridExists(name)) return { status: 'existed', message: '' }
+
+ const created = await gridExec([REMOTE, 'start', name, '--type', HARNESS_GRID_TYPE])
+ if (created.code === 'OK') {
+ // ⚠️ Sync AGAIN, after the create. A grid that has just been made has no PER-GRID access token
+ // in the local store yet — `grid info --env` answers "has no access token locally. Run `grid
+ // login` to refresh your grids", and so does `grid join`. Measured on a real first-time create.
+ // Without this the grid exists and is selectable while every use of it fails, which reads as a
+ // broken feature rather than a missing refresh.
+ await gridExec([REMOTE, 'sync'])
+ return { status: 'created', message: '' }
+ }
+
+ // A create can fail because another machine created it first — grid names are globally unique and
+ // the control plane rejects a duplicate. Rather than parse that refusal (grid's own `--json` error
+ // envelope documents `code` as null for exactly this class, and its message is prose), ask the
+ // question again: sync, look, and believe what is there. Correct however the refusal is encoded.
+ await gridExec([REMOTE, 'sync'])
+ if (await gridExists(name)) return { status: 'adopted', message: '' }
+
+ return {
+ status: 'failed',
+ message: (created.stderr.trim() || created.message).slice(0, 500),
+ }
+}
diff --git a/cli/src/lib/gridExec.ts b/cli/src/lib/gridExec.ts
new file mode 100644
index 000000000..0263f31c7
--- /dev/null
+++ b/cli/src/lib/gridExec.ts
@@ -0,0 +1,214 @@
+/**
+ * The one place this daemon runs the `grid` CLI.
+ *
+ * `gridHandoff.ts` and `gridLogout.ts` each grew their own spawn because there were two calls. The
+ * harness-grid flow adds several more — ensure, models, endpoint — and a per-caller spawn is how a
+ * PATH check, a capture bound and an exit-code meaning end up disagreeing three ways. So: one
+ * resolver, one classification, one bounded capture.
+ *
+ * **Which binary.** `HARNESS_GRID_BIN` (an explicit override, for a developer testing an unreleased
+ * grid) → the runtime this daemon manages → `grid` on PATH. The managed runtime is PINNED, and it
+ * deliberately outranks PATH: the pin is what makes [GRID_VERSION_FLOOR] a property we ship and test
+ * rather than one we discover on a user's machine. PATH is the fallback for a checkout with no
+ * runtime installed, not the preferred answer.
+ *
+ * ⚠️ The managed binary and a user's own `grid` share one `~/.grid` — credentials, device id, the
+ * network registry. They are two readers of one state directory, so a grid state-format change is a
+ * coordination point: the pin has to move before or with it.
+ */
+import { spawn } from 'node:child_process'
+import { accessSync, constants, readFileSync } from 'node:fs'
+import { join, sep } from 'node:path'
+import { env } from '../config/env.js'
+import { binaryOnPath } from './binaryOnPath.js'
+
+/** The command, as it is named on PATH. Shared with `gridHandoff.ts`, which owns the sign-in seam. */
+export const GRID_BINARY = 'grid'
+
+/**
+ * The oldest `grid` this daemon can drive.
+ *
+ * `grid login --harness` — the whole of the one-sign-in flow — landed in 0.3.36 (autonomous-grid
+ * `3286163`, 2026-09-04). An older binary answers argparse's exit 2, which the hand-off already
+ * reads as OUTDATED; this constant is what lets every OTHER call say so in one sentence instead of
+ * each one rediscovering it.
+ */
+export const GRID_VERSION_FLOOR = '0.3.36'
+
+/** A bound on what one child can put into a capture. The passthrough, where there is one, is never
+ * bounded — only what this process holds in memory. Mirrors `gridHandoff.ts`. */
+const MAX_CAPTURED_CHARS = 64 * 1024
+
+/** A `grid` call that has not answered in this long is not going to. The daemon runs these on its
+ * sign-in path, where a hung child would otherwise hang the command that spawned it. */
+const DEFAULT_TIMEOUT_MS = 30_000
+
+export type GridCode = 'OK' | 'GRID_CLI_MISSING' | 'GRID_CLI_OUTDATED' | 'GRID_FAILED'
+
+export interface GridResult {
+ code: GridCode
+ /** The child's own exit code; 1 when there was no child, or it died on a signal. */
+ exitCode: number
+ stdout: string
+ stderr: string
+ /** This module's classification, in a sentence. Empty on success. Never contains a credential. */
+ message: string
+}
+
+/** argparse exits 2 on an unknown flag, BEFORE any handler runs — so a `grid` predating a flag we
+ * pass fails at once and unmistakably. Same constant, same reason, as `gridHandoff.ts`. */
+const ARGPARSE_USAGE_EXIT = 2
+
+const MISSING_MESSAGE =
+ 'No `grid` on PATH and no managed grid runtime, so there is nothing to run. Reinstall harness, or '
+ + 'install the grid CLI yourself.'
+
+const OUTDATED_MESSAGE =
+ `This machine's \`grid\` is older than ${GRID_VERSION_FLOOR}, which is the oldest the harness can `
+ + 'drive. Update it, then try again.'
+
+function capped(sofar: string, chunk: Buffer): string {
+ return sofar.length >= MAX_CAPTURED_CHARS ? sofar : (sofar + chunk.toString()).slice(0, MAX_CAPTURED_CHARS)
+}
+
+/**
+ * The `grid` this daemon should run.
+ *
+ * Containment-checked exactly like `nodeRuntime.managedNodePath`: a pointer file is only trusted
+ * when it names something INSIDE the runtime directory we own, so a corrupted or hostile pointer
+ * cannot turn this into "run any executable on the box".
+ */
+export function gridBinaryPath(processEnv: NodeJS.ProcessEnv = process.env): string {
+ const override = processEnv.HARNESS_GRID_BIN?.trim()
+ if (override) return override
+ try {
+ const recorded = readFileSync(join(env.ADAPTER_RUNTIME_DIR, 'current-grid'), 'utf-8').trim()
+ if (recorded && recorded.startsWith(env.ADAPTER_RUNTIME_DIR + sep)) {
+ accessSync(recorded, constants.X_OK)
+ return recorded
+ }
+ } catch {
+ // absent, unreadable, or not executable → fall through to PATH
+ }
+ return GRID_BINARY
+}
+
+/** Is there a `grid` to run at all? Asked by reading rather than by spawning, so a missing binary is
+ * a sentence rather than a spawn error every caller has to recognise — and so a present-but-not-
+ * executable one (EACCES, never ENOENT) is caught too. */
+export function gridAvailable(processEnv: NodeJS.ProcessEnv = process.env): boolean {
+ return binaryOnPath(gridBinaryPath(processEnv), processEnv)
+}
+
+export interface GridExecOptions {
+ /** Written to the child's stdin, which is then closed. For the token hand-off and nothing else. */
+ stdin?: string
+ timeoutMs?: number
+ processEnv?: NodeJS.ProcessEnv
+}
+
+/**
+ * Run `grid` with `args` and classify what happened. Never throws.
+ *
+ * Both streams are captured, never inherited: every caller here is the daemon or a command that
+ * renders its own output, and a child writing straight to the terminal from inside the sign-in path
+ * would interleave with the harness's own lines.
+ */
+export async function gridExec(args: readonly string[], opts: GridExecOptions = {}): Promise<GridResult> {
+ const processEnv = opts.processEnv ?? process.env
+ const binary = gridBinaryPath(processEnv)
+ if (!binaryOnPath(binary, processEnv)) {
+ return { code: 'GRID_CLI_MISSING', exitCode: 1, stdout: '', stderr: '', message: MISSING_MESSAGE }
+ }
+ return await new Promise<GridResult>((resolve) => {
+ const child = spawn(binary, [...args], { stdio: ['pipe', 'pipe', 'pipe'] })
+ let stdout = ''
+ let stderr = ''
+ let settled = false
+ const settle = (result: GridResult): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ resolve(result)
+ }
+ const timer = setTimeout(() => {
+ try { child.kill('SIGKILL') } catch { /* already gone */ }
+ settle({
+ code: 'GRID_FAILED',
+ exitCode: 1,
+ stdout,
+ stderr,
+ message: `\`grid ${args[0] ?? ''}\` did not answer within ${Math.round((opts.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1000)}s.`,
+ })
+ }, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS)
+
+ child.stdout?.on('data', (chunk: Buffer) => { stdout = capped(stdout, chunk) })
+ child.stderr?.on('data', (chunk: Buffer) => { stderr = capped(stderr, chunk) })
+ child.once('error', (err: NodeJS.ErrnoException) => settle(err.code === 'ENOENT'
+ ? { code: 'GRID_CLI_MISSING', exitCode: 1, stdout, stderr, message: MISSING_MESSAGE }
+ : { code: 'GRID_FAILED', exitCode: 1, stdout, stderr, message: `Could not run \`${binary}\`: ${err.message}` }))
+
+ // stdio[0] is a pipe, so this is never null; refusing loudly rather than optional-chaining past
+ // it, because a child left waiting on a stdin nobody closes hangs with nothing on screen.
+ const { stdin } = child
+ if (!stdin) {
+ try { child.kill() } catch { /* ignore */ }
+ settle({ code: 'GRID_FAILED', exitCode: 1, stdout, stderr, message: `Could not open a pipe to \`${binary}\`.` })
+ return
+ }
+ stdin.on('error', () => { /* EPIPE — a child that exits before reading is its own story */ })
+ stdin.end(opts.stdin ?? '')
+
+ // `close`, not `exit`: the capture must be complete before it is reported on.
+ child.once('close', (status, signal) => {
+ if (status === 0) { settle({ code: 'OK', exitCode: 0, stdout, stderr, message: '' }); return }
+ if (status === ARGPARSE_USAGE_EXIT) {
+ settle({ code: 'GRID_CLI_OUTDATED', exitCode: status, stdout, stderr, message: OUTDATED_MESSAGE })
+ return
+ }
+ const how = status === null ? `was killed by ${signal ?? 'a signal'}` : `exited ${status}`
+ settle({ code: 'GRID_FAILED', exitCode: status ?? 1, stdout, stderr, message: `\`grid ${args[0] ?? ''}\` ${how}.` })
+ })
+ })
+}
+
+/**
+ * Run a `--json` command and parse its document, or null.
+ *
+ * Null covers every way there is no answer — no binary, a refusal, output that is not JSON — because
+ * every caller here does the same thing with all of them: carry on without the grid. The reason is
+ * still available on the `GridResult` for a caller that wants to log it.
+ */
+export async function gridJson<T>(
+ args: readonly string[],
+ opts: GridExecOptions = {},
+): Promise<{ value: T | null; result: GridResult }> {
+ const result = await gridExec([...args, '--json'], opts)
+ if (result.code !== 'OK') return { value: null, result }
+ try {
+ return { value: JSON.parse(result.stdout) as T, result }
+ } catch {
+ return { value: null, result }
+ }
+}
+
+/** `grid version` prints `grid <semver>`; null when it could not be read. */
+export async function gridVersion(opts: GridExecOptions = {}): Promise<string | null> {
+ const result = await gridExec(['version'], opts)
+ if (result.code !== 'OK') return null
+ const match = /(\d+\.\d+\.\d+)/.exec(result.stdout)
+ return match ? match[1] : null
+}
+
+/** Ordinary three-part semver compare, enough for a floor check. A version that cannot be parsed is
+ * treated as NOT meeting the floor: refusing to drive an unknown build is the safe direction. */
+export function meetsVersionFloor(version: string | null, floor: string = GRID_VERSION_FLOOR): boolean {
+ if (!version) return false
+ const parse = (value: string): number[] => value.split('.').map((part) => Number.parseInt(part, 10))
+ const [major = 0, minor = 0, patch = 0] = parse(version)
+ const [flMajor = 0, flMinor = 0, flPatch = 0] = parse(floor)
+ if ([major, minor, patch].some((n) => !Number.isFinite(n))) return false
+ if (major !== flMajor) return major > flMajor
+ if (minor !== flMinor) return minor > flMinor
+ return patch >= flPatch
+}
diff --git a/cli/src/lib/gridModels.ts b/cli/src/lib/gridModels.ts
new file mode 100644
index 000000000..2f53027c3
--- /dev/null
+++ b/cli/src/lib/gridModels.ts
@@ -0,0 +1,142 @@
+/**
+ * What the account's private harness grid can answer right now.
+ *
+ * One `grid models --json <grid>` away, so this module is a shape and a filter rather than a
+ * protocol. It exists because two things have to be decided in one place: which rows are offered to
+ * a person, and what an agent is told to ask for.
+ */
+import { gridExec, gridJson } from './gridExec.js'
+
+/** A row of `grid models --json`. `node` names the machine serving it — on a private grid, one of
+ * the user's own. */
+interface GridModelRow {
+ model?: unknown
+ engine?: unknown
+ node?: unknown
+}
+
+export interface GridModel {
+ /** The id an engine is pointed at, verbatim from the grid. */
+ id: string
+ /** Which machine answers it, or empty when the grid does not say. Display only. */
+ node: string
+}
+
+/**
+ * The grid's router entry, which is deliberately NOT offered.
+ *
+ * `auto` is served by the `grid-router` engine and picks a model per request. It is being
+ * reimplemented once the grid path is end-to-end encrypted, and offering it first would teach a
+ * selection that is about to change meaning. Matched on the ENGINE rather than the name `auto`, so a
+ * renamed router cannot leak back into the picker.
+ */
+const ROUTER_ENGINE = 'grid-router'
+
+/**
+ * Live models on `gridName`, router excluded. An empty list is a real answer — a grid nobody is
+ * serving yet has none — and is not distinguished here from a grid that could not be reached; the
+ * caller shows "no models" either way, and the reason is in the daemon log.
+ */
+export async function listGridModels(gridName: string | null): Promise<GridModel[]> {
+ if (!gridName?.trim()) return []
+ const { value } = await gridJson<GridModelRow[]>(['--remote', 'models', gridName])
+ if (!Array.isArray(value)) return []
+
+ // ⚠️ `grid models` LOWERCASES the model id; the relay does not. Measured on a real engine:
+ // `grid models --json` says `qwen3.6-35b-a3b-ud-q5_k_xl` while the relay serves
+ // `Qwen3.6-35B-A3B-UD-Q5_K_XL`, and posting the lowercased one answers
+ // `{"detail":"No providers available for this model"}`. The id an engine is pointed at has to be
+ // the one the RELAY knows, so the relay's own catalogue is the authority here and `grid models`
+ // is kept only for the node label. Case is unrecoverable from the lowercased string, so this
+ // cannot be fixed by mapping.
+ const served = await relayModelIds(gridName)
+ const nodeFor = new Map<string, string>()
+ for (const row of value) {
+ const id = typeof row.model === 'string' ? row.model.trim() : ''
+ if (id && row.engine !== ROUTER_ENGINE) nodeFor.set(id.toLowerCase(), typeof row.node === 'string' ? row.node : '')
+ }
+
+ // The relay could not be reached (offline, no token yet) → fall back to what `grid models` said.
+ // A list with the wrong case is still better than an empty picker: the engine reports the refusal
+ // plainly, whereas an empty menu looks like the grid has nothing on it.
+ const ids = served.length ? served : [...nodeFor.keys()]
+ const seen = new Set<string>()
+ const models: GridModel[] = []
+ for (const id of ids) {
+ const key = id.toLowerCase()
+ if (!nodeFor.has(key) || seen.has(key)) continue
+ seen.add(key)
+ models.push({ id, node: nodeFor.get(key) ?? '' })
+ }
+ return models
+}
+
+/** Model ids exactly as the grid's relay serves them — the names an engine must send. Empty when the
+ * relay cannot be asked, which the caller treats as "fall back", never as "no models". */
+async function relayModelIds(gridName: string): Promise<string[]> {
+ const info = await gridExec(['--remote', 'info', gridName, '--env'])
+ if (info.code !== 'OK') return []
+ const env = readEnvExports(info.stdout)
+ if (!env.baseUrl || !env.apiKey) return []
+ try {
+ const response = await fetch(`${env.baseUrl.replace(/\/$/, '')}/models`, {
+ headers: { authorization: `Bearer ${env.apiKey}` },
+ signal: AbortSignal.timeout(10_000),
+ })
+ if (!response.ok) return []
+ const body = await response.json() as { data?: Array<{ id?: unknown }> }
+ return (body.data ?? []).map((m) => (typeof m.id === 'string' ? m.id : '')).filter(Boolean)
+ } catch {
+ return []
+ }
+}
+
+
+/** `grid info --env` prints shell exports; these are the two that matter. */
+const ENV_LINE = /^export\s+(OPENAI_BASE_URL|OPENAI_API_KEY)=(.*)$/gm
+
+/**
+ * Everything an engine needs to be pointed at `gridName`, resolved on THIS machine.
+ *
+ * Deliberately not something a client sends. The app names a model; the endpoint and the credential
+ * are read here, from the `grid` CLI that is already signed in, so no grid credential ever crosses
+ * the relay and there is one source of truth for an address the app could not know anyway.
+ *
+ * ⚠️ The returned `apiKey` is a live credential. It goes into the engine's ENVIRONMENT and never into
+ * argv or a log line — `gridLaunch.ts` is what enforces that, and this value must keep travelling
+ * through it rather than around it.
+ */
+export async function resolveGridTarget(
+ gridName: string | null,
+ model: string,
+): Promise<{ networkId: string; networkName: string; baseUrl: string; apiKey: string; model: string } | null> {
+ if (!gridName?.trim() || !model.trim()) return null
+ const info = await gridExec(['--remote', 'info', gridName, '--env'])
+ if (info.code !== 'OK') return null
+ const { baseUrl, apiKey } = readEnvExports(info.stdout)
+ if (!baseUrl || !apiKey) return null
+ // The grid's own id, for the record the launch is written into. Falls back to the name, which is
+ // unique on this account and is all the launch actually needs to be re-derivable.
+ const { value: rows } = await gridJson<Array<{ grid?: unknown; id?: unknown }>>(['--remote', 'ls'])
+ const row = Array.isArray(rows) ? rows.find((r) => r.grid === gridName) : undefined
+ return {
+ networkId: typeof row?.id === 'string' ? row.id : gridName,
+ networkName: gridName,
+ baseUrl,
+ apiKey,
+ model,
+ }
+}
+
+/** The two exports out of `grid info --env`. ⚠️ Values are SHELL-QUOTED — a base URL read with the
+ * quotes still on produces a request to a host that does not exist. */
+function readEnvExports(stdout: string): { baseUrl: string; apiKey: string } {
+ let baseUrl = ''
+ let apiKey = ''
+ for (const match of stdout.matchAll(ENV_LINE)) {
+ const value = match[2]!.trim().replace(/^["']|["']$/g, '')
+ if (match[1] === 'OPENAI_BASE_URL') baseUrl = value
+ else apiKey = value
+ }
+ return { baseUrl, apiKey }
+}