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.

The grid reader reads the generated grid-protocol contract (0.1.1) instead of hand-copied names (#1315)

Kelvin333c0e58bc60
diff --git a/cli/src/lib/__fixtures__/protocol/discover--root--awake-starter-engine.json b/cli/src/lib/__fixtures__/protocol/discover--root--awake-starter-engine.json
new file mode 100644
index 000000000..856ef808d
--- /dev/null
+++ b/cli/src/lib/__fixtures__/protocol/discover--root--awake-starter-engine.json
@@ -0,0 +1,118 @@
+{
+ "schema": "discover",
+ "definition": null,
+ "request": "GET /nodes/discover",
+ "status": 200,
+ "source": "the DEV VM, through grid-proxy (grid-apis feat/grid-platform-03-proxy-env @ 12b6bae, grid-src fix/grid-platform-03-loopback-bind @ 4aa0b01), no credential",
+ "recorded_at": "2026-09-30T19:00Z",
+ "sanitized": true,
+ "body": {
+ "providers": [
+ {
+ "node_id": "grid-00000000000000000000000000000001",
+ "models": [
+ "provider:grid-00000000000000000000000000000001:model0000001",
+ "provider:grid-00000000000000000000000000000001:model0000002"
+ ],
+ "pricing": {},
+ "capabilities": {
+ "models": {
+ "provider:grid-00000000000000000000000000000001:model0000001": {
+ "context_window": 1048576,
+ "endpoints": [
+ "chat/completions",
+ "responses"
+ ],
+ "features": {
+ "audio": false,
+ "json_object": true,
+ "json_schema": true,
+ "logprobs": false,
+ "output_cap": true,
+ "parallel_tool_calls": true,
+ "tools": true,
+ "top_logprobs": false,
+ "vision": false
+ },
+ "input_modalities": [
+ "text"
+ ],
+ "limits": {
+ "max_context_tokens": 1048576,
+ "max_image_bytes": 4000000,
+ "max_images": 8,
+ "max_output_tokens": 64000,
+ "max_top_logprobs": 0
+ },
+ "max_output_tokens": 64000,
+ "output_modalities": [
+ "text"
+ ],
+ "provider_group_id": "provider-group:model0000001",
+ "provider_supplied": true,
+ "public_model_id": "provider:grid-00000000000000000000000000000001:model0000001",
+ "raw_model_id": "deepseek/deepseek-v4-flash-0731"
+ },
+ "provider:grid-00000000000000000000000000000001:model0000002": {
+ "context_window": 1000000,
+ "endpoints": [
+ "chat/completions",
+ "responses"
+ ],
+ "features": {
+ "audio": false,
+ "json_object": true,
+ "json_schema": true,
+ "logprobs": false,
+ "output_cap": true,
+ "parallel_tool_calls": true,
+ "tools": true,
+ "top_logprobs": false,
+ "vision": true
+ },
+ "input_modalities": [
+ "text",
+ "image"
+ ],
+ "limits": {
+ "max_context_tokens": 1000000,
+ "max_image_bytes": 4000000,
+ "max_images": 8,
+ "max_output_tokens": 64000,
+ "max_top_logprobs": 0
+ },
+ "max_output_tokens": 64000,
+ "output_modalities": [
+ "text"
+ ],
+ "provider_group_id": "provider-group:model0000002",
+ "provider_supplied": true,
+ "public_model_id": "provider:grid-00000000000000000000000000000001:model0000002",
+ "raw_model_id": "qwen/qwen3.8-27b"
+ }
+ },
+ "schema_version": 1
+ },
+ "load": {
+ "active_tasks": 0,
+ "platform": "linux",
+ "disk_total_gb": 115.2,
+ "disk_used_gb": 28.7,
+ "tok_s": 229.9
+ },
+ "max_concurrency": 4,
+ "endpoint_url": null,
+ "last_heartbeat": "2026-09-30T18:55:21.845867Z",
+ "first_seen_at": "2026-09-24T01:45:06.537045Z",
+ "verified_at": null,
+ "meta": {
+ "name": "node-a",
+ "name_chosen": true,
+ "engine": "starter",
+ "device": "example-device",
+ "device_class": "server"
+ }
+ }
+ ]
+ }
+}
diff --git a/cli/src/lib/__fixtures__/protocol/overview--root--awake-starter-engine.json b/cli/src/lib/__fixtures__/protocol/overview--root--awake-starter-engine.json
new file mode 100644
index 000000000..737861652
--- /dev/null
+++ b/cli/src/lib/__fixtures__/protocol/overview--root--awake-starter-engine.json
@@ -0,0 +1,115 @@
+{
+ "schema": "overview",
+ "definition": null,
+ "request": "GET /relay/v1/grid/overview",
+ "status": 200,
+ "source": "the DEV VM, through grid-proxy (grid-apis feat/grid-platform-03-proxy-env @ 12b6bae, grid-src fix/grid-platform-03-loopback-bind @ 4aa0b01), no credential",
+ "recorded_at": "2026-09-30T19:00Z",
+ "sanitized": true,
+ "body": {
+ "grid": {
+ "state": "running"
+ },
+ "router_enabled": false,
+ "advertises_chat_completions": true,
+ "advertises_responses": true,
+ "advertises_messages": true,
+ "stats": {
+ "models": 2,
+ "nodes": 1,
+ "concurrent_capacity": 4,
+ "uptime_pct": 99.9
+ },
+ "answered": {
+ "window_seconds": 86400,
+ "tokens_in": 0,
+ "tokens_cached": 0,
+ "tokens_out": 0,
+ "requests": 0
+ },
+ "models": [
+ {
+ "id": "deepseek/deepseek-v4-flash-0731",
+ "name": "deepseek/deepseek-v4-flash-0731",
+ "maker": null,
+ "modality": "chat",
+ "context_length": 1048576,
+ "vision": false,
+ "pricing": {
+ "unit": "token",
+ "input_per_1m": 0.0,
+ "output_per_1m": 0.0
+ },
+ "status": "available"
+ },
+ {
+ "id": "qwen/qwen3.8-27b",
+ "name": "qwen/qwen3.8-27b",
+ "maker": null,
+ "modality": "chat",
+ "context_length": 1000000,
+ "vision": true,
+ "pricing": {
+ "unit": "token",
+ "input_per_1m": 0.0,
+ "output_per_1m": 0.0
+ },
+ "status": "available"
+ }
+ ],
+ "nodes": [
+ {
+ "name": "node-a",
+ "provider_email": "[email protected]",
+ "device": "example-device",
+ "chip": null,
+ "memory_gb": null,
+ "vram_total_mb": null,
+ "vram_gb": null,
+ "vram_used_mb": null,
+ "gpu_util_pct": null,
+ "gpu_temp_c": null,
+ "gpu_power_w": null,
+ "gpu_power_limit_w": null,
+ "disk_total_gb": 115.2,
+ "disk_used_gb": 28.7,
+ "platform": "linux",
+ "device_class": "server",
+ "model": "deepseek/deepseek-v4-flash-0731",
+ "models": [
+ "deepseek/deepseek-v4-flash-0731",
+ "qwen/qwen3.8-27b"
+ ],
+ "model_engines": {},
+ "model_capabilities": {
+ "deepseek/deepseek-v4-flash-0731": {
+ "context_length": 1048576,
+ "vision": false
+ },
+ "qwen/qwen3.8-27b": {
+ "context_length": 1000000,
+ "vision": true
+ }
+ },
+ "responses_models": [
+ "deepseek/deepseek-v4-flash-0731",
+ "qwen/qwen3.8-27b"
+ ],
+ "engine": "starter",
+ "plan_type": null,
+ "codex_rate_limits": null,
+ "throughput_tok_s": 229.9,
+ "max_concurrency": 4,
+ "answered": {
+ "window_seconds": 86400,
+ "tokens_in": 0,
+ "tokens_cached": 0,
+ "tokens_out": 0,
+ "requests": 0,
+ "by_model": []
+ },
+ "online": true
+ }
+ ]
+ }
+}
diff --git a/cli/src/lib/__fixtures__/protocol/refusal--GridAsleep--overview-with-last-known.json b/cli/src/lib/__fixtures__/protocol/refusal--GridAsleep--overview-with-last-known.json
new file mode 100644
index 000000000..67224fc2f
--- /dev/null
+++ b/cli/src/lib/__fixtures__/protocol/refusal--GridAsleep--overview-with-last-known.json
@@ -0,0 +1,30 @@
+{
+ "schema": "refusal",
+ "definition": "GridAsleep",
+ "request": "GET /relay/v1/grid/overview",
+ "status": 503,
+ "source": "the DEV VM, through grid-proxy (grid-apis feat/grid-platform-03-proxy-env @ 12b6bae, grid-src fix/grid-platform-03-loopback-bind @ 4aa0b01), no credential",
+ "recorded_at": "2026-09-30T19:00Z",
+ "sanitized": true,
+ "body": {
+ "detail": "grid is asleep and this request does not wake it — a person's request wakes it: inference, or a signed-in read, action or `grid join`",
+ "code": "grid_asleep",
+ "last_known": {
+ "age_seconds": 1915,
+ "nodes": [
+ {
+ "name": "node-a",
+ "engine": "starter",
+ "models": [
+ "deepseek/deepseek-v4-flash-0731",
+ "qwen/qwen3.8-27b"
+ ]
+ }
+ ],
+ "ids": [
+ "deepseek/deepseek-v4-flash-0731",
+ "qwen/qwen3.8-27b"
+ ]
+ }
+ }
+}
diff --git a/cli/src/lib/__fixtures__/protocol/refusal--GridDeleted--overview.json b/cli/src/lib/__fixtures__/protocol/refusal--GridDeleted--overview.json
new file mode 100644
index 000000000..1ff25497a
--- /dev/null
+++ b/cli/src/lib/__fixtures__/protocol/refusal--GridDeleted--overview.json
@@ -0,0 +1,13 @@
+{
+ "schema": "refusal",
+ "definition": "GridDeleted",
+ "request": "GET /relay/v1/grid/overview",
+ "status": 410,
+ "source": "the DEV VM, through grid-proxy (grid-apis feat/grid-platform-03-proxy-env @ 12b6bae, grid-src fix/grid-platform-03-loopback-bind @ 4aa0b01), no credential",
+ "recorded_at": "2026-09-30T19:00Z",
+ "sanitized": true,
+ "body": {
+ "detail": "grid was deleted",
+ "code": "grid_deleted"
+ }
+}
diff --git a/cli/src/lib/__fixtures__/protocol/refusal--GridStopped--in-process.json b/cli/src/lib/__fixtures__/protocol/refusal--GridStopped--in-process.json
new file mode 100644
index 000000000..15699dc0d
--- /dev/null
+++ b/cli/src/lib/__fixtures__/protocol/refusal--GridStopped--in-process.json
@@ -0,0 +1,13 @@
+{
+ "schema": "refusal",
+ "definition": "GridStopped",
+ "request": "GET /relay/v1/grid/overview",
+ "status": 503,
+ "headers": {},
+ "source": "grid-apis @ 12b6bae, grid_proxy.build_app in-process against a closed port (its own tests/test_proxy_refusals.py harness); the DEV VM has no grid in this state",
+ "sanitized": true,
+ "body": {
+ "detail": "grid was stopped by its owner, and nothing wakes it until they start it again (`grid start`, or Start in the app)",
+ "code": "grid_stopped"
+ }
+}
diff --git a/cli/src/lib/gridPicture.ts b/cli/src/lib/gridPicture.ts
index ba16bce8a..96486f58b 100644
--- a/cli/src/lib/gridPicture.ts
+++ b/cli/src/lib/gridPicture.ts
@@ -10,16 +10,17 @@
* stale, never shorter, and never wakes anything.
*/
import { idKey, type PictureState } from './gridAnnotation.js'
+import { LAST_KNOWN_MAX_AGE_SECONDS, MODEL_RETENTION_SECONDS } from './gridProtocol.js'
import type { OfflineReading } from './gridPresence.js'
import type { LastKnown, ReadNode } from './gridReader.js'
/**
* How long a model must be missing from awake answers before it leaves the list — one node TTL (120s on
* the master) plus one 30s heartbeat from a pre-0.3.48 provider. A just-woken master has not heard from
- * its providers, so without this the read that follows a wake blanks every list. ⚠️ Cross-repo timing
- * (the lockstep register); the public repo's pin finds it by this exact name.
+ * its providers, so without this the read that follows a wake blanks every list. The wire contract's
+ * (`gridProtocol.ts`, `timing`); the public repo's pin finds it by this exact name.
*/
-export const GRID_MODEL_RETENTION_MS = 150_000
+export const GRID_MODEL_RETENTION_MS = MODEL_RETENTION_SECONDS * 1000
/**
* …and across at least this many awake answers. Implied today — the window is measured from the FIRST
@@ -43,9 +44,9 @@ const AWAKE_CONTINUITY_MS = 45_000
/**
* A sleep record older than this is ignored: the master forgets node rows after 30 days asleep, so an
- * older record lists models nobody serves any more. ⚠️ Cross-repo timing, found by this exact name.
+ * older record lists models nobody serves any more. The wire contract's (`timing`), found by this exact name.
*/
-export const GRID_LAST_KNOWN_MAX_AGE_MS = 29 * 24 * 60 * 60 * 1000
+export const GRID_LAST_KNOWN_MAX_AGE_MS = LAST_KNOWN_MAX_AGE_SECONDS * 1000
/** Engines that are a router rather than a model (`grid-router` serves `auto`) are never offered. */
const ROUTER_ENGINE = 'grid-router'
diff --git a/cli/src/lib/gridProtocol.spec.ts b/cli/src/lib/gridProtocol.spec.ts
new file mode 100644
index 000000000..02c6a1d1f
--- /dev/null
+++ b/cli/src/lib/gridProtocol.spec.ts
@@ -0,0 +1,97 @@
+/**
+ * The grid reader against REAL answers, in the shapes `grid-protocol` defines (grid-platform ticket 12).
+ *
+ * `gridProtocol.ts` is generated in the public autonomous-grid repository from the wire contract's JSON
+ * Schemas and copied here whole; the reader takes its paths, codes and field names from it. The fixtures are
+ * that repository's recordings — answers taken from the DEV VM without a credential (or from a server's own
+ * code where DEV cannot produce one), sanitized — so what is read here is what a grid actually sends, not
+ * what a test author remembered it sending.
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { createServer, type Server } from 'node:http'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import {
+ DISCOVER_PATH, GRID_ASLEEP_CODE, LAST_KNOWN_MAX_AGE_SECONDS, MODEL_RETENTION_SECONDS, OVERVIEW_PATH, REFUSAL_STATUS,
+} from './gridProtocol.js'
+import { readDiscoveryIds, readOverview } from './gridReader.js'
+import { GRID_LAST_KNOWN_MAX_AGE_MS, GRID_MODEL_RETENTION_MS } from './gridPicture.js'
+
+interface Recording { schema: string; definition: string | null; status: number; body: Record<string, unknown> }
+
+const FIXTURES = join(fileURLToPath(new URL('.', import.meta.url)), '__fixtures__', 'protocol')
+const recording = (name: string): Recording =>
+ JSON.parse(readFileSync(join(FIXTURES, `${name}.json`), 'utf8')) as Recording
+
+/** A grid that answers each path with one recording, as the proxy in front of the master would. */
+let server: Server, base: string
+const routes = new Map<string, Recording>()
+
+beforeAll(async () => {
+ server = createServer((request, response) => {
+ const found = routes.get(request.url ?? '')
+ response.writeHead(found?.status ?? 404, { 'content-type': 'application/json' })
+ response.end(JSON.stringify(found?.body ?? { detail: 'unknown network' }))
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const address = server.address()
+ base = `http://127.0.0.1:${typeof address === 'object' && address ? address.port : 0}/g`
+})
+
+afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())))
+
+const serve = (path: string, name: string): void => { routes.set(`/g${path}`, recording(name)) }
+
+describe('the reader speaks the protocol', () => {
+ it('keeps a model and a last-known record exactly as long as the contract says', () => {
+ expect(GRID_MODEL_RETENTION_MS).toBe(MODEL_RETENTION_SECONDS * 1000)
+ expect(GRID_LAST_KNOWN_MAX_AGE_MS).toBe(LAST_KNOWN_MAX_AGE_SECONDS * 1000)
+ })
+})
+
+describe('real answers', () => {
+ it('reads an awake grid off a real overview', async () => {
+ serve(OVERVIEW_PATH, 'overview--root--awake-starter-engine')
+
+ const read = await readOverview(base)
+
+ expect(read.kind).toBe('awake')
+ if (read.kind !== 'awake') return
+ expect(read.nodes).toEqual([{
+ name: 'node-a', engine: 'starter', models: ['deepseek/deepseek-v4-flash-0731', 'qwen/qwen3.8-27b'],
+ providerEmail: '[email protected]',
+ }])
+ expect(read.curatedIds).toEqual(['deepseek/deepseek-v4-flash-0731', 'qwen/qwen3.8-27b'])
+ expect(read.windows['qwen/qwen3.8-27b']).toBe(1_000_000)
+ })
+
+ it('reads a sleeping grid and what it last served off a real asleep answer', async () => {
+ const answer = recording('refusal--GridAsleep--overview-with-last-known')
+ expect(answer.status).toBe(REFUSAL_STATUS[GRID_ASLEEP_CODE])
+ serve(OVERVIEW_PATH, 'refusal--GridAsleep--overview-with-last-known')
+
+ const read = await readOverview(base)
+
+ expect(read.kind).toBe('asleep')
+ if (read.kind !== 'asleep') return
+ expect(read.lastKnown?.nodes.map((node) => node.name)).toEqual(['node-a'])
+ expect(read.lastKnown?.ids).toContain('qwen/qwen3.8-27b')
+ expect(read.lastKnown?.ageSeconds).toBeGreaterThanOrEqual(0)
+ })
+
+ it.each([
+ ['a grid its owner stopped', 'refusal--GridStopped--in-process'],
+ ['a deleted grid', 'refusal--GridDeleted--overview'],
+ ])('reads %s as not answering — never asleep, never awake', async (_label, name) => {
+ serve(OVERVIEW_PATH, name)
+
+ expect(await readOverview(base)).toEqual({ kind: 'unanswered' })
+ })
+
+ it('spells each model exactly as its engine does, off a real discovery', async () => {
+ serve(DISCOVER_PATH, 'discover--root--awake-starter-engine')
+
+ expect(await readDiscoveryIds(base)).toEqual(['deepseek/deepseek-v4-flash-0731', 'qwen/qwen3.8-27b'])
+ })
+})
diff --git a/cli/src/lib/gridProtocol.ts b/cli/src/lib/gridProtocol.ts
new file mode 100644
index 000000000..644519c95
--- /dev/null
+++ b/cli/src/lib/gridProtocol.ts
@@ -0,0 +1,819 @@
+// GENERATED by grid-protocol 0.1.1 — do not edit. The source is autonomous-grid's
+// `protocol/grid_protocol/schemas/`: change a schema there, run `python -m grid_protocol._codegen --write`,
+// and copy this file.
+
+export const PROTOCOL_VERSION = '0.1.1'
+
+export const NO_WAKE_FLAG = '--no-wake'
+
+/** GET /nodes/discover */
+export const DISCOVER_PATH = '/nodes/discover'
+
+export const PROVIDER_ROUTE_PREFIX = 'provider:'
+
+/** GET /relay/v1/models */
+export const MODELS_PATH = '/relay/v1/models'
+
+/** POST /nodes/heartbeat */
+export const HEARTBEAT_PATH = '/nodes/heartbeat'
+
+export const UNHEALTHY_MODELS_LOAD_KEY = 'unhealthy_models'
+
+/** GET /relay/v1/poll */
+export const POLL_PATH = '/relay/v1/poll'
+
+export const RELAY_PATH = '/relay/v1'
+
+/** PUT /nodes/{node_id} */
+export const NODE_PATH = '/nodes/{node_id}'
+
+export const CAPABILITIES_SCHEMA_VERSION = 1
+
+/** POST /relay/v1/response/{transaction_id} */
+export const RESPONSE_PATH = '/relay/v1/response/{transaction_id}'
+
+export const PROVIDER_ATTEMPT_HEADER = 'X-Grid-Provider-Attempt'
+
+/** POST /relay/v1/error/{transaction_id} */
+export const ERROR_REPORT_PATH = '/relay/v1/error/{transaction_id}'
+
+export const NO_PROVIDERS_AVAILABLE_CODE = 'no_providers_available'
+
+export const MODEL_NOT_FOUND_CODE = 'model_not_found'
+
+export const RELAY_RESTARTING_CODE = 'relay_restarting'
+
+/** GET /relay/v1/grid/overview */
+export const OVERVIEW_PATH = '/relay/v1/grid/overview'
+
+export const RETRY_AFTER_HEADER = 'Retry-After'
+
+export const GRID_ASLEEP_CODE = 'grid_asleep'
+
+export const GRID_STOPPED_CODE = 'grid_stopped'
+
+export const GRID_DELETED_CODE = 'grid_deleted'
+
+export const GRID_MASTER_DOWN_CODE = 'grid_master_down'
+
+export const FEATURE_RETIRED_CODE = 'feature_retired'
+
+/** How often a provider beats (public CLI `relay.HEARTBEAT_INTERVAL`). */
+export const HEARTBEAT_INTERVAL_SECONDS = 30
+
+/**
+ * A node silent this long is not selected (grid-src `NODE_TTL_SECONDS`, a knob; the heartbeat answer's
+ * `ttl_seconds`).
+ */
+export const NODE_TTL_SECONDS = 120
+
+/**
+ * How long a poll is held before its 204 (grid-src `poll_timeout_seconds`); a provider's own poll timeout
+ * must be longer.
+ */
+export const POLL_WINDOW_SECONDS = 30
+
+/** A provider parked on grid_asleep probes this often (public CLI `serve._ASLEEP_PROBE_SECONDS`). */
+export const ASLEEP_PROBE_SECONDS = 10
+
+/** A provider parked on grid_stopped probes this often: only the owner's start ends it. */
+export const STOPPED_PROBE_SECONDS = 60
+
+/** The next beat after a failed one (the platform's restart of a dead master). */
+export const AFTER_A_FAILED_BEAT_SECONDS = 10
+
+/**
+ * Inside the boot-hold window a request that finds NO provider is held this long for one to beat (grid-src
+ * `GRID_BOOT_HOLD_SECONDS`, a knob). A woken master starts with every provider past its TTL.
+ */
+export const BOOT_HOLD_SECONDS = 30
+
+/**
+ * How long after a master starts its boot hold applies (grid-src `GRID_BOOT_HOLD_WINDOW_SECONDS`, a knob).
+ */
+export const BOOT_HOLD_WINDOW_SECONDS = 120
+
+/**
+ * A model is dropped from a reader's list only after this long absent across two or more awake reads (a node
+ * TTL and a beat), so a cold wake does not blank a list (harness `GRID_MODEL_RETENTION_SECONDS|_MS`).
+ */
+export const MODEL_RETENTION_SECONDS = 150
+
+/**
+ * The last-known record is captured only from a master up this long: a node TTL and a beat, with a margin
+ * (grid-apis `sleep_record.MIN_UPTIME_SECONDS`).
+ */
+export const SLEEP_RECORD_MIN_UPTIME_SECONDS = 180
+
+/**
+ * No record is written until this long after somebody lost access to the grid: their machine can stay listed
+ * for a TTL and a beat (grid-apis `sleep_record.ACCESS_LOSS_SETTLE_SECONDS`).
+ */
+export const ACCESS_LOSS_SETTLE_SECONDS = 150
+
+/**
+ * 29 days: a last-known record older than this is not sent, and a reader ignores one (grid-apis
+ * `sleep_record.MAX_AGE_SECONDS`; harness `GRID_LAST_KNOWN_MAX_AGE_SECONDS|_MS`).
+ */
+export const LAST_KNOWN_MAX_AGE_SECONDS = 2505600
+
+/** 30 days: a master forgets a node row silent this long (grid-src `registry.prune_stale_nodes`). */
+export const MASTER_NODE_PRUNE_SECONDS = 2592000
+
+/** Each refusal code, and the HTTP status that carries it. */
+export const REFUSAL_STATUS = {
+ no_providers_available: 503,
+ model_not_found: 404,
+ relay_restarting: 503,
+ grid_asleep: 503,
+ grid_stopped: 503,
+ grid_deleted: 410,
+ grid_master_down: 503,
+ feature_retired: 410,
+} as const
+
+/**
+ * The one JSON line the public `grid` CLI writes on stderr when a `--json` command fails. Under `--no-wake`
+ * (`grid models | engines | stats`, from 0.3.49) the overview and discovery go out with no credential, an
+ * owner status already `asleep` is answered with no request at all, and `code` is `grid_asleep` when the
+ * proxy said so and null for every other refusal. A `grid` older than 0.3.49 exits 2 at argparse before it
+ * sends anything; a caller reads that as "no read" and must never retry without the flag, which would be a
+ * wake. Accepted and ignored in local mode.
+ */
+export interface CliErrorEnvelope {
+ error: {
+ code: string | null
+ message: string
+ /** The HTTP status behind the refusal, when there was one. */
+ status: number | null
+ [key: string]: unknown
+ }
+ [key: string]: unknown
+}
+
+/**
+ * A grid's provider discovery (grid-src `server.discover`). Public at the master, and a credential-less GET
+ * never wakes a sleeping grid, as for the overview. Readers take only `providers[].models` and
+ * `providers[].capabilities.models[<route id>].raw_model_id` — the exact-case model name the overview
+ * lower-cases — and read any failure as an empty list.
+ */
+export interface ProviderDiscovery {
+ providers: DiscoveredProvider[]
+ [key: string]: unknown
+}
+
+export interface DiscoveredProvider {
+ node_id: string
+ /**
+ * Route ids, `provider:<node id>:<hash>`. A route id embeds a NODE id, so nothing that outlives a
+ * membership (the sleep record) may store one. Models the provider withdrew in its heartbeat are left out.
+ */
+ models: string[]
+ pricing: {
+ [key: string]: number
+ }
+ capabilities: DiscoveredCapabilities
+ load: {
+ [key: string]: unknown
+ }
+ max_concurrency: number
+ endpoint_url: string | null
+ last_heartbeat: string | null
+ first_seen_at: string | null
+ verified_at: string | null
+ /** The node's presentation metadata, as the overview publishes it. */
+ meta: {
+ [key: string]: unknown
+ }
+ [key: string]: unknown
+}
+
+/** The provider's capability envelope, normalized by the master. `{}` when the provider published none. */
+export interface DiscoveredCapabilities {
+ schema_version?: number
+ models?: {
+ [key: string]: DiscoveredModel
+ }
+ [key: string]: unknown
+}
+
+export interface DiscoveredModel {
+ /**
+ * The model's exact-case name as its engine serves it. Shown under the display rule: a trailing `.gguf`
+ * removed, case kept.
+ */
+ raw_model_id: string
+ public_model_id?: string
+ provider_group_id?: string | null
+ provider_supplied?: boolean
+ [key: string]: unknown
+}
+
+/**
+ * What the platform recorded a grid serving when it put the grid to sleep (grid-apis
+ * `sleep_record.answer_field`), carried on the `503 grid_asleep` answer to a credential-less GET of the
+ * overview. The record is kept only from a master up SLEEP_RECORD_MIN_UPTIME_SECONDS, and is deleted when
+ * somebody loses access to the grid: it must never name a machine whose owner lost access. Drift costs a
+ * stale or empty model list on a grid the reader has never seen awake — never a wake.
+ */
+export interface LastKnown {
+ /**
+ * How old the record is, computed by the SERVER from its own clock, so no client clock matters. Never above
+ * LAST_KNOWN_MAX_AGE_SECONDS: an older record is not sent.
+ */
+ age_seconds: number
+ nodes: LastKnownNode[]
+ /** Exact-case candidate model ids: a spelling source for a case map, never a list of what is served. */
+ ids: string[]
+ [key: string]: unknown
+}
+
+export interface LastKnownNode {
+ name: string
+ engine: string | null
+ /** Lower-cased, as the overview lists them. */
+ models: string[]
+ [key: string]: unknown
+}
+
+/**
+ * The relay's OpenAI-style model list. Needs a credential (scope `inference:models`), so a GET of it WAKES a
+ * sleeping grid: it belongs to a person's act (the harness's wake read), never to an automatic read. When the
+ * router is on and the list is not empty, the router's rows (`owned_by: grid-router`) come first.
+ */
+export interface ModelList {
+ object: 'list'
+ data: ModelEntry[]
+ [key: string]: unknown
+}
+
+/**
+ * A served model, or a router row (`Auto`, and the effort-mode rows while effort mode is served), which
+ * carries only the four required keys.
+ */
+export interface ModelEntry {
+ id: string
+ object: 'model'
+ created: number
+ owned_by: string
+ display_name?: string
+ provider_count?: number
+ provider_supplied?: boolean
+ trusted?: boolean
+ raw_model_id?: string
+ raw_model_ids?: string[]
+ provider_group_id?: string | null
+ provider_group_ids?: string[]
+ /** The largest window any engine serving the model was started with. */
+ context_window?: number | null
+ [key: string]: unknown
+}
+
+/**
+ * A provider's heartbeat: the body of `POST /nodes/heartbeat`, every HEARTBEAT_INTERVAL_SECONDS, with a node
+ * token (the node is the token's, not the body's). It never wakes a sleeping grid; on a sleeping or stopped
+ * grid it is the parked provider's one probe. In grid mode the master answers 404 to a heartbeat from a node
+ * that has not completed its registration as a provider (`PUT /nodes/{node_id}` with role `provider` or
+ * `both`; a `consumer` one, which is how a provider leaves, does not count), and nothing else makes a node
+ * registered: not a token, not a heartbeat, not a poll. The public CLI registers again when it is answered
+ * 404, so a node whose row was pruned, lost in a restore or left behind by a move is serving again within one
+ * heartbeat, instead of staying connected and never being given work.
+ */
+export interface NodeHeartbeat {
+ load?: NodeLoad
+ meta?: NodeMeta
+ [key: string]: unknown
+}
+
+export interface NodeHeartbeatAnswer {
+ status: 'ok'
+ /** The master's node TTL (NODE_TTL_SECONDS by default): a node silent this long is not selected. */
+ ttl_seconds: number
+ [key: string]: unknown
+}
+
+/**
+ * Live telemetry. Each key is optional, and a key the provider did not measure is left out rather than sent
+ * as zero.
+ */
+export interface NodeLoad {
+ active_tasks?: number
+ platform?: string
+ /** Models whose engine is failing; the relay stops selecting them until they drop off this list. */
+ unhealthy_models?: string[]
+ gpu_count?: number
+ memory_total_mb?: number
+ memory_used_mb?: number
+ gpu_util?: number
+ gpu_temp_c?: number
+ gpu_power_w?: number
+ gpu_power_limit_w?: number
+ disk_total_gb?: number
+ disk_used_gb?: number
+ tok_s?: number
+ codex_rate_limits?: {
+ [key: string]: unknown
+ }
+ quota?: {
+ [key: string]: unknown
+ }
+ [key: string]: unknown
+}
+
+/**
+ * One request for a provider to serve: the 200 body of `GET /relay/v1/poll` (node token). The master
+ * long-polls for POLL_WINDOW_SECONDS and answers 204 with an EMPTY body when no work came, so a client's own
+ * timeout must be longer. A poll never wakes a sleeping grid. Readers ignore keys they do not know.
+ */
+export interface PollJob {
+ transaction_id: string
+ /**
+ * Where to send `body` on the engine: `chat/completions`, `completions`, `responses`, or a `media/` path
+ * while media is served.
+ */
+ endpoint_path: string
+ /** The request, already in `wire_format`. */
+ body: {
+ [key: string]: unknown
+ }
+ is_stream: boolean
+ /** Epoch seconds. */
+ created_at: number
+ /** What is left of the request's budget. */
+ inference_timeout_seconds: number
+ /** The dialect `body` is in. An older provider ignores it. */
+ wire_format: 'chat' | 'responses' | 'anthropic'
+ provider_attempt: number
+ /**
+ * Only for a provider whose capability entry sets `provider_attempt_tokens`; echoed in
+ * `X-Grid-Provider-Attempt` on the result.
+ */
+ provider_attempt_token?: string
+ [key: string]: unknown
+}
+
+/**
+ * A provider's registration: the body of `PUT /nodes/{node_id}`, with a node token whose node is the path's.
+ * Every key is optional at the master and an unknown key is ignored; the public CLI always sends `role`,
+ * `models` and `pricing`, and leaving a grid sends `{role: consumer, models: [], pricing: {}}`. A
+ * registration WAKES a sleeping grid (it carries a credential). A node answered 404 on its heartbeat
+ * registers again.
+ */
+export interface NodeRegistration {
+ /** `provider`, or `consumer` to stop serving. */
+ role?: string
+ models?: string[]
+ pricing?: {
+ [key: string]: number
+ }
+ capabilities?: NodeCapabilities
+ meta?: NodeMeta
+ /**
+ * Concurrent requests this provider serves. Null or absent: no change. The master clamps it to at least 1.
+ */
+ max_concurrency?: number | null
+ [key: string]: unknown
+}
+
+export interface NodeRegistrationAnswer {
+ status: 'updated'
+ [key: string]: unknown
+}
+
+/**
+ * The provider's capability envelope. The master keeps it only at this schema version (otherwise it stores
+ * `{}`), and refuses it 400 unless `models`' keys are exactly the registration's `models`.
+ */
+export interface NodeCapabilities {
+ schema_version: 1
+ models: {
+ [key: string]: ModelCapability
+ }
+ [key: string]: unknown
+}
+
+/**
+ * What one model on this node can do. `endpoints` absent means chat completions only (fail-closed for the
+ * Responses dialect).
+ */
+export interface ModelCapability {
+ /** The relay's endpoint paths, e.g. `chat/completions`, `responses`. */
+ endpoints?: string[]
+ input_modalities?: string[]
+ output_modalities?: string[]
+ context_window?: number
+ max_output_tokens?: number
+ features?: {
+ [key: string]: boolean
+ }
+ limits?: {
+ [key: string]: unknown
+ }
+ /**
+ * The provider echoes `X-Grid-Provider-Attempt`; the relay then puts `provider_attempt_token` in its poll
+ * jobs.
+ */
+ provider_attempt_tokens?: boolean
+ [key: string]: unknown
+}
+
+/** Presentation metadata. An empty object means "no change". */
+export interface NodeMeta {
+ name?: string
+ /** The operator chose `name`. Absent means NOT chosen, which is the private answer. */
+ name_chosen?: boolean
+ engine?: string
+ device?: string
+ chip?: string
+ memory_gb?: number
+ device_class?: string
+ plan_type?: string
+ [key: string]: unknown
+}
+
+/**
+ * The answer to a provider's result: `POST /relay/v1/response/{transaction_id}` with a node token, whose body
+ * is the engine's own bytes — one JSON body (`application/json`), or its SSE lines as they come
+ * (`text/event-stream`). The master checks the framing and answers `400` ResultRejected for a malformed
+ * result, `409` for a stale attempt, `410` when the transaction already ended. An upload never wakes a
+ * sleeping grid.
+ */
+export interface ResultDelivered {
+ status: 'delivered'
+ [key: string]: unknown
+}
+
+/** 400: the result's framing is wrong, and the request is failed rather than delivered. */
+export interface ResultRejected {
+ error: 'validation_failed'
+ reason: 'bare_cr_in_sse_line' | 'unterminated_sse_block' | 'invalid_responses_stream' | 'truncated_responses_stream' | 'non_stream_responses_submit' | 'invalid_responses_body' | 'non_terminal_responses_body' | 'invalid_json'
+ [key: string]: unknown
+}
+
+/** A provider's report that it could not serve the request: `POST /relay/v1/error/{transaction_id}`. */
+export interface ErrorReport {
+ /** What failed, for the log; the public CLI sends a string. */
+ error: unknown
+ /** Tokens already streamed; the relay retries on another provider only when none were. */
+ tokens_delivered?: number
+ [key: string]: unknown
+}
+
+export interface ErrorReportAnswer {
+ status: 'failed' | 'retried'
+ [key: string]: unknown
+}
+
+/**
+ * OpenAI's error envelope. A master answers an inference request's failure in it when the caller asked for
+ * OpenAI errors (a Bearer `lga_sk_` key, or the error-format header); otherwise the same failure is
+ * `{"detail": <message>}` with no code. `/messages` answers in Anthropic's envelope instead. Keys a master
+ * adds go BESIDE `error`, never inside it.
+ */
+export interface OpenAIError {
+ error: {
+ message: string
+ type: string
+ param: string | null
+ /** The relay's name for the failure. */
+ code: string | null
+ [key: string]: unknown
+ }
+ [key: string]: unknown
+}
+
+/**
+ * No provider serves the requested model now, on a grid that has served it (its engine may only be away),
+ * that has never had an engine at all, or whose master cannot tell: retryable. On a grid that has had an
+ * engine, a model none of its engines ever served is ModelNotFound instead. Inside a master's boot hold
+ * (BOOT_HOLD_WINDOW_SECONDS after it starts) a request for a model nobody serves yet is held up to
+ * BOOT_HOLD_SECONDS first, so that a provider parked on the sleeping grid can come back.
+ */
+export interface NoProvidersAvailable {
+ error: {
+ message: string
+ type: 'server_error'
+ param: string | null
+ code: 'no_providers_available'
+ [key: string]: unknown
+ }
+ [key: string]: unknown
+}
+
+/**
+ * No engine on this grid has ever served the requested model: none it still has a node row for, live or not,
+ * and nothing in its model catalog, whose rows outlive an engine that left. No wait can bring one, so it is
+ * refused at once (after a woken master's boot hold) rather than as the retryable NoProvidersAvailable, which
+ * a grid that has served the model, a grid that has never had an engine, and a master that cannot tell keep.
+ * The message names what the grid serves now and never echoes the requested name. A caller that did not ask
+ * for OpenAI errors gets `{"detail": <message>}`. Displayed, never parsed: the public CLI must not parse it.
+ */
+export interface ModelNotFound {
+ error: {
+ message: string
+ type: 'invalid_request_error'
+ param: string | null
+ code: 'model_not_found'
+ [key: string]: unknown
+ }
+ [key: string]: unknown
+}
+
+/**
+ * The master holding the request ended it while retiring or stopping: send it again. A non-stream request is
+ * answered 503 with this envelope (or `{"detail": <message>}` for a caller that did not ask for OpenAI
+ * errors). A chat stream ends with `data: {"error": <this envelope's error>}`. A Responses stream ends with a
+ * `response.failed` event whose `response.error.code` is `server_error`: the Responses code set is closed, so
+ * this name never reaches a Responses client. The public CLI must not parse it.
+ */
+export interface RelayRestarting {
+ error: {
+ message: string
+ type: 'server_error'
+ param: null
+ code: 'relay_restarting'
+ [key: string]: unknown
+ }
+ [key: string]: unknown
+}
+
+/**
+ * A grid's public overview (grid-src `overview.build_grid_overview`). The master serves it with NO
+ * authentication, and a credential-less GET never wakes a sleeping grid: grid-proxy answers it `503
+ * grid_asleep` with `last_known` instead, while a GET that carries any credential (its presence, not its
+ * validity) wakes the grid. So an automatic reader — the harness daemon, `grid models|engines|stats
+ * --no-wake` — must never add one. Readers take `nodes[].{name, engine, models}` and `models[].id`; anything
+ * that is not a 200 object with a `nodes` array is "not answering", never "awake with nothing".
+ */
+export interface GridOverview {
+ grid: {
+ /** `running` whenever a master answers. */
+ state: string
+ [key: string]: unknown
+ }
+ /** Whether the reserved model `auto` routes on this grid. */
+ router_enabled: boolean
+ advertises_chat_completions: boolean
+ advertises_responses: boolean
+ advertises_messages: boolean
+ stats: {
+ models: number
+ nodes: number
+ concurrent_capacity: number
+ /** A fixed placeholder, not a measurement. */
+ uptime_pct: number
+ [key: string]: unknown
+ }
+ /**
+ * What the grid answered in the rollup window; null until a rollup has landed (a master warming up must not
+ * report an idle grid).
+ */
+ answered: null | Answered
+ models: OverviewModel[]
+ nodes: OverviewNode[]
+ [key: string]: unknown
+}
+
+export interface Answered {
+ window_seconds: number
+ /** Includes `tokens_cached`, the cached share of the prefill. */
+ tokens_in: number
+ tokens_cached: number
+ tokens_out: number
+ requests: number
+ [key: string]: unknown
+}
+
+/** An admin-curated model a live node of its provider serves now (or a `coming_soon` placeholder). */
+export interface OverviewModel {
+ /** Lower-cased. */
+ id: string
+ name: string
+ maker: string | null
+ modality: string
+ context_length: number | null
+ vision: boolean
+ pricing: null | {
+ unit: 'token'
+ input_per_1m: number
+ output_per_1m: number
+ [key: string]: unknown
+ }
+ status: string
+ [key: string]: unknown
+}
+
+/**
+ * One live engine node. Telemetry fields are each independently null when the node did not report them —
+ * never a zero.
+ */
+export interface OverviewNode {
+ /**
+ * On an `os-community` grid, the machine's name only when its operator chose it; otherwise an anonymous
+ * `node-<id>` label.
+ */
+ name: string
+ /** Withheld (null) where the grid does not publish it. */
+ provider_email: string | null
+ device: string
+ chip?: string | null
+ memory_gb?: number | null
+ vram_total_mb?: number | null
+ vram_gb?: number | null
+ vram_used_mb?: number | null
+ gpu_util_pct?: number | null
+ gpu_temp_c?: number | null
+ gpu_power_w?: number | null
+ gpu_power_limit_w?: number | null
+ disk_total_gb?: number | null
+ disk_used_gb?: number | null
+ platform?: string | null
+ device_class: string
+ /** `models[0]`, or null when the node serves nothing. */
+ model: string | null
+ /** Every model the node serves, lower-cased (the display rule: a trailing `.gguf` removed). */
+ models: string[]
+ model_engines: {
+ [key: string]: string
+ }
+ /**
+ * Keyed like `models`. A model absent here is one the node published no capability envelope for — not one
+ * with no window.
+ */
+ model_capabilities: {
+ [key: string]: NodeModelCapability
+ }
+ responses_models: string[]
+ engine: string
+ plan_type?: string | null
+ codex_rate_limits?: {
+ [key: string]: unknown
+ } | null
+ throughput_tok_s?: number | null
+ max_concurrency: number
+ answered: null | NodeAnswered
+ online: boolean
+ [key: string]: unknown
+}
+
+export interface NodeModelCapability {
+ context_length: number | null
+ vision: boolean | null
+ [key: string]: unknown
+}
+
+export interface NodeAnswered {
+ window_seconds: number
+ tokens_in: number
+ tokens_cached: number
+ tokens_out: number
+ requests: number
+ by_model: Array<{
+ model: string
+ tokens_in: number
+ tokens_cached: number
+ tokens_out: number
+ requests: number
+ [key: string]: unknown
+ }>
+ [key: string]: unknown
+}
+
+/**
+ * The platform's coded refusal: a sentence for a person in `detail` and, BESIDE it (never under it), a
+ * machine-readable `code`. grid-proxy sends it for a grid that is not up; a master sends it for a retired
+ * feature. The public CLI compares `code` for EQUALITY, never for truthiness and never paired with the
+ * status, and reads a code it does not know, or none, as a transient failure. grid-proxy's codeless answers
+ * have this shape too: `404 unknown network`, `503` while a wake is starting (with `Retry-After: 20`), and
+ * `502`/`504` when the master did not answer. The public CLI acts on exactly three codes (grid_asleep,
+ * grid_stopped, grid_deleted); it must never parse the others, so that renaming one of them cannot change
+ * what a provider does.
+ */
+export interface Refusal {
+ /** A sentence for a person. Clients render it; its wording is not part of the contract. */
+ detail: string
+ /** The refusal's name, when it has one. Each named refusal is a definition below. */
+ code?: string
+ [key: string]: unknown
+}
+
+/**
+ * The grid is asleep and this request did not wake it. A request that may wake a grid (a signed-in read,
+ * inference, an owner's act, a provider's registration) is held and replayed instead, unless grid-proxy's
+ * limits turn it away (then with a Retry-After: past a wake limit nothing is woken, past the waiting bound
+ * the grid IS waking and only this request is not held); a provider's heartbeat, poll and callbacks, and any
+ * credential-less read, never wake one. The public CLI's provider PARKS on it: its heartbeat probes every
+ * ASLEEP_PROBE_SECONDS, bring-up on its own schedule, and the engine serves again by itself after a wake.
+ */
+export interface GridAsleep {
+ detail: string
+ code: 'grid_asleep'
+ /**
+ * Only on the answer to a credential-less GET of the overview, after `detail` and `code`. Absent when the
+ * platform holds no record for the grid, or none younger than LAST_KNOWN_MAX_AGE_SECONDS.
+ */
+ last_known?: LastKnown
+ [key: string]: unknown
+}
+
+/**
+ * The grid's OWNER stopped it, and nothing wakes it until the owner starts it: not inference, not a read, not
+ * a join. The public CLI's provider parks on it as on grid_asleep, probing every STOPPED_PROBE_SECONDS.
+ */
+export interface GridStopped {
+ detail: string
+ code: 'grid_stopped'
+ [key: string]: unknown
+}
+
+/**
+ * The grid was deleted. The only refusal that ENDS a provider: the public CLI stops the engine for good, so a
+ * false positive would stop a provider serving a live grid. An older proxy answered `404 unknown network`
+ * with no code instead.
+ */
+export interface GridDeleted {
+ detail: string
+ code: 'grid_deleted'
+ [key: string]: unknown
+}
+
+/**
+ * The grid should be running but its master refused the connection; the platform is bringing it back.
+ * Deliberately NOT parsed for its value by the public CLI: a parked provider leaves the park on any code
+ * other than a pause code, and otherwise retries it like any 503.
+ */
+export interface GridMasterDown {
+ detail: string
+ code: 'grid_master_down'
+ [key: string]: unknown
+}
+
+/**
+ * The route or model name belongs to a retired feature (media, distributed tasks, effort mode), and the
+ * master answers this instead of serving it. The public CLI must not parse it.
+ */
+export interface FeatureRetired {
+ detail: string
+ code: 'feature_retired'
+ [key: string]: unknown
+}
+
+/**
+ * The timing values two or more parties must agree on, each in seconds. The rules BETWEEN them (a parked
+ * probe fits twice in the boot hold; a model outlives a node TTL and a beat; the last-known record dies
+ * before the master forgets its nodes) are checked by grid-protocol's own tests, because JSON Schema cannot
+ * relate two values. Several are also operator knobs on the side that owns them (named in each description);
+ * the value here is the default the others were built against.
+ */
+export interface Timing {
+ /** How often a provider beats (public CLI `relay.HEARTBEAT_INTERVAL`). */
+ heartbeat_interval_seconds: 30
+ /**
+ * A node silent this long is not selected (grid-src `NODE_TTL_SECONDS`, a knob; the heartbeat answer's
+ * `ttl_seconds`).
+ */
+ node_ttl_seconds: 120
+ /**
+ * How long a poll is held before its 204 (grid-src `poll_timeout_seconds`); a provider's own poll timeout
+ * must be longer.
+ */
+ poll_window_seconds: 30
+ /** A provider parked on grid_asleep probes this often (public CLI `serve._ASLEEP_PROBE_SECONDS`). */
+ asleep_probe_seconds: 10
+ /** A provider parked on grid_stopped probes this often: only the owner's start ends it. */
+ stopped_probe_seconds: 60
+ /** The next beat after a failed one (the platform's restart of a dead master). */
+ after_a_failed_beat_seconds: 10
+ /**
+ * Inside the boot-hold window a request that finds NO provider is held this long for one to beat (grid-src
+ * `GRID_BOOT_HOLD_SECONDS`, a knob). A woken master starts with every provider past its TTL.
+ */
+ boot_hold_seconds: 30
+ /**
+ * How long after a master starts its boot hold applies (grid-src `GRID_BOOT_HOLD_WINDOW_SECONDS`, a knob).
+ */
+ boot_hold_window_seconds: 120
+ /**
+ * A model is dropped from a reader's list only after this long absent across two or more awake reads (a
+ * node TTL and a beat), so a cold wake does not blank a list (harness `GRID_MODEL_RETENTION_SECONDS|_MS`).
+ */
+ model_retention_seconds: 150
+ /**
+ * The last-known record is captured only from a master up this long: a node TTL and a beat, with a margin
+ * (grid-apis `sleep_record.MIN_UPTIME_SECONDS`).
+ */
+ sleep_record_min_uptime_seconds: 180
+ /**
+ * No record is written until this long after somebody lost access to the grid: their machine can stay
+ * listed for a TTL and a beat (grid-apis `sleep_record.ACCESS_LOSS_SETTLE_SECONDS`).
+ */
+ access_loss_settle_seconds: 150
+ /**
+ * 29 days: a last-known record older than this is not sent, and a reader ignores one (grid-apis
+ * `sleep_record.MAX_AGE_SECONDS`; harness `GRID_LAST_KNOWN_MAX_AGE_SECONDS|_MS`).
+ */
+ last_known_max_age_seconds: 2505600
+ /** 30 days: a master forgets a node row silent this long (grid-src `registry.prune_stale_nodes`). */
+ master_node_prune_seconds: 2592000
+ [key: string]: unknown
+}
diff --git a/cli/src/lib/gridReader.ts b/cli/src/lib/gridReader.ts
index c3dc89014..b30d43c19 100644
--- a/cli/src/lib/gridReader.ts
+++ b/cli/src/lib/gridReader.ts
@@ -18,26 +18,20 @@
* wake a grid (a message, Start, an explicit wake, a prewarm) goes out another way — `gridWake.ts` — on
* purpose.
*
- * The values below are cross-repo (the lockstep register; `tests/test_grid_reads_lockstep.py` in the
- * public `grid` repository finds the two literals by these exact quoted spellings).
+ * The paths, the code, the flag and every field name read below come from `gridProtocol.ts`: the wire
+ * contract, generated from its JSON Schemas in the public autonomous-grid repository (`protocol/`) and copied
+ * here whole. Never edit that file by hand; a shape changes there first.
*/
import { VERSION } from '../version.js'
import { gridEnvelopes } from './gridEnvelope.js'
import { gridExec, gridJson } from './gridExec.js'
import { idKey } from './gridPicture.js'
-
-/** The master's two public reads, under a grid's address. ⚠️ Cross-repo literals (grid-src's routes,
- * grid-apis' route rules and sleep record, the public CLI's `remote_overview`). */
-export const GRID_OVERVIEW_PATH = '/relay/v1/grid/overview'
-export const GRID_DISCOVER_PATH = '/nodes/discover'
-
-/** The code beside `detail` on a sleeping grid's 503 (grid-apis `grid_proxy.GRID_ASLEEP_CODE`). Compared
- * for EQUALITY only: any other code, or none, is "not answering" — never asleep, never awake. */
-export const GRID_ASLEEP_CODE = 'grid_asleep'
-
-/** The public CLI's flag that reads without a credential (`grid` ≥ 0.3.49). A `grid` too old for it exits
- * 2 at argparse, before anything is sent — so the fallback below can never turn into a waking read. */
-export const GRID_NO_WAKE_FLAG = '--no-wake'
+import {
+ DISCOVER_PATH, GRID_ASLEEP_CODE, NO_WAKE_FLAG, OVERVIEW_PATH, REFUSAL_STATUS,
+ type DiscoveredCapabilities, type DiscoveredModel, type DiscoveredProvider, type GridAsleep,
+ type GridOverview, type LastKnown as WireLastKnown, type LastKnownNode, type NodeModelCapability,
+ type OverviewModel, type OverviewNode, type ProviderDiscovery,
+} from './gridProtocol.js'
/** The owner status of a grid the platform's reaper slept (grid-apis `grid_sleep_state.ASLEEP`), as
* `grid info --json` passes it through. Only the grid's owner sees a status at all. */
@@ -96,6 +90,10 @@ export type GridRead =
| { kind: 'unreachable' }
type Json = Record<string, unknown>
+/** An object off the wire: the contract's key names — so a renamed field fails `tsc` here — with every value
+ * still unchecked. The generated types keep an index signature (a newer server may add keys), which would
+ * erase the names from `keyof`, so the declared keys are picked out first. */
+type Unchecked<T> = { [K in keyof T as string extends K ? never : number extends K ? never : K]?: unknown }
const isObject = (value: unknown): value is Json => !!value && typeof value === 'object' && !Array.isArray(value)
const text = (value: unknown): string =>
typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, MAX_TEXT) : ''
@@ -157,26 +155,29 @@ async function boundedJson(response: Response): Promise<unknown> {
function readNodes(value: unknown): ReadNode[] {
if (!Array.isArray(value)) return []
- return value.filter(isObject).slice(0, MAX_NODES).map((node) => ({
- name: text(node.name),
- engine: text(node.engine),
- models: strings(node.models, MAX_MODELS_PER_NODE),
- providerEmail: typeof node.provider_email === 'string' && node.provider_email ? node.provider_email : null,
- }))
+ return value.filter(isObject).slice(0, MAX_NODES).map((raw) => {
+ const node: Unchecked<OverviewNode> = raw
+ return {
+ name: text(node.name),
+ engine: text(node.engine),
+ models: strings(node.models, MAX_MODELS_PER_NODE),
+ providerEmail: typeof node.provider_email === 'string' && node.provider_email ? node.provider_email : null,
+ }
+ })
}
/** `last_known`, or null when it is absent or not in the shape grid-apis writes. Parsing it sends nothing. */
export function parseLastKnown(value: unknown): LastKnown | null {
if (!isObject(value)) return null
- const age = value.age_seconds
+ const record: Unchecked<WireLastKnown> = value
+ const age = record.age_seconds
if (typeof age !== 'number' || !Number.isFinite(age) || age < 0) return null
- if (!Array.isArray(value.nodes)) return null
- const nodes = value.nodes.filter(isObject).slice(0, MAX_NODES).map((node) => ({
- name: text(node.name),
- engine: text(node.engine),
- models: strings(node.models, MAX_MODELS_PER_NODE),
- }))
- return { ageSeconds: age, nodes, ids: strings(value.ids, MAX_IDS) }
+ if (!Array.isArray(record.nodes)) return null
+ const nodes = record.nodes.filter(isObject).slice(0, MAX_NODES).map((raw) => {
+ const node: Unchecked<LastKnownNode> = raw
+ return { name: text(node.name), engine: text(node.engine), models: strings(node.models, MAX_MODELS_PER_NODE) }
+ })
+ return { ageSeconds: age, nodes, ids: strings(record.ids, MAX_IDS) }
}
/**
@@ -189,22 +190,26 @@ export function parseLastKnown(value: unknown): LastKnown | null {
export async function readOverview(base: string): Promise<GridRead> {
let answer: { status: number; body: unknown }
try {
- answer = await get(base, GRID_OVERVIEW_PATH, 'read')
+ answer = await get(base, OVERVIEW_PATH, 'read')
} catch {
return { kind: 'unreachable' }
}
const { status, body } = answer
- if (status === 503 && isObject(body) && body.code === GRID_ASLEEP_CODE) {
- return { kind: 'asleep', lastKnown: parseLastKnown(body.last_known) }
+ if (status === REFUSAL_STATUS[GRID_ASLEEP_CODE] && isObject(body)) {
+ const refusal: Unchecked<GridAsleep> = body
+ if (refusal.code === GRID_ASLEEP_CODE) return { kind: 'asleep', lastKnown: parseLastKnown(refusal.last_known) }
}
// A 200 that is not an overview (a maintenance page, a proxy's own JSON) is not "awake with nothing":
// read as that, it would count as an empty answer and start taking models off every list.
- if (status !== 200 || !isObject(body) || !Array.isArray(body.nodes)) return { kind: 'unanswered' }
- const curatedIds = Array.isArray(body.models)
- ? body.models.filter(isObject).map((entry) => text(entry.id)).filter(Boolean).slice(0, MAX_IDS)
+ if (status !== 200 || !isObject(body)) return { kind: 'unanswered' }
+ const overview: Unchecked<GridOverview> = body
+ if (!Array.isArray(overview.nodes)) return { kind: 'unanswered' }
+ const curatedIds = Array.isArray(overview.models)
+ ? overview.models.filter(isObject).map((entry: Unchecked<OverviewModel>) => text(entry.id)).filter(Boolean)
+ .slice(0, MAX_IDS)
: []
- const rawNodes = body.nodes.filter(isObject).slice(0, MAX_NODES)
- return { kind: 'awake', nodes: readNodes(rawNodes), curatedIds, rawNodes, windows: readWindows(body.models, rawNodes) }
+ const rawNodes = overview.nodes.filter(isObject).slice(0, MAX_NODES)
+ return { kind: 'awake', nodes: readNodes(rawNodes), curatedIds, rawNodes, windows: readWindows(overview.models, rawNodes) }
}
/** No model's window is this large; a number past it is not one. */
@@ -224,11 +229,14 @@ function readWindows(curated: unknown, nodes: Array<Record<string, unknown>>): R
if (Object.keys(windows).length >= MAX_IDS && !(key in windows)) return
windows[key] = Math.max(windows[key] ?? 0, value)
}
- if (Array.isArray(curated)) for (const entry of curated.filter(isObject)) take(entry.id, entry.context_length)
- for (const node of nodes) {
+ if (Array.isArray(curated)) {
+ for (const entry of curated.filter(isObject) as Array<Unchecked<OverviewModel>>) take(entry.id, entry.context_length)
+ }
+ for (const raw of nodes) {
+ const node: Unchecked<OverviewNode> = raw
const capabilities = isObject(node.model_capabilities) ? node.model_capabilities : {}
for (const [id, cell] of Object.entries(capabilities).slice(0, MAX_MODELS_PER_NODE)) {
- if (isObject(cell)) take(id, cell.context_length)
+ if (isObject(cell)) take(id, (cell as Unchecked<NodeModelCapability>).context_length)
}
}
return windows
@@ -247,16 +255,18 @@ export function displayModelName(raw: string): string {
*/
export async function readDiscoveryIds(base: string): Promise<string[]> {
try {
- const { status, body } = await get(base, GRID_DISCOVER_PATH, 'read')
- if (status !== 200 || !isObject(body) || !Array.isArray(body.providers)) return []
+ const { status, body } = await get(base, DISCOVER_PATH, 'read')
+ if (status !== 200 || !isObject(body)) return []
+ const discovery: Unchecked<ProviderDiscovery> = body
+ if (!Array.isArray(discovery.providers)) return []
const ids: string[] = []
- for (const provider of body.providers.filter(isObject)) {
- const capabilities = isObject(provider.capabilities) ? provider.capabilities : {}
+ for (const provider of discovery.providers.filter(isObject) as Array<Unchecked<DiscoveredProvider>>) {
+ const capabilities: Unchecked<DiscoveredCapabilities> = isObject(provider.capabilities) ? provider.capabilities : {}
const entries = isObject(capabilities.models) ? capabilities.models : {}
if (!Array.isArray(provider.models)) continue
for (const route of provider.models) {
const entry = typeof route === 'string' ? entries[route] : undefined
- const raw = isObject(entry) ? text(entry.raw_model_id) : ''
+ const raw = isObject(entry) ? text((entry as Unchecked<DiscoveredModel>).raw_model_id) : ''
if (raw) ids.push(displayModelName(raw))
}
}
@@ -296,7 +306,7 @@ function envelopeCode(stderr: string): string | null {
* "no read" — a stale list, which is the direction every failure here must take.
*/
export async function readViaCli(gridName: string): Promise<GridRead> {
- const result = await gridExec(['--remote', 'models', gridName, GRID_NO_WAKE_FLAG, '--json'])
+ const result = await gridExec(['--remote', 'models', gridName, NO_WAKE_FLAG, '--json'])
if (result.code !== 'OK') {
return envelopeCode(result.stderr) === GRID_ASLEEP_CODE ? { kind: 'asleep', lastKnown: null } : { kind: 'unanswered' }
}