Skip to content

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

Team machines can't change the owner's trusted keys, and teammates' work never uses the owner's git login (#1695)

Dee88abc7b66d54
diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.ts
index c692c4f0a..c78659374 100644
--- a/backend/integration/superTabGithub.test.ts
+++ b/backend/integration/superTabGithub.test.ts
@@ -1,9 +1,9 @@
-import { randomBytes, randomUUID } from 'node:crypto'
+import { createHash, randomBytes, randomUUID } from 'node:crypto'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
-import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { afterAll, beforeAll, describe, expect, it, onTestFinished, vi } from 'vitest'
import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
import { PrismaClient } from '@prisma/client'
import Fastify, { type FastifyInstance } from 'fastify'
@@ -35,7 +35,8 @@ beforeAll(async () => {
db = new PrismaClient({ datasources: { db: { url: uri } } })
await db.user.create({ data: { id: owner.sub, externalId: `fixture-${owner.sub}`, email: owner.email, autonomousEnv: 'prod', name: 'Olive Owner' } })
await db.user.create({ data: { id: host.sub, externalId: `fixture-${host.sub}`, email: host.email, autonomousEnv: 'prod' } })
- for (const [machineId, userId, name] of [['gh-host', host.sub, 'Fixture Mac'], ['gh-host-mini', host.sub, 'Fixture Mini'], ['owner-mac', owner.sub, 'Owner Mac']]) {
+ for (const [machineId, userId, name] of [['gh-host', host.sub, 'Fixture Mac'], ['gh-host-mini', host.sub, 'Fixture Mini'], ['owner-mac', owner.sub, 'Owner Mac'],
+ ['gh-pool', host.sub, 'Fixture Pool'], ['owner-pool', owner.sub, 'Owner Pool']]) {
await db.machine.create({ data: { machineId: machineId!, userId: userId!, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod',
authMode: 'remote', name } })
}
@@ -176,6 +177,87 @@ describe('the GitHub token endpoint', () => {
})
})
+describe('a queued start\'s preparation token', () => {
+ const observed = { resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9,
+ projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null }, quotas: [], tools: { git: true },
+ runningHarnessIds: [], stoppedHarnessIds: [] }
+ /** The owner's project on github.com, with a start queued on [machineId], a machine its owner [contributor] added to the Swarm. */
+ async function queued(env: Env, machineId = 'gh-pool', contributor = host, repositoryUrl: string | null = 'https://github.com/example/app.git') {
+ const tab = (await env.store.create(owner, randomUUID(), 'Pool')).id
+ await env.run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: randomUUID(), name: 'Lead',
+ configuration: config, lead: true, project: { cwd: '/work/app', repositoryUrl } } as Command)
+ if (contributor !== owner) {
+ const invitation = await env.run(tab, { type: 'invite.create', email: contributor.email, role: 'collaborator', conversationId: 'lead' } as Command)
+ await env.run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string } as Command, contributor)
+ }
+ await env.run(tab, { type: 'machine.contribute', machineId, name: 'Pool', cwd: '/swarm-root', scope: 'swarm', engines: ['codex'], maxAgents: 2 } as Command, contributor)
+ const pool = (await env.store.hostPools(contributor, machineId)).find(p => p.tabId === tab)!
+ if (contributor === owner) await env.store.observeMachine(contributor, tab, machineId, { generation: pool.machine.generation, ...observed })
+ else {
+ // Another person's project runs only on a Team machine (#1694): this one is used only for agents (`harness team on`).
+ const computerId = createHash('sha256').update(machineId).digest('hex').slice(0, 32)
+ await db.machine.update({ where: { machineId }, data: { computerId, sessionKind: 'team' } })
+ onTestFinished(async () => { await db.machine.update({ where: { machineId }, data: { computerId: null, sessionKind: null } }) })
+ const team: AuthUser = { ...contributor, harnessSessionId: `team-${machineId}`, harnessSessionKind: 'team', harnessComputerId: computerId }
+ await env.store.observeMachine(team, tab, machineId, { generation: pool.machine.generation, ...observed, privacy: { mode: 'dedicated' } })
+ }
+ const startId = String((await env.run(tab, { type: 'agent.start', request: { conversationId: 'lead', machineId, engine: 'codex', name: 'Builder',
+ cwd: '/swarm-root/lead', permissionMode: 'full', worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } as Command)).result.startId)
+ return { tab, startId }
+ }
+ const prepare = (env: Env, tab: string, startId: string, machineId = 'gh-pool', user = host, payload: Record<string, unknown> = {}) => env.app.inject({ method: 'POST',
+ url: `/api/super-tabs/hosts/${machineId}/starts/${tab}/${startId}/github-token`, headers: { authorization: `Bearer ${user.sub}` }, payload })
+
+ it('gives the host of another person\'s start a token that only reads the project\'s repository, and says whom the work is for', async () => {
+ const env = await fresh()
+ const { tab, startId } = await queued(env)
+ const pools = await env.app.inject({ method: 'GET', url: '/api/super-tabs/hosts/gh-pool/pools', headers: { authorization: `Bearer ${host.sub}` } })
+ expect(pools.json().data.find((row: { tabId: string }) => row.tabId === tab)).toMatchObject({ githubApp: true })
+ const response = await prepare(env, tab, startId)
+ expect(response.statusCode, response.body).toBe(200)
+ expect(response.json().data).toMatchObject({ github: true, token: 'ghs_fixture_1', repository: 'example/app', requestedBy: { name: 'Olive Owner', email: owner.email } })
+ const minted = env.github.calls.find(c => c.path === '/app/installations/91/access_tokens')!
+ expect(minted.body).toEqual({ repositories: ['app'], permissions: { contents: 'read', metadata: 'read' } })
+ })
+
+ it('answers no token for the machine owner\'s own project, unless its host asks for one anyway', async () => {
+ const env = await fresh()
+ const { tab, startId } = await queued(env, 'owner-pool', owner)
+ expect((await prepare(env, tab, startId, 'owner-pool', owner)).json().data).toEqual({ github: false })
+ expect(env.github.calls).toEqual([])
+ expect((await prepare(env, tab, startId, 'owner-pool', owner, { always: true })).json().data).toMatchObject({ github: true, token: 'ghs_fixture_1' })
+ })
+
+ it('refuses anyone but the start\'s host, a start that already started, and a project without a GitHub repository', async () => {
+ const env = await fresh()
+ const { tab, startId } = await queued(env)
+ expect((await prepare(env, tab, startId, 'gh-pool', owner)).statusCode).toBe(403)
+ expect((await prepare(env, tab, startId, 'gh-host-mini')).statusCode).toBe(403)
+ expect((await prepare(env, tab, 'missing-start')).statusCode).toBe(404)
+ expect((await prepare(env, tab, startId, 'gh-pool', host, { machineId: 'gh-pool' })).statusCode).toBe(400)
+ const hostRun = (command: Command) => env.store.execute(host, tab, { operationId: randomUUID(), command }, undefined, 'gh-pool')
+ await hostRun({ type: 'agent.startDispatch', startId } as Command)
+ await hostRun({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config } as Command)
+ const settled = await prepare(env, tab, startId)
+ expect(settled.statusCode).toBe(409)
+ expect(settled.json().error.code).toBe('START_SETTLED')
+ const bare = await fresh()
+ const none = await queued(bare, 'gh-pool', host, null)
+ expect((await prepare(bare, none.tab, none.startId)).json().error.code).toBe('REPOSITORY_NOT_GITHUB')
+ expect([...env.github.calls, ...bare.github.calls].filter(c => c.path.endsWith('/access_tokens'))).toEqual([])
+ })
+
+ it('answers not configured when the server has no app, and its host rows do not claim one', async () => {
+ const env = await fresh({ github: false })
+ const { tab, startId } = await queued(env)
+ const response = await prepare(env, tab, startId)
+ expect(response.statusCode).toBe(503)
+ expect(response.json().error.code).toBe('GITHUB_APP_NOT_CONFIGURED')
+ const pools = await env.app.inject({ method: 'GET', url: '/api/super-tabs/hosts/gh-pool/pools', headers: { authorization: `Bearer ${host.sub}` } })
+ expect(pools.json().data.find((row: { tabId: string }) => row.tabId === tab)).not.toHaveProperty('githubApp')
+ })
+})
+
describe('revoking the token when the task ends', () => {
const issued = async (env: Env) => {
const work = await working(env)
diff --git a/backend/src/github/app.ts b/backend/src/github/app.ts
index 5bc5e43af..4406f718b 100644
--- a/backend/src/github/app.ts
+++ b/backend/src/github/app.ts
@@ -12,6 +12,9 @@ import type { GitHubRepository } from './repository.js'
/** What a Swarm agent's token may do, and nothing more: push to and read the repository, open and update pull requests,
* and read checks and workflow runs to see whether its pull request passes. */
export const TOKEN_PERMISSIONS = { contents: 'write', pull_requests: 'write', checks: 'read', actions: 'read', metadata: 'read' } as const
+/** What preparing an agent's folder may do before the agent has a task: clone and fetch the repository, nothing more. */
+export const PREPARE_PERMISSIONS = { contents: 'read', metadata: 'read' } as const
+export type TokenPermissions = Readonly<Record<string, 'read' | 'write'>>
/** A refusal with the code clients act on; `details` adds fields beside it, such as the install link. */
export class GitHubAppError extends Error {
@@ -155,9 +158,9 @@ export class GitHubApp {
}
/** A token for [repository] alone, with TOKEN_PERMISSIONS alone. */
- async createToken(installationId: number, repository: GitHubRepository): Promise<{ token: string; expiresAt: string }> {
+ async createToken(installationId: number, repository: GitHubRepository, permissions: TokenPermissions = TOKEN_PERMISSIONS): Promise<{ token: string; expiresAt: string }> {
const answer = await this.call('POST', `/app/installations/${installationId}/access_tokens`, `Bearer ${this.jwt()}`,
- { repositories: [repository.name], permissions: TOKEN_PERMISSIONS })
+ { repositories: [repository.name], permissions })
const body = answer.body as Record<string, unknown>
if (answer.status === 201 && typeof body.token === 'string' && typeof body.expires_at === 'string' && Number.isFinite(Date.parse(body.expires_at))) {
return { token: body.token, expiresAt: body.expires_at }
diff --git a/backend/src/github/tokens.test.ts b/backend/src/github/tokens.test.ts
index 2349147e3..b723245d6 100644
--- a/backend/src/github/tokens.test.ts
+++ b/backend/src/github/tokens.test.ts
@@ -18,6 +18,22 @@ const setup = (cacheOverride?: TokenCache) => {
}
const request = (assignmentId = 'attempt-1', agentId = 'agent-1') => ({ tabId: 'tab-1', agentId, assignmentId, repository })
+describe('preparation tokens', () => {
+ it('only read the repository, and are minted each time, never cached', async () => {
+ const { tokens, github } = setup()
+ expect(await tokens.prepare(repository)).toMatchObject({ token: 'ghs_fixture_1', repository: 'acme/app' })
+ expect((await tokens.prepare(repository)).token).toBe('ghs_fixture_2')
+ const minted = github.calls.filter(c => c.path.endsWith('/access_tokens'))
+ expect(minted.map(c => c.body)).toEqual([0, 1].map(() => ({ repositories: ['app'], permissions: { contents: 'read', metadata: 'read' } })))
+ })
+
+ it('refuses a repository the app is not installed on', async () => {
+ const { tokens, github } = setup()
+ github.installed.clear()
+ await expect(tokens.prepare(repository)).rejects.toMatchObject({ code: 'GITHUB_APP_NOT_INSTALLED' })
+ })
+})
+
describe('agent tokens', () => {
it('mints one for the task and gives the same token again until ten minutes before it expires', async () => {
const { tokens, github, advance } = setup()
diff --git a/backend/src/github/tokens.ts b/backend/src/github/tokens.ts
index d6cc1945b..b088cc65d 100644
--- a/backend/src/github/tokens.ts
+++ b/backend/src/github/tokens.ts
@@ -9,7 +9,7 @@
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'
import type { Redis } from 'ioredis'
import { logger } from '../utils/logger.js'
-import { GitHubApp, GitHubAppError, cacheSecret, githubAppConfig, type BranchProtection } from './app.js'
+import { GitHubApp, GitHubAppError, PREPARE_PERMISSIONS, cacheSecret, githubAppConfig, type BranchProtection } from './app.js'
import type { GitHubRepository } from './repository.js'
import type { WorkHold } from './holds.js'
@@ -148,6 +148,18 @@ export class GitHubTokens {
defaultBranchProtected: branch.protection === 'pull_request', defaultBranchProtection: branch.protection }
}
+ /**
+ * A token that only reads [repository], for a machine preparing a Swarm agent's folder before the agent exists (routes/
+ * superTabs.ts, a start's `github-token`): the clone and the fetch of its default branch, so that the machine's own git
+ * login is never used for another person's project. Never cached: one start asks once, and it lasts at most an hour.
+ */
+ async prepare(repository: GitHubRepository): Promise<{ token: string; expiresAt: string; repository: string }> {
+ const installation = await this.app.installation(repository)
+ if (installation === null) throw this.app.notInstalled(repository)
+ const minted = await this.app.createToken(installation, repository, PREPARE_PERMISSIONS)
+ return { ...minted, repository: repository.fullName }
+ }
+
private async revoke(tabId: string, agentId: string, entry: Entry, why: string): Promise<void> {
try { await this.app.revoke(entry.token) } catch (error) {
this.log.warn('[github] token revoke failed', { tabId, agentId, repository: entry.repository, why,
diff --git a/backend/src/lib/teamSession.test.ts b/backend/src/lib/teamSession.test.ts
index 00b006cd0..6aedcb36d 100644
--- a/backend/src/lib/teamSession.test.ts
+++ b/backend/src/lib/teamSession.test.ts
@@ -81,7 +81,10 @@ function recorder() {
return name === 'githubAssignment'
? { tabId: 'tab-1', agentId: 'agent-1', assignmentId: 'assignment-1', repositoryUrl: 'https://github.com/example/project',
requester: { name: 'Owner', email: '[email protected]' }, agentName: 'Builder', machineName: 'MacBook Pro · Team' }
- : { ok: true }
+ : name === 'githubStart'
+ ? { tabId: 'tab-1', startId: 'start-1', repositoryUrl: 'https://github.com/example/project', own: true, requester: { name: 'Owner', email: '[email protected]' } }
+ // The pools route marks each row with the app (routes/superTabs.ts), so its store answers rows.
+ : name === 'hostPools' ? [] : { ok: true }
} })
return { store: methods() as unknown as SuperTabStore, calls }
}
@@ -103,7 +106,8 @@ beforeEach(async () => {
app.setErrorHandler(errorHandler)
registerAuthMiddleware(app, authenticate as never)
// A GitHub App that hands out a fixed token: the route's own checks are the store's (githubAssignment).
- const github = { issue: vi.fn(async () => ({ token: 'fixture-token', expiresAt: new Date(0).toISOString() })), release: vi.fn(async () => {}) }
+ const github = { issue: vi.fn(async () => ({ token: 'fixture-token', expiresAt: new Date(0).toISOString() })), release: vi.fn(async () => {}),
+ prepare: vi.fn(async () => ({ token: 'fixture-read-token', expiresAt: new Date(0).toISOString(), repository: 'example/project' })) }
await app.register(superTabRoutes, { store: store.store, github: github as never })
await app.register(harnessShareRoutes)
await app.register(deviceKeyRoutes)
@@ -170,6 +174,13 @@ describe('a team session on its own machine', () => {
expect(store.calls).toEqual([{ method: 'githubAssignment', args: [expect.objectContaining({ harnessSessionKind: 'team' }), 'tab-1', 'agent-1', 'team-mac'] }])
})
+ it('asks for a queued start\'s read-only token on its own machine, always: it has no git login of its own', async () => {
+ const res = await call('POST', '/api/super-tabs/hosts/team-mac/starts/tab-1/start-1/github-token', { always: true })
+ expect(res.statusCode, res.body).toBe(200)
+ expect(res.json().data).toMatchObject({ github: true, token: 'fixture-read-token', repository: 'example/project' })
+ expect(store.calls).toEqual([{ method: 'githubStart', args: [expect.objectContaining({ harnessSessionKind: 'team' }), 'tab-1', 'start-1', 'team-mac'] }])
+ })
+
it('registers its own computer, as a team machine', async () => {
const res = await call('POST', '/api/machines/resolve-computer', { computerId: TEAM_COMPUTER.toUpperCase(), label: 'MacBook Pro · Team' })
expect(res.statusCode, res.body).toBe(200)
@@ -205,6 +216,7 @@ describe('a team session reaching past its own machine', () => {
['POST', '/api/super-tabs/hosts/owner-mac/terminal', undefined],
['GET', '/api/super-tabs/hosts/owner-mac/starts/tab-1/start-1', undefined],
['POST', '/api/super-tabs/hosts/owner-mac/starts/tab-1/start-1', startOp],
+ ['POST', '/api/super-tabs/hosts/owner-mac/starts/tab-1/start-1/github-token', { always: true }],
['POST', '/api/super-tabs/tab-1/machines/owner-mac', observation],
] as const) limited(await call(method, url, payload))
expect(store.calls).toEqual([])
diff --git a/backend/src/lib/teamSession.ts b/backend/src/lib/teamSession.ts
index bd8503325..a89b6f1d1 100644
--- a/backend/src/lib/teamSession.ts
+++ b/backend/src/lib/teamSession.ts
@@ -110,6 +110,9 @@ export const TEAM_ROUTES: readonly TeamRoute[] = [
{ method: 'POST', url: '/api/super-tabs/hosts/:machineId/terminal', scope: 'machine' },
{ method: 'GET', url: '/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', scope: 'machine' },
{ method: 'POST', url: '/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', scope: 'machine' },
+ // A read-only token for a queued start's repository, to clone and fetch its folder before the agent exists: a team account
+ // has no git login of its own (routes/superTabs.ts).
+ { method: 'POST', url: '/api/super-tabs/hosts/:machineId/starts/:tabId/:startId/github-token', scope: 'machine' },
{ method: 'POST', url: '/api/super-tabs/:tabId/machines/:machineId', scope: 'machine' },
// Reads as one of its agents.
{ method: 'GET', url: '/api/super-tabs/:tabId', scope: 'agent' },
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 9067b3a59..2b62f44c4 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -49,6 +49,7 @@ const mentionQuery = z.object({ state: z.enum(['waiting', 'earlier']) }).strict(
const savePolicy = z.object({ revision: z.number().int().nonnegative().safe(), policy: routingPolicySchema }).strict()
const stop = z.object({ assignmentId: id, receipt: z.string().min(1).max(2000) }).strict()
const githubToken = z.object({ machineId: id }).strict()
+const githubStartToken = z.object({ always: z.boolean().optional() }).strict()
async function respond(reply: FastifyReply, action: () => Promise<unknown>) {
@@ -67,8 +68,26 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
const store = options.store ?? new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env),
{ workEnded: (tabId, ended) => { void github?.release(tabId, ended).catch(error => logger.warn('[github] release failed', { tabId, error: String(error) })) } })
app.get('/api/super-tabs/grids', (req, reply) => respond(reply, () => store.hostGrids(req.user!)))
+ // Each row says whether this server has the Harness GitHub App, so the host knows to ask for a start's token below.
app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/pools', { preHandler: validateParams(hostParams) },
- (req, reply) => respond(reply, () => store.hostPools(req.user!, req.params.machineId)))
+ (req, reply) => respond(reply, async () => (await store.hostPools(req.user!, req.params.machineId)).map(row => github ? { ...row, githubApp: true } : row)))
+ // A read-only token for a queued start's project repository, for its host to clone and fetch the folder before the agent
+ // exists, so that the machine owner's own git login is never used for another person's project (docs/swarm-github-app.md).
+ // The machine owner's own project answers `github: false` and the host uses its own login, unless it asks `always` (a
+ // Harness Team account, which has none).
+ app.post<{ Params: z.infer<typeof hostStartParams>; Body: z.infer<typeof githubStartToken> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId/github-token',
+ { preHandler: [validateParams(hostStartParams), validateBody(githubStartToken)] }, (req, reply) => respond(reply, async () => {
+ if (!github) throw new GitHubAppError('GITHUB_APP_NOT_CONFIGURED', 'This Harness server has no GitHub App configured.', 503)
+ const grant = await store.githubStart(req.user!, req.params.tabId, req.params.startId, req.params.machineId)
+ if (grant.own && req.body?.always !== true) return { github: false }
+ const repository = githubRepository(grant.repositoryUrl)
+ if (!repository) {
+ throw new SuperTabError('REPOSITORY_NOT_GITHUB', grant.repositoryUrl
+ ? 'This project\'s repository is not on github.com, so the Harness GitHub App cannot give a token for it.'
+ : 'This project has no repository address yet. Its owner or Lead can share it (project.repository).', 409)
+ }
+ return { github: true, ...await github.prepare(repository), requestedBy: grant.requester }
+ }))
app.get<{ Params: z.infer<typeof hostStartParams> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', { preHandler: validateParams(hostStartParams) },
(req, reply) => respond(reply, () => store.start(req.user!, req.params.tabId, req.params.startId, undefined, req.params.machineId)))
app.post<{ Params: z.infer<typeof hostStartParams>; Body: z.infer<typeof operationSchema> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId',
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 739441c17..7bac618b6 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -845,6 +845,33 @@ export class SuperTabStore {
})
}
+ /**
+ * What a contributed machine's host needs to prepare a queued start's folder before the agent exists (routes/superTabs.ts,
+ * a start's `github-token`): the start's project repository, whom the work is for, and whether it is the machine owner's
+ * own project. Only the host of that start, while nothing has started or failed yet, as `start()` reads it.
+ */
+ async githubStart(user: AuthUser, tabId: string, startId: string, machineId: string) {
+ return transaction(this.db, async tx => {
+ const state = stateOf(await this.row(tx, user, tabId))
+ const actor = await this.poolHostActor(tx, user, state, machineId, startId)
+ const start = state.starts?.find(s => s.id === startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
+ if (start.harnessId || start.error) fail('START_SETTLED', 'This start has already started or failed; its folder is not prepared again.', 409)
+ if (person(state, start.contributorId).generation !== start.membershipGeneration) fail('FORBIDDEN', 'Only the original initiating lead can resume this start.', 403)
+ const group = readConversation(state, actor, start.request.conversationId)
+ if (actor.kind === 'agent' && group.leadId !== actor.agentId) fail('LEAD_REQUIRED', 'The coordinating lead changed.', 403)
+ if (group.archived) fail('ARCHIVED', 'This conversation is archived.')
+ const grant = await this.contribution(tx, state, actor, start.request, true)
+ if (grant.machineOwnerId !== start.machineOwnerId || (grant.hostGrant ?? null) !== start.hostGrant) {
+ fail('CONTRIBUTION_REVOKED', 'This start belongs to a machine grant that was revoked.', 403)
+ }
+ const project = groupProject(state, group)
+ const owner = await tx.user.findUnique({ where: { id: project.ownerId }, select: { name: true, email: true } })
+ const email = owner?.email ?? state.people.find(p => p.id === project.ownerId)?.email ?? ''
+ return { tabId, startId, repositoryUrl: project.repository?.repositoryUrl ?? null, own: project.ownerId === start.machineOwnerId,
+ requester: { name: owner?.name?.trim() || null, email } }
+ })
+ }
+
/** Streams one file into the bucket for a later `message.send` by the same actor in the same conversation. Access is
* checked before a byte is stored; the row that makes it sendable is written only once the whole file is. */
async upload(user: AuthUser, tabId: string, conversationId: string, file: { name: string; mime: string; body: Readable }, asAgentId?: string) {
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index c74236fc6..7f729328d 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -605,6 +605,20 @@ describe('agent_create with a receipt', () => {
expect(vi.mocked(create!).mock.calls[0][0]).toMatchObject({ cwd: '/projects/prepared', scmLaunchRecord: { kind: 'git' } })
})
+ it('fetches nothing with this machine\'s login for another person\'s Swarm worktree: its host already fetched with the app\'s token', async () => {
+ const { ask, replies } = setup()
+ await ask({ engine: 'codex', projectSource: 'worktree', gitSource: '/swarm/project', branchName: 'super-tab/start-1', branchBase: 'default',
+ swarmRole: 'dev', swarmGitHub: true, creationId: CREATION })
+ await vi.waitFor(() => expect(replies).toHaveLength(1))
+ expect(prepareProjectFolder).toHaveBeenLastCalledWith({ source: 'worktree', gitSource: '/swarm/project', branchName: 'super-tab/start-1',
+ fromDefaultBranch: true, offline: true }, expect.anything())
+ // A Swarm start that is the machine owner's own fetches as before.
+ await ask({ engine: 'codex', projectSource: 'worktree', gitSource: '/swarm/project', branchName: 'super-tab/start-2', branchBase: 'default',
+ swarmRole: 'dev', creationId: `${CREATION}-own` })
+ await vi.waitFor(() => expect(replies).toHaveLength(2))
+ expect(vi.mocked(prepareProjectFolder).mock.calls.at(-1)![0]).not.toHaveProperty('offline')
+ })
+
it('records a folder it could not prepare as failed, in the folder\'s own words when it has them', async () => {
const { ask, create, replies } = setup()
vi.mocked(prepareProjectFolder).mockRejectedValueOnce(new ProjectFolderError('CLONE_FAILED', 'Could not clone it.')).mockRejectedValueOnce(new Error('disk full'))
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 186b1761c..b2164e59c 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -410,6 +410,9 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
if (swarmGitHub !== undefined && (swarmGitHub !== true || !isSwarmRole(swarmRole))) {
reply({ error: 'INVALID_SWARM_ROLE', detail: 'swarmGitHub is true, with a Swarm role.' }); return
}
+ // Its worktree fetches nothing with this machine's own git login: its host fetched with the app's token just before
+ // (superTabs/projectFolder.ts), or, started by a Lead on its own machine, it starts from what the checkout has.
+ if (swarmGitHub === true && projectFolder?.source === 'worktree') projectFolder = { ...projectFolder, offline: true }
// Blank is "number it", the same as absent — a client that sends an empty field is not
// asking for an agent with no name.
const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim() : null
diff --git a/cli/src/gateway/accountHttp.spec.ts b/cli/src/gateway/accountHttp.spec.ts
index fb9249e43..215e9426a 100644
--- a/cli/src/gateway/accountHttp.spec.ts
+++ b/cli/src/gateway/accountHttp.spec.ts
@@ -15,10 +15,10 @@ function setup() {
let account: GatewayAccount = { machineId: 'account-a', signIn: null, autonomousEnv: 'test' }
const request = vi.fn<typeof fetch>(async () => response(body))
const tokens = { accessToken: vi.fn(async () => 'token') }
- const changed = vi.fn(), reachable = vi.fn()
+ const changed = vi.fn(), reachable = vi.fn(), listed = vi.fn()
const deps = { dataDir, account: () => account, tokens, request, base: () => 'https://backend.invalid',
- computer: { id: 'computer', name: 'Laptop', hostname: 'host' }, environment: 'prod', changed, reachable, log: vi.fn() }
- return { api: createAccountHttp(deps), deps, dataDir, request, tokens, changed, reachable,
+ computer: { id: 'computer', name: 'Laptop', hostname: 'host' }, environment: 'prod', changed, reachable, listed, log: vi.fn() }
+ return { api: createAccountHttp(deps), deps, dataDir, request, tokens, changed, reachable, listed,
account: (next: GatewayAccount) => { account = next } }
}
@@ -91,9 +91,16 @@ describe('account HTTP in the gateway', () => {
})
it('owns persistence, reports fresh lists, and uses stale rows during an outage after a restart', async () => {
- const { api, deps, dataDir, request, changed, reachable } = setup()
+ const { api, deps, dataDir, request, changed, reachable, listed } = setup()
expect(await api.machines()).toEqual({ status: 200, body })
expect(reachable).toHaveBeenLastCalledWith(['remote'])
+ // The body as the backend answered it, for the trust group's team machines (lib/e2ee/machineKinds.ts); null once signed out.
+ expect(listed).toHaveBeenLastCalledWith(body)
+ request.mockResolvedValueOnce(response({}, 401))
+ await api.machines()
+ expect(listed).toHaveBeenLastCalledWith(null)
+ request.mockResolvedValueOnce(response(body))
+ await api.machines()
expect(JSON.parse(readFileSync(join(dataDir, 'machines.json'), 'utf8')).bodyOwner).toBe('account-a')
changed.mockClear()
const restarted = createAccountHttp(deps)
diff --git a/cli/src/gateway/accountHttp.ts b/cli/src/gateway/accountHttp.ts
index b12a67329..f797b25eb 100644
--- a/cli/src/gateway/accountHttp.ts
+++ b/cli/src/gateway/accountHttp.ts
@@ -15,6 +15,9 @@ interface AccountHttpDeps {
base?: () => string
changed?(state: GatewayMachines): void
reachable?(machineIds: string[] | null): void
+ /** Every machine list the backend answered (its body), and null on a sign-out: the trust group reads which of the
+ * account's machines are team machines from it (lib/e2ee/machineKinds.ts). */
+ listed?(body: Record<string, unknown> | null): void
log?(line: string): void
}
@@ -75,6 +78,7 @@ export function createAccountHttp(deps: AccountHttpDeps) {
cache.listen((body) => {
const { machines, source } = cache.list()
deps.reachable?.(source !== 'backend' ? null : machines.filter(m => m.state !== 'offline').map(m => m.machineId))
+ deps.listed?.(source === 'backend' ? body : null)
deps.changed?.({ owner: deps.account().machineId, body, fetchedAt: cache.lastResponse()?.fetchedAt ?? Date.now() })
})
const restored = cache.lastResponse()
diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.ts
index 10718d64a..920c9ae10 100644
--- a/cli/src/gateway/start.ts
+++ b/cli/src/gateway/start.ts
@@ -32,6 +32,7 @@ import { b64d, b64e, fingerprint } from '../lib/e2ee/core.js'
import { DeviceLogStore } from '../lib/e2ee/deviceLogStore.js'
import { DeviceLogSyncer, type DeviceKeysSeen, type DeviceLogFetched, type DeviceLogTrustOutcome } from '../lib/e2ee/deviceLogSyncer.js'
import { GroupSyncer, relayRequester, SELF_STAMP } from '../lib/e2ee/groupSyncer.js'
+import { MachineKinds } from '../lib/e2ee/machineKinds.js'
import { MachinePeerStore } from '../lib/e2ee/machinePeers.js'
import { applySharedTrust, isSharedKey } from './sharedTrust.js'
import { E2eeStore } from '../lib/e2ee/store.js'
@@ -131,11 +132,19 @@ const PAIR_STATUS: Record<string, number> = {
export function startGateway(host: GatewayHost): StartedGateway {
let account = host.account
let reachable: Set<string> | null = null
+ // Which of the account's machines are team machines, whose rosters the trust group never takes (lib/e2ee/machineKinds.ts).
+ const machineKinds = new MachineKinds({
+ read: async () => {
+ const answer = await accountHttp.machines()
+ return answer.status === 200 && account.machineId ? answer.body : null
+ },
+ })
const accountHttp = createAccountHttp({
tokens: host.tokens, account: () => account,
computer: { id: host.computerId, name: host.machineName, hostname: host.hostname }, environment: host.autonomousEnv,
changed: host.machines,
reachable: (ids) => { reachable = ids ? new Set(ids) : null },
+ listed: (body) => { if (body) machineKinds.adopt(body); else machineKinds.clear() },
log: (line) => console.log(`[gateway] ${line}`),
})
const gateway = new RelayGateway({
@@ -232,6 +241,7 @@ export function startGateway(host: GatewayHost): StartedGateway {
// Only a list the backend answered says who is offline; otherwise try every member.
reachable: () => reachable,
shared: (pub) => isSharedKey(gateway.pairedPeers(), pub),
+ machineKinds,
ready: () => devLogSyncer?.current() ?? false,
log: (line) => console.log(line),
})
@@ -519,6 +529,8 @@ export function startGateway(host: GatewayHost): StartedGateway {
// under a new sign-in, even when both accounts happen to have the same preference revision.
if (next.machineId !== account.machineId || next.autonomousEnv !== account.autonomousEnv
|| next.signIn?.epoch !== account.signIn?.epoch || next.signIn?.acct !== account.signIn?.acct) void usage?.stop(true)
+ // Another account's machine list says nothing of this one's machines.
+ if (next.machineId !== account.machineId || next.autonomousEnv !== account.autonomousEnv) machineKinds.clear()
account = next
startGroup()
registerAndSweep()
diff --git a/cli/src/lib/e2ee/groupSyncer.spec.ts b/cli/src/lib/e2ee/groupSyncer.spec.ts
index 5fe93beeb..279fcf339 100644
--- a/cli/src/lib/e2ee/groupSyncer.spec.ts
+++ b/cli/src/lib/e2ee/groupSyncer.spec.ts
@@ -41,6 +41,11 @@ interface Node {
/** What `ready` answers: the device key log is this sign-in's. */
ready: boolean
droppedSessions: string[]
+ /** What this machine's copy of the account's machine list says each machine is; `kindOf` for any it does not name. */
+ kinds: Map<string, 'team' | 'computer' | null>
+ kindOf: 'team' | 'computer' | null
+ /** How often the list was read again. */
+ reads: number
}
/** A small fleet whose "relay" is a direct call: a request reaches the target only if the caller pinned
@@ -67,6 +72,9 @@ function fleet(): { add: (name: string, machine?: boolean) => Node; link: (joine
online: true,
ready: true,
droppedSessions: [],
+ kinds: new Map(),
+ kindOf: 'computer',
+ reads: 0,
} as unknown as Node
node.syncer = new S.GroupSyncer({
store: memStore,
@@ -76,6 +84,10 @@ function fleet(): { add: (name: string, machine?: boolean) => Node; link: (joine
untrust: (p) => { node.trusted.delete(p) },
paired: () => [...node.trusted].map(([identityPub, t]) => ({ identityPub, label: 'x', pairedAt: 1, role: 'web' as const, ...(t.kind ? { kind: t.kind as 'machine' } : {}), ...(t.machineId ? { machineId: t.machineId } : {}), ...(t.shared ? { shared: true as const } : {}) })),
shared: (pub) => node.trusted.get(pub)?.shared === true,
+ machineKinds: {
+ kind: (machineId) => node.kinds.has(machineId) ? node.kinds.get(machineId)! : node.kindOf,
+ fresh: async () => { node.reads++ },
+ },
request: async (machineId, frame: Frame) => {
const target = nodes.find((n) => n.machineId === machineId)
if (!target?.online) return null
@@ -142,6 +154,82 @@ describe('GroupSyncer', () => {
for (const n of f.nodes) n.syncer.stop()
})
+ it('never swaps rosters with one of the account\'s team machines, either way, and keeps it reachable', async () => {
+ vi.useFakeTimers()
+ const f = fleet()
+ // Dee's two machines and her Mac's Harness Team account, all on her account and linked to each other.
+ const [dee, dee2, team] = [f.add('d'), f.add('e'), f.add('t')]
+ f.link(dee, dee2)
+ f.link(dee, team)
+ f.link(dee2, team)
+ for (const n of [dee, dee2]) n.kinds.set(team.machineId!, 'team')
+ // The team daemon cannot read the account's machine list (a team session may not): it places nobody.
+ team.kindOf = null
+ // A hostile team daemon holds a key of its own choosing, and a removal of Dee's other machine.
+ const planted = { pub: C.b64e(C.newIdentity().pub), kind: 'viewer', label: 'planted', at: 5_000 }
+ team.syncer.linked({ pub: planted.pub, kind: 'viewer', label: 'planted' })
+ const handle = vi.spyOn(team.syncer, 'handle')
+
+ // Dee's rounds never dial it, and an exchange with it is refused before anything is sent.
+ await dee.syncer.syncAll()
+ expect(dee.reads).toBeGreaterThan(0)
+ expect(await dee.syncer.syncWith(team.machineId!)).toBe(false)
+ expect(handle).not.toHaveBeenCalled()
+ // A group_sync from it is refused, whether it describes itself as the machine it is or as an app.
+ const asItself = { self: { pub: team.pub, kind: 'machine', label: 't', machineId: team.machineId, at: S.SELF_STAMP },
+ members: [planted], removed: [{ pub: dee2.pub, at: 9_000_000 }] }
+ expect(dee.syncer.handle(team.pub, asItself)).toEqual({ error: 'TEAM_MACHINE' })
+ expect(dee.syncer.handle(team.pub, { self: { pub: team.pub, kind: 'viewer', label: 't', at: S.SELF_STAMP }, members: [planted], removed: [] }))
+ .toEqual({ error: 'TEAM_MACHINE' })
+ expect(dee.syncer.handle(team.pub, { members: [planted], removed: [] })).toEqual({ error: 'TEAM_MACHINE' })
+ await dee2.syncer.syncAll()
+
+ // Nothing it holds reached Dee's machines; nothing of theirs was dropped; it is still pinned and trusted.
+ for (const n of [dee, dee2]) {
+ expect(n.trusted.has(planted.pub)).toBe(false)
+ expect(n.syncer.roster().members.map((m) => m.pub)).not.toContain(planted.pub)
+ expect(n.peers.get(team.machineId!)?.pub).toBe(team.pub)
+ expect(n.trusted.has(team.pub)).toBe(true)
+ }
+ expect(dee.trusted.has(dee2.pub)).toBe(true)
+ expect(dee.peers.get(dee2.machineId!)?.pub).toBe(dee2.pub)
+ // Dee's own machines still swap rosters with each other.
+ expect(await dee.syncer.syncWith(dee2.machineId!)).toBe(true)
+ // And the team daemon, which places nobody, sends its roster to none of them.
+ expect(await team.syncer.syncWith(dee.machineId!)).toBe(false)
+ for (const n of f.nodes) n.syncer.stop()
+ })
+
+ it('fails closed when the account\'s machine list cannot say what a machine is, and takes a phone as before', async () => {
+ vi.useFakeTimers()
+ const f = fleet()
+ const [a, b] = [f.add('a'), f.add('b')]
+ const phone = f.add('p', false)
+ f.link(a, b)
+ f.link(phone, a)
+ a.kindOf = null
+ b.kindOf = null
+ const handle = vi.spyOn(b.syncer, 'handle')
+ expect(await a.syncer.syncWith(b.machineId!)).toBe(false)
+ await a.syncer.syncAll()
+ expect(handle).not.toHaveBeenCalled()
+ const self = { pub: a.pub, kind: 'machine', label: 'a', machineId: a.machineId, at: S.SELF_STAMP }
+ expect(b.syncer.handle(a.pub, { self, members: [], removed: [] })).toEqual({ error: 'MACHINE_UNKNOWN' })
+ // A machine key with no machine id anywhere is not taken for an app.
+ const stray = C.b64e(C.newIdentity().pub)
+ expect(b.syncer.handle(stray, { self: { pub: stray, kind: 'machine', label: 's', at: S.SELF_STAMP }, members: [], removed: [] }))
+ .toEqual({ error: 'MACHINE_UNKNOWN' })
+ // A phone is no machine: its roster is merged and it is answered, list or not.
+ const reply = a.syncer.handle(phone.pub, { self: { pub: phone.pub, kind: 'viewer', label: 'p', at: S.SELF_STAMP }, members: [], removed: [] })
+ expect(reply.error).toBeUndefined()
+ expect((reply.members as Array<{ pub: string }>).map((m) => m.pub)).toContain(b.pub)
+ // Once the list says both are the person's own, they swap again.
+ a.kindOf = 'computer'
+ b.kindOf = 'computer'
+ expect(await a.syncer.syncWith(b.machineId!)).toBe(true)
+ for (const n of f.nodes) n.syncer.stop()
+ })
+
it('A links B, A links C ⇒ B and C reach each other both ways, no password', async () => {
vi.useFakeTimers()
const f = fleet()
diff --git a/cli/src/lib/e2ee/groupSyncer.ts b/cli/src/lib/e2ee/groupSyncer.ts
index a23c01870..186e10158 100644
--- a/cli/src/lib/e2ee/groupSyncer.ts
+++ b/cli/src/lib/e2ee/groupSyncer.ts
@@ -13,9 +13,16 @@
* of this: rosters are not exchanged with it, it is not seeded from its pin or its trust, and a
* `group_sync` from it is refused. Otherwise sharing one machine would make the colleague's other
* machines trusted here, and this account's trusted by theirs.
+ *
+ * Nor is one of the account's team machines (machineKinds.ts): a Harness Team account's daemon, or a computer
+ * that runs team work only, runs teammates' agents, so a hostile one could otherwise add or drop the keys this
+ * machine trusts. It stays pinned and trusted, so the person's apps still reach it, but its roster is never
+ * merged and this one is never sent to it. A machine whose kind the account's machine list cannot say is
+ * treated the same way.
*/
import type { Frame, LocalClientSink } from '../../backendSocket.js'
import type { RelaySession } from '../remoteRelay.js'
+import type { MachineKind } from './machineKinds.js'
import type { MachinePeerStore } from './machinePeers.js'
import type { LinkedPeer } from './manager.js'
import type { PairedClient } from './store.js'
@@ -66,6 +73,9 @@ export interface GroupSyncerDeps {
/** Whether `pub` is a machine of another account trusted only because it is shared with this one (or this
* one with it): it never takes part in the group. */
shared?: (pub: string) => boolean
+ /** What the account's machine list says a machine is (machineKinds.ts): only `computer`, one of the person's own,
+ * takes part in the group. `team` and unknown (null) never do. `fresh` reads the list again when it is old. */
+ machineKinds: { kind: (machineId: string) => MachineKind | null; fresh?: () => Promise<void> }
/** Whether the roster here is the account's this machine is signed in to (deviceLogSyncer `current`).
* While not, nothing is swapped: a daemon started after a switch of accounts read the new account's
* log only after its first rounds, and handed the roster of the account it left to the new one's
@@ -208,6 +218,8 @@ export class GroupSyncer {
/** Responder side of `group_sync`, for a sealed request from the session identity `peerPub`. */
handle(peerPub: string, payload: Record<string, unknown>): Record<string, unknown> {
if (this.deps.shared?.(peerPub)) return { error: 'SHARED' }
+ const refused = this.machinePeerRefusal(peerPub, payload.self)
+ if (refused) return { error: refused }
if (this.deps.ready?.() === false) {
const none: Roster = { members: [], removed: [] }
return { ...none, digest: rosterDigest(none) }
@@ -240,6 +252,7 @@ export class GroupSyncer {
/** Every reachable machine member (and every machine pinned outside the roster), one at a time. */
async syncAll(): Promise<void> {
if (this.deps.ready?.() === false) { this.retryLater(); return }
+ await this.deps.machineKinds.fresh?.().catch(() => { /* an old list ages out on its own */ })
// Put back any pin the relay dropped. A member can hear of another before that one hears of it,
// and its first dial is then refused — remoteRelay.ts unlinks a peer that answers e2e_denied. The
// roster still says they belong together, so they are re-pinned and tried again on this round.
@@ -251,6 +264,8 @@ export class GroupSyncer {
for (const m of this.deps.store.read().members) if (m.kind === 'machine' && m.machineId && !suspended.has(m.pub)) targets.add(m.machineId)
for (const p of this.deps.peers.list()) if (!suspended.has(p.pub) && !p.shared) targets.add(p.machineId)
if (self) targets.delete(self)
+ // A team machine, or one the account's list cannot place, is not dialed: not a member that missed this round.
+ for (const machineId of targets) if (!this.ordinary(machineId)) targets.delete(machineId)
// All at once: one machine that never answers (offline, or too old to know the frame) must not
// hold up the rest for its whole timeout.
const due = [...targets].filter((machineId) => !reachable || reachable.has(machineId))
@@ -269,9 +284,12 @@ export class GroupSyncer {
}
private async exchange(machineId: string): Promise<boolean> {
- const pin = this.deps.peers.get(machineId)
- if (!pin || pin.shared || this.deps.ready?.() === false) return false
+ if (!this.deps.peers.get(machineId) || this.deps.ready?.() === false) return false
const generation = this.generation
+ await this.deps.machineKinds.fresh?.().catch(() => { /* an old list ages out on its own */ })
+ const pin = this.deps.peers.get(machineId)
+ // Nothing is sent to a team machine, or to one the account's list cannot place: this roster is not theirs to read.
+ if (!pin || pin.shared || this.deps.ready?.() === false || generation !== this.generation || !this.ordinary(machineId)) return false
const local = this.deps.store.read()
const devlog = this.devlog?.gossip()
const reply = await this.deps.request(machineId, {
@@ -318,6 +336,42 @@ export class GroupSyncer {
private selfPub(): string { return this.deps.self().pub }
+ /** Whether the account's machine list says [machineId] is one of the person's own machines. */
+ private ordinary(machineId: string): boolean {
+ return this.deps.machineKinds.kind(machineId) === 'computer'
+ }
+
+ /**
+ * Why a `group_sync` from `peerPub` is refused, or null when it may go on. A machine is known by every machine id
+ * this one holds for its key (its pin, its roster entry, its pairing) and by the one it gives for itself, and each
+ * must be one of the person's own: a team machine cannot get in by describing itself as an app, or as another
+ * machine. A peer no record or word of its own makes a machine (a phone, a desktop app) is not a machine at all.
+ */
+ private machinePeerRefusal(peerPub: string, claimedSelf: unknown): 'TEAM_MACHINE' | 'MACHINE_UNKNOWN' | null {
+ const ids = new Set<string>()
+ let machine = false
+ for (const p of this.deps.peers.list()) if (p.pub === peerPub) { ids.add(p.machineId); machine = true }
+ for (const m of this.deps.store.read().members) {
+ if (m.pub !== peerPub) continue
+ if (m.kind === 'machine') machine = true
+ if (m.machineId) ids.add(m.machineId)
+ }
+ for (const p of this.deps.paired()) {
+ if (p.identityPub !== peerPub) continue
+ if (p.kind === 'machine') machine = true
+ if (p.machineId) ids.add(p.machineId)
+ }
+ const self = claimedSelf && typeof claimedSelf === 'object' ? claimedSelf as Record<string, unknown> : null
+ if (self?.pub === peerPub) {
+ if (self.kind === 'machine') machine = true
+ if (typeof self.machineId === 'string' && self.machineId) ids.add(self.machineId)
+ }
+ if (ids.size === 0) return machine ? 'MACHINE_UNKNOWN' : null
+ const kinds = [...ids].map((id) => this.deps.machineKinds.kind(id))
+ if (kinds.includes('team')) return 'TEAM_MACHINE'
+ return kinds.every((kind) => kind === 'computer') ? null : 'MACHINE_UNKNOWN'
+ }
+
/** Links made before the group existed: every pinned machine and every paired peer that said what it is. */
private seedFromExistingLinks(): void {
const seed: GroupMember[] = []
diff --git a/cli/src/lib/e2ee/machineKinds.spec.ts b/cli/src/lib/e2ee/machineKinds.spec.ts
new file mode 100644
index 000000000..81922191b
--- /dev/null
+++ b/cli/src/lib/e2ee/machineKinds.spec.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it, vi } from 'vitest'
+import { MACHINE_KINDS_MAX_AGE_MS, MACHINE_KINDS_REFRESH_MS, MachineKinds, machineKindsOf } from './machineKinds.js'
+
+describe('machineKindsOf', () => {
+ it('reads each machine\'s sessionKind, taking a row from before team sessions as the person\'s own', () => {
+ const kinds = machineKindsOf({ success: true, data: { machines: [
+ { machineId: 'm-team', sessionKind: 'team' }, { machineId: 'm-own', sessionKind: 'computer' },
+ { machineId: 'm-old', sessionKind: null }, { machineId: 'm-older' }, { machineId: 'm-odd', sessionKind: 'phone' },
+ { machineId: '' }, null, 'm-text',
+ ] } })
+ expect(kinds).toEqual(new Map([['m-team', 'team'], ['m-own', 'computer'], ['m-old', 'computer'], ['m-older', 'computer']]))
+ expect(machineKindsOf({ machines: [{ machineId: 'x', sessionKind: 'team' }] })).toEqual(new Map([['x', 'team']]))
+ })
+
+ it('takes a machine listed twice at its stricter kind, and a body with no list as nothing', () => {
+ expect(machineKindsOf({ machines: [{ machineId: 'x', sessionKind: 'team' }, { machineId: 'x', sessionKind: 'computer' }] })?.get('x')).toBe('team')
+ expect(machineKindsOf({ machines: [{ machineId: 'x', sessionKind: 'computer' }, { machineId: 'x', sessionKind: 'team' }] })?.get('x')).toBe('team')
+ for (const body of [null, undefined, 'x', {}, { data: null }, { data: { machines: {} } }]) expect(machineKindsOf(body)).toBeNull()
+ })
+})
+
+describe('MachineKinds', () => {
+ const list = (kind: unknown) => ({ data: { machines: [{ machineId: 'm1', sessionKind: kind }] } })
+
+ it('knows nothing until a list is read, then goes by it until it is too old', async () => {
+ let now = 1_000
+ const read = vi.fn(async (): Promise<unknown> => list('computer'))
+ const kinds = new MachineKinds({ read, now: () => now })
+ expect(kinds.kind('m1')).toBeNull()
+ await kinds.fresh()
+ expect(kinds.kind('m1')).toBe('computer')
+ expect(kinds.kind('m2')).toBeNull()
+ now += MACHINE_KINDS_MAX_AGE_MS + 1
+ expect(kinds.kind('m1')).toBeNull()
+ })
+
+ it('reads again only once the list is old, one read at a time, and keeps the last list when a read fails', async () => {
+ let now = 1_000
+ const read = vi.fn(async (): Promise<unknown> => list('computer'))
+ const kinds = new MachineKinds({ read, now: () => now })
+ await Promise.all([kinds.fresh(), kinds.fresh()])
+ expect(read).toHaveBeenCalledTimes(1)
+ await kinds.fresh()
+ expect(read).toHaveBeenCalledTimes(1)
+ now += MACHINE_KINDS_REFRESH_MS
+ read.mockRejectedValueOnce(new Error('offline'))
+ await kinds.fresh()
+ expect(read).toHaveBeenCalledTimes(2)
+ expect(kinds.kind('m1')).toBe('computer')
+ read.mockResolvedValueOnce(null)
+ await kinds.fresh()
+ expect(kinds.kind('m1')).toBe('computer')
+ read.mockResolvedValueOnce(list('team'))
+ await kinds.fresh()
+ expect(kinds.kind('m1')).toBe('team')
+ })
+
+ it('takes a list the gateway read for the apps, and forgets everything on a sign-out, a read on its way included', async () => {
+ let release: (body: unknown) => void = () => {}
+ const kinds = new MachineKinds({ read: () => new Promise((resolve) => { release = resolve }) })
+ kinds.adopt(list('team'))
+ expect(kinds.kind('m1')).toBe('team')
+ kinds.adopt({ nothing: true })
+ expect(kinds.kind('m1')).toBe('team')
+ kinds.clear()
+ expect(kinds.kind('m1')).toBeNull()
+ const reading = kinds.fresh()
+ kinds.clear()
+ release(list('computer'))
+ await reading
+ expect(kinds.kind('m1')).toBeNull()
+ })
+})
diff --git a/cli/src/lib/e2ee/machineKinds.ts b/cli/src/lib/e2ee/machineKinds.ts
new file mode 100644
index 000000000..81981c68e
--- /dev/null
+++ b/cli/src/lib/e2ee/machineKinds.ts
@@ -0,0 +1,86 @@
+/**
+ * Which of the account's machines are team machines (docs/plans/2026-10-24-swarm-team-account.md), as the account's
+ * machine list says: `GET /api/machines` gives each machine's `sessionKind`, `team` for a Harness Team account's daemon
+ * or a computer that runs team work only (`harness team on`), `computer` for one of the person's own. A row with none
+ * is from before team sessions, and is the person's own.
+ *
+ * A team daemon runs teammates' agents. It is the account's machine, so the person's apps reach it, but it is no more
+ * trusted than a machine shared from another account: its roster must never change the keys the person's own machines
+ * trust, and theirs is not sent to it (groupSyncer.ts). So a machine whose kind cannot be read — no list from the
+ * backend yet, a list too old to go by, a machine the list does not hold — is treated as one that may not take part.
+ */
+export type MachineKind = 'team' | 'computer'
+
+/** A list is read again before a round once it is this old. */
+export const MACHINE_KINDS_REFRESH_MS = 60_000
+/** Past this, a list says nothing: a machine converted to team work since must not still count as the person's own. */
+export const MACHINE_KINDS_MAX_AGE_MS = 15 * 60_000
+
+/** Each machine's kind in a `GET /api/machines` body (`{ machines }` or `{ data: { machines } }`); null when it holds no
+ * list. A machine whose `sessionKind` is neither of the known values is left out, so it reads as unknown. */
+export function machineKindsOf(body: unknown): Map<string, MachineKind> | null {
+ const top = body && typeof body === 'object' ? body as Record<string, unknown> : null
+ const data = top?.data && typeof top.data === 'object' ? top.data as Record<string, unknown> : null
+ const rows = top?.machines ?? data?.machines
+ if (!Array.isArray(rows)) return null
+ const kinds = new Map<string, MachineKind>()
+ for (const raw of rows) {
+ const row = raw && typeof raw === 'object' ? raw as Record<string, unknown> : null
+ if (typeof row?.machineId !== 'string' || !row.machineId) continue
+ const kind = row.sessionKind === 'team' ? 'team' : row.sessionKind === 'computer' || row.sessionKind === undefined || row.sessionKind === null ? 'computer' : null
+ // One machine listed twice is taken at its stricter kind.
+ if (kind && kinds.get(row.machineId) !== 'team') kinds.set(row.machineId, kind)
+ }
+ return kinds
+}
+
+export interface MachineKindsDeps {
+ /** The account's machine list as the backend answered it; null when it could not be read (offline, signed out). */
+ read: () => Promise<unknown>
+ now?: () => number
+}
+
+/** The last machine list read, and reading it again when it is old. */
+export class MachineKinds {
+ private kinds: Map<string, MachineKind> | null = null
+ private readAt = 0
+ private reading: Promise<void> | null = null
+ private generation = 0
+ private readonly now: () => number
+
+ constructor(private readonly deps: MachineKindsDeps) {
+ this.now = deps.now ?? Date.now
+ }
+
+ /** A list the backend just answered (the gateway's own machine list, read for the apps). */
+ adopt(body: unknown): void {
+ const kinds = machineKindsOf(body)
+ if (!kinds) return
+ this.kinds = kinds
+ this.readAt = this.now()
+ }
+
+ /** Signed out, or another account: nothing is known any more, and a read on its way is not taken. */
+ clear(): void {
+ this.kinds = null
+ this.readAt = 0
+ this.generation++
+ }
+
+ /** What the list says [machineId] is; null when it cannot say. */
+ kind(machineId: string): MachineKind | null {
+ if (!this.kinds || this.now() - this.readAt > MACHINE_KINDS_MAX_AGE_MS) return null
+ return this.kinds.get(machineId) ?? null
+ }
+
+ /** Read the list again unless it is recent; one read at a time. Never throws. */
+ fresh(): Promise<void> {
+ if (this.kinds && this.now() - this.readAt < MACHINE_KINDS_REFRESH_MS) return Promise.resolve()
+ if (this.reading) return this.reading
+ const generation = this.generation
+ this.reading = this.deps.read()
+ .then((body) => { if (generation === this.generation && body !== null) this.adopt(body) }, () => { /* the last list stands, until it is too old */ })
+ .finally(() => { this.reading = null })
+ return this.reading
+ }
+}
diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.ts
index 81c308507..8e6d5dff8 100644
--- a/cli/src/lib/e2ee/store.ts
+++ b/cli/src/lib/e2ee/store.ts
@@ -24,6 +24,17 @@ export function peekIdentityPub(): string | null {
} catch { return null }
}
+/** This computer's identity keypair as already on disk, or null. Like `peekIdentityPub` it never creates one: a key
+ * made by a command that only needs to sign with the existing one would be on no device key log. */
+export function peekIdentity(): Identity | null {
+ try {
+ const raw = JSON.parse(readFileSync(IDENTITY_FILE, 'utf-8')) as { priv?: unknown; pub?: unknown }
+ if (typeof raw.priv !== 'string' || typeof raw.pub !== 'string' || !raw.priv || !raw.pub) return null
+ const identity = { priv: b64d(raw.priv), pub: b64d(raw.pub) }
+ return identity.priv.length === 32 && identity.pub.length === 32 ? identity : null
+ } catch { return null }
+}
+
/** Whether an identity was retired here (`identity.json.removed-*`, left by signing this device out of
* the account), so "no identity" can be told apart from "never had one". */
export function identitySpent(): boolean {
diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.ts
index 330a31de7..85e7bfe62 100644
--- a/cli/src/lib/gitProject.spec.ts
+++ b/cli/src/lib/gitProject.spec.ts
@@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'
import { placeholderBranch, sessionBranchNames, worktreeFolderName } from './agentNames.js'
import { nameBranchAfterSession } from './branchNaming.js'
-import { prepareGitProject, readGitProject, validGitPath } from './gitProject.js'
+import { fetchDefaultBranch, prepareGitProject, readGitProject, validGitPath } from './gitProject.js'
import { parseProjectFolder, prepareProjectFolder } from './projectFolder.js'
import { engineSessionTitle, namingTitle } from './sessionTitle.js'
@@ -412,6 +412,35 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
expect(await swarmStart()).toBe('pushed')
})
+ it('fetches nothing for another person\'s Swarm start: its host fetched with the app\'s token, and the worktree starts from that', async () => {
+ const before = await inClone('rev-parse', 'refs/remotes/origin/main')
+ await pushToOrigin('pushed')
+ // The daemon's own git setup is never asked: offline, the worktree starts from what the checkout has.
+ const offline = await prepareProjectFolder({ source: 'worktree', gitSource: managed, branchName: 'super-tab/start-1', fromDefaultBranch: true, offline: true }, options())
+ expect(await readFile(join(offline, 'src', 'value'), 'utf8')).toBe('main')
+ expect(await inClone('rev-parse', 'refs/remotes/origin/main')).toBe(before)
+ // Only the daemon sets it: a client cannot ask for it.
+ expect(parseProjectFolder({ projectSource: 'worktree', gitSource: managed, branchBase: 'default', offline: true })).not.toHaveProperty('offline')
+ // The host's fetch, with the environment it is given in place of the daemon's.
+ const env = { ...process.env, GIT_CONFIG_PARAMETERS: `'harness.fixture'='yes'` }
+ expect(await fetchDefaultBranch(managed, env)).toBe(true)
+ expect(await inClone('rev-parse', 'refs/remotes/origin/main')).not.toBe(before)
+ const folder = await prepareProjectFolder({ source: 'worktree', gitSource: managed, branchName: 'super-tab/start-2', fromDefaultBranch: true, offline: true }, options())
+ expect(await readFile(join(folder, 'src', 'value'), 'utf8')).toBe('pushed')
+ })
+
+ it('a host\'s fetch does nothing outside a checkout or without a default branch, and says when it could not fetch', async () => {
+ expect(await fetchDefaultBranch('relative/path', process.env)).toBe(false)
+ expect(await fetchDefaultBranch(join(root, 'nowhere'), process.env)).toBe(false)
+ const local = join(root, 'no-remote')
+ await mkdir(local)
+ await exec('git', ['-C', local, 'init', '-q', '-b', 'trunk'])
+ await exec('git', ['-C', local, ...identity, 'commit', '-q', '--allow-empty', '-m', 'initial'])
+ expect(await fetchDefaultBranch(local, process.env)).toBe(false)
+ await inClone('remote', 'set-url', 'origin', join(root, 'gone.git'))
+ expect(await fetchDefaultBranch(managed, process.env)).toBe(false)
+ })
+
it('starts from the branch it is given, not the default one', async () => {
await pushToOrigin('pushed')
expect(await swarmStart({ branchBase: undefined, branchRef: 'refs/remotes/origin/feature' })).toBe('feature')
diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.ts
index cfecf17d5..7e0dad93b 100644
--- a/cli/src/lib/gitProject.ts
+++ b/cli/src/lib/gitProject.ts
@@ -23,8 +23,10 @@ export function validGitPath(path: unknown): path is string {
return typeof path === 'string' && isAbsolute(path) && path.length <= 4096 && !/[\x00-\x1f\x7f]/.test(path)
}
-async function git(path: string, args: string[], timeout = 4000): Promise<string> {
- const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_OPTIONAL_LOCKS: '0' }
+/** [base]: the environment git starts from, the daemon's own unless a caller gives the one it must use instead
+ * (lib/swarmGitHub.ts `swarmGitPrepareEnv`). */
+async function git(path: string, args: string[], timeout = 4000, base: NodeJS.ProcessEnv = process.env): Promise<string> {
+ const env = { ...base, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_OPTIONAL_LOCKS: '0' }
for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (env as NodeJS.ProcessEnv)[key]
// core.fsmonitor names a program git runs on status/diff; a repository's own config must not choose
// one for the daemon (same guard as projectPreview.ts).
@@ -201,6 +203,19 @@ async function originDefaultRef(path: string): Promise<string | null> {
return null
}
+/**
+ * Brings the remote's default branch up to date in [source], with [env]'s git setup instead of the daemon's: a Swarm
+ * host's fetch with the Harness GitHub App's token (lib/swarmGitHub.ts `swarmGitPrepareEnv`), before the worktree starts
+ * from it. True when it fetched. Offline, slow or refused, the worktree starts from what is here, as `prepareGitProject`'s
+ * own fetch does; a repository with no `origin` default branch has nothing to fetch.
+ */
+export async function fetchDefaultBranch(source: string, env: NodeJS.ProcessEnv): Promise<boolean> {
+ if (!validGitPath(source) || !(await insideGitCheckout(source))) return false
+ const remote = remoteBranch(await originDefaultRef(source) ?? undefined)
+ if (!remote) return false
+ return git(source, ['fetch', '--quiet', '--no-tags', remote.remote, remote.refspec], 60_000, env).then(() => true, () => false)
+}
+
export type GitProjectOptions = {
root: string
worktree: boolean
@@ -210,6 +225,10 @@ export type GitProjectOptions = {
* from wherever `HEAD` is. A checkout nobody works in (a Swarm host's clone) stays where it was cloned, days
* behind. Only a Swarm start asks for it; a repository with no `origin` default branch starts from `HEAD`. */
fromDefaultBranch?: boolean
+ /** Fetch nothing: start from what the checkout already has. A Swarm start doing another person's work: its host
+ * fetched with the Harness GitHub App's token just before (`fetchDefaultBranch`), and this machine's own git
+ * login must not be used for it. */
+ offline?: boolean
/** The worktree's branch: created from `ref`, or with `existingBranch` checked out as it is. */
branchName?: string
existingBranch?: boolean
@@ -255,7 +274,7 @@ export async function prepareGitProject(source: string, options: GitProjectOptio
const upstream = options.worktree && !existing && !remote && ref
? await git(source, ['for-each-ref', '--format=%(upstream)', ref]).then(found => remoteBranch(found) ? found : null, () => null)
: null
- const fetch = remote ?? remoteBranch(upstream ?? undefined)
+ const fetch = options.offline ? null : remote ?? remoteBranch(upstream ?? undefined)
if (fetch) await git(source, ['fetch', '--quiet', '--no-tags', fetch.remote, fetch.refspec], 10_000).catch(() => '')
// Behind or level with its upstream: the upstream is the newer.
if (upstream && ref && await git(source, ['merge-base', '--is-ancestor', ref, upstream]).then(() => true, () => false)) {
diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.ts
index bc2232fc9..00843c76a 100644
--- a/cli/src/lib/projectFolder.ts
+++ b/cli/src/lib/projectFolder.ts
@@ -12,7 +12,9 @@ import type { ScmLaunchRecord } from '../scm/types.js'
* harness and the time. `suggested` marks a name the app made up (from the first task — the phone has
* no name field), which is numbered past a folder that exists rather than refused. */
export type ProjectFolder = { source: 'new'; name?: string; suggested?: boolean } | { source: 'remote'; repositoryUrl: string; name: string }
- | { source: 'worktree'; gitSource: string; branchRef?: string; branchName?: string; existingBranch?: boolean; placeholder?: boolean; fromDefaultBranch?: boolean }
+ | { source: 'worktree'; gitSource: string; branchRef?: string; branchName?: string; existingBranch?: boolean; placeholder?: boolean; fromDefaultBranch?: boolean
+ /** Fetch nothing (gitProject.ts `offline`): set by the daemon for a Swarm start doing another person's work, never by a client. */
+ offline?: boolean }
| { source: 'branch'; gitSource: string; branchRef?: string; branchName?: string }
/** Where this daemon and the desktop app put the workspaces they make. A folder directly inside it is
@@ -155,7 +157,10 @@ export async function prepareProjectFolder(
project: ProjectFolder,
options: {
root?: string
- clone?: (url: string, destination: string) => Promise<void>
+ clone?: (url: string, destination: string, env?: NodeJS.ProcessEnv) => Promise<void>
+ /** The environment a clone's git runs in instead of the daemon's own: a Swarm host's, with the Harness GitHub App's
+ * token for the project (lib/swarmGitHub.ts `swarmGitPrepareEnv`). */
+ gitEnv?: NodeJS.ProcessEnv
/** Who the harness is ("Codex", "Blender"): a new project folder is named after it and the time. */
label?: string | null
now?: () => Date
@@ -173,7 +178,7 @@ export async function prepareProjectFolder(
// The isolated-workspace path, through the SCM seam. The git implementation makes exactly the
// prepareGitProject call this used to make.
const { cwd, launchRecord } = await scmByKind('git')!.prepareIsolated(project.gitSource, {
- root, base: project.branchRef, ...(project.fromDefaultBranch ? { fromDefaultBranch: true } : {}),
+ root, base: project.branchRef, ...(project.fromDefaultBranch ? { fromDefaultBranch: true } : {}), ...(project.offline ? { offline: true } : {}),
...(project.branchName ? { name: project.branchName, existing: project.existingBranch === true, placeholder: project.placeholder === true } : {}),
})
options.onPrepared?.({ cwd, scmLaunchRecord: launchRecord })
@@ -233,7 +238,7 @@ export async function prepareProjectFolder(
}
staging = await mkdtemp(join(root, '.harness-clone-'))
const checkout = join(staging, 'checkout')
- await (options.clone ?? cloneRepository)(project.repositoryUrl, checkout)
+ await (options.clone ?? cloneRepository)(project.repositoryUrl, checkout, options.gitEnv)
if (await exists(destination)) {
// Another start cloned the same repository meanwhile: that one is kept and this staging goes (below).
if (await holdsRepository(destination, project.repositoryUrl)) return destination
@@ -252,12 +257,13 @@ export async function prepareProjectFolder(
/** No shell interpolation or interactive password prompt. Diagnostics stay
* bounded and private; only actionable, credential-free messages reach the UI. */
-function cloneRepository(url: string, destination: string): Promise<void> {
+function cloneRepository(url: string, destination: string, gitEnv?: NodeJS.ProcessEnv): Promise<void> {
return new Promise((resolve, reject) => {
+ const base = gitEnv ?? process.env
const child = spawn('git', ['clone', '--', url, destination], {
stdio: ['ignore', 'ignore', 'pipe'],
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never',
- GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes -oConnectTimeout=20' },
+ env: { ...base, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never',
+ GIT_SSH_COMMAND: base.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes -oConnectTimeout=20' },
})
let diagnostic = '', timedOut = false
let forceKill: ReturnType<typeof setTimeout> | undefined
diff --git a/cli/src/lib/swarmGitHub.spec.ts b/cli/src/lib/swarmGitHub.spec.ts
index 6561a6fc0..518925720 100644
--- a/cli/src/lib/swarmGitHub.spec.ts
+++ b/cli/src/lib/swarmGitHub.spec.ts
@@ -3,7 +3,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, st
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, describe, expect, it } from 'vitest'
-import { GIT_HOOK_NAMES, gitConfigParameters, shellWord, swarmGitHubLaunch, swarmGitHubSessionDir, writeSessionGitHub, writeSwarmGitHubTools } from './swarmGitHub.js'
+import { GIT_HOOK_NAMES, gitConfigParameters, shellWord, swarmGitHubLaunch, swarmGitHubSessionDir, swarmGitPrepareEnv, writeSessionGitHub, writeSwarmGitHubTools } from './swarmGitHub.js'
// Real git against folders made here, with a home of its own and no system config: never this machine's git settings,
// and nothing reaches github.com (only `git credential fill` and `git ls-remote --get-url`, which make no connection).
@@ -48,6 +48,33 @@ describe('git configuration for a Swarm session', () => {
})
describe('the shared helper and hooks', () => {
+ it('prepares a Swarm folder with the app\'s token alone: none of the owner\'s git setup, ssh over https, and nothing on a command line', () => {
+ const dir = fresh('prepare')
+ const ownerLog = join(dir, 'owner.log')
+ const owner = script(join(dir, 'owner-helper'), `echo "$1" >> '${ownerLog}'\n[ "$1" = get ] && printf 'username=owner\\npassword=owner-secret\\n'`)
+ // An owner whose global config has a credential helper and sends github.com over their own ssh key.
+ const ownerHome = fresh('owner-home')
+ writeFileSync(join(ownerHome, '.gitconfig'), `[credential]\n\thelper = ${owner}\n[url "[email protected]:"]\n\tinsteadOf = https://github.com/\n`)
+ const token = `ghs_${'t'.repeat(36)}`
+ const env = swarmGitPrepareEnv(token, { PATH: process.env.PATH!, HOME: ownerHome, GIT_ASKPASS: '/owner/askpass', GIT_CONFIG_COUNT: '1',
+ GIT_CONFIG_KEY_0: 'credential.helper', GIT_CONFIG_VALUE_0: owner, GH_TOKEN: 'owner-gh-token', GIT_SSH_COMMAND: 'ssh -i /owner/key' })
+ for (const key of ['GIT_ASKPASS', 'GIT_CONFIG_COUNT', 'GIT_CONFIG_KEY_0', 'GIT_CONFIG_VALUE_0', 'GH_TOKEN']) expect(env).not.toHaveProperty(key)
+ expect(env.GIT_SSH_COMMAND).not.toContain('/owner/key')
+ expect(env.GIT_CONFIG_PARAMETERS).not.toContain(token)
+ const run = (args: string[], input?: string) => spawnSync('git', args, { cwd: dir, input, encoding: 'utf8', env: env as Record<string, string> })
+ const filled = run(['credential', 'fill'], 'url=https://github.com/acme/app.git\n\n')
+ expect(filled.status).toBe(0)
+ expect(filled.stdout).toContain('username=x-access-token')
+ expect(filled.stdout).toContain(`password=${token}`)
+ expect(existsSync(ownerLog)).toBe(false)
+ // The owner's rewrite to ssh is not read; ssh addresses of github.com go over https.
+ expect(run(['ls-remote', '--get-url', 'https://github.com/acme/app.git']).stdout.trim()).toBe('https://github.com/acme/app.git')
+ expect(run(['ls-remote', '--get-url', '[email protected]:acme/app.git']).stdout.trim()).toBe('https://github.com/acme/app.git')
+ expect(run(['config', '--get-all', 'credential.helper']).stdout).not.toContain('owner-helper')
+ // A token not in GitHub's form is refused before any git runs with it.
+ expect(() => swarmGitPrepareEnv('not a token; rm -rf /')).toThrow('not in the form GitHub gives')
+ })
+
it('writes the helper for this daemon\'s CLI and one hook for every hook git runs, private to its user, once', () => {
const dataDir = fresh('data')
const { helper, hooks } = writeSwarmGitHubTools({ dataDir, command: "'/opt/node' '/opt/harness/cli.js'", port: 18500, machineId: 'machine-1' })
diff --git a/cli/src/lib/swarmGitHub.ts b/cli/src/lib/swarmGitHub.ts
index f6434a807..9a1f5e506 100644
--- a/cli/src/lib/swarmGitHub.ts
+++ b/cli/src/lib/swarmGitHub.ts
@@ -57,6 +57,45 @@ export function gitConfigParameters(helper: string, hooks: string): string {
return entries.map(([key, value]) => `${shellWord(key)}=${shellWord(value)}`).join(' ')
}
+/**
+ * The environment for the git a machine runs itself to prepare a Swarm agent's folder before the agent exists: the clone
+ * and the fetch of the default branch (superTabs/projectFolder.ts), with [token], a read-only Harness GitHub App token for
+ * the project's one repository. Nothing of the machine owner's git setup takes part: their global and system config are
+ * not read (credential helpers, a rewrite of https to ssh, an http header), the helpers git has so far are emptied for
+ * Harness's alone, ssh remotes of github.com go over https, and nothing prompts. The token is in this environment only,
+ * read by the helper from `HARNESS_SWARM_GIT_TOKEN`, never written to disk or put on a command line.
+ */
+export function swarmGitPrepareEnv(token: string, base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
+ if (!TOKEN.test(token)) throw new Error('The Harness GitHub App token is not in the form GitHub gives.')
+ const env: NodeJS.ProcessEnv = { ...base }
+ // Config from the environment, a prompt program, or an ssh setup of the owner's would put their login back in.
+ for (const key of Object.keys(env)) if (/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(key)) delete env[key]
+ for (const key of ['GIT_CONFIG_COUNT', 'GIT_CONFIG', 'GIT_ASKPASS', 'SSH_ASKPASS', 'GIT_SSH', 'GIT_SSH_COMMAND', 'GIT_DIR', 'GIT_WORK_TREE',
+ ...SWARM_GITHUB_CLEAR_ENV]) delete env[key]
+ const helper = '!f() { test "$1" = get || return 0; echo username=x-access-token; echo "password=$HARNESS_SWARM_GIT_TOKEN"; }; f'
+ const entries: Array<[string, string]> = [
+ ['credential.helper', ''],
+ ['credential.https://github.com.helper', ''],
+ ['credential.https://github.com.helper', helper],
+ ['url.https://github.com/.insteadof', '[email protected]:'],
+ ['url.https://github.com/.insteadof', 'ssh://[email protected]/'],
+ // Large files still arrive as git-lfs would bring them, when it is installed: its filter is in the global config skipped above.
+ ['filter.lfs.process', 'git-lfs filter-process'],
+ ['filter.lfs.clean', 'git-lfs clean -- %f'],
+ ['filter.lfs.smudge', 'git-lfs smudge -- %f'],
+ ]
+ return {
+ ...env,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_CONFIG_PARAMETERS: entries.map(([key, value]) => `${shellWord(key)}=${shellWord(value)}`).join(' '),
+ GIT_TERMINAL_PROMPT: '0',
+ GCM_INTERACTIVE: 'Never',
+ GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oConnectTimeout=20',
+ HARNESS_SWARM_GIT_TOKEN: token,
+ }
+}
+
export function credentialHelperScript(input: { command: string; port: number; machineId: string; dataDir: string }): string {
return '#!/bin/sh\n'
+ '# Written by Harness for Swarm agents\' git (docs/swarm-github-app.md); rewritten as agents start.\n'
diff --git a/cli/src/scm/gitScmProject.ts b/cli/src/scm/gitScmProject.ts
index 105e50c03..f20ac62b9 100644
--- a/cli/src/scm/gitScmProject.ts
+++ b/cli/src/scm/gitScmProject.ts
@@ -30,6 +30,7 @@ export class GitScmProject implements ScmProject {
const cwd = await prepareGitProject(source, {
root: options.root, worktree: true, ref: options.base,
...(options.fromDefaultBranch ? { fromDefaultBranch: true } : {}),
+ ...(options.offline ? { offline: true } : {}),
...(options.name !== undefined ? {
branchName: options.name, existingBranch: options.existing === true, placeholder: options.placeholder === true,
} : {}),
diff --git a/cli/src/scm/types.ts b/cli/src/scm/types.ts
index 6b8816310..2f0095395 100644
--- a/cli/src/scm/types.ts
+++ b/cli/src/scm/types.ts
@@ -70,6 +70,9 @@ export interface PrepareOptions {
/** No `base` was named: start from the remote's default branch, brought up to date first, instead of from where
* the source checkout is (git: `origin`'s default branch, fetched). Absent: the SCM's own default. */
fromDefaultBranch?: boolean
+ /** Bring nothing up to date over the network: start from what the source checkout has. A Swarm start doing another
+ * person's work, whose host already fetched with the Harness GitHub App's token (lib/swarmGitHub.ts). */
+ offline?: boolean
/** The name the workspace's line of work takes — git: its branch. Absent: made up. */
name?: string
/** `name` exists already and is taken as it is, rather than created from `base`. */
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index 48c00c113..92c29ab1a 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -79,6 +79,32 @@ describe('contributed machine executor', () => {
expect(f.prepare).toHaveBeenCalledTimes(2)
expect(f.start).toHaveBeenCalledTimes(2)
})
+ it('starts another person\'s work with the app for whom it is, and fails a start whose token cannot be had', async () => {
+ const f = fixture()
+ f.prepare.mockResolvedValueOnce({ requester: '[email protected]' } as never)
+ await f.machine.tick()
+ expect((f.start.mock.calls as unknown[][])[0]![0]).toEqual({ tabId: 'tab', startId: 'start', hostDispatch: true, github: { requester: '[email protected]' } })
+ f.prepare.mockRejectedValueOnce(new Error('This machine could not get a Harness GitHub App token for this project'))
+ f.advance()
+ await f.machine.tick()
+ expect(f.start).toHaveBeenCalledTimes(1)
+ const failed = f.backend.mock.calls.find(c => JSON.stringify(c[3] ?? {}).includes('could not get a Harness GitHub App token'))!
+ expect(failed[3]).toMatchObject({ command: { type: 'agent.startFailed', startId: 'start' } })
+ })
+ it('readies a start with the backend, as a team account when this daemon runs team work only', async () => {
+ for (const team of [false, true]) {
+ const f = fixture()
+ const machine = new ContributedMachines(f.core, 'host', { backend: f.backend, open: f.open, capabilities: f.capabilities, start: f.start,
+ log: f.log, env: {}, privacy: () => null, team: () => team, now: () => 1000 } as never)
+ Object.assign(f.pool, { githubApp: true })
+ f.backend.mockImplementation(async (_core: unknown, _method: string, path: string): Promise<unknown> => path.endsWith('/pools') ? [f.pool]
+ : path.endsWith('/github-token') ? { github: false } : { revision: 1 })
+ await machine.tick()
+ const asked = f.backend.mock.calls.find(c => String(c[2]).endsWith('/github-token'))!
+ expect(asked[3]).toEqual(team ? { always: true } : {})
+ expect(f.start).toHaveBeenCalledTimes(team ? 0 : 1)
+ }
+ })
it('publishes only scoped measurements and executes through the owner start endpoint', async () => {
const f = fixture()
await f.machine.tick()
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 63f698602..ba81651c8 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -8,7 +8,8 @@ import { backend, SuperTabHostError } from './host.js'
import { identifier, object } from './wire.js'
import { readCapabilities, quotaOf, meteredEngine } from './capacity.js'
import { startAgent, type ScopedRequest } from './start.js'
-import { prepareSwarmProject } from './projectFolder.js'
+import { prepareSwarmStart } from './projectFolder.js'
+import { readAuthSession } from '../lib/authSession.js'
import { createSwarmCloneTrustRepair, swarmCloneRoots } from './cloneTrust.js'
import { git } from '../lib/worktreeSweep.js'
import { projectsRoot } from '../lib/projectFolder.js'
@@ -115,7 +116,12 @@ export class ContributedMachines {
}
constructor(private readonly core: CoreApi, private readonly machineId: string,
private readonly deps: { backend: typeof backend; open: typeof openDaemon; capabilities: typeof readCapabilities;
- start: typeof startAgent; now: () => number; prepare?: typeof prepareSwarmProject; log?: (message: string) => void; env?: NodeJS.ProcessEnv
+ start: typeof startAgent; now: () => number; log?: (message: string) => void; env?: NodeJS.ProcessEnv
+ /** Readies a queued start before its agent is created (superTabs/projectFolder.ts `prepareSwarmStart`): whom the
+ * work is for when it uses the Harness GitHub App, else null. */
+ prepare?: (core: CoreApi, row: Record<string, unknown>, start: Record<string, unknown>) => Promise<{ requester: string } | null | void>
+ /** Whether this daemon runs team work only (a Harness Team account, `harness team on`): it has no git login of its own. */
+ team?: () => boolean
/** The Harness Team account's privacy check (team/privacy.ts): null for the owner's own daemon. */
privacy?: () => PrivacyObservation | null } =
{ backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }) {}
@@ -279,16 +285,21 @@ export class ContributedMachines {
error: `This computer's Harness Team account is not private (${privacy.item}): ${privacy.detail} Its owner can run \`harness team setup\` to repair it.` } })
continue
}
- if (pool.scope === 'swarm' && !start.dispatched) {
- try { await (this.deps.prepare ?? prepareSwarmProject)(this.core, row, start) }
- catch (error) {
+ // Another person's project is cloned and fetched with the Harness GitHub App's token, never this machine's own
+ // git login; a token that cannot be had fails the start (superTabs/projectFolder.ts).
+ let github: { requester: string } | null = null
+ if (!start.dispatched) {
+ try {
+ github = (await (this.deps.prepare ?? ((core, pooled, queued) => prepareSwarmStart(core, pooled, queued,
+ { backend: this.deps.backend, team: (this.deps.team ?? (() => readAuthSession()?.kind === 'team'))() })))(this.core, row, start)) ?? null
+ } catch (error) {
await scoped({ action: 'command', operationId: `prepare-failed-${start.id}`,
command: { type: 'agent.startFailed', startId: start.id,
error: error instanceof Error ? error.message : 'Could not prepare this project on the machine.' } })
continue
}
}
- const result = await this.deps.start({ tabId: row.tabId, startId: start.id, hostDispatch: true }, scoped, where, this.deps.open)
+ const result = await this.deps.start({ tabId: row.tabId, startId: start.id, hostDispatch: true, ...(github ? { github } : {}) }, scoped, where, this.deps.open)
if (result.ok === true && identifier(result.harnessId)) {
this.waiting.delete(start.id)
// Before the start settles: a settled start is no longer listed, so a missed record would never be made.
diff --git a/cli/src/superTabs/projectFolder.spec.ts b/cli/src/superTabs/projectFolder.spec.ts
index 5ec78624e..092b41bc7 100644
--- a/cli/src/superTabs/projectFolder.spec.ts
+++ b/cli/src/superTabs/projectFolder.spec.ts
@@ -2,7 +2,7 @@ import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { ProjectFolderError, RepositoryAccessError } from '../lib/projectFolder.js'
-import { prepareSwarmProject } from './projectFolder.js'
+import { prepareSwarmProject, prepareSwarmStart, startGitHub } from './projectFolder.js'
function fixture() {
const core = fakeCore({ dataDir: '/isolated-project-fixture' })
@@ -105,3 +105,99 @@ describe('per-project checkouts on a contributed swarm machine', () => {
await expect(f.run()).rejects.toThrow('does not match')
})
})
+
+const TOKEN = `ghs_${'f'.repeat(36)}`
+/** A queued start on a host whose server has the Harness GitHub App, and what the backend answers for its token. */
+function hosted(answer: unknown = { github: true, token: TOKEN, repository: 'example/project', requestedBy: { name: 'Olive', email: '[email protected]' } }) {
+ const f = fixture()
+ const row = { ...f.row, githubApp: true }
+ const start = { ...f.start, id: 'start-1', request: { ...f.start.request, worktree: true } }
+ const backend = vi.fn(async (..._args: unknown[]): Promise<unknown> => {
+ if (answer instanceof Error) throw answer
+ return answer
+ })
+ const fetch = vi.fn(async (_cwd: string, _env: NodeJS.ProcessEnv) => true)
+ return { ...f, row, start, backend, fetch,
+ ready: (team = false) => prepareSwarmStart(f.core, row, start, { backend, team, prepare: f.prepare, fetch }) }
+}
+
+describe('preparing another person\'s start with the Harness GitHub App', () => {
+ it('asks the backend for the start\'s token, clones over https with it alone, and fetches the default branch with it', async () => {
+ const f = hosted()
+ f.repository.repositoryUrl = '[email protected]:example/project.git'
+ expect(await f.ready()).toEqual({ requester: '[email protected]' })
+ expect(f.backend).toHaveBeenCalledWith(f.core, 'POST', `/api/super-tabs/hosts/${f.core.daemon.machineId()}/starts/tab/start-1/github-token`, {})
+ const [project, options] = f.prepare.mock.calls[0] as unknown as [Record<string, unknown>, { root: string; gitEnv: NodeJS.ProcessEnv }]
+ expect(project).toEqual({ source: 'remote', repositoryUrl: 'https://github.com/example/project.git', name: 'project-a' })
+ expect(options.root).toBe(f.root)
+ expect(options.gitEnv).toMatchObject({ HARNESS_SWARM_GIT_TOKEN: TOKEN, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' })
+ expect(f.fetch).toHaveBeenCalledWith(f.start.request.cwd, options.gitEnv)
+ })
+
+ it('leaves the machine owner\'s own project, and a server without the app, to the owner\'s login as before', async () => {
+ const own = hosted({ github: false })
+ expect(await own.ready()).toBeNull()
+ expect(own.prepare).toHaveBeenCalledWith({ source: 'remote', repositoryUrl: 'https://github.com/example/project.git', name: 'project-a' }, { root: own.root })
+ expect(own.fetch).not.toHaveBeenCalled()
+ const noApp = hosted()
+ delete (noApp.row as { githubApp?: boolean }).githubApp
+ expect(await noApp.ready()).toBeNull()
+ expect(noApp.backend).not.toHaveBeenCalled()
+ })
+
+ it('in a team account, always asks for a token, and fails without one rather than using any other login', async () => {
+ const team = hosted()
+ expect(await team.ready(true)).toEqual({ requester: '[email protected]' })
+ expect(team.backend.mock.calls[0]![3]).toEqual({ always: true })
+ const noApp = hosted()
+ delete (noApp.row as { githubApp?: boolean }).githubApp
+ await expect(noApp.ready(true)).rejects.toThrow('no GitHub App, and a Harness Team account has no git login')
+ expect(noApp.prepare).not.toHaveBeenCalled()
+ await expect(hosted({ github: false }).ready(true)).rejects.toThrow('answered without a GitHub token')
+ })
+
+ it('fails the start when the backend refuses a token, and never prepares it with the owner\'s login instead', async () => {
+ for (const answer of [new Error('The Harness GitHub App is not installed on example/project.'), { github: true }, { github: true, token: TOKEN, repository: 'x', requestedBy: {} }, 'nonsense']) {
+ const f = hosted(answer)
+ await expect(f.ready()).rejects.toThrow(answer instanceof Error ? answer.message : 'answered without a GitHub token')
+ expect(f.prepare).not.toHaveBeenCalled()
+ expect(f.fetch).not.toHaveBeenCalled()
+ }
+ const noIds = hosted()
+ ;(noIds.start as { id?: string }).id = undefined
+ await expect(noIds.ready()).rejects.toThrow('cannot be prepared')
+ })
+
+ it('a clone the token cannot make says so, and is not tried again another way', async () => {
+ const f = hosted()
+ f.prepare.mockRejectedValueOnce(new RepositoryAccessError('CLONE_FAILED', 'Could not access this repository.'))
+ await expect(f.ready()).rejects.toThrow("could not clone the project repository with the Harness GitHub App's token")
+ expect(f.prepare).toHaveBeenCalledTimes(1)
+ f.prepare.mockRejectedValueOnce(new ProjectFolderError('PROJECT_EXISTS', 'taken'))
+ await expect(f.ready()).rejects.toThrow('taken')
+ })
+
+ it('fetches into a project already on this host, and into a contribution that is not a Swarm folder, with the token', async () => {
+ const f = hosted()
+ f.repository.machineId = f.core.daemon.machineId()
+ f.start.request.cwd = f.repository.cwd
+ await f.ready()
+ expect(f.prepare).not.toHaveBeenCalled()
+ expect(f.fetch).toHaveBeenCalledWith('/other/repo', expect.objectContaining({ HARNESS_SWARM_GIT_TOKEN: TOKEN }))
+ const legacy = hosted()
+ legacy.row.machine.scope = ''
+ legacy.start.request.cwd = '/repo'
+ await legacy.ready()
+ expect(legacy.prepare).not.toHaveBeenCalled()
+ expect(legacy.fetch).toHaveBeenCalledWith('/repo', expect.objectContaining({ HARNESS_SWARM_GIT_TOKEN: TOKEN }))
+ const folder = hosted()
+ folder.start.request.worktree = false
+ await folder.ready()
+ expect(folder.fetch).not.toHaveBeenCalled()
+ })
+
+ it('startGitHub reads nothing it need not', async () => {
+ const f = hosted()
+ expect(await startGitHub(f.core, f.row, f.start, { backend: f.backend, team: false })).toEqual({ token: TOKEN, repository: 'example/project', requester: '[email protected]' })
+ })
+})
diff --git a/cli/src/superTabs/projectFolder.ts b/cli/src/superTabs/projectFolder.ts
index b56fd6a73..65c8997ea 100644
--- a/cli/src/superTabs/projectFolder.ts
+++ b/cli/src/superTabs/projectFolder.ts
@@ -1,10 +1,67 @@
import { isAbsolute, join, resolve } from 'node:path'
import type { CoreApi } from '../core/api.js'
+import { fetchDefaultBranch } from '../lib/gitProject.js'
import { otherGitHubTransport, parseProjectFolder, prepareProjectFolder, ProjectFolderError, RepositoryAccessError } from '../lib/projectFolder.js'
+import { swarmGitPrepareEnv } from '../lib/swarmGitHub.js'
import { identifier, object } from './wire.js'
import { repairSwarmCloneTrust, swarmCloneRoot } from './cloneTrust.js'
type Json = Record<string, unknown>
+type Backend = (core: CoreApi, method: string, path: string, body?: unknown) => Promise<unknown>
+
+/** A read-only Harness GitHub App token for a queued start's project repository, and whom that work is for. */
+export interface StartGitHub { token: string; repository: string; requester: string }
+
+const NO_APP_ON_TEAM = 'This Harness server has no GitHub App, and a Harness Team account has no git login of its own, so it cannot fetch '
+ + 'the project. Ask the server\'s administrator to set up the Harness GitHub App (docs/swarm-github-app.md).'
+
+/**
+ * Whether a queued start on this machine is prepared with the Harness GitHub App's token instead of this machine's own git
+ * login, and that token (docs/swarm-github-app.md). Asked of the backend, which knows whose project it is: another person's
+ * project gets a token that only reads its repository; the machine owner's own project answers none, and the owner's login
+ * prepares it as before. A Harness Team account ([team]) has no login, so it always asks for one. A server without the app
+ * gives none: an owner's machine prepares as before, as its agents then also use its own login; a team account cannot.
+ * Anything the backend refuses is thrown, to fail the start: never this machine's own login instead.
+ */
+export async function startGitHub(core: CoreApi, row: Json, start: Json, deps: { backend: Backend; team: boolean }): Promise<StartGitHub | null> {
+ const machineId = core.daemon.machineId()
+ if (row.githubApp !== true) {
+ if (deps.team) throw new Error(NO_APP_ON_TEAM)
+ return null
+ }
+ if (!identifier(row.tabId) || !identifier(start.id) || !identifier(machineId)) throw new Error('This start cannot be prepared on this machine.')
+ let answer: Json
+ try {
+ answer = object(await deps.backend(core, 'POST', `/api/super-tabs/hosts/${machineId}/starts/${row.tabId}/${start.id}/github-token`, deps.team ? { always: true } : {}))
+ } catch (error) {
+ const said = error instanceof Error ? error.message : String(error)
+ throw new Error(`This machine could not get a Harness GitHub App token for this project, so it was not prepared with its owner's own GitHub login either: ${said}`)
+ }
+ if (answer.github === false && !deps.team) return null
+ const requester = object(answer.requestedBy).email
+ if (answer.github !== true || typeof answer.token !== 'string' || typeof answer.repository !== 'string' || typeof requester !== 'string' || !requester) {
+ throw new Error('The Harness server answered without a GitHub token for this project.')
+ }
+ return { token: answer.token, repository: answer.repository, requester }
+}
+
+/**
+ * Everything a queued start on this machine needs before its agent is created: the Harness GitHub App's token when the work
+ * is another person's (`startGitHub`), the Swarm folder's checkout (`prepareSwarmProject`) and, for a worktree, its default
+ * branch brought up to date with that token, so the agent's worktree starts from it (the core then fetches nothing itself:
+ * core/agents/launches.ts). Returns whom the work is for, for the start; null when this machine's own login is right for it.
+ */
+export async function prepareSwarmStart(core: CoreApi, row: Json, start: Json,
+ deps: { backend: Backend; team: boolean; prepare?: typeof prepareProjectFolder; fetch?: typeof fetchDefaultBranch }): Promise<{ requester: string } | null> {
+ const github = await startGitHub(core, row, start, deps)
+ const gitEnv = github ? swarmGitPrepareEnv(github.token) : undefined
+ if (object(row.machine).scope === 'swarm') await prepareSwarmProject(core, row, start, deps.prepare, gitEnv)
+ const request = object(start.request)
+ if (gitEnv && request.worktree === true && typeof request.cwd === 'string' && isAbsolute(request.cwd)) {
+ await (deps.fetch ?? fetchDefaultBranch)(resolve(request.cwd), gitEnv)
+ }
+ return github ? { requester: github.requester } : null
+}
/** Whether a requested folder names this one. The Lead and the backend join a swarm folder with '/'
* (routeCommand.ts, backend machines.ts), which on Windows arrives as C:\…\TAB/PROJECT; this machine's
@@ -15,7 +72,7 @@ function sameFolder(requested: unknown, folder: unknown): boolean {
/** The owner granted a swarm workspace, not caller-selected filesystem paths.
* Prepare the queued project's repository there before reserving or launching. */
-export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json, prepare = prepareProjectFolder): Promise<void> {
+export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json, prepare = prepareProjectFolder, gitEnv?: NodeJS.ProcessEnv): Promise<void> {
const pool = object(row.machine)
if (pool.scope !== 'swarm' || start.dispatched) return
const request = object(start.request)
@@ -33,16 +90,27 @@ export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json,
const source = parseProjectFolder({ projectSource: 'remote', repositoryUrl: repository.repositoryUrl })
if (source?.source !== 'remote') throw new Error('This project repository is unavailable.')
let cwd: string
- try { cwd = await prepare({ ...source, name: project.id }, { root: expectedRoot }) }
- catch (error) {
- // The shared address names the repository, not how this machine signs in to GitHub: a credential helper for HTTPS,
- // a key for SSH. Desktop shares HTTPS because the daemon's remote no longer says which one the lead used.
- const other = error instanceof RepositoryAccessError ? otherGitHubTransport(source.repositoryUrl) : null
- if (!other) throw error
- try { cwd = await prepare({ ...source, repositoryUrl: other, name: project.id }, { root: expectedRoot }) }
- catch (second) {
- if (!(second instanceof ProjectFolderError) || !['CLONE_FAILED', 'CLONE_TIMEOUT'].includes(second.code)) throw second
- throw new ProjectFolderError('CLONE_FAILED', 'This machine could not access the project repository over HTTPS or SSH. Its owner needs GitHub access to it here: run gh auth login and gh auth setup-git, or add an SSH key to their GitHub account.')
+ if (gitEnv) {
+ // With the app's token: over https alone, whatever address was shared, and no other way in if it is refused.
+ const ssh = '[email protected]:'
+ const https = source.repositoryUrl.startsWith(ssh) ? `https://github.com/${source.repositoryUrl.slice(ssh.length)}` : source.repositoryUrl
+ try { cwd = await prepare({ ...source, repositoryUrl: https, name: project.id }, { root: expectedRoot, gitEnv }) }
+ catch (error) {
+ if (!(error instanceof ProjectFolderError) || !['CLONE_FAILED', 'CLONE_TIMEOUT'].includes(error.code)) throw error
+ throw new ProjectFolderError(error.code, `This machine could not clone the project repository with the Harness GitHub App's token: ${error.message}`)
+ }
+ } else {
+ try { cwd = await prepare({ ...source, name: project.id }, { root: expectedRoot }) }
+ catch (error) {
+ // The shared address names the repository, not how this machine signs in to GitHub: a credential helper for HTTPS,
+ // a key for SSH. Desktop shares HTTPS because the daemon's remote no longer says which one the lead used.
+ const other = error instanceof RepositoryAccessError ? otherGitHubTransport(source.repositoryUrl) : null
+ if (!other) throw error
+ try { cwd = await prepare({ ...source, repositoryUrl: other, name: project.id }, { root: expectedRoot }) }
+ catch (second) {
+ if (!(second instanceof ProjectFolderError) || !['CLONE_FAILED', 'CLONE_TIMEOUT'].includes(second.code)) throw second
+ throw new ProjectFolderError('CLONE_FAILED', 'This machine could not access the project repository over HTTPS or SSH. Its owner needs GitHub access to it here: run gh auth login and gh auth setup-git, or add an SSH key to their GitHub account.')
+ }
}
}
if (cwd !== expected) throw new Error('The prepared checkout does not match the authorized project.')
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index a07e49833..fd41730fd 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'
import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import type { CoreApi } from '../core/api.js'
-import { superTabService } from './service.js'
+import { sharedSwarm, superTabService } from './service.js'
import { object } from './wire.js'
const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
@@ -680,12 +680,59 @@ describe('GitHub App tokens through the service', () => {
it('keeps the tokens fresh while connected, and stops with the service', () => {
const tokens = { start: vi.fn(), stop: vi.fn() }
- const service = superTabService(fakeCore(), { githubTokens: () => tokens })
+ const engines = { start: vi.fn(), stop: vi.fn() }
+ const service = superTabService(fakeCore(), { githubTokens: () => tokens, teamEngines: () => engines })
service.port.connected()
expect(tokens.start).toHaveBeenCalledTimes(1)
+ // And, in a Harness Team account, reports its own engines to its owner (team/engines.ts).
+ expect(engines.start).toHaveBeenCalledTimes(1)
service.port.disconnected()
service.port.stop()
expect(tokens.stop).toHaveBeenCalledTimes(2)
+ expect(engines.stop).toHaveBeenCalledTimes(2)
+ })
+})
+
+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 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))
+ 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' })
+ }
+ for (const reason of [undefined, 'background', 7]) {
+ expect(await service.requests.super_tabs({ action: 'teamSetup', reason }, owner)).toEqual({ error: 'INVALID_REQUEST' })
+ }
+ await service.requests.super_tabs({ action: 'teamSetup', reason: 'startup' }, owner)
+ expect(make).toHaveBeenCalledTimes(1)
+ expect(offer).toHaveBeenCalledTimes(2)
+ })
+
+ 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 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' })
+ })
+
+ it('at app start, counts a Swarm this Mac is in with anyone else in it', async () => {
+ const answers = (pools: unknown, tabs: Record<string, unknown>) => vi.fn<CoreApi['account']['backend']>(async (_method, path) => {
+ if (path.endsWith('/pools')) return pools instanceof Error ? { status: 503, body: { success: false } } : { status: 200, body: { success: true, data: pools } }
+ const tab = tabs[path.split('/').pop()!]
+ return tab ? { status: 200, body: { success: true, data: tab } } : { status: 403, body: { success: false, error: { code: 'FORBIDDEN' } } }
+ })
+ const core = (call: CoreApi['account']['backend'], machineId = 'machine-1') => fakeCore({ account: { backend: call }, daemon: { machineId: () => machineId } as never })
+ const shared = answers([{ tabId: 'solo' }, { tabId: 'gone' }, { tabId: 'team' }],
+ { solo: { state: { people: [{ id: 'me' }] } }, team: { state: { people: [{ id: 'me' }, { id: 'kim' }] } } })
+ expect(await sharedSwarm(core(shared))).toBe(true)
+ expect(shared).toHaveBeenCalledWith('GET', '/api/super-tabs/hosts/machine-1/pools', undefined)
+ expect(await sharedSwarm(core(answers([{ tabId: 'solo' }, { tabId: '../x' }], { solo: { state: { people: [{ id: 'me' }] } } })))).toBe(false)
+ expect(await sharedSwarm(core(answers(new Error('down'), {})))).toBe(false)
+ expect(await sharedSwarm(core(answers({ not: 'a list' }, {})))).toBe(false)
+ expect(await sharedSwarm(core(answers([], {}), ''))).toBe(false)
})
})
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 60b2da34d..d8e178c0e 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -11,6 +11,8 @@ import { ContributionPreparations, prepareContribution } from './contribution.js
import { messageIdOf } from './attach.js'
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'
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 = {
@@ -126,6 +128,21 @@ function markAnswered(page: unknown, later: unknown[], agentId: string): unknown
}) }
}
+/** Whether this machine is in a Swarm with other people in it: a contribution of its own to a tab whose people are more
+ * than its owner. False when that cannot be read. */
+export async function sharedSwarm(core: CoreApi): Promise<boolean> {
+ const machineId = core.daemon.machineId()
+ if (!identifier(machineId)) return false
+ const pools = await backend(core, 'GET', `/api/super-tabs/hosts/${machineId}/pools`).catch(() => [])
+ for (const row of Array.isArray(pools) ? pools.map(object) : []) {
+ if (!identifier(row.tabId)) continue
+ const tab = object(await backend(core, 'GET', `/api/super-tabs/${row.tabId}`).catch(() => ({})))
+ const people = object(tab.state).people
+ if (Array.isArray(people) && people.length > 1) return true
+ }
+ return false
+}
+
export interface SuperTabServiceOptions {
prepareContribution?: typeof prepareContribution
capacity?: typeof readCapabilities
@@ -135,6 +152,10 @@ export interface SuperTabServiceOptions {
cards?: (core: CoreApi, machineId: string) => SwarmCards
/** What keeps Swarm sessions' GitHub tokens fresh (superTabs/github.ts), for a spec. */
githubTokens?: (core: CoreApi) => Pick<GitHubTokenRefresher, 'start' | 'stop'>
+ /** 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'>>
}
export function superTabService(core: CoreApi, options: SuperTabServiceOptions = {}): { requests: ServiceRequests; port: SuperTabsPort } {
const preparations = new ContributionPreparations(input => (options.prepareContribution ?? prepareContribution)(core, input))
@@ -168,10 +189,14 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
}
// Sessions doing another person's project work keep a live GitHub App token while their task lasts, and none after.
const tokens = (options.githubTokens ?? (api => new GitHubTokenRefresher(api)))(core)
- const disconnect = () => { preparations.clear(); host?.stop(); host = null; book?.stop(); book = null; bookMachine = null; swarmCards?.want(false); swarmCards = null; cardsMachine = null; tokens.stop() }
+ // 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
+ const disconnect = () => { preparations.clear(); host?.stop(); host = 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()
if (identifier(core.daemon.machineId()) && existsSync(hostJournalFile(core.dataDir, core.daemon.machineId()))) wake()
},
disconnected: disconnect,
@@ -201,6 +226,15 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
if (!asker.local) return { error: 'OWNER_REQUIRED' }
return await githubToken(core, String(payload.harnessId ?? ''))
}
+ // 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') {
+ if (!asker.local) return { error: 'OWNER_REQUIRED' }
+ if (!AUTO_SETUP_REASONS.includes(payload.reason as AutoSetupReason)) return { error: 'INVALID_REQUEST' }
+ 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(core)) }
+ }
if (payload.action === 'swarmRole') {
const grant = await port.swarmRole(String(payload.harnessId ?? ''))
return { ok: true, role: grant ? grant.role : grant, ...(grant ? { mode: grant.mode } : {}) }
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index 51db09f22..f733c4c78 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -831,6 +831,19 @@ describe('Swarm starts for another person\'s project', () => {
expect(await started({ state: legacy, githubApp: true })).toMatchObject({ swarmGitHub: true })
})
+ it('on a contributed machine, goes by what its host readied: the app for whom it named, nothing when it named no one', async () => {
+ const hosted = async (github: unknown) => {
+ const f = fixture({ state, githubApp: true })
+ Object.assign(f.start, { machineOwnerId: 'host-1' })
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start', hostDispatch: true, ...(github === undefined ? {} : { github }) }, f.scoped, where, f.open)).toMatchObject({ ok: true })
+ return f.request.mock.calls.find(c => c[0] === 'agent_create')![1]!
+ }
+ const payload = await hosted({ requester: '[email protected]' })
+ expect(payload).toMatchObject({ swarmRole: 'dev', swarmGitHub: true })
+ expect(String(payload.prompt)).toContain('Requested by [email protected] through Harness.')
+ for (const github of [undefined, null, {}, { requester: '' }]) expect(await hosted(github)).not.toHaveProperty('swarmGitHub')
+ })
+
it('launches as before for the machine owner\'s own project, on a server without the app, or when the Swarm cannot be read', async () => {
for (const [options, owner] of [[{ state, githubApp: true }, 'owner-1'], [{ state }, 'host-1'], [{ state: new Error('offline'), githubApp: true }, 'host-1'],
[{ state: { ...state, conversations: [{ id: 'other' }] }, githubApp: true }, 'host-1'], [{ state: { ...state, people: [] }, githubApp: true }, 'host-1']] as const) {
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index 58a6c3b03..a6647daf9 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -180,7 +180,11 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher
// The backend starts a Reviewer only on Claude Code or Codex, the engines with built-in Swarm skills.
const skilled = ['claude', 'codex'].includes(String(request.engine)), reviewer = request.role === 'reviewer'
const role = reviewer ? 'review' : 'dev', facts = skilled ? await projectFacts(scoped, request.conversationId, start.machineOwnerId) : null
- const mode = facts?.mode ?? null, github = facts?.github ?? null
+ // A contributed machine's host cannot read the tab as a Lead does: it asked the backend whose work this is when it
+ // readied the start, and prepared it with the app's token if it is another person's (superTabs/projectFolder.ts).
+ const hosted = input.hostDispatch === true ? object(input.github) : null
+ const mode = facts?.mode ?? null
+ const github = hosted ? (typeof hosted.requester === 'string' && hosted.requester ? { requester: hosted.requester } : null) : facts?.github ?? null
const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: true,
...(permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),
...(mode ? { swarmRole: role, swarmSkillMode: mode } : {}),
diff --git a/cli/src/team/autoSetup.spec.ts b/cli/src/team/autoSetup.spec.ts
new file mode 100644
index 000000000..93142a247
--- /dev/null
+++ b/cli/src/team/autoSetup.spec.ts
@@ -0,0 +1,116 @@
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { AuthSession } from '../lib/authSession.js'
+import type { TeamConfig } from './config.js'
+import {
+ AUTO_SETUP_RETRY_MS, readTeamSetupDecision, TeamAutoSetup, teamSetupDecisionFile, writeTeamSetupDecision, type AutoSetupDeps, type TeamSetupDecision,
+} from './autoSetup.js'
+
+const session: AuthSession = { version: 1, accessToken: 'access-placeholder', autonomousEnv: 'prod', computerId: 'c'.repeat(32), updatedAt: 1 }
+
+function fake(over: Partial<AutoSetupDeps> = {}) {
+ let decision: TeamSetupDecision | null = null
+ const log: string[] = []
+ const deps: AutoSetupDeps = {
+ platform: 'darwin', session: () => session, readConfig: () => null, accountExists: vi.fn(async () => false),
+ readDecision: () => decision, writeDecision: vi.fn((d: TeamSetupDecision) => { decision = d }),
+ setup: vi.fn(async () => ({ code: 0, result: { ok: true } })), now: () => 1_000_000, log: (line) => log.push(line), ...over,
+ }
+ return { auto: new TeamAutoSetup(deps), deps, log, decision: () => decision, setDecision: (d: TeamSetupDecision | null) => { decision = d } }
+}
+
+const cleanup: string[] = []
+afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+describe('the Harness Team account, set up on its own', () => {
+ it('starts setup as the person joins or adds this Mac, once at a time, and answers at once', async () => {
+ const f = fake()
+ let finish: (value: { code: number; result: Record<string, unknown> | null }) => void = () => {}
+ ;(f.deps.setup as ReturnType<typeof vi.fn>).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
+ expect(await f.auto.offer('join')).toEqual({ state: 'started' })
+ expect(await f.auto.offer('contribute')).toEqual({ state: 'running' })
+ finish({ code: 0, result: { ok: true } })
+ await f.auto.settled()
+ expect(f.deps.setup).toHaveBeenCalledTimes(1)
+ expect(f.deps.writeDecision).not.toHaveBeenCalled()
+ expect(f.log.join('\n')).toContain('the Harness Team account is set up')
+ })
+
+ it('asks nothing off a Mac, signed out, on a computer that runs team work only, or where the account exists', async () => {
+ const cases: Array<[Partial<AutoSetupDeps>, string]> = [
+ [{ platform: 'linux' }, 'unsupported'], [{ platform: 'win32' }, 'unsupported'], [{ session: () => null }, 'signed-out'],
+ [{ session: () => ({ ...session, kind: 'team' }) }, 'dedicated'], [{ readConfig: () => ({ user: 'harnessteam' }) as TeamConfig }, 'exists'],
+ [{ accountExists: vi.fn(async () => true) }, 'exists'],
+ ]
+ for (const [over, state] of cases) {
+ const f = fake(over)
+ expect(await f.auto.offer('join'), state).toEqual({ state })
+ expect(f.deps.setup).not.toHaveBeenCalled()
+ }
+ })
+
+ it('remembers a cancelled prompt and does not ask again on its own; a failed setup waits a day', async () => {
+ const cancelled = fake({ setup: vi.fn(async () => ({ code: 1, result: { ok: false, code: 'CANCELLED', message: 'Nothing was changed' } })) })
+ expect(await cancelled.auto.offer('join')).toEqual({ state: 'started' })
+ await cancelled.auto.settled()
+ expect(cancelled.decision()).toEqual({ state: 'declined', at: 1_000_000 })
+ expect(await cancelled.auto.offer('contribute')).toEqual({ state: 'declined' })
+ expect(await cancelled.auto.offer('startup', async () => true)).toEqual({ state: 'declined' })
+ expect(cancelled.deps.setup).toHaveBeenCalledTimes(1)
+
+ let now = 1_000_000
+ const failed = fake({ now: () => now, setup: vi.fn(async () => ({ code: 1, result: { ok: false, code: 'SETUP_FAILED', message: 'launchd would not start it' } })) })
+ await failed.auto.offer('join')
+ await failed.auto.settled()
+ expect(failed.decision()).toEqual({ state: 'failed', at: 1_000_000, detail: 'launchd would not start it' })
+ expect(await failed.auto.offer('join')).toEqual({ state: 'waiting' })
+ now += AUTO_SETUP_RETRY_MS
+ expect(await failed.auto.offer('join')).toEqual({ state: 'started' })
+ await failed.auto.settled()
+ // A setup that threw is a failure too; one that made the account but whose daemon has not reported is not.
+ const threw = fake({ setup: vi.fn(async () => { throw new Error('osascript missing') }) })
+ await threw.auto.offer('join'); await threw.auto.settled()
+ expect(threw.decision()).toMatchObject({ state: 'failed', detail: 'osascript missing' })
+ const slow = fake({ setup: vi.fn(async () => ({ code: 1, result: { ok: false, privacy: null } })) })
+ await slow.auto.offer('join'); await slow.auto.settled()
+ expect(slow.decision()).toBeNull()
+ expect(slow.log.join('\n')).toContain('harness team status')
+ const unreadable = fake({ setup: vi.fn(async () => ({ code: 1, result: { ok: false, code: 'CANCELLED' } })),
+ writeDecision: vi.fn(() => { throw new Error('read-only') }) })
+ await unreadable.auto.offer('join'); await unreadable.auto.settled()
+ expect(unreadable.log.join('\n')).toContain('could not remember')
+ })
+
+ it('at app start, asks only while this Mac is in a Swarm with other people in it', async () => {
+ const alone = fake()
+ expect(await alone.auto.offer('startup', async () => false)).toEqual({ state: 'not-shared' })
+ expect(await alone.auto.offer('startup')).toEqual({ state: 'not-shared' })
+ expect(await alone.auto.offer('startup', async () => { throw new Error('offline') })).toEqual({ state: 'not-shared' })
+ expect(alone.deps.setup).not.toHaveBeenCalled()
+ const shared = fake()
+ expect(await shared.auto.offer('startup', async () => true)).toEqual({ state: 'started' })
+ await shared.auto.settled()
+ expect(shared.deps.setup).toHaveBeenCalledTimes(1)
+ })
+
+ 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)
+ const file = teamSetupDecisionFile(dir)
+ expect(readTeamSetupDecision(file)).toBeNull()
+ writeTeamSetupDecision(file, { state: 'failed', at: 5, detail: 'x'.repeat(400) })
+ expect(statSync(file).mode & 0o777).toBe(0o600)
+ expect(readTeamSetupDecision(file)).toEqual({ state: 'failed', at: 5, detail: 'x'.repeat(300) })
+ writeTeamSetupDecision(file, { state: 'declined', at: 6 })
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ state: 'declined', at: 6 })
+ writeTeamSetupDecision(file, null)
+ expect(readTeamSetupDecision(file)).toBeNull()
+ writeTeamSetupDecision(file, null)
+ for (const text of ['{', '{"state":"maybe","at":1}', '{"state":"declined","at":"now"}']) {
+ writeFileSync(file, text)
+ expect(readTeamSetupDecision(file), text).toBeNull()
+ }
+ })
+})
diff --git a/cli/src/team/autoSetup.ts b/cli/src/team/autoSetup.ts
new file mode 100644
index 000000000..e3f05d208
--- /dev/null
+++ b/cli/src/team/autoSetup.ts
@@ -0,0 +1,154 @@
+/**
+ * The Harness Team account, set up on its own the moment a person joins a Swarm or adds this Mac to one
+ * (docs/plans/2026-10-24-swarm-team-account.md, Task 3). The owner chose "no button, no setup screen": the only thing a
+ * person sees is macOS's own administrator prompt, and it appears while they are at this Mac doing that. Desktop asks this
+ * Mac's own daemon (super_tabs `teamSetup`, from the local owner only) right after a join or a contribution succeeds;
+ * nothing asks from a background event, with nobody there, and nothing asks on Windows or Linux.
+ *
+ * Macs that joined and were added before this release never pass through either moment, and routing now sends
+ * teammates' work only to Team machines. So Desktop also asks once as it starts on a Mac (`startup`), with the person
+ * there: it goes ahead only while this Mac is in a Swarm with other people in it.
+ *
+ * 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.
+ */
+import { readFileSync, renameSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import type { AuthSession } from '../lib/authSession.js'
+import type { TeamConfig } from './config.js'
+import { TEAM_USER } from './layout.js'
+
+export interface TeamSetupDecision {
+ /** `declined`: the person cancelled the prompt or removed the account. `failed`: setup could not make it. */
+ state: 'declined' | 'failed'
+ at: number
+ detail?: string
+}
+
+/** Where the owner's daemon keeps the decision, in its own data folder. */
+export const teamSetupDecisionFile = (dataDir: string) => join(dataDir, 'team-setup.json')
+
+export function readTeamSetupDecision(file: string): TeamSetupDecision | null {
+ try {
+ const value = JSON.parse(readFileSync(file, 'utf8')) as Partial<TeamSetupDecision>
+ if ((value.state !== 'declined' && value.state !== 'failed') || typeof value.at !== 'number' || !Number.isFinite(value.at)) return null
+ return { state: value.state, at: value.at, ...(typeof value.detail === 'string' ? { detail: value.detail.slice(0, 300) } : {}) }
+ } catch { return null }
+}
+
+export function writeTeamSetupDecision(file: string, decision: TeamSetupDecision | null): void {
+ if (!decision) { rmSync(file, { force: true }); return }
+ mkdirSync(dirname(file), { recursive: true })
+ const next = `${file}.${process.pid}.next`
+ writeFileSync(next, `${JSON.stringify(decision)}\n`, { mode: 0o600 })
+ renameSync(next, file)
+}
+
+/** 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'
+
+/** 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']
+
+export interface AutoSetupDeps {
+ platform: NodeJS.Platform
+ session(): AuthSession | null
+ readConfig(): TeamConfig | null
+ accountExists(user: string): Promise<boolean>
+ readDecision(): TeamSetupDecision | null
+ writeDecision(decision: TeamSetupDecision): void
+ /** `harness team setup --json`, as this account: its exit code and the JSON it answered (null when it said none). */
+ setup(): Promise<{ code: number; result: Record<string, unknown> | null }>
+ now(): number
+ log(line: string): void
+}
+
+/** What a setup that made nothing answers: not cancelled, and not an account that exists but did not report in time. */
+const MADE_NOTHING = new Set(['SETUP_FAILED', 'NOT_INSTALLED', 'NOT_SIGNED_IN', 'RUN_AS_YOURSELF', 'INVALID_INPUT', 'BACKEND', 'EXPIRED', 'NOT_TEAM'])
+
+export class TeamAutoSetup {
+ private running: Promise<void> | null = null
+ constructor(private readonly deps: AutoSetupDeps) {}
+
+ /**
+ * 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).
+ */
+ async offer(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean> = async () => false): Promise<{ state: AutoSetupState }> {
+ const { deps } = this
+ if (deps.platform !== 'darwin') return { state: 'unsupported' }
+ const session = deps.session()
+ if (!session) return { state: 'signed-out' }
+ 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 (this.running) return { state: 'running' }
+ this.running = this.run().finally(() => { this.running = null })
+ return { state: 'started' }
+ }
+
+ /** Waits for a setup this started, for a spec. */
+ settled(): Promise<void> { return this.running ?? Promise.resolve() }
+
+ private async run(): Promise<void> {
+ const { deps } = this
+ deps.log('setting up the Harness Team account: macOS asks for an administrator password')
+ let outcome: { code: number; result: Record<string, unknown> | null }
+ try {
+ outcome = await deps.setup()
+ } catch (error) {
+ outcome = { code: 1, result: { ok: false, code: 'SETUP_FAILED', message: error instanceof Error ? error.message : String(error) } }
+ }
+ const code = typeof outcome.result?.code === 'string' ? outcome.result.code : null
+ const message = typeof outcome.result?.message === 'string' ? outcome.result.message : undefined
+ try {
+ if (code === 'CANCELLED') {
+ deps.writeDecision({ state: 'declined', at: deps.now() })
+ deps.log('the Harness Team account prompt was cancelled: it is not offered again on its own (harness team setup offers it)')
+ } else if (outcome.code !== 0 && code !== null && MADE_NOTHING.has(code)) {
+ deps.writeDecision({ state: 'failed', at: deps.now(), ...(message ? { detail: message } : {}) })
+ deps.log(`the Harness Team account was not set up: ${message ?? code}`)
+ } else {
+ deps.log(outcome.code === 0 ? 'the Harness Team account is set up' : `the Harness Team account was set up, with something to look at: harness team status`)
+ }
+ } catch (error) {
+ deps.log(`could not remember the Harness Team account setup: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ }
+}
+
+/** The owner's daemon's own: this account's sign-in and data folder, and `harness team setup --json` run in this process. */
+export async function realTeamAutoSetup(dataDir: string, log: (line: string) => void): Promise<TeamAutoSetup> {
+ const [{ readAuthSession }, { readTeamConfig }, { runGuestCommand }] = await Promise.all([
+ import('../lib/authSession.js'), import('./config.js'), import('../lib/guestAccounts.js')])
+ const file = teamSetupDecisionFile(dataDir)
+ return new TeamAutoSetup({
+ platform: process.platform,
+ session: readAuthSession,
+ readConfig: () => readTeamConfig(),
+ accountExists: async (user) => (await runGuestCommand('id', ['-u', user], { timeoutMs: 10_000 })).code === 0,
+ readDecision: () => readTeamSetupDecision(file),
+ writeDecision: (decision) => writeTeamSetupDecision(file, decision),
+ setup: async () => {
+ const [{ teamCommand }, { teamCommandDeps }] = await Promise.all([import('./command.js'), import('./deps.js')])
+ const lines: string[] = []
+ const refuse = async (): Promise<never> => { throw new Error('setup does not restart the daemon') }
+ const code = await teamCommand(['setup', '--json'], { ...teamCommandDeps({ stopDaemon: refuse, startDaemon: refuse }),
+ out: (line) => lines.push(line), err: (line) => lines.push(line), interactive: false })
+ const last = [...lines].reverse().find((line) => line.startsWith('{'))
+ let result: Record<string, unknown> | null = null
+ try { result = last ? JSON.parse(last) as Record<string, unknown> : null } catch { /* said nothing readable */ }
+ return { code, result }
+ },
+ now: () => Date.now(),
+ log,
+ })
+}
diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.ts
index 9de335670..29b624585 100644
--- a/cli/src/team/command.spec.ts
+++ b/cli/src/team/command.spec.ts
@@ -7,6 +7,7 @@ import type { AdminScript, RunAdmin } from './admin.js'
import { teamCommand, type TeamCommandDeps } from './command.js'
import type { TeamConfig } from './config.js'
import type { PrivacyResult, TeamStatus } from './privacy.js'
+import type { TeamEngines } from './engines.js'
import { parseLaunchctlPrint } from './deps.js'
const OWNER_HOME = '/Users/owner-placeholder'
@@ -45,6 +46,7 @@ function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnTyp
env: {}, interactive: false, ask: vi.fn(async () => 'y'), now: () => now, sleep: vi.fn(async (ms: number) => { now += ms }),
session: () => session, writeSession: vi.fn((s: AuthSession) => { session = s }), clearSession: vi.fn(() => { session = null }),
auth: vi.fn(async () => ({ session: session!, headers: { authorization: 'Bearer x' } })), post: post as never,
+ get: vi.fn(async () => ({ user: { id: 'user-placeholder-1' } })) as never, machineKey: () => ({ priv: new Uint8Array(32).fill(9) }),
computerId: () => 't'.repeat(32), autonomousEnv: 'prod',
installed: () => ({ cliDir: `${OWNER_HOME}/.harness/cli`, cliJs: `${OWNER_HOME}/.harness/cli/cli.js`,
node: `${OWNER_HOME}/.harness/runtime/node-v1/bin/node`, nodeRuntimeDir: `${OWNER_HOME}/.harness/runtime/node-v1`, tmuxRuntimeDir: null }),
@@ -54,6 +56,7 @@ function fake(over: Partial<TeamCommandDeps> & { adminResult?: Awaited<ReturnTyp
writeStatus: vi.fn((path: string, update: Partial<TeamStatus>) => { status.set(path, { ...(status.get(path) ?? { version: 1 }), ...update, version: 1 }) }),
accountExists: vi.fn(async () => false), jobState: vi.fn(async () => ({ loaded: true, pid: 4242, state: 'running' })),
takeHandoff: vi.fn(() => CODE), privacy: vi.fn((): PrivacyResult => ({ passed: true, checkedAt: now })),
+ engines: vi.fn(async (): Promise<TeamEngines> => ({ checkedAt: now, claude: { installed: true, signedIn: false }, codex: { installed: true, signedIn: true } })),
stopDaemon: vi.fn(async () => true), startDaemon: vi.fn(async () => {}),
...over,
}
@@ -91,6 +94,35 @@ describe('harness team setup', () => {
expect(text).toContain('/Library/LaunchDaemons/ai.autonomous.harness.team.plist')
expect(text).toContain('✓ The Harness Team account is signed in.')
expect(text).toContain('✓ Private')
+ // The engines setup installed in the team account, and how to sign them in (none were reported in this run).
+ expect(text).toContain('engines ? not reported yet')
+ })
+
+ it('shows the team account\'s engines as its daemon reported them in this run, and how to sign them in', async () => {
+ const f = fake({ statusAfter: (t) => ({ ...reported(t), engines: { checkedAt: t + 3_000, claude: { installed: true, signedIn: false }, codex: { installed: true, signedIn: false } } }) })
+ expect(await teamCommand(['setup'], f.deps)).toBe(0)
+ const text = f.out.join('\n')
+ expect(text).toContain('Claude Code ✓ installed · ✗ not signed in')
+ expect(text).toContain(' codex login --device-auth Codex')
+ const json = fake({ statusAfter: (t) => ({ ...reported(t), engines: { checkedAt: t - 1, claude: { installed: true, signedIn: true }, codex: { installed: true, signedIn: true } } }) })
+ await teamCommand(['setup', '--json'], json.deps)
+ expect(JSON.parse(json.out.at(-1)!)).toMatchObject({ ok: true, engines: null })
+ })
+
+ it('forgets a prompt Desktop saw cancelled once it makes the account, and a removal is remembered as declined', async () => {
+ const decision = { clear: vi.fn(), decline: vi.fn() }
+ const made = fake({ statusAfter: reported, setupDecision: decision })
+ expect(await teamCommand(['setup'], made.deps)).toBe(0)
+ expect(decision.clear).toHaveBeenCalledTimes(1)
+ const cancelled = fake({ adminResult: { ok: false, code: 'CANCELLED', message: 'x' }, setupDecision: decision })
+ await teamCommand(['setup'], cancelled.deps)
+ expect(decision.clear).toHaveBeenCalledTimes(1)
+ const removed = fake({ readConfig: () => config, setupDecision: decision })
+ expect(await teamCommand(['remove'], removed.deps)).toBe(0)
+ expect(decision.decline).toHaveBeenCalledTimes(1)
+ expect(removed.out.join('\n')).toContain('will not make it again on its own')
+ const failing = fake({ statusAfter: reported, setupDecision: { clear: () => { throw new Error('read-only') }, decline: vi.fn() } })
+ expect(await teamCommand(['setup'], failing.deps)).toBe(0)
})
it('reports a failed privacy check or sign-in, and returns failure', async () => {
@@ -160,6 +192,22 @@ describe('harness team status', () => {
}
})
+ it('says whether the team account\'s engines are installed and signed in, and exactly how to sign them in', async () => {
+ const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })
+ f.status.set(STATUS, { version: 1, engines: { checkedAt: 1_000_000 - 60_000, claude: { installed: true, signedIn: false }, codex: { installed: false, signedIn: null } } })
+ await teamCommand(['status'], f.deps)
+ const text = f.out.join('\n')
+ expect(text).toContain('engines Claude Code ✓ installed · ✗ not signed in')
+ expect(text).toContain('Codex ✗ not installed · harness team setup installs it')
+ expect(text).toContain('(checked 60s ago)')
+ expect(text).toContain('in Harness, open a terminal on this Mac\'s Harness Team machine')
+ expect(text).toContain(' claude Claude Code')
+ const json = fake({ readConfig: () => config, accountExists: vi.fn(async () => true) })
+ json.status.set(STATUS, { version: 1, engines: { checkedAt: 5, claude: { installed: true, signedIn: true }, codex: { installed: true, signedIn: true } } })
+ await teamCommand(['status', '--json'], json.deps)
+ expect(JSON.parse(json.out[0]!).engines).toEqual({ checkedAt: 5, claude: { installed: true, signedIn: true }, codex: { installed: true, signedIn: true } })
+ })
+
it('shows what is wrong: a failed check, an open home, a stopped daemon', async () => {
const f = fake({ readConfig: () => config, accountExists: vi.fn(async () => true), mode: () => 0o750,
jobState: vi.fn(async () => ({ loaded: false, pid: null, state: null })), exists: (p) => p !== config.plist })
@@ -214,15 +262,59 @@ describe('harness team remove', () => {
})
describe('harness team on and off', () => {
- it('on: mints a team sign-in with this computer\'s, redeems it here, and swaps the daemon onto it', async () => {
- const f = fake({ platform: 'linux' })
+ it('on: mints a code that converts this very computer, with its machine key\'s proof, redeems it here, and swaps the daemon onto it', async () => {
+ const f = fake({ platform: 'linux', now: () => 1761300000000 })
+ const order: string[] = []
+ f.post.mockImplementation(async (path: string) => {
+ order.push(path)
+ if (path === '/api/auth/handoff') return { code: CODE, expiresIn: 90, kind: 'team' }
+ if (path === '/api/auth/handoff/redeem') return { token: 'hta_team', refreshToken: 'htr_team', expiresIn: 3600, kind: 'team' }
+ return {}
+ })
+ ;(f.deps.stopDaemon as ReturnType<typeof vi.fn>).mockImplementation(async () => { order.push('stop'); return true })
expect(await teamCommand(['on', '--yes'], f.deps)).toBe(0)
- expect(f.post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team' }, { authorization: 'Bearer x' })
+ expect(f.post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team', computerId: 'c'.repeat(32),
+ proof: { machineId: 'm1', at: 1761300000000, sig: expect.any(String) } }, { authorization: 'Bearer x' })
expect(f.post).toHaveBeenCalledWith('/api/auth/handoff/redeem', { code: CODE, label: 'Mac-placeholder · Team', computerId: computer.computerId })
- expect(f.session()).toMatchObject({ kind: 'team', accessToken: 'hna_team', computerId: computer.computerId, machineId: 'm1' })
+ // The daemon stops before the redeem: a daemon still on the old sign-in would make this an ordinary machine again.
+ expect(order.slice(0, 3)).toEqual(['/api/auth/handoff', 'stop', '/api/auth/handoff/redeem'])
+ // The team sign-in replaces the previous one in the session file; that one is signed out where it can be.
+ expect(f.session()).toEqual(expect.objectContaining({ kind: 'team', accessToken: 'hta_team', refreshToken: 'htr_team', computerId: computer.computerId, machineId: 'm1' }))
expect(f.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_old' })
+ expect(f.out.join('\n')).toContain('previous sign-in was discarded')
+ expect(f.deps.startDaemon).toHaveBeenCalled()
+ })
+
+ it('on: an Autonomous sign-in is discarded too, and one this computer cannot prove changes nothing', async () => {
+ const sso: AuthSession = { ...computer, accessToken: 'eyJ.sso-placeholder', refreshToken: 'sso-refresh-placeholder' }
+ const f = fake({ platform: 'linux' })
+ f.setSession(sso)
+ expect(await teamCommand(['on', '--yes'], f.deps)).toBe(0)
+ expect(f.session()).toMatchObject({ kind: 'team', accessToken: 'hna_team' })
+ expect(JSON.stringify(f.session())).not.toContain('sso')
+ expect(f.post).not.toHaveBeenCalledWith('/api/auth/revoke', expect.anything())
+ const nokey = fake({ platform: 'linux', machineKey: () => null })
+ nokey.setSession(sso)
+ expect(await teamCommand(['on', '--yes'], nokey.deps)).toBe(1)
+ expect(nokey.err[0]).toContain('no device key yet')
+ expect(nokey.err[0]).toContain('Nothing was changed on this computer.')
+ expect(nokey.post).not.toHaveBeenCalled()
+ expect(nokey.deps.stopDaemon).not.toHaveBeenCalled()
+ expect(nokey.session()).toBe(sso)
+ })
+
+ it('on: a refused redeem starts the daemon again on the sign-in it had, and changes nothing', async () => {
+ const f = fake({ platform: 'linux' })
+ f.post.mockImplementation(async (path: string) => {
+ if (path === '/api/auth/handoff') return { code: CODE, expiresIn: 90, kind: 'team' }
+ throw Object.assign(new Error('That code has expired.'), { status: 401 })
+ })
+ expect(await teamCommand(['on', '--yes', '--json'], f.deps)).toBe(1)
+ expect(JSON.parse(f.out.at(-1)!)).toMatchObject({ ok: false, code: 'EXPIRED', message: expect.stringContaining('Nothing was changed on this computer.') })
+ expect(f.session()).toBe(computer)
expect(f.deps.stopDaemon).toHaveBeenCalled()
expect(f.deps.startDaemon).toHaveBeenCalled()
+ expect(f.deps.writeSession).not.toHaveBeenCalled()
})
it('on: asks first at a terminal, needs --yes otherwise, and leaves a Mac with a team account alone', async () => {
@@ -255,15 +347,16 @@ describe('harness team on and off', () => {
expect(JSON.parse(old.out.at(-1)!)).toMatchObject({ ok: false, code: 'NOT_TEAM' })
expect(old.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_phone' })
expect(old.session()).toBe(computer)
- expect(old.deps.stopDaemon).not.toHaveBeenCalled()
+ // Stopped for the redeem, and started again on the sign-in it had.
+ expect(old.deps.startDaemon).toHaveBeenCalled()
})
it('off: signs the team session out, then the ordinary sign-in at a terminal, or says how', async () => {
const signIn = vi.fn(async () => {})
const f = fake({ interactive: true, signIn })
- f.setSession({ ...computer, kind: 'team', refreshToken: 'hnr_team' })
+ f.setSession({ ...computer, kind: 'team', refreshToken: 'htr_team' })
expect(await teamCommand(['off'], f.deps)).toBe(0)
- expect(f.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_team' })
+ expect(f.post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'htr_team' })
expect(f.session()).toBeNull()
expect(signIn).toHaveBeenCalledWith(true)
const quiet = fake()
@@ -304,8 +397,14 @@ describe('internal verbs', () => {
expect(f.deps.takeHandoff).toHaveBeenCalledWith('/Users/harnessteam/.harness/team-handoff')
expect(f.post).toHaveBeenCalledWith('/api/auth/handoff/redeem', { code: CODE, label: 'Mac-placeholder · Team', computerId: 't'.repeat(32) })
expect(f.session()).toMatchObject({ kind: 'team', computerId: 't'.repeat(32), refreshToken: 'hnr_team' })
- expect(f.status.get(STATUS)).toMatchObject({ signIn: { state: 'signed-in' }, privacy: { passed: true } })
+ expect(f.status.get(STATUS)).toMatchObject({ signIn: { state: 'signed-in' }, privacy: { passed: true },
+ engines: { claude: { installed: true, signedIn: false }, codex: { installed: true, signedIn: true } } })
+ expect(f.deps.engines).toHaveBeenCalledWith(config)
expect(f.out.join('\n')).toContain('[team] signed in for team work')
+ expect(f.out.join('\n')).toContain('[team] engines: claude installed, codex signed in')
+ const broken = inTeam({ engines: vi.fn(async () => { throw new Error('no home') }) })
+ expect(await teamCommand(['__start'], broken.deps)).toBe(0)
+ expect(broken.out.join('\n')).toContain('could not check the engines: no home')
})
it('__start stores nothing when the backend makes a session that is not a team one', async () => {
diff --git a/cli/src/team/command.ts b/cli/src/team/command.ts
index 53b4383dc..df6c1e7e6 100644
--- a/cli/src/team/command.ts
+++ b/cli/src/team/command.ts
@@ -16,7 +16,8 @@
import type { AuthSession } from '../lib/authSession.js'
import type { RunAdmin } from './admin.js'
import { teamConfigJson, type TeamConfig } from './config.js'
-import { mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Post } from './handoff.js'
+import { engineLines, type TeamEngines } from './engines.js'
+import { mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Get, type Post } from './handoff.js'
import {
SENTINEL_NAME, TEAM_CONFIG_FILE, TEAM_HOME, TEAM_LABEL, TEAM_PLIST, TEAM_PORT, TEAM_REAL_NAME, TEAM_STATUS_DIR, TEAM_STATUS_FILE,
TEAM_USER, TeamInputError, carriedBackendEnv, checkPath, checkUser, teamPaths,
@@ -29,8 +30,9 @@ export const TEAM_USAGE = [
'',
' setup make the Harness Team account on this Mac for Swarm work: a separate standard user, "Harness Team"',
` (${TEAM_USER}), whose own Harness daemon runs teammates' agents so they cannot read your files. macOS asks`,
- ' for an administrator password once. Running it again repairs it (--sign-in-again: a new sign-in for it)',
- ' status whether the account exists and runs, its sign-in and privacy check, and everything setup made',
+ ' for an administrator password once. It installs the account\'s own Claude Code and Codex, which you sign in',
+ ' once in a terminal on its machine. Running it again repairs it (--sign-in-again: a new sign-in for it)',
+ ' status whether the account exists and runs, its sign-in, privacy check and engines, and everything setup made',
' remove delete the account, its home folder and its daemon (administrator password); your home stays private',
' 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)',
@@ -76,6 +78,10 @@ export interface TeamCommandDeps {
/** 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
+ /** 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'
@@ -90,15 +96,19 @@ export interface TeamCommandDeps {
accountExists(user: string): Promise<boolean>
jobState(label: string): Promise<JobState>
- /** The team account's side: its handed-over code, and the privacy check. */
+ /** 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>
+ /** What Desktop's automatic offer remembers (./autoSetup.ts): a setup that made the account forgets a cancelled prompt,
+ * and a removal is remembered as one, so the account is not made again on its own. */
+ setupDecision?: { clear(): void; decline(): void }
}
export async function teamCommand(argv: string[], deps: TeamCommandDeps): Promise<number> {
@@ -146,6 +156,7 @@ function madeLines(ownerHome: string): string[] {
` log ${team.log} (inside the account's home)`,
` setup ${TEAM_CONFIG_FILE} and ${TEAM_STATUS_DIR}/`,
` check ${ownerHome}/${SENTINEL_NAME}, a file the account must not be able to read`,
+ ` engines Claude Code and Codex in ${TEAM_HOME}/.local, installed by the account itself`,
` your home ${ownerHome}, made private (mode 700)`,
]
}
@@ -204,6 +215,7 @@ async function setup(deps: TeamCommandDeps, json: boolean, signInAgain: boolean)
if (result.code === 'CANCELLED') return fail(deps, json, 'CANCELLED', 'Nothing was changed: the administrator prompt was cancelled.')
return fail(deps, json, 'SETUP_FAILED', `The Harness Team account was not finished: ${result.message} Run \`harness team setup\` again; it repairs what is there.`)
}
+ try { deps.setupDecision?.clear() } catch { /* only Desktop's offer reads it */ }
const handedOver = /handed a sign-in to the team account/.test(result.stdout)
if (!json) deps.out(handedOver ? 'Waiting for the team daemon to sign in and check its privacy…' : 'Waiting for the team daemon to check its privacy…')
// The daemon reports through its status file (./privacy.ts): the sign-in when it redeemed one, the check every start.
@@ -219,9 +231,10 @@ async function setup(deps: TeamCommandDeps, json: boolean, signInAgain: boolean)
}
const privacy = report?.privacy && report.privacy.checkedAt >= startedAt ? report.privacy : null
const signIn = report?.signIn && (!handedOver || report.signIn.at >= startedAt) ? report.signIn : null
+ const engines = report?.engines && report.engines.checkedAt >= startedAt ? report.engines : undefined
if (json) {
const ok = privacy?.passed === true && (!handedOver || signIn?.state === 'signed-in')
- deps.out(JSON.stringify({ ok, user: TEAM_USER, home: TEAM_HOME, label: TEAM_LABEL, plist: TEAM_PLIST, privacy, signIn }))
+ deps.out(JSON.stringify({ ok, user: TEAM_USER, home: TEAM_HOME, label: TEAM_LABEL, plist: TEAM_PLIST, privacy, signIn, engines: engines ?? null }))
return ok ? 0 : 1
}
let code = 0
@@ -231,6 +244,8 @@ async function setup(deps: TeamCommandDeps, json: boolean, signInAgain: boolean)
if (privacy?.passed) deps.out('✓ Private: the team account cannot read your files.')
else if (privacy) { deps.err(`✗ Not private (${privacy.item}): ${privacy.detail}`); code = 1 }
else deps.out('! The team daemon has not reported its privacy check yet: harness team status')
+ // Installed by setup into the team account's own home; signed in once by the owner, in a terminal on the team machine.
+ for (const line of engineLines(engines, (at) => ago(deps.now(), at))) deps.out(line)
deps.out(' status: harness team status · undo: harness team remove')
return code
}
@@ -265,7 +280,7 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {
account: exists, user, realName: config?.realName ?? TEAM_REAL_NAME, home, homePresent: deps.exists(home),
label: config?.label ?? TEAM_LABEL, plist: config?.plist ?? TEAM_PLIST, plistPresent, job, port: config?.port ?? TEAM_PORT,
config: config ? TEAM_CONFIG_FILE : null, ownerHomeMode: homeMode === null ? null : homeMode.toString(8),
- signIn: report?.signIn ?? null, privacy: report?.privacy ?? null, dedicated,
+ signIn: report?.signIn ?? null, privacy: report?.privacy ?? null, engines: report?.engines ?? null, dedicated,
}))
return 0
}
@@ -278,6 +293,7 @@ async function status(deps: TeamCommandDeps, json: boolean): Promise<number> {
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)})`}`)
deps.out(` your home ${ownerHome} · mode ${homeMode === null ? 'unknown' : homeMode.toString(8)}${homeMode === 0o700 ? ' ✓' : ' ✗ should be 700: harness team setup makes it private again'}`)
+ for (const line of engineLines(report?.engines, (at) => ago(now, at))) deps.out(line)
deps.out('')
deps.out(' What setup made:')
for (const line of madeLines(ownerHome)) deps.out(` ${line}`)
@@ -305,10 +321,12 @@ async function remove(deps: TeamCommandDeps, json: boolean): Promise<number> {
if (result.code === 'CANCELLED') return fail(deps, json, 'CANCELLED', 'Nothing was removed: the administrator prompt was cancelled.')
return fail(deps, json, 'REMOVE_FAILED', `The Harness Team account was not fully removed: ${result.message} Run \`harness team remove\` again.`)
}
+ try { deps.setupDecision?.decline() } catch { /* only Desktop's offer reads it */ }
if (json) deps.out(JSON.stringify({ ok: true, removed: true }))
else {
deps.out(`✓ Removed the Harness Team account (${TEAM_USER}), ${TEAM_HOME} and the daemon ${TEAM_LABEL}.`)
deps.out(` Your home folder stays private (mode 700). Its computer stays in your list until you remove it: harness machines`)
+ deps.out(' Harness will not make it again on its own when you join a Swarm; harness team setup makes it again.')
}
return 0
}
@@ -332,22 +350,30 @@ async function teamOn(deps: TeamCommandDeps, json: boolean, yes: boolean): Promi
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 {
- const { code } = await mintTeamHandoff(() => deps.auth(), deps.post)
tokens = await redeemTeamHandoff(code, label, session.computerId, { post: deps.post, sleep: deps.sleep, now: deps.now })
} catch (error) {
- if (error instanceof TeamSignInError) throw new TeamSignInError(`${error.message} Nothing was changed on this computer.`, error.code)
- throw error
+ if (wasRunning) await deps.startDaemon()
+ throw unchanged(error)
}
- // The daemon holds the computer's sign-in in memory: it stops before the file changes, and comes back on the new one.
- const wasRunning = await deps.stopDaemon()
+ // 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. undo: harness team off')
+ 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
}
@@ -428,6 +454,11 @@ async function jobStart(deps: TeamCommandDeps, file: string | undefined): Promis
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
}
diff --git a/cli/src/team/deps.ts b/cli/src/team/deps.ts
index ac81f85a4..ae6f2eff4 100644
--- a/cli/src/team/deps.ts
+++ b/cli/src/team/deps.ts
@@ -5,8 +5,9 @@ import { dirname, join } from 'node:path'
import { createInterface } from 'node:readline'
import { env } from '../config/env.js'
import { clearAuthSession, readAuthSession, writeAuthSession } from '../lib/authSession.js'
-import { controlPlaneAuth, postJson } from '../lib/controlPlane.js'
+import { controlPlaneAuth, postJson, requestJson } from '../lib/controlPlane.js'
import { computerId } from '../lib/daemonState.js'
+import { peekIdentity } from '../lib/e2ee/store.js'
import { runGuestCommand, type GuestRunner } from '../lib/guestAccounts.js'
import { managedNodeRuntimeDir } from '../lib/guestHelperInstall.js'
import { managedNodePath } from '../lib/nodeRuntime.js'
@@ -16,6 +17,8 @@ import type { JobState, TeamCommandDeps } from './command.js'
import { readTeamConfig } from './config.js'
import { realPrivacyDeps, readTeamStatus, runPrivacyCheck, writeTeamStatus } from './privacy.js'
import { takeHandoffFile } from './handoff.js'
+import { checkTeamEngines, realEngineCheckDeps } from './engines.js'
+import { teamSetupDecisionFile, writeTeamSetupDecision } from './autoSetup.js'
/** What `launchctl print system/<label>` says of a job; not loaded when launchd does not know it. Readable without root. */
export function parseLaunchctlPrint(code: number | null, stdout: string): JobState {
@@ -53,6 +56,8 @@ export function teamCommandDeps(options: {
clearSession: clearAuthSession,
auth: controlPlaneAuth,
post: (path, body, headers) => postJson(path, body, headers ?? {}),
+ get: (path, headers) => requestJson('GET', path, undefined, headers ?? {}),
+ machineKey: () => peekIdentity(),
computerId,
autonomousEnv: env.AUTONOMOUS_ENV,
installed: () => {
@@ -78,6 +83,11 @@ export function teamCommandDeps(options: {
},
takeHandoff: (path) => takeHandoffFile(path),
privacy: (config) => runPrivacyCheck(config, realPrivacyDeps),
+ engines: (config) => checkTeamEngines(realEngineCheckDeps(config.home)),
+ setupDecision: {
+ clear: () => writeTeamSetupDecision(teamSetupDecisionFile(env.ADAPTER_DATA_DIR), null),
+ decline: () => writeTeamSetupDecision(teamSetupDecisionFile(env.ADAPTER_DATA_DIR), { state: 'declined', at: Date.now() }),
+ },
stopDaemon: options.stopDaemon,
startDaemon: options.startDaemon,
...(options.signIn ? { signIn: options.signIn } : {}),
diff --git a/cli/src/team/engines.spec.ts b/cli/src/team/engines.spec.ts
new file mode 100644
index 000000000..1704fefb4
--- /dev/null
+++ b/cli/src/team/engines.spec.ts
@@ -0,0 +1,118 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { TeamConfig } from './config.js'
+import { checkTeamEngines, engineLines, realEngineCheckDeps, teamEngineBin, TeamEngineReporter, type TeamEngines } from './engines.js'
+import { readTeamStatus, type TeamStatus } from './privacy.js'
+
+const config = { user: 'harnessteam', home: '/Users/harnessteam', statusFile: '/status.json' } as TeamConfig
+const engines = (over: Partial<TeamEngines> = {}): TeamEngines =>
+ ({ checkedAt: 1_000, claude: { installed: true, signedIn: true }, codex: { installed: true, signedIn: true }, ...over })
+
+const cleanup: string[] = []
+afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+describe('the team account\'s engines', () => {
+ it('are installed when its own ~/.local/bin holds them, and signed in as the engine\'s own files say', async () => {
+ const account = vi.fn(async (engine: string) => ({ signedIn: engine === 'claude' ? false : null, lastUsedAt: null }))
+ const result = await checkTeamEngines({ home: '/Users/harnessteam', executable: (path) => path === '/Users/harnessteam/.local/bin/claude', account, now: () => 42 })
+ expect(result).toEqual({ checkedAt: 42, claude: { installed: true, signedIn: false }, codex: { installed: false, signedIn: null } })
+ expect(teamEngineBin('/h', 'codex')).toBe('/h/.local/bin/codex')
+ const failing = await checkTeamEngines({ home: '/h', executable: () => true, account: async () => { throw new Error('unreadable') }, now: () => 1 })
+ expect(failing.claude).toEqual({ installed: true, signedIn: null })
+ })
+
+ it('reads a home it is given, never the owner\'s: an executable, and a credential file\'s presence', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'team-engines-'))
+ cleanup.push(home)
+ mkdirSync(join(home, '.local', 'bin'), { recursive: true })
+ writeFileSync(join(home, '.local', 'bin', 'codex'), '#!/bin/sh\n', { mode: 0o755 })
+ writeFileSync(join(home, '.local', 'bin', 'claude'), 'not executable', { mode: 0o644 })
+ mkdirSync(join(home, '.codex'))
+ writeFileSync(join(home, '.codex', 'auth.json'), JSON.stringify({ tokens: { refresh_token: 'present' } }))
+ // Codex's answer is read from the files; Claude Code's would also look in this Mac's Keychain, which a test leaves alone.
+ const real = realEngineCheckDeps(home, {})
+ const result = await checkTeamEngines({ ...real, now: () => 7,
+ account: (engine) => engine === 'codex' ? real.account(engine) : Promise.resolve({ signedIn: null, lastUsedAt: null }) })
+ expect(result.codex).toEqual({ installed: true, signedIn: true })
+ expect(result.claude.installed).toBe(false)
+ })
+
+ it('are said plainly in status, with exactly how to sign in the ones that are not', () => {
+ const ago = (at: number) => `${at}s ago`
+ const lines = engineLines(engines({ claude: { installed: true, signedIn: false }, codex: { installed: false, signedIn: null } }), ago).join('\n')
+ expect(lines).toContain('Claude Code ✓ installed · ✗ not signed in')
+ expect(lines).toContain('Codex ✗ not installed · harness team setup installs it')
+ expect(lines).toContain('open a terminal on this Mac\'s Harness Team machine')
+ expect(lines).toContain(' claude Claude Code')
+ expect(lines).not.toContain('codex login')
+ expect(lines).toContain('Your own sign-ins are not copied into the team account')
+ const unknown = engineLines(engines({ codex: { installed: true, signedIn: null } }), ago).join('\n')
+ expect(unknown).toContain('Codex ✓ installed · ? sign-in unknown')
+ expect(unknown).toContain(' codex login --device-auth Codex')
+ const ready = engineLines(engines(), ago).join('\n')
+ expect(ready).toContain('✓ installed · ✓ signed in')
+ 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'])
+ })
+})
+
+describe('TeamEngineReporter', () => {
+ const reporter = (over: { user?: string; config?: TeamConfig | null; checked?: TeamEngines[] } = {}) => {
+ const status: { value: TeamStatus | null } = { value: null }
+ const results = [...(over.checked ?? [engines()])]
+ const check = vi.fn(async () => results.length > 1 ? results.shift()! : results[0]!)
+ const write = vi.fn((_path: string, update: Partial<TeamStatus>) => { status.value = { ...(status.value ?? { version: 1 }), ...update, version: 1 } })
+ const r = new TeamEngineReporter({ config: () => over.config === undefined ? config : over.config, user: () => over.user ?? 'harnessteam',
+ check, read: () => status.value, write, intervalMs: 60_000 })
+ return { r, check, write, status }
+ }
+
+ it('reports only in the Harness Team account, and writes only what changed or has grown old', async () => {
+ const owner = reporter({ user: 'owner-placeholder' })
+ owner.r.start()
+ await owner.r.report()
+ expect(owner.check).not.toHaveBeenCalled()
+ await expect(reporter({ config: null }).r.report()).resolves.toBeUndefined()
+
+ const team = reporter({ checked: [engines({ checkedAt: 1_000 }), engines({ checkedAt: 2_000 }),
+ engines({ checkedAt: 3_000, claude: { installed: true, signedIn: false } }), engines({ checkedAt: 3_000 + 10 * 60_000 })] })
+ await team.r.report()
+ expect(team.write).toHaveBeenCalledTimes(1)
+ await team.r.report()
+ expect(team.write).toHaveBeenCalledTimes(1)
+ await team.r.report()
+ expect(team.write).toHaveBeenCalledTimes(2)
+ expect(team.status.value?.engines?.claude.signedIn).toBe(false)
+ await team.r.report()
+ expect(team.write).toHaveBeenCalledTimes(3)
+ })
+
+ it('looks again on a timer while started, and a failed look waits for the next', async () => {
+ vi.useFakeTimers()
+ try {
+ const team = reporter()
+ team.check.mockRejectedValueOnce(new Error('disk'))
+ team.r.start()
+ team.r.start()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(team.write).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(team.write).toHaveBeenCalledTimes(1)
+ team.r.stop()
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(team.check).toHaveBeenCalledTimes(2)
+ } finally { vi.useRealTimers() }
+ })
+
+ it('is what the status file keeps, and an engines field that is not one is dropped', () => {
+ const read = (value: unknown) => readTeamStatus('/s', () => JSON.stringify({ version: 1, engines: value }))?.engines
+ expect(read(engines())).toEqual(engines())
+ for (const bad of [null, 'x', { checkedAt: 'now' }, { checkedAt: 1, claude: { installed: true, signedIn: true } },
+ { ...engines(), codex: { installed: 'yes', signedIn: true } }, { ...engines(), codex: { installed: true, signedIn: 'maybe' } }]) {
+ expect(read(bad), JSON.stringify(bad)).toBeUndefined()
+ }
+ })
+})
diff --git a/cli/src/team/engines.ts b/cli/src/team/engines.ts
new file mode 100644
index 000000000..d96a6df54
--- /dev/null
+++ b/cli/src/team/engines.ts
@@ -0,0 +1,152 @@
+/**
+ * Claude Code and Codex in the Harness Team account (docs/plans/2026-10-24-swarm-team-account.md, Task 2).
+ *
+ * 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.
+ *
+ * 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.
+ */
+import { accessSync, constants } from 'node:fs'
+import { userInfo } from 'node:os'
+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'
+
+export type TeamEngine = 'claude' | 'codex'
+
+export interface TeamEngineInfo {
+ engine: TeamEngine
+ name: string
+ /** The vendor's npm package (lib/engineInstall.ts), installed by the team account under `~/.local`. */
+ packageName: string
+ /** What the owner runs in a terminal on the team machine to sign it in. */
+ signIn: string
+}
+
+export const TEAM_ENGINES: readonly TeamEngineInfo[] = [
+ { engine: 'claude', name: 'Claude Code', packageName: '@anthropic-ai/claude-code', signIn: 'claude' },
+ { engine: 'codex', name: 'Codex', packageName: '@openai/codex', signIn: 'codex login --device-auth' },
+]
+
+export interface EngineReadiness { installed: boolean; signedIn: boolean | null }
+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). */
+export const teamEngineBin = (home: string, engine: TeamEngine) => join(home, '.local', 'bin', engine)
+
+export interface EngineCheckDeps {
+ home: string
+ executable(path: string): boolean
+ account(engine: TeamEngine): Promise<EngineAccount>
+ now(): number
+}
+
+/** What the team account has of each engine: installed in its own home, and signed in (null when it cannot say). */
+export async function checkTeamEngines(deps: EngineCheckDeps): Promise<TeamEngines> {
+ const result = { checkedAt: deps.now() } as TeamEngines
+ for (const { engine } of TEAM_ENGINES) {
+ const installed = deps.executable(teamEngineBin(deps.home, engine))
+ let signedIn: boolean | null = null
+ try { signedIn = (await deps.account(engine)).signedIn } catch { /* cannot say */ }
+ result[engine] = { installed, signedIn }
+ }
+ return result
+}
+
+export const realEngineCheckDeps = (home: string, env: NodeJS.ProcessEnv = process.env): EngineCheckDeps => ({
+ home,
+ executable: (path) => { try { accessSync(path, constants.X_OK); return true } catch { return false } },
+ // 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(),
+})
+
+/** How often the team daemon looks again: an engine signed in shows in `harness team status` within this long. */
+export const ENGINE_RECHECK_MS = 60_000
+
+export interface EngineReporterDeps {
+ config(): TeamConfig | null
+ user(): string
+ check(config: TeamConfig): Promise<TeamEngines>
+ read(path: string): TeamStatus | null
+ write(path: string, update: Partial<Omit<TeamStatus, 'version'>>): void
+ intervalMs?: number
+}
+
+/** Writes the team account's engines to its status file, while this daemon runs in the Harness Team account. */
+export class TeamEngineReporter {
+ private timer: NodeJS.Timeout | null = null
+ private running: Promise<void> | null = null
+ constructor(private readonly deps: EngineReporterDeps) {}
+
+ start(): void {
+ if (this.timer || !this.inTeamAccount()) return
+ this.timer = setInterval(() => { void this.report() }, this.deps.intervalMs ?? ENGINE_RECHECK_MS)
+ this.timer.unref?.()
+ void this.report()
+ }
+
+ stop(): void {
+ if (this.timer) clearInterval(this.timer)
+ this.timer = null
+ }
+
+ private inTeamAccount(): TeamConfig | null {
+ const config = this.deps.config()
+ return config && config.user === this.deps.user() ? config : null
+ }
+
+ /** One look, written only when something changed; never two at once. Never throws. */
+ report(): Promise<void> {
+ this.running ??= (async () => {
+ const config = this.inTeamAccount()
+ if (!config) return
+ const engines = await this.deps.check(config)
+ const before = this.deps.read(config.statusFile)?.engines
+ const same = before && TEAM_ENGINES.every(({ engine }) =>
+ before[engine].installed === engines[engine].installed && before[engine].signedIn === engines[engine].signedIn)
+ // 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) return
+ this.deps.write(config.statusFile, { engines })
+ })().catch(() => { /* the next look reports it */ }).finally(() => { this.running = null })
+ return this.running
+ }
+}
+
+export function teamEngineReporter(): TeamEngineReporter {
+ return new TeamEngineReporter({
+ config: () => readTeamConfig(),
+ user: () => userInfo().username,
+ check: (config) => checkTeamEngines(realEngineCheckDeps(config.home)),
+ read: (path) => readTeamStatus(path),
+ write: writeTeamStatus,
+ })
+}
+
+/** What `harness team status` and setup say of the engines, and exactly how to sign them in. */
+export function engineLines(engines: TeamEngines | undefined, ago: (at: number) => string): string[] {
+ if (!engines) {
+ return [' engines ? not reported yet: the team daemon reports them once it runs']
+ }
+ const lines = TEAM_ENGINES.map(({ engine, name }, index) => {
+ 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'
+ 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)
+ 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:')
+ for (const { name, signIn } of unsigned) lines.push(` ${signIn.padEnd(28)}${name}`)
+ lines.push(' Your own sign-ins are not copied into the team account; each engine bills the account you sign in with.')
+ }
+ return lines
+}
diff --git a/cli/src/team/handoff.spec.ts b/cli/src/team/handoff.spec.ts
index bde65e931..4d6461b8e 100644
--- a/cli/src/team/handoff.spec.ts
+++ b/cli/src/team/handoff.spec.ts
@@ -3,7 +3,12 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AuthSession } from '../lib/authSession.js'
-import { mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, takeHandoffFile, teamSession, TeamSignInError } from './handoff.js'
+import { b64d, b64e, verify } from '../lib/e2ee/core.js'
+import { ed25519 } from '@noble/curves/ed25519'
+import {
+ mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, takeHandoffFile, teamConversionMessage, teamConversionProof,
+ teamSession, TeamSignInError,
+} from './handoff.js'
const CODE = `hnh_${'a'.repeat(43)}`
const computer: AuthSession = { version: 1, accessToken: 'access-placeholder', autonomousEnv: 'prod', computerId: 'c'.repeat(32), updatedAt: 1 }
@@ -35,6 +40,79 @@ describe('mintTeamHandoff', () => {
})
})
+/**
+ * The backend's own vector, made with its `teamConversionMessage` (backend/src/lib/teamSession.ts on the team sessions
+ * branch: `harness team conversion v1\n${userId}\n${computerId}\n${machineId}\n${at}`) and its noble ed25519, from the
+ * private key 32 bytes of 9 its tests use. The computer id is the backend's wire form: lowercase, no dashes.
+ */
+const VECTOR = {
+ priv: new Uint8Array(32).fill(9),
+ pub: '/RckOFqgx1tk+3jNYC+h2ZH96/drE8WO1wLqyDXp9hg=',
+ userId: 'user-placeholder-1', computerId: '0F1E2D3C-4B5A-6978-8796-A5B4C3D2E1F0', wireComputerId: '0f1e2d3c4b5a69788796a5b4c3d2e1f0',
+ machineId: 'machine-placeholder-1', at: 1761300000000,
+ message: 'harness team conversion v1\nuser-placeholder-1\n0f1e2d3c4b5a69788796a5b4c3d2e1f0\nmachine-placeholder-1\n1761300000000',
+ sig: 'Jm32Kn6SMoox+JdknfweQyzrE7k8NMkmhIUZYzjULM6gAeV/TmgwVq/xjMB8s076bXz9FKQidfz09ltW6bcKCA==',
+}
+
+describe('team conversion proof', () => {
+ it('signs the backend\'s message, byte for byte, with the machine key, over the computer id as the backend keeps it', () => {
+ expect(teamConversionMessage(VECTOR.userId, VECTOR.wireComputerId, VECTOR.machineId, VECTOR.at)).toBe(VECTOR.message)
+ expect(b64e(ed25519.getPublicKey(VECTOR.priv))).toBe(VECTOR.pub)
+ const proof = teamConversionProof({ userId: VECTOR.userId, computerId: VECTOR.computerId, machineId: VECTOR.machineId, at: VECTOR.at, priv: VECTOR.priv })
+ expect(proof).toEqual({ machineId: VECTOR.machineId, at: VECTOR.at, sig: VECTOR.sig })
+ expect(verify(b64d(VECTOR.pub), new TextEncoder().encode(VECTOR.message), b64d(proof.sig))).toBe(true)
+ })
+})
+
+describe('mintTeamConversion', () => {
+ const autonomous: AuthSession = { ...computer, computerId: VECTOR.computerId, machineId: VECTOR.machineId }
+ const harness: AuthSession = { ...autonomous, accessToken: 'hna_computer', refreshToken: 'hnr_computer', method: 'qr' }
+ const deps = (session: AuthSession, over: Record<string, unknown> = {}) => ({
+ auth: async () => ({ session, headers }),
+ post: vi.fn(async () => ({ code: CODE, expiresIn: 90, kind: 'team' })),
+ get: vi.fn(async () => ({ user: { id: VECTOR.userId } })),
+ machineKey: () => ({ priv: VECTOR.priv }),
+ now: () => VECTOR.at,
+ ...over,
+ })
+
+ it('asks for a code for this very computer, with its machine key\'s proof, whichever sign-in it has', async () => {
+ for (const session of [autonomous, harness]) {
+ const d = deps(session)
+ await expect(mintTeamConversion(d as never)).resolves.toEqual({ code: CODE, expiresIn: 90 })
+ expect(d.get).toHaveBeenCalledWith('/api/auth/me', headers)
+ expect(d.post).toHaveBeenCalledWith('/api/auth/handoff',
+ { kind: 'team', computerId: VECTOR.wireComputerId, proof: { machineId: VECTOR.machineId, at: VECTOR.at, sig: VECTOR.sig } }, headers)
+ }
+ })
+
+ it('refuses an Autonomous sign-in it cannot prove is this computer, before asking; a Harness sign-in asks without', async () => {
+ const cases: Array<[Record<string, unknown>, AuthSession, string]> = [
+ [{ machineKey: () => null }, autonomous, 'no device key'],
+ [{}, { ...autonomous, machineId: undefined }, 'Start Harness once'],
+ [{ get: vi.fn(async () => ({ user: {} })) }, autonomous, 'did not say which account'],
+ [{ get: vi.fn(async () => { throw new Error('offline') }) }, autonomous, 'offline'],
+ ]
+ for (const [over, session, says] of cases) {
+ const d = deps(session, over)
+ await expect(mintTeamConversion(d as never), says).rejects.toThrow(says)
+ expect(d.post).not.toHaveBeenCalled()
+ const own = deps({ ...session, accessToken: 'hna_computer' }, over)
+ await expect(mintTeamConversion(own as never)).resolves.toEqual({ code: CODE, expiresIn: 90 })
+ expect(own.post).toHaveBeenCalledWith('/api/auth/handoff', { kind: 'team', computerId: VECTOR.wireComputerId }, headers)
+ }
+ })
+
+ it('refuses a team sign-in and a signed-out computer, and an answer that is not a team code', async () => {
+ await expect(mintTeamConversion(deps({ ...autonomous, kind: 'team' }) as never)).rejects.toMatchObject({ code: 'TEAM_SESSION' })
+ await expect(mintTeamConversion(deps(autonomous, { auth: async () => { throw new Error('Not signed in.') } }) as never)).rejects.toMatchObject({ code: 'NOT_SIGNED_IN' })
+ await expect(mintTeamConversion(deps(autonomous, { post: vi.fn(async () => ({ code: CODE, kind: 'viewer' })) }) as never)).rejects.toMatchObject({ code: 'BACKEND' })
+ const refused = Object.assign(new Error('Only this computer can make itself a team machine'), { status: 403 })
+ await expect(mintTeamConversion(deps(autonomous, { post: vi.fn(async () => { throw refused }) }) as never))
+ .rejects.toThrow('Only this computer can make itself a team machine')
+ })
+})
+
describe('redeemTeamHandoff', () => {
it('redeems for this computer id, with its label', async () => {
const post = vi.fn(async () => ({ token: 'hna_t', refreshToken: 'hnr_r', expiresIn: 3600, kind: 'team' }))
@@ -85,6 +163,9 @@ describe('team session and revoke', () => {
const post = vi.fn(async () => ({}))
expect(await revokeHarnessRefresh(post as never, 'hnr_x')).toBe(true)
expect(post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'hnr_x' })
+ // A team session's refresh token (hta_/htr_) is the backend's own too.
+ expect(await revokeHarnessRefresh(post as never, 'htr_team')).toBe(true)
+ expect(post).toHaveBeenCalledWith('/api/auth/revoke', { refreshToken: 'htr_team' })
expect(await revokeHarnessRefresh(post as never, 'eyJ.sso')).toBe(false)
expect(await revokeHarnessRefresh(post as never, undefined)).toBe(false)
expect(await revokeHarnessRefresh((async () => { throw new Error('down') }) as never, 'hnr_x')).toBe(false)
diff --git a/cli/src/team/handoff.ts b/cli/src/team/handoff.ts
index 93eeab5ee..78067571b 100644
--- a/cli/src/team/handoff.ts
+++ b/cli/src/team/handoff.ts
@@ -8,36 +8,111 @@
*
* In the Harness Team account the code travels in a file only that account can read (owner the team account, mode
* 600), written by setup just before the job starts; the daemon reads it, deletes it, then redeems it.
+ *
+ * A computer used only for agents turns ITSELF into a team machine (`harness team on`): its code is minted for its own
+ * computer id, so its Swarm contributions and history survive. Only that computer may ask. A Harness computer sign-in
+ * says which computer it is; an Autonomous sign-in names none, so the request carries a proof: this computer's machine
+ * key on the account's device key log signs `teamConversionMessage` (the backend's, backend/src/lib/teamSession.ts).
*/
import { constants, fstatSync, openSync, readSync, closeSync, unlinkSync } from 'node:fs'
+import { b64e, sign, utf8 } from '../lib/e2ee/core.js'
import type { AuthSession } from '../lib/authSession.js'
import { HANDOFF_CODE } from './layout.js'
export type Post = <T>(path: string, body: unknown, headers?: Record<string, string>) => Promise<T>
+export type Get = <T>(path: string, headers?: Record<string, string>) => Promise<T>
+type SignedIn = { session: AuthSession; headers: Record<string, string> }
export class TeamSignInError extends Error {
- constructor(message: string, readonly code: 'NOT_SIGNED_IN' | 'TEAM_SESSION' | 'EXPIRED' | 'BACKEND' | 'NOT_TEAM' | 'UNSAFE_FILE') {
+ constructor(message: string, readonly code: 'NOT_SIGNED_IN' | 'TEAM_SESSION' | 'EXPIRED' | 'BACKEND' | 'NOT_TEAM' | 'UNSAFE_FILE' | 'NO_PROOF') {
super(message)
this.name = 'TeamSignInError'
}
}
-/** A team handoff code from this computer's own sign-in. Refused for a team sign-in: it may not hand one out. */
-export async function mintTeamHandoff(
- auth: () => Promise<{ session: AuthSession; headers: Record<string, string> }>, post: Post,
-): Promise<{ code: string; expiresIn: number }> {
- let signedIn: { session: AuthSession; headers: Record<string, string> }
+/** One wire form for a computer id, as the backend keeps it (`normalizeComputerId`): lowercase, without dashes. */
+export const wireComputerId = (raw: string) => raw.trim().toLowerCase().replace(/-/g, '')
+
+/** What a computer signs to turn itself into a team machine: the backend's `teamConversionMessage`, byte for byte.
+ * [at] is milliseconds since the epoch; the backend takes it within 5 minutes of its clock, once. */
+export function teamConversionMessage(userId: string, computerId: string, machineId: string, at: number): string {
+ return `harness team conversion v1\n${userId}\n${computerId}\n${machineId}\n${at}`
+}
+
+export interface ConversionProof { machineId: string; at: number; sig: string }
+
+/** The proof, signed with this computer's machine key (base64 ed25519 over the UTF-8 message). */
+export function teamConversionProof(input: { userId: string; computerId: string; machineId: string; at: number; priv: Uint8Array }): ConversionProof {
+ const message = teamConversionMessage(input.userId, wireComputerId(input.computerId), input.machineId, input.at)
+ return { machineId: input.machineId, at: input.at, sig: b64e(sign(input.priv, utf8(message))) }
+}
+
+async function signedIn(auth: () => Promise<SignedIn>): Promise<SignedIn> {
+ let answer: SignedIn
try {
- signedIn = await auth()
+ answer = await auth()
} catch (error) {
throw new TeamSignInError(`This computer is not signed in: ${(error as Error).message}`, 'NOT_SIGNED_IN')
}
- if (signedIn.session.kind === 'team') {
+ if (answer.session.kind === 'team') {
throw new TeamSignInError('This computer runs team work only, and a team sign-in cannot hand out another.', 'TEAM_SESSION')
}
+ return answer
+}
+
+/** A team handoff code from this computer's own sign-in. Refused for a team sign-in: it may not hand one out. */
+export async function mintTeamHandoff(auth: () => Promise<SignedIn>, post: Post): Promise<{ code: string; expiresIn: number }> {
+ const { headers } = await signedIn(auth)
+ return requestCode(post, { kind: 'team' }, headers)
+}
+
+export interface ConversionDeps {
+ auth: () => Promise<SignedIn>
+ post: Post
+ get: Get
+ /** This computer's machine key, the one the account's device key log holds for it; null when it has none yet.
+ * Never made here: a key made now would be on no log. */
+ machineKey: () => { priv: Uint8Array } | null
+ now: () => number
+}
+
+/**
+ * A code that turns THIS computer into a team machine (`harness team on`), keeping its computer id. With a proof whenever
+ * one can be made: a Harness computer sign-in from before the backend recorded its computer needs one too. Without one, only
+ * a Harness sign-in may still ask (the backend checks the computer it recorded); an Autonomous sign-in is refused here.
+ */
+export async function mintTeamConversion(deps: ConversionDeps): Promise<{ code: string; expiresIn: number }> {
+ const { session, headers } = await signedIn(deps.auth)
+ const computerId = wireComputerId(session.computerId)
+ let proof: ConversionProof | null = null
+ try {
+ proof = await conversionProof(deps, session, headers)
+ } catch (error) {
+ if (!session.accessToken.startsWith('hna_')) throw error
+ }
+ return requestCode(deps.post, { kind: 'team', computerId, ...(proof ? { proof } : {}) }, headers)
+}
+
+async function conversionProof(deps: ConversionDeps, session: AuthSession, headers: Record<string, string>): Promise<ConversionProof> {
+ if (!session.machineId) {
+ throw new TeamSignInError('This computer has not joined your account\'s machines yet. Start Harness once (harness start), then run this again.', 'NO_PROOF')
+ }
+ const key = deps.machineKey()
+ if (!key) throw new TeamSignInError('This computer has no device key yet. Start Harness once (harness start), then run this again.', 'NO_PROOF')
+ let userId: unknown
+ try {
+ userId = (await deps.get<{ user?: { id?: unknown } }>('/api/auth/me', headers))?.user?.id
+ } catch (error) {
+ throw new TeamSignInError(`Harness could not say which account this computer is signed in to: ${(error as Error).message}`, 'BACKEND')
+ }
+ if (typeof userId !== 'string' || !userId) throw new TeamSignInError('Harness did not say which account this computer is signed in to.', 'BACKEND')
+ return teamConversionProof({ userId, computerId: session.computerId, machineId: session.machineId, at: deps.now(), priv: key.priv })
+}
+
+async function requestCode(post: Post, body: Record<string, unknown>, headers: Record<string, string>): Promise<{ code: string; expiresIn: number }> {
let minted: { code?: unknown; expiresIn?: unknown }
try {
- minted = await post('/api/auth/handoff', { kind: 'team' }, signedIn.headers)
+ minted = await post('/api/auth/handoff', body, headers)
} catch (error) {
throw new TeamSignInError(`Harness would not give a team sign-in code: ${(error as Error).message}`, 'BACKEND')
}
@@ -118,9 +193,10 @@ export function teamSession(tokens: TeamTokens, computerId: string, fallbackEnv:
}
}
-/** Sign a Harness-issued session out on the backend. Best effort: an Autonomous sign-in is not ours to revoke. */
+/** Sign a Harness-issued session out on the backend: a computer's or a phone's (`hnr_`), or a team one (`htr_`). Best
+ * effort: an Autonomous sign-in is not ours to revoke. */
export async function revokeHarnessRefresh(post: Post, refreshToken: string | undefined): Promise<boolean> {
- if (!refreshToken?.startsWith('hnr_')) return false
+ if (!refreshToken?.startsWith('hnr_') && !refreshToken?.startsWith('htr_')) return false
try {
await post('/api/auth/revoke', { refreshToken })
return true
diff --git a/cli/src/team/privacy.ts b/cli/src/team/privacy.ts
index 61925b624..53221aa85 100644
--- a/cli/src/team/privacy.ts
+++ b/cli/src/team/privacy.ts
@@ -12,6 +12,7 @@
import { closeSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
import type { TeamConfig } from './config.js'
+import type { TeamEngines } from './engines.js'
export type PrivacyItem =
| 'sentinel' | 'home-listing' | 'gitconfig' | 'ssh' | 'projects' | 'keychain' | 'chrome' | 'safari' | 'standard-user'
@@ -94,6 +95,22 @@ export interface TeamStatus {
version: 1
signIn?: { state: 'signed-in' | 'failed' | 'signed-out'; at: number; detail?: string }
privacy?: PrivacyResult
+ /** Claude Code and Codex in the team account (./engines.ts). */
+ engines?: TeamEngines
+}
+
+/** The `engines` field of the status file, or undefined when it is not one. */
+export function enginesOf(value: unknown): TeamEngines | undefined {
+ if (!value || typeof value !== 'object') return undefined
+ const v = value as Record<string, unknown>
+ if (typeof v.checkedAt !== 'number' || !Number.isFinite(v.checkedAt)) return undefined
+ const result = { checkedAt: v.checkedAt } as TeamEngines
+ for (const engine of ['claude', 'codex'] as const) {
+ const e = v[engine] as Record<string, unknown> | undefined
+ if (!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 }
+ }
+ return result
}
const ITEMS = new Set<string>(['sentinel', 'home-listing', 'gitconfig', 'ssh', 'projects', 'keychain', 'chrome', 'safari', 'standard-user', 'unchecked'])
@@ -121,6 +138,8 @@ export function readTeamStatus(path: string, read: (path: string) => string = (p
}
const privacy = privacyOf(value.privacy)
if (privacy) status.privacy = privacy
+ const engines = enginesOf(value.engines)
+ if (engines) status.engines = engines
return status
}
diff --git a/cli/src/team/script.spec.ts b/cli/src/team/script.spec.ts
index c938f67ad..e86e7a9f2 100644
--- a/cli/src/team/script.spec.ts
+++ b/cli/src/team/script.spec.ts
@@ -9,7 +9,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
- SENTINEL_TEXT, TEAM_COPY, TEAM_JOB_WRAPPER, WRITE_PRIVATE, WRITE_PUBLIC, buildRemoveScript, buildSetupScript, sh, teamLaunchdPlist,
+ SENTINEL_TEXT, TEAM_COPY, TEAM_ENGINES_INSTALL, TEAM_JOB_WRAPPER, WRITE_PRIVATE, WRITE_PUBLIC, buildRemoveScript, buildSetupScript, sh, teamLaunchdPlist,
type SetupScriptInput,
} from './script.js'
@@ -89,7 +89,7 @@ describe('setup script', () => {
const order = [
'owned_by_root "$dir"', 'dscl . -create "/Users/$TEAM"', 'chmod 700 "$TEAM_HOME"', 'chmod 700 "$OWNER_HOME"',
'as_owner /bin/sh -c', 'launchctl bootout "system/$LABEL"', 'mktemp -d /private/var/tmp/harness-team.XXXXXX', 'as_team /bin/sh -c',
- 'install -o 0 -g 0 -m 0644 "$STAGE/team.json" "$CONFIG"', 'team __handoff', 'as_team /bin/sh -c \'umask 077',
+ 'npm" install --global --prefix "$home/.local"', 'install -o 0 -g 0 -m 0644 "$STAGE/team.json" "$CONFIG"', 'team __handoff', 'as_team /bin/sh -c \'umask 077',
'install -o 0 -g 0 -m 0644 "$STAGE/team.plist" "$PLIST"', 'launchctl bootstrap system "$PLIST"',
].map((needle) => at(script, needle))
expect([...order].sort((a, b) => a - b)).toEqual(order)
@@ -131,6 +131,38 @@ describe('setup script', () => {
})
})
+describe('the team account\'s own engines', () => {
+ it('are installed by the team account itself, never by root, from the vendors\' packages, and never fail setup', () => {
+ const script = buildSetupScript(input())
+ expect(script).toContain(`\nas_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" '@anthropic-ai/claude-code' '@openai/codex' || true\n`)
+ parses(script)
+ })
+
+ it('installs each package with the team account\'s own Node and npm under its own home, and goes on past one that fails', () => {
+ const root = temp()
+ const home = join(root, 'home'), bin = join(home, '.harness', 'runtime', 'node-v1', 'bin')
+ mkdirSync(bin, { recursive: true })
+ const log = join(root, 'npm.log')
+ // A stand-in npm: it records how it was run and with which PATH, and refuses one package.
+ writeFileSync(join(bin, 'npm'), `#!/bin/sh\nprintf '%s|%s|%s\\n' "$PATH" "$PWD" "$*" >> '${log}'\ncase "$*" in *@openai/codex*) exit 1 ;; esac\n`, { mode: 0o755 })
+ const run = spawnSync('/bin/sh', ['-c', TEAM_ENGINES_INSTALL, 'sh', home, 'node-v1', '@anthropic-ai/claude-code', '@openai/codex'], { encoding: 'utf8', env: { PATH: '/usr/bin:/bin' } })
+ expect(run.status).toBe(0)
+ expect(run.stdout).toContain('harness: installed @anthropic-ai/claude-code for the team account')
+ expect(run.stderr).toContain('harness: could not install @openai/codex for the team account; harness team setup tries again')
+ const calls = readFileSync(log, 'utf8').trim().split('\n').map((l) => l.split('|'))
+ expect(calls).toHaveLength(2)
+ for (const [path, cwd, args] of calls) {
+ expect(path!.split(':')[0]).toBe(bin)
+ expect(cwd).toBe(home)
+ expect(args).toContain(`install --global --prefix ${home}/.local --no-fund --no-audit --loglevel=error`)
+ }
+ // No npm in the copied Node: said, and setup goes on.
+ const bare = spawnSync('/bin/sh', ['-c', TEAM_ENGINES_INSTALL, 'sh', join(root, 'nobody'), 'node-v1', '@openai/codex'], { encoding: 'utf8' })
+ expect(bare.status).toBe(0)
+ expect(bare.stderr).toContain('has no npm')
+ })
+})
+
describe('the team account\'s copy of the runtime', () => {
it('lays the runtime, the CLI and the harness launcher into the home it is given, privately', () => {
const root = temp()
diff --git a/cli/src/team/script.ts b/cli/src/team/script.ts
index 932faa334..70288baa1 100644
--- a/cli/src/team/script.ts
+++ b/cli/src/team/script.ts
@@ -12,6 +12,7 @@
* account copies them in itself (`as_team`). Likewise the sentinel in the owner's home is written as the owner.
* - Every step checks what is there, so a second run repairs a first one that stopped part-way.
*/
+import { TEAM_ENGINES } from './engines.js'
import {
SENTINEL_NAME, TEAM_CONFIG_FILE, TEAM_LABEL, TEAM_PLIST, TEAM_SHARED_DIR, TEAM_STATUS_DIR,
checkName, checkPath, checkPort, checkUser, teamPaths,
@@ -175,6 +176,27 @@ export const TEAM_COPY = [
'chmod 755 "$bin/harness.next" && mv -f "$bin/harness.next" "$bin/harness"',
].join('\n')
+/**
+ * Claude Code and Codex for the team account (./engines.ts), installed by that account itself, never by root: the vendors'
+ * npm packages, with its own copy of Harness's Node and npm, under its own home (`~/.local`, whose bin folder is on its
+ * daemon's PATH). Positional: the home, the Node folder's name, then the packages. A package that fails is said and left,
+ * never failing setup: running setup again tries again, and `harness team status` shows what is missing.
+ */
+export const TEAM_ENGINES_INSTALL = [
+ 'set -u',
+ 'umask 022',
+ 'home=$1; node_name=$2; shift 2',
+ 'bin="$home/.harness/runtime/$node_name/bin"',
+ `[ -x "$bin/npm" ] || { printf 'harness: %s\\n' "the team account's Node has no npm; Claude Code and Codex were not installed" >&2; exit 0; }`,
+ 'PATH="$bin:/usr/bin:/bin:/usr/sbin:/sbin"; export PATH',
+ 'cd "$home" || exit 0',
+ 'for pkg in "$@"; do',
+ ' if "$bin/npm" install --global --prefix "$home/.local" --no-fund --no-audit --loglevel=error "$pkg" >/dev/null 2>&1; then',
+ ` printf 'harness: installed %s for the team account\\n' "$pkg"`,
+ ` else printf 'harness: could not install %s for the team account; harness team setup tries again\\n' "$pkg" >&2; fi`,
+ 'done',
+].join('\n')
+
/** Stdin to a file, as whoever runs it: the next name first, then a rename, so a reader never sees half of it. */
export const WRITE_PRIVATE = 'umask 077 && cat > "$1.next" && mv -f "$1.next" "$1"'
export const WRITE_PUBLIC = 'umask 022 && cat > "$1.next" && chmod 644 "$1.next" && mv -f "$1.next" "$1"'
@@ -312,6 +334,10 @@ export function buildSetupScript(input: SetupScriptInput): string {
'chmod 755 "$RT"',
`as_team /bin/sh -c ${sh(TEAM_COPY)} sh "$RT" "$TEAM_HOME" "$NODE_NAME" "$TMUX_NAME"`,
'',
+ '# 5b. Claude Code and Codex, installed by the team account itself into its own home: the owner\'s copies are inside the',
+ '# owner\'s private home. None of the owner\'s sign-ins is copied; the owner signs them in once (harness team status).',
+ `as_team /bin/sh -c ${sh(TEAM_ENGINES_INSTALL)} sh "$TEAM_HOME" "$NODE_NAME" ${TEAM_ENGINES.map((e) => sh(e.packageName)).join(' ')} || true`,
+ '',
'# 6. What setup made (root\'s), and the team account\'s status folder, which the owner can read.',
'if [ ! -d "$SHARED" ]; then mkdir -p "$SHARED"; chown 0:0 "$SHARED"; chmod 755 "$SHARED"; fi',
'owned_by_root "$SHARED"',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index c99494300..f7b7d71e9 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1894,6 +1894,39 @@ class AppNotifier extends ChangeNotifier {
return result;
}
+ /// Whether this is a Mac, as the Harness Team account offer reads it. Off
+ /// under test, on a Mac too, unless a test sets it.
+ @visibleForTesting
+ bool? macOSForTest;
+ bool _teamOfferedAtStart = false;
+
+ /// 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.
+ Future<void> offerTeamAccount(String reason) async {
+ if (!(macOSForTest ?? (Platform.isMacOS && !kUnderTest))) return;
+ final here = machineStates.values
+ .where(
+ (state) => state.isLocalMachine && !state.machine.isSharedMachine,
+ )
+ .firstOrNull;
+ if (here == null) return;
+ try {
+ await superTabMachineRequest(here.machine.machineId, {
+ 'action': 'teamSetup',
+ 'reason': reason,
+ });
+ } catch (error) {
+ // An older daemon, or one that cannot say: nothing is asked.
+ appLog.debug('super-tabs', 'team account not offered: $error');
+ }
+ }
+
Future<void> wakeSuperTabHost(String machineId) async {
await superTabMachineRequest(machineId, {'action': 'wake'});
// Share derives only the session views authorized by the tab. Its existing
@@ -5079,6 +5112,13 @@ class AppNotifier extends ChangeNotifier {
// the offline poll (the one thing that would have re-probed) stopped, and the tiles sat on
// "Offline" over a live terminal with nothing left to restore them. Measured 2026-09-18 21:50.
machine.localEndpoint ??= _cliEndpoint;
+ // Once a launch, with the person here: a Mac that joined a Swarm before
+ // teammates' work went only to Team machines never met the join or
+ // contribute moment.
+ if (!_teamOfferedAtStart && !machine.machine.isSharedMachine) {
+ _teamOfferedAtStart = true;
+ unawaited(offerTeamAccount('startup'));
+ }
} else {
machine.transportMode = MachineTransportMode.cloudE2ee;
}
diff --git a/desktop/lib/super_tabs/join_dialog.dart b/desktop/lib/super_tabs/join_dialog.dart
index 5964ec6e7..066e7a7a6 100644
--- a/desktop/lib/super_tabs/join_dialog.dart
+++ b/desktop/lib/super_tabs/join_dialog.dart
@@ -67,7 +67,11 @@ class _SwarmJoinHostState extends State<SwarmJoinHost> {
request: app.superTabs.map,
isCurrent: current,
onJoined: (id, name) {
- if (current()) app.openSuperTab(id, name);
+ if (!current()) return;
+ app.openSuperTab(id, name);
+ // Joined by the person at this Mac: macOS asks once for
+ // the Harness Team account (cli/src/team/autoSetup.ts).
+ unawaited(app.offerTeamAccount('join'));
},
)
: AlertDialog(
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 9e2a6ad3e..694f91351 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -715,6 +715,11 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
);
}
await app.wakeSuperTabHost(selected);
+ // This Mac, added while its person is here: macOS asks once
+ // for the Harness Team account (cli/src/team/autoSetup.ts).
+ if (app.stateOf(selected)?.isLocalMachine == true) {
+ unawaited(app.offerTeamAccount('contribute'));
+ }
if (context.mounted) Navigator.pop(context);
} catch (failure) {
if (context.mounted) {
diff --git a/desktop/test/team_account_offer_test.dart b/desktop/test/team_account_offer_test.dart
new file mode 100644
index 000000000..1e6aacc89
--- /dev/null
+++ b/desktop/test/team_account_offer_test.dart
@@ -0,0 +1,76 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'support/rename_connection.dart';
+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'};
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'super_tabs' && payload['action'] == 'teamSetup') {
+ asked.add(Map.of(payload));
+ return Future.value(answer);
+ }
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late _Daemon daemon;
+ late AppNotifier app;
+ setUp(() {
+ daemon = _Daemon();
+ app = createApp(connectionForTest: (_) => daemon, connected: true);
+ app.machineStates['m']!.localOnly = true;
+ app.macOSForTest = true;
+ });
+ 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 nothing off a Mac, or when the only machine here is another one',
+ () async {
+ app.macOSForTest = false;
+ await app.offerTeamAccount('join');
+ app.macOSForTest = true;
+ app.machineStates['m']!.localOnly = false;
+ await app.offerTeamAccount('join');
+ expect(daemon.asked, isEmpty);
+ },
+ );
+
+ test('a daemon that refuses or cannot say is left alone', () async {
+ daemon.answer = {'error': 'UNKNOWN_ACTION'};
+ await app.offerTeamAccount('join');
+ expect(daemon.asked, hasLength(1));
+ });
+
+ test('offers once a launch, as this Mac\'s daemon first connects', () async {
+ app.onMachineConnectedForTest('m');
+ app.onMachineConnectedForTest('m');
+ await pumpEventQueue();
+ expect(daemon.asked, [
+ {'action': 'teamSetup', 'reason': 'startup'},
+ ]);
+ });
+}
diff --git a/docs/swarm-github-app.md b/docs/swarm-github-app.md
index 42849482f..78bd50154 100644
--- a/docs/swarm-github-app.md
+++ b/docs/swarm-github-app.md
@@ -115,8 +115,32 @@ Harness wires the app into an agent when the start meets all of these conditions
A person's own agents, starts on a server without the app, and computers whose Harness
is too old to understand the request keep using the computer's own git and gh
configuration. The decision is recorded with the session, so a relaunch keeps it.
-In the planned team account, every Swarm agent qualifies, because the owner's login
-is not there. Windows is not wired yet.
+In a team account (a Mac's Harness Team account, or a computer after `harness team on`),
+every Swarm agent qualifies, because the owner's login is not there. Windows is not
+wired yet.
+
+## Preparing the folder before the agent starts
+
+Before a contributed computer creates the agent, it clones the project into its Swarm
+folder and fetches the default branch the worktree starts from. For another person's
+project it does this with the app too, never with its owner's git login:
+
+1. The host asks `POST /api/super-tabs/hosts/:machineId/starts/:tabId/:startId/github-token`.
+ For another person's project the answer is a token that can only read the project's
+ repository (`contents: read`, `metadata: read`), and whom the work is for. For the
+ machine owner's own project the answer is `{ "github": false }` and the owner's login
+ prepares it as before. A team account sends `{ "always": true }`, because it has no
+ login of its own.
+2. The clone and the fetch run with that token alone: the owner's global and system git
+ config are not read, `[email protected]:` addresses go over HTTPS, and nothing prompts.
+ The token is in the git process's environment only.
+3. The agent is created with `swarmGitHub`, and the daemon does not fetch again.
+
+If the token cannot be had (the app is not installed on the repository, the project has
+no GitHub address, or a team account's server has no app), the start fails with that
+reason. It is never prepared with the owner's login instead. A server's host rows say
+`githubApp: true` when it has the app; a server without the app, or one from before this
+endpoint, leaves an owner's computer preparing as before.
## How git and gh get the token
@@ -232,9 +256,8 @@ The server never logs a token.
## Known limits
-- Preparing a Swarm worktree still fetches with the computer's own git setup, in
- the daemon, before the agent starts. A team account has no such login, so its first
- fetch of a private repository is a follow-up.
+- A Lead that starts an agent on its own computer for another person's project starts
+ the worktree from what that computer's checkout has: nothing fetches it first.
- On a personal computer, startup files that export `GITHUB_TOKEN` reach Claude
Code's and Codex's commands again. gh then uses that token. The team account has
no such files.