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
fix: carry the child's refusal, and say when the session was reused
Kelvinb2f931a4d977
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 29a719a69..315eece53 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -418,20 +418,27 @@ async function authStatusCommand(json: boolean): Promise<void> {* once; without it the sign-in throws, as `harness login` has always done, and the top-level handler* prints it.*/+type SignInOutcome =+ /** Signed in — `alreadySignedIn` distinguishes a session that was already there from a fresh one,+ * which is the one fact a caller cannot re-derive except by watching for an `authorize_url`. */+ | { signedIn: true; alreadySignedIn: boolean }+ /** Refused. Under `--json` its own coded result line has already been emitted. */+ | { signedIn: false }+async function loginCommand(foreground: boolean,force: boolean,json: boolean,opts: { chained?: boolean } = {},-): Promise<boolean> {+): Promise<SignInOutcome> {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+ const succeed = (alreadySignedIn: boolean): SignInOutcome => {+ if (opts.chained) return { signedIn: true, alreadySignedIn }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+ return { signedIn: true, alreadySignedIn }}if (readAuthSession() && !force) {// Guarded exactly like the identical call after the exchange below. Unguarded, a hiccup on@@ -447,7 +454,7 @@ async function loginCommand(if (json && !(err instanceof AuthSessionError)) {emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message })process.exitCode = 1- return false+ return { signedIn: false }}throw err}@@ -473,7 +480,7 @@ async function loginCommand(})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 false }+ if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }throw err}if (json) {@@ -509,7 +516,7 @@ async function loginCommand(})} 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 false }+ if (json) { emit({ type: 'result', status: 'error', code: timedOut ? 'TIMEOUT' : 'CALLBACK_ERROR', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }throw err} finally {manual?.cancel()@@ -522,7 +529,7 @@ async function loginCommand(})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 false }+ if (json) { emit({ type: 'result', status: 'error', code: 'EXCHANGE_FAILED', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }throw err}const id = computerId()@@ -539,7 +546,7 @@ async function loginCommand(try {await resolveComputerMachine()} catch (err) {- if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return false }+ if (json) { emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message }); process.exitCode = 1; return { signedIn: false } }throw err}return succeed(false)@@ -564,18 +571,22 @@ async function loginCommand(* 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.+ // `extra` carries what the child itself said. Under --json both its streams are captured, so+ // without this the one channel a client is reading is left with an exit code and nothing else.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 signIn: SignInOutcomelet token: stringtry {// `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+ signIn = await loginCommand(false, force, json, { chained: true })+ // ⚠️ On the FIELD, never on the object: every outcome is truthy, so `if (!outcome)` would read+ // a refusal as a success and hand a token that was never obtained to the child.+ if (signIn.signedIn === false) returntoken = await new AuthSessionManager(backendHttpBase()).accessToken()} catch (err) {if (!(err instanceof AuthSessionError)) throw err@@ -583,16 +594,31 @@ async function gridLoginCommand(force: boolean, json: boolean): Promise<void> {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) }))+ if (handoff.code !== 'OK') { fail(handoff.code, handoff.message, handoff.exitCode, gridSaid(handoff)); return }+ if (!json) return+ // The same key `harness login --json` uses, present only when it is true, so a client driving the+ // two reads one contract rather than two — the harness sign-in's own line is worded exactly so.+ console.log(JSON.stringify({+ type: 'result',+ status: 'success',+ ...(signIn.alreadySignedIn ? { alreadySignedIn: true } : {}),+ ...gridSaid(handoff),+ }))}-/** 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 } }+/** What `grid` itself said, carried out on the result line beside this command's own classification.+ *+ * `grid`'s answer on success is a JSON document on stdout, so it travels parsed, under `grid`. Its+ * refusals go to **stderr** — every one of them already names its own way forward — and those+ * travel verbatim under `detail`, because a client reading NDJSON off stdout would otherwise have+ * the exit code and no sentence to show anybody. Both are omitted when empty rather than sent as+ * `null`: an absent key reads as "the child said nothing there", which is what it means. */+function gridSaid(handoff: { stdout: string; stderr: string }): Record<string, unknown> {+ const out = handoff.stdout.trim()+ const err = handoff.stderr.trim()+ let parsed: unknown = null+ if (out) { try { parsed = JSON.parse(out) } catch { parsed = out } }+ return { ...(out ? { grid: parsed } : {}), ...(err ? { detail: err } : {}) }}/**diff --git a/cli/src/gridCommand.spec.ts b/cli/src/gridCommand.spec.tsindex 8623cd6b1..ace4c76de 100644--- a/cli/src/gridCommand.spec.ts+++ b/cli/src/gridCommand.spec.ts@@ -44,6 +44,8 @@ process.stdin.on('end', () => {return}if (process.env.FAKE_GRID_STDOUT) process.stdout.write(process.env.FAKE_GRID_STDOUT)+ // Where the real \`grid\` puts every refusal — see the test that reads it back off the result line.+ if (process.env.FAKE_GRID_STDERR) process.stderr.write(process.env.FAKE_GRID_STDERR)process.exitCode = Number(process.env.FAKE_GRID_EXIT || '0')})`@@ -215,8 +217,10 @@ describe('harness grid login — an already-signed-in computer', () => {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' }])+ // No authorize_url anywhere: an existing session must never reopen the browser. And+ // `alreadySignedIn` is the key `harness login --json` puts on exactly this outcome — the same+ // contract, so a client driving the two does not need two readers.+ expect(lines).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true }])expect(readRecord(root).args).toEqual(['login', '--harness', '--json'])}, 20_000)@@ -255,7 +259,7 @@ describe('harness grid login — an already-signed-in computer', () => {expect(result.status).toBe(0)expect(ndjson(result.stdout)).toEqual([- { type: 'result', status: 'success', grid: { signed_in: true, email: '[email protected]', grids: [] } },+ { type: 'result', status: 'success', alreadySignedIn: true, grid: { signed_in: true, email: '[email protected]', grids: [] } },])}, 20_000)})@@ -300,6 +304,8 @@ describe('harness grid login — a signed-out computer', () => {// 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' },+ // No `alreadySignedIn`: this computer was signed OUT, and the key is absent rather than+ // `false` — which is how `harness login --json` words the same outcome.{ type: 'result', status: 'success' },])expect(readRecord(root).stdin.trim()).toBe('tok_new')@@ -343,6 +349,39 @@ describe('harness grid login — when the hand-off fails', () => {}])}, 20_000)+ it('carries the child\'s own refusal out on the result line, and still to stderr', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()+ // The shape a real refusal has: `grid` writes its sentence to STDERR and nothing to stdout.+ const refusal = 'This control plane cannot sign you in with an Autonomous account token yet.\n'++ const result = await run(root, ['grid', 'login', '--json'], base,+ { FAKE_GRID_EXIT: '1', FAKE_GRID_STDERR: refusal })++ // Needed in BOTH places, for two different readers. A client reading NDJSON off stdout would+ // otherwise hold an exit code and have no sentence to show anybody — this command's own message+ // classifies the failure, only the child's names the way out of it.+ const [line] = ndjson(result.stdout)+ expect(line).toMatchObject({ type: 'result', status: 'error', code: 'GRID_LOGIN_FAILED' })+ expect(String(line.detail)).toContain('cannot sign you in')+ // And a person watching the terminal still sees it where it has always been.+ expect(result.stderr).toContain('cannot sign you in')+ }, 20_000)++ it('says nothing where the child said nothing, rather than sending empty keys', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await signedInBackend()++ const result = await run(root, ['grid', 'login', '--json'], base, { FAKE_GRID_EXIT: '7' })++ // An ABSENT key reads as "the child said nothing there"; `null` or `''` would read as an answer.+ expect(ndjson(result.stdout)).toEqual([+ { type: 'result', status: 'error', code: 'GRID_LOGIN_FAILED', message: expect.any(String) },+ ])+ }, 20_000)+it('reads exit code 2 as an outdated grid CLI, not as a network failure', async () => {const root = tempRoot()seedSession(root)diff --git a/cli/src/lib/gridHandoff.ts b/cli/src/lib/gridHandoff.tsindex 0e65c0bf4..df4f72dd2 100644--- a/cli/src/lib/gridHandoff.ts+++ b/cli/src/lib/gridHandoff.ts@@ -33,10 +33,22 @@ 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. */+ /** This module's own classification of the failure. 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+ /** The child's stderr — where `grid` writes every refusal — captured only when `json` was asked+ * for, and passed through to this process's stderr either way. */+ stderr: string+}++/** A bound on what a child can put into one JSON line. `grid` answers a small document and refuses+ * in a sentence or two, so this is not a tuning knob; it is a bound on a process whose output this+ * one does not control, and it is applied to the CAPTURE only — the passthrough is untouched. */+const MAX_CAPTURED_CHARS = 64 * 1024++function capped(sofar: string, chunk: Buffer): string {+ return sofar.length >= MAX_CAPTURED_CHARS ? sofar : (sofar + chunk.toString()).slice(0, MAX_CAPTURED_CHARS)}const MISSING_MESSAGE =@@ -49,16 +61,20 @@ const OUTDATED_MESSAGE =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.`+ // No "see the output above": under --json there IS no above for whatever is reading the stream.+ // What `grid` said travels with the failure instead, on `stderr`.+ return `\`grid login ${GRID_HANDOFF_FLAG}\` ${how}.`}/*** 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.+ * With `json`, the child is asked for JSON too and BOTH its streams are captured, so THIS process's+ * stdout stays a clean NDJSON stream for whatever is driving it. stderr is captured **and** written+ * straight back out, because it is needed twice: `grid` refuses on stderr, so that text is the only+ * actionable thing a failure has — and a client reading NDJSON off stdout would never see it, while+ * a person watching the terminal expects it where it has always been. Without `json` both streams+ * are inherited and the child talks to the terminal directly.*/export async function handOffToGrid(token: string,@@ -69,15 +85,20 @@ export async function handOffToGrid(// 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: '' }+ return { code: 'GRID_CLI_MISSING', exitCode: 1, message: MISSING_MESSAGE, stdout: '', stderr: '' }}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'],+ stdio: ['pipe', opts.json ? 'pipe' : 'inherit', opts.json ? 'pipe' : 'inherit'],})let stdout = ''- child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })+ let stderr = ''+ child.stdout?.on('data', (chunk: Buffer) => { stdout = capped(stdout, chunk) })+ child.stderr?.on('data', (chunk: Buffer) => {+ stderr = capped(stderr, chunk)+ process.stderr.write(chunk) // the passthrough, unbounded — only the capture is bounded+ })let settled = falseconst settle = (result: GridHandoffResult): void => { if (!settled) { settled = true; resolve(result) } }@@ -88,15 +109,15 @@ export async function handOffToGrid(const { stdin } = childif (!stdin) {child.kill()- settle({ code: 'GRID_LOGIN_FAILED', exitCode: 1, message: `Could not open a pipe to \`${GRID_BINARY}\`.`, stdout })+ settle({ code: 'GRID_LOGIN_FAILED', exitCode: 1, message: `Could not open a pipe to \`${GRID_BINARY}\`.`, stdout, stderr })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 }))+ ? { code: 'GRID_CLI_MISSING', exitCode: 1, message: MISSING_MESSAGE, stdout, stderr }+ : { code: 'GRID_LOGIN_FAILED', exitCode: 1, message: `Could not run \`${GRID_BINARY}\`: ${err.message}`, stdout, stderr }))stdin.on('error', () => { /* EPIPE — see above */ })// A trailing newline as well as the close: `grid` reads one bounded LINE, so the hand-off does@@ -105,9 +126,9 @@ export async function handOffToGrid(// `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 })+ if (status === 0) { settle({ code: 'OK', exitCode: 0, message: '', stdout, stderr }); return }+ if (status === ARGPARSE_USAGE_EXIT) { settle({ code: 'GRID_CLI_OUTDATED', exitCode: status, message: OUTDATED_MESSAGE, stdout, stderr }); return }+ settle({ code: 'GRID_LOGIN_FAILED', exitCode: status ?? 1, message: failedMessage(status, signal), stdout, stderr })})})}