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
A failed grid create is retried, and the Free plan's refusal is shown instead (#1316)
Kelvin12b8b94a2fa7
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 613932d31..ba1620f0a 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -405,7 +405,7 @@ async function ensureAccountGrid(note: (line: string) => void): Promise<{ status}if (!gridName) return { status: 'skipped', name: null }const ensured = await ensureHarnessGrid(gridName)- if (ensured.status === 'failed' || ensured.status === 'skipped') note(ensured.message)+ if (ensured.status === 'failed' || ensured.status === 'skipped' || ensured.status === 'refused') note(ensured.message)else if (ensured.status === 'created') note(`Created your private grid '${gridName}'.`)return { status: ensured.status, name: gridName }}diff --git a/cli/src/lib/gridAttach.spec.ts b/cli/src/lib/gridAttach.spec.tsindex e4e4af21b..1929746ad 100644--- a/cli/src/lib/gridAttach.spec.ts+++ b/cli/src/lib/gridAttach.spec.ts@@ -287,6 +287,15 @@ describe('createGridAccess — grid set up when a feature asks', () => {expect(attempt.mock.calls[1]).toEqual([{ ownGrid: true, signedInThisRun: true }])})+ it('an own grid the Free plan refused is asked for again next time', async () => {+ // The plan can change between two asks (an upgrade, a deleted grid aging out), so a refusal is not+ // remembered any more than a failure is.+ const { attempt, grid } = access([result('signed-in', 'refused'), result('signed-in', 'created')])+ expect((await grid.ensure({ ownGrid: true })).ownGrid).toBe('refused')+ expect((await grid.ensure({ ownGrid: true })).ownGrid).toBe('created')+ expect(attempt).toHaveBeenCalledTimes(2)+ })+it('forgets everything once grid holds no sign-in — a `grid logout` run by hand', async () => {let signedIn = trueconst { attempt, grid } = access([result('signed-in', 'created'), result('signed-in', 'existed')], () => signedIn)diff --git a/cli/src/lib/gridEnsure.spec.ts b/cli/src/lib/gridEnsure.spec.tsindex 30e6535b3..145fcfb69 100644--- a/cli/src/lib/gridEnsure.spec.ts+++ b/cli/src/lib/gridEnsure.spec.ts@@ -26,11 +26,22 @@ 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}` })))+/** Every wait a retry asked for, in order — the retries never really sleep in a test. */+let slept: number[] = []+async function ensure(name = 'someone-7f3a91c4') {const { ensureHarnessGrid } = await import('./gridEnsure.js')- return ensureHarnessGrid(name)+ slept = []+ return ensureHarnessGrid(name, { sleep: async (ms) => { slept.push(ms) } })}+/** What the public CLI prints for a control-plane refusal — `remote/control_plane._raise`, whose format+ * is a contract there (`cli/auth._SESSION_EXPIRED_RE` anchors on it) — around grid-apis' 402 body. */+const QUOTA_MESSAGE = 'Free plan allows one network, and a network deleted in the last 30 days still counts. ' ++ 'You can create a new one from 2026-10-31 14:13 UTC, or upgrade to create one now'+const QUOTA_REFUSAL = 'POST https://api-grid.autonomous.ai/v1/grid/managed-networks failed (402): ' ++ JSON.stringify({ detail: { error_code: 'free_network_limit', message: QUOTA_MESSAGE } }) + '\n'+describe('ensureHarnessGrid', () => {it('creates the grid when the account has none, as a private permissioned-public one', async () => {const fake = fakeGrid({@@ -80,6 +91,7 @@ describe('ensureHarnessGrid', () => {})expect(await ensure()).toEqual({ status: 'adopted', message: '' })expect(fake.calls().filter((c) => c.includes('sync')).length).toBe(2)+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(1)})it('reports grid’s own words when the create really failed', async () => {@@ -94,6 +106,125 @@ describe('ensureHarnessGrid', () => {expect(result.message).toContain('control plane is unreachable')})+ it('looks once more after the last refusal, and uses a grid that is there', async () => {+ const fake = fakeGrid({+ version: VERSION_OK,+ sync: {},+ // Before the create, then before each retry; there at the look after the third refusal.+ ls: [{ stdout: rows() }, { stdout: rows() }, { stdout: rows() }, { stdout: rows('someone-7f3a91c4') }],+ start: { exit: 1, stderr: 'POST …/managed-networks failed (503): {"detail":"The server is low on memory right now"}\n' },+ })+ expect(await ensure()).toEqual({ status: 'adopted', message: '' })+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(3)+ })++ it('retries a failed create with backoff before saying it failed', async () => {+ // A create the control plane refused for a reason that can pass (the server low on memory, a restart)+ // is asked again, waiting longer each time — no longer reported failed at the first refusal.+ const fake = fakeGrid({+ version: VERSION_OK,+ sync: {},+ ls: { stdout: rows() },+ start: { exit: 1, stderr: 'POST …/managed-networks failed (503): {"detail":"The server is low on memory right now"}\n' },+ })+ const result = await ensure()+ expect(result.status).toBe('failed')+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(3)+ expect(slept).toEqual([2_000, 5_000])+ })++ it('creates the grid when a retry succeeds', async () => {+ const fake = fakeGrid({+ version: VERSION_OK,+ sync: {},+ ls: { stdout: rows() },+ start: [{ exit: 1, stderr: 'POST …/managed-networks failed (503): {"detail":"The server is low on memory right now"}\n' }, {}],+ })+ expect(await ensure()).toEqual({ status: 'created', message: '' })+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(2)+ expect(slept).toEqual([2_000])+ })++ it('shows the Free plan’s refusal instead of retrying it', async () => {+ // A 402 `free_network_limit` is the owner's plan, not a bad minute: asking again cannot succeed, so+ // it is never retried, and the person reads the control plane's own sentence — which says when a new+ // grid becomes possible — rather than the CLI's raw request line around it.+ const fake = fakeGrid({ version: VERSION_OK, sync: {}, ls: { stdout: rows() }, start: { exit: 1, stderr: QUOTA_REFUSAL } })+ expect(await ensure()).toEqual({ status: 'refused', message: QUOTA_MESSAGE })+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(1)+ expect(slept).toEqual([])+ // …and only after looking again: the account had no such grid, so the quota was not spent on it.+ expect(fake.calls().filter((c) => c.includes('ls')).length).toBe(2)+ })++ it('uses the grid, not the Free plan’s refusal, when the grid turns out to be there', async () => {+ // A 402 while the account holds a grid of this name means the quota counted that very grid: made by+ // another machine, or by a create that finished on the server after its client gave up.+ const fake = fakeGrid({+ version: VERSION_OK,+ sync: {},+ ls: [{ stdout: rows() }, { stdout: rows('someone-7f3a91c4') }],+ start: { exit: 1, stderr: QUOTA_REFUSAL },+ })+ expect(await ensure()).toEqual({ status: 'adopted', message: '' })+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(1)+ expect(slept).toEqual([])+ })++ it('looks again right before asking again, and uses a grid that appeared in the wait', async () => {+ const fake = fakeGrid({+ version: VERSION_OK,+ sync: {},+ ls: [{ stdout: rows() }, { stdout: rows('someone-7f3a91c4') }],+ start: { exit: 1, stderr: 'POST …/managed-networks failed (503): {"detail":"The server is low on memory right now"}\n' },+ })+ expect(await ensure()).toEqual({ status: 'adopted', message: '' })+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(1)+ expect(slept).toEqual([2_000])+ })++ // A create can outlast `grid start`'s own bound and still succeed: the control plane keeps going after+ // its client gives up, and registers the grid only at the END of the create, once the grid's server is+ // up. What the CLI prints then is no answer at all — no `failed (<status>)`.+ const NO_ANSWER = 'Cannot reach the control plane (POST https://api-grid.autonomous.ai/v1/grid/managed-networks): timed out\n'++ it('uses the grid a slow create made after grid gave up on it, and never creates it twice', async () => {+ const fake = fakeGrid({+ version: VERSION_OK,+ sync: {},+ // Not there before the create, nor at the first look after it; there once the server has finished.+ ls: [{ stdout: rows() }, { stdout: rows() }, { stdout: rows('someone-7f3a91c4') }],+ start: { exit: 1, stderr: NO_ANSWER },+ })+ expect(await ensure()).toEqual({ status: 'adopted', message: '' })+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(1)+ expect(slept).toEqual([2_000])+ })++ it('never asks again after a create that got no answer, even when no grid appears', async () => {+ // It may still be running on the server, and a second create would make a second grid of the same+ // name: the control plane does not serialize two creates. Looking is all that is safe.+ const fake = fakeGrid({ version: VERSION_OK, sync: {}, ls: { stdout: rows() }, start: { exit: 1, stderr: NO_ANSWER } })+ const result = await ensure()+ expect(result.status).toBe('failed')+ expect(result.message).toContain('timed out')+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(1)+ // Before the create, then once at once and once after each wait.+ expect(fake.calls().filter((c) => c.includes('ls')).length).toBe(4)+ expect(slept).toEqual([2_000, 5_000])+ })++ it('takes a gateway timeout for no answer: a proxy stopped waiting, the create may still be running', async () => {+ const fake = fakeGrid({+ version: VERSION_OK,+ sync: {},+ ls: { stdout: rows() },+ start: { exit: 1, stderr: 'POST …/managed-networks failed (504): <html>504 Gateway Time-out</html>\n' },+ })+ expect((await ensure()).status).toBe('failed')+ expect(fake.calls().filter((c) => c.includes('start')).length).toBe(1)+ })+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()@@ -113,3 +244,36 @@ describe('ensureHarnessGrid', () => {expect((await ensure(' ')).status).toBe('skipped')})})++describe('quotaRefusal', () => {+ it('reads the control plane’s sentence out of the CLI’s refusal line', async () => {+ const { quotaRefusal } = await import('./gridEnsure.js')+ expect(quotaRefusal(QUOTA_REFUSAL)).toBe(QUOTA_MESSAGE)+ expect(quotaRefusal(`some warning first\n${QUOTA_REFUSAL}`)).toBe(QUOTA_MESSAGE)+ })++ it('reads the sentence for an owner whose live grids fill the plan', async () => {+ // grid-apis `_free_limit_message(None)`: no deleted grid is counting, so the sentence names no date.+ const { quotaRefusal } = await import('./gridEnsure.js')+ const live = 'Free plan allows one network; upgrade to create more'+ const line = 'POST https://api-grid.autonomous.ai/v1/grid/managed-networks failed (402): ' ++ JSON.stringify({ detail: { error_code: 'free_network_limit', message: live } })+ expect(quotaRefusal(line)).toBe(live)+ })++ it('is not fooled by another refusal', async () => {+ const { quotaRefusal } = await import('./gridEnsure.js')+ expect(quotaRefusal('POST …/managed-networks failed (402): {"detail":"Insufficient balance"}')).toBeNull()+ expect(quotaRefusal('POST …/managed-networks failed (409): {"detail":"You already have a network with this name"}')).toBeNull()+ expect(quotaRefusal('POST …/managed-networks failed (503): {"detail":{"error_code":"free_network_limit"}}')).toBeNull()+ expect(quotaRefusal('the control plane is unreachable')).toBeNull()+ })++ it('still knows the refusal when the CLI cut the body short', async () => {+ // The CLI keeps the first 400 characters of a body, so a long sentence can arrive as broken JSON.+ // The code is near the front and still decides; the person then gets a sentence of our own.+ const { quotaRefusal } = await import('./gridEnsure.js')+ const cut = QUOTA_REFUSAL.slice(0, QUOTA_REFUSAL.indexOf('You can'))+ expect(quotaRefusal(cut)).toMatch(/Free plan/)+ })+})diff --git a/cli/src/lib/gridEnsure.ts b/cli/src/lib/gridEnsure.tsindex 1f7511d00..0a5db7c22 100644--- a/cli/src/lib/gridEnsure.ts+++ b/cli/src/lib/gridEnsure.ts@@ -39,11 +39,16 @@ export type EnsureStatus =| '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. */+ /** A create failed, but the grid turned out to exist anyway: another machine won the race, or this+ * create finished on the server after `grid` gave up waiting for it. */| '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. */+ /** The control plane refused the create for a reason only the person can change — the Free plan's+ * grid limit. `message` is its own sentence (it says when a new grid becomes possible), and nothing+ * retries it. */+ | 'refused'+ /** Something was attempted and did not work, after the retries. `message` carries grid's own words. */| 'failed'export interface EnsureResult {@@ -54,6 +59,69 @@ export interface EnsureResult {const REMOTE = '--remote'+/**+ * The control plane's refusal code for an owner at their Free plan's grid limit — grid-apis+ * `handler.create_managed_network`'s 402, `{"detail": {"error_code": …, "message": …}}`. A wire value,+ * matched as written; the register row says what a rename costs (a refusal retried, then shown raw).+ */+export const FREE_NETWORK_LIMIT_CODE = 'free_network_limit'++/** How long to wait before each retry of a failed create: one per retry, so two retries. A create the+ * control plane refused for a reason that can pass — a server low on memory, a restart — is asked again+ * rather than reported at the first refusal. A create it did not answer is never asked again: its waits+ * only look ([createAnswered]). Short, because a person is waiting on the answer. */+export const CREATE_RETRY_DELAYS_MS: readonly number[] = [2_000, 5_000]++/** The public CLI's line for a control plane that answered with a refusal: `failed (<status>): <body>`+ * (`remote/control_plane._raise`, the same contract [REFUSED_402] reads). */+const ANSWERED = /failed \((\d{3})\): /++/** A proxy in front of the control plane that stopped waiting answers these (nginx 504, Cloudflare 524).+ * They are not the control plane's answer, so the create behind them may still be running. */+const GATEWAY_TIMEOUTS: ReadonlySet<number> = new Set([504, 524])++/**+ * Whether the control plane answered the create whose failed `grid start` printed `output`. Its create+ * route is synchronous and repairs a failed create before it answers, so an answer means that attempt is+ * over, and asking again cannot make a second grid. No answer — `grid`'s own timeout or "cannot reach",+ * this module's bound on `grid`, a gateway timeout, a create that succeeded but could not be saved here —+ * means it may still be running on the server, or done.+ */+function createAnswered(output: string): boolean {+ const status = ANSWERED.exec(output)?.[1]+ return status !== undefined && !GATEWAY_TIMEOUTS.has(Number(status))+}++/** The public CLI's line for a control plane that answered 402: `remote/control_plane._raise`, a+ * contract in that repo (`cli/auth._SESSION_EXPIRED_RE` anchors on the same rendering). */+const REFUSED_402 = 'failed (402): '++/** The code, found in a body the CLI cut short (it keeps 400 characters of one) — so JSON cannot parse it. */+const QUOTA_CODE_IN_TEXT = new RegExp(`"error_code"\\s*:\\s*"${FREE_NETWORK_LIMIT_CODE}"`)++/** Said when the code is there but the CLI cut the sentence short (it keeps 400 characters of a body). */+const QUOTA_FALLBACK = 'Your Free plan’s grid limit is reached, so no new grid could be created. Upgrade, or try again later.'++/**+ * The control plane's own sentence when `output` — what a failed `grid start` printed — is the Free+ * plan's grid-limit refusal; null for anything else. Only the code decides: a 402 for another reason, or+ * the same code on another status, is not this.+ */+export function quotaRefusal(output: string): string | null {+ const line = output.split('\n').find((l) => l.includes(REFUSED_402))+ if (!line) return null+ const body = line.slice(line.indexOf(REFUSED_402) + REFUSED_402.length).trim()+ try {+ const detail = (JSON.parse(body) as { detail?: { error_code?: unknown; message?: unknown } }).detail+ if (detail?.error_code !== FREE_NETWORK_LIMIT_CODE) return null+ return typeof detail.message === 'string' && detail.message.trim() ? detail.message : QUOTA_FALLBACK+ } catch {+ return QUOTA_CODE_IN_TEXT.test(body) ? QUOTA_FALLBACK : null+ }+}++const realSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))+function rowNames(rows: GridRow[] | null): string[] {if (!Array.isArray(rows)) return []return rows.map((row) => (typeof row.grid === 'string' ? row.grid : '')).filter(Boolean)@@ -65,12 +133,67 @@ async function gridExists(name: string): Promise<boolean> {return rowNames(value).includes(name)}+/** Pull the account's grids, then look — the same two calls the first look makes, since `grid ls` alone+ * reads a local registry that only a sync brings up to date. */+async function syncedExists(name: string): Promise<boolean> {+ await gridExec([REMOTE, 'sync'])+ return gridExists(name)+}++const ADOPTED: EnsureResult = { status: 'adopted', message: '' }++/**+ * What a failed create came to, or null when it is safe and worth asking again — after the wait, and only+ * once a last look has not found the grid.+ *+ * ⚠️ Every outcome LOOKS before it is believed: a create can fail and still have made the grid. Another+ * machine of this account may have won the race (the control plane refuses the duplicate name, in prose —+ * and `grid`'s own `--json` envelope documents `code` as null for that class), or this create may have+ * outlasted `grid` and finished on the server. So rather than parse the refusal: sync, look, and believe+ * what is there.+ */+async function afterFailedCreate(+ name: string,+ said: string,+ waits: readonly number[],+ sleep: (ms: number) => Promise<void>,+): Promise<EnsureResult | null> {+ const failed: EnsureResult = { status: 'failed', message: said.slice(0, 500) }++ // The Free plan's limit is the one refusal read for what it says: asking again cannot succeed (it is the+ // owner's plan, or a grid they deleted still counting), so it is shown, never retried — unless the grid+ // is there after all, which is then the very grid the quota counted.+ const refused = quotaRefusal(said)+ if (refused) return (await syncedExists(name)) ? ADOPTED : { status: 'refused', message: refused }++ // ⚠️ A create the control plane did not answer may still be running there, and it registers the grid+ // only at its very end, once the grid's server is up. Asked again, it could make a SECOND grid of the+ // same name (nothing on the control plane serializes two creates), so these waits only look.+ if (!createAnswered(said)) {+ if (await syncedExists(name)) return ADOPTED+ for (const wait of waits) {+ await sleep(wait)+ if (await syncedExists(name)) return ADOPTED+ }+ return failed+ }++ if (!waits.length) return (await syncedExists(name)) ? ADOPTED : failed+ await sleep(waits[0])+ // Right before asking again: a grid made in the wait is used, never created twice.+ return (await syncedExists(name)) ? ADOPTED : null+}+/*** 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> {+export async function ensureHarnessGrid(+ name: string,+ opts: { sleep?: (ms: number) => Promise<void> } = {},+): Promise<EnsureResult> {+ const sleep = opts.sleep ?? realSleepif (!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@@ -92,26 +215,19 @@ export async function ensureHarnessGrid(name: string): Promise<EnsureResult> {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),+ for (let retry = 0; ; retry++) {+ 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: '' }+ }+ const said = created.stderr.trim() || created.message+ const outcome = await afterFailedCreate(name, said, CREATE_RETRY_DELAYS_MS.slice(retry), sleep)+ if (outcome) return outcome}}diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.tsindex 860adffad..a61d23d94 100644--- a/cli/src/services/models.spec.ts+++ b/cli/src/services/models.spec.ts@@ -639,6 +639,15 @@ describe('the models service', () => {access.ensure.mockReset()})+ it('an account grid the Free plan refused fails a Use with the control plane’s own sentence', async () => {+ const sentence = 'Free plan allows one network; upgrade to create more'+ access.ensure.mockResolvedValue({ status: 'signed-in', name: 'kelvin-1a2b3c4d', detail: sentence, ownGrid: 'refused' })+ const { ask } = setup([], named)+ expect(await ask('grid_fleet_model_start', { modelId: 'org/Model-GGUF' })).toEqual({ error: sentence })+ expect(local.act).not.toHaveBeenCalled()+ access.ensure.mockReset()+ })+it('says why in its own words when grid gives none, and takes a grid already there or adopted as ready', async () => {const { ask } = setup([], named)access.ensure.mockResolvedValueOnce({ status: 'no-cli', name: null, detail: '' })