The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Harness Team account: set it up from the row, explained first, on the owner's subscriptions; switch held to listed Swarm owners
bitcoinbuilder1d8bc9b518bf
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 6abfce307..1503e7fa5 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -153,19 +153,28 @@ const PRIVACY_ITEMS: Record<string, string> = {const ONLY_OWN = 'so it runs only its owner\'s projects'/**- * Whether a teammate's work needs a Harness Team account on every machine (`SWARM_TEAM_ACCOUNT_REQUIRED=1`). Until the- * CLI that makes team accounts is released, it does not: a machine without one takes a teammate's work as it did before- * team accounts, while a machine with one already follows the rule. Read on every call, so a test can set it.+ * Whether a teammate's work needs a Harness Team account on every machine of [state]'s Swarm+ * (`SWARM_TEAM_ACCOUNT_REQUIRED=1`). Until the CLI that makes team accounts is released, it does not: a machine without+ * one takes a teammate's work as it did before team accounts, while a machine with one already follows the rule.+ *+ * `SWARM_TEAM_ACCOUNT_OWNERS`, comma-separated emails, holds the switch to the Swarms those people own, so it can be tried+ * on production with one's own Swarm first and no other Swarm changes (2026-10-27). Empty, it is every Swarm's. Both are+ * read on every call, so a test can set them.*/-export function teamAccountRequired(): boolean {- return process.env.SWARM_TEAM_ACCOUNT_REQUIRED === '1'+export function teamAccountRequired(state?: Pick<SuperTabState, 'ownerId' | 'people'>): boolean {+ if (process.env.SWARM_TEAM_ACCOUNT_REQUIRED !== '1') return false+ const owners = (process.env.SWARM_TEAM_ACCOUNT_OWNERS ?? '').split(',').map(email => email.trim().toLowerCase()).filter(Boolean)+ if (!owners.length) return true+ const owner = state?.people.find(person => person.id === state.ownerId)?.email.toLowerCase()+ return !!owner && owners.includes(owner)}/** Why this contributed machine may not run a teammate's project now, or null when it may. `teamRow`: its account row- * says it is signed in as a team account (`Machine.sessionKind`), read by the store. */-export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow = false): TeamWorkRefusal | null {+ * says it is signed in as a team account (`Machine.sessionKind`), read by the store. `required`: whether the Swarm it is+ * in needs a team account on every machine ([teamAccountRequired] of that Swarm). */+export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow = false, required = teamAccountRequired()): TeamWorkRefusal | null {const reading = pool.observation, name = pool.name- if (!teamRow && reading?.sessionKind !== 'team' && !teamAccountRequired()) return null+ if (!teamRow && reading?.sessionKind !== 'team' && !required) return nullif (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) {// A Mac's team account goes by its Mac's name ("One machine"), and the Mac itself may well be online.return { code: 'MACHINE_OFFLINE', reason: pool.hostMachineId@@ -200,10 +209,10 @@ export function teamWorkCheck(state: SuperTabState, machineId: string, contributconst pool = state.machines?.find(m => m.machineId === machineId)if (!pool) {// Off the Machines list nothing reports a team account (store.ts teamMachines), so this is the switch alone.- if (!teamAccountRequired()) return null+ if (!teamAccountRequired(state)) return nullreturn { code: 'TEAM_ACCOUNT_REQUIRED', reason: `This machine is not a Team machine of this Swarm, ${ONLY_OWN}.` }}- return teamWorkRefusal(pool, now, teamMachines.includes(machineId))+ return teamWorkRefusal(pool, now, teamMachines.includes(machineId), teamAccountRequired(state))}// ── One machine: a Mac and its Harness Team account ─────────────────────────────────────────────────────────────────diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 345238d69..cc598e476 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -4,7 +4,7 @@* in `derived`, so a part never changes without a new version (Lead's ruling).*/import { isLeads, visibleState, type Actor, type Agent, type Conversation, type SuperTabState } from '../model.js'-import { machineSlots, teamWorkRefusal, type ContributedMachine } from '../machines.js'+import { machineSlots, teamAccountRequired, teamWorkRefusal, type ContributedMachine } from '../machines.js'import * as store from '../parts/index.js'import type { Part, SwarmParts } from '../parts/index.js'import { canReadGroup } from '../projects.js'@@ -89,7 +89,7 @@ export const progressView = (data: NonNullable<SwarmParts['progress'][number]['dfunction derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now: number, extras: ReadExtras): Derived {const machine = (pool: ContributedMachine) => {const stored = state.machines!.find(m => m.machineId === pool.machineId)!- const refusal = teamWorkRefusal(stored, now, extras.teamMachines.includes(pool.machineId))+ const refusal = teamWorkRefusal(stored, now, extras.teamMachines.includes(pool.machineId), teamAccountRequired(state))return [pool.machineId, { availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, stored)),teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const } }] as const}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex ac5a6f55c..3c7396274 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,4 +1,4 @@-import { contributedEngines, expireRemovals, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, machineSlots, observedPrivacy, recordAgentPresence, removalPreview, swarmGridRow, teamWorkRefusal, type MachineObservation } from './machines.js'+import { contributedEngines, expireRemovals, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, machineSlots, observedPrivacy, recordAgentPresence, removalPreview, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'import { createHash } from 'node:crypto'import type { Prisma, PrismaClient, SuperTab, SuperTabDelivery, SuperTabMessage } from '@prisma/client'import type { AuthUser } from '../lib/ssoAuth.js'@@ -568,7 +568,7 @@ export class SuperTabStore {const stored = state.machines!.find(m => m.machineId === pool.machineId)!// Whether it takes teammates' projects now, and if not why (machines.ts teamWorkRefusal): what routing leaves it// out for, and what Desktop can show on the machine.- const refusal = teamWorkRefusal(stored, now, teamMachines.includes(pool.machineId))+ const refusal = teamWorkRefusal(stored, now, teamMachines.includes(pool.machineId), teamAccountRequired(state))return { ...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, stored)),teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const } }}) } }diff --git a/backend/src/superTabs/teamRouting.test.ts b/backend/src/superTabs/teamRouting.test.tsindex 7f3246f36..286654ada 100644--- a/backend/src/superTabs/teamRouting.test.ts+++ b/backend/src/superTabs/teamRouting.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { applyCommand, type Command, type CommandContext } from './commands.js'-import { admitMachineStart, machineObservationSchema, machineSlots, observedPrivacy, PRIVACY_FRESH_MS, removalPreview, teamWorkRefusal, type ContributedMachine, type MachinePrivacy } from './machines.js'+import { admitMachineStart, machineObservationSchema, machineSlots, observedPrivacy, PRIVACY_FRESH_MS, removalPreview, teamAccountRequired, teamWorkRefusal, type ContributedMachine, type MachinePrivacy } from './machines.js'import { createSuperTab, SuperTabError, visibleState, type Actor, type AgentConfiguration, type AgentStart, type SuperTabState } from './model.js'import type { RouteDecision } from './routeRecord.js'@@ -373,6 +373,38 @@ describe('until a team account is required everywhere', () => {})})+// Tried on production with one person's Swarms first (2026-10-27): SWARM_TEAM_ACCOUNT_OWNERS holds the switch to the+// Swarms those people own, and every other Swarm stays as it is with the switch off.+describe('the switch held to the Swarms of listed owners', () => {+ afterEach(() => { delete process.env.SWARM_TEAM_ACCOUNT_OWNERS })++ it('requires a team account in a listed owner\'s Swarm, and in no other', () => {+ const f = swarm(), group = f.group()+ process.env.SWARM_TEAM_ACCOUNT_OWNERS = ' [email protected], [email protected] '+ expect(teamAccountRequired(f.state)).toBe(true)+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac')))?.code)+ .toBe('TEAM_ACCOUNT_REQUIRED')+ process.env.SWARM_TEAM_ACCOUNT_OWNERS = '[email protected]'+ expect(teamAccountRequired(f.state)).toBe(false)+ f.run({ type: 'agent.start', request: f.request(group, 'mate-mac') }, owner, f.pooled('mate-mac'))+ expect(f.state.starts).toHaveLength(1)+ // A Team machine follows the rule in every Swarm, as it does with the switch off.+ f.machine('mate-team').observation = reading('team', FAILED)+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'mate-team') }, owner, f.pooled('mate-team')))?.code).toBe('PRIVACY_CHECK_FAILED')+ })++ it('is every Swarm\'s with no list, and none with the switch off, list or not', () => {+ const f = swarm()+ process.env.SWARM_TEAM_ACCOUNT_OWNERS = ' , '+ expect(teamAccountRequired(f.state)).toBe(true)+ expect(teamAccountRequired()).toBe(true)+ process.env.SWARM_TEAM_ACCOUNT_OWNERS = '[email protected]'+ expect(teamAccountRequired()).toBe(false)+ delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED+ expect(teamAccountRequired(f.state)).toBe(false)+ })+})+// One machine ("One machine" in docs/plans/2026-10-24-swarm-team-account.md): a Mac's Harness Team account is a// mechanism under the scenes. Its pool names the Mac it lives on (`hostMachineId`), shows the Mac's name, joins where// the Mac was added and follows the Mac's pause, slots and removal. A teammate's project started on the Mac runs indiff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 2921988c3..1d4e64022 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -229,6 +229,21 @@ describe('creating an agent', () => {expect(vi.mocked(buildEngineLaunchArgv).mock.calls.at(-1)![1]?.clearEnv).toContain('GH_TOKEN')})+ it('in the Harness Team account, points an engine it has not signed in at the owner\'s relay; never one on a grid', async () => {+ const ownerRelay = vi.fn(async () => ({ env: { HARNESS_RELAY_TOKEN: 't' }, args: ['-c', 'model_provider="harness_owner"'] }))+ expect(await setup({ ownerRelay }).create(request({ engine: 'codex', cwd: folder() }))).toMatchObject({ ok: true })+ expect(ownerRelay).toHaveBeenCalledWith('codex')+ expect(vi.mocked(createAndRegisterPane).mock.calls.at(-1)![0].env).toMatchObject({ HARNESS_RELAY_TOKEN: 't' })+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls.at(-1)![1]?.extraArgs).toEqual(expect.arrayContaining(['model_provider="harness_owner"']))+ // No relay there (signed in, or not a team account): the launch is as before.+ const none = vi.fn(async () => null)+ await setup({ ownerRelay: none }).create(request({ cwd: folder() }))+ expect(vi.mocked(createAndRegisterPane).mock.calls.at(-1)![0].env ?? {}).not.toHaveProperty('HARNESS_RELAY_TOKEN')+ ownerRelay.mockClear()+ await setup({ ownerRelay }).create(request({ cwd: folder(), grid: { baseUrl: 'https://grid.example/relay/v1', networkName: 'g', model: 'm' } }))+ expect(ownerRelay).not.toHaveBeenCalled()+ })+it('launches as before where the GitHub App does not apply, and without a role never asks', async () => {await setup().create(request({ cwd: folder(), swarmRole: 'dev', swarmGitHub: true }))const pane = vi.mocked(createAndRegisterPane).mock.calls.at(-1)![0]diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex f0dc9d364..299fdadb3 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -96,12 +96,15 @@ export interface CreateAgentDeps {gridSetup: () => ModelsPort['ensure'] | nullprivateGridName: () => Promise<string | null>dshLaunch: Pick<DshThrough, 'materialize' | 'launch'>+ /** 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>}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,+ gridSetup, privateGridName, dshLaunch, ownerRelay,}: 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) }@@ -284,6 +287,9 @@ export function createAgentCreator({// normally launched one. The key is never printed.console.log(describeGridLaunch(engine, grid, built.launch.webSearch))}+ // In the Harness Team account, an engine it has not signed in itself spends the owner's subscription through the+ // owner's relay (team/relay.ts), where a grid would otherwise sit: a grid launch is its own provider.+ const relay = !grid && ownerRelay ? await ownerRelay(engine) : nullif (!current()) return stale()// The Swarm starts its agents in full mode, so a machine that never accepted full mode's warning stops each one there// before its first turn (Claude Code's "Yes, I accept", the Mac Studio, 2026-10-26). The Swarm's owner chose that mode@@ -360,7 +366,7 @@ export function createAgentCreator({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 } : {}) })- const extraArgs = joinedInstructions(engine, [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null) : []), ...told])+ const extraArgs = joinedInstructions(engine, [...(gridLaunch?.args ?? relay?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null) : []), ...told])// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).const firstPrompt = prompt@@ -399,7 +405,7 @@ export function createAgentCreator({// Windows: the workspace to start in and the shell the pane becomes after the engine (lib/windows/engineStart.ts).paneLaunch: windowsPaneLaunch(engine, { ...launchOptions, held: isWindowsHeldPane(argv) }),// Windows: the variables the argv's `/usr/bin/env` prefix carries elsewhere, last (engineLaunchEnv).- env: mergedLaunchEnv(freshHarnessEnvironment(engine, mergedLaunchEnv(mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? profileEnvironment(engine, codexHome) : undefined), dshEnv),+ env: mergedLaunchEnv(freshHarnessEnvironment(engine, mergedLaunchEnv(mergedLaunchEnv(gridLaunch?.env ?? mergedLaunchEnv(codexHome ? profileEnvironment(engine, codexHome) : undefined, relay?.env), dshEnv),mergedLaunchEnv(mergedLaunchEnv(scmLaunchEnv(scmLaunchRecord), swarmGitHub?.env), native?.environment)), !!grid,permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')), engineLaunchEnv(engine, native)),grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex f7ae28c75..41eadd88a 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1,6 +1,7 @@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'import { masterRunsEngineQuestionControl } from '../harnessd/services.js'@@ -2378,6 +2379,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {capabilities: () => createBackend?.capabilities() ?? Promise.resolve({ sessionEnv: true }),installCodexHooks: (codexHome) => env.DISABLE_HOOK_INSTALL ? true : engineHookFacets.codex.installIn(hookPort, codexHome),dshLaunch: dshLaunch.relaunch,+ ownerRelay: realTeamRelayLaunch,}// 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.@@ -2698,6 +2700,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {publishConfig: publishGridConfigDir,native: prepareNativeLaunch,dshLaunch,+ ownerRelay: realTeamRelayLaunch,createBackend,recoverBackend,noBackendCode: createUnavailable,diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex 0ac84d62d..1dc14ec02 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -209,6 +209,23 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (expect(calls).toEqual([])})+ it('in the Harness Team account, spends the owner\'s subscription through the relay on every relaunch', async () => {+ const relay = { env: { HARNESS_RELAY_TOKEN: 't' }, args: ['-c', 'model_provider="harness_owner"'] }+ const ownerRelay = vi.fn(async (engine: string) => engine === 'codex' ? relay+ : engine === 'claude' ? { env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:9/claude', ANTHROPIC_AUTH_TOKEN: 't' }, args: [] } : null)+ // Codex is told the relay's provider in place of its own login's: two `-c model_provider` would leave it to pick.+ expect(await buildLaunchOverrides(deps({ ownerRelay }).d, 'codex', { subscriptionModel: 'gpt-5-codex' }, 'a'))+ .toMatchObject({ ok: true, overrides: { env: { HARNESS_RELAY_TOKEN: 't' }, extraArgs: ['-c', 'model_provider="harness_owner"', '-m', 'gpt-5-codex'] } })+ expect(await buildLaunchOverrides(deps({ ownerRelay }).d, 'claude', {}, 'a'))+ .toMatchObject({ ok: true, overrides: { env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:9/claude', ANTHROPIC_AUTH_TOKEN: 't' }, extraArgs: [] } })+ expect(await buildLaunchOverrides(deps({ ownerRelay }).d, 'codex', { gridLaunch: null, codexHome: '/home/u/.codex-work' }, 'a'))+ .toMatchObject({ ok: true, overrides: { env: { CODEX_HOME: '/home/u/.codex-work', HARNESS_RELAY_TOKEN: 't' }, extraArgs: relay.args } })+ // A grid is its own provider: the relay is not asked.+ ownerRelay.mockClear()+ await buildLaunchOverrides(deps({ ownerRelay }).d, 'codex', { gridLaunch: GRID }, 'a')+ expect(ownerRelay).not.toHaveBeenCalled()+ })+it('builds OpenCode overrides without optional code and uses the requested engine facts', async () => {vi.mocked(loadEngine).mockImplementation(() => new Promise(() => {}))expect(await buildLaunchOverrides(deps().d, 'opencode', {}, 'agent-1')).toMatchObject({ ok: true })diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex 2d0e9f94e..ba52fd83d 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -104,6 +104,9 @@ export interface LaunchOverridesDeps {* file. See `ownProvider` in `engines/codex/launch.ts`.*/readCodexConfig?: (path: string) => string | null+ /** 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>/** Prepare the saved harness context before restarting. Missing or broken packages refuse the* relaunch: starting a plain agent would silently change the user's chosen harness. */dshLaunch?: (dsh: string, workspace: string, engine: AgentEngine, runtimeKey: string) => Promise<DshLaunchAnswer>@@ -326,12 +329,16 @@ async function prepareBaseLaunchOverrides(let ownLogin: LaunchOverrides | null = nullif (!source.gridLaunch) {const restored = subscriptionModelLaunch(engine, source.subscriptionModel, (await deps.machine(engine)).opencodeMajor ?? null)+ // In the Harness Team account, an engine it has not signed in itself spends the owner's subscription through the+ // owner's relay, on every relaunch as on its first: Codex keeps the relay's provider per thread, so it is named again+ // here in place of its own login's (two `-c model_provider` would leave Codex to pick one).+ const relay = await deps.ownerRelay?.(engine) ?? null// Ahead of the model on the command line: `-c` configures, `-m` selects, and Codex resolves the// model against the provider it has been given.- const provider = ownLoginProviderArgs(engine, source.codexHome, { read: deps.readCodexConfig })- if (restored || provider.length) {+ const provider = relay ? relay.args : ownLoginProviderArgs(engine, source.codexHome, { read: deps.readCodexConfig })+ if (restored || provider.length || relay) {ownLogin = {- env: { ...(restored?.env ?? {}) },+ env: { ...(relay?.env ?? {}), ...(restored?.env ?? {}) },extraArgs: [...provider, ...(restored?.args ?? [])],clearEnv: [],...(restored?.sessionModel ? { sessionModel: restored.sessionModel } : {}),diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex 64d01761c..2cc95cd57 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -14,7 +14,7 @@ import { HostFeed } from './hostFeed.js'import { SwarmReads } from './swarmReads.js'import type { PrivacyObservation } from '../team/privacy.js'-function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservation | null = () => null) {+function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservation | null = () => null, relayed: () => boolean = () => false) {let now = 1000, stamp = 's0'const core = fakeCore({ dataDir: '/isolated-pool-fixture', agents: {byAgent: vi.fn(id => id === 'running' ? { agentId: id } as never : undefined),@@ -31,7 +31,7 @@ function fixture(env: NodeJS.ProcessEnv = {}, privacy: () => PrivacyObservationconst prepare = vi.fn(async () => {})const log = vi.fn()const modelsStamp = vi.fn(async () => stamp)- const deps = { backend, open, capabilities, start, prepare, log, env, privacy, modelsStamp, now: () => now }+ const deps = { backend, open, capabilities, start, prepare, log, env, privacy, modelsStamp, relayed, now: () => now }const machine = new ContributedMachines(core, 'host', deps as never)return { deps, machine, pool, core, backend, open, request, close, capabilities, start, prepare, log, modelsStamp, advance: () => { now += 16000 }, step: (ms: number) => { now += ms },stamp: (next: string) => { stamp = next } }@@ -224,6 +224,13 @@ describe('contributed machine executor', () => {expect(probes(f)).toHaveLength(2)})+ it('reads a Harness Team account\'s engine it has not signed in as ready when its owner\'s relay is there', async () => {+ const f = fixture({}, () => null, () => true)+ withEngines(f)+ await f.machine.tick()+ expect(readings(f)[0]!.readiness?.engines).toEqual([{ engine: 'claude', installed: true, signedIn: true }, { engine: 'codex', installed: true, signedIn: null }])+ })+it('reads an engine the probe calls not installed as unknown, since a timed-out shell probe says the same (review of #1743)', async () => {const f = fixture()const usage = f.request.getMockImplementation()!diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex 6fdd034e7..6901aa729 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -18,6 +18,7 @@ import { git } from '../lib/worktreeSweep.js'import { projectsRoot } from '../lib/projectFolder.js'import { worktreeFolderName } from '../lib/agentNames.js'import { teamPrivacyObserver } from '../team/observer.js'+import { teamRelayed } from '../team/relay.js'import type { PrivacyObservation } from '../team/privacy.js'import { repositoryKey } from './route.js'@@ -105,6 +106,9 @@ export interface MachineDeps {/** When each of these harnesses' screens last changed, epoch ms (superTabs/terminal.ts `progressOf`): the backend* renews a task's lease from it, so work never sits with a dead owner (docs: swarm-never-stops). */progress?: (harnessIds: readonly string[]) => Record<string, number>+ /** In the Harness Team account: whether its engines can spend the owner's subscription through the owner's relay+ * (team/relay.ts), so one it has not signed in itself is ready all the same. */+ relayed?: () => boolean}const MACHINE_DEPS = { backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }@@ -154,8 +158,12 @@ export class ContributedMachines {// An engine that says nothing of its sign-in (an older daemon, an engine not installed) is unknown, never signed out.// Not installed is unknown too: the probe answers the same for a login shell that timed out (lib/engineProbe.ts), and// such a machine fails its first start loudly instead (review of #1743).+ // A Harness Team account that has not signed an engine in spends its owner's subscription through the owner's relay+ // (team/relay.ts): the Lead routed nothing to it while it read as signed out (routeCommand.ts `unreadyPool`).+ const relayed = (this.deps.relayed ?? teamRelayed)()const value = Array.isArray(engines) ? list(engines).filter(e => e.engine === 'claude' || e.engine === 'codex')- .map((e): ReadyEngine => ({ engine: String(e.engine), installed: e.installed === true ? true : null, signedIn: e.installed === true && typeof e.signedIn === 'boolean' ? e.signedIn : null })) : null+ .map((e): ReadyEngine => ({ engine: String(e.engine), installed: e.installed === true ? true : null,+ signedIn: e.installed === true && typeof e.signedIn === 'boolean' ? e.signedIn || relayed : null })) : nullthis.engineRead = { value, until: now + (value ? READINESS_MS : READINESS_RETRY_MS) }return value}diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex a23509584..76c7b4ed6 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -695,7 +695,7 @@ describe('GitHub App tokens through the service', () => {})it('runs a team daemon\'s Swarm host from its first connection, and a person\'s only once it hosts Swarm work', () => {- const quiet = { githubTokens: () => ({ start: vi.fn(), stop: vi.fn() }), teamEngines: () => ({ start: vi.fn(), stop: vi.fn() }) }+ const quiet = { githubTokens: () => ({ start: vi.fn(), stop: vi.fn() }), teamEngines: () => ({ start: vi.fn(), stop: vi.fn() }), teamRelay: () => ({ start: vi.fn(), stop: vi.fn(async () => {}) }) }const started = (team: boolean) => {const start = vi.fn()const service = superTabService(fakeCore({ dataDir: mkdtempSync(join(tmpdir(), 'team-wake-')) }),@@ -723,13 +723,27 @@ describe('GitHub App tokens through the service', () => {})})+describe('the owner\'s subscriptions for the Harness Team account', () => {+ it('start with the service\'s first connection and stop only with the service, not a lost connection', async () => {+ const relay = { start: vi.fn(), stop: vi.fn(async () => {}) }+ const service = superTabService(fakeCore(), { githubTokens: () => ({ start: vi.fn(), stop: vi.fn() }) as never,+ teamEngines: () => ({ start: vi.fn(), stop: vi.fn() }) as never, teamRelay: () => relay })+ service.port.connected()+ expect(relay.start).toHaveBeenCalledOnce()+ service.port.disconnected()+ expect(relay.stop).not.toHaveBeenCalled()+ service.port.stop()+ expect(relay.stop).toHaveBeenCalledOnce()+ })+})+describe('the Harness Team account, offered by Desktop on this Mac', () => {it('runs only for the local owner, for a moment the person is there, and says whether it started', async () => {const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>) => ({ state: 'started' as const }))- const make = vi.fn(async () => ({ offer }))+ const make = vi.fn(async () => ({ offer, decline: vi.fn() }))const service = superTabService(fakeCore(), { teamSetup: make })expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, owner)).toEqual({ ok: true, state: 'started' })- expect(offer).toHaveBeenCalledWith('join', expect.any(Function))+ expect(offer).toHaveBeenCalledWith('join', expect.any(Function), false)for (const asker of [visitor, { local: false, owner: true, accountOwner: true }]) {expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })}@@ -743,7 +757,7 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {it('at app start, answers at once on a Mac that hosts no Swarm work, as no regular user\'s does', async () => {const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>) => ({ state: 'not-shared' as const }))- const make = vi.fn(async () => ({ offer }))+ const make = vi.fn(async () => ({ offer, decline: vi.fn() }))const dataDir = mkdtempSync(join(tmpdir(), 'team-startup-'))const service = superTabService(fakeCore({ dataDir }), { teamSetup: make })expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'startup' }, owner)).toEqual({ ok: true, state: 'not-shared' })@@ -752,11 +766,27 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {mkdirSync(dirname(hostJournalFile(dataDir, 'machine-1')), { recursive: true })writeFileSync(hostJournalFile(dataDir, 'machine-1'), '{}')await service.requests.super_tabs({ action: 'teamSetup', reason: 'startup' }, owner)- expect(offer).toHaveBeenCalledWith('startup', expect.any(Function))+ expect(offer).toHaveBeenCalledWith('startup', expect.any(Function), false)+ })++ it('says whether it is wanted without asking macOS, runs it when the person asks, and remembers "Not now"', async () => {+ const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>, check?: boolean) => ({ state: check ? 'wanted' as const : 'started' as const }))+ const decline = vi.fn()+ const service = superTabService(fakeCore(), { teamSetup: async () => ({ offer, decline }) })+ expect(await service.requests.super_tabs({ action: 'teamSetupCheck', reason: 'join' }, owner)).toEqual({ ok: true, state: 'wanted' })+ expect(offer).toHaveBeenLastCalledWith('join', expect.any(Function), true)+ expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual' }, owner)).toEqual({ ok: true, state: 'started' })+ expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false)+ expect(await service.requests.super_tabs({ action: 'teamSetupDecline' }, owner)).toEqual({ ok: true })+ expect(decline).toHaveBeenCalledOnce()+ for (const action of ['teamSetupCheck', 'teamSetupDecline']) {+ expect(await service.requests.super_tabs({ action, reason: 'join' }, visitor)).toEqual({ error: 'OWNER_REQUIRED' })+ }+ expect(await service.requests.super_tabs({ action: 'teamSetupCheck', reason: 'later' }, owner)).toEqual({ error: 'INVALID_REQUEST' })})it('tries again to make its setup when making it failed', async () => {- const make = vi.fn().mockRejectedValueOnce(new Error('import failed')).mockResolvedValueOnce({ offer: async () => ({ state: 'exists' }) })+ const make = vi.fn().mockRejectedValueOnce(new Error('import failed')).mockResolvedValueOnce({ offer: async () => ({ state: 'exists' }), decline: vi.fn() })const service = superTabService(fakeCore(), { teamSetup: make })expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, owner)).toMatchObject({ error: 'SUPER_TAB_UNAVAILABLE' })expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, owner)).toEqual({ ok: true, state: 'exists' })diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 7239fffca..2e460f649 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -16,6 +16,10 @@ import { cardId, SwarmCards } from './cards.js'import { GitHubTokenRefresher, githubToken } from './github.js'import { teamEngineReporter, type TeamEngineReporter } from '../team/engines.js'import { AUTO_SETUP_REASONS, realTeamAutoSetup, type AutoSetupReason, type TeamAutoSetup } from '../team/autoSetup.js'+import { readTeamConfig } from '../team/config.js'+import { realTeamRelayPublisher, type TeamRelayPublisher } from '../team/relay.js'+import { createOwnerSubscriptions } from '../lib/ownerSubscriptions.js'+import { startSubscriptionRelay } from '../lib/subscriptionRelay.js'const POST_HELP = 'reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID. --attach sends a file (a screenshot, a log; up to 10 files of 10 MB each), and TEXT may then be empty.'const HELP = {@@ -173,9 +177,11 @@ export interface SuperTabServiceOptions {/** What reports the Harness Team account's own engines to its owner (team/engines.ts), for a spec. */teamEngines?: () => Pick<TeamEngineReporter, 'start' | 'stop'>/** What sets up the Harness Team account when Desktop asks (team/autoSetup.ts), for a spec. */- teamSetup?: () => Promise<Pick<TeamAutoSetup, 'offer'>>+ teamSetup?: () => Promise<Pick<TeamAutoSetup, 'offer' | 'decline'>>/** Whether this daemon runs team work only (a Harness Team account, `harness team on`), for a spec. */team?: () => boolean+ /** The owner's subscriptions for the Harness Team account (team/relay.ts), for a spec. */+ teamRelay?: () => Pick<TeamRelayPublisher, 'start' | 'stop'>}export function superTabService(core: CoreApi, options: SuperTabServiceOptions = {}): { requests: ServiceRequests; port: SuperTabsPort } {const preparations = new ContributionPreparations(input => (options.prepareContribution ?? prepareContribution)(core, input))@@ -218,12 +224,18 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =const tokens = (options.githubTokens ?? (api => new GitHubTokenRefresher(api, sources)))(core)// In the Harness Team account only: whether its Claude Code and Codex are installed and signed in, for its owner to read.const engines = (options.teamEngines ?? teamEngineReporter)()- let autoSetup: Promise<Pick<TeamAutoSetup, 'offer'>> | null = null+ // On the Mac's owner's daemon, while a Harness Team account exists here: the owner's subscriptions for it, through a+ // relay of its own (team/relay.ts). Kept through a lost backend connection, which running agents do not need.+ const relay = (options.teamRelay ?? (() => realTeamRelayPublisher(+ () => startSubscriptionRelay({ owner: createOwnerSubscriptions(), log: line => console.log(`[team] relay · ${line}`) }),+ () => readTeamConfig(), options.team ?? (() => readAuthSession()?.kind === 'team'), line => console.log(`[team] ${line}`))))()+ let autoSetup: Promise<Pick<TeamAutoSetup, 'offer' | 'decline'>> | null = nullconst disconnect = () => { preparations.clear(); host?.stop(); host = null; held = null; book?.stop(); book = null; bookMachine = null; swarmCards?.want(false); swarmCards = null; cardsMachine = null; tokens.stop(); engines.stop() }const port = {connected: () => {tokens.start()engines.start()+ relay.start()// A daemon that runs team work only is there for its Swarms: its host runs from its first connection. Its Mac's daemon adds// a Harness Team account to a Swarm without waking it (host.ts joinTeams), and a host that never ran reports no privacy// check, so the Swarm read the account as offline and never sent it a teammate's work (third VM run).@@ -231,7 +243,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =|| (options.team ?? (() => readAuthSession()?.kind === 'team'))())) wake()},disconnected: disconnect,- stop: disconnect,+ stop: () => { disconnect(); void relay.stop() },swarmRole: async (harnessId: string) => (await within(swarmRoleFor(sources(), harnessId).then(grant => ({ grant }))))?.grant,}const requests: ServiceRequests = {@@ -259,17 +271,21 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =}// Desktop on this Mac, as the person joins a Swarm, adds this Mac to one, or opens the app (team/autoSetup.ts): the// Harness Team account, behind macOS's own administrator prompt. Never through the relay, with nobody at this Mac.- if (payload.action === 'teamSetup') {+ // `teamSetupCheck` only says whether it is wanted, so Desktop explains it before macOS asks; `teamSetupDecline` is+ // that explanation's "Not now". Both are new names, so an older daemon refuses them rather than asking unexplained.+ if (payload.action === 'teamSetup' || payload.action === 'teamSetupCheck' || payload.action === 'teamSetupDecline') {if (!asker.local) return { error: 'OWNER_REQUIRED' }+ const setup = () => autoSetup ??= (options.teamSetup ?? (() => realTeamAutoSetup(core.dataDir, line => console.log(`[team] ${line}`))))()+ .catch(error => { autoSetup = null; throw error })+ if (payload.action === 'teamSetupDecline') { (await setup()).decline(); return { ok: true } }if (!AUTO_SETUP_REASONS.includes(payload.reason as AutoSetupReason)) return { error: 'INVALID_REQUEST' }// Desktop asks at every launch. A Mac that hosts no Swarm work, as no regular user's does, answers at once:// nothing read, run or asked of the backend.if (payload.reason === 'startup' && !(identifier(core.daemon.machineId()) && existsSync(hostJournalFile(core.dataDir, core.daemon.machineId())))) {return { ok: true, state: 'not-shared' }}- autoSetup ??= (options.teamSetup ?? (() => realTeamAutoSetup(core.dataDir, line => console.log(`[team] ${line}`))))()- .catch(error => { autoSetup = null; throw error })- return { ok: true, ...await (await autoSetup).offer(payload.reason as AutoSetupReason, () => sharedSwarm(sources())) }+ return { ok: true, ...await (await setup()).offer(payload.reason as AutoSetupReason, () => sharedSwarm(sources()),+ payload.action === 'teamSetupCheck') }}if (payload.action === 'swarmRole') {const grant = await port.swarmRole(String(payload.harnessId ?? ''))diff --git a/cli/src/team/autoSetup.spec.ts b/cli/src/team/autoSetup.spec.tsindex 93142a247..c04b8a897 100644--- a/cli/src/team/autoSetup.spec.ts+++ b/cli/src/team/autoSetup.spec.ts@@ -95,6 +95,30 @@ describe('the Harness Team account, set up on its own', () => {expect(shared.deps.setup).toHaveBeenCalledTimes(1)})+ it('says it is wanted without asking macOS, so Desktop can explain it first; "Not now" is remembered', async () => {+ const f = fake()+ expect(await f.auto.offer('startup', async () => true, true)).toEqual({ state: 'wanted' })+ expect(await f.auto.offer('startup', async () => false, true)).toEqual({ state: 'not-shared' })+ expect(f.deps.setup).not.toHaveBeenCalled()+ f.auto.decline()+ expect(f.decision()).toEqual({ state: 'declined', at: 1_000_000 })+ expect(await f.auto.offer('join', undefined, true)).toEqual({ state: 'declined' })+ const there = fake({ accountExists: vi.fn(async () => true) })+ expect(await there.auto.offer('manual', undefined, true)).toEqual({ state: 'exists' })+ })++ it('runs when the person asks, past a cancel or a failure remembered from before, and alone in a Swarm', async () => {+ const f = fake()+ f.setDecision({ state: 'declined', at: 1 })+ expect(await f.auto.offer('manual', undefined, true)).toEqual({ state: 'wanted' })+ expect(await f.auto.offer('manual')).toEqual({ state: 'started' })+ await f.auto.settled()+ f.setDecision({ state: 'failed', at: 1_000_000 })+ expect(await f.auto.offer('manual')).toEqual({ state: 'started' })+ await f.auto.settled()+ expect(f.deps.setup).toHaveBeenCalledTimes(2)+ })+it('keeps its memory in the daemon\'s own folder, private, and reads nothing it did not write', () => {const dir = mkdtempSync(join(tmpdir(), 'team-setup-'))cleanup.push(dir)diff --git a/cli/src/team/autoSetup.ts b/cli/src/team/autoSetup.tsindex e3f05d208..ba9155afc 100644--- a/cli/src/team/autoSetup.ts+++ b/cli/src/team/autoSetup.ts@@ -12,6 +12,11 @@* A cancelled prompt is remembered, so the next join does not ask again: only `harness team setup`, run by the person,* offers it again. Removing the account (`harness team remove`) is remembered the same way. A setup that failed is not* tried again on its own for a day.+ *+ * Desktop explains the account before macOS asks (the prompt is titled "osascript", which read as a surprise on+ * 2026-10-27): it first asks whether the setup is wanted (`check`), shows why, and only then runs it (`manual`), or+ * remembers "Not now" (`decline`). `manual` is also the machine row's Set up button: the person asked, so a cancel or+ * failure remembered from before does not stand in the way.*/import { readFileSync, renameSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'import { dirname, join } from 'node:path'@@ -48,11 +53,12 @@ export function writeTeamSetupDecision(file: string, decision: TeamSetupDecision/** A failed setup is offered again on its own after this long. */export const AUTO_SETUP_RETRY_MS = 24 * 60 * 60_000-export type AutoSetupState = 'unsupported' | 'signed-out' | 'dedicated' | 'running' | 'exists' | 'declined' | 'waiting' | 'not-shared' | 'started'+export type AutoSetupState = 'unsupported' | 'signed-out' | 'dedicated' | 'running' | 'exists' | 'declined' | 'waiting' | 'not-shared' | 'wanted' | 'started'-/** The moment the person is at this Mac: they joined a Swarm, added this Mac to one, or opened the app (`startup`). */-export type AutoSetupReason = 'join' | 'contribute' | 'startup'-export const AUTO_SETUP_REASONS: readonly AutoSetupReason[] = ['join', 'contribute', 'startup']+/** The moment the person is at this Mac: they joined a Swarm, added this Mac to one, or opened the app (`startup`); or+ * they asked for it (`manual`: Desktop's explanation was accepted, or the machine row's Set up button). */+export type AutoSetupReason = 'join' | 'contribute' | 'startup' | 'manual'+export const AUTO_SETUP_REASONS: readonly AutoSetupReason[] = ['join', 'contribute', 'startup', 'manual']export interface AutoSetupDeps {platform: NodeJS.Platform@@ -77,8 +83,9 @@ export class TeamAutoSetup {/*** Starts the setup when it is wanted, and answers at once with why it did or did not; the prompt is macOS's. At `startup`* it is wanted only while [sharedSwarm] says this Mac is in a Swarm with other people in it (false when it cannot say).+ * With [check] it starts nothing and answers `wanted` instead, for Desktop to explain the account first.*/- async offer(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean> = async () => false): Promise<{ state: AutoSetupState }> {+ async offer(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean> = async () => false, check = false): Promise<{ state: AutoSetupState }> {const { deps } = thisif (deps.platform !== 'darwin') return { state: 'unsupported' }const session = deps.session()@@ -86,15 +93,23 @@ export class TeamAutoSetup {if (session.kind === 'team') return { state: 'dedicated' }if (this.running) return { state: 'running' }if (deps.readConfig() || await deps.accountExists(TEAM_USER)) return { state: 'exists' }- const decision = deps.readDecision()- if (decision?.state === 'declined') return { state: 'declined' }- if (decision?.state === 'failed' && deps.now() - decision.at < AUTO_SETUP_RETRY_MS && deps.now() >= decision.at) return { state: 'waiting' }- if (reason === 'startup' && !await sharedSwarm().catch(() => false)) return { state: 'not-shared' }+ if (reason !== 'manual') {+ const decision = deps.readDecision()+ if (decision?.state === 'declined') return { state: 'declined' }+ if (decision?.state === 'failed' && deps.now() - decision.at < AUTO_SETUP_RETRY_MS && deps.now() >= decision.at) return { state: 'waiting' }+ if (reason === 'startup' && !await sharedSwarm().catch(() => false)) return { state: 'not-shared' }+ }+ if (check) return { state: 'wanted' }if (this.running) return { state: 'running' }this.running = this.run().finally(() => { this.running = null })return { state: 'started' }}+ /** "Not now" in Desktop's explanation: not offered again on its own, as a cancelled prompt is not. */+ decline(): void {+ this.deps.writeDecision({ state: 'declined', at: this.deps.now() })+ }+/** Waits for a setup this started, for a spec. */settled(): Promise<void> { return this.running ?? Promise.resolve() }diff --git a/cli/src/team/engines.spec.ts b/cli/src/team/engines.spec.tsindex 1704fefb4..d85afa68c 100644--- a/cli/src/team/engines.spec.ts+++ b/cli/src/team/engines.spec.ts@@ -56,6 +56,17 @@ describe('the team account\'s engines', () => {expect(ready).toContain('(checked 1000s ago)')expect(ready).not.toContain('To sign')expect(engineLines(undefined, ago)).toEqual([' engines ? not reported yet: the team daemon reports them once it runs'])+ // Not signed in, but its owner's relay is there: nothing to sign in.+ const relayed = engineLines(engines({ claude: { installed: true, signedIn: false, relayed: true }, codex: { installed: true, signedIn: null, relayed: true } }), ago).join('\n')+ expect(relayed).toContain('Claude Code ✓ installed · ✓ uses your subscription')+ expect(relayed).not.toContain('To sign')+ })++ it('says an engine it has not signed in uses the owner\'s subscription when the owner\'s relay is there', async () => {+ const result = await checkTeamEngines({ home: '/h', executable: () => true, now: () => 1, relayed: () => true,+ account: async (engine) => ({ signedIn: engine === 'codex', lastUsedAt: null }) })+ expect(result.claude).toEqual({ installed: true, signedIn: false, relayed: true })+ expect(result.codex).toEqual({ installed: true, signedIn: true })})})diff --git a/cli/src/team/engines.ts b/cli/src/team/engines.tsindex 9499d821f..53f4f1c55 100644--- a/cli/src/team/engines.ts+++ b/cli/src/team/engines.ts@@ -3,9 +3,9 @@** With the owner's home folder private, the engines installed under it are out of the team account's reach. Setup has* the team account install its own (./script.ts `TEAM_ENGINES`), with the vendors' npm packages, its own copy of- * Harness's Node and a prefix in its own home, never as root. Signing them in is one step the owner takes once, in a- * terminal on the team machine in Harness: nothing of the owner's sign-ins is copied, and each engine bills the- * account it is signed in with.+ * Harness's Node and a prefix in its own home, never as root. An engine it has not signed in spends the owner's+ * subscription through the owner's relay (./relay.ts): nothing of the owner's sign-ins is copied into it. One signed in+ * there (in a terminal on the team machine) still bills the account it is signed in with.** The owner cannot look inside the team account's home, so the team daemon reports what it finds (installed, signed in)* in its status file, as it starts and every minute after, and `harness team status` reads it there.@@ -16,6 +16,7 @@ import { join } from 'node:path'import { engineAccount, type EngineAccount } from '../lib/engineAccount.js'import { readTeamConfig, type TeamConfig } from './config.js'import { readTeamStatus, writeTeamStatus, type TeamStatus } from './privacy.js'+import { teamRelayed } from './relay.js'export type TeamEngine = 'claude' | 'codex'@@ -33,7 +34,8 @@ export const TEAM_ENGINES: readonly TeamEngineInfo[] = [{ engine: 'codex', name: 'Codex', packageName: '@openai/codex', signIn: 'codex login --device-auth' },]-export interface EngineReadiness { installed: boolean; signedIn: boolean | null }+/** [relayed]: not signed in itself, it spends the owner's subscription through the owner's relay (team/relay.ts). */+export interface EngineReadiness { installed: boolean; signedIn: boolean | null; relayed?: boolean }export type TeamEngines = { checkedAt: number } & Record<TeamEngine, EngineReadiness>/** Where the team account's engines are: its npm prefix's bin folder, on its daemon's PATH (./script.ts). */@@ -44,6 +46,8 @@ export interface EngineCheckDeps {executable(path: string): booleanaccount(engine: TeamEngine): Promise<EngineAccount>now(): number+ /** Whether the owner's relay is there for the team account's engines (team/relay.ts `teamRelayed`). */+ relayed?(): boolean}/** What the team account has of each engine: installed in its own home, and signed in (null when it cannot say). */@@ -53,7 +57,7 @@ export async function checkTeamEngines(deps: EngineCheckDeps): Promise<TeamEnginconst installed = deps.executable(teamEngineBin(deps.home, engine))let signedIn: boolean | null = nulltry { signedIn = (await deps.account(engine)).signedIn } catch { /* cannot say */ }- result[engine] = { installed, signedIn }+ result[engine] = { installed, signedIn, ...(signedIn !== true && deps.relayed?.() ? { relayed: true } : {}) }}return result}@@ -64,6 +68,7 @@ export const realEngineCheckDeps = (home: string, env: NodeJS.ProcessEnv = proce// Only presence is read, never a secret (lib/engineAccount.ts). The team daemon has no login shell of the owner's to read.account: (engine) => engineAccount(engine, { home, env, lastUsed: false }),now: () => Date.now(),+ relayed: teamRelayed,})/** How often the team daemon looks again: an engine signed in shows in `harness team status` within this long. */@@ -109,7 +114,8 @@ export class TeamEngineReporter {const engines = await this.deps.check(config)const before = this.deps.read(config.statusFile)?.enginesconst same = before && TEAM_ENGINES.every(({ engine }) =>- before[engine].installed === engines[engine].installed && before[engine].signedIn === engines[engine].signedIn)+ before[engine].installed === engines[engine].installed && before[engine].signedIn === engines[engine].signedIn+ && !before[engine].relayed === !engines[engine].relayed)// Unchanged, the file is left alone, but a stamp more than ten minutes old is renewed so status can say it is current.if (same && engines.checkedAt - before.checkedAt < 10 * ENGINE_RECHECK_MS) returnthis.deps.write(config.statusFile, { engines })@@ -138,11 +144,12 @@ export function engineLines(engines: TeamEngines | undefined, ago: (at: number)const e = engines[engine]const state = !e.installed ? '✗ not installed · harness team setup installs it': e.signedIn === true ? '✓ installed · ✓ signed in'- : e.signedIn === false ? '✓ installed · ✗ not signed in' : '✓ installed · ? sign-in unknown'+ : e.relayed ? '✓ installed · ✓ uses your subscription'+ : e.signedIn === false ? '✓ installed · ✗ not signed in' : '✓ installed · ? sign-in unknown'return ` ${index === 0 ? 'engines' : ' '} ${name.padEnd(12)}${state}`})lines.push(` (checked ${ago(engines.checkedAt)})`)- const unsigned = TEAM_ENGINES.filter(({ engine }) => engines[engine].installed && engines[engine].signedIn !== true)+ const unsigned = TEAM_ENGINES.filter(({ engine }) => engines[engine].installed && engines[engine].signedIn !== true && !engines[engine].relayed)if (unsigned.length) {lines.push('', ' To sign the team account\'s engines in, once: in Harness, open a terminal on this Mac\'s Harness Team machine',' (it is listed among your machines), and run there:')diff --git a/cli/src/team/privacy.ts b/cli/src/team/privacy.tsindex 53221aa85..cc32c8035 100644--- a/cli/src/team/privacy.ts+++ b/cli/src/team/privacy.ts@@ -108,7 +108,7 @@ export function enginesOf(value: unknown): TeamEngines | undefined {for (const engine of ['claude', 'codex'] as const) {const e = v[engine] as Record<string, unknown> | undefinedif (!e || typeof e !== 'object' || typeof e.installed !== 'boolean' || (typeof e.signedIn !== 'boolean' && e.signedIn !== null)) return undefined- result[engine] = { installed: e.installed, signedIn: e.signedIn as boolean | null }+ result[engine] = { installed: e.installed, signedIn: e.signedIn as boolean | null, ...(e.relayed === true ? { relayed: true } : {}) }}return result}diff --git a/cli/src/team/relay.spec.ts b/cli/src/team/relay.spec.tsnew file mode 100644index 000000000..1dca87584--- /dev/null+++ b/cli/src/team/relay.spec.ts@@ -0,0 +1,160 @@+import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { SubscriptionRelay } from '../lib/subscriptionRelay.js'+import type { TeamConfig } from './config.js'+import {+ publishTeamRelay, readTeamRelay, TEAM_RELAY_GUEST, teamRelayDir, teamRelayFile, teamRelayLaunch, teamRelayPublished, TeamRelayPublisher,+ type TeamRelayLaunchDeps, type TeamRelayPublisherDeps, type TeamRelayReadDeps,+} from './relay.js'++const config = { user: 'harnessteam', owner: 'owner', ownerHome: '/Users/owner' } as TeamConfig+const TOKEN = 'a'.repeat(43)+const cleanup: string[] = []+afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true }) })++function relay(): SubscriptionRelay {+ return { port: 9, url: 'http://127.0.0.1:9', mintToken: vi.fn(() => TOKEN), revoke: vi.fn(), close: vi.fn(async () => {}) }+}++function publisher(over: Partial<TeamRelayPublisherDeps> = {}) {+ const running = relay()+ let present = false+ const deps: TeamRelayPublisherDeps = {+ config: () => config, user: () => 'owner', team: () => false,+ startRelay: vi.fn(async () => running),+ publish: vi.fn(async () => { present = true }),+ published: () => present,+ withdraw: vi.fn(() => { present = false }),+ log: vi.fn(), intervalMs: 60_000, ...over,+ }+ return { p: new TeamRelayPublisher(deps), deps, running, remove: () => { present = false } }+}++describe('the owner\'s daemon, for the Harness Team account', () => {+ it('starts a relay, mints the team account\'s token and leaves it for the team account, once', async () => {+ const f = publisher()+ await f.p.tick()+ expect(f.running.mintToken).toHaveBeenCalledWith(TEAM_RELAY_GUEST)+ expect(f.deps.publish).toHaveBeenCalledWith(config, { url: 'http://127.0.0.1:9', token: TOKEN })+ await f.p.tick()+ expect(f.deps.publish).toHaveBeenCalledTimes(1)+ // The folder removed by someone: left again, with the same token.+ f.remove()+ await f.p.tick()+ expect(f.deps.publish).toHaveBeenCalledTimes(2)+ expect(f.deps.startRelay).toHaveBeenCalledTimes(1)+ })++ it('publishes nothing in the team account itself, on a Mac without one, or as another account than its owner', async () => {+ for (const over of [{ team: () => true }, { config: () => null }, { user: () => 'someone' }] as Array<Partial<TeamRelayPublisherDeps>>) {+ const f = publisher(over)+ f.p.start()+ await f.p.tick()+ await f.p.stop()+ expect(f.deps.startRelay).not.toHaveBeenCalled()+ }+ })++ it('takes the relay away once the team account is gone, and on stop', async () => {+ let present: TeamConfig | null = config+ const f = publisher({ config: () => present })+ await f.p.tick()+ present = null+ await f.p.tick()+ expect(f.deps.withdraw).toHaveBeenCalledWith('owner')+ expect(f.running.close).toHaveBeenCalledOnce()+ present = config+ f.p.start()+ await f.p.tick()+ await f.p.stop()+ expect(f.deps.withdraw).toHaveBeenCalledTimes(2)+ })++ it('starts a relay that failed again on the next look, and says why', async () => {+ const f = publisher()+ vi.mocked(f.deps.startRelay).mockRejectedValueOnce(new Error('no port'))+ await f.p.tick()+ expect(f.deps.log).toHaveBeenCalledWith('team relay: no port')+ await f.p.tick()+ expect(f.deps.publish).toHaveBeenCalledOnce()+ vi.mocked(f.deps.publish).mockRejectedValueOnce('odd')+ f.remove()+ await f.p.tick()+ expect(f.deps.log).toHaveBeenCalledWith('team relay: odd')+ })++ it('writes the grant readable by this user and, through an ACL, the team account alone', async () => {+ const dir = join(mkdtempSync(join(tmpdir(), 'team-relay-')), 'relay')+ cleanup.push(dir)+ const allowed: string[][] = []+ await publishTeamRelay(config, { url: 'http://127.0.0.1:9', token: TOKEN }, process.getuid!(),+ async (path, user, rights) => { allowed.push([path.endsWith('.next') ? 'file' : path, user, rights]) }, dir)+ expect(JSON.parse(readFileSync(join(dir, 'relay.json'), 'utf8'))).toEqual({ url: 'http://127.0.0.1:9', token: TOKEN })+ expect(statSync(dir).mode & 0o777).toBe(0o700)+ expect(statSync(join(dir, 'relay.json')).mode & 0o777).toBe(0o600)+ expect(allowed).toEqual([[dir, 'harnessteam', 'list,search,readattr'], ['file', 'harnessteam', 'read,readattr']])+ // Again, over its own folder; never into one another user made.+ await publishTeamRelay(config, { url: 'http://127.0.0.1:9', token: TOKEN }, process.getuid!(), async () => {}, dir)+ await expect(publishTeamRelay(config, { url: 'http://127.0.0.1:9', token: TOKEN }, process.getuid!() + 1, async () => {}, dir))+ .rejects.toThrow('is not this account\'s')+ await expect(publishTeamRelay(config, { url: 'u', token: TOKEN }, 0, async () => {}, join(dir, 'missing', 'deeper')))+ .rejects.toThrow()+ })++ it('names one folder per owner under /Users/Shared', () => {+ expect(teamRelayDir('owner')).toBe('/Users/Shared/.harness-team-relay-owner')+ expect(teamRelayFile('owner')).toBe('/Users/Shared/.harness-team-relay-owner/relay.json')+ expect(teamRelayPublished(config, (path) => path === teamRelayFile('owner'))).toBe(true)+ expect(teamRelayPublished(config, () => false)).toBe(false)+ })+})++describe('the team daemon, reading its owner\'s relay', () => {+ const entry = (uid: number, mode: number, dir: boolean) => ({ uid, mode, isDirectory: () => dir, isFile: () => !dir })+ function reader(over: { dir?: ReturnType<typeof entry>; file?: ReturnType<typeof entry>; text?: string } = {}): TeamRelayReadDeps {+ return {+ ownerUid: () => 501,+ lstat: (path) => path.endsWith('relay.json') ? over.file ?? entry(501, 0o100600, false) : over.dir ?? entry(501, 0o40700, true),+ read: () => over.text ?? JSON.stringify({ url: 'http://127.0.0.1:9', token: TOKEN }),+ }+ }++ it('reads it only from the owner the root-owned config names, private to them', () => {+ expect(readTeamRelay(config, reader())).toEqual({ url: 'http://127.0.0.1:9', token: TOKEN })+ for (const over of [+ { dir: entry(502, 0o40700, true) }, { dir: entry(501, 0o40777, true) }, { dir: entry(501, 0o100600, false) },+ { file: entry(502, 0o100600, false) }, { file: entry(501, 0o100644, false) }, { file: entry(501, 0o40700, true) },+ { text: JSON.stringify({ url: 'http://evil.example:9', token: TOKEN }) }, { text: JSON.stringify({ url: 'http://127.0.0.1:9', token: 'short' }) },+ { text: '{' },+ ]) expect(readTeamRelay(config, reader(over)), JSON.stringify(over)).toBeNull()+ })+})++describe('a launch in the team account', () => {+ const grant = { url: 'http://127.0.0.1:9', token: TOKEN }+ const launchDeps = (over: Partial<TeamRelayLaunchDeps> = {}): TeamRelayLaunchDeps => ({+ team: () => true, config: () => config, signedIn: async () => false, read: () => grant, onboarded: vi.fn(), ...over,+ })++ it('spends the owner\'s subscription for an engine it has not signed in itself', async () => {+ const deps = launchDeps()+ expect(await teamRelayLaunch('claude', deps)).toEqual({ env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:9/claude', ANTHROPIC_AUTH_TOKEN: TOKEN }, args: [] })+ expect(deps.onboarded).toHaveBeenCalledWith('claude')+ const codex = await teamRelayLaunch('codex', deps)+ expect(codex?.env).toEqual({ HARNESS_RELAY_TOKEN: TOKEN })+ expect(codex?.args).toContain('model_provider="harness_owner"')+ // A first-run screen that cannot be recorded is left for the engine to ask.+ expect(await teamRelayLaunch('claude', launchDeps({ onboarded: () => { throw new Error('read-only') } }))).not.toBeNull()+ expect(await teamRelayLaunch('codex', launchDeps({ signedIn: async () => { throw new Error('keychain') } }))).not.toBeNull()+ })++ it('adds nothing elsewhere: another engine, the owner\'s own daemon, no team account, its own sign-in, no relay', async () => {+ expect(await teamRelayLaunch('opencode', launchDeps())).toBeNull()+ expect(await teamRelayLaunch('claude', launchDeps({ team: () => false }))).toBeNull()+ expect(await teamRelayLaunch('claude', launchDeps({ config: () => null }))).toBeNull()+ expect(await teamRelayLaunch('claude', launchDeps({ signedIn: async () => true }))).toBeNull()+ expect(await teamRelayLaunch('claude', launchDeps({ read: () => null }))).toBeNull()+ })+})diff --git a/cli/src/team/relay.ts b/cli/src/team/relay.tsnew file mode 100644index 000000000..ffb8fb478--- /dev/null+++ b/cli/src/team/relay.ts@@ -0,0 +1,246 @@+/**+ * The owner's Claude Code and Codex subscriptions for the Harness Team account, without signing it in.+ *+ * Teammates' agents run in the team account (docs/plans/2026-10-24-swarm-team-account.md), which had to sign Claude Code+ * and Codex in on its own before any of them could start: a step the owner had to take in a terminal on that Mac, and+ * the Lead routed nothing there until they did (superTabs/routeCommand.ts `unreadyPool`). Machine sharing already lets a+ * guest's agent spend the owner's subscription through the owner subscription relay (lib/subscriptionRelay.ts), which+ * holds the owner's sign-ins in the owner's own daemon and hands out only revocable loopback tokens. The team account+ * uses the same relay:+ *+ * - The owner's daemon keeps a relay of its own for the team account while one exists on this Mac, and leaves its address+ * and token in a folder it owns under /Users/Shared, readable by the team account alone through a macOS ACL. Not+ * a guest's, not any other local user's: the token spends the owner's subscription.+ * - The team daemon reads it at each launch, only when the folder and the file belong to the owner the root-owned team+ * config names (another local user could otherwise leave a relay of their own there and read teammates' prompts), and+ * only for an engine the team account has not signed in itself: a sign-in of its own wins.+ *+ * ⚠️ The token is never logged, and lives only in the file and in the launched engine's environment.+ */+import { execFile } from 'node:child_process'+import { chmodSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { homedir, userInfo } from 'node:os'+import { join } from 'node:path'+import type { AgentEngine } from '../engines/types.js'+import { recordAcceptanceIn } from '../engines/kit/folderTrust.js'+import { readAuthSession } from '../lib/authSession.js'+import { engineAccount } from '../lib/engineAccount.js'+import { claudeRelayEnv, codexRelayArgs, codexRelayEnv, type SubscriptionRelay } from '../lib/subscriptionRelay.js'+import { readTeamConfig, type TeamConfig } from './config.js'++/** The owner's folder for the hand-off, per owner so two people's Macs never share one. */+export const teamRelayDir = (owner: string) => `/Users/Shared/.harness-team-relay-${owner}`+export const teamRelayFile = (owner: string) => join(teamRelayDir(owner), 'relay.json')+/** The name the relay knows the team account's token by, in its logs (a fingerprint of it) and to revoke it. */+export const TEAM_RELAY_GUEST = 'harness-team'++export interface TeamRelayGrant { url: string; token: string }++/** A relay's address as `startSubscriptionRelay` makes it: loopback, a port, nothing else. */+const RELAY_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}$/+const TOKEN = /^[A-Za-z0-9_-]{20,200}$/++// ── The owner's daemon ────────────────────────────────────────────────────────────────────────++export interface TeamRelayPublisherDeps {+ config(): TeamConfig | null+ /** This daemon's OS user. */+ user(): string+ /** Whether this daemon runs team work only: it never publishes. */+ team(): boolean+ startRelay(): Promise<SubscriptionRelay>+ publish(config: TeamConfig, grant: TeamRelayGrant): Promise<void>+ /** Whether the published file is still there (someone may have removed the folder). */+ published(config: TeamConfig): boolean+ withdraw(owner: string): void+ log(line: string): void+ intervalMs?: number+}++/** How often the owner's daemon looks again: a team account set up later gets its relay within this long. */+export const TEAM_RELAY_CHECK_MS = 60_000++export class TeamRelayPublisher {+ private timer: ReturnType<typeof setInterval> | null = null+ private relay: Promise<SubscriptionRelay> | null = null+ private grant: TeamRelayGrant | null = null+ private owner: string | null = null+ private running: Promise<void> | null = null+ constructor(private readonly deps: TeamRelayPublisherDeps) {}++ start(): void {+ if (this.timer || this.deps.team()) return+ void this.tick()+ this.timer = setInterval(() => void this.tick(), this.deps.intervalMs ?? TEAM_RELAY_CHECK_MS)+ this.timer.unref?.()+ }++ tick(): Promise<void> {+ return this.running ??= this.pass().catch((error: unknown) => {+ this.deps.log(`team relay: ${error instanceof Error ? error.message : String(error)}`)+ }).finally(() => { this.running = null })+ }++ private async pass(): Promise<void> {+ if (this.deps.team()) return+ const config = this.deps.config()+ // Only the Mac's owner's daemon holds the owner's sign-ins: another account's daemon on this Mac publishes nothing.+ if (!config || config.owner !== this.deps.user()) { await this.close(); return }+ if (this.grant && this.owner === config.owner && this.deps.published(config)) return+ this.relay ??= this.deps.startRelay()+ // A relay that could not start is started again on the next pass.+ const relay = await this.relay.catch((error: unknown) => { this.relay = null; throw error })+ this.grant ??= { url: relay.url, token: relay.mintToken(TEAM_RELAY_GUEST) }+ await this.deps.publish(config, this.grant)+ this.owner = config.owner+ this.deps.log('team relay: the Harness Team account uses this Mac\'s subscriptions')+ }++ private async close(): Promise<void> {+ if (this.owner) this.deps.withdraw(this.owner)+ this.owner = null+ this.grant = null+ const relay = await this.relay?.catch(() => null)+ this.relay = null+ await relay?.close()+ }++ async stop(): Promise<void> {+ if (this.timer) clearInterval(this.timer)+ this.timer = null+ await this.running+ await this.close()+ }+}++/** Grants [user] what macOS calls [rights] on [path], and nobody else beyond the owner (the mode says the rest). */+const allow = (path: string, user: string, rights: string) => new Promise<void>((resolve, reject) => {+ // `-N` first: each publish sets the one entry again rather than adding a copy of it.+ execFile('/bin/chmod', ['-N', path], () => {+ execFile('/bin/chmod', ['+a', `user:${user} allow ${rights}`, path], (error) => error ? reject(new Error(`could not let ${user} read ${path}`)) : resolve())+ })+})++/** Writes the grant where only the team account (and this user) can read it. */+export async function publishTeamRelay(config: TeamConfig, grant: TeamRelayGrant, uid: number = process.getuid?.() ?? -1,+ grantRead: (path: string, user: string, rights: string) => Promise<void> = allow, dir: string = teamRelayDir(config.owner)): Promise<void> {+ try { mkdirSync(dir, { mode: 0o700 }) } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }+ // /Users/Shared lets anyone make a folder: one this user did not make is someone else's, and is left alone.+ const folder = lstatSync(dir)+ if (!folder.isDirectory() || folder.uid !== uid) throw new Error(`${dir} is not this account's: the Harness Team account cannot use this Mac's subscriptions`)+ chmodSync(dir, 0o700)+ await grantRead(dir, config.user, 'list,search,readattr')+ const next = join(dir, `.relay.${process.pid}.next`)+ writeFileSync(next, `${JSON.stringify(grant)}\n`, { mode: 0o600 })+ await grantRead(next, config.user, 'read,readattr')+ renameSync(next, join(dir, 'relay.json'))+}++export function withdrawTeamRelay(owner: string): void {+ rmSync(teamRelayFile(owner), { force: true })+}++export const teamRelayPublished = (config: TeamConfig, exists: (path: string) => boolean = (path) => {+ try { lstatSync(path); return true } catch { return false }+}) => exists(teamRelayFile(config.owner))++export function realTeamRelayPublisher(startRelay: () => Promise<SubscriptionRelay>, config: () => TeamConfig | null,+ team: () => boolean, log: (line: string) => void): TeamRelayPublisher {+ return new TeamRelayPublisher({+ // Tests inject a publisher: a test never reads this Mac's own team account, starts a relay on the owner's sign-ins,+ // or writes to /Users/Shared (a service spec did, 2026-10-27). Production never has VITEST set.+ config: () => process.env.VITEST ? null : config(),+ team, startRelay, log,+ user: () => userInfo().username,+ publish: (c, grant) => publishTeamRelay(c, grant),+ published: (c) => teamRelayPublished(c),+ withdraw: withdrawTeamRelay,+ })+}++// ── The team daemon ───────────────────────────────────────────────────────────────────────────++export interface TeamRelayReadDeps {+ lstat(path: string): { uid: number; mode: number; isDirectory(): boolean; isFile(): boolean }+ /** The owner's uid, from their home folder (the team account may look at it, not into it). */+ ownerUid(home: string): number+ /** The file's text, refusing a link. */+ read(path: string): string+}++const realReadDeps: TeamRelayReadDeps = {+ lstat: (path) => lstatSync(path),+ ownerUid: (home) => statSync(home).uid,+ read: (path) => {+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW)+ try {+ const size = Math.min(fstatSync(fd).size, 4096)+ const buffer = Buffer.alloc(size)+ readSync(fd, buffer, 0, size, 0)+ return buffer.toString('utf8')+ } finally { closeSync(fd) }+ },+}++/** The owner's relay for this team account, when the owner's daemon left one; null otherwise. */+export function readTeamRelay(config: TeamConfig, deps: TeamRelayReadDeps = realReadDeps): TeamRelayGrant | null {+ try {+ const owner = deps.ownerUid(config.ownerHome)+ const dir = deps.lstat(teamRelayDir(config.owner))+ if (!dir.isDirectory() || dir.uid !== owner || (dir.mode & 0o022) !== 0) return null+ const file = deps.lstat(teamRelayFile(config.owner))+ if (!file.isFile() || file.uid !== owner || (file.mode & 0o077) !== 0) return null+ const value = JSON.parse(deps.read(teamRelayFile(config.owner))) as Record<string, unknown>+ if (typeof value.url !== 'string' || !RELAY_URL.test(value.url) || typeof value.token !== 'string' || !TOKEN.test(value.token)) return null+ return { url: value.url, token: value.token }+ } catch {+ return null+ }+}++/** What a Claude Code or Codex launch adds to spend the owner's subscription through the relay. */+export interface OwnerRelayLaunch { env: Record<string, string>; args: string[] }++export interface TeamRelayLaunchDeps {+ /** Whether this daemon runs team work only. */+ team(): boolean+ config(): TeamConfig | null+ /** Whether the team account signed this engine in itself. */+ signedIn(engine: 'claude' | 'codex'): Promise<boolean>+ read(config: TeamConfig): TeamRelayGrant | null+ /** Claude Code that never ran in the team account opens on its first-run screens, which nobody is there to answer:+ * recorded as done, in the team account's own home, before the first launch on the relay. */+ onboarded(engine: 'claude' | 'codex'): void+}++/** In the team daemon, for an engine it has not signed in itself: the owner's relay, when there is one. */+export async function teamRelayLaunch(engine: AgentEngine, deps: TeamRelayLaunchDeps): Promise<OwnerRelayLaunch | null> {+ if (engine !== 'claude' && engine !== 'codex') return null+ if (!deps.team()) return null+ const config = deps.config()+ if (!config) return null+ if (await deps.signedIn(engine).catch(() => false)) return null+ const grant = deps.read(config)+ if (!grant) return null+ try { deps.onboarded(engine) } catch { /* The engine asks on its screen, as it would have. */ }+ return engine === 'claude'+ ? { env: claudeRelayEnv(grant.url, grant.token), args: [] }+ : { env: codexRelayEnv(grant.token), args: codexRelayArgs(grant.url) }+}++/** The team daemon's own: its sign-in, the root-owned config, its engines' sign-ins in its own home. */+export const realTeamRelayLaunch = (engine: AgentEngine) => teamRelayLaunch(engine, {+ team: () => readAuthSession()?.kind === 'team',+ config: () => readTeamConfig(),+ // Only presence is read, never a secret (lib/engineAccount.ts); the team daemon has no login shell to read.+ signedIn: async (e) => (await engineAccount(e, { home: homedir(), env: process.env, lastUsed: false })).signedIn === true,+ read: (config) => readTeamRelay(config),+ onboarded: (e) => { if (e === 'claude') recordAcceptanceIn(join(homedir(), '.claude.json'), 'hasCompletedOnboarding') },+})++/** In the team daemon: whether the owner's relay is there for its engines (superTabs/machines.ts readiness). */+export const teamRelayed = (): boolean => {+ if (readAuthSession()?.kind !== 'team') return false+ const config = readTeamConfig()+ return !!config && !!readTeamRelay(config)+}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 4148c4496..597c12e84 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -77,6 +77,7 @@ import '../state/harness_launch_integration.dart';import '../super_tabs/launch.dart';import '../super_tabs/pm_chat.dart' show countText;import '../super_tabs/pm_chat_shortcut.dart';+import '../super_tabs/team_account_setup.dart';import '../super_tabs/workspace.dart';import '../super_tabs/actions.dart';import 'swarm_menu_bus.dart';@@ -294,6 +295,7 @@ class _SwarmScreenState extends State<SwarmScreen> {bool _deviceRevealInFlight = false;StreamSubscription<void>? _modelsRequests;StreamSubscription<String>? _superTabClosures;+ StreamSubscription<String>? _teamSetupAsks;// The one Swarm notice: whether it exists (queued or shown), whether it// is on screen, and the closed tab its Reopen restores.int _superTabNoticeSerial = 0;@@ -837,6 +839,10 @@ class _SwarmScreenState extends State<SwarmScreen> {}});_superTabClosures = app.superTabClosures.listen(_offerSuperTabReopen);+ // The Harness Team account, explained before macOS asks for the password (super_tabs/team_account_setup.dart).+ _teamSetupAsks = app.teamSetupAsks.listen((_) {+ if (mounted) unawaited(showTeamAccountSetup(context, app, asked: true));+ });if (!kUnderTest) {WidgetsBinding.instance.addPostFrameCallback((_) {if (!mounted) return;@@ -991,6 +997,7 @@ class _SwarmScreenState extends State<SwarmScreen> {app.modelManager.setPanelVisible(false);_modelsRequests?.cancel();_superTabClosures?.cancel();+ _teamSetupAsks?.cancel();_keymap.removeListener(_keymapChanged);_defaultKeymap.dispose();grid.AppTheme.palette.removeListener(_paletteChanged);diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex b2b37cb35..e5551aa3b 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1911,30 +1911,82 @@ class AppNotifier extends ChangeNotifier {/// The Harness Team account on this Mac (cli/src/team/autoSetup.ts),/// offered while the person is here: as they join a Swarm ([reason]/// `join`), add this Mac to one (`contribute`), or open the app- /// (`startup`). This Mac's own daemon decides whether to ask: no account- /// yet, not declined before, and at start only while this Mac is in a- /// Swarm with other people in it. macOS's administrator prompt is all the- /// person sees. Nothing on Windows or Linux, and never for another machine,- /// where nobody may be at it.+ /// (`startup`). This Mac's own daemon decides whether it is wanted: no+ /// account yet, not declined before, and at start only while this Mac is in+ /// a Swarm with other people in it. It is then explained before macOS asks+ /// ([teamSetupAsks]): macOS's prompt is titled "osascript", which nobody+ /// recognised as Harness (2026-10-27). Nothing on Windows or Linux, and never+ /// for another machine, where nobody may be at it.Future<void> offerTeamAccount(String reason) async {- if (!(macOSForTest ?? (Platform.isMacOS && !kUnderTest))) return;- final here = machineStates.values- .where(- (state) => state.isLocalMachine && !state.machine.isSharedMachine,- )- .firstOrNull;+ final here = _teamAccountHere();if (here == null) return;try {- await superTabMachineRequest(here.machine.machineId, {- 'action': 'teamSetup',+ final answer = await superTabMachineRequest(here, {+ 'action': 'teamSetupCheck','reason': reason,});+ if (answer['state'] == 'wanted') _teamSetupAsks.add(reason);} catch (error) {// An older daemon, or one that cannot say: nothing is asked.appLog.debug('super-tabs', 'team account not offered: $error');}}+ /// This Mac's own machine, when the Harness Team account can be made here.+ String? _teamAccountHere() {+ if (!(macOSForTest ?? (Platform.isMacOS && !kUnderTest))) return null;+ return machineStates.values+ .where(+ (state) => state.isLocalMachine && !state.machine.isSharedMachine,+ )+ .firstOrNull+ ?.machine+ .machineId;+ }++ /// Whether this Mac can make its Harness Team account: the machine row's+ /// Set up button shows only then.+ bool get canSetUpTeamAccount => _teamAccountHere() != null;++ final StreamController<String> _teamSetupAsks =+ StreamController<String>.broadcast();++ /// Each moment the Harness Team account is wanted on this Mac, by its+ /// reason: the screen explains it, then [setUpTeamAccount] or+ /// [declineTeamAccount].+ Stream<String> get teamSetupAsks => _teamSetupAsks.stream;++ /// Starts the Harness Team account's setup on this Mac, the person having+ /// asked: macOS's administrator prompt follows. Answers the daemon's state+ /// (`started`, `exists`, `running`, ...), or `update` from a daemon too old+ /// to set it up from here.+ Future<String> setUpTeamAccount() async {+ final here = _teamAccountHere();+ if (here == null) return 'unsupported';+ try {+ final answer = await superTabMachineRequest(here, {+ 'action': 'teamSetup',+ 'reason': 'manual',+ });+ return answer['state']?.toString() ?? 'started';+ } on SuperTabFailure catch (failure) {+ if (failure.code == 'INVALID_REQUEST') return 'update';+ rethrow;+ }+ }++ /// "Not now": not offered again on its own. The machine row keeps its Set+ /// up button.+ Future<void> declineTeamAccount() async {+ final here = _teamAccountHere();+ if (here == null) return;+ try {+ await superTabMachineRequest(here, {'action': 'teamSetupDecline'});+ } catch (error) {+ appLog.debug('super-tabs', 'team account decline not saved: $error');+ }+ }+Future<void> wakeSuperTabHost(String machineId) async {await superTabMachineRequest(machineId, {'action': 'wake'});// Share derives only the session views authorized by the tab. Its existing@@ -21490,6 +21542,7 @@ class AppNotifier extends ChangeNotifier {unawaited(_daemonFrames.close());unawaited(_modelsRequests.close());unawaited(_superTabClosures.close());+ unawaited(_teamSetupAsks.close());super.dispose();}}diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 86654bd72..ef5958e33 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -31,6 +31,7 @@ import '../models/swarm_models_target.dart' show swarmSharedWithYouShown;import 'machine_details.dart';import 'machine_status.dart';import 'model.dart';+import 'team_account_setup.dart';import 'section_heading.dart';export 'machine_status.dart';@@ -1139,12 +1140,21 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {}}}+ final problem = _teammatesLine(shared, team, contributor);return _MachineView(apiModels: apiModels,localModels: localModels,id: id,name: name,- problem: _teammatesLine(shared, team, contributor),+ problem: problem,+ setUpTeam:+ problem != null &&+ team == null &&+ (shared?['teamWork'] as Map?)?['code'] == 'TEAM_ACCOUNT_REQUIRED' &&+ contributor == c.accountId &&+ app != null &&+ app.canSetUpTeamAccount &&+ app.stateOf(id)?.isLocalMachine == true,owner: person,contributor: contributor,shared: shared,@@ -1577,6 +1587,9 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {c.toggleMachineExpanded(view.id);_changed();},+ onSetUpTeam: view.setUpTeam+ ? () => showTeamAccountSetup(context, widget.app!)+ : null,),),);@@ -1941,12 +1954,16 @@ class _MachineView {required this.allowances,required this.tip,this.problem,+ this.setUpTeam = false,this.apiModels = const [],this.localModels = const [],});final String id, name, details, tip;+ /// Its [problem] is this Mac's, its own person looking: no Harness Team account yet, which they can set up here.+ final bool setUpTeam;+/// Its one line when teammates' agents cannot run there ([superTabTeammatesPaused]); null otherwise.final String? problem;final SuperTabPerson? owner;@@ -2054,12 +2071,16 @@ class _MachineLine extends StatelessWidget {required this.view,required this.expanded,required this.onToggle,+ this.onSetUpTeam,});final _MachineView view;final bool expanded;final VoidCallback onToggle;+ /// This Mac's row, without its Harness Team account: Set up under the paused line.+ final VoidCallback? onSetUpTeam;+@overrideWidget build(BuildContext context) {final muted =@@ -2134,6 +2155,18 @@ class _MachineLine extends StatelessWidget {overflow: TextOverflow.ellipsis,style: DesktopChrome.metadata(),),+ if (onSetUpTeam != null)+ TextButton(+ key: ValueKey('super-machine-team-setup-${view.id}'),+ onPressed: onSetUpTeam,+ style: TextButton.styleFrom(+ padding: EdgeInsets.zero,+ minimumSize: const Size(0, 22),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ alignment: Alignment.centerLeft,+ ),+ child: const Text('Set up'),+ ),],);},diff --git a/desktop/lib/super_tabs/team_account_setup.dart b/desktop/lib/super_tabs/team_account_setup.dartnew file mode 100644index 000000000..42ebb43c5--- /dev/null+++ b/desktop/lib/super_tabs/team_account_setup.dart@@ -0,0 +1,134 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import 'controller.dart';++/// The Harness Team account explained before macOS asks for the password (cli/src/team/autoSetup.ts). macOS's own+/// prompt is titled "osascript" with a script icon, and on 2026-10-27 people met it with no idea it was Harness's.+///+/// [asked]: Harness offered it (a join, this Mac added to a Swarm, or the app opening); "Not now" is then remembered so+/// it is not offered again on its own. Otherwise the person pressed Set up on this Mac's row, and Cancel forgets nothing.+Future<void> showTeamAccountSetup(+ BuildContext context,+ AppNotifier app, {+ bool asked = false,+}) => showAppDialog<void>(+ context: context,+ barrierDismissible: false,+ builder: (context) => _TeamAccountSetup(app: app, asked: asked),+);++class _TeamAccountSetup extends StatefulWidget {+ const _TeamAccountSetup({required this.app, required this.asked});++ final AppNotifier app;+ final bool asked;++ @override+ State<_TeamAccountSetup> createState() => _TeamAccountSetupState();+}++class _TeamAccountSetupState extends State<_TeamAccountSetup> {+ bool _busy = false;++ /// What happened once the person pressed Continue; null before.+ String? _outcome;++ Future<void> _continue() async {+ setState(() => _busy = true);+ String outcome;+ try {+ outcome = switch (await widget.app.setUpTeamAccount()) {+ 'started' || 'running' =>+ 'macOS is asking for your password in a window titled “osascript”. '+ 'Setup then takes a minute or two. This Mac\'s row updates when it is ready.',+ 'exists' => 'Harness Team is already set up on this Mac.',+ 'update' =>+ 'This Mac\'s Harness is too old to set it up from here. Update Harness, '+ 'or run harness team setup in Terminal.',+ _ => 'Harness Team cannot be set up on this Mac right now.',+ };+ } on SuperTabFailure catch (failure) {+ outcome = failure.message;+ } catch (_) {+ outcome = 'Could not reach Harness on this Mac. Try again.';+ }+ if (mounted) {+ setState(() {+ _busy = false;+ _outcome = outcome;+ });+ }+ }++ Future<void> _notNow() async {+ if (widget.asked) await widget.app.declineTeamAccount();+ if (mounted) Navigator.pop(context);+ }++ @override+ Widget build(BuildContext context) {+ final body = grid.AppType.body(height: 1.45);+ final muted = body.copyWith(color: Theme.of(context).hintColor);+ final outcome = _outcome;+ return AlertDialog(+ key: const Key('team-account-setup'),+ title: const Text('Set up Harness Team on this Mac'),+ content: SizedBox(+ width: 420,+ child: outcome != null+ ? Text(+ outcome,+ key: const Key('team-account-setup-outcome'),+ style: body,+ )+ : Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'Teammates\' agents in your Swarms run on this Mac in a separate macOS '+ 'account, Harness Team. They cannot read your files or use your GitHub login. '+ 'They use this Mac\'s Claude Code and Codex subscriptions, so nobody signs in again.',+ style: body,+ ),+ const SizedBox(height: 12),+ Text(+ 'macOS asks for your password once, in a window titled “osascript”. '+ 'That is the macOS tool Harness uses to ask.',+ style: body,+ ),+ const SizedBox(height: 12),+ Text(+ 'Your home folder becomes private to you. Your own agents work as before. '+ 'To remove the account later, run harness team remove.',+ style: muted,+ ),+ ],+ ),+ ),+ actions: outcome != null+ ? [+ FilledButton(+ key: const Key('team-account-setup-done'),+ onPressed: () => Navigator.pop(context),+ child: const Text('OK'),+ ),+ ]+ : [+ TextButton(+ key: const Key('team-account-setup-later'),+ onPressed: _busy ? null : _notNow,+ child: Text(widget.asked ? 'Not now' : 'Cancel'),+ ),+ FilledButton(+ key: const Key('team-account-setup-continue'),+ onPressed: _busy ? null : _continue,+ child: const Text('Continue'),+ ),+ ],+ );+ }+}diff --git a/desktop/test/super_tab_team_machine_test.dart b/desktop/test/super_tab_team_machine_test.dartindex 6c5d664a9..8ba40251e 100644--- a/desktop/test/super_tab_team_machine_test.dart+++ b/desktop/test/super_tab_team_machine_test.dart@@ -8,6 +8,7 @@ import 'package:harness/super_tabs/agent_details.dart';import 'package:harness/super_tabs/machines.dart';import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show createApp;const _offlineAge = 10 * 60 * 1000;@@ -230,6 +231,57 @@ void main() {await _unmount(tester, c);});+ testWidgets(+ 'on this Mac\'s own row, its person can set the Harness Team account up there; nobody else, nowhere else',+ (tester) async {+ final app = createApp(connected: true)..macOSForTest = true;+ app.machineStates['m']!.localOnly = true;+ Future<bool> button({+ String account = 'owner',+ String id = 'm',+ String code = 'TEAM_ACCOUNT_REQUIRED',+ }) async {+ final server = _swarm();+ server.state['machines'] = [+ _pool(+ id,+ contributor: account == 'peer' ? 'owner' : 'owner',+ teamWork: _refused(code),+ ),+ ];+ final c = server.controller(account: account);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabMachines(+ controller: c,+ app: app,+ onAddAgent: (_) {},+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final shown = find+ .byKey(ValueKey('super-machine-team-setup-$id'))+ .evaluate()+ .isNotEmpty;+ await _unmount(tester, c);+ return shown;+ }++ expect(await button(), isTrue);+ // A teammate reads the Mac's line, never its button; another Mac's row has none; nor a privacy refusal.+ expect(await button(account: 'peer'), isFalse);+ expect(await button(id: 'other'), isFalse);+ expect(await button(code: 'PRIVACY_CHECK_FAILED'), isFalse);+ app.macOSForTest = false;+ expect(await button(), isFalse);+ app.dispose();+ },+ );+testWidgets('the line stays away when it would say nothing new', (tester,) async {diff --git a/desktop/test/team_account_offer_test.dart b/desktop/test/team_account_offer_test.dartindex 1e6aacc89..f7d9ea79f 100644--- a/desktop/test/team_account_offer_test.dart+++ b/desktop/test/team_account_offer_test.dart@@ -1,5 +1,7 @@+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/team_account_setup.dart';import 'support/rename_connection.dart';import 'swarm_state_test.dart' show createApp;@@ -7,7 +9,7 @@ import 'swarm_state_test.dart' show createApp;/// Records what this Mac's daemon is asked; no socket is opened.class _Daemon extends RenameConnection {final asked = <Map<String, dynamic>>[];- Map<String, dynamic> answer = {'ok': true, 'state': 'started'};+ Map<String, dynamic> answer = {'ok': true, 'state': 'wanted'};@overrideFuture<Map<String, dynamic>> request(@@ -15,7 +17,8 @@ class _Daemon extends RenameConnection {Map<String, dynamic> payload = const {},Duration timeout = const Duration(seconds: 20),}) {- if (type == 'super_tabs' && payload['action'] == 'teamSetup') {+ if (type == 'super_tabs' &&+ '${payload['action']}'.startsWith('teamSetup')) {asked.add(Map.of(payload));return Future.value(answer);}@@ -35,17 +38,39 @@ void main() {});tearDown(() => app.dispose());- test(- 'asks this Mac\'s own daemon, with the moment the person is here',- () async {- await app.offerTeamAccount('join');- await app.offerTeamAccount('contribute');- expect(daemon.asked, [- {'action': 'teamSetup', 'reason': 'join'},- {'action': 'teamSetup', 'reason': 'contribute'},- ]);- },- );+ test('asks this Mac\'s own daemon whether it is wanted, and explains it only then', () async {+ final explained = <String>[];+ final listening = app.teamSetupAsks.listen(explained.add);+ await app.offerTeamAccount('join');+ daemon.answer = {'ok': true, 'state': 'declined'};+ await app.offerTeamAccount('contribute');+ await pumpEventQueue();+ expect(daemon.asked, [+ {'action': 'teamSetupCheck', 'reason': 'join'},+ {'action': 'teamSetupCheck', 'reason': 'contribute'},+ ]);+ expect(explained, ['join']);+ await listening.cancel();+ });++ test('sets it up when the person asks, and remembers "Not now"', () async {+ daemon.answer = {'ok': true, 'state': 'started'};+ expect(await app.setUpTeamAccount(), 'started');+ await app.declineTeamAccount();+ expect(daemon.asked, [+ {'action': 'teamSetup', 'reason': 'manual'},+ {'action': 'teamSetupDecline'},+ ]);+ expect(app.canSetUpTeamAccount, isTrue);+ app.macOSForTest = false;+ expect(app.canSetUpTeamAccount, isFalse);+ expect(await app.setUpTeamAccount(), 'unsupported');+ });++ test('a daemon too old to set it up from here says so', () async {+ daemon.answer = {'error': 'INVALID_REQUEST'};+ expect(await app.setUpTeamAccount(), 'update');+ });test('asks nothing off a Mac, or when the only machine here is another one',@@ -70,7 +95,59 @@ void main() {app.onMachineConnectedForTest('m');await pumpEventQueue();expect(daemon.asked, [- {'action': 'teamSetup', 'reason': 'startup'},+ {'action': 'teamSetupCheck', 'reason': 'startup'},+ ]);+ });++ Future<void> open(WidgetTester tester, {bool asked = false}) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => TextButton(+ onPressed: () => showTeamAccountSetup(context, app, asked: asked),+ child: const Text('open'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('open'));+ await tester.pumpAndSettle();+ }++ testWidgets(+ 'explains the account and the "osascript" prompt before macOS asks',+ (tester) async {+ daemon.answer = {'ok': true, 'state': 'started'};+ await open(tester);+ expect(find.textContaining('separate macOS account'), findsOneWidget);+ expect(find.textContaining('titled “osascript”'), findsOneWidget);+ expect(daemon.asked, isEmpty);+ await tester.tap(find.byKey(const Key('team-account-setup-continue')));+ await tester.pumpAndSettle();+ expect(daemon.asked, [+ {'action': 'teamSetup', 'reason': 'manual'},+ ]);+ expect(+ find.byKey(const Key('team-account-setup-outcome')),+ findsOneWidget,+ );+ await tester.tap(find.byKey(const Key('team-account-setup-done')));+ await tester.pumpAndSettle();+ expect(find.byKey(const Key('team-account-setup')), findsNothing);+ },+ );++ testWidgets('"Not now" on an offer is remembered; Cancel on Set up is not', (+ tester,+ ) async {+ await open(tester, asked: true);+ await tester.tap(find.text('Not now'));+ await tester.pumpAndSettle();+ await open(tester);+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ expect(daemon.asked, [+ {'action': 'teamSetupDecline'},]);});}diff --git a/docs/plans/2026-10-24-swarm-team-account.md b/docs/plans/2026-10-24-swarm-team-account.mdindex 6b6fbbe53..076bcd228 100644--- a/docs/plans/2026-10-24-swarm-team-account.md+++ b/docs/plans/2026-10-24-swarm-team-account.md@@ -84,6 +84,9 @@ How it works (`backend/src/superTabs/machines.ts`, `teamWorkCheck`):- **Routing.** The tab read gives each machine `teamWork`: `{ allowed: true }`, or `{ allowed: false, code, reason }`. The CLI's route leaves those machines out for a teammate's project and lists the reason in `excluded[]`. The backend does the same with any candidate an older CLI still sends, and refuses a pick there ("… Route again.").- **Migration.** Nothing is stopped. Agents already running on personal machines keep their current task, its reports, messages and their sessions. New starts, new assignments and new Reviewer groups for another person's project follow the rule. A personal machine contributed with scope "swarm" now serves only its owner's projects. So does a machine contributed before projects (no scope) by someone other than the Swarm's owner: the Swarm's first project is the owner's.- **Switch.** The backend shipped (1.3.28) before the CLI that makes team accounts. So the rule is held to every machine only with `SWARM_TEAM_ACCOUNT_REQUIRED=1` (`machines.ts` `teamAccountRequired`). Until then, a machine without a team account takes a teammate's work as it did before, and a machine with one already follows the rule. Turn it on with the CLI and Desktop release that makes team accounts.+- **One person's Swarms first.** `SWARM_TEAM_ACCOUNT_OWNERS`, comma-separated emails, holds the switch to the Swarms+ those people own (2026-10-27), so it can be tried on production without changing anyone else's: every other Swarm+ behaves as with the switch off. Empty, the switch is every Swarm's.- **GitHub App first.** A team account has no git login, so it can fetch and push only with the Harness GitHub App. Until the server has the app (`docs/swarm-github-app.md`), a team account joins no Swarm and takes no teammates' work, and starts on its Mac stay with the Mac (`teamAccountsIdle`). Configure the app before turning `SWARM_TEAM_ACCOUNT_REQUIRED` on, or teammates' work has nowhere to run.## Task 4: Harness GitHub App (backend, CLI)@@ -103,6 +106,40 @@ Files: `backend/src/superTabs/commands.ts` (`message.send`), a small detector mo- [ ] Tests for JWTs, GitHub tokens, OpenAI and Anthropic keys, AWS keys, Slack tokens and private key blocks; ordinary hashes and commit ids pass.- [ ] Redact before storing, keep the rest of the message, and tell the sender what was removed and that the credential should be revoked.+## Task 6: The owner's subscriptions, and setting it up from the app (CLI, Desktop)++Added 2026-10-27, after the Swarm had the GitHub App and the switch on and four of five Macs read "Teammates' agents+paused: not set up": nobody had been asked, or had cancelled a prompt titled "osascript", and nothing in the app could+ask again. The team account's engines also needed signing in by hand, and the Lead routed nothing there until they were.++- **Set up from the row.** This Mac's own row, for its own person, shows Set up under "not set up". Desktop explains the+ account before macOS asks (the prompt's "osascript" title included); the daemon's `teamSetupCheck` says whether it is+ wanted, `teamSetup` with reason `manual` runs it (past a remembered cancel or failure), `teamSetupDecline` is "Not now".+ An older daemon refuses the new action names, so it never asks unexplained.+- **The owner's subscriptions.** The owner's daemon runs an owner subscription relay (lib/subscriptionRelay.ts, machine+ sharing's) for the team account while one exists, and leaves its loopback address and a token in+ `/Users/Shared/.harness-team-relay-<owner>/relay.json`: the owner's folder, mode 700, with a macOS ACL letting the team+ user alone read it. The team daemon uses it for an engine it has not signed in itself, on every launch and relaunch+ (Codex is named the relay's provider in place of its own login's), and reports that engine ready to the Swarm.++### Design++- **Growth:** one file per Mac, rewritten in place; removed when the team account is gone or the owner's daemon stops.+- **Concurrency:** one writer, the owner's daemon, writing a temporary file and renaming it; readers read it whole.+- **Read cost:** one small file read per team-account launch, and per readiness probe (every ten minutes).+- **Scale:** per Mac, not per Swarm; 10x Swarms changes nothing. The relay's requests are the owner's subscription's.+- **Compatibility:** a team daemon without this reads no file and launches as before (its own sign-in, or none). Desktop+ with an older daemon gets no answer to `teamSetupCheck` and shows nothing; Set up says to update.+- **Migration and rollback:** nothing stored to migrate; rolling back leaves one unused file in /Users/Shared, removed by hand or by a later start.+- **Audience:** the file is the owner's, readable by the team user through an ACL and by nobody else; the team daemon+ reads it only when the folder and file belong to the owner the root-owned team config names, so another local user+ cannot plant a relay of their own. The token reaches the relay on loopback only, and spends the owner's subscription.+- **Identity:** the owner's sign-ins never leave the owner's daemon; the team account holds only a revocable token.+ Teammates' agents spend the owner's subscription, as a guest's do on a shared machine: the owner chose to add the Mac.+- **Failure:** a relay that cannot start is retried each minute and logged; without it the team account's engines read+ "not signed in" as before, and the Lead routes elsewhere.+- **Platforms:** macOS only, like the team account.+## One machineOwner, 24 Oct 2026: "The isolated team account is just an under-the-scenes mechanism." A Mac with a Harness Team account is one machine in the Swarm's views, for the owner and for teammates: the machines view, Add machine, and wherever an agent's computer is named. Swarm is a hidden feature, so this lives in Super Tab code only (`desktop/lib/super_tabs/`, `cli/src/superTabs/`, `cli/src/team/`, and the backend's Swarm state and team sign-in). App-wide lists are unchanged: Desktop's rail, Machines, pickers, menus and web onboarding, `harness machines` and hn list the team account as its own machine, as before.