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.

Add Grid Harness for managing model fleets with live telemetry

Dee3623073e4906
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index bd782b808..f9d3299fd 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -28,6 +28,7 @@ import { ENGINES, type AgentEngine } from './engines/types.js'
import { listDir } from './lib/fsBrowse.js'
import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'
import { gridCliPresence } from './lib/gridExec.js'
+import { GridFleetRpc, GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS, parseGridFleetRequest } from './lib/gridFleetRpc.js'
import { gridCapableEngines, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
import { listGridModels, resolveGridTarget } from './lib/gridModels.js'
import { deriveHarnessGridName } from './lib/gridDerive.js'
@@ -81,7 +82,8 @@ import {
TerminalHopDirection,
type TerminalBinaryClear,
} from './lib/terminalBinary.js'
-import { b64d, fingerprint, ENCRYPTED_RPC_RESULT_TYPES, isEncryptedDownType, isWrapped } from './lib/e2ee/core.js'
+import { b64d, fingerprint, isWrapped } from './lib/e2ee/core.js'
+import { encryptDownFrame, encryptRpcResult } from './lib/e2ee/applicationFrames.js'
import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'
import { shouldReplayCommander } from './lib/commanderReplay.js'
import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from './lib/runtimeProfileController.js'
@@ -300,6 +302,7 @@ async function enrichSubagentStats(events: SessionEvent[], transcriptPath: strin
}
export class BackendSocket {
+ private readonly gridFleet = new GridFleetRpc()
private ws: WebSocket | null = null
private connecting = false
/** A 401 on the upgrade is being answered with a token refresh; that refresh owns the next connect. */
@@ -1105,12 +1108,12 @@ export class BackendSocket {
private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {
const resultType = `${type}_result`
// Before the E2EE wrap: an RPC reply is only readable here.
- if (env.LOG_FRAMES && type !== 'agent_read_file' && type !== 'project_preview') logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
+ if (env.LOG_FRAMES && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview') logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
if (this.localClients.has(connId)) {
this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })
return
}
- if (connId && this.e2ee.hasSession(connId) && ENCRYPTED_RPC_RESULT_TYPES.has(resultType)) {
+ if (connId && this.e2ee.hasSession(connId) && encryptRpcResult(resultType)) {
let replyPayload = payload
if (resultType === 'agent_recent_result') {
const trim = fitRecentReplyPayloadForDevice(
@@ -1133,7 +1136,7 @@ export class BackendSocket {
// adapter plaintext. A real client gets a targeted error; the legacy backend nodeRequest awaiter
// (`connId === ''`) gets a broadcast error with the same requestId so it fails closed without data.
//
- if (ENCRYPTED_RPC_RESULT_TYPES.has(resultType)) {
+ if (encryptRpcResult(resultType)) {
const errorFrame = { type: resultType, payload: { requestId, error: 'E2EE_REQUIRED' } }
if (connId) this.sendTo(connId, errorFrame)
else this.send(errorFrame)
@@ -1161,7 +1164,7 @@ export class BackendSocket {
}
// Client→adapter encrypted frames: chat messages plus trusted web control actions. Plaintext
// passes through for legacy/device transition paths; undecryptable ciphertext is dropped.
- if (!local && isEncryptedDownType(type)) {
+ if (!local && encryptDownFrame(type)) {
if (type !== 'message' && type !== 'question_response' && !isWrapped(frame.payload)) {
const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId
if (requestId !== undefined) this.emitReply(connId, type, requestId, { error: 'E2EE_REQUIRED' })
@@ -1179,7 +1182,7 @@ export class BackendSocket {
// than as an opaque __e2e envelope.
// Terminal frames contain raw keystrokes, paste text and screen bytes after
// unwrap. Never pass them to the frame logger, even in diagnostic mode.
- if (env.LOG_FRAMES && !type.startsWith('terminal_') && type !== 'agent_read_file' && type !== 'project_preview') {
+ if (env.LOG_FRAMES && !type.startsWith('terminal_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview') {
logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)
}
const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)
@@ -1253,6 +1256,21 @@ export class BackendSocket {
try {
switch (type) {
+ case 'grid_fleet_capabilities':
+ reply(type, requestId, { protocol: GRID_FLEET_PROTOCOL, gridCli: gridCliPresence(), maxTimeoutMs: GRID_FLEET_MAX_TIMEOUT_MS, thinkingControl: true })
+ return
+ case 'grid_fleet_run': {
+ const request = parseGridFleetRequest(payload)
+ if (!request || typeof requestId !== 'string') { reply(type, requestId, { error: 'INVALID_GRID_COMMAND' }); return }
+ // Detached: pulls/builds can take minutes. Keep typing, cancellation, and telemetry responsive.
+ void this.gridFleet.run(connId, requestId, request)
+ .then(result => reply(type, requestId, { ...result }))
+ .catch(() => reply(type, requestId, { ok: false, code: 1, error: 'Grid command failed unexpectedly.' }))
+ return
+ }
+ case 'grid_fleet_cancel':
+ reply(type, requestId, { cancelled: typeof payload.commandId === 'string' && this.gridFleet.cancel(connId, payload.commandId) })
+ return
case 'device_e2ee_pair':
await this.e2ee.pairDeviceFromTrustedWeb(connId, payload)
return
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
new file mode 100644
index 000000000..37ed920c9
--- /dev/null
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -0,0 +1,9 @@
+/** Harness-only RPC extensions. The shared, pinned crypto core remains byte-identical across clients.
+ * Both the originating machine relay and receiving daemon use these classifications. Older clients
+ * do not send these frames; older targets answer UNSUPPORTED before any command is attempted. */
+import { ENCRYPTED_RPC_RESULT_TYPES, isEncryptedDownType } from './core.js'
+
+const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'grid_fleet_cancel'])
+const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
+export const encryptDownFrame = (type: string): boolean => isEncryptedDownType(type) || FLEET_REQUESTS.has(type)
+export const encryptRpcResult = (type: string): boolean => ENCRYPTED_RPC_RESULT_TYPES.has(type) || FLEET_RESULTS.has(type)
diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.ts
index 60637721d..335b70ee1 100644
--- a/cli/src/lib/e2ee/relayClient.ts
+++ b/cli/src/lib/e2ee/relayClient.ts
@@ -11,6 +11,7 @@
*/
import { WebSocket } from 'ws'
import * as C from './core.js'
+import { encryptDownFrame } from './applicationFrames.js'
import { deriveTerminalBinaryKey, openTerminalBinary, sealTerminalBinary, type TerminalBinaryClear } from '../terminalBinary.js'
import { pwCpaceGenerator, pwContext, stretchPassword } from './passwordPake.js'
import { ReplayWindow } from './replayWindow.js'
@@ -103,7 +104,7 @@ export class RelaySessionCrypto {
/** Encrypt an outgoing (local app → remote machine) frame if its type requires it. */
wrapOutgoing(frame: Frame): Frame {
const type = frame.type as string | undefined
- if (!type || !this.c2s || !C.isEncryptedDownType(type)) return frame
+ if (!type || !this.c2s || !encryptDownFrame(type)) return frame
const payload = C.wrapPayload(this.c2s, 'p', this.c2sCounter++, type, undefined, frame.payload)
return { ...frame, payload }
}
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index 5f3821246..190377af3 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -130,6 +130,15 @@ describe('remote-password link + relay session crypto (interop with the real E2e
expect(decrypted).not.toBeNull()
expect((decrypted!.payload as Record<string, unknown>).foo).toBe('bar')
+ const gridRequest = { requestId: 'grid-1', args: ['chat', 'private prompt'] }
+ const sealedGrid = crypto.wrapOutgoing({ type: 'grid_fleet_run', payload: gridRequest })
+ expect(sealedGrid.payload).not.toHaveProperty('args')
+ expect(manager.unwrapDown('session-conn', sealedGrid)?.payload).toEqual(gridRequest)
+ const gridResult = { requestId: 'grid-1', stdout: 'private answer', code: 0 }
+ const sealedResult = manager.wrapTarget('session-conn', 'grid_fleet_run_result', gridResult)!
+ expect(sealedResult.payload).not.toHaveProperty('stdout')
+ expect(crypto.unwrapIncoming(sealedResult)?.payload).toEqual(gridResult)
+
// Creation recovery must take the same encrypted route as creation; its result contains
// the agent's name and working folder. The relay sees neither the receipt nor those fields.
const checking = { requestId: 'check-1', creationId: 'creation-fixture-001' }
@@ -339,6 +348,57 @@ describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
// A fake AuthSessionManager — RemoteRelayPool only ever calls .accessToken({force}).
const fakeAuth = { accessToken: async () => 'unused-in-this-fake' } as unknown as import('../authSession.js').AuthSessionManager
+ it('isolates concurrent fleet clients from each other and the desktop connection', async () => {
+ const wss = new WebSocketServer({ port: 0 })
+ const sockets = new Map<string, import('ws').WebSocket>()
+ const manager = new E2eeManagerCtor({
+ machineId: MACHINE_ID, isConnected: () => true,
+ sendTo: (id, frame) => sockets.get(id)?.send(JSON.stringify(frame)),
+ })
+ let next = 0
+ wss.on('connection', ws => {
+ const id = `client-${++next}`; sockets.set(id, ws)
+ ws.on('close', () => { sockets.delete(id); manager.dropSession(id) })
+ ws.on('message', raw => {
+ const frame = JSON.parse(raw.toString())
+ if (frame.type === 'machine_select') ws.send(JSON.stringify({ type: 'connected', payload: { machineId: MACHINE_ID } }))
+ else if (frame.type.startsWith('e2e_')) manager.handleFrame(id, frame)
+ else if (frame.type === 'grid_fleet_run') {
+ expect(frame.payload).not.toHaveProperty('args')
+ const clear = manager.unwrapDown(id, frame)
+ ws.send(JSON.stringify(manager.wrapTarget(id, 'grid_fleet_run_result', clear!.payload as Record<string, unknown>)))
+ }
+ })
+ })
+ const base = `ws://127.0.0.1:${(wss.address() as AddressInfo).port}`
+ const identity = C.newIdentity()
+ await manager.setRemotePassword(REMOTE_PASSWORD)
+ const claim = await connectWithPassword({ targetMachineId: MACHINE_ID, password: REMOTE_PASSWORD, selfIdentity: identity, accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: 5000 })
+ expect(claim.ok).toBe(true)
+ if (!claim.ok) throw new Error('pairing failed')
+ const peers = new MachinePeerStore(); peers.pin(MACHINE_ID, C.b64e(claim.peerPub), 'test')
+ const pool = new RemoteRelayPool(fakeAuth, base, identity, peers)
+ const inboxes: Frame[][] = [[], [], []]
+ const select = { type: 'machine_select', payload: { machineId: MACHINE_ID } }
+ const sink = (i: number) => ({ sendFrame: (f: Frame) => { inboxes[i].push(f); return true }, sendBinary: () => true })
+ const desktop = await pool.acquire(MACHINE_ID, 'prod', select, sink(0), () => {})
+ const a = await pool.acquireIsolated(MACHINE_ID, 'prod', select, sink(1), () => {})
+ const b = await pool.acquireIsolated(MACHINE_ID, 'prod', select, sink(2), () => {})
+ try {
+ await Promise.all([desktop, a, b].map((s, i) => s.send({ type: 'grid_fleet_run', payload: { requestId: `r-${i}`, args: [`model-${i}`] } })))
+ await new Promise(resolve => setTimeout(resolve, 100))
+ inboxes.forEach((inbox, i) => expect(inbox.filter(f => f.type === 'grid_fleet_run_result').map(f => f.payload)).toEqual([{ requestId: `r-${i}`, args: [`model-${i}`] }]))
+ a.detach()
+ await desktop.send({ type: 'grid_fleet_run', payload: { requestId: 'still-connected', args: ['version'] } })
+ await new Promise(resolve => setTimeout(resolve, 100))
+ expect(inboxes[0].at(-1)?.payload).toMatchObject({ requestId: 'still-connected' })
+ } finally {
+ a.detach(); b.detach(); pool.invalidate(MACHINE_ID)
+ for (const ws of wss.clients) ws.terminate()
+ await new Promise<void>(resolve => wss.close(() => resolve()))
+ }
+ }, PW_SCRYPT_TEST_TIMEOUT_MS)
+
it('e2e_denied during the handshake unlinks the peer and surfaces NO_PEER_LINK', async () => {
const wss = new WebSocketServer({ port: 0 })
wss.on('connection', (ws) => {
diff --git a/cli/src/lib/gridFleetRpc.spec.ts b/cli/src/lib/gridFleetRpc.spec.ts
new file mode 100644
index 000000000..fdaeddf1e
--- /dev/null
+++ b/cli/src/lib/gridFleetRpc.spec.ts
@@ -0,0 +1,62 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { GridFleetRpc, GridOutputCapture, parseGridFleetRequest } from './gridFleetRpc.js'
+import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'
+
+const directories: string[] = []
+afterEach(() => { for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true }) })
+function fixture(body: string) {
+ const dir = mkdtempSync(join(tmpdir(), 'grid-fleet-rpc-')); directories.push(dir)
+ const file = join(dir,'grid'); writeFileSync(file,`#!${process.execPath}\n${body}\n`); chmodSync(file,0o700)
+ return new GridFleetRpc({ ...process.env, HARNESS_GRID_BIN: file })
+}
+describe('paired Grid fleet commands', () => {
+ it('validates bounded argv and runtime, rejecting NULs and command strings', () => {
+ expect(parseGridFleetRequest({args:['--remote','chat','a prompt\nwith lines']})).toEqual({args:['--remote','chat','a prompt\nwith lines'],timeoutMs:30000})
+ for (const payload of [{args:'grid ls'},{args:[]},{args:['x\0y']},{args:['x'.repeat(17000)]},{args:['ls'],timeoutMs:1_800_001},{args:['ls'],timeoutMs:-1}]) expect(parseGridFleetRequest(payload)).toBeNull()
+ })
+ it('preserves argument boundaries and exit status without shell interpretation', async () => {
+ const rpc=fixture('console.log(JSON.stringify(process.argv.slice(2)));process.exit(7)')
+ const args=['--local','chat','$(echo secret); `pwd`',"single'quote",'line\nline']
+ const result=await rpc.run('owner','one',{args,timeoutMs:3000})
+ expect(result.code).toBe(7);expect(result.ok).toBe(false);expect(JSON.parse(result.stdout)).toEqual(args)
+ })
+ it('keeps timeout failures even when a child handles SIGTERM with exit zero', async () => {
+ const rpc=fixture("process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)")
+ const result=await rpc.run('owner','timeout',{args:['join'],timeoutMs:200})
+ expect(result).toMatchObject({ok:false,code:124});expect(result.error).toContain('timed out')
+ })
+ it('applies explicit thinking to this child only, without allowing arbitrary environment input', async () => {
+ expect(parseGridFleetRequest({args:['join'],thinking:'off'})).toBeNull()
+ const rpc=fixture("console.log(process.env.LLAMA_ARG_CHAT_TEMPLATE_KWARGS || 'unset')")
+ expect((await rpc.run('owner','off',{args:['join'],timeoutMs:3000,thinking:false})).stdout.trim()).toBe('{"enable_thinking":false}')
+ expect((await rpc.run('owner','default',{args:['join'],timeoutMs:3000})).stdout.trim()).toBe('unset')
+ })
+ it('owns cancellation by connection and refuses duplicate live requests', async () => {
+ const rpc=fixture('setInterval(()=>{},1000)')
+ const pending=rpc.run('owner','job',{args:['pull'],timeoutMs:5000})
+ expect(rpc.cancel('stranger','job')).toBe(false)
+ expect((await rpc.run('owner','job',{args:['pull'],timeoutMs:5000})).error).toContain('already running')
+ expect(rpc.cancel('owner','job')).toBe(true)
+ expect(await pending).toMatchObject({ok:false,code:124})
+ })
+ it('fails loud on oversized output instead of returning a truncated successful JSON result', async () => {
+ const result=await fixture("process.stdout.write('x'.repeat(600000));setInterval(()=>{},1000)").run('owner','large',{args:['models'],timeoutMs:3000})
+ expect(result).toMatchObject({ok:false,code:124});expect(result.error).toContain('512 KiB')
+ })
+ it('keeps download progress bounded while retaining completed diagnostics', async () => {
+ const output=new GridOutputCapture()
+ output.append('Downloading model\n\rfirst');output.append('\r');output.append('last\r');output.append('\nDone\n')
+ expect(output.text).toBe('Downloading model\nlast\nDone\n')
+ const result=await fixture("for(let i=0;i<50000;i++)process.stderr.write('\\r['+i+'/50000] downloading model');console.log('saved model.gguf')").run('owner','progress',{args:['pull'],timeoutMs:10000})
+ expect(result).toMatchObject({ok:true,code:0});expect(result.stdout).toBe('saved model.gguf\n')
+ expect(result.stderr).toBe('[49999/50000] downloading model')
+ })
+ it('requires pairwise encryption in both directions for every fleet RPC', () => {
+ for(const type of ['grid_fleet_capabilities','grid_fleet_run','grid_fleet_cancel']) {
+ expect(encryptDownFrame(type)).toBe(true);expect(encryptRpcResult(`${type}_result`)).toBe(true)
+ }
+ })
+})
diff --git a/cli/src/lib/gridFleetRpc.ts b/cli/src/lib/gridFleetRpc.ts
new file mode 100644
index 000000000..f8555f50c
--- /dev/null
+++ b/cli/src/lib/gridFleetRpc.ts
@@ -0,0 +1,93 @@
+/** Grid's complete argv API, carried over the existing paired-machine connection. No shell. */
+import { spawn } from 'node:child_process'
+import { gridBinaryPath, gridChildEnv } from './gridExec.js'
+
+export const GRID_FLEET_PROTOCOL = 1
+export const GRID_FLEET_MAX_TIMEOUT_MS = 30 * 60_000
+const MAX_OUTPUT = 512 * 1024
+export interface GridFleetRequest { args: string[]; timeoutMs: number; thinking?: boolean }
+export interface GridFleetResult { ok: boolean; code: number; stdout: string; stderr: string; error: string | null }
+
+/** Grid redraws download progress for every MiB, even on pipes. Retain the current terminal line
+ * instead of counting those redraws as permanent output; completed diagnostic lines stay intact. */
+export class GridOutputCapture {
+ private completed = ''
+ private line = ''
+ private rewind = false
+ append(chunk: string): void {
+ for (const part of chunk.split(/([\r\n])/)) {
+ if (!part) continue
+ if (part === '\r') this.rewind = true
+ else if (part === '\n') { this.completed += this.line + '\n'; this.line = ''; this.rewind = false }
+ else { if (this.rewind) this.line = ''; this.rewind = false; this.line += part }
+ }
+ }
+ get text(): string { return this.completed + this.line }
+}
+
+export function parseGridFleetRequest(payload: Record<string, unknown>): GridFleetRequest | null {
+ const { args, timeoutMs = 30_000, thinking } = payload
+ if (!Array.isArray(args) || !args.length || args.length > 256
+ || args.some(a => typeof a !== 'string' || a.includes('\0') || a.length > 16_384)
+ || args.reduce((n, a) => n + a.length, 0) > 128 * 1024
+ || !Number.isInteger(timeoutMs) || (timeoutMs as number) < 100 || (timeoutMs as number) > GRID_FLEET_MAX_TIMEOUT_MS
+ || (thinking !== undefined && typeof thinking !== 'boolean')) return null
+ return { args: args as string[], timeoutMs: timeoutMs as number, ...(thinking === undefined ? {} : { thinking: thinking as boolean }) }
+}
+
+/** Bounded, connection-owned jobs. Dropping a connection does not repeat or silently roll back a deployment. */
+export class GridFleetRpc {
+ private readonly jobs = new Map<string, AbortController>()
+ constructor(private readonly processEnv: NodeJS.ProcessEnv = process.env) {}
+
+ cancel(owner: string, id: string): boolean {
+ const job = this.jobs.get(JSON.stringify([owner, id]))
+ job?.abort()
+ return !!job
+ }
+
+ async run(owner: string, id: string, request: GridFleetRequest): Promise<GridFleetResult> {
+ const fail = (code: number, error: string): GridFleetResult => ({ ok: false, code, stdout: '', stderr: '', error })
+ if (!owner || !/^[a-zA-Z0-9_-]{1,100}$/.test(id)) return fail(2, 'Invalid Grid request identity.')
+ const key = JSON.stringify([owner, id])
+ if (this.jobs.has(key)) return fail(2, 'This Grid command is already running; it was not started again.')
+ if (this.jobs.size >= 8) return fail(75, 'This machine is already running eight Grid commands. Retry when one finishes.')
+ const controller = new AbortController()
+ this.jobs.set(key, controller)
+ try {
+ return await new Promise<GridFleetResult>(resolve => {
+ const output = { stdout: new GridOutputCapture(), stderr: new GridOutputCapture() }
+ let stopped: string | null = null, done = false
+ let timeout: ReturnType<typeof setTimeout>, kill: ReturnType<typeof setTimeout> | undefined
+ const child = spawn(gridBinaryPath(this.processEnv), request.args, {
+ env: { ...gridChildEnv(this.processEnv), ...(request.thinking === undefined ? {} : {
+ LLAMA_ARG_CHAT_TEMPLATE_KWARGS: JSON.stringify({ enable_thinking: request.thinking }),
+ }) }, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ const finish = (code: number, error: string | null) => {
+ if (done) return
+ done = true; clearTimeout(timeout); clearTimeout(kill)
+ resolve({ ok: code === 0 && !error, code, stdout: output.stdout.text, stderr: output.stderr.text, error })
+ }
+ const stop = (reason: string) => {
+ if (stopped || done) return
+ stopped = reason; child.kill('SIGTERM')
+ kill = setTimeout(() => { child.kill('SIGKILL'); finish(124, reason) }, 1500)
+ }
+ const capture = (which: 'stdout' | 'stderr', chunk: string) => {
+ if (stopped) return
+ output[which].append(chunk)
+ if (Buffer.byteLength(output.stdout.text) + Buffer.byteLength(output.stderr.text) > MAX_OUTPUT) {
+ stop('Grid output exceeded 512 KiB; use a narrower query.'); return
+ }
+ }
+ child.stdout.setEncoding('utf8').on('data', (data: string) => capture('stdout', data))
+ child.stderr.setEncoding('utf8').on('data', (data: string) => capture('stderr', data))
+ child.once('error', () => finish(127, 'Grid could not start on this machine. Check its Grid installation.'))
+ child.once('close', code => finish(stopped ? 124 : code ?? 1, stopped || (code === 0 ? null : 'Grid command failed.')))
+ timeout = setTimeout(() => stop('Grid command timed out. Verify the target state before retrying a deployment.'), request.timeoutMs)
+ controller.signal.addEventListener('abort', () => stop('Grid command interrupted. Verify the target state before retrying.'), { once: true })
+ })
+ } finally { this.jobs.delete(key) }
+ }
+}
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index 7772ce5c2..b0acf29ea 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -178,6 +178,21 @@ export class RemoteRelayPool {
private readonly peers: MachinePeerStore,
) {}
+ /** Background CLI jobs must not replace the desktop window's one pooled sink. Each isolated
+ * client gets its own encrypted session, released immediately instead of retained for reconnect. */
+ async acquireIsolated(
+ machineId: string, autonomousEnv: string, selectFrame: Frame,
+ sink: LocalClientSink, onClosed: (code: number, reason: string) => void,
+ ): Promise<RelaySession> {
+ const isolated = new RemoteRelayPool(this.auth, this.backendWsBase, this.selfIdentity, this.peers)
+ const session = await isolated.acquire(machineId, autonomousEnv, selectFrame, {
+ ...sink,
+ sendFrame: frame => sink.sendFrame(frame.type === 'connected'
+ ? { ...frame, payload: { ...framePayload(frame), relayIsolation: true } } : frame),
+ }, onClosed)
+ return { ...session, detach: () => isolated.invalidate(machineId) }
+ }
+
/** Force-drops a pooled entry so the next `acquire()` dials fresh instead of reusing it. For when
* the transport itself never closed but the app-level session behind it is known dead anyway — e.g.
* the relayed machine's own Harness process restarted, dropping its in-memory E2EE session state
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 345745070..958f4c103 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -291,9 +291,12 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
// its pooled entry is suspect (most commonly the relayed machine's own Harness process
// restarted, dropping its E2EE session without the transport itself ever closing). Drop it
// so this select dials fresh instead of handing back the same dead session again.
- if (payload?.forceReconnect === true) options.relayPool.invalidate(requestedMachineId)
+ if (payload?.forceReconnect === true && payload?.relayIsolation !== true) options.relayPool.invalidate(requestedMachineId)
try {
- relay = await options.relayPool.acquire(requestedMachineId, options.autonomousEnv, frame, sink, close)
+ relay = payload?.relayIsolation === true
+ ? await options.relayPool.acquireIsolated(requestedMachineId, options.autonomousEnv, frame, sink, close)
+ : await options.relayPool.acquire(requestedMachineId, options.autonomousEnv, frame, sink, close)
+ if (ws.readyState !== WebSocket.OPEN) { relay.detach(); return }
selected = true
} catch (err) {
const noPeerLink = err instanceof RelayConnectError && err.message === 'NO_PEER_LINK'
diff --git a/desktop/assets/store/grid-fleet.png b/desktop/assets/store/grid-fleet.png
new file mode 100644
index 000000000..a00364ca7
Binary files /dev/null and b/desktop/assets/store/grid-fleet.png differ
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 7ea7196f7..e78122aad 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -13,6 +13,10 @@ const int e2eVersion = 1;
/// to the CLI's own list, because a type missing here fails nowhere: the frame simply leaves in the
/// clear, and for terminal_* the relay then drops it as TERMINAL_FRAME_REJECTED.
const Set<String> encryptedDownTypes = {
+ // Harness's application RPC extensions (CLI e2ee/applicationFrames.ts).
+ 'grid_fleet_capabilities',
+ 'grid_fleet_run',
+ 'grid_fleet_cancel',
'message',
'question_response',
'agents_list',
diff --git a/desktop/lib/store/store_editorial.dart b/desktop/lib/store/store_editorial.dart
index 3fbee919a..88f4f3bc8 100644
--- a/desktop/lib/store/store_editorial.dart
+++ b/desktop/lib/store/store_editorial.dart
@@ -7,7 +7,7 @@ const storeCategoryDomains = <String, Set<String>>{
'Media': {'Documents', 'Slides', 'Video', 'Math animation', 'Music'},
'Science': {'Chemistry', 'Notebooks', 'Simulation'},
'Games': {'Games'},
- 'Code': {'Code'},
+ 'Code': {'Code', 'Compute'},
};
String storeCategoryFor(DshEntry entry) {
@@ -57,6 +57,17 @@ const _pcb = StoreStory(
);
const storeStories = <String, StoreStory>{
+ 'autonomous/autonomous-grid': StoreStory(
+ benefit: 'Your machines. Your models. One conversation.',
+ headline: 'Meet your\npersonal AI fleet.',
+ description: 'Deploy open-weight models by talking to Grid.\nWatch your machines, models, and performance live.',
+ asset: 'assets/store/grid-fleet.png',
+ caption: 'Grid Viewer · Illustrative telemetry',
+ prompts: [
+ 'Discover my machines and deploy an open-weight model that fits.',
+ 'Find the best placement for a coding model and a fast chat model across my fleet.',
+ ],
+ ),
'autonomous/blender': StoreStory(
benefit: 'Your imagination, in three dimensions.',
headline: 'You can\ndesign in 3D.',
diff --git a/store/agents/autonomous-grid/.gitignore b/store/agents/autonomous-grid/.gitignore
new file mode 100644
index 000000000..5acb34d33
--- /dev/null
+++ b/store/agents/autonomous-grid/.gitignore
@@ -0,0 +1,3 @@
+.venv/
+node_modules/
+.harness/
diff --git a/store/agents/autonomous-grid/AGENTS.md b/store/agents/autonomous-grid/AGENTS.md
new file mode 100644
index 000000000..ac3f69c73
--- /dev/null
+++ b/store/agents/autonomous-grid/AGENTS.md
@@ -0,0 +1,36 @@
+# Grid agent
+
+These instructions apply in a **materialized Grid workspace** containing `grid-fleet.json`.
+You are the user's fleet operator. They describe what they want to run; you find a sensible place
+for it, deploy it with the real Grid CLI, verify an answer, and keep the viewer current.
+
+Read `skills/grid-operations/SKILL.md` from this package (or its workspace skill link) before operating
+the fleet. `$GRID_FLEET` is the workspace-aware command runner; `$GRID_CLI` is the selected Grid CLI.
+Use the runner for operations so progress appears in the viewer. The terminal beside the viewer is
+the conversation; do not build another chat UI or run a second background agent.
+
+At the start of a fleet task, inspect `grid-fleet.json` and run `"$GRID_FLEET" status`. This reads the
+viewer's published observations without network access. For questions about running models and
+machines, use a fresh, live snapshot and its observation time; do not start a second network poll.
+Downloaded files and catalog entries are not proof of serving models. If there is no selected grid,
+use `fleet connect --mode local|remote --grid NAME`; add `--remember` when the user wants that fleet
+reused by future Grid workspaces. Never assume a grid named `home`.
+
+`refresh`, `connect`, machine discovery and most `run` commands need network access. In a restricted
+agent sandbox, request the normal scoped network approval before those commands. An EPERM/network
+denial is a permission boundary, not proof that a machine or model is offline. Do not disable the
+sandbox or change global permissions. If the viewer observation is stale, obtain an approved live
+refresh before reporting current health. If there is no grid yet, inventory the machine and explain
+the smallest useful first deployment. When deployment is
+requested, perform it and test it; a plan alone is not completion. Continue through a failed model
+load to diagnosis or rollback, preserving other workloads.
+
+Keep the user informed in plain language: which machine, which model, how much capacity it needs,
+and what changed. Use real measurements; never manufacture utilization, temperatures, benchmark
+scores, discovered machines, or a successful deployment. Hardware data that Grid cannot report is
+unavailable, not zero. An API or subscription engine does not contribute its host's RAM to model capacity.
+
+Keep durable user preferences and explicitly configured machine access in `grid-fleet.json`; put
+plans and measured comparisons in `plans/`. Credentials belong in Grid's or SSH's existing credential
+stores, never in this workspace, a plan, a prompt, or viewer data. The viewer observes live Grid state
+and recorded operations automatically. Do not edit its snapshot to make a deployment look successful.
diff --git a/store/agents/autonomous-grid/LICENSE b/store/agents/autonomous-grid/LICENSE
new file mode 100644
index 000000000..63dcf2196
--- /dev/null
+++ b/store/agents/autonomous-grid/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Autonomous
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/autonomous-grid/README.md b/store/agents/autonomous-grid/README.md
new file mode 100644
index 000000000..8323fa800
--- /dev/null
+++ b/store/agents/autonomous-grid/README.md
@@ -0,0 +1,86 @@
+# Grid, as a Harness agent
+
+Manage open-weight models across your machines by talking to Grid. The agent uses the existing
+[Grid CLI](https://github.com/autonomous-ai/autonomous-grid), with a live fleet viewer beside it:
+gold connections, machine and engine details, model placement, memory, GPU temperature, power,
+utilization, decode estimates, recent telemetry, and operation progress. Topology and rack views
+share the same real observations. No hosted dashboard or second inference service is required.
+
+## Install and open
+
+Choose **Grid** in the Harness Store, or install this checkout:
+
+```sh
+harness dsh install "$PWD/store/agents/autonomous-grid" --link
+harness dsh doctor autonomous/autonomous-grid
+```
+
+Open Grid in a new workspace and ask: “Find the best way to run a coding model and a fast chat
+model on my machines.” It runs on the Codex engine already supported by Harness. Setup uses
+Harness's managed Grid runtime when present; otherwise it installs the upstream revision in
+`VERSIONS` into a package-local Python environment. Setup does not download models or start engines.
+
+New workspaces reuse your remembered fleet, or Grid's reachable active selection, and import your
+Harness machine inventory. They never assume an old local grid named `home`. Use
+`fleet connect --mode remote --grid NAME --remember` to make a verified fleet the default for future
+Grid workspaces; `--remember` stores only fleet configuration in `~/.harness/grid-fleet/default.json`.
+Existing workspaces keep their own explicit selection. Without a clear selection, the viewer asks
+you to choose a grid instead of reporting an unrelated old endpoint as your fleet.
+
+`fleet status` reads the viewer's published observations without network access. The agent uses
+fresh observations for routine model and machine questions. Explicit live refreshes and operations
+use the agent's normal network-approval flow when its sandbox requires it; no global permission
+changes are needed. See [Codex's documented network boundary](https://learn.chatgpt.com/docs/agent-approvals-security#network-access).
+
+`fleet discover --add` imports additional Harness machines;
+commands travel over their existing paired, encrypted Harness links, without SSH setup. Both the
+controller and target need the Harness CLI's Grid fleet protocol (capabilities are checked before
+running commands). Older targets show an update requirement. Known SSH hosts remain supported;
+keys and host trust stay with SSH. Grid can also observe a remote grid through its existing sign-in.
+Remote telemetry does not by itself grant administrative access to each serving machine.
+
+## How it works
+
+- `toolchain/grid.sh` selects the same managed Grid runtime as Harness, with an explicit developer
+ override (`HARNESS_GRID_BIN`) and a pinned package fallback.
+- `toolchain/fleet run --machine ID -- …` forwards the complete Grid CLI, preserving arguments and
+ exit codes over local, paired Harness, or SSH execution. Each operation updates a small workspace record.
+ Harness connections use Node 22's WebSocket and bounded, noninteractive commands; use the machine's
+ terminal for interactive sign-in. No remote command is automatically retried after a lost connection.
+- `viewer.mjs` polls `info`, `engines`, `models`, remote `stats`, and managed hosts' `device-info`.
+ It serves a read-only loopback viewer and SSE updates. No credential files, full CLI output,
+ arbitrary workspace files, or mutation endpoints are exposed to the browser.
+- The viewer uses only reported metrics. Local Grid currently exposes less live telemetry than
+ remote Grid. Missing temperature or speed reads `—`; a failed refresh preserves a visibly stale
+ observation. Speeds are per-engine last decode estimates, never summed into a fictional fleet rate.
+- Model deployment and removal happen through the agent. The skill distinguishes undeploying an
+ instance from deleting weights and verifies service with a real request after `join`.
+- `fleet run --machine ID --thinking off -- join ...` starts a supported model with thinking disabled
+ through llama.cpp's template setting. This explicit control complements Grid's token budget and is
+ checked against the remote daemon's capabilities before startup. Omit it to retain the model default.
+
+## Develop and verify
+
+```sh
+npm test --prefix store/agents/autonomous-grid
+harness dsh check "$PWD/store/agents/autonomous-grid"
+node store/tools/catalog.mjs
+
+# Viewer against a workspace; the selected port is printed.
+HARNESS_WORKSPACE=/path/to/workspace store/agents/autonomous-grid/viewer.sh
+```
+
+The opt-in live test takes `GRID_TEST_MODEL` (a real GGUF file) and `GRID_TEST_ENGINE_DIR`
+(a directory containing llama-server and its libraries), creates an isolated `GRID_HOME`, then
+starts a private loopback Grid, deploys, chats, undeploys, verifies removal, and cleans up.
+`npm run test:live` does not touch the user's existing grids. See `test/live.mjs` for inputs.
+The automated fixture tests cover full command forwarding and telemetry failure cases; they do not
+claim to exercise every remote, media, or training workload.
+
+## Credit and stewardship
+
+Grid is Autonomous's [autonomous-grid](https://github.com/autonomous-ai/autonomous-grid) project,
+licensed MIT. This package wraps its unmodified CLI. Grid's own README video inspired the fleet
+visualization; the viewer and Harness integration are new code. Upstream CLI and engine issues
+belong in the Grid repository; package, agent and viewer issues belong in OpenHarness. A future
+move of this wrapper into Grid's repository can retain its Store identity.
diff --git a/store/agents/autonomous-grid/VERSIONS b/store/agents/autonomous-grid/VERSIONS
new file mode 100644
index 000000000..54b751c75
--- /dev/null
+++ b/store/agents/autonomous-grid/VERSIONS
@@ -0,0 +1,4 @@
+# Runtime floor matches Harness's managed Grid runtime. Fallback installs this exact upstream.
+GRID_MIN_VERSION="0.3.47"
+UPSTREAM_REPO="https://github.com/autonomous-ai/autonomous-grid.git"
+UPSTREAM_COMMIT="0b8d0e34109735ffd73aadf7288120451cc436fc"
diff --git a/store/agents/autonomous-grid/harness.json b/store/agents/autonomous-grid/harness.json
new file mode 100644
index 000000000..b96f00c8b
--- /dev/null
+++ b/store/agents/autonomous-grid/harness.json
@@ -0,0 +1,32 @@
+{
+ "spec": 1,
+ "id": "autonomous/autonomous-grid",
+ "name": "Grid",
+ "category": "Compute",
+ "author": "Autonomous",
+ "description": "Talk to your fleet. Deploy open-weight models, find the right machine for each workload, and watch your Grid come alive with a live map of engines, models, memory, temperature and performance.",
+ "engine": "codex",
+ "workspace": {
+ "template": "template",
+ "marker": "grid-fleet.json",
+ "init": "toolchain/init-workspace.sh"
+ },
+ "agent": {
+ "instructions": "AGENTS.md",
+ "skills": ["skills"],
+ "env": {
+ "GRID_CLI": "${dsh}/toolchain/grid.sh",
+ "GRID_FLEET": "${dsh}/toolchain/fleet",
+ "GRID_NO_UPDATE_CHECK": "1"
+ }
+ },
+ "toolchain": {
+ "setup": "toolchain/setup.sh",
+ "doctor": "toolchain/doctor.sh"
+ },
+ "viewer": {
+ "command": "./viewer.sh",
+ "url": "http://127.0.0.1:${port}/"
+ },
+ "verdict": ".harness/verdict.json"
+}
diff --git a/store/agents/autonomous-grid/lib/connect.mjs b/store/agents/autonomous-grid/lib/connect.mjs
new file mode 100644
index 000000000..301a9e70f
--- /dev/null
+++ b/store/agents/autonomous-grid/lib/connect.mjs
@@ -0,0 +1,105 @@
+import { homedir } from 'node:os';
+import { isAbsolute, join } from 'node:path';
+import { atomicJson, gridJson, now, readConfig, readJson, stateDir, text, validateConfig } from './fleet.mjs';
+import { discoverMachines } from './harness.mjs';
+
+export function defaultsPath(env = process.env) {
+ const path = env.GRID_FLEET_DEFAULTS || join(homedir(), '.harness', 'grid-fleet', 'default.json');
+ if (!isAbsolute(path)) throw new Error('GRID_FLEET_DEFAULTS must be an absolute path.');
+ return path;
+}
+
+export function mergeMachines(config, found) {
+ const result = structuredClone(config);
+ for (const machine of found) {
+ const local = result.machines.find(m => m.transport === 'local');
+ if (machine.current && local) {
+ if (local.name === 'This machine') local.name = machine.name;
+ continue;
+ }
+ if (result.machines.length >= 32 || result.machines.some(m => m.id === machine.id || m.machineId === machine.machineId)) continue;
+ result.machines.push(machine);
+ }
+ return validateConfig(result);
+}
+
+/** Resolve a fresh workspace without changing Grid's global mode/default or starting a service. */
+export async function initializeWorkspace(workspace, { runJson = gridJson, discover = discoverMachines, profilePath = defaultsPath() } = {}) {
+ let config = await readConfig(workspace), source = 'workspace', message = '', candidates = [];
+ const controller = () => config.machines.find(m => m.id === config.controller);
+ const read = (mode, args) => runJson(controller(), mode, args, { timeoutMs: 5000 }).catch(() => ({ ok: false }));
+ if (!config.grid) {
+ const saved = await readJson(profilePath, null);
+ if (saved) {
+ config = validateConfig(saved); source = 'remembered fleet';
+ // An explicit remembered fleet stays selected through an outage. Never switch its owner
+ // to an unrelated reachable grid just because that other grid currently answers.
+ message = `Selected your remembered ${config.mode} fleet ${config.grid}; checking live telemetry.`;
+ } else {
+ const mode = await read(config.mode, ['mode']);
+ const preferred = ['local','remote'].includes(mode.value?.mode) ? mode.value.mode : config.mode;
+ config.mode = preferred;
+ const active = await read(preferred, ['use']);
+ const selected = text(active.value?.active);
+ if (selected && !selected.startsWith('-')) {
+ const engines = await read(preferred, ['engines', selected]);
+ if (engines.ok && Array.isArray(engines.value)) {
+ config.grid = selected; source = 'Grid selection';
+ }
+ }
+ if (!config.grid) {
+ const listings = await Promise.all(['local','remote'].map(async mode => ({mode,result:await read(mode,['ls'])})));
+ for (const {mode,result} of listings) for (const row of Array.isArray(result.value) ? result.value.slice(0,16) : []) {
+ const grid = text(row.grid || row.name || row.id);
+ if (grid && !grid.startsWith('-') && !candidates.some(c => c.mode === mode && c.grid === grid)) candidates.push({mode,grid});
+ }
+ // Only a unique known grid is an unambiguous fallback. Multiple grids stay a choice,
+ // even when one happens to have more traffic. Probe only the candidate we may select.
+ if (candidates.length === 1) {
+ const candidate = candidates[0], engines = await read(candidate.mode,['engines',candidate.grid]);
+ if (engines.ok && Array.isArray(engines.value)) {
+ config.mode = candidate.mode; config.grid = candidate.grid; source = 'only reachable grid';
+ }
+ }
+ if (!config.grid) message = 'Choose a grid with fleet connect --mode local|remote --grid NAME. The existing default was not reachable or the selection is ambiguous.';
+ }
+ if (config.grid) message = `Connected this workspace to ${config.mode} grid ${config.grid}.`;
+ }
+ }
+ config = mergeMachines(config, await discover().catch(() => []));
+ await atomicJson(join(workspace,'grid-fleet.json'),config);
+ const connection = { source, mode:config.mode, grid:config.grid, message, candidates, observedAt:now() };
+ await atomicJson(join(stateDir(workspace),'connection.json'),connection);
+ return {config,connection};
+}
+
+export async function connectWorkspace(workspace, {mode,grid,remember=false}, {runJson=gridJson,discover=discoverMachines,profilePath=defaultsPath()} = {}) {
+ let config = validateConfig({...await readConfig(workspace),mode,grid});
+ if (!grid) throw new Error('Choose an explicit grid name, ID or URL.');
+ const controller = config.machines.find(m => m.id === config.controller);
+ const probe = await runJson(controller,mode,['engines',grid],{timeoutMs:15000});
+ if (!probe.ok || !Array.isArray(probe.value)) throw new Error(probe.error || 'This grid did not return an engine list; the workspace selection was not changed.');
+ config = mergeMachines(config,await discover().catch(() => []));
+ await atomicJson(join(workspace,'grid-fleet.json'),config);
+ if (remember) await atomicJson(profilePath,config);
+ await atomicJson(join(stateDir(workspace),'connection.json'),{source:'explicit selection',mode,grid,remembered:remember,observedAt:now()});
+ return config;
+}
+
+/** Read the viewer's published observation, with no sockets or subprocesses. */
+export async function readStatus(workspace, time = Date.now()) {
+ const config = await readConfig(workspace);
+ const snapshot = await readJson(join(stateDir(workspace),'snapshot.json'),null);
+ const scope = JSON.stringify([config.mode,config.grid,config.controller]);
+ if (!snapshot || snapshot.scope !== scope) return {
+ spec:1,status:config.grid?'connecting':'unconfigured',fresh:false,mode:config.mode,grid:config.grid,
+ models:[],nodes:[],machines:config.machines,
+ message:config.grid?'The viewer has not published this fleet yet. Wait for it, or run fleet refresh with the required network approval.':'No grid selected. Run fleet connect --mode local|remote --grid NAME.',
+ };
+ const ageMs = time-Date.parse(snapshot.observedAt), fresh = Number.isFinite(ageMs) && ageMs >= -5000 && ageMs <= Math.max(30000,(snapshot.pollIntervalMs||8000)*3);
+ const {history,events,...view} = snapshot;
+ return {...view,status:fresh?snapshot.status:'stale',fresh,cached:true,ageSeconds:Number.isFinite(ageMs)?Math.max(0,Math.floor(ageMs/1000)):null,
+ nodes:(snapshot.nodes||[]).map(n=>fresh?n:{...n,stale:true}),operations:(snapshot.operations||[]).slice(0,5),
+ ...(!fresh?{message:'These are last-known observations. The viewer is no longer updating; request network approval for fleet refresh before reporting current health.'}:{}),
+ };
+}
diff --git a/store/agents/autonomous-grid/lib/fleet.mjs b/store/agents/autonomous-grid/lib/fleet.mjs
new file mode 100644
index 000000000..b650752ea
--- /dev/null
+++ b/store/agents/autonomous-grid/lib/fleet.mjs
@@ -0,0 +1,156 @@
+import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { harnessExecute } from './harness.mjs';
+
+export const PACKAGE = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+export const DEFAULT_CONFIG = { spec: 1, mode: 'local', grid: null, machines: [{ id: 'local', name: 'This machine', transport: 'local' }], preferences: { goal: 'Run useful models on the machines I own', keepFreeMemoryGb: 4, allowAutomaticChanges: false } };
+export const now = () => new Date().toISOString();
+export const stateDir = workspace => join(workspace, '.harness', 'grid');
+const idPattern = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$/;
+export const text = (value, max = 240) => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, max) : '';
+export const number = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
+
+export async function readJson(file, fallback, limit = 2 * 1024 * 1024) {
+ try {
+ if ((await stat(file)).size > limit) throw new Error('File is too large');
+ return JSON.parse(await readFile(file, 'utf8'));
+ } catch (error) {
+ if (error.code === 'ENOENT' && fallback !== undefined) return structuredClone(fallback);
+ throw new Error(`Cannot read ${file}: ${error.message}`);
+ }
+}
+
+export async function atomicJson(file, value) {
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
+ const temporary = `${file}.${randomUUID()}.tmp`;
+ try {
+ await writeFile(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
+ await rename(temporary, file);
+ } finally { await unlink(temporary).catch(() => {}); }
+}
+
+export function validateConfig(raw) {
+ if (!raw || raw.spec !== 1 || !['local', 'remote'].includes(raw.mode)) throw new Error('grid-fleet.json needs spec: 1 and mode: local or remote.');
+ if (raw.grid !== null && (typeof raw.grid !== 'string' || !raw.grid.trim() || raw.grid.length > 240 || raw.grid.startsWith('-') || /[\x00-\x1f]/.test(raw.grid))) throw new Error('grid must be a name, ID, URL, or null.');
+ if (!Array.isArray(raw.machines) || !raw.machines.length || raw.machines.length > 32) throw new Error('machines must contain 1–32 local, Harness, or SSH targets.');
+ const ids = new Set();
+ const machines = raw.machines.map(m => {
+ if (!m || !idPattern.test(m.id) || ids.has(m.id)) throw new Error('Every machine needs a unique, simple id.');
+ ids.add(m.id);
+ if (!['local', 'ssh', 'harness'].includes(m.transport)) throw new Error(`Unknown transport for ${m.id}.`);
+ if (m.transport === 'harness' && (typeof m.machineId !== 'string' || !/^[a-zA-Z0-9_-]{1,100}$/.test(m.machineId))) throw new Error(`A Harness machineId is required for ${m.id}.`);
+ if (m.transport === 'harness' && (m.gridHome || m.gridBinary)) throw new Error(`Harness targets use their daemon's Grid installation and home: ${m.id}.`);
+ if (m.transport === 'ssh' && (typeof m.host !== 'string' || !/^(?:[A-Za-z0-9_.-]+@)?[A-Za-z0-9][A-Za-z0-9_.:-]*$/.test(m.host))) throw new Error(`Invalid SSH host for ${m.id}; use an SSH config alias or user@host.`);
+ if (m.port !== undefined && (!Number.isInteger(m.port) || m.port < 1 || m.port > 65535)) throw new Error(`Invalid SSH port for ${m.id}.`);
+ for (const key of ['gridBinary', 'gridHome']) if (m[key] !== undefined && (typeof m[key] !== 'string' || !m[key].startsWith('/') || m[key].includes('\0') || m[key].length > 1024)) throw new Error(`${key} for ${m.id} must be an absolute path.`);
+ return { id: m.id, name: text(m.name) || m.id, transport: m.transport, ...(m.transport === 'harness' ? { machineId: m.machineId } : {}), ...(m.transport === 'ssh' ? { host: m.host, ...(m.port ? { port: m.port } : {}) } : {}), ...(m.gridBinary ? { gridBinary: m.gridBinary } : {}), ...(m.gridHome ? { gridHome: m.gridHome } : {}) };
+ });
+ // The controller is explicit, so editing the order of an inventory cannot redirect fleet reads.
+ const controller = raw.controller || machines.find(m => m.transport === 'local')?.id || machines[0].id;
+ if (!ids.has(controller)) throw new Error('controller must name a configured machine.');
+ return { spec: 1, mode: raw.mode, grid: raw.grid, controller, machines, preferences: { goal: text(raw.preferences?.goal, 500) || DEFAULT_CONFIG.preferences.goal, keepFreeMemoryGb: number(raw.preferences?.keepFreeMemoryGb) ?? 4, allowAutomaticChanges: raw.preferences?.allowAutomaticChanges === true } };
+}
+export async function readConfig(workspace) { return validateConfig(await readJson(join(workspace, 'grid-fleet.json'), DEFAULT_CONFIG)); }
+
+export const shellQuote = value => `'${String(value).replace(/'/g, `'"'"'`)}'`;
+
+export function invocation(machine, args, env = process.env, thinking) {
+ if (!Array.isArray(args) || args.some(a => typeof a !== 'string' || a.includes('\0'))) throw new Error('Grid arguments must be strings without NUL bytes.');
+ const template = thinking === undefined ? null : JSON.stringify({ enable_thinking: thinking });
+ const childEnv = { ...env, GRID_NO_UPDATE_CHECK: '1', ...(machine.gridHome ? { GRID_HOME: machine.gridHome } : {}), ...(template === null ? {} : { LLAMA_ARG_CHAT_TEMPLATE_KWARGS: template }) };
+ if (machine.transport === 'local') return { file: machine.gridBinary || join(PACKAGE, 'toolchain', 'grid.sh'), args, env: childEnv };
+ if (machine.transport !== 'ssh') throw new Error('This transport does not use a shell invocation.');
+ // SSH accepts a shell command, not an argv vector. Quote each argument separately; never join
+ // user input as shell syntax. BatchMode and strict host keys use the user's established SSH trust.
+ const argv = ['-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=8'];
+ if (machine.port) argv.push('-p', String(machine.port));
+ const choose = machine.gridBinary ? `bin=${shellQuote(machine.gridBinary)}` : 'runtime="${ADAPTER_RUNTIME_DIR:-$HOME/.harness/runtime}"; bin="$(cat "$runtime/current-grid" 2>/dev/null || true)"; case "$bin" in "$runtime"/*) test -x "$bin" || bin="";; *) bin="";; esac; if test -z "$bin"; then bin="$(command -v grid || true)"; fi; if test -z "$bin"; then bin="$HOME/.local/bin/grid"; fi';
+ const remote = `export GRID_NO_UPDATE_CHECK=1; ${template === null ? '' : `export LLAMA_ARG_CHAT_TEMPLATE_KWARGS=${shellQuote(template)}; `}${machine.gridHome ? `export GRID_HOME=${shellQuote(machine.gridHome)}; ` : ''}${choose}; exec "$bin" ${args.map(shellQuote).join(' ')}`;
+ return { file: 'ssh', args: [...argv, machine.host, remote], env: childEnv };
+}
+
+export function execute(machine, args, { timeoutMs = 15_000, inherit = false, env = process.env, signal, thinking } = {}) {
+ if (thinking !== undefined && typeof thinking !== 'boolean') throw new Error('Thinking must be a boolean.');
+ if (machine.transport === 'harness') {
+ if (!Array.isArray(args) || args.some(a => typeof a !== 'string' || a.includes('\0'))) throw new Error('Grid arguments must be strings without NUL bytes.');
+ return harnessExecute(machine, args, { timeoutMs, inherit, env, signal, thinking });
+ }
+ const call = invocation(machine, args, env, thinking);
+ return new Promise(resolveResult => {
+ let stdout = '', stderr = '', finished = false, timer, killTimer, child, termination = null;
+ const finish = result => {
+ if (finished) return;
+ finished = true; clearTimeout(timer); clearTimeout(killTimer); signal?.removeEventListener('abort', abort);
+ resolveResult({ stdout, stderr, ...result });
+ };
+ const stop = message => {
+ if (finished || termination) return;
+ termination = message;
+ child.kill('SIGTERM');
+ killTimer = setTimeout(() => { child.kill('SIGKILL'); finish({ ok: false, code: 124, error: message }); }, 1500);
+ };
+ const abort = () => stop('Grid command was interrupted; verify the engine state before retrying.');
+ try { child = spawn(call.file, call.args, { env: call.env, stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'] }); }
+ catch (error) { finish({ ok: false, code: 127, error: error.message }); return; }
+ let stopping = false;
+ const capture = which => chunk => {
+ if (stopping) return;
+ if (stdout.length + stderr.length + chunk.length > 4 * 1024 * 1024) { stopping = true; stop('Grid output exceeded 4 MiB.'); return; }
+ if (which === 'out') stdout += chunk; else stderr += chunk;
+ };
+ child.stdout?.setEncoding('utf8').on('data', capture('out'));
+ child.stderr?.setEncoding('utf8').on('data', capture('err'));
+ child.once('error', error => finish({ ok: false, code: 127, error: error.code === 'ENOENT' ? 'Grid or SSH is not installed on this machine.' : error.message }));
+ child.once('close', (code, sig) => finish(termination ? { ok: false, code: 124, error: termination } : { ok: code === 0, code: code ?? 1, error: code === 0 ? null : `Grid exited ${code ?? sig}.` }));
+ timer = setTimeout(() => { stopping = true; stop(`Grid did not answer within ${Math.round(timeoutMs / 1000)} seconds; the operation may still be running on the target.`); }, timeoutMs);
+ signal?.addEventListener('abort', abort, { once: true });
+ if (signal?.aborted) abort();
+ });
+}
+
+export async function gridJson(machine, mode, args, options) {
+ const result = await execute(machine, [`--${mode}`, ...args, '--json'], options);
+ if (!result.ok) {
+ const blocked = /(?:could not reach|network|socket)[\s\S]{0,600}(?:operation not permitted|EPERM|denied|blocked)/i.test(`${result.stdout}\n${result.stderr}`);
+ return { ok: false, error: blocked ? 'Network access was blocked by the agent sandbox. Use fleet status for viewer observations, or request scoped network approval before retrying this Grid command.' : result.code === 127 ? result.error : `grid ${args[0]} failed (${result.code}). Run it in the agent terminal for details.` };
+ }
+ try {
+ const value = JSON.parse(result.stdout);
+ if (value?.error) return { ok: false, error: `grid ${args[0]} reported an error.` };
+ return { ok: true, value };
+ } catch { return { ok: false, error: `grid ${args[0]} did not return valid JSON.` }; }
+}
+
+export async function operations(workspace) {
+ const folder = join(stateDir(workspace), 'operations');
+ const names = await readdir(folder).catch(() => []);
+ const entries = await Promise.all(names.filter(n => /^[a-f0-9-]+\.json$/.test(n)).map(async name => ({ name, mtime: (await stat(join(folder,name)).catch(() => null))?.mtimeMs || 0 })));
+ entries.sort((a,b) => b.mtime-a.mtime);
+ const rows = await Promise.all(entries.slice(0,200).map(({name}) => readJson(join(folder, name), null, 16 * 1024).catch(() => null)));
+ return rows.filter(row => row && typeof row.startedAt === 'string').sort((a,b) => b.startedAt.localeCompare(a.startedAt)).slice(0, 40).map(row => {
+ let phase = ['running', 'done', 'failed', 'interrupted'].includes(row.phase) ? row.phase : 'interrupted';
+ if (phase === 'running' && Number.isInteger(row.pid) && row.pid > 0) {
+ try { process.kill(row.pid, 0); } catch (error) { if (error.code === 'ESRCH') phase = 'interrupted'; }
+ }
+ return { id: text(row.id), machine: text(row.machine), command: text(row.command, 80), phase, startedAt: text(row.startedAt), endedAt: text(row.endedAt) || null, exitCode: number(row.exitCode) };
+ });
+}
+
+export async function runTracked(workspace, machine, mode, args, options = {}) {
+ const command = args.find(a => !a.startsWith('-')) || 'overview';
+ const op = { id: randomUUID(), machine: machine.id, command: `grid ${text(command, 40)}`, phase: 'running', startedAt: now(), endedAt: null, exitCode: null, pid: process.pid };
+ const file = join(stateDir(workspace), 'operations', `${op.id}.json`);
+ await atomicJson(file, op);
+ try {
+ const result = await execute(machine, [`--${mode}`, ...args], { inherit: true, timeoutMs: 30 * 60_000, ...options });
+ Object.assign(op, { phase: result.ok ? 'done' : result.code === 124 ? 'interrupted' : 'failed', endedAt: now(), exitCode: result.code });
+ await atomicJson(file, op);
+ return result;
+ } catch (error) {
+ await atomicJson(file, { ...op, phase: 'failed', endedAt: now(), exitCode: 1 });
+ throw error;
+ }
+}
diff --git a/store/agents/autonomous-grid/lib/harness.mjs b/store/agents/autonomous-grid/lib/harness.mjs
new file mode 100644
index 000000000..e14e60b6b
--- /dev/null
+++ b/store/agents/autonomous-grid/lib/harness.mjs
@@ -0,0 +1,84 @@
+import { randomUUID } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+
+const updateMessage = 'This machine needs a Harness version with Grid fleet support. Update Harness there, or configure an existing SSH target.';
+
+export async function discoverMachines() {
+ const { stdout } = await promisify(execFile)('harness', ['machines', '--json'], { timeout: 20_000, maxBuffer: 512 * 1024 });
+ return stdout.split('\n').filter(Boolean).map(line => JSON.parse(line)).filter(row => typeof row.machineId === 'string').map(row => ({
+ id: row.machineId, machineId: row.machineId, name: String(row.name || row.hostname || row.machineId).slice(0,240),
+ transport: row.current ? 'local' : 'harness', current: row.current === true, online: row.status === 'running',
+ }));
+}
+
+/** Node's WebSocket talks only to Harness's loopback bridge; Harness owns pairing and encryption. */
+export function bridgeUrl(env = process.env) {
+ const url = new URL(env.HARNESS_GRID_BRIDGE_URL || 'ws://127.0.0.1:18473/api/local-ws');
+ if (url.protocol !== 'ws:' || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
+ || url.pathname !== '/api/local-ws' || url.username || url.password || url.search || url.hash) throw new Error('Harness bridge must be its local WebSocket endpoint.');
+ return url.href;
+}
+
+export async function harnessExecute(machine, args, { timeoutMs = 15_000, inherit = false, signal, thinking, env = process.env, WebSocketImpl = globalThis.WebSocket } = {}) {
+ if (!WebSocketImpl) return { ok: false, code: 127, stdout: '', stderr: '', error: 'Node 22 or newer is required for Harness machine connections.' };
+ let socket;
+ try { socket = new WebSocketImpl(bridgeUrl(env)); }
+ catch { return { ok: false, code: 127, stdout: '', stderr: '', error: 'Could not open the local Harness bridge.' }; }
+ return await new Promise(resolve => {
+ let done = false, running = false, selected = false, heartbeat, deadline;
+ const commandId = randomUUID(), capabilityId = randomUUID();
+ const send = (type, payload) => socket.send(JSON.stringify({ type, payload }));
+ const finish = result => {
+ if (done) return;
+ done = true; clearTimeout(deadline); clearInterval(heartbeat); signal?.removeEventListener('abort', abort); socket.close();
+ if (inherit) { if (result.stdout) process.stdout.write(result.stdout); if (result.stderr) process.stderr.write(result.stderr); }
+ resolve(result);
+ };
+ const fail = error => finish({ ok: false, code: running ? 124 : 127, stdout: '', stderr: '', error });
+ const abort = () => {
+ if (running && socket.readyState === 1) send('grid_fleet_cancel', { requestId: randomUUID(), commandId });
+ fail('Grid command interrupted. Verify the target state before retrying.');
+ };
+ deadline = setTimeout(() => fail('Harness did not connect to this machine. Check that it is online and linked.'), Math.min(timeoutMs, 20_000));
+ socket.addEventListener('open', () => send('machine_select', { machineId: machine.machineId, localProtocolVersion: 1, relayIsolation: true }));
+ socket.addEventListener('error', () => fail('Harness connection failed. Start Harness and check the machine link.'));
+ socket.addEventListener('close', event => {
+ if (done) return;
+ if (event.code === 4404) fail('Link this machine in Harness Machines before managing it from Grid.');
+ else fail(running ? 'Harness connection closed. The command may still be running; inspect the target before retrying.' : 'Harness could not connect. Check that this machine is online and linked.');
+ });
+ socket.addEventListener('message', event => {
+ if (typeof event.data !== 'string' || event.data.length > 2 * 1024 * 1024) return;
+ let frame; try { frame = JSON.parse(event.data); } catch { return; }
+ const { type, payload = {} } = frame;
+ if (type === 'connected') {
+ if (selected) return;
+ selected = true;
+ if (payload.relayIsolation !== true && payload.transport !== 'local') {
+ fail('Update Harness on this controller to support independent Grid fleet connections.'); return;
+ }
+ clearTimeout(deadline);
+ deadline = setTimeout(() => fail(updateMessage), Math.min(timeoutMs, 15_000));
+ send('grid_fleet_capabilities', { requestId: capabilityId });
+ heartbeat = setInterval(() => send('ping', {}), 15_000);
+ } else if (type === 'grid_fleet_capabilities_result' && payload.requestId === capabilityId) {
+ if (running) return;
+ if (payload.protocol !== 1) { fail(updateMessage); return; }
+ if (thinking !== undefined && payload.thinkingControl !== true) { fail('Update Harness on this machine to support explicit model thinking controls.'); return; }
+ if (payload.gridCli === 'missing') { fail('Grid is not installed on this machine. Install the Grid Harness there first.'); return; }
+ clearTimeout(deadline); running = true;
+ const duration = Math.min(timeoutMs, payload.maxTimeoutMs || 1_800_000);
+ deadline = setTimeout(() => { abort(); }, duration + 5000);
+ send('grid_fleet_run', { requestId: commandId, args, timeoutMs: duration, ...(thinking === undefined ? {} : { thinking }) });
+ } else if (type === 'grid_fleet_run_result' && payload.requestId === commandId) {
+ finish({ ok: payload.ok === true, code: Number.isInteger(payload.code) ? payload.code : 1,
+ stdout: typeof payload.stdout === 'string' ? payload.stdout : '', stderr: typeof payload.stderr === 'string' ? payload.stderr : '',
+ error: payload.ok === true ? null : typeof payload.error === 'string' ? payload.error : 'Grid command failed.' });
+ } else if (['error', 'connection_error', 'local_protocol_error', 'machine_link_required'].includes(type)) {
+ fail('This machine is unavailable or needs linking in Harness Machines.');
+ }
+ });
+ signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort();
+ });
+}
diff --git a/store/agents/autonomous-grid/lib/telemetry.mjs b/store/agents/autonomous-grid/lib/telemetry.mjs
new file mode 100644
index 000000000..7f968a768
--- /dev/null
+++ b/store/agents/autonomous-grid/lib/telemetry.mjs
@@ -0,0 +1,167 @@
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+import { atomicJson, gridJson, now, number, operations, readConfig, readJson, stateDir, text } from './fleet.mjs';
+
+const array = value => Array.isArray(value) ? value : [];
+const objects = value => array(value).filter(v => v && typeof v === 'object' && !Array.isArray(v));
+const firstNumber = (...values) => values.map(number).find(n => n !== null) ?? null;
+const gb = mb => number(mb) === null ? null : mb / 1024;
+const unique = values => [...new Set(values)];
+const key = value => createHash('sha256').update(value).digest('hex').slice(0, 16);
+
+export function normalizeNode(raw, mode, modelNames = new Map(), index = 0) {
+ const name = text(raw.name || raw.engine || raw.node_id || raw.id) || `Engine ${index + 1}`;
+ const endpoint = safeUrl(raw.where || raw.endpoint_url);
+ const plan = text(raw.plan_type);
+ // Grid's engine inventory can advertise one card's memory_gb while live VRAM spans
+ // every GPU. Use the matching aggregate sensor pair before rounded inventory fields.
+ const memoryTotal = plan ? null : firstNumber(gb(raw.vram_total_mb), raw.vram_gb, raw.memory_gb);
+ const used = plan ? null : firstNumber(gb(raw.vram_used_mb), raw.memory_used_gb);
+ const platform = text(raw.platform);
+ const models = unique(array(raw.models).map(v => text(typeof v === 'string' ? v : v?.model)).filter(Boolean)).map(id => modelNames.get(id.toLowerCase()) || id);
+ const id = key(JSON.stringify([text(raw.node_id || raw.id), name, endpoint]));
+ const answered = normalizeAnswered(raw.answered);
+ return {
+ id, name, engine: text(raw.kind || (raw.name ? raw.engine : '')) || 'Grid engine', endpoint,
+ hardware: text(raw.chip || raw.hardware || raw.device), platform, hosted: Boolean(plan), plan: plan || null,
+ online: raw.online === true ? true : raw.online === false ? false : mode === 'local' ? true : null,
+ models, memoryKind: plan ? null : (text(raw.memory_kind) || (platform.toLowerCase().startsWith('macos-arm') ? 'Unified memory' : 'VRAM')),
+ memoryTotalGb: memoryTotal, memoryUsedGb: used,
+ memoryFreeGb: memoryTotal !== null && used !== null ? Math.max(0, memoryTotal - used) : null,
+ temperatureC: firstNumber(raw.gpu_temp_c), utilizationPct: firstNumber(raw.gpu_util_pct),
+ powerW: firstNumber(raw.gpu_power_w), powerLimitW: firstNumber(raw.gpu_power_limit_w),
+ diskTotalGb: firstNumber(raw.disk_total_gb), diskUsedGb: firstNumber(raw.disk_used_gb),
+ tokS: firstNumber(raw.throughput_tok_s), concurrency: firstNumber(raw.max_concurrency, raw.parallel),
+ activeRequests: firstNumber(raw.active_tasks, raw.load?.active_tasks), answered,
+ capabilities: models.map(model => {
+ const caps = raw.model_capabilities?.[model.toLowerCase()] || raw.model_capabilities?.[model];
+ const entry = array(raw.models).find(m => m?.model === model);
+ return { model, contextLength: firstNumber(caps?.context_length, entry?.context_length), responses: array(raw.responses_models).some(m => String(m).toLowerCase() === model.toLowerCase()) };
+ }),
+ };
+}
+
+export function normalizeAnswered(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ return { windowSeconds: number(raw.window_seconds), tokensIn: number(raw.tokens_in), tokensCached: number(raw.tokens_cached), tokensOut: number(raw.tokens_out), requests: number(raw.requests) };
+}
+
+export function safeUrl(value) {
+ try {
+ const url = new URL(value);
+ if (!['http:', 'https:'].includes(url.protocol)) return null;
+ url.username = ''; url.password = ''; url.search = ''; url.hash = '';
+ return url.href.replace(/\/$/, '');
+ } catch { return null; }
+}
+
+export function normalizeDevice(machine, raw, observedAt) {
+ const memory = raw?.memory || {}, disk = raw?.disk || {}, cpu = raw?.cpu || {}, device = raw?.machine || {};
+ return {
+ id: machine.id, name: machine.name, transport: machine.transport, observedAt,
+ hardware: text(device.model || cpu.brand), platform: text(device.platform), backend: text(raw?.backend),
+ memoryTotalGb: number(memory.total_gb), memoryAvailableGb: number(memory.available_gb),
+ usableModelGb: number(raw?.usable_bytes) === null ? null : raw.usable_bytes / (1024 ** 3),
+ cpuCores: number(cpu.physical_cores), cpuThreads: number(cpu.logical_threads),
+ diskTotalGb: number(disk.total_gb), diskFreeGb: number(disk.free_gb),
+ gpus: objects(raw?.gpus).map(g => ({ name: text(g.name), memoryGb: gb(g.memory_total_mb), memoryUsedGb: gb(g.memory_used_mb), temperatureC: firstNumber(g.temperature_c, g.gpu_temp_c), utilizationPct: firstNumber(g.utilization_pct, g.utilization_percent, g.gpu_util_pct), powerW: firstNumber(g.power_draw_w, g.gpu_power_w) })),
+ };
+}
+
+export function assemble(config, reads, previous = null, observedAt = now()) {
+ const scope = JSON.stringify([config.mode, config.grid, config.controller]);
+ if (previous?.scope !== scope) previous = null;
+ const sources = Object.fromEntries(Object.entries(reads).map(([name, result]) => [name, { ok: result.ok, error: result.ok ? null : result.error, observedAt }]));
+ const info = reads.info?.ok && reads.info.value && typeof reads.info.value === 'object' ? reads.info.value : {};
+ const stats = reads.stats?.ok && reads.stats.value && typeof reads.stats.value === 'object' ? reads.stats.value : {};
+ const modelNames = new Map(objects(reads.models?.value).map(m => [text(m.model).toLowerCase(), text(m.model)]).filter(([a,b]) => a && b));
+ let nodes;
+ const fresh = reads.engines?.ok && Array.isArray(reads.engines.value);
+ if (fresh) {
+ const cards = objects(stats.engines);
+ nodes = objects(reads.engines.value).slice(0, 256).map((raw,i) => {
+ const matches = cards.filter(c => c.engine === raw.name);
+ const normalized = normalizeNode(matches.length === 1 ? { ...matches[0], ...raw } : raw, config.mode, modelNames, i);
+ return { ...normalized, observedAt, stale: false };
+ });
+ // A missing engine remains visible briefly as offline. Do not invent ongoing traffic after it left.
+ const ids = new Set(nodes.map(n => n.id));
+ for (const node of previous?.nodes || []) if (!ids.has(node.id) && Date.parse(observedAt) - Date.parse(node.observedAt) < 10 * 60_000) nodes.push({ ...node, online: false, activeRequests: null, stale: false });
+ } else {
+ nodes = (previous?.nodes || []).map(n => ({ ...n, stale: true }));
+ if (reads.engines?.ok) sources.engines = { ok: false, error: 'Grid returned an unexpected engine list.', observedAt };
+ }
+ // An id is a node identity, not a display label. Keep duplicate names independently inspectable.
+ const seen = new Map();
+ nodes = nodes.map(n => { const count = seen.get(n.id) || 0; seen.set(n.id, count + 1); return count ? { ...n, id: `${n.id}-${count}` } : n; });
+ const online = nodes.filter(n => n.online === true && !n.stale);
+ const modelIds = unique(online.flatMap(n => n.models));
+ const models = modelIds.map(id => ({ id, nodes: online.filter(n => n.models.includes(id)).map(n => n.id) }));
+ const history = Object.fromEntries(nodes.map(n => {
+ const samples = [...(previous?.history?.[n.id] || [])].filter(s => Date.parse(observedAt) - Date.parse(s.at) < 15 * 60_000);
+ if (fresh && n.online === true) samples.push({ at: observedAt, tokS: n.tokS, temperatureC: n.temperatureC, utilizationPct: n.utilizationPct, memoryUsedGb: n.memoryUsedGb, powerW: n.powerW });
+ return [n.id, samples.slice(-90)];
+ }));
+ const events = [...(previous?.events || [])];
+ const addEvent = (kind, message, nodeId) => events.unshift({ id: `${observedAt}:${kind}:${nodeId}`, at: observedAt, kind, message, nodeId });
+ if (fresh) for (const n of nodes) {
+ const old = previous?.nodes?.find(p => p.id === n.id);
+ if ((!old || old.online !== true) && n.online === true) addEvent('online', `${n.name} joined the grid`, n.id);
+ if (old?.online === true && n.online === false) addEvent('offline', `${n.name} is no longer serving`, n.id);
+ if (old && n.online === true && JSON.stringify(old.models) !== JSON.stringify(n.models)) addEvent('models', `${n.name} updated its models`, n.id);
+ }
+ return {
+ spec: 1, scope, observedAt, mode: config.mode, grid: text(info.grid || stats.grid || config.grid) || 'Your grid', endpoint: safeUrl(info.grid_url),
+ status: !fresh ? 'unavailable' : Object.values(sources).some(s => !s.ok) ? 'partial' : 'live',
+ sources, nodes, models, history, events: events.slice(0, 40),
+ summary: { enginesOnline: online.length, enginesKnown: nodes.length, modelsServing: models.length, answered: normalizeAnswered(stats.answered), uptimePct: number(stats.uptime_pct), concurrency: number(stats.parallel), activeRequests: online.length && online.every(n => n.activeRequests !== null) ? online.reduce((sum,n) => sum + n.activeRequests, 0) : null },
+ preferences: config.preferences,
+ };
+}
+
+export function createCollector(workspace, { runJson = gridJson, intervalMs = 8000 } = {}) {
+ let inFlight, deviceCache = new Map(), previous;
+ async function collect() {
+ const config = await readConfig(workspace);
+ if (!config.grid) {
+ const observedAt=now(),message='Choose a grid with fleet connect --mode local|remote --grid NAME. No fleet has been selected for this workspace.';
+ const snapshot={spec:1,scope:JSON.stringify([config.mode,config.grid,config.controller]),observedAt,mode:config.mode,grid:'Choose your grid',status:'unconfigured',nodes:[],models:[],machines:[],history:{},events:[],operations:[],sources:{configuration:{ok:false,error:message,observedAt}},summary:{},preferences:config.preferences,pollIntervalMs:intervalMs};
+ await atomicJson(join(stateDir(workspace),'snapshot.json'),snapshot);
+ await atomicJson(join(workspace,'.harness','verdict.json'),{spec:1,ready:false,summary:'Choose a grid to connect your fleet',findings:[],updatedAt:observedAt});
+ previous=snapshot;return snapshot;
+ }
+ const controller = config.machines.find(m => m.id === config.controller);
+ const selector = config.grid ? [config.grid] : [];
+ const names = ['info', 'engines', 'models', ...(config.mode === 'remote' ? ['stats'] : [])];
+ const results = await Promise.allSettled(names.map(command => runJson(controller, config.mode, [command, ...selector])));
+ const reads = Object.fromEntries(results.map((result,i) => [names[i], result.status === 'fulfilled' ? result.value : { ok: false, error: `grid ${names[i]} could not be read.` }]));
+ previous ||= await readJson(join(stateDir(workspace), 'snapshot.json'), null).catch(() => null);
+ const observedAt = now();
+ const snapshot = assemble(config, reads, previous, observedAt);
+ snapshot.machines = await Promise.all(config.machines.map(async machine => {
+ const cacheKey = JSON.stringify(machine);
+ let cached = deviceCache.get(cacheKey);
+ if (!cached || Date.now() - cached.fetchedAt > 60_000) {
+ const result = await runJson(machine, config.mode, ['device-info']).catch(() => ({ ok: false, error: 'Machine did not answer.' }));
+ cached = { fetchedAt: Date.now(), result }; deviceCache.set(cacheKey, cached);
+ }
+ return cached.result.ok ? { ...normalizeDevice(machine, cached.result.value, new Date(cached.fetchedAt).toISOString()), reachable: true } : { id: machine.id, name: machine.name, transport: machine.transport, reachable: false, error: cached.result.error, observedAt: new Date(cached.fetchedAt).toISOString() };
+ }));
+ // Inventory edits should not retain unbounded old host entries in this long-running process.
+ const activeKeys = new Set(config.machines.map(m => JSON.stringify(m)));
+ for (const k of deviceCache.keys()) if (!activeKeys.has(k)) deviceCache.delete(k);
+ snapshot.operations = await operations(workspace);
+ snapshot.pollIntervalMs = intervalMs;
+ await atomicJson(join(stateDir(workspace), 'snapshot.json'), snapshot);
+ const failures = Object.entries(snapshot.sources).filter(([,s]) => !s.ok);
+ await atomicJson(join(workspace, '.harness', 'verdict.json'), {
+ spec: 1, ready: snapshot.status !== 'unavailable',
+ summary: snapshot.status === 'unavailable' ? 'Grid unavailable · ask the agent to connect your fleet' : `${snapshot.summary.enginesOnline} engines online · ${snapshot.summary.modelsServing} models serving${snapshot.status === 'partial' ? ' · partial telemetry' : ''}`,
+ findings: failures.map(([kind,s]) => ({ severity: kind === 'engines' ? 'error' : 'warning', kind, message: s.error })),
+ phases: [{ id: 'connect', name: 'Connect', state: snapshot.status === 'unavailable' ? 'active' : 'done' }, { id: 'observe', name: 'Observe', state: snapshot.status === 'unavailable' ? 'pending' : 'active' }], updatedAt: observedAt,
+ });
+ previous = snapshot;
+ return snapshot;
+ }
+ return () => inFlight ||= collect().finally(() => { inFlight = null; });
+}
diff --git a/store/agents/autonomous-grid/package.json b/store/agents/autonomous-grid/package.json
new file mode 100644
index 000000000..bfc1790f0
--- /dev/null
+++ b/store/agents/autonomous-grid/package.json
@@ -0,0 +1,11 @@
+{
+ "name": "@autonomous/grid-harness",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "test": "node --test test/*.test.mjs",
+ "test:live": "node test/live.mjs",
+ "start": "./viewer.sh"
+ },
+ "engines": { "node": ">=22" }
+}
diff --git a/store/agents/autonomous-grid/screenshots/grid-topology.png b/store/agents/autonomous-grid/screenshots/grid-topology.png
new file mode 100644
index 000000000..a00364ca7
Binary files /dev/null and b/store/agents/autonomous-grid/screenshots/grid-topology.png differ
diff --git a/store/agents/autonomous-grid/skills/grid-operations/SKILL.md b/store/agents/autonomous-grid/skills/grid-operations/SKILL.md
new file mode 100644
index 000000000..ab63b60e2
--- /dev/null
+++ b/store/agents/autonomous-grid/skills/grid-operations/SKILL.md
@@ -0,0 +1,140 @@
+---
+name: grid-operations
+description: "Operate a Grid fleet from this harness workspace: discover capacity, deploy and undeploy open-weight models, compare placement and performance, and use Grid routing, usage, media and training commands."
+---
+
+# Grid operations
+
+`$GRID_FLEET` and `$GRID_CLI` are executable paths, not directories. Quote them. Start with
+`"$GRID_FLEET" config` and `"$GRID_FLEET" status`. `status` reads the viewer's published snapshot
+without opening a socket or launching Grid. Check `fresh`, `status` and `observedAt`; use fresh live
+observations to answer ordinary inventory questions. A downloaded weight file or a catalog entry
+is not a serving model. The viewer reads actual CLI data, and the
+runner records operation start/completion without recording prompts, credentials or full argv.
+
+In a restricted agent sandbox, `refresh`, `connect`, `discover` and network-using `run` commands
+require the engine's normal scoped network approval. Request it before calling them rather than
+repeating commands that fail with EPERM. This also applies to the loopback Harness bridge. Do not
+disable the sandbox or broaden global permissions. A denied network call does not prove a host is
+offline; use fresh viewer observations or an approved live check.
+
+## Targets and access
+
+`grid-fleet.json` holds the mode (`local` or `remote`), grid selector, controller machine, managed
+machines and user preferences. A null grid means the workspace is not connected; the viewer must not
+fall through to an old CLI default. Fresh workspaces reuse the remembered fleet, then a reachable
+active Grid selection; ambiguous choices remain explicit. Connect with
+`"$GRID_FLEET" connect --mode remote --grid NAME --remember` to select a verified grid and reuse it
+in future workspaces. `--remember` writes this controller's `~/.harness/grid-fleet/default.json`;
+existing workspace selections remain independent. Changing this workspace's mode never requires
+changing Grid's global mode.
+
+The default machine is this computer. Use `"$GRID_FLEET" discover` to list the user's Harness machines,
+and `discover --add` to add them when fleet management is requested. Paired Harness links need no SSH
+setup; the runner checks the target's Grid fleet protocol before any command. An older Harness must
+be updated before this transport works. An offline or unlinked machine stays unavailable.
+Alternatively, add a known SSH target using an established SSH config alias
+or `user@host`; do not infer SSH access from a display name in Grid. Grid lists serving engines,
+which are not necessarily distinct physical machines. See [fleet configuration](references/fleet.md).
+An engine can be observed through the relay without having permission or a transport to administer its host.
+
+```sh
+"$GRID_FLEET" run -- ls --json
+"$GRID_FLEET" run -- engines GRID --json
+"$GRID_FLEET" run --machine MACHINE -- device-info --json
+"$GRID_FLEET" run --machine MACHINE -- catalog --json
+```
+
+`run` passes every argument after `--` to the real Grid CLI and applies the workspace's mode.
+It supports Grid's entire CLI, including nested commands. Local and SSH execution accept interactive
+input; Harness transport is noninteractive, so sign-in prompts belong in that machine's terminal. The controller is
+the default execution machine. Model files and `join`/`leave` operations belong on the machine
+that runs the engine; listing, routing and requests can run on the controller.
+
+## Deploy and verify
+
+1. Inspect capacity and current workloads on the intended host. Use **per-machine available memory**,
+ Grid's usable model budget, disk space, model size/quantization, context/KV cache, and the user's
+ `keepFreeMemoryGb`. Do not add multiple machines' memory to claim a model fits. Prefer a smaller
+ model or supported quantization when headroom is tight.
+2. Use the installed CLI's `--help` for current flags. Discover weights through `catalog --json`, or
+ verify an exact Hugging Face repository/file. Check the model card's license and capabilities when
+ selecting a new model. Describe downloads and intended placement within the user's stated scope.
+3. Install an engine if needed, pull an explicit file, then join the intended grid. Give each served
+ instance a unique, recognizable `--name` and `--advertise-as`. Use explicit ports when several
+ instances share a host. Local hosts join using the controller's reachable grid URL.
+
+Choose a reasoning budget deliberately. Grid's GPU default can spend more tokens thinking than a
+small output limit permits, yielding no final answer. For an everyday low-latency assistant, start
+with `fleet run --thinking off -- join ... --reasoning-budget 0`. `--thinking off` sets llama.cpp's
+`enable_thinking:false` template parameter for the newly started engine; it is needed on builds
+where a zero token budget alone still produces reasoning. Use `--thinking on` to enable a supported
+model's thinking explicitly. These switches configure startup, not an already running instance.
+For a reasoning model, reserve an explicit budget smaller than
+`--n-predict`, leaving room for the answer. Verify `message.content` contains the requested result;
+reasoning text alone, a length-limited completion, or a successful HTTP status is not acceptance.
+
+```sh
+"$GRID_FLEET" run --machine MACHINE -- engine install llama.cpp
+"$GRID_FLEET" run --machine MACHINE -- pull OWNER/REPO:EXACT_FILE.gguf
+"$GRID_FLEET" run --machine MACHINE -- join GRID_URL_OR_ID --serve EXACT_FILE.gguf --name MACHINE-MODEL --advertise-as MODEL_ALIAS --endpoint-port PORT
+"$GRID_FLEET" run -- models GRID --json
+"$GRID_FLEET" run -- chat --grid GRID -m MODEL_ALIAS "A short representative test" --json
+"$GRID_FLEET" refresh
+```
+
+An existing Ollama, vLLM, MLX or LM Studio engine can join with `--at URL -m MODEL --name NAME`.
+Use `join --help` to choose the appropriate engine flags. Do not install a second engine needlessly.
+A successful `join` may mean **starting**, not ready: poll `models` and send a real request before
+reporting that the model works. For a bounded retry, wait up to the loading deadline warranted by
+the model's size, inspect Grid's named logs on failure, and report the concrete blocker.
+
+For remote Grid, `--parallel N` reserves llama.cpp slots, while `--max-concurrency N` separately
+controls how many requests Grid dispatches. Set both deliberately for concurrent service, and verify
+the advertised concurrency. `--ctx-size` is per request, so reserved context memory grows with the
+slot count. Raising concurrency needs a new serving process and a representative concurrent test.
+
+## Undeploy and move
+
+`leave GRID --engine SELECTOR` on the serving machine stops/unregisters that instance. Match an
+exact unique engine identity from `engines` first. `leave --all` affects other workloads; use it only
+for a user-requested whole-grid teardown. `rm MODEL --yes` deletes downloaded weights and is a
+different action from undeploying; retain files unless deletion is requested.
+
+Verify the engine disappears from discovery after `leave`, with bounded polling. Local Grid can retain
+a stopped engine until its 60-second heartbeat TTL expires; remote grids have their own convergence
+delay. A successful exit alone is not proof of removal. If it persists beyond the deadline, inspect
+the named process/logs and report a failed or incomplete undeployment, not a successful one.
+
+For a move: verify the destination can answer the same model alias, check whether the source has
+active work when that telemetry exists, then remove the source instance and verify routing again.
+Do not promise seamless draining or conversation migration: the CLI does not guarantee either.
+If the destination fails, keep the source serving. Keep a rollback command in the plan.
+
+## Placement and model discovery
+
+Use user needs (latency, coding quality, vision, privacy, power, quiet hours, concurrency) to compare
+placements. `stats GRID --verbose --json` and `usage GRID --by model --json` are remote-grid reads.
+Local grids expose a smaller surface; `device-info` gives hardware inventory, not a complete live
+GPU sensor feed. Missing sensor values cannot justify moving a workload.
+
+`throughput_tok_s` is the last measured decode estimate for one engine. Do not sum engines' rates
+or present it as a simultaneous fleet benchmark. Compare candidates using the same representative
+task and context; preserve the observed timings, output and model/quantization in `plans/`.
+
+The shipped catalog is curated, not a live feed of every new release. For newly released models,
+check primary model cards/release sources and offer a measured trial. Automatic replacement needs
+the user's explicit standing policy (`allowAutomaticChanges` plus a concrete scope); a suggestion
+does not authorize an unrequested fleet-wide upgrade. Existing authorization for a deployment or
+move is enough to carry it through without asking again.
+
+## The rest of Grid
+
+Use `"$GRID_FLEET" run -- --help`, then a command's `--help`, to discover the installed surface.
+See [command routes](references/commands.md) for the main families. Routing, training, media,
+projects and agents are available through the same runner. Do not change credentials, memberships,
+pricing, external API billing or training jobs as a side effect of an ordinary local deployment.
+
+Keep failures visible. A timeout or dropped SSH session leaves the remote result uncertain; inspect
+the engine before retrying a mutation. Exit zero and the operation record alone do not prove service
+health: verify through `engines`, `models` and an actual request.
diff --git a/store/agents/autonomous-grid/skills/grid-operations/references/commands.md b/store/agents/autonomous-grid/skills/grid-operations/references/commands.md
new file mode 100644
index 000000000..d0504e015
--- /dev/null
+++ b/store/agents/autonomous-grid/skills/grid-operations/references/commands.md
@@ -0,0 +1,25 @@
+# Command routes
+
+Always check the selected CLI's help before unfamiliar operations. All commands use
+`"$GRID_FLEET" run [--machine ID] -- ...`. Grid's current reference is
+https://github.com/autonomous-ai/autonomous-grid/blob/main/docs/cli.md.
+
+| Need | Grid commands |
+|---|---|
+| Lifecycle and selection | `start`, `stop`, `delete`, `ls`, `info`, `use`, `mode` |
+| Host inventory | `device-info --json` |
+| Model discovery and weights | `catalog --json`, `pull REPO:FILE`, `ctx FILE --json`, `rm FILE` |
+| Engine provisioning | `engine install`, `engine pull`, `engine start`, `engine status`, `engine stop` |
+| Serving and removal | `join`, `leave --engine SELECTOR`, `engines --json`, `models --json` |
+| Inference checks | `chat`, `image`, `edit`, `video`, `stt` |
+| Remote telemetry | `stats --verbose --json`, `usage --by model|member|engine --json` |
+| Remote request routing | `router --help` (inspect before changing policies or advisors) |
+| Training and evaluation | `train --help`, `train doctor`, `train packs`, `train eval`, `train deploy` |
+| Apps and coding agents | `agent --help`, `launch --help` |
+| Projects and tasks | `project --help`, `task --help` |
+| Remote account administration | `login`, `sync`, `members`, `price`, `credential`, `logout` |
+
+The wrapper never limits Grid to this table; new subcommands pass through unchanged. A command's
+availability depends on the installed Grid version and current mode. `stats`/`usage` need remote
+mode and a reachable grid; media and training need their own engines, models and hardware. A test
+of help text proves forwarding, not that those workloads or remote services were exercised.
diff --git a/store/agents/autonomous-grid/skills/grid-operations/references/fleet.md b/store/agents/autonomous-grid/skills/grid-operations/references/fleet.md
new file mode 100644
index 000000000..7a5d3b1e6
--- /dev/null
+++ b/store/agents/autonomous-grid/skills/grid-operations/references/fleet.md
@@ -0,0 +1,52 @@
+# Fleet configuration
+
+The viewer polls the controller's selected grid and collects `device-info` on each managed host.
+Remote telemetry can include engines on machines absent from this inventory. Those engines
+are observable, but the agent needs a configured route before administering their host.
+
+```json
+{
+ "spec": 1,
+ "mode": "remote",
+ "grid": "my-grid-id",
+ "controller": "local",
+ "machines": [
+ { "id": "local", "name": "My laptop", "transport": "local" },
+ { "id": "linked-rig", "name": "Linked GPU rig", "transport": "harness", "machineId": "MACHINE_ID_FROM_DISCOVER" },
+ { "id": "studio", "name": "Mac Studio", "transport": "ssh", "host": "studio" },
+ { "id": "gpu", "name": "GPU workstation", "transport": "ssh", "host": "me@gpu-box", "port": 22 }
+ ],
+ "preferences": {
+ "goal": "Fast coding on the workstation, quiet chat on the Studio",
+ "keepFreeMemoryGb": 8,
+ "allowAutomaticChanges": false
+ }
+}
+```
+
+Harness targets use the exact machine ID returned by `fleet discover`, the local Harness daemon,
+and the existing encrypted machine pairing. `fleet discover --add` preserves configured targets and
+adds the rest. Both daemons must support Grid fleet protocol 1. It never copies credentials or
+changes trust. Target runtime and Grid home belong to the target daemon, with no path overrides.
+
+SSH uses the user's existing config, keys, agent and known_hosts, with strict host-key checking and
+noninteractive authentication. Establish new host trust through the user's normal SSH workflow;
+do not disable host verification or embed passwords in this file. Both local and SSH machines may
+set absolute `gridBinary` and `gridHome` paths when deliberately selecting an alternate runtime or
+isolated environment. Otherwise, the managed Harness Grid runtime takes precedence over PATH.
+
+`fleet connect --mode local|remote --grid NAME` verifies the selected grid before writing its mode
+and selector. Add `--remember` to save this fleet for newly created workspaces on the controller;
+it does not change Grid's global selection or overwrite existing workspace choices. A null selector
+is an unconfigured workspace, not an instruction to connect to a stale default.
+
+Run `"$GRID_FLEET" config` after editing to validate it, then an approved `refresh`. `fleet status`
+reads the viewer's already-published telemetry without a network request and marks old observations
+as stale. A dropped machine reports
+unreachable without blanking the others. Node identity is separate from its display name. The
+viewer calls them engines because multiple instances can share one physical host.
+
+Snapshots live in `.harness/grid/snapshot.json`, with at most 90 recent samples per engine and
+40 displayed fleet events. `.harness/grid/operations/` contains one small record per command;
+the viewer displays the latest 40. Records intentionally omit full arguments and command output.
+These are observations, not a source of desired deployment state.
diff --git a/store/agents/autonomous-grid/store.json b/store/agents/autonomous-grid/store.json
new file mode 100644
index 000000000..3894f8b3c
--- /dev/null
+++ b/store/agents/autonomous-grid/store.json
@@ -0,0 +1,8 @@
+{
+ "homepage": "https://github.com/autonomous-ai/autonomous-grid",
+ "upstream": "https://github.com/autonomous-ai/autonomous-grid",
+ "license": "MIT",
+ "screenshots": [
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/agents/autonomous-grid/screenshots/grid-topology.png"
+ ]
+}
diff --git a/store/agents/autonomous-grid/template/grid-fleet.json b/store/agents/autonomous-grid/template/grid-fleet.json
new file mode 100644
index 000000000..90b2122a9
--- /dev/null
+++ b/store/agents/autonomous-grid/template/grid-fleet.json
@@ -0,0 +1,13 @@
+{
+ "spec": 1,
+ "mode": "local",
+ "grid": null,
+ "machines": [
+ { "id": "local", "name": "This machine", "transport": "local" }
+ ],
+ "preferences": {
+ "goal": "Run useful models on the machines I own",
+ "keepFreeMemoryGb": 4,
+ "allowAutomaticChanges": false
+ }
+}
diff --git a/store/agents/autonomous-grid/test/browser.mjs b/store/agents/autonomous-grid/test/browser.mjs
new file mode 100644
index 000000000..0bb7e12d9
--- /dev/null
+++ b/store/agents/autonomous-grid/test/browser.mjs
@@ -0,0 +1,52 @@
+// Visual/interaction QA against the real viewer, with an explicitly labelled telemetry fixture.
+// GRID_TEST_PLAYWRIGHT is the path to an installed Playwright entrypoint; no shipped browser dependency.
+import assert from 'node:assert/strict';
+import { mkdir, mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { createViewer } from '../viewer.mjs';
+import { assemble, normalizeDevice } from '../lib/telemetry.mjs';
+import { config, device, reads } from './fixtures.mjs';
+
+if(!process.env.GRID_TEST_PLAYWRIGHT)throw new Error('Set GRID_TEST_PLAYWRIGHT to an installed Playwright entrypoint.');
+const {chromium}=await import(pathToFileURL(process.env.GRID_TEST_PLAYWRIGHT).href);
+const workspace=await mkdtemp(join(tmpdir(),'grid-browser-'));
+const output=resolve(process.env.GRID_TEST_OUTPUT || workspace);await mkdir(output,{recursive:true});
+let fixture;
+for(let i=0;i<30;i++)fixture=assemble(config,reads,fixture,new Date(Date.now()-(29-i)*8000).toISOString());
+fixture.grid='Home lab · test fixture';fixture.machines=[{...normalizeDevice(config.machines[0],device,new Date().toISOString()),reachable:true}];fixture.operations=[];
+const viewer=createViewer({workspace,intervalMs:200,collect:async()=>fixture});
+const port=await viewer.start();
+const browser=await chromium.launch({headless:true,...(process.env.GRID_TEST_BROWSER?{executablePath:process.env.GRID_TEST_BROWSER}:{})});
+try{
+ const page=await browser.newPage({viewport:{width:1440,height:1100},deviceScaleFactor:1});
+ const errors=[];page.on('pageerror',e=>errors.push(e.message));
+ await page.goto(`http://127.0.0.1:${port}`);await page.locator('.node').first().waitFor();await page.waitForTimeout(300);
+ assert.equal(await page.locator('.node').count(),8);
+ await page.screenshot({path:join(output,'grid-topology.png'),fullPage:true});
+ await page.locator('.node').filter({hasText:'GPU workstation'}).click();await page.locator('.inspector h2').filter({hasText:'GPU workstation'}).waitFor();
+ assert.match(await page.locator('.inspector').innerText(),/109\.4/);assert.match(await page.locator('.inspector').innerText(),/67/);
+ await page.screenshot({path:join(output,'grid-engine.png'),fullPage:true});
+ await page.selectOption('#metric','temperatureC');assert.match(await page.locator('.node').filter({hasText:'GPU workstation'}).innerText(),/67/);
+ await page.click('#rack-button');assert.equal(await page.locator('.rack-engine').count(),8);assert.equal(await page.locator('#topology').isVisible(),false);
+ await page.screenshot({path:join(output,'grid-rack.png'),fullPage:true});
+ await page.click('#topology-button');await page.click('#motion');assert.equal(await page.locator('#motion').innerText(),'Resume motion');
+ const overlaps=[];
+ for(const size of [1440,1024,820,736,540,390,320]){
+ await page.setViewportSize({width:size,height:1100});await page.waitForTimeout(150);
+ const layout=await page.evaluate(()=>{
+ const nodes=[...document.querySelectorAll('.node')].map(n=>({name:n.querySelector('.node-name').textContent,r:n.getBoundingClientRect()}));
+ const collisions=[];
+ for(let i=0;i<nodes.length;i++)for(let j=i+1;j<nodes.length;j++){const a=nodes[i].r,b=nodes[j].r;if(a.left<b.right&&a.right>b.left&&a.top<b.bottom&&a.bottom>b.top)collisions.push([nodes[i].name,nodes[j].name]);}
+ return {overflow:document.documentElement.scrollWidth>innerWidth,collisions};
+ });
+ assert.equal(layout.overflow,false,`horizontal overflow at ${size}`);if(layout.collisions.length)overlaps.push({width:size,collisions:layout.collisions});
+ if(size===390)await page.screenshot({path:join(output,'grid-mobile.png'),fullPage:true});
+ }
+ assert.deepEqual(overlaps,[],'machine cards overlap');
+ fixture={...fixture,status:'unavailable',nodes:fixture.nodes.map(n=>({...n,stale:true})),sources:{engines:{ok:false,error:'Test connection interrupted'}}};
+ await page.waitForFunction(()=>document.getElementById('connection-label').textContent==='Grid unavailable');
+ assert.equal(await page.locator('.node.stale').count(),8);
+ assert.deepEqual(errors,[]);console.log(JSON.stringify({result:'passed',widths:[1440,1024,820,736,540,390,320],checks:['topology','engine inspector','metric switch','rack view','pause motion','no overlap','no horizontal overflow','stale telemetry'],output},null,2));
+}finally{await browser.close();await viewer.close();await rm(workspace,{recursive:true,force:true});}
diff --git a/store/agents/autonomous-grid/test/connect.test.mjs b/store/agents/autonomous-grid/test/connect.test.mjs
new file mode 100644
index 000000000..95bc4e654
--- /dev/null
+++ b/store/agents/autonomous-grid/test/connect.test.mjs
@@ -0,0 +1,69 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { connectWorkspace, initializeWorkspace, readStatus } from '../lib/connect.mjs';
+import { atomicJson, DEFAULT_CONFIG, gridJson, readConfig } from '../lib/fleet.mjs';
+import { createCollector } from '../lib/telemetry.mjs';
+
+async function setup(t, config=DEFAULT_CONFIG) {
+ const dir=await mkdtemp(join(tmpdir(),'grid-startup-'));t.after(()=>rm(dir,{recursive:true,force:true}));
+ await atomicJson(join(dir,'grid-fleet.json'),config);
+ return {dir,profilePath:join(dir,'defaults.json')};
+}
+const discover=async()=>[{id:'host-id',machineId:'host-id',name:'This computer',transport:'local',current:true},{id:'gpu-id',machineId:'gpu-id',name:'GPU rig',transport:'harness'}];
+test('a fresh workspace reuses the remembered remote fleet and imports machines',async t=>{
+ const {dir,profilePath}=await setup(t);
+ await atomicJson(profilePath,{...DEFAULT_CONFIG,mode:'remote',grid:'working-fleet'});
+ const result=await initializeWorkspace(dir,{profilePath,discover,runJson:async()=>{throw new Error('must not choose a different CLI default');}});
+ assert.equal(result.config.grid,'working-fleet');assert.equal(result.config.mode,'remote');assert.equal(result.config.machines.length,2);
+ assert.equal(result.config.controller,'local');assert.equal(result.config.machines[0].name,'This computer');
+ assert.equal(result.connection.source,'remembered fleet');
+});
+test('fresh initialization follows a reachable active remote selection, not the template local mode',async t=>{
+ const {dir,profilePath}=await setup(t),calls=[];
+ const runJson=async(_host,mode,args)=>{calls.push([mode,...args]);return {ok:true,value:args[0]==='mode'?{mode:'remote'}:args[0]==='use'?{active:'my-fleet'}:[]};};
+ const {config}=await initializeWorkspace(dir,{profilePath,discover,runJson});
+ assert.equal(config.mode,'remote');assert.equal(config.grid,'my-fleet');
+ assert.deepEqual(calls,[['local','mode'],['remote','use'],['remote','engines','my-fleet']]);
+});
+test('an unreachable active grid and ambiguous inventory never silently select old home',async t=>{
+ const {dir,profilePath}=await setup(t);
+ const runJson=async(_host,mode,args)=>args[0]==='mode'?{ok:true,value:{mode:'remote'}}:args[0]==='use'?{ok:true,value:{active:'broken'}}:args[0]==='engines'?{ok:false,error:'unreachable'}:{ok:true,value:mode==='local'?[{grid:'home'}]:[{grid:'working'},{grid:'other'}]};
+ const result=await initializeWorkspace(dir,{profilePath,discover,runJson});
+ assert.equal(result.config.grid,null);assert.equal(result.connection.candidates.length,3);
+ let calls=0;const snapshot=await createCollector(dir,{runJson:async()=>{calls++;throw new Error('do not contact a default grid');}})();
+ assert.equal(calls,0);assert.equal(snapshot.status,'unconfigured');assert.deepEqual(snapshot.nodes,[]);
+});
+test('an existing explicit workspace keeps its selection and preferences',async t=>{
+ const {dir,profilePath}=await setup(t,{...DEFAULT_CONFIG,grid:'isolated-local',preferences:{...DEFAULT_CONFIG.preferences,keepFreeMemoryGb:12}});
+ await atomicJson(profilePath,{...DEFAULT_CONFIG,mode:'remote',grid:'different'});
+ const {config}=await initializeWorkspace(dir,{profilePath,discover:async()=>[],runJson:async()=>{throw new Error('must not rediscover');}});
+ assert.equal(config.grid,'isolated-local');assert.equal(config.mode,'local');assert.equal(config.preferences.keepFreeMemoryGb,12);
+});
+test('connect verifies service before changing workspace or remembered defaults',async t=>{
+ const {dir,profilePath}=await setup(t);
+ const fail={profilePath,discover,runJson:async()=>({ok:false,error:'Grid unreachable'})};
+ await assert.rejects(connectWorkspace(dir,{mode:'remote',grid:'broken',remember:true},fail),/unreachable/);
+ assert.equal((await readConfig(dir)).grid,null);await assert.rejects(readFile(profilePath),{code:'ENOENT'});
+ const ok={...fail,runJson:async()=>({ok:true,value:[{name:'node',api_key:'must-not-save'}]})};
+ await connectWorkspace(dir,{mode:'remote',grid:'working',remember:true},ok);
+ assert.equal((await readConfig(dir)).grid,'working');assert.equal(JSON.parse(await readFile(profilePath)).machines.length,2);
+ assert.doesNotMatch(await readFile(profilePath,'utf8'),/must-not-save|api_key/);
+});
+test('status reads the viewer observation without network and distinguishes fresh, stale and another grid',async t=>{
+ const {dir}=await setup(t,{...DEFAULT_CONFIG,mode:'remote',grid:'working'}),time=Date.now();
+ const snapshot={spec:1,scope:JSON.stringify(['remote','working','local']),status:'live',grid:'working',mode:'remote',observedAt:new Date(time).toISOString(),models:[{id:'running-model'}],nodes:[{name:'node',online:true,stale:false}],history:{privateHistory:[]}};
+ await atomicJson(join(dir,'.harness/grid/snapshot.json'),snapshot);
+ const fresh=await readStatus(dir,time+5000);assert.equal(fresh.fresh,true);assert.equal(fresh.status,'live');assert.equal(fresh.models[0].id,'running-model');assert.equal('history' in fresh,false);
+ const stale=await readStatus(dir,time+45000);assert.equal(stale.fresh,false);assert.equal(stale.status,'stale');assert.equal(stale.nodes[0].stale,true);
+ await atomicJson(join(dir,'grid-fleet.json'),{...DEFAULT_CONFIG,grid:'different'});
+ const different=await readStatus(dir,time);assert.equal(different.status,'connecting');assert.deepEqual(different.models,[]);
+});
+test('Grid network denials explain the approval boundary rather than claiming a dead engine',async t=>{
+ const {dir}=await setup(t),file=join(dir,'grid');
+ await writeFile(file,'#!/bin/sh\necho "Could not reach grid home: [Errno 1] Operation not permitted"\nexit 1\n',{mode:0o755});
+ const result=await gridJson({transport:'local',gridBinary:file},'local',['models','home']);
+ assert.equal(result.ok,false);assert.match(result.error,/scoped network approval/);assert.match(result.error,/fleet status/);
+});
diff --git a/store/agents/autonomous-grid/test/fixtures.mjs b/store/agents/autonomous-grid/test/fixtures.mjs
new file mode 100644
index 000000000..89752e360
--- /dev/null
+++ b/store/agents/autonomous-grid/test/fixtures.mjs
@@ -0,0 +1,19 @@
+// Explicit test data, never a fallback used by the shipped viewer.
+export const config = { spec:1, mode:'remote', grid:'test-grid', controller:'local', machines:[{id:'local',name:'Test workstation',transport:'local'}], preferences:{goal:'Coding and quiet chat',keepFreeMemoryGb:8,allowAutomaticChanges:false} };
+export const remoteNodes = [
+ { node_id:'studio-a',name:'Mac Studio',engine:'llama.cpp',chip:'Apple M4 Max',platform:'macos-arm64',online:true,models:['qwen3.5-27b'],vram_gb:64,vram_used_mb:32768,gpu_temp_c:null,gpu_util_pct:73,gpu_power_w:62,throughput_tok_s:42.8,disk_total_gb:1000,disk_used_gb:482,max_concurrency:4,answered:{window_seconds:86400,tokens_in:120000,tokens_cached:22000,tokens_out:46000,requests:218},model_capabilities:{'qwen3.5-27b':{context_length:32768}} },
+ { node_id:'rtx-a',name:'GPU workstation',engine:'vllm',chip:'NVIDIA RTX 4090',platform:'linux-x86_64',online:true,models:['qwen3.5-9b'],vram_gb:24,vram_used_mb:15155,gpu_temp_c:67,gpu_util_pct:86,gpu_power_w:274,gpu_power_limit_w:450,throughput_tok_s:109.4,disk_total_gb:2000,disk_used_gb:1142,max_concurrency:8 },
+ { node_id:'mini-a',name:'Mac mini',engine:'mlx',chip:'Apple M4 Pro',platform:'macos-arm64',online:true,models:['gemma-3-4b'],vram_gb:24,vram_used_mb:6042,gpu_util_pct:28,throughput_tok_s:51.6,max_concurrency:2 },
+ { node_id:'laptop-a',name:'MacBook Pro',engine:'llama.cpp',chip:'Apple M3 Pro',platform:'macos-arm64',online:true,models:['qwen2.5-coder-7b'],vram_gb:36,vram_used_mb:8320,gpu_util_pct:11,throughput_tok_s:27.3,max_concurrency:1 },
+ { node_id:'a6000-a',name:'Inference server',engine:'vllm',chip:'NVIDIA RTX A6000',platform:'linux-x86_64',online:true,models:['qwen3.5-27b'],vram_gb:48,vram_used_mb:34201,gpu_temp_c:72,gpu_util_pct:93,gpu_power_w:247,gpu_power_limit_w:300,throughput_tok_s:68.2,max_concurrency:8 },
+ { node_id:'linux-a',name:'Linux box',engine:'llama.cpp',chip:'NVIDIA RTX 3090',platform:'linux-x86_64',online:true,models:['qwen3.5-9b'],vram_gb:24,vram_used_mb:14643,gpu_temp_c:54,gpu_util_pct:47,gpu_power_w:151,throughput_tok_s:72.1,max_concurrency:4 },
+ { node_id:'studio-b',name:'Studio · lab',engine:'mlx',chip:'Apple M3 Ultra',platform:'macos-arm64',online:true,models:['qwen3.5-27b','gemma-3-4b'],vram_gb:96,vram_used_mb:36864,gpu_util_pct:36,throughput_tok_s:61.2,max_concurrency:4 },
+ { node_id:'pro-a',name:'Mac Pro',engine:'llama.cpp',chip:'Apple M2 Ultra',platform:'macos-arm64',online:false,models:['qwen2.5-coder-7b'],vram_gb:128,vram_used_mb:0,gpu_util_pct:0,throughput_tok_s:31.5,max_concurrency:4 },
+];
+export const device = { backend:'metal',machine:{model:'Mac Studio',platform:'macos-arm64'},cpu:{brand:'Apple M4 Max',physical_cores:16,logical_threads:16},memory:{total_gb:64,available_gb:28},disk:{total_gb:1000,free_gb:518},usable_bytes:24*1024**3,gpus:[{name:'Apple M4 Max',memory_total_mb:65536}] };
+export const reads = {
+ info:{ok:true,value:{grid:'Home lab',grid_url:'https://grid.example.test/relay/v1?token=do-not-expose'}},
+ engines:{ok:true,value:remoteNodes},
+ models:{ok:true,value:[{model:'Qwen3.5-27B'},{model:'Qwen3.5-9B'},{model:'Gemma-3-4B'},{model:'Qwen2.5-Coder-7B'}]},
+ stats:{ok:true,value:{answered:{window_seconds:86400,tokens_in:580000,tokens_cached:73000,tokens_out:231840,requests:1482},uptime_pct:99.97,parallel:24}},
+};
diff --git a/store/agents/autonomous-grid/test/fleet.test.mjs b/store/agents/autonomous-grid/test/fleet.test.mjs
new file mode 100644
index 000000000..e9c75eee6
--- /dev/null
+++ b/store/agents/autonomous-grid/test/fleet.test.mjs
@@ -0,0 +1,51 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { atomicJson, DEFAULT_CONFIG, execute, invocation, operations, runTracked, validateConfig } from '../lib/fleet.mjs';
+
+const temporary = async t => { const dir=await mkdtemp(join(tmpdir(),'grid-harness-test-'));t.after(()=>rm(dir,{recursive:true,force:true}));return dir; };
+test('inventory accepts explicit targets and refuses duplicates, SSH options and malformed paths',()=>{
+ const config=validateConfig({...DEFAULT_CONFIG,machines:[{id:'gpu',transport:'ssh',host:'me@gpu-box',port:2222}]});
+ assert.equal(config.controller,'gpu');
+ for(const machines of [[{id:'a',transport:'ssh',host:'-oProxyCommand=evil'}],[{id:'a',transport:'ssh',host:'host; touch /tmp/oops'}],[{id:'a',transport:'local'},{id:'a',transport:'local'}],[{id:'a',transport:'local',gridHome:'relative'}]])assert.throws(()=>validateConfig({...DEFAULT_CONFIG,machines}));
+});
+test('local forwarding preserves quotes, spaces, shell syntax and exit status without evaluating it',async t=>{
+ const dir=await temporary(t),script=join(dir,'record.mjs');
+ await writeFile(script,'console.log(JSON.stringify(process.argv.slice(2)));process.exit(7)');
+ const args=[script,'pull','repo:file with spaces.gguf',"a'b",'$(touch DO_NOT_CREATE)','; exit 0'];
+ const result=await execute({transport:'local',gridBinary:process.execPath},args);
+ assert.equal(result.code,7);assert.equal(result.ok,false);assert.deepEqual(JSON.parse(result.stdout),args.slice(1));
+});
+test('SSH quotes every remote argument and retains normal host verification',()=>{
+ const call=invocation({transport:'ssh',host:'studio',gridHome:"/tmp/grid's state",gridBinary:'/opt/grid bin/grid'},['chat','-m','model','$(touch /tmp/no); "hello"']);
+ assert.equal(call.file,'ssh');assert.ok(call.args.includes('StrictHostKeyChecking=yes'));assert.ok(call.args.includes('BatchMode=yes'));
+ assert.match(call.args.at(-1),/'\$\(touch \/tmp\/no\); "hello"'/);
+ assert.match(call.args.at(-1),/grid'"'"'s state/);
+});
+test('thinking configuration reaches local and SSH engine startup as a fixed JSON boolean',()=>{
+ assert.equal(invocation({transport:'local'},['join'],{},false).env.LLAMA_ARG_CHAT_TEMPLATE_KWARGS,'{"enable_thinking":false}');
+ assert.match(invocation({transport:'ssh',host:'rig'},['join'],{},true).args.at(-1),/LLAMA_ARG_CHAT_TEMPLATE_KWARGS='\{"enable_thinking":true\}'/);
+ assert.equal(invocation({transport:'local'},['join'],{}).env.LLAMA_ARG_CHAT_TEMPLATE_KWARGS,undefined);
+});
+test('timeouts are unsuccessful even when the child handles termination and exits zero',async t=>{
+ const dir=await temporary(t),script=join(dir,'hang.mjs');
+ await writeFile(script,"process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)");
+ const result=await execute({transport:'local',gridBinary:process.execPath},[script],{timeoutMs:200});
+ assert.equal(result.code,124);assert.equal(result.ok,false);assert.match(result.error,/did not answer/);
+});
+test('operation records show completion but never retain model prompts or keys',async t=>{
+ const dir=await temporary(t),script=join(dir,'grid');
+ await writeFile(script,'#!/bin/sh\nexit 3\n',{mode:0o755});
+ const result=await runTracked(dir,{id:'local',transport:'local',gridBinary:script},'local',['chat','-m','test','private-user-prompt','--api-key','private-secret'],{inherit:false});
+ assert.equal(result.code,3);
+ const rows=await operations(dir);assert.equal(rows.length,1);assert.equal(rows[0].phase,'failed');assert.equal(rows[0].command,'grid chat');
+ assert.doesNotMatch(JSON.stringify(rows),/private-/);
+});
+test('invalid and abandoned operation files cannot crash the viewer',async t=>{
+ const dir=await temporary(t);
+ await atomicJson(join(dir,'.harness/grid/operations/a.json'),{id:'a',phase:'running',pid:2147483647,startedAt:'2026-09-18T00:00:00Z'});
+ await atomicJson(join(dir,'.harness/grid/operations/b.json'),{unrelated:true});
+ const rows=await operations(dir);assert.equal(rows.length,1);assert.equal(rows[0].phase,'interrupted');
+});
diff --git a/store/agents/autonomous-grid/test/harness.test.mjs b/store/agents/autonomous-grid/test/harness.test.mjs
new file mode 100644
index 000000000..8968bdc10
--- /dev/null
+++ b/store/agents/autonomous-grid/test/harness.test.mjs
@@ -0,0 +1,85 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { bridgeUrl, harnessExecute } from '../lib/harness.mjs';
+import { validateConfig } from '../lib/fleet.mjs';
+
+function socketClass(respond) {
+ return class FakeSocket extends EventTarget {
+ readyState = 1;
+ constructor(url) { super(); this.url = url; queueMicrotask(() => this.dispatchEvent(new Event('open'))); }
+ send(data) { respond(JSON.parse(data), frame => queueMicrotask(() => this.dispatchEvent(new MessageEvent('message',{data:JSON.stringify(frame)}))), this); }
+ close() { this.readyState=3; this.dispatchEvent(new Event('close')); }
+ };
+}
+const machine={id:'rig',name:'GPU rig',transport:'harness',machineId:'machine-123'};
+test('Harness targets are explicit identities, with no binary overrides or remote bridge URLs',()=>{
+ assert.equal(validateConfig({spec:1,mode:'remote',grid:'home',machines:[machine]}).machines[0].machineId,'machine-123');
+ assert.throws(()=>validateConfig({spec:1,mode:'remote',grid:'home',machines:[{...machine,gridBinary:'/bin/sh'}]}));
+ for(const url of ['wss://example.com/api/local-ws','ws://127.0.0.1/elsewhere','ws://user:[email protected]/api/local-ws']) assert.throws(()=>bridgeUrl({HARNESS_GRID_BRIDGE_URL:url}));
+});
+test('connected Harness machine receives exact CLI arguments and its own output',async()=>{
+ let ran=0;const args=['--remote','chat','one; $(literal)','two words'];
+ const WebSocketImpl=socketClass((frame,reply)=>{
+ if(frame.type==='machine_select'){assert.equal(frame.payload.machineId,'machine-123');reply({type:'connected',payload:{relayIsolation:true}});}
+ if(frame.type==='grid_fleet_capabilities')reply({type:frame.type+'_result',payload:{...frame.payload,protocol:1,gridCli:'managed'}});
+ if(frame.type==='grid_fleet_run'){ran++;assert.deepEqual(frame.payload.args,args);reply({type:frame.type+'_result',payload:{requestId:frame.payload.requestId,ok:true,code:0,stdout:'answer',stderr:''}});}
+ });
+ assert.deepEqual(await harnessExecute(machine,args,{WebSocketImpl}),{ok:true,code:0,stdout:'answer',stderr:'',error:null});assert.equal(ran,1);
+});
+test('an older remote daemon fails with an actionable compatibility message before any mutation',async()=>{
+ const WebSocketImpl=socketClass((frame,reply)=>{
+ if(frame.type==='machine_select')reply({type:'connected',payload:{relayIsolation:true}});
+ else if(frame.type==='grid_fleet_capabilities')reply({type:frame.type+'_result',payload:{requestId:frame.payload.requestId,error:'UNSUPPORTED'}});
+ else assert.fail('must not run');
+ });
+ const result=await harnessExecute(machine,['join','home'],{WebSocketImpl});assert.equal(result.ok,false);assert.match(result.error,/Update Harness/);
+});
+test('lost connections do not retry mutations',async()=>{
+ let ran=0;
+ const WebSocketImpl=socketClass((frame,reply,socket)=>{
+ if(frame.type==='machine_select')reply({type:'connected',payload:{relayIsolation:true}});
+ if(frame.type==='grid_fleet_capabilities')reply({type:frame.type+'_result',payload:{requestId:frame.payload.requestId,protocol:1}});
+ if(frame.type==='grid_fleet_run'){ran++;queueMicrotask(()=>socket.close());}
+ });
+ const result=await harnessExecute(machine,['join','home'],{WebSocketImpl});assert.equal(result.code,124);assert.equal(ran,1);assert.match(result.error,/may still be running/);
+});
+test('duplicate connection and capability events cannot replay a deployment',async()=>{
+ let runs=0;
+ const WebSocketImpl=socketClass((frame,reply)=>{
+ if(frame.type==='machine_select'){
+ assert.equal(frame.payload.relayIsolation,true);
+ reply({type:'connected',payload:{relayIsolation:true}});reply({type:'connected',payload:{relayIsolation:true}});
+ }
+ if(frame.type==='grid_fleet_capabilities'){
+ const response={type:frame.type+'_result',payload:{requestId:frame.payload.requestId,protocol:1}};reply(response);reply(response);
+ }
+ if(frame.type==='grid_fleet_run'){runs++;reply({type:frame.type+'_result',payload:{requestId:frame.payload.requestId,ok:true,code:0}});}
+ });
+ assert.equal((await harnessExecute(machine,['join','home'],{WebSocketImpl})).ok,true);assert.equal(runs,1);
+});
+test('an older local bridge cannot share the desktop connection for a fleet command',async()=>{
+ const WebSocketImpl=socketClass((frame,reply)=>{
+ if(frame.type==='machine_select')reply({type:'connected',payload:{}});
+ else assert.fail('no command may run without an isolated connection');
+ });
+ assert.match((await harnessExecute(machine,['join','home'],{WebSocketImpl})).error,/controller/);
+});
+test('thinking controls require remote support before starting the engine',async()=>{
+ let runs=0;
+ const WebSocketImpl=socketClass((frame,reply)=>{
+ if(frame.type==='machine_select')reply({type:'connected',payload:{relayIsolation:true}});
+ if(frame.type==='grid_fleet_capabilities')reply({type:frame.type+'_result',payload:{requestId:frame.payload.requestId,protocol:1}});
+ if(frame.type==='grid_fleet_run')runs++;
+ });
+ assert.match((await harnessExecute(machine,['join'],{WebSocketImpl,thinking:false})).error,/thinking/);assert.equal(runs,0);
+});
+test('cancellation addresses the same command through the same connection',async()=>{
+ const controller=new AbortController();let commandId,cancelled;
+ const WebSocketImpl=socketClass((frame,reply)=>{
+ if(frame.type==='machine_select')reply({type:'connected',payload:{relayIsolation:true}});
+ if(frame.type==='grid_fleet_capabilities')reply({type:frame.type+'_result',payload:{requestId:frame.payload.requestId,protocol:1}});
+ if(frame.type==='grid_fleet_run'){commandId=frame.payload.requestId;queueMicrotask(()=>controller.abort());}
+ if(frame.type==='grid_fleet_cancel')cancelled=frame.payload.commandId;
+ });
+ const result=await harnessExecute(machine,['pull','model'],{WebSocketImpl,signal:controller.signal});assert.equal(result.code,124);assert.equal(cancelled,commandId);
+});
diff --git a/store/agents/autonomous-grid/test/live.mjs b/store/agents/autonomous-grid/test/live.mjs
new file mode 100644
index 000000000..a0841d8a9
--- /dev/null
+++ b/store/agents/autonomous-grid/test/live.mjs
@@ -0,0 +1,80 @@
+// Opt-in real model smoke. All mutations use a newly allocated GRID_HOME and unique loopback ports.
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { createServer } from 'node:net';
+import { access, mkdir, mkdtemp, readFile, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { basename, join, resolve } from 'node:path';
+import { atomicJson, DEFAULT_CONFIG, execute, now, PACKAGE } from '../lib/fleet.mjs';
+import { createCollector } from '../lib/telemetry.mjs';
+import { createViewer } from '../viewer.mjs';
+
+const model=process.env.GRID_TEST_MODEL,engineDir=process.env.GRID_TEST_ENGINE_DIR;
+if(!model||!engineDir)throw new Error('Set GRID_TEST_MODEL to a real GGUF and GRID_TEST_ENGINE_DIR to its llama-server installation directory.');
+await access(model);await access(join(engineDir,'llama-server'));
+const workspace=await mkdtemp(join(process.env.GRID_TEST_OUTPUT || tmpdir(),'grid-harness-live-'));
+const gridHome=join(workspace,'grid-home');
+await mkdir(join(gridHome,'engines'),{recursive:true});await symlink(resolve(engineDir),join(gridHome,'engines','llama.cpp'));
+await mkdir(join(gridHome,'models'),{recursive:true});await symlink(resolve(model),join(gridHome,'models',basename(model)));
+const env={...process.env,GRID_HOME:gridHome,GRID_NO_UPDATE_CHECK:'1',HARNESS_WORKSPACE:workspace,LLAMA_SERVER:join(resolve(engineDir),'llama-server')};
+const machine={id:'local',transport:'local',gridHome};
+const freePort=()=>new Promise((ok,fail)=>{const server=createServer();server.once('error',fail);server.listen(0,'127.0.0.1',()=>{const port=server.address().port;server.close(()=>ok(port));});});
+const port=await freePort(),enginePort=await freePort(),name='grid-harness-test',alias='grid-harness-smoke',nodeName='grid-harness-test-node';
+await atomicJson(join(workspace,'grid-fleet.json'),{...DEFAULT_CONFIG,grid:name,machines:[{...machine,name:'Isolated test host'}]});
+const report={startedAt:now(),workspace,model:basename(model),gridVersion:null,checks:[],cleanup:[],result:'running'};
+const run=async(args,{allowFailure=false,timeoutMs=120_000}={})=>{
+ const result=await new Promise((ok,fail)=>{
+ const child=spawn(process.execPath,[join(PACKAGE,'toolchain','fleet.mjs'),'run','--',...args],{env,stdio:['ignore','pipe','pipe']});
+ let stdout='',stderr='';child.stdout.on('data',d=>stdout+=d);child.stderr.on('data',d=>stderr+=d);
+ const timer=setTimeout(()=>{child.kill('SIGTERM');setTimeout(()=>child.kill('SIGKILL'),2000).unref();},timeoutMs);
+ child.on('error',fail);child.on('close',code=>{clearTimeout(timer);ok({code,stdout,stderr});});
+ });
+ await writeFile(join(workspace,'commands.log'),`grid ${args[0]}\n${result.stdout}\n${result.stderr}\n`,{flag:'a'});
+ if(!allowFailure)assert.equal(result.code,0,`${args[0]}: ${result.stderr || result.stdout}`);
+ return result;
+};
+let viewer;
+try{
+ report.gridVersion=(await run(['version'])).stdout.trim();
+ await run(['start',name,'--port',String(port),'--host','127.0.0.1','--advertise-host','127.0.0.1']);report.checks.push('start isolated local grid');
+ await run(['join',name,'--serve',basename(model),'--name',nodeName,'--advertise-as',alias,'--endpoint-port',String(enginePort),'--advertise-host','127.0.0.1','--ctx-size','1024','--n-predict','48','--parallel','1']);report.checks.push('deploy real GGUF through Grid');
+ let modelRows=[];
+ for(let retry=0;retry<30;retry++){
+ const listed=await run(['models',name,'--json']);modelRows=JSON.parse(listed.stdout);
+ if(modelRows.some(row=>row.model===alias))break;
+ await new Promise(done=>setTimeout(done,1000));
+ }
+ assert.ok(modelRows.some(row=>row.model===alias),'model must be advertised');report.checks.push('discover served model');
+ const chat=await run(['chat','--grid',name,'-m',alias,'Say hello in one short sentence.','--json','--timeout','60']);
+ const response=JSON.parse(chat.stdout);const reply=response.choices?.[0]?.message?.content;
+ assert.equal(typeof reply,'string');assert.ok(reply.trim());report.reply=reply;report.checks.push('receive real model chat response');
+ const collect=createCollector(workspace);
+ const snapshot=await collect();assert.equal(snapshot.status,'live');assert.ok(snapshot.nodes.some(node=>node.models.includes(alias)));report.checks.push('CLI telemetry → normalized snapshot → ready verdict');
+ viewer=createViewer({workspace,collect,intervalMs:1000});const viewerPort=await viewer.start();
+ let served;
+ for(let retry=0;retry<20;retry++){served=await(await fetch(`http://127.0.0.1:${viewerPort}/api/snapshot`)).json();if(served.nodes.length)break;await new Promise(done=>setTimeout(done,250));}
+ assert.ok(served.nodes.some(node=>node.models.includes(alias)));report.checks.push('live HTTP viewer observes deployed model');
+ const engines=JSON.parse((await run(['engines',name,'--json'])).stdout);
+ const target=engines.find(engine=>engine.models.includes(alias));assert.ok(target);
+ await run(['leave',name,'--engine',target.engine]);
+ // Local Grid expires a stopped child at its 60 s heartbeat TTL if shutdown could not unregister.
+ // Verify convergence, never equate a successful leave command with completed discovery removal.
+ const leaveAt=Date.now();let remaining=[];
+ do {
+ remaining=JSON.parse((await run(['models',name,'--json'])).stdout);
+ if(!remaining.some(row=>row.model===alias))break;
+ await new Promise(done=>setTimeout(done,2000));
+ } while(Date.now()-leaveAt<80_000);
+ assert.ok(!remaining.some(row=>row.model===alias),'stopped model must disappear from discovery within 80 seconds');
+ report.undeployConvergenceMs=Date.now()-leaveAt;report.checks.push('undeploy exact engine and verify model removed');
+ const after=await collect();assert.equal(after.summary.modelsServing,0);report.checks.push('viewer observes removal');
+ report.result='passed';
+}catch(error){report.result='failed';report.error=error.message;process.exitCode=1;}
+finally{
+ await viewer?.close();
+ for(const args of [['leave',name,'--all'],['stop',name],['delete',name,'--yes']]){
+ const result=await run(args,{allowFailure:true,timeoutMs:70_000});report.cleanup.push({command:args[0],code:result.code});
+ if(result.code!==0){report.result='failed';process.exitCode=1;}
+ }
+ report.finishedAt=now();await atomicJson(join(workspace,'report.json'),report);console.log(JSON.stringify(report,null,2));
+}
diff --git a/store/agents/autonomous-grid/test/server.test.mjs b/store/agents/autonomous-grid/test/server.test.mjs
new file mode 100644
index 000000000..11e3e2fb7
--- /dev/null
+++ b/store/agents/autonomous-grid/test/server.test.mjs
@@ -0,0 +1,26 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { request } from 'node:http';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createViewer } from '../viewer.mjs';
+import { assemble } from '../lib/telemetry.mjs';
+import { config, reads } from './fixtures.mjs';
+
+test('viewer serves its real app and SSE, blocks mutations and never serves workspace secrets',async t=>{
+ const workspace=await mkdtemp(join(tmpdir(),'grid-viewer-'));
+ let fail=false;
+ const viewer=createViewer({workspace,intervalMs:50,collect:async()=>{if(fail)throw new Error('secret token');return {...assemble(config,reads),machines:[],operations:[]};}});
+ const port=await viewer.start();t.after(async()=>{await viewer.close();await rm(workspace,{recursive:true,force:true});});
+ const base=`http://127.0.0.1:${port}`;
+ const page=await fetch(base);assert.equal(page.status,200);assert.match(await page.text(),/id="connections"/);assert.match(page.headers.get('content-security-policy'),/default-src 'self'/);
+ for(const asset of ['app.css','app.js'])assert.equal((await fetch(`${base}/${asset}`)).status,200);
+ assert.equal((await fetch(`${base}/api/snapshot`,{method:'POST',body:'delete everything'})).status,405);
+ assert.equal((await fetch(`${base}/api/snapshot`,{headers:{origin:'https://evil.example'}})).status,403);
+ assert.equal((await fetch(`${base}/grid-fleet.json`)).status,404);
+ assert.equal((await fetch(`${base}/.harness/grid/../secret`)).status,404);
+ const blocked=await new Promise(resolve=>{request(base,{headers:{host:'attacker.test'}},res=>{res.resume();resolve(res.statusCode);}).end();});assert.equal(blocked,403);
+ const abort=new AbortController();const events=await fetch(`${base}/events`,{signal:abort.signal});const reader=events.body.getReader();const chunk=new TextDecoder().decode((await reader.read()).value);assert.match(chunk,/event: snapshot/);assert.match(chunk,/Mac Studio/);abort.abort();
+ fail=true;await new Promise(resolve=>setTimeout(resolve,90));const stale=await (await fetch(`${base}/api/snapshot`)).json();assert.equal(stale.status,'unavailable');assert.ok(stale.nodes.every(n=>n.stale));assert.doesNotMatch(JSON.stringify(stale),/secret token/);
+});
diff --git a/store/agents/autonomous-grid/test/telemetry.test.mjs b/store/agents/autonomous-grid/test/telemetry.test.mjs
new file mode 100644
index 000000000..e7c902b3a
--- /dev/null
+++ b/store/agents/autonomous-grid/test/telemetry.test.mjs
@@ -0,0 +1,69 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { assemble, createCollector, normalizeDevice, normalizeNode, safeUrl } from '../lib/telemetry.mjs';
+import { atomicJson, DEFAULT_CONFIG } from '../lib/fleet.mjs';
+import { config, device, reads, remoteNodes } from './fixtures.mjs';
+
+test('remote telemetry preserves zero, missing values, correct model case and unified memory',()=>{
+ const data=assemble(config,reads,null,'2026-09-18T00:00:00Z');
+ assert.equal(data.status,'live');assert.equal(data.summary.enginesOnline,7);assert.equal(data.models.length,4);
+ const studio=data.nodes[0];assert.equal(studio.memoryKind,'Unified memory');assert.equal(studio.memoryUsedGb,32);assert.equal(studio.temperatureC,null);assert.equal(studio.models[0],'Qwen3.5-27B');
+ assert.equal(data.nodes.at(-1).memoryUsedGb,0);assert.equal(data.summary.activeRequests,null);
+ assert.equal(data.endpoint,'https://grid.example.test/relay/v1');assert.equal(data.summary.answered.tokensOut,231840);
+ assert.equal('tokS' in data.summary,false);
+});
+test('local engines stay useful when Grid exposes no GPU sensors',()=>{
+ const local={...config,mode:'local'};
+ const data=assemble(local,{info:{ok:true,value:{grid:'home'}},engines:{ok:true,value:[{engine:'cpu-model',where:'http://localhost:8081',models:['tiny']}]},models:{ok:true,value:[]}});
+ assert.equal(data.nodes[0].online,true);assert.equal(data.nodes[0].tokS,null);assert.equal(data.nodes[0].temperatureC,null);assert.equal(data.nodes[0].memoryTotalGb,null);assert.equal(data.summary.modelsServing,1);
+});
+test('hosted models cannot claim local model memory; booleans are not measurements',()=>{
+ const node=normalizeNode({...remoteNodes[0],plan_type:'subscription',vram_gb:256,gpu_temp_c:true,throughput_tok_s:'50'},'remote');
+ assert.equal(node.memoryTotalGb,null);assert.equal(node.memoryUsedGb,null);assert.equal(node.temperatureC,null);assert.equal(node.tokS,null);
+});
+test('device inventory reads the GPU memory and utilization fields emitted by Grid',()=>{
+ const host=normalizeDevice(config.machines[0],{gpus:[{name:'GPU',memory_total_mb:24576,memory_used_mb:1024,utilization_pct:0,temperature_c:31,power_draw_w:20}]},'now');
+ assert.deepEqual(host.gpus[0],{name:'GPU',memoryGb:24,memoryUsedGb:1,utilizationPct:0,temperatureC:31,powerW:20});
+});
+test('dual GPU live memory uses aggregate capacity instead of single-card inventory',()=>{
+ const node=normalizeNode({name:'dual4090',memory_gb:24,vram_gb:48,vram_total_mb:49128,vram_used_mb:28097,memory_used_gb:27.4},'remote');
+ assert.equal(node.memoryTotalGb,49128/1024);assert.equal(node.memoryUsedGb,28097/1024);
+ assert.equal(node.memoryFreeGb,(49128-28097)/1024);assert.ok(node.memoryUsedGb<node.memoryTotalGb);
+});
+test('a failed poll keeps stale observations, and an actual departure becomes offline',()=>{
+ const before=assemble(config,reads,null,'2026-09-18T00:00:00Z');
+ const failed=assemble(config,{...reads,engines:{ok:false,error:'network unavailable'}},before,'2026-09-18T00:00:08Z');
+ assert.equal(failed.status,'unavailable');assert.equal(failed.nodes.length,8);assert.ok(failed.nodes.every(n=>n.stale));assert.equal(failed.history[before.nodes[0].id].length,1);
+ const left=assemble(config,{...reads,engines:{ok:true,value:[]}},before,'2026-09-18T00:00:08Z');
+ assert.equal(left.summary.enginesOnline,0);assert.ok(left.nodes.every(n=>n.online===false));assert.ok(left.events.some(e=>e.kind==='offline'));
+ const expired=assemble(config,{...reads,engines:{ok:true,value:[]}},left,'2026-09-18T00:11:00Z');assert.equal(expired.nodes.length,0);
+});
+test('changing grid selection never carries another grid’s cached nodes',()=>{
+ const before=assemble(config,reads);
+ const changed=assemble({...config,grid:'elsewhere'},{engines:{ok:false,error:'unavailable'}},before);
+ assert.equal(changed.nodes.length,0);assert.deepEqual(changed.history,{});
+});
+test('histories are bounded and duplicate display names remain separate',()=>{
+ let data;
+ const input={...reads,engines:{ok:true,value:remoteNodes.map(n=>({...n,name:'same-name'}))}};
+ for(let i=0;i<110;i++)data=assemble(config,input,data,new Date(Date.UTC(2026,8,18,0,0,i*8)).toISOString());
+ assert.equal(new Set(data.nodes.map(n=>n.id)).size,8);assert.equal(data.history[data.nodes[0].id].length,90);
+});
+test('source payloads cannot expose credentials or arbitrary fields in the browser projection',()=>{
+ const data=assemble(config,{...reads,engines:{ok:true,value:[{...remoteNodes[0],access_token:'secret',api_key:'secret',nested:{password:'secret'}}]}});
+ assert.doesNotMatch(JSON.stringify(data),/secret|access_token|api_key/);
+ assert.equal(safeUrl('https://user:[email protected]/a?token=secret#secret'),'https://host.test/a');assert.equal(safeUrl('javascript:alert(1)'),null);
+ const host=normalizeDevice(config.machines[0],device,'now');assert.equal(host.usableModelGb,24);assert.equal(host.memoryAvailableGb,28);
+});
+test('collector coalesces concurrent refreshes, caches hardware and writes a truthful verdict',async t=>{
+ const dir=await mkdtemp(join(tmpdir(),'grid-collect-'));t.after(()=>rm(dir,{recursive:true,force:true}));
+ await atomicJson(join(dir,'grid-fleet.json'),config);
+ const calls=[];
+ const collect=createCollector(dir,{runJson:async(_machine,mode,args)=>{calls.push(args[0]);await new Promise(r=>setTimeout(r,2));return args[0]==='device-info'?{ok:true,value:device}:reads[args[0]];}});
+ const [a,b]=await Promise.all([collect(),collect()]);assert.equal(a,b);assert.equal(calls.length,5);
+ await collect();assert.equal(calls.filter(c=>c==='device-info').length,1);
+ const verdict=JSON.parse(await readFile(join(dir,'.harness/verdict.json'),'utf8'));assert.equal(verdict.ready,true);assert.match(verdict.summary,/7 engines/);
+});
diff --git a/store/agents/autonomous-grid/toolchain/doctor.sh b/store/agents/autonomous-grid/toolchain/doctor.sh
new file mode 100755
index 000000000..adb0fea3f
--- /dev/null
+++ b/store/agents/autonomous-grid/toolchain/doctor.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+. toolchain/runtimes.sh
+harness_node 20
+node toolchain/fleet.mjs doctor
diff --git a/store/agents/autonomous-grid/toolchain/fleet b/store/agents/autonomous-grid/toolchain/fleet
new file mode 100755
index 000000000..4a66c53dd
--- /dev/null
+++ b/store/agents/autonomous-grid/toolchain/fleet
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")/.." && pwd)"
+. "$here/toolchain/runtimes.sh"
+harness_node 22
+exec node "$here/toolchain/fleet.mjs" "$@"
diff --git a/store/agents/autonomous-grid/toolchain/fleet.mjs b/store/agents/autonomous-grid/toolchain/fleet.mjs
new file mode 100644
index 000000000..22e9c3a11
--- /dev/null
+++ b/store/agents/autonomous-grid/toolchain/fleet.mjs
@@ -0,0 +1,97 @@
+#!/usr/bin/env node
+import { join, resolve } from 'node:path';
+import { atomicJson, DEFAULT_CONFIG, execute, readConfig, runTracked } from '../lib/fleet.mjs';
+import { createCollector } from '../lib/telemetry.mjs';
+import { discoverMachines } from '../lib/harness.mjs';
+import { connectWorkspace, initializeWorkspace, mergeMachines, readStatus } from '../lib/connect.mjs';
+
+const workspace = resolve(process.env.HARNESS_WORKSPACE || process.cwd());
+const [command = 'help', ...args] = process.argv.slice(2);
+try {
+ if (command === 'init') {
+ const { access, mkdir } = await import('node:fs/promises');
+ await mkdir(workspace, { recursive: true });
+ await access(join(workspace, 'grid-fleet.json')).catch(() => atomicJson(join(workspace, 'grid-fleet.json'), DEFAULT_CONFIG));
+ const {connection} = await initializeWorkspace(workspace);
+ await createCollector(workspace)();
+ console.log(`Grid workspace ready: ${workspace}`);
+ if (connection.message) console.log(connection.message);
+ } else if (command === 'connect') {
+ let mode,grid,remember=false;
+ for(let i=0;i<args.length;i++) {
+ if(args[i]==='--mode' && mode===undefined) mode=args[++i];
+ else if(args[i]==='--grid' && grid===undefined) grid=args[++i];
+ else if(args[i]==='--remember' && !remember) remember=true;
+ else throw new Error('Use: fleet connect --mode local|remote --grid NAME [--remember]');
+ }
+ await connectWorkspace(workspace,{mode,grid,remember});
+ const snapshot = await createCollector(workspace)();
+ console.log(JSON.stringify({mode,grid,remembered:remember,status:snapshot.status,enginesOnline:snapshot.summary.enginesOnline},null,2));
+ } else if (command === 'status') {
+ if(args.length && !(args.length===1 && args[0]==='--json')) throw new Error('Use: fleet status [--json]');
+ console.log(JSON.stringify(await readStatus(workspace),null,2));
+ } else if (command === 'doctor') {
+ const result = await execute({ transport: 'local' }, ['version']);
+ const version = result.stdout.match(/\d+\.\d+\.\d+/)?.[0];
+ const [a=0,b=0,c=0] = (version || '').split('.').map(Number);
+ if (!result.ok || !(a > 0 || b > 3 || (b === 3 && c >= 47))) throw new Error('Grid >= 0.3.47 is required. Run toolchain/setup.sh or update the selected Harness runtime.');
+ console.log(`ok Grid ${version}\nok Node ${process.versions.node}\nok local fleet viewer\ninfo Paired Harness machines use encrypted connections; SSH targets use existing keys`);
+ } else if (command === 'discover') {
+ if (args.length && (args.length !== 1 || args[0] !== '--add')) throw new Error('Use: fleet discover [--add]');
+ const found = await discoverMachines();
+ if (args[0] === '--add') {
+ const config = await readConfig(workspace);
+ await atomicJson(join(workspace,'grid-fleet.json'), mergeMachines(config,found));
+ }
+ console.log(JSON.stringify(found,null,2));
+ } else if (command === 'refresh') {
+ const snapshot = await createCollector(workspace)();
+ console.log(JSON.stringify(snapshot, null, 2));
+ process.exitCode = snapshot.status === 'unavailable' ? 1 : 0;
+ } else if (command === 'config') {
+ console.log(JSON.stringify(await readConfig(workspace), null, 2));
+ } else if (command === 'run') {
+ const boundary = args.indexOf('--');
+ if (boundary < 0 || boundary === args.length - 1) throw new Error('Use: fleet run [--machine ID] -- <grid arguments>');
+ const flags = args.slice(0,boundary), gridArgs = args.slice(boundary + 1);
+ let target, thinking;
+ for (let i=0;i<flags.length;i+=2) {
+ if (flags[i]==='--machine' && target===undefined && flags[i+1]) target=flags[i+1];
+ else if (flags[i]==='--thinking' && thinking===undefined && ['on','off'].includes(flags[i+1])) thinking=flags[i+1]==='on';
+ else throw new Error('Use --machine ID and/or --thinking on|off before --.');
+ }
+ if (thinking!==undefined && gridArgs[0]!=='join') throw new Error('--thinking configures engine startup; use it with join.');
+ const config = await readConfig(workspace);
+ const machineId = target || config.controller;
+ const machine = config.machines.find(m => m.id === machineId);
+ if (!machine) throw new Error(`Unknown machine ${machineId}. Add it to grid-fleet.json first.`);
+ const abort = new AbortController();
+ process.once('SIGINT', () => abort.abort()); process.once('SIGTERM', () => abort.abort());
+ const result = await runTracked(workspace, machine, config.mode, gridArgs, { signal: abort.signal, thinking });
+ if (!result.ok && result.error) console.error(result.error);
+ process.exitCode = result.code;
+ } else {
+ console.log(`Grid fleet workspace tools
+
+ fleet init Initialize from your remembered or active Grid
+ fleet connect --mode MODE --grid NAME [--remember]
+ Select a reachable grid; optionally reuse it in new workspaces
+ fleet status [--json] Read the viewer's observations without network access
+ fleet doctor Check Grid and Node
+ fleet discover [--add] Discover your Harness machines
+ fleet config Validate and print fleet inventory
+ fleet refresh Read Grid, update viewer and verdict
+ fleet run [--machine ID] -- ARGS Run any Grid command on a configured machine
+
+Use --thinking on|off before -- to configure a supported model's thinking at join.
+
+Examples:
+ "$GRID_FLEET" run -- engines --json
+ "$GRID_FLEET" run --machine studio --thinking off -- join home --serve model.gguf --name studio
+ "$GRID_FLEET" run --machine studio -- leave home --engine studio
+
+Grid’s own help is available with: fleet run -- --help
+Workspace: ${workspace}`);
+ if (command !== 'help') process.exitCode = 2;
+ }
+} catch (error) { console.error(error.message); process.exitCode = 1; }
diff --git a/store/agents/autonomous-grid/toolchain/grid.sh b/store/agents/autonomous-grid/toolchain/grid.sh
new file mode 100755
index 000000000..94632bbf0
--- /dev/null
+++ b/store/agents/autonomous-grid/toolchain/grid.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")/.." && pwd)"
+export GRID_NO_UPDATE_CHECK=1
+# Same priority as Harness: explicit override, managed runtime, package fallback, user's CLI.
+if [ -n "${HARNESS_GRID_BIN:-}" ]; then exec "$HARNESS_GRID_BIN" "$@"; fi
+runtime="${ADAPTER_RUNTIME_DIR:-${HOME}/.harness/runtime}"
+recorded="$(cat "$runtime/current-grid" 2>/dev/null || true)"
+case "$recorded" in "$runtime"/*)
+ if [ -x "$recorded" ]; then exec "$recorded" "$@"; fi ;;
+esac
+if [ -x "$here/.venv/bin/grid" ]; then exec "$here/.venv/bin/grid" "$@"; fi
+if command -v grid >/dev/null 2>&1; then exec grid "$@"; fi
+if [ -x "${HOME}/.local/bin/grid" ]; then exec "${HOME}/.local/bin/grid" "$@"; fi
+echo 'Grid is missing. Run this harness’s toolchain/setup.sh.' >&2
+exit 127
diff --git a/store/agents/autonomous-grid/toolchain/init-workspace.sh b/store/agents/autonomous-grid/toolchain/init-workspace.sh
new file mode 100755
index 000000000..acce30126
--- /dev/null
+++ b/store/agents/autonomous-grid/toolchain/init-workspace.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")/.." && pwd)"
+. "$here/toolchain/runtimes.sh"
+harness_node 22
+exec node "$here/toolchain/fleet.mjs" init
diff --git a/store/agents/autonomous-grid/toolchain/runtimes.sh b/store/agents/autonomous-grid/toolchain/runtimes.sh
new file mode 100644
index 000000000..7223c78dc
--- /dev/null
+++ b/store/agents/autonomous-grid/toolchain/runtimes.sh
@@ -0,0 +1,192 @@
+# shellcheck shell=bash
+# runtimes.sh — the interpreters a store package runs on, found on this machine or fetched, never
+# asked of the person who pressed Get.
+#
+# Sourced (not run) by a package's setup, doctor and viewer scripts. A new Mac has Apple's Python 3.9,
+# no Homebrew and, for most people, no Node on PATH; a package that answers "brew install [email protected]"
+# has failed its install. So:
+#
+# harness_node 18 node >= 18 on PATH, with npm: the machine's own, else the Node Harness
+# itself runs on (~/.harness/runtime/current-node, laid down with the CLI)
+# harness_uv uv on PATH: the machine's own, else a pinned, checksummed release
+# fetched into ~/.harness/runtime
+# harness_venv DIR 3.12 [MIN [BELOW]]
+# DIR is a venv on CPython 3.12, which uv downloads when the machine
+# has none. A venv already there on a Python in [MIN, BELOW) is kept.
+# harness_pip DIR PKG… install into that venv, through uv
+# harness_micromamba micromamba, pinned and checksummed, for native libraries PyPI has
+# no wheel for (pycairo on macOS)
+# harness_conda_env DIR SPEC… DIR is a conda-forge environment with those packages
+#
+# Every function prints `miss …` and returns 1 when it cannot deliver, so `harness_node 18 || exit 1`
+# reads like the rest of a setup script. Nothing here touches the user's shell profile; what it
+# installs lands in ~/.harness/runtime or the package's own directory (uv keeps its download cache
+# where it always does, which a venv does not depend on).
+#
+# ONE copy is written by hand: store/tools/runtimes.sh in the OpenHarness repository. Each package
+# carries an identical copy (a package installs alone, so it cannot reach this one);
+# `node store/tools/sync-runtimes.mjs` rewrites them and the CLI's store spec fails when one drifts.
+
+HARNESS_RUNTIME="${ADAPTER_RUNTIME_DIR:-${HOME:-}/.harness/runtime}"
+# The Pythons uv downloads live with Harness's other runtimes, not in uv's own ~/.local/share/uv:
+# a package's venv points at its interpreter, and `uv python uninstall` there must not break it.
+UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-$HARNESS_RUNTIME/python}"
+export UV_PYTHON_INSTALL_DIR
+HARNESS_UV_VERSION=0.12.15
+HARNESS_MICROMAMBA_VERSION=2.9.0-0
+
+_harness_platform() {
+ case "$(uname -s)-$(uname -m)" in
+ Darwin-arm64) echo darwin-arm64 ;;
+ Darwin-x86_64) echo darwin-x64 ;;
+ Linux-x86_64) echo linux-x64 ;;
+ Linux-aarch64 | Linux-arm64) echo linux-arm64 ;;
+ *) return 1 ;;
+ esac
+}
+
+_harness_sha256() {
+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
+ else sha256sum "$1" | cut -d' ' -f1; fi
+}
+
+# _harness_fetch URL DEST SHA256 — DEST exists only if what arrived matches the pinned checksum.
+_harness_fetch() {
+ local part="$2.part.$$"
+ if ! curl -fsSL --retry 3 --connect-timeout 20 --max-time 900 -o "$part" "$1"; then
+ rm -f "$part"; echo "miss could not download $1 — check this machine's internet connection"; return 1
+ fi
+ if [ "$(_harness_sha256 "$part")" != "$3" ]; then
+ rm -f "$part"; echo "miss $1 did not match its pinned checksum; nothing was installed"; return 1
+ fi
+ mv -f "$part" "$2"
+}
+
+_harness_node_at_least() {
+ command -v node >/dev/null 2>&1 || return 1
+ node -e '
+ const [a, b = 0] = process.argv[1].split(".").map(Number)
+ const [x, y] = process.versions.node.split(".").map(Number)
+ process.exit(x > a || (x === a && y >= b) ? 0 : 1)
+ ' "$1" >/dev/null 2>&1
+}
+
+harness_node() {
+ local min="${1:-18}" recorded saved="$PATH" own=0
+ _harness_node_at_least "$min" && own=1
+ # A node without npm beside it (a distro's nodejs package) cannot run a setup's `npm ci`.
+ if [ "$own" = 1 ] && command -v npm >/dev/null 2>&1; then return 0; fi
+ recorded="$(cat "$HARNESS_RUNTIME/current-node" 2>/dev/null || true)"
+ # Already Harness's own (a second call, or a wrapper calling a script that asks again): nothing to add.
+ if [ "$own" = 1 ] && [ -n "$recorded" ] && [ "$(command -v node)" = "${recorded%/*}/node" ]; then return 0; fi
+ if [ -n "$recorded" ] && [ -x "${recorded%/*}/node" ]; then
+ PATH="${recorded%/*}:$PATH"; export PATH; hash -r 2>/dev/null || true
+ _harness_node_at_least "$min" && return 0
+ PATH="$saved"; export PATH; hash -r 2>/dev/null || true
+ [ "$own" = 1 ] && return 0
+ echo "miss node >= $min — this machine's newest is $("${recorded%/*}/node" -v), Harness's own; update Harness"
+ return 1
+ fi
+ [ "$own" = 1 ] && return 0
+ echo "miss node >= $min, and Harness's own Node is not in $HARNESS_RUNTIME — run \`harness start\` once to lay it down"
+ return 1
+}
+
+harness_uv() {
+ local dir asset sum tmp
+ command -v uv >/dev/null 2>&1 && return 0
+ for dir in "${HOME:-}/.local/bin" "${HOME:-}/.cargo/bin"; do
+ [ -n "${HOME:-}" ] || break
+ if [ -x "$dir/uv" ]; then PATH="$dir:$PATH"; export PATH; return 0; fi
+ done
+ dir="$HARNESS_RUNTIME/uv-$HARNESS_UV_VERSION"
+ if [ ! -x "$dir/uv" ]; then
+ case "$(_harness_platform)" in
+ darwin-arm64) asset=uv-aarch64-apple-darwin sum=dc304b9ed1b24174572290fba60ac3f6fe63c73a671f0439e62a91375841964d ;;
+ darwin-x64) asset=uv-x86_64-apple-darwin sum=e9ca61775532368fe518ab03e7a354c7ecab8ccb3c7d941c775fcc4a362b801b ;;
+ linux-x64) asset=uv-x86_64-unknown-linux-gnu sum=f97935763c04be3e692460a7aaeaaab8fc3b78fcf8b389da820b38ae7423a638 ;;
+ linux-arm64) asset=uv-aarch64-unknown-linux-gnu sum=0e9a3499b0587d449c9ff684c0160da607826e4af1cee220bc87f378702d3e08 ;;
+ *) echo "miss uv — there is no uv release for $(uname -s) $(uname -m); install it from https://docs.astral.sh/uv/"; return 1 ;;
+ esac
+ echo " fetching uv $HARNESS_UV_VERSION into $HARNESS_RUNTIME (it brings Python and the packages)"
+ mkdir -p "$HARNESS_RUNTIME" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }
+ tmp="$(mktemp -d "$HARNESS_RUNTIME/.uv.XXXXXX")" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }
+ if ! _harness_fetch "https://github.com/astral-sh/uv/releases/download/$HARNESS_UV_VERSION/$asset.tar.gz" "$tmp/uv.tar.gz" "$sum"; then
+ rm -rf "$tmp"; return 1
+ fi
+ tar -xzf "$tmp/uv.tar.gz" -C "$tmp" && chmod +x "$tmp/$asset/uv" "$tmp/$asset/uvx" \
+ || { rm -rf "$tmp"; echo "miss the uv archive would not unpack"; return 1; }
+ # Two installs at once both get here; whichever renames first wins and the other's copy goes.
+ # (mv onto a directory that exists would nest the copy inside it, hence the test.)
+ [ -e "$dir" ] || mv "$tmp/$asset" "$dir" 2>/dev/null || true
+ rm -rf "$tmp"
+ [ -x "$dir/uv" ] || { echo "miss uv did not land in $dir"; return 1; }
+ fi
+ PATH="$dir:$PATH"; export PATH
+}
+
+# harness_venv DIR VERSION [MIN [BELOW]] — MIN defaults to VERSION; BELOW is exclusive and optional.
+harness_venv() {
+ local dir="${1:?harness_venv needs a directory}" want="${2:?harness_venv needs a Python version}"
+ local min="${3:-$2}" below="${4:-}"
+ if [ -x "$dir/bin/python" ] && "$dir/bin/python" -c '
+import sys
+at = lambda s: tuple(int(p) for p in s.split("."))
+v = sys.version_info[:2]
+sys.exit(0 if v >= at(sys.argv[1]) and (not sys.argv[2] or v < at(sys.argv[2])) else 1)
+' "$min" "$below" 2>/dev/null; then
+ echo "ok $("$dir/bin/python" --version) in $dir"
+ return 0
+ fi
+ harness_uv || return 1
+ echo " python $want in $dir (uv downloads it when this machine has none)"
+ rm -rf "$dir"
+ # only-managed: the same python-build-standalone interpreter on every machine, so a package tested
+ # once is tested everywhere — not whichever Homebrew or pyenv Python happened to be first on PATH.
+ uv venv --quiet --seed --python "$want" --python-preference only-managed "$dir" \
+ || { echo "miss could not make a Python $want environment in $dir"; return 1; }
+ echo "ok $("$dir/bin/python" --version) in $dir"
+}
+
+harness_pip() {
+ local dir="${1:?harness_pip needs a venv}"
+ shift
+ harness_uv || return 1
+ # uv's own error comes first; the miss line is last, so it is the line the store shows.
+ uv pip install --quiet --python "$dir/bin/python" "$@" \
+ || { echo "miss could not install $* into $dir"; return 1; }
+}
+
+harness_micromamba() {
+ local dir asset sum
+ dir="$HARNESS_RUNTIME/micromamba-$HARNESS_MICROMAMBA_VERSION"
+ if [ ! -x "$dir/micromamba" ]; then
+ case "$(_harness_platform)" in
+ darwin-arm64) asset=micromamba-osx-arm64 sum=ec2a072f028e1a7cf20f3e2e74d5a8127cf5a5f27636375b5359811565f4e5be ;;
+ darwin-x64) asset=micromamba-osx-64 sum=1e71054bb3ac9a076e21f7ec48acfef536f9b3f1408f371a942784bf5ef83d8a ;;
+ linux-x64) asset=micromamba-linux-64 sum=366cd9cd8be14df1ab8ed50352a82111082a36686b2d389fdb79a92c3fafb3e3 ;;
+ linux-arm64) asset=micromamba-linux-aarch64 sum=9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7 ;;
+ *) echo "miss micromamba — there is no release for $(uname -s) $(uname -m)"; return 1 ;;
+ esac
+ echo " fetching micromamba $HARNESS_MICROMAMBA_VERSION into $HARNESS_RUNTIME (native libraries PyPI has no wheel for)"
+ mkdir -p "$dir" || { echo "miss cannot write $dir"; return 1; }
+ _harness_fetch "https://github.com/mamba-org/micromamba-releases/releases/download/$HARNESS_MICROMAMBA_VERSION/$asset" "$dir/micromamba.$$" "$sum" || return 1
+ chmod +x "$dir/micromamba.$$" && mv -f "$dir/micromamba.$$" "$dir/micromamba" \
+ || { rm -f "$dir/micromamba.$$"; echo "miss micromamba would not install into $dir"; return 1; }
+ fi
+ HARNESS_MICROMAMBA="$dir/micromamba"
+ export HARNESS_MICROMAMBA
+}
+
+# harness_conda_env DIR SPEC… — conda-forge only, packages cached under ~/.harness/runtime/mamba.
+harness_conda_env() {
+ local dir="${1:?harness_conda_env needs a directory}"
+ shift
+ # micromamba takes a relative --prefix as a name under its root prefix and "succeeds" there.
+ case "$dir" in /*) ;; *) dir="$PWD/$dir" ;; esac
+ harness_micromamba || return 1
+ MAMBA_ROOT_PREFIX="$HARNESS_RUNTIME/mamba" "$HARNESS_MICROMAMBA" create --yes --quiet \
+ --prefix "$dir" --override-channels --channel conda-forge "$@" >/dev/null \
+ && [ -d "$dir/conda-meta" ] \
+ || { echo "miss could not make the conda-forge environment in $dir ($*)"; return 1; }
+}
diff --git a/store/agents/autonomous-grid/toolchain/setup.sh b/store/agents/autonomous-grid/toolchain/setup.sh
new file mode 100755
index 000000000..23a8e63c4
--- /dev/null
+++ b/store/agents/autonomous-grid/toolchain/setup.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+. ./VERSIONS
+. toolchain/runtimes.sh
+harness_node 22
+version="$(toolchain/grid.sh version 2>/dev/null || true)"
+if ! node --input-type=module - "$version" "$GRID_MIN_VERSION" <<'JS'
+const parse = s => (s.match(/\d+\.\d+\.\d+/)?.[0] || '0.0.0').split('.').map(Number);
+const a = parse(process.argv[2]), b = parse(process.argv[3]);
+process.exit(a[0] > b[0] || (a[0] === b[0] && (a[1] > b[1] || (a[1] === b[1] && a[2] >= b[2]))) ? 0 : 1);
+JS
+then
+ if [ -n "${HARNESS_GRID_BIN:-}" ] || [ -f "$HARNESS_RUNTIME/current-grid" ]; then
+ echo "miss Grid >= $GRID_MIN_VERSION — update the selected Harness runtime, then run setup again"
+ exit 1
+ fi
+ harness_venv .venv 3.12 3.11
+ harness_pip .venv "git+$UPSTREAM_REPO@$UPSTREAM_COMMIT"
+fi
+echo "ok $(toolchain/grid.sh version)"
+echo 'ok Grid viewer (no browser dependencies or model downloads needed)'
diff --git a/store/agents/autonomous-grid/viewer.mjs b/store/agents/autonomous-grid/viewer.mjs
new file mode 100644
index 000000000..2e011cc3d
--- /dev/null
+++ b/store/agents/autonomous-grid/viewer.mjs
@@ -0,0 +1,83 @@
+import { createServer } from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { atomicJson, now, operations, PACKAGE } from './lib/fleet.mjs';
+import { createCollector } from './lib/telemetry.mjs';
+
+export function createViewer({ workspace, port = 0, intervalMs = 8000, collect = createCollector(workspace, { intervalMs }) }) {
+ const clients = new Set();
+ let snapshot = { spec: 1, status: 'connecting', grid: 'Your grid', nodes: [], machines: [], models: [], events: [], operations: [], history: {}, sources: {}, summary: {}, observedAt: null, pollIntervalMs: intervalMs };
+ let stopped = false, pollTimer, opTimer, heartbeat;
+ const headers = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' };
+ const json = (res, code, value) => { res.writeHead(code, { ...headers, 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(value)); };
+ const publish = () => {
+ const body = `event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`;
+ for (const client of clients) {
+ if (client.writableLength > 256 * 1024) { client.destroy(); clients.delete(client); }
+ else client.write(body);
+ }
+ };
+ const server = createServer(async (req, res) => {
+ try {
+ const address = server.address();
+ const hosts = new Set([`127.0.0.1:${address?.port}`, `localhost:${address?.port}`, `[::1]:${address?.port}`]);
+ if (!hosts.has(req.headers.host)) { json(res, 403, { error: 'Loopback requests only.' }); return; }
+ if (!['GET', 'HEAD'].includes(req.method)) { res.setHeader('allow', 'GET, HEAD'); json(res, 405, { error: 'This viewer is read-only. Talk to the Grid agent to make changes.' }); return; }
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const origin = req.headers.origin;
+ if (origin && origin !== url.origin) { json(res, 403, { error: 'Cross-origin requests are not allowed.' }); return; }
+ if (url.pathname === '/health') { json(res, 200, { ok: true }); return; }
+ if (url.pathname === '/api/snapshot') { json(res, 200, snapshot); return; }
+ if (url.pathname === '/events') {
+ if (req.method === 'HEAD') { res.writeHead(200, headers); res.end(); return; }
+ if (clients.size >= 32) { json(res, 503, { error: 'Too many viewer connections.' }); return; }
+ res.writeHead(200, { ...headers, 'content-type': 'text/event-stream', connection: 'keep-alive', 'x-accel-buffering': 'no' });
+ res.write(`event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`);
+ clients.add(res); res.on('close', () => clients.delete(res)); return;
+ }
+ const assets = { '/': ['index.html', 'text/html; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/app.css': ['app.css', 'text/css; charset=utf-8'] };
+ if (!assets[url.pathname]) { json(res, 404, { error: 'Not found' }); return; }
+ const [file, contentType] = assets[url.pathname];
+ const content = await readFile(join(PACKAGE, 'viewer', file));
+ res.writeHead(200, { ...headers, 'content-type': contentType, 'content-security-policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'" });
+ res.end(req.method === 'HEAD' ? undefined : content);
+ } catch { if (!res.headersSent) json(res, 500, { error: 'The viewer could not serve this request.' }); else res.end(); }
+ });
+ async function poll() {
+ try { snapshot = await collect(); }
+ catch {
+ snapshot = { ...snapshot, status: 'unavailable', nodes: snapshot.nodes.map(n => ({ ...n, stale: true })), sources: { configuration: { ok: false, error: 'Cannot refresh the fleet. Ask the agent to check grid-fleet.json and run fleet refresh.' } } };
+ await atomicJson(join(workspace, '.harness', 'verdict.json'), { spec: 1, ready: false, summary: 'Grid telemetry could not refresh', findings: [{ severity: 'error', kind: 'telemetry', message: snapshot.sources.configuration.error }], updatedAt: now() }).catch(() => {});
+ }
+ if (stopped) return;
+ publish(); pollTimer = setTimeout(poll, intervalMs);
+ }
+ async function pollOperations() {
+ const latest = await operations(workspace).catch(() => []);
+ if (!stopped && JSON.stringify(latest) !== JSON.stringify(snapshot.operations)) { snapshot = { ...snapshot, operations: latest }; publish(); }
+ if (!stopped) opTimer = setTimeout(pollOperations, 1500);
+ }
+ return {
+ server,
+ start: () => new Promise((ok, fail) => {
+ server.once('error', fail);
+ server.listen(port, '127.0.0.1', () => {
+ server.removeListener('error', fail); poll(); pollOperations();
+ heartbeat = setInterval(() => { for (const client of clients) client.write(': pulse\n\n'); }, 20_000);
+ ok(server.address().port);
+ });
+ }),
+ close: async () => { stopped = true; clearTimeout(pollTimer); clearTimeout(opTimer); clearInterval(heartbeat); for (const client of clients) client.end(); server.closeAllConnections(); await new Promise(done => server.close(done)); },
+ };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ const workspace = resolve(process.env.HARNESS_WORKSPACE || process.cwd());
+ const port = Number(process.env.HARNESS_VIEWER_PORT || 0);
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('HARNESS_VIEWER_PORT must be a port number.');
+ const viewer = createViewer({ workspace, port });
+ console.log(`[grid] http://127.0.0.1:${await viewer.start()}/`);
+ const close = () => viewer.close().then(() => process.exit(0));
+ process.once('SIGINT', close); process.once('SIGTERM', close);
+}
diff --git a/store/agents/autonomous-grid/viewer.sh b/store/agents/autonomous-grid/viewer.sh
new file mode 100755
index 000000000..e9a5146c0
--- /dev/null
+++ b/store/agents/autonomous-grid/viewer.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")"
+. toolchain/runtimes.sh
+harness_node 22
+exec node viewer.mjs
diff --git a/store/agents/autonomous-grid/viewer/app.css b/store/agents/autonomous-grid/viewer/app.css
new file mode 100644
index 000000000..24429a99e
--- /dev/null
+++ b/store/agents/autonomous-grid/viewer/app.css
@@ -0,0 +1,9 @@
+:root{color-scheme:dark;--bg:#080b0f;--surface:#10151b;--surface-2:#161c23;--stroke:#232a31;--text:#e7e9ec;--muted:#89929f;--gold:#dfb465;--gold-dim:#8b7145;--green:#78bb98;--red:#e98576;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:14px;background:var(--bg);color:var(--text)}
+*{box-sizing:border-box}body{margin:0}button,select{font:inherit}button{cursor:pointer;color:inherit}button:disabled{cursor:default;opacity:.5}[hidden]{display:none!important}button:focus-visible,select:focus-visible{outline:2px solid var(--gold);outline-offset:4px}button{touch-action:manipulation}h1,h2,h3,p{margin:0}#grid-app{min-width:320px;max-width:2200px;margin:auto}.chrome{height:74px;border-bottom:1px solid #ffffff0b;display:flex;align-items:center;justify-content:space-between;padding:0 32px;gap:16px}.brand{display:flex;align-items:center;gap:13px;font-size:15px;letter-spacing:3px}.brand-mark{display:grid;grid-template-columns:5px 5px;gap:4px;transform:rotate(-8deg)}.brand-mark i{width:5px;height:5px;background:var(--gold);border-radius:1px;box-shadow:0 0 14px #dfb46540}.brand-divider{height:20px;width:1px;background:var(--stroke);margin:0 3px}.grid-name{font-size:13px;color:var(--muted);letter-spacing:0;overflow:hidden;text-overflow:ellipsis;max-width:330px;white-space:nowrap}.connection{display:flex;align-items:center;gap:8px;font-size:12px;white-space:nowrap}.status-dot,.footer-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--green);box-shadow:0 0 10px #78bb9830}.status-dot.pending{background:var(--gold)}.status-dot.offline{background:var(--red)}.mode{color:var(--muted);border-left:1px solid var(--stroke);padding-left:10px;margin-left:4px;text-transform:uppercase;font-size:10px;letter-spacing:1px}.workspace{display:grid;grid-template-columns:minmax(0,1fr) 304px}.main-column{min-width:0}.view-toolbar{display:flex;align-items:center;justify-content:space-between;padding:22px 30px 4px;gap:16px}.segmented{display:flex;gap:4px;background:#11161c;padding:3px;border-radius:7px}.segmented button{background:transparent;border:0;border-radius:5px;padding:7px 13px;font-size:12px;color:var(--muted)}.segmented button[aria-pressed=true]{background:#222a33;color:#eef0f2;box-shadow:0 1px 3px #0005}.metric-select{display:flex;align-items:center;gap:9px;color:var(--muted);font-size:11px}.metric-select select{background:transparent;color:#c0c7cf;border:0;font-size:12px;max-width:155px;cursor:pointer}.metric-select option{background:var(--surface)}.topology{height:560px;position:relative;isolation:isolate;overflow:hidden;background:radial-gradient(ellipse at 52% 49%,#6d4c1712,transparent 48%),radial-gradient(ellipse at 97% 50%,#16395110,transparent 55%)}#connections{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}.map-heading{position:absolute;left:32px;top:25px;display:flex;flex-direction:column;gap:8px;pointer-events:none}.eyebrow{font-size:10px;letter-spacing:1.7px;font-weight:500;color:#acb3bd}.map-subtitle{font-size:12px;color:#677382}.node-layer{position:absolute;inset:0;pointer-events:none}.node{position:absolute;transform:translate(-50%,-50%);min-width:140px;max-width:196px;text-align:left;padding:13px 14px 11px;background:linear-gradient(145deg,#191f26,#11161c);border:1px solid #343940;border-radius:10px;box-shadow:0 8px 24px #0003;pointer-events:auto;touch-action:none;user-select:none;transition:border-color .2s,box-shadow .2s,opacity .2s}.node:hover{border-color:#877046;box-shadow:0 8px 28px #0006,0 0 20px #ac7d1720}.node[aria-pressed=true]{border-color:var(--gold);box-shadow:0 0 30px #d8a34016}.node.offline{opacity:.55;border-style:dashed}.node.stale{border-style:dashed}.node-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.node-name{font-size:12px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.node-dot{width:5px;height:5px;border-radius:50%;background:var(--green);flex-shrink:0;box-shadow:0 0 8px #78bb9840}.node.offline .node-dot{background:#74808b;box-shadow:none}.node.stale .node-dot{background:var(--gold)}.node-model{font-size:10px;color:#87929f;margin-top:5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.node-reading{display:flex;align-items:baseline;gap:4px;margin-top:11px;font-size:17px;font-weight:400;letter-spacing:-.4px;color:var(--gold);font-variant-numeric:tabular-nums}.node-reading small{color:#818b97;font-size:10px;letter-spacing:0}.node-reading .unmeasured{font-size:11px;letter-spacing:0;color:#687685}.node-bar{height:2px;margin-top:9px;background:#ffffff08;border-radius:2px;overflow:hidden}.node-bar span{display:block;height:100%;background:var(--gold);opacity:.55}.node-hardware{position:absolute;left:50%;bottom:-22px;transform:translateX(-50%);color:#727e8b;font-size:10px;white-space:nowrap;max-width:180px;overflow:hidden;text-overflow:ellipsis;pointer-events:none}.hub{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);border:1px solid #9c772e;background:linear-gradient(130deg,#282111,#161711);box-shadow:0 0 45px #c3932720,inset 0 0 24px #cb9c2110;border-radius:13px;width:126px;padding:14px 10px 13px;text-align:center;color:var(--gold);z-index:2}.hub-kicker{display:block;font-size:8px;letter-spacing:2px;color:#9f864f}.hub-name{display:block;font-size:22px;letter-spacing:-.8px;margin:6px 0}.hub-status{display:block;font-size:9px;letter-spacing:.4px;color:#a89c7e}.map-controls{position:absolute;bottom:18px;left:32px;right:28px;display:flex;justify-content:space-between;align-items:center;gap:16px;font-size:10px;color:#657181}.map-controls button{background:none;border:0;color:#98a2ae;font-size:11px;padding:7px 0}.map-empty{position:absolute;inset:80px 26px 50px;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;gap:14px;pointer-events:none}.empty-orbit{font-size:86px;font-weight:200;color:var(--gold);opacity:.7}.map-empty h1{font-size:26px;letter-spacing:-.7px;font-weight:400}.map-empty p{font-size:13px;color:var(--muted);line-height:1.7;max-width:370px}.fleet-totals{display:flex;justify-content:center;gap:clamp(22px,6vw,90px);padding:4px 25px 30px}.fleet-totals>div{display:flex;flex-direction:column;gap:7px}.total-label{font-size:9px;letter-spacing:1.6px;color:#84909f}.fleet-totals strong{font-size:32px;line-height:1.1;letter-spacing:-1px;font-weight:400;font-variant-numeric:tabular-nums}.fleet-totals>div>span:last-child{font-size:10px;color:#657181}.activity{padding:20px 30px 26px;border-top:1px solid #ffffff0b}.section-heading{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:15px}.section-heading h2{font-weight:500;font-size:12px}.section-heading>span{font-size:10px;color:#6d7a89}.activity-row{display:grid;grid-template-columns:7px minmax(0,1fr) auto;align-items:center;gap:11px;margin-top:13px;font-size:11px;color:#b6bec7}.activity-row .pip{width:5px;height:5px;border-radius:50%;background:#80704e}.activity-row.running .pip{background:var(--gold);box-shadow:0 0 10px #dfb46555}.activity-row.failed .pip{background:var(--red)}.activity-row .activity-time{font-size:10px;color:#627080}.activity-row .message{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.quiet{font-size:12px;line-height:1.65;color:#728090}.inspector{border-left:1px solid #ffffff0b;padding:28px 24px;background:#0b0f14;min-width:0}.inspector-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:20px}.inspector-head h2{font-size:23px;font-weight:400;letter-spacing:-.8px;overflow-wrap:anywhere;margin-top:8px}.inspector-head .close{background:none;border:0;color:var(--muted);font-size:22px;padding:0 1px}.subline{color:var(--muted);font-size:11px;line-height:1.7;overflow-wrap:anywhere;margin-top:8px}.detail-status{display:flex;align-items:center;gap:7px;margin:16px 0 22px;font-size:11px;color:#aeb7c1}.detail-section{padding-top:21px;margin-top:22px;border-top:1px solid #ffffff0d}.detail-section h3{font-weight:500;font-size:11px;color:#9aa5b3;margin-bottom:13px}.detail-metrics{display:grid;grid-template-columns:1fr 1fr;gap:24px 15px}.detail-metric{min-width:0}.detail-metric .label{font-size:10px;color:#8190a1;display:block;margin-bottom:7px}.detail-metric .value{font-size:23px;font-weight:400;letter-spacing:-.7px;font-variant-numeric:tabular-nums}.detail-metric .value small{font-size:11px;color:#929ca8;letter-spacing:0}.detail-metric .hint{display:block;color:#657385;font-size:10px;margin-top:5px;line-height:1.5}.memory-track{height:4px;border-radius:3px;background:#ffffff0a;overflow:hidden;margin:11px 0 9px}.memory-track span{display:block;height:100%;background:linear-gradient(90deg,#95702e,var(--gold));border-radius:3px}.memory-labels{display:flex;justify-content:space-between;gap:10px;font-size:10px;color:#7c8c9b}.model-entry{display:flex;align-items:center;gap:10px;padding:10px 0}.model-glyph{width:24px;height:24px;border-radius:6px;color:#c9aa70;background:#b2853213;display:grid;place-items:center;font-size:15px;flex-shrink:0}.model-entry .model-title{font-size:11px;line-height:1.55;overflow-wrap:anywhere;flex:1}.model-entry .model-caption{display:block;font-size:10px;color:#6e7d8d;margin-top:2px}.host-row{display:flex;align-items:center;gap:9px;margin:13px 0;font-size:11px;color:#b3bcc8}.host-row button{border:0;background:transparent;padding:0;text-align:left;flex:1}.host-row small{display:block;font-size:10px;color:#67798b;line-height:1.5;margin-top:3px}.host-row .host-dot{width:5px;height:5px;border-radius:50%;background:var(--green)}.host-row.offline .host-dot{background:var(--red)}.detail-pair{display:flex;justify-content:space-between;gap:12px;font-size:11px;line-height:1.7;padding:5px 0}.detail-pair span{color:#7e8b9a}.detail-pair strong{font-weight:400;text-align:right;overflow-wrap:anywhere;max-width:65%;font-variant-numeric:tabular-nums}.endpoint{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:10px;color:#92a0af;overflow-wrap:anywhere;line-height:1.7}.source-error{padding:11px 12px;margin-top:12px;background:#bb86330c;border-left:2px solid #9c7137;color:#baac8e;font-size:11px;line-height:1.65}.ask-prompt{padding:14px;border:1px solid #dfb46524;border-radius:9px;margin-top:19px;background:#c59b4108}.ask-prompt p{font-size:12px;line-height:1.7;color:#c0b59e}.ask-prompt span{display:block;font-size:10px;color:#857651;margin-bottom:7px}.copy-prompt{background:transparent;color:var(--gold);border:0;padding:10px 0 0;font-size:11px}.spark{width:100%;height:73px;display:block}.spark-labels{display:flex;justify-content:space-between;font-size:9px;color:#627385;margin-top:5px}.spark-empty{height:73px;display:grid;place-items:center;font-size:10px;color:#657585;background:repeating-linear-gradient(0deg,transparent,transparent 23px,#ffffff04 24px)}.rack{padding:30px;display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:14px;min-height:500px;align-content:start}.rack-engine{background:linear-gradient(120deg,#141b22,#10151b);border:1px solid #2b3540;border-radius:9px;text-align:left;position:relative;padding:19px;min-width:0}.rack-engine[aria-pressed=true]{border-color:var(--gold)}.rack-engine.offline{opacity:.55}.rack-engine h3{font-size:14px;font-weight:500;overflow-wrap:anywhere}.rack-engine .rack-hardware{font-size:10px;color:var(--muted);margin-top:6px}.rack-engine .rack-models{font-size:11px;color:#a2adba;margin-top:16px;overflow-wrap:anywhere;line-height:1.5;min-height:30px}.rack-metrics{display:flex;flex-wrap:wrap;gap:18px;margin-top:18px}.rack-metrics>div{font-size:18px;letter-spacing:-.5px;font-variant-numeric:tabular-nums}.rack-metrics small{font-size:10px;letter-spacing:0;color:#7d8d9e}.rack-metrics label{display:block;font-size:9px;letter-spacing:0;color:#607387;margin-top:4px}.rack-strip{position:absolute;width:3px;left:0;top:20px;bottom:20px;background:#997b41;border-radius:2px}.footer{padding:16px 30px;border-top:1px solid #ffffff0b;display:flex;align-items:center;justify-content:space-between;gap:16px;font-size:10px;color:#677789}.footer>span:first-child{display:flex;align-items:center;gap:8px}.footer-dot{background:#806b42;width:4px;height:4px;box-shadow:none}.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);padding:12px 18px;border:1px solid #4e442b;background:#211c12;color:#dfc894;border-radius:9px;font-size:12px;z-index:10;max-width:90%;box-shadow:0 6px 32px #0008}
+.gpu-detail+.gpu-detail{margin-top:18px}
+@media(min-width:1051px){.topology[data-density=spacious] .node{min-width:210px;max-width:250px}}
+@media(min-width:1500px){.workspace{grid-template-columns:minmax(0,1fr) 340px}.topology{height:660px}.inspector{padding:32px}.node{min-width:166px;padding:16px}.node-name{font-size:14px}.node-model{font-size:11px}}
+@media(max-width:1050px){.workspace{grid-template-columns:minmax(0,1fr) 270px}.inspector{padding:24px 19px}.topology{height:600px}.node{min-width:126px;max-width:158px;padding:11px}.node-hardware{max-width:140px}.view-toolbar{padding-left:23px;padding-right:23px}.map-heading{left:23px}.map-controls{left:23px;right:23px}.fleet-totals{gap:30px}.total-label{letter-spacing:1px}.fleet-totals strong{font-size:28px}}
+@media(max-width:820px){.workspace{display:block}.inspector{border-left:0;border-top:1px solid #ffffff0b;padding:25px 28px}.inspector .detail-metrics{grid-template-columns:repeat(4,1fr)}.topology{height:560px}.inspector-head{margin-bottom:12px}.inspector .detail-section{margin-top:19px;padding-top:19px}.chrome{padding:0 24px}.node{min-width:134px}.spark{height:90px}}
+@media(max-width:540px){.chrome{height:auto;min-height:70px;padding:18px;flex-wrap:wrap;gap:12px}.brand{font-size:13px;gap:10px}.brand-divider{margin:0}.grid-name{max-width:150px}.connection{font-size:10px}.view-toolbar{padding:19px 16px 0;gap:8px}.metric-select{font-size:0;gap:0}.metric-select select{font-size:11px;max-width:126px}.segmented button{padding:7px 10px;font-size:11px}.map-heading{left:18px;top:23px}.map-subtitle{font-size:10px}.eyebrow{font-size:9px}.topology{height:665px}.node{min-width:111px;max-width:142px;padding:10px;border-radius:8px}.node-name{font-size:11px}.node-model{font-size:9px}.node-reading{font-size:16px;margin-top:8px}.node-reading small,.node-hardware{font-size:9px}.node-hardware{max-width:127px;bottom:-18px}.hub{width:110px;padding:11px 5px}.hub-name{font-size:20px}.hub-kicker{font-size:7px}.map-controls{left:18px;right:18px;font-size:9px;gap:8px}.map-controls button{font-size:10px}.fleet-totals{gap:20px;padding:8px 18px 25px;justify-content:space-between}.total-label{font-size:8px;letter-spacing:.7px}.fleet-totals strong{font-size:27px}.fleet-totals>div>span:last-child{font-size:9px;max-width:94px;line-height:1.5}.activity{padding:20px 18px}.inspector{padding:24px 20px}.inspector .detail-metrics{grid-template-columns:repeat(2,1fr)}.rack{padding:25px 18px}.footer{padding:16px 18px;font-size:9px;align-items:flex-start}.footer>span{max-width:50%;line-height:1.6}}
+@media(prefers-reduced-motion:reduce){*{transition:none!important}}
diff --git a/store/agents/autonomous-grid/viewer/app.js b/store/agents/autonomous-grid/viewer/app.js
new file mode 100644
index 000000000..11dcaf05c
--- /dev/null
+++ b/store/agents/autonomous-grid/viewer/app.js
@@ -0,0 +1,193 @@
+(() => {
+ 'use strict';
+ const $ = id => document.getElementById(id);
+ const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' }[c]));
+ const finite = n => typeof n === 'number' && Number.isFinite(n);
+ const fmt = (n, digits = 1) => finite(n) ? n.toLocaleString(undefined, { maximumFractionDigits: digits }) : '—';
+ const age = time => { const seconds = Math.max(0, (Date.now() - Date.parse(time)) / 1000); return !Number.isFinite(seconds) ? '' : seconds < 60 ? `${Math.floor(seconds)}s ago` : `${Math.floor(seconds / 60)}m ago`; };
+ const clockTime = time => time ? new Date(time).toLocaleTimeString([], { hour:'2-digit', minute:'2-digit' }) : '';
+ const metricInfo = { tokS: ['Last decode rate', 'tok/s'], temperatureC: ['GPU temperature', '°C'], utilizationPct: ['GPU utilization', '%'], memoryUsedGb: ['Memory used', 'GB'], powerW: ['GPU power', 'W'] };
+ let snapshot = null, selected = null, view = 'topology', metric = 'tokS';
+ let paused = matchMedia('(prefers-reduced-motion: reduce)').matches, positions = new Map(), drags = {}, dragging = null, moved = false;
+ let width = 0, height = 0, hub = { x:0,y:0 }, t = 0, previousFrame = 0, lastReceived = 0, transportLost = false, graphNodes = [];
+ let activeScope = '', toastTimer;
+ const stage = $('topology'), canvas = $('connections'), ctx = canvas.getContext('2d');
+ const nodeButtons = new Map();
+ const storage = { read: key => { try { return JSON.parse(localStorage.getItem(key)); } catch { return null; } }, write: (key,value) => { try { localStorage.setItem(key,JSON.stringify(value)); } catch {} } };
+ function measured(n) { return !n.stale && n.online !== false; }
+ function reading(n, field = metric) { return measured(n) ? n[field] : null; }
+ function metricMarkup(n, field = metric) { const value=reading(n,field); return finite(value) ? `${fmt(value)} <small>${metricInfo[field][1]}</small>` : '<span class="unmeasured">not reported</span>'; }
+ function toast(message) { $('toast').textContent=message; $('toast').hidden=false; clearTimeout(toastTimer); toastTimer=setTimeout(()=>{$('toast').hidden=true;},4000); }
+ function status() {
+ if (!snapshot) return;
+ const late = lastReceived && Date.now() - lastReceived > Math.max(30_000, (snapshot.pollIntervalMs || 8000)*3);
+ const state = transportLost || late ? 'disconnected' : snapshot.status;
+ const labels={live:'Grid connected',partial:'Partial telemetry',unavailable:'Grid unavailable',unconfigured:'Choose a grid',connecting:'Connecting',disconnected:'Connection lost'};
+ $('connection-label').textContent=labels[state] || 'Waiting for Grid';
+ $('connection-dot').className='status-dot'+(['unavailable','disconnected'].includes(state)?' offline':state==='live'?'':' pending');
+ $('observed').textContent=snapshot.observedAt?`Observed ${age(snapshot.observedAt)}`:'Waiting for Grid';
+ $('footer-status').textContent=['unavailable','disconnected'].includes(state)?'Last observations remain visible. Ask Grid to reconnect.':'Talk to Grid in the agent pane.';
+ }
+ function consume(data) {
+ if (!data || data.spec!==1 || !Array.isArray(data.nodes)) return;
+ snapshot=data;lastReceived=Date.now();transportLost=false;
+ if (activeScope!==data.scope) {
+ activeScope=data.scope || 'default';selected=null;
+ const saved=storage.read('grid-map:'+activeScope);drags=saved&&typeof saved==='object'?saved:{};
+ }
+ render();
+ }
+ function render() {
+ if (!snapshot) return;
+ $('grid-name').textContent=snapshot.grid;
+ $('mode').textContent=snapshot.mode || '';
+ const available=!['connecting','unavailable','unconfigured'].includes(snapshot.status);
+ $('total-engines').textContent=available?fmt(snapshot.summary.enginesOnline,0):'—';
+ $('total-known').textContent=snapshot.nodes.length?`${snapshot.nodes.length} known to this grid`:'waiting for engines';
+ $('total-models').textContent=available?fmt(snapshot.summary.modelsServing,0):'—';
+ const answered=snapshot.summary.answered;
+ $('total-requests').textContent=available?fmt(answered?.requests,0):'—';
+ $('requests-window').textContent=finite(answered?.windowSeconds)?`last ${fmt(answered.windowSeconds/3600,1)} hours`:'not reported by this grid';
+ graphNodes=snapshot.nodes.slice(0,12);
+ stage.dataset.density=graphNodes.length<=4?'spacious':'compact';
+ $('map-subtitle').textContent=snapshot.nodes.length>12?`12 of ${snapshot.nodes.length} engines · see every engine in Rack`:'Every machine has a place.';
+ $('map-empty').hidden=graphNodes.length>0;
+ $('hub').hidden=graphNodes.length===0;
+ $('empty-message').textContent=snapshot.status==='unconfigured'?'Ask the Grid agent to connect one of your existing grids, or help you create your first fleet.':snapshot.status==='unavailable'?'Grid isn’t reachable yet. Ask the agent to check your connection, choose a grid, or start one.':'Ask the Grid agent to discover this machine and deploy your first model.';
+ $('hub-status').textContent=available?`${snapshot.summary.enginesOnline || 0} engines online`:'awaiting connection';
+ const ids=new Set(graphNodes.map(n=>n.id));
+ for (const [id,b] of nodeButtons) if (!ids.has(id)) { b.remove();nodeButtons.delete(id); }
+ for (const n of graphNodes) {
+ let b=nodeButtons.get(n.id);
+ if(!b){
+ b=document.createElement('button');b.type='button';b.dataset.node=n.id;
+ b.addEventListener('click',()=>{if(moved){moved=false;return;}select(n.id);});
+ b.addEventListener('pointerdown',event=>{if(event.button!==0)return;dragging={id:n.id,x:event.clientX,y:event.clientY};moved=false;b.setPointerCapture?.(event.pointerId);});
+ b.addEventListener('pointermove',event=>{
+ if(!dragging||dragging.id!==n.id)return;
+ if(Math.hypot(event.clientX-dragging.x,event.clientY-dragging.y)>5)moved=true;
+ if(!moved)return;
+ const bounds=stage.getBoundingClientRect();
+ drags[n.id]={x:(event.clientX-bounds.left)/width,y:(event.clientY-bounds.top)/height};position();draw();
+ });
+ b.addEventListener('pointerup',()=>{dragging=null;if(moved)storage.write('grid-map:'+activeScope,drags);});
+ b.addEventListener('pointercancel',()=>{dragging=null;moved=false;});
+ $('nodes').appendChild(b);nodeButtons.set(n.id,b);
+ }
+ b.className=`node${n.online===false?' offline':''}${n.stale?' stale':''}`;
+ b.setAttribute('aria-pressed',String(selected===n.id));
+ b.setAttribute('aria-label',`${n.name}, ${n.stale?'stale observation':n.online===false?'offline':n.online===true?'online':'status not reported'}, ${n.models.join(', ') || 'no models'}, ${metricInfo[metric][0]} ${fmt(reading(n))} ${metricInfo[metric][1]}`);
+ const usage=finite(n.memoryUsedGb)&&n.memoryTotalGb>0?Math.min(100,n.memoryUsedGb/n.memoryTotalGb*100):null;
+ b.innerHTML=`<span class="node-head"><span class="node-name">${escape(n.name)}</span><span class="node-dot"></span></span><span class="node-model" style="display:block">${escape(n.models[0] || 'No models')}${n.models.length>1?` +${n.models.length-1}`:''}</span><span class="node-reading">${metricMarkup(n)}</span>${usage!==null?`<span class="node-bar" style="display:block"><span style="width:${usage}%"></span></span>`:''}<span class="node-hardware">${escape(n.hardware || n.engine)}</span>`;
+ }
+ renderRack();renderInspector();renderActivity();resize();status();
+ }
+ function select(id) {selected=selected===id?null:id;for(const [key,b]of nodeButtons)b.setAttribute('aria-pressed',String(key===selected));renderInspector();renderRack();draw();}
+ function renderRack() {
+ if(!snapshot)return;
+ $('rack').innerHTML=snapshot.nodes.length?snapshot.nodes.map(n=>`<button class="rack-engine${n.online===false?' offline':''}" type="button" data-select="${escape(n.id)}" aria-pressed="${selected===n.id}"><span class="rack-strip"></span><h3>${escape(n.name)}</h3><div class="rack-hardware">${escape(n.hardware || n.engine)} · ${n.stale?'stale':n.online===false?'offline':n.online===true?'online':'status unavailable'}</div><div class="rack-models">${escape(n.models.join(' · ') || 'No models advertised')}</div><div class="rack-metrics"><div>${metricMarkup(n,'tokS')}<label>last decode</label></div><div>${metricMarkup(n,'temperatureC')}<label>temperature</label></div><div>${metricMarkup(n,'memoryUsedGb')}<label>memory used</label></div></div></button>`).join(''):'<div class="quiet">Your engines will appear here when they join Grid.</div>';
+ }
+ const pair=(label,value)=>`<div class="detail-pair"><span>${escape(label)}</span><strong>${escape(value)}</strong></div>`;
+ const detailMetric=(label,value,unit,hint='')=>`<div class="detail-metric"><span class="label">${escape(label)}</span><span class="value">${fmt(value)} <small>${escape(unit)}</small></span>${hint?`<span class="hint">${escape(hint)}</span>`:''}</div>`;
+ function prompt(text) {return `<div class="ask-prompt"><span>ASK YOUR GRID AGENT</span><p>${escape(text)}</p><button class="copy-prompt" type="button" data-prompt="${escape(text)}">Copy request ↗</button></div>`;}
+ function gpuDetails(g) {
+ const used=finite(g.memoryUsedGb)&&g.memoryGb>0?Math.max(0,Math.min(100,g.memoryUsedGb/g.memoryGb*100)):0;
+ return `<div class="gpu-detail"><div class="model-entry"><span class="model-glyph">▧</span><span class="model-title">${escape(g.name)}<span class="model-caption">${fmt(g.memoryUsedGb)} / ${fmt(g.memoryGb)} GB used</span></span></div><div class="memory-track"><span style="width:${used}%"></span></div><div class="memory-labels"><span>${fmt(g.utilizationPct)}% load</span><span>${fmt(g.temperatureC)} °C · ${fmt(g.powerW)} W</span></div></div>`;
+ }
+ function renderInspector() {
+ if(!snapshot)return;
+ const node=snapshot.nodes.find(n=>n.id===selected), machine=snapshot.machines?.find(m=>'machine:'+m.id===selected);
+ const panel=$('inspector');
+ if(machine){
+ panel.innerHTML=`<div class="inspector-head"><div><span class="eyebrow">MANAGED MACHINE</span><h2>${escape(machine.name)}</h2><p class="subline">${escape(machine.hardware || machine.error || '')}</p></div><button class="close" type="button" data-close aria-label="Close machine details">×</button></div><div class="detail-status"><span class="status-dot${machine.reachable?'':' offline'}"></span>${machine.reachable?'Reachable':'Unreachable'} · ${escape(machine.transport)}</div><div class="detail-metrics">${detailMetric('System memory',machine.memoryTotalGb,'GB')}${detailMetric('Grid RAM estimate',machine.memoryAvailableGb,'GB','Inventory, not live usage')}${detailMetric('Grid model budget',machine.usableModelGb,'GB')}${detailMetric('Free disk',machine.diskFreeGb,'GB')}</div><div class="detail-section">${pair('Platform',machine.platform || '—')}${pair('Backend',machine.backend || '—')}${pair('CPU cores',fmt(machine.cpuCores,0))}${pair('Observed',age(machine.observedAt))}</div><div class="detail-section"><h3>Graphics</h3>${machine.gpus?.map(gpuDetails).join('')||'<p class="quiet">No GPU reported. CPU models can still be useful.</p>'}</div>${prompt(`Find an open-weight model that fits ${machine.name}, keeping enough memory free for my other work. Explain the tradeoff before deploying it.`)}`;
+ return;
+ }
+ if(node){
+ const total=node.memoryTotalGb,used=node.memoryUsedGb;
+ const fill=total>0&&finite(used)?Math.max(0,Math.min(100,used/total*100)):0;
+ panel.innerHTML=`<div class="inspector-head"><div><span class="eyebrow">ENGINE DETAILS</span><h2>${escape(node.name)}</h2><p class="subline">${escape(node.hardware || node.engine)}${node.platform?`<br>${escape(node.platform)}`:''}</p></div><button class="close" type="button" data-close aria-label="Close engine details">×</button></div><div class="detail-status"><span class="status-dot${node.stale?' pending':node.online===false?' offline':''}"></span>${node.stale?'Last known observation':node.online===true?'Online':node.online===false?'Offline':'Status not reported'}${node.hosted?' · hosted model':''}</div><div class="detail-metrics">${detailMetric('Last decode rate',node.tokS,'tok/s','Per-engine estimate')}${detailMetric('GPU temperature',node.temperatureC,'°C')}${detailMetric('GPU utilization',node.utilizationPct,'%')}${detailMetric('GPU power',node.powerW,'W',node.powerLimitW!==null?`${fmt(node.powerLimitW)} W limit`:'')}</div><div class="detail-section"><h3>${escape(node.memoryKind || 'Model memory')}${node.stale?' · last known':''}</h3>${node.hosted?'<p class="quiet">Hosted models do not contribute local GPU memory.</p>':`<div class="detail-pair"><strong>${fmt(used)} <span>/ ${fmt(total)} GB</span></strong></div><div class="memory-track"><span style="width:${fill}%"></span></div><div class="memory-labels"><span>${fmt(node.memoryFreeGb)} GB free</span><span>${total>0&&finite(used)?fmt(used/total*100,0)+'% used':'not reported'}</span></div>`}</div><div class="detail-section"><h3>${escape(metricInfo[metric][0])} · recent observations</h3>${spark(node.id)}</div><div class="detail-section"><h3>Models on this engine · ${node.models.length}</h3>${node.models.map(model=>{const caps=node.capabilities?.find(c=>c.model===model);return `<div class="model-entry"><span class="model-glyph">◇</span><span class="model-title">${escape(model)}<span class="model-caption">${caps?.contextLength?`${fmt(caps.contextLength,0)} context tokens`:''}${caps?.responses?' · Responses API':''}</span></span></div>`;}).join('')||'<p class="quiet">No models advertised.</p>'}</div><div class="detail-section">${pair('Engine',node.engine)}${pair('Concurrency',fmt(node.concurrency,0))}${pair('Active requests',fmt(node.activeRequests,0))}${pair('Disk',`${fmt(node.diskUsedGb)} / ${fmt(node.diskTotalGb)} GB`)}${pair('Output tokens',fmt(node.answered?.tokensOut,0))}${pair('Usage window',node.answered?.windowSeconds?`${fmt(node.answered.windowSeconds/3600)} hours`:'—')}${pair('Last observed',age(node.observedAt))}${node.endpoint?`<div class="endpoint">${escape(node.endpoint)}</div>`:''}</div>${prompt(`Review the models on ${node.name} and suggest a better placement for my workload, using measured memory and performance.`)}`;
+ return;
+ }
+ const errors=Object.values(snapshot.sources || {}).filter(s=>!s.ok);
+ panel.innerHTML=`<div class="inspector-head"><div><span class="eyebrow">FLEET OVERVIEW</span><h2>One grid.<br>All your compute.</h2><p class="subline">An agent that knows your machines.<br>A place for every model.</p></div></div><div class="detail-section" style="border-top:0;padding-top:0"><h3>Serving on your grid</h3>${snapshot.models.map(m=>`<div class="model-entry"><span class="model-glyph">◇</span><span class="model-title">${escape(m.id)}<span class="model-caption">${m.nodes.length} ${m.nodes.length===1?'engine':'engines'}</span></span></div>`).join('')||'<p class="quiet">No serving models reported yet.</p>'}</div><div class="detail-section"><h3>Managed machines · ${snapshot.machines?.length||0}</h3>${(snapshot.machines||[]).map(m=>`<div class="host-row${m.reachable?'':' offline'}"><span class="host-dot"></span><button type="button" data-select="machine:${escape(m.id)}">${escape(m.name)}<small>${escape(m.hardware || (m.reachable?m.transport:'unreachable'))}${finite(m.memoryTotalGb)?` · ${fmt(m.memoryTotalGb,0)} GB`:''}</small></button></div>`).join('')}<p class="quiet">Select a machine to inspect its capacity.</p></div>${snapshot.endpoint?`<div class="detail-section"><h3>Your endpoint</h3><div class="endpoint">${escape(snapshot.endpoint)}</div></div>`:''}${errors.map(s=>`<div class="source-error">${escape(s.error)}</div>`).join('')}${prompt(snapshot.nodes.length?'Find the best way to run a coding model and a fast everyday chat model across my machines.':'Discover my machines and help me deploy an open-weight model that fits.')}`;
+ }
+ function spark(id) {
+ const samples=snapshot.history?.[id]||[],valid=samples.filter(s=>finite(s[metric]));
+ if(valid.length<2)return '<div class="spark-empty">Waiting for measured history</div>';
+ const start=Date.parse(samples[0].at),end=Date.parse(samples.at(-1).at),span=end-start||1,max=Math.max(...valid.map(s=>s[metric]),1)*1.15;
+ let d='',pen=false;
+ for(const sample of samples){if(!finite(sample[metric])){pen=false;continue;}const x=3+(Date.parse(sample.at)-start)/span*244,y=64-sample[metric]/max*53;d+=`${pen?'L':'M'}${x.toFixed(1)},${y.toFixed(1)} `;pen=true;}
+ return `<svg class="spark" viewBox="0 0 250 73" role="img" aria-label="${escape(metricInfo[metric][0])} history, ${valid.length} observations"><path d="M0 64H250 M0 37H250 M0 10H250" stroke="#ffffff0a" fill="none"/><path d="${d}" stroke="#dfb465" stroke-width="1.6" fill="none"/><text x="247" y="9" fill="#778799" font-size="8" text-anchor="end">${fmt(max)} ${metricInfo[metric][1]}</text></svg><div class="spark-labels"><span>${clockTime(samples[0].at)}</span><span>${clockTime(samples.at(-1).at)}</span></div>`;
+ }
+ function renderActivity() {
+ const operations=(snapshot.operations||[]).map(op=>({id:op.id,at:op.endedAt||op.startedAt,kind:op.phase,message:`${snapshot.machines?.find(m=>m.id===op.machine)?.name||op.machine} · ${op.command} · ${op.phase}`}));
+ const events=[...operations,...(snapshot.events||[])].sort((a,b)=>Date.parse(b.at)-Date.parse(a.at)).slice(0,5);
+ $('activity-list').innerHTML=events.length?events.map(event=>`<div class="activity-row ${escape(event.kind)}"><span class="pip"></span><span class="message">${escape(event.message)}</span><span class="activity-time">${escape(age(event.at))}</span></div>`).join(''):'<div class="quiet">Grid operations and changes to your fleet appear here.</div>';
+ }
+ function resize() {
+ if(view==='rack')return;
+ width=stage.clientWidth||800;
+ const small=width<620;
+ const expanded=small?230+Math.ceil(graphNodes.length/2)*144:graphNodes.length>8?Math.max(680,200+Math.ceil(graphNodes.length/4)*150):560;
+ stage.style.height=Math.max(width<540?600:560,expanded)+'px';height=stage.clientHeight;
+ const dpr=Math.min(window.devicePixelRatio||1,2);canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr);ctx?.setTransform(dpr,0,0,dpr,0,0);
+ position();draw();
+ }
+ function position() {
+ const small=width<620,count=graphNodes.length;
+ hub={x:width*.5,y:small?150:height*.49};
+ $('hub').style.left=hub.x+'px';$('hub').style.top=hub.y+'px';
+ const anchors=[[.14,.31],[.36,.18],[.15,.63],[.36,.83],[.69,.17],[.85,.40],[.85,.73],[.64,.88]];
+ const smallFleet={1:[[.22,.49]],2:[[.22,.35],[.78,.65]],3:[[.20,.34],[.80,.34],[.50,.85]],4:[[.20,.32],[.80,.32],[.20,.76],[.80,.76]]};
+ graphNodes.forEach((n,i)=>{
+ const b=nodeButtons.get(n.id);if(!b)return;
+ let base;
+ if(small)base={x:width*(i%2===0?.25:.75),y:275+Math.floor(i/2)*144};
+ else if(count<=8){const a=(smallFleet[count]||anchors)[i];base={x:width*a[0],y:height*a[1]};}
+ else {const half=Math.ceil(count/2),left=i<half;const k=left?i:i-half;base={x:width*(left?.18:.82),y:115+k*(height-190)/(half-1)};}
+ const stored=drags[n.id];if(stored&&finite(stored.x)&&finite(stored.y))base={x:stored.x*width,y:stored.y*height};
+ const inset=(b.offsetWidth||140)/2+12;
+ const x=Math.max(inset,Math.min(width-inset,base.x+(dragging?.id===n.id?0:Math.sin(t*.20+i*.78)*3)));
+ const y=Math.max(105,Math.min(height-95,base.y+(dragging?.id===n.id?0:Math.cos(t*.18+i*.64)*3)));
+ positions.set(n.id,{x,y});b.style.left=x+'px';b.style.top=y+'px';
+ });
+ }
+ function draw() {
+ if(!ctx||view!=='topology')return;
+ ctx.clearRect(0,0,width,height);
+ if(!graphNodes.length)return;
+ const glow=ctx.createRadialGradient(hub.x,hub.y,10,hub.x,hub.y,180);glow.addColorStop(0,'rgba(185,134,36,.13)');glow.addColorStop(1,'rgba(170,117,27,0)');ctx.fillStyle=glow;ctx.fillRect(0,0,width,height);
+ for(let i=0;i<70;i++){ctx.fillStyle=`rgba(171,159,130,${i%6===0?.16:.06})`;ctx.beginPath();ctx.arc(((i*173.87+42)%991)/991*width,((i*131.2+31)%587)/587*height,i%5===0?1:.55,0,Math.PI*2);ctx.fill();}
+ for(let i=0;i<graphNodes.length;i++){
+ const node=graphNodes[i],p=positions.get(node.id);if(!p)continue;
+ const online=node.online===true&&!node.stale&&!transportLost&&Date.now()-lastReceived<30000,active=finite(node.activeRequests)?node.activeRequests:0,chosen=selected===node.id;
+ ctx.beginPath();ctx.strokeStyle=chosen?'rgba(237,188,85,.70)':online?'rgba(173,140,74,.31)':'rgba(115,126,141,.17)';ctx.lineWidth=chosen?1.35:.75;ctx.setLineDash(online?[]:[3,7]);ctx.moveTo(hub.x,hub.y);ctx.lineTo(p.x,p.y);ctx.stroke();ctx.setLineDash([]);
+ // Connection pulses express online membership. Only measured active requests add extra pulses.
+ if(online){const pulses=1+Math.min(3,active);for(let j=0;j<pulses;j++){const progress=(t*(.045+Math.min(active,4)*.008)+i*.137+j/pulses)%1;const x=hub.x+(p.x-hub.x)*progress,y=hub.y+(p.y-hub.y)*progress;ctx.beginPath();ctx.strokeStyle='rgba(232,183,78,.27)';ctx.moveTo(x-(p.x-hub.x)*.026,y-(p.y-hub.y)*.026);ctx.lineTo(x,y);ctx.stroke();ctx.fillStyle=chosen?'#f4d795':'#c4a25e';ctx.shadowColor='#d5ab52';ctx.shadowBlur=6;ctx.beginPath();ctx.arc(x,y,chosen?1.8:1.25,0,Math.PI*2);ctx.fill();ctx.shadowBlur=0;}}
+ }
+ for(let ring=0;ring<3;ring++){ctx.beginPath();ctx.strokeStyle=ring===0?'rgba(211,165,72,.63)':`rgba(190,146,55,${ring===1?.12:.05})`;ctx.lineWidth=ring===0?1.7:1;const angle=t*.075*(ring%2?-1:1);ctx.arc(hub.x,hub.y,88+ring*13,angle,angle+Math.PI*(ring===0?1.85:1.4));ctx.stroke();}
+ }
+ function frame(time) {
+ if(!paused&&!document.hidden&&view==='topology') {t+=Math.min((time-previousFrame)/1000,.08)||0;position();draw();}
+ previousFrame=time;requestAnimationFrame(frame);
+ }
+ function setView(value) {view=value;$('topology').hidden=value!=='topology';$('rack').hidden=value!=='rack';$('topology-button').setAttribute('aria-pressed',String(value==='topology'));$('rack-button').setAttribute('aria-pressed',String(value==='rack'));resize();}
+ $('topology-button').addEventListener('click',()=>setView('topology'));
+ $('rack-button').addEventListener('click',()=>setView('rack'));
+ $('metric').addEventListener('change',event=>{metric=event.target.value;render();});
+ $('motion').addEventListener('click',()=>{paused=!paused;$('motion').textContent=paused?'Resume motion':'Pause motion';$('motion').setAttribute('aria-pressed',String(paused));});
+ $('motion').textContent=paused?'Resume motion':'Pause motion';$('motion').setAttribute('aria-pressed',String(paused));
+ $('hub').addEventListener('click',()=>{selected=null;render();});
+ document.addEventListener('click',async event=>{
+ const close=event.target.closest('[data-close]'),selection=event.target.closest('[data-select]'),copy=event.target.closest('[data-prompt]');
+ if(close){selected=null;render();}else if(selection)select(selection.dataset.select);
+ else if(copy){try{await navigator.clipboard.writeText(copy.dataset.prompt);toast('Request copied. Paste it into your Grid agent.');}catch{toast('Select the request text and paste it into your Grid agent.');}}
+ });
+ new ResizeObserver(()=>resize()).observe(stage);
+ const stream=new EventSource('events');
+ stream.addEventListener('snapshot',event=>{try{consume(JSON.parse(event.data));}catch{transportLost=true;status();}});
+ stream.onerror=()=>{transportLost=true;status();};
+ const fetchSnapshot=()=>fetch('api/snapshot',{signal:AbortSignal.timeout(12_000)}).then(r=>{if(!r.ok)throw new Error();return r.json();}).then(consume).catch(()=>{transportLost=true;status();});
+ fetchSnapshot();setInterval(()=>{status();if(transportLost)fetchSnapshot();},8000);
+ requestAnimationFrame(frame);
+})();
diff --git a/store/agents/autonomous-grid/viewer/index.html b/store/agents/autonomous-grid/viewer/index.html
new file mode 100644
index 000000000..844f456b4
--- /dev/null
+++ b/store/agents/autonomous-grid/viewer/index.html
@@ -0,0 +1,45 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="color-scheme" content="dark">
+ <title>Grid · Your AI fleet</title>
+ <link rel="stylesheet" href="app.css">
+ <script src="app.js" defer></script>
+</head>
+<body>
+ <main id="grid-app">
+ <header class="chrome">
+ <div class="brand"><span class="brand-mark" aria-hidden="true"><i></i><i></i><i></i><i></i></span><span>GRID</span><span class="brand-divider"></span><span class="grid-name" id="grid-name">Your grid</span></div>
+ <div class="connection"><span id="connection-dot" class="status-dot pending"></span><span id="connection-label">Connecting</span><span id="mode" class="mode"></span></div>
+ </header>
+ <section class="workspace">
+ <div class="main-column">
+ <div class="view-toolbar">
+ <div class="segmented" aria-label="Fleet view"><button id="topology-button" type="button" aria-pressed="true">Topology</button><button id="rack-button" type="button" aria-pressed="false">Rack</button></div>
+ <label class="metric-select">Show <select id="metric"><option value="tokS">Decode speed</option><option value="temperatureC">Temperature</option><option value="utilizationPct">GPU load</option><option value="memoryUsedGb">Memory used</option><option value="powerW">Power</option></select></label>
+ </div>
+ <div class="topology" id="topology">
+ <canvas id="connections" aria-hidden="true"></canvas>
+ <div class="map-heading"><span class="eyebrow">YOUR COMPUTE, CONNECTED</span><span class="map-subtitle" id="map-subtitle">Every machine has a place.</span></div>
+ <div class="node-layer" id="nodes" aria-label="Grid engines"></div>
+ <button class="hub" id="hub" type="button" aria-label="Inspect your grid"><span class="hub-kicker">THE NETWORK</span><span class="hub-name">your grid</span><span class="hub-status" id="hub-status">connecting</span></button>
+ <div class="map-empty" id="map-empty" hidden><span class="empty-orbit" aria-hidden="true">◎</span><h1>Your fleet starts here.</h1><p id="empty-message">Ask the Grid agent to discover this machine and connect your first model.</p></div>
+ <div class="map-controls"><span id="map-legend">Links show Grid membership</span><button type="button" id="motion" aria-pressed="false">Pause motion</button></div>
+ </div>
+ <section class="rack" id="rack" aria-label="Engine rack" hidden></section>
+ <div class="fleet-totals">
+ <div><span class="total-label">ENGINES ONLINE</span><strong id="total-engines">—</strong><span id="total-known"></span></div>
+ <div><span class="total-label">MODELS SERVING</span><strong id="total-models">—</strong><span>across your grid</span></div>
+ <div><span class="total-label">REQUESTS</span><strong id="total-requests">—</strong><span id="requests-window">waiting for a measurement</span></div>
+ </div>
+ <section class="activity"><div class="section-heading"><h2>Activity</h2><span id="observed">Waiting for Grid</span></div><div id="activity-list" aria-live="polite"><div class="quiet">Listening for your fleet.</div></div></section>
+ </div>
+ <aside class="inspector" id="inspector" aria-label="Fleet details"></aside>
+ </section>
+ <footer class="footer"><span><span class="footer-dot"></span> Your machines. Your models.</span><span id="footer-status">Talk to Grid in the agent pane.</span></footer>
+ <div class="toast" id="toast" role="status" hidden></div>
+ </main>
+</body>
+</html>