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: add harness flash command to download and execute remote device firmware flasher

0xken153b09f2b5eeaa
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 919e1f726..649436534 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -26,6 +26,7 @@ import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
+import { flashCommand } from './lib/flash.js'
import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'
@@ -153,6 +154,8 @@ Machine:
harness status show whether it's running (+ version)
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
+ flasher: --detect-only, --port, --version, --yes, --erase-nvs
Browser end-to-end encryption:
harness browser-link print a reusable 7-day setup link for browsers
@@ -2286,6 +2289,13 @@ switch (cmd) {
case 'update':
updateCommand().catch(onError)
break
+ case 'flash':
+ // Everything after `flash` belongs to the flasher, not to us — see lib/flash.ts on why the flags
+ // are not parsed here. Its exit code is ours, so `harness flash --detect-only` works in a script.
+ flashCommand(process.argv.slice(3))
+ .then((code) => { process.exitCode = code })
+ .catch(onError)
+ break
default:
console.error(`Unknown command: ${cmd}`)
usage()
diff --git a/cli/src/lib/flash.spec.ts b/cli/src/lib/flash.spec.ts
new file mode 100644
index 000000000..69d215aca
--- /dev/null
+++ b/cli/src/lib/flash.spec.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest'
+import { flashCommand, scriptUrl, type FlashDeps } from './flash.js'
+
+/**
+ * `harness flash` owns three things — which script, how to get it, and handing the user's flags over
+ * untouched. Everything that decides whether a board survives the write lives in the shell script and
+ * is deliberately NOT duplicated here, so these assertions stop at the wrapper.
+ *
+ * Nothing in this file may touch hardware. The one thing that cannot be proven here — that a real
+ * board ends up running the firmware — is a manual gate, not a test.
+ */
+
+const SCRIPT = '#!/usr/bin/env bash\necho flasher\n'
+
+function harness(over: Partial<FlashDeps> & { cache?: string | null } = {}) {
+ const calls: { args: string[][]; written: string[]; logs: string[]; warns: string[] } =
+ { args: [], written: [], logs: [], warns: [] }
+ let cache = over.cache ?? null
+ const deps: Partial<FlashDeps> = {
+ fetchScript: over.fetchScript ?? (async () => SCRIPT),
+ readCache: over.readCache ?? (() => cache),
+ writeCache: over.writeCache ?? ((body) => { cache = body; calls.written.push(body) }),
+ run: over.run ?? (async (_p, args) => { calls.args.push(args); return 0 }),
+ log: (l) => calls.logs.push(l),
+ warn: (l) => calls.warns.push(l),
+ }
+ return { deps, calls }
+}
+
+describe('harness flash — getting the script', () => {
+ it('prefers the network copy and caches it', async () => {
+ const { deps, calls } = harness()
+
+ expect(await flashCommand([], deps)).toBe(0)
+ expect(calls.written).toEqual([SCRIPT])
+ // Says which copy it ran. A flasher that silently ran something other than the newest is exactly
+ // what the server's `no-store` header exists to prevent.
+ expect(calls.logs.join('\n')).toContain(scriptUrl())
+ expect(calls.warns).toEqual([])
+ })
+
+ /** A bench with no connection is a real situation, so the cache is a fallback — but a LOUD one. */
+ it('falls back to the cache when the network fails, and warns', async () => {
+ const { deps, calls } = harness({
+ fetchScript: async () => { throw new Error('getaddrinfo ENOTFOUND') },
+ cache: SCRIPT,
+ })
+
+ expect(await flashCommand([], deps)).toBe(0)
+ const warned = calls.warns.join('\n')
+ expect(warned).toContain('CACHED')
+ expect(warned).toContain('may be out of date')
+ expect(calls.args).toHaveLength(1) // it still ran
+ })
+
+ it('refuses, with the manual commands, when there is no network and no cache', async () => {
+ const { deps } = harness({
+ fetchScript: async () => { throw new Error('offline') },
+ cache: null,
+ })
+
+ await expect(flashCommand([], deps)).rejects.toThrow(/no cached copy/)
+ await expect(flashCommand([], deps)).rejects.toThrow(/curl -fsSL/)
+ })
+
+ /**
+ * A captive portal or an error page answers 200 with HTML. Writing that to the cache would poison
+ * the fallback for every later run, so the shebang check happens before anything is stored — this
+ * asserts the caller sees a failure rather than a "successful" flash of nothing.
+ */
+ it('treats a non-script response as a failure', async () => {
+ const { deps, calls } = harness({
+ fetchScript: async () => { throw new Error('response is not a shell script (proxy or error page?)') },
+ cache: null,
+ })
+
+ await expect(flashCommand([], deps)).rejects.toThrow(/not a shell script/)
+ expect(calls.written).toEqual([])
+ })
+})
+
+describe('harness flash — handing over the flags', () => {
+ /**
+ * The wrapper does not parse the flasher's flags, so a flag it has never heard of has to reach the
+ * script unchanged. This is what keeps the two from drifting when the script gains an option.
+ */
+ it('passes every argument through verbatim, including unknown ones', async () => {
+ const { deps, calls } = harness()
+ const args = ['--detect-only', '--port', '/dev/cu.usbmodem21301', '--totally-new-flag', 'x y']
+
+ await flashCommand(args, deps)
+
+ expect(calls.args[0]).toEqual(args)
+ })
+
+ /** `harness flash --detect-only` has to be usable in a shell condition, so the code is not swallowed. */
+ it("returns the script's own exit code", async () => {
+ const { deps } = harness({ run: async () => 3 })
+
+ expect(await flashCommand(['--detect-only'], deps)).toBe(3)
+ })
+
+ it('explains itself when bash is missing rather than failing bare', async () => {
+ const { deps } = harness({
+ run: async () => { throw Object.assign(new Error('spawn bash ENOENT'), { code: 'ENOENT' }) },
+ })
+
+ await expect(flashCommand([], deps)).rejects.toThrow(/bash was not found/)
+ })
+})
+
+describe('harness flash — where it points', () => {
+ it('builds the URL from WEB_URL, so a local web app is used in dev', () => {
+ // WEB_URL already falls back to loopback when BACKEND_WS_URL is local (config/env.ts), which is
+ // why this command needs no environment variable of its own.
+ expect(scriptUrl()).toMatch(/^https?:\/\/.+\/flash-circle\.sh$/)
+ })
+})
diff --git a/cli/src/lib/flash.ts b/cli/src/lib/flash.ts
new file mode 100644
index 000000000..309083508
--- /dev/null
+++ b/cli/src/lib/flash.ts
@@ -0,0 +1,144 @@
+/**
+ * `harness flash` — re-flash a plugged-in CIRCLE device over USB.
+ *
+ * This is a WRAPPER, deliberately. The flasher itself is a 415-line shell script published at
+ * `<WEB_URL>/flash-circle.sh`, and it stays the single source of truth for everything that decides
+ * whether a board survives the write: the chip it will talk to, the app offset, the otadata and NVS
+ * regions, the flash mode/size/frequency, and the sha256 checks on both esptool and the firmware.
+ * Re-implementing that here would put those numbers in two places, and the failure mode of a
+ * disagreement is a bricked board that needs a USB cable and a person to recover.
+ *
+ * So this file owns three things and nothing else: WHICH script to run, HOW to get it, and getting the
+ * user's flags to it untouched.
+ *
+ * Flags are passed through verbatim rather than parsed. `--detect-only`, `--port`, `--yes`,
+ * `--version`, `--erase-nvs`, `--no-verify` and `--no-flash` therefore work without this file knowing
+ * they exist — and a flag added to the script later works the day it ships, instead of the day someone
+ * remembers to widen a list here.
+ */
+
+import { spawn } from 'child_process'
+import { mkdirSync, readFileSync, writeFileSync } from 'fs'
+import { dirname, join } from 'path'
+import { homedir } from 'os'
+import { env } from '../config/env.js'
+
+/**
+ * The script caches its own downloads (esptool, firmware) under `~/.harness/flasher` via
+ * `HARNESS_FLASHER_CACHE`. Keeping our copy of the script in the same directory is deliberate: one
+ * place holds everything the flasher owns, so "delete this folder" is a complete reset.
+ */
+const CACHE_DIR = process.env.HARNESS_FLASHER_CACHE || join(homedir(), '.harness', 'flasher')
+const CACHED_SCRIPT = join(CACHE_DIR, 'flash-circle.sh')
+const FETCH_TIMEOUT_MS = 20_000
+
+export interface FlashDeps {
+ /** Overridden in tests; the real one is `fetch`. */
+ fetchScript: (url: string) => Promise<string>
+ readCache: () => string | null
+ writeCache: (body: string) => void
+ run: (scriptPath: string, args: string[]) => Promise<number>
+ log: (line: string) => void
+ warn: (line: string) => void
+}
+
+export function scriptUrl(): string {
+ return `${env.WEB_URL.replace(/\/+$/, '')}/flash-circle.sh`
+}
+
+async function realFetch(url: string): Promise<string> {
+ const res = await fetch(url, {
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ // The server already answers `no-store` for a reason it states out loud: an operator must never be
+ // handed a stale flasher after a fix has shipped. Say the same thing from this side so a proxy in
+ // between cannot decide otherwise.
+ headers: { 'cache-control': 'no-cache' },
+ })
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)
+ const body = await res.text()
+ // A captive portal or an error page returns 200 with HTML. Running that under bash does nothing
+ // useful and reports it confusingly, so check it is a script before it is ever written to disk.
+ if (!body.startsWith('#!')) throw new Error('response is not a shell script (proxy or error page?)')
+ return body
+}
+
+function realRun(scriptPath: string, args: string[]): Promise<number> {
+ return new Promise((resolve, reject) => {
+ // `inherit`, not a pipe. The script prints progress as it goes and asks for confirmation on
+ // /dev/tty; capturing its output would hide the first and break the second.
+ const child = spawn('bash', [scriptPath, ...args], { stdio: 'inherit' })
+ child.on('error', reject)
+ child.on('close', (code) => resolve(code ?? 1))
+ })
+}
+
+const defaults: FlashDeps = {
+ fetchScript: realFetch,
+ readCache: () => {
+ try { return readFileSync(CACHED_SCRIPT, 'utf-8') } catch { return null }
+ },
+ writeCache: (body) => {
+ mkdirSync(dirname(CACHED_SCRIPT), { recursive: true })
+ writeFileSync(CACHED_SCRIPT, body, { mode: 0o755 })
+ },
+ run: realRun,
+ log: (line) => console.log(line),
+ warn: (line) => console.error(line),
+}
+
+/**
+ * Fetch-then-fall-back, and always say which one happened.
+ *
+ * The network copy wins whenever it can be had, because a flasher fix has to reach the person holding
+ * the board. The cache exists only so a flash is still possible on a machine that is offline — which
+ * is a real situation at a bench — and using it is reported, never silent.
+ */
+async function resolveScript(deps: FlashDeps): Promise<{ body: string; source: 'fetched' | 'cached' }> {
+ const url = scriptUrl()
+ try {
+ const body = await deps.fetchScript(url)
+ deps.writeCache(body)
+ return { body, source: 'fetched' }
+ } catch (err) {
+ const cached = deps.readCache()
+ const why = err instanceof Error ? err.message : String(err)
+ if (cached === null) {
+ throw new Error(
+ `could not download the flasher from ${url} (${why}), and no cached copy exists.\n`
+ + 'With a working connection you can always run it by hand:\n'
+ + ` curl -fsSL ${url} -o flash-circle.sh\n`
+ + ' bash flash-circle.sh',
+ )
+ }
+ deps.warn(`! could not reach ${url} (${why})`)
+ deps.warn(`! running the CACHED flasher from ${CACHED_SCRIPT} — it may be out of date`)
+ return { body: cached, source: 'cached' }
+ }
+}
+
+/**
+ * Run the published circle flasher with `args` passed straight through.
+ *
+ * Returns the script's own exit code so `harness flash --detect-only` is usable in a shell condition:
+ * the script exits non-zero when it finds no board, and that has to survive the wrapper.
+ */
+export async function flashCommand(args: string[], overrides: Partial<FlashDeps> = {}): Promise<number> {
+ const deps: FlashDeps = { ...defaults, ...overrides }
+ const { source } = await resolveScript(deps)
+ deps.log(`>> circle flasher (${source === 'fetched' ? scriptUrl() : `cached: ${CACHED_SCRIPT}`})`)
+ try {
+ return await deps.run(CACHED_SCRIPT, args)
+ } catch (err) {
+ // The only way `spawn` itself fails here in practice. Every macOS and Linux ships bash; a machine
+ // without it cannot run the flasher at all, so say what to do instead of just failing.
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') {
+ throw new Error(
+ 'bash was not found on PATH, and the flasher is a bash script.\n'
+ + `Install bash, or run it yourself on a machine that has one:\n`
+ + ` curl -fsSL ${scriptUrl()} -o flash-circle.sh\n`
+ + ' bash flash-circle.sh',
+ )
+ }
+ throw err
+ }
+}