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 status | remove | on | off` (docs/plans/2026-10-24-swarm-team-account.md, Task 2).
*
* On a Mac or a Linux computer, Swarm work from teammates runs in the Harness Team account: a separate standard user with
* its own Harness daemon, which cannot read the owner's files (Linux: docs/superpowers/plans/2026-10-28-harness-team-account-linux.md).
* A computer used only for agents (a Mac mini, a Linux or Windows box) needs no second user: `harness team on` signs that
* computer in for team work only.
*
* Internal verbs, run by the scripts and the team daemon's job, not by people:
* __handoff (as the owner, from setup's script) print a fresh team sign-in code
* __start <file> (as the team account, before its daemon) redeem a handed-over code, run the privacy check
*
* Nothing here falls back to the owner: a team account that is missing, signed out or not private is reported, and
* team work does not run as the owner instead.
*/
import type { AgentTmpState } from '../lib/agentTmp.js'
import { sameSignIn, type AuthSession } from '../lib/authSession.js'
import { SIGN_OUT_BUTTON_FLAG, type SignOutAsked } from '../lib/signOut.js'
import { psQuote, type RunAdmin } from './admin.js'
import type { TeamConfig } from './config.js'
import type { TeamEngines } from './engines.js'
import { handedTeamSignInEpoch, mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Delete, type Get, type Post } from './handoff.js'
import {
SENTINEL_NAME, TEAM_PORT, TEAM_REAL_NAME, TEAM_STATUS_FILE,
TEAM_USER, TeamInputError, pathCheck, teamLayout, teamPaths, userCheck, type TeamLayout, type TeamPlatform,
} from './layout.js'
import type { PrivacyResult, TeamStatus } from './privacy.js'
import { REMOVE_REFUSED, buildLinuxRemoveScript, buildRemoveScript, type EngineCopy, type RemoveScriptInput } from './script.js'
import { windowsTeamPaths } from './windowsLayout.js'
import { buildWindowsRemoveScript } from './windowsScript.js'
/** How a platform with a Harness Team account makes and removes it (Windows:
* docs/superpowers/plans/2026-10-28-harness-team-account-windows.md). */
interface TeamScripts {
remove(input: RemoveScriptInput): string
}
const SCRIPTS: Record<TeamPlatform, TeamScripts> = {
darwin: { remove: buildRemoveScript },
linux: { remove: buildLinuxRemoveScript },
win32: { remove: buildWindowsRemoveScript },
}
interface TeamHere { layout: TeamLayout; scripts: TeamScripts; mac: boolean; windows: boolean; where: string; system: string }
/** This computer's layout and scripts, or null where no Harness Team account was ever made. */
function teamHere(platform: NodeJS.Platform): TeamHere | null {
const layout = teamLayout(platform)
if (!layout) return null
const mac = layout.platform === 'darwin'
const windows = layout.platform === 'win32'
return { layout, scripts: SCRIPTS[layout.platform], mac, windows, where: mac ? 'this Mac' : 'this computer',
system: mac ? 'macOS' : windows ? 'Windows' : 'Linux' }
}
export const TEAM_USAGE = [
'Usage: harness team <status | logs | remove | on | off> [--json]',
'',
' A Harness Team account was a separate user made for Swarm work before Swarm v3, which has none: `setup` makes no new',
' one. Its daemon stops once no agent runs in it.',
' status whether the account and its daemon are still there, its privacy check, and everything setup made',
' logs the team daemon\'s last 40 lines (--lines N): what its agents are doing',
' remove delete the account, its home folder and its daemon; your home stays private. Run it in Terminal: sudo',
' asks for your password, and macOS asks once to let Terminal administer your computer, which it needs',
' on for a computer used only for agents (a Mac mini, a Linux or Windows box): sign it in for team work',
' only. It then runs Swarm agents and reaches none of your other computers (--yes skips the question)',
' off sign this computer out of team work, then sign it in as your own computer again',
].join('\n')
/** What the administrator prompt says (sudo's prompt on Linux; pkexec shows polkit's own words). */
const prompts = (where: string) => ({
remove: `Harness wants to remove the Harness Team account, its home folder and its daemon from ${where}.`,
})
export const REMOVE_PROMPT = prompts('this Mac').remove
export interface Installed {
/** The owner's installed CLI folder and its cli.js. */
cliDir: string
cliJs: string
/** The managed Node the installed CLI runs on, and its runtime folder (null without a managed runtime). */
node: string
nodeRuntimeDir: string | null
tmuxRuntimeDir: string | null
/** Windows: the owner's terminal host payload in use (`runtime\pty\<version>`), copied for the team account, which has no
* installer of its own to lay one down; null without one. */
ptyDir?: string | null
/** A Mac: the owner's own installed Claude Code and Codex (./engines.ts `ownerEngineCopies`), copied for the team account
* instead of downloaded again (#3169). */
engineCopies?: EngineCopy[]
}
export interface JobState { loaded: boolean; pid: number | null; state: string | null }
export interface TeamCommandDeps {
platform: NodeJS.Platform
out(line: string): void
err(line: string): void
/** This process's account, home and uid. */
user(): string
home(): string
uid(): number
hostname(): string
env: NodeJS.ProcessEnv
interactive: boolean
ask(question: string): Promise<string>
/** Like [ask], but what is typed is not echoed: for an API key. */
askSecret?(question: string): Promise<string>
now(): number
sleep(ms: number): Promise<void>
session(): AuthSession | null
writeSession(session: AuthSession): void
/** Rewrites the newest sign-in under the refresh lock, leaving a signed-out mark alone (lib/authSession.ts
* `updateAuthSession`): [change] gives the new one, or null to leave it. */
updateSession(change: (latest: AuthSession) => AuthSession | null): Promise<AuthSession | null>
/** How a person asked for this computer's sign-in to go, or null when nothing says one did (lib/signOut.ts). */
signOutAsked(flags: readonly string[]): SignOutAsked | null
/** Takes the sign-in away, logged with who asked (lib/signOut.ts `removeSignIn`). */
removeSignIn(asked: SignOutAsked): void
/** Bearer headers for this computer's sign-in, refreshed when stale (lib/controlPlane.ts). */
auth(): Promise<{ session: AuthSession; headers: Record<string, string> }>
post: Post
get: Get
delete: Delete
/** This computer's machine key on the account's device key log (lib/e2ee/store.ts), never made here; null when it has
* none. `team on` signs with it to show the backend it is this computer. */
machineKey(): { priv: Uint8Array } | null
computerId(): string
autonomousEnv: 'prod' | 'stag'
installed(): Installed
exists(path: string): boolean
/** A path's permission bits, or null when it cannot be read. */
mode(path: string): number | null
admin: RunAdmin
/** Setup's step as it goes, for Desktop's waiting screen (./autoSetup.ts): `password` while the prompt is open, then
* each step the script says (./script.ts `step`), then `report` while the team daemon signs in and checks. */
progress?(step: string): void
readConfig(): TeamConfig | null
readStatus(path: string): TeamStatus | null
writeStatus(path: string, update: Partial<Omit<TeamStatus, 'version'>>): void
accountExists(user: string): Promise<boolean>
jobState(label: string): Promise<JobState>
/** The owner's agents' private temporary folder (lib/agentTmp.ts); absent on Windows, which has its own per account. */
agentTmp?(): AgentTmpState
/** The team account's side: its handed-over code, the privacy check, and its own Claude Code and Codex (./engines.ts). */
takeHandoff(path: string): string | null
privacy(config: TeamConfig): PrivacyResult
engines(config: TeamConfig): Promise<TeamEngines>
/** This computer's daemon: stopped (true when one was running), started again (prints its status and may exit),
* and the ordinary sign-in, for `team off` (which starts the daemon again when [restart]). */
stopDaemon(): Promise<boolean>
startDaemon(): Promise<void>
signIn?(restart: boolean): Promise<void>
/** Windows, as the owner and before User Account Control: this account's SID (`whoami /user`), or null. */
ownerSid?(): Promise<string | null>
/** Windows, as the owner after the elevated script: the sign-in code, into the handover folder setup made. */
handOver?(code: string): void
/** Windows: asks Task Scheduler to start the team daemon's task; false when it would not. */
startTeamTask?(): Promise<boolean>
}
export async function teamCommand(argv: string[], deps: TeamCommandDeps): Promise<number> {
const words = argv.filter((arg) => !arg.startsWith('-'))
const flags = argv.filter((arg) => arg.startsWith('-'))
const json = flags.includes('--json')
const verb = words[0]
if (verb === undefined || verb === 'help' || flags.includes('-h') || flags.includes('--help')) {
deps.out(TEAM_USAGE)
return 0
}
try {
switch (verb) {
case 'setup': case 'model': case 'sign-in': return removed(deps, json)
case 'status': return await status(deps, json)
case 'logs': return await teamLogs(deps, words, flags, json)
case 'remove': return await remove(deps, json)
case 'on': return await teamOn(deps, json, flags.includes('--yes'))
case 'off': return await teamOff(deps, json, flags)
case '__handoff': return await handoff(deps)
case '__start': return await jobStart(deps, words[1])
default:
deps.err(`Unknown command: harness team ${verb}\n\n${TEAM_USAGE}`)
return 2
}
} catch (error) {
if (!(error instanceof TeamInputError) && !(error instanceof TeamSignInError)) throw error
return fail(deps, json, error instanceof TeamSignInError ? error.code : 'INVALID_INPUT', error.message)
}
}
function fail(deps: TeamCommandDeps, json: boolean, code: string, message: string, extra: Record<string, unknown> = {}): number {
if (json) deps.out(JSON.stringify({ ok: false, code, message, ...extra }))
else deps.err(`✗ ${message}`)
return 1
}
/** The folder above the status folder on Linux (/var/lib/harness), which setup also made and marked. */
const parentOf = (path: string): string => path.slice(0, path.lastIndexOf('/'))
/** What setup makes, said plainly so anyone can audit it or take it off the computer by hand. */
function madeLines({ layout, mac, windows }: TeamHere, owner: string, ownerHome: string): string[] {
const { label, file } = layout.service
if (windows) {
const team = windowsTeamPaths(layout.home)
return [
` account ${TEAM_REAL_NAME} (${TEAM_USER}): a standard user (Users only) with a random password nobody knows, listed on the sign-in screen`,
` home ${layout.home}`,
` daemon ${label}, a scheduled task at startup, running as ${TEAM_USER} on port ${TEAM_PORT}`,
` log ${team.log} (inside the account's profile)`,
` setup ${layout.configFile} and ${layout.statusDir}\\`,
` check ${ownerHome}\\${SENTINEL_NAME}, a file the account must not be able to read`,
` engines Claude Code and Codex in ${team.npmPrefix}, installed by the account itself`,
` your home ${ownerHome}: any access Everyone, Users or Authenticated Users had to it is taken off`,
]
}
const team = teamPaths(layout.home)
return [
mac
? ` account ${TEAM_REAL_NAME} (${TEAM_USER}): a standard user with a random password nobody knows, listed in Users & Groups`
: ` account ${TEAM_REAL_NAME} (${TEAM_USER}): a standard user with a locked password, never an administrator`,
` home ${layout.home}`,
` daemon ${label}, ${mac ? 'a LaunchDaemon' : 'a systemd unit'} at ${file}, running as ${TEAM_USER} on port ${TEAM_PORT}`,
` log ${team.log} (inside the account's home)`,
` setup ${layout.configFile} and ${layout.statusDir}/`,
` check ${ownerHome}/${SENTINEL_NAME}, a file the account must not be able to read`,
` engines Claude Code and Codex in ${layout.home}/.local, installed by the account itself`,
` your home ${ownerHome}, made private (mode 700)`,
]
}
function byHandLines({ layout, mac, windows }: TeamHere, owner: string, ownerHome: string): string[] {
const { label, file } = layout.service
if (windows) {
return [
' To remove it by hand, in Windows PowerShell run as administrator:',
` Unregister-ScheduledTask -TaskPath '\\Harness\\' -TaskName 'Harness Team' -Confirm:$false`,
` Get-CimInstance Win32_UserProfile | Where-Object LocalPath -eq '${layout.home}' | Remove-CimInstance; Remove-LocalUser ${TEAM_USER}`,
` Remove-Item -Recurse '${layout.configFile}', '${layout.statusDir}', '${layout.relayDir(owner)}', '${layout.sharedMark}', '${ownerHome}\\${SENTINEL_NAME}'`,
` Remove-Item '${layout.sharedDir}' (only when it is empty)`,
]
}
if (!mac) {
const state = parentOf(layout.statusDir)
const stateMark = `${state}/${layout.sharedMark.slice(layout.sharedMark.lastIndexOf('/') + 1)}`
return [
' To remove it by hand, in a terminal:',
` sudo systemctl disable --now ${label}; sudo pkill -KILL -u ${TEAM_USER}; sudo userdel -r ${TEAM_USER}`,
` sudo rm ${file}; sudo rm -rf ${layout.configFile} ${layout.statusDir} ${layout.relayDir(owner)} ${layout.sharedMark} ${stateMark}`,
` rm ${ownerHome}/${SENTINEL_NAME}; sudo rmdir ${layout.sharedDir} ${state} (only when they are empty)`,
]
}
return [
' To remove it by hand, in Terminal (macOS asks to let Terminal administer your computer for the first line):',
` sudo dscl . -delete /Users/${TEAM_USER}`,
` sudo launchctl bootout system/${label}; sudo rm ${file}; sudo rm -rf ${layout.home}`,
` sudo rm -rf '${layout.configFile}' '${layout.statusDir}' '${layout.sharedMark}'; rm ${ownerHome}/${SENTINEL_NAME}`,
` sudo rmdir '${layout.sharedDir}' (only when it is empty)`,
]
}
/** A script's reason as a sentence, so the one after it does not run on: the scripts' own reasons end without a stop. */
const sentence = (text: string): string => /[.!?]$/.test(text) ? text : `${text}.`
/** Swarm v3 has no Team accounts (anh Dee, 2026-11-07): nothing makes one, signs its engines in or gives it a model now.
* `harness team remove` deletes one made before. */
function removed(deps: TeamCommandDeps, json: boolean): number {
return fail(deps, json, 'TEAM_ACCOUNTS_REMOVED', 'Swarm v3 has no Team accounts: Swarm work runs in your own account. '
+ 'To delete one made before: harness team remove.')
}
function ago(now: number, at: number): string {
const seconds = Math.max(0, Math.round((now - at) / 1000))
if (seconds < 90) return `${seconds}s ago`
if (seconds < 90 * 60) return `${Math.round(seconds / 60)}m ago`
return `${Math.round(seconds / 3600)}h ago`
}
async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {
const session = deps.session()
const dedicated = session?.kind === 'team'
const here = teamHere(deps.platform)
const config = here ? deps.readConfig() : null
const exists = here ? await deps.accountExists(config?.user ?? TEAM_USER) : false
if (!here || (!config && !exists)) {
if (json) deps.out(JSON.stringify({ account: false, dedicated }))
else if (dedicated) deps.out('This computer runs team work only (harness team on): Swarm agents run here, and it reaches none of your other computers.\n undo: harness team off')
else deps.out(`No Harness Team account on this computer.${here ? '' : ' On a computer used only for agents: harness team on.'}`)
return 0
}
const { layout } = here
const user = config?.user ?? TEAM_USER
const home = config?.home ?? layout.home
const owner = config?.owner ?? deps.user()
const ownerHome = config?.ownerHome ?? deps.home()
const label = config?.label ?? layout.service.label
const serviceFile = config?.plist ?? layout.service.file
const job = await deps.jobState(label)
const report = deps.readStatus(config?.statusFile ?? layout.statusFile)
const homeMode = deps.mode(ownerHome)
// Task Scheduler keeps its definitions where a standard owner cannot look: what it says of the task is what is there.
const plistPresent = here.windows ? job.loaded : deps.exists(serviceFile)
const agentTmp = here.windows ? null : deps.agentTmp?.() ?? null
if (json) {
deps.out(JSON.stringify({
account: exists, user, realName: config?.realName ?? TEAM_REAL_NAME, home, homePresent: deps.exists(home),
label, plist: serviceFile, plistPresent, job, port: config?.port ?? TEAM_PORT,
config: config ? layout.configFile : null, ownerHomeMode: homeMode === null ? null : homeMode.toString(8),
signIn: report?.signIn ?? null, privacy: report?.privacy ?? null, engines: report?.engines ?? null, purges: report?.purges ?? null, dedicated,
agentTmp: agentTmp && { ...agentTmp, mode: agentTmp.mode === null ? null : agentTmp.mode.toString(8) },
}))
return 0
}
const now = deps.now()
deps.out(`Harness Team account · ${config?.realName ?? TEAM_REAL_NAME} (${user})`)
deps.out(' Swarm v3 has no Team accounts: its daemon stops once no agent runs in it. harness team remove deletes the account, its home and its daemon.')
deps.out(` account ${exists ? '● exists' : '○ missing'}`)
deps.out(` daemon ${job.pid !== null ? `● running (pid ${job.pid})` : job.loaded ? `◍ loaded, not running${job.state ? ` (${job.state})` : ''}` : plistPresent ? '○ installed, stopped · harness team remove removes it' : '○ not installed · harness team remove removes what is left'}`)
const signIn = report?.signIn
deps.out(` sign-in ${!signIn ? '? not reported yet' : signIn.state === 'signed-in' ? `✓ signed in (${ago(now, signIn.at)})` : `✗ ${signIn.state}${signIn.detail ? `: ${signIn.detail}` : ''}`}`)
const privacy = report?.privacy
deps.out(` privacy ${!privacy ? '? not checked yet' : privacy.passed ? `Private ✓ (checked ${ago(now, privacy.checkedAt)})` : `✗ ${privacy.item}: ${privacy.detail} (checked ${ago(now, privacy.checkedAt)})`}`)
// On Linux a home with ACL entries (a guest's) shows their mask as its group bits, 710: setup keeps that mask
// (script.ts), so there the privacy check is what says it is private, with nothing open to others.
const homePrivate = homeMode === 0o700
|| (deps.platform === 'linux' && homeMode !== null && (homeMode & 0o007) === 0 && privacy?.passed === true)
// Windows has no mode bits to show: an ACL keeps the profile private, and the privacy check is what proves it.
deps.out(here.windows
? ` your home ${ownerHome} · ${privacy?.passed ? 'private ✓' : '? not proven private yet: the privacy check says why; harness team remove takes broad access off it'}`
: ` your home ${ownerHome} · mode ${homeMode === null ? 'unknown' : homeMode.toString(8)}${homePrivate ? ' ✓' : ' ✗ should be 700: harness team remove makes it private'}`)
if (agentTmp) {
deps.out(` temp files ${agentTmp.path} · ${agentTmp.state === 'not-made' ? 'made when your next agent starts'
: agentTmp.state === 'private' ? 'mode 700 ✓'
: `${agentTmp.mode === null ? 'not a private folder' : `mode ${agentTmp.mode.toString(8)}`} ✗ your agents may use the shared /tmp: your next agent makes it private, or says why not in the daemon's log`}`)
}
for (const line of purgeLines(report?.purges, (at) => ago(now, at))) deps.out(line)
deps.out('')
deps.out(' What setup made:')
for (const line of madeLines(here, owner, ownerHome)) deps.out(` ${line}`)
deps.out('')
deps.out(' undo: harness team remove')
for (const line of byHandLines(here, owner, ownerHome)) deps.out(line)
return 0
}
/** What `harness team status` says of ended sessions' data not deleted yet (superTabs/inCore/teamPurge.ts): nothing when none
* waits. It holds the account, so this says why it takes no other project's work. */
function purgeLines(purges: TeamStatus['purges'], ago: (at: number) => string): string[] {
if (purges?.unreadable) {
return [' purges ✗ the record of what is still to delete can\'t be read: the Team daemon\'s log says where it was kept.',
' Until its owner clears it, this account takes no other project\'s work.']
}
if (!purges?.pending) return []
const count = purges.pending === 1 ? '1 ended session\'s' : `${purges.pending} ended sessions'`
return [` purges ◍ ${count} data not deleted yet (checked ${ago(purges.at)}). The daemon keeps trying by itself;`,
' this account takes no other project\'s work until it has.']
}
/** A terminal app's bundle id as macOS gives it to what the app starts, for the one command that asks again. */
const BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]{0,127}$/
/** What to do when macOS keeps the account ([REMOVE_REFUSED]): nothing was removed, and the account runs as before. */
function refusedLines(deps: TeamCommandDeps, inTerminal: boolean): string[] {
const usersAndGroups = `delete "${TEAM_REAL_NAME}" in System Settings > Users & Groups (ⓘ, Delete User…, Delete the home folder), then run harness team remove again for the rest`
if (!inTerminal) {
return [
' macOS 26 deletes an account only for an app you allow to administer this Mac, and it cannot ask that for this prompt. Either:',
' · run harness team remove in Terminal: it asks for your password there, then macOS asks to let Terminal',
' administer your computer. Choose Allow.',
` · or ${usersAndGroups}.`,
]
}
const app = deps.env.__CFBundleIdentifier?.trim()
const reset = `tccutil reset SystemPolicySysAdminFiles${app && BUNDLE_ID.test(app) ? ` ${app}` : ''}`
return [
' macOS deletes an account only for an app you allow to administer this Mac. If you chose Don\'t Allow when it asked,',
` it asks again after: ${reset}`,
` Or ${usersAndGroups}.`,
]
}
interface MachineRow { machineId: string; sessionKind?: string | null; hostMachineId?: string | null }
/**
* This computer's team machine, off the owner's Harness account: the backend ends the team sign-in bound to it with it.
* Only after the account is gone: a removal macOS refuses must leave the account signed in and running.
*
* Found by the Mac the backend recorded for it, from the owner's sign-in when setup minted the code (`hostMachineId`), which
* nothing a team session sends can set. Never by a computer id from the Team account's files: a Team agent could write there
* the id of the owner's team machine on another Mac, and this would remove that one (audit L3). A team machine with no Mac
* recorded stays, and the person is told to remove it.
*/
async function forgetTeamComputer(deps: TeamCommandDeps): Promise<{ removed: number } | { error: string }> {
if (!deps.session()) return { error: 'this computer is not signed in to Harness' }
try {
const { session, headers } = await deps.auth()
if (!session.machineId) return { removed: 0 }
const { machines = [] } = await deps.get<{ machines?: MachineRow[] }>('/api/machines', headers)
const ours = machines.filter((m) => m.sessionKind === 'team' && m.hostMachineId === session.machineId && m.machineId !== session.machineId)
for (const machine of ours) await deps.delete(`/api/machines/${encodeURIComponent(machine.machineId)}`, headers)
return { removed: ours.length }
} catch (error) {
return { error: (error as Error).message }
}
}
async function remove(deps: TeamCommandDeps, json: boolean): Promise<number> {
const here = teamHere(deps.platform)
if (!here) return fail(deps, json, 'UNSUPPORTED', 'The Harness Team account is made on a Mac, a Linux or a Windows computer; this computer has none. To stop team work here: harness team off.')
const { layout, scripts, mac, windows } = here
if (deps.uid() === 0) return fail(deps, json, 'RUN_AS_YOURSELF', 'Run this as yourself, not with sudo: Harness asks for an administrator password itself.')
const config = deps.readConfig()
const ownerHome = pathCheck(deps.platform)(config?.ownerHome ?? deps.home(), 'home folder')
if (!config && !await deps.accountExists(TEAM_USER) && !deps.exists(layout.service.file) && !deps.exists(layout.home)) {
if (json) deps.out(JSON.stringify({ ok: true, removed: false }))
else deps.out(`No Harness Team account on ${here.where}; nothing to remove.`)
return 0
}
// In a terminal, with sudo there: macOS then asks to let the terminal app administer the Mac, which deleting an account
// needs (./admin.ts). Elsewhere (Desktop, a script), the administrator prompt, which macOS 26 refuses it. Windows has
// User Account Control's alone.
const inTerminal = deps.interactive && !windows
if (inTerminal && !json) {
deps.out(mac ? 'Harness will remove the Harness Team account. sudo asks for your password here; macOS may then ask to let this terminal administer your computer.'
: 'Harness will remove the Harness Team account. sudo asks for your password here.')
}
const result = await deps.admin(() => ({
// Only the Linux removal names the owner (the relay folder setup made for them); a Mac's removal never read it, so its
// name is not checked there.
script: scripts.remove({ user: config?.user ?? TEAM_USER, home: config?.home ?? layout.home, ownerHome,
...mac ? {} : { owner: userCheck(deps.platform)(config?.owner ?? deps.user(), 'owner account') } }),
}), prompts(here.where).remove, inTerminal ? 'sudo' : 'prompt')
if (!result.ok) {
if (result.code === 'CANCELLED') {
return fail(deps, json, 'CANCELLED', `Nothing was removed: ${inTerminal ? 'sudo did not get an administrator password' : 'the administrator prompt was cancelled'}.`)
}
if (result.code === 'NO_PROMPT') return fail(deps, json, 'NO_PROMPT', 'No administrator prompt here: run harness team remove in a terminal.')
if (result.status === REMOVE_REFUSED) {
// Linux: userdel keeps a user something still runs as, which the removal stopped first; a restart ends it for certain.
// Windows: a process of the account still holds its profile, which the same restart ends.
const next = mac ? refusedLines(deps, inTerminal) : [' Something on this computer still runs as the account. Restart it, then run harness team remove again.']
if (json) return fail(deps, json, 'DELETE_REFUSED', sentence(result.message), { next: next.map((line) => line.trim()) })
fail(deps, json, 'DELETE_REFUSED', `${here.system} kept the Harness Team account: ${sentence(result.message)}`)
for (const line of next) deps.err(line)
return 1
}
return fail(deps, json, 'REMOVE_FAILED', `The Harness Team account was not fully removed: ${sentence(result.message)} Run \`harness team remove\` again.`)
}
const forgotten = await forgetTeamComputer(deps)
if (json) {
deps.out(JSON.stringify({ ok: true, removed: true, computer: forgotten }))
return 0
}
deps.out(`✓ Removed the Harness Team account (${TEAM_USER}), ${layout.home} and the daemon ${layout.service.label}.`)
const teamMachine = `"${deps.hostname().slice(0, 60)} · Team"`
if ('error' in forgotten) deps.out(`! Its computer is still on your Harness account (${forgotten.error}). Remove ${teamMachine}: harness machines`)
else if (forgotten.removed > 0) deps.out('✓ Took its computer off your Harness account, which signs it out.')
else deps.out(` If its computer, ${teamMachine}, is still on your Harness account, remove it there: harness machines`)
// Windows may hold the profile's registry files until it restarts (./windowsScript.ts remove, step 5): said as it said it.
const later = result.stdout.split('\n').find((line) => line.includes('is removed at the next restart'))
if (later) deps.out(` ${later.replace(/^harness: /, '').trim()}.`)
deps.out(windows ? ' Your profile stays private.' : ' Your home folder stays private (mode 700).')
return 0
}
async function teamOn(deps: TeamCommandDeps, json: boolean, yes: boolean): Promise<number> {
const session = deps.session()
if (!session) return fail(deps, json, 'NOT_SIGNED_IN', 'Sign this computer in first (harness login), then run harness team on.')
if (session.kind === 'team') {
if (json) deps.out(JSON.stringify({ ok: true, changed: false }))
else deps.out('This computer already runs team work only. undo: harness team off')
return 0
}
const here = teamHere(deps.platform)
if (here && deps.readConfig()) {
return fail(deps, json, 'TEAM_ACCOUNT', `This ${here.mac ? 'Mac' : 'computer'} has a Harness Team account, which runs its team work. \`harness team on\` is for a computer used only for agents.`)
}
if (!yes) {
if (!deps.interactive || json) return fail(deps, json, 'CONFIRM', 'Add --yes to sign this computer in for team work only.')
deps.out('This computer will run Swarm agents for your team and will no longer reach your other computers.')
deps.out('Use it only on a computer used for agents alone: they can read everything this account can.')
const answer = (await deps.ask('Sign this computer in for team work only? [y/N] ')).trim()
if (!/^y(es)?$/i.test(answer)) return fail(deps, json, 'CANCELLED', 'Nothing was changed.')
}
const label = `${deps.hostname().slice(0, 60)} · Team`
const unchanged = (error: unknown) => error instanceof TeamSignInError
? new TeamSignInError(`${error.message}${/[.!?]$/.test(error.message) ? '' : '.'} Nothing was changed on this computer.`, error.code) : error
// A code that turns this very computer into a team machine, keeping its computer id (./handoff.ts).
let code: string
try {
({ code } = await mintTeamConversion({ auth: () => deps.auth(), post: deps.post, get: deps.get, machineKey: deps.machineKey, now: deps.now }))
} catch (error) { throw unchanged(error) }
// Stopped before the code is redeemed: redeeming ends this computer's ordinary sign-in on the backend, and a daemon still
// running on it, an Autonomous one above all, would connect again under it and make this an ordinary machine again.
const wasRunning = await deps.stopDaemon()
let tokens: Awaited<ReturnType<typeof redeemTeamHandoff>>
try {
tokens = await redeemTeamHandoff(code, label, session.computerId, { post: deps.post, sleep: deps.sleep, now: deps.now })
} catch (error) {
if (wasRunning) await deps.startDaemon()
throw unchanged(error)
}
// The team sign-in takes the previous one's place in the session file, so nothing here can sign in with that one again.
const previous = deps.session() ?? session
deps.writeSession(teamSession(tokens, session.computerId, deps.autonomousEnv, deps.now(),
session.machineId ? { machineId: session.machineId } : {}))
await revokeHarnessRefresh(deps.post, previous.refreshToken)
if (json) deps.out(JSON.stringify({ ok: true, changed: true }))
else deps.out('✓ This computer now runs team work only. Its previous sign-in was discarded. undo: harness team off')
if (wasRunning) await deps.startDaemon()
return 0
}
async function teamOff(deps: TeamCommandDeps, json: boolean, flags: readonly string[]): Promise<number> {
const session = deps.session()
if (session?.kind !== 'team') {
if (json) deps.out(JSON.stringify({ ok: true, changed: false }))
else deps.out('This computer does not run team work only; nothing to change.')
return 0
}
// Before anything stops or is revoked. 10-27: a `harness logout` nobody asked for signed a whole Mac out.
const asked = deps.signOutAsked(flags)
if (!asked) {
return fail(deps, json, 'NOT_A_PERSON', '`harness team off` signs this computer out, and nothing says a person '
+ `asked: it has no terminal, and no ${SIGN_OUT_BUTTON_FLAG}. Run it in a terminal.`)
}
const wasRunning = await deps.stopDaemon()
await revokeHarnessRefresh(deps.post, session.refreshToken)
deps.removeSignIn(asked)
if (json) {
deps.out(JSON.stringify({ ok: true, changed: true, next: 'harness login' }))
if (wasRunning) await deps.startDaemon()
return 0
}
deps.out('✓ Signed this computer out of team work.')
// A team sign-in cannot hand out a computer's one (Task 1): signing in again is the ordinary sign-in.
if (deps.interactive && deps.signIn) {
await deps.signIn(wasRunning)
return 0
}
deps.out(' Sign it in as your own computer: harness login')
if (wasRunning) await deps.startDaemon()
return 0
}
/** `team __handoff`: run as the owner by setup's script, the moment the code is handed over. Prints only the code. */
async function handoff(deps: TeamCommandDeps): Promise<number> {
const { code } = await mintTeamHandoff(() => deps.auth(), deps.post)
deps.out(code)
return 0
}
/**
* The team account's machine id, in its session file, before its daemon starts. `harness start` resolves a session's machine
* (cli.ts `resolveMachineIfUnknown`), but launchd runs this account's master directly, so without this its daemon ran as its
* computer id: its gateway counted it signed out and never put its key on the device key log, so its Mac's daemon could not
* reach it to add it to a Swarm, and its Swarm host polled under an id that is not its machine (third VM run,
* docs/plans/2026-10-24-swarm-team-account.md). The first resolve creates its machine, named "<this Mac> · Team".
* Never fails the start: the next start tries again.
*/
async function recordTeamMachine(deps: TeamCommandDeps, label: string, log: (line: string) => void): Promise<void> {
const session = deps.session()
if (session?.kind !== 'team' || session.machineId) return
try {
const { headers } = await deps.auth()
const answer = await deps.post<{ machine?: { machineId?: unknown } }>('/api/machines/resolve-computer',
{ computerId: session.computerId, label }, headers)
const machineId = answer?.machine?.machineId
if (typeof machineId !== 'string' || !machineId) throw new Error('Harness answered without a machine id')
// A refresh may have rewritten the session meanwhile: the machine id goes into the newest one, while it is still the sign-in
// this asked for. A new owner's sign-in drops it, and its own start looks up its own.
const kept = await deps.updateSession((latest) => latest.kind !== 'team' || latest.computerId !== session.computerId
|| !sameSignIn(latest, session.signInEpoch) || latest.machineId === machineId ? null : { ...latest, machineId, updatedAt: deps.now() })
if (kept?.machineId !== machineId) return
log(`runs as machine ${machineId}`)
} catch (error) {
log(`could not look up this account's machine yet (${(error as Error).message}); the next start tries again`)
}
}
/**
* `team __start <file>`: run by the team daemon's job, as the team account, before its master starts. Its lines go
* to the daemon's log. Always exits 0: the daemon starts either way, signed out if the sign-in failed, and reports
* the privacy check it failed. Team work never runs as the owner instead.
*/
async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promise<number> {
const config = deps.readConfig()
const mine = config && config.user === deps.user() ? config : null
const statusFile = mine?.statusFile ?? TEAM_STATUS_FILE
const log = (line: string) => deps.out(`${new Date(deps.now()).toISOString()} [team] ${line}`)
const report = (update: Partial<Omit<TeamStatus, 'version'>>) => {
if (!mine) return
try { deps.writeStatus(statusFile, update) } catch (error) { log(`could not write ${statusFile}: ${(error as Error).message}`) }
}
const label = `${deps.hostname().slice(0, 60)} · Team`
if (mine && deps.session()?.kind !== 'team') {
report({ signIn: { state: 'signed-out', at: deps.now(), detail: 'The Team sign-in is no longer available.' } })
}
if (file) {
let code: string | null = null
try {
// On Windows the handover folder's file (./windowsLayout.ts WINDOWS_TEAM_HANDOFF_FILE), which the owner wrote.
code = deps.takeHandoff(pathCheck(deps.platform)(file, 'sign-in file'))
} catch (error) {
log((error as Error).message)
report({ signIn: { state: 'failed', at: deps.now(), detail: (error as Error).message } })
}
// Setup hands a code over only when this account has no sign-in, or when its owner asked for a new one
// (`--sign-in-again`): a sign-in already here is replaced, and kept when the new one cannot be had.
if (code) {
const previous = deps.session()
try {
const computerId = deps.computerId()
const tokens = await redeemTeamHandoff(code, label, computerId, { post: deps.post, sleep: deps.sleep, now: deps.now })
// The owner's setup run handed it over: a sign-in by hand, so the device key log may start over for its account (#3262).
const handed = teamSession(tokens, computerId, deps.autonomousEnv, deps.now(), { signInEpoch: handedTeamSignInEpoch(deps.now()) })
deps.writeSession(handed)
// Pin the account while this is still the handed sign-in. The first device-log read may happen much later.
try {
const me = await deps.get<{ user?: { id?: unknown } }>('/api/auth/me', {
authorization: `Bearer ${handed.accessToken}`, 'x-autonomous-env': handed.autonomousEnv,
})
const acct = me?.user?.id
if (typeof acct !== 'string' || !acct) throw new Error('no account')
await deps.updateSession((latest) => latest.signInEpoch === handed.signInEpoch
? { ...latest, signInAcct: acct } : null)
} catch {
log('could not record the signed-in account; trust recovery requires a connection within ten minutes')
}
if (previous) await revokeHarnessRefresh(deps.post, previous.refreshToken)
log(previous ? 'signed in for team work again; the previous sign-in was ended' : 'signed in for team work')
report({ signIn: { state: 'signed-in', at: deps.now() } })
} catch (error) {
log(`sign-in failed: ${(error as Error).message}${previous ? '; the previous sign-in is kept' : ''}`)
report({ signIn: { state: 'failed', at: deps.now(), detail: (error as Error).message } })
}
}
}
await recordTeamMachine(deps, label, log)
if (mine) {
const privacy = deps.privacy(mine)
log(privacy.passed ? 'privacy check passed' : `privacy check FAILED (${privacy.item}): ${privacy.detail}`)
report({ privacy })
try {
const engines = await deps.engines(mine)
log(`engines: ${(['claude', 'codex'] as const).map((e) => `${e} ${engines[e].installed ? engines[e].signedIn === true ? 'signed in' : 'installed' : 'missing'}`).join(', ')}`)
report({ engines })
} catch (error) { log(`could not check the engines: ${(error as Error).message}`) }
}
return 0
}
/** A POSIX single-quoted word, for the one path the log script names. */
const quoted = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`
/**
* `harness team logs`: the team daemon's log, which only root can read (it lives in the account's private home).
* A server user has no Harness app to open it in, so the command reads it here (headless run, 2026-11-03).
*/
async function teamLogs(deps: TeamCommandDeps, words: readonly string[], flags: readonly string[], json: boolean): Promise<number> {
const where = deps.platform === 'darwin' ? 'this Mac' : 'this computer'
const config = deps.readConfig()
if (!config) return fail(deps, json, 'NO_ACCOUNT', `No Harness Team account on ${where}.`)
const inline = flags.find((flag) => flag.startsWith('--lines='))
const asked = inline ? Number(inline.slice('--lines='.length)) : flags.includes('--lines') ? Number(words[1]) : 40
const lines = Number.isInteger(asked) && asked > 0 && asked <= 5000 ? asked : 40
// Windows has no tail. -ErrorAction Stop: a log not there yet is said as an error, as tail says it.
const read = deps.platform === 'win32'
? `Get-Content -LiteralPath ${psQuote(windowsTeamPaths(config.home).log)} -Tail ${lines} -Encoding UTF8 -ErrorAction Stop`
: `tail -n ${lines} ${quoted(teamPaths(config.home).log)}`
const result = await deps.admin(() => ({ script: read }),
`Harness wants to read the Harness Team account's log on ${where}.`)
if (!result.ok) {
if (result.code === 'NO_PROMPT') deps.err(`✗ ${result.message} Run it in a terminal.`)
else if (result.code !== 'CANCELLED') deps.err(`✗ ${result.message}`)
return 1
}
if (json) { deps.out(JSON.stringify({ ok: true, lines })); return 0 }
deps.out(result.stdout.replace(/\n$/, ''))
return 0
}