Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Swarm: a subsystem the daemon core runs without (HARNESS_SWARM=off) (#1765)

0xken15ee2384ad15a1
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.ts
index 22c5cba58..b8f909d27 100644
--- a/cli/e2e/agentClient.e2e.ts
+++ b/cli/e2e/agentClient.e2e.ts
@@ -18,7 +18,7 @@ import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
import { LocalClient } from './harness/client.js'
import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
-import { retainedHarnesses } from '../src/superTabs/retention.js'
+import { retainContributions, retainedHarnesses } from '../src/superTabs/retention.js'
import { overOldRoutes } from './harness/swarmReads.js'
const HARNESS_INSTRUCTIONS = 'You are running in Harness, and the person can watch you. You can hand work to other agents (Claude Code, Codex) that run in their own harnesses: `harness new`, `harness wait`, `harness show`, `harness close` (see `harness --help`). Start one only for work that can run in parallel, needs another model, or takes long; do quick work yourself, and close each one once you have its answer. Only use or close harnesses you started.'
@@ -83,7 +83,7 @@ describe('Harness for agents, end to end', () => {
await backend?.close(); backend = undefined
})
/** A daemon signed in to the fake backend, whose account has [experiments] on, read and kept before the test goes on. */
- const signedIn = async (experiments: Record<string, boolean>, options: { trustPrompt?: boolean; before?: (d: IsolatedDaemon) => void } = {}) => {
+ const signedIn = async (experiments: Record<string, boolean>, options: { trustPrompt?: boolean; before?: (d: IsolatedDaemon) => void; env?: Record<string, string> } = {}) => {
const relay = await FakeBackend.start()
backend = relay
relay.addMachine(ME)
@@ -91,7 +91,7 @@ describe('Harness for agents, end to end', () => {
Object.assign(relay.experiments, experiments)
const d = await IsolatedDaemon.create({ trustPrompt: options.trustPrompt, env: {
BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId,
- HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000', ...options.env,
} })
daemon = d
onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-200).join('\n')}`) })
@@ -283,6 +283,37 @@ describe('Harness for agents, end to end', () => {
client.close()
})
+ // HARNESS_SWARM=off (the review of #1765): the agent cleanup, in the edge host, is handed none of the Swarm, and a harness
+ // the Swarm's saved roster names is closed with its starter as any other. On, the test above keeps it (`shared`).
+ it('with the Swarm off, a harness the Swarm\'s saved roster keeps is closed with its starter, as any other', async () => {
+ const { d } = await signedIn({ agents_start_agents: true }, { env: { HARNESS_SWARM: 'off' } })
+ const client = await LocalClient.connect(d, { machineId: ME.machineId })
+ const list = async () => (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents
+ const dir = join(d.projectsDir, 'lead')
+ mkdirSync(dir, { recursive: true })
+ const made = await client.request('agent_create', { engine: 'claude', cwd: dir, bypassPermission: true, name: 'lead' }, 90_000)
+ expect(made.error, JSON.stringify(made)).toBeUndefined()
+ const lead = await until('lead to bind its conversation', async () => {
+ const row = (await list()).find((a) => a.id === made.agent.id)
+ return row?.sessionId && row.status === 'active' ? row : null
+ }, 60_000, 500)
+ const from = client.frames.length
+ client.send('message', { agentId: lead.id, content: 'hello lead' })
+ await client.waitFor((f) => f.type === 'turn_ended' && f.agentId === lead.id, 60_000, 'lead\'s first turn to end', from)
+ const started = await harness(d, String(lead.tmuxPane), ['new', 'claude', 'kept', '--name', 'kept', '--', 'hello kept'])
+ expect(started.code, started.out + started.err).toBe(0)
+ const kept = await until('kept to run', async () => (await list()).find((a) => a.name === 'kept' && a.status === 'active' && a.tmuxPane) ?? null, 60_000, 500)
+ // What the Swarm's host would have kept here had it run: its retention names the harness as a Super Tab member.
+ retainContributions(d.dataDir, ME.machineId, [{ tabId: 'retained-team', agent: { harnessId: kept.id, machineId: ME.machineId } }])
+ expect(retainedHarnesses(d.dataDir).has(kept.id)).toBe(true)
+ const closed = await client.request('agent_close', { agentId: lead.id, sessionId: lead.sessionId, createdAt: lead.createdAt, mode: 'now' }, 60_000)
+ expect(closed, JSON.stringify(closed)).toMatchObject({ closed: true })
+ await until('kept to close with lead', async () => (await list()).find((a) => a.id === kept.id)?.status === 'stopped' || null, 60_000, 500)
+ expect(d.log()).toMatch(/\[agent-cleanup\] closed kept \(\w+\): the harness that started it was closed\./)
+ expect(d.log()).not.toMatch(/\[harnessd\] service superTabs started/)
+ client.close()
+ })
+
it('signed out, the person starts, waits for, reads and closes a harness from a terminal', async () => {
// Never signed in: the daemon runs as this computer (core/main.ts), and the app made harnesses while `harness new`
// refused with "This computer is not signed in to Harness".
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index 118abe2b7..682ba5740 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -307,6 +307,9 @@ export class IsolatedDaemon {
TERMINAL_BACKENDS: 'tmux',
TMUX_REAP_INTERVAL_MS: '5000',
TERMINAL_RECONCILE_INTERVAL_MS: '5000',
+ // The Swarm switch (harnessd/services.ts), as the run was started with: `HARNESS_SWARM=off npm run test:e2e` runs
+ // every daemon of the suite with the Swarm off. A test's own env still decides.
+ ...(process.env.HARNESS_SWARM !== undefined ? { HARNESS_SWARM: process.env.HARNESS_SWARM } : {}),
...options.env,
})
// A Claude Code home moved in the environment this run was started from is the person's: the daemon
diff --git a/cli/e2e/harness/loadedModules.mjs b/cli/e2e/harness/loadedModules.mjs
new file mode 100644
index 000000000..38f4d6c5b
--- /dev/null
+++ b/cli/e2e/harness/loadedModules.mjs
@@ -0,0 +1,8 @@
+// What each daemon process loads (e2e/swarmSwitch.e2e.ts): every module a process resolves to load, one file:// URL a
+// line, in <E2E_LOADED_MODULES_DIR>/<pid>.txt. Given through NODE_OPTIONS, it rides into every process the master
+// starts: the core, each service's process and the engines' readers.
+import { register } from 'node:module'
+import { join } from 'node:path'
+
+const dir = process.env.E2E_LOADED_MODULES_DIR
+if (dir) register('./loadedModulesHooks.mjs', import.meta.url, { data: { file: join(dir, `${process.pid}.txt`) } })
diff --git a/cli/e2e/harness/loadedModulesHooks.mjs b/cli/e2e/harness/loadedModulesHooks.mjs
new file mode 100644
index 000000000..ebfee6a17
--- /dev/null
+++ b/cli/e2e/harness/loadedModulesHooks.mjs
@@ -0,0 +1,11 @@
+// The module hooks loadedModules.mjs registers: each module resolved to load is written down as it resolves, after
+// whatever resolver came before (tsx, from the sources), so a TypeScript source is written as the file it is.
+import { appendFileSync } from 'node:fs'
+
+let file = ''
+export function initialize(data) { file = data.file }
+export async function resolve(specifier, context, next) {
+ const resolved = await next(specifier, context)
+ if (file && resolved.url.startsWith('file:')) appendFileSync(file, `${resolved.url}\n`)
+ return resolved
+}
diff --git a/cli/e2e/swarmSwitch.e2e.ts b/cli/e2e/swarmSwitch.e2e.ts
new file mode 100644
index 000000000..4efbfd7cf
--- /dev/null
+++ b/cli/e2e/swarmSwitch.e2e.ts
@@ -0,0 +1,129 @@
+/**
+ * The Swarm switch on the real daemon (harnessd/services.ts `HARNESS_SWARM`; Dee, v1's last item: the daemon core stays
+ * small and reliable, and the Swarm is a subsystem that can be switched off). Off, the master never starts the Swarm's
+ * process and the core loads none of its code (superTabs/inCore.ts), even on a computer that has the Swarm's saved state:
+ * agents start, run and close exactly as without the Swarm, a Lead the Swarm keeps is no longer protected, a start that
+ * asks for a Swarm role is refused, and the Swarm's requests are answered unavailable. On, the default, nothing changes:
+ * the saved state wakes its process, its requests are answered, and its Lead is never closed.
+ */
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+
+const MACHINE = 'b9'.repeat(16)
+/** The Swarm's code, as a process started from the sources loads it: its folder, its libraries and its service. */
+const SWARM_CODE = /\/src\/(superTabs\/|lib\/swarm|services\/superTabs(Process)?\.ts$)/
+/** Every module each daemon process loaded (harness/loadedModules.mjs), by process: started from the sources, so each
+ * file is the source it is (the shipped build's files are held to the same in src/leanEntry.spec.ts). */
+function loadedModules(dir: string): Map<string, string[]> {
+ return new Map(readdirSync(dir).map((name) => [name, readFileSync(join(dir, name), 'utf8').split('\n').filter(Boolean)]))
+}
+const swarmStarts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service superTabs started/g)].length
+
+const row = async (client: LocalClient, agentId: string) =>
+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)
+ .find((agent) => agent.id === agentId)
+async function create(d: IsolatedDaemon, client: LocalClient, folder: string): Promise<Record<string, any>> {
+ const cwd = join(d.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+}
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const ended = client.next((frame: Frame) => frame.type === 'turn_ended' && frame.agentId === agentId, 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ await ended
+}
+/** What the Swarm's host keeps on a computer that contributed to one: its host file, which wakes the service at a start,
+ * and its retention naming `lead` as an active project's Lead, which the core never closes while the Swarm is on. */
+function swarmState(d: IsolatedDaemon, lead?: string): void {
+ mkdirSync(join(d.dataDir, 'super-tabs'), { recursive: true, mode: 0o700 })
+ writeFileSync(join(d.dataDir, 'super-tabs', `host-${MACHINE}.json`), JSON.stringify({ version: 1, machineId: MACHINE }), { mode: 0o600 })
+ if (lead) writeFileSync(join(d.dataDir, 'super-tabs', 'retained.json'), JSON.stringify({ version: 2, machineId: MACHINE, harnesses: [lead], leads: [lead] }), { mode: 0o600 })
+}
+const close = (client: LocalClient, agent: Record<string, any>) =>
+ client.request('agent_close', { agentId: agent.id, sessionId: agent.sessionId, createdAt: agent.createdAt, mode: 'now' }, 60_000)
+
+describe('the Swarm switch', () => {
+ let daemon: IsolatedDaemon | undefined
+ const clients: LocalClient[] = []
+ const recorded: string[] = []
+ const recordIn = (prefix: string): string => { const dir = mkdtempSync(join(tmpdir(), prefix)); recorded.push(dir); return dir }
+ afterEach(async () => {
+ clients.splice(0).forEach(client => client.close())
+ await daemon?.close(); daemon = undefined
+ recorded.splice(0).forEach(dir => rmSync(dir, { recursive: true, force: true }))
+ })
+ const fresh = async (env: Record<string, string>, modules?: string) => {
+ const record = modules ? { E2E_LOADED_MODULES_DIR: modules, NODE_OPTIONS: `--import=${pathToFileURL(join(CLI_ROOT, 'e2e/harness/loadedModules.mjs')).href}` } : {}
+ const d = await IsolatedDaemon.create({ env: { ...env, ...record }, ...(modules ? { launch: ['--import', 'tsx', 'src/cli.ts', '__harnessd'] } : {}) })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ swarmState(d)
+ await d.start()
+ const client = await LocalClient.connect(d)
+ clients.push(client)
+ return { d, client }
+ }
+
+ it('off, runs agents as without the Swarm: its process never starts, its requests are unavailable, its Lead is not kept', async () => {
+ const modules = recordIn('swarm-off-modules-')
+ const { d, client } = await fresh({ HARNESS_SWARM: 'off' }, modules)
+ const agent = await create(d, client, 'swarm-off')
+ await turn(client, agent.id, 'the core works with the Swarm off')
+ await until('the core to leave the Swarm off', () => d.log().includes('[services] superTabs is turned off on this computer') || null, 30_000, 200)
+ expect(await client.request('super_tabs', { action: 'help' }, 30_000)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'superTabs' })
+ const role = await client.request('agent_create', { engine: 'claude', cwd: join(d.projectsDir, 'swarm-off'), bypassPermission: true, swarmRole: 'dev' }, 30_000)
+ expect(role).toMatchObject({ error: 'INVALID_SWARM_ROLE', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' })
+ // Named a Lead by the Swarm's saved retention, it closes as any agent does: no Swarm code guards it.
+ swarmState(d, agent.id)
+ expect(await close(client, agent)).toMatchObject({ closed: true })
+ expect(swarmStarts(d), 'the Swarm\'s process, with the Swarm off').toBe(0)
+ // No process loaded any of its code (the review of #1765): the master, the core and every service's process.
+ const loaded = loadedModules(modules)
+ expect(loaded.size, 'the master, the core and the edge host, at least').toBeGreaterThanOrEqual(3)
+ expect([...loaded.values()].flat().some((url) => url.includes('/src/core/main.ts')), 'the core\'s own code, recorded').toBe(true)
+ expect([...loaded.values()].flat().filter((url) => SWARM_CODE.test(url))).toEqual([])
+ }, 240_000)
+
+ // With every service in the core's process (`HARNESSD_SERVICES=none`): the agent cleanup, Share, the change-agent handoff
+ // and models start there, and with the Swarm off none of them loads its retention, observers, records or grid code.
+ it('off with every service in the core, runs agents and loads none of the Swarm\'s code', async () => {
+ const modules = recordIn('swarm-off-inline-modules-')
+ const { d, client } = await fresh({ HARNESS_SWARM: 'off', HARNESSD_SERVICES: 'none' }, modules)
+ const agent = await create(d, client, 'swarm-off-inline')
+ await turn(client, agent.id, 'the core works with every service in it and the Swarm off')
+ await until('the core to leave the Swarm off', () => d.log().includes('[services] superTabs is turned off on this computer') || null, 30_000, 200)
+ expect(await client.request('super_tabs', { action: 'help' }, 30_000)).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'superTabs' })
+ expect(await close(client, agent)).toMatchObject({ closed: true })
+ const loaded = [...loadedModules(modules).values()].flat()
+ expect(loaded.some((url) => url.includes('/src/services/inline.ts')), 'the services, in the core\'s process').toBe(true)
+ expect(loaded.some((url) => url.includes('/src/services/agentCleanup.ts')), 'the agent cleanup, in the core\'s process').toBe(true)
+ expect(loaded.filter((url) => SWARM_CODE.test(url))).toEqual([])
+ }, 240_000)
+
+ it('on by default, nothing changes: its saved state wakes its process, its requests are answered, its Lead is never closed', async () => {
+ // Empty reads as unset, whatever the run was started with (`HARNESS_SWARM=off npm run test:e2e`).
+ const modules = recordIn('swarm-on-modules-')
+ const { d, client } = await fresh({ HARNESS_SWARM: '' }, modules)
+ const agent = await create(d, client, 'swarm-on')
+ await turn(client, agent.id, 'the core works with the Swarm on')
+ await until('the Swarm\'s process, woken by its saved state', () => swarmStarts(d) > 0 || null, 60_000, 200)
+ expect(await client.request('super_tabs', { action: 'help' }, 60_000)).toMatchObject({ ok: true })
+ swarmState(d, agent.id)
+ expect(await close(client, agent)).toMatchObject({ error: 'LEAD_PROTECTED' })
+ expect(d.log()).not.toContain('[services] superTabs is turned off on this computer')
+ // The recording sees the Swarm's code where it runs: its side of the core, and its own process.
+ const loaded = [...loadedModules(modules).values()].flat()
+ expect(loaded.some((url) => url.includes('/src/superTabs/inCore.ts'))).toBe(true)
+ expect(loaded.some((url) => url.includes('/src/services/superTabsProcess.ts'))).toBe(true)
+ }, 240_000)
+})
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index ccee18193..609626362 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -93,6 +93,23 @@ function importsFor(path: string, text: string): Array<{ from: string; dynamic:
*/
const IN_PROCESS_ONLY = 'services/inline.ts'
+/**
+ * The Swarm's doors: the only imports of its code from outside it, each dynamic and taken only while the Swarm is on
+ * (`HARNESS_SWARM`, harnessd/swarmSwitch.ts), or, for the CLI's own commands, only when one is run. A walk passes over
+ * them, so a process with the Swarm off loads none of its code; a static import of the same file is walked.
+ */
+const SWARM_DOORS: Readonly<Record<string, readonly string[]>> = {
+ // Its side of the core's process, and of the services that act on it when they run there.
+ 'core/main.ts': ['superTabs/inCore.ts', 'superTabs/inServices.ts'],
+ // Its side of the services that act on it, in their own processes, and its own service's process, which the master
+ // starts only while it is on (harnessd/services.ts `servicesOn`).
+ 'serviceProcess.ts': ['superTabs/inServices.ts', 'services/superTabsProcess.ts'],
+ // `harness super-tab` and git's credential helper in a Swarm session: from the sources every daemon process runs cli.ts.
+ 'cli.ts': ['superTabs/command.ts', 'superTabs/gitCredential.ts'],
+}
+/** The Swarm's code (Super Tabs): its folder, its libraries and its service. */
+const isSwarmCode = (file: string): boolean => /^superTabs\//.test(file) || /^lib\/swarm/.test(file) || /^services\/superTabs(Process)?\.ts$/.test(file)
+
/**
* The files whose `import()`s the core's walk does not follow: the loader of the other twelve engines' code,
* which the core loads in its own process only once one of their sessions needs it
@@ -122,9 +139,9 @@ function closureOf(entry: string): Map<string, number> {
}
/** Whether the walk follows an import of `target` written in `importer`: every one but an `import()` of
- * `IN_PROCESS_ONLY`, or one written in a lazy loader. */
+ * `IN_PROCESS_ONLY`, one through a Swarm door (`SWARM_DOORS`), or one written in a lazy loader. */
function followed(importer: string, target: string, dynamic: boolean): boolean {
- return !dynamic || (target !== IN_PROCESS_ONLY && !LAZY_LOADERS.has(importer))
+ return !dynamic || (target !== IN_PROCESS_ONLY && !SWARM_DOORS[importer]?.includes(target) && !LAZY_LOADERS.has(importer))
}
/** Each file read and parsed once, however many walks pass through it. */
@@ -191,6 +208,8 @@ const EDGE: RegExp[] = [
/^lib\/(normalize|transcriptReader)\.ts$/, /^lib\/sessionSearch\/externals\/(claude|codex)\.ts$/,
/^engines\/(runtime|(claude|codex)\/runtimeProfile)\.ts$/, /^lib\/runtimeProfile\.ts$/,
/^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^orchestrator\//, /^services\//,
+ // The Swarm (Super Tabs) is a subsystem that can be switched off: the core loads its code only through its doors.
+ /^superTabs\//,
/^lib\/grid(Attach|Credentials|Derive|Ensure|Envelope|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,
/^lib\/localModels\.ts$/,
// The grid and saved-API launch builders are models': the core asks it for a launch (ModelsPort.gridLaunch) and keeps
@@ -311,6 +330,44 @@ describe('the daemon\'s shape', () => {
expect(wrong, 'The core calls services only through CorePorts, and is handed the socket\'s pieces as dependencies (src/core/AGENTS.md).').toEqual([])
})
+ it('the core imports nothing of the Swarm\'s, not even its types: its code is loaded only while it is on', () => {
+ // Dee's rule (v1's last item): the daemon core stays small and reliable, and the Swarm is a subsystem that can be
+ // switched off. What the core needs of it is in core/api.ts; what the Swarm runs in the core's process is
+ // handed in by the core's entry from its doors, imported dynamically and only while the Swarm is on.
+ const wrong = importsIn('core').filter(({ from }) => /(^|\/)superTabs\//.test(from) || /(^|\/)lib\/swarm/.test(from))
+ .map(({ file, from }) => `${file} imports ${from}`)
+ expect(wrong, 'Declare what the core needs of the Swarm in core/api.ts, and hand its code in from superTabs/inCore.ts.').toEqual([])
+ const main = importsFor('core/main.ts', readFileSync(join(SRC, 'core', 'main.ts'), 'utf8')).filter(({ from }) => /(^|\/)superTabs\//.test(from))
+ expect(main).toEqual([{ from: '../superTabs/inCore.js', dynamic: true }, { from: '../superTabs/inServices.js', dynamic: true }])
+ expect(followed('core/main.ts', 'superTabs/inCore.ts', true)).toBe(false)
+ expect(followed('core/main.ts', 'superTabs/inCore.ts', false)).toBe(true)
+ expect(followed('services/models.ts', 'superTabs/inServices.ts', true)).toBe(true)
+ }, WALK_TIMEOUT_MS)
+
+ // The review of #1765: with the Swarm off, every core still loaded its skills through the registry, and with every
+ // service in the core's process (`HARNESSD_SERVICES=none`) its retention, observers and grid code, and the agent cleanup
+ // kept its members. Every import of its code from outside it is now a door, and no process's start reaches it.
+ it('with the Swarm off no process loads its code, imports included: its code is reached only through its doors', () => {
+ const resolveFrom = (file: string, from: string): string => {
+ const base = resolve(dirname(join(SRC, file)), from)
+ return relative(SRC, [base.replace(/\.js$/, '.ts'), `${base}.ts`, join(base, 'index.ts')].find((candidate) => { try { return statSync(candidate).isFile() } catch { return false } }) ?? base)
+ }
+ const sources = (dir: string): string[] => readdirSync(join(SRC, dir), { withFileTypes: true }).flatMap((entry) => entry.isDirectory()
+ ? sources(join(dir, entry.name)) : /\.ts$/.test(entry.name) && !/\.(spec|test|e2e)\.ts$/.test(entry.name) ? [join(dir, entry.name)] : [])
+ const outside = sources('.').filter((file) => !isSwarmCode(file) && !file.startsWith('testing/'))
+ const doors = outside.flatMap((file) => importsFor(file, readFileSync(join(SRC, file), 'utf8'))
+ .map(({ from, dynamic }) => ({ file, target: resolveFrom(file, from), dynamic })).filter(({ target }) => isSwarmCode(target)))
+ expect(doors.filter(({ file, target, dynamic }) => !dynamic || !SWARM_DOORS[file]?.includes(target)).map(({ file, target }) => `${file} imports ${target}`),
+ 'Hand the Swarm\'s code in through superTabs/inCore.ts or superTabs/inServices.ts, loaded only while it is on.').toEqual([])
+ expect(doors.map(({ file, target }) => `${file} → ${target}`).sort()).toEqual(Object.entries(SWARM_DOORS).flatMap(([file, targets]) => targets.map((target) => `${file} → ${target}`)).sort())
+ // The core (normal and inline), the master, the services' process and each service: none reaches the Swarm's code.
+ const entries = ['coreProcess.ts', 'leanCoreEntry.ts', 'core/main.ts', 'services/inline.ts', 'leanEntry.ts', 'masterProcess.ts', 'serviceProcess.ts',
+ ...sources('services').filter((file) => /Process\.ts$/.test(file) && !isSwarmCode(file))]
+ for (const entry of entries) expect([...closureOf(entry).keys()].filter(isSwarmCode), entry).toEqual([])
+ // The Swarm's own entries do reach it: the walk passes over a door, and only a door.
+ expect([...closureOf('superTabs/inServices.ts').keys()].filter(isSwarmCode).length).toBeGreaterThan(5)
+ }, WALK_TIMEOUT_MS)
+
it('live transcript coordination depends on engine contracts, with neutral folding mechanics', () => {
const owners = new Set(['core/transcripts/attach.ts', 'core/transcripts/ingest.ts', 'core/transcripts/normalizers.ts'])
const wrong = importsIn('core').filter(({ file, from, typeOnly }) => owners.has(file) && !typeOnly
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index c327016f9..5709098a6 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -408,7 +408,7 @@ export class DaemonCableHost implements CableHost {
}
}
- /** The Swarm cards the core last handed the devices; a device that attaches later is shown them (core/superTabCards.ts replays). */
+ /** The Swarm cards the core last handed the devices; a device that attaches later is shown them (superTabs/inCore/cards.ts replays). */
private cards: SwarmCard[] = []
setSwarmCards(items: SwarmCard[]): void {
@@ -985,7 +985,7 @@ export function cableQuestionFor(
const requestId = frame.payload?.requestId
const questions = frame.payload?.questions
if (typeof requestId !== 'string' || !requestId || !Array.isArray(questions)) return null
- // A Super Tab member waiting on a person (core/superTabAttention.ts): the tab's name and what it needs ride along.
+ // A Super Tab member waiting on a person (superTabs/inCore/attention.ts): the tab's name and what it needs ride along.
const superTab = frame.payload?.superTab, attention = frame.payload?.attention
const tab = typeof superTab === 'string' && superTab && (attention === 'decision' || attention === 'stuck') ? { superTab, attention } as SuperTabAsk : null
return { agentId: frame.agentId, requestId, questions, ...(tab ? { superTab: tab } : {}) }
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index efb04ab5d..7dce3b577 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -287,7 +287,7 @@ export interface AppSwarms {
/** Why the list is as short as it is. The dial renders this, instead of drawing an empty wheel. */
export type CableMachineSource = 'backend' | 'local' | 'signed-out'
/**
- * What a Super Tab member's wait adds to its `question` (core/superTabAttention.ts): the tab's name and whether it needs a
+ * What a Super Tab member's wait adds to its `question` (superTabs/inCore/attention.ts): the tab's name and whether it needs a
* decision or is stuck. The Harness Pro makes it an alert whose toast stays; firmware without it, and the round dial,
* read the words alone. Nobody answers it on a device.
*/
@@ -335,7 +335,7 @@ export interface CableHost {
listSwarms(): { selected: string; swarms: CableSwarm[]; tiles: CableTile[] }
/** The dial picked a swarm. Relayed to the window, which switches and re-describes its desk. */
selectSwarm(swarmId: string): void
- /** The Swarm cards the core last told the devices (core/superTabCards.ts); empty until it has. */
+ /** The Swarm cards the core last told the devices (superTabs/inCore/cards.ts); empty until it has. */
swarmCards?(): SwarmCard[]
/** A device that speaks `swarmCard: 'v1'` is attached (true) or gone (false): the core starts or stops reading the Swarms. */
swarmCardsWanted?(on: boolean): void
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 775366ed2..0ab1fc326 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2641,8 +2641,6 @@ async function logsExportCommand(json: boolean): Promise<void> {
}
import { orchestratorCommand } from './orchestrator/command.js'
-import { superTabCommand } from './superTabs/command.js'
-import { gitCredentialCommand } from './superTabs/gitCredential.js'
import { paneOwner, sendCommand } from './messages/command.js'
import { agentOrigin, closeCommand, psCommand, replyCommand, showCommand, tellCommand, waitCommand, whoamiCommand } from './agentClient/commands.js'
import { agentsHelp, helpFor } from './agentClient/help.js'
@@ -2726,12 +2724,14 @@ switch (cmd) {
case 'orchestrator':
orchestratorCommand(rest).then(code => { process.exitCode = code }).catch(onError)
break
+ // The Swarm's commands are loaded only when run: started from the sources, every daemon process runs this file, and
+ // with the Swarm off (`HARNESS_SWARM`) none of them loads its code (src/architecture.spec.ts).
case 'super-tab':
- superTabCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ import('./superTabs/command.js').then(({ superTabCommand }) => superTabCommand(rest)).then(code => { process.exitCode = code }).catch(onError)
break
case 'git-credential':
// git's credential helper in a Swarm agent's session (docs/swarm-github-app.md); git runs it, people do not.
- gitCredentialCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ import('./superTabs/gitCredential.js').then(({ gitCredentialCommand }) => gitCredentialCommand(rest)).then(code => { process.exitCode = code }).catch(onError)
break
case 'login': {
// The result line goes out FIRST (loginCommand prints it), then the daemon is swapped onto the
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index 1f4407a42..c98be691e 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -17,7 +17,16 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
attach that read an 803 MB transcript whole.
5. **100% coverage, per file** (`npm run test:core`), and an end-to-end test (`../../e2e/`) for any
behaviour a person can see. The end-to-end suite has found every race fixed here so far: run it.
-6. **Evidence must be newer than the state it contradicts.** A scan, probe or read that began before
+6. **The Swarm is a subsystem the core runs without.** `HARNESS_SWARM=off` (harnessd/swarmSwitch.ts, on by default)
+ leaves the Super Tab service off and loads none of the Swarm's code, in the core or any service. So no core file
+ imports anything of `../superTabs/` or `../lib/swarm*`, not even types. What the core needs of it is typed in
+ `api.ts` (`SuperTabsCore`, `SuperTabsPort`, `SwarmAgents`, `SwarmLaunch`, `AdoptSwarmSkill`) and handed in by
+ `main.ts` from `../superTabs/inCore.ts`; the services that act on it get their side from `../superTabs/inServices.ts`
+ (`serviceProcess.ts`, or `main.ts` when they run here). Both are imported dynamically and only while it is on.
+ Every such dependency is optional, and absent is exactly the daemon without the Swarm. `src/architecture.spec.ts`
+ holds every import of its code to those doors and walks each process's imports; `src/leanEntry.spec.ts` checks the
+ shipped build, and `e2e/swarmSwitch.e2e.ts` what each process loads.
+7. **Evidence must be newer than the state it contradicts.** A scan, probe or read that began before
a change must not be used to undo that change (see `terminalAgentReconciler.ts` `probedAs`,
`routeTouched`, and `transcripts/relaunch.ts`). Most of the races found end to end were this.
@@ -54,7 +63,10 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
master is too old to run it, still in its own process.
- `stall.ts`: a test-only fault that holds the core's event loop still (`HARNESSD_TEST_FAULTS=core.stall:…`).
- `main.ts`: the core's entry (`harness __run`) and composition root, `runForeground`: it builds these
- modules, starts the services through `serviceHost` and wires the socket. The one core file that imports
+ modules, starts the services through `serviceHost` and wires the socket. While the Swarm is on it loads the Swarm's
+ side of this process from `../superTabs/inCore.ts` (and `../superTabs/inServices.ts` for the services that act on it,
+ when they run here) and hands it to the modules that take it; off, it leaves the
+ Super Tab service off (`serviceHost.leaveOff`), whose requests are then answered `SERVICE_UNAVAILABLE`. The one core file that imports
services and the socket, and the one outside the 100% coverage: wiring only, run end to end. The
services that run in their own processes by default it imports only dynamically, through
`../services/inline.ts`, and only when one runs in this process instead.
diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.ts
index 0f119cfbf..251d6a133 100644
--- a/cli/src/core/agents/close.ts
+++ b/cli/src/core/agents/close.ts
@@ -35,7 +35,7 @@ export interface ClosingDeps {
engineReady: (engine: string, ms: number) => Promise<void>
/** The agents stopped and kept: a close of one already closed is answered closed. */
stoppedAgents?: Pick<StoppedAgentStore, 'get' | 'resumeReservedAt'>
- /** Whether the agent may be the Lead of an active Swarm project: never closed (superTabs/retention.ts `mayBeLead`). */
+ /** Whether the agent may be a Lead, which is never closed, as core/main.ts hands it in; absent, none is. */
leadProtected?: (agentId: string) => boolean
}
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index 1d4e64022..4ef7d5b5a 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -28,6 +28,7 @@ import { NativeFiles } from '../../engines/kit/nativeFiles.js'
import { agentLaunchArgs } from '../../lib/agentAttribution.js'
import { WindowsBatchLaunchRefused } from '../../lib/windows/launch.js'
import { swarmGitHubLaunch } from '../../lib/swarmGitHub.js'
+import { SWARM_LAUNCH } from '../../superTabs/inCore/launch.js'
vi.mock('../../lib/projectFolder.js', async real => {
const actual = await real<typeof import('../../lib/projectFolder.js')>()
@@ -153,6 +154,7 @@ function setup(over: Partial<CreateAgentDeps> = {}) {
gridSetup: vi.fn(() => vi.fn(async () => ({}))) as never,
privateGridName: vi.fn(async () => 'grid-me'),
dshLaunch: { launch: launchDsh, materialize: async () => ({ ok: true, ...await materializeWorkspace() }) },
+ swarmLaunch: SWARM_LAUNCH,
...over,
}
return { deps, create: createAgentCreator(deps) }
@@ -261,6 +263,19 @@ describe('creating an agent', () => {
expect(createAndRegisterPane).not.toHaveBeenCalled()
})
+ // HARNESS_SWARM=off: the core holds none of the Swarm's launch code, so a start that asks for a Swarm role is
+ // refused before anything is written or launched, and every other start is as it was.
+ it('refuses a Swarm role while the Swarm is off, before opening a pane, and starts everything else as before', async () => {
+ acceptFullMode.mockClear()
+ const off = setup({ swarmLaunch: undefined })
+ expect(await off.create(request({ cwd: folder(), swarmRole: 'dev' })))
+ .toEqual({ ok: false, error: 'SWARM_SKILL_FAILED', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ expect(acceptFullMode).not.toHaveBeenCalled()
+ expect(await off.create(request({ cwd: folder() }))).toMatchObject({ ok: true })
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0]![0]).not.toHaveProperty('swarmSkill')
+ })
+
it('refuses an unsafe Swarm runtime before opening a pane', async () => {
const cwd = folder(['.harness'])
expect(await setup().create(request({ cwd, swarmRole: 'dev' }))).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED' })
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index 299fdadb3..0c03c6b5a 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -1,5 +1,3 @@
-import { prepareSwarmSkill } from '../../lib/swarmSkills.js'
-import { swarmGitHubLaunch } from '../../lib/swarmGitHub.js'
import type { NativeLaunch, NativeLaunchResult, NativeLaunchSource } from '../../engines/nativeLaunch.js'
/**
* Creating an agent (`agent_create`): open a fresh pane running the chosen engine in the chosen
@@ -13,7 +11,7 @@ import { realpathSync, statSync } from 'node:fs'
import { readdir } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import type { BackendSocket } from '../../backendSocket.js'
-import type { ModelsPort } from '../api.js'
+import type { ModelsPort, SwarmLaunch } from '../api.js'
import { MODEL_MANAGER_ID } from '../../dsh/builtinIds.js'
import { installedDsh } from '../../dsh/installed.js'
import { harnessEnvToClear, type DshAccount } from '../../dsh/launch.js'
@@ -99,17 +97,20 @@ export interface CreateAgentDeps {
/** In the Harness Team account, for an engine it has not signed in itself: the owner's subscription through the
* owner's relay (team/relay.ts `teamRelayLaunch`), null otherwise. Absent ⇒ never. */
ownerRelay?: (engine: AgentEngine) => Promise<{ env: Record<string, string>; args: string[] } | null>
+ /** The Swarm's part of a start with a Swarm role (superTabs/inCore/launch.ts); absent while the Swarm is off. */
+ swarmLaunch?: SwarmLaunch
}
export function createAgentCreator({
native: inspectNative, publishConfig, createBackend: initialBackend, recoverBackend, noBackendCode = 'TMUX_UNAVAILABLE', registry, externalResume, watchNewPane, announceSession, attachDsh,
prepareApiTools, hookPort, hooksDisabled, installOpencodePlugin, gridLaunchMachine, buildGridLaunch, terminalHintMachineName, blocksFolder,
- gridSetup, privateGridName, dshLaunch, ownerRelay,
+ gridSetup, privateGridName, dshLaunch, ownerRelay, swarmLaunch,
}: CreateAgentDeps) {
const prepare = async (input: Parameters<CreateAgent>[0], authority: LaunchAuthority, context?: { local: boolean }): Promise<LaunchPreparation<Awaited<ReturnType<CreateAgent>>>> => {
if (input.resumeSessionId) return { ok: true, dispatch: () => externalResume(input) }
const stale = () => ({ ok: false as const, error: 'LAUNCH_AUTHORITY_CHANGED', unavailable: 'launch', detail: 'Waiting for the original launch request’s authority.' })
if (!authority.current()) return stale()
+ if (input.swarmRole && !swarmLaunch) return { ok: false, error: 'SWARM_SKILL_FAILED', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' }
let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord, startedBy, parentAgentId, launchModel } = input
let createBackend = initialBackend
if (!createBackend && recoverBackend) {
@@ -346,9 +347,9 @@ export function createAgentCreator({
// is supposed to use exactly these variables.
// Another person's project work (superTabs/start.ts): git and gh use the Harness GitHub App's token for the task,
// never this machine owner's own GitHub login (lib/swarmGitHub.ts). Kept on the row's skill, so a relaunch keeps it.
- let swarmGitHub: ReturnType<typeof swarmGitHubLaunch> = null
- if (input.swarmRole && input.swarmGitHub) {
- try { swarmGitHub = swarmGitHubLaunch(label) }
+ let swarmGitHub: ReturnType<SwarmLaunch['github']> = null
+ if (swarmLaunch && input.swarmRole && input.swarmGitHub) {
+ try { swarmGitHub = swarmLaunch.github(label) }
catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }
}
const clearEnv = [...(gridLaunch ? gridConflictingEnvToClear(gridLaunch) : []), ...harnessEnvToClear(dshEnv), ...swarmGitHub?.clearEnv ?? []]
@@ -361,8 +362,8 @@ export function createAgentCreator({
const swarmSkill = input.swarmRole ? { role: input.swarmRole, key: label, ...(input.swarmSkillMode ? { mode: input.swarmSkillMode } : {}),
...(swarmGitHub ? { github: true as const } : {}) } : undefined
let swarmInstructions: string | undefined
- if (swarmSkill) {
- try { swarmInstructions = prepareSwarmSkill(cwd, swarmSkill).instructions }
+ if (swarmLaunch && swarmSkill) {
+ try { swarmInstructions = swarmLaunch.prepare(cwd, swarmSkill).instructions }
catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }
}
const told = agentLaunchArgs(engine, startedBy, { cwd, profile: codexHome, environment: native?.environment, ...(swarmInstructions ? { swarmInstructions } : {}) })
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 55308ea64..3db57538c 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -17,6 +17,7 @@ import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from '..
import type { RegisteredSession } from '../../lib/registry.js'
import { createLaunchRequests, type CreateAgent, type ForkAgent, type LaunchRequestDeps, type RestartAgent, type ResumeAgent } from './launches.js'
import * as pendingLaunches from './pendingLaunches.js'
+import { SWARM_LAUNCH } from '../../superTabs/inCore/launch.js'
/**
* The requests that start an agent's process, answered by the core: every refusal before a pane exists,
@@ -91,6 +92,7 @@ function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: Creat
createAgent: () => create, forkAgent: () => fork, resumeAgent: () => resume, restartAgent: () => restart,
byAgent: (id) => known.get(id), toProject: vi.fn(async (s: RegisteredSession) => frameOf(s)),
modelTarget: resolveNewAgentModel,
+ swarmLaunch: SWARM_LAUNCH,
...over,
}
const requests = createLaunchRequests(deps)
@@ -304,6 +306,17 @@ describe('agent_create, refused before any pane exists', () => {
expect(vi.mocked(create!).mock.calls).toHaveLength(calls)
})
+ // HARNESS_SWARM=off: nothing of the Swarm's is asked of a launch, and a start that asks for it is refused at the wire.
+ it('refuses every Swarm field while the Swarm is off, before dispatch, and starts everything else as before', async () => {
+ const { ask, create } = setup({ swarmLaunch: undefined })
+ for (const payload of [{ swarmRole: 'dev' }, { swarmSkillMode: 'default' }, { swarmGitHub: true }, { swarmRole: 'lead', swarmSkillMode: 'orchestration', swarmGitHub: true }]) {
+ expect(await ask({ engine: 'claude', cwd: '/w', ...payload })).toStrictEqual({ error: 'INVALID_SWARM_ROLE', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' })
+ }
+ expect(create).not.toHaveBeenCalled()
+ await ask({ engine: 'claude', cwd: '/w', swarmRole: null })
+ expect(vi.mocked(create!).mock.calls.at(-1)![0]).not.toHaveProperty('swarmRole')
+ })
+
it('a first prompt that is not text, too long, or for an engine that cannot take one', async () => {
const { ask, create } = setup()
expect(await ask({ engine: 'claude', cwd: '/w', prompt: 7 })).toStrictEqual({ error: 'INVALID_PROMPT', detail: 'prompt must be a string' })
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 85df23634..87028681c 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -12,7 +12,7 @@ import { readdir, rmdir } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, isAbsolute } from 'node:path'
import type { BackendSocket } from '../../backendSocket.js'
-import type { Asker } from '../api.js'
+import type { Asker, SwarmLaunch } from '../api.js'
import { installedDsh } from '../../dsh/installed.js'
import { DSH_ID_RE, dshSupportedEngines } from '../../dsh/manifest.js'
import { folderTrust } from '../../engines/launchPrep.js'
@@ -22,7 +22,6 @@ import { ENGINES, isTerminalEngine, type AgentEngine } from '../../engines/types
import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationOutcome, type AgentCreationReceipts, type AgentCreationStatus, type CreationAuthority } from '../../lib/agentCreationReceipt.js'
import type { AgentFrame } from '../../lib/agentFrame.js'
import { engineLabel } from '../../lib/agentNames.js'
-import { isSwarmRole, isSwarmSkillMode } from '../../lib/swarmSkills.js'
import {
AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves,
permissionModeFlags, supportsFirstPrompt, supportsNamedAgent, unsupportedLaunchModelFlag,
@@ -75,12 +74,14 @@ export interface LaunchRequestDeps {
modelTarget: (selection: NewAgentModel) => Promise<GridLaunchOverride | null>
/** A guest's New Harness, as the guest's own OS user (core/agents/guestCreate.ts); null where there is none. */
guestCreate?: () => GuestCreate | null
+ /** Which Swarm roles and skill modes a start may ask for (superTabs/inCore/launch.ts); absent while the Swarm is off. */
+ swarmLaunch?: Pick<SwarmLaunch, 'role' | 'mode'>
}
type Reply = (result: Record<string, unknown>) => void
type CreateInput = Parameters<CreateAgent>[0]
-export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget, guestCreate }: LaunchRequestDeps) {
+export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget, guestCreate, swarmLaunch }: LaunchRequestDeps) {
const validateInstalled = async (input: CreateInput, known?: ReturnType<typeof installedDsh>): Promise<{ error: string; detail: string } | null> => {
if (input.dsh) {
const installed = known ?? installedDsh(input.dsh)
@@ -407,13 +408,17 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
prompt = trimmed || null
}
const swarmRole = payload.swarmRole
+ if (!swarmLaunch && ((swarmRole !== undefined && swarmRole !== null) || payload.swarmSkillMode !== undefined || payload.swarmGitHub !== undefined)) {
+ reply({ error: 'INVALID_SWARM_ROLE', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' }); return
+ }
+ const isSwarmRole = (value: unknown): value is NonNullable<CreateInput['swarmRole']> => !!swarmLaunch?.role(value)
if (swarmRole !== undefined && swarmRole !== null &&
(!isSwarmRole(swarmRole) || (engine !== 'claude' && engine !== 'codex'))) {
reply({ error: 'INVALID_SWARM_ROLE', detail: 'A Swarm role is lead, dev or review, for Claude Code or Codex.' }); return
}
// The skills of the project the agent joins (superTabs/start.ts); a start from before modes sends none.
const swarmSkillMode = payload.swarmSkillMode
- if (swarmSkillMode !== undefined && !isSwarmSkillMode(swarmSkillMode)) {
+ if (swarmSkillMode !== undefined && !swarmLaunch?.mode(swarmSkillMode)) {
reply({ error: 'INVALID_SWARM_ROLE', detail: 'A Swarm skill mode is default or orchestration.' }); return
}
// Another person's project work: git and gh use the Harness GitHub App's token for the task (lib/swarmGitHub.ts).
diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.ts
index 32b6b2289..922617fc9 100644
--- a/cli/src/core/agents/lifecycle.ts
+++ b/cli/src/core/agents/lifecycle.ts
@@ -61,7 +61,7 @@ export interface LifecycleDeps {
stopped?: (agentId: string) => void
/** An agent a move a dead daemon left may still run beside (main.ts `moveHeld`): no engine of it starts this start. */
moveHeld?: (agentId: string) => boolean
- /** Whether the agent is the Lead of an active Swarm project here (superTabs/retention.ts `retainedLeads`). */
+ /** Whether the agent is a Lead the core must never stop, as core/main.ts hands it in; absent, none is. */
leadProtected?: (agentId: string) => boolean
}
diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.ts
index 7ad4e6f22..4bddc2c99 100644
--- a/cli/src/core/agents/restart.spec.ts
+++ b/cli/src/core/agents/restart.spec.ts
@@ -11,7 +11,7 @@ import { processLaunchArgs } from '../../lib/processTable.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import { createAgentRestarter, type RestartDeps } from './restart.js'
import { createLaunchAuthority } from './launchAuthority.js'
-import { createSwarmSkillAdoption } from './swarmSkills.js'
+import { createSwarmSkillAdoption } from '../../superTabs/inCore/adoption.js'
import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'
import { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.ts
index 4750025c0..bb9accec1 100644
--- a/cli/src/core/agents/restart.ts
+++ b/cli/src/core/agents/restart.ts
@@ -3,7 +3,7 @@
*
* Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).
*/
-import type { AdoptSwarmSkill } from './swarmSkills.js'
+import type { AdoptSwarmSkill } from '../api.js'
import { homedir } from 'node:os'
import { isTerminalEngine, type AgentEngine } from '../../engines/types.js'
import { engineBin, enginePathOverride } from '../../lib/engineBin.js'
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index e367c79d9..679445da0 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'
-import { CLOUD_DOWN, CLOUD_FALLBACKS, CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, accountIdentity, AGENT_ACTIONS_OFF, AGENT_CLEANUP_FALLBACKS, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, STORE_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, RECAPS_FALLBACKS, resolveAgent, SHARED_MACHINES_FALLBACKS, SHARED_MACHINES_OFF, SHARING_FALLBACKS, MESSAGES_FALLBACKS, TAB_KEY_OFF, TAB_RELAY_OFF, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'
+import { CLOUD_DOWN, CLOUD_FALLBACKS, CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, accountIdentity, AGENT_ACTIONS_OFF, AGENT_CLEANUP_FALLBACKS, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, STORE_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, RECAPS_FALLBACKS, resolveAgent, SHARED_MACHINES_FALLBACKS, SHARED_MACHINES_OFF, SHARING_FALLBACKS, MESSAGES_FALLBACKS, TAB_KEY_OFF, TAB_RELAY_OFF, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps, type SwarmAgentDeps } from './api.js'
import { FAIL, readFallback } from './serviceHost.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
@@ -9,127 +9,20 @@ describe('the core API services stand on', () => {
it('allows a bounded batch of GitHub reads to finish outside the core', () => {
expect(LONG_ANSWERS.projects).toEqual({ git_pull_requests_status: 120_000 })
})
- it('closes only the original Swarm-started native session and treats an absent session as gone', async () => {
- const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', expiresAt: Date.now() + 120_000, createdAt: new Date(1000).toISOString() }
- const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const }
- const deps = coreDeps(), byAgent = vi.fn(() => session as RegisteredSession | undefined)
- const closeAgent = vi.fn(async () => ({ closed: true as const }))
- const creationStatus = vi.fn(async () => ({ creationId: request.creationId, state: 'created' as const, agentId: 'worker' }))
- const core = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent } as CoreApiDeps['registry'], closeAgent, creationStatus })
- expect(await core.agents.closeSwarm!(request)).toEqual({ closed: true })
- expect(closeAgent).toHaveBeenCalledWith({ agentId: 'worker', sessionId: 'native', createdAt: request.createdAt, mode: 'now', onlyIfOriginalLaunch: true, expiresAt: request.expiresAt })
- closeAgent.mockClear()
- byAgent.mockReturnValue({ ...session, startedBy: undefined })
- expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: 'NOT_SWARM_STARTED' })
- byAgent.mockReturnValue({ ...session, registeredAt: 2000 })
- expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: 'AGENT_CHANGED' })
- byAgent.mockReturnValue({ ...session, sessionId: 'replacement' })
- expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: 'AGENT_CHANGED' })
- byAgent.mockReturnValue(session)
- creationStatus.mockResolvedValueOnce({ creationId: request.creationId, state: 'created', agentId: 'other' })
- expect(await core.agents.closeSwarm!(request)).toMatchObject({ error: 'NOT_SWARM_STARTED' })
- expect(closeAgent).not.toHaveBeenCalled()
- const withoutCreation = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent } as CoreApiDeps['registry'], closeAgent })
- expect(await withoutCreation.agents.closeSwarm!(request)).toEqual({ error: 'NOT_SWARM_STARTED' })
- const noLifecycle = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent } as CoreApiDeps['registry'], creationStatus })
- expect(await noLifecycle.agents.closeSwarm!(request)).toEqual({ error: 'UNSUPPORTED' })
- for (const partial of [{ agentId: 'worker' }, { ...request, creationId: '' }, { ...request, sessionId: undefined }, { ...request, createdAt: undefined }]) {
- expect(await core.agents.closeSwarm!(partial)).toEqual({ error: 'NOT_SWARM_STARTED' })
- }
- byAgent.mockReturnValue(undefined)
- expect(await core.agents.closeSwarm!({ agentId: 'worker' })).toEqual({ closed: true })
- })
-
- // A machine restart stops Swarm sessions; reopened, each keeps its harness, conversation and registeredAt but is marked
- // resume-only. On 2026-10-23 such a worker could no longer be stopped by the Swarm ("not started by the Swarm").
- it('closes a Swarm session reopened on its own conversation, and refuses one whose conversation changed during the lookup', async () => {
- const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', expiresAt: Date.now() + 120_000, createdAt: new Date(1000).toISOString() }
- const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const, resumeOnly: true as const }
- const deps = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))
- const creationStatus = vi.fn(async () => ({ creationId: request.creationId, state: 'created' as const, agentId: 'worker' }))
- const core = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent: () => session } as CoreApiDeps['registry'], closeAgent, creationStatus })
- expect(await core.agents.closeSwarm!(request)).toEqual({ closed: true })
- expect(closeAgent).toHaveBeenCalledOnce()
- closeAgent.mockClear()
- creationStatus.mockImplementationOnce(async () => {
- session.sessionId = 'personal-resume'
- return { creationId: request.creationId, state: 'created' as const, agentId: 'worker' }
- })
- expect(await core.agents.closeSwarm!(request)).toEqual({ error: 'AGENT_CHANGED' })
- expect(closeAgent).not.toHaveBeenCalled()
- })
-
- // The Super Tab host keeps a Swarm Lead alive and closes the sessions its backend ends (owner, 2026-10-23). The core
- // decides what a service may do: reopen only a stopped Lead the host's retention names, close only a member it names.
- it('reopens only a stopped Swarm Lead, and says a live one is up', async () => {
- const deps = coreDeps(), resumeAgent = vi.fn(async () => ({ ok: true as const, session: row('stopped'), resumed: true }))
- const leads = vi.fn(() => new Set(['stopped', 'live']))
- const core = createCoreApi({ ...deps, resumeAgent, swarmMembers: { leads, harnesses: () => new Set() } })
- expect(await core.agents.keepLeadAlive!('stopped')).toEqual({ ok: true })
- expect(resumeAgent).toHaveBeenCalledWith('stopped')
- expect(await core.agents.keepLeadAlive!('live')).toEqual({ ok: true })
- leads.mockReturnValue(new Set(['live']))
- expect(await core.agents.keepLeadAlive!('stopped')).toEqual({ ok: false, error: 'NOT_A_LEAD', detail: 'Only a stopped Product Manager of a Swarm project is reopened.' })
- leads.mockReturnValue(new Set(['gone']))
- expect(await core.agents.keepLeadAlive!('gone')).toMatchObject({ ok: false, error: 'NOT_A_LEAD' })
- expect(resumeAgent).toHaveBeenCalledTimes(1)
- leads.mockReturnValue(new Set(['stopped']))
- resumeAgent.mockResolvedValueOnce({ ok: false, error: 'AGENT_BUSY', detail: 'busy' } as never)
- expect(await core.agents.keepLeadAlive!('stopped')).toEqual({ ok: false, error: 'AGENT_BUSY', detail: 'busy' })
- resumeAgent.mockResolvedValueOnce({ ok: false, error: 'RESUME_FAILED' } as never)
- expect(await core.agents.keepLeadAlive!('stopped')).toEqual({ ok: false, error: 'RESUME_FAILED' })
- expect(await createCoreApi(deps).agents.keepLeadAlive!('stopped')).toEqual({ ok: false, error: 'UNSUPPORTED' })
- })
-
- it('closes now only a Super Tab member the host retains, and treats an absent one as closed', async () => {
- const base = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))
- const deps = { ...base, registry: { ...base.registry, byAgent: (id: string) => id === 'live' ? { ...row('live'), registeredAt: 1000 } : undefined } as CoreApiDeps['registry'] }
- const harnesses = vi.fn(() => new Set(['live']))
- const core = createCoreApi({ ...deps, closeAgent, swarmMembers: { leads: () => new Set(), harnesses } })
- expect(await core.agents.closeMember!('live')).toEqual({ closed: true })
- expect(closeAgent).toHaveBeenCalledWith({ agentId: 'live', sessionId: 's-live', createdAt: new Date(1000).toISOString(), mode: 'now' })
- expect(await core.agents.closeMember!('absent')).toEqual({ closed: true })
- harnesses.mockReturnValue(new Set())
- expect(await core.agents.closeMember!('live')).toEqual({ error: 'NOT_A_MEMBER' })
- harnesses.mockImplementation(() => { throw new Error('Super Tab retention is unreadable.') })
- expect(await core.agents.closeMember!('live')).toEqual({ error: 'NOT_A_MEMBER' })
- expect(closeAgent).toHaveBeenCalledTimes(1)
- expect(await createCoreApi({ ...deps, closeAgent }).agents.closeMember!('live')).toEqual({ error: 'UNSUPPORTED' })
- expect(await createCoreApi({ ...deps, swarmMembers: { leads: () => new Set(), harnesses: () => new Set(['live']) } }).agents.closeMember!('live')).toEqual({ error: 'UNSUPPORTED' })
- })
-
- // The review of #1635: an agent removed before its host wrote a roster naming it is no member there; the exact receipt of
- // the Swarm's start proves it is the Swarm's own to close, and a receipt naming another harness proves nothing.
- it('closes a member the retention does not name only when its start receipt names it', async () => {
- const base = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))
- const creationStatus = vi.fn(async (creationId: string) => ({ creationId, state: 'created' as const, agentId: 'live' }))
- const deps = { ...base, closeAgent, creationStatus, swarmMembers: { leads: () => new Set<string>(), harnesses: () => new Set<string>() },
- registry: { ...base.registry, byAgent: (id: string) => id === 'live' ? { ...row('live'), registeredAt: 1000 } : undefined } as CoreApiDeps['registry'] }
- const core = createCoreApi(deps)
- expect(await core.agents.closeMember!('live')).toEqual({ error: 'NOT_A_MEMBER' })
- expect(await core.agents.closeMember!('live', 'super-start')).toEqual({ closed: true })
- expect(creationStatus).toHaveBeenCalledWith('super-start')
- creationStatus.mockResolvedValueOnce({ creationId: 'super-start', state: 'created', agentId: 'another' })
- expect(await core.agents.closeMember!('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })
- creationStatus.mockResolvedValueOnce(null as never)
- expect(await core.agents.closeMember!('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })
- expect(await createCoreApi({ ...deps, creationStatus: undefined }).agents.closeMember!('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })
- expect(closeAgent).toHaveBeenCalledTimes(1)
- })
-
- it('refuses missing or expired close leases, including expiry during the creation lookup', async () => {
- let now = 1000
- const clock = vi.spyOn(Date, 'now').mockImplementation(() => now)
- try {
- const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', createdAt: new Date(1000).toISOString(), expiresAt: 1100 }
- const deps = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const }))
- const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const }
- const creationStatus = vi.fn(async () => { now = 1200; return { creationId: request.creationId, state: 'created' as const, agentId: 'worker' } })
- const core = createCoreApi({ ...deps, registry: { ...deps.registry, byAgent: () => session } as CoreApiDeps['registry'], closeAgent, creationStatus })
- for (const expiresAt of [undefined, NaN, 999]) expect(await core.agents.closeSwarm!({ ...request, expiresAt })).toEqual({ error: 'STOP_LEASE_EXPIRED' })
- expect(await core.agents.closeSwarm!(request)).toEqual({ error: 'STOP_LEASE_EXPIRED' })
- expect(closeAgent).not.toHaveBeenCalled()
- } finally { clock.mockRestore() }
+ // The Swarm decides which of its agents it may close or reopen (superTabs/inCore/agents.ts); the core hands it what it
+ // reads them by, and has none of those members while the Swarm is off.
+ it('offers the Swarm\'s agent members only when handed them, built on the core\'s own registry, receipts, close and resume', async () => {
+ const deps = coreDeps(), closeAgent = vi.fn(async () => ({ closed: true as const })), resumeAgent = vi.fn(async () => ({ ok: true as const }))
+ const creationStatus = vi.fn(async () => null)
+ const off = createCoreApi(deps).agents
+ expect([off.closeSwarm, off.keepLeadAlive, off.closeMember]).toEqual([undefined, undefined, undefined])
+ const swarm = { closeSwarm: vi.fn(async () => ({ closed: true as const })), keepLeadAlive: vi.fn(async () => ({ ok: true as const })), closeMember: vi.fn(async () => ({ closed: true as const })) }
+ let given: SwarmAgentDeps | null = null
+ const on = createCoreApi({ ...deps, closeAgent, resumeAgent, creationStatus, swarmAgents: (agentDeps) => { given = agentDeps; return swarm } }).agents
+ expect([on.closeSwarm, on.keepLeadAlive, on.closeMember]).toEqual([swarm.closeSwarm, swarm.keepLeadAlive, swarm.closeMember])
+ expect(given!.byAgent('live')).toEqual(row('live'))
+ expect(given!.stoppedIds()).toEqual(['stopped'])
+ expect([given!.closeAgent, given!.resumeAgent, given!.creationStatus]).toEqual([closeAgent, resumeAgent, creationStatus])
})
it('exposes an optional native-turn observer without importing feature state', () => {
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index f17095ac2..9d5366a8f 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -23,7 +23,6 @@ import type { NativeTurnRead } from '../lib/nativeTurnObservations.js'
import type { ReviewedAnswer } from '../cable/questionInbox.js'
import type { AgentEngine } from '../engines/types.js'
import type { AppSwarms } from '../cable/cableSession.js'
-import type { LeadRecap, SwarmCard } from '../superTabs/cards.js'
import type { UnreadNotification } from '../lib/notificationRead.js'
import type { AutonomousDeviceAgent, AutonomousDeviceDelivery, AutonomousDeviceReceipt } from '../lib/autonomous-device/service.js'
import type { StoreAgent } from '../lib/autonomous-device/store.js'
@@ -1190,12 +1189,47 @@ export interface SuperTabAttention {
text: string
}
-/** The Super Tab service's door into the core (core/superTabAttention.ts): the waits of its members here. */
+/** What the core hands the Swarm's own close and reopen (superTabs/inCore/agents.ts): the live registry, the stopped
+ * records, and the core's close, resume and creation receipts. */
+export interface SwarmAgentDeps {
+ byAgent(agentId: string): RegisteredSession | undefined
+ stoppedIds(): string[]
+ closeAgent?: (request: AgentCloseRequest) => Promise<AgentCloseResult>
+ resumeAgent?: (agentId: string) => Promise<{ ok: true } | { ok: false; error: string; detail?: string }>
+ creationStatus?: (creationId: string) => Promise<CreationObservation | null>
+}
+export type SwarmAgents = Required<Pick<CoreApi['agents'], 'closeSwarm' | 'keepLeadAlive' | 'closeMember'>>
+
+type SwarmSkill = NonNullable<RegisteredSession['swarmSkill']>
+/** The Swarm's part of an agent's start (superTabs/inCore/launch.ts), handed to the launches while the Swarm is on: the
+ * roles and skill modes a start may ask for, the role's skill written into the project folder (what the engine is told
+ * to read), and the Harness GitHub App's git and gh for another person's project work (null where it has none). */
+export interface SwarmLaunch {
+ role(value: unknown): value is SwarmSkill['role']
+ mode(value: unknown): value is NonNullable<SwarmSkill['mode']>
+ prepare(cwd: string, skill: SwarmSkill): { instructions: string }
+ github(key: string): { env: Record<string, string>; clearEnv: string[] } | null
+}
+
+/** Fill a missing Swarm role of an older Swarm session at its restart or resume (superTabs/inCore/adoption.ts): the row
+ * to launch, or null when the launch is no longer this one's. Absent while the Swarm is off. */
+export type AdoptSwarmSkill = (session: RegisteredSession, current: () => boolean) => Promise<RegisteredSession | null>
+
+export type LeadState = 'ask' | 'stuck' | 'work' | 'done'
+/** One Swarm's Lead on a Harness Pro's card (superTabs/cards.ts). `order`: the project's index in the Swarm (the app's
+ * order), so a dial can show the Leads as the app does whatever their urgency. */
+export interface SwarmLead { id: string; projectId: string; project: string; engine: string; owner: string; local: string; state: LeadState; order: number; since?: number }
+/** One Swarm this account is in, as a Harness Pro's card: its Leads, most urgent first. */
+export interface SwarmCard { id: string; name: string; count: number; leads: SwarmLead[] }
+/** A Lead's last message, for its card. */
+export interface LeadRecap { tabId: string; leadId: string; text: string; at: number; none: boolean }
+
+/** The Super Tab service's door into the core (superTabs/inCore/attention.ts): the waits of its members here. */
export interface SuperTabsCore {
/** Every wait, replacing the last set: the core raises what is new on the devices and closes what is gone. */
attention(items: SuperTabAttention[]): void
/** Every Swarm this account is in, whole, each time it changes: the core keeps the last list for a dial that attaches
- * later and hands it to the devices (core/superTabCards.ts). */
+ * later and hands it to the devices (superTabs/inCore/cards.ts). */
cards(items: SwarmCard[]): void
/** What one Lead last said, pushed when the recap on a Harness Pro's screen moved on. */
cardRecap(recap: LeadRecap): void
@@ -1203,7 +1237,7 @@ export interface SuperTabsCore {
* state wakes it only as the core starts, so a machine that joined a Swarm while running never invited anyone and
* each member's pane read "must be online" (River on a contributed machine, 2026-10-23). */
shareObservers(): void
- /** A member's terminal as plain text for its Lead (core/superTabTerminal.ts): the visible screen, with up to 200 lines
+ /** A member's terminal as plain text for its Lead (superTabs/inCore/terminal.ts): the visible screen, with up to 200 lines
* of scrollback when asked, and what the screen reader says it waits on (a permission prompt, a question). */
screen(agentId: string, scrollback: number): Promise<SuperTabScreen>
/** Text, then each key by its tmux name, typed into a member's terminal under the pane's write lock. */
@@ -1285,7 +1319,7 @@ export interface DevicesPort {
desk(agentIds: string[], foreground: boolean): void
/** The window's tabs, or null once it has gone. */
swarms(swarms: AppSwarms | null): void
- /** The Swarms' cards for a Harness Pro (core/superTabCards.ts), whole; replayed to a dial that attaches. */
+ /** The Swarms' cards for a Harness Pro (superTabs/inCore/cards.ts), whole; replayed to a dial that attaches. */
swarmCards(items: SwarmCard[]): void
/** One Lead's last message, for the recap a Harness Pro has open. */
swarmCardRecap(recap: LeadRecap): void
@@ -1820,9 +1854,9 @@ export interface CoreApiDeps {
activityAt?: (session: RegisteredSession) => Promise<number | null>
/** A resume of a stopped agent (core/agents/lifecycle.ts `resumeAgent`), for `keepLeadAlive`. */
resumeAgent?: (agentId: string) => Promise<{ ok: true } | { ok: false; error: string; detail?: string }>
- /** The Swarm Leads and members this machine's Super Tab host keeps (superTabs/retention.ts), for `keepLeadAlive` and
- * `closeMember`; absent, neither does anything. */
- swarmMembers?: { leads(): Set<string>; harnesses(): Set<string> }
+ /** The Swarm's `closeSwarm`, `keepLeadAlive` and `closeMember` (superTabs/inCore/agents.ts), built on what the core
+ * reads its agents by; absent while the Swarm is off, and then the core offers none of them. */
+ swarmAgents?: (deps: SwarmAgentDeps) => SwarmAgents
signedIn: CoreApi['account']['signedIn']
environment: CoreApi['account']['environment']
machines: CoreApi['account']['machines']
@@ -1837,7 +1871,7 @@ export interface CoreApiDeps {
wifi: CoreApi['wifi']
/** The cloud agents' doors (core/agents/cloud.ts). */
cloud?: CloudCore
- /** The Super Tab service's door (core/superTabAttention.ts). */
+ /** The Super Tab service's door (superTabs/inCore/attention.ts). */
superTabs?: SuperTabsCore
/** The devices' way to the Super Tab service's card requests. */
superTabRequest?: CoreApi['superTabRequest']
@@ -1855,7 +1889,7 @@ export function createCoreApi({
dataDir, registry, stoppedAgents, databaseHistory, syncSession, runtimeModels, viewerChanged,
gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, observerKey, tabKey, tabRelay, connectorVault, observer, privateGridName, machineName, backend, onNotice,
runtimeProfile, setRuntime, fork, create, creationStatus, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, conversations = CONVERSATIONS_OFF, viewerFrame, machine, activityText, activitySnapshot, activity, summaries,
- closeAgent, activityAt, resumeAgent, swarmMembers,
+ closeAgent, activityAt, resumeAgent, swarmAgents,
signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, cloud, superTabs, superTabRequest, cloudRows, lastTurn, nativeTurns, turnCard, turnSummary,
log = (line) => console.warn(line),
}: CoreApiDeps): CoreApi {
@@ -1894,48 +1928,10 @@ export function createCoreApi({
activitySnapshot,
activity: activity ?? (async () => ({})),
summaries: summaries ?? (async () => ({})),
+ // The Swarm's own close and reopen (superTabs/inCore/agents.ts), handed in while it is on.
+ ...swarmAgents?.({ byAgent: id => registry.byAgent(id), stoppedIds: () => stoppedAgents.ids(), closeAgent, resumeAgent, creationStatus }),
// Decided here, not in the service: whatever the cleanup asks, from its process or this one, the core closes only
// a harness another agent started, the conversation it reviewed (`agent_close`'s identity), and keeps it.
- closeSwarm: async request => {
- const session = registry.byAgent(request.agentId)
- // This is the authoritative live registry, not a service's possibly old snapshot or a failed read.
- if (!session) return { closed: true }
- // A reopen (resume-only) of the same conversation is still the Swarm's session: the identity below proves it.
- if (session.startedBy !== 'agent' || !request.creationId || typeof request.sessionId !== 'string' || !request.createdAt) return { error: 'NOT_SWARM_STARTED' }
- if (session.sessionId !== request.sessionId || session.registeredAt !== Date.parse(request.createdAt)) return { error: 'AGENT_CHANGED' }
- if (!Number.isFinite(request.expiresAt) || request.expiresAt! <= Date.now()) return { error: 'STOP_LEASE_EXPIRED' }
- const creation = await creationStatus?.(request.creationId)
- if (creation?.state !== 'created' || creation.agentId !== request.agentId) return { error: 'NOT_SWARM_STARTED' }
- if (request.expiresAt! <= Date.now()) return { error: 'STOP_LEASE_EXPIRED' }
- const latest = registry.byAgent(request.agentId)
- if (!latest || latest.startedBy !== 'agent' || latest.sessionId !== request.sessionId
- || latest.registeredAt !== Date.parse(request.createdAt)) return { error: 'AGENT_CHANGED' }
- return closeAgent ? closeAgent({ agentId: request.agentId, sessionId: request.sessionId, createdAt: request.createdAt, mode: 'now', onlyIfOriginalLaunch: true, expiresAt: request.expiresAt }) : { error: 'UNSUPPORTED' }
- },
- keepLeadAlive: async agentId => {
- if (!resumeAgent || !swarmMembers) return { ok: false, error: 'UNSUPPORTED' }
- if (registry.byAgent(agentId)) return { ok: true }
- if (!swarmMembers.leads().has(agentId) || !stoppedAgents.ids().includes(agentId)) {
- return { ok: false, error: 'NOT_A_LEAD', detail: 'Only a stopped Product Manager of a Swarm project is reopened.' }
- }
- const reply = await resumeAgent(agentId)
- return reply.ok ? { ok: true } : { ok: false, error: reply.error, ...(reply.detail ? { detail: reply.detail } : {}) }
- },
- closeMember: async (agentId, creationId) => {
- if (!closeAgent || !swarmMembers) return { error: 'UNSUPPORTED' }
- const session = registry.byAgent(agentId)
- if (!session) return { closed: true }
- let member = false
- try { member = swarmMembers.harnesses().has(agentId) } catch { /* An unreadable retention names no member. */ }
- // An agent removed before its host wrote a roster naming it: the Swarm's own start receipt proves it (the review of #1635).
- if (!member && creationId) {
- const creation = await creationStatus?.(creationId)
- member = creation?.state === 'created' && creation.agentId === agentId
- }
- if (!member) return { error: 'NOT_A_MEMBER' }
- // The close itself refuses a session that changed during the receipt read.
- return closeAgent({ agentId, sessionId: session.sessionId, createdAt: new Date(session.registeredAt).toISOString(), mode: 'now' })
- },
closeStarted: async (agentId, mode) => {
const session = registry.byAgent(agentId)
if (!session) return { error: 'AGENT_CHANGED' }
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index 04a461f34..ccca3315c 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -22,13 +22,13 @@
* - `cloud_publish`, `cloud_ask`, `cloud_unask`: the cloud agents' harnesses and their questions
* (`core.cloud`, core/agents/cloud.ts), for the cloud service alone;
* - `super_tab_attention`: the Super Tab members here waiting on a person (`core.superTabs`,
- * core/superTabAttention.ts), for the Super Tab service alone;
+ * superTabs/inCore/attention.ts), for the Super Tab service alone;
* - `super_tab_cards`, `super_tab_card_recap`: the Swarms' cards and a Lead's last message for the Harness Pro
- * (`core.superTabs`, core/superTabCards.ts), for the Super Tab service alone;
+ * (`core.superTabs`, superTabs/inCore/cards.ts), for the Super Tab service alone;
* - `super_tab_observers`: members may watch an agent here, so Share must run (`core.superTabs`), for the Super Tab
* service alone;
* - `super_tab_screen`, `super_tab_input`: a member's terminal read as plain text and typed into for its Lead
- * (`core.superTabs`, core/superTabTerminal.ts), for the Super Tab service alone.
+ * (`core.superTabs`, superTabs/inCore/terminal.ts), for the Super Tab service alone.
* The core answers them only for the experiments (core/api.ts `EXPERIMENTS`): creating an agent or
* telling the windows something is no other process's to ask. The process's side is
* services/processCoreApi.ts. Agent Messages, an experiment until 2026-10-12, asks a few of the same and is
@@ -161,14 +161,14 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
return {}
}
case 'super_tab_attention': {
- // The core checks each item (core/superTabAttention.ts): what reaches the devices is decided there, not here.
+ // The core checks each item (superTabs/inCore/attention.ts): what reaches the devices is decided there, not here.
if (service !== 'superTabs' || !core.superTabs) return { error: 'NOT_SUPER_TABS' }
core.superTabs.attention(Array.isArray(payload.items) ? payload.items : [])
return {}
}
case 'super_tab_cards':
case 'super_tab_card_recap': {
- // Checked by the core (core/superTabCards.ts), which drops what is not sound; here only the list's shape.
+ // Checked by the core (superTabs/inCore/cards.ts), which drops what is not sound; here only the list's shape.
if (service !== 'superTabs' || !core.superTabs) return { error: 'NOT_SUPER_TABS' }
if (query === 'super_tab_cards') core.superTabs.cards(Array.isArray(payload.items) ? payload.items : [])
else core.superTabs.cardRecap(payload.recap as never)
diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.ts
index f1ff9c2f7..ef0be33cd 100644
--- a/cli/src/core/input.spec.ts
+++ b/cli/src/core/input.spec.ts
@@ -14,6 +14,7 @@ import { createInput, createMessageRequest, deviceInputDeps, heldScreen, message
import { createScreens } from './engines/screens.js'
import { screenFor } from '../engines/screens.js'
import { readerEngine } from '../engines/worker/protocol.js'
+import { typesWhileBusy } from '../superTabs/inCore/deliveries.js'
const ok: TerminalActionResult = { state: 'succeeded', dispatch: 'executed' }
const fixture = (name: string) => readFileSync(new URL(`../lib/__fixtures__/${name}`, import.meta.url), 'utf8')
@@ -63,6 +64,7 @@ function deps(over: Partial<InputDeps> = {}) {
agentIdFor: (sessionId) => agents.get(sessionId)?.agentId ?? sessionId,
commandcode: (sessionId) => sessionId === 'cc-s' ? normalizer as unknown as CommandCodeNormalizer : undefined,
emit: vi.fn(),
+ typesWhileBusy,
...over,
}
return { deps: base, calls, device, normalizer, setPane: (next: string | null) => { pane = next } }
@@ -89,6 +91,14 @@ describe('the session input controller\'s dependencies', () => {
expect(await wired.injectTeam!(id, 'peer message', 'team:peer')).toMatchObject({ dispatch: 'not_started', reason: 'team_waiting_idle' })
})
+ // HARNESS_SWARM=off: no maker's typed delivery is queued while the agent works; each waits for idle, as Agent Messages' do.
+ it('waits for idle with every typed delivery when none is handed a busy queue', async () => {
+ const t = deps({ typesWhileBusy: undefined }), wired = sessionInputDeps(t.deps, () => lock(t.calls))
+ t.setPane('Working (esc to interrupt)\n' + READY_PANE)
+ expect(await wired.injectTeam!('a1', 'chat follow-up', 'team:service:superTabs:busy')).toMatchObject({ dispatch: 'not_started', reason: 'team_waiting_idle' })
+ expect(t.deps.terminal.submitTerminalAction).not.toHaveBeenCalled()
+ })
+
it.each([
[null, 'team_waiting_unavailable'],
[CLAUDE_PERMISSION, 'team_waiting_user'],
diff --git a/cli/src/core/input.ts b/cli/src/core/input.ts
index 2d2c404fa..caaa8de89 100644
--- a/cli/src/core/input.ts
+++ b/cli/src/core/input.ts
@@ -63,6 +63,9 @@ export interface InputDeps {
/** While an agent changes host, its messages wait here and go to the pane it ends on (hostMove/gate.ts): the one
* gate the terminal streams hold its keystrokes in too. */
moveGate?: MoveGate
+ /** Whether a typed delivery's maker queues it in the engine's own input while the agent works (the Swarm's chat,
+ * superTabs/inCore/deliveries.ts), where the engine takes that; absent, every typed delivery waits for idle. */
+ typesWhileBusy?: (deliveryId: string) => boolean
}
/**
@@ -145,11 +148,11 @@ export function sessionInputDeps(
const { resolve, terminal, deliveries, device, clients, agentIdFor, commandcode, emit } = deps
const { captureTerminal, validateTerminal, keyTerminalAction } = terminal
const writeMessage = messageWriter(deps)
- // Swarm chat uses the native input queue, while Agent Messages still waits for idle.
+ // A maker's chat may use the native input queue (`typesWhileBusy`), while Agent Messages still waits for idle.
// Both paths keep the same draft and dialog checks under the pane's writer lock.
const deliveryHold = (session: RegisteredSession, screen: ScreenReading | null, capture: string | null, deliveryId?: string): string | null => {
if (!screen) return 'team_waiting_unavailable'
- return deliveryId?.startsWith('team:service:superTabs:') && deps.submission.policy(session.engine)?.typesWhileBusy
+ return deliveryId && deps.typesWhileBusy?.(deliveryId) && deps.submission.policy(session.engine)?.typesWhileBusy
? teamHold(session.engine, capture ?? '', screen.pane, screen.question, true) : screen.teamHold
}
return {
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 56518feec..66d31ffe2 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1,6 +1,3 @@
-import { createSwarmSkillAdoption } from './agents/swarmSkills.js'
-import { swarmRoleThrough } from './superTabSkills.js'
-import { mayBeLead, retainedHarnesses, retainedLeads } from '../superTabs/retention.js'
import { realTeamRelayLaunch } from '../team/relay.js'
import { createGridAssignments } from './agents/gridAssignments.js'
import { createQuestionControls } from './engines/questionControls.js'
@@ -211,15 +208,12 @@ import { createTerminalWatch } from './terminalWatch.js'
import { createSharingLink } from './sharingLink.js'
import { createAgentSettingsSync, createExperimentHooks, wakeExperiments } from './experiments.js'
import { answerExperimentQuery, answerMachineAddonsQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'
-import { createSuperTabAttention } from './superTabAttention.js'
-import { createSuperTabTerminal } from './superTabTerminal.js'
-import { createSuperTabCards } from './superTabCards.js'
import { answerConnectorsQuery } from './connectorsQueries.js'
import { answerSharedMachinesQuery } from './sharedMachinesQueries.js'
import { inlineSharedMachinesPort } from '../lib/sharedMachinesPort.js'
import { createOrchestratorLink } from './orchestratorLink.js'
import { daemonCommand } from '../lib/daemonCommand.js'
-import { KNOWN_SERVICES, masterRunsEngineRuntime, masterRunsLiveEngines, servicesTheMasterRuns } from '../harnessd/services.js'
+import { KNOWN_SERVICES, masterRunsEngineRuntime, masterRunsLiveEngines, servicesOn, servicesTheMasterRuns, swarmOn } from '../harnessd/services.js'
import { askForMessages, createMessagesLink } from './messagesLink.js'
import { createDevicesLink } from './devicesLink.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND } from '../harnessd/protocol.js'
@@ -260,7 +254,6 @@ import { createRuntimeTransport } from './engines/runtimeTransport.js'
import { RuntimeProfileController } from '../lib/runtimeControl.js'
import { installTimestampedConsole, sid, prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS } from '../lib/log.js'
import { backendHttpBase } from '../lib/controlPlane.js'
-import { forwardAttachmentUpload } from '../lib/superTabAttachmentProxy.js'
// Daemon stdout/stderr. Capped at LOG_MAX_BYTES — see prepareLogFile/trimLogFile in lib/log.ts.
const LOG_FILE = DAEMON_LOG_FILE
@@ -703,7 +696,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const syncRecapPool = (): void => {
ports.devices?.engines(registry.active().map((session) => session.engine))
}
- const outOfProcess = servicesTheMasterRuns(harnessd, KNOWN_SERVICES)
+ // The Swarm switch (harnessd/services.ts `HARNESS_SWARM`, on unless set off): its code in this process comes from one
+ // entry, loaded only while it is on (superTabs/inCore.ts), and its service is left off with it.
+ const swarm = swarmOn(harnessd) ? await import('../superTabs/inCore.js') : null
+ const knownServices = servicesOn(harnessd, KNOWN_SERVICES)
+ const outOfProcess = servicesTheMasterRuns(harnessd, knownServices)
// The viewers' process (the viewers and the Store) runs once something needs it (core/viewersWake.ts).
const viewersWake = createViewersWake({ want: (service) => coreLink.want(service), outOfProcess })
const liveHosted = masterRunsLiveEngines(harnessd, process.ppid)
@@ -722,8 +719,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const isolatedNativeControl = (engine: string): boolean => nativeControlHosted && isolatedLive(engine)
const isolatedSubmission = (engine: string): boolean => submissionHosted && isolatedLive(engine)
const isolatedRuntime = (engine: string): boolean => runtimeHosted && isolatedLive(engine)
- const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !runtimeHosted || !screenHosted || !modelControlHosted || !questionControlHosted || !submissionHosted || !nativeControlHosted
+ const inline = knownServices.some((name) => !outOfProcess.has(name)) || !runtimeHosted || !screenHosted || !modelControlHosted || !questionControlHosted || !submissionHosted || !nativeControlHosted
? await import('../services/inline.js') : null
+ // The Swarm's side of the services that act on it, for those of them that run in this process while it is on
+ // (superTabs/inServices.ts): off, or with them in their own processes, none of it is loaded here.
+ const swarmServices = swarm && ['sharing', 'handoff', 'models'].some((name) => !outOfProcess.has(name))
+ ? await import('../superTabs/inServices.js') : null
let serviceLinksRef: ServiceLinks | null = null
const runtimeTransport = createRuntimeTransport({
call: (service, type, payload, waitMs) => serviceLinksRef?.call(service, type, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }),
@@ -846,33 +847,33 @@ async function runForeground(session: AuthSession | null): Promise<void> {
ask: (agentId, requestId, question) => cloudAgents?.doors.ask(agentId, requestId, question),
unask: (agentId, requestId) => cloudAgents?.doors.unask(agentId, requestId),
}
- // The Super Tab members here waiting on a person, on the devices alone (core/superTabAttention.ts). Read only once
- // the questions exist, below: the service starts after them.
- const superTabWaits = createSuperTabAttention({
- send: (frame) => ports.devices?.card(frame),
- asking: (agentId) => [...openQuestions.values()].some((asked) => asked.agentId === agentId),
- })
- // A member's terminal for its Lead (core/superTabTerminal.ts): read plain, typed under the pane's write lock, which is
- // built below, after the inputs.
- const superTabTerminal = createSuperTabTerminal({
- resolve: (agentId) => registry.byAgent(agentId),
- capture: (session, options) => terminals.capture(session, options),
- read: (session, capture) => screens.read(session, capture),
- type: typeTerminal,
- key: keyTerminal,
- locked: (agentId, write) => deviceInput.legacyWrite(agentId, write),
- })
- // The Swarms' cards and Leads' recaps for the Harness Pro, on the devices alone (core/superTabCards.ts): kept whole, and shown
- // again to a dial that attaches.
const routeSuperTabs = (payload: Record<string, unknown>): Promise<Record<string, unknown>> => new Promise((resolve) => {
const asker = { local: true, owner: true }
if (!(serviceLinksRef?.route('super_tabs', payload, asker, resolve) || serviceHost.route('super_tabs', payload, asker, resolve))) resolve({ error: 'SERVICE_UNAVAILABLE' })
})
- const superTabCards = createSuperTabCards({
- swarmCards: (items) => ports.devices?.swarmCards(items),
- swarmCardRecap: (recap) => ports.devices?.swarmCardRecap(recap),
- request: (payload) => routeSuperTabs(payload),
- })
+ // The Swarm's doors in this process, while it is on (superTabs/inCore/): its members here waiting on a person, on the
+ // devices alone, read only once the questions exist below (the service starts after them); a member's terminal for its
+ // Lead, read plain and typed under the pane's write lock, built below after the inputs; and the Swarms' cards and Leads'
+ // recaps for the Harness Pro, on the devices alone, kept whole and shown again to a dial that attaches.
+ const swarmDoors = swarm && {
+ waits: swarm.createSuperTabAttention({
+ send: (frame) => ports.devices?.card(frame),
+ asking: (agentId) => [...openQuestions.values()].some((asked) => asked.agentId === agentId),
+ }),
+ terminal: swarm.createSuperTabTerminal({
+ resolve: (agentId) => registry.byAgent(agentId),
+ capture: (session, options) => terminals.capture(session, options),
+ read: (session, capture) => screens.read(session, capture),
+ type: typeTerminal,
+ key: keyTerminal,
+ locked: (agentId, write) => deviceInput.legacyWrite(agentId, write),
+ }),
+ cards: swarm.createSuperTabCards({
+ swarmCards: (items) => ports.devices?.swarmCards(items),
+ swarmCardRecap: (recap) => ports.devices?.swarmCardRecap(recap),
+ request: (payload) => routeSuperTabs(payload),
+ }),
+ }
// Shared tabs' relay, a socket per shared tab held by the gateway (gateway/tabRelay.ts), and which of them the core saw
// opened: opened again after a gateway-only restart, closed when Agent Messages' process goes (core/gatewayLink.ts).
const tabRelay = tabRelayOf(() => gatewayOps.tabRelay)
@@ -882,13 +883,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const coreApi = createCoreApi({
nativeTurns: async (agentId, cursor) => nativeTurns.read(agentId, cursor),
cloud: cloudDoors,
- superTabs: { attention: (items) => superTabWaits.attention(items), cards: (items) => superTabCards.cards(items), cardRecap: (recap) => superTabCards.recap(recap),
- // In the core's own process Share was started with it; out of it, the master starts Share's process.
- shareObservers: () => { if (outOfProcess.has('sharing')) coreLink.want('sharing') },
- screen: (agentId, scrollback) => superTabTerminal.screen(agentId, scrollback),
- input: (agentId, text, keys) => superTabTerminal.input(agentId, text, keys) },
- // The devices' `cardsWanted`, `cardRecap` and `cardOpen`, and no other action of the Super Tab service (core/superTabCards.ts `ask`).
- superTabRequest: (payload) => superTabCards.ask(payload),
+ ...(swarmDoors ? {
+ superTabs: { attention: (items) => swarmDoors.waits.attention(items), cards: (items) => swarmDoors.cards.cards(items), cardRecap: (recap) => swarmDoors.cards.recap(recap),
+ // In the core's own process Share was started with it; out of it, the master starts Share's process.
+ shareObservers: () => { if (outOfProcess.has('sharing')) coreLink.want('sharing') },
+ screen: (agentId, scrollback) => swarmDoors.terminal.screen(agentId, scrollback),
+ input: (agentId, text, keys) => swarmDoors.terminal.input(agentId, text, keys) },
+ // The devices' `cardsWanted`, `cardRecap` and `cardOpen`, and no other action of the Super Tab service (superTabs/inCore/cards.ts `ask`).
+ superTabRequest: (payload) => swarmDoors.cards.ask(payload),
+ } : {}),
cloudRows: () => (cloudAgents?.dialRows() ?? []) as unknown as RegisteredSession[],
// Agents' terminals: a literal-argv launch, and a read-only view for Share's observers (core/terminalWatch.ts).
terminals: { ...TERMINALS_OFF, ...createTerminalOpener({ createBackend, recoverBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd), noBackendCode: createUnavailable }), watch: terminalWatch.watch },
@@ -978,8 +981,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (attached) for (const frame of openQuestions.values()) ports.devices?.card(frame)
if (attached) void mirror.liveCards().then((cards) => { for (const frame of cards) ports.devices?.card(frame) })
if (attached) for (const frame of cloudAgents?.liveCards() ?? []) ports.devices?.card(frame)
- if (attached) superTabWaits.replay()
- if (attached) superTabCards.replay()
+ if (attached) swarmDoors?.waits.replay()
+ if (attached) swarmDoors?.cards.replay()
},
// What a device or another machine asks of an agent here: the SAME handlers the backend socket
// drives, called directly — the slash-command adaptation and the turn and question plumbing live there.
@@ -999,7 +1002,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The Super Tab host keeps its Leads alive and closes the sessions its backend ends (superTabs/host.ts). Read when it
// asks, never now: the lifecycle is built further down, and one asked before then is refused, and asked again later.
resumeAgent: async (agentId) => lifecycle.resumeAgent(agentId),
- swarmMembers: { leads: () => retainedLeads(env.ADAPTER_DATA_DIR), harnesses: () => retainedHarnesses(env.ADAPTER_DATA_DIR) },
+ // What it may close and reopen is decided in this process, on what its host retains (superTabs/inCore/agents.ts).
+ ...(swarm ? { swarmAgents: (agentDeps) => swarm.createSwarmAgents({ ...agentDeps,
+ members: { leads: () => swarm.retainedLeads(env.ADAPTER_DATA_DIR), harnesses: () => swarm.retainedHarnesses(env.ADAPTER_DATA_DIR) } }) } : {}),
dsh: (session) => backendRef?.dshFrameProvider?.(session) ?? null,
windows: (frame) => backendRef?.sendLocal(frame),
daemon: { command: daemonCommand(), port: env.PORT, machineId: () => backendRef?.machineId ?? '', autonomousEnv: session?.autonomousEnv ?? env.AUTONOMOUS_ENV },
@@ -1338,6 +1343,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.sessionsProvider = history.sessionsList
// Everything the core writes into a pane, and the device's pane lock (core/input.ts).
const inputs = createInput({
+ // The Swarm's chat is queued in the engine's own input while an agent works (superTabs/inCore/deliveries.ts).
+ ...(swarm ? { typesWhileBusy: swarm.typesWhileBusy } : {}),
readScreen: screens.read,
submission: submissions,
resolve: (id) => registry.resolve(id),
@@ -1594,7 +1601,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The gateway first hears what it starts from, then the shared tabs it held before a restart.
if (service === 'gateway') { gatewayLink?.connected(); tabRelay.connected() }
if (service === 'devices') devicesLink.connected()
- if (service === 'superTabs') superTabCards.serviceUp()
+ if (service === 'superTabs') swarmDoors?.cards.serviceUp()
if (service === 'wifi') wifiCore.started(appVoiceFocus ?? null)
if (service === 'viewers') viewersLink.connected()
devicesWake.connected(service)
@@ -1617,7 +1624,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (service === 'gateway') gatewayLink?.disconnected()
// Agent Messages' process went: its tabs' sockets have no one to hear them, and it opens them again as it starts.
if (service === 'messages') tabRelay.closeOpened()
- if (service === 'devices') { devicesLink.disconnected(); superTabCards.devicesGone() }
+ if (service === 'devices') { devicesLink.disconnected(); swarmDoors?.cards.devicesGone() }
if (service === 'wifi') wifiCore.stopped()
if (service === 'recaps') recapsLink.disconnected()
void terminalWatch.gone(service)
@@ -1661,7 +1668,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Share (services/sharing.ts): in this process, or in its own once it is on (core/sharingLink.ts). Its
// observers' frames reach it as the relay hands them over.
if (outOfProcess.has('sharing')) ports.sharing = createSharingLink({ call: (type, payload) => serviceLinks.call('sharing', type, payload), notify: (frame) => serviceLinks.notify('sharing', frame) })
- else serviceHost.start('sharing', inline!.startSharing, coreApi, SHARING_FALLBACKS, SHARE_REQUESTS)
+ else serviceHost.start('sharing', (core, given) => inline!.startSharing(core, given, swarmServices ? { observers: swarmServices.observerSource } : {}), coreApi, SHARING_FALLBACKS, SHARE_REQUESTS)
backend.observers = { receive: (connId, type, payload) => ports.sharing?.observer(connId, type, payload), closeAll: () => ports.sharing?.linkDown() }
// Agent Messages (services/messages.ts): in the edge host, or in this process behind the service host's guard (a
// fault there costs no message its write).
@@ -1699,8 +1706,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (!outOfProcess.has('windowNames')) serviceHost.serve('windowNames', inline!.startWindowNames, coreApi, WINDOW_NAMES_REQUESTS)
if (!outOfProcess.has('memory')) serviceHost.serve('memory', inline!.startMemory, coreApi, MEMORY_REQUESTS)
if (!outOfProcess.has('router')) serviceHost.serve('router', inline!.startRouter, coreApi, ROUTER_REQUESTS)
- if (!outOfProcess.has('superTabs')) serviceHost.start('superTabs', inline!.startSuperTabs, coreApi, SUPER_TAB_FALLBACKS, SUPER_TAB_REQUESTS)
- if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', inline!.startHandoff, coreApi, HANDOFF_REQUESTS)
+ if (!swarm) serviceHost.leaveOff('superTabs', SUPER_TAB_REQUESTS)
+ else if (!outOfProcess.has('superTabs')) serviceHost.start('superTabs', swarm.startSuperTabs, coreApi, SUPER_TAB_FALLBACKS, SUPER_TAB_REQUESTS)
+ if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', (core) => inline!.startHandoff(core, undefined, undefined, swarmServices?.recordReplacement), coreApi, HANDOFF_REQUESTS)
// Connected services' MCP bridge and the Connectors screen (services/connectors.ts): here, or in the edge host.
if (!outOfProcess.has('connectors')) serviceHost.serve('connectors', inline!.startConnectors, coreApi, CONNECTORS_REQUESTS)
// Sharing this machine with other accounts, and the machines shared with this one (services/sharedMachines.ts).
@@ -1715,13 +1723,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The recaps: in this process, or in the edge host (services/recapsProcess.ts), told each turn's lifecycle.
if (outOfProcess.has('recaps')) ports.recaps = recapsLink.port; else serviceHost.start('recaps', inline!.startRecaps, coreApi, RECAPS_FALLBACKS)
// Cleaning up after agents: the harnesses a closed harness started, and those idle half an hour (services/agentCleanup.ts).
- if (outOfProcess.has('agentCleanup')) ports.agentCleanup = agentCleanupLink.port; else serviceHost.start('agentCleanup', inline!.startAgentCleanup, coreApi, AGENT_CLEANUP_FALLBACKS)
+ if (outOfProcess.has('agentCleanup')) ports.agentCleanup = agentCleanupLink.port; else serviceHost.start('agentCleanup', (core, given) => inline!.startAgentCleanup(core, given, swarm?.retainedHarnesses), coreApi, AGENT_CLEANUP_FALLBACKS)
if (!outOfProcess.has('shell')) serviceHost.serve('shell', inline!.startShell, coreApi, SHELL_REQUESTS)
// Models: grid access and its pin, the model pictures on agents' frames, the keystroke prewarm, where an
// agent on a grid model sends its inference, and the models requests the apps send (services/models.ts):
// in this process, or in its own (services/modelsProcess.ts), reached through core/modelsLink.ts.
if (outOfProcess.has('models')) ports.models = modelsLink.port
- else serviceHost.start('models', inline!.startModels, coreApi, MODELS_FALLBACKS, MODELS_REQUESTS)
+ else serviceHost.start('models', (core, given) => inline!.startModels(core, given, swarmServices ?? undefined), coreApi, MODELS_FALLBACKS, MODELS_REQUESTS)
// What the socket asks of models: read on each use, so a models service switched off answers its fallbacks.
backend.models = () => ports.models ?? MODELS_OFF
@@ -2151,8 +2159,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onAgentSettingsWrite: (body) => agentSettings.settingsWrite(body),
onProductFeedback: (body) => proxyBackend('POST', '/api/product-usage/feedback', body),
onSignInAnswer: (action, body) => proxyBackend('POST', `/api/auth/qr/${action}`, body),
- onSuperTabAttachment: (req, res, path) => forwardAttachmentUpload(req, res, path,
- { accessToken: () => auth.accessToken(), environment: autonomousEnv, base: backendHttpBase() }),
+ ...(swarm ? { onSuperTabAttachment: (req, res, path) => swarm.forwardAttachmentUpload(req, res, path,
+ { accessToken: () => auth.accessToken(), environment: autonomousEnv, base: backendHttpBase() }) } : {}),
onProductUsageReport: (body) => proxyBackend('POST', '/api/product-usage/report', body),
onProductUsageRead: () => proxyBackend('GET', '/api/product-usage/settings'),
onProductUsageWrite: (body) => proxyBackend('POST', '/api/product-usage/settings', body),
@@ -2369,6 +2377,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
downloading: (engine) => engineDownloading(engine),
})
const launchOverridesDeps: LaunchOverridesDeps = {
+ // A Swarm session's skill and GitHub App on every relaunch; off, such a session is not relaunched.
+ ...(swarm ? { swarm: swarm.SWARM_LAUNCH } : {}),
publishConfig: publishGridConfigDir,
machine: gridLaunchMachine,
native: prepareNativeLaunch,
@@ -2384,11 +2394,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// What a relaunch needs to bring a pane back (core/agents/launch.ts). Declared before the restore
// pass below, which calls these for every pane it rebuilds.
const launchAuthority = createLaunchAuthority({ byAgent: id => registry.byAgent(id), revision: restoreRevision, cancelled: id => launchCancelled(id) })
- const adoptSwarmSkill = createSwarmSkillAdoption({
+ const adoptSwarmSkill = swarm?.createSwarmSkillAdoption({
authority: launchAuthority,
- candidate: id => retainedHarnesses(env.ADAPTER_DATA_DIR).has(id),
+ candidate: id => swarm.retainedHarnesses(env.ADAPTER_DATA_DIR).has(id),
role: outOfProcess.has('superTabs')
- ? swarmRoleThrough((type, payload) => serviceLinks.call('superTabs', type, payload, 3500))
+ ? swarm.swarmRoleThrough((type, payload) => serviceLinks.call('superTabs', type, payload, 3500))
: id => ports.superTabs?.swarmRole(id) ?? Promise.resolve(undefined),
save: (id, skill) => registry.setSwarmSkill(id, skill),
})
@@ -2697,6 +2707,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Creating an agent (core/agents/create.ts).
const creator = createAgentCreator({
+ ...(swarm ? { swarmLaunch: swarm.SWARM_LAUNCH } : {}),
publishConfig: publishGridConfigDir,
native: prepareNativeLaunch,
dshLaunch,
@@ -2820,7 +2831,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
stopped: (agentId) => ports.agentCleanup?.closed(agentId),
moveHeld: (agentId) => moveHeld.has(agentId),
// The Lead of an active Swarm project is never stopped (owner, 2026-10-23); its host keeps the list (superTabs/retention.ts).
- leadProtected: (agentId) => mayBeLead(env.ADAPTER_DATA_DIR, agentId),
+ ...(swarm ? { leadProtected: (agentId: string) => swarm.mayBeLead(env.ADAPTER_DATA_DIR, agentId) } : {}),
})
const stopJobs = lifecycle.stopJobs
launchCancelled = id => stopJobs.has(id)
@@ -2846,7 +2857,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
announceSession,
engineReady: (engine, ms) => engineLinks.ready(engine, ms),
stoppedAgents,
- leadProtected: (agentId) => mayBeLead(env.ADAPTER_DATA_DIR, agentId),
+ ...(swarm ? { leadProtected: (agentId: string) => swarm.mayBeLead(env.ADAPTER_DATA_DIR, agentId) } : {}),
})
backend.closeAgentService = closing.closeAgentService
backend.closeAgentService.start()
@@ -2944,6 +2955,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The requests that start an agent's process, and the receipts of those asked with a creationId
// (core/agents/launches.ts). The orchestrator and the cable create and fork through the socket's slots.
const launches = createLaunchRequests({
+ ...(swarm ? { swarmLaunch: swarm.SWARM_LAUNCH } : {}),
receipts: new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations')),
createAgent: () => backend.onCreateAgent, forkAgent: () => backend.onForkAgent,
prepareCreate: creator.prepare, prepareEngine: prepareNativeLaunch,
@@ -3126,7 +3138,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The web-tools cache lives exactly as long as the sign-in. `harness logout` and `reset` stop
// the daemon outright; this is the one sign-out the daemon learns of from inside.
ports.models?.signedOut()
- superTabCards.reset()
+ swarmDoors?.cards.reset()
void shutdown('revoked')
}
@@ -3155,7 +3167,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// In their own process they are told everything the windows said as they connect (core/devicesLink.ts):
// said here too, it reached a dial still opening its port, before its greeting.
// The Swarm cards the Super Tab service sent before this line had no devices to reach: they are shown now.
- if (outOfProcess.has('devices')) { ports.devices = devicesLink.port; superTabCards.replay() }
+ if (outOfProcess.has('devices')) { ports.devices = devicesLink.port; swarmDoors?.cards.replay() }
else {
serviceHost.start('devices', (core, started) => inline!.startDevices(core, started, {
logsDir: env.HARNESS_LOGS_DIR, testDialPort: harnessd.HARNESSD_TEST_DIAL_PORT,
@@ -3195,9 +3207,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const full = card.type === 'commander_event' && payload?.kind === 'summary' && typeof card.agentId === 'string'
? mirror.lastFullText(registry.byAgent(card.agentId)?.sessionId ?? card.agentId) ?? cloudAgents?.said(card.agentId) : undefined
// An engine's question takes the place of a Super Tab wait on the devices, which shows again once it closes.
- superTabWaits.before(card)
+ swarmDoors?.waits.before(card)
ports.devices?.card(full ? { ...card, payload: { ...payload, fullText: full } } : card)
- superTabWaits.after(card)
+ swarmDoors?.waits.after(card)
}
// Last: every handler is wired and the restored agents are confirmed, so requests that arrived while
diff --git a/cli/src/core/serviceHost.spec.ts b/cli/src/core/serviceHost.spec.ts
index 638e247f0..8ef621127 100644
--- a/cli/src/core/serviceHost.spec.ts
+++ b/cli/src/core/serviceHost.spec.ts
@@ -301,6 +301,26 @@ describe('hosting services so one that fails cannot take the core down', () => {
expect(h.lines.at(-1)).toBe('[services] catalog switched off after 1 failures in 60s · it stays off until the daemon restarts')
})
+ it('leaves a service the computer switched off off: its requests answered SERVICE_UNAVAILABLE, its port empty, nothing started', () => {
+ const h = host()
+ h.ports.search = new FakeSearch() as unknown as SearchPort
+ h.services.leaveOff('search', ['session_search'])
+ h.services.leaveOff('catalog', ['dsh_list'])
+ const { got, reply } = collect()
+ h.services.route('session_search', {}, ASKER, reply)
+ h.services.route('dsh_list', {}, ASKER, reply)
+ expect(got).toEqual([
+ { error: 'SERVICE_UNAVAILABLE', service: 'search', retryable: false },
+ { error: 'SERVICE_UNAVAILABLE', service: 'catalog', retryable: false },
+ ])
+ expect(h.ports.search).toBeNull()
+ expect(h.services.isOff('search')).toBe(true)
+ expect(h.lines).toEqual(['[services] search is turned off on this computer', '[services] catalog is turned off on this computer'])
+ // Its types stay its own: another service declaring them is the mistake it always was.
+ h.services.serve('other', () => ({ dsh_list: () => ({}) }), fakeCore(), ['dsh_list'])
+ expect(h.lines.at(-1)).toBe('[services] other did not start · dsh_list is answered by catalog · the core runs without it')
+ })
+
it('answers a handler that throws, rejects or replies with nothing SERVICE_FAILED, and counts each against its service', async () => {
const h = host({ maxFailures: 3 })
h.services.serve('catalog', () => ({
diff --git a/cli/src/core/serviceHost.ts b/cli/src/core/serviceHost.ts
index 6b0272939..3ad33a175 100644
--- a/cli/src/core/serviceHost.ts
+++ b/cli/src/core/serviceHost.ts
@@ -270,6 +270,16 @@ export function createServiceHost(ports: CorePorts, options: ServiceHostOptions
closeConnection(connection: string): void {
for (const [closed, asked] of answering) if (asked === connection) closed.abort()
},
+ /**
+ * Leave a service this computer turned off (harnessd/services.ts `servicesOn`) off: nothing of it is started, its
+ * port stays empty, and its requests are answered `SERVICE_UNAVAILABLE`, as for one that did not start.
+ */
+ leaveOff(name: string, requests: readonly string[]): void {
+ claim(name, requests)
+ off.add(name)
+ if (Object.hasOwn(ports, name)) ports[name as PortName] = null
+ log(`[services] ${name} is turned off on this computer`)
+ },
/** Run `handler` once, when `name` is switched off. */
onOff(name: string, handler: () => void): void {
offHandlers.set(name, [...offHandlers.get(name) ?? [], handler])
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index ae031bbaa..bc9b27f75 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
- DEFAULT_SERVICE_OPTIONS, ENGINE_LIVE_ENV, ENGINE_RUNTIME_ENV, ENGINE_SCREEN_ENV, ENGINE_MODEL_CONTROL_ENV, masterRunsEngineModelControl, ENGINE_QUESTION_CONTROL_ENV, masterRunsEngineQuestionControl, ENGINE_SUBMISSION_ENV, masterRunsEngineSubmission, ENGINE_NATIVE_CONTROL_ENV, masterRunsEngineNativeControl, KNOWN_SERVICES, SERVICE_HOSTS, SERVICE_PROCESSES_ENV, ServiceSupervisor, UPDATER_HOST, masterRunsLiveEngines, masterRunsEngineRuntime, masterRunsEngineScreen, serviceOptions, serviceProcessesEnv, serviceSpecs, servicesTheMasterRuns,
+ DEFAULT_SERVICE_OPTIONS, ENGINE_LIVE_ENV, ENGINE_RUNTIME_ENV, ENGINE_SCREEN_ENV, ENGINE_MODEL_CONTROL_ENV, masterRunsEngineModelControl, ENGINE_QUESTION_CONTROL_ENV, masterRunsEngineQuestionControl, ENGINE_SUBMISSION_ENV, masterRunsEngineSubmission, ENGINE_NATIVE_CONTROL_ENV, masterRunsEngineNativeControl, KNOWN_SERVICES, SERVICE_HOSTS, SERVICE_PROCESSES_ENV, ServiceSupervisor, UPDATER_HOST, masterRunsLiveEngines, masterRunsEngineRuntime, masterRunsEngineScreen, serviceOptions, serviceProcessesEnv, serviceSpecs, servicesTheMasterRuns, SWARM_ENV, servicesOn, swarmOn,
type ServiceSpec, type ServiceSupervisorDeps, type ServiceSupervisorOptions,
} from './services.js'
import type { CoreHandle } from './supervisor.js'
@@ -568,6 +568,26 @@ describe('ServiceSupervisor', () => {
})
})
+describe('the Swarm switch', () => {
+ it('is on unless HARNESS_SWARM says off, so nothing changes for anyone who does not set it', () => {
+ expect(SWARM_ENV).toBe('HARNESS_SWARM')
+ expect(swarmOn({})).toBe(true)
+ for (const on of ['', 'on', '1', 'true', 'yes', 'anything']) expect(swarmOn({ HARNESS_SWARM: on }), on).toBe(true)
+ for (const off of ['off', 'OFF', ' off ', '0', 'false', 'no']) expect(swarmOn({ HARNESS_SWARM: off }), off).toBe(false)
+ })
+
+ it('off, leaves the Swarm\'s service out of the services this computer runs, and out of every process the master starts', () => {
+ expect(servicesOn({}, ['search', 'superTabs', 'cloud'])).toEqual(['search', 'superTabs', 'cloud'])
+ expect(servicesOn({ HARNESS_SWARM: 'off' }, ['search', 'superTabs', 'cloud'])).toEqual(['search', 'cloud'])
+ const processes = (env: NodeJS.ProcessEnv): string[] => serviceSpecs(env, SERVICE_HOSTS).flatMap(spec => spec.services)
+ expect(processes({})).toContain('superTabs')
+ expect(processes({ HARNESS_SWARM: 'off' })).not.toContain('superTabs')
+ // Named outright, it still stays off: the switch is the computer's, HARNESSD_SERVICES only says where services run.
+ expect(serviceSpecs({ HARNESSD_SERVICES: 'superTabs,search', HARNESS_SWARM: 'off' }, SERVICE_HOSTS).map(spec => spec.name)).toEqual(['search'])
+ expect(processes({ HARNESS_SWARM: 'off' })).toEqual(processes({}).filter(service => service !== 'superTabs'))
+ })
+})
+
describe('which services the core leaves to its master', () => {
const known = ['search', 'viewers', 'workspaces', 'messages']
const supervised = { HARNESSD_SUPERVISED: '1', HARNESSD_SERVICE_TOKEN: 'token' }
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 4e61e8f2a..314f93ec6 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -14,6 +14,7 @@
*/
import { SERVICE_EXIT_RESTART, describeStaged, heartbeatGraceMs, isCoreMessage, isUpdaterMessage, type StagedUpdate } from './protocol.js'
import { describeExit, type CoreHandle } from './supervisor.js'
+import { SWARM_ENV, swarmOn } from './swarmSwitch.js'
export interface ServiceSpec {
/** The process's name: what the master logs it as and the process is titled (`harnessd <name>`). */
@@ -524,6 +525,15 @@ export function servicesTheMasterRuns(env: NodeJS.ProcessEnv, known: readonly st
return new Set(said.split(',').map((name) => name.trim()).filter((name) => known.includes(name)))
}
+/** The Swarm switch (harnessd/swarmSwitch.ts): off, the Swarm's service is left out of every process the master starts. */
+export { SWARM_ENV, swarmOn }
+const SWARM_SERVICES: ReadonlySet<string> = new Set(['superTabs'])
+
+/** The services of `known` that run on this computer, wherever they run: all of them, but the Swarm's while it is off. */
+export function servicesOn(env: NodeJS.ProcessEnv, known: readonly string[]): string[] {
+ return swarmOn(env) ? [...known] : known.filter((name) => !SWARM_SERVICES.has(name))
+}
+
/**
* The processes to run the services in: every service this build knows, unless `HARNESSD_SERVICES`
* names a subset, by service (`search,workspaces`) or by process (`edge`, every service it hosts); `none`
@@ -539,8 +549,9 @@ export function serviceSpecs(env: NodeJS.ProcessEnv, hosts: Readonly<Record<stri
const named = env.HARNESSD_SERVICES === undefined ? null
: new Set(env.HARNESSD_SERVICES.split(',').map((name) => name.trim()).filter((name) => name && name !== 'none'))
const heap = Number(env.HARNESSD_SERVICE_HEAP_LIMIT_MIB)
+ const on = new Set(servicesOn(env, Object.values(hosts).flatMap((host) => host.services)))
return Object.entries(hosts).flatMap(([name, host]) => {
- const services = host.services.filter((service) => !named || named.has(service) || named.has(name))
+ const services = host.services.filter((service) => on.has(service) && (!named || named.has(service) || named.has(name)))
// A process on demand named outright runs from the start, as every service named does (a test, support).
const onDemand = host.onDemand && !named ? { onDemand: true } : {}
const { onDemand: _given, ...rest } = host
diff --git a/cli/src/harnessd/swarmSwitch.ts b/cli/src/harnessd/swarmSwitch.ts
new file mode 100644
index 000000000..39eb4d283
--- /dev/null
+++ b/cli/src/harnessd/swarmSwitch.ts
@@ -0,0 +1,14 @@
+/**
+ * The Swarm switch. The Swarm (Super Tabs, src/superTabs/) is a subsystem a computer can run without (Dee, v1's last
+ * item: the daemon core stays small and reliable): `HARNESS_SWARM=off` (or `0`, `false`, `no`) leaves its service out
+ * of every process the master starts (harnessd/services.ts `servicesOn`), and the core and the services that act on it
+ * then load none of its code (core/main.ts, serviceProcess.ts). Unset, or anything else, it is on, as it was before
+ * there was a switch. Read once, as each process starts, from the environment the master hands on.
+ *
+ * Its own file, with no imports, so a service's process reads it without loading the master's code.
+ */
+export const SWARM_ENV = 'HARNESS_SWARM'
+
+export function swarmOn(env: NodeJS.ProcessEnv): boolean {
+ return !['off', '0', 'false', 'no'].includes((env[SWARM_ENV] ?? '').trim().toLowerCase())
+}
diff --git a/cli/src/leanEntry.spec.ts b/cli/src/leanEntry.spec.ts
index 29ea42c6c..cd44a2f32 100644
--- a/cli/src/leanEntry.spec.ts
+++ b/cli/src/leanEntry.spec.ts
@@ -45,6 +45,10 @@ describe('the lean bundle a release carries', () => {
const roots = role === 'core' ? [LEAN_CORE_ENTRY, runner!]
: role === 'master' ? [LEAN_ENTRY, runner!]
: [LEAN_ENTRY, [...files.keys()].find((name) => name.startsWith('serviceProcess-'))!, runner!]
+ return reach(roots)
+ }
+ /** The files [roots] import, and what those import, but not what any imports only when asked (`import("…")`). */
+ function reach(roots: string[]): Set<string> {
const seen = new Set<string>()
const visit = (name: string): void => {
if (seen.has(name)) return
@@ -106,6 +110,31 @@ describe('the lean bundle a release carries', () => {
expect([...loads('core')].filter((name) => files.get(name)!.includes(marker))).toEqual([])
})
+ // HARNESS_SWARM=off (the review of #1765): the Swarm's code is in files of its own, which a process loads only through
+ // a door while the Swarm is on (src/architecture.spec.ts `SWARM_DOORS`). With it off, the core, with every service in
+ // it too (`HARNESSD_SERVICES=none`), the master and every other service load none of it.
+ it.each([
+ ['its side of the core', 'Only a stopped Product Manager of a Swarm project is reopened.'],
+ ['its skills', 'A Swarm skill needs a role and session key'],
+ ['its GitHub App', 'The Harness GitHub App token is not in the form GitHub gives.'],
+ ['its retention', 'Super Tab retention'],
+ ['its replacements', 'Invalid agent replacement.'],
+ ['its shared APIs', 'This computer could not open a local endpoint for the API.'],
+ ])('leaves the Swarm\'s code, %s, out of every process but its own until it is on', (_, marker) => {
+ expect([...files.values()].some((code) => code.includes(marker)), 'the marker is in the build').toBe(true)
+ const inline = [...files.keys()].find((name) => name.startsWith('core-inline-'))
+ expect(inline, 'the core\'s inline services').toBeDefined()
+ const processes: Array<[string, Set<string>]> = [...ROLES.filter((role) => role !== 'superTabs').map((role) => [role, loads(role)] as [string, Set<string>]),
+ ['core with every service in it', new Set([...loads('core'), ...reach([inline!])])]]
+ for (const [role, loaded] of processes) expect([...loaded].filter((name) => files.get(name)!.includes(marker)), role).toEqual([])
+ })
+
+ it('loads the Swarm\'s code in its own process, which the master starts only while it is on', () => {
+ for (const marker of ['Super Tab retention', 'A Swarm skill needs a role and session key']) {
+ expect([...loads('superTabs')].some((name) => files.get(name)!.includes(marker)), marker).toBe(true)
+ }
+ })
+
it('loads native hook declarations eagerly without importing the optional compatibility entry', () => {
const core = loads('core')
// This is native source data written into Amp's plugin file, not Amp's optional transcript reader.
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index 761fd2644..015820bca 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -1,4 +1,4 @@
-import type { SwarmSkill } from './swarmSkills.js'
+import type { SwarmSkill } from './savedSkill.js'
/**
* Open a tmux pane for a new agent and claim it in the registry, retrying the claim up to
* `maxAttempts` times.
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index 1dc14ec02..c7ed078ab 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -11,6 +11,8 @@ import { DSH_SESSION_ENV } from '../dsh/launch.js'
import { GRID_CONFLICTING_ENV_VARS, type GridLaunchOverride } from './gridLaunch.js'
import { gridLaunchInProcess } from '../testing/gridLaunchInProcess.js'
import { AGENT_ATTRIBUTION_LINE, HARNESS_INSTRUCTIONS } from './agentAttribution.js'
+import { prepareSwarmSkill } from './swarmSkills.js'
+import { swarmGitHubLaunch } from './swarmGitHub.js'
const GRID: GridLaunchOverride = {
networkId: 'grid-abc',
@@ -36,6 +38,8 @@ function deps(overrides: Partial<LaunchOverridesDeps> = {}) {
// No Codex configuration unless a test says so — otherwise every relaunch built here would
// consult the config.toml of whoever is running the suite.
readCodexConfig: () => null,
+ // The Swarm on, as by default (`HARNESS_SWARM`); a test of it off leaves it out.
+ swarm: { prepare: prepareSwarmSkill, github: (key) => swarmGitHubLaunch(key) },
...overrides,
}
return { d, calls }
@@ -481,6 +485,21 @@ describe('buildLaunchOverrides — a Swarm session on the Harness GitHub App', (
expect(result.overrides.clearEnv).not.toContain('GH_TOKEN')
})
+ // HARNESS_SWARM=off: the core hands in no Swarm, and a session the Swarm started is not relaunched without its role.
+ it('refuses a Swarm session with the Swarm off, before it asks or writes anything', async () => {
+ const native = vi.fn(), dshLaunch = vi.fn()
+ const { d, calls } = deps({ swarm: undefined, native, dshLaunch })
+ for (const swarmSkill of [skill, { role: 'lead' as const, key: 'harness-claude-plain' }]) {
+ expect(await buildLaunchOverrides(d, 'claude', { cwd: workspace(), dsh: 'fixture/blender', swarmSkill }, 'agent-1', () => true))
+ .toEqual({ ok: false, error: 'SWARM_SKILL_FAILED', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' })
+ }
+ expect(native).not.toHaveBeenCalled()
+ expect(dshLaunch).not.toHaveBeenCalled()
+ expect(calls).toEqual([])
+ // A session the Swarm never started relaunches as it always did.
+ expect(await buildLaunchOverrides(d, 'claude', { cwd: workspace() }, 'agent-1', () => true)).toMatchObject({ ok: true })
+ })
+
it('refuses the relaunch when the app\'s files cannot be written', async () => {
const root = join(env.ADAPTER_DATA_DIR, 'swarm-github')
rmSync(root, { recursive: true, force: true })
diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.ts
index ba52fd83d..92fb1e5b8 100644
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@ -1,5 +1,4 @@
-import { prepareSwarmSkill, type SwarmSkill } from './swarmSkills.js'
-import { swarmGitHubLaunch } from './swarmGitHub.js'
+import type { SwarmSkill } from './savedSkill.js'
/**
* What a pane has to be launched WITH, beyond the engine's own argv, for the engine to come back
* where it was: on the same grid with the same credential, or under the same Codex profile.
@@ -113,8 +112,19 @@ export interface LaunchOverridesDeps {
/** Read an engine's settings for the pull request line (engines/launches.ts `attributionArgs`). A seam, like
* `readCodexConfig`: absent ⇒ the real file. */
readAttribution?: (path: string) => string | null
+ /** What the Swarm prepares on every relaunch of a session it started: its skill file and instructions
+ * (lib/swarmSkills.ts) and the Harness GitHub App's git and gh (lib/swarmGitHub.ts), handed in by the core from
+ * superTabs/inCore.ts. Absent while the Swarm is off (`HARNESS_SWARM`), when such a session is not relaunched: as
+ * with a harness package that is missing, starting it without its role would silently change what it is. */
+ swarm?: {
+ prepare(workspace: string, saved: SwarmSkill): { instructions: string }
+ github(key: string): { env: Record<string, string>; clearEnv: string[] } | null
+ }
}
+/** The answer to relaunching a Swarm session while the Swarm is off on this computer. */
+export const SWARM_OFF = { ok: false, error: 'SWARM_SKILL_FAILED', detail: 'The Swarm is off on this computer (HARNESS_SWARM).' } as const
+
/** Where the agent should come back: the registry row, or an override the desktop just sent. */
export interface LaunchSource extends NativeLaunchSource {
gridLaunch?: GridLaunchOverride | null
@@ -214,6 +224,8 @@ export async function prepareLaunchOverrides(
): Promise<LaunchPreparationResult> {
const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during launch preparation.' } as const
if (!current()) return changed
+ if (source.swarmSkill && !deps.swarm) return SWARM_OFF
+ const swarm = deps.swarm
const owner = current
source = structuredClone(source)
const inspected = capturedNative ? { ok: true as const, launch: capturedNative } : await deps.native?.(engine, source, { id: configKey, current: owner })
@@ -276,8 +288,8 @@ export async function prepareLaunchOverrides(
if (scmEnv) overrides = { ...overrides, env: { ...overrides.env, ...scmEnv } }
// A session started for another person's project keeps git and gh on the Harness GitHub App (lib/swarmGitHub.ts).
if (source.swarmSkill?.github) {
- let github: ReturnType<typeof swarmGitHubLaunch>
- try { github = swarmGitHubLaunch(source.swarmSkill.key) } catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }
+ let github: ReturnType<NonNullable<LaunchOverridesDeps['swarm']>['github']>
+ try { github = swarm!.github(source.swarmSkill.key) } catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }
if (github) overrides = { ...overrides, env: { ...overrides.env, ...github.env }, clearEnv: [...overrides.clearEnv, ...github.clearEnv] }
}
// The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an
@@ -296,7 +308,7 @@ export async function prepareLaunchOverrides(
if (source.swarmSkill) {
try {
if (!source.cwd) throw new Error('The Swarm session has no saved workspace')
- swarmInstructions = prepareSwarmSkill(source.cwd, source.swarmSkill).instructions
+ swarmInstructions = swarm!.prepare(source.cwd, source.swarmSkill).instructions
} catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }
}
const told = agentLaunchArgs(engine, source.startedBy, {
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 0c66644ec..9b5753079 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -1,4 +1,4 @@
-import { parseSwarmSkill, type SwarmSkill } from './swarmSkills.js'
+import { parseSwarmSkill, type SwarmSkill } from './savedSkill.js'
/**
* Registry of process-owned AGENTS — one per supported top-level engine process in a tmux pane.
*
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index cdba5c3c7..77cb73fd9 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -1,5 +1,5 @@
/** Exact-resume lifecycle shared by the daemon and its isolated acceptance tests. */
-import type { AdoptSwarmSkill } from '../core/agents/swarmSkills.js'
+import type { AdoptSwarmSkill } from '../core/api.js'
import { transcriptSize, type RelaunchMarks } from '../core/transcripts/relaunch.js'
import { isTerminalEngine } from '../engines/types.js'
import { installedDsh } from '../dsh/installed.js'
diff --git a/cli/src/lib/savedSkill.ts b/cli/src/lib/savedSkill.ts
new file mode 100644
index 000000000..49f0c086c
--- /dev/null
+++ b/cli/src/lib/savedSkill.ts
@@ -0,0 +1,23 @@
+/**
+ * The Swarm skill a registry row keeps (`swarmSkill`), as data: its shape and how a saved one is read back. Apart from
+ * the skill itself (lib/swarmSkills.ts), so the registry, which every process loads, reads its rows without loading the
+ * Swarm's code: with the Swarm off (`HARNESS_SWARM`, harnessd/services.ts) a row keeps the field and nothing acts on it.
+ */
+export type SwarmRole = 'lead' | 'dev' | 'review'
+/** A Swarm project's skill set, which its owner chooses (2026-10-23): Default is the team process alone, Harness orchestration
+ * adds Harness practices. A session saved without one launched before modes, on the orchestration text. */
+export type SwarmSkillMode = 'default' | 'orchestration'
+/** `github`: git and gh in this session use the Harness GitHub App's token for its task (lib/swarmGitHub.ts), set when a
+ * start does another person's project work (superTabs/start.ts) and kept for every relaunch. */
+export interface SwarmSkill { role: SwarmRole; key: string; mode?: SwarmSkillMode; github?: true }
+/** What a session's current Swarm membership grants it, before it has a key. */
+export type SwarmSkillGrant = Omit<SwarmSkill, 'key' | 'github'>
+export const isSwarmRole = (value: unknown): value is SwarmRole => value === 'lead' || value === 'dev' || value === 'review'
+export const isSwarmSkillMode = (value: unknown): value is SwarmSkillMode => value === 'default' || value === 'orchestration'
+
+export function parseSwarmSkill(value: unknown): SwarmSkill | undefined {
+ if (!value || typeof value !== 'object') return undefined
+ const { role, key, mode, github } = value as Partial<SwarmSkill>
+ return isSwarmRole(role) && typeof key === 'string' && key.length > 0
+ ? { role, key, ...(isSwarmSkillMode(mode) ? { mode } : {}), ...(github === true ? { github } : {}) } : undefined
+}
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 86e2a07a8..bd0a33127 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -9,6 +9,9 @@ import { agentLaunchArgs } from './agentAttribution.js'
import { buildLaunchOverrides } from './launchOverrides.js'
import { gridLaunchInProcess } from '../testing/gridLaunchInProcess.js'
+/** The Swarm's relaunch preparation, as the core hands it in while the Swarm is on (lib/launchOverrides.ts `swarm`). */
+const SWARM = { prepare: prepareSwarmSkill, github: () => null }
+
const roots: string[] = []
const fixture = () => { const root = mkdtempSync(join(tmpdir(), 'swarm-skills-')); roots.push(root); return root }
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
@@ -404,7 +407,7 @@ describe('built-in Swarm skills', () => {
const cwd = fixture(), swarmSkill = { role: 'dev' as const, key: 'original' }
const first = prepareSwarmSkill(cwd, swarmSkill)
const result = await buildLaunchOverrides({ capabilities: async () => ({ sessionEnv: true }), installCodexHooks: () => true, machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(),
- writeGridConfigDir: async () => '/unused', readCodexConfig: () => null, readAttribution: () => null }, engine, { cwd, swarmSkill }, 'new-registry-id')
+ writeGridConfigDir: async () => '/unused', readCodexConfig: () => null, readAttribution: () => null, swarm: SWARM }, engine, { cwd, swarmSkill }, 'new-registry-id')
expect(result.ok).toBe(true)
if (result.ok) expect(result.overrides?.extraArgs.join(' ')).toContain(first.file)
expect(readdirSync(join(cwd, '.harness', 'runtime'))).toHaveLength(1)
@@ -413,8 +416,8 @@ describe('built-in Swarm skills', () => {
it('refuses relaunch with a missing workspace or a redirected runtime', async () => {
const cwd = fixture(), swarmSkill = { role: 'dev' as const, key: 'original' }
symlinkSync(fixture(), join(cwd, '.harness'))
- const deps = { capabilities: async () => ({ sessionEnv: true }), installCodexHooks: () => true, machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(), writeGridConfigDir: async () => '/unused' }
- expect(await buildLaunchOverrides(deps, 'claude', { swarmSkill }, 'a')).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED' })
- expect(await buildLaunchOverrides(deps, 'claude', { cwd, swarmSkill }, 'a')).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED' })
+ const deps = { capabilities: async () => ({ sessionEnv: true }), installCodexHooks: () => true, machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(), writeGridConfigDir: async () => '/unused', swarm: SWARM }
+ expect(await buildLaunchOverrides(deps, 'claude', { swarmSkill }, 'a')).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED', detail: expect.stringContaining('no saved workspace') })
+ expect(await buildLaunchOverrides(deps, 'claude', { cwd, swarmSkill }, 'a')).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED', detail: expect.not.stringContaining('HARNESS_SWARM') })
})
})
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index adbcacf97..10615ed59 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -3,25 +3,11 @@ import { ignoreHarnessRuntime } from './harnessRuntimeIgnore.js'
import { createHash, randomUUID } from 'node:crypto'
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
import { join, relative, sep } from 'node:path'
+import { isSwarmRole, isSwarmSkillMode, parseSwarmSkill, type SwarmRole, type SwarmSkill, type SwarmSkillGrant, type SwarmSkillMode } from './savedSkill.js'
-export type SwarmRole = 'lead' | 'dev' | 'review'
-/** A Swarm project's skill set, which its owner chooses (2026-10-23): Default is the team process alone, Harness orchestration
- * adds Harness practices. A session saved without one launched before modes, on the orchestration text. */
-export type SwarmSkillMode = 'default' | 'orchestration'
-/** `github`: git and gh in this session use the Harness GitHub App's token for its task (lib/swarmGitHub.ts), set when a
- * start does another person's project work (superTabs/start.ts) and kept for every relaunch. */
-export interface SwarmSkill { role: SwarmRole; key: string; mode?: SwarmSkillMode; github?: true }
-/** What a session's current Swarm membership grants it, before it has a key. */
-export type SwarmSkillGrant = Omit<SwarmSkill, 'key' | 'github'>
-export const isSwarmRole = (value: unknown): value is SwarmRole => value === 'lead' || value === 'dev' || value === 'review'
-export const isSwarmSkillMode = (value: unknown): value is SwarmSkillMode => value === 'default' || value === 'orchestration'
-
-export function parseSwarmSkill(value: unknown): SwarmSkill | undefined {
- if (!value || typeof value !== 'object') return undefined
- const { role, key, mode, github } = value as Partial<SwarmSkill>
- return isSwarmRole(role) && typeof key === 'string' && key.length > 0
- ? { role, key, ...(isSwarmSkillMode(mode) ? { mode } : {}), ...(github === true ? { github } : {}) } : undefined
-}
+// The saved record's shape and parse live with the registry's rows (lib/savedSkill.ts), which load without the Swarm.
+export { isSwarmRole, isSwarmSkillMode, parseSwarmSkill }
+export type { SwarmRole, SwarmSkill, SwarmSkillGrant, SwarmSkillMode }
/** The owner's texts, used verbatim. */
const orchestration: Record<SwarmRole, string> = {
diff --git a/cli/src/serviceProcess.spec.ts b/cli/src/serviceProcess.spec.ts
index 1c651f737..013e38f67 100644
--- a/cli/src/serviceProcess.spec.ts
+++ b/cli/src/serviceProcess.spec.ts
@@ -89,6 +89,30 @@ describe('a service in its own process', () => {
expect(stops.usage).toHaveBeenCalledOnce()
})
+ // The review of #1765: with the Swarm off, the edge host still loaded its retention and the agent cleanup kept its
+ // members. Its side is loaded only on, only for a service that acts on it, and handed to it there.
+ it('hands the Swarm\'s side only to the services that act on it, only while the Swarm is on', async () => {
+ const swarm = { retainedHarnesses: () => new Set(['member']) } as never
+ const load = vi.fn(async () => swarm)
+ const run = async (named: string, env: Record<string, string | undefined>) => {
+ const seen: ServiceProcessOptions[] = []
+ const runners = new Map(['agentCleanup', 'sharing', 'handoff', 'models', 'search', 'workspaces'].map(name =>
+ [name, async () => (options: ServiceProcessOptions) => { seen.push(options); return { stop: vi.fn() } }]))
+ const saved = process.env.HARNESS_SWARM
+ if (env.HARNESS_SWARM === undefined) delete process.env.HARNESS_SWARM; else process.env.HARNESS_SWARM = env.HARNESS_SWARM
+ try { await startServiceProcess(named, { runners, host: fakeHost().host, swarm: load }) } finally {
+ if (saved === undefined) delete process.env.HARNESS_SWARM; else process.env.HARNESS_SWARM = saved
+ }
+ return seen.map(options => options.swarm)
+ }
+ for (const named of ['agentCleanup', 'sharing', 'handoff', 'models']) expect(await run(named, {}), named).toEqual([swarm])
+ expect(await run('workspaces,agentCleanup', {})).toEqual([swarm, swarm])
+ expect(load).toHaveBeenCalledTimes(5)
+ expect(await run('search,workspaces', {})).toEqual([undefined, undefined])
+ for (const off of ['off', 'OFF', '0', 'false', 'no']) expect(await run('workspaces,agentCleanup,models', { HARNESS_SWARM: off }), off).toEqual([undefined, undefined, undefined])
+ expect(load).toHaveBeenCalledTimes(5)
+ })
+
it('leaves off a service that cannot start and runs the others; with none started it fails as a lone one did', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const fails = async () => () => { throw new Error('injected fault: usage') }
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 1b9f50581..f4ed9a93f 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -9,19 +9,28 @@
* (2026-10-05).
*/
import { env } from './config/env.js'
+import { swarmOn } from './harnessd/swarmSwitch.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
import { harnessdEnv, holdHarnessdEnv } from './lib/harnessdEnv.js'
import { readOrMintComputerId } from './lib/computerIdentity.js'
import { unixSocketPath } from './lib/localSocket.js'
import { ignoreLogWriteErrors, installTimestampedConsole } from './lib/log.js'
import { hostServices, type ServiceHost, type ServiceHostOptions, type ServiceProcess } from './services/process.js'
+import type * as SwarmServicesEntry from './superTabs/inServices.js'
export interface ServiceProcessOptions {
dataDir: string
socketPath: string
machineId: string
token: string
+ /** The Swarm's side of the services that act on it (superTabs/inServices.ts): loaded only while the Swarm is on, and
+ * only for those services (`SWARM_HELPED`). Absent, each runs as it does without the Swarm. */
+ swarm?: SwarmServices
}
+export type SwarmServices = typeof SwarmServicesEntry
+
+/** The services that act on the Swarm from outside it, each given its side while it is on (superTabs/inServices.ts). */
+export const SWARM_HELPED: ReadonlySet<string> = new Set(['agentCleanup', 'sharing', 'handoff', 'models'])
type Runner = (options: ServiceProcessOptions) => ServiceProcess
/** The processes the master runs that speak only to it, never to the core: they need no local socket. */
@@ -68,6 +77,8 @@ export interface ServiceProcessDeps {
/** The process the services run in; swapped in tests for one that touches no channel, signal or exit. */
host?: (options: ServiceHostOptions) => ServiceHost
exit?: (code: number) => never
+ /** Loads the Swarm's side of the services (superTabs/inServices.ts); swapped in tests. */
+ swarm?: () => Promise<SwarmServices>
}
const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error))
@@ -109,11 +120,16 @@ export async function startServiceProcess(named: string | undefined, deps: Servi
// a service's said nothing of when.
installTimestampedConsole()
const loaded = await Promise.all(names.map(async (name) => [name, await runners.get(name)!()] as const))
+ // Off (`HARNESS_SWARM`), none of the Swarm's code is loaded here; on, only a process running a service that acts on it
+ // loads its side, as the services did before there was a switch.
+ const swarm = swarmOn(harnessdEnv()) && names.some((name) => SWARM_HELPED.has(name))
+ ? await (deps.swarm ?? (() => import('./superTabs/inServices.js')))() : undefined
const options: ServiceProcessOptions = {
dataDir: env.ADAPTER_DATA_DIR,
socketPath: socketPath ?? '',
machineId: readOrMintComputerId(env.ADAPTER_COMPUTER_ID_FILE, env.ADAPTER_COMPUTER_ID),
token: harnessdEnv().HARNESSD_SERVICE_TOKEN ?? '',
+ ...(swarm ? { swarm } : {}),
}
const running: ServiceProcess[] = []
let failure: unknown = null
diff --git a/cli/src/services/agentCleanup.spec.ts b/cli/src/services/agentCleanup.spec.ts
index 95ebb487e..0a9ab1f90 100644
--- a/cli/src/services/agentCleanup.spec.ts
+++ b/cli/src/services/agentCleanup.spec.ts
@@ -6,7 +6,7 @@ import { emptyPorts } from '../core/api.js'
import type { AgentCloseResult } from '../lib/closeAgentService.js'
import type { RegisteredSession } from '../lib/registry.js'
import { fakeCore } from '../testing/fakeCore.js'
-import { RETENTION_LAPSE_MS, retainContributions, retentionFile } from '../superTabs/retention.js'
+import { RETENTION_LAPSE_MS, retainContributions, retainedHarnesses, retentionFile } from '../superTabs/retention.js'
import { ASK_AGAIN_MS, CASCADE_RETRY_MS, CASCADE_TRIES, createAgentCleanup, IDLE_CLOSE_MS, JOINED_MAX, joinedPath, LOOK_EVERY_MS, startAgentCleanup, type AgentCleanupDeps } from './agentCleanup.js'
const NOW = Date.parse('2026-10-12T12:00:00Z')
@@ -45,8 +45,9 @@ function setup(sessions: RegisteredSession[], quietFor: Record<string, number |
const log = vi.fn()
let tick: (() => void) | null = null
const waited: number[] = []
+ // The Swarm on, as by default (`HARNESS_SWARM`): its members are kept. A test of it off leaves `retained` out.
const cleanup = createAgentCleanup(core, { now: () => clock, log, every: (_ms, run) => { tick = run; return () => { tick = null } },
- wait: async (ms) => { waited.push(ms) }, ...over })
+ wait: async (ms) => { waited.push(ms) }, retained: (dataDir) => retainedHarnesses(dataDir), ...over })
return { cleanup, core, closeStarted, lastActivity, log, waited, advance: (ms: number) => { clock += ms }, tick: () => tick }
}
@@ -93,6 +94,36 @@ it('never closes a Swarm Lead, idle or orphaned, even once its roster has lapsed
t.cleanup.port.stop()
})
+// HARNESS_SWARM=off: the Swarm hands in no members, its saved roster is not read, and a harness it kept is an ordinary
+// one another agent started: closed with its starter, closed once idle, and closable by the core. The review of #1765
+// found it kept, where the same harness on a computer without the Swarm is closed.
+it('with the Swarm off, cleans up a harness its saved roster names, as any other', async () => {
+ retainContributions(dir, 'machine-1', [{ tabId: 'tab', lead: true, agent: { harnessId: 'pm', machineId: 'machine-1' } },
+ { tabId: 'tab', agent: { harnessId: 'orphan', machineId: 'machine-1' } }, { tabId: 'tab', agent: { harnessId: 'idle', machineId: 'machine-1' } }])
+ expect(retainedHarnesses(dir)).toEqual(new Set(['pm', 'orphan', 'idle']))
+ const sessions = [kid('orphan'), kid('idle', { parentAgentId: 'alive' }), kid('pm', { parentAgentId: 'alive' }), row('alive')]
+ const t = setup(sessions, { idle: 2 * IDLE_CLOSE_MS, pm: 2 * IDLE_CLOSE_MS }, { retained: undefined })
+ await t.cleanup.closeStartedBy('lead')
+ expect(t.closeStarted.mock.calls).toEqual([['orphan', 'now']])
+ await t.cleanup.look()
+ t.advance(IDLE_CLOSE_MS)
+ await t.cleanup.look()
+ expect(t.closeStarted.mock.calls).toEqual([['orphan', 'now'], ['idle', 'idle'], ['pm', 'idle']])
+ expect(sessions.map(s => s.agentId)).toEqual(['alive'])
+ t.cleanup.port.stop()
+ // In the core's process too (services/inline.ts): started without the Swarm it keeps no one, and with it, its members.
+ for (const [retained, closed] of [[undefined, ['orphan']], [(dataDir: string) => retainedHarnesses(dataDir), []]] as const) {
+ const ports = emptyPorts(), live = [kid('orphan')]
+ const closeStarted = vi.fn(async (agentId: string) => { live.splice(live.findIndex(s => s.agentId === agentId), 1); return { closed: true as const } })
+ startAgentCleanup(fakeCore({ dataDir: dir, agents: { live: vi.fn(() => [...live]), resolve: vi.fn(() => undefined), closeStarted } }), ports, retained)
+ ports.agentCleanup!.closed('lead')
+ await vi.waitFor(() => expect(live.map(s => s.agentId)).toEqual(closed.length ? [] : ['orphan']))
+ await settle()
+ expect(closeStarted.mock.calls.map(([id]) => id)).toEqual(closed)
+ ports.agentCleanup!.stop()
+ }
+})
+
it('rechecks retention after waiting on activity or another orphan close', async () => {
const t = setup([kid('member')], { member: 2 * IDLE_CLOSE_MS })
await t.cleanup.look()
diff --git a/cli/src/services/agentCleanup.ts b/cli/src/services/agentCleanup.ts
index 26236bdea..42c2cc1c4 100644
--- a/cli/src/services/agentCleanup.ts
+++ b/cli/src/services/agentCleanup.ts
@@ -17,7 +17,9 @@
* theirs from then on, and kept so in `<data>/agent-cleanup.json` across restarts. A harness the person started is
* never one this may close: the core refuses (`CoreApi.agents.closeStarted`).
* - **Keep shared members.** Super Tab membership also protects a harness from both forms of cleanup, even when its
- * terminal is hidden or its host is offline. Only a confirmed roster removal releases that protection.
+ * terminal is hidden or its host is offline. Only a confirmed roster removal releases that protection. The Swarm hands
+ * that membership in while it is on (`retained`); off (`HARNESS_SWARM`), its saved roster is not read and such a
+ * harness is cleaned up as any other.
*
* A close keeps the conversation, as `harness close` does: the person can resume it, and `harness show` still reads its
* answer. One line in the log for each close.
@@ -27,7 +29,6 @@ import { dirname, join } from 'node:path'
import type { AgentCleanupPort, CoreApi, CorePorts } from '../core/api.js'
import type { AgentCloseResult } from '../lib/closeAgentService.js'
import type { RegisteredSession } from '../lib/registry.js'
-import { retainedHarnesses } from '../superTabs/retention.js'
/** How long a harness another agent started may sit idle after its last answer before it is closed. */
export const IDLE_CLOSE_MS = 30 * 60_000
@@ -55,8 +56,13 @@ export interface AgentCleanupDeps {
every?: (ms: number, look: () => void) => () => void
/** Waits [ms] before a starter's harnesses are tried again. */
wait?: (ms: number) => Promise<void>
+ /** The Super Tab members the Swarm keeps here (superTabs/retention.ts `retainedHarnesses`, through
+ * superTabs/inServices.ts): absent while the Swarm is off, when none is kept. */
+ retained?: (dataDir: string) => ReadonlySet<string>
}
+const NONE_RETAINED: ReadonlySet<string> = new Set()
+
function readJoined(file: string): Map<string, number> {
try {
const saved = (JSON.parse(readFileSync(file, 'utf8')) as { joined?: Record<string, unknown> }).joined ?? {}
@@ -78,6 +84,7 @@ export function createAgentCleanup(core: CoreApi, deps: AgentCleanupDeps = {}) {
const log = deps.log ?? ((line: string) => console.log(line))
const refresh = deps.refresh ?? (async () => {})
const wait = deps.wait ?? ((ms: number) => new Promise<void>((done) => { setTimeout(done, ms).unref() }))
+ const retainedHarnesses = deps.retained ?? (() => NONE_RETAINED)
const file = joinedPath(core.dataDir)
const joined = readJoined(file)
/** When one that would not close may be asked again. */
@@ -220,6 +227,6 @@ export function createAgentCleanup(core: CoreApi, deps: AgentCleanupDeps = {}) {
return { port, look, closeStartedBy }
}
-export function startAgentCleanup(core: CoreApi, ports: CorePorts): void {
- ports.agentCleanup = createAgentCleanup(core).port
+export function startAgentCleanup(core: CoreApi, ports: CorePorts, retained?: AgentCleanupDeps['retained']): void {
+ ports.agentCleanup = createAgentCleanup(core, retained ? { retained } : {}).port
}
diff --git a/cli/src/services/agentCleanupProcess.spec.ts b/cli/src/services/agentCleanupProcess.spec.ts
index 3682b0b50..ca75217d0 100644
--- a/cli/src/services/agentCleanupProcess.spec.ts
+++ b/cli/src/services/agentCleanupProcess.spec.ts
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { CoreApi } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import { agentCleanupCoreApi, runAgentCleanupService } from './agentCleanupProcess.js'
+import type { createAgentCleanup } from './agentCleanup.js'
import { runServiceProcess, type CoreConnection, type ServiceProcessOptions } from './process.js'
// The real default reaches a real socket: never in a test.
@@ -77,6 +78,18 @@ describe('the agent cleanup in its own process', () => {
expect(await gone.agents.closeStarted!('k1', 'idle')).toEqual({ error: 'SERVICE_UNAVAILABLE' })
})
+ // HARNESS_SWARM: the Super Tab members it keeps come from the Swarm's side, which its process loads only while it is on.
+ it('keeps the members the Swarm hands it while it is on, and none without it', () => {
+ const given: Array<Parameters<typeof createAgentCleanup>[1]> = []
+ const create = (_core: CoreApi, deps?: Parameters<typeof createAgentCleanup>[1]) => { given.push(deps); return { port: { closed: vi.fn(), typed: vi.fn(), stop: vi.fn() }, look: vi.fn(), closeStartedBy: vi.fn() } }
+ const retainedHarnesses = vi.fn(() => new Set(['member']))
+ const base = { dataDir: dir, socketPath: '/s', machineId: 'm', token: 't', run: () => ({ stop: vi.fn() }), create }
+ runAgentCleanupService({ ...base, swarm: { retainedHarnesses } })
+ runAgentCleanupService(base)
+ expect(given[0]!.retained).toBe(retainedHarnesses)
+ expect(given[1]).not.toHaveProperty('retained')
+ })
+
it('stops its looks with the process', () => {
const { service, port, stop } = setup()
service.stop()
diff --git a/cli/src/services/agentCleanupProcess.ts b/cli/src/services/agentCleanupProcess.ts
index 059805281..653b075bd 100644
--- a/cli/src/services/agentCleanupProcess.ts
+++ b/cli/src/services/agentCleanupProcess.ts
@@ -8,6 +8,7 @@
import type { CoreApi } from '../core/api.js'
import type { AgentCloseResult } from '../lib/closeAgentService.js'
import type { RegisteredSession } from '../lib/registry.js'
+import type { SwarmServices } from '../serviceProcess.js'
import { createAgentCleanup } from './agentCleanup.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { agentsIn, processCoreApi } from './processCoreApi.js'
@@ -21,6 +22,8 @@ export interface AgentCleanupServiceOptions {
run?: typeof runServiceProcess
/** Swapped in tests. */
create?: typeof createAgentCleanup
+ /** The Swarm's side of this service, while the Swarm is on (serviceProcess.ts, superTabs/inServices.ts). */
+ swarm?: Pick<SwarmServices, 'retainedHarnesses'>
}
/** The core API the cleanup runs on here: the light services' (processCoreApi.ts), with the two ways it acts. */
@@ -48,6 +51,7 @@ export function runAgentCleanupService(options: AgentCleanupServiceOptions): Ser
const cleanup = (options.create ?? createAgentCleanup)(agentCleanupCoreApi(options.dataDir, () => agents, ask), {
// A core that cannot say leaves none: nothing is closed on a list that may be stale.
refresh: async () => { agents = agentsIn(await ask('live', {}).catch(() => null)) ?? [] },
+ ...(options.swarm ? { retained: options.swarm.retainedHarnesses } : {}),
})
const service = (options.run ?? runServiceProcess)({
name: 'agentCleanup',
diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.ts
index f22d3c797..4411428eb 100644
--- a/cli/src/services/devices.ts
+++ b/cli/src/services/devices.ts
@@ -164,7 +164,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
try { return await core.superTabRequest!(payload) } catch { return { error: 'SERVICE_UNAVAILABLE' } }
}
// How many attached devices asked for Swarm cards, and which Swarms the desktop has tabs for (read first). The core keeps
- // whether they are wanted (core/superTabCards.ts); this says it on a change and again when the core connects anew.
+ // whether they are wanted (superTabs/inCore/cards.ts); this says it on a change and again when the core connects anew.
let cardDevices = 0
let cardInclude: string[] = []
const tellCards = (): void => { void askCards({ action: 'cardsWanted', on: cardDevices > 0, include: cardDevices > 0 ? cardInclude : [] }) }
@@ -441,7 +441,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
const close = cableQuestionCloseFor(frame as Parameters<typeof cableQuestionCloseFor>[0])
if (close) { inOrder(close.agentId, () => { void cable.questionClose(close.agentId, close.requestId) }); return }
const question = cableQuestionFor(frame as Parameters<typeof cableQuestionFor>[0])
- // A Super Tab member waiting on a person (core/superTabAttention.ts) is an alert as any question is.
+ // A Super Tab member waiting on a person (superTabs/inCore/attention.ts) is an alert as any question is.
if (question) { tally(cableHost.describe(question.agentId)?.name ?? '', 'alert', question.superTab ? 'rule:super-tab' : 'rule:question', 'question', 0); inOrder(question.agentId, () => { void cable.question(question.agentId, question.requestId, question.questions, question.superTab) }); return }
// A shell result is only the stats' input: the dial is told the sums when the turn ends.
const ran = frame as { type?: string; agentId?: string; payload?: { kind?: string; id?: string; command?: string; isError?: boolean; outputTail?: string } }
diff --git a/cli/src/services/handoff.spec.ts b/cli/src/services/handoff.spec.ts
index 6d213fece..131cdc5df 100644
--- a/cli/src/services/handoff.spec.ts
+++ b/cli/src/services/handoff.spec.ts
@@ -4,7 +4,8 @@ import type { HandoffDeps } from '../lib/agentHandoff.js'
import type { RegisteredSession } from '../lib/registry.js'
import { fakeCore } from '../testing/fakeCore.js'
import { HANDOFF_REQUESTS, startHandoff } from './handoff.js'
-import { mkdtempSync, rmSync } from 'node:fs'
+import { recordReplacement } from '../superTabs/replacements.js'
+import { existsSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -17,16 +18,32 @@ describe('the change-agent handoff service', () => {
try {
const old = { agentId: 'old', cwd: '/repo', resumeOnly: true }, target = { agentId: 'new', cwd: '/repo', engine: 'claude' }
const core = fakeCore({ dataDir, conversations: { resolve: vi.fn(async id => (id === 'old' ? old : target) as never) } })
- const handler = startHandoff(core).agent_handoff_complete!
+ const handler = startHandoff(core, undefined, undefined, recordReplacement).agent_handoff_complete!
const payload = { agentId: 'old', replacementId: 'new', changeId: '0123456789abcdef', targetEngine: 'claude' }
expect(await handler(payload, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(existsSync(join(dataDir, 'super-tabs'))).toBe(false)
expect(await handler(payload, owner)).toEqual({ ok: true })
+ expect(existsSync(join(dataDir, 'super-tabs'))).toBe(true)
expect(await handler(payload, owner)).toEqual({ ok: true })
expect(await handler({ ...payload, replacementId: 'old' }, owner)).toMatchObject({ error: 'HANDOFF_UNAVAILABLE' })
const closed = new AbortController(); closed.abort()
expect(await handler(payload, owner, closed.signal)).toMatchObject({ error: 'HANDOFF_UNAVAILABLE' })
} finally { rmSync(dataDir, { recursive: true, force: true }) }
})
+ // HARNESS_SWARM=off: the edge host hands in no Swarm, and a completed change is the person's alone: nothing is recorded
+ // for a Super Tab's host, and none of its saved state is written.
+ it('records nothing for the Swarm while it is off, and still asks the owner', async () => {
+ const dataDir = mkdtempSync(join(tmpdir(), 'handoff-off-'))
+ try {
+ const resolve = vi.fn(async () => null)
+ const handler = startHandoff(fakeCore({ dataDir, conversations: { resolve } })).agent_handoff_complete!
+ const payload = { agentId: 'old', replacementId: 'new', changeId: '0123456789abcdef', targetEngine: 'claude' }
+ expect(await handler(payload, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(await handler(payload, owner)).toEqual({ ok: true })
+ expect(resolve).not.toHaveBeenCalled()
+ expect(existsSync(join(dataDir, 'super-tabs'))).toBe(false)
+ } finally { rmSync(dataDir, { recursive: true, force: true }) }
+ })
it('uses the real provider by default and preserves its unknown-agent answer', async () => {
const handlers = startHandoff(fakeCore())
expect(Object.keys(handlers)).toEqual([...HANDOFF_REQUESTS])
diff --git a/cli/src/services/handoff.ts b/cli/src/services/handoff.ts
index d10469659..f35ae77a8 100644
--- a/cli/src/services/handoff.ts
+++ b/cli/src/services/handoff.ts
@@ -4,11 +4,13 @@ import { performance } from 'node:perf_hooks'
import { HANDOFF_REQUESTS, type CoreApi, type CorePorts, type ServiceRequests } from '../core/api.js'
import { prepareAgentHandoff, type HandoffDeps } from '../lib/agentHandoff.js'
import { createHandoffRequest } from './handoffRequest.js'
-import { recordReplacement } from '../superTabs/replacements.js'
+import type { recordReplacement } from '../superTabs/replacements.js'
export { HANDOFF_REQUESTS }
-export function startHandoff(core: CoreApi, _ports?: CorePorts, prepare = prepareAgentHandoff): ServiceRequests {
+/** `replacements`: a Super Tab member's replacement, recorded for its host (superTabs/replacements.ts, through
+ * superTabs/inServices.ts). Absent while the Swarm is off (`HARNESS_SWARM`), when a completed change records nothing. */
+export function startHandoff(core: CoreApi, _ports?: CorePorts, prepare = prepareAgentHandoff, replacements?: typeof recordReplacement): ServiceRequests {
const reads = core.conversations
const deps: HandoffDeps = {
resolve: (id) => reads.resolve(id),
@@ -32,7 +34,7 @@ export function startHandoff(core: CoreApi, _ports?: CorePorts, prepare = prepar
if (!asker.owner) return { error: 'OWNER_REQUIRED' }
try {
if (closed?.aborted) return { error: 'HANDOFF_UNAVAILABLE' }
- await recordReplacement(core, payload)
+ await replacements?.(core, payload)
return { ok: true }
} catch { return { error: 'HANDOFF_UNAVAILABLE' } }
} }
diff --git a/cli/src/services/handoffProcess.spec.ts b/cli/src/services/handoffProcess.spec.ts
index 61430afba..90bdafcea 100644
--- a/cli/src/services/handoffProcess.spec.ts
+++ b/cli/src/services/handoffProcess.spec.ts
@@ -123,6 +123,16 @@ describe('the handoff in the edge host', () => {
expect(Object.keys(vi.mocked(runServiceProcess).mock.calls.at(-1)![0].requests)).toEqual([...HANDOFF_REQUESTS])
})
+ // HARNESS_SWARM: a member's replacement is recorded by the Swarm's side, which its process loads only while it is on.
+ it('hands the change-agent handoff the Swarm\'s record while it is on, and none without it', () => {
+ const start = vi.fn((..._args: Parameters<typeof startHandoff>) => ({}))
+ const recordReplacement = vi.fn()
+ const base = { dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't', run: () => ({ stop: vi.fn() }), start }
+ runHandoffService({ ...base, swarm: { recordReplacement } })
+ runHandoffService(base)
+ expect(start.mock.calls.map(call => call[3])).toEqual([recordReplacement, undefined])
+ })
+
it('reads SQLite only for a store-backed conversation and hands that one over', async () => {
const ws = mkdtempSync(join(tmpdir(), 'handoff-store-'))
try {
diff --git a/cli/src/services/handoffProcess.ts b/cli/src/services/handoffProcess.ts
index dd935894c..dc513929b 100644
--- a/cli/src/services/handoffProcess.ts
+++ b/cli/src/services/handoffProcess.ts
@@ -4,6 +4,7 @@ import { HandoffError, handoffBaseName, type HandoffOutcome } from '../lib/hando
import type { CoreApi } from '../core/api.js'
import { ENGINES, type AgentEngine } from '../engines/types.js'
import { databaseHistory } from '../lib/databaseHistory.js'
+import type { SwarmServices } from '../serviceProcess.js'
import { startHandoff } from './handoff.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { isSession, processCoreApi } from './processCoreApi.js'
@@ -71,6 +72,8 @@ export interface HandoffServiceOptions {
token: string
run?: typeof runServiceProcess
start?: typeof startHandoff
+ /** The Swarm's side of this service, while the Swarm is on (serviceProcess.ts, superTabs/inServices.ts). */
+ swarm?: Pick<SwarmServices, 'recordReplacement'>
}
export function runHandoffService(options: HandoffServiceOptions): ServiceProcess {
@@ -79,7 +82,7 @@ export function runHandoffService(options: HandoffServiceOptions): ServiceProces
core.daemon = { ...core.daemon, machineId: () => options.machineId }
return (options.run ?? runServiceProcess)({
name: 'handoff', socketPath: options.socketPath, machineId: options.machineId, token: options.token,
- requests: (options.start ?? startHandoff)(core),
+ requests: (options.start ?? startHandoff)(core, undefined, undefined, options.swarm?.recordReplacement),
onConnected: (linked) => { connection = linked },
})
}
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index bd5c037f3..b8ae7e909 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -29,7 +29,6 @@ import { startShell } from './shell.js'
import { startSharedMachines } from './sharedMachines.js'
import { startSharing } from './sharing.js'
import { startStoreInCore } from './store.js'
-import { startSuperTabs } from './superTabs.js'
import { startUsageInCore } from './usage.js'
import { startViewers } from './viewers.js'
import { startWifi } from './wifi.js'
@@ -37,7 +36,9 @@ import { startWindowNames } from './windowNames.js'
import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
+ // The Swarm's own start is the Swarm's entry's (superTabs/inCore.ts), loaded only while it is on: a core running every
+ // service in its process with the Swarm off loads none of it.
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startMachineAddons, startProjects, startRecaps, startRouter, startSearch, startSharedMachines, startSharing, startShell, startStoreInCore, startSuperTabs, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startMachineAddons, startProjects, startRecaps, startRouter, startSearch, startSharedMachines, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 229626f1f..88c07c913 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -37,7 +37,6 @@ export { startMachineAddons } from './machineAddons.js'
export { startProjects } from './projects.js'
export { startRecaps } from './recaps.js'
export { startRouter } from './router.js'
-export { startSuperTabs } from './superTabs.js'
export { startSearch } from './search.js'
export { startShell } from './shell.js'
export { startSharing } from './sharing.js'
diff --git a/cli/src/services/models.spec.ts b/cli/src/services/models.spec.ts
index a303c6537..33ab0f9df 100644
--- a/cli/src/services/models.spec.ts
+++ b/cli/src/services/models.spec.ts
@@ -29,6 +29,11 @@ import { compactRuntimePickerModels, launchTarget, MODELS_REQUESTS, startModels,
import { gridExec } from '../lib/gridExec.js'
import { syncSwarmGrid } from '../lib/swarmGrid.js'
import { SwarmApiShares } from '../lib/swarmApiShares.js'
+import { liveModels, SwarmHeal } from '../lib/swarmHeal.js'
+import { SwarmOffers } from '../lib/swarmOffers.js'
+
+/** The Swarm's side of models, as its process hands it in while the Swarm is on (superTabs/inServices.ts). */
+const SWARM = { syncSwarmGrid, SwarmApiShares, SwarmHeal, liveModels, SwarmOffers }
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', () => ({
@@ -124,11 +129,11 @@ type AttemptDeps = Parameters<typeof reconcileGridAttach>[0]
type Over = Parameters<typeof fakeCore>[0]
const onGrid = (agentId: string, state: string) => ({ agentId, grid: { state } }) as unknown as RegisteredSession
-function setup(advertised: RegisteredSession[] = [], over: Over = {}) {
+function setup(advertised: RegisteredSession[] = [], over: Over = {}, swarm: typeof SWARM | null = SWARM) {
const list = [...advertised]
const core = fakeCore({ ...over, agents: { advertised: vi.fn(() => list), sync: vi.fn(), ...over.agents } })
const ports = emptyPorts()
- const requests = startModels(core, ports)
+ const requests = startModels(core, ports, swarm ?? undefined)
const options = vi.mocked(createGridAccess).mock.calls.at(-1)![0]
const changed = vi.mocked(onGridModelsChanged).mock.calls.at(-1)![0]
/** Ask one request as a local window would. */
@@ -493,6 +498,27 @@ describe('the models service', () => {
expect(swarmOffers.list).toHaveBeenLastCalledWith(undefined)
})
+ // HARNESS_SWARM=off: its process hands in no Swarm. Nothing of it starts (no API is restored or served to a Swarm's
+ // grid), its requests are answered as its own service's are, and a deleted API has no share to come off.
+ it('with the Swarm off, serves nothing to a Swarm and answers its requests unavailable', async () => {
+ vi.mocked(SwarmApiShares).mockClear()
+ vi.mocked(SwarmOffers).mockClear()
+ const { requests } = setup([], {}, null)
+ expect(SwarmApiShares).not.toHaveBeenCalled()
+ expect(SwarmOffers).not.toHaveBeenCalled()
+ for (const type of ['grid_swarm_sync', 'grid_swarm_api_share', 'grid_swarm_api_shares', 'grid_swarm_offer', 'grid_swarm_offers', 'grid_swarm_heal']) {
+ expect(await requests[type]!({ grid: 'swarm-0123456789ab', members: [], connectionId: 'c1', model: 'm', action: 'start' }, asker), type)
+ .toEqual({ error: 'SERVICE_UNAVAILABLE', service: 'superTabs', retryable: false })
+ }
+ expect(syncSwarmGrid).not.toHaveBeenCalled()
+ expect(apiShares.share).not.toHaveBeenCalled()
+ expect(apiShares.restore).not.toHaveBeenCalled()
+ await requests.api_connections!({ action: 'remove', id: 'c1' }, asker)
+ expect(apiShares.stopConnection).not.toHaveBeenCalled()
+ // The rest of models is as it is with the Swarm on.
+ expect(await requests.grid_fleet_run!(COMMAND, asker)).toMatchObject({ ok: true })
+ })
+
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' })
diff --git a/cli/src/services/models.ts b/cli/src/services/models.ts
index 9bb712be5..164657799 100644
--- a/cli/src/services/models.ts
+++ b/cli/src/services/models.ts
@@ -41,10 +41,7 @@ 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 { liveModels, SwarmHeal } from '../lib/swarmHeal.js'
-import { SwarmOffers } from '../lib/swarmOffers.js'
+import type * as SwarmServicesEntry from '../superTabs/inServices.js'
import { internalOnThrow } from './requestErrors.js'
/** The requests models answers for the apps, declared in core/api.ts for the core to route. */
@@ -58,7 +55,12 @@ interface GridSetUp {
setUp(): boolean
}
-export function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {
+/** What models runs of the Swarm while it is on (superTabs/inServices.ts, docs/plans/2026-10-23-swarm-local-models.md):
+ * a Swarm's grid, the APIs and models shared with it, and the check that keeps them there. Absent while the Swarm is
+ * off (`HARNESS_SWARM`): none of it is loaded, no API is served to a Swarm, and its requests are answered unavailable. */
+export type SwarmModels = Pick<typeof SwarmServicesEntry, 'syncSwarmGrid' | 'SwarmApiShares' | 'SwarmHeal' | 'liveModels' | 'SwarmOffers'>
+
+export function startModels(core: CoreApi, ports: CorePorts, swarm?: SwarmModels): ServiceRequests {
// A managed grid already here follows its pin on EVERY start of this service — the daemon's, and the
// restart a self-update ends in — not only on `--repair`: the pin is expected to move, and a machine
// installed last month has to notice. A machine with none gets none from a start: grid is an add-on,
@@ -179,7 +181,7 @@ export function startModels(core: CoreApi, ports: CorePorts): ServiceRequests {
// The web-tools cache lives exactly as long as the sign-in.
signedOut: () => clearGridMcpUrlCache(),
}
- return modelsRequests(core, grid, privateGridName)
+ return modelsRequests(core, grid, privateGridName, swarm)
}
/**
@@ -242,9 +244,9 @@ async function moveTarget(
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 {
+function swarmApiShares(dataDir: string, swarm: SwarmModels): InstanceType<SwarmModels['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') })
+ const shares = new swarm.SwarmApiShares({ access: (id) => saved.modelAccess(id), exec: (args) => gridExec(args), stateFile: join(dataDir, 'swarm-api-shares.json') })
void shares.restore().catch(() => {})
return shares
}
@@ -261,7 +263,7 @@ type LocalModelRequest = 'grid_fleet_models_list' | 'grid_fleet_model_download'
* answered them itself. A failure is answered as the socket answered it, sentences included: the apps
* show them.
*/
-function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => Promise<string | null>): ServiceRequests {
+function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => Promise<string | null>, swarm?: SwarmModels): ServiceRequests {
// The Model Manager reads the grid it runs on through the same credential-less reader as every picker
// (never `grid engines`, which carries the grid credential and so wakes a sleeping grid on every tick),
// and a start or stop it finishes makes every list read again — pushed to the window when it changes.
@@ -277,17 +279,8 @@ function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => P
appEngines: appEngineOps(process.env),
gpuProcesses: nvidiaComputeApps,
})
- // One set of shared APIs for the process, and the check that keeps them and the local models on each Swarm's grid
- // (lib/swarmHeal.ts).
- const shares = swarmApiShares(core.dataDir)
- const heal = new SwarmHeal({
- live: async (name) => {
- const answer = await gridExec(['--remote', 'models', name, '--json'])
- return answer.code === 'OK' ? liveModels(answer.stdout) : null
- },
- shares: { list: (name) => shares.list(name), rejoin: (name, connectionId, model) => shares.rejoin(name, connectionId, model) },
- apps: { served: (name) => localModels.servedApps(name), rejoin: (name) => localModels.rejoinApp(name) },
- })
+ // A Swarm's grid, the APIs and models shared with it and the check that keeps them there, while the Swarm is on.
+ const swarmSide = swarm ? swarmGridRequests(grid, core.dataDir, swarm, localModels) : null
/** The grid listing currently out, shared by every `grid_models_list` for the same own grid that lands
* meanwhile. */
let listing: { gridName: string | null; grids: Promise<GridSection[]> } | null = null
@@ -398,40 +391,40 @@ function modelsRequests(core: CoreApi, grid: GridSetUp, privateGridName: () => P
grid_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'),
- // What this computer serves on a Swarm's grid that the grid really lists, joined again when it lost them: read by
- // every machine reading (superTabs/machines.ts).
- grid_swarm_heal: async (payload) => {
- if (typeof payload.grid !== 'string' || !SWARM_GRID.test(payload.grid)) return { error: 'INVALID_REQUEST' }
- return { ...await heal.check(payload.grid) }
- },
- ...gridCommands(grid, core.dataDir, shares),
- ...launchTargetRequests(core, (id) => shares.stopConnection(id)),
+ ...gridCommands(),
+ ...(swarmSide?.requests ?? SWARM_OFF_REQUESTS),
+ ...launchTargetRequests(core, async (id) => { await swarmSide?.shares.stopConnection(id) }),
}
}
+/** The Swarm's requests to models (core/api.ts `MODELS_REQUESTS`), answered while it is off as its own service's are. */
+const SWARM_MODELS_REQUESTS = ['grid_swarm_sync', 'grid_swarm_api_share', 'grid_swarm_api_shares', 'grid_swarm_offer', 'grid_swarm_offers', 'grid_swarm_heal'] as const
+const SWARM_OFF_REQUESTS: ServiceRequests = Object.fromEntries(SWARM_MODELS_REQUESTS.map((type) =>
+ [type, () => ({ error: 'SERVICE_UNAVAILABLE', service: 'superTabs', retryable: false })]))
+
/**
- * The Model Manager's grid commands: grid's own argv, run here (`lib/gridFleetRpc.ts`). A command is a job
- * of the connection that started it, keyed by that connection and the id it was asked under (`Asker`),
- * and a cancel stops only that connection's own. Run against grid AS IT STANDS — never set up first: a
- * Grid harness session issues these on its own the moment its viewer comes up (every open one, on every
- * daemon start), so setting grid up here signed a machine in to grid right after a Harness-only sign-in,
- * with nobody asking. Grid is set up by the picker's Set up, by making or opening a Model Manager, and by
- * 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`).
+ * What models answers a Swarm while it is on: its own grid, kept in step with its people (lib/swarmGrid.ts), a saved API
+ * or a model shared with it (lib/swarmApiShares.ts, lib/swarmOffers.ts), and what this computer serves there, checked
+ * against what the grid lists (lib/swarmHeal.ts). One set of shared APIs for the process, since each holds a live
+ * endpoint; its `stopConnection` takes a deleted API off every Swarm first.
*/
-function gridCommands(grid: GridSetUp, dataDir: string, shares: SwarmApiShares = swarmApiShares(dataDir),
- offers: SwarmOffers = new SwarmOffers(join(dataDir, 'swarm-offers.json'))): 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.
- grid_fleet_run: async (payload, asker) => {
- const request = parseGridFleetRequest(payload)
- if (!request || !asker.connection || !asker.requestId) return { error: 'INVALID_GRID_COMMAND' }
- try {
- return { ...await fleet.run(asker.connection, asker.requestId, request) }
- } catch {
- return { ok: false, code: 1, error: 'Grid command failed unexpectedly.' }
- }
+function swarmGridRequests(grid: GridSetUp, dataDir: string, swarm: SwarmModels, localModels: Pick<LocalModels, 'servedApps' | 'rejoinApp'>) {
+ const shares = swarmApiShares(dataDir, swarm)
+ const offers = new swarm.SwarmOffers(join(dataDir, 'swarm-offers.json'))
+ const heal = new swarm.SwarmHeal({
+ live: async (name) => {
+ const answer = await gridExec(['--remote', 'models', name, '--json'])
+ return answer.code === 'OK' ? swarm.liveModels(answer.stdout) : null
+ },
+ shares: { list: (name) => shares.list(name), rejoin: (name, connectionId, model) => shares.rejoin(name, connectionId, model) },
+ apps: { served: (name) => localModels.servedApps(name), rejoin: (name) => localModels.rejoinApp(name) },
+ })
+ const requests: ServiceRequests = {
+ // What this computer serves on a Swarm's grid that the grid really lists, joined again when it lost them: read by
+ // every machine reading (superTabs/machines.ts).
+ grid_swarm_heal: async (payload) => {
+ if (typeof payload.grid !== 'string' || !SWARM_GRID.test(payload.grid)) return { error: 'INVALID_REQUEST' }
+ return { ...await heal.check(payload.grid) }
},
// 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) => {
@@ -441,7 +434,7 @@ function gridCommands(grid: GridSetUp, dataDir: string, shares: SwarmApiShares =
// 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) }
+ return { ...await swarm.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.
@@ -476,6 +469,33 @@ function gridCommands(grid: GridSetUp, dataDir: string, shares: SwarmApiShares =
grid_swarm_offers: (payload) => ({
offers: offers.list(typeof payload.grid === 'string' ? payload.grid : undefined),
}),
+ }
+ return { requests, shares }
+}
+
+/**
+ * The Model Manager's grid commands: grid's own argv, run here (`lib/gridFleetRpc.ts`). A command is a job
+ * of the connection that started it, keyed by that connection and the id it was asked under (`Asker`),
+ * and a cancel stops only that connection's own. Run against grid AS IT STANDS — never set up first: a
+ * Grid harness session issues these on its own the moment its viewer comes up (every open one, on every
+ * daemon start), so setting grid up here signed a machine in to grid right after a Harness-only sign-in,
+ * with nobody asking. Grid is set up by the picker's Set up, by making or opening a Model Manager, and by
+ * 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 {
+ const fleet = new GridFleetRpc()
+ return {
+ // Pulls and builds can take minutes; the host answers when it is done and holds nothing else for it.
+ grid_fleet_run: async (payload, asker) => {
+ const request = parseGridFleetRequest(payload)
+ if (!request || !asker.connection || !asker.requestId) return { error: 'INVALID_GRID_COMMAND' }
+ try {
+ return { ...await fleet.run(asker.connection, asker.requestId, request) }
+ } catch {
+ return { ok: false, code: 1, error: 'Grid command failed unexpectedly.' }
+ }
+ },
grid_fleet_cancel: (payload, asker) => ({
cancelled: !!asker.connection && typeof payload.commandId === 'string' && fleet.cancel(asker.connection, payload.commandId),
}),
diff --git a/cli/src/services/modelsProcess.spec.ts b/cli/src/services/modelsProcess.spec.ts
index dd6ad07b1..61b67a21e 100644
--- a/cli/src/services/modelsProcess.spec.ts
+++ b/cli/src/services/modelsProcess.spec.ts
@@ -76,6 +76,16 @@ describe('models in its own process', () => {
expect(service.stop).toHaveBeenCalled()
})
+ // HARNESS_SWARM: a Swarm's grid and shares come from the Swarm's side, which its process loads only while it is on.
+ it('hands models the Swarm\'s side while it is on, and none without it', () => {
+ const given: unknown[] = []
+ const start = (_core: CoreApi, ports: CorePorts, swarm?: unknown) => { given.push(swarm); ports.models = fakeModels().port; return {} }
+ const swarm = { SwarmApiShares: vi.fn() } as never
+ setup({ start, swarm })
+ setup({ start })
+ expect(given).toEqual([swarm, undefined])
+ })
+
it('a start that fills no port is no models at all', () => {
expect(() => runModelsService({ dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't', run: () => ({ stop: vi.fn() }), start: () => ({}) }))
.toThrow('models did not start')
diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.ts
index 5f53a2910..a52347730 100644
--- a/cli/src/services/modelsProcess.ts
+++ b/cli/src/services/modelsProcess.ts
@@ -22,6 +22,7 @@ import { parseGridLaunchOverride, type GridLaunchRequest } from '../lib/gridLaun
import { ENGINES, type AgentEngine } from '../engines/types.js'
import { gridGlances, onGridModelsChanged } from '../lib/gridModels.js'
import type { RuntimeModelOption } from '../lib/runtimeProfile.js'
+import type { SwarmServices } from '../serviceProcess.js'
import { startModels } from './models.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { UNASKED } from './processCoreApi.js'
@@ -37,6 +38,8 @@ export interface ModelsServiceOptions {
run?: typeof runServiceProcess
/** Swapped in tests for models that read no grid and start nothing. */
start?: typeof startModels
+ /** The Swarm's side of this service, while the Swarm is on (serviceProcess.ts, superTabs/inServices.ts). */
+ swarm?: SwarmServices
/** Every grid at a glance, and being told when that changes: the pictures', unless a test says. */
glances?: () => GridGlance[]
onChanged?: (listener: () => void) => () => void
@@ -151,7 +154,7 @@ export function runModelsService(options: ModelsServiceOptions): ServiceProcess
const ask = (query: string, payload: Payload = {}): Promise<Payload> =>
core ? core.query(query, payload) : Promise.reject(new Error('not connected to the core'))
const ports = emptyPorts()
- const requests = (options.start ?? startModels)(modelsCoreApi(options.dataDir, ask), ports)
+ const requests = (options.start ?? startModels)(modelsCoreApi(options.dataDir, ask), ports, options.swarm)
if (!ports.models) throw new Error('models did not start')
const models = ports.models
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index 64f0287ad..8381510f6 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -250,15 +250,15 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
ask: (agentId, requestId, question) => { void ask('cloud_ask', { agentId, questionId: requestId, question }).catch(() => {}) },
unask: (agentId, requestId) => { void ask('cloud_unask', { agentId, questionId: requestId }).catch(() => {}) },
} satisfies CloudCore,
- // The Super Tab service's waits (core/superTabAttention.ts), the whole set each time: a core that missed one
+ // The Super Tab service's waits (superTabs/inCore/attention.ts), the whole set each time: a core that missed one
// hears the next, and a new core the host's first roster (superTabs/host.ts).
superTabs: {
attention: (items) => { void ask('super_tab_attention', { items }).catch(() => {}) },
- // The Swarm cards, whole each time they change, and one Lead's recap (core/superTabCards.ts).
+ // The Swarm cards, whole each time they change, and one Lead's recap (superTabs/inCore/cards.ts).
cards: (items) => { void ask('super_tab_cards', { items }).catch(() => {}) },
cardRecap: (recap) => { void ask('super_tab_card_recap', { recap }).catch(() => {}) },
shareObservers: () => { void ask('super_tab_observers', {}).catch(() => {}) },
- // A Lead's read of a member's terminal and its typing (core/superTabTerminal.ts), answered by the core.
+ // A Lead's read of a member's terminal and its typing (superTabs/inCore/terminal.ts), answered by the core.
screen: (agentId, scrollback) => terminalAnswer(ask('super_tab_screen', { agentId, scrollback })) as Promise<SuperTabScreen>,
input: (agentId, text, keys) => terminalAnswer(ask('super_tab_input', { agentId, text, keys })),
} satisfies SuperTabsCore,
diff --git a/cli/src/services/sharing.spec.ts b/cli/src/services/sharing.spec.ts
index 107e1d424..04f928dde 100644
--- a/cli/src/services/sharing.spec.ts
+++ b/cli/src/services/sharing.spec.ts
@@ -11,11 +11,37 @@ import { setAgentSettingsForTest, signedOutForTest } from '../testing/agentSetti
import type { RegisteredSession } from '../lib/registry.js'
import { observerContext, recipientHandshake } from '../sharing/crypto.js'
import { fakeCore } from '../testing/fakeCore.js'
-import { SHARE_REQUESTS, startSharing, viewerPage, watchStreams } from './sharing.js'
+import { SHARE_REQUESTS, shareObservers, startSharing, viewerPage, watchStreams } from './sharing.js'
+import { observerSource, publishObservers } from '../superTabs/observers.js'
const identity = newIdentity()
const agent = { agentId: 'agent', sessionId: 's', engine: 'codex', active: true } as unknown as RegisteredSession
+// HARNESS_SWARM=off: Share's process hands in no Swarm. Its observers then watch nothing, invitations kept as for a host
+// that stalled, and a session a roster marked confidential still refuses every share (sharing/swarmMarks.ts).
+describe('who a Super Tab lets watch a harness here', () => {
+ let dataDir: string
+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'sharing-observers-')) })
+ afterEach(() => { rmSync(dataDir, { recursive: true, force: true }) })
+ const core = () => fakeCore({ dataDir, daemon: { command: 'harness', port: 1, machineId: () => 'machine' } })
+ const grant = (agentId: string, tab?: string) => ({ agentId, recipientEmail: '[email protected]', ...(tab ? { tab } : {}) }) as never
+
+ it('is the Swarm\'s roster while it is on, and with it off, none of a Super Tab\'s and no confidential session\'s', () => {
+ publishObservers(dataDir, 'machine', [{ tabId: 'tab', agent: { harnessId: 'member', machineId: 'machine' }, observers: [{ email: '[email protected]' }] },
+ { tabId: 'tab', confidential: true, agent: { harnessId: 'lead', machineId: 'machine' }, observers: [] }], Date.now() + 5_000)
+ const on = shareObservers(core(), observerSource)
+ expect(on.known()).toEqual([expect.objectContaining({ tab: 'super:tab', agentId: 'member', email: '[email protected]' })])
+ expect(on.allows(grant('member', 'super:tab'))).toBe(true)
+ expect(on.allows(grant('lead'))).toBe(false)
+ expect(on.allows(grant('ordinary'))).toBe(true)
+ const off = shareObservers(core())
+ expect(off.known()).toBeNull()
+ expect(off.allows(grant('member', 'super:tab'))).toBe(false)
+ expect(off.allows(grant('lead'))).toBe(false)
+ expect(off.allows(grant('ordinary'))).toBe(true)
+ })
+})
+
describe('Share, as a service', () => {
let dataDir: string
beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'sharing-service-')) })
diff --git a/cli/src/services/sharing.ts b/cli/src/services/sharing.ts
index 3b7678c03..789f56e3f 100644
--- a/cli/src/services/sharing.ts
+++ b/cli/src/services/sharing.ts
@@ -17,7 +17,8 @@
* wants are derived from (sharing/rosterGrants.ts): the messages process is that file's only writer.
* The observers' frames reach it through its port, as the relay hands them over.
*/
-import { observerSource } from '../superTabs/observers.js'
+import { withoutSwarm } from '../sharing/swarmMarks.js'
+import type { observerSource } from '../superTabs/observers.js'
import { join } from 'node:path'
import type { CoreApi, CorePorts, ServiceRequests, TerminalWatch } from '../core/api.js'
import { SHARE_REQUESTS } from '../core/api.js'
@@ -36,6 +37,10 @@ export { SHARE_REQUESTS } from '../core/api.js'
export interface SharingOptions {
/** The pool that captures a shared viewer; swapped in tests for one that starts no browser. */
viewers?: Pick<SharedViewerPool, 'watch' | 'stop'>
+ /** Who a Super Tab's roster lets watch a harness here (superTabs/observers.ts, through superTabs/inServices.ts): absent
+ * while the Swarm is off, when its observers watch nothing and confidential sessions still refuse every share
+ * (sharing/swarmMarks.ts `withoutSwarm`). */
+ observers?: typeof observerSource
}
/** The core's read-only streams, as the owner's own stream manager was: frames in, what each observer is shown out. */
@@ -57,9 +62,14 @@ export const viewerPage = (core: Pick<CoreApi, 'agents'>) => (agentId: string):
return agent ? core.agents.dsh(agent)?.viewerUrl ?? null : null
}
+/** Who a Super Tab's roster lets watch a harness here: the Swarm's own source while it is on, and with it off none of its
+ * observers and no confidential session (sharing/swarmMarks.ts). */
+export const shareObservers = (core: Pick<CoreApi, 'dataDir' | 'daemon'>, observers?: SharingOptions['observers']) =>
+ (observers ?? withoutSwarm)(core.dataDir, () => core.daemon.machineId())
+
export function startSharing(core: CoreApi, ports: CorePorts, options: SharingOptions = {}): ServiceRequests {
const viewers = options.viewers ?? new SharedViewerPool(viewerPage(core))
- const superTabs = observerSource(core.dataDir, () => core.daemon.machineId())
+ const superTabs = shareObservers(core, options.observers)
const owner = new HarnessShareOwner({
derivedGrants: superTabs.known,
allowsGrant: superTabs.allows,
diff --git a/cli/src/services/sharingProcess.spec.ts b/cli/src/services/sharingProcess.spec.ts
index 2172b53a6..32243ce62 100644
--- a/cli/src/services/sharingProcess.spec.ts
+++ b/cli/src/services/sharingProcess.spec.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { CoreApi, CorePorts, SharingPort } from '../core/api.js'
+import type { startSharing } from './sharing.js'
import type { RegisteredSession } from '../lib/registry.js'
import type { CoreConnection, ServiceProcessOptions } from './process.js'
import { AGENTS_FRESH_MS, runSharingService } from './sharingProcess.js'
@@ -135,6 +136,19 @@ describe('Share in its own process', () => {
expect(stop).toHaveBeenCalledOnce()
})
+ // HARNESS_SWARM: who a Super Tab lets watch comes from the Swarm's side, which its process loads only while it is on.
+ it('hands Share the Swarm\'s observers while it is on, and none without it', () => {
+ const given: Array<Parameters<typeof startSharing>[2]> = []
+ const start = (_core: CoreApi, ports: CorePorts, options?: Parameters<typeof startSharing>[2]) => {
+ given.push(options); ports.sharing = { observer: vi.fn(), linkDown: vi.fn(), stop: vi.fn() } as never; return {}
+ }
+ const observerSource = vi.fn() as never
+ const base = { dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't', run: () => ({ stop: vi.fn() }), start }
+ runSharingService({ ...base, swarm: { observerSource } })
+ runSharingService(base)
+ expect(given).toEqual([{ observers: observerSource }, {}])
+ })
+
it('runs the real Share and process when given neither', async () => {
const { runServiceProcess } = await import('./process.js')
const process = runSharingService({ dataDir: '/data-that-is-not-there', socketPath: '/s', machineId: 'm', token: 't' })
diff --git a/cli/src/services/sharingProcess.ts b/cli/src/services/sharingProcess.ts
index 431850e3a..7cbd6aa9f 100644
--- a/cli/src/services/sharingProcess.ts
+++ b/cli/src/services/sharingProcess.ts
@@ -15,6 +15,7 @@
import { emptyPorts, SHARE_REQUESTS, type DaemonAddress, type ServiceRequests, type SharingPort } from '../core/api.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { agentsIn, daemonIn, processCoreApi, type ShownAgent } from './processCoreApi.js'
+import type { SwarmServices } from '../serviceProcess.js'
import { startSharing } from './sharing.js'
import { watchLink } from './watchLink.js'
@@ -33,6 +34,8 @@ export interface SharingServiceOptions {
/** Swapped in tests for a Share that keeps nothing on disk and starts no browser. */
start?: typeof startSharing
now?: () => number
+ /** The Swarm's side of this service, while the Swarm is on (serviceProcess.ts, superTabs/inServices.ts). */
+ swarm?: Pick<SwarmServices, 'observerSource'>
}
export function runSharingService(options: SharingServiceOptions): ServiceProcess {
@@ -65,7 +68,7 @@ export function runSharingService(options: SharingServiceOptions): ServiceProces
const build = () => {
const ports = emptyPorts()
- const requests = (options.start ?? startSharing)(api, ports)
+ const requests = (options.start ?? startSharing)(api, ports, options.swarm ? { observers: options.swarm.observerSource } : {})
return { requests, port: ports.sharing! }
}
let built: { requests: ServiceRequests; port: SharingPort } = build()
diff --git a/cli/src/sharing/swarmMarks.spec.ts b/cli/src/sharing/swarmMarks.spec.ts
new file mode 100644
index 000000000..722faa593
--- /dev/null
+++ b/cli/src/sharing/swarmMarks.spec.ts
@@ -0,0 +1,43 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { observerSnapshotFile, savedConfidential, superTabOf, withoutSwarm } from './swarmMarks.js'
+
+describe('the Swarm\'s marks on Share, read with the Swarm off', () => {
+ let dataDir: string
+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'swarm-marks-')) })
+ afterEach(() => { rmSync(dataDir, { recursive: true, force: true }) })
+ const save = (value: unknown) => {
+ const file = observerSnapshotFile(dataDir, 'machine')
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, typeof value === 'string' ? value : JSON.stringify(value))
+ return file
+ }
+
+ it('tells a Super Tab\'s grant from an ordinary one', () => {
+ expect(superTabOf({ tab: 'super:tab-1' })).toBe('tab-1')
+ expect(superTabOf({ tab: 'team' })).toBeNull()
+ expect(superTabOf({ tab: null })).toBeNull()
+ })
+
+ it('reads the confidential sessions this machine\'s snapshot names, and nothing from one it cannot trust', () => {
+ expect(observerSnapshotFile(dataDir, 'machine')).toBe(join(dataDir, 'super-tabs', 'observers-machine.json'))
+ const file = save({ machineId: 'machine', confidential: ['lead', 'not an id', 7] })
+ expect(savedConfidential(file, 'machine')).toEqual(['lead'])
+ expect(savedConfidential(file, 'another')).toEqual([])
+ for (const bad of ['{', '[]', 'null', { machineId: 'machine', confidential: 'lead' }]) expect(savedConfidential(save(bad), 'machine'), JSON.stringify(bad)).toEqual([])
+ expect(savedConfidential(join(dataDir, 'absent.json'), 'machine')).toEqual([])
+ })
+
+ it('without the Swarm, says no roster is in force, refuses a Super Tab\'s grants and every share of a confidential session', () => {
+ const marks = withoutSwarm(dataDir, () => 'machine')
+ const grant = (agentId: string, tab?: string) => ({ agentId, recipientEmail: '[email protected]', ...(tab ? { tab } : {}) }) as never
+ expect(marks.known()).toBeNull()
+ expect(marks.allows(grant('lead'))).toBe(true)
+ save({ machineId: 'machine', until: 0, wanted: [], confidential: ['lead'] })
+ expect(marks.allows(grant('lead'))).toBe(false)
+ expect(marks.allows(grant('member', 'super:tab'))).toBe(false)
+ expect(marks.allows(grant('member'))).toBe(true)
+ })
+})
diff --git a/cli/src/sharing/swarmMarks.ts b/cli/src/sharing/swarmMarks.ts
new file mode 100644
index 000000000..de174b347
--- /dev/null
+++ b/cli/src/sharing/swarmMarks.ts
@@ -0,0 +1,45 @@
+/**
+ * The Swarm's marks on Share that hold whether the Swarm is on or not (`HARNESS_SWARM`, harnessd/services.ts): which
+ * grants are a Super Tab's, and which sessions its rosters marked confidential (a Lead, or in a private chat). The Swarm
+ * writes them (superTabs/observers.ts); Share reads them here, without loading the Swarm's code.
+ *
+ * With the Swarm off, Share runs on `withoutSwarm`: no Super Tab roster is in force, so its observers watch nothing
+ * (their invitations are kept, as for a host that stalled, and viewing is withheld), and a confidential session keeps
+ * refusing every share, ordinary ones too. Turning the Swarm off must not reopen what a roster closed (final review of
+ * the observers, Critical 1): that mark is the one piece of the Swarm's saved state still read while it is off.
+ */
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import type { HarnessGrant } from './grants.js'
+
+const PREFIX = 'super:'
+const identifier = (v: unknown): v is string => typeof v === 'string' && /^[A-Za-z0-9_-]{1,160}$/.test(v)
+
+/** The Super Tab a grant is for, or null for an ordinary share. */
+export function superTabOf(grant: Pick<HarnessGrant, 'tab'>): string | null {
+ return grant.tab?.startsWith(PREFIX) ? grant.tab.slice(PREFIX.length) : null
+}
+
+/** Where the Swarm keeps what the last roster wants watched, and the sessions marked confidential. */
+export function observerSnapshotFile(dataDir: string, machineId: string): string {
+ return join(dataDir, 'super-tabs', `observers-${machineId}.json`)
+}
+
+/** The sessions the last snapshot recorded as confidential (a Lead, or in a private chat, in some Swarm). */
+export function savedConfidential(file: string, machineId: string): string[] {
+ try {
+ const saved: unknown = JSON.parse(readFileSync(file, 'utf8'))
+ if (!saved || typeof saved !== 'object' || Array.isArray(saved)) return []
+ const { machineId: owner, confidential } = saved as { machineId?: unknown; confidential?: unknown }
+ return owner === machineId && Array.isArray(confidential) ? confidential.filter(identifier) : []
+ } catch { return [] }
+}
+
+/** Share's observers with the Swarm off (services/sharing.ts): none of a Super Tab's, and no confidential session's. */
+export function withoutSwarm(dataDir: string, machine: () => string) {
+ return {
+ known: (): null => null,
+ allows: (grant: HarnessGrant): boolean => !superTabOf(grant)
+ && !savedConfidential(observerSnapshotFile(dataDir, machine()), machine()).includes(grant.agentId),
+ }
+}
diff --git a/cli/src/superTabs/attention.ts b/cli/src/superTabs/attention.ts
index 79a55fa5a..9a39a633f 100644
--- a/cli/src/superTabs/attention.ts
+++ b/cli/src/superTabs/attention.ts
@@ -5,7 +5,7 @@
* backend from before it sends no `attention`, and nothing is raised.
*
* The roster is the whole truth each time: the set is handed to the core whole (`core.superTabs.attention`), which
- * raises what is new and closes what is gone (core/superTabAttention.ts). A status that moves on, a new attempt, a
+ * raises what is new and closes what is gone (superTabs/inCore/attention.ts). A status that moves on, a new attempt, a
* removed agent, a paused or deleted tab: each is a row that no longer says so, and its alert closes.
*/
import { createHash } from 'node:crypto'
diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.ts
index bb64d19bf..0efbb3d20 100644
--- a/cli/src/superTabs/cards.ts
+++ b/cli/src/superTabs/cards.ts
@@ -18,11 +18,9 @@ import { identifier, object } from './wire.js'
import { SwarmReads, type SwarmRead } from './swarmReads.js'
type Json = Record<string, unknown>
-export type LeadState = 'ask' | 'stuck' | 'work' | 'done'
-/** `order`: the project's index in the Swarm (the app's order), so a dial can show the Leads as the app does whatever their urgency. */
-export interface SwarmLead { id: string; projectId: string; project: string; engine: string; owner: string; local: string; state: LeadState; order: number; since?: number }
-export interface SwarmCard { id: string; name: string; count: number; leads: SwarmLead[] }
-export interface LeadRecap { tabId: string; leadId: string; text: string; at: number; none: boolean }
+/** The cards' shapes are the core's contract with the Swarm (core/api.ts), which the core declares and the Swarm imports. */
+import type { LeadRecap, LeadState, SwarmCard, SwarmLead } from '../core/api.js'
+export type { LeadRecap, LeadState, SwarmCard, SwarmLead } from '../core/api.js'
const MAX_CARDS = 16, MAX_LEADS = 12, NAME_BYTES = 48, RECAP_BYTES = 1500, MAX_LIST_PAGES = 10, MAX_RECAPS_IN_FLIGHT = 2
/** The Pro keeps an id in 48 bytes with its NUL: 47 characters at most reach it. */
diff --git a/cli/src/superTabs/inCore.ts b/cli/src/superTabs/inCore.ts
new file mode 100644
index 000000000..57bb0cae6
--- /dev/null
+++ b/cli/src/superTabs/inCore.ts
@@ -0,0 +1,23 @@
+/**
+ * The Swarm's side of the core's process: the one entry the core loads it through, dynamically and only while the Swarm
+ * is on (core/main.ts, `HARNESS_SWARM` in harnessd/services.ts). Off, none of this is loaded and the core runs as it
+ * does without the Swarm; src/architecture.spec.ts checks that the core reaches the Swarm's code by no other way.
+ *
+ * What it hands the core is typed by core/api.ts, the core's contract: the Super Tab members' waits and cards on the
+ * devices (`SuperTabsCore`), a member's terminal for its Lead, the close and reopen of its agents (`SwarmAgents`), a
+ * start's Swarm role (`SwarmLaunch`), an older session's role at its restart (`AdoptSwarmSkill`), its chat queued while
+ * an agent works, the Leads that are never stopped, and its chat files streamed to the backend. And the Super Tab
+ * service's own start, for when it runs in the core's process (services/superTabs.ts), so a core running every service
+ * there with the Swarm off loads none of it either.
+ */
+export { createSuperTabAttention } from './inCore/attention.js'
+export { createSuperTabCards } from './inCore/cards.js'
+export { createSuperTabTerminal } from './inCore/terminal.js'
+export { swarmRoleThrough } from './inCore/role.js'
+export { createSwarmSkillAdoption } from './inCore/adoption.js'
+export { createSwarmAgents } from './inCore/agents.js'
+export { SWARM_LAUNCH } from './inCore/launch.js'
+export { typesWhileBusy } from './inCore/deliveries.js'
+export { mayBeLead, retainedHarnesses, retainedLeads } from './retention.js'
+export { forwardAttachmentUpload } from '../lib/superTabAttachmentProxy.js'
+export { startSuperTabs } from '../services/superTabs.js'
diff --git a/cli/src/core/agents/swarmSkills.spec.ts b/cli/src/superTabs/inCore/adoption.spec.ts
similarity index 97%
rename from cli/src/core/agents/swarmSkills.spec.ts
rename to cli/src/superTabs/inCore/adoption.spec.ts
index 4e860649c..e9c7241b0 100644
--- a/cli/src/core/agents/swarmSkills.spec.ts
+++ b/cli/src/superTabs/inCore/adoption.spec.ts
@@ -1,8 +1,8 @@
import { describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../../lib/registry.js'
import type { SwarmSkillGrant } from '../../lib/swarmSkills.js'
-import { createLaunchAuthority } from './launchAuthority.js'
-import { createSwarmSkillAdoption } from './swarmSkills.js'
+import { createLaunchAuthority } from '../../core/agents/launchAuthority.js'
+import { createSwarmSkillAdoption } from './adoption.js'
const row = (over: Partial<RegisteredSession> = {}) => ({ agentId: 'old-session', engine: 'claude', sessionId: 'conversation',
registeredAt: 1, cwd: '/project', runtimes: [], ...over }) as RegisteredSession
diff --git a/cli/src/core/agents/swarmSkills.ts b/cli/src/superTabs/inCore/adoption.ts
similarity index 90%
rename from cli/src/core/agents/swarmSkills.ts
rename to cli/src/superTabs/inCore/adoption.ts
index 8ec93a439..721644cfa 100644
--- a/cli/src/core/agents/swarmSkills.ts
+++ b/cli/src/superTabs/inCore/adoption.ts
@@ -1,10 +1,9 @@
/** Older Swarm sessions predate role metadata. Adopt only at restart/resume, from current membership,
* before native launch authority is captured; changing the live row later would revoke that launch. */
-import type { RegisteredSession, registry } from '../../lib/registry.js'
+import type { AdoptSwarmSkill } from '../../core/api.js'
+import type { registry } from '../../lib/registry.js'
import type { SwarmSkillGrant } from '../../lib/swarmSkills.js'
-export type AdoptSwarmSkill = (session: RegisteredSession, current: () => boolean) => Promise<RegisteredSession | null>
-
export function createSwarmSkillAdoption(deps: {
role(harnessId: string): Promise<SwarmSkillGrant | null | undefined>
candidate(harnessId: string): boolean
diff --git a/cli/src/superTabs/inCore/agents.spec.ts b/cli/src/superTabs/inCore/agents.spec.ts
new file mode 100644
index 000000000..c9721d19d
--- /dev/null
+++ b/cli/src/superTabs/inCore/agents.spec.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { SwarmAgentDeps } from '../../core/api.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { createSwarmAgents } from './agents.js'
+
+const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
+const NO_MEMBERS = { leads: () => new Set<string>(), harnesses: () => new Set<string>() }
+const deps = (over: Partial<SwarmAgentDeps> = {}): SwarmAgentDeps => ({
+ byAgent: (agentId: string) => (agentId === 'live' ? row('live') : undefined),
+ stoppedIds: () => ['stopped'],
+ ...over,
+})
+
+describe('the Swarm\'s agents, as the core lets it close and reopen them', () => {
+ it('closes only the original Swarm-started native session and treats an absent session as gone', async () => {
+ const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', expiresAt: Date.now() + 120_000, createdAt: new Date(1000).toISOString() }
+ const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const }
+ const byAgent = vi.fn(() => session as RegisteredSession | undefined)
+ const closeAgent = vi.fn(async () => ({ closed: true as const }))
+ const creationStatus = vi.fn(async () => ({ creationId: request.creationId, state: 'created' as const, agentId: 'worker' }))
+ const swarm = createSwarmAgents({ ...deps({ byAgent, closeAgent, creationStatus }), members: NO_MEMBERS })
+ expect(await swarm.closeSwarm(request)).toEqual({ closed: true })
+ expect(closeAgent).toHaveBeenCalledWith({ agentId: 'worker', sessionId: 'native', createdAt: request.createdAt, mode: 'now', onlyIfOriginalLaunch: true, expiresAt: request.expiresAt })
+ closeAgent.mockClear()
+ byAgent.mockReturnValue({ ...session, startedBy: undefined })
+ expect(await swarm.closeSwarm(request)).toMatchObject({ error: 'NOT_SWARM_STARTED' })
+ byAgent.mockReturnValue({ ...session, registeredAt: 2000 })
+ expect(await swarm.closeSwarm(request)).toMatchObject({ error: 'AGENT_CHANGED' })
+ byAgent.mockReturnValue({ ...session, sessionId: 'replacement' })
+ expect(await swarm.closeSwarm(request)).toMatchObject({ error: 'AGENT_CHANGED' })
+ byAgent.mockReturnValue(session)
+ creationStatus.mockResolvedValueOnce({ creationId: request.creationId, state: 'created', agentId: 'other' })
+ expect(await swarm.closeSwarm(request)).toMatchObject({ error: 'NOT_SWARM_STARTED' })
+ expect(closeAgent).not.toHaveBeenCalled()
+ const withoutCreation = createSwarmAgents({ ...deps({ byAgent, closeAgent }), members: NO_MEMBERS })
+ expect(await withoutCreation.closeSwarm(request)).toEqual({ error: 'NOT_SWARM_STARTED' })
+ const noLifecycle = createSwarmAgents({ ...deps({ byAgent, creationStatus }), members: NO_MEMBERS })
+ expect(await noLifecycle.closeSwarm(request)).toEqual({ error: 'UNSUPPORTED' })
+ for (const partial of [{ agentId: 'worker' }, { ...request, creationId: '' }, { ...request, sessionId: undefined }, { ...request, createdAt: undefined }]) {
+ expect(await swarm.closeSwarm(partial)).toEqual({ error: 'NOT_SWARM_STARTED' })
+ }
+ byAgent.mockReturnValue(undefined)
+ expect(await swarm.closeSwarm({ agentId: 'worker' })).toEqual({ closed: true })
+ })
+
+ // A machine restart stops Swarm sessions; reopened, each keeps its harness, conversation and registeredAt but is marked
+ // resume-only. On 2026-10-23 such a worker could no longer be stopped by the Swarm ("not started by the Swarm").
+ it('closes a Swarm session reopened on its own conversation, and refuses one whose conversation changed during the lookup', async () => {
+ const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', expiresAt: Date.now() + 120_000, createdAt: new Date(1000).toISOString() }
+ const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const, resumeOnly: true as const }
+ const closeAgent = vi.fn(async () => ({ closed: true as const }))
+ const creationStatus = vi.fn(async () => ({ creationId: request.creationId, state: 'created' as const, agentId: 'worker' }))
+ const swarm = createSwarmAgents({ ...deps({ byAgent: () => session, closeAgent, creationStatus }), members: NO_MEMBERS })
+ expect(await swarm.closeSwarm(request)).toEqual({ closed: true })
+ expect(closeAgent).toHaveBeenCalledOnce()
+ closeAgent.mockClear()
+ creationStatus.mockImplementationOnce(async () => {
+ session.sessionId = 'personal-resume'
+ return { creationId: request.creationId, state: 'created' as const, agentId: 'worker' }
+ })
+ expect(await swarm.closeSwarm(request)).toEqual({ error: 'AGENT_CHANGED' })
+ expect(closeAgent).not.toHaveBeenCalled()
+ })
+
+ // The Super Tab host keeps a Swarm Lead alive and closes the sessions its backend ends (owner, 2026-10-23). The core
+ // decides what a service may do: reopen only a stopped Lead the host's retention names, close only a member it names.
+ it('reopens only a stopped Swarm Lead, and says a live one is up', async () => {
+ const resumeAgent = vi.fn(async () => ({ ok: true as const }))
+ const leads = vi.fn(() => new Set(['stopped', 'live']))
+ const swarm = createSwarmAgents({ ...deps({ resumeAgent }), members: { leads, harnesses: () => new Set() } })
+ expect(await swarm.keepLeadAlive('stopped')).toEqual({ ok: true })
+ expect(resumeAgent).toHaveBeenCalledWith('stopped')
+ expect(await swarm.keepLeadAlive('live')).toEqual({ ok: true })
+ leads.mockReturnValue(new Set(['live']))
+ expect(await swarm.keepLeadAlive('stopped')).toEqual({ ok: false, error: 'NOT_A_LEAD', detail: 'Only a stopped Product Manager of a Swarm project is reopened.' })
+ leads.mockReturnValue(new Set(['gone']))
+ expect(await swarm.keepLeadAlive('gone')).toMatchObject({ ok: false, error: 'NOT_A_LEAD' })
+ expect(resumeAgent).toHaveBeenCalledTimes(1)
+ leads.mockReturnValue(new Set(['stopped']))
+ resumeAgent.mockResolvedValueOnce({ ok: false, error: 'AGENT_BUSY', detail: 'busy' } as never)
+ expect(await swarm.keepLeadAlive('stopped')).toEqual({ ok: false, error: 'AGENT_BUSY', detail: 'busy' })
+ resumeAgent.mockResolvedValueOnce({ ok: false, error: 'RESUME_FAILED' } as never)
+ expect(await swarm.keepLeadAlive('stopped')).toEqual({ ok: false, error: 'RESUME_FAILED' })
+ expect(await createSwarmAgents({ ...deps(), members: { leads, harnesses: () => new Set() } }).keepLeadAlive('stopped')).toEqual({ ok: false, error: 'UNSUPPORTED' })
+ })
+
+ it('closes now only a Super Tab member the host retains, and treats an absent one as closed', async () => {
+ const closeAgent = vi.fn(async () => ({ closed: true as const }))
+ const byAgent = (id: string) => id === 'live' ? { ...row('live'), registeredAt: 1000 } : undefined
+ const harnesses = vi.fn(() => new Set(['live']))
+ const swarm = createSwarmAgents({ ...deps({ byAgent, closeAgent }), members: { leads: () => new Set(), harnesses } })
+ expect(await swarm.closeMember('live')).toEqual({ closed: true })
+ expect(closeAgent).toHaveBeenCalledWith({ agentId: 'live', sessionId: 's-live', createdAt: new Date(1000).toISOString(), mode: 'now' })
+ expect(await swarm.closeMember('absent')).toEqual({ closed: true })
+ harnesses.mockReturnValue(new Set())
+ expect(await swarm.closeMember('live')).toEqual({ error: 'NOT_A_MEMBER' })
+ harnesses.mockImplementation(() => { throw new Error('Super Tab retention is unreadable.') })
+ expect(await swarm.closeMember('live')).toEqual({ error: 'NOT_A_MEMBER' })
+ expect(closeAgent).toHaveBeenCalledTimes(1)
+ expect(await createSwarmAgents({ ...deps({ byAgent }), members: { leads: () => new Set(), harnesses: () => new Set(['live']) } }).closeMember('live')).toEqual({ error: 'UNSUPPORTED' })
+ })
+
+ // The review of #1635: an agent removed before its host wrote a roster naming it is no member there; the exact receipt of
+ // the Swarm's start proves it is the Swarm's own to close, and a receipt naming another harness proves nothing.
+ it('closes a member the retention does not name only when its start receipt names it', async () => {
+ const closeAgent = vi.fn(async () => ({ closed: true as const }))
+ const creationStatus = vi.fn(async (creationId: string) => ({ creationId, state: 'created' as const, agentId: 'live' }))
+ const byAgent = (id: string) => id === 'live' ? { ...row('live'), registeredAt: 1000 } : undefined
+ const swarm = createSwarmAgents({ ...deps({ byAgent, closeAgent, creationStatus }), members: NO_MEMBERS })
+ expect(await swarm.closeMember('live')).toEqual({ error: 'NOT_A_MEMBER' })
+ expect(await swarm.closeMember('live', 'super-start')).toEqual({ closed: true })
+ expect(creationStatus).toHaveBeenCalledWith('super-start')
+ creationStatus.mockResolvedValueOnce({ creationId: 'super-start', state: 'created', agentId: 'another' })
+ expect(await swarm.closeMember('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })
+ creationStatus.mockResolvedValueOnce(null as never)
+ expect(await swarm.closeMember('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })
+ expect(await createSwarmAgents({ ...deps({ byAgent, closeAgent }), members: NO_MEMBERS }).closeMember('live', 'super-start')).toEqual({ error: 'NOT_A_MEMBER' })
+ expect(closeAgent).toHaveBeenCalledTimes(1)
+ })
+
+ it('refuses missing or expired close leases, including expiry during the creation lookup', async () => {
+ let now = 1000
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now)
+ try {
+ const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', createdAt: new Date(1000).toISOString(), expiresAt: 1100 }
+ const closeAgent = vi.fn(async () => ({ closed: true as const }))
+ const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const }
+ const creationStatus = vi.fn(async () => { now = 1200; return { creationId: request.creationId, state: 'created' as const, agentId: 'worker' } })
+ const swarm = createSwarmAgents({ ...deps({ byAgent: () => session, closeAgent, creationStatus }), members: NO_MEMBERS })
+ for (const expiresAt of [undefined, NaN, 999]) expect(await swarm.closeSwarm({ ...request, expiresAt })).toEqual({ error: 'STOP_LEASE_EXPIRED' })
+ expect(await swarm.closeSwarm(request)).toEqual({ error: 'STOP_LEASE_EXPIRED' })
+ expect(closeAgent).not.toHaveBeenCalled()
+ } finally { clock.mockRestore() }
+ })
+})
diff --git a/cli/src/superTabs/inCore/agents.ts b/cli/src/superTabs/inCore/agents.ts
new file mode 100644
index 000000000..5c392118f
--- /dev/null
+++ b/cli/src/superTabs/inCore/agents.ts
@@ -0,0 +1,55 @@
+/**
+ * Which of its agents the Swarm may close or reopen, decided in the core's process from the core's own live registry,
+ * stopped records and creation receipts, never from the Super Tab service's possibly old snapshot: the Swarm's original
+ * start alone (`closeSwarm`), a stopped Lead its host keeps (`keepLeadAlive`), a member its host retains or whose start
+ * receipt names it (`closeMember`). The core offers these only while the Swarm is on (core/api.ts `swarmAgents`).
+ */
+import type { SwarmAgentDeps, SwarmAgents } from '../../core/api.js'
+
+export function createSwarmAgents({ byAgent, stoppedIds, closeAgent, resumeAgent, creationStatus, members }: SwarmAgentDeps & {
+ /** The Leads and members this machine's Super Tab host keeps (superTabs/retention.ts). */
+ members: { leads(): Set<string>; harnesses(): Set<string> }
+}): SwarmAgents {
+ return {
+ closeSwarm: async request => {
+ const session = byAgent(request.agentId)
+ // This is the authoritative live registry, not a service's possibly old snapshot or a failed read.
+ if (!session) return { closed: true }
+ // A reopen (resume-only) of the same conversation is still the Swarm's session: the identity below proves it.
+ if (session.startedBy !== 'agent' || !request.creationId || typeof request.sessionId !== 'string' || !request.createdAt) return { error: 'NOT_SWARM_STARTED' }
+ if (session.sessionId !== request.sessionId || session.registeredAt !== Date.parse(request.createdAt)) return { error: 'AGENT_CHANGED' }
+ if (!Number.isFinite(request.expiresAt) || request.expiresAt! <= Date.now()) return { error: 'STOP_LEASE_EXPIRED' }
+ const creation = await creationStatus?.(request.creationId)
+ if (creation?.state !== 'created' || creation.agentId !== request.agentId) return { error: 'NOT_SWARM_STARTED' }
+ if (request.expiresAt! <= Date.now()) return { error: 'STOP_LEASE_EXPIRED' }
+ const latest = byAgent(request.agentId)
+ if (!latest || latest.startedBy !== 'agent' || latest.sessionId !== request.sessionId
+ || latest.registeredAt !== Date.parse(request.createdAt)) return { error: 'AGENT_CHANGED' }
+ return closeAgent ? closeAgent({ agentId: request.agentId, sessionId: request.sessionId, createdAt: request.createdAt, mode: 'now', onlyIfOriginalLaunch: true, expiresAt: request.expiresAt }) : { error: 'UNSUPPORTED' }
+ },
+ keepLeadAlive: async agentId => {
+ if (!resumeAgent) return { ok: false, error: 'UNSUPPORTED' }
+ if (byAgent(agentId)) return { ok: true }
+ if (!members.leads().has(agentId) || !stoppedIds().includes(agentId)) {
+ return { ok: false, error: 'NOT_A_LEAD', detail: 'Only a stopped Product Manager of a Swarm project is reopened.' }
+ }
+ const reply = await resumeAgent(agentId)
+ return reply.ok ? { ok: true } : { ok: false, error: reply.error, ...(reply.detail ? { detail: reply.detail } : {}) }
+ },
+ closeMember: async (agentId, creationId) => {
+ if (!closeAgent) return { error: 'UNSUPPORTED' }
+ const session = byAgent(agentId)
+ if (!session) return { closed: true }
+ let member = false
+ try { member = members.harnesses().has(agentId) } catch { /* An unreadable retention names no member. */ }
+ // An agent removed before its host wrote a roster naming it: the Swarm's own start receipt proves it (the review of #1635).
+ if (!member && creationId) {
+ const creation = await creationStatus?.(creationId)
+ member = creation?.state === 'created' && creation.agentId === agentId
+ }
+ if (!member) return { error: 'NOT_A_MEMBER' }
+ // The close itself refuses a session that changed during the receipt read.
+ return closeAgent({ agentId, sessionId: session.sessionId, createdAt: new Date(session.registeredAt).toISOString(), mode: 'now' })
+ },
+ }
+}
diff --git a/cli/src/core/superTabAttention.spec.ts b/cli/src/superTabs/inCore/attention.spec.ts
similarity index 97%
rename from cli/src/core/superTabAttention.spec.ts
rename to cli/src/superTabs/inCore/attention.spec.ts
index 361030f92..2c796d678 100644
--- a/cli/src/core/superTabAttention.spec.ts
+++ b/cli/src/superTabs/inCore/attention.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
-import type { SuperTabAttention } from './api.js'
-import { createSuperTabAttention } from './superTabAttention.js'
+import type { SuperTabAttention } from '../../core/api.js'
+import { createSuperTabAttention } from './attention.js'
const wait = (agentId: string, over: Partial<SuperTabAttention> = {}): SuperTabAttention =>
({ agentId, requestId: `supertab:as-${agentId}:needs_human`, superTab: 'Pilot', attention: 'decision', text: 'Ship it?', ...over })
diff --git a/cli/src/core/superTabAttention.ts b/cli/src/superTabs/inCore/attention.ts
similarity index 99%
rename from cli/src/core/superTabAttention.ts
rename to cli/src/superTabs/inCore/attention.ts
index 275e91efc..f3319df5b 100644
--- a/cli/src/core/superTabAttention.ts
+++ b/cli/src/superTabs/inCore/attention.ts
@@ -12,7 +12,7 @@
* engine's question comes first: ours is taken down before it shows (`before`) and put back once it is gone (`after`),
* and one raised while an engine's question is open waits for that question to close.
*/
-import { SUPER_TAB_REQUEST_PREFIX, type SuperTabAttention } from './api.js'
+import { SUPER_TAB_REQUEST_PREFIX, type SuperTabAttention } from '../../core/api.js'
type Frame = Record<string, unknown>
diff --git a/cli/src/core/superTabCards.spec.ts b/cli/src/superTabs/inCore/cards.spec.ts
similarity index 99%
rename from cli/src/core/superTabCards.spec.ts
rename to cli/src/superTabs/inCore/cards.spec.ts
index f5596a4e5..09ca014da 100644
--- a/cli/src/core/superTabCards.spec.ts
+++ b/cli/src/superTabs/inCore/cards.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
-import { createSuperTabCards } from './superTabCards.js'
+import { createSuperTabCards } from './cards.js'
const lead = (id: string, over: Record<string, unknown> = {}) =>
({ id, projectId: `p-${id}`, project: 'mobile', engine: 'claude', owner: '', local: 'h1', state: 'work', order: 0, since: 12, ...over })
diff --git a/cli/src/core/superTabCards.ts b/cli/src/superTabs/inCore/cards.ts
similarity index 98%
rename from cli/src/core/superTabCards.ts
rename to cli/src/superTabs/inCore/cards.ts
index bc8359b8e..0ba85ed91 100644
--- a/cli/src/core/superTabCards.ts
+++ b/cli/src/superTabs/inCore/cards.ts
@@ -9,11 +9,11 @@
* later is shown it (`replay`). A list is taken whole or not at all: one item that is not one drops the list and the last
* good one stays, so a device never shows half a Swarm. A recap is one Lead's and is forwarded as it comes.
*
- * The core also owns whether the cards are wanted at all (like core/superTabAttention.ts owns its waits): the devices say
+ * The core also owns whether the cards are wanted at all (like attention.ts owns its waits): the devices say
* whether a capable Pro is attached and which Swarms the desktop has tabs for (`want`), and the core says it to the Super Tab
* service, again whenever that service (re)connects (`serviceUp`), and takes it back when the devices go (`devicesGone`).
*/
-import type { LeadRecap, SwarmCard, SwarmLead } from '../superTabs/cards.js'
+import type { LeadRecap, SwarmCard, SwarmLead } from '../../core/api.js'
export interface SuperTabCardsDeps {
/** The devices' door for the list (`ports.devices.swarmCards`). */
diff --git a/cli/src/superTabs/inCore/deliveries.spec.ts b/cli/src/superTabs/inCore/deliveries.spec.ts
new file mode 100644
index 000000000..191fb3211
--- /dev/null
+++ b/cli/src/superTabs/inCore/deliveries.spec.ts
@@ -0,0 +1,7 @@
+import { expect, it } from 'vitest'
+import { typesWhileBusy } from './deliveries.js'
+
+it('queues the Swarm\'s own chat deliveries while an agent works, and no other maker\'s', () => {
+ expect(typesWhileBusy('team:service:superTabs:assignment-1')).toBe(true)
+ for (const other of ['team:peer', 'team:service:orchestrator:1', 'wifi:1', 'team:service:superTabsX', '']) expect(typesWhileBusy(other), other).toBe(false)
+})
diff --git a/cli/src/superTabs/inCore/deliveries.ts b/cli/src/superTabs/inCore/deliveries.ts
new file mode 100644
index 000000000..358de8f7c
--- /dev/null
+++ b/cli/src/superTabs/inCore/deliveries.ts
@@ -0,0 +1,8 @@
+/**
+ * The Swarm's chat messages, as the core writes them into an agent (core/input.ts `typesWhileBusy`): queued in the
+ * engine's own input while the agent works, where the engine takes them (Claude Code and Codex), instead of waiting for
+ * idle as Agent Messages' do. Under the same draft and dialog checks, behind the pane's writer lock.
+ */
+const SWARM_DELIVERY = 'team:service:superTabs:'
+
+export const typesWhileBusy = (deliveryId: string): boolean => deliveryId.startsWith(SWARM_DELIVERY)
diff --git a/cli/src/superTabs/inCore/launch.spec.ts b/cli/src/superTabs/inCore/launch.spec.ts
new file mode 100644
index 000000000..4377b2c62
--- /dev/null
+++ b/cli/src/superTabs/inCore/launch.spec.ts
@@ -0,0 +1,33 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { swarmGitHubLaunch } from '../../lib/swarmGitHub.js'
+import { SWARM_LAUNCH } from './launch.js'
+
+// The Harness GitHub App's launch writes files in the daemon's folder (lib/swarmGitHub.ts): never this machine's here.
+vi.mock('../../lib/swarmGitHub.js', () => ({ swarmGitHubLaunch: vi.fn(() => null) }))
+
+const folders: string[] = []
+afterEach(() => { for (const folder of folders.splice(0)) rmSync(folder, { recursive: true, force: true }) })
+
+it('lets a start ask for the three roles and two skill modes, and nothing else', () => {
+ for (const role of ['lead', 'dev', 'review']) expect(SWARM_LAUNCH.role(role), role).toBe(true)
+ for (const role of ['builder', '', 7, null, undefined]) expect(SWARM_LAUNCH.role(role), String(role)).toBe(false)
+ for (const mode of ['default', 'orchestration']) expect(SWARM_LAUNCH.mode(mode), mode).toBe(true)
+ for (const mode of ['light', 7, null]) expect(SWARM_LAUNCH.mode(mode), String(mode)).toBe(false)
+})
+
+it('writes the role\'s skill into the project folder and tells the engine where to read it', () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'swarm-launch-'))
+ folders.push(cwd)
+ const { instructions } = SWARM_LAUNCH.prepare(cwd, { role: 'review', key: 'harness-claude-1' })
+ expect(instructions).toContain('swarm-review/SKILL.md')
+ expect(() => SWARM_LAUNCH.prepare(cwd, { role: 'review', key: '' })).toThrow('A Swarm skill needs a role and session key')
+})
+
+it('hands the GitHub App\'s git and gh for the session it is asked for', () => {
+ vi.mocked(swarmGitHubLaunch).mockReturnValueOnce({ env: { GH_CONFIG_DIR: '/fixture/gh' }, clearEnv: ['GH_TOKEN'] })
+ expect(SWARM_LAUNCH.github('harness-codex-2')).toEqual({ env: { GH_CONFIG_DIR: '/fixture/gh' }, clearEnv: ['GH_TOKEN'] })
+ expect(swarmGitHubLaunch).toHaveBeenCalledWith('harness-codex-2')
+})
diff --git a/cli/src/superTabs/inCore/launch.ts b/cli/src/superTabs/inCore/launch.ts
new file mode 100644
index 000000000..af7498476
--- /dev/null
+++ b/cli/src/superTabs/inCore/launch.ts
@@ -0,0 +1,15 @@
+/**
+ * The Swarm's part of an agent's start (core/api.ts `SwarmLaunch`): which roles and skill modes a start may ask for, the
+ * role's skill written into the project folder, and the Harness GitHub App's git and gh for another person's project
+ * work. The core is handed it while the Swarm is on, and refuses a start with a Swarm role while it is off.
+ */
+import type { SwarmLaunch } from '../../core/api.js'
+import { swarmGitHubLaunch } from '../../lib/swarmGitHub.js'
+import { isSwarmRole, isSwarmSkillMode, prepareSwarmSkill } from '../../lib/swarmSkills.js'
+
+export const SWARM_LAUNCH: SwarmLaunch = {
+ role: isSwarmRole,
+ mode: isSwarmSkillMode,
+ prepare: prepareSwarmSkill,
+ github: (key) => swarmGitHubLaunch(key),
+}
diff --git a/cli/src/core/superTabSkills.spec.ts b/cli/src/superTabs/inCore/role.spec.ts
similarity index 95%
rename from cli/src/core/superTabSkills.spec.ts
rename to cli/src/superTabs/inCore/role.spec.ts
index 19438060b..e077198b7 100644
--- a/cli/src/core/superTabSkills.spec.ts
+++ b/cli/src/superTabs/inCore/role.spec.ts
@@ -1,5 +1,5 @@
import { expect, it, vi } from 'vitest'
-import { swarmRoleThrough } from './superTabSkills.js'
+import { swarmRoleThrough } from './role.js'
it('reads only validated role answers, with their project\'s skill mode, through the Super Tab process', async () => {
const answers = [{ ok: true, role: 'lead', mode: 'default' }, { ok: true, role: 'dev', mode: 'orchestration' }, { ok: true, role: 'review', mode: 'light' },
diff --git a/cli/src/core/superTabSkills.ts b/cli/src/superTabs/inCore/role.ts
similarity index 95%
rename from cli/src/core/superTabSkills.ts
rename to cli/src/superTabs/inCore/role.ts
index 365d10b41..f8f470e09 100644
--- a/cli/src/core/superTabSkills.ts
+++ b/cli/src/superTabs/inCore/role.ts
@@ -1,5 +1,5 @@
/** The same role lookup in a separate Super Tab process. Missing/older services grant no skill. */
-import { isSwarmRole, isSwarmSkillMode, type SwarmSkillGrant } from '../lib/swarmSkills.js'
+import { isSwarmRole, isSwarmSkillMode, type SwarmSkillGrant } from '../../lib/swarmSkills.js'
export function swarmRoleThrough(call: (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>) {
return async (harnessId: string): Promise<SwarmSkillGrant | null | undefined> => {
diff --git a/cli/src/core/superTabTerminal.spec.ts b/cli/src/superTabs/inCore/terminal.spec.ts
similarity index 95%
rename from cli/src/core/superTabTerminal.spec.ts
rename to cli/src/superTabs/inCore/terminal.spec.ts
index c12a09b91..0868ca808 100644
--- a/cli/src/core/superTabTerminal.spec.ts
+++ b/cli/src/superTabs/inCore/terminal.spec.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
-import type { RegisteredSession } from '../lib/registry.js'
-import type { ScreenReading } from '../engines/facets/screen.js'
-import { createSuperTabTerminal } from './superTabTerminal.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { ScreenReading } from '../../engines/facets/screen.js'
+import { createSuperTabTerminal } from './terminal.js'
const session = { agentId: 'h1', engine: 'claude' } as RegisteredSession
const reading = (messageHold: ScreenReading['messageHold']) => ({ messageHold } as ScreenReading)
diff --git a/cli/src/core/superTabTerminal.ts b/cli/src/superTabs/inCore/terminal.ts
similarity index 93%
rename from cli/src/core/superTabTerminal.ts
rename to cli/src/superTabs/inCore/terminal.ts
index 56c5f31de..42beec69a 100644
--- a/cli/src/core/superTabTerminal.ts
+++ b/cli/src/superTabs/inCore/terminal.ts
@@ -6,10 +6,10 @@
* pane as every other writer does, under the pane's write lock.
*/
import { stripVTControlCharacters } from 'node:util'
-import type { ScreenReading } from '../engines/facets/screen.js'
-import type { RegisteredSession } from '../lib/registry.js'
-import type { TerminalCaptureOptions, TerminalReadResult } from '../lib/terminalTypes.js'
-import type { SuperTabScreen, SuperTabTyped } from './api.js'
+import type { ScreenReading } from '../../engines/facets/screen.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { TerminalCaptureOptions, TerminalReadResult } from '../../lib/terminalTypes.js'
+import type { SuperTabScreen, SuperTabTyped } from '../../core/api.js'
export interface SuperTabTerminalDeps {
resolve(agentId: string): RegisteredSession | undefined
diff --git a/cli/src/superTabs/inServices.ts b/cli/src/superTabs/inServices.ts
new file mode 100644
index 000000000..3e741be4f
--- /dev/null
+++ b/cli/src/superTabs/inServices.ts
@@ -0,0 +1,19 @@
+/**
+ * The Swarm's side of the services that act on it from outside it: the one entry they get it through, loaded only while
+ * the Swarm is on (`HARNESS_SWARM`, harnessd/services.ts), in a service's own process (serviceProcess.ts) or in the
+ * core's when they run there (core/main.ts). Off, none of this is loaded and each runs as it does without the Swarm;
+ * src/architecture.spec.ts checks that they reach the Swarm's code by no other way.
+ *
+ * - The agent cleanup: the Super Tab members it keeps from both forms of cleanup (services/agentCleanup.ts `retained`).
+ * - Share: the observers a Super Tab's roster lets watch a harness (services/sharing.ts `observers`).
+ * - Change agent: a member's replacement, recorded for its host (services/handoff.ts `replacements`).
+ * - Models: a Swarm's grid, the APIs and models shared with it, and the check that keeps them there
+ * (services/models.ts `SwarmModels`).
+ */
+export { retainedHarnesses } from './retention.js'
+export { observerSource } from './observers.js'
+export { recordReplacement } from './replacements.js'
+export { syncSwarmGrid } from '../lib/swarmGrid.js'
+export { SwarmApiShares } from '../lib/swarmApiShares.js'
+export { liveModels, SwarmHeal } from '../lib/swarmHeal.js'
+export { SwarmOffers } from '../lib/swarmOffers.js'
diff --git a/cli/src/superTabs/observers.ts b/cli/src/superTabs/observers.ts
index ce686b5eb..641c64d98 100644
--- a/cli/src/superTabs/observers.ts
+++ b/cli/src/superTabs/observers.ts
@@ -1,13 +1,14 @@
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import type { DerivedGrant, HarnessGrant } from '../sharing/grants.js'
+import { observerSnapshotFile, savedConfidential, superTabOf } from '../sharing/swarmMarks.js'
import { identifier, object } from './wire.js'
+// Which grants are a Super Tab's, and the confidential marks: read by Share with the Swarm off too (sharing/swarmMarks.ts).
+export { observerSnapshotFile, superTabOf }
+
type Wanted = Omit<DerivedGrant, 'ownerPublicKey'>
const PREFIX = 'super:'
-export function superTabOf(grant: Pick<HarnessGrant, 'tab'>): string | null {
- return grant.tab?.startsWith(PREFIX) ? grant.tab.slice(PREFIX.length) : null
-}
/** How long a published roster authorizes its observers, counted from the roster read that answered: the host's
* refresh cadence (superTabs/host.ts reads the roster each second) plus a margin for a slow read. It was 2.5 s from
* the moment a read was ASKED, while the roster read took 1 to 2.8 s: measured 2026-10-23 on MacBookPro2021, the
@@ -17,16 +18,6 @@ export function superTabOf(grant: Pick<HarnessGrant, 'tab'>): string | null {
* them, and the backend checks membership again for every observer connection (routes/harnessShares.ts). */
export const OBSERVER_REFRESH_MS = 1_000, OBSERVER_SLOW_READ_MS = 10_000
export const OBSERVER_VALID_MS = OBSERVER_REFRESH_MS + OBSERVER_SLOW_READ_MS
-export function observerSnapshotFile(dataDir: string, machineId: string) {
- return join(dataDir, 'super-tabs', `observers-${machineId}.json`)
-}
-/** The sessions the last snapshot recorded as confidential (a Lead, or in a private chat, in some Swarm). */
-function savedConfidential(file: string, machineId: string): string[] {
- try {
- const saved = object(JSON.parse(readFileSync(file, 'utf8')))
- return saved.machineId === machineId && Array.isArray(saved.confidential) ? saved.confidential.filter(identifier) : []
- } catch { return [] }
-}
/** Ephemeral authorization, not a durable grant. A stalled or dead producer's
* snapshot expires; restarting Share never extends it from the clock alone.
diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.ts
index 9bed02872..de86b42a2 100644
--- a/cli/src/superTabs/terminal.ts
+++ b/cli/src/superTabs/terminal.ts
@@ -2,7 +2,7 @@
* The host's side of a Lead reading and typing into a worker's terminal (spec/2026-10-23-lead-sees-agent-terminal.md).
* Workers got stuck on what only their terminal showed (a permission prompt, a usage-limit screen, a model picker) and
* only a person at that machine could see and clear it. The backend relays the Lead's request to the host of the agent's
- * machine; the host reads or types with the core's own capture and input (core/superTabTerminal.ts) and answers as that
+ * machine; the host reads or types with the core's own capture and input (superTabs/inCore/terminal.ts) and answers as that
* agent. It also tells the Lead, once per episode, when a worker has sat on a prompt for 3 minutes or its screen shows
* a usage limit. The same reads tell the machine report when each agent's screen last changed: the backend renews the
* agent's lease on its task from that (docs: swarm-never-stops, v1 liveness).
@@ -25,7 +25,7 @@ const PROMPT_WAIT_MS = 3 * 60_000
const MAX_SCREEN_BYTES = 64 * 1024
/** What the screen reader says a prompt or a question is waiting on; a popup or a hidden prompt is not one. */
export const WAITING: ReadonlySet<MessageHold> = new Set(['permission_open', 'question_open', 'menu_open', 'trust_open', 'update_prompt_open', 'model_prompt_open', 'sign_in_open'])
-/** The spec's named keys, in any case: the name the Lead's request carries, and the terminal's own (core/superTabTerminal.ts).
+/** The spec's named keys, in any case: the name the Lead's request carries, and the terminal's own (superTabs/inCore/terminal.ts).
* Ctrl-D and the like are left out: one closes an engine. */
const KEYS: Record<string, [string, string]> = { enter: ['Enter', 'Enter'], esc: ['Esc', 'Escape'], escape: ['Esc', 'Escape'], tab: ['Tab', 'Tab'],
up: ['Up', 'Up'], down: ['Down', 'Down'], left: ['Left', 'Left'], right: ['Right', 'Right'], 'ctrl-c': ['Ctrl-C', 'C-c'],
diff --git a/cli/vitest.super-tabs.config.ts b/cli/vitest.super-tabs.config.ts
index 9e748c33c..f115e2c89 100644
--- a/cli/vitest.super-tabs.config.ts
+++ b/cli/vitest.super-tabs.config.ts
@@ -3,8 +3,10 @@ import { defineConfig } from 'vitest/config'
import base from './vitest.config.js'
/** Super Tab routing v1 (docs/superpowers/specs/2026-10-19-super-tab-routing-v1-design.md): new files outside
- * the core and services, which no other gate covers, held to 100% in every file. */
-const FILES = ['src/superTabs/route.ts', 'src/superTabs/routeCommand.ts', 'src/superTabs/shortCommand.ts']
+ * the core and services, which no other gate covers, held to 100% in every file. And the Swarm's side of the core's
+ * process (superTabs/inCore/), which left the core's own 100% gate when the Swarm became a switch. */
+const IN_CORE = ['adoption', 'agents', 'attention', 'cards', 'deliveries', 'launch', 'role', 'terminal'].map(name => `src/superTabs/inCore/${name}.ts`)
+const FILES = ['src/superTabs/route.ts', 'src/superTabs/routeCommand.ts', 'src/superTabs/shortCommand.ts', ...IN_CORE]
export default defineConfig({
test: {
...base.test,
diff --git a/docs/swarms.md b/docs/swarms.md
index f87489434..9bd4b7616 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -247,6 +247,34 @@ summary, or `text: null` when nothing merits another message. Human questions,
serious blockers and completion are reported immediately. This does not start
a second summarizing model or forward every terminal turn.
+## Switching Swarms off on a computer
+
+Swarms are on by default. To run a computer's daemon without them, set
+`HARNESS_SWARM=off` (`0`, `false` and `no` also work) in the environment the
+daemon starts with, then restart it (`harness stop && harness start`). Anything else, or
+leaving it unset, keeps Swarms on.
+
+With Swarms off:
+
+- The daemon never starts the Swarm service, even if the computer has saved
+ Swarm state. No daemon process loads the Swarm's code: not the core, and not
+ the agent cleanup, Share, change agent or models.
+- Agents start, run and close exactly as they do without Swarms. A Product
+ Manager the Swarm kept running can now be stopped like any other agent, and a
+ harness an agent started is cleaned up like any other, even if a Swarm kept it.
+- The computer can't contribute to a Swarm. Swarm requests, including
+ `harness super-tab` and the Swarm's model requests, answer that the service is
+ unavailable. A new agent that asks for a Swarm role is refused, and so is
+ reopening an agent a Swarm started, since it would come back without its role.
+- The computer serves no saved API or model to a Swarm's grid.
+- People watching a harness through a Swarm can't see it, and a session a Swarm
+ marked confidential (a Product Manager, or one in a private chat) still
+ can't be shared at all. That mark is the one piece of saved Swarm state still
+ read while Swarms are off.
+
+Turn Swarms back on by removing the setting and restarting the daemon. Saved
+Swarm state is kept while they're off, so the computer picks up where it left off.
+
## Compatibility and rollout
The internal `superTab` storage keys and `harness super-tab` command stay stable.