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
cli: carry the grid CLI as a managed runtime — laid down by the installer, kept at its pin by the daemon
Kelvin38e83641b6f5
diff --git a/cli/scripts/install.sh b/cli/scripts/install.shindex d5b2be6b1..f5e05266f 100755--- a/cli/scripts/install.sh+++ b/cli/scripts/install.sh@@ -70,11 +70,16 @@ RUNTIME_METADATA_URL="${HARNESS_RUNTIME_METADATA_URL:-https://storage.googleapis# Published by release-tmux-runtime.yml (`make upload-tmux-runtime`): macOS tmux built against static# libevent/ncurses, its own manifest because the Node one already has a "darwin-arm64" key.TMUX_METADATA_URL="${HARNESS_TMUX_METADATA_URL:-https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/runtime/tmux/metadata.json}"+# Published by release-grid-runtime.yml: the grid CLI at the version this harness release PINS, in its+# own manifest for the reason tmux has one. This installer lays the first one down (step 3b); the+# daemon follows the pin on every start after that (ensureManagedGrid, cli/src/lib/runtimeInstall.ts).+GRID_METADATA_URL="${HARNESS_GRID_METADATA_URL:-https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/runtime/grid/metadata.json}"HARNESS_KEY="${HARNESS_KEY:-cli}"CLI_DIR="$HOME/.harness/cli"RUNTIME_DIR="$HOME/.harness/runtime"CURRENT_NODE_FILE="$RUNTIME_DIR/current-node"CURRENT_TMUX_FILE="$RUNTIME_DIR/current-tmux"+CURRENT_GRID_FILE="$RUNTIME_DIR/current-grid"BIN_DIR="$HOME/.local/bin"LAUNCHER="$BIN_DIR/harness"@@ -152,6 +157,74 @@ case "$(basename "${SHELL:-/bin/sh}")" inesac}+# The managed grid for this computer: download, verify, unpack under ~/.harness/runtime and record it+# in current-grid (what the daemon reads, like current-node). Returns non-zero, having said why,+# instead of exiting: the caller decides that a missing grid is not a failed install — the harness+# works without one, and the daemon fetches it on its next start. Laid down READ-ONLY, the bin+# directory too: `grid update` replaces the binary with a rename INTO that directory, and a directory+# it cannot write to is what makes that fail loudly instead of overwriting the pin. Never linked into+# ~/.local/bin — see the call site.+install_managed_grid() {+ platform="$(manifest_platform)"+ [ -n "$platform" ] || {+ echo " ✗ No managed grid is published for $(uname -s)/$(uname -m)." >&2+ return 1+ }+ grid_manifest="$(curl -fsSL "$GRID_METADATA_URL")" || {+ echo " ✗ Could not fetch the grid manifest: $GRID_METADATA_URL" >&2+ return 1+ }+ grid_entry="$(manifest_entry "$grid_manifest" "$platform")"+ grid_url="$(entry_field "$grid_entry" url)"+ grid_sha="$(entry_field "$grid_entry" sha256)"+ grid_root="$(entry_field "$grid_entry" archiveRoot)"+ grid_version="$(entry_field "$grid_entry" version)"+ if [ -z "$grid_url" ] || [ -z "$grid_sha" ] || [ -z "$grid_root" ] || [ -z "$grid_version" ]; then+ echo " ✗ The grid manifest has no usable '$platform' entry." >&2+ return 1+ fi+ grid_target="$RUNTIME_DIR/$grid_root"+ if [ ! -x "$grid_target/bin/grid" ]; then+ mkdir -p "$RUNTIME_DIR"+ chmod 700 "$RUNTIME_DIR" 2>/dev/null || true+ grid_staging="$RUNTIME_DIR/.grid-staging-$$"+ rm -rf "$grid_staging"+ mkdir -p "$grid_staging"+ echo " ▸ downloading grid $grid_version ($platform)…"+ if ! curl -fsSL "$grid_url" -o "$grid_staging/grid.tar.gz"; then+ echo " ✗ Could not download $grid_url" >&2+ rm -rf "$grid_staging"+ return 1+ fi+ grid_got="$(sha256_of "$grid_staging/grid.tar.gz")"+ if [ "$grid_got" != "$grid_sha" ]; then+ echo " ✗ grid download failed checksum verification (expected $grid_sha, got $grid_got)" >&2+ rm -rf "$grid_staging"+ return 1+ fi+ if ! tar -xzf "$grid_staging/grid.tar.gz" -C "$grid_staging" || [ ! -x "$grid_staging/$grid_root/bin/grid" ]; then+ echo " ✗ The grid archive has no $grid_root/bin/grid" >&2+ rm -rf "$grid_staging"+ return 1+ fi+ # A half-laid-down target from an earlier attempt may already be read-only; give it back first.+ chmod -R u+w "$grid_target" 2>/dev/null || true+ rm -rf "$grid_target"+ mv "$grid_staging/$grid_root" "$grid_target"+ rm -rf "$grid_staging"+ fi+ chmod 555 "$grid_target/bin/grid" "$grid_target/bin" 2>/dev/null || true+ # Its update check off, as the daemon keeps it: this binary is the pin, not grid's to replace.+ if ! GRID_NO_UPDATE_CHECK=1 "$grid_target/bin/grid" --version >/dev/null 2>&1; then+ echo " ✗ The managed grid does not run on this computer: $grid_target/bin/grid" >&2+ return 1+ fi+ printf '%s\n' "$grid_target/bin/grid" > "$CURRENT_GRID_FILE"+ chmod 600 "$CURRENT_GRID_FILE" 2>/dev/null || true+ echo " ✓ installed grid $grid_version → $grid_target"+ return 0+}+# 1. Host requirements (standalone and --host). The CLI runs tmux, `ps`, and on a Linux desktop the# clipboard helper — those are checked, and only what is missing is obtained. This installer# already runs in a terminal, so package-manager password prompts stay with the OS — never Harness.@@ -571,6 +644,17 @@ const bin = path.join(os.homedir(), '.local', 'bin')})().catch((err) => { console.error('✗ install failed: ' + err.message); process.exit(1) })HARNESSJS+# 3b. The managed grid — the grid CLI this release pins, beside Node and tmux: the daemon shells out+# to it, and an agent's pane runs it by name. Optional where Node and tmux are not: the harness+# works without it (every grid call says so, in a sentence), and the daemon follows the pin on+# every start, so a download that fails here is retried by `harness start`. Never linked into+# ~/.local/bin — that path is grid's own installer's (uv's, on a Mac) — the daemon puts the+# managed grid on an agent pane's PATH itself. Host mode installs no CLI, so no grid either.+if [ "$INSTALL_MODE" != "host" ]; then+ echo "▸ Installing the managed grid into $RUNTIME_DIR"+ install_managed_grid || echo " · the grid runtime will be fetched by the daemon on its next start"+fi+# 4. Ensure ~/.local/bin is on PATH (per shell), idempotently — defined up with the other helpers.ensure_path_rcdiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex f9fc4f585..735294940 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -148,7 +148,7 @@ import {type Poller, type UpdateEntry,} from './lib/selfUpdate.js'import { managedNodePath } from './lib/nodeRuntime.js'-import { ensureLauncher, ensureManagedRuntime } from './lib/runtimeInstall.js'+import { ensureLauncher, ensureManagedGrid, ensureManagedRuntime } from './lib/runtimeInstall.js'import { stat } from 'fs/promises'import { CodexNormalizer, codexTaskError, lastCodexTurnText } from './engines/codex/normalizer.js'import { codexSubagentResolverFor } from './engines/codex/subagent.js'@@ -1095,6 +1095,14 @@ async function runForeground(session: AuthSession): Promise<void> {console.error('[fatal-guard] uncaughtException:', err instanceof Error ? (err.stack ?? err.message) : err)})+ // The managed grid follows its pin on EVERY daemon start — this one, and the restart a self-update+ // ends in — not only on `--repair`: the pin is expected to move, and a machine installed last month+ // has to notice. Not awaited: a download must never hold the control port back, and every grid+ // call resolves the binary afresh (`gridBinaryPath`), so whatever lands is picked up as it lands.+ // Best-effort by construction — it returns rather than throws — and the fatal guard above is the+ // net under the promise itself.+ void ensureManagedGrid((m) => console.log(`[grid-runtime] ${m}`))+registry.load()// Persisted locators are hints until this process has observed their terminal root and PID/start marker.// Mark them dormant before the backend socket can publish anything; the first authoritative reconcile@@ -4943,6 +4951,11 @@ async function launch(foreground: boolean, repair: boolean = false): Promise<voiruntimeNode = repairedensureLauncher(repaired, (m) => console.log(m))}+ // The managed grid too, in the open, for the daemon this command is about to spawn: it follows+ // its pin quietly on every start (runForeground), and `--repair` is where a person watches it+ // happen. A FOREGROUND start becomes the daemon itself and runForeground's own call prints to+ // this same terminal — once is enough.+ if (!foreground) await ensureManagedGrid((m) => console.log(m))}// Foreground mode (supervisor) OR dev/tsx (can't cleanly spawn a .ts detached) → run inline.if (foreground || SCRIPT_PATH.endsWith('.ts')) {diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 6a7bf2942..1071d8e26 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -406,6 +406,14 @@ const envSchema = z.object({ADAPTER_RUNTIME_METADATA_URL: z.string().default('https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/runtime/metadata.json'),+ // The managed grid's manifest — its own document, as tmux's is (harness/runtime/tmux/metadata.json):+ // install.sh slices a manifest by the FIRST platform key it finds, and Node's already has one. The+ // same entry shape (version/url/sha256/size/archiveRoot), and its version is the PIN: the grid this+ // build of the CLI drives, moved on purpose by a release and never by grid's own updater — see+ // ensureManagedGrid() in lib/runtimeInstall.ts, which follows it on every daemon start.+ ADAPTER_GRID_RUNTIME_METADATA_URL: z+ .string()+ .default('https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/runtime/grid/metadata.json'),// Where the `harness` launcher lives. Same name (and default) `scripts/install-cli.sh` uses, so a// sandboxed install and this process agree on which launcher they are talking about.HARNESS_BIN_DIR: z.string().default(adapterBinDir),diff --git a/cli/src/lib/gridExec.spec.ts b/cli/src/lib/gridExec.spec.tsindex 36b80ee70..073c50931 100644--- a/cli/src/lib/gridExec.spec.ts+++ b/cli/src/lib/gridExec.spec.ts@@ -102,6 +102,10 @@ describe('gridCliPresence', () => {process.env.HARNESS_GRID_BIN = fakeGrid(join(root, 'elsewhere'))expect(gridCliPresence()).toBe('path')++ // Wherever the override lives — even under the runtime dir — it is the developer's, not the pin.+ process.env.HARNESS_GRID_BIN = fakeGrid(join(runtimeDir, 'grid-dev-build'))+ expect(gridCliPresence()).toBe('path')})it('is `missing` when there is nothing to run at all', async () => {diff --git a/cli/src/lib/gridExec.ts b/cli/src/lib/gridExec.tsindex 9dbceeeb9..46fc19380 100644--- a/cli/src/lib/gridExec.ts+++ b/cli/src/lib/gridExec.ts@@ -94,15 +94,15 @@ function capped(sofar: string, chunk: Buffer): string {}/**- * The `grid` this daemon should run.+ * The managed grid — the runtime `current-grid` names — or null when there is none this daemon+ * would trust.** Containment-checked exactly like `nodeRuntime.managedNodePath`: a pointer file is only trusted* when it names something INSIDE the runtime directory we own, so a corrupted or hostile pointer- * cannot turn this into "run any executable on the box".+ * cannot turn this into "run any executable on the box". `runtimeInstall.ts` writes the pointer and+ * asks this to learn what is already laid down.*/-export function gridBinaryPath(processEnv: NodeJS.ProcessEnv = process.env): string {- const override = processEnv.HARNESS_GRID_BIN?.trim()- if (override) return override+export function managedGridPath(): string | null {try {const recorded = readFileSync(join(env.ADAPTER_RUNTIME_DIR, 'current-grid'), 'utf-8').trim()if (recorded && recorded.startsWith(env.ADAPTER_RUNTIME_DIR + sep)) {@@ -110,9 +110,16 @@ export function gridBinaryPath(processEnv: NodeJS.ProcessEnv = process.env): strreturn recorded}} catch {- // absent, unreadable, or not executable → fall through to PATH+ // absent, unreadable, or not executable → there is no managed grid}- return GRID_BINARY+ return null+}++/** The `grid` this daemon should run: the override, the managed runtime, or the name on PATH. */+export function gridBinaryPath(processEnv: NodeJS.ProcessEnv = process.env): string {+ const override = processEnv.HARNESS_GRID_BIN?.trim()+ if (override) return override+ return managedGridPath() ?? GRID_BINARY}/** Is there a `grid` to run at all? Asked by reading rather than by spawning, so a missing binary is@@ -135,6 +142,9 @@ export type GridCliPresence = 'managed' | 'path' | 'missing'export function gridCliPresence(processEnv: NodeJS.ProcessEnv = process.env): GridCliPresence {const binary = gridBinaryPath(processEnv)if (!binaryOnPath(binary, processEnv)) return 'missing'+ // An override is the developer's wherever it lives — under the runtime dir included. Only what the+ // pointer names is the pin.+ if (processEnv.HARNESS_GRID_BIN?.trim()) return 'path'return binary.startsWith(env.ADAPTER_RUNTIME_DIR + sep) ? 'managed' : 'path'}diff --git a/cli/src/lib/runtimeInstall.spec.ts b/cli/src/lib/runtimeInstall.spec.tsindex 486e8fe85..60d5c51f8 100644--- a/cli/src/lib/runtimeInstall.spec.ts+++ b/cli/src/lib/runtimeInstall.spec.ts@@ -1,8 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { execFileSync } from 'node:child_process'import { createHash } from 'node:crypto'-import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'-import { join } from 'node:path'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'import { tmpdir } from 'node:os'let root = ''@@ -16,20 +16,50 @@ async function load() {process.env.HARNESS_BIN_DIR = binDirprocess.env.ADAPTER_CLI_DIR = cliDirprocess.env.ADAPTER_RUNTIME_METADATA_URL = 'https://example.test/runtime/metadata.json'+ process.env.ADAPTER_GRID_RUNTIME_METADATA_URL = 'https://example.test/runtime/grid/metadata.json'+ delete process.env.HARNESS_GRID_BINreturn import('./runtimeInstall.js')}-/** A real gzipped tarball laid out the way nodejs.org ships one, with a runnable `bin/node`. */-function buildArchive(version: string, key: string): { bytes: Buffer; root: string } {- const archiveRoot = `node-${version}-${key}`- const source = join(root, 'src')+/** A real gzipped tarball laid out the way every managed runtime ships — `<name>-<version>-<key>/bin/<name>`+ * (nodejs.org's own shape, which tmux and grid copy) — with a runnable binary inside. */+function buildArchive(version: string, key: string, name: string = 'node'): { bytes: Buffer; root: string } {+ const archiveRoot = `${name}-${version}-${key}`+ const source = join(root, 'src', archiveRoot)+ rmSync(source, { recursive: true, force: true })mkdirSync(join(source, archiveRoot, 'bin'), { recursive: true })- writeFileSync(join(source, archiveRoot, 'bin', 'node'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })+ writeFileSync(join(source, archiveRoot, 'bin', name), '#!/bin/sh\nexit 0\n', { mode: 0o755 })const archive = join(root, `${archiveRoot}.tar.gz`)execFileSync('/usr/bin/tar', ['-czf', archive, '-C', source, archiveRoot])return { bytes: readFileSync(archive), root: archiveRoot }}+/** A manifest of the shape every managed runtime publishes: `{ <name>: { <platform>: entry } }`. */+function manifestFor(name: string, key: string, version: string, bytes: Buffer, root: string, overrides: Record<string, unknown> = {}): unknown {+ return {+ [name]: {+ [key]: {+ version,+ url: `https://example.test/runtime/${name}/${root}.tar.gz`,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ size: bytes.length,+ archiveRoot: root,+ ...overrides,+ },+ },+ }+}++/** A grid already laid down under the runtime dir, the way an earlier ensure leaves it. */+function installedGrid(version: string, key: string, current: boolean): string {+ const dir = join(runtimeDir, `grid-${version}-${key}`, 'bin')+ mkdirSync(dir, { recursive: true })+ const bin = join(dir, 'grid')+ writeFileSync(bin, '#!/bin/sh\nexit 0\n', { mode: 0o755 })+ if (current) writeFileSync(join(runtimeDir, 'current-grid'), `${bin}\n`)+ return bin+}+function currentPlatformKey(): string {const os = process.platform === 'darwin' ? 'darwin' : 'linux'return `${os}-${process.arch === 'arm64' ? 'arm64' : 'x64'}`@@ -63,7 +93,7 @@ describe('ensureManagedRuntime', () => {afterEach(() => {vi.unstubAllGlobals()rmSync(root, { recursive: true, force: true })- for (const key of ['ADAPTER_RUNTIME_DIR', 'HARNESS_BIN_DIR', 'ADAPTER_CLI_DIR', 'ADAPTER_RUNTIME_METADATA_URL']) {+ for (const key of ['ADAPTER_RUNTIME_DIR', 'HARNESS_BIN_DIR', 'ADAPTER_CLI_DIR', 'ADAPTER_RUNTIME_METADATA_URL', 'ADAPTER_GRID_RUNTIME_METADATA_URL', 'HARNESS_GRID_BIN']) {delete process.env[key]}})@@ -161,6 +191,152 @@ describe('ensureManagedRuntime', () => {})})+/**+ * The managed grid follows the PIN, where the managed Node stops at "one is installed": the harness+ * manifest names the grid version this daemon can drive, and a pin that moved must reach a machine+ * that already has an older one. Everything else — the archive shape, the staging, the pointer —+ * is the runtime convention Node and tmux already use.+ */+describe('ensureManagedGrid', () => {+ const key = currentPlatformKey()++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'harness-grid-install-'))+ runtimeDir = join(root, '.harness', 'runtime')+ binDir = join(root, '.local', 'bin')+ cliDir = join(root, '.harness', 'cli')+ for (const dir of [runtimeDir, binDir, cliDir]) mkdirSync(dir, { recursive: true })+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ // 0555 directories cannot be emptied as they are; give them back before the sweep.+ for (const entry of readdirSync(runtimeDir)) {+ try { chmodSync(join(runtimeDir, entry, 'bin'), 0o755) } catch { /* not a runtime dir */ }+ }+ rmSync(root, { recursive: true, force: true })+ for (const key of ['ADAPTER_RUNTIME_DIR', 'HARNESS_BIN_DIR', 'ADAPTER_CLI_DIR', 'ADAPTER_RUNTIME_METADATA_URL', 'ADAPTER_GRID_RUNTIME_METADATA_URL', 'HARNESS_GRID_BIN']) {+ delete process.env[key]+ }+ })++ it('downloads, verifies and unpacks the pinned grid from its own manifest, records it, and lays it down read-only', async () => {+ const { bytes, root: archiveRoot } = buildArchive('0.3.47', key, 'grid')+ stubFetch(manifestFor('grid', key, '0.3.47', bytes, archiveRoot), bytes)++ const { ensureManagedGrid } = await load()+ const grid = await ensureManagedGrid()++ expect(grid).toBe(join(runtimeDir, `grid-0.3.47-${key}`, 'bin', 'grid'))+ expect(readFileSync(join(runtimeDir, 'current-grid'), 'utf8').trim()).toBe(grid)+ // `grid update` replaces the binary with os.replace — a rename INTO this directory. A directory+ // it cannot write to is what makes that fail loudly instead of overwriting the pin.+ expect(statSync(grid!).mode & 0o777).toBe(0o555)+ expect(statSync(dirname(grid!)).mode & 0o777).toBe(0o555)+ expect(readdirSync(runtimeDir).filter((n) => n.startsWith('.grid-staging-'))).toEqual([])+ })++ it('fetches only the manifest when the installed grid IS the pin', async () => {+ const installed = installedGrid('0.3.47', key, true)+ const { bytes, root: archiveRoot } = buildArchive('0.3.47', key, 'grid')+ const urls: string[] = []+ stubFetch(manifestFor('grid', key, '0.3.47', bytes, archiveRoot), bytes)+ const served = globalThis.fetch+ vi.stubGlobal('fetch', async (input: string | URL) => { urls.push(String(input)); return served(input) })++ const { ensureManagedGrid } = await load()++ expect(await ensureManagedGrid()).toBe(installed)+ expect(urls).toEqual(['https://example.test/runtime/grid/metadata.json'])+ })++ it('follows a pin that moved: installs the new version, keeps the one it replaces, drops older ones', async () => {+ installedGrid('0.3.45', key, false)+ const previous = installedGrid('0.3.46', key, true)+ const { bytes, root: archiveRoot } = buildArchive('0.3.47', key, 'grid')+ stubFetch(manifestFor('grid', key, '0.3.47', bytes, archiveRoot), bytes)++ const { ensureManagedGrid } = await load()+ const grid = await ensureManagedGrid()++ expect(grid).toBe(join(runtimeDir, `grid-0.3.47-${key}`, 'bin', 'grid'))+ expect(readFileSync(join(runtimeDir, 'current-grid'), 'utf8').trim()).toBe(grid)+ // A pane launched before the move has the OLD directory on its PATH for as long as it lives;+ // deleting it would take `grid` away from an agent mid-conversation. One version back stays.+ expect(existsSync(previous)).toBe(true)+ expect(existsSync(join(runtimeDir, `grid-0.3.45-${key}`))).toBe(false)+ })++ it('tries a pin that does not run on this computer ONCE, and remembers', async () => {+ const installed = installedGrid('0.3.46', key, true)+ const { bytes, root: archiveRoot } = buildArchive('0.3.47', key, 'grid')+ // The archive's grid records every run, then refuses — a wrong-arch build, say.+ const runs = join(root, 'runs')+ const source = join(root, 'src', archiveRoot, archiveRoot, 'bin', 'grid')+ writeFileSync(source, `#!/bin/sh\necho ran >> '${runs}'\nexit 1\n`, { mode: 0o755 })+ execFileSync('/usr/bin/tar', ['-czf', join(root, `${archiveRoot}.tar.gz`), '-C', join(root, 'src', archiveRoot), archiveRoot])+ const rebuilt = readFileSync(join(root, `${archiveRoot}.tar.gz`))+ stubFetch(manifestFor('grid', key, '0.3.47', rebuilt, archiveRoot), rebuilt)+ void bytes++ const { ensureManagedGrid } = await load()++ // The pointer stays on the grid that works, and the one that does not is marked.+ expect(await ensureManagedGrid()).toBe(installed)+ expect(readFileSync(join(runtimeDir, 'current-grid'), 'utf8').trim()).toBe(installed)+ expect(existsSync(join(runtimeDir, `grid-0.3.47-${key}`, '.unrunnable'))).toBe(true)+ // Every daemon start asks again; a start must not pay a download and a hung exec for a pin this+ // computer has already refused. One manifest fetch, no second run.+ expect(await ensureManagedGrid()).toBe(installed)+ expect(readFileSync(runs, 'utf8')).toBe('ran\n')+ })++ it('refuses a manifest that pins a grid older than the floor this daemon can drive', async () => {+ const installed = installedGrid('0.3.47', key, true)+ const { bytes, root: archiveRoot } = buildArchive('0.3.35', key, 'grid')+ stubFetch(manifestFor('grid', key, '0.3.35', bytes, archiveRoot), bytes)++ const { ensureManagedGrid } = await load()++ expect(await ensureManagedGrid()).toBe(installed)+ expect(existsSync(join(runtimeDir, `grid-0.3.35-${key}`))).toBe(false)+ expect(readFileSync(join(runtimeDir, 'current-grid'), 'utf8').trim()).toBe(installed)+ })++ it('leaves a developer\'s HARNESS_GRID_BIN alone: nothing fetched, nothing laid down', async () => {+ const fetchSpy = vi.fn()+ vi.stubGlobal('fetch', fetchSpy)+ const { ensureManagedGrid } = await load()+ process.env.HARNESS_GRID_BIN = '/somewhere/else/grid'++ expect(await ensureManagedGrid()).toBeNull()+ expect(fetchSpy).not.toHaveBeenCalled()+ expect(existsSync(join(runtimeDir, 'current-grid'))).toBe(false)+ })++ it('keeps the grid it has when the manifest is unreachable, and has nothing when it has nothing', async () => {+ vi.stubGlobal('fetch', async () => { throw new Error('ENOTFOUND') })+ const { ensureManagedGrid } = await load()++ await expect(ensureManagedGrid()).resolves.toBeNull()++ const installed = installedGrid('0.3.47', key, true)+ await expect(ensureManagedGrid()).resolves.toBe(installed)+ })++ it('refuses an archive whose bytes do not match the manifest, and keeps the pointer where it was', async () => {+ const installed = installedGrid('0.3.46', key, true)+ const { bytes, root: archiveRoot } = buildArchive('0.3.47', key, 'grid')+ stubFetch(manifestFor('grid', key, '0.3.47', bytes, archiveRoot, { sha256: 'a'.repeat(64) }), bytes)++ const { ensureManagedGrid } = await load()++ expect(await ensureManagedGrid()).toBe(installed)+ expect(readFileSync(join(runtimeDir, 'current-grid'), 'utf8').trim()).toBe(installed)+ expect(existsSync(join(runtimeDir, `grid-0.3.47-${key}`))).toBe(false)+ })+})+describe('ensureLauncher', () => {const NODE = '/opt/harness/runtime/node-v22/bin/node'diff --git a/cli/src/lib/runtimeInstall.ts b/cli/src/lib/runtimeInstall.tsindex 27d2a8d1e..a31725c98 100644--- a/cli/src/lib/runtimeInstall.ts+++ b/cli/src/lib/runtimeInstall.ts@@ -1,8 +1,9 @@import { execFileSync } from 'node:child_process'-import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'-import { join, sep } from 'node:path'+import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { dirname, join, sep } from 'node:path'import { env } from '../config/env.js'+import { gridChildEnv, managedGridPath, meetsVersionFloor } from './gridExec.js'import { managedNodePath } from './nodeRuntime.js'import { downloadVerified } from './selfUpdate.js'@@ -35,19 +36,22 @@ interface RuntimeArtifact {archiveRoot: string}-function artifactFor(document: unknown, key: string): RuntimeArtifact | null {- const node = (document as { node?: Record<string, unknown> } | null)?.node- const raw = node?.[key] as Partial<RuntimeArtifact> | undefined+/** The `<name>` → `<platform>` → entry document every managed runtime publishes, read for one runtime. */+function artifactFor(document: unknown, name: string, key: string): RuntimeArtifact | null {+ const runtime = (document as Record<string, Record<string, unknown> | undefined> | null)?.[name]+ const raw = runtime?.[key] as Partial<RuntimeArtifact> | undefinedif (!raw || typeof raw.version !== 'string' || typeof raw.url !== 'string') return nullif (typeof raw.sha256 !== 'string' || typeof raw.archiveRoot !== 'string') return null- // Refuse a plaintext URL: this archive becomes the interpreter for everything the CLI runs.+ // Refuse a plaintext URL: this archive becomes something the daemon executes.if (!raw.url.startsWith('https://')) return nullreturn { version: raw.version, url: raw.url, sha256: raw.sha256, size: raw.size, archiveRoot: raw.archiveRoot }}-function runs(node: string): boolean {+/** Does `binary --version` answer? `env` and `timeout` for a runtime whose first run is slow — a+ * onefile grid unpacks itself the first time, and must not be told to update itself while it does. */+function runs(binary: string, timeout: number = 15_000, childEnv?: NodeJS.ProcessEnv): boolean {try {- execFileSync(node, ['--version'], { timeout: 15_000, stdio: 'ignore' })+ execFileSync(binary, ['--version'], { timeout, stdio: 'ignore', ...(childEnv ? { env: childEnv } : {}) })return true} catch {return false@@ -55,62 +59,193 @@ function runs(node: string): boolean {}/**- * The managed Node, installing it when this computer has not got one. Returns its path, or null when- * no runtime could be provisioned — callers keep whatever interpreter they already have.- *- * Idempotent and cheap once installed: [managedNodePath] returning a path under the runtime directory- * means the work is already done, and nothing is fetched.+ * One managed runtime, as this module lays it down. Node and grid differ in four things and share+ * everything else: the archive shape (`<name>-<version>-<key>/bin/<name>`), the staging, the rename+ * race, the pointer file — the convention nodejs.org's tarballs set and tmux and grid copy.*/-export async function ensureManagedRuntime(log: (message: string) => void = () => {}): Promise<string | null> {- const existing = managedNodePath()- if (existing.startsWith(env.ADAPTER_RUNTIME_DIR + sep)) return existing+interface ManagedArchive {+ /** The manifest's top-level key and the runtime's name in every path. */+ name: 'node' | 'grid'+ /** How the runtime is named to a person. */+ label: string+ manifestUrl: string+ /** The executable, relative to the archive root. */+ binary: string+ /** What this daemon already resolved to under the runtime dir, or null when nothing is there. */+ installed: () => string | null+ /**+ * Whether an installed runtime that is not the manifest's version is replaced. Node stops at "one+ * is installed" — which version is the installer's business, and a daemon must not swap the+ * interpreter it is running on. The grid follows the PIN: the manifest names the version this build+ * of the CLI drives, and a pin that moved must reach a machine that already has an older one.+ */+ followsPin: boolean+ /** A version the manifest may not go below — this daemon's floor, which a manifest cannot lower. */+ acceptsVersion?: (version: string) => boolean+ /** Does the laid-down binary run on this computer? Asked before the pointer is written. */+ runs: (binary: string) => boolean+ /**+ * Lay the binary and its directory down read-only. For a runtime whose own updater would replace+ * the file in place — `grid update` is an os.replace INTO the directory — a directory it cannot+ * write to is what makes that fail loudly instead of overwriting the pin.+ */+ readOnly?: boolean+ log: (message: string) => void+}+/**+ * Install [spec]'s runtime from its manifest, or move to the version the manifest pins, or leave it+ * be. Returns the binary this daemon should use — which is whatever it already had whenever the+ * manifest, the download or the unpacked binary cannot be trusted — or null when there is nothing.+ *+ * Everything here is best-effort and returns rather than throws: a daemon must not fail to start+ * because a download failed.+ */+async function ensureManagedArchive(spec: ManagedArchive): Promise<string | null> {+ const installed = spec.installed()+ if (installed && !spec.followsPin) return installedconst key = platformKey()- if (!key) return null+ if (!key) return installedtry {- const response = await fetch(env.ADAPTER_RUNTIME_METADATA_URL)- if (!response.ok) return null- const artifact = artifactFor(await response.json(), key)- if (!artifact) return null-- const target = join(env.ADAPTER_RUNTIME_DIR, `node-${artifact.version}-${key}`)- const node = join(target, 'bin', 'node')- if (!existsSync(node)) {- log(`▸ installing the Harness Node runtime (${artifact.version}, ${key})…`)+ const response = await fetch(spec.manifestUrl)+ if (!response.ok) return installed+ const artifact = artifactFor(await response.json(), spec.name, key)+ if (!artifact) return installed+ if (spec.acceptsVersion && !spec.acceptsVersion(artifact.version)) return installed++ const target = join(env.ADAPTER_RUNTIME_DIR, `${spec.name}-${artifact.version}-${key}`)+ const binary = join(target, spec.binary)+ // The pin is what is installed: nothing to fetch, nothing to write.+ if (installed === binary) return installed+ if (!existsSync(binary)) {+ spec.log(`▸ installing the Harness ${spec.label} runtime (${artifact.version}, ${key})…`)// downloadVerified checks the sha256 but not the length, so check it here: a truncated body// that somehow collided would be caught by the hash anyway, but a mismatch here is the cheaper// and clearer failure.const bytes = await downloadVerified(artifact)- if (artifact.size !== undefined && bytes.length !== artifact.size) return null+ if (artifact.size !== undefined && bytes.length !== artifact.size) return installedmkdirSync(env.ADAPTER_RUNTIME_DIR, { recursive: true, mode: 0o700 })- const staging = join(env.ADAPTER_RUNTIME_DIR, `.node-staging-${process.pid}-${Date.now()}`)+ const staging = join(env.ADAPTER_RUNTIME_DIR, `.${spec.name}-staging-${process.pid}-${Date.now()}`)try {mkdirSync(staging, { recursive: true, mode: 0o700 })- const archive = join(staging, 'node.tar.gz')+ const archive = join(staging, `${spec.name}.tar.gz`)writeFileSync(archive, bytes)execFileSync('/usr/bin/tar', ['-xzf', archive, '-C', staging], { timeout: 120_000, stdio: 'ignore' })const unpacked = join(staging, artifact.archiveRoot)- if (!existsSync(join(unpacked, 'bin', 'node'))) return null+ if (!existsSync(join(unpacked, spec.binary))) return installed// Another start may have won the race; theirs is as good as ours.if (!existsSync(target)) renameSync(unpacked, target)} finally {rmSync(staging, { recursive: true, force: true })}}+ // After the rename, never in staging: a read-only directory cannot be emptied, and staging must+ // always be.+ if (spec.readOnly) {+ chmodSync(binary, 0o555)+ chmodSync(dirname(binary), 0o555)+ }- if (!runs(node)) return null+ // A pin this computer could not run is tried ONCE and remembered. A runtime that follows its pin+ // is asked on every daemon start, and without this a wrong-arch or broken build would cost a+ // hung exec each time until the manifest moved. A new pin is a new directory, and starts clean.+ const unrunnable = join(target, '.unrunnable')+ if (spec.followsPin && existsSync(unrunnable)) return installed+ if (!spec.runs(binary)) {+ if (spec.followsPin) {+ try { writeFileSync(unrunnable, `${new Date().toISOString()}\n`, { mode: 0o600 }) } catch { /* the retry is the cost */ }+ }+ return installed+ }// Written last, and only once the binary has answered: Desktop Harness and the hook installer// both read this file to decide what to execute, so it must never name something that cannot run.- writeFileSync(join(env.ADAPTER_RUNTIME_DIR, 'current-node'), `${node}\n`, { mode: 0o600 })- log(` ✓ Node runtime ready → ${target}`)- return node+ writeFileSync(join(env.ADAPTER_RUNTIME_DIR, `current-${spec.name}`), `${binary}\n`, { mode: 0o600 })+ spec.log(` ✓ ${spec.label} runtime ready → ${target}`)+ if (spec.followsPin) retireSuperseded(spec.name, key, target, installed)+ return binary+ } catch {+ return installed+ }+}++/**+ * Every `<name>-*-<key>` under the runtime dir except the one just installed and the one it+ * replaced.+ *+ * One version back stays on purpose. A pane launched before the pin moved has the OLD directory on+ * its PATH for as long as it lives (`gridPanePrelude` in engineLaunch.ts), and deleting it would+ * take `grid` away from an agent mid-conversation. Two versions of a 20 MB runtime is the price;+ * the third is not paid.+ */+function retireSuperseded(name: string, key: string, target: string, previous: string | null): void {+ const keep = new Set([target, previous ? dirname(dirname(previous)) : ''])+ try {+ for (const entry of readdirSync(env.ADAPTER_RUNTIME_DIR)) {+ if (!entry.startsWith(`${name}-`) || !entry.endsWith(`-${key}`)) continue+ const dir = join(env.ADAPTER_RUNTIME_DIR, entry)+ if (keep.has(dir)) continue+ // A read-only `bin/` cannot be emptied as it is; give it back before the sweep.+ try { chmodSync(join(dir, 'bin'), 0o755) } catch { /* not laid down read-only */ }+ rmSync(dir, { recursive: true, force: true })+ }} catch {- return null+ // Disk housekeeping only; the runtime that matters is already in place and recorded.}}+/**+ * The managed Node, installing it when this computer has not got one. Returns its path, or null when+ * no runtime could be provisioned — callers keep whatever interpreter they already have.+ *+ * Idempotent and cheap once installed: [managedNodePath] returning a path under the runtime directory+ * means the work is already done, and nothing is fetched.+ */+export async function ensureManagedRuntime(log: (message: string) => void = () => {}): Promise<string | null> {+ return ensureManagedArchive({+ name: 'node',+ label: 'Node',+ manifestUrl: env.ADAPTER_RUNTIME_METADATA_URL,+ binary: join('bin', 'node'),+ installed: () => {+ const existing = managedNodePath()+ return existing.startsWith(env.ADAPTER_RUNTIME_DIR + sep) ? existing : null+ },+ followsPin: false,+ runs: (node) => runs(node),+ log,+ })+}++/**+ * The managed grid at the version the harness manifest PINS — installing it, moving to it, or+ * leaving it be. Returns its path, or null when there is none: callers fall back to whatever `grid`+ * PATH has (`gridBinaryPath`), and an agent's pane is told when it has none (`gridCliPresence`).+ *+ * Best-effort like the Node runtime: a daemon must not fail to start because a download failed. Asked+ * on every daemon start rather than on `--repair` only, because the pin is expected to MOVE and a+ * machine installed last month has to notice. Never below [GRID_VERSION_FLOOR]: the floor is this+ * daemon's, and a manifest cannot lower it. A developer's HARNESS_GRID_BIN is left alone entirely —+ * it outranks the pin at resolution, so a pin laid down under it would be work nobody asked for.+ */+export async function ensureManagedGrid(log: (message: string) => void = () => {}): Promise<string | null> {+ if (process.env.HARNESS_GRID_BIN?.trim()) return null+ return ensureManagedArchive({+ name: 'grid',+ label: 'grid',+ manifestUrl: env.ADAPTER_GRID_RUNTIME_METADATA_URL,+ binary: join('bin', 'grid'),+ installed: managedGridPath,+ followsPin: true,+ acceptsVersion: (version) => meetsVersionFloor(version),+ // A minute, not fifteen seconds: a onefile grid unpacks itself the first time it runs.+ runs: (grid) => runs(grid, 60_000, gridChildEnv()),+ readOnly: true,+ log,+ })+}+/** The trailing `exec …` line, which is the only line any launcher we ship varies. */const EXEC_LINE = /^exec .*$/mdiff --git a/cli/src/scripts/install.spec.ts b/cli/src/scripts/install.spec.tsindex d0a715b86..3a69857d6 100644--- a/cli/src/scripts/install.spec.ts+++ b/cli/src/scripts/install.spec.ts@@ -1,6 +1,6 @@import { spawnSync } from "child_process";import { join } from "path";-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, writeFileSync } from "fs";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "fs";import { tmpdir } from "os";import { describe, expect, it } from "vitest";@@ -652,6 +652,145 @@ describe("scripts/install.sh command contract", () => {}});+ // ── the managed grid ──────────────────────────────────────────────────────────────────────────+ //+ // The grid CLI the release PINS, laid down beside Node and tmux — but unlike them, optional: the+ // harness works without it, the daemon follows the pin on every start, so this step may fail and+ // the install still succeeds. And never linked into ~/.local/bin: that path is grid's own+ // installer's (uv's, on a Mac); the daemon puts the managed grid on an agent pane's PATH itself.++ // The helpers plus the grid step alone, as one runnable unit.+ const gridStepOf = (source: string) =>+ source.slice(source.indexOf('METADATA_URL="${HARNESS_METADATA_URL'), source.indexOf("# 1. Host requirements")) ++ source.slice(source.indexOf("# 3b. The managed grid"), source.indexOf("# 4. Ensure ~/.local/bin"));++ it("installs the managed grid after the CLI and before PATH, as a step the install can survive", () => {+ const source = readFileSync(installer, "utf8");+ const cliStep = source.indexOf("# 3. Fetch manifest");+ const gridStep = source.indexOf("# 3b. The managed grid");+ const pathStep = source.indexOf("# 4. Ensure ~/.local/bin");+ expect(cliStep).toBeGreaterThan(0);+ expect(gridStep).toBeGreaterThan(cliStep);+ expect(pathStep).toBeGreaterThan(gridStep);+ expect(source).toContain('GRID_METADATA_URL="${HARNESS_GRID_METADATA_URL:-');+ expect(source).toContain('CURRENT_GRID_FILE="$RUNTIME_DIR/current-grid"');+ // Optional, by construction: the call is guarded, and the function returns instead of exiting.+ expect(source.slice(gridStep, pathStep)).toMatch(/install_managed_grid \|\|/);+ const fn = source.slice(source.indexOf("install_managed_grid() {"), source.indexOf("# 1. Host requirements"));+ expect(fn).not.toContain("exit ");+ expect(fn).not.toContain("ln -s");+ });++ const gridFixture = (scratch: string, tamperSha = false) => {+ const home = join(scratch, "home");+ const root = "grid-9.9-darwin-arm64";+ const stage = join(scratch, "stage", root, "bin");+ mkdirSync(stage, { recursive: true });+ writeCommand(stage, "grid", ["printf 'grid 9.9\\n'"]);+ const archive = join(scratch, `${root}.tar.gz`);+ spawnSync("tar", ["-czf", archive, "-C", join(scratch, "stage"), root]);+ const sha = spawnSync("shasum", ["-a", "256", archive], { encoding: "utf8" }).stdout.split(" ")[0];+ writeFileSync(join(scratch, "manifest.json"), JSON.stringify({+ grid: {+ "darwin-arm64": {+ version: "9.9",+ url: "https://cdn.example/grid.tar.gz",+ sha256: tamperSha ? "0".repeat(64) : sha,+ size: 1,+ archiveRoot: root,+ },+ },+ }, null, 2));+ writeCommand(scratch, "curl", [+ `printf '%s\\n' "$*" >> '${join(scratch, "curl-invocations")}'`,+ `case "$*" in *"-o "*) cp '${archive}' "$4" ;; *) cat '${join(scratch, "manifest.json")}' ;; esac`,+ ]);+ writeCommand(scratch, "uname", [`if [ "$1" = "-m" ]; then printf 'arm64\\n'; else printf 'Darwin\\n'; fi`]);+ mkdirSync(home, { recursive: true });+ return { home, root };+ };++ const runGridStep = (scratch: string, home: string, mode: string) =>+ spawnSync("/bin/sh", ["-c", gridStepOf(readFileSync(installer, "utf8"))], {+ encoding: "utf8",+ env: {+ ...process.env,+ HOME: home,+ INSTALL_MODE: mode,+ PATH: `${scratch}:/usr/bin:/bin`,+ HARNESS_GRID_METADATA_URL: "https://cdn.example/manifest.json",+ },+ });++ it("downloads, verifies and records the managed grid read-only, and links nothing", () => {+ const scratch = mkdtempSync(join(tmpdir(), "harness-grid-managed-"));+ try {+ const { home, root } = gridFixture(scratch);+ const result = runGridStep(scratch, home, "standalone");++ expect(result.status).toBe(0);+ expect(result.stdout).toContain("downloading grid 9.9 (darwin-arm64)");+ expect(result.stdout).toContain(`installed grid 9.9 → ${join(home, ".harness", "runtime", root)}`);+ const binary = join(home, ".harness", "runtime", root, "bin", "grid");+ expect(readFileSync(join(home, ".harness", "runtime", "current-grid"), "utf8").trim()).toBe(binary);+ // `grid update` is a rename INTO bin/; a bin/ it cannot write to is what makes that fail loudly.+ expect(statSync(binary).mode & 0o777).toBe(0o555);+ expect(statSync(join(home, ".harness", "runtime", root, "bin")).mode & 0o777).toBe(0o555);+ expect(existsSync(join(home, ".local", "bin", "grid"))).toBe(false);+ expect(readFileSync(join(scratch, "curl-invocations"), "utf8")).toContain("https://cdn.example/manifest.json");+ } finally {+ // The read-only bin/ the step lays down cannot be emptied as it is; give it back before the sweep.+ try { chmodSync(join(scratch, "home", ".harness", "runtime", "grid-9.9-darwin-arm64", "bin"), 0o755); } catch { /* never laid down */ }+ rmSync(scratch, { recursive: true, force: true });+ }+ }, 20_000);++ it("survives a grid whose checksum does not match: says so, records nothing, and the install goes on", () => {+ const scratch = mkdtempSync(join(tmpdir(), "harness-grid-tampered-"));+ try {+ const { home } = gridFixture(scratch, true);+ const result = runGridStep(scratch, home, "standalone");++ expect(result.status).toBe(0);+ expect(result.stderr).toContain("checksum verification");+ expect(result.stdout).toContain("fetched by the daemon");+ expect(existsSync(join(home, ".harness", "runtime", "current-grid"))).toBe(false);+ expect(readdirSync(join(home, ".harness", "runtime")).filter((n) => n.startsWith(".grid-staging-"))).toEqual([]);+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }+ }, 20_000);++ it("says which platform has no managed grid, fetches nothing, and the install goes on", () => {+ const scratch = mkdtempSync(join(tmpdir(), "harness-grid-platform-"));+ try {+ const { home } = gridFixture(scratch);+ writeCommand(scratch, "uname", [`if [ "$1" = "-m" ]; then printf 'riscv64\\n'; else printf 'Linux\\n'; fi`]);+ const result = runGridStep(scratch, home, "standalone");++ expect(result.status).toBe(0);+ expect(result.stderr).toContain("No managed grid is published for Linux/riscv64");+ expect(existsSync(join(scratch, "curl-invocations"))).toBe(false);+ expect(existsSync(join(home, ".harness", "runtime", "current-grid"))).toBe(false);+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }+ }, 20_000);++ it("fetches no grid in host mode, which installs no CLI either", () => {+ const scratch = mkdtempSync(join(tmpdir(), "harness-grid-host-"));+ try {+ const { home } = gridFixture(scratch);+ const result = runGridStep(scratch, home, "host");++ expect(result.status).toBe(0);+ expect(existsSync(join(scratch, "curl-invocations"))).toBe(false);+ expect(existsSync(join(home, ".harness", "runtime", "current-grid"))).toBe(false);+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }+ }, 20_000);+it("desktop mode skips all host package and tmux work", () => {const source = readFileSync(installer, "utf8");const hostSetup = hostSetupOf(source);