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: a grid per Swarm, local, shared and API models for Builders
bitcoinbuilder214ff87d7af3
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex a7d4e0ed8..c1edf8e42 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -54,6 +54,7 @@ async function respond(reply: FastifyReply, action: () => Promise<unknown>) {/** Uses the normal authenticated control API. It never accepts caller-provided host/contributor identities. */export async function superTabRoutes(app: FastifyInstance, options: { store?: SuperTabStore } = {}) {const store = options.store ?? new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env))+ app.get('/api/super-tabs/grids', (req, reply) => respond(reply, () => store.hostGrids(req.user!)))app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/pools', { preHandler: validateParams(hostParams) },(req, reply) => respond(reply, () => store.hostPools(req.user!, req.params.machineId)))app.get<{ Params: z.infer<typeof hostStartParams> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', { preHandler: validateParams(hostStartParams) },diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex e8de2d69e..ce1fb4382 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -1,9 +1,10 @@import { describe, expect, it } from 'vitest'import { applyCommand, commandSchema, PAIR_CHAIN_LIMIT, type Command, type CommandContext } from './commands.js'-import { machineSlots, removalPreview } from './machines.js'+import { hostLocalGrid, machineSlots, removalPreview, swarmGridRow } from './machines.js'import { activeWork, agentRole, createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'import type { RouteDecision } from './routeRecord.js'import { agentTarget, broken } from './rules.js'+import { DEFAULT_ROUTING_POLICY, effectivePolicy } from './routingPolicy.js'const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }@@ -1940,3 +1941,117 @@ describe('other projects\' work for Leads', () => {.messages.filter(m => m.conversationId === f.state.leadsConversationId)).toEqual([])})})++describe('the Local models add-on', () => {+ const served = (f: ReturnType<typeof fixture>, grid: string, model = 'qwen3-30b', receivedAt = 1000) => {+ f.state.machines = [{ machineId: 'host', name: 'Studio', contributorId: 'owner', membershipGeneration: f.state.people[0]!.generation, generation: 'g1',+ cwd: '/repo', scope: 'swarm', engines: ['claude', 'codex'], maxAgents: 4, paused: false,+ observation: { receivedAt, localModels: [{ grid, model, name: 'Qwen3 30B' }] } } as never]+ }+ const start = (gridName: string, patch: Record<string, unknown> = {}) => ({ conversationId: 'lead', machineId: 'host', engine: 'claude', name: 'Local builder',+ cwd: '/repo/lead', worktree: true, gridModel: 'qwen3-30b', gridName, ...patch,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } })+ const grant = { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }++ it('is off until the owner turns it on, mints one grid name, and keeps it when turned off', () => {+ const f = fixture()+ expect(f.state.localModels).toBeUndefined()+ f.invite()+ expect(() => f.run({ type: 'localModels.set', enabled: true }, peer)).toThrow(expect.objectContaining({ code: 'OWNER_REQUIRED' }))+ const on = f.run({ type: 'localModels.set', enabled: true })+ expect(on.result.grid).toMatch(/^swarm-[0-9a-f]{12}$/)+ expect(f.state.localModels).toEqual({ grid: on.result.grid, enabled: true })+ f.run({ type: 'localModels.set', enabled: false })+ f.run({ type: 'localModels.set', enabled: true })+ expect(f.state.localModels).toEqual({ grid: on.result.grid, enabled: true })+ })++ it('gives the owner\'s computer the grid and the people who may act, and a host the grid only while it is on', () => {+ const f = fixture()+ expect(swarmGridRow('tab', f.state)).toBeNull()+ expect(hostLocalGrid(f.state)).toEqual({})+ f.invite()+ const grid = f.run({ type: 'localModels.set', enabled: true }).result.grid as string+ expect(swarmGridRow('tab', f.state)).toEqual({ tabId: 'tab', grid, enabled: true, ready: null, members: [peer.email] })+ expect(hostLocalGrid(f.state)).toEqual({ localGrid: grid })+ f.run({ type: 'localModels.status', grid, ready: true })+ f.run({ type: 'localModels.set', enabled: false })+ expect(swarmGridRow('tab', f.state)).toMatchObject({ enabled: false, ready: true })+ expect(hostLocalGrid(f.state)).toEqual({})+ // A viewer may not act in the Swarm, so is no member of its grid.+ const viewing = fixture()+ viewing.invite('viewer')+ viewing.run({ type: 'localModels.set', enabled: true })+ expect(swarmGridRow('tab', viewing.state)!.members).toEqual([])+ })++ it('takes the owner\'s computer\'s report of its grid, and nothing about another grid', () => {+ const f = fixture()+ const grid = f.run({ type: 'localModels.set', enabled: true }).result.grid as string+ f.run({ type: 'localModels.status', grid, ready: false, error: 'grid: plan limit reached' })+ expect(f.state.localModels).toMatchObject({ ready: false, error: 'grid: plan limit reached' })+ f.run({ type: 'localModels.status', grid, ready: true })+ expect(f.state.localModels).toEqual({ grid, enabled: true, ready: true })+ expect(() => f.run({ type: 'localModels.status', grid: 'swarm-other', ready: true })).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))+ })++ it('lets a contributed machine run a Builder on a model the Swarm\'s grid serves now, and only then', () => {+ const f = fixture()+ const grid = f.run({ type: 'localModels.set', enabled: true }).result.grid as string+ served(f, grid)+ f.run({ type: 'agent.start', request: start(grid) }, owner, grant)+ expect(f.state.starts).toHaveLength(1)++ const refused = (request: Record<string, unknown>, now = 1000) => () => applyCommand(f.state, owner, { type: 'agent.start', request } as Command,+ { now, operationId: 'op-x', ...grant })+ expect(refused(start('swarm-other'))).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ expect(refused(start(grid, { gridModel: 'llama-70b' }))).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ expect(refused(start(grid, { model: 'opus' }))).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ // A reading too old to trust says nothing is served.+ expect(refused(start(grid), 1000 + 60_000)).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ f.run({ type: 'localModels.set', enabled: false })+ expect(refused(start(grid))).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ })++ it('lets a machine run a Builder on a model shared with its owner on another grid, and only that machine', () => {+ const f = fixture()+ const grid = f.run({ type: 'localModels.set', enabled: true }).result.grid as string+ served(f, grid)+ const host = f.state.machines![0]!+ host.observation!.localModels = [{ grid: 'team-grid', model: 'qwen3-30b', kind: 'shared' }]+ // A second machine whose reading does not list it.+ f.state.machines!.push({ ...structuredClone(host), machineId: 'mini', name: 'Mini', observation: { ...structuredClone(host.observation!), localModels: [] } })+ const refused = (request: Record<string, unknown>, now = 1000) => () => applyCommand(f.state, owner, { type: 'agent.start', request } as Command,+ { now, operationId: 'op-x', ...grant })+ expect(refused(start('team-grid', { machineId: 'mini' }))).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ expect(refused(start('team-grid', { gridModel: 'llama-70b' }))).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ expect(refused(start('team-grid'), 1000 + 60_000)).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ f.run({ type: 'agent.start', request: start('team-grid') }, owner, grant)+ expect(f.state.starts).toEqual([expect.objectContaining({ request: expect.objectContaining({ machineId: 'host', gridName: 'team-grid', gridModel: 'qwen3-30b' }) })])+ // Not while the add-on is off.+ f.run({ type: 'localModels.set', enabled: false })+ expect(refused(start('team-grid'))).toThrow(expect.objectContaining({ code: 'OUTSIDE_CONTRIBUTION' }))+ })++ it('matches a start to a local route candidate by its grid model, and records it on the decision', () => {+ const f = fixture()+ const lead = f.add('lead', 'owner', 'lead', true)+ const grid = f.run({ type: 'localModels.set', enabled: true }).result.grid as string+ served(f, grid)+ const local = candidate('c0', { machineId: 'host', model: 'default', effort: 'default', quality: 1, cost: 1, gridModel: 'qwen3-30b', gridName: grid })+ const decision = { routeDecision: { id: 'd1', conversationId: 'lead', record: record({ candidates: [local, candidate('c1')], pick: 'c0' }),+ final: null, override: null, assignmentId: null, outcome: null } as unknown as RouteDecision }+ const actor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }+ const effects = f.run({ type: 'agent.start', request: start(grid), routeDecisionId: 'd1' }, actor, { ...grant, ...decision })+ expect(effects.routeDecisions).toEqual([expect.objectContaining({ op: 'final', final: expect.objectContaining({ gridModel: 'qwen3-30b', gridName: grid }) })])+ expect(effects.messages.some(m => m.source?.kind === 'route-override')).toBe(false)+ })++ it('reads the policy\'s local quality, low by default, from policies saved before the add-on', () => {+ expect(effectivePolicy(null, null).policy.localModels).toEqual({ quality: 1, enabled: true })+ const saved = { ...DEFAULT_ROUTING_POLICY } as Record<string, unknown>+ delete saved.localModels+ expect(effectivePolicy(saved, null).policy.localModels).toEqual({ quality: 1, enabled: true })+ expect(effectivePolicy(saved, { localModels: { quality: 2, enabled: true } }).policy.localModels).toEqual({ quality: 2, enabled: true })+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 1277c3218..f8724de80 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto'import { admitMachineStart, expireRemovals, machineContribution, ownedMachine, type ContributedMachine } from './machines.js'import { assignAgentDisplayNames } from './agentNames.js'import { z } from 'zod'@@ -64,6 +65,8 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),z.object({ type: z.literal('machine.remove'), machineId: id }).strict(),z.object({ type: z.literal('machine.cleaned'), machineId: id, removalId: id }).strict(),+ z.object({ type: z.literal('localModels.set'), enabled: z.boolean() }).strict(),+ z.object({ type: z.literal('localModels.status'), grid: z.string().min(1).max(160), ready: z.boolean(), error: z.string().trim().max(500).optional() }).strict(),z.object({ type: z.literal('tab.rename'), name: title }).strict(),z.object({ type: z.literal('tab.project'), machineId: id, project }).strict(),z.object({ type: z.literal('tab.pause'), paused: z.boolean() }).strict(),@@ -744,6 +747,27 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaresult.removedAgents = [...removed]break}+ case 'localModels.set': {+ // An add-on the owner turns on: its grid is theirs, and nothing calls grid until they do.+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Swarm owner turns Local models on or off.', 403)+ const current = state.localModels+ state.localModels = current+ ? { ...current, enabled: command.enabled }+ : { grid: swarmGridName(state.id), enabled: command.enabled }+ if (command.enabled && !current?.ready) { delete state.localModels.ready; delete state.localModels.error }+ result.grid = state.localModels.grid+ break+ }+ case 'localModels.status': {+ // The owner's host reports the grid it created and keeps in step with the Swarm's people.+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Swarm owner\'s computer reports its grid.', 403)+ const current = state.localModels+ if (!current || current.grid !== command.grid) fail('NOT_FOUND', 'This Swarm has no such grid.', 404)+ current.ready = command.ready+ if (command.error) current.error = command.error+ else delete current.error+ break+ }case 'tab.rename':// Writable people manage the swarm even when its original project is// gone. Agents retain the existing Lead-conversation authority.@@ -909,8 +933,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst r = command.requestconst model = r.model ?? 'default', effort = r.effort ?? 'default'const { decision, expected, override } = linkDecision(r.conversationId,- c => c.kind === 'new' && c.machineId === r.machineId && c.engine === r.engine && c.model === model && c.effort === effort,- () => ({ kind: 'new', startId: operationId, machineId: r.machineId, engine: r.engine, model, effort }), command.overrideReason)+ c => c.kind === 'new' && c.machineId === r.machineId && c.engine === r.engine && c.model === model && c.effort === effort+ && (c.gridModel ?? null) === (r.gridModel ?? null) && (c.gridName ?? null) === (r.gridName ?? null),+ () => ({ kind: 'new', startId: operationId, machineId: r.machineId, engine: r.engine, model, effort,+ ...(r.gridModel && r.gridName ? { gridModel: r.gridModel, gridName: r.gridName } : {}) }), command.overrideReason)if (override) message(r.conversationId, `Lead started ${r.name} instead of ${expected.title}. Reason: ${override.reason}`, [], null,{ kind: 'route-override', decisionId: decision.id, by: 'lead' })personChose = !override && decision.override?.by === 'person'@@ -1393,6 +1419,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}/** A contribution owns capacity independently of membership. Reuse invalidates every prior stop proof. */+/** The Swarm's grid name: `swarm-` and 12 hex of sha256(tab id). Derived so it is reproducible when supported; the+ * stored value is authoritative and never renamed. */+export function swarmGridName(tabId: string): string {+ return `swarm-${createHash('sha256').update(tabId).digest('hex').slice(0, 12)}`+}+function reserveHarnessSlot(state: SuperTabState, machineId: string, harnessId: string, generation: string) {const observation = state.machines?.find(m => m.machineId === machineId)?.observationconst renewed = !!(state.harnessReservations?.some(r => r.machineId === machineId && r.harnessId === harnessId)diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex ce297c1b0..674088414 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -50,6 +50,13 @@ export const machineObservationSchema = z.object({ generation: z.string().max(16quotas: z.array(quota).max(32), runningHarnessIds: z.array(z.string().max(160)).max(1000),stoppedHarnessIds: z.array(z.string().max(160)).max(1000),stoppedReservations: z.array(z.object({ harnessId: z.string().min(1).max(160), generation: z.string().min(1).max(160) }).strict()).max(1000).optional(),+ /** The Local models add-on (docs/plans/2026-10-23-swarm-local-models.md); absent from hosts before it. On the Swarm's+ * grid: what this machine serves there (`local` an engine of its own, `api` a saved API it shares), usable by agents on+ * any machine. On any other grid: a model its owner may use there (`shared`, shared with them), usable only by agents+ * on this machine, since only its sign-in reaches that grid. */+ localModels: 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(),}).strict()export type MachineObservation = z.infer<typeof machineObservationSchema>@@ -144,6 +151,38 @@ export function machineSlots(state: SuperTabState, pool: ContributedMachine) {return running.size + pending}+/** Machines of the Swarm serving models on its grid now, by model: only fresh readings count. */+/** What a Swarm's owner's computer keeps on grid for it (docs/plans/2026-10-23-swarm-local-models.md): the grid, and as its+ * members the people who may act in the Swarm. A viewer is not one, and the owner is the grid's admin already. */+export function swarmGridRow(tabId: string, state: SuperTabState) {+ const local = state.localModels+ if (!local) return null+ return { tabId, grid: local.grid, enabled: local.enabled, ready: local.ready ?? null,+ members: state.people.filter(p => p.role !== 'viewer' && p.id !== state.ownerId).map(p => p.email) }+}++/** The grid a contributed machine reports served models on: only while the add-on is on, so the host asks grid nothing otherwise. */+export const hostLocalGrid = (state: SuperTabState) => state.localModels?.enabled ? { localGrid: state.localModels.grid } : {}++export function servedLocalModels(state: SuperTabState, now: number) {+ const grid = state.localModels?.enabled ? state.localModels.grid : null+ if (!grid) return []+ return (state.machines ?? []).flatMap(m => !m.observation || now - m.observation.receivedAt > MACHINE_FRESH_MS ? []+ : (m.observation.localModels ?? []).filter(l => l.grid === grid).map(l => ({ ...l, machineId: m.machineId })))+}++/** Whether a start names a model it may run on now: one the Swarm's grid serves, from any machine; or one on another grid+ * that the start's own machine reads it can use (shared with its owner, owner 2026-10-23). Grid models carry no+ * subscription model or effort. */+export function localModelAllowed(state: SuperTabState, request: AgentStartRequest, now: number): boolean {+ const grid = state.localModels?.enabled ? state.localModels.grid : null+ if (!grid || !request.gridModel || !request.gridName || request.model || request.effort) return false+ if (request.gridName === grid) return servedLocalModels(state, now).some(l => l.model === request.gridModel)+ const pool = (state.machines ?? []).find(m => m.machineId === request.machineId)+ return !!pool?.observation && now - pool.observation.receivedAt <= MACHINE_FRESH_MS+ && (pool.observation.localModels ?? []).some(l => l.grid === request.gridName && l.model === request.gridModel)+}+export function admitMachineStart(state: SuperTabState, request: AgentStartRequest, now: number, start?: AgentStart) {const pool = machineContribution(state, request.machineId)if (!pool) return null@@ -161,7 +200,10 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartRequeif (request.cwd !== cwd) refused.push(`cwd (this project uses ${cwd} on it)`)const engines = contributedEngines(pool)if (!engines.includes(request.engine)) refused.push(`engine (it contributes ${engines.join(', ') || 'no engines'})`)- const settings = (['codexHome', 'gridModel', 'gridName'] as const).filter(key => request[key])+ // A model served on the Swarm's own grid is the one exception to "default account settings": the owner turned the+ // add-on on, and some machine of the Swarm serves it now.+ const local = localModelAllowed(state, request, now)+ const settings = (['codexHome', 'gridModel', 'gridName'] as const).filter(key => request[key] && !(local && key !== 'codexHome'))if (settings.length) refused.push(`${settings.join(', ')} (it runs with its own default account settings, so leave ${settings.length > 1 ? 'them' : 'it'} out)`)if (request.permissionMode !== undefined && request.permissionMode !== 'full') {refused.push('permissionMode (only full is accepted; leave it out to use the machine’s default)')diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex d71bdb159..04e469c34 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -193,6 +193,17 @@ export interface SuperTabState {machineCleanups?: import('./machines.js').MachineCleanup[]/** Conversations of a kind a later release added, set aside unchanged by a release that does not know it (parkLaterConversations). */parkedConversations?: Conversation[]+ /** The Local models add-on (docs/plans/2026-10-23-swarm-local-models.md): off until the owner turns it on, and only+ * then does anything call grid. The grid is kept when it is turned off, so turning it on again is instant. */+ localModels?: SwarmLocalModels+}+export interface SwarmLocalModels {+ /** The Swarm's own grid, minted on first turn-on and never renamed. */+ grid: string+ enabled: boolean+ /** What the owner's host last reported: the grid created and its members in step, or why not. */+ ready?: boolean+ error?: string}export interface OtherProjectWork {conversationId: stringdiff --git a/backend/src/superTabs/routeRecord.ts b/backend/src/superTabs/routeRecord.tsindex 9b6fd21df..e7cb81760 100644--- a/backend/src/superTabs/routeRecord.ts+++ b/backend/src/superTabs/routeRecord.ts@@ -31,6 +31,9 @@ export const routeCandidateSchema = z.object({/** The criterion line Jev was shown. */label: z.string().trim().min(1).max(640),fit: fit.optional(),+ /** A new agent on a model served on the Swarm's grid: its model and effort are `default`. */+ gridModel: z.string().min(1).max(200).optional(),+ gridName: z.string().min(1).max(160).optional(),}).strict().refine(c => (c.kind === 'member') === !!c.agentId, 'Members name their agent; new agents do not.')export const routeRecordSchema = z.object({assessment: z.object({ difficulty: level, risk: level, why: z.string().trim().min(1).max(300),@@ -58,7 +61,8 @@ export const routeRecordSchema = z.object({*/export const startedAs = (candidate: RouteCandidate, final: Extract<RouteFinal, { kind: 'new' }>): boolean =>final.machineId === candidate.machineId && final.engine === candidate.engine &&- (final.requested?.model ?? final.model) === candidate.model && (final.requested?.effort ?? final.effort) === candidate.effort+ (final.requested?.model ?? final.model) === candidate.model && (final.requested?.effort ?? final.effort) === candidate.effort &&+ (final.gridModel ?? null) === (candidate.gridModel ?? null) && (final.gridName ?? null) === (candidate.gridName ?? null)/** Whether a decision's final names this candidate: the same agent, or the same start. */export const finalMatches = (candidate: RouteCandidate, final: RouteFinal | null): boolean => !!final && (candidate.kind === 'member'@@ -70,7 +74,8 @@ export type RouteRecord = z.infer<typeof routeRecordSchema>export type RouteFinal =| { kind: 'member'; agentId: string; machineId: string }/** After a failed model switch, `model` and `effort` are what ran and `requested` is what routing asked for. */- | { kind: 'new'; startId: string; machineId: string; engine: string; model: string; effort: string; requested?: { model: string; effort: string } }+ | { kind: 'new'; startId: string; machineId: string; engine: string; model: string; effort: string; requested?: { model: string; effort: string };+ gridModel?: string; gridName?: string }export interface RouteOverride { by: 'lead' | 'person'; actorKey: string; candidateId?: string; reason: string }export interface RouteDecision {id: string; conversationId: string; record: RouteRecorddiff --git a/backend/src/superTabs/routingPolicy.ts b/backend/src/superTabs/routingPolicy.tsindex fd8c2bba8..1507779bb 100644--- a/backend/src/superTabs/routingPolicy.ts+++ b/backend/src/superTabs/routingPolicy.ts@@ -18,6 +18,9 @@ const fields = {floor: z.object({ low: quality, medium: quality, high: quality }).strict(),quotaReserve: z.number().int().min(0).max(90),notes: z.string().trim().max(500),+ /** How strong a model served on the Swarm's grid counts (the Local models add-on). Optional: policies saved before it+ * still parse, and read the default. */+ localModels: z.object({ quality, enabled: z.boolean() }).strict().optional(),}export const routingPolicySchema = z.object({ version: z.literal(1), ...fields }).strict()export const routingOverrideSchema = z.object(fields).partial().strict()@@ -36,6 +39,8 @@ export const DEFAULT_ROUTING_POLICY: RoutingPolicy = {floor: { low: 1, medium: 2, high: 3 },quotaReserve: 10,notes: '',+ // Local models are free but weaker: low-difficulty, well-specified work unless the owner says otherwise.+ localModels: { quality: 1, enabled: true },}export function effectivePolicy(account: unknown, override: unknown) {@@ -55,5 +60,6 @@ export function effectivePolicy(account: unknown, override: unknown) {overridden.push(...(Object.keys(parsed.data) as Array<keyof RoutingOverride>))}}+ policy = { ...policy, localModels: policy.localModels ?? DEFAULT_ROUTING_POLICY.localModels }return { policy, warnings, overridden }}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex e423fa684..f40e590d9 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,4 +1,4 @@-import { contributedEngines, machineContribution, machineObservationSchema, machineSlots, recordAgentPresence, removalPreview, type MachineObservation } from './machines.js'+import { contributedEngines, hostLocalGrid, machineContribution, machineObservationSchema, machineSlots, recordAgentPresence, removalPreview, swarmGridRow, type MachineObservation } from './machines.js'import { createHash } from 'node:crypto'import type { Prisma, PrismaClient, SuperTab, SuperTabDelivery } from '@prisma/client'import type { AuthUser } from '../lib/ssoAuth.js'@@ -979,6 +979,9 @@ export class SuperTabStore {groupProject(state, conversation(state, s.request.conversationId)).id === p.id)).map(p => ({ id: p.id, leadConversationId: p.leadConversationId, repository: p.repository,conversationIds: state.conversations.filter(c => !isLeads(c) && groupProject(state, c).id === p.id).map(c => c.id) })) } : {}),+ // The Swarm's grid while the Local models add-on is on: the host reports the models it serves there, and asks grid+ // nothing while it is off.+ ...hostLocalGrid(state),reservations: (state.harnessReservations ?? []).filter(r => r.machineId === machineId).map(({ harnessId, generation }) => ({ harnessId, generation })),harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...(state.harnessReservations ?? []).filter(r => r.machineId === machineId).map(r => r.harnessId), ...(state.starts ?? []).filter(s => s.request.machineId === machineId && s.harnessId).map(s => s.harnessId!)])] }]})@@ -995,6 +998,12 @@ export class SuperTabStore {})}+ /** The owner's Swarms with the Local models add-on: what the owner's computer creates on grid and keeps in step. */+ async hostGrids(user: AuthUser) {+ const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, ownerId: user.sub }, take: 100 })+ return rows.flatMap(row => swarmGridRow(row.id, stateOf(row)) ?? [])+ }+async observeMachine(user: AuthUser, tabId: string, machineId: string, input: MachineObservation) {const observation = machineObservationSchema.parse(input)return transaction(this.db, async tx => {diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 53e54f555..25083d4a2 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_fleet_run', 'grid_fleet_cancel', 'grid_swarm_sync', 'grid_swarm_api_share', 'grid_swarm_api_shares','api_connections', 'codex_profiles_list', 'codex_profile_link',] as constdiff --git a/cli/src/lib/localModels.spec.ts b/cli/src/lib/localModels.spec.tsindex 4a83b07a9..765223a9a 100644--- a/cli/src/lib/localModels.spec.ts+++ b/cli/src/lib/localModels.spec.ts@@ -1664,6 +1664,30 @@ describe('models other apps downloaded, started in their own app', () => {expect(JSON.parse(await readFile(join(stateDir, 'app-engines.json'), 'utf8'))).toEqual([])})+ it('says a model is served on a Swarm\'s grid while its engine runs there, and keeps it from starting twice', async () => {+ const swarm = 'swarm-0123456789ab'+ const models = appService()+ await models.act(swarm, ollama.id, 'start'); await models.settled()+ let row = (await models.list('home', true)).models.find(m => m.id === ollama.id)!+ expect(row).toMatchObject({ state: 'downloaded', canStart: false, servedOn: [{ grid: swarm, servedAs: ['llama3.2:3b'] }] })+ // Its engine gone: nothing is served there, and it starts again.+ up.clear()+ row = (await models.list('home', true)).models.find(m => m.id === ollama.id)!+ expect(row).toMatchObject({ canStart: true })+ expect(row).not.toHaveProperty('servedOn')+ })++ 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 })+ await mkdir(stateDir, { recursive: true })+ await writeFile(join(stateDir, 'app-engines.json'), JSON.stringify([record('home'), record('swarm-0123456789ab')]))+ up.add(ollama.id); joinedAliases.add('llama3.2:3b')+ const row = (await appService().list('home', true)).models.find(m => m.id === ollama.id)!+ expect(row.servedOn).toEqual([{ grid: 'home', servedAs: ['llama3.2:3b'] }, { grid: 'swarm-0123456789ab', servedAs: ['llama3.2:3b'] }])+ expect((await appService({ appEngines: undefined }).list('home', true)).models.find(m => m.id === ollama.id)).not.toHaveProperty('servedOn')+ })+it('keeps an engine it started stoppable when a later scan reads the model differently', async () => {const models = appService()await models.act('home', ollama.id, 'start'); await models.settled()diff --git a/cli/src/lib/localModels.ts b/cli/src/lib/localModels.tsindex c8acc43cb..a26929799 100644--- a/cli/src/lib/localModels.ts+++ b/cli/src/lib/localModels.ts@@ -809,7 +809,11 @@ export class LocalModels {const elsewhere = this.elsewhere?.grid !== grid ? this.elsewhere?.operation : undefinedconst operation = this.active?.operation ?? elsewhere ?? (this.receipt?.grid === grid ? this.receipt.operation : undefined)const apps = await this.apps(force)- const records = (await this.records()).filter(record => record.grid === grid)+ const allRecords = await this.records()+ const records = allRecords.filter(record => record.grid === grid)+ // An app's engine this daemon started on another grid — a Swarm's (docs/plans/2026-10-23-swarm-local-models.md):+ // its model is served there, so the row says so and cannot start a second engine beside it.+ const away = allRecords.filter(record => record.grid !== grid)// An engine this daemon started is read from its record, whatever a later scan makes of the model: a// scan that missed the person's llama-server (busy serving, it answered `--version` late) once listed// a running engine as Grid's, and Stop then had nothing to stop.@@ -877,8 +881,13 @@ export class LocalModels {const alive = record && this.options.appEngines ? await this.options.appEngines.alive(record) : falseconst listed = !!record && listedHere(record.alias)const running = alive && (listed || asleep)+ const elsewhere: ServedOn[] = []+ for (const there of away.filter(r => r.modelId === id)) {+ if (this.options.appEngines && await this.options.appEngines.alive(there)) elsewhere.push({ grid: there.grid, servedAs: [there.alias] })+ }return { id, name, app: APP_LABEL[app], state: running ? 'running' : 'downloaded', ...extra, ...(record ? { servedAs: [record.alias] } : {}),- canStart: !inventoryError && !record, canStop: !inventoryError && !!record,+ ...(elsewhere.length ? { servedOn: [...(running && record ? [{ grid, servedAs: [record.alias] }] : []), ...elsewhere] } : {}),+ canStart: !inventoryError && !record && !elsewhere.length, canStop: !inventoryError && !!record,operation: operation?.modelId === id ? operation : undefined, ...(running && !listed ? { gridAsleep: true } : {}) }}for (const app of apps.filter(a => a.engine !== 'grid' || recorded(a.id))) {diff --git a/cli/src/lib/swarmApiShares.spec.ts b/cli/src/lib/swarmApiShares.spec.tsnew file mode 100644index 000000000..7244965d5--- /dev/null+++ b/cli/src/lib/swarmApiShares.spec.ts@@ -0,0 +1,130 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { mkdtemp, readFile, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { SwarmApiShares } from './swarmApiShares.js'+import type { ApiConnection } from './apiConnections.js'+import type { GridResult } from './gridExec.js'++const GRID = 'swarm-0123456789ab'+const ok: GridResult = { code: 'OK', exitCode: 0, stdout: '', stderr: '', message: '' }+const connection = { id: 'c1', name: 'OpenRouter', baseUrl: 'https://api.example.test/v1/' } as unknown as ApiConnection+const KEY = 'fixture-secret-key'++function setup(patch: { exec?: (args: readonly string[]) => Promise<GridResult>; fetch?: typeof fetch; access?: () => { connection: ApiConnection; apiKey: string }; stateFile?: string } = {}) {+ const exec = vi.fn(patch.exec ?? (async () => ok))+ const upstream = vi.fn(patch.fetch ?? (async () => new Response('{"ok":true}', { status: 200, headers: { 'content-type': 'application/json' } })))+ const shares = new SwarmApiShares({ access: patch.access ?? (() => ({ connection, apiKey: KEY })), exec, fetch: upstream as unknown as typeof fetch, ...(patch.stateFile ? { stateFile: patch.stateFile } : {}) })+ /** The local endpoint grid was told to join. */+ const at = () => { const args = exec.mock.calls.find(c => c[0].includes('join'))![0]; return args[args.indexOf('--at') + 1]! }+ return { shares, exec, upstream, at }+}++describe('an API shared with a Swarm', () => {+ let open: SwarmApiShares | null = null+ afterEach(async () => { await open?.stopAll(); open = null })++ it('joins a local endpoint under a secret path, which forwards completions and model lists with the key', async () => {+ const f = setup(); open = f.shares+ expect(await f.shares.share(GRID, 'c1', 'deepseek/deepseek-chat')).toEqual({ ok: true })+ const args = f.exec.mock.calls[0]![0]+ expect(args).toEqual(['--remote', 'join', GRID, '--at', expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+\/[0-9a-f]{36}\/v1$/), '-m', 'deepseek/deepseek-chat',+ '--advertise-as', 'deepseek/deepseek-chat', '--max-concurrency', '4', '--name', 'OpenRouter'])+ expect(args.join(' ')).not.toContain(KEY)+ expect(f.shares.list(GRID)).toEqual([{ grid: GRID, connectionId: 'c1', model: 'deepseek/deepseek-chat', name: 'OpenRouter' }])+ expect(f.shares.list('other')).toEqual([])+ // Sharing it again is done already.+ expect(await f.shares.share(GRID, 'c1', 'deepseek/deepseek-chat')).toEqual({ ok: true })+ expect(f.exec).toHaveBeenCalledOnce()++ const answer = await fetch(`${f.at()}/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'text/event-stream' }, body: '{"model":"m"}' })+ expect(answer.status).toBe(200)+ expect(await answer.json()).toEqual({ ok: true })+ const [url, init] = f.upstream.mock.calls[0]! as unknown as [string, RequestInit & { headers: Record<string, string> }]+ expect(url).toBe('https://api.example.test/v1/chat/completions')+ expect(init.headers).toEqual({ authorization: `Bearer ${KEY}`, 'content-type': 'application/json', accept: 'text/event-stream' })+ expect(String(init.body)).toBe('{"model":"m"}')+ expect((await fetch(`${f.at()}/models`)).status).toBe(200)+ expect(f.upstream.mock.calls[1]![1]).not.toHaveProperty('body')+ })++ it('answers nothing outside its path and its three calls, too large a request, or an API that cannot be reached', async () => {+ const f = setup({ fetch: (async () => { throw new Error('offline') }) as unknown as typeof fetch }); open = f.shares+ await f.shares.share(GRID, 'c1', 'm')+ const root = f.at().replace(/\/[0-9a-f]{36}\/v1$/, '')+ expect((await fetch(`${root}/v1/models`)).status).toBe(404)+ expect((await fetch(`${f.at()}/embeddings`, { method: 'POST', body: '{}' })).status).toBe(404)+ expect((await fetch(`${f.at()}/models`, { method: 'DELETE' })).status).toBe(404)+ expect((await fetch(`${f.at()}/chat/completions`, { method: 'POST', body: Buffer.alloc(33 * 1024 * 1024) }).catch(() => ({ status: 413 }))).status).toBe(413)+ expect((await fetch(`${f.at()}/chat/completions?x=1`, { method: 'POST', body: '{}' })).status).toBe(502)+ expect(f.upstream).toHaveBeenCalledOnce()+ })++ it('passes a body-less answer through, and its type when the API names none', async () => {+ const f = setup({ fetch: (async () => new Response(null, { status: 204 })) as unknown as typeof fetch }); open = f.shares+ await f.shares.share(GRID, 'c1', 'm')+ const answer = await fetch(`${f.at()}/chat/completions`, { method: 'POST', body: '{}' })+ expect(answer.status).toBe(204)+ })++ it('stops by leaving the grid and closing its endpoint, and says why when grid or the API refuses', async () => {+ const f = setup(); open = f.shares+ await f.shares.share(GRID, 'c1', 'm')+ const at = f.at()+ expect(await f.shares.stop(GRID, 'c1', 'm')).toEqual({ ok: true })+ expect(f.exec).toHaveBeenLastCalledWith(['--remote', 'leave', GRID, '--engine', 'm'])+ await expect(fetch(`${at}/models`)).rejects.toThrow()+ expect(f.shares.list()).toEqual([])+ expect(await f.shares.stop(GRID, 'c1', 'm')).toEqual({ ok: true })++ const refused = setup({ exec: async () => ({ ...ok, code: 'GRID_FAILED', exitCode: 1, stderr: 'not a member\n' }) })+ expect(await refused.shares.share(GRID, 'c1', 'm')).toEqual({ error: 'not a member' })+ expect(refused.shares.list()).toEqual([])+ const silent = setup({ exec: async () => ({ ...ok, code: 'GRID_FAILED', exitCode: 1 }) })+ expect(await silent.shares.share(GRID, 'c1', 'm')).toEqual({ error: 'grid refused the request.' })++ const unsaved = setup({ access: () => { throw new Error('This API is not saved.') } })+ expect(await unsaved.shares.share(GRID, 'c9', 'm')).toEqual({ error: 'This API is not saved.' })+ const odd = setup({ access: () => { throw 'odd' } })+ expect(await odd.shares.share(GRID, 'c9', 'm')).toEqual({ error: 'This API is not saved.' })++ // Leaving refused: still shared, and said.+ const stuck = setup(); open = stuck.shares+ await stuck.shares.share(GRID, 'c1', 'm')+ stuck.exec.mockResolvedValueOnce({ ...ok, code: 'GRID_FAILED', exitCode: 1, stderr: 'busy' })+ expect(await stuck.shares.stop(GRID, 'c1', 'm')).toEqual({ error: 'busy' })+ expect(stuck.shares.list()).toHaveLength(1)+ })++ it('notes its shares without the key, and the next process shares them again', async () => {+ const stateFile = join(await mkdtemp(join(tmpdir(), 'swarm-api-shares-')), 'shares.json')+ const f = setup({ stateFile }); open = f.shares+ await f.shares.share(GRID, 'c1', 'm')+ const noted = await readFile(stateFile, 'utf8')+ expect(JSON.parse(noted)).toEqual([{ grid: GRID, alias: 'm', connectionId: 'c1' }])+ expect(noted).not.toContain(KEY)+ await f.shares.stopAll()+ // The process ended without stopping it: the note is still there.+ await writeFile(stateFile, noted)+ const next = setup({ stateFile }); open = next.shares+ await next.shares.restore()+ expect(next.exec.mock.calls.map(c => c[0].slice(0, 3))).toEqual([['--remote', 'leave', GRID], ['--remote', 'join', GRID]])+ 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' }])+ 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 })+ await old.shares.restore()+ expect(old.exec.mock.calls).toEqual([[['--remote', 'leave', GRID, '--engine', 'x']]])+ 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()+ expect(failing.shares.list()).toEqual([])+ expect(await failing.shares.share(GRID, 'c1', 'm')).toEqual({ error: 'grid could not be run on this computer.' })+ await writeFile(stateFile, 'not json')+ await setup({ stateFile }).shares.restore()+ 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.tsnew file mode 100644index 000000000..cdc7942f1--- /dev/null+++ b/cli/src/lib/swarmApiShares.ts@@ -0,0 +1,138 @@+/**+ * A saved API shared with a Swarm (docs/plans/2026-10-23-swarm-local-models.md, owner 2026-10-23): Builders on any of the+ * Swarm's machines may run on one of its models, through the Swarm's grid, on the sharer's key and credits.+ *+ * Grid joins only engines it can reach as OpenAI-compatible endpoints, and its own `--api` kinds cover OpenAI alone, so+ * this computer answers for the API: a server on 127.0.0.1, under a path no other process knows, that forwards a model+ * list or a completion to the API with the saved key — the way an app's local engine is joined (`localModels.ts`). The key+ * stays in this process: never in argv, a record on disk, a log line or a reply.+ */+import { randomBytes } from 'node:crypto'+import { readFile, writeFile } from 'node:fs/promises'+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'+import { Readable } from 'node:stream'+import type { ApiConnection } from './apiConnections.js'+import type { GridResult } from './gridExec.js'++/** What a request may do through a share: list models, or complete. Nothing else of the API is reachable. */+const ALLOWED = new Set(['GET /models', 'POST /chat/completions', 'POST /completions'])+/** A Claude Code turn sends its whole context; this is well above one and well below what would hurt the process. */+const MAX_BODY = 32 * 1024 * 1024+/** Several Builders may share one API model, unlike a local engine that answers one at a time. */+const CONCURRENCY = 4++export interface SwarmApiShare { grid: string; connectionId: string; model: string; name: string }++export interface SwarmApiSharesDeps {+ access: (connectionId: string) => { connection: ApiConnection; apiKey: string }+ exec: (args: readonly string[]) => Promise<GridResult>+ fetch?: typeof fetch+ /** Where the shares are noted, by grid, API and model, never the key: an endpoint dies with this process, and the next+ * one shares them again ([restore]). */+ stateFile?: string+}++interface Running extends SwarmApiShare { server: Server; alias: 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>()+ constructor(private readonly deps: SwarmApiSharesDeps) {}++ 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 }> {+ 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,+ '--advertise-as', model, '--max-concurrency', String(CONCURRENCY), '--name', access.connection.name]).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 }> {+ 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])+ if (left.code !== 'OK') return { error: said(left) }+ running.server.close()+ this.running.delete(keyOf(running))+ await this.note()+ 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> {+ if (!this.deps.stateFile) return+ const 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 }+ 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(() => {})+ }+ 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(() => {})+ }++ /** Every share off its grid, as the process ends: an endpoint that is gone serves nothing. */+ async stopAll(): Promise<void> {+ for (const share of [...this.running.values()]) await this.stop(share.grid, share.connectionId, share.model).catch(() => {})+ }++ private serve(token: string, { connection, apiKey }: { connection: ApiConnection; apiKey: string }): Server {+ const prefix = `/${token}/v1`+ return createServer((req, res) => { void this.forward(req, res, prefix, connection, apiKey) })+ }++ private async forward(req: IncomingMessage, res: ServerResponse, prefix: string, connection: ApiConnection, apiKey: string): Promise<void> {+ const url = req.url ?? ''+ const path = url.startsWith(`${prefix}/`) ? url.slice(prefix.length).split('?')[0]! : null+ if (path === null || !ALLOWED.has(`${req.method} ${path}`)) { res.writeHead(404).end(); return }+ const chunks: Buffer[] = []+ let size = 0+ for await (const chunk of req) {+ size += (chunk as Buffer).length+ if (size > MAX_BODY) { res.writeHead(413).end(); return }+ chunks.push(chunk as Buffer)+ }+ try {+ const answer = await (this.deps.fetch ?? fetch)(`${connection.baseUrl.replace(/\/+$/, '')}${path}`, {+ method: req.method,+ headers: { authorization: `Bearer ${apiKey}`, ...(req.headers['content-type'] ? { 'content-type': req.headers['content-type'] } : {}),+ ...(req.headers.accept ? { accept: req.headers.accept } : {}) },+ ...(req.method === 'POST' ? { body: Buffer.concat(chunks) } : {}),+ })+ res.writeHead(answer.status, { 'content-type': answer.headers.get('content-type') ?? 'application/json' })+ if (answer.body) Readable.fromWeb(answer.body as never).pipe(res)+ else res.end()+ } catch {+ if (!res.headersSent) res.writeHead(502)+ res.end()+ }+ }+}diff --git a/cli/src/lib/swarmGrid.spec.ts b/cli/src/lib/swarmGrid.spec.tsnew file mode 100644index 000000000..2f4ce5dab--- /dev/null+++ b/cli/src/lib/swarmGrid.spec.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest'+import { syncSwarmGrid, type SwarmGridDeps } from './swarmGrid.js'+import type { GridResult } from './gridExec.js'++const GRID = 'swarm-0123456789ab'+const ok: GridResult = { code: 'OK', exitCode: 0, stdout: '', stderr: '', message: '' }+const failed = (stderr: string, message = ''): GridResult => ({ ...ok, code: 'GRID_FAILED', exitCode: 1, stderr, message })++function deps(listed: unknown, patch: Partial<SwarmGridDeps> = {}) {+ const exec = vi.fn(async (_args: readonly string[]) => ok)+ const json = vi.fn(async () => ({ value: listed, result: ok })) as unknown as SwarmGridDeps['json']+ return { ensure: vi.fn(async () => ({ status: 'existed' as const, message: '' })), exec, json, ...patch }+}++describe('a Swarm\'s grid', () => {+ it('adds the people it lacks as both, removes those the Swarm no longer has, and never its admin', async () => {+ const d = deps([{ email: '[email protected]', roles: ['admin'] }, { email: '[email protected]', roles: ['both'] }, { email: '[email protected]' }, { roles: [] }, null])+ expect(await syncSwarmGrid(GRID, [' [email protected]', '[email protected]', ''], d)).toEqual({ ready: true, added: ['[email protected]'], removed: ['[email protected]'] })+ expect(d.ensure).toHaveBeenCalledWith(GRID)+ expect(d.json).toHaveBeenCalledWith(['--remote', 'members', 'list', GRID])+ expect(vi.mocked(d.exec).mock.calls).toEqual([[['--remote', 'members', 'add', GRID, '[email protected]', '--role', 'both']], [['--remote', 'members', 'remove', GRID, '[email protected]']]])+ })+ it('reads a member list wrapped in an object, and treats anything else as empty', async () => {+ expect(await syncSwarmGrid(GRID, ['[email protected]'], deps({ members: [{ email: '[email protected]' }] }))).toEqual({ ready: true, added: [], removed: [] })+ expect(await syncSwarmGrid(GRID, ['[email protected]'], deps(null))).toMatchObject({ ready: true, added: ['[email protected]'] })+ })+ it('counts a grid made, found or adopted as there, and says why otherwise', async () => {+ for (const status of ['created', 'adopted'] as const) expect((await syncSwarmGrid(GRID, [], deps([], { ensure: async () => ({ status, message: '' }) }))).ready).toBe(true)+ expect(await syncSwarmGrid(GRID, [], deps([], { ensure: async () => ({ status: 'refused', message: 'Free plan limit.' }) })))+ .toEqual({ ready: false, error: 'Free plan limit.', final: true, added: [], removed: [] })+ expect(await syncSwarmGrid(GRID, [], deps([], { ensure: async () => ({ status: 'failed', message: '' }) })))+ .toEqual({ ready: false, error: 'The grid could not be set up.', added: [], removed: [] })+ })+ it('stops at the first refusal, in grid\'s own words', async () => {+ const unlisted = deps([], { json: (async () => ({ value: null, result: failed('', 'grid is not signed in.') })) as unknown as SwarmGridDeps['json'] })+ expect(await syncSwarmGrid(GRID, [], unlisted)).toEqual({ ready: false, error: 'grid is not signed in.', added: [], removed: [] })+ const silent = deps([], { json: (async () => ({ value: null, result: failed('') })) as unknown as SwarmGridDeps['json'] })+ expect((await syncSwarmGrid(GRID, [], silent)).error).toBe('grid refused the request.')+ const adding = deps([], { exec: vi.fn(async () => failed('not an admin\n')) })+ expect(await syncSwarmGrid(GRID, ['[email protected]'], adding)).toEqual({ ready: false, error: 'Could not add [email protected]: not an admin', added: [], removed: [] })+ const removing = deps([{ email: '[email protected]' }], { exec: vi.fn(async () => failed('busy')) })+ expect(await syncSwarmGrid(GRID, [], removing)).toEqual({ ready: false, error: 'Could not remove [email protected]: busy', added: [], removed: [] })+ })+})diff --git a/cli/src/lib/swarmGrid.ts b/cli/src/lib/swarmGrid.tsnew file mode 100644index 000000000..0991b9a83--- /dev/null+++ b/cli/src/lib/swarmGrid.ts@@ -0,0 +1,59 @@+/**+ * A Swarm's own grid (docs/plans/2026-10-23-swarm-local-models.md): created by the Swarm owner's computer once the owner+ * turns the Local models add-on on, and kept so its members are the Swarm's people who may act there. Only the owner, the+ * grid's admin, changes its members (owner, 2026-10-23), so this runs on the owner's computer alone.+ *+ * Every call goes through `grid` (`gridExec.ts`): the control plane owns the grid and its member list, Harness only asks.+ */+import { ensureHarnessGrid, type EnsureResult } from './gridEnsure.js'+import { gridExec, gridJson, type GridResult } from './gridExec.js'++const REMOTE = '--remote'+/** A member that can both use and serve models (owner, 2026-10-23). */+const ROLE = 'both'++export interface SwarmGridDeps {+ ensure: (name: string) => Promise<EnsureResult>+ exec: (args: readonly string[]) => Promise<GridResult>+ json: <T>(args: readonly string[]) => Promise<{ value: T | null; result: GridResult }>+}+const DEPS: SwarmGridDeps = { ensure: name => ensureHarnessGrid(name), exec: args => gridExec(args), json: args => gridJson(args) }++/** [final]: grid refused for a reason only the person can change (its plan's grid limit); asking again changes nothing. */+export interface SwarmGridSync { ready: boolean; error?: string; final?: boolean; added: string[]; removed: string[] }++const said = (r: GridResult) => (r.stderr.trim() || r.message || 'grid refused the request.').slice(0, 400)+const normal = (email: string) => email.trim().toLowerCase()++/** Creates [name] if it is missing, then adds the [members] it lacks and removes members the Swarm no longer has. The+ * admin (the owner) is never removed: grid keeps the creator's role on every membership write. */+export async function syncSwarmGrid(name: string, members: readonly string[], deps: SwarmGridDeps = DEPS): Promise<SwarmGridSync> {+ const ensured = await deps.ensure(name)+ if (!['created', 'existed', 'adopted'].includes(ensured.status)) {+ return { ready: false, error: ensured.message || 'The grid could not be set up.', ...(ensured.status === 'refused' ? { final: true } : {}), added: [], removed: [] }+ }+ const listed = await deps.json<unknown>([REMOTE, 'members', 'list', name])+ if (listed.result.code !== 'OK') return { ready: false, error: said(listed.result), added: [], removed: [] }+ const rows = Array.isArray(listed.value) ? listed.value : Array.isArray((listed.value as { members?: unknown } | null)?.members)+ ? (listed.value as { members: unknown[] }).members : []+ const current = rows.flatMap(row => {+ const r = (row && typeof row === 'object' ? row : {}) as { email?: unknown; roles?: unknown }+ const roles = Array.isArray(r.roles) ? r.roles : []+ return typeof r.email === 'string' ? [{ email: normal(r.email), admin: roles.includes('admin') }] : []+ })+ const wanted = new Set(members.map(normal).filter(Boolean))+ const added: string[] = [], removed: string[] = []+ for (const email of wanted) {+ if (current.some(m => m.email === email)) continue+ const result = await deps.exec([REMOTE, 'members', 'add', name, email, '--role', ROLE])+ if (result.code !== 'OK') return { ready: false, error: `Could not add ${email}: ${said(result)}`, added, removed }+ added.push(email)+ }+ for (const member of current) {+ if (member.admin || wanted.has(member.email)) continue+ const result = await deps.exec([REMOTE, 'members', 'remove', name, member.email])+ if (result.code !== 'OK') return { ready: false, error: `Could not remove ${member.email}: ${said(result)}`, added, removed }+ removed.push(member.email)+ }+ return { ready: true, added, removed }+}diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.tsindex dc71e4bcd..29737ee81 100644--- a/cli/src/lib/swarmSkills.spec.ts+++ b/cli/src/lib/swarmSkills.spec.ts@@ -45,6 +45,9 @@ describe('built-in Swarm skills', () => {const terminal = '- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.\n'// The approved overlap line (spec/2026-10-23-leads-see-and-talk.md, call 6), the Lead's alone, in both modes.const overlap = '- Before assigning, look at other projects\' active work; if your task touches the same code, say so in the Leads conversation and agree an order first.\n'+ // The Local models line (owner, 2026-10-23: the Lead considers Builders on local models; docs/plans/2026-10-23-swarm-local-models.md).+ const local = '- Local models: when the Swarm serves one (a member\'s model, a shared API, a model shared with a member), the route may pick it for low-difficulty, well-specified work; it costs no subscription. Set "local":true in the route only when a person asks for a local model. When a person names a model, set "model" to their words ("deepseek 4.1 flash"): the route then offers that model alone. Start the pick with the gridModel and gridName the route gives, never a model or effort.\n'+ const localDefault = '- Local models: the route may pick one for low-difficulty, well-specified work; set "local":true only when a person asks for one, set "model" to a model a person names, and start it with the route\'s gridModel and gridName.\n'const twoHours = '- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).\n'it.each([['lead', '5fc83d8c43b66b44cdab27b48235dbc86b7ab11a57153edc1ae7e92831642a8e'],@@ -60,7 +63,8 @@ describe('built-in Swarm skills', () => {expect(text.split(twoHours)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(terminal)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(overlap)).toHaveLength(role === 'lead' ? 2 : 1)- expect(sha(text.replace(twoHours, '').replace(terminal, '').replace(overlap, ''))).toBe(sha256)+ expect(text.split(local)).toHaveLength(role === 'lead' ? 2 : 1)+ expect(sha(text.replace(twoHours, '').replace(terminal, '').replace(overlap, '').replace(local, ''))).toBe(sha256)}})it('adds the 2-hour line to section 7 right after the 6-hour rule', () => {@@ -90,7 +94,8 @@ describe('built-in Swarm skills', () => {const text = readFileSync(prepared.file, 'utf8')expect(text.split(terminal)).toHaveLength(role === 'lead' ? 2 : 1)expect(text.split(overlap)).toHaveLength(role === 'lead' ? 2 : 1)- expect(sha(text.replace(terminal, '').replace(overlap, ''))).toBe(sha256)+ expect(text.split(localDefault)).toHaveLength(role === 'lead' ? 2 : 1)+ expect(sha(text.replace(terminal, '').replace(overlap, '').replace(localDefault, ''))).toBe(sha256)expect(prepared.instructions).toBe(`Use the swarm-${role} skill for this session: the team process; otherwise work your usual way. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)})diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsindex c4021b118..c2858bc1a 100644--- a/cli/src/lib/swarmSkills.ts+++ b/cli/src/lib/swarmSkills.ts@@ -108,6 +108,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc- Route each group before starting or assigning: difficulty, risk, size, why, needs. Use the pick, or override with a reason.- Match strength to work: mechanical → cheaper; integration and judgment → standard; design or subtle risk → strongest. A review is at least as strong as the build. Don't go below the standard tier for Reviewers, or for Builders working from prose; the cheapest models take more turns and end up costing more.- Reuse an idle agent before starting a new one. Start only on the Swarm's listed machines, from the branch the work builds on.+- Local models: when the Swarm serves one (a member's model, a shared API, a model shared with a member), the route may pick it for low-difficulty, well-specified work; it costs no subscription. Set "local":true in the route only when a person asks for a local model. When a person names a model, set "model" to their words ("deepseek 4.1 flash"): the route then offers that model alone. Start the pick with the gridModel and gridName the route gives, never a model or effort.- The brief is all a Builder gets. Never pass your chat history; put everything needed in the brief.- Before assigning, look at other projects' active work; if your task touches the same code, say so in the Leads conversation and agree an order first.@@ -382,6 +383,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir## 3. Route, start, assign- Route each group; reuse an idle agent before starting one; start only on the Swarm's machines.+- Local models: the route may pick one for low-difficulty, well-specified work; set "local":true only when a person asks for one, set "model" to a model a person names, and start it with the route's gridModel and gridName.- The brief is all a Builder gets; never rely on chat history.- Before assigning, look at other projects' active work; if your task touches the same code, say so in the Leads conversation and agree an order first.diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.tsindex a61d23d94..51ebef6b8 100644--- a/cli/src/services/models.spec.ts+++ b/cli/src/services/models.spec.ts@@ -25,7 +25,10 @@ import { ApiConnections, apiConnectionsRequest } from '../lib/apiConnections.js'import { apiModelsRequest, apiTargetAnswer, refreshApiFor, rememberSavedApis } from '../lib/apiModels.js'import { linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'import { fakeCore } from '../testing/fakeCore.js'-import { compactRuntimePickerModels, launchTarget, MODELS_REQUESTS, startModels } from './models.js'+import { compactRuntimePickerModels, launchTarget, MODELS_REQUESTS, startModels, swarmLaunchTarget } from './models.js'+import { gridExec } from '../lib/gridExec.js'+import { syncSwarmGrid } from '../lib/swarmGrid.js'+import { SwarmApiShares } from '../lib/swarmApiShares.js'const access = vi.hoisted(() => ({ ensure: vi.fn(async (_request?: { ownGrid?: boolean }): Promise<GridAttachResult> => ({ status: 'converged', name: 'grid-1', detail: 'ok' })) }))vi.mock('../lib/gridAttach.js', () => ({@@ -35,7 +38,14 @@ vi.mock('../lib/gridAttach.js', () => ({}))vi.mock('../lib/gridDerive.js', () => ({ deriveHarnessGridName: vi.fn(async () => null), resetGridDeriveMemo: vi.fn(), signedInGridEmail: vi.fn(() => '[email protected]') }))vi.mock('../lib/gridEnsure.js', () => ({ ensureHarnessGrid: vi.fn(async () => 'converged') }))-vi.mock('../lib/gridExec.js', () => ({ gridAvailable: vi.fn(() => true), gridCliPresence: vi.fn(() => 'managed'), managedGridPath: vi.fn(() => null) }))+vi.mock('../lib/gridExec.js', () => ({ gridAvailable: vi.fn(() => true), gridCliPresence: vi.fn(() => 'managed'), managedGridPath: vi.fn(() => null), gridExec: vi.fn(async () => ({ code: 'OK' })) }))+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> => {}),+}))+vi.mock('../lib/swarmApiShares.js', () => ({ SwarmApiShares: vi.fn(function () { return apiShares }) }))+vi.mock('../lib/swarmGrid.js', () => ({ syncSwarmGrid: vi.fn(async () => ({ ready: true, added: ['[email protected]'], removed: [] })) }))/** The Model Manager's grid commands: what each job was run as, and what it answers. */const fleet = vi.hoisted(() => ({ run: vi.fn(async (..._args: unknown[]): Promise<Record<string, unknown>> => ({ ok: true, code: 0, stdout: '[]', stderr: '', error: null })), cancel: vi.fn((..._args: unknown[]) => true) }))vi.mock('../lib/gridFleetRpc.js', async (real) => ({@@ -64,7 +74,8 @@ vi.mock('../lib/runtimeInstall.js', () => ({ ensureManagedGrid: vi.fn(async () =/** The saved APIs and the Codex profiles: their files and folders are the lib's, never this machine's here. */const apis = vi.hoisted(() => ({ stores: [] as string[], bases: vi.fn(() => [] as string[]) }))vi.mock('../lib/apiConnections.js', () => ({- ApiConnections: class { constructor(dataDir: string) { apis.stores.push(dataDir) } recognizedBases = apis.bases },+ ApiConnections: class { constructor(dataDir: string) { apis.stores.push(dataDir) } recognizedBases = apis.bases+ modelAccess(id: string) { return { connection: { id }, apiKey: 'fixture' } } },apiConnectionsRequest: vi.fn((_store: unknown, payload: Record<string, unknown>) => ({ connections: [], presets: [], action: payload.action })),}))vi.mock('../lib/apiModels.js', () => ({@@ -345,6 +356,20 @@ describe('the models service', () => {}})+ it('a new agent on a Swarm\'s grid signs grid in and pulls the account\'s grids first, and starts nothing when grid cannot be set up', async () => {+ vi.mocked(listGridModels).mockResolvedValueOnce([{ id: 'qwen3', node: 'Mac Studio' }])+ vi.mocked(resolveGridTarget).mockResolvedValueOnce(target)+ const { port } = setup()+ expect(await port.launchTarget({ model: 'qwen3', grid: 'swarm-0123456789ab' })).toEqual(target)+ expect(access.ensure).toHaveBeenCalledWith({ ownGrid: false })+ expect(gridExec).toHaveBeenCalledWith(['--remote', 'sync'])+ expect(resolveGridTarget).toHaveBeenCalledWith('swarm-0123456789ab', 'qwen3')+ const sync = vi.fn(async () => {})+ access.ensure.mockResolvedValueOnce({ status: 'handoff-failed', name: null, detail: 'signed out' })+ expect(await swarmLaunchTarget(access as never, { model: 'qwen3', grid: 'swarm-0123456789ab' }, sync)).toBeNull()+ expect(sync).not.toHaveBeenCalled()+ })+it('a move grid cannot be set up for says why and reads no grid; one whose endpoint cannot be read says so', async () => {const { port } = setup()access.ensure.mockResolvedValueOnce({ status: 'handoff-failed', name: null, detail: 'no grid on this computer' })@@ -367,6 +392,50 @@ describe('the models service', () => {expect(GridFleetRpc).toHaveBeenCalledTimes(1)})+ it('keeps a Swarm\'s grid in step for its owner only, with the Swarm\'s grid name and real addresses', async () => {+ const { requests } = setup()+ const sync = requests.grid_swarm_sync!+ expect(await sync({ grid: 'swarm-0123456789ab', members: ['[email protected]', 'not an address', 7] }, asker)).toEqual({ ready: true, added: ['[email protected]'], removed: [] })+ expect(syncSwarmGrid).toHaveBeenCalledWith('swarm-0123456789ab', ['[email protected]'])+ expect(await sync({ grid: 'swarm-0123456789ab', members: [] }, { ...asker, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })+ expect(await sync({ grid: 'my-grid', members: [] }, asker)).toEqual({ error: 'INVALID_REQUEST' })+ expect(await sync({ grid: 7, members: [] }, asker)).toEqual({ error: 'INVALID_REQUEST' })+ expect(await sync({ grid: 'swarm-0123456789ab' }, asker)).toEqual({ error: 'INVALID_REQUEST' })+ expect(await sync({ grid: 'swarm-0123456789ab', members: Array.from({ length: 201 }, (_, i) => `p${i}@example.com`) }, asker)).toEqual({ error: 'INVALID_REQUEST' })+ access.ensure.mockResolvedValueOnce({ status: 'handoff-failed', name: null, detail: 'signed out' })+ expect(await sync({ grid: 'swarm-0123456789ab', members: [] }, asker)).toEqual({ ready: false, error: 'signed out', added: [], removed: [] })+ expect(syncSwarmGrid).toHaveBeenCalledTimes(1)+ })++ it('shares a saved API with a Swarm\'s grid for this computer\'s own person, signed in to grid first', async () => {+ // Clearing what an earlier process left never holds the service up, even when it fails.+ apiShares.restore.mockRejectedValueOnce(new Error('grid gone'))+ const { requests } = setup()+ const share = requests.grid_swarm_api_share!+ const ask = { grid: 'swarm-0123456789ab', connectionId: 'c1', model: 'm', action: 'start' }+ expect(await share(ask, asker)).toEqual({ ok: true })+ expect(apiShares.share).toHaveBeenCalledWith('swarm-0123456789ab', 'c1', 'm')+ expect(await share({ ...ask, action: 'stop' }, asker)).toEqual({ ok: true })+ expect(apiShares.stop).toHaveBeenCalledWith('swarm-0123456789ab', 'c1', 'm')+ expect(await share(ask, { ...asker, local: false })).toEqual({ error: 'OWNER_REQUIRED' })+ expect(await share(ask, { ...asker, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })+ for (const bad of [{ grid: 'team' }, { connectionId: 7 }, { model: '' }, { model: 'x'.repeat(201) }, { model: 7 }, { action: 'pause' }]) {+ expect(await share({ ...ask, ...bad }, asker)).toEqual({ error: 'INVALID_REQUEST' })+ }+ access.ensure.mockResolvedValueOnce({ status: 'handoff-failed', name: null, detail: 'signed out' })+ expect(await share(ask, asker)).toEqual({ error: 'signed out' })+ expect(apiShares.share).toHaveBeenCalledTimes(1)+ expect(requests.grid_swarm_api_shares!({ grid: 'swarm-0123456789ab' }, asker)).toEqual({ shares: [expect.objectContaining({ model: 'm' })] })+ expect(apiShares.list).toHaveBeenLastCalledWith('swarm-0123456789ab')+ requests.grid_swarm_api_shares!({}, asker)+ expect(apiShares.list).toHaveBeenLastCalledWith(undefined)+ // Its endpoint reads the saved API afresh and runs this computer's grid.+ const deps = (vi.mocked(SwarmApiShares).mock.calls.at(-1) as unknown as [{ access: (id: string) => unknown; exec: (args: string[]) => Promise<unknown> }])[0]+ expect(deps.access('c1')).toEqual({ connection: { id: 'c1' }, apiKey: 'fixture' })+ await deps.exec(['--remote', 'ls'])+ expect(gridExec).toHaveBeenLastCalledWith(['--remote', 'ls'])+ })+it('refuses a command it cannot read, or one with no connection or request to belong to', async () => {const { requests } = setup()expect(await requests.grid_fleet_run!({ args: [] }, asker)).toEqual({ error: 'INVALID_GRID_COMMAND' })@@ -606,6 +675,19 @@ describe('the models service', () => {expect(local.act).not.toHaveBeenCalled()})+ it('a start or stop with a Swarm `grid` runs on that grid; a download, or a name that is not a Swarm grid, does not', async () => {+ const { ask } = setup([], named)+ local.act.mockClear()+ await ask('grid_fleet_model_start', { modelId: 'org/Model-GGUF', grid: 'swarm-0123456789ab' })+ await ask('grid_fleet_model_stop', { modelId: 'org/Model-GGUF', grid: 'swarm-0123456789ab' })+ await ask('grid_fleet_model_download', { modelId: 'org/Model-GGUF', grid: 'swarm-0123456789ab' })+ await ask('grid_fleet_model_start', { modelId: 'org/Model-GGUF', grid: 'someone-elses-grid' })+ expect(local.act.mock.calls).toEqual([+ ['swarm-0123456789ab', 'org/Model-GGUF', 'start'], ['swarm-0123456789ab', 'org/Model-GGUF', 'stop'],+ ['kelvin-1a2b3c4d', 'org/Model-GGUF', 'download'], ['kelvin-1a2b3c4d', 'org/Model-GGUF', 'start'],+ ])+ })+it('answers what the act answers, as it is', async () => {local.act.mockResolvedValueOnce({ operation: { action: 'start', modelId: 'org/Model-GGUF' } })local.act.mockResolvedValueOnce({ error: 'fixture refusal' })diff --git a/cli/src/services/models.ts b/cli/src/services/models.tsindex 16c1d2bf2..26a22a5cb 100644--- a/cli/src/services/models.ts+++ b/cli/src/services/models.ts@@ -23,7 +23,7 @@ import { linkCodexProfile, listCodexProfiles } from '../lib/codexProfiles.js'import { createGridAccess, gridNamesLocal, reconcileGridAttach } from '../lib/gridAttach.js'import { deriveHarnessGridName, resetGridDeriveMemo, signedInGridEmail } from '../lib/gridDerive.js'import { ensureHarnessGrid } from '../lib/gridEnsure.js'-import { gridAvailable, managedGridPath } from '../lib/gridExec.js'+import { gridAvailable, gridExec, managedGridPath } from '../lib/gridExec.js'import { GridFleetRpc, parseGridFleetRequest } from '../lib/gridFleetRpc.js'import { handOffToGrid } from '../lib/gridHandoff.js'import { ensureGridInstalled } from '../lib/gridInstall.js'@@ -41,6 +41,8 @@ import type { NewAgentModel } from '../lib/newAgentModel.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'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 { internalOnThrow } from './requestErrors.js'/** The requests models answers for the apps, declared in core/api.ts for the core to route. */@@ -149,7 +151,7 @@ export function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {// The keystroke prewarm (grid-reads-without-waking issue 03): typing into a pane whose agent runs on// a sleeping grid starts that grid while the person types.prewarm: (target) => { void keystrokePrewarm(target).catch(() => {}) },- launchTarget: (selection) => launchTarget(selection),+ launchTarget: (selection) => SWARM_GRID.test(selection.grid) ? swarmLaunchTarget(grid, selection) : launchTarget(selection),moveTarget: (request) => moveTarget(grid, privateGridName, core, request),// The agent is on a grid model now and its pane is restarting: start that grid meanwhile if it sleeps,// so the first message rarely waits on a boot (issue 03). It decides for itself whether a wake is@@ -190,6 +192,17 @@ export async function launchTarget(selection: NewAgentModel): Promise<GridLaunchreturn resolveGridTarget(selection.grid, selection.model)}+/**+ * A Builder on a model served on a Swarm's grid (docs/plans/2026-10-23-swarm-local-models.md) may start on a machine that+ * never used grid: it signs in first (the Harness sign-in handed to `grid login --harness`), then pulls the account's grids,+ * since the Swarm's grid is new to this machine until a sync lists it.+ */+export async function swarmLaunchTarget(grid: GridSetUp, selection: NewAgentModel, sync: () => Promise<unknown> = () => gridExec(['--remote', 'sync'])): Promise<GridLaunchOverride | null> {+ if (await notReady(grid, false)) return null+ await sync()+ return launchTarget(selection)+}+/*** Grid set up for an act, or the sentence saying why it could not be: null when it is ready. The* picker's Set up, a Get, a Use and a move onto a grid model each ask it.@@ -226,6 +239,17 @@ async function moveTarget(/** Sections one `grid_models_list` may ask to wake — a person presses one "Show models" at a time. */const MAX_WAKES_PER_ASK = 8+/** The APIs this computer shares with Swarms: one set for the process, since each holds a live endpoint. */+function swarmApiShares(dataDir: string): SwarmApiShares {+ const saved = new ApiConnections(dataDir)+ const shares = new SwarmApiShares({ access: (id) => saved.modelAccess(id), exec: (args) => gridExec(args), stateFile: join(dataDir, 'swarm-api-shares.json') })+ void shares.restore().catch(() => {})+ return shares+}++/** A Swarm's grid name as the backend mints it (backend/src/superTabs/commands.ts `swarmGridName`). */+const SWARM_GRID = /^swarm-[0-9a-f]{12}$/+type LocalModelRequest = 'grid_fleet_models_list' | 'grid_fleet_model_download' | 'grid_fleet_model_start' | 'grid_fleet_model_stop'/**@@ -275,9 +299,12 @@ function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => Preturn { ...snapshot, ...(needed ? { gridSetupNeeded: true } : {}), ...(unready ? { gridSetupError: unready } : {}) }}if (unready) return { error: unready }- // A start or stop for the community grid of this computer's OS (`osGrid`): run there, for its members.+ // A start or stop for the community grid of this computer's OS (`osGrid`): run there, for its members. Or for a+ // Swarm's own grid (docs/plans/2026-10-23-swarm-local-models.md), named by the Swarm and checked by grid itself:+ // only its members may serve there.const community = payload.community === true && type !== 'grid_fleet_model_download'- const target = community ? await localModels.communityGrid() : gridName+ const swarm = type !== 'grid_fleet_model_download' && typeof payload.grid === 'string' && SWARM_GRID.test(payload.grid) ? payload.grid : null+ const target = swarm ?? (community ? await localModels.communityGrid() : gridName)if (community && !target) return { error: 'This computer is in no community grid.' }return { ...await localModels.act(target, payload.modelId, type === 'grid_fleet_model_download' ? 'download' : type === 'grid_fleet_model_start' ? 'start' : 'stop') }} catch {@@ -354,7 +381,7 @@ 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(),+ ...gridCommands(grid, core.dataDir),...launchTargetRequests(core),}}@@ -369,7 +396,7 @@ function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => P* that harness's own `harness grid setup`; until then grid answers these in its own words. Their* handshake, `grid_fleet_capabilities`, is the socket's (core/api.ts `MODELS_REQUESTS`).*/-function gridCommands(): ServiceRequests {+function gridCommands(grid: GridSetUp, dataDir: string, shares: SwarmApiShares = swarmApiShares(dataDir)): ServiceRequests {const fleet = new GridFleetRpc()return {// Pulls and builds can take minutes; the host answers when it is done and holds nothing else for it.@@ -382,6 +409,31 @@ function gridCommands(): ServiceRequests {return { ok: false, code: 1, error: 'Grid command failed unexpectedly.' }}},+ // A Swarm's own grid, created and kept in step with its people by the owner's computer (lib/swarmGrid.ts).+ grid_swarm_sync: async (payload, asker) => {+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }+ const members = Array.isArray(payload.members) ? payload.members.filter((m): m is string => typeof m === 'string' && /^[^\s@]+@[^\s@]+$/.test(m)) : null+ if (typeof payload.grid !== 'string' || !SWARM_GRID.test(payload.grid) || !members || members.length > 200) return { error: 'INVALID_REQUEST' }+ // Signed in first: the owner may never have used grid on this computer before turning the add-on on.+ const unready = await notReady(grid, false)+ if (unready) return { ready: false, error: unready, added: [], removed: [] }+ return { ...await syncSwarmGrid(payload.grid, members) }+ },+ // A saved API shared with a Swarm's grid, on this computer's key (lib/swarmApiShares.ts). This computer's own person+ // alone: the key is theirs, and so are the credits every Builder in the Swarm then spends.+ grid_swarm_api_share: async (payload, asker) => {+ if (!asker.local || !asker.owner) return { error: 'OWNER_REQUIRED' }+ const { grid: name, connectionId, model, action } = payload+ if (typeof name !== 'string' || !SWARM_GRID.test(name) || typeof connectionId !== 'string' || typeof model !== 'string'+ || !model || model.length > 200 || (action !== 'start' && action !== 'stop')) return { error: 'INVALID_REQUEST' }+ if (action === 'stop') return { ...await shares.stop(name, connectionId, model) }+ const unready = await notReady(grid, false)+ if (unready) return { error: unready }+ return { ...await shares.share(name, connectionId, model) }+ },+ grid_swarm_api_shares: (payload) => ({+ shares: shares.list(typeof payload.grid === 'string' ? payload.grid : undefined),+ }),grid_fleet_cancel: (payload, asker) => ({cancelled: !!asker.connection && typeof payload.commandId === 'string' && fleet.cancel(asker.connection, payload.commandId),}),diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 3a74cfae9..dbfd5e608 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -1,5 +1,6 @@import { OBSERVER_VALID_MS, publishObservers } from './observers.js'import { ContributedMachines } from './machines.js'+import { SwarmGrids } from './swarmGrids.js'import { retainContributions } from './retention.js'import { configurationObservation } from './configuration.js'import { NativeRecorder, nativeJournalFile } from './native.js'@@ -198,6 +199,7 @@ export class SuperTabHost {private timer: ReturnType<typeof setTimeout> | null = nullprivate native: NativeRecorder | null = nullprivate machines: ContributedMachines | null = null+ private grids: SwarmGrids | null = null/** The waits last handed to the core (superTabs/attention.ts); null until the first roster, which is always handed* over whole, so a restarted service closes what its predecessor raised and no longer holds. */private attention: string | null = null@@ -307,6 +309,8 @@ export class SuperTabHost {private pollMachines() {this.machines ??= new ContributedMachines(this.core, this.machineId)void this.machines.tick().catch(error => this.log(error instanceof Error ? error.message : String(error)))+ this.grids ??= new SwarmGrids(this.core, this.machineId)+ void this.grids.tick().catch(error => this.log(`Swarm grid: ${error instanceof Error ? error.message : String(error)}`))}private recordNative(): void {if (!this.native?.hasWork || this.stopped) returndiff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex a63db31bd..dd4b7a853 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 { ContributedMachines, swarmWorktreesFile } from './machines.js'+import { apisOn, ContributedMachines, servedOn, sharedWith, swarmWorktreesFile } from './machines.js'import { SuperTabHostError } from './host.js'import { startAgent } from './start.js'@@ -155,6 +155,76 @@ describe('contributed machine executor', () => {expect(posts[1]![3]).not.toHaveProperty('toolProbeErrors')})+ it('lists the models it serves on the Swarm\'s grid only while the add-on is on, and drops them for an older backend', async () => {+ const GRID = 'swarm-0123456789ab'+ const f = fixture()+ await f.machine.tick()+ const local = (await f.open.mock.results[0]!.value) as { request: ReturnType<typeof vi.fn> }+ expect(local.request.mock.calls.some(c => c[0] === 'grid_fleet_models_list')).toBe(false)+ expect(f.backend.mock.calls.find(c => c[1] === 'POST')![3]).not.toHaveProperty('localModels')+ Object.assign(f.pool, { localGrid: GRID })+ local.request.mockImplementation((async (type: string) => type === 'grid_fleet_models_list'+ ? { 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' }] })+ // 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()!+ f.backend.mockImplementation(async (core, method, path, body) => {+ if (method === 'POST' && (body as Record<string, unknown>)?.localModels) throw new SuperTabHostError('VALIDATION_ERROR', 'Unrecognized key: localModels', 400)+ return original(core, method, path, body)+ })+ f.advance(); await f.machine.tick()+ const posts = f.backend.mock.calls.filter(c => c[1] === 'POST')+ expect(posts.at(-2)![3]).toMatchObject({ localModels: [] })+ expect(posts.at(-1)![3]).not.toHaveProperty('localModels')+ })+ it('adds the APIs it shares on the Swarm\'s grid and the models shared with its owner, and reads other grids once a minute', 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> }+ local.request.mockImplementation((async (type: string) => type === 'grid_swarm_api_shares'+ ? { shares: [{ grid: GRID, connectionId: 'c1', model: 'deepseek/deepseek-chat', name: 'OpenRouter' }] }+ : type === 'grid_models_list' ? { grids: [{ name: 'team-grid', models: [{ id: 'qwen3-30b' }] }] } : { 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: 'deepseek/deepseek-chat', name: 'deepseek/deepseek-chat · OpenRouter', kind: 'api' },+ { grid: 'team-grid', model: 'qwen3-30b', kind: 'shared' },+ ] })+ const reads = () => local.request.mock.calls.filter(c => c[0] === 'grid_models_list').length+ const before = reads()+ f.advance(); await f.machine.tick()+ expect(reads()).toBe(before)+ f.step(60_000); await f.machine.tick()+ expect(reads()).toBe(before + 1)+ })+ it('reads only live models of grids other than Swarms\', once each, and shared APIs of this Swarm alone', () => {+ const GRID = 'swarm-0123456789ab'+ expect(sharedWith(null, GRID)).toEqual([])+ expect(sharedWith({ grids: [+ { name: GRID, models: [{ id: 'mine' }] }, { name: 'swarm-ffffffffffff', models: [{ id: 'theirs' }] },+ { name: 'team', models: [{ id: 'a' }, { id: 'a' }, { id: 'down', unavailable: { reason: 'offline' } }, { id: 7 }, { id: '' }] },+ { name: 7, models: [{ id: 'b' }] }, { name: 'x'.repeat(161), models: [{ id: 'c' }] },+ ] }, GRID)).toEqual([{ grid: 'team', model: 'a', kind: 'shared' }])+ expect(apisOn({ shares: [{ grid: GRID, model: 'm' }, { grid: 'other', model: 'n' }, { grid: GRID, model: '' }, { grid: GRID, model: 'x'.repeat(201) }] }, GRID))+ .toEqual([{ grid: GRID, model: 'm', kind: 'api' }])+ expect(apisOn(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([])+ expect(servedOn({ models: [+ { name: 7, contextWindow: 1.5, servedOn: [{ grid: 'other', servedAs: ['elsewhere'] }, { grid: GRID, servedAs: ['', 9, 'qwen3'] }] },+ { servedOn: [{ grid: GRID, servedAs: 'qwen3' }] }, { servedOn: [{ grid: GRID, servedAs: ['x'.repeat(201)] }] }, { contextWindow: -1, servedOn: [{ grid: GRID }] },+ ] }, GRID)).toEqual([{ grid: GRID, model: 'qwen3', kind: 'local' }])+ const many = { models: Array.from({ length: 20 }, (_, i) => ({ name: 'n'.repeat(300), servedOn: [{ grid: GRID, servedAs: [`m${i}`] }] })) }+ const read = servedOn(many, GRID)+ expect(read).toHaveLength(16)+ expect(read[0]!.name).toHaveLength(200)+ })+it('binds stopped native proof to the current slot reservation generation', async () => {const f = fixture()Object.assign(f.pool, { reservations: [{ harnessId: 'stopped', generation: 'new-contribution' }] })diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex a186033b8..8748293cf 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -88,6 +88,16 @@ export class ContributedMachines {private readonly cleaning = new Map<string, Promise<void>>()/** Per removal whose cleanup or acknowledgement failed, how often and when it may run again. */private readonly cleanupRetries = new Map<string, { failures: number; at: number }>()+ /** The grids this machine reads, at most once a minute: every Swarm's reading shares it. */+ private gridModelsRead: { at: number; answer: unknown } | null = null+ private async gridModels(local: { request: (type: string, payload: Record<string, unknown>, timeoutMs: number) => Promise<unknown> }): Promise<unknown> {+ const now = this.deps.now()+ if (this.gridModelsRead && now - this.gridModelsRead.at < GRID_MODELS_MS) return this.gridModelsRead.answer+ const answer = await local.request('grid_models_list', { rowState: true }, 20_000).catch(() => ({}))+ // A failed read is asked again next time, not held for a minute as "nothing shared".+ if (Array.isArray(object(answer).grids)) this.gridModelsRead = { at: now, answer }+ return answer+ }constructor(private readonly core: CoreApi, private readonly machineId: string,private readonly deps: { backend: typeof backend; open: typeof openDaemon; capabilities: typeof readCapabilities;start: typeof startAgent; now: () => number; prepare?: typeof prepareSwarmProject; log?: (message: string) => void; env?: NodeJS.ProcessEnv } =@@ -171,7 +181,14 @@ export class ContributedMachines {? list(object(await local.request('engines_probe', { engines: ['claude', 'codex'] }, 20_000).catch(() => ({}))).engines).filter(engine => supported(String(engine.engine)) && engine.installed === true).map(engine => String(engine.engine)): listedEngines.filter(supported)- const observation = { generation: pool.generation, tools: reportedTools,+ // 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 it may use on other grids (shared with its owner, usable here alone).+ 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),+ ...sharedWith(await this.gridModels(local), row.localGrid),+ ].slice(0, MAX_LOCAL_MODELS) : null+ const observation = { generation: pool.generation, tools: reportedTools, ...(localModels ? { localModels } : {}),...(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),@@ -189,9 +206,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)) throw error- // Older backends reject the additive field. Their boolean-only view still safely refuses an unverified tool.- const { toolProbeErrors: _probeErrors, ...legacy } = observation+ if (!(error instanceof SuperTabHostError) || error.status !== 400 || error.code !== 'VALIDATION_ERROR' || !('toolProbeErrors' in observation || 'localModels' 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 } = observationawait this.deps.backend(this.core, 'POST', path, legacy)}this.published.set(String(row.tabId), { at: began, signature })@@ -316,3 +333,46 @@ export class ContributedMachines {command: { type: 'machine.cleaned', machineId: this.machineId, removalId } })}}++/** The backend's limit on one machine's local models (`machineObservationSchema`). */+const MAX_LOCAL_MODELS = 64+/** How often the grids this machine may use are read again for its Swarms. */+const GRID_MODELS_MS = 60_000+/** Every Swarm's grid, as the backend mints its name: their models belong to their own Swarm. */+const SWARM_GRID = /^swarm-[0-9a-f]{12}$/++type LocalModelReading = { grid: string; model: string; name?: string; contextWindow?: number; kind: 'local' | 'api' | 'shared' }++/** 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)+ .map(s => ({ grid, model: String(s.model), ...(typeof s.name === 'string' ? { name: `${String(s.model)} · ${s.name}`.slice(0, 200) } : {}), kind: 'api' as const }))+}++/** The live models a `grid_models_list` answer says this machine may use on grids other than Swarms' (owner, 2026-10-23:+ * Builders may use local models shared with their machine's owner). Each Swarm's grid is left to its own Swarm. */+export function sharedWith(answer: unknown, swarmGrid: string): LocalModelReading[] {+ const out: LocalModelReading[] = []+ for (const section of list(object(answer).grids)) {+ const grid = typeof section.name === 'string' ? section.name : ''+ if (!grid || grid.length > 160 || grid === swarmGrid || SWARM_GRID.test(grid)) continue+ for (const model of list(section.models)) {+ if (typeof model.id !== 'string' || !model.id || model.id.length > 200 || model.unavailable) continue+ if (!out.some(m => m.grid === grid && m.model === model.id)) out.push({ grid, model: model.id, kind: 'shared' })+ }+ }+ return out+}++/** 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[] = []+ for (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) : undefined+ if (!served || out.length >= 16) continue+ 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' })+ }+ return out+}diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.tsindex 8adfb44d9..80476a907 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 { 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 { 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>@@ -487,3 +487,55 @@ describe('the owner\'s rules', () => {expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x' })).not.toHaveProperty('kind')})})++describe('local models on the Swarm\'s grid', () => {+ const local = (patch: Partial<Probe> = {}) => probe({ model: 'default', effort: 'default', quality: 1, cost: 1, quota: { known: false, leftPercent: null, resetsAt: null },+ gridModel: 'qwen3', gridName: 'swarm-0123456789ab', gridLabel: 'Qwen 3', ...patch })+ it('reads local only as true, and leaves it out otherwise', () => {+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', local: true })).toMatchObject({ local: true })+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', local: false })).not.toHaveProperty('local')+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', local: 'yes' })).toContain('local')+ })+ it('fits a local model on no subscription, names it as local and records where it is served', () => {+ const r = ok(choose([local()], policy, a({ difficulty: 'low' }), NOW))+ expect(r.shown[0]).toMatchObject({ title: 'New agent · Claude on Qwen 3 (local) · remote-1', fit: { status: 'fits', account: 'local:swarm-0123456789ab:qwen3' } })+ expect(r.shown[0]!.label).toContain('Claude on Qwen 3 (local)')+ expect((recordOf(r, decide(r), a(), policy) as { candidates: unknown[] }).candidates[0]).toMatchObject({ gridModel: 'qwen3', gridName: 'swarm-0123456789ab' })+ // Without a name or a label: the model stands for both, and nothing about the grid is recorded without a grid.+ const bare = ok(choose([local({ gridName: undefined, gridLabel: undefined })], policy, a({ difficulty: 'low' }), NOW))+ expect(bare.shown[0]).toMatchObject({ title: 'New agent · Claude on qwen3 (local) · remote-1', fit: { account: 'local::qwen3' } })+ expect((recordOf(bare, decide(bare), a(), policy) as { candidates: unknown[] }).candidates[0]).not.toHaveProperty('gridModel')+ })+ it('keeps a local model under the floor of a harder task, and keeps it beside a subscription row of the same name', () => {+ const r = ok(choose([probe(), local()], policy, a(), NOW))+ expect(r.shown.map(s => s.gridModel)).toEqual([undefined])+ // Same machine, engine, model and effort as a subscription `default` row: both stay, being different models.+ const both = ok(choose([probe({ model: 'default', effort: 'default', quality: 1, cost: 1, quota: windows([80, 3 * H], [90, 5 * D]) }), local()], policy, a({ difficulty: 'low' }), NOW))+ expect(both.shown).toHaveLength(2)+ })+ it('considers only local models when a person asked for one, whatever the floor, and says when none is served', () => {+ const r = ok(choose([probe({ model: 'opus', effort: 'high', quality: 3, cost: 3 }), local()], policy, a({ difficulty: 'high', local: true }), NOW))+ expect(r.shown.map(s => s.gridModel)).toEqual(['qwen3'])+ expect(r.belowFloor).toBe(false)+ expect(choose([probe()], policy, a({ local: true }), NOW)).toEqual({ error: 'NO_CANDIDATE', excluded: [{ title: 'Local models', reason: LOCAL_NONE }] })+ })++ it('offers only the model a person named, whatever its strength, and says when nothing runs it', () => {+ const api = local({ gridModel: 'deepseek/deepseek-v4.1-flash-1017', gridLabel: 'deepseek/deepseek-v4.1-flash-1017 · OpenRouter', gridKind: 'api' })+ const older = local({ gridModel: 'DeepSeek-V4-Flash-0731', gridLabel: undefined, gridKind: 'shared' })+ const opus = probe({ model: 'opus', effort: 'high', quality: 3, cost: 3, quota: windows([80, 3 * H], [90, 5 * D]) })+ const r = ok(choose([opus, older, api], policy, a({ difficulty: 'high', model: 'deepseek 4.1 flash' }), NOW))+ expect(r.shown.map(s => s.gridModel)).toEqual(['deepseek/deepseek-v4.1-flash-1017'])+ expect(r.shown[0]!.title).toBe('New agent · Claude on deepseek/deepseek-v4.1-flash-1017 · OpenRouter (API) · remote-1')+ expect(r.belowFloor).toBe(false)+ // A subscription model by name, and the engine's name counts as one of its words.+ 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.' }] })+ 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')+ })+})diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.tsindex fd21aa843..2ad5348cd 100644--- a/cli/src/superTabs/route.ts+++ b/cli/src/superTabs/route.ts@@ -9,7 +9,11 @@ import { claudeAliasForModel } from '../engines/claude/runtimeProfile.js'export type Level = 'low' | 'medium' | 'high'export type Size = 'small' | 'medium' | 'large'/** `kind` is a word the Lead may give (`ui`, `docs`) for the owner's preferred-engine rules; a review group's is `review`. */-export interface Assessment { difficulty: Level; risk: Level; size: Size; why: string; kind?: string; needs: { tools: string[]; devices: string[]; cwd?: string } }+/** `local`: a person asked for a local model by hand, so only models served on the Swarm's grid are considered and the+ * quality floor does not apply (docs/plans/2026-10-23-swarm-local-models.md). */+/** `model`: a model a person named, in their words ("deepseek 4.1 flash"); only candidates running it are considered,+ * whatever their strength (owner, 2026-10-23: a Builder on a named API model was ranked below Opus and never offered). */+export interface Assessment { difficulty: Level; risk: Level; size: Size; why: string; kind?: string; local?: boolean; model?: string; needs: { tools: string[]; devices: string[]; cwd?: string } }/** The owner's rules as the backend keeps them (backend/src/superTabs/rules.ts); only the rule and its words are read here. */export type Rule =| { kind: 'forbidModel'; engine?: string; model: string }@@ -19,7 +23,9 @@ export type Rule =| { kind: 'preferIdle' }export interface SwarmRule { rule: Rule; text: string }export interface PolicyModel { engine: 'claude' | 'codex'; model: string; effort: string; quality: number; cost: number; enabled: boolean }-export interface Policy { version: 1; models: PolicyModel[]; floor: Record<Level, number>; quotaReserve: number; notes: string }+export interface Policy { version: 1; models: PolicyModel[]; floor: Record<Level, number>; quotaReserve: number; notes: string;+ /** How strong a model served on the Swarm's grid counts; absent from a backend before it, which serves none. */+ localModels?: { quality: number; enabled: boolean } }/** One usage window, named by the reader (`5-hour`, `weekly`); `leftPercent` is what remains of it. */export interface QuotaWindow { name: string | null; leftPercent: number; resetsAt: number | null }/** `leftPercent` and `resetsAt` are the tightest window's; `windows` is every window. `account` is the reading's hashed@@ -42,6 +48,9 @@ export interface Probe {terminalUnverified?: boolean/** New agents: what the machine has. */load?: MachineLoad+ /** A new agent on a model served on the Swarm's grid: free, reached through the grid relay, `model`/`effort` `default`.+ * [gridKind]: a member's engine (`local`), a member's API (`api`), or a model shared with this machine's owner. */+ gridModel?: string; gridName?: string; gridLabel?: string; gridKind?: 'local' | 'api' | 'shared'}export interface Attempt { agent: string; outcome: string; result?: string }export interface RecentRoute { title: string; via?: string; outcome: string | null }@@ -117,7 +126,10 @@ export function parseAssessment(value: unknown): Assessment | string {const cwd = needs.cwdif (cwd !== undefined && (typeof cwd !== 'string' || !isAbsolute(cwd))) return 'needs.cwd must be an absolute path.'if (v.kind !== undefined && (typeof v.kind !== 'string' || !/^[a-z][a-z0-9-]{0,39}$/.test(v.kind))) return 'Set kind to one lowercase word, such as ui or docs.'+ if (v.local !== undefined && typeof v.local !== 'boolean') return 'Set local to true only when a person asked for a local model.'+ if (v.model !== undefined && (typeof v.model !== 'string' || !words(v.model).length || v.model.length > 200)) return 'Set model to the model a person named, in their words.'return { difficulty: v.difficulty as Level, risk: v.risk as Level, size: size as Size, why, ...(v.kind ? { kind: v.kind as string } : {}),+ ...(v.local === true ? { local: true } : {}), ...(typeof v.model === 'string' ? { model: v.model.trim() } : {}),needs: { tools: list(needs.tools), devices: list(needs.devices), ...(cwd ? { cwd } : {}) } }}@@ -165,7 +177,17 @@ export function rateFor(policy: Policy, engine: string, model: string | null, efreturn row ? { quality: row.quality, cost: row.cost } : { quality: 1, cost: 1 }}-const titleOf = (p: Probe) => cut(`${p.kind === 'member' ? p.name ?? 'Member' : 'New agent'} · ${ENGINE[p.engine]} ${p.model} ${p.effort} · ${p.machineName}`, 160)+const KIND_WORD = { local: 'local', api: 'API', shared: 'shared' } as const+const runs = (p: Probe) => p.gridModel ? `${ENGINE[p.engine]} on ${p.gridLabel ?? p.gridModel} (${KIND_WORD[p.gridKind ?? 'local']})` : `${ENGINE[p.engine]} ${p.model} ${p.effort}`+/** A name's words for matching: lowercase letters and digits, "4.1" read as "41". */+const words = (text: string) => text.toLowerCase().split(/[^a-z0-9.]+/).map(w => w.replace(/\./g, '')).filter(Boolean)+/** Whether [p] runs the model a person named: every word of theirs is in its model's name. */+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 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 {if (ms < 3_600_000) return `${Math.max(1, Math.round(ms / 60_000))}m`@@ -204,7 +226,7 @@ function machineText(load: MachineLoad): string[] {}/** The most telling parts come first and the least last, because the log's limit cuts the end. */const labelOf = (p: Probe & Sized, now: number) => cut([- p.kind === 'member' ? `Member ${cut(p.name ?? '', 40)}`.trim() : 'New agent', `${ENGINE[p.engine]} ${p.model} ${p.effort}`, `quality ${p.quality}, cost ${p.cost}`,+ p.kind === 'member' ? `Member ${cut(p.name ?? '', 40)}`.trim() : 'New agent', runs(p), `quality ${p.quality}, cost ${p.cost}`,p.text, cut(p.machineName, 40), p.activity, ...(p.kind === 'member' ? memberText(p, now) : p.load ? machineText(p.load) : []),...(p.earlier?.length ? [`earlier here: ${p.earlier.slice(0, 3).map(e => `${cut(e.group, 40)} ${e.outcome}`).join('; ')}`] : []), quotaText(p.quota, now),].join(' · '), 640)@@ -217,6 +239,11 @@ const round = (n: number) => Math.round(n * 100) / 100/** How the probe's account would carry a task of this size (phase 1 §2–3). */function sizeUp(p: Probe, policy: Policy, a: Assessment, now: number, open: Commitment[]): Sized {+ // A local model spends no subscription: it always fits, at its policy cost, and its node is its account.+ if (p.gridModel) {+ return { fit: { status: 'fits', coverage: null, effectiveCost: p.cost, expiring: 0, spend: { '5-hour': 0, weekly: 0 },+ account: `local:${p.gridName ?? ''}:${p.gridModel}` }, tight: null, text: 'fits: a local model on the Swarm\'s grid uses no subscription' }+ }const { minutes, spend: base } = SIZES[a.size], runMs = minutes * 60_000const account = p.quota.account ?? `${p.machineId}:${p.engine}`const spend = { '5-hour': base['5-hour'] * p.cost / 2, weekly: base.weekly * p.cost / 2 }@@ -248,6 +275,7 @@ 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).'/** 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@@ -277,14 +305,21 @@ function withEveryMachine<T extends { machineId: string }>(ranked: T[]): T[] {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 }> } {// A lifted row can equal another row on the same machine (Codex `default` lifted to high beside Codex high); one is kept.- const raised = probes.map(p => lifted(rules, p)), key = (p: Probe) => `${p.kind}\0${p.machineId}\0${p.engine}\0${p.model}\0${p.effort}`+ // A person asking for a local model considers local models alone, whatever their strength.+ if (a.local) probes = probes.filter(p => p.gridModel)+ // A person naming a model considers that model alone.+ const named = a.model+ if (named) probes = probes.filter(p => runsNamed(p, named))+ const raised = probes.map(p => lifted(rules, p)), key = (p: Probe) => `${p.kind}\0${p.machineId}\0${p.engine}\0${p.model}\0${p.effort}\0${p.gridModel ?? ''}`const ruled = raised.filter((p, i) => p === probes[i] || !raised.some((q, j) => j !== i && key(q) === key(p) && (q === probes[j] || j < i))).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 })if (!viable.length) return { error: 'NO_CANDIDATE', excluded }const floor = floorFor(policy, a)- const meeting = viable.filter(p => p.quality >= floor)+ const meeting = a.local || named ? viable : viable.filter(p => p.quality >= floor)const byFloor = meeting.length ? meeting : viable// Strength beats fit (owner, 2026-10-21): a hard task never goes to a weaker model because the strong ones are short of quota.const top = Math.max(...byFloor.map(p => p.quality))@@ -312,7 +347,8 @@ export function recordOf(choice: Choice, verdict: Verdict, a: Assessment, policyreturn {assessment: { difficulty: a.difficulty, risk: a.risk, why: a.why, ...(v1 ? {} : { size: a.size }) },candidates: choice.shown.map(s => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,- engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label, ...(v1 ? {} : { fit: s.fit }) })),+ engine: s.engine, model: s.model, effort: s.effort, quality: s.quality, cost: s.cost, title: s.title, label: s.label, ...(v1 ? {} : { fit: s.fit }),+ ...(s.gridModel && s.gridName ? { gridModel: s.gridModel, gridName: s.gridName } : {}) })),excluded: choice.excluded.slice(0, 200).map(e => ({ title: e.title, reason: cut(e.reason, 500) })),floor: choice.floor, notes: policy.notes.length > 0,pick: verdict.pick.id, via: verdict.via, p: verdict.p, belowFloor: choice.belowFloor, why: cut(verdict.why, 300),diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex 36c7a28bb..1b63c8a4d 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -3,9 +3,10 @@ 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 { routeTask } from './routeCommand.js'+import { 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'const policy = { version: 1, floor: { low: 1, medium: 2, high: 3 }, quotaReserve: 10, notes: '', models: [{ engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 3, enabled: true },@@ -784,3 +785,73 @@ describe('routing contributed capacity', () => {expect(failed.answer.excluded).toEqual(expect.arrayContaining([expect.objectContaining({ reason: expect.stringMatching(/Required tool not verified: git.*interactive shell timed out/) })]))})})++describe('local models on the Swarm\'s grid', () => {+ const GRID = 'swarm-0123456789ab', NOW = 1_000_000_000+ const served = (models: Array<Record<string, unknown>>, receivedAt: unknown = NOW - 1_000) => ({ machineId: 'm1', observation: { receivedAt, localModels: models } })+ const state = (patch: Record<string, unknown> = {}) => ({ localModels: { grid: GRID, enabled: true }, machines: [served([{ grid: GRID, model: 'qwen3', name: 'Qwen 3' }])], agents: [], starts: [], ...patch })+ const base = (patch: Partial<Probe> = {}): Probe => ({ kind: 'new', machineId: 'm1', machineName: 'remote-1', engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2, cost: 2,+ quota: { known: true, leftPercent: 50, resetsAt: null }, activity: 'new agent', known: true, refusals: [], ...patch })+ const assessment = { difficulty: 'low', risk: 'low', size: 'medium', why: 'x', needs: { tools: [], devices: [] } } as Assessment+ const routing = policy as unknown as Policy+ const offered = (s: Record<string, unknown>, opts: { probes?: Probe[]; a?: Assessment; review?: boolean; policy?: Policy } = {}) =>+ localProbes(s, opts.policy ?? routing, opts.probes ?? [base()], opts.a ?? assessment, opts.review ?? false, NOW)++ it('offers one new agent per machine and engine on each served model, free and at the policy\'s local quality', () => {+ const probes = [base(), base({ model: 'opus', effort: 'high' }), base({ engine: 'codex', refusals: ['Its subscription is used up.', 'Too little memory.'] }),+ base({ kind: 'member', agentId: 'a1' }), base({ gridModel: 'other' })]+ const rows = offered(state(), { probes, policy: { ...routing, localModels: { quality: 2, enabled: true } } })+ expect(rows.map(r => [r.engine, r.model, r.effort, r.quality, r.cost, r.gridModel, r.gridName, r.gridLabel, r.refusals])).toEqual([+ ['claude', 'default', 'default', 2, 1, 'qwen3', GRID, 'Qwen 3', []],+ ['codex', 'default', 'default', 2, 1, 'qwen3', GRID, 'Qwen 3', ['Too little memory.']],+ ])+ expect(rows[0]!.quota).toMatchObject({ known: false })+ // A backend before the add-on sends no policy for it: quality 1. A model with no name is called by its model.+ const unnamed = state({ machines: [served([{ grid: GRID, model: 'qwen3' }])] })+ expect(offered(unnamed)[0]).toMatchObject({ quality: 1, gridLabel: 'qwen3' })+ })+ it('offers nothing with the add-on off, for a review, or when the owner turned local models off and nobody asked for one', () => {+ expect(offered(state({ localModels: undefined }))).toEqual([])+ expect(offered(state({ localModels: { grid: GRID, enabled: false } }))).toEqual([])+ expect(offered(state({ localModels: { enabled: true } }))).toEqual([])+ expect(offered(state(), { review: true })).toEqual([])+ const off = { ...routing, localModels: { quality: 1, enabled: false } }+ expect(offered(state(), { policy: off })).toEqual([])+ expect(offered(state(), { policy: off, a: { ...assessment, local: true } })).toHaveLength(1)+ })+ it('reads only fresh readings, and of a model on another grid only on the machine that reaches it', () => {+ expect(offered(state({ machines: [served([{ grid: GRID, model: 'qwen3' }], NOW - 60_000)] }))).toEqual([])+ expect(offered(state({ machines: [served([{ grid: GRID, model: 'qwen3' }], 'soon')] }))).toEqual([])+ expect(offered(state({ machines: [served([{ grid: GRID, model: 7 }, { grid: 3, model: 'x' }])] }))).toEqual([])+ // Shared with m1's owner on their team grid: offered on m1 alone, while one on the Swarm's grid is offered on both.+ const reach = state({ machines: [served([{ grid: 'team-grid', model: 'team-model', kind: 'shared' }]), { machineId: 'm2', observation: { receivedAt: NOW - 1_000, localModels: [{ grid: GRID, model: 'qwen3' }] } }] })+ const rows = offered(reach, { probes: [base(), base({ machineId: 'm2', machineName: 'mac' })] })+ expect(rows.map(r => [r.machineId, r.gridName, r.gridModel, r.gridKind])).toEqual([+ ['m1', 'team-grid', 'team-model', 'shared'], ['m1', GRID, 'qwen3', 'local'], ['m2', GRID, 'qwen3', 'local'],+ ])+ // An API a member shares, by its kind; another grid's model without one is shared with that machine's owner.+ const kinds = state({ machines: [served([{ grid: GRID, model: 'ds', kind: 'api' }, { grid: 'team-grid', model: 'tm' }])] })+ expect(offered(kinds).map(r => [r.gridModel, r.gridKind])).toEqual([['ds', 'api'], ['tm', 'shared']])+ // A Builder started on the shared model takes it, by its own grid.+ expect(offered({ ...reach, starts: [{ request: { gridModel: 'team-model', gridName: 'team-grid' } }] }, { probes: [base()] }).map(r => r.gridModel)).toEqual(['qwen3'])+ })+ it('keeps a model for the Builder started on it until that Builder leaves the Swarm', () => {+ const start = (patch: Record<string, unknown>) => ({ request: { gridModel: 'qwen3' }, ...patch })+ expect(offered(state({ starts: [start({})] }))).toEqual([])+ expect(offered(state({ starts: [start({ harnessId: 'h9' })], agents: [{ harnessId: 'h9' }] }))).toEqual([])+ expect(offered(state({ starts: [start({ harnessId: 'h9' })] }))).toHaveLength(1)+ expect(offered(state({ starts: [start({ error: 'NO_CAPACITY' })] }))).toHaveLength(1)+ expect(offered(state({ starts: [{ request: { model: 'opus' } }, {}] }))).toHaveLength(1)+ })+ 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' }] } }] })+ const s = scoped({ tab: t })+ const result = await routeTask({ ...input, assessment: { ...input.assessment, difficulty: 'low', local: true } }, s, where as never, opener(), () => 'op')+ expect(result).toMatchObject({ ok: true, pick: { kind: 'new', gridModel: 'qwen3', gridName: GRID } })+ const hint = JSON.parse(/start OPERATION_ID (\{.*\}), then/.exec(result.next as string)![1]!)+ expect(hint).toMatchObject({ engine: 'claude', gridModel: 'qwen3', gridName: GRID })+ expect(hint).not.toHaveProperty('model')+ expect(recorded(s).command.decision.candidates[0]).toMatchObject({ gridModel: 'qwen3', gridName: GRID })+ })+})diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex 26e1513f9..97c65a488 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -180,6 +180,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;const probes = probed.flat().map(p => p.kind === 'member' ? { ...p, repo: repoMatch(folder, p.frame ?? null, p.machineId === where.machineId),refusals: [...p.refusals, ...limited(p.agentId)],earlier: ended.filter(e => e.agentId === p.agentId).reverse().slice(0, 3).map(e => ({ group: e.group, outcome: e.outcome })) } : p)+ probes.push(...localProbes(state, policy, probes, assessment, review))// 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)@@ -196,7 +197,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;const routeDecisionId = recorded.ok === true ? object(object(recorded.value).result).routeDecisionId : undefinedconst decision = typeof routeDecisionId === 'string' ? `,"routeDecisionId":"${routeDecisionId}"` : ''const publicOf = (s: typeof verdict.pick) => ({ id: s.id, kind: s.kind, ...(s.agentId ? { agentId: s.agentId } : {}), machineId: s.machineId,- engine: s.engine, model: s.model, effort: s.effort, title: s.title })+ engine: s.engine, model: s.model, effort: s.effort, title: s.title, ...(s.gridModel ? { gridModel: s.gridModel, gridName: s.gridName } : {}) })return {ok: true, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : { unrecorded: true }),pick: publicOf(verdict.pick), via: verdict.via, p: verdict.p, belowFloor: choice.belowFloor, why: verdict.why,@@ -207,8 +208,10 @@ export async function routeTask(input: { tabId: string; conversationId: string;next: verdict.pick.kind === 'member'? `Assign with: command OPERATION_ID {"type":"work.assign","conversationId":"${input.conversationId}","agentId":"${verdict.pick.agentId}"${decision}}`: `Start with: start OPERATION_ID ${JSON.stringify({ conversationId: input.conversationId, name: review ? 'Reviewer' : 'Builder', ...(review ? { role: 'reviewer' } : {}), cwd: text(machines.get(verdict.pick.machineId)?.pool?.cwd) ?? assessment.needs.cwd ?? '/absolute/repo/on/that/machine',- worktree: true, requirements: startRequirements(assessment.needs), machineId: verdict.pick.machineId, engine: verdict.pick.engine, model: verdict.pick.model,- effort: verdict.pick.effort, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : {}) })}, then assign the started agent${decision ? ' with the same routeDecisionId' : ''}. It starts from the repository's default branch, fetched first; add "branchRef":"refs/remotes/origin/BRANCH" to start from another branch.`,+ worktree: true, requirements: startRequirements(assessment.needs), machineId: verdict.pick.machineId, engine: verdict.pick.engine,+ // A local model is named by the grid alone: no subscription model or effort goes with it.+ ...(verdict.pick.gridModel ? { gridModel: verdict.pick.gridModel, gridName: verdict.pick.gridName } : { model: verdict.pick.model, effort: verdict.pick.effort }),+ ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : {}) })}, then assign the started agent${decision ? ' with the same routeDecisionId' : ''}. It starts from the repository's default branch, fetched first; add "branchRef":"refs/remotes/origin/BRANCH" to start from another branch.`,}}@@ -218,6 +221,52 @@ function alternativesTo<T extends { id: string; machineId: string }>(pick: T, shreturn shown.filter(s => s.id !== pick.id).filter((s, i) => { const best = !seen.has(s.machineId); seen.add(s.machineId); return i < 2 || best })}+/** A reading this old says nothing is served (backend `MACHINE_FRESH_MS`). */+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 []+ // 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 }>()+ 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 l of list(observed.localModels)) {+ if (typeof l.grid !== 'string' || typeof l.model !== 'string') continue+ const key = `${l.grid}\0${l.model}`, anywhere = l.grid === swarm+ const 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>() }+ 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)))+ 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 (!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>()+ for (const p of probes) if (p.kind === 'new' && !p.gridModel && !bases.has(`${p.machineId}\0${p.engine}`)) bases.set(`${p.machineId}\0${p.engine}`, p)+ const quality = policy.localModels?.quality ?? 1+ return [...bases.values()].flatMap(base => [...served.values()].filter(m => !m.machines || m.machines.has(base.machineId))+ .map((m): Probe => ({ ...base, model: 'default', effort: 'default', quality, cost: 1, quota: UNKNOWN_QUOTA, known: true,+ refusals: base.refusals.filter(r => !SUBSCRIPTION.test(r)), gridModel: m.model, gridName: m.grid, gridLabel: m.label, gridKind: m.kind })))+}+async function probeMachine(machineId: string, { name: machineName, status, account, pool }: { name: string; status: string; account: boolean; pool?: Json },members: Json[], allModels: Policy['models'], policy: Policy, a: Assessment, where: Where, open: typeof openDaemon): Promise<Probe[]> {const listedEngines = Array.isArray(pool?.engines) ? pool.engines.filter((engine): engine is string => typeof engine === 'string') : []diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 245b626fc..7c5f9f63f 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -20,7 +20,7 @@ const HELP = {start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on. Set role "reviewer" to start a Reviewer; leave role out for a Builder. The role is kept for the session. On Custom skills, add "roleId" to the start request to start the agent in that role of its kind (a builder or reviewer role from status); without it the agent takes the first role of its kind. A Reviewer runs on claude or codex and is assigned only review groups (conversation.create with reviewOf naming the group it reviews); a review group is assigned only to a Reviewer. Add the Reviewer to the reviewed group with conversation.agent so it is told when that work is ready for review and can pass its independent check. Start one with a routeDecisionId like any agent.',release: 'When a Builder finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',resume: 'resume START_ID: finish a pending start without creating another agent.',- route: 'route GROUP JSON: before you start an agent or assign work to another agent, choose who does it. Work you do yourself is not routed. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"optional word such as ui or docs","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. Candidates that break the owner\'s hard rules are left out; soft rules (a preferred engine for the kind, idle agents first) rank the rest. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason. An agent\'s start or work.assign without a routeDecisionId is refused, so route first; a person can still start and assign by hand.',+ route: 'route GROUP JSON: before you start an agent or assign work to another agent, choose who does it. Work you do yourself is not routed. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"optional word such as ui or docs","local":"optional true, only when a person asked for a local model","model":"optional: the model a person named, in their words; only it is offered","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. Candidates that break the owner\'s hard rules are left out; soft rules (a preferred engine for the kind, idle agents first) rank the rest. A pick on a model served on the Swarm\'s grid starts with gridModel and gridName in place of model and effort. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason. An agent\'s start or work.assign without a routeDecisionId is refused, so route first; a person can still start and assign by hand.',screen: 'screen AGENT [--scrollback N]: read a worker\'s terminal as plain text, with up to 200 lines of scrollback. Only its project\'s Lead may. Use it when a worker seems stuck.',type: 'type AGENT [TEXT] [--key K]...: type text, then keys (Enter, Esc, Tab, Up, Down, Left, Right, Ctrl-C, 0-9), into a worker\'s terminal. Answer prompts within its task; ask the owner before approving anything risky.',capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',diff --git a/cli/src/superTabs/swarmGrids.spec.ts b/cli/src/superTabs/swarmGrids.spec.tsnew file mode 100644index 000000000..777314909--- /dev/null+++ b/cli/src/superTabs/swarmGrids.spec.ts@@ -0,0 +1,109 @@+import { describe, expect, it, vi } from 'vitest'+import { fakeCore } from '../testing/fakeCore.js'+import { GRID_POLL_MS, SwarmGrids } from './swarmGrids.js'+import { SuperTabHostError } from './host.js'++const GRID = 'swarm-0123456789ab'+type Row = Record<string, unknown>++function fixture(rows: Row[], answer: (payload: Row) => Promise<unknown> = async () => ({ ready: true, added: [], removed: [] })) {+ let now = 1_000+ const core = fakeCore({ dataDir: '/isolated-grid-fixture' })+ const backend = vi.fn(async (_core: unknown, method: string, _path: string, _body?: unknown): Promise<unknown> => method === 'GET' ? rows : { revision: 1 })+ const request = vi.fn(async (_type: string, payload: Row, _timeout?: number) => answer(payload))+ const close = vi.fn(), open = vi.fn(async () => ({ request, close }))+ let id = 0+ const grids = new SwarmGrids(core, 'host', { backend, open, now: () => now, newId: () => `id${++id}` } as never)+ const posts = () => backend.mock.calls.filter(c => c[1] === 'POST').map(c => [c[2], c[3]])+ return { grids, backend, request, open, close, posts, later: () => { now += GRID_POLL_MS } }+}+const row = (patch: Row = {}): Row => ({ tabId: 'tab1', grid: GRID, enabled: true, ready: false, members: ['[email protected]', '[email protected]', 7], ...patch })++describe('the owner\'s Swarm grids', () => {+ it('brings a turned-on Swarm\'s grid to its people and tells the Swarm, then leaves it alone until something changes', async () => {+ const f = fixture([row()])+ await f.grids.tick()+ expect(f.backend).toHaveBeenCalledWith(expect.anything(), 'GET', '/api/super-tabs/grids')+ expect(f.request).toHaveBeenCalledWith('grid_swarm_sync', { grid: GRID, members: ['[email protected]', '[email protected]'] }, 180_000)+ expect(f.posts()).toEqual([['/api/super-tabs/tab1/commands', { operationId: 'grid-id1', command: { type: 'localModels.status', grid: GRID, ready: true } }]])+ expect(f.close).toHaveBeenCalledOnce()+ // Within the minute nothing is read; after it, a ready grid with the same people is not asked again.+ await f.grids.tick()+ expect(f.backend).toHaveBeenCalledTimes(2)+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? [row({ ready: true })] : {}) as never)+ f.later(); await f.grids.tick()+ expect(f.request).toHaveBeenCalledOnce()+ expect(f.open).toHaveBeenCalledOnce()+ // A new person is.+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? [row({ ready: true, members: ['[email protected]'] })] : {}) as never)+ f.later(); await f.grids.tick()+ expect(f.request).toHaveBeenLastCalledWith('grid_swarm_sync', { grid: GRID, members: ['[email protected]'] }, 180_000)+ })+ it('reports a failure in grid\'s words, and tries again a minute later', async () => {+ const f = fixture([row({ members: undefined })], async () => ({ ready: false, error: 'x'.repeat(600) }))+ await f.grids.tick()+ expect(f.request).toHaveBeenCalledWith('grid_swarm_sync', { grid: GRID, members: [] }, 180_000)+ expect(f.posts()[0]![1]).toMatchObject({ command: { ready: false, error: 'x'.repeat(500) } })+ f.request.mockRejectedValueOnce(new Error('daemon gone'))+ f.later(); await f.grids.tick()+ expect(f.posts()[1]![1]).toMatchObject({ command: { ready: false, error: 'daemon gone' } })+ f.request.mockRejectedValueOnce('odd')+ f.later(); await f.grids.tick()+ expect(f.posts()[2]![1]).toMatchObject({ command: { ready: false, error: 'The grid could not be reached.' } })+ f.request.mockResolvedValueOnce(null)+ f.later(); await f.grids.tick()+ expect(f.posts()[3]![1]).toMatchObject({ command: { ready: false } })+ expect(f.posts()[3]![1]).not.toHaveProperty('command.error')+ })+ it('opens nothing when no Swarm has the add-on on, and forgets a Swarm that turned it off', async () => {+ const f = fixture([row({ enabled: false }), row({ tabId: '../x' }), row({ grid: 7 }), 'junk' as unknown as Row])+ await f.grids.tick()+ expect(f.open).not.toHaveBeenCalled()+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? [row({ ready: true })] : {}) as never)+ f.later(); await f.grids.tick()+ expect(f.request).toHaveBeenCalledOnce()+ // Off, then on again: asked afresh, though nothing else changed.+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? { not: 'a list' } : {}) as never)+ f.later(); await f.grids.tick()+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? [row({ ready: true })] : {}) as never)+ f.later(); await f.grids.tick()+ expect(f.request).toHaveBeenCalledTimes(2)+ })+ it('does not ask grid again about a refusal only the person can change, until the Swarm\'s people change', async () => {+ const f = fixture([row()], async () => ({ ready: false, error: 'Free plan allows one network', final: true }))+ await f.grids.tick()+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? [row({ ready: false })] : {}) as never)+ f.later(); await f.grids.tick()+ expect(f.request).toHaveBeenCalledOnce()+ // Off and on again within the minute: the Swarm no longer shows the refusal, so grid is asked again.+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? [row({ ready: undefined })] : {}) as never)+ f.later(); await f.grids.tick()+ expect(f.request).toHaveBeenCalledTimes(2)+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? [row({ ready: false })] : {}) as never)+ f.later(); await f.grids.tick()+ expect(f.request).toHaveBeenCalledTimes(2)+ f.backend.mockImplementation((async (_c: unknown, method: string) => method === 'GET' ? [row({ ready: false, members: ['[email protected]'] })] : {}) as never)+ f.later(); await f.grids.tick()+ expect(f.request).toHaveBeenCalledTimes(3)+ })+ it('reads a backend before the add-on as having no grids, and lets any other failure through', async () => {+ const f = fixture([])+ f.backend.mockRejectedValueOnce(new SuperTabHostError('NOT_FOUND', 'This Super Tab is unavailable.', 404))+ await f.grids.tick()+ expect(f.open).not.toHaveBeenCalled()+ f.backend.mockRejectedValueOnce(new SuperTabHostError('BACKEND_UNAVAILABLE', 'down'))+ f.later()+ await expect(f.grids.tick()).rejects.toThrow('down')+ })+ it('runs one pass at a time', async () => {+ let release!: () => void+ const f = fixture([row()], () => new Promise(done => { release = () => done({ ready: true }) }))+ const first = f.grids.tick()+ await vi.waitFor(() => expect(f.request).toHaveBeenCalledOnce())+ f.later()+ const second = f.grids.tick()+ expect(second).toBe(first)+ release(); await first+ expect(f.request).toHaveBeenCalledOnce()+ })+})diff --git a/cli/src/superTabs/swarmGrids.ts b/cli/src/superTabs/swarmGrids.tsnew file mode 100644index 000000000..08792779f--- /dev/null+++ b/cli/src/superTabs/swarmGrids.ts@@ -0,0 +1,65 @@+/**+ * The owner's computer's half of the Local models add-on (docs/plans/2026-10-23-swarm-local-models.md): for each of the+ * owner's Swarms with it on, create the Swarm's grid and keep its members in step with the Swarm's people, then tell+ * the Swarm how that went (`localModels.status`).+ *+ * Grid is asked only when there is something to do: a Swarm turned on, its people changed, or the last attempt failed+ * (then at most once a minute, unless grid's answer was one only the person can change, such as its plan limit). With the add-on off everywhere, a pass is one backend read and nothing else.+ */+import { randomUUID } from 'node:crypto'+import type { CoreApi } from '../core/api.js'+import { openDaemon } from '../agentClient/daemon.js'+import { backend, identifier, object, SuperTabHostError } from './host.js'++/** How often the owner's Swarms are read. */+export const GRID_POLL_MS = 60_000++interface Deps { backend: typeof backend; open: typeof openDaemon; now: () => number; newId: () => string }++export class SwarmGrids {+ private next = 0+ private running: Promise<void> | null = null+ /** What each Swarm's grid was last brought to: its members, and whether that worked. */+ private readonly synced = new Map<string, { signature: string; ready: boolean; final: boolean }>()+ constructor(private readonly core: CoreApi, private readonly machineId: string,+ private readonly deps: Deps = { backend, open: openDaemon, now: Date.now, newId: randomUUID }) {}++ tick(): Promise<void> {+ if (this.deps.now() < this.next) return Promise.resolve()+ this.next = this.deps.now() + GRID_POLL_MS+ return this.running ??= this.pass().finally(() => { this.running = null })+ }++ private async pass(): Promise<void> {+ // A backend before the add-on reads `grids` as a Swarm id and answers 404: it has no grids to keep.+ const listed = await this.deps.backend(this.core, 'GET', '/api/super-tabs/grids').catch((error: unknown) => {+ if (error instanceof SuperTabHostError && error.status === 404) return []+ throw error+ })+ const rows = (Array.isArray(listed) ? listed : []).map(object)+ .filter(row => row.enabled === true && identifier(row.tabId) && typeof row.grid === 'string')+ for (const tab of [...this.synced.keys()]) if (!rows.some(row => row.tabId === tab)) this.synced.delete(tab)+ if (!rows.length) return+ let local: Awaited<ReturnType<typeof openDaemon>> | null = null+ try {+ for (const row of rows) {+ const members = (Array.isArray(row.members) ? row.members : []).filter((m): m is string => typeof m === 'string').sort()+ const signature = JSON.stringify([row.grid, members])+ const last = this.synced.get(String(row.tabId))+ // A final refusal is left alone while the Swarm still shows it; turning the add-on off and on clears what the+ // Swarm shows, even between two passes, and that asks again.+ if (last?.signature === signature && (last.ready ? row.ready === true : last.final && row.ready === false)) continue+ local ??= await this.deps.open({ dataDir: this.core.dataDir, port: this.core.daemon.port, machineId: this.machineId })+ const result = object(await local.request('grid_swarm_sync', { grid: row.grid, members }, 180_000)+ .catch((error: unknown) => ({ ready: false, error: error instanceof Error ? error.message : 'The grid could not be reached.' })))+ const ready = result.ready === true+ const error = typeof result.error === 'string' ? result.error.slice(0, 500) : undefined+ // A refusal only the person can change (grid's plan limit) is not asked again every minute: only once the+ // Swarm's people change, or the owner turns the add-on off and on.+ this.synced.set(String(row.tabId), { signature, ready, final: result.final === true })+ await this.deps.backend(this.core, 'POST', `/api/super-tabs/${row.tabId}/commands`, { operationId: `grid-${this.deps.newId()}`,+ command: { type: 'localModels.status', grid: row.grid, ready, ...(error ? { error } : {}) } })+ }+ } finally { local?.close() }+ }+}diff --git a/desktop/lib/models/local_model.dart b/desktop/lib/models/local_model.dartindex ec8c023e7..4ebd90535 100644--- a/desktop/lib/models/local_model.dart+++ b/desktop/lib/models/local_model.dart@@ -35,6 +35,7 @@ class LocalModel {this.paramsB,this.app,this.servedAs = const [],+ this.servedOnGrids = const [],});final String id, name, state;@@ -43,6 +44,13 @@ class LocalModel {/// (`Qwen3.8-27B`), so its grid listing is matched to it by these.final List<String> servedAs;+ /// Every grid this machine serves it on now (`servedOn`'s names; empty from an older daemon): the account's own,+ /// and a Swarm's that it runs for (docs/plans/2026-10-23-swarm-local-models.md).+ final List<String> servedOnGrids;++ /// Whether it runs for the Swarm whose grid is [grid].+ bool servedOn(String grid) => servedOnGrids.contains(grid);+/// Whether the grid's [modelId] is this model: its id, its name, or a name it is served under.bool answersTo(String modelId) {final id = modelId.toLowerCase();@@ -124,6 +132,13 @@ class LocalModel {final List<dynamic> names => names.whereType<String>().toList(),_ => const [],},+ servedOnGrids: switch (data['servedOn']) {+ final List<dynamic> grids => [+ for (final grid in grids)+ if (grid is Map && grid['grid'] is String) grid['grid'] as String,+ ],+ _ => const [],+ },);}diff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dartindex 12f414568..00f3dc723 100644--- a/desktop/lib/models/model_manager_controller.dart+++ b/desktop/lib/models/model_manager_controller.dart@@ -719,7 +719,8 @@ class ModelManagerController extends ChangeNotifier {}}- Future<void> control(LocalModel model, String action) async {+ /// [grid]: start or stop it on that Swarm's grid instead of the account's own (docs/plans/2026-10-23-swarm-local-models.md).+ Future<void> control(LocalModel model, String action, {String? grid}) async {final owner = machine;if (owner == null ||owner.connectionStatus != ConnectionStatus.connected ||@@ -740,7 +741,8 @@ class ModelManagerController extends ChangeNotifier {if (!supportsDownload || current.downloaded || !current.canStart) return;} else if (startModel) {if (!current.canStart) return;- } else if (action != 'stop' || !current.canStop) {+ } else if (action != 'stop' ||+ !(grid == null ? current.canStop : current.servedOn(grid))) {return;}pendingId = model.id;@@ -758,6 +760,7 @@ class ModelManagerController extends ChangeNotifier {owner.machine.machineId,model.id,start: startModel,+ grid: grid,);if (!_current(owner)) return;error = answer['error'] as String?;diff --git a/desktop/lib/models/swarm_models_target.dart b/desktop/lib/models/swarm_models_target.dartnew file mode 100644index 000000000..50fca7089--- /dev/null+++ b/desktop/lib/models/swarm_models_target.dart@@ -0,0 +1,80 @@+import 'package:flutter/foundation.dart';++import '../state/app_state.dart';++/// The Models picker opened for a Swarm's Local models (docs/plans/2026-10-23-swarm-local-models.md): the same+/// sections as ⌘I's Models, less Subscriptions, whose actions put a model on the Swarm's grid instead of starting a+/// harness on it. A model of this computer's runs for the Swarm; a saved API is shared with it, on this computer's key;+/// a model shared with the person is usable by agents on their machines and needs nothing done.+class SwarmModelsTarget extends ChangeNotifier {+ SwarmModelsTarget({+ required this.app,+ required this.grid,+ required this.machineId,+ });++ final AppNotifier app;++ /// The Swarm's grid.+ final String grid;++ /// This computer: the APIs are its own saved ones, and only it shares them.+ final String machineId;++ /// The APIs this computer shares with the Swarm, by `connectionId` and model.+ Set<String> shares = {};+ String? error;+ bool _disposed = false;++ static String shareKey(String connectionId, String model) =>+ '$connectionId\u0000$model';++ bool shared(String connectionId, String model) =>+ shares.contains(shareKey(connectionId, model));++ Future<void> refresh() async {+ try {+ final answer = await app.swarmApiShares(machineId, grid);+ shares = {+ for (final row+ in answer['shares'] is List ? answer['shares'] as List : const [])+ if (row is Map &&+ row['connectionId'] is String &&+ row['model'] is String)+ shareKey(row['connectionId'] as String, row['model'] as String),+ };+ } catch (_) {+ // Unknown, not "none": keep what was last read.+ }+ if (!_disposed) notifyListeners();+ }++ /// Shares, or stops sharing, [model] of the saved API [connectionId]. Returns why it could not, or null.+ Future<String?> share(+ String connectionId,+ String model, {+ required bool start,+ }) async {+ error = null;+ try {+ final answer = await app.swarmApiShare(+ machineId,+ grid: grid,+ connectionId: connectionId,+ model: model,+ start: start,+ );+ error = answer['error'] as String?;+ } catch (_) {+ error = 'This computer could not be reached. Try again.';+ }+ await refresh();+ return error;+ }++ @override+ void dispose() {+ _disposed = true;+ super.dispose();+ }+}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex ff73acc70..787d170bb 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -11281,16 +11281,46 @@ class AppNotifier extends ChangeNotifier {return connection.request('connectors', payload: payload, timeout: timeout);}+ /// Starts or stops a local model; with [grid], on that Swarm's grid instead of the account's own+ /// (docs/plans/2026-10-23-swarm-local-models.md).Future<Map<String, dynamic>> controlLocalModel(String machineId,String modelId, {required bool start,+ String? grid,}) => _conn(machineId).request(start ? 'grid_fleet_model_start' : 'grid_fleet_model_stop',- payload: {'modelId': modelId},+ payload: {'modelId': modelId, 'grid': ?grid},timeout: const Duration(seconds: 12),);+ /// The saved APIs [machineId] shares with the Swarm whose grid is [grid] (CLI `lib/swarmApiShares.ts`).+ Future<Map<String, dynamic>> swarmApiShares(String machineId, String grid) =>+ _conn(machineId).request(+ 'grid_swarm_api_shares',+ payload: {'grid': grid},+ timeout: const Duration(seconds: 10),+ );++ /// Shares [model] of the saved API [connectionId] with the Swarm whose grid is [grid], or stops: every Builder in+ /// the Swarm may then run on it, on this computer's key and credits.+ Future<Map<String, dynamic>> swarmApiShare(+ String machineId, {+ required String grid,+ required String connectionId,+ required String model,+ required bool start,+ }) => _conn(machineId).request(+ 'grid_swarm_api_share',+ payload: {+ 'grid': grid,+ 'connectionId': connectionId,+ 'model': model,+ 'action': start ? 'start' : 'stop',+ },+ timeout: const Duration(minutes: 2),+ );+Future<Map<String, dynamic>> downloadLocalModel(String machineId,String modelId,diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex 40e8b3af4..2f7dec2eb 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/swarm_models_target.dart';import '../usage/models_menu_controller.dart' show subscriptionSearchId;import '../core/dsh_catalog.dart';import '../store/experimental_harnesses.dart';@@ -99,6 +100,7 @@ class SwarmSearchController extends ChangeNotifier {this.resultsFromBottom = false,this.noteFor,this.additionalDestinations = const [],+ this.swarmModels,this.harnessContext,this._placement,this._split,@@ -136,6 +138,10 @@ class SwarmSearchController extends ChangeNotifier {final HarnessPickerContext? harnessContext;final SwarmProjectStore? projects;final ModelSearchCatalog? models;++ /// Set when these Models are a Swarm's Local models ([SwarmModelsTarget]): no Subscriptions, and a model's action+ /// puts it on the Swarm's grid ([swarmModelAction]) rather than starting a harness on it.+ final SwarmModelsTarget? swarmModels;bool modelDownloadsVisible = false;bool isModelDownloadsRow(SwarmDestination? row) =>isModelMode && row?.id == 'model:downloads';@@ -306,6 +312,21 @@ class SwarmSearchController extends ChangeNotifier {final catalog = models;final entry = catalog?.entries[row.modelId];if (entry == null || catalog == null) return null;+ // A Swarm's Local models say what each row is to the Swarm.+ if (swarmModels case final swarm?) {+ final local = entry.local;+ final owner = entry.controller ?? catalog.manager;+ if (local != null &&+ (owner.operationFor(local)?.active == true ||+ owner.pendingId == local.id)) {+ return catalog.localStatusWord(local, controller: owner);+ }+ if (local?.servedOn(swarm.grid) == true) return 'In Swarm';+ if (entry.apiModel case final model?) {+ return swarm.shared(entry.api!.id, model.id) ? 'Shared' : null;+ }+ if (local == null && entry.api == null) return 'Usable';+ }if (modelRowInUse(row)) return inUseWord;// An API's model says what Enter does on it — Use, when this pane can run on it, else nothing.// Its entry's status is only the API's name, which the row it sits under already shows.@@ -441,6 +462,63 @@ class SwarmSearchController extends ChangeNotifier {(owner.targetMachineId == null || owner.machine?.isOffline == false);}+ /// What a model row does in a Swarm's Local models ([swarmModels]): a model of this person's machines runs for the+ /// Swarm or stops (Get first, when it is not downloaded); an API's model is shared with the Swarm or no longer. Null+ /// outside a Swarm, and for a row with nothing to do: an API's own row (it opens its models), a model shared with the+ /// person (agents on their machines use it as it is), a download under way (the preview's Cancel).+ ({String label, String command, Future<String?> Function()? run})?+ swarmModelAction(SwarmDestination? row) {+ final swarm = swarmModels;+ final entry = models?.entries[row?.modelId];+ if (swarm == null || entry == null) return null;+ if (entry.local case final local?) {+ final owner = entry.controller ?? models!.manager;+ if (owner.downloading(local)) return null;+ final ready =+ !owner.busy &&+ owner.inventoryAvailable &&+ owner.machine?.connectionStatus == ConnectionStatus.connected &&+ owner.machine?.needsLink == false &&+ (owner.targetMachineId == null || owner.machine?.isOffline == false);+ Future<String?> Function() act(String action, {String? grid}) =>+ () async {+ await owner.control(local, action, grid: grid);+ return owner.error;+ };+ if (local.servedOn(swarm.grid)) {+ return (+ label: 'Stop for Swarm',+ command: 'picker.model_stop',+ run: ready ? act('stop', grid: swarm.grid) : null,+ );+ }+ if (!local.downloaded && !local.canStop) {+ return (+ label: 'Get',+ command: 'picker.model_download',+ run: ready && local.canStart && owner.supportsDownload+ ? act('download')+ : null,+ );+ }+ return (+ label: 'Run for Swarm',+ command: 'picker.model_start',+ run: ready && local.canStart ? act('start', grid: swarm.grid) : null,+ );+ }+ if (entry.apiModel case final model?) {+ final api = entry.api!;+ final on = swarm.shared(api.id, model.id);+ return (+ label: on ? 'Stop sharing' : 'Share with Swarm',+ command: 'picker.accept',+ run: () => swarm.share(api.id, model.id, start: !on),+ );+ }+ return null;+ }+Future<String?> getModel(SwarmDestination row) async {if (!canGetModel(row)) return null;final entry = models!.entries[row.modelId]!;@@ -2141,6 +2219,17 @@ class SwarmSearchController extends ChangeNotifier {: [...found, ?create];}if (isModelMode) {+ // A subscription is one person's own: nothing in it can be given to a Swarm. And what the Swarm's own grid serves+ // is the Swarm's already, not shared with the person: its models are listed where they come from.+ if (swarmModels case final swarm?) {+ rows = rows.where((row) {+ if (modelSection(row) == ModelSearchSection.subscriptions) {+ return false;+ }+ final entry = models?.entries[row.modelId];+ return entry?.local != null || entry?.gridModel?.grid != swarm.grid;+ }).toList();+ }if (matchQuery.trim().isEmpty && _downloadCount > shownDownloads) {rows = [...rows, _downloadsRow];}@@ -2389,6 +2478,12 @@ class SwarmSearchController extends ChangeNotifier {notifyListeners();return null;}+ if (swarmModels != null && destination.isModel) {+ // Return does what the preview's button does, for the Swarm.+ final run = swarmModelAction(destination)?.run;+ if (run != null) unawaited(run());+ return null;+ }if (destination.isModel &&!canSelectModel(destination) &&!canGetModel(destination)) {diff --git a/desktop/lib/super_tabs/local_models.dart b/desktop/lib/super_tabs/local_models.dartnew file mode 100644index 000000000..10b7a3a59--- /dev/null+++ b/desktop/lib/super_tabs/local_models.dart@@ -0,0 +1,371 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../models/model_search_catalog.dart';+import '../models/swarm_models_target.dart';+import '../shared/theme/app_icons.dart';+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../state/swarm_navigation.dart';+import '../state/swarm_search.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/swarm_resource_preview.dart';+import '../widgets/swarm_switcher.dart';+import 'controller.dart';+import 'dialog_scope.dart';+import 'identity.dart';+import 'model.dart';++/// The Swarm's Local models (docs/plans/2026-10-23-swarm-local-models.md): the owner's switch for the add-on, off until+/// they turn it on since it is the only thing here that asks grid for anything, and, once it is ready, the Models picker+/// of ⌘I made for the Swarm ([SwarmModelsTarget]): your models to run for it, models to get, your APIs to share with it,+/// and the models shared with you that agents on your machines can use.+Future<void> showSwarmLocalModels(+ BuildContext context,+ SuperTabController c, {+ AppNotifier? app,+ DateTime Function() now = DateTime.now,+}) => showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ requireWrite: false,+ child: _SwarmModelsWindow(controller: c, app: app, now: now),+ ),+);++class _SwarmModelsWindow extends StatelessWidget {+ const _SwarmModelsWindow({+ required this.controller,+ required this.app,+ required this.now,+ });++ final SuperTabController controller;+ final AppNotifier? app;+ final DateTime Function() now;++ @override+ Widget build(BuildContext context) {+ final c = controller;+ final size = MediaQuery.sizeOf(context);+ return ListenableBuilder(+ listenable: c,+ builder: (context, _) {+ final local = c.snapshot?.localModels;+ final on = local?.enabled == true;+ final picker = on && local?.ready == true && app != null;+ final served = [+ if (local != null)+ for (final pool in c.snapshot?.machines ?? const [])+ for (final m in superTabServedModels(+ pool,+ local.grid,+ now: now(),+ ))+ '${m.name} on ${superTabMachineName(pool['name'] as String? ?? 'a machine')}',+ ];+ final header = Padding(+ padding: const EdgeInsets.fromLTRB(24, 20, 16, 12),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ 'Local models',+ style: DesktopChrome.text(size: 15, medium: true),+ ),+ ),+ Text('Use local models', style: DesktopChrome.control()),+ const SizedBox(width: 8),+ Switch(+ key: const ValueKey('super-local-models-switch'),+ value: on,+ onChanged: !c.isOwner || !c.canWrite || c.saving+ ? null+ : (value) => unawaited(+ c.command({+ 'type': 'localModels.set',+ 'enabled': value,+ }),+ ),+ ),+ const SizedBox(width: 4),+ IconButton(+ key: const ValueKey('super-local-models-close'),+ tooltip: 'Close',+ icon: const Icon(Icons.close, size: 18),+ onPressed: () => Navigator.pop(context),+ ),+ ],+ ),+ const SizedBox(height: 4),+ Text(+ 'People in this Swarm can run AI models on their own machines and share their APIs. '+ 'The product manager can give simple tasks to them, at no subscription cost.',+ style: DesktopChrome.text(),+ ),+ const SizedBox(height: 8),+ Text(+ key: const ValueKey('super-local-models-status'),+ _status(local, owner: c.isOwner),+ style: DesktopChrome.metadata(+ color: on && local?.ready == false+ ? Theme.of(context).colorScheme.error+ : null,+ ),+ ),+ if (on && served.isNotEmpty) ...[+ const SizedBox(height: 4),+ Text(+ key: const ValueKey('super-local-models-running'),+ 'Running now: ${served.join(', ')}',+ style: DesktopChrome.metadata(),+ ),+ ],+ ],+ ),+ );+ // The ⌘I picker's look: its rows and preview read [DesktopChrome] to draw as the desktop app, not a terminal.+ return Dialog(+ clipBehavior: Clip.antiAlias,+ child: DesktopChrome(+ child: SizedBox(+ width: picker ? (size.width - 80).clamp(360, 1120) : 480,+ height: picker ? (size.height - 80).clamp(360, 720) : null,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ header,+ if (picker) ...[+ Divider(height: 1, color: DesktopChrome.rim),+ Expanded(+ child: _SwarmModelsPicker(app: app!, grid: local!.grid),+ ),+ ] else+ const SizedBox(height: 12),+ ],+ ),+ ),+ ),+ );+ },+ );+ }+}++/// ⌘I's Models list and preview, for the Swarm whose grid is [grid].+class _SwarmModelsPicker extends StatefulWidget {+ const _SwarmModelsPicker({required this.app, required this.grid});++ final AppNotifier app;+ final String grid;++ @override+ State<_SwarmModelsPicker> createState() => _SwarmModelsPickerState();+}++class _SwarmModelsPickerState extends State<_SwarmModelsPicker> {+ late final ModelSearchCatalog _catalog;+ late final SwarmModelsTarget _target;+ late final SwarmSearchController _search;+ final _editing = TextEditingController();+ final _focus = FocusNode();+ final _controls = SearchPreviewControls();++ @override+ void initState() {+ super.initState();+ final app = widget.app;+ app.modelManager.start();+ app.modelManager.setPanelVisible(true);+ _catalog = ModelSearchCatalog(app.modelManager, app.modelsMenu)+ ..setVisible(true);+ _target = SwarmModelsTarget(+ app: app,+ grid: widget.grid,+ machineId: app.modelManager.machine?.machine.machineId ?? '',+ );+ unawaited(_target.refresh());+ // `adding`/`offersCreate`: the APIs section ends in Add API connection, as ⌘I's does.+ _search = SwarmSearchController(+ app,+ const [],+ models: _catalog,+ swarmModels: _target,+ adding: true,+ offersCreate: true,+ )..setQuery(':');+ }++ @override+ void dispose() {+ widget.app.modelManager.setPanelVisible(false);+ _search.dispose();+ _catalog.dispose();+ _target.dispose();+ _controls.dispose();+ _editing.dispose();+ _focus.dispose();+ super.dispose();+ }++ /// What ⌘I does with a chosen row here: Add API connection opens the add form in the preview, beside it. Every+ /// other row acts from its preview's button ([SwarmSearchController.swarmModelAction]).+ void _choose(SwarmSearchSelection? choice) {+ final row = choice?.destination;+ if (row == null || !row.isCreate) return;+ final index = _search.rows.indexWhere((r) => r.id == row.id);+ if (index >= 0) _search.move(index - _search.cursor);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _controls.invoke('picker.resource_add_api');+ });+ }++ void _query(String words) =>+ _search.setQuery(words.trim().isEmpty ? ':' : ': ${words.trim()}');++ @override+ Widget build(BuildContext context) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 12, 16, 8),+ child: Row(+ children: [+ Icon(AppIcons.search, size: 18, color: DesktopChrome.muted),+ const SizedBox(width: 12),+ Expanded(+ child: TextField(+ key: const ValueKey('super-local-models-search'),+ controller: _editing,+ focusNode: _focus,+ autofocus: true,+ onChanged: _query,+ onSubmitted: (_) {+ _choose(_search.submit());+ _focus.requestFocus();+ },+ decoration: const InputDecoration.collapsed(+ hintText: 'Search models',+ ),+ style: DesktopChrome.text(),+ ),+ ),+ ],+ ),+ ),+ Expanded(+ child: ListenableBuilder(+ listenable: Listenable.merge([_search, _target]),+ builder: (context, _) => SwarmSearchResults(+ search: _search,+ onChoose: _choose,+ onRefocus: _focus.requestFocus,+ sideBySideMinWidth: 700,+ previewBuilder: () => SwarmResourcePreview(+ search: _search,+ controls: _controls,+ onChoose: _choose,+ onRefocus: _focus.requestFocus,+ onModalChanged: (_) {},+ onCommands: () {},+ ),+ ),+ ),+ ),+ ],+ );+ }+}++String _status(SuperTabLocalModels? local, {required bool owner}) {+ if (local == null || !local.enabled) {+ return owner+ ? 'Off. Only you can turn it on.'+ : 'Off. The Swarm owner can turn it on.';+ }+ return switch (local.ready) {+ true =>+ 'On. Run your models for the Swarm, or share an API with it, below.',+ false =>+ 'Could not finish setting up: ${_sentence(local.error ?? 'try again later')}',+ null =>+ owner+ ? 'Setting up. Keep Harness open on one of your computers for a minute.'+ : 'Setting up on the owner\'s computer.',+ };+}++/// [text] as a sentence: grid's own words often end without a full stop.+String _sentence(String text) {+ final t = text.trim();+ return RegExp(r'[.!?]$').hasMatch(t) ? t : '$t.';+}++/// The Local models part of a machine's details: what it runs for the Swarm, and on the viewer's own machine, a way to+/// run or stop one.+class SuperTabMachineLocalModels extends StatelessWidget {+ const SuperTabMachineLocalModels({+ super.key,+ required this.controller,+ required this.machineId,+ required this.mine,+ this.app,+ this.now = DateTime.now,+ });++ final SuperTabController controller;+ final String machineId;++ /// The viewer's own machine, which their window can reach: only they start a model on it.+ final bool mine;+ final AppNotifier? app;+ final DateTime Function() now;++ @override+ Widget build(BuildContext context) {+ final local = controller.snapshot?.localModels;+ if (local == null || !local.enabled) return const SizedBox.shrink();+ final pool = controller.snapshot?.machines+ .where((m) => m['machineId'] == machineId)+ .firstOrNull;+ final served = superTabServedModels(pool, local.grid, now: now());+ return Padding(+ key: ValueKey('super-machine-local-models-$machineId'),+ padding: const EdgeInsets.only(top: 24),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text('Local models', style: DesktopChrome.control(medium: true)),+ const SizedBox(height: 8),+ Text(+ served.isEmpty+ ? 'Not running a model for this Swarm.'+ : 'Running ${served.map((m) => m.name).join(', ')} for this Swarm.',+ style: DesktopChrome.control(),+ ),+ if (mine && app != null) ...[+ const SizedBox(height: 8),+ Align(+ alignment: Alignment.centerLeft,+ child: OutlinedButton(+ key: const ValueKey('super-machine-local-models-run'),+ onPressed: () => unawaited(+ showSwarmLocalModels(context, controller, app: app, now: now),+ ),+ child: const Text('Run a local model…'),+ ),+ ),+ ],+ ],+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/machine_details.dart b/desktop/lib/super_tabs/machine_details.dartindex ac10ea0ab..d0eebadbf 100644--- a/desktop/lib/super_tabs/machine_details.dart+++ b/desktop/lib/super_tabs/machine_details.dart@@ -18,6 +18,7 @@ class SuperTabMachineDetails extends StatelessWidget {this.resources,this.cwd,this.engines,+ this.footer,});final String name, status;@@ -26,6 +27,9 @@ class SuperTabMachineDetails extends StatelessWidget {final List<String>? engines;final List<Map<String, Object?>> accounts;+ /// Below the details, inside the same scroll: what a Swarm adds about the machine (its local models).+ final Widget? footer;+Widget _row(String label, String value, {required bool stacked}) => Padding(padding: const EdgeInsets.symmetric(vertical: 5),child: stacked@@ -185,6 +189,7 @@ class SuperTabMachineDetails extends StatelessWidget {for (final detail in hardware)_row(detail.$1, detail.$2, stacked: stacked),]),+ ?footer,],),),diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 140799062..16e60a2d8 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -26,6 +26,7 @@ import 'agent_details.dart';import 'controller.dart';import 'dialog_scope.dart';import 'identity.dart';+import 'local_models.dart';import 'machine_details.dart';import 'machine_status.dart';import 'model.dart';@@ -1377,6 +1378,16 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {cwd: shared?['cwd'] as String?,engines: allowed,accounts: dim ? const [] : accounts,+ footer: SuperTabMachineLocalModels(+ controller: c,+ machineId: id,+ // Only on a machine of the viewer's own that this window reaches does Run start anything.+ mine:+ (person?.id ?? contributor) == c.accountId &&+ widget.app?.stateOf(id) != null,+ app: widget.app,+ now: widget.now,+ ),),actions: [if (shared != null && contributor == c.accountId)@@ -1707,6 +1718,26 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {? () => unawaited(_contribute()): null,addTooltip: 'Add machine',+ // The Local models add-on: the owner turns it on here; everyone else sees it once it is on.+ actions: [+ if (c.isOwner || c.snapshot?.localModels?.enabled == true)+ AppIconButton(+ key: const ValueKey('super-local-models'),+ icon: AppIcons.cpu,+ tooltip: 'Local models',+ color: c.snapshot?.localModels?.enabled == true+ ? DesktopChrome.accent+ : DesktopChrome.muted,+ onPressed: () => unawaited(+ showSwarmLocalModels(+ context,+ c,+ app: widget.app,+ now: widget.now,+ ),+ ),+ ),+ ],// Only a Swarm that can't be read is news; a live one says nothing.trailing: c.backendUnreachable? SuperTabMachinesPill(diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex b61c0facb..d30e9ba59 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -188,7 +188,8 @@ class SuperTabSnapshot {row['invitations'],(row) => Map<String, dynamic>.unmodifiable(row),),- leadsConversationId = row['leadsConversationId'] as String? {+ leadsConversationId = row['leadsConversationId'] as String?,+ localModels = SuperTabLocalModels.read(row['localModels']) {if (row['version'] != 1) {throw const FormatException('Update Harness to open this Swarm.');}@@ -222,6 +223,9 @@ class SuperTabSnapshot {/// Where the projects' Product Managers talk, Swarm-wide; null in a Swarm/// from before it (spec 2026-10-23-leads-see-and-talk.md).final String? leadsConversationId;++ /// The Local models add-on, once the owner has turned it on; null before.+ final SuperTabLocalModels? localModels;SuperTabConversation? conversation(String id) =>conversations.where((c) => c.id == id).firstOrNull;SuperTabAgent? agent(String id) =>@@ -281,6 +285,66 @@ class SuperTabSnapshot {: message.authorName;}+/// The Swarm's Local models add-on (docs/plans/2026-10-23-swarm-local-models.md): its grid, whether it is on, and what the+/// owner's computer last reported about setting the grid up (`ready` null until it has).+class SuperTabLocalModels {+ const SuperTabLocalModels({+ required this.grid,+ required this.enabled,+ this.ready,+ this.error,+ });++ static SuperTabLocalModels? read(Object? value) {+ if (value is! Map || value['grid'] is! String) return null;+ return SuperTabLocalModels(+ grid: value['grid'] as String,+ enabled: value['enabled'] == true,+ ready: value['ready'] is bool ? value['ready'] as bool : null,+ error: value['error'] is String ? value['error'] as String : null,+ );+ }++ final String grid;+ final bool enabled;+ final bool? ready;+ final String? error;+}++/// One model a machine serves on the Swarm's grid, as its last reading says.+typedef SuperTabServedModel = ({String model, String name});++/// The models [pool]'s reading says it serves on [grid]. A reading older than [freshFor] says nothing (backend+/// `MACHINE_FRESH_MS`), as the route reads it.+List<SuperTabServedModel> superTabServedModels(+ Map<String, dynamic>? pool,+ String grid, {+ required DateTime now,+ Duration freshFor = const Duration(seconds: 45),+}) {+ final observation = pool?['observation'];+ if (observation is! Map) return const [];+ final at = observation['receivedAt'];+ if (at is! num ||+ now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt())) >+ freshFor) {+ return const [];+ }+ return [+ for (final m+ in observation['localModels'] is List+ ? observation['localModels'] as List+ : const [])+ if (m is Map && m['grid'] == grid && m['model'] is String)+ (+ model: m['model'] as String,+ name: m['name'] is String+ ? m['name'] as String+ : m['model'] as String,+ ),+ ];+}+class SuperTabRouteChoice {const SuperTabRouteChoice(this.id, this.title);final String id, title;diff --git a/desktop/lib/super_tabs/routing_policy.dart b/desktop/lib/super_tabs/routing_policy.dartindex db683be64..21598b8b7 100644--- a/desktop/lib/super_tabs/routing_policy.dart+++ b/desktop/lib/super_tabs/routing_policy.dart@@ -56,6 +56,7 @@ class RoutingPolicy {required this.floor,required this.quotaReserve,required this.notes,+ this.localModels,});factory RoutingPolicy.fromJson(Map<String, dynamic> j) {@@ -71,6 +72,9 @@ class RoutingPolicy {},quotaReserve: (j['quotaReserve'] as num).toInt(),notes: j['notes'] as String? ?? '',+ localModels: j['localModels'] is Map+ ? Map<String, dynamic>.unmodifiable(j['localModels'] as Map)+ : null,);}@@ -79,6 +83,10 @@ class RoutingPolicy {final int quotaReserve;final String notes;+ /// How the route weighs models served on a Swarm's grid (`{quality, enabled}`). Not edited here; kept so that+ /// saving the rest does not reset it to the backend's default.+ final Map<String, dynamic>? localModels;+RoutingPolicy copyWith({List<RoutingModel>? models,Map<String, int>? floor,@@ -89,6 +97,7 @@ class RoutingPolicy {floor: floor ?? this.floor,quotaReserve: quotaReserve ?? this.quotaReserve,notes: notes ?? this.notes,+ localModels: localModels,);Map<String, dynamic> toJson() => {@@ -97,6 +106,7 @@ class RoutingPolicy {'quotaReserve': quotaReserve,'notes': notes,'models': [for (final m in models) m.toJson()],+ if (localModels != null) 'localModels': localModels,};/// This policy with one field taken from [other], for a field that goes backdiff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dartindex 93cc6bd5b..fa439bb75 100644--- a/desktop/lib/widgets/swarm_resource_preview.dart+++ b/desktop/lib/widgets/swarm_resource_preview.dart@@ -925,6 +925,32 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {final local = model?.local;final api = model?.api;final owner = model?.controller ?? catalog.manager;+ // A Swarm's Local models: each model's one action is for the Swarm (SwarmSearchController.swarmModelAction).+ if (search.swarmModels != null &&+ !(local != null && owner.downloading(local))) {+ final swarm = search.swarmModelAction(selected);+ if (swarm != null) {+ final run = swarm.run;+ return [+ _ResourceAction(+ swarm.label,+ !busy && run != null ? () => unawaited(_run(run)) : null,+ command: swarm.command,+ ),+ ];+ }+ if (api != null && model?.apiModel == null) {+ return [+ if (search.canExpandApi(selected))+ _ResourceAction(+ search.actionLabel(selected),+ _open,+ command: 'picker.accept',+ ),+ ];+ }+ return const [];+ }if (local != null && owner.downloading(local)) {// A download under way: cancelling it is the one action open while it runs.return [@@ -1452,6 +1478,15 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {widget.search.modelUseError != null)errorLine(widget.search.modelUseError!),SizedBox(height: cell.height),+ if (widget.search.swarmModels case final swarm?)+ labelValue(+ 'Swarm',+ local == null+ ? 'Usable by agents on your machines'+ : local.servedOn(swarm.grid)+ ? 'Running for this Swarm'+ : 'Run for Swarm lets agents on any machine in the Swarm use it',+ ),if (local != null) ...[// A model another app downloaded starts in that app, joined to the grid from there.if (local.app case final app?) labelValue('Runs in', app),@@ -1627,7 +1662,13 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {if (model.name case final name?) ('Name', name),('Via', '${api.name} · ${api.host}'),'',- if (reason == null)+ if (widget.search.swarmModels case final swarm?) ...[+ swarm.shared(api.id, model.id)+ ? 'Shared with this Swarm.'+ : 'Share with Swarm lets agents on any machine in this Swarm run on it.',+ 'They use the key saved on ${widget.search.models!.manager.apis.hostLabel}, '+ 'and every request they send is charged to that key.',+ ] else if (reason == null)'Use runs this harness on it, with the key saved on ''${widget.search.models!.manager.apis.hostLabel}.'else if (reason == 'Other machine')diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex 67789f1e0..e509bb921 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -642,6 +642,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {// An empty section still says it is there, so there is somewhere to add to — except the// downloads, which a machine with the whole catalog, or none, has nothing under, and what is// shared with you while Grid is not set up: the Set up row under Your models stands for it.+ // A Swarm's Local models have no Subscriptions: nothing in one can be given to a Swarm.+ if (search.swarmModels != null &&+ section == ModelSearchSection.subscriptions) {+ continue;+ }if (indices.isEmpty &&(search.matchQuery.trim().isNotEmpty ||section == ModelSearchSection.catalog ||@@ -846,6 +851,15 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {}void _submit([SwarmDestination? row]) {+ // In a Swarm's Local models a click chooses a model to read about: what it does to the Swarm (an API shared on+ // the person's key and credits) is the preview's button, or Return, once its preview has been seen.+ if (row != null &&+ search.swarmModels != null &&+ search.swarmModelAction(row) != null) {+ _focusResult(row.id);+ widget.onRefocus();+ return;+ }final choice = search.submit(row);if (choice != null) {widget.onChoose(choice);diff --git a/desktop/test/local_model_picker_test.dart b/desktop/test/local_model_picker_test.dartindex cb9431b93..a508119c9 100644--- a/desktop/test/local_model_picker_test.dart+++ b/desktop/test/local_model_picker_test.dart@@ -167,6 +167,7 @@ class _LocalApp extends ModelManagerTestApp {String machineId,String modelId, {required bool start,+ String? grid,}) async {if (!start) await stopGate?.future;final answer = await super.controlLocalModel(diff --git a/desktop/test/resource_picker_test.dart b/desktop/test/resource_picker_test.dartindex afe555a6c..958098806 100644--- a/desktop/test/resource_picker_test.dart+++ b/desktop/test/resource_picker_test.dart@@ -174,6 +174,7 @@ class _ModelSelectionApp extends ModelManagerTestApp {String machineId,String modelId, {required bool start,+ String? grid,}) async {final answer = await super.controlLocalModel(machineId,diff --git a/desktop/test/routing_policy_test.dart b/desktop/test/routing_policy_test.dartindex 9d889e73a..0427f7136 100644--- a/desktop/test/routing_policy_test.dart+++ b/desktop/test/routing_policy_test.dart@@ -38,6 +38,15 @@ Widget formOf(Widget form) => MaterialApp(void main() {test('round-trips the backend policy', () {expect(RoutingPolicy.fromJson(json).toJson(), json);+ // How local models count is not edited here, but an edit elsewhere keeps it.+ final local = {+ ...json,+ 'localModels': {'quality': 2, 'enabled': false},+ };+ expect(+ RoutingPolicy.fromJson(local).copyWith(notes: 'x').toJson(),+ {...local, 'notes': 'x'},+ );});testWidgets('edits a model, the floor, the reserve and the notes', (diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dartindex 4de5c4510..53cb5d4b8 100644--- a/desktop/test/super_tab_machines_test.dart+++ b/desktop/test/super_tab_machines_test.dart@@ -938,6 +938,156 @@ void main() {},);+ group('Local models', () {+ const swarmGrid = 'swarm-0123456789ab';+ Map<String, dynamic> machine({+ List<Map<String, dynamic>> served = const [],+ }) => {+ 'machineId': 'studio',+ 'name': 'Studio',+ 'contributorId': 'owner',+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'localModels': served,+ },+ };+ Future<void> mount(WidgetTester tester, dynamic c) async {+ await tester.pumpWidget(+ MaterialApp(+ // As the sidebar does: the section is rebuilt whenever the Swarm changes.+ home: Scaffold(+ body: ListenableBuilder(+ listenable: c,+ builder: (context, _) =>+ SuperTabMachines(controller: c, onAddAgent: (_) {}),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ final open = find.byKey(const ValueKey('super-local-models'));+ final toggle = find.byKey(const ValueKey('super-local-models-switch'));++ testWidgets('the owner turns them on from Machines; it is off until then', (+ tester,+ ) async {+ final server = ConversationServer();+ server.state['machines'] = [machine()];+ final c = server.controller();+ await c.refresh();+ await mount(tester, c);+ await tester.tap(open);+ await tester.pumpAndSettle();+ expect(tester.widget<Switch>(toggle).value, isFalse);+ expect(find.text('Off. Only you can turn it on.'), findsOneWidget);+ await tester.tap(toggle);+ await tester.pumpAndSettle();+ expect(+ server.posts+ .map((p) => p['command'])+ .where((cmd) => (cmd as Map)['type'] == 'localModels.set')+ .single,+ {'type': 'localModels.set', 'enabled': true},+ );+ await tester.tap(find.byKey(const ValueKey('super-local-models-close')));+ await tester.pumpAndSettle();+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });++ testWidgets(+ 'others see them only once on, cannot switch them, and see what each machine runs',+ (tester) async {+ final server = ConversationServer();+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ server.state['machines'] = [machine()];+ final c = server.controller(account: 'peer');+ await c.refresh();+ await mount(tester, c);+ expect(open, findsNothing);++ server.state['localModels'] = {+ 'grid': swarmGrid,+ 'enabled': true,+ 'ready': true,+ };+ server.state['machines'] = [+ machine(+ served: [+ {'grid': swarmGrid, 'model': 'qwen3', 'name': 'Qwen 3'},+ {'grid': 'swarm-ffffffffffff', 'model': 'other'},+ ],+ ),+ ];+ server.revision++;+ await c.refresh();+ await tester.pumpAndSettle();+ await tester.tap(open);+ await tester.pumpAndSettle();+ expect(tester.widget<Switch>(toggle).onChanged, isNull);+ expect(find.text('Running now: Qwen 3 on Studio'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('super-local-models-close')));+ await tester.pumpAndSettle();++ // The machine's details say what it runs; Run is for the machine's own person, in their window.+ await tester.tap(find.byKey(const ValueKey('super-machine-studio')));+ await tester.pumpAndSettle();+ expect(find.text('Running Qwen 3 for this Swarm.'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-machine-local-models-run')),+ findsNothing,+ );+ await tester.tap(find.widgetWithText(TextButton, 'Close'));+ await tester.pumpAndSettle();+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ },+ );++ test(+ 'a reading serves models on the Swarm grid only while it is fresh',+ () {+ final now = DateTime.fromMillisecondsSinceEpoch(1000000);+ Map<String, dynamic> pool(int at) => {+ 'observation': {+ 'receivedAt': at,+ 'localModels': [+ {'grid': swarmGrid, 'model': 'qwen3'},+ {'grid': swarmGrid, 'model': 7},+ 'junk',+ ],+ },+ };+ expect(superTabServedModels(pool(990000), swarmGrid, now: now), [+ (model: 'qwen3', name: 'qwen3'),+ ]);+ expect(+ superTabServedModels(pool(900000), swarmGrid, now: now),+ isEmpty,+ );+ expect(superTabServedModels(null, swarmGrid, now: now), isEmpty);+ expect(SuperTabLocalModels.read({'enabled': true}), isNull);+ expect(+ SuperTabLocalModels.read({+ 'grid': swarmGrid,+ 'enabled': true,+ 'ready': false,+ 'error': 'plan limit',+ })!.error,+ 'plan limit',+ );+ },+ );+ });+group('Remove from Swarm', () {Map<String, dynamic> machine(String contributorId) => {'machineId': 'studio',diff --git a/desktop/test/support/model_manager.dart b/desktop/test/support/model_manager.dartindex f5e79d035..dcdfdf532 100644--- a/desktop/test/support/model_manager.dart+++ b/desktop/test/support/model_manager.dart@@ -116,6 +116,9 @@ class ModelManagerTestApp extends AppNotifier {}final actions = <({String machine, String model, bool start})>[];++ /// The Swarm grid each start or stop named, beside [actions] (null: the account's own).+ final grids = <String?>[];final downloads = <({String machine, String model})>[];@override@@ -202,8 +205,10 @@ class ModelManagerTestApp extends AppNotifier {String machineId,String modelId, {required bool start,+ String? grid,}) async {actions.add((machine: machineId, model: modelId, start: start));+ grids.add(grid);final inventory = inventoryFor(machineId);if (actionReply != null) return actionReply!.future;final operation = <String, dynamic>{diff --git a/desktop/test/swarm_local_models_picker_test.dart b/desktop/test/swarm_local_models_picker_test.dartnew file mode 100644index 000000000..0c05ac895--- /dev/null+++ b/desktop/test/swarm_local_models_picker_test.dart@@ -0,0 +1,240 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/models/model_search_catalog.dart';+import 'package:harness/models/swarm_models_target.dart';+import 'package:harness/state/swarm_navigation.dart';+import 'package:harness/state/swarm_search.dart';+import 'package:harness/usage/models_menu_controller.dart';++import 'support/model_manager.dart';++const _grid = 'swarm-0123456789ab';++class _Subscriptions extends ModelsMenuController {+ @override+ List<Map<String, Object?>> get rows => const [+ {'engine': 'codex', 'title': 'OpenAI'},+ ];+}++/// The test app, answering the Swarm's API share requests as the CLI would.+class _SwarmApp extends ModelManagerTestApp {+ _SwarmApp() : super(ModelManagerConnection());+ final shareCalls = <({String connectionId, String model, bool start})>[];+ final shared = <({String connectionId, String model})>{};+ String? shareError;+ bool sharesFail = false;++ @override+ Future<Map<String, dynamic>> swarmApiShares(+ String machineId,+ String grid,+ ) async {+ if (sharesFail) throw StateError('offline');+ return {+ 'shares': [+ for (final s in shared)+ {'grid': grid, 'connectionId': s.connectionId, 'model': s.model},+ {'grid': grid, 'model': 7},+ ],+ };+ }++ @override+ Future<Map<String, dynamic>> swarmApiShare(+ String machineId, {+ required String grid,+ required String connectionId,+ required String model,+ required bool start,+ }) async {+ shareCalls.add((connectionId: connectionId, model: model, start: start));+ if (shareError != null) return {'error': shareError};+ final key = (connectionId: connectionId, model: model);+ start ? shared.add(key) : shared.remove(key);+ return {'ok': true};+ }+}++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ late _SwarmApp app;+ late ModelsMenuController subscriptions;+ late ModelSearchCatalog catalog;+ late SwarmModelsTarget target;+ late SwarmSearchController search;++ setUp(() async {+ app = _SwarmApp();+ app.localInventory = {+ 'supportsDownload': true,+ 'models': [+ {+ 'id': 'downloaded',+ 'name': 'Downloaded model',+ 'state': 'downloaded',+ 'canStart': true,+ },+ {+ 'id': 'served',+ 'name': 'Served model',+ 'state': 'downloaded',+ 'canStart': false,+ 'canStop': false,+ 'servedOn': [+ {+ 'grid': _grid,+ 'servedAs': ['served'],+ },+ ],+ },+ {+ 'id': 'catalog',+ 'name': 'Catalog model',+ 'state': 'available',+ 'canStart': true,+ },+ ],+ };+ subscriptions = _Subscriptions();+ catalog = ModelSearchCatalog(+ app.modelManager,+ subscriptions,+ pollHosts: false,+ );+ target = SwarmModelsTarget(app: app, grid: _grid, machineId: 'm');+ search = SwarmSearchController(+ app,+ const [],+ models: catalog,+ swarmModels: target,+ )..setQuery(':');+ await catalog.refresh();+ });+ tearDown(() {+ search.dispose();+ target.dispose();+ catalog.dispose();+ subscriptions.dispose();+ app.dispose();+ });++ SwarmDestination row(String modelId) =>+ search.rows.firstWhere((r) => r.modelId == 'model:local:$modelId');++ test(+ 'lists models shared with you, but not what the Swarm\'s own grid serves',+ () async {+ app.inventory = const GridModels(+ gridName: 'home',+ models: [],+ grids: [+ GridSection(+ name: 'Team',+ own: false,+ models: [GridModel(id: 'Shared Qwen', node: 'team.lan')],+ ),+ GridSection(+ name: _grid,+ own: false,+ models: [GridModel(id: 'deepseek/v4', node: 'This Mac')],+ ),+ ],+ );+ await app.modelManager.refresh(force: true);+ final shared = search.rows+ .where((r) => search.modelSection(r) == ModelSearchSection.shared)+ .map((r) => r.title);+ expect(shared, ['Shared Qwen · team.lan · Team']);+ expect(+ search.modelRowStatus(+ search.rows.firstWhere((r) => r.title.startsWith('Shared Qwen')),+ ),+ 'Usable',+ );+ },+ );++ test('lists no subscriptions: nothing in one can be given to a Swarm', () {+ expect(+ search.rows.where(+ (r) =>+ catalog.entries[r.modelId]?.section ==+ ModelSearchSection.subscriptions,+ ),+ isEmpty,+ );+ // The same catalog outside a Swarm lists them.+ final plain = SwarmSearchController(app, const [], models: catalog)+ ..setQuery(':');+ addTearDown(plain.dispose);+ expect(+ plain.rows.where(+ (r) =>+ catalog.entries[r.modelId]?.section ==+ ModelSearchSection.subscriptions,+ ),+ isNotEmpty,+ );+ });++ test('ends its APIs in Add API connection, as \u2318I does, with no Swarm action of its own', () {+ final adding = SwarmSearchController(+ app,+ const [],+ models: catalog,+ swarmModels: target,+ adding: true,+ offersCreate: true,+ )..setQuery(':');+ addTearDown(adding.dispose);+ final create = adding.rows.singleWhere((r) => r.isCreate);+ expect(adding.modelSection(create), ModelSearchSection.apis);+ expect(adding.swarmModelAction(create), isNull);+ // Choosing it is the window's to answer (it opens the add form), never a harness start.+ expect(adding.submit(create)?.destination.isCreate, isTrue);+ });++ test('offers Run for Swarm, Stop for Swarm and Get by what the model is to the Swarm', () async {+ expect(search.modelRowStatus(row('served')), 'In Swarm');+ expect(search.swarmModelAction(row('served'))!.label, 'Stop for Swarm');+ expect(search.swarmModelAction(row('catalog'))!.label, 'Get');+ final run = search.swarmModelAction(row('downloaded'))!;+ expect(run.label, 'Run for Swarm');+ expect(await run.run!(), isNull);+ expect(app.actions.last, (machine: 'm', model: 'downloaded', start: true));+ expect(app.grids.last, _grid);+ // Outside a Swarm there is no Swarm action.+ final plain = SwarmSearchController(app, const [], models: catalog)+ ..setQuery(':');+ addTearDown(plain.dispose);+ expect(plain.swarmModelAction(row('downloaded')), isNull);+ });++ 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));+ expect(app.grids.last, _grid);+ });++ test('shares an API model with the Swarm and stops, and keeps what it knew when the read fails', () async {+ expect(target.shared('c1', 'deepseek'), isFalse);+ expect(await target.share('c1', 'deepseek', start: true), isNull);+ expect(app.shareCalls.single, (+ connectionId: 'c1',+ model: 'deepseek',+ start: true,+ ));+ expect(target.shared('c1', 'deepseek'), isTrue);+ app.sharesFail = true;+ await target.refresh();+ expect(target.shared('c1', 'deepseek'), isTrue);+ app.sharesFail = false;+ app.shareError = 'not a member';+ expect(await target.share('c1', 'deepseek', start: false), 'not a member');+ expect(target.error, 'not a member');+ app.shareError = null;+ expect(await target.share('c1', 'deepseek', start: false), isNull);+ expect(target.shared('c1', 'deepseek'), isFalse);+ });+}diff --git a/docs/plans/2026-10-23-swarm-local-models.md b/docs/plans/2026-10-23-swarm-local-models.mdnew file mode 100644index 000000000..1a8123834--- /dev/null+++ b/docs/plans/2026-10-23-swarm-local-models.md@@ -0,0 +1,48 @@+# Swarm local models++**Goal.** A Swarm's members can serve local models from their machines, and the Lead (Product Manager) can start+Builders on them when that fits the work. It is an add-on: nothing calls grid until the Swarm's owner turns it on.++## Flow++| # | Who | Does | Behind it |+|---|---|---|---|+| 0 | Anyone | Creates a Swarm | No grid. Routing uses subscriptions only. |+| 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. |+| 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. |++## Decisions (owner, 2026-10-23)++- Off by default; grid is called only on turn-on, on starting or stopping a model, and on a Builder launch on one.+- Only the owner (the grid's admin) manages its members; a newcomer gets access when the owner's computer is next online.+- No Harness limit on grids. Members are added as `both`.+- 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.++## 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`),+ `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`.++## Local models window (owner, 2026-10-23)++The ⌘I Models picker made for the Swarm (`SwarmModelsTarget` on `SwarmSearchController`), without Subscriptions:++- **Your models:** Run for Swarm / Stop for Swarm (start or stop on the Swarm's grid); Get first when not downloaded.+- **APIs:** a saved API's model can be shared with the Swarm. This computer runs a local endpoint (127.0.0.1, secret+ path) that adds the key and forwards completions to the API; grid joins it with `--at`. Every Builder in the Swarm then+ spends the sharer's key and credits, which the preview says. Shares end when the models service restarts (it takes+ stale ones off the grid at start).+- **Shared with you:** models other people share with you are usable by agents on *your* machines only (your machine's+ grid sign-in reaches them). The backend admits such a start only on a machine whose fresh reading lists the model.+- A click only selects a row; the preview's button (or Return) acts.