The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: harness grid login hands this computer's account token to grid
Kelvin1743bbcda5fc
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex a41ead4f6..29a719a69 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -41,6 +41,7 @@ import { flashCommand } from './lib/flash.js'import { readOrMintComputerId } from './lib/computerIdentity.js'import { renderLoginSuccessHtml } from './lib/loginPage.js'import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'+import { handOffToGrid } from './lib/gridHandoff.js'import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'@@ -235,6 +236,12 @@ Machine:harness flash [flags] re-flash a plugged-in circle device over USB. Flags go straight to theflasher: --detect-only, --port, --version, --yes, --erase-nvs+Grid (the fleet of AI engines the \`grid\` CLI serves — needs \`grid\` on PATH):+ harness grid login sign in to your grid reusing THIS computer's Autonomous account —+ no second browser, no second approval+ harness grid login --force sign the harness in as a different account first, then the grid+ harness grid login --json emit the same machine-readable NDJSON \`harness login --json\` emits+Browser end-to-end encryption:harness browser-link print a reusable 7-day setup link for browsersharness pair <code> pair a BROWSER (code shown on the machine page)@@ -401,14 +408,50 @@ async function authStatusCommand(json: boolean): Promise<void> {else console.log(`\n ${payload.loggedIn ? '✓ Signed in' : '✗ Not signed in'}${payload.machineId ? ` (machine ${payload.machineId})` : ''}\n`)}-async function loginCommand(foreground: boolean, force: boolean, json: boolean): Promise<void> {+/**+ * `harness login` — and, `chained`, the first half of `harness grid login`.+ *+ * Returns whether this computer ended up signed in, so a caller can go on to its own step. `chained`+ * suppresses only the terminating SUCCESS line — the authorize URL, the SSH paste fallback and every+ * error line are the sign-in's to emit either way, and the caller adds the one result line that ends+ * the stream. Under `--json` a sign-in failure therefore still arrives as itself, coded, exactly+ * once; without it the sign-in throws, as `harness login` has always done, and the top-level handler+ * prints it.+ */+async function loginCommand(+ foreground: boolean,+ force: boolean,+ json: boolean,+ opts: { chained?: boolean } = {},+): Promise<boolean> {if (foreground) throw new Error('`harness login` does not run the adapter. Use `harness start -f`.')const emit = (line: Record<string, unknown>): void => { if (json) console.log(JSON.stringify(line)) }+ const succeed = (alreadySignedIn: boolean): boolean => {+ if (opts.chained) return true+ if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true } : { type: 'result', status: 'success' })+ else if (alreadySignedIn) console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')+ else console.log('\n ✓ Signed in. Run `harness start` to connect this computer.\n')+ return true+ }if (readAuthSession() && !force) {- await resolveComputerMachine()- if (json) emit({ type: 'result', status: 'success', alreadySignedIn: true })- else console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')- return+ // Guarded exactly like the identical call after the exchange below. Unguarded, a hiccup on+ // `/api/machines/resolve-computer` reached `onError`, which is JSON-unaware — so the ONE mode a+ // client drives answered a stack trace and NO result line at all, on the commonest path there+ // is (a computer that is already signed in).+ try {+ await resolveComputerMachine()+ } catch (err) {+ // An `AuthSessionError` is passed on rather than coded here: it is not the backend failing, it+ // is THIS computer's harness session, and only the caller knows which of the two sign-ins the+ // person should be sent to. `harness login` is unaffected — it never caught this before either.+ if (json && !(err instanceof AuthSessionError)) {+ emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message })+ process.exitCode = 1+ return false+ }+ throw err+ }+ return succeed(true)}// A forced login may intentionally switch SSO accounts. The old daemon must not keep streaming// under its existing socket while this process replaces the durable session.@@ -430,7 +473,7 @@ async function loginCommand(foreground: boolean, force: boolean, json: boolean):})if (!start.authorizeUrl || !start.tx) throw new Error('Backend did not return an SSO authorize URL')} catch (err) {- if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return }+ if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return false }throw err}if (json) {@@ -466,7 +509,7 @@ async function loginCommand(foreground: boolean, force: boolean, json: boolean):})} catch (err) {const timedOut = (err as Error).message === 'SSO login timed out'- if (json) { emit({ type: 'result', status: 'error', code: timedOut ? 'TIMEOUT' : 'CALLBACK_ERROR', message: (err as Error).message }); process.exitCode = 1; return }+ if (json) { emit({ type: 'result', status: 'error', code: timedOut ? 'TIMEOUT' : 'CALLBACK_ERROR', message: (err as Error).message }); process.exitCode = 1; return false }throw err} finally {manual?.cancel()@@ -479,7 +522,7 @@ async function loginCommand(foreground: boolean, force: boolean, json: boolean):})if (!exchanged.token) throw new Error('SSO exchange returned no access token')} catch (err) {- if (json) { emit({ type: 'result', status: 'error', code: 'EXCHANGE_FAILED', message: (err as Error).message }); process.exitCode = 1; return }+ if (json) { emit({ type: 'result', status: 'error', code: 'EXCHANGE_FAILED', message: (err as Error).message }); process.exitCode = 1; return false }throw err}const id = computerId()@@ -496,16 +539,62 @@ async function loginCommand(foreground: boolean, force: boolean, json: boolean):try {await resolveComputerMachine()} catch (err) {- if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return }+ if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return false }throw err}- if (json) emit({ type: 'result', status: 'success' })- else console.log('\n ✓ Signed in. Run `harness start` to connect this computer.\n')+ return succeed(false)} finally {await new Promise<void>((resolve) => callback.close(() => resolve()))}}+// ── grid ───────────────────────────────────────────────────────────────────────────────────────+/**+ * `harness grid login` — sign in to your grid with the Autonomous account this computer already has.+ *+ * Two halves and one result. The first is `loginCommand` reused WHOLE, so this command inherits its+ * already-signed-in short-circuit (no browser when a session exists), `--force`, the NDJSON contract+ * and the paste-the-callback-URL fallback an SSH session needs — rather than reimplementing any of+ * them. The second is the hand-off: the token goes to `grid login --harness` on its standard input.+ *+ * The token comes from `AuthSessionManager.accessToken()` and never off disk, which is the whole of+ * this command's answer to "the harness token expired": a refresh happens transparently there,+ * already coalesced in this process and across processes by the file lock. A refresh token that has+ * gone invalid is an `AuthSessionError` whose own sentence names `harness login`, so the person is+ * told WHICH of the two sign-ins broke instead of reading a stack trace about the other one.+ */+async function gridLoginCommand(force: boolean, json: boolean): Promise<void> {+ // `extra` carries whatever the child managed to say before failing: under --json its stdout is+ // captured, so without this the one channel a client is reading loses it entirely.+ const fail = (code: string, message: string, exitCode: number, extra: Record<string, unknown> = {}): void => {+ if (json) console.log(JSON.stringify({ type: 'result', status: 'error', code, message, ...extra }))+ else console.error(`\n ✗ ${message}\n`)+ process.exitCode = exitCode+ }+ let token: string+ try {+ // `chained`: the sign-in emits its authorize URL and any error line, but not a success line, so+ // what a client driving this reads is exactly one terminating result — this command's.+ if (!await loginCommand(false, force, json, { chained: true })) return+ token = await new AuthSessionManager(backendHttpBase()).accessToken()+ } catch (err) {+ if (!(err instanceof AuthSessionError)) throw err+ fail('AUTH_ERROR', err.message, 1)+ return+ }+ const handoff = await handOffToGrid(token, { json })+ if (handoff.code !== 'OK') { fail(handoff.code, handoff.message, handoff.exitCode, gridAnswer(handoff.stdout)); return }+ if (json) console.log(JSON.stringify({ type: 'result', status: 'success', ...gridAnswer(handoff.stdout) }))+}++/** What `grid` said, carried out on the result line so a client driving `--json` is not left with an+ * exit code alone. Parsed when it is JSON (it is asked for JSON), kept verbatim when it is not. */+function gridAnswer(stdout: string): Record<string, unknown> {+ const text = stdout.trim()+ if (!text) return {}+ try { return { grid: JSON.parse(text) } } catch { return { grid: text } }+}+/*** Pulls `code`/`state`/`error` out of whatever the user pasted — the full callback URL, just its query* string (with or without a leading `?`), or a bare `code=...&state=...` pair with no URL shape at all.@@ -4300,6 +4389,10 @@ switch (cmd) {case 'pairings':pairingsCommand().catch(onError)break+ case 'grid':+ if (args[0] === 'login') gridLoginCommand(flags.includes('--force'), flags.includes('--json')).catch(onError)+ else { console.error(`Unknown command: grid ${args[0] ?? ''}`); usage(1) }+ breakcase 'machines':if (!args[0]) machinesListCommand(flags.includes('--json')).catch(onError)else if (args[0] === 'list') machinesListCommand(flags.includes('--json')).catch(onError)diff --git a/cli/src/gridCommand.spec.ts b/cli/src/gridCommand.spec.tsnew file mode 100644index 000000000..1ab1b6933--- /dev/null+++ b/cli/src/gridCommand.spec.ts@@ -0,0 +1,465 @@+/**+ * `harness grid login` — the real CLI as a subprocess, against a fake backend and a fake `grid`.+ *+ * The fake `grid` is first on PATH and records the argv and the standard input it was handed. It+ * **refuses** argv without `--harness`: asserting that the harness asked for the hand-off is the one+ * thing a fake binary can honestly check, since it cannot exchange a token the way the real CLI does.+ */+import { spawn } from 'child_process'+import { createServer, type Server } from 'http'+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { delimiter, 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 servers: Server[] = []++afterEach(async () => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ for (const server of servers.splice(0)) {+ server.closeAllConnections?.()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+})++/** Records what it was given, then behaves as the surrounding test's env vars tell it to.+ * Extensionless, so Node runs it as CommonJS regardless of any package.json above it. */+const FAKE_GRID = `#!/usr/bin/env node+'use strict'+const { writeFileSync } = require('fs')+const args = process.argv.slice(2)+let stdin = ''+process.stdin.setEncoding('utf8')+process.stdin.on('data', (chunk) => { stdin += chunk })+process.stdin.on('end', () => {+ writeFileSync(process.env.FAKE_GRID_RECORD, JSON.stringify({ args, stdin, env: process.env }))+ if (!args.includes('--harness')) {+ process.stderr.write('fake grid: refusing argv that does not ask for the hand-off\\n')+ process.exitCode = 64+ return+ }+ if (process.env.FAKE_GRID_STDOUT) process.stdout.write(process.env.FAKE_GRID_STDOUT)+ process.exitCode = Number(process.env.FAKE_GRID_EXIT || '0')+})+`++function tempRoot(): string {+ const root = mkdtempSync(join(tmpdir(), 'harness-cli-grid-'))+ dirs.push(root)+ return root+}++type GridOnPath = 'runnable' | 'absent' | 'not-executable'++/** A `grid` on PATH, in one of the three states the hand-off has to tell apart.+ *+ * `not-executable` is the one that earns its keep: it is the only case where the PATH pre-check and+ * the spawn disagree — the check refuses it as unrunnable, while a spawn would answer EACCES, which+ * is NOT the ENOENT the fallback recognises. Without it, deleting the pre-check entirely leaves the+ * absent case green, and the test named for it would be measuring nothing of its own. */+function fakeGridBin(root: string, state: GridOnPath): string {+ const dir = join(root, 'bin')+ mkdirSync(dir, { recursive: true })+ if (state === 'absent') return dir+ const script = join(dir, 'grid')+ writeFileSync(script, FAKE_GRID)+ chmodSync(script, state === 'runnable' ? 0o755 : 0o644)+ return dir+}++function recordFile(root: string): string { return join(root, 'grid-invocation.json') }++function readRecord(root: string): { args: string[]; stdin: string; env: Record<string, string> } {+ return JSON.parse(readFileSync(recordFile(root), 'utf8'))+}++function seedSession(root: string, overrides: Record<string, unknown> = {}): void {+ const authDir = join(root, 'auth')+ mkdirSync(authDir, { recursive: true })+ writeFileSync(join(authDir, 'session.json'), JSON.stringify({+ version: 1,+ accessToken: 'tok_seeded',+ refreshToken: 'refresh_seeded',+ expiresAt: Date.now() + 60 * 60_000, // an hour out — accessToken() must not attempt a refresh+ autonomousEnv: 'prod',+ computerId: 'a'.repeat(32),+ machineId: 'm_seeded',+ updatedAt: Date.now(),+ ...overrides,+ }))+}++function envFor(root: string, backendUrl?: string, extra: NodeJS.ProcessEnv = {}, grid: GridOnPath = 'runnable'): NodeJS.ProcessEnv {+ return {+ ...process.env,+ HOME: root,+ HARNESS_AUTH_DIR: join(root, 'auth'),+ ADAPTER_DATA_DIR: join(root, 'data'),+ ADAPTER_CLI_DIR: join(root, 'cli'),+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),+ ADAPTER_UPDATE_DISABLE: 'true',+ // The fake goes FIRST so it wins over any real `grid` this machine has. Unless it is meant to be+ // unusable — then the rest of PATH is dropped entirely, or a developer's own installed `grid`+ // answers and the test measures their machine instead of the refusal (it did: a real CLI+ // predating `--harness` exited 2, which read as an outdated CLI rather than an absent one).+ PATH: grid === 'runnable'+ ? `${fakeGridBin(root, grid)}${delimiter}${process.env.PATH ?? ''}`+ : fakeGridBin(root, grid),+ FAKE_GRID_RECORD: recordFile(root),+ ...(backendUrl ? { BACKEND_WS_URL: backendUrl } : {}),+ ...extra,+ }+}++type Run = { status: number | null; stdout: string; stderr: string }++/** Async spawn — REQUIRED whenever the child talks to a fake backend hosted in THIS process, which+ * spawnSync would block the event loop of until the child exits, deadlocking both. */+function run(root: string, args: string[], backendUrl?: string, extra: NodeJS.ProcessEnv = {}, grid: GridOnPath = 'runnable'): Promise<Run> {+ return new Promise((resolve) => {+ const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], {+ cwd: CLI_ROOT,+ env: envFor(root, backendUrl, extra, grid),+ })+ let stdout = ''+ let stderr = ''+ child.stdout.on('data', (c: Buffer) => { stdout += c.toString() })+ child.stderr.on('data', (c: Buffer) => { stderr += c.toString() })+ child.once('exit', (status) => resolve({ status, stdout, stderr }))+ })+}++function ndjson(stdout: string): Record<string, unknown>[] {+ return stdout.trim().split('\n').filter(Boolean).map((line) => JSON.parse(line))+}++/** The `/api/auth/*` + resolve-computer calls the harness sign-in makes — real network shape. */+function fakeBackend(handlers: {+ authorizeNative?: (body: any) => any+ exchange?: (body: any) => any+ resolveComputer?: (body: any) => any+ refresh?: (body: any) => { status: number; body: unknown }+}): Promise<{ server: Server; base: string }> {+ return new Promise((resolve) => {+ const server = createServer((req, res) => {+ let raw = ''+ req.on('data', (c) => { raw += c })+ req.on('end', () => {+ const body = raw ? JSON.parse(raw) : {}+ const send = (data: unknown): void => {+ res.writeHead(200, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ success: true, data }))+ }+ if (req.url === '/api/auth/authorize-native' && handlers.authorizeNative) { send(handlers.authorizeNative(body)); return }+ if (req.url === '/api/auth/exchange' && handlers.exchange) { send(handlers.exchange(body)); return }+ if (req.url === '/api/machines/resolve-computer' && handlers.resolveComputer) { send(handlers.resolveComputer(body)); return }+ if (req.url === '/api/auth/refresh' && handlers.refresh) {+ const answer = handlers.refresh(body)+ res.writeHead(answer.status, { 'content-type': 'application/json' })+ res.end(JSON.stringify(answer.body))+ return+ }+ res.writeHead(404, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ success: false, error: { message: 'not stubbed' } }))+ })+ })+ servers.push(server)+ server.listen(0, '127.0.0.1', () => {+ const address = server.address()+ const port = typeof address === 'object' && address ? address.port : 0+ resolve({ server, base: `http://127.0.0.1:${port}` })+ })+ })+}++const signedInBackend = () => fakeBackend({ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }) })++describe('harness grid login — an already-signed-in computer', () => {+ it('hands the token over with no browser and one terminating result line', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base)++ expect(result.status).toBe(0)+ const lines = ndjson(result.stdout)+ // No authorize_url anywhere: an existing session must never reopen the browser.+ expect(lines).toEqual([{ type: 'result', status: 'success' }])+ expect(readRecord(root).args).toEqual(['login', '--harness', '--json'])+ }, 20_000)++ it('writes the token on standard input, and puts it in neither argv nor the environment', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ await run(root, ['grid', 'login', '--json'], base)++ const record = readRecord(root)+ expect(record.stdin.trim()).toBe('tok_seeded')+ expect(JSON.stringify(record.args)).not.toContain('tok_seeded')+ expect(JSON.stringify(record.env)).not.toContain('tok_seeded')+ }, 20_000)++ it('lets the child\'s own output through on the human path, and asks it for no JSON', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login'], base, { FAKE_GRID_STDOUT: 'Signed in as [email protected].\n' })++ expect(result.status).toBe(0)+ expect(result.stdout).toContain('Signed in as [email protected].')+ expect(readRecord(root).args).toEqual(['login', '--harness'])+ }, 20_000)++ it('carries the child\'s JSON answer out on the result line', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base,+ { FAKE_GRID_STDOUT: '{"signed_in":true,"email":"[email protected]","grids":[]}\n' })++ expect(result.status).toBe(0)+ expect(ndjson(result.stdout)).toEqual([+ { type: 'result', status: 'success', grid: { signed_in: true, email: '[email protected]', grids: [] } },+ ])+ }, 20_000)+})++describe('harness grid login — a signed-out computer', () => {+ it('runs the whole loopback sign-in first, then hands the new token over', async () => {+ const root = tempRoot()+ let capturedRedirectUri = ''+ const { base } = await fakeBackend({+ authorizeNative: (body) => { capturedRedirectUri = body.redirectUri; return { authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' } },+ exchange: () => ({ token: 'tok_new', refreshToken: 'refresh_new', expiresIn: 3600, autonomousEnv: 'prod' }),+ resolveComputer: () => ({ machine: { machineId: 'm_new' } }),+ })++ const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'grid', 'login', '--json'], {+ cwd: CLI_ROOT,+ env: envFor(root, base),+ })+ let stdout = ''+ const lines: Record<string, unknown>[] = []+ const gotUrl = new Promise<void>((resolve) => {+ child.stdout.on('data', (chunk: Buffer) => {+ stdout += chunk.toString()+ while (stdout.includes('\n')) {+ const idx = stdout.indexOf('\n')+ const line = stdout.slice(0, idx).trim()+ stdout = stdout.slice(idx + 1)+ if (line) { lines.push(JSON.parse(line)); resolve() }+ }+ })+ })++ await gotUrl+ expect(lines[0]).toEqual({ type: 'authorize_url', url: 'https://sso.example.test/authorize?tx=abc' })++ // Simulate the browser completing SSO against this CLI's own loopback callback server.+ await fetch(`${capturedRedirectUri}?code=code_123&state=state_456`)++ const status = await new Promise<number | null>((resolve) => child.once('exit', resolve))+ if (stdout.trim()) lines.push(JSON.parse(stdout.trim()))+ expect(status).toBe(0)+ // Two lines total: the sign-in's authorize_url, and ONE terminating result — not one per half.+ expect(lines).toEqual([+ { type: 'authorize_url', url: 'https://sso.example.test/authorize?tx=abc' },+ { type: 'result', status: 'success' },+ ])+ expect(readRecord(root).stdin.trim()).toBe('tok_new')+ }, 30_000)+})++describe('harness grid login — when the hand-off fails', () => {+ it('propagates the child\'s exit code', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base, { FAKE_GRID_EXIT: '7' })++ expect(result.status).toBe(7)+ expect(ndjson(result.stdout)).toEqual([+ { type: 'result', status: 'error', code: 'GRID_LOGIN_FAILED', message: expect.any(String) },+ ])+ }, 20_000)++ /** ⚠️ Not a shape today's `grid` produces: it refuses on STDERR (`cli/json_error.py` prints there,+ * and a `SystemExit` string goes there too), and that stream is inherited, so a refusal already+ * reaches the caller untouched. What this pins is the seam's own property — captured stdout is+ * never SWALLOWED — which is what stops a child that does write there from vanishing under the+ * one mode whose whole point is that a client can read the answer. */+ it('does not swallow what the child put on stdout before failing', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base,+ { FAKE_GRID_EXIT: '7', FAKE_GRID_STDOUT: '{"error":{"message":"no such grid"}}\n' })++ expect(result.status).toBe(7)+ expect(ndjson(result.stdout)).toEqual([{+ type: 'result',+ status: 'error',+ code: 'GRID_LOGIN_FAILED',+ message: expect.any(String),+ grid: { error: { message: 'no such grid' } },+ }])+ }, 20_000)++ it('reads exit code 2 as an outdated grid CLI, not as a network failure', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base, { FAKE_GRID_EXIT: '2' })++ expect(result.status).toBe(2)+ const [line] = ndjson(result.stdout)+ expect(line).toMatchObject({ type: 'result', status: 'error', code: 'GRID_CLI_OUTDATED' })+ expect(String(line.message)).toContain('too old')+ }, 20_000)++ it('says the same thing in the human text', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login'], base, { FAKE_GRID_EXIT: '2' })++ expect(result.status).toBe(2)+ expect(result.stderr).toContain('too old')+ }, 20_000)++ it('reports a missing grid CLI when there is none on PATH', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base, {}, 'absent')++ expect(result.status).toBe(1)+ expect(ndjson(result.stdout)).toEqual([+ { type: 'result', status: 'error', code: 'GRID_CLI_MISSING', message: expect.any(String) },+ ])+ }, 20_000)++ it('reports a grid it cannot RUN as missing too, rather than as a failed sign-in', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base, {}, 'not-executable')++ // The case above would stay green with the PATH pre-check deleted, because a spawn into an+ // empty PATH answers ENOENT and the fallback maps that to the same code. This one would not: a+ // present-but-unrunnable file is EACCES, which the fallback does NOT recognise, so without the+ // pre-check it would surface as GRID_LOGIN_FAILED.+ expect(result.status).toBe(1)+ expect(ndjson(result.stdout)).toEqual([+ { type: 'result', status: 'error', code: 'GRID_CLI_MISSING', message: expect.any(String) },+ ])+ }, 20_000)+})++describe('harness grid login — when the harness session itself is broken', () => {+ it('names the harness sign-in, not the grid one, when the refresh token is invalid', async () => {+ const root = tempRoot()+ seedSession(root, { expiresAt: Date.now() - 60_000 })+ const { base } = await fakeBackend({+ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }),+ refresh: () => ({ status: 401, body: { success: false, error: { code: 'REFRESH_TOKEN_INVALID', message: 'nope' } } }),+ })++ const result = await run(root, ['grid', 'login', '--json'], base)++ expect(result.status).toBe(1)+ const [line] = ndjson(result.stdout)+ expect(line).toMatchObject({ type: 'result', status: 'error', code: 'AUTH_ERROR' })+ expect(String(line.message)).toContain('harness login')+ }, 20_000)+})++describe('harness grid login — the sign-in half it inherits', () => {+ it('refreshes an expired token and hands over the NEW one, never the stale one', async () => {+ const root = tempRoot()+ seedSession(root, { expiresAt: Date.now() - 60_000 })+ const { base } = await fakeBackend({+ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }),+ refresh: () => ({ status: 200, body: { success: true, data: { token: 'tok_refreshed', refreshToken: 'refresh_2', expiresIn: 3600 } } }),+ })++ const result = await run(root, ['grid', 'login', '--json'], base)++ // The whole of this command's answer to "the harness token expired" is that it asks the session+ // manager rather than reading the file: a token read off disk would be `tok_seeded`, and the+ // hand-off would trade a credential the control plane has already stopped accepting.+ expect(result.status).toBe(0)+ expect(readRecord(root).stdin.trim()).toBe('tok_refreshed')+ }, 20_000)++ it('--force reaches the sign-in, so a session on disk does not short-circuit it', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await fakeBackend({+ authorizeNative: () => ({ authorizeUrl: 'https://sso.example.test/authorize?tx=forced', tx: 'tx_forced' }),+ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }),+ })++ const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'grid', 'login', '--force', '--json'], {+ cwd: CLI_ROOT,+ env: envFor(root, base),+ })+ const first = await new Promise<Record<string, unknown>>((resolve) => {+ let buffered = ''+ child.stdout.on('data', (chunk: Buffer) => {+ buffered += chunk.toString()+ const idx = buffered.indexOf('\n')+ if (idx >= 0) resolve(JSON.parse(buffered.slice(0, idx).trim()))+ })+ })+ child.kill() // it would otherwise wait five minutes for a callback nothing is going to send++ // A seeded session is present, so WITHOUT --force reaching loginCommand this would short-circuit+ // and the first line would be the terminating result instead.+ expect(first).toEqual({ type: 'authorize_url', url: 'https://sso.example.test/authorize?tx=forced' })+ }, 20_000)++ it('codes a backend failure in the sign-in half rather than crashing out of --json', async () => {+ const root = tempRoot()+ seedSession(root)+ // Nothing stubbed: resolve-computer answers 404, the way a backend having a bad minute would.+ const { base } = await fakeBackend({})++ const result = await run(root, ['grid', 'login', '--json'], base)++ // The stream must stay NDJSON. Unguarded this produced a stack trace and NO result line at all.+ expect(result.status).toBe(1)+ expect(ndjson(result.stdout)).toEqual([+ { type: 'result', status: 'error', code: 'BACKEND_ERROR', message: expect.any(String) },+ ])+ expect(result.stderr).not.toContain('Failed to start adapter')+ }, 20_000)+})++describe('the harness grid namespace', () => {+ it('refuses a subcommand it does not have', async () => {+ const root = tempRoot()+ seedSession(root)++ const result = await run(root, ['grid', 'nonsense'], 'http://127.0.0.1:1')++ expect(result.status).toBe(1)+ expect(result.stderr).toContain('Unknown command: grid nonsense')+ }, 20_000)+})diff --git a/cli/src/lib/gridHandoff.ts b/cli/src/lib/gridHandoff.tsnew file mode 100644index 000000000..0e65c0bf4--- /dev/null+++ b/cli/src/lib/gridHandoff.ts@@ -0,0 +1,113 @@+/**+ * Hand an Autonomous account token to the `grid` CLI, so signing in to a grid needs no second browser.+ *+ * The seam is a child process and nothing else: `grid login --harness` reads the token off its own+ * standard input, exchanges it at the control plane, and owns everything after that. This module's+ * whole job is to run that child honestly — put the credential somewhere a process listing cannot+ * reach, let its output and its exit code through, and turn the one exit code that means something+ * specific into a sentence.+ *+ * **Standard input, never argv and never the environment.** An argument would put a live account+ * credential into `ps` output for every user on the machine, for the life of the call; an environment+ * variable would put it in `/proc/<pid>/environ` and in anything the child later spawns.+ */+import { spawn } from 'node:child_process'+import { binaryOnPath } from './binaryOnPath.js'++/** The command, and the flag on it that means "read the token off stdin" (autonomous-grid's+ * `cli/parser.py`). Located on PATH with no environment override: tests control PATH directly, so an+ * override would be a knob with no user. */+export const GRID_BINARY = 'grid'+export const GRID_HANDOFF_FLAG = '--harness'++/**+ * argparse exits 2 on an unknown flag — BEFORE the handler, the network, or anything else in `grid`+ * runs. So a `grid` predating `--harness` fails here loudly and at once, which is what makes the+ * three-repo rollout order a deployment convenience rather than a correctness requirement.+ */+const ARGPARSE_USAGE_EXIT = 2++export type GridHandoffCode = 'OK' | 'GRID_CLI_MISSING' | 'GRID_CLI_OUTDATED' | 'GRID_LOGIN_FAILED'++export interface GridHandoffResult {+ code: GridHandoffCode+ /** The child's own exit code, propagated; 1 when there was no child, or it died on a signal. */+ exitCode: number+ /** Empty on success. Never contains the token. */+ message: string+ /** The child's stdout, captured only when `json` was asked for; otherwise it went straight out. */+ stdout: string+}++const MISSING_MESSAGE =+ 'No `grid` on PATH, so there is nothing to hand this sign-in to. Install the grid CLI, then run '+ + '`harness grid login` again.'++const OUTDATED_MESSAGE =+ `Your \`grid\` CLI is too old: it does not understand \`grid login ${GRID_HANDOFF_FLAG}\`. Update `+ + 'it, then run `harness grid login` again.'++function failedMessage(status: number | null, signal: NodeJS.Signals | null): string {+ const how = status === null ? `was killed by ${signal ?? 'a signal'}` : `exited ${status}`+ return `\`grid login ${GRID_HANDOFF_FLAG}\` ${how}. Its own output above says why.`+}++/**+ * Run `grid login --harness`, writing `token` to its standard input and closing it.+ *+ * With `json`, the child is asked for JSON too and its stdout is captured, so THIS process's stdout+ * stays a clean NDJSON stream for whatever is driving it; its stderr still passes through, which is+ * where `grid --json` puts everything a person needs to read. Without `json` both streams are+ * inherited and the child talks to the terminal directly.+ */+export async function handOffToGrid(+ token: string,+ opts: { json?: boolean } = {},+): Promise<GridHandoffResult> {+ // Asking PATH rather than spawning to find out: a missing `grid` is a sentence about installing+ // one, not a spawn error the caller has to recognise. This process's own environment, inherited —+ // there is nothing to override, and a parameter for one would be the knob with no user the ticket+ // refuses.+ if (!binaryOnPath(GRID_BINARY)) {+ return { code: 'GRID_CLI_MISSING', exitCode: 1, message: MISSING_MESSAGE, stdout: '' }+ }+ const args = ['login', GRID_HANDOFF_FLAG, ...(opts.json ? ['--json'] : [])]+ return await new Promise<GridHandoffResult>((resolve) => {+ const child = spawn(GRID_BINARY, args, {+ stdio: ['pipe', opts.json ? 'pipe' : 'inherit', 'inherit'],+ })+ let stdout = ''+ child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })++ let settled = false+ const settle = (result: GridHandoffResult): void => { if (!settled) { settled = true; resolve(result) } }++ // stdio[0] is a pipe, so this is never null. Refusing loudly anyway rather than optional-chaining+ // past it: with no pipe the token is never delivered, and a `grid` left waiting for one on a+ // stdin nobody will close would hang with nothing on screen from either process.+ const { stdin } = child+ if (!stdin) {+ child.kill()+ settle({ code: 'GRID_LOGIN_FAILED', exitCode: 1, message: `Could not open a pipe to \`${GRID_BINARY}\`.`, stdout })+ return+ }++ // Between the PATH check and the spawn the binary can still be gone; and a child that exits+ // before reading breaks the pipe. Both are the child's story to tell, never a crash here.+ child.once('error', (err: NodeJS.ErrnoException) => settle(err.code === 'ENOENT'+ ? { code: 'GRID_CLI_MISSING', exitCode: 1, message: MISSING_MESSAGE, stdout }+ : { code: 'GRID_LOGIN_FAILED', exitCode: 1, message: `Could not run \`${GRID_BINARY}\`: ${err.message}`, stdout }))+ stdin.on('error', () => { /* EPIPE — see above */ })++ // A trailing newline as well as the close: `grid` reads one bounded LINE, so the hand-off does+ // not depend on which of the two it notices first.+ stdin.end(`${token}\n`)++ // `close`, not `exit`: the captured stdout must be complete before it is reported.+ child.once('close', (status, signal) => {+ if (status === 0) { settle({ code: 'OK', exitCode: 0, message: '', stdout }); return }+ if (status === ARGPARSE_USAGE_EXIT) { settle({ code: 'GRID_CLI_OUTDATED', exitCode: status, message: OUTDATED_MESSAGE, stdout }); return }+ settle({ code: 'GRID_LOGIN_FAILED', exitCode: status ?? 1, message: failedMessage(status, signal), stdout })+ })+ })+}