The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Swarm local models: keep models on the grid, keep small models from Builders, alert a stalled Builder
bitcoinbuilderfab0e076fa1d
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex f8724de80..bf9dd91dd 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -131,7 +131,7 @@ export const commandSchema = z.discriminatedUnion('type', [...(['agent.screenResult', 'agent.inputResult'] as const).map(type => z.object({ type: z.literal(type), requestId: id, ok: z.boolean(),text: z.string().refine(value => Buffer.byteLength(value) <= 65_536, 'A screen is at most 64 KB.').optional(),error: z.string().trim().min(1).max(500).optional() }).strict().refine(c => c.ok || c.error !== undefined, 'Say why the request failed.')),- z.object({ type: z.literal('agent.alert'), agentId: id, alert: z.enum(['prompt', 'limit']), active: z.boolean(), resetAt: z.iso.datetime().optional() }).strict(),+ z.object({ type: z.literal('agent.alert'), agentId: id, alert: z.enum(['prompt', 'limit', 'model']), active: z.boolean(), resetAt: z.iso.datetime().optional() }).strict(),z.object({ type: z.literal('work.check'), conversationId: id, assignmentId: id, checkId: id, passed: z.boolean(), evidence: text }).strict(),])export type Command = z.infer<typeof commandSchema>diff --git a/backend/src/superTabs/machines.test.ts b/backend/src/superTabs/machines.test.tsindex 52353ea42..78230d511 100644--- a/backend/src/superTabs/machines.test.ts+++ b/backend/src/superTabs/machines.test.ts@@ -13,6 +13,15 @@ it('accepts optional tool probe failures while preserving older observations', (expect(machineObservationSchema.safeParse({ ...sent, tools: { git: true }, toolProbeErrors: { flutter: 'interactive shell timed out' } }).success).toBe(true)})+it('accepts the served models Builders are not offered, with why', () => {+ const { receivedAt: _receivedAt, ...sent } = observation+ const refused = { grid: 'swarm-0123456789ab', model: 'llama3.2:3b', name: 'llama3.2:3b', why: 'llama3.2:3b is too small for a coding agent.' }+ expect(machineObservationSchema.safeParse({ ...sent, refusedModels: [refused] }).success).toBe(true)+ expect(machineObservationSchema.safeParse({ ...sent, refusedModels: [{ ...refused, why: '' }] }).success).toBe(false)+ expect(machineObservationSchema.safeParse({ ...sent, refusedModels: [{ ...refused, extra: 1 }] }).success).toBe(false)+ expect(machineObservationSchema.safeParse({ ...sent, refusedModels: Array(17).fill(refused) }).success).toBe(false)+})+function setup(machine: Partial<ContributedMachine> = {}) {const state: SuperTabState = createSuperTab('tab', 'Team', { id: 'owner', email: '[email protected]' }, 'test')state.machines = [{ machineId: 'host', name: 'Studio Mac', contributorId: 'owner', membershipGeneration: 'tab', generation: 'g1',diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 674088414..3af921fb6 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -57,6 +57,10 @@ export const machineObservationSchema = z.object({ generation: z.string().max(16localModels: z.array(z.object({ grid: z.string().min(1).max(160), model: z.string().min(1).max(200),name: z.string().max(200).optional(), contextWindow: z.number().int().positive().nullable().optional(),kind: z.enum(['local', 'api', 'shared']).optional() }).strict()).max(64).optional(),+ /** Models this machine serves on the Swarm's grid that Builders are not offered, too small or too slow to drive a coding+ * agent (cli/src/lib/codingModel.ts), with why: so the route can tell a Lead asked for one why it is not offered. */+ refusedModels: z.array(z.object({ grid: z.string().min(1).max(160), model: z.string().min(1).max(200),+ name: z.string().max(200).optional(), why: z.string().min(1).max(300) }).strict()).max(16).optional(),}).strict()export type MachineObservation = z.infer<typeof machineObservationSchema>diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 04e469c34..0e62d8246 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -46,7 +46,7 @@ export interface Agent {/** A usage limit seen on its terminal; routing skips the agent until then. Shown as null once passed (terminal.ts). */limitedUntil?: string | null/** Terminal alert episodes in progress, so each one posts a single row (terminal.ts). */- alerting?: Array<'prompt' | 'limit'>+ alerting?: Array<'prompt' | 'limit' | 'model'>}export type AgentRole = 'builder' | 'reviewer'export const agentRole = (agent: Pick<Agent, 'role'>): AgentRole => agent.role ?? 'builder'diff --git a/backend/src/superTabs/terminal.test.ts b/backend/src/superTabs/terminal.test.tsindex 1a27edc14..2f0cdcc85 100644--- a/backend/src/superTabs/terminal.test.ts+++ b/backend/src/superTabs/terminal.test.ts@@ -163,6 +163,17 @@ describe('terminal alerts', () => {expect(lead.messages[0]).toMatchObject({ conversationId: 'lead', recipients: [] })})+ it('tells the Lead when an agent cannot get answers from its model, once per episode', () => {+ const s = swarm()+ const on = () => s.run({ type: 'agent.alert', agentId: s.worker, alert: 'model', active: true }, as(s.worker)).messages+ expect(on()[0]).toMatchObject({ recipients: [s.lead], source: { kind: 'terminal-alert', agentId: s.worker, alert: 'model' },+ text: `${name(s, s.worker)} can't get answers from its model: its requests keep failing. Stop it, or give the work to another model.` })+ expect(on()).toEqual([])+ expect(s.state.agents.find(a => a.id === s.worker)!.limitedUntil).toBeUndefined()+ s.run({ type: 'agent.alert', agentId: s.worker, alert: 'model', active: false }, as(s.worker))+ expect(on()).toHaveLength(1)+ })+it('takes alerts only from the agent\'s own host', () => {const s = swarm()expect(() => s.run({ type: 'agent.alert', agentId: s.worker, alert: 'prompt', active: true }, as(s.lead))).toThrow()diff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.tsindex 31c3cd530..9565454d0 100644--- a/backend/src/superTabs/terminal.ts+++ b/backend/src/superTabs/terminal.ts@@ -84,7 +84,7 @@ export function terminalResult(state: SuperTabState, actor: Actor, request: Term/** One row per episode: a repeated observation adds nothing, and `active: false` ends the episode. No screen text goes in the row.* It is delivered to the agent's project Lead, in the agent's group when the Lead is there, else by a second row in the Lead's chat. */export function terminalAlert(state: SuperTabState, actor: Actor, sender: Author, id: string, now: number,- command: { agentId: string; alert: 'prompt' | 'limit'; active: boolean; resetAt?: string }): MessageDraft[] {+ command: { agentId: string; alert: 'prompt' | 'limit' | 'model'; active: boolean; resetAt?: string }): MessageDraft[] {const target = agent(state, command.agentId)if (actor.kind !== 'agent' || actor.agentId !== target.id) fail('HOST_REQUIRED', 'Only the host of this agent’s terminal reports its alerts.', 403)const alerting = target.alerting ?? []@@ -104,6 +104,9 @@ export function terminalAlert(state: SuperTabState, actor: Actor, sender: Authortarget.limitedUntil = source.limitedUntil = new Date(reset).toISOString()text = `${nameOf(target)} hit a usage limit. Routing skips it until ${target.limitedUntil.slice(11, 16)} UTC.`}+ // Its engine has been retrying its model for 10 minutes (2026-10-24: a Builder on a small local model retried for an+ // hour while its Lead waited on it).+ if (command.alert === 'model') text = `${nameOf(target)} can't get answers from its model: its requests keep failing. Stop it, or give the work to another model.`const here = !!lead && group.agentIds.includes(lead)const row = { id, conversationId: group.id, author: sender, replyTo: null, recipients: here ? [lead] : [], text, source }return here || !lead || !chat.agentIds.includes(lead) ? [row] : [row, { ...row, id: stableId(id, 'lead'), conversationId: chat.id, recipients: [lead] }]diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex ec3647946..4e622f7b3 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -722,7 +722,7 @@ export const OS_DEVICE_REQUESTS = ['os_device'] as constexport const MODELS_REQUESTS = ['grid_models_list', 'models_list','grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop',- 'grid_fleet_run', 'grid_fleet_cancel', 'grid_swarm_sync', 'grid_swarm_api_share', 'grid_swarm_api_shares', 'grid_swarm_offer', 'grid_swarm_offers',+ 'grid_fleet_run', 'grid_fleet_cancel', 'grid_swarm_sync', 'grid_swarm_api_share', 'grid_swarm_api_shares', 'grid_swarm_offer', 'grid_swarm_offers', 'grid_swarm_heal','api_connections', 'codex_profiles_list', 'codex_profile_link',] as constdiff --git a/cli/src/lib/codingModel.spec.ts b/cli/src/lib/codingModel.spec.tsnew file mode 100644index 000000000..6b892fe56--- /dev/null+++ b/cli/src/lib/codingModel.spec.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest'+import { codingRefusal, paramsFromName, paramsOf } from './codingModel.js'++const GB = 1e9++describe('a local model that can drive a coding agent', () => {+ it('reads the parameter count off a name, the total and never an active count', () => {+ expect(paramsFromName('llama3.2:3b')).toBe(3)+ expect(paramsFromName('Qwen3.6-35B-A3B')).toBe(35)+ expect(paramsFromName('Qwen3-4B-Instruct-2507')).toBe(4)+ expect(paramsFromName('qwen2.5-coder:7b-instruct')).toBe(7)+ expect(paramsFromName('mixtral-8x7b')).toBeUndefined()+ expect(paramsFromName('gemma-4-E2B-it')).toBeUndefined()+ expect(paramsFromName('Llama-3.3-70B')).toBe(70)+ })++ it('counts parameters from the model, its name, else its weights and quant', () => {+ expect(paramsOf({ name: 'x', paramsB: 12 })).toBe(12)+ expect(paramsOf({ name: 'llama3.2:3b', sizeBytes: 40 * GB })).toBe(3)+ expect(paramsOf({ name: 'gemma-4-E2B-it', sizeBytes: 3.2 * GB })).toBeCloseTo(5.33, 1)+ expect(paramsOf({ name: 'm', sizeBytes: 16 * GB, quantization: 'BF16' })).toBeCloseTo(8)+ expect(paramsOf({ name: 'm', sizeBytes: 4.25 * GB, quantization: 'MXFP4' })).toBeCloseTo(8)+ expect(paramsOf({ name: 'm', sizeBytes: 4.3 * GB, quantization: 'IQ4_XS' })).toBeCloseTo(8)+ expect(paramsOf({ name: 'm', sizeBytes: 8.8 * GB, quantization: 'Q8_0' })).toBeCloseTo(8)+ expect(paramsOf({ name: 'm' })).toBeUndefined()+ })++ it('refuses a model too small or too slow, and says why; anything unknown passes', () => {+ expect(codingRefusal({ name: 'llama3.2:3b' })).toBe('llama3.2:3b is too small for a coding agent (about 3B parameters; Builders need 7B or more).')+ expect(codingRefusal({ name: 'Qwen3.6-35B-A3B', estTokS: 4.4 }))+ .toBe('Qwen3.6-35B-A3B is too slow on this computer for a coding agent (about 4 tok/s; Builders need 10 or more).')+ expect(codingRefusal({ name: 'Qwen3.6-35B-A3B', estTokS: 4, tokensPerSecond: 40 })).toBeNull()+ expect(codingRefusal({ name: 'Qwen3.6-35B-A3B', estTokS: 30 })).toBeNull()+ expect(codingRefusal({ name: 'mystery' })).toBeNull()+ })+})diff --git a/cli/src/lib/codingModel.ts b/cli/src/lib/codingModel.tsnew file mode 100644index 000000000..2cfe3fd66--- /dev/null+++ b/cli/src/lib/codingModel.ts@@ -0,0 +1,49 @@+/**+ * Whether a local model can drive a coding agent, beside the 64K context floor (`codingContext.ts`). 2026-10-24: a Builder+ * on llama3.2:3b, with a 128K window, made over a thousand requests for a one-line edit and never finished; a qwen3 4B+ * Builder timed out the day before. A model this small cannot keep up with a coding agent's tools and context, and one+ * that answers slowly has the grid's relay give up on it. Such a model is not offered to Builders, and Run for Swarm+ * says why (desktop `lib/models/coding_model.dart` holds the same rule).+ */++/** Fewer parameters than this, and Claude Code or Codex goes round in circles. */+export const MIN_CODING_PARAMS_B = 7+/** Slower than this on the machine that runs it, and a turn outlasts what the relay waits for. */+export const MIN_CODING_TOK_S = 10++export interface CodingModelFacts {+ name: string; paramsB?: number; sizeBytes?: number; quantization?: string; tokensPerSecond?: number; estTokS?: number+}++/** Roughly how many bits a weight takes at [quant]: Q4 about 4.8, IQ4 about 4.3, MXFP4 4.25, half precision 16. */+function bitsPerWeight(quant = ''): number {+ const q = quant.toUpperCase()+ if (/MXFP4/.test(q)) return 4.25+ if (/BF16|FP16|F16/.test(q)) return 16+ const digit = /(IQ|Q)(\d)/.exec(q)+ return digit ? Number(digit[2]) + (digit[1] === 'IQ' ? 0.3 : 0.8) : 4.8+}++/** The parameter count a model's name gives (`llama3.2:3b`, `Qwen3.6-35B-A3B`: the total, not the active `A3B`). */+export function paramsFromName(name: string): number | undefined {+ const match = /(?:^|[^a-z0-9.])(\d+(?:\.\d+)?)b(?![a-z0-9])/i.exec(name)+ return match ? Number(match[1]) : undefined+}++/** Billions of parameters: the model's own count, else its name's, else read off its weights and quant. */+export function paramsOf(m: CodingModelFacts): number | undefined {+ return m.paramsB ?? paramsFromName(m.name) ?? (m.sizeBytes ? m.sizeBytes * 8 / bitsPerWeight(m.quantization) / 1e9 : undefined)+}++/** Why [m] cannot drive a coding agent, in a sentence, or null when it can or nothing says otherwise. */+export function codingRefusal(m: CodingModelFacts): string | null {+ const params = paramsOf(m)+ if (params !== undefined && params < MIN_CODING_PARAMS_B) {+ return `${m.name} is too small for a coding agent (about ${Math.round(params * 10) / 10}B parameters; Builders need ${MIN_CODING_PARAMS_B}B or more).`+ }+ const speed = m.tokensPerSecond ?? m.estTokS+ if (speed !== undefined && speed < MIN_CODING_TOK_S) {+ return `${m.name} is too slow on this computer for a coding agent (about ${Math.round(speed)} tok/s; Builders need ${MIN_CODING_TOK_S} or more).`+ }+ return null+}diff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.tsindex 7fd448f89..a0404cb9e 100644--- a/cli/src/lib/localModels.spec.ts+++ b/cli/src/lib/localModels.spec.ts@@ -292,6 +292,13 @@ describe('local model discovery and lifecycle', () => {await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()expect((await service.list('home', true)).models.find(m => m.id === 'org/Small-GGUF')!.operation).toMatchObject({ phase: 'failed', error: 'Open Model Manager to add a model alongside those already running.' })+ // An app's engine this daemon joined there is named, so the person knows what to stop.+ await mkdir(stateDir, { recursive: true })+ await writeFile(join(stateDir, 'app-engines.json'), JSON.stringify([{ spec: 1, modelId: 'app:ollama:llama3.2:3b', grid: 'home',+ name: 'llama3.2:3b', engine: 'ollama', served: 'llama3.2:3b', alias: 'llama3.2:3b', port: 41003, binary: '/usr/local/bin/ollama' }]))+ await service.act('home', 'org/Small-GGUF', 'start'); await service.settled()+ expect((await service.list('home', true)).models.find(m => m.id === 'org/Small-GGUF')!.operation)+ .toMatchObject({ phase: 'failed', error: 'Stop llama3.2:3b first to start another local model.' })})it('never offers Stop for an external endpoint or another machine', async () => {@@ -1691,6 +1698,32 @@ describe('models other apps downloaded, started in their own app', () => {expect(row).not.toHaveProperty('servedOn')})+ it('names the live engines it joined to a grid, and joins the first again as it was started', async () => {+ const swarm = 'swarm-0123456789ab'+ const record = (grid: string, modelId = ollama.id) => ({ spec: 1, modelId, grid, name: 'llama3.2:3b', engine: 'ollama', served: 'llama3.2:3b',+ alias: 'llama3.2:3b', port: 41000, binary: '/usr/local/bin/ollama', pid: 4242 })+ await mkdir(stateDir, { recursive: true })+ await writeFile(join(stateDir, 'app-engines.json'), JSON.stringify([record('home'), record(swarm, 'app:gone'), record(swarm)]))+ up.add(ollama.id)+ const models = appService({ machineName: () => 'Studio Mac' })+ expect(await models.servedApps(swarm)).toEqual(['llama3.2:3b'])+ expect(await models.rejoinApp(swarm)).toBe(true)+ expect(calls.at(-1)).toEqual(['--remote', 'join', swarm, '--at', 'http://127.0.0.1:41000/v1', '-m', 'llama3.2:3b',+ '--advertise-as', 'llama3.2:3b', '--max-concurrency', '1', '--name', 'Studio Mac'])+ // No name, or none an argument can carry: joined without one. Nothing alive there: nothing joined.+ expect(await appService({ machineName: () => '-x' }).rejoinApp(swarm)).toBe(true)+ expect(calls.at(-1)).not.toContain('--name')+ // An engine that cannot be checked is not served.+ ops.alive.mockRejectedValueOnce(new Error('ps')).mockRejectedValueOnce(new Error('ps'))+ expect(await models.servedApps(swarm)).toEqual([])+ ops.alive.mockRejectedValueOnce(new Error('ps')).mockRejectedValueOnce(new Error('ps'))+ expect(await models.rejoinApp(swarm)).toBe(false)+ up.clear()+ expect(await models.servedApps(swarm)).toEqual([])+ expect(await models.rejoinApp(swarm)).toBe(false)+ expect(await appService({ appEngines: undefined }).servedApps(swarm)).toEqual([])+ })+it('lists the own grid beside a Swarm\'s when one model is served on both, and reads none without its app\'s engines', async () => {const record = (grid: string) => ({ spec: 1, modelId: ollama.id, grid, name: 'llama3.2:3b', engine: 'ollama', served: 'llama3.2:3b',alias: 'llama3.2:3b', port: 41000, binary: '/usr/local/bin/ollama', pid: 4242 })diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.tsindex e58a5df42..c29dfbafa 100644--- a/cli/src/lib/localModels.ts+++ b/cli/src/lib/localModels.ts@@ -515,7 +515,10 @@ export class LocalModels {grids ??= rows(await this.json(['--remote', 'ls', '--json']))const gridId = str(grids.find(g => g.grid === grid)?.id)const { owned, blocker } = await this.engineRecords(gridId)- if (blocker) this.blockers.set(grid, blocker)+ // An app's engine this daemon joined there is named, as the list names it: read again before a start, the grid's+ // record alone said only to open Model Manager, with llama3.2:3b from Ollama running for a Swarm (2026-10-24).+ const app = blocker ? (await this.records()).find(record => record.grid === grid) : undefined+ if (blocker) this.blockers.set(grid, app ? `Stop ${cleanName(app.name)} first to start another local model.` : blocker)return owned}@@ -765,6 +768,30 @@ export class LocalModels {return kept}+ /** The names this computer's app engines are joined to [grid] under (`swarmHeal.ts` compares them with what the grid+ * lists). An engine whose process is gone is not served by anything here. */+ async servedApps(grid: string): Promise<string[]> {+ const served: string[] = []+ for (const record of (await this.records()).filter(r => r.grid === grid)) {+ if (await this.options.appEngines?.alive(record).catch(() => false)) served.push(record.alias)+ }+ return served+ }++ /** Joins this computer's first live app engine on [grid] again, as it was started: grid restarts its one engine+ * process for the grid with every model this computer joined there, so this also brings back an API shared beside it+ * (2026-10-24: after a daemon restart the grid listed nothing this Mac served). Whether grid took it. */+ async rejoinApp(grid: string): Promise<boolean> {+ for (const record of (await this.records()).filter(r => r.grid === grid)) {+ if (!await this.options.appEngines?.alive(record).catch(() => false)) continue+ const named = this.options.machineName?.()?.trim()+ return (await this.run(['--remote', 'join', grid, '--at', `http://127.0.0.1:${record.port}/v1`, '-m', record.served,+ '--advertise-as', record.alias, '--max-concurrency', String(NODE_CONCURRENCY),+ ...(named && validArg(named) ? ['--name', named] : [])], undefined, 10 * 60_000)).ok+ }+ return false+ }+/** A Jev engine still running: stopped, and off its grid (best effort — its record is already gone). */private async retire(record: AppEngineRecord): Promise<void> {try {diff --git a/cli/src/lib/swarmApiShares.spec.ts b/cli/src/lib/swarmApiShares.spec.tsindex 5b4e25656..761011cbc 100644--- a/cli/src/lib/swarmApiShares.spec.ts+++ b/cli/src/lib/swarmApiShares.spec.ts@@ -96,27 +96,72 @@ describe('an API shared with a Swarm', () => {expect(stuck.shares.list()).toHaveLength(1)})- it('notes its shares without the key, and the next process shares them again', async () => {+ it('joins a share again at the address it has, never leaving first, and shares one it does not have', async () => {+ const f = setup(); open = f.shares+ await f.shares.share(GRID, 'c1', 'm')+ const before = f.at()+ expect(await f.shares.rejoin(GRID, 'c1', 'm')).toEqual({ ok: true })+ expect(f.exec.mock.calls.map(c => c[0].slice(0, 2))).toEqual([['--remote', 'join'], ['--remote', 'join']])+ expect(f.exec.mock.calls[1]![0][f.exec.mock.calls[1]![0].indexOf('--at') + 1]).toBe(before)+ f.exec.mockResolvedValueOnce({ ...ok, code: 'GRID_FAILED', exitCode: 1, stderr: 'busy' })+ expect(await f.shares.rejoin(GRID, 'c1', 'm')).toEqual({ error: 'busy' })+ f.exec.mockRejectedValueOnce(new Error('gone'))+ expect(await f.shares.rejoin(GRID, 'c1', 'm')).toEqual({ error: 'grid could not be run on this computer.' })+ expect(f.shares.list(GRID)).toHaveLength(1)+ expect(await f.shares.rejoin(GRID, 'c1', 'other')).toEqual({ ok: true })+ expect(f.shares.list(GRID)).toHaveLength(2)+ })++ it('runs its joins and leaves one at a time, whoever asks', async () => {+ let running = 0, most = 0+ const f = setup({ exec: async () => { running++; most = Math.max(most, running); await new Promise(r => setTimeout(r, 10)); running--; return ok } })+ open = f.shares+ await Promise.all([f.shares.share(GRID, 'c1', 'a'), f.shares.share(GRID, 'c1', 'b'), f.shares.rejoin(GRID, 'c1', 'a'), f.shares.stop(GRID, 'c1', 'b')])+ expect(most).toBe(1)+ expect(f.shares.list(GRID).map(s => s.model)).toEqual(['a'])+ // A join that throws does not hold the rest up.+ f.exec.mockRejectedValueOnce(new Error('gone'))+ expect(await f.shares.share(GRID, 'c1', 'c')).toEqual({ error: 'grid could not be run on this computer.' })+ expect(await f.shares.share(GRID, 'c1', 'd')).toEqual({ ok: true })+ })++ it('notes its shares and their addresses without the key, and the next process shares them again where they were', async () => {const stateFile = join(await mkdtemp(join(tmpdir(), 'swarm-api-shares-')), 'shares.json')const f = setup({ stateFile }); open = f.sharesawait f.shares.share(GRID, 'c1', 'm')+ const at = f.at()const noted = await readFile(stateFile, 'utf8')- expect(JSON.parse(noted)).toEqual([{ grid: GRID, alias: 'm', connectionId: 'c1' }])+ const [port, token] = /^http:\/\/127\.0\.0\.1:(\d+)\/([0-9a-f]{36})\/v1$/.exec(at)!.slice(1)+ expect(JSON.parse(noted)).toEqual([{ grid: GRID, alias: 'm', connectionId: 'c1', port: Number(port), token }])expect(noted).not.toContain(KEY)await f.shares.stopAll()- // The process ended without stopping it: the note is still there.+ // The process ended without stopping it: the note is still there, and the share comes back at the same address,+ // joined without a leave.await writeFile(stateFile, noted)const next = setup({ stateFile }); open = next.sharesawait next.shares.restore()- expect(next.exec.mock.calls.map(c => c[0].slice(0, 3))).toEqual([['--remote', 'leave', GRID], ['--remote', 'join', GRID]])+ expect(next.exec.mock.calls.map(c => c[0].slice(0, 3))).toEqual([['--remote', 'join', GRID]])+ expect(next.at()).toBe(at)expect(next.shares.list()).toEqual([{ grid: GRID, connectionId: 'c1', model: 'm', name: 'OpenRouter' }])- expect(JSON.parse(await readFile(stateFile, 'utf8'))).toEqual([{ grid: GRID, alias: 'm', connectionId: 'c1' }])+ expect(JSON.parse(await readFile(stateFile, 'utf8'))).toEqual(JSON.parse(noted))+ // Its port taken meanwhile: the old address leaves first, and it joins at a new one.await next.shares.stopAll()- // A note from before connections were noted is taken off and not shared; junk, failures and no file break nothing.- await writeFile(stateFile, JSON.stringify([null, { grid: 7 }, { grid: GRID, alias: 'x' }]))- const old = setup({ stateFile })+ const blocker = (await import('node:net')).createServer()+ await new Promise<void>(resolve => blocker.listen(Number(port), '127.0.0.1', resolve))+ await writeFile(stateFile, noted)+ const moved = setup({ stateFile }); open = moved.shares+ await moved.shares.restore()+ expect(moved.exec.mock.calls.map(c => c[0].slice(0, 2))).toEqual([['--remote', 'leave'], ['--remote', 'join']])+ expect(moved.at()).not.toBe(at)+ await moved.shares.stopAll()+ blocker.close()+ // A note from before connections were noted is taken off and not shared; one from before addresses were noted is taken+ // off and shared anew; a token that is not one is no address. Junk, failures and no file break nothing.+ await writeFile(stateFile, JSON.stringify([null, { grid: 7 }, { grid: GRID, alias: 'x' }, { grid: GRID, alias: 'y', connectionId: 'c1', port: 70000, token: 'zz' }]))+ const old = setup({ stateFile }); open = old.sharesawait old.shares.restore()- expect(old.exec.mock.calls).toEqual([[['--remote', 'leave', GRID, '--engine', 'x']]])+ expect(old.exec.mock.calls.map(c => c[0].slice(0, 2))).toEqual([['--remote', 'leave'], ['--remote', 'leave'], ['--remote', 'join']])+ await old.shares.stopAll()await writeFile(stateFile, JSON.stringify([{ grid: GRID, alias: 'x', connectionId: 'c1' }]))const failing = setup({ stateFile, exec: async () => { throw new Error('gone') } })await failing.shares.restore()@@ -127,4 +172,5 @@ describe('an API shared with a Swarm', () => {await setup({ stateFile: join(stateFile, 'missing', 'x.json') }).shares.restore()await setup().shares.restore()})+})diff --git a/cli/src/lib/swarmApiShares.ts b/cli/src/lib/swarmApiShares.tsindex daa4fe4de..69c2e6713 100644--- a/cli/src/lib/swarmApiShares.ts+++ b/cli/src/lib/swarmApiShares.ts@@ -32,45 +32,79 @@ export interface SwarmApiSharesDeps {stateFile?: string}-interface Running extends SwarmApiShare { server: Server; alias: string }+interface Running extends SwarmApiShare { server: Server; alias: string; port: number; token: string }+/** Where a share listens: kept across restarts, so its address on the grid stays the same. */+type Address = { port: number; token: string }const keyOf = (s: Pick<SwarmApiShare, 'grid' | 'connectionId' | 'model'>) => `${s.grid}\0${s.connectionId}\0${s.model}`const said = (r: GridResult) => (r.stderr.trim() || r.message || 'grid refused the request.').slice(0, 400)export class SwarmApiShares {private readonly running = new Map<string, Running>()+ /** Every join and leave, one at a time: grid restarts its one engine process for a grid on each, and two at once killed+ * each other's process before either registered (2026-10-24: the restore and a heal right after a restart left the+ * grid with nothing; grid's log said another process held the engine's lock). */+ private queue: Promise<unknown> = Promise.resolve()constructor(private readonly deps: SwarmApiSharesDeps) {}+ private serial<T>(work: () => Promise<T>): Promise<T> {+ const next = this.queue.then(work, work)+ this.queue = next.catch(() => {})+ return next+ }+list(grid?: string): SwarmApiShare[] {return [...this.running.values()].filter(s => !grid || s.grid === grid).map(({ grid: g, connectionId, model, name }) => ({ grid: g, connectionId, model, name }))}/** Puts [model] of the saved API [connectionId] on [grid]. Sharing what is already shared answers as done. */- async share(grid: string, connectionId: string, model: string): Promise<{ ok: true } | { error: string }> {+ share(grid: string, connectionId: string, model: string): Promise<{ ok: true } | { error: string }> {+ return this.serial(() => this.shareNow(grid, connectionId, model))+ }++ /** Shares [model] at [at] when an earlier process noted one and it is free, else at a new address. Grid keys a joined+ * engine by its address (`_spec_key`): a new one each restart left the old, dead one in grid's engine record beside it,+ * and grid's engine process did not come up while it named one (2026-10-24). */+ private async shareNow(grid: string, connectionId: string, model: string, at?: Address): Promise<{ ok: true } | { error: string }> {const key = keyOf({ grid, connectionId, model })if (this.running.has(key)) return { ok: true }let access: { connection: ApiConnection; apiKey: string }try { access = this.deps.access(connectionId) } catch (error) { return { error: error instanceof Error ? error.message : 'This API is not saved.' } }- const token = randomBytes(18).toString('hex')- const server = this.serve(token, access)- const port = await new Promise<number>((resolve, reject) => {- server.once('error', reject)- server.listen(0, '127.0.0.1', () => resolve((server.address() as { port: number }).port))- }).catch(() => null)- if (port === null) return { error: 'This computer could not open a local endpoint for the API.' }- const joined = await this.deps.exec(['--remote', 'join', grid, '--at', `http://127.0.0.1:${port}/${token}/v1`, '-m', model,+ const listen = async (token: string, port: number) => {+ const server = this.serve(token, access)+ const bound = await new Promise<number>((resolve, reject) => {+ server.once('error', reject)+ server.listen(port, '127.0.0.1', () => resolve((server.address() as { port: number }).port))+ }).catch(() => null)+ return bound === null ? null : { server, port: bound, token }+ }+ const opened = (at ? await listen(at.token, at.port) : null) ?? await listen(randomBytes(18).toString('hex'), 0)+ if (!opened) return { error: 'This computer could not open a local endpoint for the API.' }+ // A noted share that could not keep its address: its old one goes first, or grid would keep naming it.+ if (at && (opened.port !== at.port || opened.token !== at.token)) {+ await this.deps.exec(['--remote', 'leave', grid, '--engine', model]).catch(() => {})+ }+ const joined = await this.join(grid, model, opened)+ if (joined?.code !== 'OK') { opened.server.close(); return { error: joined ? said(joined) : 'grid could not be run on this computer.' } }+ this.running.set(key, { grid, connectionId, model, name: access.connection.name, server: opened.server, alias: model, port: opened.port, token: opened.token })+ await this.note()+ return { ok: true }+ }++ private join(grid: string, model: string, at: Address): Promise<GridResult | null> {+ return this.deps.exec(['--remote', 'join', grid, '--at', `http://127.0.0.1:${at.port}/${at.token}/v1`, '-m', model,// No `--name`: on a remote grid it names this computer's node, not the engine, and an API's name there read as if// OpenRouter were the machine serving every model on it (2026-10-23).'--advertise-as', model, '--max-concurrency', String(CONCURRENCY)]).catch(() => null)- if (joined?.code !== 'OK') { server.close(); return { error: joined ? said(joined) : 'grid could not be run on this computer.' } }- this.running.set(key, { grid, connectionId, model, name: access.connection.name, server, alias: model })- await this.note()- return { ok: true }}/** Takes [model] off [grid] and closes its endpoint. Stopping what is not shared answers as done. */- async stop(grid: string, connectionId: string, model: string): Promise<{ ok: true } | { error: string }> {+ stop(grid: string, connectionId: string, model: string): Promise<{ ok: true } | { error: string }> {+ return this.serial(() => this.stopNow(grid, connectionId, model))+ }++ private async stopNow(grid: string, connectionId: string, model: string): Promise<{ ok: true } | { error: string }> {const running = this.running.get(keyOf({ grid, connectionId, model }))if (!running) return { ok: true }const left = await this.deps.exec(['--remote', 'leave', grid, '--engine', running.alias])@@ -81,24 +115,45 @@ export class SwarmApiShares {return { ok: true }}- /** Brings back the shares an earlier process noted: their endpoints died with it, so each is taken off its grid and- * shared again on a new one, reading the saved API afresh. One whose API is no longer saved, or that grid refuses,- * stays off: a person shares again from the Swarm's Local models. */- async restore(): Promise<void> {+ /** Joins [model] to [grid] again at the address it already has: grid merges it into what it serves and restarts its+ * engine process for the grid with every model this computer joined there (`swarmHeal.ts`). Never a leave first: a+ * remote leave stops every engine process of the grid, the one it just restarted too (grid `shared/orphan_sweep.py`),+ * and a leave-then-join left the grid with nothing (2026-10-24). */+ rejoin(grid: string, connectionId: string, model: string): Promise<{ ok: true } | { error: string }> {+ return this.serial(async () => {+ const running = this.running.get(keyOf({ grid, connectionId, model }))+ if (!running) return this.shareNow(grid, connectionId, model)+ const joined = await this.join(grid, model, running)+ return joined?.code === 'OK' ? { ok: true as const } : { error: joined ? said(joined) : 'grid could not be run on this computer.' }+ })+ }++ /** Brings back the shares an earlier process noted: their endpoints died with it, so each listens again at the address+ * it had and joins again, reading the saved API afresh. A note from before addresses were kept is taken off its grid+ * and shared at a new one. One whose API is no longer saved, or that grid refuses, stays off: a person shares again+ * from the Swarm's Manage models. */+ restore(): Promise<void> {+ return this.serial(() => this.restoreNow())+ }++ private async restoreNow(): Promise<void> {if (!this.deps.stateFile) returnconst noted = await readFile(this.deps.stateFile, 'utf8').then(text => JSON.parse(text) as unknown).catch(() => [])for (const row of Array.isArray(noted) ? noted : []) {- const { grid, alias, connectionId } = (row && typeof row === 'object' ? row : {}) as { grid?: unknown; alias?: unknown; connectionId?: unknown }+ const { grid, alias, connectionId, port, token } = (row && typeof row === 'object' ? row : {}) as Record<string, unknown>if (typeof grid !== 'string' || typeof alias !== 'string') continue- await this.deps.exec(['--remote', 'leave', grid, '--engine', alias]).catch(() => {})- if (typeof connectionId === 'string') await this.share(grid, connectionId, alias).catch(() => {})+ const at = typeof port === 'number' && Number.isInteger(port) && port > 0 && port < 65536 && typeof token === 'string' && /^[0-9a-f]{36}$/.test(token)+ ? { port, token } : undefined+ if (!at) await this.deps.exec(['--remote', 'leave', grid, '--engine', alias]).catch(() => {})+ if (typeof connectionId === 'string') await this.shareNow(grid, connectionId, alias, at).catch(() => {})}await this.note()}private async note(): Promise<void> {if (!this.deps.stateFile) return- await writeFile(this.deps.stateFile, JSON.stringify([...this.running.values()].map(({ grid, alias, connectionId }) => ({ grid, alias, connectionId }))), { mode: 0o600 }).catch(() => {})+ // The path token is noted (the file is the person's alone, 0600) so the address survives a restart; the key never is.+ await writeFile(this.deps.stateFile, JSON.stringify([...this.running.values()].map(({ grid, alias, connectionId, port, token }) => ({ grid, alias, connectionId, port, token }))), { mode: 0o600 }).catch(() => {})}/** Every share off its grid, as the process ends: an endpoint that is gone serves nothing. */diff --git a/cli/src/lib/swarmHeal.spec.ts b/cli/src/lib/swarmHeal.spec.tsnew file mode 100644index 000000000..f1c9f511d--- /dev/null+++ b/cli/src/lib/swarmHeal.spec.ts@@ -0,0 +1,68 @@+import { describe, expect, it, vi } from 'vitest'+import { HEAL_MS, liveModels, SwarmHeal } from './swarmHeal.js'++const GRID = 'swarm-0123456789ab'+const share = (model: string) => ({ grid: GRID, connectionId: 'c1', model, name: 'OpenRouter' })++function setup(patch: { live?: Set<string> | null | Error; shares?: string[]; apps?: string[] } = {}) {+ let now = 1_000_000+ const deps = {+ live: vi.fn(async () => { if (patch.live instanceof Error) throw patch.live; return patch.live === undefined ? new Set<string>() : patch.live }),+ shares: { list: vi.fn(() => (patch.shares ?? []).map(share)), rejoin: vi.fn(async () => ({ ok: true })) },+ apps: { served: vi.fn(async () => patch.apps ?? []), rejoin: vi.fn(async () => true) },+ now: () => now,+ }+ return { heal: new SwarmHeal(deps), deps, later: (ms: number) => { now += ms } }+}++describe('keeping this computer\'s models on a Swarm\'s grid', () => {+ it('says what the grid lists, and does nothing while it lists all of this computer\'s models', async () => {+ const f = setup({ live: new Set(['ds', 'llama', 'other']), shares: ['ds'], apps: ['llama'] })+ expect(await f.heal.check(GRID)).toEqual({ live: ['ds', 'llama', 'other'], missing: [] })+ expect(f.deps.shares.rejoin).not.toHaveBeenCalled()+ expect(f.deps.apps.rejoin).not.toHaveBeenCalled()+ })++ it('joins a missing API share again, then waits before trying again', async () => {+ const f = setup({ live: new Set(), shares: ['ds'], apps: ['llama'] })+ // Not in the process's first minutes, while the restore joins them.+ await f.heal.check(GRID)+ expect(f.deps.shares.rejoin).not.toHaveBeenCalled()+ f.later(HEAL_MS)+ expect(await f.heal.check(GRID)).toEqual({ live: [], missing: ['ds', 'llama'] })+ expect(f.deps.shares.rejoin).toHaveBeenCalledWith(GRID, 'c1', 'ds')+ // One join restarts grid's engine with every model: an app engine is not joined beside it.+ expect(f.deps.apps.rejoin).not.toHaveBeenCalled()+ f.later(HEAL_MS - 1)+ await f.heal.check(GRID)+ expect(f.deps.shares.rejoin).toHaveBeenCalledOnce()+ f.later(1)+ await f.heal.check(GRID)+ expect(f.deps.shares.rejoin).toHaveBeenCalledTimes(2)+ })++ it('joins an app engine again when no API share is missing, and a failing join breaks nothing', async () => {+ const f = setup({ live: new Set(['ds']), shares: ['ds'], apps: ['llama'] })+ f.later(HEAL_MS)+ f.deps.apps.rejoin.mockRejectedValueOnce(new Error('grid'))+ expect(await f.heal.check(GRID)).toEqual({ live: ['ds'], missing: ['llama'] })+ expect(f.deps.apps.rejoin).toHaveBeenCalledWith(GRID)+ })++ it('says nothing about a grid it could not read, and reads an app list that fails as none', async () => {+ expect(await setup({ live: null, shares: ['ds'] }).heal.check(GRID)).toEqual({ live: null, missing: [] })+ expect(await setup({ live: new Error('offline'), shares: ['ds'] }).heal.check(GRID)).toEqual({ live: null, missing: [] })+ const f = setup({ live: new Set() })+ f.deps.apps.served.mockRejectedValueOnce(new Error('state'))+ expect(await f.heal.check(GRID)).toEqual({ live: [], missing: [] })+ // With the default clock too.+ const plain = new SwarmHeal({ ...f.deps, now: undefined })+ expect(await plain.check(GRID)).toEqual({ live: [], missing: [] })+ })++ it('reads the models a `grid models --json` answer lists', () => {+ expect(liveModels('[{"model":"ds","node":"m"},{"model":7},null,{"engine":"x"}]')).toEqual(new Set(['ds']))+ expect(liveModels('{"model":"ds"}')).toBeNull()+ expect(liveModels('(no live models)')).toBeNull()+ })+})diff --git a/cli/src/lib/swarmHeal.ts b/cli/src/lib/swarmHeal.tsnew file mode 100644index 000000000..5f9afada1--- /dev/null+++ b/cli/src/lib/swarmHeal.ts@@ -0,0 +1,55 @@+/**+ * What this computer serves on a Swarm's grid, checked against what the grid lists, and joined again when the grid lost+ * it (docs/plans/2026-10-23-swarm-local-models.md). 2026-10-24: after a few daemon restarts in a row the grid listed none+ * of this Mac's models, while its shares and its local model were still "shared" here. Grid runs one engine process per+ * grid for every model a computer joins there, and each join restarts it: the restore's leave-and-join per share killed+ * the process before it registered, and nothing looked again. Builders then waited without end for a model the grid did+ * not have. Read every pass (`superTabs/machines.ts`), this joins once more, at most every [HEAL_MS], and tells the+ * reading what is really live, so the route never offers a model the grid cannot reach.+ */+import type { SwarmApiShare } from './swarmApiShares.js'++/** How long a join is given to register before another is tried: grid's engine process takes seconds to come up. */+export const HEAL_MS = 3 * 60_000++export interface SwarmHealDeps {+ /** The model names the grid lists as live, or null when the grid could not be read. */+ live: (grid: string) => Promise<Set<string> | null>+ shares: { list: (grid: string) => SwarmApiShare[]; rejoin: (grid: string, connectionId: string, model: string) => Promise<unknown> }+ apps: { served: (grid: string) => Promise<string[]>; rejoin: (grid: string) => Promise<boolean> }+ now?: () => number+}++export class SwarmHeal {+ private readonly tried = new Map<string, number>()+ /** Nothing is joined in the first [HEAL_MS] of the process: the shares' restore joins them then, and the grid lists them+ * only once that has registered. */+ private readonly started: number+ constructor(private readonly deps: SwarmHealDeps) { this.started = (deps.now ?? Date.now)() }++ /** What [grid] lists as live (null: unknown), and which of this computer's models it lacks. One of those is joined+ * again when none was in the last [HEAL_MS]: an API share if one is missing, else an app engine. */+ async check(grid: string): Promise<{ live: string[] | null; missing: string[] }> {+ const live = await this.deps.live(grid).catch(() => null)+ if (!live) return { live: null, missing: [] }+ const shares = this.deps.shares.list(grid)+ const mine = [...shares.map(s => s.model), ...await this.deps.apps.served(grid).catch(() => [])]+ const missing = mine.filter(model => !live.has(model))+ const now = (this.deps.now ?? Date.now)()+ if (missing.length && now - (this.tried.get(grid) ?? this.started) >= HEAL_MS) {+ this.tried.set(grid, now)+ const share = shares.find(s => missing.includes(s.model))+ await (share ? this.deps.shares.rejoin(grid, share.connectionId, share.model) : this.deps.apps.rejoin(grid)).catch(() => {})+ }+ return { live: [...live], missing }+ }+}++/** The models a `grid --remote models GRID --json` answer lists. */+export function liveModels(stdout: string): Set<string> | null {+ let rows: unknown+ try { rows = JSON.parse(stdout) } catch { return null }+ if (!Array.isArray(rows)) return null+ return new Set(rows.flatMap(row => row && typeof row === 'object' && typeof (row as { model?: unknown }).model === 'string'+ ? [(row as { model: string }).model] : []))+}diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.tsindex 99c3058ae..29c852558 100644--- a/cli/src/services/models.spec.ts+++ b/cli/src/services/models.spec.ts@@ -43,6 +43,7 @@ const apiShares = vi.hoisted(() => ({share: vi.fn(async () => ({ ok: true })), stop: vi.fn(async () => ({ ok: true })),list: vi.fn((_grid?: string) => [{ grid: 'swarm-0123456789ab', connectionId: 'c1', model: 'm', name: 'OpenRouter' }]),restore: vi.fn(async (): Promise<void> => {}),+ rejoin: vi.fn(async () => ({ ok: true })),}))const swarmOffers = vi.hoisted(() => ({set: vi.fn((): unknown[] => [{ grid: 'swarm-0123456789ab', sharedGrid: 'team', model: 'muse' }]),@@ -104,6 +105,8 @@ const local = vi.hoisted(() => ({list: vi.fn(async (_grid: string | null, _force?: boolean): Promise<Record<string, unknown>> => ({ models: [], busy: false, observedAt: 'now' })),act: vi.fn(async (_grid: string | null, _modelId: unknown, _action: string): Promise<Record<string, unknown>> => ({})),communityGrid: vi.fn(async (): Promise<string | null> => 'Omagrid'),+ servedApps: vi.fn(async (_grid: string): Promise<string[]> => []),+ rejoinApp: vi.fn(async (_grid: string): Promise<boolean> => true),}))vi.mock('../lib/localModels.js', () => ({LocalModels: class {@@ -111,6 +114,8 @@ vi.mock('../lib/localModels.js', () => ({list = local.listact = local.actcommunityGrid = local.communityGrid+ servedApps = local.servedApps+ rejoinApp = local.rejoinApp},}))@@ -441,6 +446,31 @@ describe('the models service', () => {expect(gridExec).toHaveBeenLastCalledWith(['--remote', 'ls'])})+ it('says what a Swarm\'s grid lists, and joins this computer\'s models again when it lost them', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const { requests } = setup()+ // Past the first minutes of the process, when the shares' restore joins them itself.+ vi.setSystemTime(Date.now() + 10 * 60_000)+ const heal = requests.grid_swarm_heal!+ vi.mocked(gridExec).mockResolvedValueOnce({ code: 'OK', exitCode: 0, stdout: '[{"model":"llama"}]', stderr: '', message: '' })+ local.servedApps.mockResolvedValueOnce(['llama'])+ // The shared API is missing: it is joined again, which brings the rest back beside it.+ expect(await heal({ grid: 'swarm-0123456789ab' }, asker)).toEqual({ live: ['llama'], missing: ['m'] })+ expect(apiShares.rejoin).toHaveBeenCalledWith('swarm-0123456789ab', 'c1', 'm')+ expect(gridExec).toHaveBeenCalledWith(['--remote', 'models', 'swarm-0123456789ab', '--json'])+ // A grid that cannot be read says nothing, and joins nothing.+ vi.mocked(gridExec).mockResolvedValueOnce({ code: 'GRID_FAILED', exitCode: 1, stdout: '', stderr: 'offline', message: '' })+ expect(await heal({ grid: 'swarm-0123456789ab' }, asker)).toEqual({ live: null, missing: [] })+ expect(await heal({ grid: 'team' }, asker)).toEqual({ error: 'INVALID_REQUEST' })+ // Only an app engine missing, on another grid not tried yet: the app engine is joined again.+ apiShares.list.mockReturnValueOnce([])+ vi.mocked(gridExec).mockResolvedValueOnce({ code: 'OK', exitCode: 0, stdout: '[]', stderr: '', message: '' })+ local.servedApps.mockResolvedValueOnce(['llama'])+ expect(await heal({ grid: 'swarm-ba9876543210' }, asker)).toEqual({ live: [], missing: ['llama'] })+ expect(local.rejoinApp).toHaveBeenCalledWith('swarm-ba9876543210')+ vi.useRealTimers()+ })+it('offers a model shared with this computer\'s person to a Swarm, for them only, and lists what is offered', async () => {const { requests } = setup()const offer = requests.grid_swarm_offer!diff --git a/cli/src/services/models.ts b/cli/src/services/models.tsindex 46ea62603..dad70ee12 100644--- a/cli/src/services/models.ts+++ b/cli/src/services/models.ts@@ -43,6 +43,7 @@ import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'import { ensureManagedGrid, startGridPinRecheck } from '../lib/runtimeInstall.js'import { syncSwarmGrid } from '../lib/swarmGrid.js'import { SwarmApiShares } from '../lib/swarmApiShares.js'+import { liveModels, SwarmHeal } from '../lib/swarmHeal.js'import { SwarmOffers } from '../lib/swarmOffers.js'import { internalOnThrow } from './requestErrors.js'@@ -276,6 +277,17 @@ function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => PappEngines: appEngineOps(process.env),gpuProcesses: nvidiaComputeApps,})+ // One set of shared APIs for the process, and the check that keeps them and the local models on each Swarm's grid+ // (lib/swarmHeal.ts).+ const shares = swarmApiShares(core.dataDir)+ const heal = new SwarmHeal({+ live: async (name) => {+ const answer = await gridExec(['--remote', 'models', name, '--json'])+ return answer.code === 'OK' ? liveModels(answer.stdout) : null+ },+ shares: { list: (name) => shares.list(name), rejoin: (name, connectionId, model) => shares.rejoin(name, connectionId, model) },+ apps: { served: (name) => localModels.servedApps(name), rejoin: (name) => localModels.rejoinApp(name) },+ })/** The grid listing currently out, shared by every `grid_models_list` for the same own grid that lands* meanwhile. */let listing: { gridName: string | null; grids: Promise<GridSection[]> } | null = null@@ -382,7 +394,13 @@ function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => Pgrid_fleet_model_download: localModel('grid_fleet_model_download'),grid_fleet_model_start: localModel('grid_fleet_model_start'),grid_fleet_model_stop: localModel('grid_fleet_model_stop'),- ...gridCommands(grid, core.dataDir),+ // What this computer serves on a Swarm's grid that the grid really lists, joined again when it lost them: read by+ // every machine reading (superTabs/machines.ts).+ grid_swarm_heal: async (payload) => {+ if (typeof payload.grid !== 'string' || !SWARM_GRID.test(payload.grid)) return { error: 'INVALID_REQUEST' }+ return { ...await heal.check(payload.grid) }+ },+ ...gridCommands(grid, core.dataDir, shares),...launchTargetRequests(core),}}diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex f19a4ec0c..ecf6e8d7c 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -5,7 +5,7 @@ import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../lib/registry.js'import { fakeCore } from '../testing/fakeCore.js'-import { apisOn, ContributedMachines, offered, servedOn, sharedWith, swarmWorktreesFile } from './machines.js'+import { apisOn, ContributedMachines, liveOn, offered, refusedOn, servedOn, sharedWith, swarmWorktreesFile } from './machines.js'import { SuperTabHostError } from './host.js'import { startAgent } from './start.js'@@ -167,6 +167,20 @@ describe('contributed machine executor', () => {? { models: [{ name: 'Qwen 3', contextWindow: 32768, servedOn: [{ grid: GRID, servedAs: ['qwen3'] }] }] } : { providers: [] }) as never)f.advance(); await f.machine.tick()expect(f.backend.mock.calls.filter(c => c[1] === 'POST').at(-1)![3]).toMatchObject({ localModels: [{ grid: GRID, model: 'qwen3', name: 'Qwen 3', contextWindow: 32768, kind: 'local' }] })+ expect(f.backend.mock.calls.filter(c => c[1] === 'POST').at(-1)![3]).not.toHaveProperty('refusedModels')+ // A model too small for Builders is reported apart, with why; an older backend that refuses the field gets it without.+ local.request.mockImplementation((async (type: string) => type === 'grid_fleet_models_list'+ ? { models: [{ name: 'llama3.2:3b', servedOn: [{ grid: GRID, servedAs: ['llama3.2:3b'] }] }] } : { providers: [] }) as never)+ const before = f.backend.getMockImplementation()!+ f.backend.mockImplementation(async (core, method, path, body) => {+ if (method === 'POST' && (body as Record<string, unknown>)?.refusedModels) throw new SuperTabHostError('VALIDATION_ERROR', 'Unrecognized key: refusedModels', 400)+ return before(core, method, path, body)+ })+ f.advance(); await f.machine.tick()+ const refusedPosts = f.backend.mock.calls.filter(c => c[1] === 'POST')+ expect(refusedPosts.at(-2)![3]).toMatchObject({ localModels: [], refusedModels: [{ grid: GRID, model: 'llama3.2:3b', name: 'llama3.2:3b', why: expect.stringContaining('too small') }] })+ expect(refusedPosts.at(-1)![3]).not.toHaveProperty('refusedModels')+ f.backend.mockImplementation(before)// A failed read serves nothing; an older backend that refuses the field gets the observation without it.local.request.mockImplementation((async (type: string) => { if (type === 'grid_fleet_models_list') throw new Error('timeout'); return { providers: [] } }) as never)const original = f.backend.getMockImplementation()!@@ -201,6 +215,30 @@ describe('contributed machine executor', () => {f.step(60_000); await f.machine.tick()expect(reads()).toBe(before + 1)})+ it('reports what it serves on the Swarm\'s grid only while the grid lists it, and everything when the grid is unread', async () => {+ const GRID = 'swarm-0123456789ab'+ const f = fixture()+ Object.assign(f.pool, { localGrid: GRID })+ await f.machine.tick()+ const local = (await f.open.mock.results[0]!.value) as { request: ReturnType<typeof vi.fn> }+ let heal: unknown = { live: ['qwen3'], missing: ['deepseek/deepseek-chat'] }+ local.request.mockImplementation((async (type: string) => type === 'grid_swarm_api_shares'+ ? { shares: [{ grid: GRID, connectionId: 'c1', model: 'deepseek/deepseek-chat' }] }+ : type === 'grid_fleet_models_list' ? { models: [{ servedOn: [{ grid: GRID, servedAs: ['qwen3'] }] }] }+ : type === 'grid_swarm_heal' ? heal : { providers: [] }) as never)+ const reported = async () => { f.advance(); await f.machine.tick(); return (f.backend.mock.calls.filter(c => c[1] === 'POST').at(-1)![3] as { localModels: Array<{ model: string }> }).localModels.map(m => m.model) }+ expect(await reported()).toEqual(['qwen3'])+ expect(local.request).toHaveBeenCalledWith('grid_swarm_heal', { grid: GRID }, 30_000)+ heal = { live: null, missing: [] }+ expect(await reported()).toEqual(['qwen3', 'deepseek/deepseek-chat'])+ heal = Promise.reject(new Error('older daemon'))+ expect(await reported()).toEqual(['qwen3', 'deepseek/deepseek-chat'])+ })+ it('reads the models a heal answer says are live', () => {+ expect(liveOn({ live: ['a', 7, 'b'] })).toEqual(new Set(['a', 'b']))+ expect(liveOn({ live: null })).toBeNull()+ expect(liveOn(null)).toBeNull()+ })it('keeps of the models shared with its owner only those they offer', () => {const shared = [{ grid: 'team', model: 'a', kind: 'shared' as const }, { grid: 'team', model: 'b', kind: 'shared' as const }]expect(offered(shared, { offers: [{ sharedGrid: 'team', model: 'b' }] })).toEqual([shared[1]])@@ -218,6 +256,20 @@ describe('contributed machine executor', () => {.toEqual([{ grid: GRID, model: 'm', kind: 'api' }])expect(apisOn(null, GRID)).toEqual([])})+ it('leaves out a served model too small or too slow for a coding agent', () => {+ const GRID = 'swarm-0123456789ab'+ const on = (servedAs: string, more: Record<string, unknown> = {}) => ({ ...more, servedOn: [{ grid: GRID, servedAs: [servedAs] }] })+ expect(servedOn({ models: [+ on('llama3.2:3b', { name: 'llama3.2:3b', sizeBytes: 2e9 }), on('Qwen3-4B'), on('slow', { name: 'Qwen3.6-35B-A3B', estTokS: 3 }),+ on('fast', { name: 'Qwen3.6-35B-A3B', estTokS: 3, tokensPerSecond: 40, paramsB: 35, quant: 'Q4_K_M' }), on('gemma', { name: 'gemma-4-E2B-it', sizeBytes: 3.2e9 }),+ ] }, GRID).map(m => m.model)).toEqual(['fast'])+ // What is left out is reported with why, so a Lead asked for it hears that rather than to share it.+ expect(refusedOn({ models: [on('llama3.2:3b', { name: 'llama3.2:3b', sizeBytes: 2e9 }), on('Qwen3-4B'), on('fast', { paramsB: 35, tokensPerSecond: 40 })] }, GRID)).toEqual([+ { grid: GRID, model: 'llama3.2:3b', name: 'llama3.2:3b', why: 'llama3.2:3b is too small for a coding agent (about 3B parameters; Builders need 7B or more).' },+ { grid: GRID, model: 'Qwen3-4B', why: 'Qwen3-4B is too small for a coding agent (about 4B parameters; Builders need 7B or more).' },+ ])+ expect(refusedOn(null, GRID)).toEqual([])+ })it('reads a served model by the first name grid lists it under, and keeps sixteen at most', () => {const GRID = 'swarm-0123456789ab'expect(servedOn(null, GRID)).toEqual([])diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex 862ac94a5..320162202 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -3,6 +3,7 @@ import { lstat, readFile, realpath, rm } from 'node:fs/promises'import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'import type { CoreApi } from '../core/api.js'import { openDaemon } from '../agentClient/daemon.js'+import { codingRefusal } from '../lib/codingModel.js'import { backend, SuperTabHostError } from './host.js'import { identifier, object } from './wire.js'import { readCapabilities, quotaOf, meteredEngine } from './capacity.js'@@ -183,13 +184,22 @@ export class ContributedMachines {: listedEngines.filter(supported)// Only while the owner has the Local models add-on on: the models this machine serves on the Swarm's grid (its own// engines, the APIs it shares), then the ones shared with its owner that they offer to this Swarm (usable here alone).+ // What this machine serves there counts only while the Swarm's grid lists it: the grid can lose a model this+ // machine still thinks it shares, and a Builder sent to one waits without end (lib/swarmHeal.ts, which also joins+ // it again). Unknown — the grid could not be read — keeps the reading as it is.+ const live = typeof row.localGrid === 'string'+ ? liveOn(await local.request('grid_swarm_heal', { grid: row.localGrid }, 30_000).catch(() => ({}))) : null+ const listed = (m: LocalModelReading) => !live || live.has(m.model)+ const fleet = typeof row.localGrid === 'string' ? await local.request('grid_fleet_models_list', {}, 20_000).catch(() => ({})) : null+ const refusedModels = typeof row.localGrid === 'string' ? refusedOn(fleet, row.localGrid) : []const localModels = typeof row.localGrid === 'string' ? [- ...servedOn(await local.request('grid_fleet_models_list', {}, 20_000).catch(() => ({})), row.localGrid),- ...apisOn(await local.request('grid_swarm_api_shares', { grid: row.localGrid }, 10_000).catch(() => ({})), row.localGrid),+ ...servedOn(fleet, row.localGrid).filter(listed),+ ...apisOn(await local.request('grid_swarm_api_shares', { grid: row.localGrid }, 10_000).catch(() => ({})), row.localGrid).filter(listed),...offered(sharedWith(await this.gridModels(local), row.localGrid),await local.request('grid_swarm_offers', { grid: row.localGrid }, 10_000).catch(() => ({}))),].slice(0, MAX_LOCAL_MODELS) : nullconst observation = { generation: pool.generation, tools: reportedTools, ...(localModels ? { localModels } : {}),+ ...(refusedModels.length ? { refusedModels } : {}),...(Object.keys(toolProbeErrors).length ? { toolProbeErrors } : {}),resources: { cpuPercent: finite(resources.cpuPercent), memoryUsedBytes: finite(resources.memoryUsedBytes), memoryTotalBytes: finite(resources.memoryTotalBytes),diskFreeBytes: finite(resources.diskFreeBytes), diskTotalBytes: finite(resources.diskTotalBytes), projectDiskFreeBytes: finite(resources.projectDiskFreeBytes), projectDiskTotalBytes: finite(resources.projectDiskTotalBytes),@@ -207,9 +217,9 @@ export class ContributedMachines {const path = `/api/super-tabs/${row.tabId}/machines/${this.machineId}`try { await this.deps.backend(this.core, 'POST', path, observation) }catch (error) {- if (!(error instanceof SuperTabHostError) || error.status !== 400 || error.code !== 'VALIDATION_ERROR' || !('toolProbeErrors' in observation || 'localModels' in observation)) throw error+ if (!(error instanceof SuperTabHostError) || error.status !== 400 || error.code !== 'VALIDATION_ERROR' || !('toolProbeErrors' in observation || 'localModels' in observation || 'refusedModels' in observation)) throw error// Older backends reject the additive fields. Their boolean-only view still safely refuses an unverified tool.- const { toolProbeErrors: _probeErrors, localModels: _served, ...legacy } = observation+ const { toolProbeErrors: _probeErrors, localModels: _served, refusedModels: _refused, ...legacy } = observationawait this.deps.backend(this.core, 'POST', path, legacy)}this.published.set(String(row.tabId), { at: began, signature })@@ -344,6 +354,13 @@ const SWARM_GRID = /^swarm-[0-9a-f]{12}$/type LocalModelReading = { grid: string; model: string; name?: string; contextWindow?: number; kind: 'local' | 'api' | 'shared' }+/** The models a `grid_swarm_heal` answer says the Swarm's grid lists, or null when it could not say (an older daemon, or+ * the grid unread). */+export function liveOn(answer: unknown): Set<string> | null {+ const live = object(answer).live+ return Array.isArray(live) ? new Set(live.filter((m): m is string => typeof m === 'string')) : null+}+/** The APIs a `grid_swarm_api_shares` answer says this machine shares on [grid] (`lib/swarmApiShares.ts`). */export function apisOn(answer: unknown, grid: string): LocalModelReading[] {return list(object(answer).shares).filter(s => s.grid === grid && typeof s.model === 'string' && s.model.length > 0 && s.model.length <= 200)@@ -372,15 +389,31 @@ export function offered(shared: LocalModelReading[], answer: unknown): LocalModereturn shared.filter(m => offers.has(`${m.grid}\0${m.model}`))}-/** The models a `grid_fleet_models_list` answer says this machine serves on [grid], by the name grid lists each under. */-export function servedOn(answer: unknown, grid: string): LocalModelReading[] {- const out: LocalModelReading[] = []+/** The models a `grid_fleet_models_list` answer says this machine serves on [grid], by the name grid lists each under,+ * each with why Builders are not offered it when it is too small or too slow to drive a coding agent (lib/codingModel.ts). */+function fleetOn(answer: unknown, grid: string): Array<LocalModelReading & { why: string | null }> {+ const out: Array<LocalModelReading & { why: string | null }> = []+ const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : undefinedfor (const model of list(object(answer).models)) {const on = list(model.servedOn).find(s => s.grid === grid)const served = Array.isArray(on?.servedAs) ? on.servedAs.find((n): n is string => typeof n === 'string' && n.length > 0 && n.length <= 200) : undefinedif (!served || out.length >= 16) continue+ const why = codingRefusal({ name: typeof model.name === 'string' ? model.name : served, paramsB: num(model.paramsB), sizeBytes: num(model.sizeBytes),+ quantization: typeof model.quant === 'string' ? model.quant : undefined, tokensPerSecond: num(model.tokensPerSecond), estTokS: num(model.estTokS) })out.push({ grid, model: served, ...(typeof model.name === 'string' ? { name: model.name.slice(0, 200) } : {}),- ...(typeof model.contextWindow === 'number' && Number.isInteger(model.contextWindow) && model.contextWindow > 0 ? { contextWindow: model.contextWindow } : {}), kind: 'local' })+ ...(typeof model.contextWindow === 'number' && Number.isInteger(model.contextWindow) && model.contextWindow > 0 ? { contextWindow: model.contextWindow } : {}), kind: 'local', why })}return out}++/** The models this machine serves on [grid] that Builders may run on. One too small or too slow to drive a coding agent is+ * left out: the route never offers it ([refusedOn] says why). */+export function servedOn(answer: unknown, grid: string): LocalModelReading[] {+ return fleetOn(answer, grid).filter(m => m.why === null).map(({ why: _why, ...reading }) => reading)+}++/** The models this machine serves on [grid] that Builders are not offered, with why: a Lead asked for one is told that,+ * not to share a model the Swarm already has (2026-10-24). */+export function refusedOn(answer: unknown, grid: string): Array<{ grid: string; model: string; name?: string; why: string }> {+ return fleetOn(answer, grid).flatMap(({ grid: g, model, name, why }) => why === null ? [] : [{ grid: g, model, ...(name ? { name } : {}), why: why.slice(0, 300) }])+}diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.tsindex 80476a907..bf4e4f630 100644--- a/cli/src/superTabs/route.spec.ts+++ b/cli/src/superTabs/route.spec.ts@@ -1,6 +1,6 @@// cli/src/superTabs/route.spec.tsimport { describe, expect, it } from 'vitest'-import { LOCAL_NONE, breaks, choose, decide, floorFor, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, type Assessment, type Commitment, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'+import { API_BUILDERS, LOCAL_NONE, breaks, choose, decide, floorFor, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, type Assessment, type Commitment, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'const object = (v: unknown) => v as Record<string, unknown>@@ -532,10 +532,43 @@ describe('local models on the Swarm\'s grid', () => {expect(ok(choose([opus, api], policy, a({ model: 'Claude Opus' }), NOW)).shown.map(s => s.model)).toEqual(['opus'])expect(ok(choose([older], policy, a({ difficulty: 'low' }), NOW)).shown[0]!.title).toContain('(shared)')expect(choose([opus], policy, a({ model: 'gpt 9' }), NOW)).toEqual({ error: 'NO_CANDIDATE',- excluded: [{ title: 'Named model', reason: 'No candidate runs "gpt 9". Share it with the Swarm (Local models), or check its name.' }] })+ excluded: [{ title: 'Named model', reason: 'No candidate runs "gpt 9". Share it with the Swarm (Manage models), or check its name.' }] })expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', model: ' deepseek 4.1 flash ' })).toMatchObject({ model: 'deepseek 4.1 flash' })expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', model: '...' })).toContain('model')expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', model: 7 })).toContain('model')expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', model: 'x'.repeat(201) })).toContain('model')})++ it('puts a model that runs on a machine before an API or another grid\'s model, at equal cost and strength', () => {+ const api = local({ gridModel: 'aaa-api', gridLabel: 'aaa-api', gridKind: 'api' })+ const shared = local({ gridModel: 'aab-shared', gridLabel: 'aab-shared', gridKind: 'shared' })+ const engine = local({ gridModel: 'zzz-llama', gridLabel: 'zzz-llama', gridKind: 'local' })+ expect(ok(choose([api, shared, engine], policy, a({ local: true }), NOW)).shown.map(s => s.gridModel)).toEqual(['zzz-llama', 'aaa-api', 'aab-shared'])+ // A model with no kind runs on the Swarm's grid, as an engine does.+ const bare = local({ gridModel: 'zzz-bare', gridLabel: 'zzz-bare', gridKind: undefined })+ expect(ok(choose([api, bare], policy, a({ local: true }), NOW)).shown.map(s => s.gridModel)).toEqual(['zzz-bare', 'aaa-api'])+ })++ it('offers the Builder already on a named model, and says who holds a named or local model it cannot offer', () => {+ // A member running the named model is a candidate like any other.+ const wren = probe({ kind: 'member', agentId: 'wren', name: 'Wren', model: 'deepseek/deepseek-v4.1-flash-1017', effort: 'xhigh', quality: 1, cost: 1 })+ expect(ok(choose([probe(), wren], policy, a({ model: 'deepseek 4.1 flash' }), NOW)).shown.map(s => s.agentId)).toEqual(['wren'])+ const ds = { model: 'deepseek/deepseek-v4.1-flash-1017', label: 'deepseek/deepseek-v4.1-flash-1017 · OpenRouter', kind: 'api' as const, holders: ['Wren', 'Ada', 'Bo', 'Cy'] }+ const qwen = { model: 'qwen3:4b', label: 'Qwen 3 4B', kind: 'local' as const, holders: ['Faye'] }+ expect(choose([probe()], policy, a({ model: 'deepseek 4.1 flash' }), NOW, [], [], [qwen, ds])).toEqual({ error: 'NO_CANDIDATE', excluded: [{ title: 'Named model',+ reason: `"deepseek/deepseek-v4.1-flash-1017 · OpenRouter" is shared with the Swarm, but Builders Wren, Ada, Bo and Cy are on it: an API model takes ${API_BUILDERS} Builders at a time. Assign the work to one of them once it is free, or stop one to free the model.` }] })+ // A name nothing holds still reads as not shared.+ expect(choose([probe()], policy, a({ model: 'gpt 9' }), NOW, [], [], [qwen])).toMatchObject({ excluded: [{ reason: expect.stringContaining('No candidate runs "gpt 9"') }] })+ expect(choose([probe()], policy, a({ local: true }), NOW, [], [], [qwen])).toEqual({ error: 'NO_CANDIDATE', excluded: [{ title: 'Local models',+ reason: '"Qwen 3 4B" is shared with the Swarm, but Builder Faye is on it: a local model serves one Builder at a time. Assign the work to that Builder once it is free, or stop it to free the model.' }] })+ expect(LOCAL_NONE).toContain('Manage models')+ })++ it('says why a named model the Swarm has is never offered to Builders, rather than to share it', () => {+ const llama = { model: 'llama3.2:3b', label: 'llama3.2:3b', kind: 'local' as const, holders: [],+ refused: 'llama3.2:3b is too small for a coding agent (about 3B parameters; Builders need 7B or more).' }+ const reason = '"llama3.2:3b" is shared with the Swarm, but Builders are not offered it: llama3.2:3b is too small for a coding agent (about 3B parameters; Builders need 7B or more). Ask a member to run a larger model, or share an API (Manage models).'+ expect(choose([probe()], policy, a({ model: 'llama 3.2 3b' }), NOW, [], [], [llama])).toEqual({ error: 'NO_CANDIDATE', excluded: [{ title: 'Named model', reason }] })+ expect(choose([probe()], policy, a({ local: true }), NOW, [], [], [llama])).toEqual({ error: 'NO_CANDIDATE', excluded: [{ title: 'Local models', reason }] })+ })})diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.tsindex 2ad5348cd..387e4098c 100644--- a/cli/src/superTabs/route.ts+++ b/cli/src/superTabs/route.ts@@ -186,7 +186,23 @@ function runsNamed(p: Probe, named: string): boolean {const name = words([p.gridModel ?? p.model, p.gridLabel ?? '', ENGINE[p.engine]].join(' ')).join('')return words(named).every(w => name.includes(w))}-const NAMED_NONE = (named: string) => `No candidate runs "${named}". Share it with the Swarm (Local models), or check its name.`+const NAMED_NONE = (named: string) => `No candidate runs "${named}". Share it with the Swarm (Manage models), or check its name.`++/** How many Builders may run on one API model a member shares: the share answers four requests at once+ * (cli/src/lib/swarmApiShares.ts CONCURRENCY), unlike a local engine, which answers one conversation at a time. */+export const API_BUILDERS = 4++/** A model served for the Swarm that takes no more Builders, and who is on it, or that Builders are never offered and why+ * ([refused]: too small or too slow to drive a coding agent) (routeCommand.ts heldLocalModels). */+export interface HeldModel { model: string; label: string; kind: 'local' | 'api' | 'shared'; holders: string[]; refused?: string }++/** Why a held model is not offered, and what frees it: a model in use reads as unshared otherwise (owner, 2026-10-24). */+function heldReason(m: HeldModel): string {+ if (m.refused) return `"${m.label}" is shared with the Swarm, but Builders are not offered it: ${m.refused} Ask a member to run a larger model, or share an API (Manage models).`+ const who = m.holders.length === 1 ? `Builder ${m.holders[0]} is on it` : `Builders ${m.holders.slice(0, -1).join(', ')} and ${m.holders.at(-1)} are on it`+ const limit = m.kind === 'api' ? `an API model takes ${API_BUILDERS} Builders at a time` : 'a local model serves one Builder at a time'+ return `"${m.label}" is shared with the Swarm, but ${who}: ${limit}. Assign the work to ${m.holders.length === 1 ? 'that Builder once it is free, or stop it' : 'one of them once it is free, or stop one'} to free the model.`+}const titleOf = (p: Probe) => cut(`${p.kind === 'member' ? p.name ?? 'Member' : 'New agent'} · ${runs(p)} · ${p.machineName}`, 160)/** A reset or a last activity is told as how far away it is, which reads the same whenever the log is opened. */function span(ms: number): string {@@ -275,19 +291,24 @@ function sizeUp(p: Probe, policy: Policy, a: Assessment, now: number, open: Commconst WAY = ['right away', 'about a quarter of the way in', 'about halfway', 'about three quarters of the way in', 'near the end']const runsOut = (w: Measured) => `The ${w.name} window is expected to run out ${WAY[Math.round(Math.max(0, w.usable / w.needed) * 4)]}${w.resetsIn === null ? '' : `; resets in ${span(w.resetsIn)}`}.`const UNREAD = 'Its quota could not be read in full, and another candidate\'s quota fits this task.'-export const LOCAL_NONE = 'No local model is being served on this Swarm\'s grid. Ask a member to run one (their machine\'s details → Run a local model).'+export const LOCAL_NONE = 'No local model is being served on this Swarm\'s grid. Ask a member to run one or share an API (Manage models, in the Swarm\'s sidebar).'/** The fixed order: the owner's preferred engine, an idle member before a new agent and a less busy machine first when the- * owner prefers idle agents; then the policy order: cheaper in effect, stronger, more room on the tightest window, an idle- * member in the task's repository before a new agent, then by title. */+ * owner prefers idle agents; then the policy order: cheaper in effect, stronger, a model that runs on a machine before one+ * reached through a shared API or another grid, more room on the tightest window, an idle member in the task's repository+ * before a new agent, then by title. */function compare(x: Probe & Sized, y: Probe & Sized, soft: Soft): number {const placed = (p: Probe) => p.kind === 'member' && (p.repo ?? 'same') === 'same' ? 0 : 1const preferred = (p: Probe) => soft.engine && p.engine !== soft.engine ? 1 : 0const fresh = (p: Probe) => soft.idle && p.kind === 'new' ? 1 : 0const busy = (p: Probe) => soft.idle && p.kind === 'new' ? p.load?.agents ?? 1000 : 0+ // On-machine first (owner, 2026-10-24): an API spends a member's key and credits, and a model shared on another grid is+ // someone else's machine; at equal cost and strength the Swarm's own engine goes first.+ const remote = (p: Probe) => p.gridModel && (p.gridKind === 'api' || p.gridKind === 'shared') ? 1 : 0return preferred(x) - preferred(y) || fresh(x) - fresh(y) || busy(x) - busy(y)|| x.fit.effectiveCost - y.fit.effectiveCost|| y.quality - x.quality+ || remote(x) - remote(y)|| (y.tight?.usable ?? -Infinity) - (x.tight?.usable ?? -Infinity)|| placed(x) - placed(y)|| titleOf(x).localeCompare(titleOf(y))@@ -303,7 +324,7 @@ function withEveryMachine<T extends { machineId: string }>(ranked: T[]): T[] {return ranked.filter(p => keep.has(p))}-export function choose(probes: Probe[], policy: Policy, a: Assessment, now: number = Date.now(), open: Commitment[] = [], rules: SwarmRule[] = []): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {+export function choose(probes: Probe[], policy: Policy, a: Assessment, now: number = Date.now(), open: Commitment[] = [], rules: SwarmRule[] = [], held: HeldModel[] = []): Choice | { error: 'NO_CANDIDATE'; excluded: Array<{ title: string; reason: string }> } {// A lifted row can equal another row on the same machine (Codex `default` lifted to high beside Codex high); one is kept.// A person asking for a local model considers local models alone, whatever their strength.if (a.local) probes = probes.filter(p => p.gridModel)@@ -315,8 +336,15 @@ export function choose(probes: Probe[], policy: Policy, a: Assessment, now: numb.map(p => { const why = breaks(rules, p); return why ? { ...p, refusals: [...p.refusals, why] } : p })const excluded = ruled.filter(p => p.refusals.length).map(p => ({ title: titleOf(p), reason: p.refusals.join(' ') }))const viable = ruled.filter(p => !p.refusals.length)- if (named && !probes.length) excluded.push({ title: 'Named model', reason: NAMED_NONE(named) })- else if (a.local && !probes.length) excluded.push({ title: 'Local models', reason: LOCAL_NONE })+ // Nothing offered: a model that is served but taken says who has it, rather than reading as unshared.+ const heldNamed = named ? held.filter(m => words(named).every(w => words(`${m.model} ${m.label}`).join('').includes(w))) : []+ if (named && !probes.length) {+ if (heldNamed.length) excluded.push(...heldNamed.map(m => ({ title: 'Named model', reason: heldReason(m) })))+ else excluded.push({ title: 'Named model', reason: NAMED_NONE(named) })+ } else if (a.local && !probes.length) {+ if (held.length) excluded.push(...held.map(m => ({ title: 'Local models', reason: heldReason(m) })))+ else excluded.push({ title: 'Local models', reason: LOCAL_NONE })+ }if (!viable.length) return { error: 'NO_CANDIDATE', excluded }const floor = floorFor(policy, a)const meeting = a.local || named ? viable : viable.filter(p => p.quality >= floor)diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex 1b63c8a4d..3d64c4333 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -3,7 +3,7 @@ import type { openDaemon } from '../agentClient/daemon.js'import { mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { localProbes, routeTask } from './routeCommand.js'+import { heldLocalModels, localProbes, routeTask } from './routeCommand.js'import type { describeScmProject } from '../scm/scmProjects.js'import { admission, quotaOf } from './capacity.js'import type { Assessment, Policy, Probe } from './route.js'@@ -843,6 +843,40 @@ describe('local models on the Swarm\'s grid', () => {expect(offered(state({ starts: [start({ error: 'NO_CAPACITY' })] }))).toHaveLength(1)expect(offered(state({ starts: [{ request: { model: 'opus' } }, {}] }))).toHaveLength(1)})+ it('lets up to four Builders share an API model, which answers several requests at once', () => {+ const api = state({ machines: [served([{ grid: GRID, model: 'ds', name: 'DeepSeek', kind: 'api' }])] })+ const starts = (n: number) => Array.from({ length: n }, (_, i) => ({ request: { gridModel: 'ds' }, harnessId: `h${i}` }))+ const agents = (n: number) => Array.from({ length: n }, (_, i) => ({ harnessId: `h${i}`, name: `B${i}` }))+ expect(offered({ ...api, starts: starts(3), agents: agents(3) })).toHaveLength(1)+ expect(offered({ ...api, starts: starts(4), agents: agents(4) })).toEqual([])+ })+ it('names the Builders on each model that takes no more, so the route can say why it is not offered', () => {+ const api = served([{ grid: GRID, model: 'ds', name: 'DeepSeek', kind: 'api' }, { grid: GRID, model: 'qwen3', name: 'Qwen 3' }])+ const s = state({ machines: [api],+ starts: [{ request: { gridModel: 'qwen3' }, harnessId: 'h1' }, { request: { gridModel: 'qwen3' } },+ ...['h2', 'h3', 'h4', 'h5'].map(harnessId => ({ request: { gridModel: 'ds' }, harnessId }))],+ agents: [{ harnessId: 'h1', displayName: 'Faye', name: 'Builder' }, { harnessId: 'h2', name: 'Wren' }, { harnessId: 'h3' }, { harnessId: 'h4', name: 'Ada' }, { harnessId: 'h5', name: 'Bo' }] })+ expect(heldLocalModels(s, NOW)).toEqual([+ { model: 'ds', label: 'DeepSeek', kind: 'api', holders: ['Wren', 'a Builder', 'Ada', 'Bo'] },+ { model: 'qwen3', label: 'Qwen 3', kind: 'local', holders: ['Faye', 'a Builder that is starting'] },+ ])+ // Nothing is held while the add-on is off, or with a model nobody is on.+ expect(heldLocalModels(state({ localModels: { grid: GRID, enabled: false } }), NOW)).toEqual([])+ expect(heldLocalModels(state(), NOW)).toEqual([])+ expect(heldLocalModels(state({ localModels: undefined }))).toEqual([])+ })+ it('adds the models a fresh reading says Builders are never offered, with why, once each', () => {+ const why = 'llama3.2:3b is too small for a coding agent.'+ const refusing = (receivedAt: unknown, refusedModels: unknown) => ({ machineId: 'm2', observation: { receivedAt, refusedModels } })+ const s = state({ machines: [served([]), refusing(NOW - 1_000, [+ { grid: GRID, model: 'llama3.2:3b', why }, { grid: GRID, model: 'llama3.2:3b', why }, { grid: GRID, model: 'tiny', name: 'Tiny 1B', why: 'small' },+ { grid: 'other-grid', model: 'x', why }, { grid: GRID, model: 7, why }, { grid: GRID, model: 'no-why' }]),+ refusing(NOW - 60_000, [{ grid: GRID, model: 'stale', why }]), refusing('soon', [{ grid: GRID, model: 'odd', why }])] })+ expect(heldLocalModels(s, NOW)).toEqual([+ { model: 'llama3.2:3b', label: 'llama3.2:3b', kind: 'local', holders: [], refused: why },+ { model: 'tiny', label: 'Tiny 1B', kind: 'local', holders: [], refused: 'small' },+ ])+ })it('routes a low task to a served model and starts it on the grid, with no subscription model', async () => {const t = tab(); Object.assign(t.state, { localModels: { grid: GRID, enabled: true },machines: [{ machineId: 'm1', observation: { receivedAt: Date.now(), localModels: [{ grid: GRID, model: 'qwen3', name: 'Qwen 3' }] } }] })diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex 97c65a488..f422f3198 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -7,7 +7,7 @@ import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'import { requiredToolReason, startRequirements } from './capacity.js'import { inspectCapacity, type ScopedRequest } from './start.js'import { ENDED_WORK, object, within } from './wire.js'-import { choose, decide, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, type Assessment, type Commitment, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'+import { API_BUILDERS, choose, decide, parseAssessment, quotaOf2, rateFor, recordOf, repoMatch, type Assessment, type Commitment, type HeldModel, type MemberFrame, type Policy, type Probe, type SwarmRule, type TaskFolder } from './route.js'import { stat } from 'node:fs/promises'import { describeScmProject } from '../scm/scmProjects.js'@@ -184,7 +184,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;// Picks started or assigned and still at work hold part of their account's quota; the log, and so this, is per Swarm.const working = (decisions ?? []).filter(d => d.final && d.outcome === null && typeof d.account === 'string').map(d => ({ account: d.account, spend: object(d.spend), size: d.size, createdAt: Date.parse(String(d.createdAt)) }) as Commitment)- const choice = choose(probes, policy, assessment, Date.now(), working, rules)+ const choice = choose(probes, policy, assessment, Date.now(), working, rules, heldLocalModels(state))if ('error' in choice) return choiceconst verdict = decide(choice)const operationId = `route-${newId()}`@@ -226,17 +226,13 @@ const LOCAL_FRESH_MS = 45_000/** Refusals about a subscription's allowance, which a local model does not spend. */const SUBSCRIPTION = /subscription/i-/** New agents on local models (docs/plans/2026-10-23-swarm-local-models.md), only while the owner has the add-on on and a- * fresh reading lists the model. One served on the Swarm's grid, an engine of a member's or an API one shares, is reached- * through the grid relay from any Swarm machine that can start Claude Code or Codex. One on another grid, shared with a- * machine's owner, only from that machine (owner, 2026-10-23). One Builder per model, since a node answers one- * conversation at a time. Never for a review. */-export function localProbes(state: Json, policy: Policy, probes: Probe[], a: Assessment, review: boolean, now: number = Date.now()): Probe[] {- const addOn = object(state.localModels)- const swarm = addOn.enabled === true && typeof addOn.grid === 'string' ? addOn.grid : null- if (!swarm || review || (policy.localModels?.enabled === false && !a.local)) return []+interface Served { grid: string; model: string; label: string; kind: 'local' | 'api' | 'shared'; machines: Set<string> | null; holders: string[] }++/** The models served for the Swarm while the owner has the add-on on and a fresh reading lists them, by grid and model, each+ * with the Builders on it: one started on a model, or starting on it, holds it until it leaves the Swarm. */+function servedModels(state: Json, swarm: string, now: number): Map<string, Served> {// By grid and model: its label, and the machines that may run it (null: any).- const served = new Map<string, { grid: string; model: string; label: string; kind: 'local' | 'api' | 'shared'; machines: Set<string> | null }>()+ const served = new Map<string, Served>()for (const machine of list(state.machines)) {const observed = object(machine.observation)if (!finite(observed.receivedAt) || now - observed.receivedAt > LOCAL_FRESH_MS) continue@@ -244,19 +240,52 @@ export function localProbes(state: Json, policy: Policy, probes: Probe[], a: Assif (typeof l.grid !== 'string' || typeof l.model !== 'string') continueconst key = `${l.grid}\0${l.model}`, anywhere = l.grid === swarmconst kind = l.kind === 'api' || l.kind === 'shared' ? l.kind : anywhere ? 'local' : 'shared'- const known = served.get(key) ?? { grid: l.grid, model: l.model, label: text(l.name) ?? l.model, kind, machines: anywhere ? null : new Set<string>() }+ const known = served.get(key) ?? { grid: l.grid, model: l.model, label: text(l.name) ?? l.model, kind, machines: anywhere ? null : new Set<string>(), holders: [] }known.machines?.add(String(machine.machineId))served.set(key, known)}}- // A model a Builder started on, or is starting on, is taken until that Builder leaves the Swarm.- const members = new Set(list(state.agents).map(agent => String(agent.harnessId)))+ const agents = new Map(list(state.agents).map(agent => [String(agent.harnessId), text(agent.displayName) ?? text(agent.name) ?? 'a Builder']))for (const start of list(state.starts)) {const request = object(start.request)- if (typeof request.gridModel === 'string' && !start.error && (!start.harnessId || members.has(String(start.harnessId)))) {- served.delete(`${typeof request.gridName === 'string' ? request.gridName : swarm}\0${request.gridModel}`)+ if (typeof request.gridModel !== 'string' || start.error || (start.harnessId && !agents.has(String(start.harnessId)))) continue+ served.get(`${typeof request.gridName === 'string' ? request.gridName : swarm}\0${request.gridModel}`)?.holders+ .push(start.harnessId ? agents.get(String(start.harnessId))! : 'a Builder that is starting')+ }+ return served+}++/** Whether [m] can take another Builder: a local engine or a model shared with a member takes one, an API model up to [API_BUILDERS]. */+const takesBuilder = (m: Served) => m.holders.length < (m.kind === 'api' ? API_BUILDERS : 1)++/** The Swarm's served models that take no more Builders, and who is on them, then those a fresh reading says Builders are+ * never offered, and why (superTabs/machines.ts refusedOn): what the route says when it offers none. */+export function heldLocalModels(state: Json, now: number = Date.now()): HeldModel[] {+ const addOn = object(state.localModels)+ if (addOn.enabled !== true || typeof addOn.grid !== 'string') return []+ const held: HeldModel[] = [...servedModels(state, addOn.grid, now).values()].filter(m => !takesBuilder(m))+ .map(({ model, label, kind, holders }) => ({ model, label, kind, holders }))+ for (const machine of list(state.machines)) {+ const observed = object(machine.observation)+ if (!finite(observed.receivedAt) || now - observed.receivedAt > LOCAL_FRESH_MS) continue+ for (const r of list(observed.refusedModels)) {+ if (r.grid !== addOn.grid || typeof r.model !== 'string' || typeof r.why !== 'string' || held.some(m => m.model === r.model)) continue+ held.push({ model: r.model, label: text(r.name) ?? r.model, kind: 'local', holders: [], refused: r.why })}}+ return held+}++/** New agents on local models (docs/plans/2026-10-23-swarm-local-models.md), only while the owner has the add-on on and a+ * fresh reading lists the model. One served on the Swarm's grid, an engine of a member's or an API one shares, is reached+ * through the grid relay from any Swarm machine that can start Claude Code or Codex. One on another grid, shared with a+ * machine's owner, only from that machine (owner, 2026-10-23). One Builder per local engine, since it answers one+ * conversation at a time; up to [API_BUILDERS] per API model (owner, 2026-10-24). Never for a review. */+export function localProbes(state: Json, policy: Policy, probes: Probe[], a: Assessment, review: boolean, now: number = Date.now()): Probe[] {+ const addOn = object(state.localModels)+ const swarm = addOn.enabled === true && typeof addOn.grid === 'string' ? addOn.grid : null+ if (!swarm || review || (policy.localModels?.enabled === false && !a.local)) return []+ const served = new Map([...servedModels(state, swarm, now)].filter(([, m]) => takesBuilder(m)))if (!served.size) return []// One base per machine and engine: the first new-agent row the policy offers there, which carries the machine's refusals.const bases = new Map<string, Probe>()diff --git a/cli/src/superTabs/terminal.spec.ts b/cli/src/superTabs/terminal.spec.tsindex 802df8bf0..e838bb858 100644--- a/cli/src/superTabs/terminal.spec.ts+++ b/cli/src/superTabs/terminal.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from 'vitest'import type { CoreApi, SuperTabScreen } from '../core/api.js'import { fakeCore } from '../testing/fakeCore.js'-import { capScreen, limitOf, TerminalHost, typedKeys } from './terminal.js'+import { capScreen, limitOf, modelFailing, TerminalHost, typedKeys } from './terminal.js'const row = (agentId = 'a1', harnessId = 'h1', over: Record<string, unknown> = {}) => ({ tabId: 'tab', agent: { id: agentId, harnessId, machineId: 'm1' }, ...over })type Sent = { path: string; body: Record<string, any> }@@ -180,6 +180,34 @@ describe('the stuck and usage-limit alerts', () => {expect(t.alerts()[1]).toEqual({ type: 'agent.alert', agentId: 'a1', alert: 'limit', active: false })})+ it('alerts once its model has failed for 10 minutes, and ends it when answers come again', async () => {+ const failing = (): SuperTabScreen => ({ ok: true, text: '✻ Waiting for API response · will retry in 2m 38s · check your network\n❯ ', hold: null })+ const t = setup({ screen: failing })+ await t.host.tick([row()])+ t.wait(540_000); await t.host.tick([row()])+ expect(t.alerts()).toEqual([])+ t.wait(60_000); await t.host.tick([row()])+ expect(t.alerts()).toEqual([{ type: 'agent.alert', agentId: 'a1', alert: 'model', active: true }])+ // Answers coming again end it only once no retry has shown for ten minutes.+ t.showing(idle); t.wait(15_000); await t.host.tick([row()])+ expect(t.alerts()).toHaveLength(1)+ t.wait(585_000); await t.host.tick([row()])+ expect(t.alerts()[1]).toEqual({ type: 'agent.alert', agentId: 'a1', alert: 'model', active: false })+ })++ it('counts retries with fresh attempts between them as one failing stretch', async () => {+ // Claude Code shows its countdown, then a plain spinner for the minutes each new attempt takes.+ const failing = (): SuperTabScreen => ({ ok: true, text: '✻ Waiting for API response · will retry in 1m 18s · check your network\n❯ ', hold: null })+ const attempt = (): SuperTabScreen => ({ ok: true, text: '✻ Thinking… (4m 12s · esc to interrupt)\n❯ ', hold: null })+ const t = setup({ screen: failing })+ await t.host.tick([row()])+ for (let minute = 0; minute < 10; minute += 2) {+ t.showing(attempt); t.wait(60_000); await t.host.tick([row()])+ t.showing(failing); t.wait(60_000); await t.host.tick([row()])+ }+ expect(t.alerts()).toEqual([{ type: 'agent.alert', agentId: 'a1', alert: 'model', active: true }])+ })+it('tries an alert the backend did not take again on the next read', async () => {const t = setup({ screen: () => ({ ok: true, text: 'Claude usage limit reached. Your limit will reset at 3pm.', hold: null }) })const real = vi.mocked(t.backend).getMockImplementation()!@@ -217,3 +245,14 @@ describe('reading a usage limit off a screen', () => {expect(limitOf('> ', now)).toBeNull()})})++describe('reading a model that keeps failing off a screen', () => {+ it('knows the engines\' retry lines near the prompt, and nothing far up or in the agent\'s own words', () => {+ for (const line of ['✻ Waiting for API response · will retry in 2m 38s · check your network', ' ⎿ API Error: 503 upstream unavailable',+ 'API Error: Request timed out.', 'API Error: Connection error.', '⚠ stream disconnected - retrying turn (3/5 in 1.2s)…', 'Reconnecting... 2/5']) {+ expect(modelFailing(`work\n${line}\n> `)).toBe(true)+ }+ expect(modelFailing('I will handle the case where the API response is slow.\n> ')).toBe(false)+ expect(modelFailing(`Waiting for API response\n${'line\n'.repeat(30)}> `)).toBe(false)+ })+})diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.tsindex 07a9e5d5d..d7dd807fd 100644--- a/cli/src/superTabs/terminal.ts+++ b/cli/src/superTabs/terminal.ts@@ -61,6 +61,23 @@ const LIMIT_LINE = /^[^A-Za-z]*(?:api error:\s*)?(?:claude\s+)?(?:(?:usage|5-houconst LIMIT_NEAR_LINES = 15const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']+/** An engine retrying a model that does not answer: Claude Code's "Waiting for API response · will retry in 2m 38s · check+ * your network" and its "API Error: 503 …", "Request timed out" or "Connection error", and Codex's "stream disconnected -+ * retrying" and "Reconnecting…". 2026-10-24: a Builder on a small local model retried for an hour, the relay giving up on+ * every answer, while its Lead waited on it. Only near the prompt, as a limit is. */+const MODEL_LINE = /waiting for api response|api error:\s*(?:5\d\d|overloaded|request timed out|connection)|stream (?:error|disconnected)[^\n]*retrying|^\W*reconnecting\b/i+/** Retries come and go on a busy model; ten minutes of them is a model the work cannot get answers from. */+const MODEL_WAIT_MS = 10 * 60_000+/** How long a screen must stay clear of retries before its model counts as answering again. Between retries the engine+ * shows a plain spinner for the minutes a new attempt takes: 2026-10-24, a Builder on Qwen3.6 35B, whose every answer the+ * relay had already dropped, read as answering on each attempt, so its ten minutes never ran out. */+const MODEL_CLEAR_MS = 10 * 60_000++/** Whether the screen shows its engine retrying its model. */+export function modelFailing(text: string): boolean {+ return text.split('\n').slice(-LIMIT_NEAR_LINES).some(line => MODEL_LINE.test(line))+}+/** A usage limit on screen, with when it resets if the screen says; null for none. */export function limitOf(text: string, now: number): { resetAt?: string } | null {const lines = text.split('\n')@@ -95,7 +112,8 @@ function resetOf(said: string, now: number): number | null {return date.getTime()}-interface Watched { prompt: { since: number; alerted: boolean } | null; limit: { since: number; alerted: boolean } | null }+type Episode = { since: number; alerted: boolean } | null+interface Watched { prompt: Episode; limit: Episode; model: Episode; retried?: number }export class TerminalHost {private nextServeAt = 0@@ -179,14 +197,15 @@ export class TerminalHost {await backend(this.core, 'POST', `/api/super-tabs/${agent.tabId}/commands`, { operationId, asAgentId: agent.agentId, command })}- /** One alert per episode: a prompt waiting 3 minutes, or a usage limit on screen; each ended once it is gone. An alert+ /** One alert per episode: a prompt waiting 3 minutes, a usage limit on screen, or its model failing for 10 minutes; each+ * ended once it is gone. An alert* the backend did not take is tried again on the next read. */private async watch(own: Own[]): Promise<void> {const keys = new Set(own.map(a => `${a.tabId}:${a.agentId}`))for (const key of this.watched.keys()) if (!keys.has(key)) this.watched.delete(key)for (const agent of own) {const key = `${agent.tabId}:${agent.agentId}`- const state = this.watched.get(key) ?? { prompt: null, limit: null }+ const state = this.watched.get(key) ?? { prompt: null, limit: null, model: null }this.watched.set(key, state)// A screen that could not be read says nothing either way.const read = await this.core.superTabs!.screen(agent.harnessId, 0).catch(() => null)@@ -195,11 +214,14 @@ export class TerminalHost {state.prompt = await this.episode(agent, 'prompt', state.prompt, read.hold !== null && WAITING.has(read.hold), now, since => now - since >= PROMPT_WAIT_MS, {})const limit = limitOf(read.text, now)state.limit = await this.episode(agent, 'limit', state.limit, limit !== null, now, () => true, limit ?? {})+ if (modelFailing(read.text)) state.retried = now+ const retrying = state.retried !== undefined && now - state.retried < MODEL_CLEAR_MS+ state.model = await this.episode(agent, 'model', state.model, retrying, now, since => now - since >= MODEL_WAIT_MS, {})}}- private async episode(agent: Own, alert: 'prompt' | 'limit', current: Watched['prompt'], seen: boolean, now: number,- due: (since: number) => boolean, extra: Json): Promise<Watched['prompt']> {+ private async episode(agent: Own, alert: 'prompt' | 'limit' | 'model', current: Episode, seen: boolean, now: number,+ due: (since: number) => boolean, extra: Json): Promise<Episode> {const episode = seen ? current ?? { since: now, alerted: false } : currentif (!episode) return nullif (seen === episode.alerted || (seen && !due(episode.since))) return seen ? episode : nulldiff --git a/desktop/lib/models/coding_model.dart b/desktop/lib/models/coding_model.dartnew file mode 100644index 000000000..33a48bbd0--- /dev/null+++ b/desktop/lib/models/coding_model.dart@@ -0,0 +1,49 @@+import 'local_model.dart';++/// Whether a local model can drive a coding agent: the CLI's rule (`cli/src/lib/codingModel.ts`), which keeps such a+/// model out of what a machine offers its Swarm, here so Run for Swarm can say why before anything starts. 2026-10-24: a+/// Builder on llama3.2:3b made over a thousand requests for a one-line edit and never finished.+const minCodingParamsB = 7.0;+const minCodingTokS = 10.0;++double _bitsPerWeight(String? quant) {+ final q = (quant ?? '').toUpperCase();+ if (q.contains('MXFP4')) return 4.25;+ if (RegExp(r'BF16|FP16|F16').hasMatch(q)) return 16;+ final digit = RegExp(r'(IQ|Q)(\d)').firstMatch(q);+ return digit == null+ ? 4.8+ : int.parse(digit.group(2)!) + (digit.group(1) == 'IQ' ? 0.3 : 0.8);+}++/// The parameter count a model's name gives (`llama3.2:3b`, `Qwen3.6-35B-A3B`: the total, not the active `A3B`).+double? paramsFromName(String name) {+ final match = RegExp(+ r'(?:^|[^a-z0-9.])(\d+(?:\.\d+)?)b(?![a-z0-9])',+ caseSensitive: false,+ ).firstMatch(name);+ return match == null ? null : double.parse(match.group(1)!);+}++/// Why [model] cannot drive a coding agent, in a sentence, or null when it can or nothing says otherwise.+String? codingRefusal(LocalModel model) {+ final size = model.sizeBytes;+ final params =+ model.paramsB ??+ paramsFromName(model.name) ??+ (size == null || size <= 0+ ? null+ : size * 8 / _bitsPerWeight(model.quantization) / 1e9);+ if (params != null && params < minCodingParamsB) {+ final shown = (params * 10).round() / 10;+ return '${model.shownName} is too small for a coding agent (about '+ '${shown == shown.roundToDouble() ? shown.toInt() : shown}B parameters; '+ 'Builders need ${minCodingParamsB.toInt()}B or more).';+ }+ final speed = model.tokensPerSecond ?? model.estTokS;+ if (speed != null && speed < minCodingTokS) {+ return '${model.shownName} is too slow on this computer for a coding agent '+ '(about ${speed.round()} tok/s; Builders need ${minCodingTokS.toInt()} or more).';+ }+ return null;+}diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex e06556050..bbd2e6306 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -9,6 +9,7 @@ import '../models/api_connections_controller.dart'show ApiConnection, ApiModel, agentOnApiModel;import '../models/local_model.dart';import '../models/model_search_catalog.dart';+import '../models/coding_model.dart';import '../models/swarm_models_target.dart';import '../usage/models_menu_controller.dart' show subscriptionSearchId;import '../core/dsh_catalog.dart';@@ -498,11 +499,14 @@ class SwarmSearchController extends ChangeNotifier {run: ready ? act('stop', grid: swarm.grid) : null,);}+ // Too small or too slow to drive a coding agent: no Builder would be offered it, so neither Get nor Run is+ // (coding_model.dart; the preview says why).+ final capable = codingRefusal(local) == null;if (!local.downloaded && !local.canStop) {return (label: 'Get',command: 'picker.model_download',- run: ready && local.canStart && owner.supportsDownload+ run: ready && capable && local.canStart && owner.supportsDownload? act('download'): null,);@@ -510,7 +514,9 @@ class SwarmSearchController extends ChangeNotifier {return (label: 'Run for Swarm',command: 'picker.model_start',- run: ready && local.canStart ? act('start', grid: swarm.grid) : null,+ run: ready && capable && local.canStart+ ? act('start', grid: swarm.grid)+ : null,);}if (entry.apiModel case final model?) {diff --git a/desktop/lib/super_tabs/local_models.dart b/desktop/lib/super_tabs/local_models.dartindex 1db1bcab1..c036e807f 100644--- a/desktop/lib/super_tabs/local_models.dart+++ b/desktop/lib/super_tabs/local_models.dart@@ -489,16 +489,19 @@ class _SwarmModelsHints extends StatelessWidget {@overrideWidget build(BuildContext context) {final row = search.selected;+ final action = row == null ? null : search.swarmModelAction(row);final enter = row == null? null: row.isCreate? 'Add API connection'- : search.swarmModelAction(row)?.label ??- (search.canExpandApi(row) ||- search.isModelDownloadsRow(row) ||- search.canGetModel(row)- ? search.actionLabel(row)- : null);+ // Enter does nothing on an action that cannot run (a model too small for Builders): no hint for it.+ : action != null+ ? (action.run == null ? null : action.label)+ : search.canExpandApi(row) ||+ search.isModelDownloadsRow(row) ||+ search.canGetModel(row)+ ? search.actionLabel(row)+ : null;Widget hint(String key, String label) => Row(mainAxisSize: MainAxisSize.min,children: [diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dartindex 8288cb546..7ade69f21 100644--- a/desktop/lib/widgets/swarm_resource_preview.dart+++ b/desktop/lib/widgets/swarm_resource_preview.dart@@ -35,6 +35,7 @@ import 'swarm_search_preview.dart';import 'swarm_preview_scroll.dart';import 'terminal_text_action.dart';import 'desktop_chrome.dart';+import '../models/coding_model.dart';import 'swarm_model_tile.dart';import 'key_hints.dart';@@ -1819,6 +1820,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {)? 'Offered: the PM can start Builders on your machines on it': 'Offer to Swarm lets the PM start Builders on your machines on it'+ : codingRefusal(local) != null+ ? 'The Lead routes Builders only onto models that can drive a coding agent.': local.servedOn(swarm.grid)? 'Running for this Swarm: the Lead can route Builders on any machine in it onto this model.': 'Run for Swarm lets the Lead route Builders on any machine in the Swarm onto this model.',@@ -1967,6 +1970,13 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {: swarmBlurb,facts: facts,errors: errors,+ // Too small or too slow for a coding agent: Builders are never offered it, running or not (coding_model.dart).+ note: switch (codingRefusal(local!)) {+ final why? when local.servedOn(widget.search.swarmModels!.grid) =>+ 'Not offered to Builders: $why',+ final why? => why,+ null => null,+ },);}diff --git a/desktop/test/coding_model_test.dart b/desktop/test/coding_model_test.dartnew file mode 100644index 000000000..65c2132af--- /dev/null+++ b/desktop/test/coding_model_test.dart@@ -0,0 +1,47 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/models/coding_model.dart';+import 'package:harness/models/local_model.dart';++LocalModel _model(Map<String, Object?> json) =>+ LocalModel.fromJson({'id': 'm', 'state': 'downloaded', ...json});++void main() {+ test('reads the parameter count off a name: the total, never an active count', () {+ expect(paramsFromName('llama3.2:3b'), 3);+ expect(paramsFromName('Qwen3.6-35B-A3B'), 35);+ expect(paramsFromName('mixtral-8x7b'), isNull);+ expect(paramsFromName('gemma-4-E2B-it'), isNull);+ });++ test('refuses a model too small or too slow, as the CLI does, and lets anything unknown pass', () {+ expect(+ codingRefusal(_model({'name': 'llama3.2:3b'})),+ 'llama3.2:3b is too small for a coding agent (about 3B parameters; Builders need 7B or more).',+ );+ expect(+ codingRefusal(_model({'name': 'gemma-4-E2B-it', 'sizeBytes': 3.2e9})),+ 'gemma-4-E2B-it is too small for a coding agent (about 5.3B parameters; Builders need 7B or more).',+ );+ expect(+ codingRefusal(_model({'name': 'm', 'sizeBytes': 16e9, 'quant': 'BF16'})),+ isNull,+ );+ expect(+ codingRefusal(_model({'name': 'm', 'sizeBytes': 4.3e9, 'quant': 'IQ4_XS'})),+ isNull,+ );+ expect(+ codingRefusal(_model({'name': 'm', 'sizeBytes': 4.25e9, 'quant': 'MXFP4'})),+ isNull,+ );+ expect(+ codingRefusal(_model({'name': 'Qwen3.6-35B-A3B', 'estTokS': 4.4})),+ 'Qwen3.6-35B-A3B is too slow on this computer for a coding agent (about 4 tok/s; Builders need 10 or more).',+ );+ expect(+ codingRefusal(_model({'name': 'Qwen3.6-35B-A3B', 'paramsB': 35, 'estTokS': 30})),+ isNull,+ );+ expect(codingRefusal(_model({'name': 'mystery'})), isNull);+ });+}diff --git a/desktop/test/swarm_local_models_picker_test.dart b/desktop/test/swarm_local_models_picker_test.dartindex dec9cba0a..d4ef1a83c 100644--- a/desktop/test/swarm_local_models_picker_test.dart+++ b/desktop/test/swarm_local_models_picker_test.dart@@ -120,6 +120,18 @@ void main() {'state': 'available','canStart': true,},+ {+ 'id': 'tiny',+ 'name': 'llama3.2:3b',+ 'state': 'downloaded',+ 'canStart': true,+ },+ {+ 'id': 'tiny-get',+ 'name': 'qwen3:4b',+ 'state': 'available',+ 'canStart': true,+ },],};subscriptions = _Subscriptions();@@ -259,6 +271,16 @@ void main() {expect(search.rows.map(search.modelSection).toSet(), sections);});+ test('offers neither Run nor Get for a model too small to drive a coding agent', () {+ final run = search.swarmModelAction(row('tiny'))!;+ expect(run.label, 'Run for Swarm');+ expect(run.run, isNull);+ final get = search.swarmModelAction(row('tiny-get'))!;+ expect(get.label, 'Get');+ expect(get.run, isNull);+ expect(search.swarmModelAction(row('downloaded'))!.run, isNotNull);+ });+test('stops a model running for the Swarm on the Swarm\'s grid', () async {await search.swarmModelAction(row('served'))!.run!();expect(app.actions.last, (machine: 'm', model: 'served', start: false));diff --git a/docs/plans/2026-10-23-swarm-local-models.md b/docs/plans/2026-10-23-swarm-local-models.mdindex 9f0ea2e7c..fb750a665 100644--- a/docs/plans/2026-10-23-swarm-local-models.md+++ b/docs/plans/2026-10-23-swarm-local-models.md@@ -11,7 +11,7 @@ Builders on them when that fits the work. It is an add-on: nothing calls grid un| 1 | Owner | Machines heading → Local models (chip icon) → Use local models | Backend mints `state.localModels.grid` (`swarm-<12 hex>`). The owner's host creates the grid (`grid --remote start`, `permissioned-public`), keeps its members in step with the Swarm's people (`grid members add|remove`, role `both`), and reports `localModels.status`. || 2 | A member | Local models window (⌘I's Models: APIs, Your models, Get for this Mac, Shared with you) → a model → Run for Swarm, or an API's model → Share with Swarm | That machine's daemon signs in to grid (Harness sign-in handed to `grid login --harness`), serves the model on the Swarm's grid, and lists it in its machine readings (`observation.localModels`). || 3 | Everyone | Sees it in the machine's details and the Local models dialog ("Qwen 3 on Studio") | Served models come from fresh readings only (45 s). |-| 4 | Lead | Routes as usual | Local candidates exist only while a model is served: free, quality from the policy (`localModels.quality`, default 1), one Builder per served model. A person asking for a local model overrides the floor. |+| 4 | Lead | Routes as usual | Local candidates exist only while a model is served: free, quality from the policy (`localModels.quality`, default 1), one Builder per local engine and up to four per shared API model (2026-10-24). A person asking for a local model overrides the floor. When nothing is offered because a model is taken, the route names the Builders on it. || 5 | Lead | Starts the Builder | Any Swarm machine with a slot runs Claude Code or Codex on the model through the grid relay. The backend admits `gridModel`/`gridName` on a contributed machine only for the Swarm's grid while a fresh reading serves the model. || 6 | Member | Stops the model | It leaves the readings; routing stops offering it. || 7 | Owner | Turns Local models off | No new local starts. The grid is kept. |@@ -24,13 +24,23 @@ Builders on them when that fits the work. It is an add-on: nothing calls grid un- Local models count as quality 1 unless the owner raises it; a person's explicit request overrides.- Turning it off keeps the grid.- Not limited to the machine serving the model: a Builder on another machine reaches it through the grid relay.+- (2026-10-24) A local model must be able to drive a coding agent: 7B parameters or more and, when measured, 10 tok/s or+ more (`lib/codingModel.ts`, mirrored in `desktop/lib/models/coding_model.dart`). A smaller one gets no Run or Get for+ the Swarm; one already served is reported as `refusedModels` with why, never offered, and a Lead asked for it is told+ why. A llama3.2:3b Builder made over a thousand requests for a one-line edit.+- (2026-10-24) A Builder whose engine keeps retrying its model for ten minutes alerts its Lead (`agent.alert` `model`).+- (2026-10-24) A machine keeps what it serves on the grid: shares keep their address across restarts, and+ `lib/swarmHeal.ts` joins again what the grid stopped listing.+- Known limit (grid): a local model answers a Claude Code turn only after reading its whole prompt (~45K tokens, over+ three minutes for Qwen3.6 35B on an M-series Mac); the relay ends the transaction first and every retry starts again.+ It still finished a one-line edit in 14 minutes. Needs a relay keepalive and prompt-cache reuse in grid.## Where the code is- Backend: `superTabs/commands.ts` (`localModels.set`, `localModels.status`), `machines.ts` (admission, `swarmGridRow`,`hostLocalGrid`), `routingPolicy.ts` (`localModels` policy), `GET /api/super-tabs/grids`.- CLI: `superTabs/swarmGrids.ts` + `lib/swarmGrid.ts` (owner's computer keeps the grid), `superTabs/machines.ts`- (`servedOn`), `superTabs/routeCommand.ts` (`localProbes`), `superTabs/route.ts` (`local`, `LOCAL_NONE`),+ (`servedOn`, `refusedOn`, the `grid_swarm_heal` reading), `superTabs/routeCommand.ts` (`localProbes`, `heldLocalModels`), `superTabs/route.ts` (`local`, `LOCAL_NONE`),`services/models.ts` (`grid_swarm_sync`, Swarm-grid start/stop, `swarmLaunchTarget`), Lead skill line in `lib/swarmSkills.ts`.- Desktop: `super_tabs/local_models.dart`, wired in `super_tabs/machines.dart`.