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: implement harness machines command to list and delete remote machines

0xken15beec403e9377
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 8d6769477..de3f56837 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -666,3 +666,20 @@ describe('Grok session_get history', () => {
expect(paginated).toMatchObject({ hasMore: false, oldestCursor: null })
})
})
+
+describe('adapter-ws dial url', () => {
+ const dialUrl = (socket: BackendSocket): string => (socket as unknown as { url: string }).url
+
+ it('carries the machine id this daemon still holds, so a revoked one gets 403 not a new machine', () => {
+ const machineId = 'b'.repeat(32)
+
+ expect(dialUrl(new BackendSocket(machineId, undefined, () => {}, 'computer-1')))
+ .toContain(`&machine=${machineId}`)
+ })
+
+ it('omits the claim when the first argument is a test token rather than a machine id', () => {
+ // Constructed without an AuthSessionManager, the first argument is a token — sending it as a
+ // machine id would be a lie the backend then has to reject.
+ expect(dialUrl(new BackendSocket('token', undefined, () => {}, 'computer-1'))).not.toContain('&machine=')
+ })
+})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 174093b7b..67f8df60a 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -385,7 +385,12 @@ export class BackendSocket {
// `?v=<VERSION>` is our own version, which the backend stores on the machine at every connect (the
// analytics report also carries it, but that path is opt-in, so this is the reliable one).
const base = `${env.BACKEND_WS_URL.replace(/\/$/, '')}/api/adapter-ws?label=${encodeURIComponent(hostname())}&v=${encodeURIComponent(VERSION)}&autonomousEnv=${encodeURIComponent(autonomousEnv)}`
- this.url = computerId ? `${base}&computer=${encodeURIComponent(computerId)}` : base
+ // `?machine=<id>` is the machine this daemon still believes it is. The backend uses it to tell a
+ // REVOKED daemon — one whose machine was deleted while it was offline — apart from a first-time
+ // pairing, and answers 403 instead of quietly minting a replacement machine. Guarded on shape
+ // because in test mode the first constructor argument carries a token, not a machine id.
+ const claim = /^[a-f0-9]{32}$/.test(machineId) ? `&machine=${encodeURIComponent(machineId)}` : ''
+ this.url = (computerId ? `${base}&computer=${encodeURIComponent(computerId)}` : base) + claim
this.onStatus = onStatus
this.machineId = machineId
this.e2ee = new E2eeManager({
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 047e54aa5..5374da035 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -228,6 +228,8 @@ Machine:
harness stop stop the background adapter (keeps the SSO session)
harness reset stop the adapter and clear local CLI state
harness status show whether it's running (+ version)
+ harness machines list the machines on this account (this computer's is marked)
+ harness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)
harness version print the installed version (v${VERSION})
harness update update to the latest build now (it also self-updates in the background)
harness flash [flags] re-flash a plugged-in circle device over USB. Flags go straight to the
@@ -299,12 +301,18 @@ function setupBrowserLink(machineId: string, token: string): string {
return u.toString()
}
-/** POST JSON to the backend and return its `data` envelope; throws on a non-2xx / bad body. */
-async function postJson<T>(path: string, body: unknown, headers: Record<string, string> = {}): Promise<T> {
+/** One control-plane call, returning the backend's `data` envelope; throws on a non-2xx / bad body. */
+async function requestJson<T>(
+ method: 'GET' | 'POST' | 'DELETE',
+ path: string,
+ body?: unknown,
+ headers: Record<string, string> = {},
+): Promise<T> {
+ // A GET/DELETE with no body must not carry a content-type — some proxies reject that pairing.
const res = await fetch(`${backendHttpBase()}${path}`, {
- method: 'POST',
- headers: { 'content-type': 'application/json', ...headers },
- body: JSON.stringify(body),
+ method,
+ headers: body === undefined ? headers : { 'content-type': 'application/json', ...headers },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
})
const json = (await res.json().catch(() => ({}))) as { success?: boolean; data?: T; error?: { message?: string } }
if (!res.ok || json.success === false) {
@@ -313,6 +321,27 @@ async function postJson<T>(path: string, body: unknown, headers: Record<string,
return json.data as T
}
+/** POST JSON to the backend and return its `data` envelope; throws on a non-2xx / bad body. */
+async function postJson<T>(path: string, body: unknown, headers: Record<string, string> = {}): Promise<T> {
+ return requestJson<T>('POST', path, body, headers)
+}
+
+/**
+ * Bearer + environment headers for a control-plane call, refreshing a stale SSO token first.
+ *
+ * Returns the session too, because every caller also needs `machineId` to tell THIS computer's
+ * machine apart from the others in the answer.
+ */
+async function controlPlaneAuth(): Promise<{ session: AuthSession; headers: Record<string, string> }> {
+ const session = readAuthSession()
+ if (!session) throw new Error('Not signed in. Run `harness login`.')
+ const accessToken = await new AuthSessionManager(backendHttpBase()).accessToken()
+ return {
+ session,
+ headers: { authorization: `Bearer ${accessToken}`, 'x-autonomous-env': session.autonomousEnv },
+ }
+}
+
/** Resolve the canonical machine for the durable computer id without ever using a machine API key. */
async function resolveComputerMachine(): Promise<AuthSession> {
const current = readAuthSession()
@@ -322,6 +351,9 @@ async function resolveComputerMachine(): Promise<AuthSession> {
const result = await postJson<{ machine?: { machineId?: string } }>('/api/machines/resolve-computer', {
computerId: current.computerId,
label: hostname(),
+ // Same claim the adapter-ws dial carries: a machine deleted while this computer was offline must
+ // come back as 403, not as a quietly minted replacement.
+ ...(current.machineId ? { machineId: current.machineId } : {}),
}, {
authorization: `Bearer ${accessToken}`,
'x-autonomous-env': current.autonomousEnv,
@@ -4055,6 +4087,130 @@ async function linkUnlinkCommand(machineId: string | undefined): Promise<void> {
process.exit(0)
}
+/** One row of `GET /api/machines`. Only the fields this CLI shows are declared. */
+interface OwnerMachineRow {
+ machineId: string
+ name: string | null
+ hostname: string | null
+ status: string
+ agentCount: number
+}
+
+/** The caller's machines, newest first. The backend already excludes deleted ones. */
+async function fetchMachines(headers: Record<string, string>): Promise<OwnerMachineRow[]> {
+ const data = await requestJson<{ machines?: OwnerMachineRow[] }>('GET', '/api/machines', undefined, headers)
+ return data.machines ?? []
+}
+
+/** A machine's own name, else the hostname of the computer that last connected it. */
+function machineLabel(machine: OwnerMachineRow): string {
+ return machine.name?.trim() || machine.hostname?.trim() || '(unnamed)'
+}
+
+/** True when `id` names this machine — accepts the short prefix the list prints, not just the full id. */
+function matchesMachineId(machineId: string, id: string): boolean {
+ return machineId === id || machineId.startsWith(id)
+}
+
+/** `harness machines` — every machine on this account, with this computer's own marked. */
+async function machinesListCommand(json: boolean): Promise<void> {
+ const { session, headers } = await controlPlaneAuth()
+ const machines = await fetchMachines(headers)
+ if (json) {
+ for (const machine of machines) {
+ console.log(JSON.stringify({ ...machine, current: machine.machineId === session.machineId }))
+ }
+ process.exit(0)
+ }
+ if (!machines.length) {
+ console.log('\n No machines on this account yet.\n Run `harness start` to connect this computer as one.\n')
+ process.exit(0)
+ }
+ const rows = machines.map((machine) => ({
+ id: machine.machineId.slice(0, 8),
+ name: machineLabel(machine),
+ status: machine.status || 'unknown',
+ agents: String(machine.agentCount ?? 0),
+ current: machine.machineId === session.machineId,
+ }))
+ const nameWidth = Math.max(4, ...rows.map((row) => row.name.length))
+ const statusWidth = Math.max(6, ...rows.map((row) => row.status.length))
+ console.log('')
+ console.log(` ${'MACHINE'.padEnd(8)} ${'NAME'.padEnd(nameWidth)} ${'STATUS'.padEnd(statusWidth)} AGENTS`)
+ for (const row of rows) {
+ const line = ` ${row.id.padEnd(8)} ${row.name.padEnd(nameWidth)} ${row.status.padEnd(statusWidth)} ${row.agents.padStart(6)}`
+ console.log(row.current ? `${line} ← this computer` : line)
+ }
+ console.log('\n Delete one: harness machines delete <machine>\n')
+ process.exit(0)
+}
+
+/**
+ * `harness machines delete <machine>` — remove ANOTHER of your machines from this account.
+ *
+ * Deleting the machine this CLI is running as is refused, and refused BEFORE any network call. That
+ * delete revokes the very credential the command is authenticating with: the daemon would be told to
+ * wipe its session and stop while the command that asked for it is still running, and the operation
+ * the user actually wants there has its own name — `harness logout` detaches this computer and stops
+ * the daemon cleanly. The web UI can still delete this machine; that path is the one the daemon's
+ * revoke handling exists for.
+ */
+async function machinesDeleteCommand(id: string | undefined, assumeYes: boolean): Promise<void> {
+ if (!id) {
+ console.error('Usage: harness machines delete <machine> (see: harness machines)')
+ process.exit(1)
+ return
+ }
+ // Read the session straight off disk for this first check: refusing THIS machine must not depend on
+ // a token refresh, which is a network round trip that can fail or hang. The refusal is a local fact.
+ const local = readAuthSession()
+ const refuseSelf = (): never => {
+ console.error('\n ✗ That is THIS computer\'s machine — refusing to delete it from here.')
+ console.error(' ▸ To sign this computer out: harness logout')
+ console.error(' ▸ To also clear its local state: harness reset\n')
+ process.exit(1)
+ }
+ if (local?.machineId && matchesMachineId(local.machineId, id)) refuseSelf()
+
+ const { session, headers } = await controlPlaneAuth()
+ const machines = await fetchMachines(headers)
+ const matches = machines.filter((machine) => matchesMachineId(machine.machineId, id))
+ if (!matches.length) {
+ console.error(`\n ✗ No machine matches "${id}".`)
+ console.error(' ▸ Run `harness machines` to see them.\n')
+ process.exit(1)
+ return
+ }
+ if (matches.length > 1) {
+ console.error(`\n ✗ "${id}" matches ${matches.length} machines:\n`)
+ for (const machine of matches) console.error(` ${machine.machineId.slice(0, 8)} ${machineLabel(machine)}`)
+ console.error('\n ▸ Use more characters of the id.\n')
+ process.exit(1)
+ return
+ }
+ const target = matches[0]
+ // Re-checked against the RESOLVED id: a short prefix that missed the session's machineId above can
+ // still resolve to this computer's machine here.
+ if (session.machineId === target.machineId) refuseSelf()
+
+ if (!assumeYes) {
+ process.stdout.write(
+ `\n Delete machine ${target.machineId.slice(0, 8)} (${machineLabel(target)})?`
+ + ' Its agents stop being reachable and the computer running it signs out.'
+ + '\n Type the short id to confirm: ',
+ )
+ const answer = (await readStdinLine()).trim()
+ if (answer !== target.machineId.slice(0, 8)) {
+ console.log('\n Cancelled — nothing was deleted.\n')
+ process.exit(1)
+ }
+ }
+ await requestJson('DELETE', `/api/machines/${target.machineId}`, undefined, headers)
+ console.log(`\n ✓ Deleted ${target.machineId.slice(0, 8)} (${machineLabel(target)}).`)
+ console.log(' If that computer is running the daemon it signs out and stops on its own.\n')
+ process.exit(0)
+}
+
/** `harness status` — print the info block with the current running state. */
async function status(): Promise<void> {
const pid = readPid()
@@ -4124,6 +4280,13 @@ switch (cmd) {
case 'pairings':
pairingsCommand().catch(onError)
break
+ case 'machines':
+ if (!args[0]) machinesListCommand(flags.includes('--json')).catch(onError)
+ else if (args[0] === 'list') machinesListCommand(flags.includes('--json')).catch(onError)
+ else if (args[0] === 'delete' || args[0] === 'rm') {
+ machinesDeleteCommand(args[1], flags.includes('--yes')).catch(onError)
+ } else { console.error(`Unknown command: machines ${args[0]}`); usage(1) }
+ break
case 'link':
if (args[0] === 'connect') linkConnectCommand(args[1], flags.includes('--stdin'), flags.includes('--json')).catch(onError)
else if (args[0] === 'list') linkListCommand().catch(onError)
diff --git a/cli/src/machinesCommand.spec.ts b/cli/src/machinesCommand.spec.ts
new file mode 100644
index 000000000..d6488f0a4
--- /dev/null
+++ b/cli/src/machinesCommand.spec.ts
@@ -0,0 +1,89 @@
+import { spawnSync } from 'child_process'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { fileURLToPath } from 'url'
+import { afterEach, describe, expect, it } from 'vitest'
+
+const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))
+const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')
+const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')
+const dirs: string[] = []
+const MACHINE_ID = 'a'.repeat(32)
+
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+/**
+ * Run the CLI with an isolated HOME, and point the backend at a port nothing listens on.
+ *
+ * That unreachable address is the assertion mechanism, not a detail: a command that refuses locally
+ * must succeed at refusing WITHOUT reaching the network, so any code path that tries to talk to the
+ * backend fails loudly here instead of quietly passing.
+ */
+function run(args: string[], session?: Record<string, unknown>) {
+ const root = mkdtempSync(join(tmpdir(), 'harness-machines-'))
+ dirs.push(root)
+ const authDir = join(root, 'auth')
+ if (session) {
+ mkdirSync(authDir, { recursive: true })
+ writeFileSync(join(authDir, 'session.json'), JSON.stringify(session), { mode: 0o600 })
+ }
+ return spawnSync(process.execPath, [TSX, CLI_SOURCE, ...args], {
+ cwd: CLI_ROOT,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ HOME: root,
+ HARNESS_AUTH_DIR: authDir,
+ ADAPTER_DATA_DIR: join(root, 'data'),
+ ADAPTER_CLI_DIR: join(root, 'cli'),
+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),
+ ADAPTER_UPDATE_DISABLE: 'true',
+ BACKEND_WS_URL: 'ws://127.0.0.1:9',
+ },
+ })
+}
+
+const signedIn = {
+ version: 1,
+ accessToken: 'test-access-token',
+ autonomousEnv: 'prod',
+ computerId: 'computer-under-test',
+ machineId: MACHINE_ID,
+ updatedAt: Date.now(),
+}
+
+describe('harness machines delete', () => {
+ it('refuses to delete THIS computer\'s machine, without reaching the backend', () => {
+ const result = run(['machines', 'delete', MACHINE_ID], signedIn)
+
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('THIS computer\'s machine')
+ expect(result.stderr).toContain('harness logout')
+ // The unreachable backend would surface as a connect error; its absence is the proof that the
+ // refusal happened locally, before any token refresh or list fetch.
+ expect(result.stderr).not.toContain('ECONNREFUSED')
+ expect(result.stderr).not.toContain('fetch failed')
+ })
+
+ it('refuses on the short id the list prints, not just the full one', () => {
+ const result = run(['machines', 'delete', MACHINE_ID.slice(0, 8)], signedIn)
+
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('THIS computer\'s machine')
+ })
+
+ it('asks for an id rather than guessing one', () => {
+ const result = run(['machines', 'delete'], signedIn)
+
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('Usage: harness machines delete')
+ })
+
+ it('reports being signed out instead of failing against the backend', () => {
+ const result = run(['machines'])
+
+ expect(result.status).toBe(1)
+ expect(`${result.stdout}${result.stderr}`).toContain('Not signed in')
+ })
+})