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.

Local models: the longest context that runs, never under 64K, told to every agent

bitcoinbuilder5dd92c6bca86
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index dd8cf40bf..dcb0f75d2 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -74,6 +74,15 @@ describe('parseGridLaunchOverride', () => {
expect(parseGridLaunchOverride({ ...WIRE, model: ' ' }).state).toBe('invalid')
})
+ it('keeps a context window, and drops a malformed one without refusing the launch', () => {
+ // A hint, not a credential: a persisted launch whose window is garbled must still relaunch.
+ expect(parseGridLaunchOverride({ ...WIRE, contextWindow: 131072 }))
+ .toEqual({ state: 'ok', override: { ...OVERRIDE, contextWindow: 131072 } })
+ for (const contextWindow of ['131072', 1.5, -1, 0, 100, 2 ** 40, null]) {
+ expect(parseGridLaunchOverride({ ...WIRE, contextWindow })).toEqual({ state: 'ok', override: OVERRIDE })
+ }
+ })
+
it('refuses a grid that is not an object', () => {
expect(parseGridLaunchOverride('autonomous.ai').state).toBe('invalid')
expect(parseGridLaunchOverride([WIRE]).state).toBe('invalid')
@@ -326,8 +335,10 @@ describe('gridEnvVarNames', () => {
it('names every variable claude is launched with', () => {
// GRID_API_KEY among them: the probe asks for a launch with web tools, and moving an agent to
// another grid has to take the old grid's MCP credential out of the pane with everything else.
+ // CLAUDE_CODE_MAX_CONTEXT_TOKENS too: a window told for a grid model must not follow the agent
+ // back onto its own login, where it would describe a model it is no longer talking to.
expect(gridEnvVarNames('claude').sort())
- .toEqual(['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL', 'GRID_API_KEY'])
+ .toEqual(['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL', 'CLAUDE_CODE_MAX_CONTEXT_TOKENS', 'GRID_API_KEY'])
})
it("names the scope Hermes' web tools are written into", () => {
@@ -483,12 +494,24 @@ describe('opencode declares the grid as a provider', () => {
expect(config().provider['autonomous-ai'].options.baseURL).toBe(base.baseUrl)
})
- it('omits `limit` entirely rather than writing half of one', () => {
+ it('omits `limit` entirely when the window is unknown, rather than writing half of one', () => {
// OpenCode requires `context` and `output` together and rejects the config given only one.
const models = config('DeepSeek-V4-Flash-0731').provider['autonomous-ai'].models
for (const entry of Object.values(models)) expect(entry).not.toHaveProperty('limit')
})
+ it.each([
+ [262144, 32000],
+ [131072, 32000],
+ [65536, 16384],
+ ])('writes both halves of `limit` for a %i window', (contextWindow, output) => {
+ // Without it OpenCode never knew how much room was left, and ran on until the relay refused.
+ const built = buildGridEngineLaunch('opencode', { ...base, model: 'Qwen', contextWindow }, PLAIN_MACHINE)
+ if (!built.ok) throw new Error('opencode refused')
+ const entry = JSON.parse(built.launch.configDir!.files[0].content).provider['autonomous-ai'].models.Qwen
+ expect(entry.limit).toEqual({ context: contextWindow, output })
+ })
+
it('points OPENCODE_CONFIG at the file, not at the directory holding it', () => {
expect(launch().configDir!.envVar).toBe('OPENCODE_CONFIG')
expect(launch().configDir!.pointAt).toBe('opencode.json')
@@ -829,3 +852,32 @@ describe('web search status — what the app is told about the launch it got', (
}
})
})
+
+describe('each engine is told the real context window', () => {
+ // ⚠️ Every one of these assumed a window for a model it did not recognise — Claude Code 200K, Pi
+ // 200K, Codex and OpenCode nothing — so none compacted before a smaller grid engine refused the
+ // request as too long, and the session died where it should have summarised.
+ const WITH_WINDOW: GridLaunchOverride = { ...WITH_MODEL, contextWindow: 131072 }
+
+ it('Claude Code, through the variable its docs give for unrecognised model ids', () => {
+ expect(launchOf('claude', WITH_WINDOW).env.CLAUDE_CODE_MAX_CONTEXT_TOKENS).toBe('131072')
+ expect(launchOf('claude', WITH_MODEL).env).not.toHaveProperty('CLAUDE_CODE_MAX_CONTEXT_TOKENS')
+ })
+
+ it('Codex, with the window and a compaction point inside it', () => {
+ const args = launchOf('codex', WITH_WINDOW).args
+ expect(args).toContain('model_context_window=131072')
+ expect(args).toContain('model_auto_compact_token_limit=117964')
+ expect(args[args.indexOf('model_context_window=131072') - 1]).toBe('-c')
+ expect(launchOf('codex', WITH_MODEL).args.join(' ')).not.toContain('model_context_window')
+ })
+
+ it('Pi, in the window its models file declares', () => {
+ const models = (launch: ReturnType<typeof launchOf>) =>
+ JSON.parse(launch.configDir!.files.find((f) => f.name === 'models.json')!.content)
+ const [model] = Object.values<any>(models(launchOf('pi', WITH_WINDOW)).providers)[0].models
+ expect(model.contextWindow).toBe(131072)
+ const [unknown] = Object.values<any>(models(launchOf('pi', WITH_MODEL)).providers)[0].models
+ expect(unknown.contextWindow).toBe(200000)
+ })
+})
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index 1ca1be3c3..cadc1b363 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -111,6 +111,34 @@ export interface GridLaunchOverride {
* Absent means no web tools, which is exactly what an older desktop sends.
*/
mcpUrl?: string
+ /**
+ * The model's context window in tokens, as the grid's relay reports it (`context_window` on its
+ * `/models` row) — the size the engine serving it was actually started with.
+ *
+ * ⚠️ Every coding agent here assumes a window for a model it does not recognise, and a grid model
+ * is never one it recognises: Claude Code assumes 200K, Codex and OpenCode know nothing at all. An
+ * agent that does not know the real window never compacts before it — the server rejects the
+ * request as too long first, and the session dies where it should have summarised. So each engine
+ * is TOLD, in its own dialect ([contextWindowHint] and the contracts below).
+ *
+ * Absent means the relay did not say, and each engine keeps its own assumption, as before.
+ */
+ contextWindow?: number
+}
+
+/** The smallest window believed. Anything below it is not a model a coding agent can run on, and a
+ * value that small is likelier a misreport than a real engine — better to say nothing than to have
+ * an agent compact every turn. */
+const MIN_CONTEXT_WINDOW = 4096
+/** The largest believed: no engine serves more, and a bigger number is a unit error. */
+const MAX_CONTEXT_WINDOW = 16 * 1024 * 1024
+
+/** A context window worth handing an engine, or undefined. Lenient on purpose, unlike every other
+ * field here: this is a hint, and a malformed one must cost only the hint — refusing the whole
+ * override would strand a persisted launch that is otherwise fine. */
+export function contextWindowHint(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= MIN_CONTEXT_WINDOW && value <= MAX_CONTEXT_WINDOW
+ ? value : undefined
}
export type GridOverrideParse =
@@ -184,6 +212,7 @@ export function parseGridLaunchOverride(raw: unknown): GridOverrideParse {
if (hasMcpUrl && !mcpUrl) return { state: 'invalid', reason: 'grid mcpUrl must be a non-empty string' }
const badMcpUrl = mcpUrl ? urlProblem('mcpUrl', mcpUrl) : null
if (badMcpUrl) return { state: 'invalid', reason: badMcpUrl }
+ const contextWindow = contextWindowHint(source.contextWindow)
return {
state: 'ok',
override: {
@@ -193,6 +222,7 @@ export function parseGridLaunchOverride(raw: unknown): GridOverrideParse {
apiKey: apiKey as string,
...(model ? { model } : {}),
...(mcpUrl ? { mcpUrl } : {}),
+ ...(contextWindow ? { contextWindow } : {}),
},
}
}
@@ -263,11 +293,21 @@ export function gridProviderId(networkName: string): string {
* the literal is recommended, because an unset variable silently becomes an empty string and a
* human-launched OpenCode has no guarantee the variable is set. Here it IS guaranteed: the
* daemon puts it in the pane's environment with `tmux new-session -e` before the engine starts.
- * 4. **No `limit` block.** OpenCode requires `context` and `output` TOGETHER and rejects the config
- * if only one is present. The relay reports a context window per model but this module is not
- * the thing that read it, and inventing one would be worse than the defaults OpenCode already
- * uses.
+ * 4. **`limit` only when the window is known, and then BOTH halves.** OpenCode requires `context`
+ * and `output` together and rejects the config given only one. It is how OpenCode knows how much
+ * room is left, so without it a session ran on until the relay refused a request as too long,
+ * never having compacted. Absent when the relay did not report a window: inventing one would be
+ * worse than OpenCode's own defaults. `output` is a quarter of the window, capped at OpenCode's
+ * own 32K output ceiling — it is also what OpenCode holds back from the window for the reply, so
+ * a larger share would compact a small window after every other turn.
*/
+/** OpenCode's own ceiling on a reply, which it also reserves out of the window. */
+const OPENCODE_OUTPUT_MAX = 32_000
+
+function opencodeOutputLimit(contextWindow: number): number {
+ return Math.min(OPENCODE_OUTPUT_MAX, Math.floor(contextWindow / 4))
+}
+
function opencodeGridConfig(
provider: string,
override: GridLaunchOverride,
@@ -282,7 +322,14 @@ function opencodeGridConfig(
// may rewrite. One model here makes the answer a fact about a file that cannot change under us.
//
// Choosing a different model is what every other engine here does too: per agent, at creation.
- const models: Record<string, { name: string }> = { [model]: { name: model } }
+ const models: Record<string, { name: string; limit?: { context: number; output: number } }> = {
+ [model]: {
+ name: model,
+ ...(override.contextWindow
+ ? { limit: { context: override.contextWindow, output: opencodeOutputLimit(override.contextWindow) } }
+ : {}),
+ },
+ }
return `${JSON.stringify({
$schema: 'https://opencode.ai/config.json',
provider: {
@@ -514,7 +561,7 @@ export function gridConflictingEnvToClear(launch: Pick<GridEngineLaunch, 'env' |
* serves. The context/cost numbers are Pi's own bookkeeping for its display; the grid decides what
* the model really takes.
*/
-function piModelsJson(baseUrl: string, model: string): string {
+function piModelsJson(baseUrl: string, model: string, contextWindow?: number): string {
return JSON.stringify({
providers: {
[GRID_PROVIDER_ID]: {
@@ -528,7 +575,9 @@ function piModelsJson(baseUrl: string, model: string): string {
name: model,
reasoning: false,
input: ['text'],
- contextWindow: 200000,
+ // The real window when the relay reported one — the same fault as every engine here:
+ // told 200K, Pi never compacted before a smaller server refused the request.
+ contextWindow: contextWindow ?? 200000,
maxTokens: 8192,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
}],
@@ -574,6 +623,11 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// has no standing to choose a user's model. That reasoning does not carry here: the desktop
// app ASKED, and this is the answer. Left unset when the user picked no model.
...(override.model ? { ANTHROPIC_MODEL: override.model } : {}),
+ // The window to compact within. A grid model's id is one Claude Code does not recognise, so
+ // it assumes 200K and compacts only near that — on a smaller server, never, because the
+ // server refuses the request first. This is the documented variable for exactly that
+ // case (code.claude.com/docs/en/model-config, "unrecognized model IDs").
+ ...(override.contextWindow ? { CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(override.contextWindow) } : {}),
// Only when there are web tools to reach: the variable exists to be referenced by the config
// below, and setting it otherwise would leave a key in the pane that nothing reads.
...(override.mcpUrl ? { [GRID_KEY_VAR]: override.apiKey } : {}),
@@ -625,6 +679,15 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
...CODEX_DISABLE_WEB_SEARCH_ARGS,
...(override.mcpUrl ? codexMcpArgs(override.mcpUrl) : []),
...(override.model ? ['-m', override.model] : []),
+ // The window, and where to compact inside it. Codex knows neither for a model it does not
+ // recognise, so it never compacted and the relay refused the request as too long instead.
+ // 90% leaves the summary request itself room to fit.
+ ...(override.contextWindow
+ ? [
+ '-c', `model_context_window=${override.contextWindow}`,
+ '-c', `model_auto_compact_token_limit=${Math.floor(override.contextWindow * 0.9)}`,
+ ]
+ : []),
],
webSearch: webSearchWhenWired(override),
}),
@@ -839,7 +902,7 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
configDir: {
envVar: 'PI_CODING_AGENT_DIR',
files: [
- { name: 'models.json', content: piModelsJson(relayBaseUrl(override.baseUrl), model) },
+ { name: 'models.json', content: piModelsJson(relayBaseUrl(override.baseUrl), model, override.contextWindow) },
{ name: 'settings.json', content: piSettingsJson(userPiSkillsDir()) },
],
},
@@ -977,6 +1040,9 @@ const PROBE_OVERRIDE: GridLaunchOverride = {
// this answers, and a probe that left them out would move an agent to another grid while its old
// grid's MCP credential stayed in the pane — the exact staleness the doc comment below warns of.
mcpUrl: 'https://example.invalid/v1/grid/web-mcp/',
+ // Present for the same reason: a launch that knew its window sets a variable (Claude Code's), and
+ // moving back to the own login must take it out of the pane with the rest.
+ contextWindow: 131072,
}
/**
diff --git a/cli/src/lib/gridModels.spec.ts b/cli/src/lib/gridModels.spec.ts
index 0221a2d02..71e9e9bdd 100644
--- a/cli/src/lib/gridModels.spec.ts
+++ b/cli/src/lib/gridModels.spec.ts
@@ -3,7 +3,7 @@
* resolved target carries. There was no spec for this module before web tools gave it a second
* subprocess whose ORDER matters — `mcp config` renews the token, `info --env` reads it.
*/
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { fakeGridAnswers, installFakeGrid, type FakeGrid, type FakeGridPlan } from './__fixtures__/fakeGrid.js'
import { clearGridMcpUrlCache } from './gridMcpUrl.js'
import { resolveGridTarget } from './gridModels.js'
@@ -16,11 +16,22 @@ function install(overrides: FakeGridPlan = {}): FakeGrid {
return fake
}
+/** The relay's `/models`, answered here so no test reaches the network. Empty unless a test says. */
+let relayRows: unknown[] = []
+const relayFetch = vi.fn(async (_url: string | URL, _init?: RequestInit) =>
+ new Response(JSON.stringify({ data: relayRows }), { status: 200, headers: { 'content-type': 'application/json' } }))
+beforeEach(() => {
+ relayRows = []
+ relayFetch.mockClear()
+ vi.stubGlobal('fetch', relayFetch)
+})
+
afterEach(() => {
fake?.dispose()
fake = null
clearGridMcpUrlCache()
vi.restoreAllMocks()
+ vi.unstubAllGlobals()
})
describe('resolveGridTarget', () => {
@@ -63,6 +74,50 @@ describe('resolveGridTarget', () => {
expect(await resolveGridTarget(GRID, 'GLM-4.7-Flash')).toBeNull()
})
+ // ── the model's context window ─────────────────────────────────────────────────────────────────
+ //
+ // A coding agent compacts only inside the window it believes, and it believes nothing true about
+ // a grid model — so the target carries the relay's figure for the engine to be told.
+
+ it("carries the relay's context window for the chosen model", async () => {
+ install()
+ relayRows = [
+ { id: 'DeepSeek-V4-Flash-0731', context_window: 262144 },
+ { id: 'GLM-4.7-Flash', context_window: 131072 },
+ ]
+ const target = await resolveGridTarget(GRID, 'GLM-4.7-Flash')
+ expect(target?.contextWindow).toBe(131072)
+ // Asked of the relay the launch will talk to, with the credential it will use.
+ expect(String(relayFetch.mock.calls[0]![0])).toBe(`${BASE_URL.replace(/\/$/, '')}/models`)
+ })
+
+ it('matches the id without regard to case only when no exact row exists', async () => {
+ install()
+ relayRows = [{ id: 'glm-4.7-flash', context_window: 65536 }]
+ expect((await resolveGridTarget(GRID, 'GLM-4.7-Flash'))?.contextWindow).toBe(65536)
+ })
+
+ it.each([
+ ['the relay lists no window', [{ id: 'GLM-4.7-Flash' }]],
+ ['the window is not a number', [{ id: 'GLM-4.7-Flash', context_window: '131072' }]],
+ ['the window is implausibly small', [{ id: 'GLM-4.7-Flash', context_window: 512 }]],
+ ['the model is not listed', [{ id: 'Other', context_window: 131072 }]],
+ ])('resolves without a window when %s', async (_case, rows) => {
+ install()
+ relayRows = rows
+ const target = await resolveGridTarget(GRID, 'GLM-4.7-Flash')
+ expect(target).toMatchObject({ baseUrl: BASE_URL, model: 'GLM-4.7-Flash' })
+ expect(target).not.toHaveProperty('contextWindow')
+ })
+
+ it('resolves without a window when the relay cannot be asked', async () => {
+ install()
+ relayFetch.mockRejectedValueOnce(new Error('offline'))
+ const target = await resolveGridTarget(GRID, 'GLM-4.7-Flash')
+ expect(target).toMatchObject({ apiKey: TOKEN, model: 'GLM-4.7-Flash' })
+ expect(target).not.toHaveProperty('contextWindow')
+ })
+
it('asks nothing of `grid` without a grid name or a model', async () => {
const grid = install()
expect(await resolveGridTarget(null, 'GLM-4.7-Flash')).toBeNull()
diff --git a/cli/src/lib/gridModels.ts b/cli/src/lib/gridModels.ts
index a18151326..8449a852a 100644
--- a/cli/src/lib/gridModels.ts
+++ b/cli/src/lib/gridModels.ts
@@ -6,6 +6,7 @@
* a person, and what an agent is told to ask for.
*/
import { gridExec, gridJson } from './gridExec.js'
+import { contextWindowHint } from './gridLaunch.js'
import { resolveGridMcpUrl } from './gridMcpUrl.js'
/** A row of `grid models --json`. `node` names the machine serving it — on a private grid, one of
@@ -158,14 +159,26 @@ async function relayModelIds(gridName: string): Promise<string[]> {
if (info.code !== 'OK') return []
const env = readEnvExports(info.stdout)
if (!env.baseUrl || !env.apiKey) return []
+ return (await relayModels(env.baseUrl, env.apiKey)).map((m) => m.id)
+}
+
+/** A row of the relay's `/models`: the id it routes, and the context window it reports for it. */
+interface RelayModel { id: string; contextWindow?: number }
+
+/** The relay's own catalogue. Empty when it cannot be asked — callers read that as "fall back". */
+async function relayModels(baseUrl: string, apiKey: string): Promise<RelayModel[]> {
try {
- const response = await fetch(`${env.baseUrl.replace(/\/$/, '')}/models`, {
- headers: { authorization: `Bearer ${env.apiKey}` },
+ const response = await fetch(`${baseUrl.replace(/\/$/, '')}/models`, {
+ headers: { authorization: `Bearer ${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)
+ const body = await response.json() as { data?: Array<{ id?: unknown; context_window?: unknown }> }
+ return (body.data ?? []).flatMap((m) => {
+ if (typeof m.id !== 'string' || !m.id) return []
+ const contextWindow = contextWindowHint(m.context_window)
+ return [{ id: m.id, ...(contextWindow ? { contextWindow } : {}) }]
+ })
} catch {
return []
}
@@ -186,6 +199,9 @@ export interface GridTarget {
/** The control plane's web-tools MCP endpoint. Absent when it could not be obtained; the agent
* then runs on the grid with no web tools, and the daemon log says why. */
mcpUrl?: string
+ /** The model's context window as the relay reports it, so the engine can be told to compact
+ * inside it (`GridLaunchOverride.contextWindow`). Absent when the relay did not say. */
+ contextWindow?: number
}
/**
@@ -214,9 +230,15 @@ export async function resolveGridTarget(gridName: string | null, model: string):
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'])
+ // unique on this account and is all the launch actually needs to be re-derivable. The relay's
+ // catalogue alongside it, not after: it is only for the window, and a click waits on both.
+ const [{ value: rows }, served] = await Promise.all([
+ gridJson<Array<{ grid?: unknown; id?: unknown }>>(['--remote', 'ls']),
+ relayModels(baseUrl, apiKey),
+ ])
const row = Array.isArray(rows) ? rows.find((r) => r.grid === gridName) : undefined
+ // Exact first: the relay is case-sensitive about ids and the picker sends the relay's spelling.
+ const listed = served.find((m) => m.id === model) ?? served.find((m) => m.id.toLowerCase() === model.toLowerCase())
return {
networkId: typeof row?.id === 'string' ? row.id : gridName,
networkName: gridName,
@@ -224,6 +246,7 @@ export async function resolveGridTarget(gridName: string | null, model: string):
apiKey,
model,
...(mcpUrl ? { mcpUrl } : {}),
+ ...(listed?.contextWindow ? { contextWindow: listed.contextWindow } : {}),
}
}
diff --git a/cli/src/lib/localModels.integration.spec.ts b/cli/src/lib/localModels.integration.spec.ts
index fe050a41b..ac6487224 100644
--- a/cli/src/lib/localModels.integration.spec.ts
+++ b/cli/src/lib/localModels.integration.spec.ts
@@ -20,7 +20,7 @@ it('discovers, downloads, starts, verifies, stops and restarts across real subpr
expect(body.device.usable_bytes).toBe(16 * 1024 ** 3)
catalogReads++
res.end(JSON.stringify({ models: [{ repo_id: modelId, runnable: true, task: 'text-generation', format: 'GGUF',
- fit: { version: 'Q4', ctx: 4096 }, versions: [{ version: 'Q4', size_bytes: 64, pull_spec: `${modelId}:tiny.gguf` }] }] }))
+ fit: { version: 'Q4', ctx: 131072 }, versions: [{ version: 'Q4', size_bytes: 64, pull_spec: `${modelId}:tiny.gguf` }] }] }))
} else {
expect(req.url).toBe('/v1/chat/completions')
expect(req.headers.authorization).toBe('Bearer inference-fixture')
diff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.ts
index 111fcda90..0650c7312 100644
--- a/cli/src/lib/localModels.spec.ts
+++ b/cli/src/lib/localModels.spec.ts
@@ -4,12 +4,12 @@ import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { createHash } from 'node:crypto'
import { rmSync, writeFileSync } from 'node:fs'
-import { compatibleModels, LocalModels } from './localModels.js'
+import { compatibleModels, contextLadder, LocalModels } from './localModels.js'
import { GridFleetRpc, type GridFleetResult } from './gridFleetRpc.js'
import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'
const card = (id = 'org/Small-GGUF') => ({ repo_id: id, runnable: true, task: 'text-generation', format: 'GGUF',
- fit: { version: 'Q4', ctx: 32768, size: 64 },
+ fit: { version: 'Q4', ctx: 131072, size: 64 },
versions: [{ version: 'Q4', size_bytes: 64, pull_spec: `${id}:Small-Q4.gguf`, urls: ['https://example.test/Small-Q4.gguf'] }] })
const ok = (value: unknown = {}) => ({ ok: true, code: 0, stdout: JSON.stringify(value), stderr: '', error: null })
const response = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } })
@@ -21,6 +21,12 @@ let downloadFails: boolean, catalogFails: boolean
/** What `grid info` says of the grid. Down (`stopped`/`asleep`) refuses `engines` and `join`, as
* the real grid does, until `grid start` brings it back. */
let gridState: 'running' | 'stopped' | 'asleep'
+/** What `grid ctx FILE` reads from a file's header (null: the command fails), and the window the
+ * serving engine reports once started (undefined: Grid does not say). */
+let trainedWindow: number | null, servedWindow: number | undefined
+/** The relay's own test request — as opposed to the probe sent straight to the engine on this
+ * machine (`127.0.0.1`), which a start now makes first. */
+const RELAY_CHAT = 'inference.example.test/v1/chat/completions'
const refused = (message: string) => ({ ok: false, code: 1, stdout: '', stderr: message, error: 'Grid command failed.' })
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'local-models-'))
@@ -28,6 +34,7 @@ beforeEach(async () => {
await mkdir(records, { recursive: true }); await mkdir(join(home, 'models'))
await writeFile(join(home, 'credentials.toml'), 'session_token = "test-only-token"\napi_url = "https://catalog.example.test"\n')
calls = []; serving = false; catalogCards = [card()]; downloadFails = false; catalogFails = false; gridState = 'running'
+ trainedWindow = null; servedWindow = undefined
run = vi.fn(async (args: string[], output?: (s: string) => void) => {
calls.push(args)
if (args[0] === 'device-info') return ok({ device_class: 'apple-silicon', backend: 'metal', usable_bytes: 54 * 1024 ** 3, memory: { total_gb: 64 } })
@@ -36,7 +43,9 @@ beforeEach(async () => {
if (args[1] === 'start') { gridState = 'running'; return ok() }
const down = gridState !== 'running'
if (down && (args.includes('engines') || args.includes('join'))) return refused("Grid home isn't up; run `grid start home` first.")
+ if (args[0] === 'ctx') return trainedWindow === null ? refused('no header') : ok({ file: args[1], context_length: trainedWindow })
if (args.includes('engines')) return ok(serving ? [{ node_id: 'local-node', online: true, models: ['Small-Q4.gguf'], throughput_tok_s: 17.6,
+ ...(servedWindow === undefined ? {} : { model_capabilities: { 'small-q4': { context_length: servedWindow, vision: false } } }),
vram_used_mb: 99999, answered: { window_seconds: 3600, requests: 4, by_model: [{ model: 'Small-Q4.gguf', requests: 4 }] } }] : [])
if (args[0] === 'pull') {
output?.('42%')
@@ -102,8 +111,8 @@ describe('local model discovery and lifecycle', () => {
expect(snapshot.models[0]).toMatchObject({ state: 'running', canStop: true,
tokensPerSecond: 17.6, requests: 4, windowSeconds: 3600, operation: { phase: 'done', stage: 'verifying' } })
expect(snapshot.models[0]).not.toHaveProperty('memoryBytes')
- expect(calls.find(args => args.includes('join'))).toEqual(['--remote', 'join', 'home', '--serve', 'Small-Q4.gguf', '--max-concurrency', '1', '--ctx-size', '16384', '--reasoning-budget', '0'])
- expect(request.mock.calls.some(([url]) => String(url).includes('chat/completions'))).toBe(true)
+ expect(calls.find(args => args.includes('join'))).toEqual(['--remote', 'join', 'home', '--serve', 'Small-Q4.gguf', '--max-concurrency', '1', '--ctx-size', '131072', '--endpoint-port', expect.stringMatching(/^\d+$/), '--reasoning-budget', '0'])
+ expect(request.mock.calls.some(([url]) => String(url).includes(RELAY_CHAT))).toBe(true)
expect(await readFile(join(stateDir, (await readdir(stateDir))[0]), 'utf8')).not.toContain('token')
})
@@ -138,12 +147,12 @@ describe('local model discovery and lifecycle', () => {
let release!: () => void
const barrier = new Promise<void>(resolve => { release = resolve })
const original = request.getMockImplementation()!
- request.mockImplementation(async (url, init) => { if (String(url).includes('chat/completions')) await barrier; return original(url, init) })
+ request.mockImplementation(async (url, init) => { if (String(url).includes(RELAY_CHAT)) await barrier; return original(url, init) })
const first = await service.act('home', 'org/Small-GGUF', 'start')
const second = await service.act('home', 'org/Small-GGUF', 'start')
expect(second.operation?.id).toBe(first.operation?.id)
expect((await service.act('home', 'other', 'start')).error).toContain('Wait')
- await vi.waitFor(() => expect(request.mock.calls.some(([url]) => String(url).includes('chat/completions'))).toBe(true))
+ await vi.waitFor(() => expect(request.mock.calls.some(([url]) => String(url).includes(RELAY_CHAT))).toBe(true))
expect((await service.list('home')).models[0].operation).toMatchObject({ stage: 'verifying', phase: 'running' })
release(); await service.settled()
expect(calls.filter(args => args.includes('join'))).toHaveLength(1)
@@ -236,6 +245,8 @@ describe('local model discovery and lifecycle', () => {
const path = join(stateDir, (await readdir(stateDir)).find(name => name.endsWith('.known.json'))!)
const saved = JSON.parse(await readFile(path, 'utf8'))
expect(saved[0].aliases).toEqual(['team/my-model'])
+ // What receipts from before the 64K floor carried: a pinned 16K that must not be replayed.
+ saved[0].context = 16384
if (scenario === 'legacy') delete saved[0].aliases
if (scenario === 'malformed') saved[0].aliases = [42, '', '--invalid', 'invalid\nname']
await writeFile(path, JSON.stringify(saved))
@@ -243,8 +254,11 @@ describe('local model discovery and lifecycle', () => {
await fresh.act('home', id, 'start'); await fresh.settled()
const expectedAlias = scenario === 'current' ? 'team/my-model' : scenario === 'legacy' ? 'my-model' : null
const joined = calls.find(args => args.includes('join'))!
- expect(joined.slice(11)).toEqual(expectedAlias ? ['--advertise-as', expectedAlias] : [])
- const inference = request.mock.calls.find(([url]) => String(url).includes('chat/completions'))!
+ expect(joined.slice(joined.indexOf('--reasoning-budget') + 2)).toEqual(expectedAlias ? ['--advertise-as', expectedAlias] : [])
+ // Not sized by any catalog and its header unread here, so the start begins at 128K — and a
+ // receipt's saved context, which older ones pinned at 16K, is never replayed.
+ expect(joined[joined.indexOf('--ctx-size') + 1]).toBe('131072')
+ const inference = request.mock.calls.find(([url]) => String(url).includes(RELAY_CHAT))!
expect(JSON.parse(String(inference[1]?.body)).model).toBe(expectedAlias ?? 'Small-Q4.gguf')
expect((await fresh.list('home')).models[0].operation?.phase).toBe('done')
})
@@ -598,7 +612,7 @@ describe('local model discovery and lifecycle', () => {
await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
expect(calls.filter(args => args.includes('join'))).toHaveLength(1)
- expect(request.mock.calls.filter(([url]) => String(url).includes('chat/completions'))).toHaveLength(2)
+ expect(request.mock.calls.filter(([url]) => String(url).includes(RELAY_CHAT))).toHaveLength(2)
})
it.each([false, true])('handles an explicit engine override (available=%s)', async available => {
@@ -616,7 +630,7 @@ describe('local model discovery and lifecycle', () => {
run.mockImplementation(async (args, output) => args.includes('info') ? ok() : original(args, output))
await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
expect((await service.list('home')).models[0].operation?.phase).toBe('failed')
- expect(request.mock.calls.some(([url]) => String(url).includes('chat/completions'))).toBe(false)
+ expect(request.mock.calls.some(([url]) => String(url).includes(RELAY_CHAT))).toBe(false)
})
it.each(['reasoning only', 'http error', 'network error'])('requires a real test reply and bounds retries for %s', async scenario => {
@@ -624,7 +638,8 @@ describe('local model discovery and lifecycle', () => {
let attempted!: () => void
const first = new Promise<void>(resolve => { attempted = resolve })
request.mockImplementation(async (url, init) => {
- if (String(url).includes('/catalog')) return original(url, init)
+ // The catalog, and the engine on this machine, answer normally: this is about the RELAY check.
+ if (String(url).includes('/catalog') || String(url).includes('127.0.0.1')) return original(url, init)
attempted()
if (scenario === 'network error') throw new Error('private-token')
return scenario === 'http error' ? new Response('private-token', { status: 503 })
@@ -756,3 +771,156 @@ describe('local model discovery and lifecycle', () => {
expect((await service.list('home')).models[0]).toMatchObject({ name: 'Small-Q4', state: 'running', operation: { phase: 'failed' } })
})
})
+
+describe('a context a coding agent can work in', () => {
+ // ⚠️ REGRESSION. Every model was offered and started at 16K or less — a model that loads, passes
+ // its one-word check, and then cannot hold a coding agent's first prompt. Codex, Claude Code and
+ // OpenCode all need 64K at the least; the most this machine can give is what a start now asks for.
+
+ it.each([
+ [32768, false], [65535, false], [65536, true], [262144, true],
+ ])("a catalog fit of %i on this machine is offered: %s", async (ctx, offered) => {
+ catalogCards[0].fit.ctx = ctx
+ expect((await service.list('home')).models.length).toBe(offered ? 1 : 0)
+ })
+
+ it('pins the whole fit, capped at the most the model was trained for', async () => {
+ Object.assign(catalogCards[0].fit, { ctx: 262144, max_ctx: 196608 })
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ const joined = calls.find(args => args.includes('join'))!
+ expect(joined[joined.indexOf('--ctx-size') + 1]).toBe('196608')
+ })
+
+ it('shrinks to what fits at start when memory has since tightened, but never under 64K', async () => {
+ catalogCards[0].fit.ctx = 262144
+ await service.list('home')
+ catalogCards[0].fit.ctx = 98304
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ const joined = calls.find(args => args.includes('join'))!
+ expect(joined[joined.indexOf('--ctx-size') + 1]).toBe('98304')
+ })
+
+ it('refuses to start at all when the fit at start is under 64K', async () => {
+ await service.list('home')
+ catalogCards[0].fit.ctx = 32768
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ expect(calls.some(args => args.includes('join'))).toBe(false)
+ expect((await service.list('home')).models[0].operation).toMatchObject({ phase: 'failed', error: expect.stringContaining('make room') })
+ })
+
+ it('hides a model on disk whose file can never hold 64K, and keeps one it cannot read', async () => {
+ catalogCards = []; serving = true
+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))
+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', engines: [{ models: ['Small-Q4.gguf'] }] }))
+ await writeFile(join(records, 'remote.heartbeat'), '')
+ const id = (await service.list('home')).models[0].id
+ await service.act('home', id, 'stop'); await service.settled()
+ // Unreadable header: unknown is not "too small".
+ expect((await service.list('home', true)).models.map(m => m.id)).toEqual([id])
+ trainedWindow = 32768
+ const fresh = new LocalModels({ stateDir, processEnv: { GRID_HOME: home }, run, request: request as typeof fetch })
+ expect((await fresh.list('home')).models).toEqual([])
+ })
+
+ it.each([
+ [131072, 'done'], [undefined, 'done'], [32768, 'failed'],
+ ] as const)('after a start that served %s tokens, the start is %s', async (window, phase) => {
+ servedWindow = window
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ const operation = (await service.list('home', true)).models[0].operation
+ expect(operation?.phase).toBe(phase)
+ if (phase === 'failed') {
+ // Served too small: taken back down rather than left answering prompts it cannot hold.
+ expect(calls.find(args => args.includes('leave'))).toEqual(['--remote', 'leave', 'home', '--engine', 'Small-Q4.gguf'])
+ expect(operation?.error).toBe('Small could only get a 32K context here. Coding agents need at least 64K. Close some apps, or choose a smaller model.')
+ } else {
+ expect(calls.some(args => args.includes('leave'))).toBe(false)
+ }
+ })
+})
+
+describe('stepping down to the context that actually runs', () => {
+ // ⚠️ REGRESSION, measured on a 64 GB M1 Max. Left to the engine, a 35B model took its whole
+ // trained 256K, loaded, and then failed its very first request — "Insufficient Memory
+ // (kIOGPUCommandBufferCallbackErrorOutOfMemory)", then "Compute error." for every request after.
+ // The relay check waited three minutes and said only "did not answer". The same file ran at 128K.
+
+ const joinedAt = () => calls.filter(args => args.includes('join')).map(args => Number(args[args.indexOf('--ctx-size') + 1]))
+ /** The engine on this machine runs out of memory at any context above [limit]. */
+ const gpuHolds = (limit: number) => {
+ const original = request.getMockImplementation()!
+ request.mockImplementation(async (url, init) => {
+ if (String(url).includes('127.0.0.1') && String(url).endsWith('/chat/completions') && joinedAt().at(-1)! > limit) {
+ return new Response(JSON.stringify({ error: { code: 500, message: 'Compute error.', type: 'server_error' } }), { status: 500 })
+ }
+ return original(url, init)
+ })
+ }
+
+ it('halves to the 64K floor and no further', () => {
+ expect(contextLadder(262144)).toEqual([262144, 131072, 65536])
+ expect(contextLadder(196608)).toEqual([196608, 98304, 65536])
+ expect(contextLadder(100000)).toEqual([100000, 65536])
+ expect(contextLadder(65536)).toEqual([65536])
+ expect(contextLadder(50000)).toEqual([])
+ })
+
+ it('takes a size the GPU cannot run back down, and settles on the next that does', async () => {
+ catalogCards[0].fit.ctx = 262144
+ gpuHolds(131072)
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ expect(joinedAt()).toEqual([262144, 131072])
+ // Down between the two, and Grid's registration restored before the second join.
+ const between = calls.slice(calls.findIndex(a => a.includes('join')) + 1, calls.findLastIndex(a => a.includes('join')))
+ expect(between).toContainEqual(['--remote', 'leave', 'home', '--engine', 'Small-Q4.gguf'])
+ expect(between).toContainEqual(['--remote', 'sync'])
+ expect((await service.list('home', true)).models[0]).toMatchObject({ state: 'running', operation: { phase: 'done' } })
+ })
+
+ it('says it is memory, in words, when not even 64K runs — without waiting on the relay', async () => {
+ catalogCards[0].fit.ctx = 262144
+ gpuHolds(0)
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ expect(joinedAt()).toEqual([262144, 131072, 65536])
+ expect(request.mock.calls.some(([url]) => String(url).includes(RELAY_CHAT))).toBe(false)
+ expect((await service.list('home', true)).models[0].operation).toMatchObject({ phase: 'failed',
+ error: 'This computer does not have the memory to run Small with a 64K context. Close some apps, or choose a smaller model.' })
+ })
+
+ it('steps down from a size whose join fails, since a failed allocation at load looks like that', async () => {
+ catalogCards[0].fit.ctx = 262144
+ const original = run.getMockImplementation()!
+ run.mockImplementation(async (args, output) => args.includes('join') && args.includes('262144') ? refused('engine exited') : original(args, output))
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ const joins = run.mock.calls.map(([args]) => args).filter(args => args.includes('join'))
+ expect(joins.map(a => a[a.indexOf('--ctx-size') + 1])).toEqual(['262144', '131072'])
+ expect((await service.list('home', true)).models[0].operation?.phase).toBe('done')
+ })
+
+ it.each([
+ ['nothing is listening on this machine', () => { throw new Error('ECONNREFUSED') }],
+ ['the engine fails for another reason', () => new Response('{"error":{"message":"template error"}}', { status: 500 })],
+ // Not a load in progress (503), so not waited on for ten minutes.
+ ['its health check answers something unexpected', () => new Response('teapot', { status: 418 })],
+ ])('leaves the judgement to the relay check when %s', async (_case, answer) => {
+ const original = request.getMockImplementation()!
+ request.mockImplementation(async (url, init) => String(url).includes('127.0.0.1') ? answer() : original(url, init))
+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()
+ expect(joinedAt()).toEqual([131072])
+ expect(request.mock.calls.some(([url]) => String(url).includes(RELAY_CHAT))).toBe(true)
+ expect((await service.list('home', true)).models[0].operation?.phase).toBe('done')
+ })
+
+ it('starts a file on disk at the most its header says it holds', async () => {
+ catalogCards = []; serving = true
+ await writeFile(join(home, 'models', 'Small-Q4.gguf'), Buffer.alloc(64))
+ await writeFile(join(records, 'remote.json'), JSON.stringify({ node_id: 'local-node', engines: [{ models: ['Small-Q4.gguf'] }] }))
+ await writeFile(join(records, 'remote.heartbeat'), '')
+ const id = (await service.list('home')).models[0].id
+ await service.act('home', id, 'stop'); await service.settled()
+ trainedWindow = 262144
+ const fresh = new LocalModels({ stateDir, processEnv: { GRID_HOME: home }, run, request: request as typeof fetch })
+ await fresh.act('home', id, 'start'); await fresh.settled()
+ expect(joinedAt()).toEqual([262144])
+ })
+})
diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.ts
index 8291f4694..2e38d0c9b 100644
--- a/cli/src/lib/localModels.ts
+++ b/cli/src/lib/localModels.ts
@@ -2,6 +2,7 @@
* download and process authority. A click is a durable daemon operation, never a chat task. */
import { createHash, randomUUID } from 'node:crypto'
import { readFile, readdir, stat, mkdir, rename, writeFile, statfs } from 'node:fs/promises'
+import { createServer, type AddressInfo } from 'node:net'
import { basename, dirname, join } from 'node:path'
import { GridFleetRpc, type GridFleetResult } from './gridFleetRpc.js'
import { gridCredentialsPath } from './gridCredentials.js'
@@ -21,6 +22,40 @@ const validArg = (v: string): boolean => !!v && !v.startsWith('-') && !/[\x00-\x
/** `grid info` statuses of a grid that is not up. Grid refuses `engines` and `join` on one, and
* names `grid start` as the way back. Anything else unknown stays unknown rather than "down". */
const DOWN = new Set(['stopped', 'asleep'])
+/** The smallest context a coding agent can work in. Codex, Claude Code and OpenCode each open a
+ * session with a system prompt and tool list of several thousand tokens and grow from there; Ollama's
+ * own guides for all three put the floor at 64K, and below it a session survives a few turns and then
+ * fails. Every model offered here is one this machine can give at least this much. */
+export const MIN_CODING_CONTEXT = 64 * 1024
+/** Where a start begins for a file whose header could not be read: the size a 64 GB Mac was seen
+ * to hold for a 35B model, one step above the floor. */
+const UNREAD_CONTEXT = 128 * 1024
+
+/** The context sizes a start tries, largest first: [first], then halved, ending on the 64K floor.
+ * 256K → 128K → 64K. Empty when even [first] is under the floor. */
+export function contextLadder(first: number): number[] {
+ const sizes: number[] = []
+ for (let ctx = Math.floor(first); ctx >= MIN_CODING_CONTEXT; ctx = Math.floor(ctx / 2)) sizes.push(ctx)
+ if (sizes.length && sizes.at(-1)! > MIN_CODING_CONTEXT) sizes.push(MIN_CODING_CONTEXT)
+ return sizes
+}
+
+/** A port nothing on this machine is listening on, for the engine to take. */
+function freePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const server = createServer()
+ server.unref()
+ server.on('error', reject)
+ server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address() as AddressInfo
+ server.close(() => resolve(port))
+ })
+ })
+}
+
+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
+/** What llama.cpp answers once its GPU backend has failed an allocation — every request after. */
+const OUT_OF_MEMORY = /compute error|out of memory|insufficient memory|failed to allocate/i
export interface LocalModel {
id: string; name: string; state: 'available' | 'downloaded' | 'running'
@@ -42,10 +77,14 @@ export interface LocalModelsSnapshot {
observedAt: string; busy: boolean
}
interface Candidate {
- id: string; name: string; pull: string; file: string; files: string[]; size: number; quant: string; context: number
+ id: string; name: string; pull: string; file: string; files: string[]; size: number; quant: string
+ /** The window to pin at start: the catalog's fit for this machine, which is the largest it can
+ * hold. Absent for a model found on disk, which the catalog never sized — the engine then measures
+ * free memory at load and takes the largest window that fits (`grid join` without `--ctx-size`). */
+ context?: number
aliases?: string[]
}
-interface Owned { file: string; selector: string; aliases: string[]; nodeId: string; name: string; live: boolean; context: number; siblings: number }
+interface Owned { file: string; selector: string; aliases: string[]; nodeId: string; name: string; live: boolean; siblings: number }
interface Receipt { spec: 1; grid: string; operation?: ModelOperation }
interface Options {
stateDir: string; processEnv?: NodeJS.ProcessEnv
@@ -54,7 +93,12 @@ interface Options {
}
/** One concrete, machine-fitted version per model. Non-chat and unprobed offline
- * catalog rows are never called compatible. Split GGUF files stay one model. */
+ * catalog rows are never called compatible. Split GGUF files stay one model.
+ *
+ * ⚠️ A model whose fit on this machine is under [MIN_CODING_CONTEXT] is not offered at all. It used
+ * to be, pinned at 16K — a model that loads, answers "ok", and then cannot hold a coding agent's
+ * first prompt. The context pinned is the whole fit, not a slice of it: the fit is already the
+ * largest window this machine can hold beside the weights. */
export function compatibleModels(raw: unknown): Candidate[] {
const seen = new Set<string>()
return rows(obj(raw).models).flatMap(row => {
@@ -63,7 +107,8 @@ export function compatibleModels(raw: unknown): Candidate[] {
const version = rows(row.versions).find(v => v.version === fit.version)
const pull = str(version?.pull_spec), size = num(version?.size_bytes)
const id = str(row.repo_id), split = pull.indexOf(':')
- if (!id || seen.has(id) || !validArg(pull) || split < 1 || !size || !num(fit.ctx)) return []
+ const fitted = Math.floor(Math.min(num(fit.ctx) ?? 0, num(fit.max_ctx) ?? Infinity))
+ if (!id || seen.has(id) || !validArg(pull) || split < 1 || !size || fitted < MIN_CODING_CONTEXT) return []
const file = basename(pull.slice(split + 1))
if (!file.toLowerCase().endsWith('.gguf')) return []
const files = (Array.isArray(version?.urls) ? version.urls : []).flatMap((url: unknown) => {
@@ -71,7 +116,7 @@ export function compatibleModels(raw: unknown): Candidate[] {
})
seen.add(id)
return [{ id, name: cleanName(id), pull, file, files: files.length ? files : [file], size,
- quant: str(fit.version), context: Math.min(16384, Math.floor(fit.ctx)) }]
+ quant: str(fit.version), context: fitted }]
})
}
@@ -206,7 +251,7 @@ export class LocalModels {
const advertised = Array.isArray(record.advertise_as) && specs.length === 1
? record.advertise_as.filter((v: unknown) => typeof v === 'string' && v.length > 0) : []
const aliases: string[] = advertised.length ? advertised : [file]
- result.push({ file: basename(file), selector: file, aliases, nodeId: str(record.node_id), name: str(record.meta_name), live, context: Math.min(16384, num(record.ctx_size) || 8192), siblings: specs.length + (record.media ? 1 : 0) })
+ result.push({ file: basename(file), selector: file, aliases, nodeId: str(record.node_id), name: str(record.meta_name), live, siblings: specs.length + (record.media ? 1 : 0) })
this.blockers.set(grid, `Stop ${cleanName(aliases[0])} first to start another local model.`)
}
}
@@ -223,8 +268,10 @@ export class LocalModels {
try {
known = rows(JSON.parse(await readFile(path, 'utf8'))).filter(c =>
c.id === `local:${c.file}` && basename(str(c.file)) === c.file && validArg(c.file) &&
- c.pull === '' && typeof c.name === 'string' && c.name.length < 256 && num(c.size) && num(c.context) && c.context <= 16384 &&
- Array.isArray(c.files) && c.files.length === 1 && c.files[0] === c.file).map(c => ({
+ c.pull === '' && typeof c.name === 'string' && c.name.length < 256 && num(c.size) &&
+ Array.isArray(c.files) && c.files.length === 1 && c.files[0] === c.file).map(({ context: _pinned, ...c }) => ({
+ // A saved `context` is dropped, not carried: older receipts pinned 16K, and a model
+ // restarted from one would come back too small for a coding agent. The engine sizes it.
...c,
// Older receipts kept only the displayed alias. Preserve that name
// when upgrading, and never forward malformed saved argv values.
@@ -240,7 +287,7 @@ export class LocalModels {
const file = await stat(join(this.home, 'models', instance.file)).catch(() => null)
if (!file?.isFile() || !file.size) continue
known.push({ id: `local:${instance.file}`, name: cleanName(instance.aliases[0]),
- file: instance.file, files: [instance.file], pull: '', size: file.size, quant: '', context: instance.context,
+ file: instance.file, files: [instance.file], pull: '', size: file.size, quant: '',
aliases: instance.aliases.filter(validArg) })
changed = true
}
@@ -249,10 +296,73 @@ export class LocalModels {
const temp = `${path}.${randomUUID()}.tmp`
await writeFile(temp, JSON.stringify(known), { mode: 0o600 }); await rename(temp, path)
}
- const existing = await Promise.all(known.map(async candidate => await this.downloaded(candidate) ? candidate : null))
+ const existing = await Promise.all(known.map(async candidate =>
+ await this.downloaded(candidate) && !await this.tooSmallToCode(candidate.file) ? candidate : null))
return existing.filter((c): c is Candidate => c !== null)
}
+ /** The window each file was trained for, read once from its header (`grid ctx`). */
+ private trained = new Map<string, number | null>()
+
+ private async trainedWindow(file: string): Promise<number | null> {
+ if (!this.trained.has(file)) {
+ const window = await this.json(['ctx', file, '--json']).then(v => num(obj(v).context_length) ?? null, () => null)
+ this.trained.set(file, window)
+ }
+ return this.trained.get(file) ?? null
+ }
+
+ /** Whether [file] can never give a coding agent [MIN_CODING_CONTEXT], however much memory there
+ * is. Only a file the catalog did not size needs asking; unknown is not "too small". */
+ private async tooSmallToCode(file: string): Promise<boolean> {
+ const window = await this.trainedWindow(file)
+ return window != null && window < MIN_CODING_CONTEXT
+ }
+
+ /** Whether the engine just started on [port] can actually compute, asked of the engine itself.
+ *
+ * ⚠️ Not through the relay. An engine whose GPU ran out of memory answers every request with
+ * "Compute error." at once — but it reports that to the relay, and those reports timed out, so the
+ * relay check waited its whole three minutes and said only "did not answer". Asked directly, the
+ * failure is a second away and says what it is.
+ *
+ * `unknown` when there is nothing to ask (no engine listening on this machine, or no answer in
+ * time): the relay check that follows is then the judge, as it always was. */
+ private async probeEngine(port: number): Promise<'ok' | 'out-of-memory' | 'unknown'> {
+ const base = `http://127.0.0.1:${port}`
+ // `grid join` returns once the engine has loaded, so it is listening by now; 503 is a load still
+ // finishing, and the only answer worth waiting on. Nothing listening, twice, is not an engine
+ // this can reach; anything else is not a question this probe can answer.
+ const deadline = Date.now() + 10 * 60_000
+ for (let refused = 0; ;) {
+ const status = await this.request(`${base}/health`, { signal: AbortSignal.timeout(5_000), redirect: 'error' }).then(r => r.status, () => 0)
+ if (status === 200) break
+ if (status === 0 ? ++refused >= 2 : status !== 503) return 'unknown'
+ if (Date.now() > deadline) return 'unknown'
+ await sleep(500)
+ }
+ try {
+ const response = await this.request(`${base}/v1/chat/completions`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ messages: [{ role: 'user', content: 'Reply with the single word: ok' }], max_tokens: 8 }),
+ // Long: the engine's one slot may be busy with Grid's own first probe of the new engine.
+ signal: AbortSignal.timeout(5 * 60_000), redirect: 'error',
+ })
+ if (response.ok) return 'ok'
+ return OUT_OF_MEMORY.test(await response.text().catch(() => '')) ? 'out-of-memory' : 'unknown'
+ } catch { return 'unknown' }
+ }
+
+ /** The window the engine serving [model] on [grid] actually took, or undefined when Grid does not
+ * report one. Read after a start because a window left to the engine is decided at load. */
+ private async servedWindow(grid: string, model: string, nodeId: string): Promise<number | undefined> {
+ const nodes = rows(await this.json(['--remote', 'engines', grid, '--json']).catch(() => []))
+ const node = nodes.find(n => str(n.node_id || n.id) === nodeId) ?? (nodes.length === 1 ? nodes[0] : undefined)
+ const capabilities = obj(node?.model_capabilities)
+ const entry = Object.entries(capabilities).find(([name]) => modelKey(name) === modelKey(model))
+ return num(obj(entry?.[1]).context_length)
+ }
+
private receiptPath(grid: string): string { return join(this.options.stateDir, `${key(grid)}.json`) }
private async readReceipt(grid: string): Promise<void> {
if (this.receiptScope === grid) return
@@ -418,7 +528,7 @@ export class LocalModels {
if (candidate.pull) {
const current = compatibleModels(await this.catalog({ ...currentDevice, usable_bytes: Math.max(0, budget) })).find(c => c.id === candidate.id)
if (!current || current.size < candidate.size) throw new ModelError('Stop a running model to make room, then try again.')
- candidate.context = Math.min(candidate.context, current.context)
+ candidate.context = Math.min(candidate.context ?? Infinity, current.context ?? Infinity)
} else if (candidate.size * 1.25 + 2 * GiB > budget) {
throw new ModelError('Stop a running model to make room, then try again.')
}
@@ -454,13 +564,48 @@ export class LocalModels {
if (override) throw new ModelError('The local engine needs attention. Open Model Manager.')
await must(['engine', 'install', 'llama.cpp'], 'The model engine could not start. Try again.')
}
- await must(['--remote', 'join', grid, '--serve', candidate.file,
- '--max-concurrency', '1', '--ctx-size', String(candidate.context), '--reasoning-budget', '0',
- ...(candidate.aliases ?? []).flatMap(alias => ['--advertise-as', alias])],
- 'The model could not start. Try again.')
+ // ⚠️ ALWAYS pinned, and stepped down when it does not run. Left to the engine, the window
+ // was the model's whole trained 256K on a 64 GB Mac whose GPU could hold 128K: it loaded, ran
+ // out of memory on its first request, and failed every request after. The catalog's fit is
+ // optimistic the same way. So the most the model is sized for is tried first, and each size
+ // that cannot compute is taken back down and halved — to the 64K floor, never below it.
+ const first = candidate.context ?? await this.trainedWindow(candidate.file) ?? UNREAD_CONTEXT
+ let started = false, outOfMemory = false
+ for (const ctx of contextLadder(first)) {
+ const port = await freePort()
+ const joined = await this.run(['--remote', 'join', grid, '--serve', candidate.file,
+ '--max-concurrency', '1', '--ctx-size', String(ctx), '--endpoint-port', String(port),
+ '--reasoning-budget', '0',
+ ...(candidate.aliases ?? []).flatMap(alias => ['--advertise-as', alias])], undefined, 30 * 60_000)
+ // A join that fails at a size is also stepped down from: an allocation that fails at load
+ // takes the engine down before Grid can register it.
+ const probe = joined.ok ? await this.probeEngine(port) : 'failed'
+ if (probe === 'ok' || probe === 'unknown') { started = true; break }
+ outOfMemory ||= probe === 'out-of-memory'
+ // Down before the next size. The last engine leaving drops Grid's local registration, which
+ // the next join needs back — the same restore a start begins with.
+ await this.run(['--remote', 'leave', grid, '--engine', candidate.file], undefined, 30 * 60_000)
+ await this.run(['--remote', 'sync'], undefined, 30 * 60_000)
+ if (DOWN.has(await this.gridStatus(grid).catch(() => ''))) await this.run(['--remote', 'start', grid], undefined, 30 * 60_000)
+ }
+ if (!started) {
+ throw new ModelError(outOfMemory
+ ? `This computer does not have the memory to run ${candidate.name} with a 64K context. Close some apps, or choose a smaller model.`
+ : 'The model could not start. Try again.')
+ }
}
await change('verifying')
- await this.verify(grid, instance?.aliases[0] || candidate.aliases?.[0] || candidate.file)
+ const model = instance?.aliases[0] || candidate.aliases?.[0] || candidate.file
+ await this.verify(grid, model)
+ // The floor, checked against what was actually served rather than what was asked: a window
+ // left to the engine is decided by the memory free at load, and can come in under it. A model
+ // that answers but cannot hold a coding agent's prompt is worse than one that did not start.
+ const serving = instance ?? (await this.owned(grid)).find(o => o.file === candidate.file)
+ const window = serving ? await this.servedWindow(grid, model, serving.nodeId) : undefined
+ if (serving && window !== undefined && window < MIN_CODING_CONTEXT) {
+ await this.run(['--remote', 'leave', grid, '--engine', serving.selector], undefined, 30 * 60_000)
+ throw new ModelError(`${candidate.name} could only get a ${Math.floor(window / 1024)}K context here. Coding agents need at least 64K. Close some apps, or choose a smaller model.`)
+ }
}
operation.phase = 'done'
await this.save(grid, operation)
diff --git a/store/agents/autonomous-grid/AGENTS.md b/store/agents/autonomous-grid/AGENTS.md
index fe88cdf2c..df79304e6 100644
--- a/store/agents/autonomous-grid/AGENTS.md
+++ b/store/agents/autonomous-grid/AGENTS.md
@@ -15,11 +15,13 @@ status`, then a live read where the request needs one) and the one thing named d
questions exist for facts you don't have; they are never a script to run from the top. "Raise it to
more memory", "make it two at once", "turn vision off", "stop it", "what's running" are about a
model already there — read its settings, change or report that one thing, and never re-ask what the
-person already said. A request that carries its answers ("a coding model, just for me") skips every
-question those answers cover.
+person already said. Starting a model asks no setup questions: the skill picks the model, the
+longest context this machine can give (never under 64K), concurrency and vision for coding on this
+machine, and says what it picked and what it costs in memory. A person who wants something
+different says so, and that one thing changes.
**Ask through a tool, not prose.** Every "ask" means the question tool with real options — the
-intent questions, the model shortlist, every go-ahead before a slow step. A question mark in a
+model shortlist when they ask for other options, every go-ahead before a slow step. A question mark in a
paragraph is not a stop. **Talk the way Harness talks:** short, declarative, second person; say what
is true and what happens next; no "I'd be happy to", no exclamation marks; a thing that is not set
up is said plainly and stopped at, the way a failed build is reported.
diff --git a/store/agents/autonomous-grid/skills/grid-operations/SKILL.md b/store/agents/autonomous-grid/skills/grid-operations/SKILL.md
index 75d37bcb0..a21c4102b 100644
--- a/store/agents/autonomous-grid/skills/grid-operations/SKILL.md
+++ b/store/agents/autonomous-grid/skills/grid-operations/SKILL.md
@@ -1,6 +1,6 @@
---
name: grid-operations
-description: "Look after the models on the user's machines — one laptop or a fleet: recognise their private grid, ask what they need in plain words, pick a model that fits from disk, catalog or Hugging Face, start it with vision and context that fit, prove it answers with one bounded call, change or stop a running one, and use Grid routing, usage, media and training commands."
+description: "Look after the models on the user's machines — one laptop or a fleet: recognise their private grid, pick the model and settings that fit this machine for coding without asking, start it with the longest context the machine can give (never under 64K), say what it costs in memory, prove it answers with one bounded call, change or stop a running one, and use Grid routing, usage, media and training commands."
---
# Grid operations
@@ -76,47 +76,45 @@ that runs the engine; listing, routing and requests can run on the controller.
## First local model: help from this conversation
The Models panel normally handles discovery and Start/Stop directly. If the user asks this
-conversation to help set up a local model, begin inspecting
-this computer immediately. This is the short onboarding path: coding and everyday work, one
-person, a responsive first reply, and enough free memory for other apps. Prefer a suitable
-model already running or downloaded. Inspect device-info and the live catalog, choose one
-comfortable fit, and explain the download size and memory needs in plain words. Offer
-**Start this model** and **Other options** through the question tool. That single choice
-covers installing the required engine and downloading/starting the recommended model.
-Choose context from the model's measured fit and the session's needs. Do not ask the user to
-choose an engine, quantization, token count, concurrency, or vision setting. Use suitable
-existing defaults; extra questions belong to explicit advanced requests. Keep setup on this
-computer. Other machines are available when the user asks for them.
+conversation to help set up a local model, begin inspecting this computer immediately and follow
+**Start a model** below — the same defaults, no setup questions. Keep setup on this computer;
+other machines are available when the user asks for them.
Use the tracked fleet runner for hardware checks, downloads, and startup, so the viewer retains
-progress while the conversation is closed or interrupted. After the model appears in discovery,
-run `"$GRID_FLEET" verify --grid GRID --model MODEL_ALIAS` once. This bounded check records
-readiness only after a real reply. On failure, report the problem and offer recovery. On success,
-say **"Your model is running. Select it from the model picker in a session."** The setup ends at a usable model.
+progress while the conversation is closed or interrupted. The setup ends at a usable model: on
+success, say **"Your model is running. Select it from the model picker in a session."**
## Start a model
Slow steps are a real stop: a download or an engine build is asked about through the question tool
and runs in the **next** turn, never in the message that asks. Every model you offer comes from
something you looked up — the host's disk, the catalog, or Hugging Face — never from memory. The
-pick is made once; after the person chooses, that is the model through the download, the vision
-question and the start, unless it fails (won't fit, won't pull, won't answer).
-
-**1. What they need — three questions, in plain words, through the question tool.** Skip any the
-person already answered. The engine numbers in brackets are yours; they are never shown.
-
- "What will you mostly use it for?" — the work decides which model is worth downloading
- Coding · Chat and writing · Reading images · Just something fast
- "How much can it hold in its head at once?" — its working memory for one conversation; when it
- fills, it forgets the beginning; more costs memory on the machine
- Short, about 20 pages [32K] · Medium, about 40 pages [64K] · Long, about 80 pages [128K] ·
- As much as this machine can give it
- "How many things will talk to it at the same time?" — each one reserves its own share of memory
- up front; when every share is taken, the next request waits
- Just me, one agent at a time [1] · Two agents at once [2] · A few agents or people at once [4]
-
-Coding wants Long (an agent burns context as a session grows); chat is fine at Short; "just me" on
-a laptop someone is also working on.
+pick is made once; that is the model through the download and the start, unless it fails (won't
+fit, won't pull, won't answer) or the person asks for a different one.
+
+**1. What they need — decided for them, not asked.** Harness is a coding tool: the model is for a
+coding agent unless the person says otherwise. Do **not** ask them to choose an engine,
+quantization, context size, concurrency or vision — pick what fits this machine best, say what you
+picked and what it costs, and change one thing only when they ask for something different ("make it
+two at once", "turn vision off", "a smaller one"). The defaults:
+
+ - **Context: the longest this machine can give, and never under 64K tokens.** Codex, Claude Code
+ and OpenCode each open a session with thousands of tokens of instructions and tools and grow
+ from there; below 64K a session survives a few turns and then fails. A model that cannot get
+ 64K on this machine is not offered — pick a smaller model or quant instead. There is no 32K
+ option.
+ - **One at a time** (`--max-concurrency 1`): one agent. Every extra slot reserves its own full
+ context up front, so a second one halves what each can hold.
+ - **Vision on** when the model has a projector (it reads screenshots) and the context still clears
+ 64K with it; otherwise text only, said in one line.
+ - **The quant the catalog fits** (`fit.version`), or the file already on disk.
+
+**Say it in pages, and say what it costs.** A page is about 650 tokens (≈500 words), so 64K is
+about 100 pages, 128K about 200 and 256K about 400 — tokens ÷ 650, rounded. Never shown as bare
+token counts. The cost in memory is the weights (the file size) plus the context's reservation:
+before the start say "the model takes W GB, and its context uses the rest of the U GB this computer
+can give models" (`usable_bytes` from `device-info`); after the start, give Grid's measured figure
+when `engines --json` reports one. Never invent a number.
**2. What the host has.** `device-info --json` on the intended host first: `usable_bytes` is the
real ceiling for weights plus context. Per-machine, never summed across hosts. The engine check is
@@ -127,15 +125,16 @@ install what was already built. Only when the binary is missing, ask (build from
and run `engine install llama.cpp [--from-source]` in the next turn.
**3. What is already on the host's disk comes first.** `ls ~/.grid/models/*.gguf` minus the
-`.mmproj.gguf` sidecars; `ctx FILE --json` says how much each can hold; a `<stem>.mmproj.gguf`
-beside a file means it reads images. Anything that fits the answers is offered first as "already on
-this computer, no download", beside one option to fetch something new. Only that option goes on.
+`.mmproj.gguf` sidecars; `ctx FILE --json` says the most each was trained to hold — a file under
+64K is skipped; a `<stem>.mmproj.gguf` beside a file means it reads images. A suitable file already
+here is the pick ("already on this computer, no download"); fetch something new only when none is.
**4. The catalog, then Hugging Face.** `catalog --json` is sized for the host: keep entries that are
-`runnable`, whose `fit.ctx` covers the context asked, and that suit the purpose; pull
-`fit.version`'s `pull_spec`. Offer 2–3 in the same plain terms as step 1 — what it is good at, the
-download size in GB, how much it can hold in pages, whether it reads images. No speed figure
-(`fit.est_tok_s` only orders the list for "fast"), no quant name, no token count as the whole answer.
+`runnable`, whose `fit.ctx` is at least 65536, and that are good at code; pull `fit.version`'s
+`pull_spec`. Pick the best one for coding yourself and name it with the download size in GB, how
+much it can hold in pages and whether it reads images; offer a shortlist of 2–3 only when the person
+asks for other options. No speed figure (`fit.est_tok_s` only orders the list for "fast"), no quant
+name, no token count as the whole answer.
When the person names a model the catalog lacks, the catalog is not a wall — `pull` takes any
`<repo>:<file>.gguf` on Hugging Face and fetches its projector too:
@@ -157,26 +156,29 @@ the file names, and put "reads images" or "text only" on each option; for "Readi
only repos with an mmproj. After the pull, the disk proves it:
`test -f ~/.grid/models/<stem>.mmproj.gguf`.
-**5. Two checks, then the start.** *Fit:* `--ctx-size` is per request and the engine reserves
-context × slots up front (grid passes `ctx × slots` to llama.cpp; 4 slots at 64K is 256K tokens of
-KV cache before the first request, and a size the host cannot hold fails to start rather than
-shrinking). Check context × the asked concurrency against `usable_bytes` minus the weights and
-`keepFreeMemoryGb`; if it doesn't fit, offer a smaller context or fewer slots through a tool.
-*Vision:* when the projector is on disk, ONE question whose options say what each does —
-"Serve it with vision on?" · *Yes, with vision — it reads screenshots and photos (some extra
-memory)* · *No, text only — the vision file is set aside for this run; say the word to put it back*.
-On "no", rename the projector yourself (`mv <stem>.mmproj.gguf <stem>.mmproj.gguf.off`) before the
-join and say so in one line — never a second question about the file.
+**5. The context, then the start.** `--ctx-size` is per request and the engine reserves context ×
+slots up front (4 slots at 64K is 256K tokens of KV cache before the first request). **Always pass
+it** — start from the most the model is sized for: a catalog model's `fit.ctx` (capped at
+`fit.max_ctx`), or for a file the catalog never sized, what `ctx FILE --json` says it was trained
+for. ⚠️ Never leave it off. Left to the engine, a 35B model took its whole trained 256K on a 64 GB
+Mac whose GPU could hold 128K: it loaded, then failed its very first request with `Insufficient
+Memory (kIOGPUCommandBufferCallbackErrorOutOfMemory)` and every request after with `Compute
+error.`; the catalog's fit is optimistic the same way. So **step down when it does not run**: if
+the first request after the join (step 6) answers `Compute error`, out of memory, or the join itself
+fails, `leave`, `sync`, and join again at half — 256K → 128K → 64K. If 64K fails too, stop and say
+this computer does not have the memory for this model with a 64K context; offer a smaller model. *Vision:* on by default when the projector is
+on disk. When the person asks for text only, rename the projector yourself
+(`mv <stem>.mmproj.gguf <stem>.mmproj.gguf.off`) before the join and say so in one line.
"$GRID_FLEET" run --machine MACHINE -- pull OWNER/REPO:EXACT_FILE.gguf
"$GRID_FLEET" run --machine MACHINE -- join GRID --serve EXACT_FILE.gguf --advertise-as MODEL_ALIAS \
--name MACHINE-MODEL --max-concurrency N --ctx-size CTX --endpoint-port PORT
`--advertise-as` is the name the person will see in their model picker; `--name` is the machine's
-display name — different things. `--max-concurrency N` is the step-1 answer; don't pass
+display name — different things. `--max-concurrency N` is 1 unless they asked for more; don't pass
`--parallel` (grid derives the slot count from it) and don't pass `--jinja` (on by default in the
-engine grid ships). `--ctx-size` always, capped at the file's `fit.max_ctx` ("as much as fits" =
-`fit.ctx`): left off, the engine takes a 16K default, smaller than an agent's own prompt. Use
+engine grid ships). Never pin `--ctx-size` under 65536 — a window that small cannot hold a coding
+agent's own prompt (a 32K engine here refused an agent's first request of 59,561 tokens). Use
explicit ports when several instances share a host. An existing Ollama, vLLM, MLX or LM Studio
engine can join with `--at URL -m MODEL --name NAME`; do not install a second engine needlessly.
@@ -196,6 +198,12 @@ is "not yet", not "broken"):
until "$GRID_FLEET" run -- models GRID 2>/dev/null | grep -qx 'MODEL_ALIAS'; do sleep 10; done
"$GRID_FLEET" verify --grid GRID --model MODEL_ALIAS
+A `verify` that fails with a compute or out-of-memory error is the context not fitting — step down
+as step 5 says rather than retrying the same size. Then read the window it actually got:
+`engines GRID --json`, this machine's row, `model_capabilities[<model>].context_length`. Under
+65536, `leave` it, say in one line it could only get N pages here, and move to a smaller model or
+quant. A null means Grid did not say; report the context you passed.
+
⚠️ Not `chat` for this check. `chat` sets no output limit and the engine's default is tens of
thousands of tokens, so a small model that runs away answering "ok" holds the slot for minutes — and
with one slot everything after it waits, including a second check. `max_tokens` is what makes this
@@ -210,8 +218,9 @@ one step larger from the same list (tiny models loop), or more requests at once,
`message.content` contains the requested result; reasoning text alone or a successful HTTP status is
not acceptance. Then `"$GRID_FLEET" refresh`.
-**7. Say where it is.** "<alias> is running on <machine>, N at a time, vision on/off. Pick it from
-the model dropdown at the top of any agent's pane, and that agent switches to it." In the Models
+**7. Say where it is, and what it costs.** "<alias> is running on <machine> with room for about
+N pages (<K>K tokens), one at a time, vision on/off; it uses about M GB of memory. Pick it from the
+model dropdown at the top of any agent's pane, and that agent switches to it." In the Models
panel, **Use** returns to the person's session or opens one when needed. Don't offer to wire it into an agent's
config or add a provider — the picker is the whole hand-off.
@@ -268,8 +277,8 @@ Say what failed and stop; translate every message, never repeat a raw line that
- **`No providers available for this model`** right after a join → not registered yet; wait as
step 6 says.
- **`exceeds the available context size`** (an agent may show it as a garbled "expected array
- `choices`") → served with too small a window, usually `--ctx-size` left off: leave, join again
- with the asked context.
+ `choices`") → served with too small a window: leave, and join again with the longest context
+ that fits (step 5) — never under 64K.
- **`Jinja Exception: System message must be at the beginning`** → the model's template refuses a
system message after the first turn; the relay now hoists system/developer messages to the
front, so the relay this machine talks to predates that fix. The model is fine; nothing to