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.

feat(team): a headless computer can give its team account a model API (#2743)

lingrd68e31ef8377a
diff --git a/cli/src/lib/engineAccount.spec.ts b/cli/src/lib/engineAccount.spec.ts
index ec09180e2..eea75bd06 100644
--- a/cli/src/lib/engineAccount.spec.ts
+++ b/cli/src/lib/engineAccount.spec.ts
@@ -25,6 +25,20 @@ describe('engineAccount', () => {
expect(asked).toEqual([])
})
+ it('counts a saved model API as a sign-in, so a machine with no subscription can take Swarm work', async () => {
+ // Headless run, 2026-11-03: a working OpenRouter key was saved for the team account, and the machine still read
+ // "not signed in", so no Swarm start was admitted.
+ const root = home()
+ const data = join(root, '.harness', 'cli', 'data', 'api-connections')
+ mkdirSync(data, { recursive: true })
+ writeFileSync(join(data, 'connections.json'), JSON.stringify({ version: 1, recognizedBases: ['https://openrouter.ai/api/v1'],
+ connections: [{ id: 'openrouter', provider: 'openrouter', name: 'OpenRouter', baseUrl: 'https://openrouter.ai/api/v1',
+ keyEnv: 'OPENROUTER_API_KEY', authHeader: 'Authorization', authPrefix: 'Bearer', apiKey: 'sk-x' }] }))
+ expect((await engineAccount('claude', { home: root, ...linux })).signedIn).toBe(true)
+ // Codex's own launch needs its config, so a saved API alone does not sign it in.
+ expect((await engineAccount('codex', { home: root, ...linux })).signedIn).toBe(false)
+ })
+
it('finds Claude Code signed in by its credential file, an apiKeyHelper, its Keychain item, or the environment', async () => {
const withFile = home()
mkdirSync(join(withFile, '.claude'), { recursive: true })
diff --git a/cli/src/lib/engineAccount.ts b/cli/src/lib/engineAccount.ts
index 96395692c..c0ecea516 100644
--- a/cli/src/lib/engineAccount.ts
+++ b/cli/src/lib/engineAccount.ts
@@ -17,6 +17,7 @@
* engine the person works in.
*/
import { isCodexRelayAuth } from './subscriptionRelay.js'
+import { readApiConnectionStore } from './apiConnectionMetadata.js'
import { createHash } from 'node:crypto'
import { execFile } from 'node:child_process'
import { readdir, readFile, stat } from 'node:fs/promises'
@@ -87,11 +88,19 @@ export async function engineAccount(engine: AgentEngine, deps: EngineAccountDeps
// process (loginShellEnv.ts), with the daemon's own on top.
const env = deps.env ?? { ...await warmLoginShellEnvironment(), ...process.env }
const platform = deps.platform ?? process.platform
+ // A model API saved on this computer (Models ▸ APIs, or `harness team model set`) serves Claude Code without a
+ // subscription, so the machine can take Swarm work on it (headless run, 2026-11-03: a working OpenRouter key saved,
+ // and the account read "not signed in").
+ const savedApi = (() => {
+ try { return readApiConnectionStore(env.ADAPTER_DATA_DIR || join(home, '.harness', 'cli', 'data')).connections }
+ catch { return [] }
+ })().some((row) => row.authHeader.toLowerCase() === 'authorization' && row.authPrefix.toLowerCase() === 'bearer')
if (engine === 'claude') {
const custom = env.CLAUDE_CONFIG_DIR
const dir = custom || join(home, '.claude')
const lastUsedAt = deps.lastUsed === false ? null : await newestChild(join(dir, 'projects'))
if (CLAUDE_ENV.some(name => Boolean(env[name]))) return { signedIn: true, lastUsedAt }
+ if (savedApi) return { signedIn: true, lastUsedAt }
if (await exists(join(dir, '.credentials.json'))) return { signedIn: true, lastUsedAt }
if (typeof (await readJson(join(dir, 'settings.json')))?.apiKeyHelper === 'string') return { signedIn: true, lastUsedAt }
if (platform === 'darwin') {
diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.ts
index 899f2ef19..13a797caf 100644
--- a/cli/src/team/command.spec.ts
+++ b/cli/src/team/command.spec.ts
@@ -91,7 +91,7 @@ describe('harness team', () => {
it('prints its help, and refuses an unknown verb', async () => {
const f = fake()
expect(await teamCommand([], f.deps)).toBe(0)
- expect(f.out[0]).toContain('Usage: harness team <setup | status | remove | on | off>')
+ expect(f.out[0]).toContain('Usage: harness team <setup | status | model | remove | on | off>')
expect(await teamCommand(['frobnicate'], f.deps)).toBe(2)
})
})
diff --git a/cli/src/team/command.ts b/cli/src/team/command.ts
index 454d4deae..6c38775e7 100644
--- a/cli/src/team/command.ts
+++ b/cli/src/team/command.ts
@@ -19,6 +19,7 @@ import { SIGN_OUT_BUTTON_FLAG, type SignOutAsked } from '../lib/signOut.js'
import type { AdminVia, RunAdmin } from './admin.js'
import { teamConfigJson, type TeamConfig } from './config.js'
import { engineLines, type TeamEngines } from './engines.js'
+import { teamModelSet } from './model.js'
import { mintTeamConversion, mintTeamHandoff, redeemTeamHandoff, revokeHarnessRefresh, teamSession, TeamSignInError, type Delete, type Get, type Post } from './handoff.js'
import {
SENTINEL_NAME, TEAM_PORT, TEAM_REAL_NAME, TEAM_STATUS_FILE,
@@ -68,13 +69,15 @@ function teamHere(platform: NodeJS.Platform): TeamHere | null {
}
export const TEAM_USAGE = [
- 'Usage: harness team <setup | status | remove | on | off> [--json]',
+ 'Usage: harness team <setup | status | model | remove | on | off> [--json]',
'',
' setup make the Harness Team account on this Mac, Linux or Windows computer for Swarm work: a separate standard user,',
` "Harness Team" (${TEAM_USER}), whose own Harness daemon runs teammates' agents so they cannot read your files.`,
' The system asks 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)',
' status whether the account exists and runs, its sign-in, privacy check and engines, and everything setup made',
+ ' model the team account\'s own model API instead of your subscription: `harness team model set <provider> --model <id>`',
+ ' (asks for the key, hidden; --clear undoes it)',
' remove delete the account, its home folder and its daemon; your home stays private. Run it in Terminal: sudo',
' asks for your password, and macOS asks once to let Terminal administer your computer, which it needs',
' on for a computer used only for agents (a Mac mini, a Linux or Windows box): sign it in for team work',
@@ -124,6 +127,8 @@ export interface TeamCommandDeps {
env: NodeJS.ProcessEnv
interactive: boolean
ask(question: string): Promise<string>
+ /** Like [ask], but what is typed is not echoed: for an API key. */
+ askSecret?(question: string): Promise<string>
now(): number
sleep(ms: number): Promise<void>
@@ -195,6 +200,7 @@ export async function teamCommand(argv: string[], deps: TeamCommandDeps): Promis
switch (verb) {
case 'setup': return await setup(deps, json, flags.includes('--sign-in-again'))
case 'status': return await status(deps, json)
+ case 'model': return await teamModelSet(deps, words, flags, json)
case 'remove': return await remove(deps, json)
case 'on': return await teamOn(deps, json, flags.includes('--yes'))
case 'off': return await teamOff(deps, json, flags)
diff --git a/cli/src/team/deps.ts b/cli/src/team/deps.ts
index f4ff716aa..f475487b3 100644
--- a/cli/src/team/deps.ts
+++ b/cli/src/team/deps.ts
@@ -81,6 +81,32 @@ export function teamCommandDeps(options: {
const rl = createInterface({ input: process.stdin, output: process.stdout })
rl.question(question, (answer) => { rl.close(); resolve(answer) })
}),
+ // A key is never echoed, and never asked where nothing can hide it (a pipe): the command tells that caller to use
+ // --key-stdin instead.
+ askSecret: (question) => new Promise((resolve) => {
+ const stdin = process.stdin
+ process.stdout.write(question)
+ const wasRaw = stdin.isRaw
+ let text = ''
+ const finish = (value: string) => {
+ stdin.off('data', onData)
+ stdin.setRawMode?.(wasRaw === true)
+ stdin.pause()
+ process.stdout.write('\n')
+ resolve(value)
+ }
+ const onData = (chunk: Buffer) => {
+ for (const char of chunk.toString('utf8')) {
+ if (char === '\r' || char === '\n') return finish(text)
+ if (char === '\u0003') { finish(''); process.exit(130) }
+ if (char === '\u007f') { text = text.slice(0, -1); continue }
+ text += char
+ }
+ }
+ stdin.setRawMode?.(true)
+ stdin.resume()
+ stdin.on('data', onData)
+ }),
now: () => Date.now(),
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
session: readAuthSession,
diff --git a/cli/src/team/model.spec.ts b/cli/src/team/model.spec.ts
new file mode 100644
index 000000000..d21728c8c
--- /dev/null
+++ b/cli/src/team/model.spec.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it, vi } from 'vitest'
+import { buildModelScript, teamModelSet, MODEL_USAGE } from './model.js'
+import type { TeamCommandDeps } from './command.js'
+
+const config = { user: 'harnessteam', home: '/home/harnessteam', node: '/home/harnessteam/.harness/runtime/node/bin/node', label: 'harness-team.service' }
+
+function setup(over: Record<string, unknown> = {}) {
+ const out: string[] = [], errors: string[] = [], built: Array<{ script: string; files: Record<string, string> }> = []
+ const admin = vi.fn(async (build: (stage: string) => { script: string; files?: Record<string, string> }) => {
+ built.push(build('/stage') as { script: string; files: Record<string, string> })
+ return { ok: true as const, stdout: 'done' }
+ })
+ const deps = {
+ platform: 'linux', out: (line: string) => out.push(line), err: (line: string) => errors.push(line),
+ interactive: true, uid: () => 501, readConfig: () => config, admin,
+ askSecret: async () => 'sk-test-key', ask: async () => 'sk-test-key', ...over,
+ } as unknown as TeamCommandDeps
+ return { deps, out, errors, built, admin }
+}
+
+describe('harness team model set', () => {
+ it('saves the key as a saved API and the engine settings, and says it in two lines', async () => {
+ const f = setup()
+ expect(await teamModelSet(f.deps, ['model', 'set', 'openrouter', 'deepseek/deepseek-v4.1-flash-1017'], ['--model'])).toBe(0)
+ expect(f.admin).toHaveBeenCalledTimes(1)
+ const [{ script, files }] = f.built
+ expect(script).toContain('api-connections/connections.json')
+ expect(script).toContain('systemctl restart')
+ expect(files['connections.json']).toContain('"apiKey":"sk-test-key"')
+ expect(files['model.json']).toContain('"ANTHROPIC_BASE_URL":"https://openrouter.ai/api"')
+ expect(f.out.join('\n')).toContain('now runs Claude Code on OpenRouter · deepseek/deepseek-v4.1-flash-1017')
+ expect(f.out.join('\n')).not.toContain('sk-test-key')
+ })
+
+ it('refuses without a key, a model, a known provider, or an account, and never on Windows', async () => {
+ const noModel = setup()
+ expect(await teamModelSet(noModel.deps, ['model', 'set', 'openrouter'], [])).toBe(1)
+ expect(noModel.errors.join('\n')).toContain('--model is needed')
+ const unknown = setup()
+ expect(await teamModelSet(unknown.deps, ['model', 'set', 'nope'], ['--model', 'x'])).toBe(1)
+ expect(unknown.errors.join('\n')).toContain('Unknown provider')
+ const anthropic = setup()
+ expect(await teamModelSet(anthropic.deps, ['model', 'set', 'anthropic'], ['--model', 'claude'])).toBe(1)
+ const bare = setup({ readConfig: () => null })
+ expect(await teamModelSet(bare.deps, ['model', 'set', 'openrouter'], ['--model', 'x'])).toBe(1)
+ expect(bare.errors.join('\n')).toContain('Run harness team setup first')
+ const windows = setup({ platform: 'win32' })
+ expect(await teamModelSet(windows.deps, ['model', 'set', 'openrouter'], ['--model', 'x'])).toBe(1)
+ expect(windows.admin).not.toHaveBeenCalled()
+ })
+
+ it('clears it again, and never asks for a key to do so', async () => {
+ const asked = vi.fn(async () => 'never')
+ const f = setup({ askSecret: asked })
+ expect(await teamModelSet(f.deps, ['model', 'set'], ['--clear'])).toBe(0)
+ expect(asked).not.toHaveBeenCalled()
+ expect(f.built[0]!.script).toContain('rm -f "$DATA/api-connections/connections.json"')
+ expect(f.out.join('\n')).toContain('has no model API again')
+ })
+
+ it('keeps the usage short enough to read', () => {
+ expect(MODEL_USAGE.split('\n').length).toBeLessThan(12)
+ expect(MODEL_USAGE).toContain('hidden prompt')
+ })
+})
diff --git a/cli/src/team/model.ts b/cli/src/team/model.ts
new file mode 100644
index 000000000..8c24ab658
--- /dev/null
+++ b/cli/src/team/model.ts
@@ -0,0 +1,189 @@
+/**
+ * `harness team model set …`: the Harness Team account's own model API, for a computer whose owner has no subscription
+ * for the relay to lend, or wants another model. The key is asked for here, hidden, and never reaches a command line.
+ *
+ * It writes the four things a person would otherwise edit by hand: the saved API (Models ▸ APIs) in the team account's
+ * data folder, the engine's base URL, token and model in its Claude settings, and a restart of its daemon.
+ */
+import { API_PRESETS, servesModels } from '../lib/apiConnections.js'
+import type { TeamCommandDeps } from './command.js'
+import { teamPaths } from './layout.js'
+
+export const MODEL_USAGE = [
+ 'Usage: harness team model set <provider> --model <model-id> [--key-stdin] [--clear]',
+ '',
+ ' <provider> openrouter, openai, anthropic, requesty, fal, replicate, or custom with --base-url <url>',
+ ' --model the model id that provider serves, e.g. deepseek/deepseek-v4.1-flash-1017',
+ ' --key-stdin read the API key from stdin instead of the hidden prompt (for scripts)',
+ ' --clear remove it again, back to the owner\'s subscription through the relay',
+ '',
+ 'The key is asked for here: never printed, never in your shell history.',
+].join('\n')
+
+/** The wide line the hidden prompt leaves behind, and the two lines the command ends with. */
+const DONE = (provider: string, model: string, where: string): string[] => [
+ ` ✓ ${where}'s Harness Team account now runs Claude Code on ${provider} · ${model}.`,
+ ' Next: harness team status',
+]
+
+interface Chosen { provider: string; name: string; baseUrl: string; keyEnv: string }
+
+function choose(deps: TeamCommandDeps, words: readonly string[], flags: readonly string[]): Chosen | null {
+ const provider = words[2]
+ if (!provider) { deps.err(MODEL_USAGE); return null }
+ if (provider === 'custom') {
+ const url = flags.includes('--base-url') ? words[3] : undefined
+ if (!url) { deps.err('✗ --base-url is needed with custom (the provider\'s API address, ending in /v1).'); return null }
+ return { provider, name: 'Custom', baseUrl: url.replace(/\/+$/, ''), keyEnv: 'CUSTOM_API_KEY' }
+ }
+ const preset = API_PRESETS.find((row) => row.provider === provider)
+ if (!preset) { deps.err(`✗ Unknown provider "${provider}".
+
+${MODEL_USAGE}`); return null }
+ return { provider, name: preset.name, baseUrl: preset.baseUrl, keyEnv: preset.keyEnv }
+}
+
+/** `--model <id>` and `--model=<id>`, beside the flags the dispatcher already split out. */
+function modelOf(words: readonly string[], flags: readonly string[]): string | null {
+ const inline = flags.find((flag) => flag.startsWith('--model='))
+ if (inline) return inline.slice('--model='.length)
+ return flags.includes('--model') ? words[3] ?? null : null
+}
+
+function baseUrlOf(words: readonly string[], flags: readonly string[]): string | null {
+ const inline = flags.find((flag) => flag.startsWith('--base-url='))
+ if (inline) return inline.slice('--base-url='.length)
+ return flags.includes('--base-url') ? words[3] ?? null : null
+}
+
+/** The team account's settings.json, with [change] applied: its own env entries and model, or those taken out again. */
+const MERGE = [
+ "import { readFileSync, writeFileSync, renameSync, chmodSync } from 'node:fs'",
+ 'const [payloadPath, settingsPath, team] = process.argv.slice(2)',
+ 'const payload = JSON.parse(readFileSync(payloadPath, "utf8"))',
+ 'let settings = {}',
+ 'try { settings = JSON.parse(readFileSync(settingsPath, "utf8")) } catch {}',
+ 'const env = settings.env && typeof settings.env === "object" ? settings.env : {}',
+ 'const keys = payload.clear ? ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"] : Object.keys(payload.env)',
+ 'for (const key of keys) delete env[key]',
+ 'if (!payload.clear) Object.assign(env, payload.env)',
+ 'if (Object.keys(env).length) settings.env = env; else delete settings.env',
+ 'if (payload.clear) delete settings.model; else settings.model = payload.model',
+ 'const next = settingsPath + ".next"',
+ 'writeFileSync(next, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 })',
+ 'renameSync(next, settingsPath)',
+ 'chmodSync(settingsPath, 0o600)',
+].join('\n')
+
+/** What the root script does: the saved API as the team account, the engine's settings, then its daemon again. */
+export function buildModelScript(input: {
+ platform: NodeJS.Platform
+ team: string
+ home: string
+ node: string
+ label: string
+ stage: string
+ clear: boolean
+}): string {
+ const data = teamPaths(input.home).data
+ const mac = input.platform === 'darwin'
+ return [
+ '#!/bin/sh',
+ '# Harness Team account: its model API (cli/src/team/model.ts), run once as root.',
+ 'set -eu',
+ 'cd /',
+ 'PATH=/usr/sbin:/usr/bin:/sbin:/bin; export PATH',
+ `TEAM=${JSON.stringify(input.team)}`,
+ `TEAM_HOME=${JSON.stringify(input.home)}`,
+ `NODE=${JSON.stringify(input.node)}`,
+ `STAGE=${JSON.stringify(input.stage)}`,
+ `DATA=${JSON.stringify(data)}`,
+ `LABEL=${JSON.stringify(input.label)}`,
+ `if [ ! -x "$NODE" ]; then echo "harness: the team account has no Node runtime" >&2; exit 4; fi`,
+ 'install -d -o "$TEAM" -m 700 "$DATA/api-connections"',
+ input.clear
+ ? 'rm -f "$DATA/api-connections/connections.json"'
+ : `install -o "$TEAM" -m 600 "$STAGE/connections.json" "$DATA/api-connections/connections.json"`,
+ 'mkdir -p "$TEAM_HOME/.claude"',
+ '"$NODE" "$STAGE/merge.mjs" "$STAGE/model.json" "$TEAM_HOME/.claude/settings.json" "$TEAM"',
+ 'chown "$TEAM" "$TEAM_HOME/.claude/settings.json"',
+ 'chmod 600 "$TEAM_HOME/.claude/settings.json"',
+ mac
+ ? 'launchctl kickstart -k "system/$LABEL" >/dev/null 2>&1 || true'
+ : 'systemctl restart "$LABEL" >/dev/null 2>&1 || true',
+ 'echo "done"',
+ ].join('\n')
+}
+
+/** `harness team model set`: the team account's own model API. */
+export async function teamModelSet(deps: TeamCommandDeps, words: readonly string[], flags: readonly string[], json = false): Promise<number> {
+ const where = deps.platform === 'darwin' ? 'this Mac' : 'this computer'
+ const config = deps.readConfig()
+ if (!config) { deps.err(`✗ No Harness Team account on ${where}. Run harness team setup first.`); return 1 }
+ if (deps.platform === 'win32') {
+ deps.err('✗ A model API for the team account is not on Windows yet. Sign the engines in from Harness: harness team status shows how.')
+ return 1
+ }
+ const clear = flags.includes('--clear')
+ let chosen: Chosen | null = null, model: string | null = null
+ if (!clear) {
+ chosen = choose(deps, words, flags)
+ if (!chosen) return 1
+ model = modelOf(words, flags)
+ if (!model) { deps.err(`✗ --model is needed: the model id that ${chosen.name} serves.`); return 1 }
+ if (!servesModels({ authHeader: 'Authorization', authPrefix: 'Bearer' })) return 1
+ if (chosen.provider === 'anthropic') {
+ deps.err('✗ Anthropic\'s own API does not fit a Swarm engine. Use openrouter, openai or custom.')
+ return 1
+ }
+ }
+ let key = ''
+ if (!clear) {
+ if (flags.includes('--key-stdin')) key = (await readStdin()).trim()
+ else if (!deps.interactive) { deps.err('✗ No terminal to ask for the key. Pipe it: ... | harness team model set … --key-stdin'); return 1 }
+ else {
+ const question = `Paste the ${chosen!.name} API key: `
+ key = (await (deps.askSecret ? deps.askSecret(question) : deps.ask(question))).trim()
+ }
+ if (!key) { deps.err('✗ No API key was given.'); return 1 }
+ }
+ const baseUrl = chosen ? (baseUrlOf(words, flags) ?? chosen.baseUrl).replace(/\/+$/, '') : ''
+ // Claude reads its endpoint as the API root: OpenRouter's Anthropic-compatible messages live under /api/v1.
+ const claudeBase = baseUrl.replace(/\/v1$/, '')
+ const connections = JSON.stringify({
+ version: 1,
+ connections: chosen
+ ? [{ id: chosen.provider, provider: chosen.provider, name: chosen.name, baseUrl, keyEnv: chosen.keyEnv,
+ authHeader: 'Authorization', authPrefix: 'Bearer', apiKey: key }]
+ : [],
+ recognizedBases: baseUrl ? [baseUrl] : [],
+ })
+ const payload = JSON.stringify(chosen
+ ? { clear: false, model, env: { ANTHROPIC_BASE_URL: claudeBase, ANTHROPIC_AUTH_TOKEN: key, ANTHROPIC_API_KEY: '' } }
+ : { clear: true })
+ const result = await deps.admin((stageDir) => ({
+ script: buildModelScript({ platform: deps.platform, team: config.user, home: config.home, node: config.node,
+ label: config.label, stage: stageDir, clear }),
+ files: { 'connections.json': connections, 'model.json': payload, 'merge.mjs': MERGE },
+ }), chosen ? `Harness wants to give the Harness Team account on ${where} the model API ${chosen.name}.` : `Harness wants to remove the Harness Team account's model API on ${where}.`)
+ if (!result.ok) {
+ if (result.code === 'NO_PROMPT') deps.err(`✗ ${result.message} Run it in a terminal.`)
+ else if (result.code !== 'CANCELLED') deps.err(`✗ ${result.message}`)
+ return 1
+ }
+ if (json) { deps.out(JSON.stringify({ ok: true, provider: chosen?.provider ?? null, model: model ?? null })); return 0 }
+ for (const line of clear ? [` ✓ The Harness Team account on ${where} has no model API again.`, ' Next: harness team status'] : DONE(chosen!.name, model!, where)) deps.out(line)
+ return 0
+}
+
+/** The key from stdin, for scripts and for a terminal that cannot hide typing. */
+function readStdin(): Promise<string> {
+ return new Promise((resolve) => {
+ let text = ''
+ process.stdin.setEncoding('utf8')
+ process.stdin.on('data', (chunk) => { text += chunk })
+ process.stdin.on('end', () => resolve(text))
+ process.stdin.on('error', () => resolve(text))
+ })
+}
+