The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Add the Machines harness: the fleet, managed by asking (#161)
Dee3a0cbe648882
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex f1d4b8685..97194744d 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -797,6 +797,15 @@ class _SwarmScreenState extends State<SwarmScreen> {case 'linkMachine':await _dialog(() => showSwarmLinkDialog(context, app));case 'manageMachines':+ // The Machines harness: the fleet managed by talking to it, with the+ // live map beside the terminal. Wrapped like Open Grid because the+ // notifier opens New Harness here and the tab it makes takes focus.+ await _dialog(() => app.manageMachines(context));+ // BRIDGE, until the Machines menu goes: the old list, so nothing is lost+ // between this release and that one. When the menu is removed, delete+ // this case, `machines.list` below, machines_manager.dart and its test,+ // and the `machineList` action in SwarmTitlebar.swift + keymap_commands.+ case 'machineList':unawaited(_dialog(() => showMachinesManager(context, app)));case 'refreshMachines':unawaited(app.retryMachines());@@ -883,6 +892,7 @@ class _SwarmScreenState extends State<SwarmScreen> {'newAgent','newTerminal','manageMachines',+ 'machineList','deleteMachine','splitRight','splitDown',@@ -1491,7 +1501,8 @@ class _SwarmScreenState extends State<SwarmScreen> {'pane.focus_$i': () => app.focusPaneByIndex(i - 1),'navigation.commands': _showSearchCommands,'machine.link': () => _dialog(() => showSwarmLinkDialog(context, app)),- 'machines.manage': () => _dialog(() => showMachinesManager(context, app)),+ 'machines.manage': () => _dialog(() => app.manageMachines(context)),+ 'machines.list': () => _dialog(() => showMachinesManager(context, app)),'project.add': _addProject,'keyboard.open_config': () => openKeyboardConfig(context),'pane.resize': app.beginPaneResize,diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex 0d97adfa9..9f23a981a 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -302,10 +302,16 @@ final harnessCommands = <HarnessCommand>[),const HarnessCommand('machines.manage',- 'Open Machines Manager',+ 'Manage Machines',ShortcutGroup.actions,nativeAction: 'manageMachines',),+ const HarnessCommand(+ 'machines.list',+ 'Open Machines Manager',+ ShortcutGroup.actions,+ nativeAction: 'machineList',+ ),const HarnessCommand('machine.link','Link machine',diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 5d3d71fbc..ba3c86207 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -3988,8 +3988,38 @@ class AppNotifier extends ChangeNotifier {await openStoreAgent(context, this, gridHarness, machineId);}- /// The machine Grid belongs on when no door named one: this computer's own- /// when the app has one, else whatever the person is looking at.+ /// The Store harness the Machines menu opens: the fleet itself, managed by+ /// talking to it, with the live map of every machine beside the terminal.+ static const machinesHarness = 'autonomous/machines';++ /// Open Machines, the same way [runLocalModel] opens Grid.+ ///+ /// It belongs on THIS computer and nowhere else: everything it reads — the+ /// machine list, each machine's roster — it reads through the local daemon,+ /// so a copy opened on a remote machine would be describing that machine's+ /// fleet, not the one in front of the person. Not installed here → the+ /// Store, open on its page, whose Install is the way in.+ Future<void> manageMachines(BuildContext context) async {+ final machine = _localModelMachine();+ if (machine == null) {+ _lastError = 'Connect a machine before opening Machines.';+ _lastErrorRetryable = false;+ notifyListeners();+ return;+ }+ final machineId = machine.machine.machineId;+ await probeDsh(machineId);+ if (machine.dsh[machinesHarness]?.installed != true) {+ openStore(harness: machinesHarness);+ return;+ }+ if (!context.mounted) return;+ await openStoreAgent(context, this, machinesHarness, machineId);+ }++ /// The machine Grid and Machines belong on when no door named one: this+ /// computer's own when the app has one, else whatever the person is looking+ /// at.MachineState? _localModelMachine() {final local = machineStates.values.where((state) => state.isLocalMachine)diff --git a/desktop/lib/state/command_bar_catalog.dart b/desktop/lib/state/command_bar_catalog.dartindex 1134fcb69..45424e629 100644--- a/desktop/lib/state/command_bar_catalog.dart+++ b/desktop/lib/state/command_bar_catalog.dart@@ -11,7 +11,9 @@ const commandBarCommands = {'navigation.history': 'Return to previously opened harnesses and sessions.','app.settings':'Change preferences, appearance, account or connection settings.',- 'machines.manage': 'See connected computers and manage machine connections.',+ 'machines.manage':+ 'Open Machines, the harness that links, names and retires your computers.',+ 'machines.list': 'See connected computers and their link state.','machine.link': 'Open the setup dialog to connect another computer.','swarm.new': 'Open a fresh empty tab.','swarm.reopen': 'Reopen the most recently closed harness.',@@ -38,9 +40,10 @@ const _commandPhrases = {'show settings','open preferences',],- 'machines.manage': [+ 'machines.manage': ['manage machines', 'open machines'],+ 'machines.list': ['show machines',- 'manage machines',+ 'machine list','show connected computers',],'machine.link': ['link machine', 'connect a computer'],diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 406f8a823..d14f7c3f0 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -100,7 +100,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}private func sendTabAction(_ method: String, arguments: Any?) {- guard ["select", "close", "new", "rename", "commands", "notifications", "addAgent", "newAgent", "newTerminal", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines"].contains(method) else {+ guard ["select", "close", "new", "rename", "commands", "notifications", "addAgent", "newAgent", "newTerminal", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {channel.invokeMethod(method, arguments: arguments)return}@@ -324,10 +324,18 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {$0.count.isEmpty ? $0.status : $0.count)})let trailingEdge = ceil((compactEdge + 62) * 1.2) - 62+ // Two doors for one release: the Machines harness, which manages the fleet by conversation and+ // draws it, and the plain list beneath it. The second is a bridge — it goes when this menu does,+ // along with machines_manager.dart and the "machineList" action.+ let manage = NSMenuItem(title: "Manage Machines…", action: #selector(menuAction(_:)), keyEquivalent: "")+ manage.target = self+ manage.representedObject = "manageMachines"+ manage.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "manageMachines")+ machinesMenu.addItem(manage)let manager = NSMenuItem(title: "Open Machines Manager", action: #selector(menuAction(_:)), keyEquivalent: "")manager.target = self- manager.representedObject = "manageMachines"- manager.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "manageMachines")+ manager.representedObject = "machineList"+ manager.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "machineList")machinesMenu.addItem(manager)machinesMenu.addItem(.separator())var lastSection: Bool? = nildiff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dartindex 3239bb598..5b2ea0616 100644--- a/desktop/test/machines_manager_test.dart+++ b/desktop/test/machines_manager_test.dart@@ -56,7 +56,8 @@ void main() {final input = <TerminalBinaryFrame>[];app.adoptSessionForTest(terminal('a0', input));await mount(tester, app, nativeTabs: true);- final opened = native(tester, 'manageMachines');+ // 'manageMachines' now opens the Machines harness; the plain list is 'machineList'.+ final opened = native(tester, 'machineList');await tester.pumpAndSettle();await opened;expect(find.text('Machines Manager'), findsOneWidget);diff --git a/store/agents/machines/.gitignore b/store/agents/machines/.gitignorenew file mode 100644index 000000000..5acb34d33--- /dev/null+++ b/store/agents/machines/.gitignore@@ -0,0 +1,3 @@+.venv/+node_modules/+.harness/diff --git a/store/agents/machines/AGENTS.md b/store/agents/machines/AGENTS.mdnew file mode 100644index 000000000..5363a1fd0--- /dev/null+++ b/store/agents/machines/AGENTS.md@@ -0,0 +1,64 @@+# Machines agent++These instructions apply in a **materialized Machines workspace** containing `machines.json`.+You look after the computers the person works on — one laptop, or a desk of machines and a rack in+a cupboard. They say what they want; you find the machine, do the one thing, and leave the map+beside you true. Say **machine** for a computer, **harness** for one running session on it, and+**agent** for who is running in it (Claude, Codex, Marp…). Never say "DSH", "node" or "grid".++**Greet, then listen, then look, then act — in that order.** "hi", "hello", anything with no+request in it gets two lines and one question: who you are in their terms, what you can do here,+and the question tool with the options *Show my machines · Bring a computer in · Link a machine ·+Rename or retire one*. Nothing runs until they pick. A request gets the fleet looked at+(`"$MACHINES_CLI" status`) and the one named thing done.++**Ask through a tool, not prose.** Every "ask" means the question tool with real options — which+machine, which name, the go-ahead before anything irreversible. A question mark in a paragraph is+not a stop. **Talk the way Harness talks:** short, declarative, second person; say what is true and+what happens next; no "I'd be happy to", no exclamation marks. Something that is not set up is said+plainly and stopped at, the way a failed build is reported.++Read `skills/fleet-operations/SKILL.md` from this package before operating the fleet. `$MACHINES_CLI`+is the command runner; every operation below is one of its subcommands, and running them is how the+pane and this workspace stay in step. The terminal beside the pane is the conversation: do not build+another interface, and do not hand the person a command to type — the one exception is a command+that must run on **another** computer, which is theirs to run there.++**Look before you act.** `"$MACHINES_CLI" status` reads the observation the pane has already+published — no network, no second poll. Use `list` or `refresh` when the person has just changed+something on another machine and the published reading would be behind. A machine that is not+linked from this computer has **no roster at all**: say "not readable from here", never "no+harnesses". Never invent a machine, a count, a project or a harness; a number you did not read is a+number you do not have.++**The remote password is never yours to hold.** Linking a machine proves you know the password set+on that machine. It belongs in the pane: the row for an unlinked machine has a Link field that+sends it straight to Harness. Point the person there; do not ask them to type it to you, and if+they type it anyway, pipe it once (`link <machine> --stdin`), never repeat it, and never write it+down. `machines password status` says whether THIS computer can be linked to; setting one is the+same rule.++**Bringing a computer in** is two halves. `machines invite` prints the steps for the other machine —+install, `harness login` on this account, `harness start && harness remote-password set` — and those+three are the person's to run over there. Then `machines watch` waits and tells them the moment it+signs in. Offer to link it and to name it while you are both there.++**Removing a machine cannot be undone.** Say what it means in one line (the machine leaves the+account; its harnesses are no longer reachable from anywhere; it can sign in again as a new+machine), get an explicit yes through the question tool, then run `remove <machine> --yes`. Never+remove the computer you are running on — `harness logout` is that machine's own door. `unlink` is+the gentle one: it drops this computer's link and leaves the machine alone; offer it when the+person means "I do not want to reach it from here".++**Names.** `rename` changes the machine's real name for every screen on the account. `nickname` is+a label only this workspace uses, for when the person wants "the loud one in the cupboard" without+renaming a shared machine. `note` remembers a fact about a machine; `group` keeps a set of them+together. Those three live in `machines.json` and are yours to keep tidy.++Keep the person informed in plain language: which machine, what changed, what it costs. When a+machine is linked, say what it turned out to be carrying. When something cannot be done — a machine+offline, a password refused, Harness not running here — say that in one line, say the one thing+that would fix it, and stop.++You are not a general coding assistant. Asked for something outside the machines and what runs on+them, say so in one line and offer the one thing you do.diff --git a/store/agents/machines/LICENSE b/store/agents/machines/LICENSEnew file mode 100644index 000000000..a499cd17e--- /dev/null+++ b/store/agents/machines/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Autonomous, Inc.++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/machines/README.md b/store/agents/machines/README.mdnew file mode 100644index 000000000..06191eb9b--- /dev/null+++ b/store/agents/machines/README.md@@ -0,0 +1,86 @@+# Machines, as a Harness agent++Your computers, managed by talking. Ask for a machine to be linked, renamed, grouped, noted or+retired; ask what any of them is carrying; ask how to bring a new one in. Beside the conversation,+a live map: every machine you own, the harnesses each one holds, the projects those harnesses are+in, and when the work started.++It reads nothing but Harness. The machine list is the one the app itself shows+(`GET /api/machines`, proxied by the local daemon), and each machine's roster comes over Harness's+own machine bridge — the same paired, encrypted path the app uses to open a pane on another+computer. This package never holds a token, a key or a password.++## Install and open++Choose **Machines** in the Harness Store, or install this checkout:++```sh+harness dsh install "$PWD/store/agents/machines" --link+harness dsh doctor autonomous/machines+```++Open Machines in a new workspace and ask: "Show me my machines, and link the one that needs it."++## What it can do++| Ask for | What happens |+|---|---|+| "show me my machines" | The published observation: every machine, its state, what it is carrying |+| "what is the studio iMac running?" | That machine's projects and harnesses, newest first |+| "link the 4090 rig" | The pane's Link row takes the remote password; the roster fills in |+| "call it the loud one" | A rename on the account, or a nickname only this workspace uses |+| "I'm setting up a new laptop" | The three steps to run there, then a watch that names it when it signs in |+| "retire the old MacBook" | What retiring means, an explicit yes, then it leaves the account |++The agent's runner is `$MACHINES_CLI` (`toolchain/machines`): `status`, `list`, `show`, `rename`,+`nickname`, `note`, `group`, `link`, `unlink`, `links`, `password`, `invite`, `watch`, `remove`,+`refresh`, `doctor`. `--json` on any read.++## The pane++Three views over one observation:++- **Fleet** — every machine around this computer. Each machine is a ring of ticks, one per harness,+ grouped into an arc per project: a long breathing tick is a harness still open, a short faint one+ is closed, and the hue is the agent running in it. The number inside is how many are open. A+ dashed, empty ring means the machine could not be read — never that it is idle. Lines are this+ computer's links; dotted amber is a machine still waiting for one.+- **Projects** — every project with a harness open, threaded to the machines it is open on.+- **Activity** — each harness as a mark at the time it was created, over 24 hours, 7 days or 30.++The pane is read-only with one exception: the row of an unlinked machine takes its remote password+and hands it straight to `harness link connect`. That is deliberate — a password typed to an agent+lives in a transcript, and this one never needs to.++## Honesty rules the pane keeps++- A machine that is **not linked**, offline, or shared read-only has **no roster**. It reads "not+ readable from here", never "no harnesses".+- **Presence and link state are separate**: "online · link required" is a healthy computer that+ simply is not linked yet.+- **Open** means a harness session still exists. It is not a claim that an agent is mid-turn.+- The only per-harness time a roster reports honestly is when it was **created**; the registry's+ `updatedAt` is stamped by its own reconcile pass, so nothing here draws "last worked on".+- A machine that was readable and then fails keeps its last roster, visibly stale, with the reason.++## Develop and verify++```sh+npm test --prefix store/agents/machines+harness dsh check "$PWD/store/agents/machines"+node store/tools/catalog.mjs++# The pane against a workspace; the chosen port is printed.+HARNESS_WORKSPACE=/path/to/workspace store/agents/machines/viewer.sh+```++The tests run without a daemon: the collector's reads and the machine bridge are both injectable,+so a whole fleet — linked, unlinked, offline, shared, failing — is exercised from fixtures. What+they do not cover is a real relayed dial to another computer; `harness dsh doctor autonomous/machines`+on a machine with peers is the check for that.++## Credit and stewardship++Built by Autonomous for Harness, MIT. It wraps Harness's own machine APIs and adds no service of its+own. Issues with linking, presence or the machine list belong in the Harness CLI; the agent, the+runner and the pane belong here.diff --git a/store/agents/machines/harness.json b/store/agents/machines/harness.jsonnew file mode 100644index 000000000..3327ffe6d--- /dev/null+++ b/store/agents/machines/harness.json@@ -0,0 +1,30 @@+{+ "spec": 1,+ "id": "autonomous/machines",+ "name": "Machines",+ "category": "Compute",+ "author": "Autonomous",+ "description": "Talk to your fleet of computers. Link one, name it, retire it — and watch every machine, project and harness you own come alive on one map.",+ "engine": "claude",+ "workspace": {+ "template": "template",+ "marker": "machines.json",+ "init": "toolchain/init-workspace.sh"+ },+ "agent": {+ "instructions": "AGENTS.md",+ "skills": ["skills"],+ "env": {+ "MACHINES_CLI": "${dsh}/toolchain/machines"+ }+ },+ "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/machines/lib/daemon.mjs b/store/agents/machines/lib/daemon.mjsnew file mode 100644index 000000000..1df37d87f--- /dev/null+++ b/store/agents/machines/lib/daemon.mjs@@ -0,0 +1,176 @@+/**+ * The one door to Harness itself.+ *+ * Everything this package knows about machines comes through the local Harness daemon on loopback:+ * the control-plane reads it already proxies for the desktop app (`/api/machines`, `/api/auth/me`),+ * and its machine bridge (`/api/local-ws`), which is how the app reaches another of your computers+ * without this package ever holding a token, a key or a password. Harness owns the pairing and the+ * encryption; we ask it questions in the same words the app does.+ *+ * No credential is read here, and none is ever put in a snapshot. A machine's remote password is+ * typed into `harness link connect` on a terminal, never passed through this module.+ */+import { randomUUID } from 'node:crypto';+import { readFile } from 'node:fs/promises';+import { homedir } from 'node:os';+import { join } from 'node:path';++const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]']);++/** The daemon's loopback control port. `harness status` prints it; 18473 is the fixed default. */+export function daemonBase(env = process.env) {+ const url = new URL(env.HARNESS_MACHINES_DAEMON || 'http://127.0.0.1:18473/');+ if (url.protocol !== 'http:' || !LOOPBACK.has(url.hostname) || url.search || url.hash || url.username || url.password) {+ throw new Error('The Harness daemon address must be a plain loopback http:// URL.');+ }+ return url;+}++/** Node's WebSocket talks only to Harness's loopback bridge; Harness owns pairing and encryption. */+export function bridgeUrl(env = process.env) {+ const base = daemonBase(env);+ return `ws://${base.host}/api/local-ws`;+}++/** Where the CLI keeps its own state. Read-only here, and only for facts the app shows too. */+export function dataDir(env = process.env) {+ return env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data');+}++const DOWN = 'Harness is not running on this computer. Start it (the app, or `harness start`) and ask again.';++async function call(method, path, { body, timeoutMs = 15_000, env = process.env } = {}) {+ let res;+ try {+ res = await fetch(new URL(path, daemonBase(env)), {+ method,+ headers: { 'x-adapter-local': '1', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ signal: AbortSignal.timeout(timeoutMs),+ });+ } catch (err) {+ return { ok: false, status: 0, error: err?.name === 'TimeoutError' ? `Harness did not answer ${method} ${path} in time.` : DOWN };+ }+ let payload = {};+ try { payload = await res.json(); } catch { /* an empty or non-JSON body is an error body */ }+ if (res.status === 401 || res.status === 403) return { ok: false, status: res.status, signedOut: true, error: 'Not signed in to Harness on this computer. Run `harness login`.' };+ if (!res.ok || payload?.success === false) {+ return { ok: false, status: res.status, error: payload?.error?.message || `Harness answered ${res.status} for ${method} ${path}.` };+ }+ return { ok: true, status: res.status, data: payload?.data ?? payload };+}++/** Every machine on the account, as the app sees them. `stale` means the daemon served its cache. */+export async function listMachines(env = process.env) {+ const result = await call('GET', '/api/machines', { env });+ if (!result.ok) return { ...result, machines: [] };+ const data = result.data ?? {};+ return { ok: true, machines: Array.isArray(data.machines) ? data.machines : [], stale: data.stale === true, staleSince: data.staleSince ?? null };+}++export async function authMe(env = process.env) {+ const result = await call('GET', '/api/auth/me', { env });+ return result.ok ? { ok: true, user: result.data?.user ?? result.data ?? null } : result;+}++/** The daemon's own view of this computer: its machine id, version, and the harnesses it watches. */+export async function daemonStatus(env = process.env) {+ const result = await call('GET', '/api/status', { env, timeoutMs: 5000 });+ return result.ok ? { ok: true, status: result.data } : result;+}++export async function sharedMachines(env = process.env) {+ const result = await call('GET', '/api/harness-shares', { env });+ if (!result.ok) return { ...result, machines: [] };+ return { ok: true, machines: Array.isArray(result.data?.machines) ? result.data.machines : [] };+}++export async function renameMachine(machineId, name, env = process.env) {+ return call('PATCH', `/api/machines/${encodeURIComponent(machineId)}`, { body: { name }, env });+}++export async function deleteMachine(machineId, env = process.env) {+ return call('DELETE', `/api/machines/${encodeURIComponent(machineId)}`, { env });+}++/**+ * The machines this computer has linked, from the CLI's own trust file.+ *+ * Only the machine id and when it was pinned are read; the peer's key stays on disk. A link is what+ * lets this computer reach another one's harnesses at all, so it is the difference between a machine+ * that can be looked inside and one that can only be named.+ */+export async function linkedPeers(env = process.env) {+ try {+ const raw = JSON.parse(await readFile(join(dataDir(env), 'e2e', 'machinePeers.json'), 'utf8'));+ if (!Array.isArray(raw)) return [];+ return raw.filter(p => typeof p?.machineId === 'string').map(p => ({+ machineId: p.machineId,+ linkedAt: Number.isFinite(p.linkedAt) ? new Date(p.linkedAt).toISOString() : null,+ }));+ } catch { return []; }+}++/**+ * Whether this computer has a remote password set — what lets ANOTHER machine link to it.+ *+ * Asked of the daemon rather than read off disk: the file beside the peer list holds the stretched+ * verifier for that password, and nothing here should ever open it.+ */+export async function remotePasswordSet(env = process.env) {+ const result = await call('GET', '/api/remote-password/status', { env, timeoutMs: 5000 });+ return result.ok ? result.data?.hasPassword === true : false;+}++/**+ * The harnesses running on one machine, over Harness's own bridge.+ *+ * `relayIsolation` asks for a session of this package's own, so polling a machine never disturbs the+ * window the person is working in. Close code 4404 is the one answer that is not a failure: that+ * machine is not linked from here yet, which is a thing to offer, not an error to report.+ */+export async function listHarnesses(machineId, { timeoutMs = 20_000, env = process.env, WebSocketImpl = globalThis.WebSocket } = {}) {+ if (!WebSocketImpl) return { ok: false, error: 'Node 22 or newer is required to read a machine roster.' };+ let socket;+ try { socket = new WebSocketImpl(bridgeUrl(env)); }+ catch { return { ok: false, error: DOWN }; }+ return await new Promise(resolve => {+ let done = false, deadline, heartbeat;+ const requestId = randomUUID();+ const finish = value => {+ if (done) return;+ done = true;+ clearTimeout(deadline); clearInterval(heartbeat);+ try { socket.close(); } catch { /* already gone */ }+ resolve(value);+ };+ deadline = setTimeout(() => finish({ ok: false, error: 'This machine did not answer in time.' }), timeoutMs);+ socket.addEventListener('open', () => socket.send(JSON.stringify({+ type: 'machine_select',+ payload: { machineId, localProtocolVersion: 1, relayIsolation: true },+ })));+ socket.addEventListener('error', () => finish({ ok: false, error: DOWN }));+ socket.addEventListener('close', event => {+ if (event.code === 4404) finish({ ok: false, needsLink: true, error: 'This machine is not linked from this computer yet.' });+ else finish({ ok: false, error: event.code === 4403 ? 'Harness would not connect to this machine.' : 'The connection to this machine closed before it answered.' });+ });+ socket.addEventListener('message', event => {+ if (typeof event.data !== 'string' || event.data.length > 8 * 1024 * 1024) return;+ let frame;+ try { frame = JSON.parse(event.data); } catch { return; }+ if (frame?.type === 'connected') {+ heartbeat = setInterval(() => { try { socket.send(JSON.stringify({ type: 'ping', payload: {} })); } catch { /* closing */ } }, 15_000);+ // The id rides in the payload — that is where the daemon reads it, and the reply carries it back.+ socket.send(JSON.stringify({ type: 'agents_list', payload: { requestId } }));+ return;+ }+ if (frame?.type === 'agents_list_result' && frame.payload?.requestId === requestId) {+ finish({ ok: true, harnesses: Array.isArray(frame.payload.agents) ? frame.payload.agents : [] });+ return;+ }+ if (['error', 'connection_error', 'local_protocol_error', 'machine_link_required'].includes(frame?.type)) {+ finish({ ok: false, needsLink: frame.type === 'machine_link_required', error: 'This machine is unavailable, or needs linking from this computer.' });+ }+ });+ });+}diff --git a/store/agents/machines/lib/fleet.mjs b/store/agents/machines/lib/fleet.mjsnew file mode 100644index 000000000..b2bb97afd--- /dev/null+++ b/store/agents/machines/lib/fleet.mjs@@ -0,0 +1,140 @@+/**+ * The workspace's own memory: what the person calls each machine, how they group them, what has+ * been done here, and the verdict the pane header reads.+ *+ * Harness owns the machines themselves. This file owns only what Harness has nowhere to keep — a+ * nickname, a note, a group — plus a small log of the operations run from this workspace, so the+ * pane can say what just happened and the agent can say what it did without asking the network.+ */+import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++export const PACKAGE = resolve(dirname(fileURLToPath(import.meta.url)), '..');+export const now = () => new Date().toISOString();++export const DEFAULT_RECORD = {+ spec: 1,+ nicknames: {},+ groups: {},+ notes: {},+ preferences: { confirmBeforeRemoving: true, watchForNewMachinesSeconds: 300 },+};++export function stateDir(workspace) { return join(workspace, '.harness'); }++export async function readJson(path, fallback = null) {+ try { return JSON.parse(await readFile(path, 'utf8')); } catch { return fallback; }+}++/** Write through a temporary file: a reader never sees half a record, and a crash never truncates one. */+export async function atomicJson(path, value) {+ await mkdir(dirname(path), { recursive: true });+ const temporary = `${path}.${process.pid}.tmp`;+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`);+ await rename(temporary, path);+ return value;+}++const object = value => (value && typeof value === 'object' && !Array.isArray(value) ? value : {});+const shortText = (value, limit = 120) => String(value ?? '').slice(0, limit);++/** Keep a record readable whatever is in the file: unknown keys stay, known ones get their shape. */+export function validateRecord(raw) {+ const record = object(raw);+ const preferences = object(record.preferences);+ const seconds = Number(preferences.watchForNewMachinesSeconds);+ return {+ ...record,+ spec: 1,+ nicknames: Object.fromEntries(Object.entries(object(record.nicknames)).slice(0, 256).map(([id, name]) => [id, shortText(name, 40)])),+ groups: Object.fromEntries(Object.entries(object(record.groups)).slice(0, 64).map(([name, ids]) => [+ shortText(name, 40),+ (Array.isArray(ids) ? ids : []).filter(id => typeof id === 'string').slice(0, 128),+ ])),+ notes: Object.fromEntries(Object.entries(object(record.notes)).slice(0, 256).map(([id, note]) => [id, shortText(note, 400)])),+ preferences: {+ ...preferences,+ confirmBeforeRemoving: preferences.confirmBeforeRemoving !== false,+ watchForNewMachinesSeconds: Number.isFinite(seconds) ? Math.min(3600, Math.max(30, Math.round(seconds))) : 300,+ },+ };+}++export async function readRecord(workspace) {+ return validateRecord(await readJson(join(workspace, 'machines.json'), DEFAULT_RECORD));+}++export async function writeRecord(workspace, record) {+ return atomicJson(join(workspace, 'machines.json'), validateRecord(record));+}++const OPERATIONS_KEPT = 40;++/** What has been done from this workspace, newest first. Never a password, never a key — a sentence. */+export async function recordOperation(workspace, entry) {+ const path = join(stateDir(workspace), 'operations.json');+ const previous = await readJson(path, []);+ const list = Array.isArray(previous) ? previous : [];+ const operation = {+ at: now(),+ kind: shortText(entry?.kind, 40),+ machineId: entry?.machineId ? shortText(entry.machineId, 64) : null,+ machine: entry?.machine ? shortText(entry.machine, 80) : null,+ detail: shortText(entry?.detail, 200),+ ok: entry?.ok !== false,+ };+ await atomicJson(path, [operation, ...list].slice(0, OPERATIONS_KEPT));+ return operation;+}++export async function operations(workspace) {+ const list = await readJson(join(stateDir(workspace), 'operations.json'), []);+ return Array.isArray(list) ? list.slice(0, OPERATIONS_KEPT) : [];+}++/**+ * The pane header's line, written from the same snapshot the map draws.+ *+ * The header answers ONE question: is what you are looking at true? So `ready` means the fleet was+ * read, and a severity is about the READING, not about the fleet's shape. A machine that is offline,+ * or that you have never linked, is a state the map already draws plainly — making it a warning put+ * a yellow triangle on a healthy fleet and left it there forever, which is how a header stops being+ * read at all. Those are `info`. A warning is a machine that should have answered and did not; an+ * error is a fleet that could not be read at all.+ */+export function verdictFor(snapshot) {+ const machines = snapshot?.machines ?? [];+ const summary = snapshot?.summary ?? {};+ const findings = [];+ if (snapshot?.status === 'signed-out') {+ findings.push({ severity: 'error', kind: 'signed_out', message: 'Not signed in to Harness on this computer. Run `harness login`.' });+ } else if (snapshot?.status === 'unavailable') {+ findings.push({ severity: 'error', kind: 'daemon', message: snapshot.message || 'Harness is not answering on this computer.' });+ }+ for (const machine of machines) {+ // Offline first: a machine that is not on cannot be linked either, and saying "link required"+ // about a computer that is switched off points the person at the wrong problem.+ if (machine.status === 'offline') findings.push({ severity: 'info', kind: 'offline', message: `${machine.name} is offline.`, ref: machine.id });+ else if (machine.needsLink) findings.push({ severity: 'info', kind: 'needs_link', message: `${machine.name} is not linked from this computer yet, so its harnesses cannot be read.`, ref: machine.id });+ else if (machine.error) findings.push({ severity: 'warning', kind: 'unreadable', message: `${machine.name} did not answer: ${machine.error}`, ref: machine.id });+ }+ const counted = [+ `${summary.machines ?? machines.length} ${(summary.machines ?? machines.length) === 1 ? 'machine' : 'machines'}`,+ `${summary.online ?? 0} online`,+ `${summary.harnesses ?? 0} ${(summary.harnesses ?? 0) === 1 ? 'harness' : 'harnesses'}`,+ ].join(' · ');+ // A workspace that has not observed anything yet has not learned that there are no machines.+ const nothingRead = !machines.length && (snapshot?.status === 'connecting' || !snapshot?.observedAt);+ return {+ spec: 1,+ ready: findings.every(f => f.severity === 'info') && machines.length > 0,+ summary: machines.length ? counted : nothingRead ? 'Reading your machines…' : 'No machines on this account yet',+ findings: findings.slice(0, 20),+ updatedAt: snapshot?.observedAt || now(),+ };+}++export async function writeVerdict(workspace, snapshot) {+ return atomicJson(join(stateDir(workspace), 'verdict.json'), verdictFor(snapshot));+}diff --git a/store/agents/machines/lib/ops.mjs b/store/agents/machines/lib/ops.mjsnew file mode 100644index 000000000..67d2cee1e--- /dev/null+++ b/store/agents/machines/lib/ops.mjs@@ -0,0 +1,142 @@+/**+ * The operations: the small set of things that actually change a machine.+ *+ * Reads go through the daemon's loopback API (lib/daemon.mjs). The three changes that only the+ * `harness` CLI can make — linking to another machine, dropping that link, and this computer's own+ * remote password — are run here as bounded, non-interactive subprocesses.+ *+ * A remote password is a secret the person owns. It is written to the child's stdin and nowhere+ * else: never an argument (which any `ps` can read), never a file, never a log line, never a+ * returned value. Nothing in this module puts one in a snapshot or an operation record.+ */+import { execFile } from 'node:child_process';++const CLI = process.env.HARNESS_CLI || 'harness';++/** Run the Harness CLI without a shell, with a bound on time and output. `input` goes to stdin. */+export function runCli(args, { input, timeoutMs = 60_000, env = process.env } = {}) {+ return new Promise(resolve => {+ const child = execFile(env.HARNESS_CLI || CLI, args, { timeout: timeoutMs, maxBuffer: 1024 * 1024, encoding: 'utf8' },+ (error, stdout, stderr) => resolve({+ ok: !error,+ code: error?.code ?? 0,+ stdout: stdout ?? '',+ stderr: stderr ?? '',+ error: error ? (error.killed ? 'The Harness CLI did not finish in time.' : null) : null,+ }));+ child.on('error', () => resolve({ ok: false, code: 127, stdout: '', stderr: '', error: `Could not run \`${CLI}\`. Harness's CLI is not on PATH here.` }));+ if (input !== undefined) { child.stdin.end(input.endsWith('\n') ? input : `${input}\n`); }+ else child.stdin.end();+ });+}++/** The CLI's `--json` commands answer in NDJSON; the last object is the result. */+export function lastJson(stdout) {+ let value = null;+ for (const line of String(stdout).split('\n')) {+ const trimmed = line.trim();+ if (!trimmed.startsWith('{')) continue;+ try { value = JSON.parse(trimmed); } catch { /* a progress line that is not JSON */ }+ }+ return value;+}++const normalize = value => String(value ?? '').trim().toLowerCase();++/**+ * Find the machine a person named, however they named it: its id, the first characters of its id,+ * its name, its hostname, or a nickname given in this workspace.+ *+ * An ambiguous name is never guessed — a wrong guess here renames or deletes the wrong computer.+ */+export function resolveMachine(machines, query) {+ const wanted = normalize(query);+ if (!wanted) return { error: 'Name a machine — its name, its hostname, or the first characters of its id.' };+ const exact = machines.filter(m => normalize(m.id) === wanted);+ if (exact.length === 1) return { machine: exact[0] };+ const named = machines.filter(m => [m.name, m.givenName, m.nickname, m.hostname].some(value => normalize(value) === wanted));+ if (named.length === 1) return { machine: named[0] };+ if (named.length > 1) return { error: `More than one machine is called "${query}".`, candidates: named };+ const partial = machines.filter(m => normalize(m.id).startsWith(wanted)+ || [m.name, m.givenName, m.nickname, m.hostname].some(value => normalize(value).includes(wanted)));+ if (partial.length === 1) return { machine: partial[0] };+ if (partial.length > 1) return { error: `"${query}" matches ${partial.length} machines.`, candidates: partial };+ return { error: `No machine here matches "${query}".`, candidates: machines };+}++/**+ * Link this computer to another of your machines, proving you know that machine's remote password.+ *+ * The password arrives as an argument to this function and leaves on the child's stdin. Callers+ * must not keep it, print it, or record it; the result says only whether the link was made.+ */+export async function linkMachine(machineId, password, { displayName, env = process.env } = {}) {+ if (!/^[0-9a-f]{8,64}$/i.test(String(machineId))) return { ok: false, error: 'That is not a machine id.' };+ if (typeof password !== 'string' || !password.trim()) return { ok: false, error: 'Enter the remote password set on that machine.' };+ const args = ['link', 'connect', machineId, '--stdin', '--json'];+ if (displayName) args.push(`--name=${String(displayName).slice(0, 80)}`);+ const result = await runCli(args, { input: password, timeoutMs: 120_000, env });+ const payload = lastJson(result.stdout);+ if (payload?.ok === true) return { ok: true, machineId: payload.machineId ?? machineId };+ const reason = payload?.error || result.error || result.stderr.trim().split('\n').pop() || 'The link did not complete.';+ // A wrong password is the common answer here, and it is worth saying plainly rather than as a code.+ return { ok: false, error: /PASSWORD|AUTH/i.test(reason) ? 'That password was not accepted by the other machine.' : reason.slice(0, 200) };+}++export async function unlinkMachine(machineId, { env = process.env } = {}) {+ const result = await runCli(['link', 'unlink', machineId], { env, timeoutMs: 20_000 });+ if (result.ok) return { ok: true };+ return { ok: false, error: (result.error || result.stderr.trim().split('\n').filter(Boolean).pop() || 'Could not unlink that machine.').slice(0, 200) };+}++/** The machines THIS computer trusts, with when each link was made. */+export async function listLinks({ env = process.env } = {}) {+ const result = await runCli(['link', 'list'], { env, timeoutMs: 20_000 });+ return { ok: result.ok, text: (result.stdout || result.stderr).trim() };+}++/** Whether this computer can be linked TO — i.e. whether it has a remote password set. */+export async function remotePasswordStatus({ env = process.env } = {}) {+ const result = await runCli(['remote-password', 'status', '--json'], { env, timeoutMs: 20_000 });+ const payload = lastJson(result.stdout);+ return { ok: result.ok, set: payload?.set === true || payload?.hasPassword === true, raw: payload };+}++export async function setRemotePassword(password, { env = process.env } = {}) {+ if (typeof password !== 'string' || password.trim().length < 8) return { ok: false, error: 'Use at least 8 characters.' };+ const result = await runCli(['remote-password', 'set', '--stdin', '--json'], { input: password, env, timeoutMs: 30_000 });+ const payload = lastJson(result.stdout);+ if (result.ok && payload?.ok !== false) return { ok: true };+ return { ok: false, error: (payload?.error || result.error || 'Could not set the remote password.').slice(0, 200) };+}++export async function clearRemotePassword({ env = process.env } = {}) {+ const result = await runCli(['remote-password', 'clear', '--json'], { env, timeoutMs: 20_000 });+ const payload = lastJson(result.stdout);+ if (result.ok && payload?.ok !== false) return { ok: true };+ return { ok: false, error: (payload?.error || result.error || 'Could not clear the remote password.').slice(0, 200) };+}++/**+ * Wait for a machine that is not on the account yet to appear on it.+ *+ * This is the other half of bringing a computer in: the person installs Harness and signs in over+ * there, and this watches the account until the new machine shows up, so nobody has to keep asking+ * "is it there yet".+ */+export async function watchForNewMachine({ seconds = 300, pollMs = 4000, list, env = process.env, signal } = {}) {+ const fetchList = list ?? (await import('./daemon.mjs')).listMachines;+ const first = await fetchList(env);+ if (!first.ok) return { ok: false, error: first.error };+ const known = new Set(first.machines.map(m => m.machineId));+ const deadline = Date.now() + Math.min(3600, Math.max(1, seconds)) * 1000;+ while (Date.now() < deadline) {+ if (signal?.aborted) return { ok: false, error: 'Stopped waiting.' };+ await new Promise(done => setTimeout(done, pollMs));+ const latest = await fetchList(env);+ if (!latest.ok) continue;+ const arrived = latest.machines.filter(m => !known.has(m.machineId));+ if (arrived.length) return { ok: true, machines: arrived };+ }+ return { ok: false, timedOut: true, error: 'No new machine signed in while waiting.' };+}diff --git a/store/agents/machines/lib/snapshot.mjs b/store/agents/machines/lib/snapshot.mjsnew file mode 100644index 000000000..7aaf04c7f--- /dev/null+++ b/store/agents/machines/lib/snapshot.mjs@@ -0,0 +1,276 @@+/**+ * One observation of the fleet: the machines on the account, the harnesses each one is carrying,+ * and the projects those harnesses are in.+ *+ * Every number here was reported by Harness. A machine that cannot be read keeps its last known+ * roster, marked stale, and says why — a roster this package could not fetch is never zero+ * harnesses, and a machine that is merely unlinked is never offline.+ */+import { readFile } from 'node:fs/promises';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { authMe, daemonStatus, linkedPeers, listHarnesses, listMachines, remotePasswordSet, sharedMachines } from './daemon.mjs';+import { now, readRecord } from './fleet.mjs';++/** How many machines are asked for their roster at once. A fleet is small; a relayed dial is not free. */+const ROSTER_CONCURRENCY = 4;+/** Harness rows kept per machine. Beyond this the counts stay true and the map stops drawing ticks. */+export const ROSTER_LIMIT = 240;++const text = (value, limit = 200) => (typeof value === 'string' ? value.slice(0, limit) : null);+const iso = value => { const at = Date.parse(value); return Number.isFinite(at) ? new Date(at).toISOString() : null; };++/** Machine presence, as the app reads it: `running` is the only word that means online. */+function presenceOf(row) {+ if (row.status === 'running') return 'online';+ if (row.status === 'stopped' || row.status === 'offline') return 'offline';+ return 'unknown';+}++/** A machine's name is its own, else the hostname of the computer that last connected it. */+export function machineName(row, nicknames = {}) {+ return text(nicknames[row.machineId], 40) || text(row.name, 80) || text(row.hostname, 80) || `machine ${String(row.machineId).slice(0, 8)}`;+}++/** Two harnesses are in the same project when they are in the same repository, else the same folder. */+export function projectKey(machineId, project) {+ if (!project) return null;+ if (project.remote) return `repo:${project.remote}`;+ return `dir:${machineId}:${project.root || project.cwd}`;+}++function harnessRow(raw, machineId) {+ const project = raw?.project && typeof raw.project === 'object' ? raw.project : null;+ return {+ id: text(raw?.id, 64),+ machineId,+ name: text(raw?.name, 120) || 'Harness',+ title: text(raw?.title, 160),+ // The agent is the who: a harness package's name when it has one, else the bare engine.+ agent: text(raw?.dshName, 60) || text(raw?.engine, 40) || 'agent',+ engine: text(raw?.engine, 40) || 'unknown',+ dsh: text(raw?.dsh, 80),+ // The registry calls a session active when it is still open — a pane that exists, a process+ // that is alive. It is not a claim that the agent is mid-turn, and nothing here says it is.+ open: raw?.status === 'active',+ project: project ? {+ key: projectKey(machineId, project),+ name: text(project.name, 80) || 'project',+ cwd: text(project.cwd, 240),+ branch: text(project.branch, 80),+ repo: text(project.remote, 160),+ } : null,+ verdict: raw?.verdict && typeof raw.verdict === 'object' ? {+ ready: raw.verdict.ready === true,+ summary: text(raw.verdict.summary, 120),+ errors: Number.isFinite(raw.verdict.errors) ? raw.verdict.errors : 0,+ warnings: Number.isFinite(raw.verdict.warnings) ? raw.verdict.warnings : 0,+ } : null,+ createdAt: iso(raw?.createdAt),+ // The registry stamps this when it reconciles, so a whole machine's harnesses share the moment+ // it was last polled. It is kept for completeness and is never read as "last worked on": the+ // honest time signal a roster carries is when each harness was CREATED.+ updatedAt: iso(raw?.updatedAt),+ };+}++/** Run `work` over `items`, a few at a time, in order of completion. */+async function pooled(items, limit, work) {+ const results = new Array(items.length);+ let next = 0;+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {+ for (let index = next++; index < items.length; index = next++) results[index] = await work(items[index], index);+ });+ await Promise.all(runners);+ return results;+}++/** This computer's own lifetime counters, written by the app. Absent is absent, never zero. */+export async function localTotals(env = process.env) {+ const dir = env.HARNESS_APP_DIR || join(homedir(), '.harness', 'desktop-app-v2');+ try {+ const raw = JSON.parse(await readFile(join(dir, 'harness-stats.json'), 'utf8'));+ const number = value => (Number.isFinite(value) && value >= 0 ? value : null);+ return {+ harnessesStarted: number(raw?.agentsSpawned),+ turns: number(raw?.turns),+ workedMs: number(raw?.workedMs),+ since: iso(raw?.firstEventAt),+ };+ } catch { return null; }+}++/** Projects, gathered across every machine that could be read. */+export function projectsOf(machines) {+ const projects = new Map();+ for (const machine of machines) {+ for (const harness of machine.harnesses) {+ if (!harness.project?.key) continue;+ const found = projects.get(harness.project.key) ?? {+ key: harness.project.key, name: harness.project.name, repo: harness.project.repo,+ branches: [], machines: [], harnesses: 0, open: 0, newestAt: null,+ };+ found.harnesses += 1;+ if (harness.open) found.open += 1;+ if (harness.project.branch && !found.branches.includes(harness.project.branch)) found.branches.push(harness.project.branch);+ if (!found.machines.includes(machine.id)) found.machines.push(machine.id);+ if (harness.createdAt && (!found.newestAt || harness.createdAt > found.newestAt)) found.newestAt = harness.createdAt;+ projects.set(found.key, found);+ }+ }+ return [...projects.values()].sort((a, b) => b.open - a.open || b.harnesses - a.harnesses || a.name.localeCompare(b.name));+}++/**+ * A collector holds one thing between polls: the last roster each machine gave, so an unreachable+ * machine keeps its harnesses on the map with an honest "last seen" instead of emptying out.+ */+export function createCollector(workspace, { env = process.env, intervalMs = 15_000, read = {} } = {}) {+ // Every read this collector makes, in one place, so a test can hand it a fleet and a real run+ // reaches Harness the only way this package ever does.+ const source = {+ machines: listMachines, account: authMe, daemon: daemonStatus, peers: linkedPeers,+ shares: sharedMachines, password: remotePasswordSet, totals: localTotals, roster: listHarnesses,+ record: readRecord, ...read,+ };+ const lastRosters = new Map();++ return async function collect() {+ const observedAt = now();+ const [record, account, daemon, machineList, peers, shares, passwordSet, totals] = await Promise.all([+ source.record(workspace).catch(() => ({ nicknames: {}, notes: {}, groups: {} })),+ source.account(env), source.daemon(env), source.machines(env), source.peers(env),+ source.shares(env), source.password(env), source.totals(env),+ ]);++ const sources = {+ machines: { ok: machineList.ok, error: machineList.ok ? null : machineList.error },+ account: { ok: account.ok, error: account.ok ? null : account.error },+ daemon: { ok: daemon.ok, error: daemon.ok ? null : daemon.error },+ };+ if (!machineList.ok) {+ return {+ spec: 1,+ status: machineList.signedOut ? 'signed-out' : 'unavailable',+ message: machineList.error,+ observedAt, pollIntervalMs: intervalMs,+ account: null, localMachineId: daemon.status?.machineId ?? null,+ machines: [], projects: [], summary: { machines: 0, online: 0, needsLink: 0, harnesses: 0, open: 0, projects: 0, engines: {} },+ thisComputer: null, totals, sources,+ };+ }++ const localMachineId = daemon.status?.machineId ?? null;+ const linked = new Map(peers.map(peer => [peer.machineId, peer]));+ const shared = new Map(shares.machines.filter(m => typeof m?.machineId === 'string').map(m => [m.machineId, m]));+ const rows = machineList.machines.filter(row => typeof row?.machineId === 'string');++ const machines = await pooled(rows, ROSTER_CONCURRENCY, async row => {+ const id = row.machineId;+ const local = id === localMachineId;+ const isShared = shared.has(id);+ const presence = presenceOf(row);+ const linkState = local ? 'local' : isShared ? 'shared' : linked.has(id) ? 'linked' : 'unlinked';+ const base = {+ id,+ name: machineName(row, record.nicknames),+ givenName: text(row.name, 80),+ nickname: text(record.nicknames?.[id], 40),+ note: text(record.notes?.[id], 400),+ hostname: text(row.hostname, 80),+ local, shared: isShared,+ ownerName: isShared ? text(shared.get(id)?.ownerName, 80) : null,+ status: presence,+ linkState,+ linkedAt: linked.get(id)?.linkedAt ?? null,+ needsLink: false,+ plan: text(row.planName, 60),+ authMode: text(row.authMode, 40),+ billingStatus: text(row.billingStatus, 40),+ engine: text(row.engine, 40),+ reportedHarnessCount: Number.isFinite(row.agentCount) ? row.agentCount : null,+ createdAt: iso(row.createdAt),+ groups: Object.entries(record.groups ?? {}).filter(([, ids]) => ids.includes(id)).map(([name]) => name),+ };++ // A machine that is offline, unlinked or shared read-only is not asked; that is not a failure,+ // it is a state with a name, and the map says which one.+ if (presence === 'offline' || linkState === 'unlinked' || linkState === 'shared') {+ const remembered = lastRosters.get(id);+ return {+ ...base,+ needsLink: linkState === 'unlinked',+ harnesses: remembered?.harnesses ?? [],+ harnessesTruncated: remembered?.truncated ?? false,+ rosterObservedAt: remembered?.observedAt ?? null,+ stale: Boolean(remembered),+ error: null,+ };+ }++ const roster = await source.roster(id, { env });+ if (!roster.ok) {+ const remembered = lastRosters.get(id);+ return {+ ...base,+ needsLink: roster.needsLink === true,+ harnesses: remembered?.harnesses ?? [],+ harnessesTruncated: remembered?.truncated ?? false,+ rosterObservedAt: remembered?.observedAt ?? null,+ stale: Boolean(remembered),+ error: roster.needsLink ? null : roster.error,+ };+ }+ const all = roster.harnesses.map(raw => harnessRow(raw, id)).filter(h => h.id);+ const harnesses = all.slice(0, ROSTER_LIMIT);+ lastRosters.set(id, { harnesses, truncated: all.length > harnesses.length, observedAt });+ return { ...base, harnesses, harnessesTruncated: all.length > harnesses.length, rosterObservedAt: observedAt, stale: false, error: null };+ });++ for (const machine of machines) {+ machine.harnessCount = machine.harnesses.length;+ machine.openCount = machine.harnesses.filter(h => h.open).length;+ machine.projectCount = new Set(machine.harnesses.map(h => h.project?.key).filter(Boolean)).size;+ machine.newestAt = machine.harnesses.reduce((latest, h) => (h.createdAt && h.createdAt > latest ? h.createdAt : latest), '') || null;+ }+ // This computer first, then the machines that are up, then by name — the order the map lays out.+ machines.sort((a, b) => Number(b.local) - Number(a.local)+ || Number(b.status === 'online') - Number(a.status === 'online')+ || a.name.localeCompare(b.name));++ const engines = {};+ for (const machine of machines) for (const harness of machine.harnesses) engines[harness.engine] = (engines[harness.engine] ?? 0) + 1;+ const projects = projectsOf(machines);+ // A machine that has never been linked is a state with a name, shown as such, and not a partial+ // observation. Only a machine that SHOULD have answered and did not makes this reading partial.+ const unreadable = machines.filter(m => m.error).length;++ return {+ spec: 1,+ status: machineList.stale ? 'partial' : unreadable ? 'partial' : 'live',+ message: machineList.stale ? 'These machines are the last list Harness could fetch.' : null,+ observedAt, pollIntervalMs: intervalMs,+ account: account.ok ? { email: text(account.user?.email, 160), name: text(account.user?.name, 80) } : null,+ localMachineId,+ thisComputer: daemon.ok ? {+ machineId: daemon.status?.machineId ?? null,+ version: text(daemon.status?.version, 40),+ connected: daemon.status?.connected === true,+ uptimeSec: Number.isFinite(daemon.status?.uptimeSec) ? daemon.status.uptimeSec : null,+ remotePasswordSet: passwordSet,+ } : null,+ machines, projects,+ summary: {+ machines: machines.length,+ online: machines.filter(m => m.status === 'online').length,+ needsLink: machines.filter(m => m.needsLink).length,+ harnesses: machines.reduce((total, m) => total + m.harnessCount, 0),+ open: machines.reduce((total, m) => total + m.openCount, 0),+ projects: projects.length,+ engines,+ },+ totals,+ sources,+ };+ };+}diff --git a/store/agents/machines/package.json b/store/agents/machines/package.jsonnew file mode 100644index 000000000..679ceb787--- /dev/null+++ b/store/agents/machines/package.json@@ -0,0 +1,10 @@+{+ "name": "@autonomous/machines-harness",+ "private": true,+ "type": "module",+ "scripts": {+ "test": "node --test test/*.test.mjs",+ "start": "./viewer.sh"+ },+ "engines": { "node": ">=22" }+}diff --git a/store/agents/machines/skills/fleet-operations/SKILL.md b/store/agents/machines/skills/fleet-operations/SKILL.mdnew file mode 100644index 000000000..0b6c15bd0--- /dev/null+++ b/store/agents/machines/skills/fleet-operations/SKILL.md@@ -0,0 +1,109 @@+---+name: fleet-operations+description: Manage the machines on a Harness account by conversation — read the fleet, link and unlink, rename, note and group, bring a new computer in, remove one. Use in a Machines workspace whenever the person asks about their computers, what is running on them, or wants one added, named, linked or retired.+---++# Fleet operations++One runner does everything: `"$MACHINES_CLI" <command>`. Text by default, `--json` when you want to+read fields rather than a table. Exit code 1 means it did not happen, and the line above says why.++Name a machine however the person did — its name, its hostname, a nickname set here, or the first+characters of its id. An ambiguous name is refused with the candidates listed; put those in front+of the person with the question tool instead of guessing. A wrong guess renames or deletes the+wrong computer.++## Look++| Command | What it is for |+|---|---|+| `status` | The observation the pane has already published. No network. **Start here.** |+| `refresh` | Observe now and republish. Use after something changed elsewhere. |+| `list` | A fresh read of every machine on the account. |+| `show <machine>` | One machine: state, link, projects, harnesses. |+| `doctor` | Can this computer manage the fleet at all? |++What a reading contains, and what it does not:++- **Presence and link state are separate.** "online · link required" is a machine that is perfectly+ well and simply not linked from here. Do not collapse the two.+- A machine that is **not linked**, **offline**, or **shared read-only** has no roster. Report it as+ *not readable from here*, never as zero harnesses.+- `open` means a harness is still there — a session that exists. It is not a claim that an agent is+ typing this second, and you must not upgrade it into one.+- The only honest time a roster carries per harness is when it was **created**. Say "started 3d+ ago". There is no "last worked on" in this data.++## Link++Linking lets this computer reach another machine's harnesses. It needs the remote password set on+**that** machine, and that password never comes through the conversation:++1. `show <machine>` to confirm it is the right one and that it needs a link.+2. Tell the person to click **Link** on that machine in the pane and type the password there.+3. `refresh` once they say it went through; then say what the machine turned out to be carrying.++If they paste the password to you anyway, use it once and let it go: `printf '%s' '<password>' |+"$MACHINES_CLI" link <machine> --stdin`. Never echo it, never put it in a note, never keep it.++`unlink <machine>` drops this computer's link only. The machine stays on the account, keeps running,+and can be linked again. `links` lists what this computer has linked. `password [status|clear]` is+about THIS computer — whether another machine can link to it.++A refused password says so plainly; it usually means the password was changed on the other machine,+or `harness remote-password set` was never run there.++## Bring a computer in++`invite` prints the three steps the person runs **on the other computer**: install Harness, sign in+to this account, start it and set a remote password. Then:++```sh+"$MACHINES_CLI" watch --seconds=600+```++waits and names the machine the moment it signs in. Offer, in one question: link it now, name it,+or both. A machine can also be brought in by installing the Harness app there and signing in — the+CLI steps are for a server with no screen.++## Name, note, group++| Command | Reach |+|---|---|+| `rename <machine> <name>` | The machine's real name, on every screen of the account. Max 40 characters. |+| `nickname <machine> <text>` | A label only this workspace uses. `--clear` removes it. |+| `note <machine> <text>` | Something to remember: what it is for, where it lives. `--clear` removes it. |+| `group <name> add\|remove <machine>` | Keep a set of machines together (`studio`, `rack`). |++Renaming a machine that is shared with other people changes it for them too; say so before doing it.+A nickname is the polite alternative.++## Remove++`remove <machine> --yes` takes a machine off the account. It cannot be undone. Before running it:++- Say what it means: the machine leaves the account, its harnesses stop being reachable from+ anywhere, and anything running on it keeps running on that computer but is no longer on this map.+- Get an explicit yes through the question tool. Without `--yes` the command refuses, which is the+ backstop, not the conversation.+- The computer you are running on is refused outright. `harness logout` on that machine is its own+ door, and it is the person's to open.++Prefer `unlink` when the person means "stop reaching it from here", and `remove` only when they+mean "this computer is not mine / not in use any more".++## When something is wrong++- **"Harness is not running on this computer"** — the daemon is down. `harness start`, or open the+ Harness app. Nothing else here will work until then.+- **"Not signed in"** — `harness login` on this computer.+- **A machine did not answer** — it was reachable a moment ago and is not now. Say so, keep the last+ known reading (the pane marks it stale), and offer to try again rather than declaring it offline.+- **The pane has published nothing** — run `refresh`; that writes the observation the pane reads.++Every operation you run is recorded in this workspace and appears in the pane's Recent list, so the+person can see what changed without asking you to repeat it.++The header above the pane answers one question — is what you are looking at true? A machine that is+offline or not yet linked is a state it reports quietly; only a machine that should have answered+and did not is a warning there. Do not read "ready" as "the fleet is perfect".diff --git a/store/agents/machines/skills/fleet-operations/references/reading-the-pane.md b/store/agents/machines/skills/fleet-operations/references/reading-the-pane.mdnew file mode 100644index 000000000..8cc0b1a09--- /dev/null+++ b/store/agents/machines/skills/fleet-operations/references/reading-the-pane.md@@ -0,0 +1,25 @@+# Reading the pane++The map beside you is drawn from exactly the observation `status` returns, so anything on it can be+talked about without another read. It has three views.++**Fleet.** Every machine, with this computer in the middle. Each machine is a ring of ticks: one+tick per harness, grouped into an arc per project. A long, breathing tick is a harness that is still+open; a short faint one is closed. The number inside the ring is how many are open. A dashed empty+ring means the machine could not be read — not that it is idle. The lines are this computer's links:+solid to a machine it can reach, dotted amber to one still waiting to be linked.++**Projects.** Every project with a harness open, and the machines it is open on, as threads. This is+the view that answers "where is this work happening" and "what is this machine carrying that nothing+else is". It shows the busiest projects first when there are more than fit.++**Activity.** Each mark is one harness, stacked at the time it was created, over 24 hours, 7 days or+30 days. It answers "when did all this start" and "which machine has been picking up work". It does+not claim anything about how long a harness ran — that is not in the data.++The right rail is the inspector: the fleet's totals with nothing selected, one machine's detail when+a machine is picked, one project's when a project is. Its "Ask the agent" block is a phrase the+person can copy into the terminal; treat a pasted one as an ordinary request.++The pane takes exactly one input — a remote password, on the row of a machine waiting to be linked.+Everything else is read-only and changes through you.diff --git a/store/agents/machines/store.json b/store/agents/machines/store.jsonnew file mode 100644index 000000000..a6006bce1--- /dev/null+++ b/store/agents/machines/store.json@@ -0,0 +1,7 @@+{+ "homepage": "https://harness.autonomous.ai",+ "license": "MIT",+ "tagline": "Every computer you own, on one live map",+ "screenshots": [],+ "examples": []+}diff --git a/store/agents/machines/template/machines.json b/store/agents/machines/template/machines.jsonnew file mode 100644index 000000000..f313a5093--- /dev/null+++ b/store/agents/machines/template/machines.json@@ -0,0 +1,10 @@+{+ "spec": 1,+ "nicknames": {},+ "groups": {},+ "notes": {},+ "preferences": {+ "confirmBeforeRemoving": true,+ "watchForNewMachinesSeconds": 300+ }+}diff --git a/store/agents/machines/test/daemon.test.mjs b/store/agents/machines/test/daemon.test.mjsnew file mode 100644index 000000000..76ff9b618--- /dev/null+++ b/store/agents/machines/test/daemon.test.mjs@@ -0,0 +1,85 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { bridgeUrl, daemonBase, listHarnesses } from '../lib/daemon.mjs';++test('the daemon address must be loopback http, and the bridge follows it', () => {+ assert.equal(daemonBase({}).href, 'http://127.0.0.1:18473/');+ assert.equal(bridgeUrl({}), 'ws://127.0.0.1:18473/api/local-ws');+ assert.equal(bridgeUrl({ HARNESS_MACHINES_DAEMON: 'http://localhost:9999/' }), 'ws://localhost:9999/api/local-ws');+ for (const bad of ['https://127.0.0.1:18473/', 'http://example.com/', 'http://user:[email protected]/', 'http://127.0.0.1/?x=1']) {+ assert.throws(() => daemonBase({ HARNESS_MACHINES_DAEMON: bad }), /loopback/, bad);+ }+});++/** A WebSocket that plays one scripted exchange, so the roster read is testable without a daemon. */+function scripted({ frames = [], closeWith = null, onSend = () => {} }) {+ return class {+ constructor() {+ this.listeners = {};+ queueMicrotask(() => {+ this.fire('open', {});+ for (const frame of frames) this.fire('message', { data: JSON.stringify(frame) });+ if (closeWith) this.fire('close', closeWith);+ });+ }+ addEventListener(type, handler) { (this.listeners[type] ??= []).push(handler); }+ fire(type, event) { for (const handler of this.listeners[type] ?? []) handler(event); }+ send(raw) { onSend(JSON.parse(raw), this); }+ close() {}+ };+}++test('a roster read selects the machine, asks once, and returns what came back', async () => {+ const sent = [];+ const WebSocketImpl = scripted({+ frames: [{ type: 'connected', payload: { transport: 'local' } }],+ onSend: (frame, socket) => {+ sent.push(frame);+ if (frame.type === 'agents_list') {+ // The daemon reads the id from the payload and echoes it back there.+ socket.fire('message', { data: JSON.stringify({ type: 'agents_list_result', payload: { requestId: frame.payload.requestId, agents: [{ id: 'h1' }] } }) });+ }+ },+ });+ const result = await listHarnesses('a'.repeat(32), { WebSocketImpl, timeoutMs: 500 });+ assert.equal(result.ok, true);+ assert.deepEqual(result.harnesses, [{ id: 'h1' }]);+ assert.equal(sent[0].type, 'machine_select');+ assert.equal(sent[0].payload.relayIsolation, true, 'a poll must not disturb the window the person is using');+ assert.equal(sent[1].type, 'agents_list');+ assert.equal(typeof sent[1].payload.requestId, 'string');+});++test('a reply for another request is ignored', async () => {+ const WebSocketImpl = scripted({+ frames: [+ { type: 'connected', payload: {} },+ { type: 'agents_list_result', payload: { requestId: 'someone-else', agents: [{ id: 'not mine' }] } },+ ],+ });+ const result = await listHarnesses('a'.repeat(32), { WebSocketImpl, timeoutMs: 120 });+ assert.equal(result.ok, false);+ assert.match(result.error, /did not answer in time/);+});++test('an unlinked machine is a state with a name, not a failure', async () => {+ const WebSocketImpl = scripted({ closeWith: { code: 4404, reason: 'NO_PEER_LINK' } });+ const result = await listHarnesses('a'.repeat(32), { WebSocketImpl, timeoutMs: 500 });+ assert.equal(result.ok, false);+ assert.equal(result.needsLink, true);+ assert.match(result.error, /not linked/);+});++test('a refused connection is reported without claiming the machine is empty', async () => {+ const WebSocketImpl = scripted({ closeWith: { code: 4403, reason: 'machine mismatch' } });+ const result = await listHarnesses('a'.repeat(32), { WebSocketImpl, timeoutMs: 500 });+ assert.equal(result.ok, false);+ assert.equal(result.needsLink, undefined);+ assert.equal(result.harnesses, undefined);+});++test('without a WebSocket there is an answer, not a crash', async () => {+ const result = await listHarnesses('a'.repeat(32), { WebSocketImpl: null });+ assert.equal(result.ok, false);+ assert.match(result.error, /Node 22/);+});diff --git a/store/agents/machines/test/fixtures.mjs b/store/agents/machines/test/fixtures.mjsnew file mode 100644index 000000000..fffefb574--- /dev/null+++ b/store/agents/machines/test/fixtures.mjs@@ -0,0 +1,43 @@+/** A small fleet with every state that matters: this computer, a linked machine, one still waiting+ * to be linked, one offline, and one shared read-only. */+export const OWNER_MACHINES = [+ { machineId: 'a'.repeat(32), computerId: 'c1', name: 'Studio', hostname: 'studio.local', status: 'running', agentCount: 2, engine: 'claude', planName: 'Remote', authMode: 'remote', billingStatus: 'not_required', createdAt: '2026-08-01T10:00:00.000Z' },+ { machineId: 'b'.repeat(32), computerId: 'c2', name: 'Rack', hostname: 'rack', status: 'running', agentCount: 0, engine: 'claude', planName: 'Remote', authMode: 'remote', billingStatus: 'not_required', createdAt: '2026-08-02T10:00:00.000Z' },+ { machineId: 'c'.repeat(32), computerId: 'c3', name: null, hostname: 'loft', status: 'running', agentCount: 0, engine: 'claude', planName: null, authMode: 'remote', billingStatus: 'not_required', createdAt: '2026-08-03T10:00:00.000Z' },+ { machineId: 'd'.repeat(32), computerId: 'c4', name: 'Old laptop', hostname: 'old', status: 'offline', agentCount: 0, engine: 'claude', planName: null, authMode: 'remote', billingStatus: 'not_required', createdAt: '2026-08-04T10:00:00.000Z' },+ { machineId: 'e'.repeat(32), computerId: 'c5', name: 'Borrowed', hostname: 'borrowed', status: 'running', agentCount: 1, engine: 'codex', planName: null, authMode: 'remote', billingStatus: 'not_required', createdAt: '2026-08-05T10:00:00.000Z' },+];++const harness = (id, name, engine, project, branch, open, createdAt, extra = {}) => ({+ id, sessionId: `s-${id}`, name, title: `${name} title`, status: open ? 'active' : 'offline', engine,+ createdAt, updatedAt: '2026-09-20T12:00:00.000Z',+ project: project ? { name: project, cwd: `/w/${project}`, root: `/w/${project}`, remote: `github.com/acme/${project}`, branch } : null,+ ...extra,+});++export const STUDIO_ROSTER = [+ harness('h1', 'board fab check', 'claude', 'circuit', 'main', true, '2026-09-18T09:00:00.000Z', { dsh: 'autonomous/autonomous-circuit', dshName: 'Autonomous Circuit' }),+ harness('h2', 'deck', 'claude', 'keynote', 'main', true, '2026-09-19T09:00:00.000Z'),+ harness('h3', 'old thing', 'codex', 'circuit', 'main', false, '2026-09-01T09:00:00.000Z'),+];++export const RACK_ROSTER = [+ harness('h4', 'training run', 'codex', 'circuit', 'gpu', true, '2026-09-19T18:00:00.000Z'),+];++/** The reads a collector makes, answered from memory. */+export function fakeReads({ machines = OWNER_MACHINES, rosters = {}, peers = [], shares = [], totals = null, record = {} } = {}) {+ return {+ machines: async () => ({ ok: true, machines, stale: false }),+ account: async () => ({ ok: true, user: { email: '[email protected]', name: 'Someone' } }),+ daemon: async () => ({ ok: true, status: { machineId: 'a'.repeat(32), version: '0.2.0', connected: true, uptimeSec: 60 } }),+ peers: async () => peers,+ shares: async () => ({ ok: true, machines: shares }),+ password: async () => true,+ totals: async () => totals,+ record: async () => ({ nicknames: {}, notes: {}, groups: {}, ...record }),+ roster: async machineId => (rosters[machineId]+ ? { ok: true, harnesses: rosters[machineId] }+ : { ok: false, needsLink: true, error: 'This machine is not linked from this computer yet.' }),+ };+}diff --git a/store/agents/machines/test/fleet.test.mjs b/store/agents/machines/test/fleet.test.mjsnew file mode 100644index 000000000..153121cdd--- /dev/null+++ b/store/agents/machines/test/fleet.test.mjs@@ -0,0 +1,106 @@+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 test from 'node:test';+import { operations, readRecord, recordOperation, validateRecord, verdictFor, writeRecord } from '../lib/fleet.mjs';++async function workspace() {+ const dir = await mkdtemp(join(tmpdir(), 'machines-test-'));+ test.after(() => rm(dir, { recursive: true, force: true }));+ return dir;+}++test('a record keeps unknown keys and bounds the known ones', () => {+ const record = validateRecord({+ nicknames: { abc: 'x'.repeat(200) },+ groups: { studio: ['a', 'b', 7] },+ preferences: { watchForNewMachinesSeconds: 999_999, confirmBeforeRemoving: false },+ somethingElse: { kept: true },+ });+ assert.equal(record.nicknames.abc.length, 40);+ assert.deepEqual(record.groups.studio, ['a', 'b']);+ assert.equal(record.preferences.watchForNewMachinesSeconds, 3600);+ assert.equal(record.preferences.confirmBeforeRemoving, false);+ assert.deepEqual(record.somethingElse, { kept: true });+});++test('a record round-trips through the workspace', async () => {+ const dir = await workspace();+ await writeRecord(dir, { nicknames: { a: 'studio' }, notes: {}, groups: {} });+ const read = await readRecord(dir);+ assert.equal(read.nicknames.a, 'studio');+ assert.equal(read.preferences.confirmBeforeRemoving, true, 'defaults fill in');+});++test('operations are kept newest first and never keep more than the log holds', async () => {+ const dir = await workspace();+ for (let index = 0; index < 45; index += 1) await recordOperation(dir, { kind: 'rename', detail: `rename ${index}` });+ const log = await operations(dir);+ assert.equal(log.length, 40);+ assert.equal(log[0].detail, 'rename 44');+});++test('a failed operation is recorded as failed, and carries no secret', async () => {+ const dir = await workspace();+ await recordOperation(dir, { kind: 'link', machine: 'Rack', ok: false, detail: 'Link refused: that password was not accepted' });+ const [entry] = await operations(dir);+ assert.equal(entry.ok, false);+ const raw = await readFile(join(dir, '.harness', 'operations.json'), 'utf8');+ assert.ok(!raw.includes('password was not accepted\n'), 'the detail is a sentence, not a transcript');+ assert.equal(Object.keys(entry).sort().join(','), 'at,detail,kind,machine,machineId,ok');+});++test('the verdict counts the fleet and names what needs doing', () => {+ const verdict = verdictFor({+ status: 'live', observedAt: '2026-09-20T10:00:00.000Z',+ summary: { machines: 3, online: 2, harnesses: 12 },+ machines: [+ { id: 'a', name: 'Studio', status: 'online', needsLink: false },+ { id: 'b', name: 'Rack', status: 'online', needsLink: true },+ { id: 'c', name: 'Old laptop', status: 'offline', needsLink: true },+ ],+ });+ assert.equal(verdict.summary, '3 machines · 2 online · 12 harnesses');+ assert.equal(verdict.findings.find(f => f.ref === 'b').kind, 'needs_link');+ assert.equal(verdict.findings.find(f => f.ref === 'c').kind, 'offline', 'an offline machine is not a linking job');+ // A fleet you have not finished linking is not a fleet in trouble: the header stays quiet.+ assert.ok(verdict.findings.every(finding => finding.severity === 'info'));+ assert.equal(verdict.ready, true);+});++test('a machine that should have answered and did not is the one warning', () => {+ const verdict = verdictFor({+ status: 'partial', observedAt: '2026-09-20T10:00:00.000Z',+ summary: { machines: 2, online: 2, harnesses: 4 },+ machines: [+ { id: 'a', name: 'Studio', status: 'online', needsLink: false },+ { id: 'b', name: 'Rack', status: 'online', needsLink: false, error: 'This machine did not answer in time.' },+ ],+ });+ assert.equal(verdict.ready, false);+ assert.equal(verdict.findings.filter(f => f.severity === 'warning').length, 1);+ assert.match(verdict.findings[0].message, /Rack did not answer/);+});++test('a fleet with nothing to do is ready', () => {+ const verdict = verdictFor({+ status: 'live', summary: { machines: 1, online: 1, harnesses: 4 },+ machines: [{ id: 'a', name: 'Studio', status: 'online', needsLink: false }],+ });+ assert.equal(verdict.ready, true);+ assert.deepEqual(verdict.findings, []);+});++test('a signed-out computer is an error in the header, not a ready fleet', () => {+ const verdict = verdictFor({ status: 'signed-out', observedAt: '2026-09-20T10:00:00.000Z', machines: [], summary: {} });+ assert.equal(verdict.ready, false);+ assert.equal(verdict.findings[0].kind, 'signed_out');+ assert.equal(verdict.summary, 'No machines on this account yet');+});++test('a workspace that has read nothing yet says so, instead of claiming an empty account', () => {+ const verdict = verdictFor({ status: 'connecting', machines: [], summary: {} });+ assert.equal(verdict.summary, 'Reading your machines…');+ assert.equal(verdict.ready, false);+});diff --git a/store/agents/machines/test/ops.test.mjs b/store/agents/machines/test/ops.test.mjsnew file mode 100644index 000000000..32682ba17--- /dev/null+++ b/store/agents/machines/test/ops.test.mjs@@ -0,0 +1,63 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { lastJson, linkMachine, resolveMachine, setRemotePassword, watchForNewMachine } from '../lib/ops.mjs';++const MACHINES = [+ { id: 'a'.repeat(32), name: 'Studio', givenName: 'Studio', nickname: null, hostname: 'studio.local' },+ { id: 'b'.repeat(32), name: 'Rack', givenName: 'Rack', nickname: null, hostname: 'rack' },+ { id: 'c'.repeat(32), name: 'iMac Office', givenName: 'iMac Office', nickname: 'the office one', hostname: 'imac-office' },+ { id: 'd'.repeat(32), name: 'iMac Home', givenName: 'iMac Home', nickname: null, hostname: 'imac-home' },+];++test('a machine is found by id, id prefix, name, hostname or nickname', () => {+ assert.equal(resolveMachine(MACHINES, 'a'.repeat(32)).machine.name, 'Studio');+ assert.equal(resolveMachine(MACHINES, 'bbbbbbbb').machine.name, 'Rack');+ assert.equal(resolveMachine(MACHINES, 'rack').machine.name, 'Rack');+ assert.equal(resolveMachine(MACHINES, 'the office one').machine.name, 'iMac Office');+ assert.equal(resolveMachine(MACHINES, 'imac-home').machine.name, 'iMac Home');+});++test('an ambiguous name is refused with its candidates, never guessed', () => {+ const found = resolveMachine(MACHINES, 'iMac');+ assert.equal(found.machine, undefined);+ assert.match(found.error, /matches 2 machines/);+ assert.deepEqual(found.candidates.map(machine => machine.name), ['iMac Office', 'iMac Home']);+});++test('a name nothing matches is refused, and an empty one asks', () => {+ assert.match(resolveMachine(MACHINES, 'nowhere').error, /No machine here matches/);+ assert.match(resolveMachine(MACHINES, ' ').error, /Name a machine/);+});++test('the last JSON line of an NDJSON answer is the result', () => {+ assert.deepEqual(lastJson('progress\n{"ok":false}\n{"ok":true,"machineId":"x"}\n'), { ok: true, machineId: 'x' });+ assert.equal(lastJson('nothing to see'), null);+});++test('linking refuses before it runs anything when the inputs are not a link', async () => {+ assert.equal((await linkMachine('not-an-id', 'hunter2')).error, 'That is not a machine id.');+ assert.match((await linkMachine('a'.repeat(32), ' ')).error, /Enter the remote password/);+ assert.match((await setRemotePassword('short')).error, /at least 8 characters/);+});++test('watching reports the machine that arrives, and gives up when none does', async () => {+ const first = [{ machineId: 'a'.repeat(32) }];+ let calls = 0;+ const list = async () => {+ calls += 1;+ return { ok: true, machines: calls > 1 ? [...first, { machineId: 'z'.repeat(32), name: 'New rig' }] : first };+ };+ const found = await watchForNewMachine({ seconds: 5, pollMs: 5, list });+ assert.equal(found.ok, true);+ assert.equal(found.machines[0].name, 'New rig');++ const nothing = await watchForNewMachine({ seconds: 1, pollMs: 20, list: async () => ({ ok: true, machines: first }) });+ assert.equal(nothing.ok, false);+ assert.equal(nothing.timedOut, true);+});++test('watching says so when the fleet itself cannot be read', async () => {+ const result = await watchForNewMachine({ seconds: 1, pollMs: 5, list: async () => ({ ok: false, error: 'Harness is not running on this computer.' }) });+ assert.equal(result.ok, false);+ assert.match(result.error, /not running/);+});diff --git a/store/agents/machines/test/server.test.mjs b/store/agents/machines/test/server.test.mjsnew file mode 100644index 000000000..43d49a6bc--- /dev/null+++ b/store/agents/machines/test/server.test.mjs@@ -0,0 +1,139 @@+import assert from 'node:assert/strict';+import { request } from 'node:http';+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import test from 'node:test';+import { createViewer } from '../viewer.mjs';++const SNAPSHOT = {+ spec: 1, status: 'live', observedAt: '2026-09-20T10:00:00.000Z', pollIntervalMs: 15_000,+ account: { email: '[email protected]', name: 'Someone' }, localMachineId: 'a'.repeat(32),+ thisComputer: { machineId: 'a'.repeat(32), version: '0.2.0', connected: true, remotePasswordSet: true },+ machines: [+ { id: 'a'.repeat(32), name: 'Studio', local: true, status: 'online', needsLink: false, harnesses: [], harnessCount: 0, openCount: 0, projectCount: 0 },+ { id: 'b'.repeat(32), name: 'Rack', local: false, status: 'online', needsLink: true, harnesses: [], harnessCount: 0, openCount: 0, projectCount: 0 },+ ],+ projects: [], summary: { machines: 2, online: 2, needsLink: 1, harnesses: 0, open: 0, projects: 0, engines: {} }, sources: {},+};++async function serve(collect = async () => SNAPSHOT) {+ const workspace = await mkdtemp(join(tmpdir(), 'machines-server-'));+ const viewer = createViewer({ workspace, port: 0, intervalMs: 60_000, collect });+ const port = await viewer.start();+ test.after(async () => { await viewer.close(); await rm(workspace, { recursive: true, force: true }); });+ return { base: `http://127.0.0.1:${port}`, workspace };+}++test('the pane serves its own observation and its three files', async () => {+ const { base } = await serve();+ const snapshot = await (await fetch(`${base}/api/snapshot`)).json();+ assert.equal(snapshot.summary.machines, 2);++ const page = await fetch(`${base}/`);+ assert.equal(page.status, 200);+ assert.match(page.headers.get('content-security-policy'), /default-src 'self'/);+ assert.match(await page.text(), /<title>Machines/);++ for (const path of ['/app.js', '/app.css']) assert.equal((await fetch(`${base}${path}`)).status, 200);+ assert.equal((await fetch(`${base}/../lib/daemon.mjs`)).status, 404);+});++/** The first poll runs as the server starts; wait for what it writes rather than racing it. */+async function eventually(read, attempts = 40) {+ for (let attempt = 0; attempt < attempts; attempt += 1) {+ try { return await read(); } catch { await new Promise(done => setTimeout(done, 25)); }+ }+ return read();+}++test('the observation is published to the workspace, with a verdict beside it', async () => {+ const { workspace } = await serve();+ const published = await eventually(async () => JSON.parse(await readFile(join(workspace, '.harness', 'snapshot.json'), 'utf8')));+ assert.equal(published.machines.length, 2);+ const verdict = await eventually(async () => JSON.parse(await readFile(join(workspace, '.harness', 'verdict.json'), 'utf8')));+ assert.equal(verdict.spec, 1);+ assert.equal(verdict.summary, '2 machines · 2 online · 0 harnesses');+});++test('a request that was not addressed to this loopback port is refused', async () => {+ const { base } = await serve();+ const port = Number(new URL(base).port);+ // `fetch` will not let a caller set Host, and that is exactly the header the guard reads — so this+ // one goes out over a plain socket, the way a page on another origin would reach the port.+ const status = await new Promise((done, fail) => {+ const call = request({ host: '127.0.0.1', port, path: '/api/snapshot', headers: { host: 'somewhere.example.com' } }, response => {+ response.resume();+ done(response.statusCode);+ });+ call.on('error', fail);+ call.end();+ });+ assert.equal(status, 403);+});++test('the pane takes no writes but the one', async () => {+ const { base } = await serve();+ for (const method of ['PUT', 'DELETE', 'PATCH']) {+ const response = await fetch(`${base}/api/snapshot`, { method });+ assert.equal(response.status, 405);+ assert.match((await response.json()).error, /read-only/);+ }+ const post = await fetch(`${base}/api/rename`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });+ assert.equal(post.status, 405);+});++test('a link request is checked before anything is run', async () => {+ const { base } = await serve();+ const link = (body) => fetch(`${base}/api/link`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });++ const unknown = await link({ machineId: 'z'.repeat(32), password: 'hunter2hunter2' });+ assert.equal(unknown.status, 404);++ const empty = await link({ machineId: 'b'.repeat(32), password: ' ' });+ assert.equal(empty.status, 400);+ assert.match((await empty.json()).error, /remote password/);++ const huge = await fetch(`${base}/api/link`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: 'x'.repeat(5000) });+ assert.equal(huge.status, 413);+});++test('a reading that throws leaves the machines on screen, marked stale, and says what happened', async () => {+ let fail = false;+ const workspace = await mkdtemp(join(tmpdir(), 'machines-server-'));+ const viewer = createViewer({+ workspace, port: 0, intervalMs: 30,+ collect: async () => { if (fail) throw new Error('the daemon went away'); return SNAPSHOT; },+ });+ const port = await viewer.start();+ test.after(async () => { await viewer.close(); await rm(workspace, { recursive: true, force: true }); });++ const read = async () => (await fetch(`http://127.0.0.1:${port}/api/snapshot`)).json();+ assert.equal((await eventually(async () => {+ const snapshot = await read();+ if (snapshot.status !== 'live') throw new Error('not yet');+ return snapshot;+ })).machines.length, 2);++ fail = true;+ const broken = await eventually(async () => {+ const snapshot = await read();+ if (snapshot.status !== 'unavailable') throw new Error('not yet');+ return snapshot;+ });+ assert.equal(broken.machines.length, 2, 'the machines stay until a new reading replaces them');+ assert.ok(broken.machines.every(machine => machine.stale), 'and every one of them is marked stale');+ assert.match(broken.sources.collector.error, /went away/);+});++test('the event stream opens with the current observation', async () => {+ const { base } = await serve();+ const response = await fetch(`${base}/events`);+ assert.equal(response.headers.get('content-type'), 'text/event-stream');+ const reader = response.body.getReader();+ const { value } = await reader.read();+ const text = new TextDecoder().decode(value);+ assert.match(text, /^event: snapshot/);+ assert.match(text, /"status":"live"/);+ await reader.cancel();+});diff --git a/store/agents/machines/test/snapshot.test.mjs b/store/agents/machines/test/snapshot.test.mjsnew file mode 100644index 000000000..78eb436cc--- /dev/null+++ b/store/agents/machines/test/snapshot.test.mjs@@ -0,0 +1,107 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { createCollector, machineName, projectKey, projectsOf } from '../lib/snapshot.mjs';+import { fakeReads, OWNER_MACHINES, RACK_ROSTER, STUDIO_ROSTER } from './fixtures.mjs';++const A = 'a'.repeat(32), B = 'b'.repeat(32), C = 'c'.repeat(32), D = 'd'.repeat(32), E = 'e'.repeat(32);+const collect = (options = {}) => createCollector('/tmp/does-not-matter', {+ read: fakeReads(options), env: {},+})();++test('a machine is named by its nickname, then its name, then its hostname', () => {+ assert.equal(machineName({ machineId: A, name: 'Studio', hostname: 'studio.local' }, {}), 'Studio');+ assert.equal(machineName({ machineId: A, name: 'Studio', hostname: 'studio.local' }, { [A]: 'the loud one' }), 'the loud one');+ assert.equal(machineName({ machineId: A, name: null, hostname: 'studio.local' }, {}), 'studio.local');+ assert.equal(machineName({ machineId: A, name: null, hostname: null }, {}), `machine ${A.slice(0, 8)}`);+});++test('the same repository on two machines is one project; two folders are not', () => {+ const repo = { name: 'circuit', cwd: '/a', root: '/a', remote: 'github.com/acme/circuit', branch: 'main' };+ assert.equal(projectKey(A, repo), projectKey(B, repo));+ const folder = { name: 'notes', cwd: '/a/notes', root: null, remote: null, branch: null };+ assert.notEqual(projectKey(A, folder), projectKey(B, folder));+});++test('a reading carries every machine, and only the linked ones carry a roster', async () => {+ const snapshot = await collect({ rosters: { [A]: STUDIO_ROSTER, [B]: RACK_ROSTER }, peers: [{ machineId: B, linkedAt: '2026-09-01T00:00:00.000Z' }] });+ assert.equal(snapshot.machines.length, OWNER_MACHINES.length);+ const byId = Object.fromEntries(snapshot.machines.map(machine => [machine.id, machine]));++ assert.equal(byId[A].local, true);+ assert.equal(byId[A].harnessCount, 3);+ assert.equal(byId[A].openCount, 2);+ assert.equal(byId[A].projectCount, 2);++ assert.equal(byId[B].linkState, 'linked');+ assert.equal(byId[B].harnessCount, 1);++ // Never asked, and so never reported as empty: the pane must be able to tell the two apart.+ assert.equal(byId[C].needsLink, true);+ assert.equal(byId[C].harnesses.length, 0);+ // Presence and link state are independent: a machine can be offline AND still need a link, and+ // both are reported, the way the app's own machine menu reports them.+ assert.equal(byId[D].status, 'offline');+ assert.equal(byId[D].needsLink, true);+ assert.equal(byId[D].harnesses.length, 0);+});++test('an unlinked machine does not make the whole reading partial', async () => {+ const snapshot = await collect({ rosters: { [A]: STUDIO_ROSTER } });+ assert.equal(snapshot.status, 'live');+ assert.equal(snapshot.summary.needsLink, 4);+});++test('a machine that was readable and then fails keeps its last roster, marked stale', async () => {+ let answer = { ok: true, harnesses: STUDIO_ROSTER };+ const collector = createCollector('/tmp/does-not-matter', {+ env: {},+ read: { ...fakeReads({}), roster: async () => answer },+ });+ const first = await collector();+ assert.equal(first.machines.find(m => m.id === A).harnessCount, 3);+ answer = { ok: false, error: 'This machine did not answer in time.' };+ const second = await collector();+ const machine = second.machines.find(m => m.id === A);+ assert.equal(machine.harnessCount, 3, 'the last known roster stays');+ assert.equal(machine.stale, true);+ assert.equal(machine.error, 'This machine did not answer in time.');+ assert.equal(second.status, 'partial');+});++test('a shared machine is never dialled', async () => {+ const dialled = [];+ const reads = fakeReads({ shares: [{ machineId: E, ownerName: 'A teammate' }] });+ const snapshot = await createCollector('/tmp/x', { env: {}, read: { ...reads, roster: async id => { dialled.push(id); return reads.roster(id); } } })();+ assert.ok(!dialled.includes(E));+ const shared = snapshot.machines.find(m => m.id === E);+ assert.equal(shared.shared, true);+ assert.equal(shared.ownerName, 'A teammate');+});++test('projects gather across machines, busiest first, with their branches', async () => {+ const snapshot = await collect({ rosters: { [A]: STUDIO_ROSTER, [B]: RACK_ROSTER }, peers: [{ machineId: B, linkedAt: null }] });+ const circuit = snapshot.projects.find(project => project.name === 'circuit');+ assert.equal(circuit.harnesses, 3);+ assert.equal(circuit.open, 2);+ assert.deepEqual(circuit.machines.sort(), [A, B].sort());+ assert.deepEqual(circuit.branches.sort(), ['gpu', 'main']);+ assert.equal(snapshot.projects[0].name, 'circuit', 'the busiest project leads');+});++test('the newest harness is read from creation time, never from the registry’s reconcile stamp', () => {+ const projects = projectsOf([{ id: A, harnesses: [+ { open: true, createdAt: '2026-09-18T09:00:00.000Z', updatedAt: '2026-09-20T12:00:00.000Z', project: { key: 'repo:x', name: 'x', branch: 'main', repo: 'x' } },+ { open: false, createdAt: '2026-09-19T09:00:00.000Z', updatedAt: '2026-09-20T12:00:00.000Z', project: { key: 'repo:x', name: 'x', branch: 'main', repo: 'x' } },+ ] }]);+ assert.equal(projects[0].newestAt, '2026-09-19T09:00:00.000Z');+});++test('a signed-out computer is said so, with no machines invented', async () => {+ const snapshot = await createCollector('/tmp/x', {+ env: {},+ read: { ...fakeReads({}), machines: async () => ({ ok: false, signedOut: true, error: 'Not signed in to Harness on this computer. Run `harness login`.', machines: [] }) },+ })();+ assert.equal(snapshot.status, 'signed-out');+ assert.deepEqual(snapshot.machines, []);+ assert.match(snapshot.message, /harness login/);+});diff --git a/store/agents/machines/toolchain/doctor.sh b/store/agents/machines/toolchain/doctor.shnew file mode 100755index 000000000..1307de2fd--- /dev/null+++ b/store/agents/machines/toolchain/doctor.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+. toolchain/runtimes.sh+harness_node 22+node toolchain/machines.mjs doctordiff --git a/store/agents/machines/toolchain/init-workspace.sh b/store/agents/machines/toolchain/init-workspace.shnew file mode 100755index 000000000..43e095ff9--- /dev/null+++ b/store/agents/machines/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 >/dev/null+exec node "$here/toolchain/machines.mjs" initdiff --git a/store/agents/machines/toolchain/machines b/store/agents/machines/toolchain/machinesnew file mode 100755index 000000000..14a5428dc--- /dev/null+++ b/store/agents/machines/toolchain/machines@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# The command the agent runs. Keeps Harness's own Node on PATH so a machine without one still works.+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+. "$here/runtimes.sh"+harness_node 22 >/dev/null+exec node "$here/machines.mjs" "$@"diff --git a/store/agents/machines/toolchain/machines.mjs b/store/agents/machines/toolchain/machines.mjsnew file mode 100644index 000000000..941455971--- /dev/null+++ b/store/agents/machines/toolchain/machines.mjs@@ -0,0 +1,352 @@+#!/usr/bin/env node+/**+ * `machines …` — the agent's hands on the fleet.+ *+ * Every subcommand is one thing a person asks for in plain words: show me my machines, call that+ * one the studio Mac, link it, drop it, what is it running. Reads prefer the observation the pane+ * already published (no second poll); anything that changes a machine re-reads the live list first,+ * so a rename or a removal is never aimed at a row that has gone stale.+ *+ * Text by default, because the person is watching this terminal. `--json` for a machine-readable+ * answer. Exit code 1 means the thing did not happen.+ */+import { resolve } from 'node:path';+import { deleteMachine, listMachines, renameMachine } from '../lib/daemon.mjs';+import { now, readJson, readRecord, recordOperation, stateDir, writeRecord, writeVerdict } from '../lib/fleet.mjs';+import { clearRemotePassword, linkMachine, listLinks, remotePasswordStatus, resolveMachine, setRemotePassword, unlinkMachine, watchForNewMachine } from '../lib/ops.mjs';+import { createCollector, machineName } from '../lib/snapshot.mjs';++const workspace = resolve(process.env.HARNESS_WORKSPACE || process.cwd());+const argv = process.argv.slice(2);+const flags = new Set(argv.filter(a => a.startsWith('--')));+const named = key => argv.find(a => a.startsWith(`--${key}=`))?.slice(key.length + 3);+const words = argv.filter(a => !a.startsWith('--'));+const asJson = flags.has('--json');++const out = (text = '') => process.stdout.write(`${text}\n`);+const emit = (value, text) => { if (asJson) out(JSON.stringify(value, null, 2)); else text(); };+function fail(message, extra = {}) {+ if (asJson) out(JSON.stringify({ ok: false, error: message, ...extra }, null, 2));+ else process.stderr.write(`${message}\n`);+ process.exit(1);+}++const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;+function ago(time) {+ const at = Date.parse(time);+ if (!Number.isFinite(at)) return 'never';+ const seconds = Math.max(0, (Date.now() - at) / 1000);+ if (seconds < 90) return `${Math.round(seconds)}s ago`;+ if (seconds < 5400) return `${Math.round(seconds / 60)}m ago`;+ if (seconds < 172800) return `${Math.round(seconds / 3600)}h ago`;+ return `${Math.round(seconds / 86400)}d ago`;+}+/** Presence and link state are independent segments, the same split the Machines menu makes. */+function stateWord(machine) {+ if (machine.local) return 'this computer';+ if (machine.shared) return 'shared with you';+ const presence = machine.status === 'online' ? 'online' : machine.status === 'offline' ? 'offline' : 'status unknown';+ return machine.needsLink ? `${presence} · link required` : presence;+}++/** The pane's latest observation. The pane writes it every poll; nothing here re-polls to read it. */+async function published() {+ return readJson(`${stateDir(workspace)}/snapshot.json`, null);+}++/** A fresh observation, written where the pane and the agent both read it. */+async function observe() {+ const snapshot = await createCollector(workspace)();+ await writeVerdict(workspace, snapshot).catch(() => {});+ return snapshot;+}++/** Machines as the fleet currently reports them — always live, for anything that changes one. */+async function liveMachines() {+ const list = await listMachines();+ if (!list.ok) fail(list.error);+ const record = await readRecord(workspace);+ return list.machines.filter(row => typeof row?.machineId === 'string').map(row => ({+ id: row.machineId,+ name: machineName(row, record.nicknames),+ givenName: typeof row.name === 'string' ? row.name : null,+ nickname: record.nicknames?.[row.machineId] ?? null,+ hostname: typeof row.hostname === 'string' ? row.hostname : null,+ status: row.status === 'running' ? 'online' : row.status === 'offline' || row.status === 'stopped' ? 'offline' : 'unknown',+ local: false,+ }));+}++function pick(machines, query) {+ const found = resolveMachine(machines, query);+ if (found.machine) return found.machine;+ const names = (found.candidates ?? []).slice(0, 12).map(m => ` ${m.name}${m.hostname && m.hostname !== m.name ? ` (${m.hostname})` : ''} ${m.id.slice(0, 8)}`);+ fail([found.error, ...(names.length ? ['', 'Machines here:', ...names] : [])].join('\n'), { candidates: found.candidates?.map(m => ({ id: m.id, name: m.name })) });+}++function printFleet(snapshot) {+ if (!snapshot?.machines?.length) { out(snapshot?.message || 'No machines on this account yet.'); return; }+ const rows = snapshot.machines.map(machine => [+ machine.name,+ stateWord(machine),+ machine.needsLink ? '—' : plural(machine.harnessCount ?? 0, 'harness', 'harnesses'),+ machine.openCount ? `${machine.openCount} open` : '',+ machine.id.slice(0, 8),+ ]);+ const width = column => Math.max(...rows.map(row => row[column].length));+ for (const row of rows) {+ out(` ${row[0].padEnd(width(0))} ${row[1].padEnd(width(1))} ${row[2].padEnd(width(2))} ${row[3].padEnd(width(3))} ${row[4]}`);+ }+ const summary = snapshot.summary ?? {};+ out('');+ out(` ${plural(summary.machines ?? 0, 'machine')} · ${summary.online ?? 0} online · ${plural(summary.harnesses ?? 0, 'harness', 'harnesses')} · ${plural(summary.projects ?? 0, 'project')}`);+ if (snapshot.observedAt) out(` observed ${ago(snapshot.observedAt)}`);+ const linkable = snapshot.machines.filter(machine => machine.needsLink && machine.status !== 'offline').length;+ if (linkable) out(` ${plural(linkable, 'machine')} can be linked from this computer right now.`);+}++function printMachine(machine) {+ out(` ${machine.name}${machine.nickname ? ` (called "${machine.nickname}" here)` : ''}`);+ out(` ${stateWord(machine)}${machine.hostname ? ` · ${machine.hostname}` : ''}`);+ out(` id ${machine.id}`);+ if (machine.linkedAt) out(` linked from this computer ${ago(machine.linkedAt)}`);+ if (machine.note) out(` note: ${machine.note}`);+ if (machine.error) out(` could not be read: ${machine.error}`);+ const projects = new Map();+ for (const harness of machine.harnesses ?? []) {+ const key = harness.project?.key ?? 'none';+ const found = projects.get(key) ?? { name: harness.project?.name ?? 'no project', branch: harness.project?.branch ?? null, harnesses: [] };+ found.harnesses.push(harness);+ projects.set(key, found);+ }+ if (!projects.size) { out(machine.needsLink ? ' Link it to see what it is running.' : ' Nothing running here.'); return; }+ out('');+ for (const project of projects.values()) {+ out(` ${project.name}${project.branch ? ` · ${project.branch}` : ''}`);+ for (const harness of project.harnesses.slice(0, 12)) {+ out(` ${harness.open ? '●' : '○'} ${harness.name} ${harness.agent}${harness.createdAt ? ` · started ${ago(harness.createdAt)}` : ''}`);+ }+ if (project.harnesses.length > 12) out(` …and ${project.harnesses.length - 12} more`);+ }+}++const usage = `machines — your computers, managed by asking++ machines status what the pane is showing right now (no network)+ machines list [--json] a fresh read of every machine on the account+ machines show <machine> one machine: state, projects, harnesses+ machines rename <machine> <name> rename it everywhere (this is the real name)+ machines nickname <machine> <text|--clear> a name only this workspace uses+ machines note <machine> <text|--clear> something to remember about it+ machines group <name> add|remove <machine> keep a set of machines together+ machines link <machine> [--name=<label>] link it from here (password on stdin)+ machines unlink <machine> drop this computer's link to it+ machines links what this computer has linked+ machines password [set|clear] this computer's remote password (stdin)+ machines invite how to bring a new computer in+ machines watch [--seconds=N] wait for a new machine to sign in+ machines remove <machine> --yes remove it from the account (not undoable)+ machines refresh observe now and rewrite the pane's snapshot+ machines doctor can this computer manage the fleet?`;++async function main() {+ const command = words[0] ?? 'status';+ switch (command) {+ case 'status': {+ const snapshot = await published();+ if (!snapshot) { out('The pane has not published an observation yet. Run `machines refresh`.'); return; }+ emit(snapshot, () => printFleet(snapshot));+ return;+ }+ case 'refresh': {+ const snapshot = await observe();+ emit(snapshot, () => printFleet(snapshot));+ return;+ }+ case 'list': {+ const snapshot = await observe();+ emit({ ok: true, machines: snapshot.machines, summary: snapshot.summary }, () => printFleet(snapshot));+ return;+ }+ case 'show': {+ const snapshot = (await published()) ?? (await observe());+ const machine = pick(snapshot.machines ?? [], words.slice(1).join(' '));+ emit({ ok: true, machine }, () => printMachine(machine));+ return;+ }+ case 'rename': {+ const machines = await liveMachines();+ const machine = pick(machines, words[1]);+ const name = words.slice(2).join(' ').trim();+ if (!name) fail('Say what to call it: machines rename <machine> <name>');+ if (name.length > 40) fail('A machine name is at most 40 characters.');+ const result = await renameMachine(machine.id, name);+ if (!result.ok) fail(result.error);+ await recordOperation(workspace, { kind: 'rename', machineId: machine.id, machine: name, detail: `Renamed ${machine.name} to ${name}` });+ emit({ ok: true, machineId: machine.id, name }, () => out(` ${machine.name} is now ${name}.`));+ return;+ }+ case 'nickname':+ case 'note': {+ const record = await readRecord(workspace);+ const snapshot = (await published()) ?? { machines: await liveMachines() };+ const machine = pick(snapshot.machines ?? [], words[1]);+ const field = command === 'nickname' ? 'nicknames' : 'notes';+ const value = words.slice(2).join(' ').trim();+ if (flags.has('--clear') || !value) delete record[field][machine.id];+ else record[field][machine.id] = value;+ await writeRecord(workspace, record);+ emit({ ok: true, machineId: machine.id, [command]: record[field][machine.id] ?? null }, () => out(+ record[field][machine.id] ? ` ${machine.name} · ${command} "${record[field][machine.id]}"` : ` Cleared the ${command} for ${machine.name}.`));+ return;+ }+ case 'group': {+ const [, name, action, ...rest] = words;+ if (!name || !['add', 'remove'].includes(action)) fail('Usage: machines group <name> add|remove <machine>');+ const record = await readRecord(workspace);+ const snapshot = (await published()) ?? { machines: await liveMachines() };+ const machine = pick(snapshot.machines ?? [], rest.join(' '));+ const members = new Set(record.groups[name] ?? []);+ if (action === 'add') members.add(machine.id); else members.delete(machine.id);+ record.groups[name] = [...members];+ if (!record.groups[name].length) delete record.groups[name];+ await writeRecord(workspace, record);+ emit({ ok: true, group: name, members: record.groups[name] ?? [] }, () => out(` ${name}: ${plural((record.groups[name] ?? []).length, 'machine')}`));+ return;+ }+ case 'link': {+ const machines = await liveMachines();+ const machine = pick(machines, words.slice(1).join(' '));+ // Always --stdin, never a positional: a password in an argument is in the shell history and+ // in every `ps` on the machine. Without the flag this command only explains where it belongs.+ if (!flags.has('--stdin')) {+ // The password is the person's, and the pane is where it belongs: typed once, into the row+ // that is asking for it, never through the conversation or a shell line.+ fail([`${machine.name} needs its remote password to link.`,+ 'Ask the person to click Link on that machine in the pane and type it there.',+ 'If they would rather pipe it: machines link <machine> --stdin, with the password on stdin.'].join('\n'),+ { machineId: machine.id, needsPassword: true });+ }+ const password = await new Promise(done => { let buffer = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', chunk => { buffer += chunk; }); process.stdin.on('end', () => done(buffer.trim())); });+ const result = await linkMachine(machine.id, password, { displayName: named('name') || machine.name });+ await recordOperation(workspace, { kind: 'link', machineId: machine.id, machine: machine.name, detail: result.ok ? `Linked ${machine.name}` : `Link refused: ${result.error}`, ok: result.ok });+ if (!result.ok) fail(result.error, { machineId: machine.id });+ emit({ ok: true, machineId: machine.id }, () => out(` Linked ${machine.name}. Its harnesses will appear in the pane on the next observation.`));+ return;+ }+ case 'unlink': {+ const machines = await liveMachines();+ const machine = pick(machines, words.slice(1).join(' '));+ const result = await unlinkMachine(machine.id);+ await recordOperation(workspace, { kind: 'unlink', machineId: machine.id, machine: machine.name, detail: result.ok ? `Unlinked ${machine.name}` : `Unlink failed: ${result.error}`, ok: result.ok });+ if (!result.ok) fail(result.error);+ emit({ ok: true, machineId: machine.id }, () => out(` Unlinked ${machine.name}. It stays on the account; this computer just cannot reach into it.`));+ return;+ }+ case 'links': {+ const result = await listLinks();+ emit({ ok: result.ok, text: result.text }, () => out(result.text));+ return;+ }+ case 'password': {+ const action = words[1] ?? 'status';+ if (action === 'status') {+ const status = await remotePasswordStatus();+ emit({ ok: true, set: status.set }, () => out(status.set+ ? ' This computer has a remote password, so your other machines can link to it.'+ : ' No remote password here. Set one to let another machine link to this computer.'));+ return;+ }+ if (action === 'clear') {+ const result = await clearRemotePassword();+ if (!result.ok) fail(result.error);+ await recordOperation(workspace, { kind: 'password', detail: 'Cleared this computer\'s remote password' });+ emit({ ok: true }, () => out(' Cleared. Machines that linked with it stay linked; new links cannot use it.'));+ return;+ }+ if (action === 'set') {+ if (process.stdin.isTTY) fail('Pipe the new password in: machines password set < ‹the password›. It never goes in an argument.');+ const password = await new Promise(done => { let buffer = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', chunk => { buffer += chunk; }); process.stdin.on('end', () => done(buffer.trim())); });+ const result = await setRemotePassword(password);+ if (!result.ok) fail(result.error);+ await recordOperation(workspace, { kind: 'password', detail: 'Set this computer\'s remote password' });+ emit({ ok: true }, () => out(' Set. Another machine can now link to this one with it.'));+ return;+ }+ fail('Usage: machines password [status|set|clear]');+ return;+ }+ case 'invite': {+ const status = await remotePasswordStatus();+ const steps = [+ 'On the computer you are bringing in:',+ ' 1. Install Harness — the app from autonomous.ai/harness, or:',+ ' curl -fsSL https://cdn.autonomous.ai/harness/cli/install.sh | bash',+ ' 2. Sign in to THIS account: harness login',+ ' 3. Let this computer reach it: harness start && harness remote-password set',+ '',+ 'Then it appears on the account by itself, and its remote password links it from here.',+ status.set ? 'This computer already has a remote password, so it can be linked to as well.'+ : 'This computer has no remote password yet, so nothing can link to it. Say the word and I will set one.',+ ];+ emit({ ok: true, steps, remotePasswordSet: status.set }, () => out(steps.join('\n')));+ return;+ }+ case 'watch': {+ const seconds = Number(named('seconds') ?? 300);+ const result = await watchForNewMachine({ seconds });+ if (!result.ok) fail(result.error, { timedOut: result.timedOut === true });+ const arrivals = result.machines.map(row => ({ id: row.machineId, name: row.name || row.hostname || row.machineId.slice(0, 8) }));+ for (const arrival of arrivals) await recordOperation(workspace, { kind: 'joined', machineId: arrival.id, machine: arrival.name, detail: `${arrival.name} signed in` });+ emit({ ok: true, machines: arrivals }, () => out(` ${arrivals.map(a => a.name).join(', ')} signed in just now.`));+ return;+ }+ case 'remove': {+ const machines = await liveMachines();+ const machine = pick(machines, words.slice(1).join(' '));+ const snapshot = await published();+ const local = snapshot?.localMachineId ?? null;+ if (machine.id === local) fail('That is this computer. Removing it from here would cut the connection you are using; `harness logout` is the way to release it.');+ if (!flags.has('--yes')) fail(`Removing ${machine.name} from the account cannot be undone. Confirm with the person, then run it again with --yes.`);+ const result = await deleteMachine(machine.id);+ if (!result.ok) fail(result.error);+ await recordOperation(workspace, { kind: 'remove', machineId: machine.id, machine: machine.name, detail: `Removed ${machine.name} from the account` });+ emit({ ok: true, machineId: machine.id }, () => out(` Removed ${machine.name}. It can sign in again at any time and come back as a new machine.`));+ return;+ }+ case 'doctor': {+ const snapshot = await createCollector(workspace)();+ const lines = [];+ lines.push(snapshot.status === 'unavailable' || snapshot.status === 'signed-out'+ ? `miss ${snapshot.message}`+ : `ok Harness answers on this computer${snapshot.thisComputer?.version ? ` (v${snapshot.thisComputer.version})` : ''}`);+ if (snapshot.account?.email) lines.push(`ok signed in as ${snapshot.account.email}`);+ if (snapshot.machines.length) lines.push(`ok ${plural(snapshot.machines.length, 'machine')} on this account, ${snapshot.summary.online} online`);+ // Only a machine that is up and unlinked is something to do now; an offline one is a fact.+ for (const machine of snapshot.machines.filter(m => m.needsLink && m.status !== 'offline')) {+ lines.push(`warn ${machine.name} is online but not linked from this computer`);+ }+ const asleep = snapshot.machines.filter(m => m.status === 'offline').length;+ if (asleep) lines.push(`ok ${plural(asleep, 'machine')} offline`);+ out(lines.join('\n'));+ process.exit(lines.some(line => line.startsWith('miss')) ? 1 : 0);+ return;+ }+ case 'init': {+ // First run in a fresh workspace: lay down the record and a verdict, so the header has a state+ // before the first prompt. No network is required for this to succeed.+ const record = await readRecord(workspace);+ await writeRecord(workspace, record);+ await writeVerdict(workspace, { status: 'connecting', observedAt: now(), machines: [], summary: {} });+ out('Machines workspace ready.');+ return;+ }+ case 'help': case '--help': case '-h':+ out(usage);+ return;+ default:+ fail(`Unknown command: ${command}\n\n${usage}`);+ }+}++main().catch(error => fail(String(error?.message || error)));diff --git a/store/agents/machines/toolchain/runtimes.sh b/store/agents/machines/toolchain/runtimes.shnew file mode 100644index 000000000..7223c78dc--- /dev/null+++ b/store/agents/machines/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/machines/toolchain/setup.sh b/store/agents/machines/toolchain/setup.shnew file mode 100755index 000000000..de836cdb3--- /dev/null+++ b/store/agents/machines/toolchain/setup.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+. toolchain/runtimes.sh+harness_node 22+echo "ok node $(node -v) (the pane and the fleet commands need nothing else)"+echo "ok Machines talks to Harness on this computer — no service to install, no model to download"diff --git a/store/agents/machines/viewer.mjs b/store/agents/machines/viewer.mjsnew file mode 100644index 000000000..bc999b7b2--- /dev/null+++ b/store/agents/machines/viewer.mjs@@ -0,0 +1,179 @@+/**+ * The pane: a read-only loopback server that publishes one observation of the fleet and streams+ * every new one to the page beside the terminal.+ *+ * It serves three files and two endpoints. Everything that changes a machine — a name, a link, a+ * removal — happens in the conversation, through the agent, so the map is a mirror of what Harness+ * reports and not a second control panel.+ *+ * There is exactly ONE write, and it exists for a secret: another machine's remote password. That+ * password is the person's, and typing it to an agent would put it in a transcript, so the row that+ * needs it takes it here instead — straight into `harness link connect`'s stdin, never stored,+ * never logged, never in a snapshot. Nothing else on this server accepts input.+ */+import { createServer } from 'node:http';+import { readFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { atomicJson, operations, PACKAGE, recordOperation, stateDir, writeVerdict } from './lib/fleet.mjs';+import { linkMachine } from './lib/ops.mjs';+import { createCollector } from './lib/snapshot.mjs';++const EMPTY = {+ spec: 1, status: 'connecting', message: null, observedAt: null, pollIntervalMs: 15_000,+ account: null, localMachineId: null, thisComputer: null,+ machines: [], projects: [], operations: [], totals: null,+ summary: { machines: 0, online: 0, needsLink: 0, harnesses: 0, open: 0, projects: 0, engines: {} },+ sources: {},+};++export function createViewer({ workspace, port = 0, intervalMs = 15_000, collect = createCollector(workspace, { intervalMs }) }) {+ const clients = new Set();+ let snapshot = { ...EMPTY, pollIntervalMs: intervalMs };+ let stopped = false, pollTimer, opTimer, heartbeat, linking = false;+ // The poll in flight, so close() can wait for it instead of leaving a write racing the exit.+ let polling = null;+ 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; }+ const url = new URL(req.url, `http://${req.headers.host}`);+ if (req.headers.origin && req.headers.origin !== url.origin) { json(res, 403, { error: 'Cross-origin requests are not allowed.' }); return; }+ // The one write: a remote password, on its way to `harness link connect` and nowhere else.+ if (req.method === 'POST' && url.pathname === '/api/link') {+ if (linking) { json(res, 409, { error: 'One link at a time.' }); return; }+ let body = '';+ for await (const chunk of req) {+ body += chunk;+ if (body.length > 4096) { json(res, 413, { error: 'Too large.' }); return; }+ }+ let request = {};+ try { request = JSON.parse(body || '{}'); } catch { json(res, 400, { error: 'Send JSON.' }); return; }+ const machineId = String(request.machineId ?? '');+ const password = typeof request.password === 'string' ? request.password : '';+ const machine = snapshot.machines.find(row => row.id === machineId);+ if (!machine) { json(res, 404, { error: 'That machine is not on this account.' }); return; }+ if (!password.trim()) { json(res, 400, { error: 'Enter the remote password set on that machine.' }); return; }+ linking = true;+ try {+ const result = await linkMachine(machineId, password, { displayName: machine.name });+ await recordOperation(workspace, {+ kind: 'link', machineId, machine: machine.name, ok: result.ok,+ detail: result.ok ? `Linked ${machine.name} from the pane` : `Link refused: ${result.error}`,+ });+ if (!result.ok) { json(res, 400, { error: result.error }); return; }+ json(res, 200, { ok: true });+ clearTimeout(pollTimer);+ polling = poll();+ } finally { linking = false; }+ return;+ }+ if (!['GET', 'HEAD'].includes(req.method)) {+ res.setHeader('allow', 'GET, HEAD, POST');+ json(res, 405, { error: 'This pane is read-only. Ask the Machines agent to change something.' });+ 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 pane could not serve this request.' }); else res.end();+ }+ });++ async function poll() {+ try {+ const observed = await collect();+ // A poll that lands after close() has nothing to publish: the workspace may already be gone,+ // and a write from a viewer that is shutting down is a file nobody asked for.+ if (stopped) return;+ snapshot = { ...observed, operations: snapshot.operations ?? [] };+ // The agent reads this file instead of polling Harness a second time; the header reads the verdict.+ await atomicJson(join(stateDir(workspace), 'snapshot.json'), snapshot).catch(() => {});+ await writeVerdict(workspace, snapshot).catch(() => {});+ } catch (error) {+ if (stopped) return;+ snapshot = {+ ...snapshot, status: 'unavailable',+ message: 'The fleet could not be read. Ask the agent to check that Harness is running on this computer.',+ machines: snapshot.machines.map(machine => ({ ...machine, stale: true })),+ sources: { ...snapshot.sources, collector: { ok: false, error: String(error?.message || error).slice(0, 200) } },+ };+ await writeVerdict(workspace, snapshot).catch(() => {});+ }+ if (stopped) return;+ publish();+ pollTimer = setTimeout(() => { polling = 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);+ polling = 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);+ await polling?.catch(() => {});+ 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(`[machines] 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/machines/viewer.sh b/store/agents/machines/viewer.shnew file mode 100755index 000000000..e9a5146c0--- /dev/null+++ b/store/agents/machines/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.mjsdiff --git a/store/agents/machines/viewer/app.css b/store/agents/machines/viewer/app.cssnew file mode 100644index 000000000..14f795995--- /dev/null+++ b/store/agents/machines/viewer/app.css@@ -0,0 +1,252 @@+/* The Machines pane.+ Light is the default palette; the two blocks under it redefine the same tokens for dark — the+ contract every DSH viewer in this store keeps (store/agents/autonomous-grid/viewer/app.css), so+ the page follows the appearance the app is in (data-theme on the root) or the system's when the+ app has not said. Every colour below this block is one of these tokens. */+:root {+ color-scheme: light;+ --bg: #ffffff;+ --panel: #f8f8f7; /* menus, the segmented track */+ --card: #f3f3f1; /* filled chips */+ --overlay-hover: rgba(0, 0, 0, .05);+ --overlay-selected: rgba(0, 0, 0, .08);+ --overlay-border: rgba(0, 0, 0, .10);+ --line: rgba(0, 0, 0, .08);+ --ink: #17181a;+ --ink-2: #585b61;+ --ink-3: #8a8d93;+ --accent: #2b5fd9; /* this computer, its links, the thing you picked */+ --accent-soft: rgba(43, 95, 217, .12);+ --live: #1f8a5f; /* a machine that is up, a harness that is working */+ --warn: #a8730f; /* a machine that needs linking before it can be read */+ --off: #b8402f;+ /* Engines, by hue. Length and glow say "working"; hue says who is doing it. */+ --engine-claude: #c2703d;+ --engine-codex: #4a72b8;+ --engine-third: #7a5ba6;+ --engine-other: #8a8d93;+ --node-bg-1: #fdfdfc; --node-bg-2: #f2f2f0; --node-border: #e3e2de; --node-border-hover: #c9cdd6;+ --selected-ring: rgba(0, 0, 0, .34); --selected-glow: rgba(0, 0, 0, .07);+ --local-border: #b9c8ef; --local-glow: rgba(43, 95, 217, .10);+ --sky-1: rgba(43, 95, 217, .05); --sky-2: rgba(31, 138, 95, .04);+ --shadow-card: 0 6px 16px rgba(0, 0, 0, .07);+ --shadow-menu: 0 14px 34px rgba(0, 0, 0, .14), 0 2px 6px rgba(0, 0, 0, .06);+ --toast-bg: #1d1f22; --toast-border: #3a3d42; --toast-ink: #eceef1;+ font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ font-size: 14px;+ background: var(--bg);+ color: var(--ink);+}+@media (prefers-color-scheme: dark) {+ :root:not([data-theme="light"]) {+ color-scheme: dark;+ --bg: #0a0c0f; --panel: #151a20; --card: #171d24;+ --overlay-hover: #ffffff0d; --overlay-selected: #ffffff14; --overlay-border: #ffffff12; --line: #ffffff0d;+ --ink: #e8eaed; --ink-2: #8b939e; --ink-3: #6c7580;+ --accent: #82aaff; --accent-soft: rgba(130, 170, 255, .14);+ --live: #78bb98; --warn: #d9ab5c; --off: #e98576;+ --engine-claude: #e0955f; --engine-codex: #8fb1e8; --engine-third: #b193d6; --engine-other: #7f8893;+ --node-bg-1: #191f26; --node-bg-2: #11161c; --node-border: #2f353d; --node-border-hover: #454d58;+ --selected-ring: rgba(255, 255, 255, .38); --selected-glow: rgba(255, 255, 255, .08);+ --local-border: #3c5580; --local-glow: rgba(130, 170, 255, .12);+ --sky-1: rgba(130, 170, 255, .06); --sky-2: rgba(120, 187, 152, .04);+ --shadow-card: 0 8px 24px rgba(0, 0, 0, .35);+ --shadow-menu: 0 10px 30px #0009, 0 2px 6px #0006;+ --toast-bg: #1b2026; --toast-border: #333a43; --toast-ink: #e2e6ea;+ }+}+:root[data-theme="dark"] {+ color-scheme: dark;+ --bg: #0a0c0f; --panel: #151a20; --card: #171d24;+ --overlay-hover: #ffffff0d; --overlay-selected: #ffffff14; --overlay-border: #ffffff12; --line: #ffffff0d;+ --ink: #e8eaed; --ink-2: #8b939e; --ink-3: #6c7580;+ --accent: #82aaff; --accent-soft: rgba(130, 170, 255, .14);+ --live: #78bb98; --warn: #d9ab5c; --off: #e98576;+ --engine-claude: #e0955f; --engine-codex: #8fb1e8; --engine-third: #b193d6; --engine-other: #7f8893;+ --node-bg-1: #191f26; --node-bg-2: #11161c; --node-border: #2f353d; --node-border-hover: #454d58;+ --selected-ring: rgba(255, 255, 255, .38); --selected-glow: rgba(255, 255, 255, .08);+ --local-border: #3c5580; --local-glow: rgba(130, 170, 255, .12);+ --sky-1: rgba(130, 170, 255, .06); --sky-2: rgba(120, 187, 152, .04);+ --shadow-card: 0 8px 24px rgba(0, 0, 0, .35);+ --shadow-menu: 0 10px 30px #0009, 0 2px 6px #0006;+ --toast-bg: #1b2026; --toast-border: #333a43; --toast-ink: #e2e6ea;+}++* { box-sizing: border-box }+html, body { height: 100%; margin: 0; overflow: hidden }+button, select, input { font: inherit }+button { cursor: pointer; color: inherit; background: transparent; border: 0 }+button:disabled { cursor: default; opacity: .5 }+button:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px }+[hidden] { display: none !important }+h1, h2, h3, p { margin: 0 }+#app { height: 100%; display: flex; flex-direction: column; overflow: hidden; min-width: 320px }+.workspace { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) 306px }+.main-column { min-width: 0; min-height: 0; display: flex; flex-direction: column }+.scrolls { overflow-y: auto; scrollbar-width: none }+.scrolls::-webkit-scrollbar { display: none }+.quiet { color: var(--ink-3); font-size: 12px; padding: 6px 0 }++/* ── toolbar ─────────────────────────────────────────────────────────────── */+.view-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 24px 2px }+.segmented { display: flex; gap: 4px; background: var(--panel); padding: 3px; border-radius: 7px }+.segmented button { border-radius: 5px; padding: 6px 13px; font-size: 12px; color: var(--ink-2) }+.segmented button[aria-pressed=true] { background: var(--overlay-selected); color: var(--ink); box-shadow: 0 1px 3px rgba(0,0,0,.08) }+.toolbar-selects { display: flex; align-items: center; gap: 8px }+.ghost { border: 1px solid transparent; border-radius: 6px; padding: 5px 9px; font-size: 12px; color: var(--ink-2) }+.ghost:hover { background: var(--overlay-hover); border-color: var(--overlay-border) }+.menu { position: relative }+.menu-button { display: flex; align-items: center; gap: 7px; border: 1px solid transparent; border-radius: 6px; padding: 5px 9px; font-size: 12px; color: var(--ink-2) }+.menu-button:hover, .menu-button[aria-expanded=true] { background: var(--overlay-hover); border-color: var(--overlay-border) }+.menu-kicker { font-size: 11px; color: var(--ink-2) }+.menu-value { color: var(--ink) }+.menu-chevron { font-size: 9px; color: var(--ink-2) }+.menu-list { position: absolute; top: calc(100% + 6px); right: 0; z-index: 20; min-width: 170px; padding: 6px 0; background: var(--panel);+ border: 1px solid var(--overlay-border); border-radius: 8px; box-shadow: var(--shadow-menu) }+.menu-row { display: flex; width: calc(100% - 12px); margin: 0 6px; padding: 5px 8px; border-radius: 5px; text-align: left; font-size: 12.5px; color: var(--ink) }+.menu-row:hover { background: var(--overlay-hover) }+.menu-row[aria-selected=true] { background: var(--overlay-selected) }++/* ── the stage ───────────────────────────────────────────────────────────── */+.stage { flex: 1; min-height: 0; position: relative; isolation: isolate; overflow: hidden;+ background: radial-gradient(ellipse at 50% 46%, var(--sky-1), transparent 52%), radial-gradient(ellipse at 96% 60%, var(--sky-2), transparent 55%) }+#links { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none }+.stage-heading { position: absolute; left: 24px; top: 12px; display: flex; flex-direction: column; gap: 4px; pointer-events: none }+.eyebrow { font-size: 10px; letter-spacing: 1.7px; font-weight: 500; color: var(--ink-2) }+.stage-subtitle { font-size: 12px; color: var(--ink-3) }+.node-layer { position: absolute; inset: 0; pointer-events: none }+.stage-foot { position: absolute; left: 24px; bottom: 10px; font-size: 11px; color: var(--ink-3); pointer-events: none }+.stage-empty { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; text-align: center; padding: 24px }+.stage-empty h1 { font-size: 19px; font-weight: 600 }+.stage-empty p { font-size: 13px; color: var(--ink-2); max-width: 32ch }+.empty-mark { font-size: 30px; color: var(--ink-3) }++/* a machine */+.node { position: absolute; pointer-events: auto; display: flex; flex-direction: column; align-items: center; gap: 7px;+ padding: 6px; border-radius: 14px; transform: translate(-50%, -50%); width: 168px; text-align: center }+.node:hover { background: var(--overlay-hover) }+/* Picked is a ring, not a filled tile: the fills on this stage all mean something about the+ machine, and a click should not repaint one of them. */+.node[aria-pressed=true] { background: transparent }+.node[aria-pressed=true] .orb::before { border-color: var(--selected-ring); box-shadow: 0 0 0 4px var(--selected-glow) }+.orb { position: relative; width: 132px; height: 132px; display: grid; place-items: center }+.orb::before { content: ""; position: absolute; inset: 22px; border-radius: 50%;+ background: linear-gradient(160deg, var(--node-bg-1), var(--node-bg-2)); border: 1px solid var(--node-border) }+.node:hover .orb::before { border-color: var(--node-border-hover) }+.node.local .orb::before { border-color: var(--local-border); box-shadow: 0 0 0 5px var(--local-glow) }+.node.offline .orb::before { border-style: dashed }+.node.offline .corona, .node.offline .core { opacity: .45 }+.corona { position: absolute; inset: 0; width: 132px; height: 132px; overflow: visible }+.corona line { stroke-linecap: round; transform-origin: center }+.corona line.dormant { opacity: .38 }+.corona line.open { opacity: .95; animation: breathe 3.4s ease-in-out infinite }+.paused .corona line.open { animation: none }+@keyframes breathe { 0%, 100% { opacity: .55 } 50% { opacity: 1 } }+@media (prefers-reduced-motion: reduce) { .corona line.open { animation: none } }+.corona circle.dashed { fill: none; stroke: var(--node-border); stroke-dasharray: 3 5 }+.core { position: relative; display: flex; flex-direction: column; align-items: center; line-height: 1.05 }+.core strong { font-size: 25px; font-weight: 600; font-variant-numeric: tabular-nums }+.core small { font-size: 9.5px; letter-spacing: .9px; text-transform: uppercase; color: var(--ink-3); margin-top: 3px }+.core.blank strong { font-size: 15px; font-weight: 500; color: var(--ink-3) }+.node-name { font-size: 13px; font-weight: 550; display: flex; align-items: center; gap: 6px; max-width: 100% }+.node-name .label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis }+.node-sub { font-size: 11px; color: var(--ink-3); max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis }+.dot { width: 6px; height: 6px; border-radius: 50%; background: var(--live); box-shadow: 0 0 8px var(--live); flex: none }+.dot.offline { background: var(--off); box-shadow: none }+.dot.warn { background: var(--warn); box-shadow: none }+.dot.unknown { background: var(--ink-3); box-shadow: none }++/* ── the boards (projects, activity) ─────────────────────────────────────── */+.board { flex: 1; min-height: 0; padding: 8px 24px 16px }+.board-note { font-size: 11.5px; color: var(--ink-3); padding: 2px 0 10px }+.loom { width: 100%; display: block }+.loom .thread { fill: none; stroke: var(--line); stroke-width: 1.5 }+.loom .thread.open { stroke: var(--accent); opacity: .55 }+.loom .thread.dim { opacity: .12 }+.loom text { font-size: 11.5px; fill: var(--ink-2) }+.loom text.title { font-size: 12.5px; fill: var(--ink) }+.loom text.faint { fill: var(--ink-3); font-size: 10.5px }+.loom .row:hover text.title { fill: var(--accent) }+.loom .knot { fill: var(--ink-3) }+.loom .knot.open { fill: var(--live) }++.lane { display: grid; grid-template-columns: 132px minmax(0, 1fr); gap: 12px; align-items: end; padding: 9px 0; border-top: 1px solid var(--line) }+.lane:first-of-type { border-top: 0 }+.lane-label { min-width: 0 }+.lane-label b { display: block; font-size: 12.5px; font-weight: 550; white-space: nowrap; overflow: hidden; text-overflow: ellipsis }+.lane-label span { font-size: 10.5px; color: var(--ink-3) }+.track { position: relative; min-height: 18px }+.track .grid-line { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--line) }+.track .block { position: absolute; height: 5px; border-radius: 1.5px; opacity: .42 }+.track .block.open { opacity: 1 }+.track .more { position: absolute; font-size: 9px; line-height: 6px; color: var(--ink-3) }+.axis { position: relative; height: 16px; font-size: 10px; color: var(--ink-3); margin-left: 144px }+.axis span { position: absolute; top: 0; transform: translateX(-50%); white-space: nowrap }+.axis .now-label { left: auto; right: 0; transform: none }++/* ── totals + log ────────────────────────────────────────────────────────── */+.totals { display: flex; gap: 26px; padding: 12px 24px; border-top: 1px solid var(--line) }+.totals div { display: flex; flex-direction: column; gap: 2px }+.totals strong { font-size: 19px; font-weight: 600; font-variant-numeric: tabular-nums }+.totals .total-label { font-size: 9.5px; letter-spacing: 1.1px; color: var(--ink-3) }+.totals small { font-size: 11px; color: var(--ink-3) }+.log { border-top: 1px solid var(--line); padding: 10px 24px 14px; max-height: 148px; overflow-y: auto; scrollbar-width: none }+.log::-webkit-scrollbar { display: none }+.section-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; padding-bottom: 6px }+.section-heading h2 { font-size: 12px; font-weight: 600 }+.section-heading span { font-size: 11px; color: var(--ink-3) }+.entry { display: flex; gap: 10px; align-items: baseline; padding: 3px 0; font-size: 12px }+.entry time { color: var(--ink-3); font-size: 11px; font-variant-numeric: tabular-nums; flex: none }+.entry.failed { color: var(--off) }++/* ── inspector ───────────────────────────────────────────────────────────── */+.inspector { border-left: 1px solid var(--line); padding: 16px 18px 24px; background: var(--bg) }+.inspector-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; padding-bottom: 12px }+.inspector-head h2 { font-size: 17px; font-weight: 600; line-height: 1.25 }+.subline { font-size: 12px; color: var(--ink-2); margin-top: 4px }+.close { font-size: 17px; color: var(--ink-3); line-height: 1; padding: 2px 6px; border-radius: 5px }+.close:hover { background: var(--overlay-hover) }+.detail-status { display: flex; align-items: center; gap: 7px; font-size: 12px; color: var(--ink-2); padding-bottom: 10px }+.section { border-top: 1px solid var(--line); padding: 12px 0 }+.section h3 { font-size: 10px; letter-spacing: 1.1px; text-transform: uppercase; color: var(--ink-3); font-weight: 600; padding-bottom: 8px }+.pair { display: flex; justify-content: space-between; gap: 12px; font-size: 12px; padding: 3px 0 }+.pair span { color: var(--ink-3) }+.pair strong { font-weight: 500; text-align: right; word-break: break-word }+.project-block { padding: 6px 0 }+.project-block b { font-size: 12.5px; font-weight: 550 }+.project-block .branch { font-size: 11px; color: var(--ink-3); margin-left: 6px }+.harness-row { display: flex; gap: 8px; align-items: baseline; font-size: 12px; padding: 3px 0 3px 2px; color: var(--ink-2) }+.harness-row .mark { font-size: 9px; flex: none }+.harness-row .mark.open { color: var(--live) }+.harness-row .mark.dormant { color: var(--ink-3) }+.harness-row .what { color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap }+.harness-row .when { margin-left: auto; color: var(--ink-3); font-size: 11px; flex: none }+.chip { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--ink-2); background: var(--card);+ border-radius: 999px; padding: 3px 9px; margin: 0 5px 5px 0 }+.swatch { width: 7px; height: 7px; border-radius: 2px; flex: none }+.ask { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 12px }+.ask span { font-size: 9.5px; letter-spacing: 1.1px; color: var(--ink-3) }+.ask p { font-size: 12.5px; color: var(--ink); padding: 6px 0 8px; line-height: 1.4 }+.ask button { font-size: 11.5px; color: var(--accent); border: 1px solid var(--overlay-border); border-radius: 6px; padding: 4px 9px }+.ask button:hover { background: var(--accent-soft) }+.link-form { display: flex; flex-direction: column; gap: 8px; padding-top: 4px }+.link-form input { background: var(--card); border: 1px solid var(--overlay-border); border-radius: 6px; padding: 7px 9px; font-size: 12.5px; color: var(--ink) }+.link-form .row { display: flex; gap: 8px; align-items: center }+.link-form button { background: var(--accent); color: #fff; border-radius: 6px; padding: 6px 12px; font-size: 12px; font-weight: 500 }+:root[data-theme="dark"] .link-form button, :root:not([data-theme="light"]) .link-form button { color: #0a0c0f }+@media (prefers-color-scheme: light) { :root:not([data-theme="dark"]) .link-form button { color: #fff } }+.link-form .why { font-size: 11px; color: var(--ink-3); line-height: 1.45 }+.link-form .error { font-size: 11.5px; color: var(--off) }++.toast { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); background: var(--toast-bg); color: var(--toast-ink);+ border: 1px solid var(--toast-border); border-radius: 8px; padding: 8px 14px; font-size: 12px; box-shadow: var(--shadow-menu); z-index: 40 }++/* A narrow pane: the inspector becomes a drawer over the stage. */+@media (max-width: 860px) {+ .workspace { grid-template-columns: minmax(0, 1fr) }+ .inspector { position: absolute; top: 0; right: 0; bottom: 0; width: min(320px, 86vw); transform: translateX(100%);+ transition: transform .18s ease; box-shadow: var(--shadow-menu); z-index: 30 }+ .inspector.open { transform: none }+ .lane { grid-template-columns: 96px minmax(0, 1fr) }+ .axis { margin-left: 108px }+}diff --git a/store/agents/machines/viewer/app.js b/store/agents/machines/viewer/app.jsnew file mode 100644index 000000000..e4ad40ed7--- /dev/null+++ b/store/agents/machines/viewer/app.js@@ -0,0 +1,670 @@+(() => {+ 'use strict';++ const $ = id => document.getElementById(id);+ const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+ const clamp = (value, low, high) => Math.min(high, Math.max(low, value));++ function ago(time) {+ const at = Date.parse(time);+ if (!Number.isFinite(at)) return '';+ const seconds = Math.max(0, (Date.now() - at) / 1000);+ if (seconds < 90) return `${Math.round(seconds)}s ago`;+ if (seconds < 5400) return `${Math.round(seconds / 60)}m ago`;+ if (seconds < 172800) return `${Math.round(seconds / 3600)}h ago`;+ return `${Math.round(seconds / 86400)}d ago`;+ }+ const clock = time => (time ? new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '');+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;++ // Hue says who is working; length and glow say whether it is working now.+ const ENGINE_VARS = { claude: '--engine-claude', codex: '--engine-codex', opencode: '--engine-third', gemini: '--engine-third' };+ const engineVar = engine => ENGINE_VARS[String(engine || '').toLowerCase()] ?? '--engine-other';+ const engineColor = engine => `var(${engineVar(engine)})`;++ const WINDOWS = [+ { id: 'day', label: '24 hours', ms: 24 * 3600e3 },+ { id: 'week', label: '7 days', ms: 7 * 24 * 3600e3 },+ { id: 'month', label: '30 days', ms: 30 * 24 * 3600e3 },+ ];+ /** How many ticks one machine draws. Past this the counts stay true and the corona stops thickening. */+ const TICK_CAP = 120;++ 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 { /* private window */ } },+ };++ let snapshot = null, view = 'fleet', selected = null, windowId = storage.read('machines:window') || 'week';+ let paused = matchMedia('(prefers-reduced-motion: reduce)').matches;+ let positions = new Map(), drags = storage.read('machines:layout') || {}, dragging = null, moved = false;+ let width = 0, height = 0, frame = 0, lastReceived = 0, transportLost = false, toastTimer;+ const stage = $('stage'), canvas = $('links'), ctx = canvas.getContext('2d');+ const nodeButtons = new Map();++ function toast(message) {+ $('toast').textContent = message;+ $('toast').hidden = false;+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => { $('toast').hidden = true; }, 4000);+ }++ /* ── the stream ───────────────────────────────────────────────────────── */++ function consume(data) {+ if (!data || data.spec !== 1 || !Array.isArray(data.machines)) return;+ snapshot = data;+ lastReceived = Date.now();+ transportLost = false;+ render();+ }++ function listen() {+ const source = new EventSource('/events');+ source.addEventListener('snapshot', event => { try { consume(JSON.parse(event.data)); } catch { /* a partial frame */ } });+ source.addEventListener('error', () => { transportLost = true; status(); });+ }++ function status() {+ if (!snapshot) return;+ const late = lastReceived && Date.now() - lastReceived > Math.max(45_000, (snapshot.pollIntervalMs || 15_000) * 3);+ const linkable = (snapshot.machines ?? []).filter(machine => machine.needsLink && machine.status !== 'offline').length;+ const waiting = linkable ? ` · ${plural(linkable, 'machine')} waiting to be linked` : '';+ const words = {+ live: snapshot.observedAt ? `Observed ${ago(snapshot.observedAt)}${waiting}` : 'Observing',+ partial: snapshot.observedAt ? `Observed ${ago(snapshot.observedAt)} · a machine did not answer${waiting}` : 'A machine did not answer',+ connecting: 'Asking Harness about your machines',+ unavailable: 'Harness is not answering on this computer',+ 'signed-out': 'Not signed in to Harness on this computer',+ };+ $('observed').textContent = transportLost || late ? 'The pane lost its connection to the fleet reader' : (words[snapshot.status] ?? 'Waiting for Harness');+ }++ /* ── render ───────────────────────────────────────────────────────────── */++ function render() {+ if (!snapshot) return;+ $('stage').hidden = view !== 'fleet';+ $('projects').hidden = view !== 'projects';+ $('activity').hidden = view !== 'activity';+ $('window-menu').hidden = view !== 'activity';+ for (const [id, name] of [['view-fleet', 'fleet'], ['view-projects', 'projects'], ['view-activity', 'activity']]) {+ $(id).setAttribute('aria-pressed', String(view === name));+ }+ if (view === 'fleet') renderFleet();+ if (view === 'projects') renderProjects();+ if (view === 'activity') renderActivity();+ renderTotals();+ renderLog();+ renderInspector();+ status();+ }++ function select(kind, id) {+ const same = selected && selected.kind === kind && selected.id === id;+ selected = same ? null : { kind, id };+ for (const [machineId, button] of nodeButtons) button.setAttribute('aria-pressed', String(selected?.kind === 'machine' && selected.id === machineId));+ renderInspector();+ if (view === 'projects') renderProjects();+ draw();+ }++ /* ── fleet: a machine and the harnesses it carries ────────────────────── */++ /** Harnesses to draw: every open one, then the newest, up to what one ring can hold. */+ function visibleHarnesses(machine) {+ const all = [...(machine.harnesses ?? [])];+ if (all.length <= TICK_CAP) return all;+ const open = all.filter(h => h.open);+ const rest = all.filter(h => !h.open).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));+ return [...open, ...rest].slice(0, TICK_CAP);+ }++ /** Harnesses grouped into the projects they are in — the arcs the corona reads as clusters. */+ function groupByProject(harnesses) {+ const groups = new Map();+ for (const harness of harnesses) {+ const key = harness.project?.key ?? 'none';+ const found = groups.get(key) ?? { key, name: harness.project?.name ?? 'No project', branch: harness.project?.branch ?? null, harnesses: [] };+ found.harnesses.push(harness);+ groups.set(key, found);+ }+ return [...groups.values()].sort((a, b) => b.harnesses.length - a.harnesses.length);+ }++ /**+ * The corona: one tick per harness, laid around the machine and broken into an arc per project.+ * An open harness is a long tick that breathes; a dormant one is a short faint mark. Nothing is drawn+ * for a machine that could not be read — an empty ring means "not read", never "nothing running".+ */+ function corona(machine) {+ const inner = 46;+ if (machine.needsLink || machine.status === 'offline' || !machine.harnesses?.length) {+ return `<svg class="corona" viewBox="-66 -66 132 132" aria-hidden="true"><circle class="dashed" r="${inner + 4}"></circle></svg>`;+ }+ const harnesses = visibleHarnesses(machine);+ const groups = groupByProject(harnesses);+ const gap = groups.length > 1 ? Math.min(7, 60 / groups.length) : 0;+ const per = (360 - gap * groups.length) / harnesses.length;+ let angle = -90 + gap / 2;+ const lines = [];+ for (const group of groups) {+ for (const harness of group.harnesses) {+ const radians = angle * Math.PI / 180;+ const length = harness.open ? 11 : 6;+ const x1 = Math.cos(radians) * inner, y1 = Math.sin(radians) * inner;+ const x2 = Math.cos(radians) * (inner + length), y2 = Math.sin(radians) * (inner + length);+ const title = [harness.name, group.name === 'No project' ? null : group.name, harness.agent,+ harness.createdAt ? `started ${ago(harness.createdAt)}` : null, harness.open ? 'open' : 'closed'].filter(Boolean).join(' · ');+ lines.push(`<line class="${harness.open ? 'open' : 'dormant'}" x1="${x1.toFixed(1)}" y1="${y1.toFixed(1)}" x2="${x2.toFixed(1)}" y2="${y2.toFixed(1)}" stroke="${engineColor(harness.engine)}" stroke-width="${harness.open ? 2.4 : 1.8}" style="animation-delay:${(lines.length % 12) * 0.2}s"><title>${escape(title)}</title></line>`);+ angle += per;+ }+ angle += gap;+ }+ return `<svg class="corona" viewBox="-66 -66 132 132">${lines.join('')}</svg>`;+ }++ function coreOf(machine) {+ if (machine.needsLink) return '<span class="core blank"><strong>Link</strong><small>required</small></span>';+ if (machine.shared) return `<span class="core blank"><strong>${machine.harnessCount || 0}</strong><small>shared</small></span>`;+ if (machine.status === 'offline') return '<span class="core blank"><strong>—</strong><small>offline</small></span>';+ return `<span class="core"><strong>${machine.openCount ?? 0}</strong><small>open</small></span>`;+ }++ /**+ * Presence and link state are independent, and both are said — the split the app's own machine+ * menu makes. A computer that is up but has never been linked reads "online · link required",+ * because "link required" alone hides that the machine itself is perfectly fine.+ */+ function stateWord(machine) {+ if (machine.local) return 'this computer';+ if (machine.shared) return machine.ownerName ? `shared by ${machine.ownerName}` : 'shared with you';+ const presence = machine.status === 'offline' ? 'offline' : machine.status === 'unknown' ? 'status unknown' : 'online';+ return machine.needsLink ? `${presence} · link required` : presence;+ }++ function dotClass(machine) {+ if (machine.needsLink) return 'warn';+ if (machine.status === 'offline') return 'offline';+ if (machine.status === 'unknown') return 'unknown';+ return '';+ }++ /**+ * Where each machine sits before anyone drags it: this computer at the middle, the rest around it.+ *+ * The ring order is by machine id, not by the order the list happens to be sorted in — a machine+ * that goes offline (or comes back) changes that sort, and a map whose nodes swap places whenever+ * a status changes is a map nobody can hold in their head.+ */+ function layout(machines) {+ const places = new Map();+ const local = machines.find(m => m.local);+ const others = machines.filter(m => m !== local).sort((a, b) => a.id.localeCompare(b.id));+ if (local) places.set(local.id, { x: .5, y: .48 });+ const count = others.length;+ if (!count) return places;+ if (!local && count <= 3) {+ others.forEach((machine, index) => places.set(machine.id, { x: (index + 1) / (count + 1), y: .48 }));+ return places;+ }+ const radius = count <= 4 ? .3 : count <= 8 ? .34 : .38;+ others.forEach((machine, index) => {+ const angle = -Math.PI / 2 + (index + (local ? 0 : .5)) * (2 * Math.PI / count);+ places.set(machine.id, { x: .5 + Math.cos(angle) * radius * (height / Math.max(width, 1) < .7 ? 1 : .8), y: .48 + Math.sin(angle) * radius });+ });+ return places;+ }++ function place() {+ const box = stage.getBoundingClientRect();+ width = box.width; height = box.height;+ const machines = snapshot?.machines ?? [];+ const defaults = layout(machines);+ positions = new Map();+ for (const machine of machines) {+ const saved = drags[machine.id], base = defaults.get(machine.id) ?? { x: .5, y: .5 };+ const point = saved && Number.isFinite(saved.x) ? saved : base;+ positions.set(machine.id, { x: clamp(point.x, .1, .9) * width, y: clamp(point.y, .16, .86) * height });+ }+ for (const [id, button] of nodeButtons) {+ const point = positions.get(id);+ if (point) { button.style.left = `${point.x}px`; button.style.top = `${point.y}px`; }+ }+ }++ function renderFleet() {+ const machines = snapshot.machines ?? [];+ const ids = new Set(machines.map(m => m.id));+ for (const [id, button] of nodeButtons) if (!ids.has(id)) { button.remove(); nodeButtons.delete(id); }++ for (const machine of machines) {+ let button = nodeButtons.get(machine.id);+ if (!button) {+ button = document.createElement('button');+ button.type = 'button';+ button.dataset.machine = machine.id;+ button.addEventListener('click', () => { if (moved) { moved = false; return; } select('machine', machine.id); });+ button.addEventListener('pointerdown', event => {+ if (event.button !== 0) return;+ dragging = { id: machine.id, x: event.clientX, y: event.clientY };+ moved = false;+ button.setPointerCapture?.(event.pointerId);+ });+ button.addEventListener('pointermove', event => {+ if (dragging?.id !== machine.id) return;+ if (Math.hypot(event.clientX - dragging.x, event.clientY - dragging.y) > 5) moved = true;+ if (!moved) return;+ const box = stage.getBoundingClientRect();+ drags[machine.id] = { x: (event.clientX - box.left) / width, y: (event.clientY - box.top) / height };+ place(); draw();+ });+ button.addEventListener('pointerup', () => { dragging = null; if (moved) storage.write('machines:layout', drags); });+ button.addEventListener('pointercancel', () => { dragging = null; moved = false; });+ $('nodes').appendChild(button);+ nodeButtons.set(machine.id, button);+ }+ button.className = `node${machine.local ? ' local' : ''}${machine.status === 'offline' || machine.needsLink ? ' offline' : ''}${paused ? ' paused' : ''}`;+ button.setAttribute('aria-pressed', String(selected?.kind === 'machine' && selected.id === machine.id));+ const carrying = machine.needsLink ? 'nothing readable yet'+ : machine.harnessCount ? plural(machine.harnessCount, 'harness', 'harnesses') : 'no harness open';+ button.setAttribute('aria-label', `${machine.name}, ${stateWord(machine)}, ${carrying}`);+ button.innerHTML = `<span class="orb">${corona(machine)}${coreOf(machine)}</span>`+ + `<span class="node-name"><span class="dot ${dotClass(machine)}"></span><span class="label">${escape(machine.name)}</span></span>`+ + `<span class="node-sub">${escape(machine.needsLink ? stateWord(machine) : `${stateWord(machine)} · ${carrying}`)}</span>`;+ }++ $('stage-empty').hidden = machines.length > 0;+ if (!machines.length) {+ $('empty-title').textContent = snapshot.status === 'signed-out' ? 'Not signed in.' : 'No machines yet.';+ $('empty-message').textContent = snapshot.status === 'signed-out'+ ? 'Sign in to Harness on this computer and your machines appear here.'+ : snapshot.message || 'Ask me to bring your first computer in.';+ }+ const readable = machines.filter(m => !m.needsLink && m.status !== 'offline').length;+ $('stage-subtitle').textContent = machines.length+ ? `${plural(machines.length, 'machine')} · ${readable} readable from here`+ : 'Looking for your computers.';+ $('stage-legend').textContent = machines.some(m => !m.local)+ ? 'Lines are this computer’s links · each tick is one harness, grouped by project'+ : 'Each tick is one harness, grouped by project';+ place();+ draw();+ }++ /** The links out of this computer: solid where one exists, dashed where one is still needed. */+ function draw() {+ const ratio = Math.min(2, window.devicePixelRatio || 1);+ const pixels = [Math.max(1, Math.floor(width * ratio)), Math.max(1, Math.floor(height * ratio))];+ // Only on a real size change: assigning width or height reallocates the backing store, and this+ // runs on every animation frame.+ if (canvas.width !== pixels[0] || canvas.height !== pixels[1]) {+ [canvas.width, canvas.height] = pixels;+ }+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);+ ctx.clearRect(0, 0, width, height);+ if (view !== 'fleet' || !snapshot) return;+ const style = getComputedStyle(document.documentElement);+ const accent = style.getPropertyValue('--accent').trim() || '#2b5fd9';+ const line = style.getPropertyValue('--ink-3').trim() || '#8a8d93';+ const warn = style.getPropertyValue('--warn').trim() || '#a8730f';+ const local = snapshot.machines.find(m => m.local);+ const from = local && positions.get(local.id);+ if (!from) return;+ for (const machine of snapshot.machines) {+ if (machine.local) continue;+ const to = positions.get(machine.id);+ if (!to) continue;+ const midX = (from.x + to.x) / 2 + (to.y - from.y) * .07;+ const midY = (from.y + to.y) / 2 - (to.x - from.x) * .07;+ const chosen = selected?.kind === 'machine' && (selected.id === machine.id);+ ctx.save();+ ctx.beginPath();+ ctx.moveTo(from.x, from.y);+ ctx.quadraticCurveTo(midX, midY, to.x, to.y);+ if (machine.needsLink) { ctx.strokeStyle = warn; ctx.globalAlpha = .5; ctx.setLineDash([2, 6]); }+ else if (machine.status === 'offline') { ctx.strokeStyle = line; ctx.globalAlpha = .28; ctx.setLineDash([1, 7]); }+ else { ctx.strokeStyle = accent; ctx.globalAlpha = chosen ? .85 : .45; ctx.setLineDash([7, 7]); ctx.lineDashOffset = paused ? 0 : -frame * .35; }+ ctx.lineWidth = chosen ? 2 : 1.4;+ ctx.stroke();+ ctx.restore();+ }+ }++ function animate() {+ frame += 1;+ if (!paused && view === 'fleet' && snapshot?.machines?.some(m => !m.local && !m.needsLink && m.status !== 'offline')) draw();+ requestAnimationFrame(animate);+ }++ /* ── projects: the same work, seen across machines ────────────────────── */++ function renderProjects() {+ const projects = (snapshot.projects ?? []).slice(0, 24);+ const machines = (snapshot.machines ?? []).filter(m => m.harnessCount > 0);+ if (!projects.length) {+ $('projects').innerHTML = `<p class="board-note">${escape(snapshot.machines?.some(m => m.needsLink)+ ? 'Link a machine and the projects it is working in appear here.'+ : 'No project has a harness open right now.')}</p>`;+ return;+ }+ const rowHeight = 32, padding = 26;+ const rows = Math.max(projects.length, machines.length);+ const height = rows * rowHeight + padding * 2;+ const boardWidth = Math.max(420, $('projects').clientWidth || 640);+ const leftX = 4, rightX = boardWidth - 4;+ const knotLeft = Math.min(300, boardWidth * .42), knotRight = boardWidth - Math.min(190, boardWidth * .28);+ const y = (index, count) => padding + (rows - count) * rowHeight / 2 + index * rowHeight + rowHeight / 2;++ const threads = [];+ projects.forEach((project, index) => {+ const py = y(index, projects.length);+ for (const machineId of project.machines) {+ const machineIndex = machines.findIndex(m => m.id === machineId);+ if (machineIndex < 0) continue;+ const my = y(machineIndex, machines.length);+ const dim = selected?.kind === 'project' && selected.id !== project.key;+ threads.push(`<path class="thread${project.open ? ' open' : ''}${dim ? ' dim' : ''}" d="M ${knotLeft} ${py} C ${(knotLeft + knotRight) / 2} ${py}, ${(knotLeft + knotRight) / 2} ${my}, ${knotRight} ${my}" stroke-width="${clamp(Math.sqrt(project.harnesses) * .9, 1, 5).toFixed(1)}"></path>`);+ }+ });++ const projectRows = projects.map((project, index) => {+ const py = y(index, projects.length);+ const detail = [plural(project.harnesses, 'harness', 'harnesses'), project.open ? `${project.open} open` : null, project.branches.slice(0, 2).join(', ')]+ .filter(Boolean).join(' · ');+ return `<g class="row" data-project="${escape(project.key)}" role="button" tabindex="0">`+ + `<rect x="${leftX}" y="${py - rowHeight / 2}" width="${knotLeft - leftX}" height="${rowHeight}" fill="transparent"></rect>`+ + `<text class="title" x="${leftX + 2}" y="${py - 1}">${escape(project.name)}</text>`+ + `<text class="faint" x="${leftX + 2}" y="${py + 12}">${escape(detail)}</text>`+ + `<circle class="knot${project.open ? ' open' : ''}" cx="${knotLeft}" cy="${py}" r="3"></circle></g>`;+ });++ const machineRows = machines.map((machine, index) => {+ const my = y(index, machines.length);+ return `<g class="row" data-machine="${escape(machine.id)}" role="button" tabindex="0">`+ + `<rect x="${knotRight}" y="${my - rowHeight / 2}" width="${rightX - knotRight}" height="${rowHeight}" fill="transparent"></rect>`+ + `<circle class="knot${machine.openCount ? ' open' : ''}" cx="${knotRight}" cy="${my}" r="3"></circle>`+ + `<text class="title" x="${knotRight + 10}" y="${my - 1}">${escape(machine.name)}</text>`+ + `<text class="faint" x="${knotRight + 10}" y="${my + 12}">${escape(plural(machine.harnessCount, 'harness', 'harnesses'))}</text></g>`;+ });++ const shown = (snapshot.projects ?? []).length;+ $('projects').innerHTML = `<p class="board-note">${escape(shown > projects.length+ ? `The ${projects.length} busiest of ${shown} projects, and the machines each one is open on.`+ : 'Every project with a harness open, and the machines it is open on.')}</p>`+ + `<svg class="loom" viewBox="0 0 ${boardWidth} ${height}" height="${height}">${threads.join('')}${projectRows.join('')}${machineRows.join('')}</svg>`;+ }++ /* ── activity: what the machines have been doing ──────────────────────── */++ /**+ * When the work started.+ *+ * A roster reports one time per harness that means what it says: when it was created. (Its+ * `updatedAt` is stamped by the registry's own reconcile pass, so it would draw every harness as+ * busy right now — this view does not use it, and neither does anything else here.) So each mark+ * below is one harness, stacked into the hour or day it began: a machine's week, as a skyline.+ */+ function renderActivity() {+ const span = (WINDOWS.find(w => w.id === windowId) ?? WINDOWS[1]).ms;+ const now = Date.now(), start = now - span;+ const machines = (snapshot.machines ?? []).filter(m => (m.harnesses ?? []).length);+ if (!machines.length) {+ $('activity').innerHTML = '<p class="board-note">Nothing to show yet: no machine here has a harness this pane can read.</p>';+ return;+ }+ const columns = span <= 24 * 3600e3 ? 48 : span <= 7 * 24 * 3600e3 ? 56 : 60;+ const STACK_CAP = 9;+ // Gridlines fall on real boundaries — midnight, or every six hours in the day view — so a stack+ // can be read against a date instead of an arbitrary slice of the window.+ const hourly = span <= 24 * 3600e3;+ const step = hourly ? 6 * 3600e3 : 86400e3;+ const ticks = [];+ const first = new Date(start);+ if (hourly) first.setMinutes(0, 0, 0);+ else first.setHours(0, 0, 0, 0);+ for (let at = first.getTime() + step; at < now && ticks.length < 12; at += step) {+ ticks.push({ at, left: ((at - start) / span) * 100, label: hourly+ ? new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })+ : new Date(at).toLocaleDateString([], { month: 'short', day: 'numeric' }) });+ }+ const marks = ticks.map(tick => tick.left);++ const lanes = machines.map(machine => {+ const buckets = new Map();+ let before = 0;+ for (const harness of machine.harnesses ?? []) {+ const at = Date.parse(harness.createdAt);+ if (!Number.isFinite(at)) continue;+ if (at < start) { before += 1; continue; }+ const column = Math.min(columns - 1, Math.floor(((at - start) / span) * columns));+ const found = buckets.get(column) ?? [];+ found.push(harness);+ buckets.set(column, found);+ }+ const started = [...buckets.values()].reduce((total, list) => total + list.length, 0);+ const tallest = Math.max(1, ...[...buckets.values()].map(list => Math.min(list.length, STACK_CAP)));+ const trackHeight = tallest * 6 + 8;+ const width = 100 / columns;+ const blocks = [];+ for (const [column, list] of buckets) {+ list.slice(0, STACK_CAP).forEach((harness, index) => {+ const title = [harness.name, harness.project?.name, harness.agent,+ `started ${new Date(harness.createdAt).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}`,+ harness.open ? 'still open' : 'closed'].filter(Boolean).join(' · ');+ blocks.push(`<span class="block${harness.open ? ' open' : ''}" style="left:${(column * width).toFixed(2)}%;width:${Math.max(width - .35, .6).toFixed(2)}%;bottom:${index * 6}px;background:${engineColor(harness.engine)}" title="${escape(title)}"></span>`);+ });+ if (list.length > STACK_CAP) {+ blocks.push(`<span class="more" style="left:${(column * width).toFixed(2)}%;bottom:${STACK_CAP * 6}px" title="${escape(`${list.length - STACK_CAP} more started here`)}">+</span>`);+ }+ }+ const note = started+ ? `${plural(started, 'harness', 'harnesses')} started${before ? ` · ${before} older` : ''}`+ : `nothing started here${before ? ` · ${plural(before, 'older harness', 'older harnesses')}` : ''}`;+ return `<div class="lane"><div class="lane-label"><b>${escape(machine.name)}</b><span>${escape(note)}</span></div>`+ + `<div class="track" style="height:${trackHeight}px">${marks.map(mark => `<span class="grid-line" style="left:${mark}%"></span>`).join('')}${blocks.join('')}</div></div>`;+ });++ $('activity').innerHTML = '<p class="board-note">Each mark is one harness, stacked where it was created. Hue is the agent; a solid mark is a harness still open.</p>'+ + `<div class="axis">${ticks.map(tick => `<span style="left:${tick.left.toFixed(2)}%">${escape(tick.label)}</span>`).join('')}<span class="now-label">now</span></div>`+ + lanes.join('');+ }++ /* ── totals and the log ───────────────────────────────────────────────── */++ function renderTotals() {+ const summary = snapshot.summary ?? {};+ const totals = snapshot.totals;+ const blocks = [+ ['MACHINES', summary.machines ?? 0, `${summary.online ?? 0} online`],+ ['HARNESSES', summary.harnesses ?? 0, summary.open ? `${summary.open} open now` : 'none open'],+ ['PROJECTS', summary.projects ?? 0, 'with a harness open'],+ ];+ if (totals?.workedMs) blocks.push(['THIS COMPUTER', `${Math.round(totals.workedMs / 3600e3)}h`, `agent time since ${new Date(totals.since).toLocaleDateString([], { month: 'short', day: 'numeric' })}`]);+ $('totals').innerHTML = blocks.map(([label, value, note]) =>+ `<div><span class="total-label">${label}</span><strong>${escape(value)}</strong><small>${escape(note)}</small></div>`).join('');+ }++ function renderLog() {+ const entries = snapshot.operations ?? [];+ $('log-list').innerHTML = entries.length+ ? entries.slice(0, 12).map(entry => `<div class="entry${entry.ok === false ? ' failed' : ''}"><time>${escape(clock(entry.at))}</time><span>${escape(entry.detail || entry.kind)}</span></div>`).join('')+ : '<div class="quiet">Nothing has changed here yet. Ask me to link, rename or retire a machine.</div>';+ }++ /* ── inspector ────────────────────────────────────────────────────────── */++ const pair = (label, value) => `<div class="pair"><span>${escape(label)}</span><strong>${escape(value)}</strong></div>`;+ const ask = text => `<div class="ask"><span>ASK THE AGENT</span><p>${escape(text)}</p><button type="button" class="copy" data-text="${escape(text)}">Copy request</button></div>`;++ function harnessList(harnesses) {+ const groups = groupByProject(harnesses);+ if (!groups.length) return '<p class="quiet">Nothing running here.</p>';+ return groups.slice(0, 10).map(group => `<div class="project-block"><b>${escape(group.name)}</b>${group.branch ? `<span class="branch">${escape(group.branch)}</span>` : ''}`+ + group.harnesses.slice(0, 8).map(harness => `<div class="harness-row"><span class="mark ${harness.open ? 'open' : 'dormant'}">${harness.open ? '●' : '○'}</span>`+ + `<span class="what">${escape(harness.title || harness.name)}</span><span class="when">${escape(harness.createdAt ? ago(harness.createdAt) : '')}</span></div>`).join('')+ + (group.harnesses.length > 8 ? `<div class="quiet">and ${group.harnesses.length - 8} more</div>` : '')+ + '</div>').join('');+ }++ function linkForm(machine) {+ return `<div class="section"><h3>Link this machine</h3><form class="link-form" data-link="${escape(machine.id)}">`+ + `<p class="why">Its remote password proves you own it. Type it here — it goes straight to Harness and is never part of the conversation.</p>`+ + `<input type="password" name="password" autocomplete="off" placeholder="Remote password" aria-label="Remote password for ${escape(machine.name)}">`+ + `<div class="row"><button type="submit">Link ${escape(machine.name)}</button><span class="error" data-error></span></div>`+ + `<p class="why">Not set one yet? On that machine: <code>harness remote-password set</code>.</p></form></div>`;+ }++ function renderInspector() {+ const panel = $('inspector');+ const machine = selected?.kind === 'machine' ? snapshot.machines.find(m => m.id === selected.id) : null;+ const project = selected?.kind === 'project' ? snapshot.projects.find(p => p.key === selected.id) : null;+ // What was selected can go away between readings — a machine removed, a project whose last+ // harness closed. Let the selection go with it rather than holding a drawer open on nothing.+ if (selected && !machine && !project) selected = null;+ panel.classList.toggle('open', Boolean(selected));++ if (machine) {+ panel.innerHTML = `<div class="inspector-head"><div><span class="eyebrow">${machine.local ? 'THIS COMPUTER' : 'MACHINE'}</span>`+ + `<h2>${escape(machine.name)}</h2><p class="subline">${escape(machine.hostname || machine.id.slice(0, 12))}</p></div>`+ + '<button class="close" type="button" data-close aria-label="Close">×</button></div>'+ + `<div class="detail-status"><span class="dot ${dotClass(machine)}"></span>${escape(stateWord(machine))}${machine.stale ? ' · last known' : ''}</div>`+ + (machine.needsLink ? linkForm(machine) : '')+ + `<div class="section">${pair('Harnesses', machine.needsLink ? 'not readable from here' : String(machine.harnessCount ?? 0))}`+ + pair('Open now', machine.needsLink ? '—' : String(machine.openCount ?? 0))+ + pair('Projects', machine.needsLink ? '—' : String(machine.projectCount ?? 0))+ + (machine.newestAt ? pair('Newest harness', ago(machine.newestAt)) : '')+ + (machine.linkedAt ? pair('Linked', ago(machine.linkedAt)) : '')+ + (machine.createdAt ? pair('On the account since', new Date(machine.createdAt).toLocaleDateString()) : '')+ + (machine.plan ? pair('Plan', machine.plan) : '')+ + pair('Id', machine.id.slice(0, 12))+ + (machine.note ? pair('Note', machine.note) : '')+ + '</div>'+ + (machine.error ? `<div class="section"><h3>Could not be read</h3><p class="quiet">${escape(machine.error)}</p></div>` : '')+ + (machine.needsLink ? '' : `<div class="section"><h3>What it is carrying</h3>${harnessList(machine.harnesses ?? [])}</div>`)+ + ask(machine.needsLink+ ? `Walk me through linking ${machine.name} from this computer.`+ : machine.local+ ? 'What is this computer working on right now, and is anything stuck?'+ : `What is ${machine.name} working on, and should anything move to another machine?`);+ return;+ }++ if (project) {+ const machines = snapshot.machines.filter(m => project.machines.includes(m.id));+ const harnesses = machines.flatMap(m => (m.harnesses ?? []).filter(h => h.project?.key === project.key));+ panel.innerHTML = '<div class="inspector-head"><div><span class="eyebrow">PROJECT</span>'+ + `<h2>${escape(project.name)}</h2><p class="subline">${escape(project.repo || 'a folder, not a repository')}</p></div>`+ + '<button class="close" type="button" data-close aria-label="Close">×</button></div>'+ + `<div class="section">${pair('Harnesses', String(project.harnesses))}${pair('Open now', String(project.open))}`+ + pair('Machines', machines.map(m => m.name).join(', ') || '—')+ + (project.branches.length ? pair('Branches', project.branches.slice(0, 4).join(', ')) : '')+ + (project.newestAt ? pair('Newest harness', ago(project.newestAt)) : '') + '</div>'+ + `<div class="section"><h3>Harnesses</h3>${harnessList(harnesses)}</div>`+ + ask(`Give me the state of ${project.name} across my machines — what is running where, and what finished.`);+ return;+ }++ const summary = snapshot.summary ?? {};+ const engines = Object.entries(summary.engines ?? {}).sort((a, b) => b[1] - a[1]).slice(0, 6);+ // Only the machines that could actually be linked right now: an offline one is a different job.+ const needsLink = snapshot.machines.filter(m => m.needsLink && m.status !== 'offline');+ panel.innerHTML = '<div class="inspector-head"><div><span class="eyebrow">YOUR FLEET</span>'+ + '<h2>Every computer<br>you work on.</h2>'+ + `<p class="subline">${escape(snapshot.account?.email ? `Signed in as ${snapshot.account.email}` : 'One account, one map.')}</p></div></div>`+ + `<div class="section" style="border-top:0;padding-top:0">${pair('Machines', String(summary.machines ?? 0))}`+ + pair('Online', String(summary.online ?? 0))+ + pair('Harnesses', String(summary.harnesses ?? 0))+ + pair('Open now', String(summary.open ?? 0))+ + (snapshot.thisComputer?.version ? pair('Harness version', `v${snapshot.thisComputer.version}`) : '')+ + (snapshot.thisComputer ? pair('Linkable from elsewhere', snapshot.thisComputer.remotePasswordSet ? 'yes' : 'no password set') : '')+ + '</div>'+ + (engines.length ? `<div class="section"><h3>Agents on your machines</h3>${engines.map(([engine, count]) =>+ `<span class="chip"><span class="swatch" style="background:${engineColor(engine)}"></span>${escape(engine)} · ${count}</span>`).join('')}</div>` : '')+ + (needsLink.length ? `<div class="section"><h3>Waiting to be linked</h3>${needsLink.map(machine =>+ `<div class="harness-row"><span class="mark idle">○</span><span class="what">${escape(machine.name)}</span></div>`).join('')}</div>` : '')+ + ask(needsLink.length+ ? `Link ${needsLink[0].name} so I can see what it is running.`+ : snapshot.machines.length > 1+ ? 'Which of my machines is carrying the most, and what would you move?'+ : 'Help me bring another computer into this account.');+ }++ /* ── events ───────────────────────────────────────────────────────────── */++ document.addEventListener('click', async event => {+ const copy = event.target.closest('.copy');+ if (copy) {+ try { await navigator.clipboard.writeText(copy.dataset.text); toast('Request copied — paste it in the terminal.'); }+ catch { toast('This pane could not reach the clipboard.'); }+ return;+ }+ if (event.target.closest('[data-close]')) { selected = null; renderInspector(); render(); return; }+ const row = event.target.closest('[data-project]');+ if (row) { select('project', row.dataset.project); return; }+ const machineRow = event.target.closest('[data-machine]');+ if (machineRow && !machineRow.classList.contains('node')) { select('machine', machineRow.dataset.machine); }+ });++ document.addEventListener('submit', async event => {+ const form = event.target.closest('[data-link]');+ if (!form) return;+ event.preventDefault();+ const input = form.querySelector('input[name=password]');+ const error = form.querySelector('[data-error]');+ const button = form.querySelector('button');+ error.textContent = '';+ button.disabled = true;+ button.textContent = 'Linking…';+ try {+ const response = await fetch('/api/link', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ machineId: form.dataset.link, password: input.value }),+ });+ const body = await response.json().catch(() => ({}));+ input.value = '';+ if (!response.ok) { error.textContent = body.error || 'That did not work.'; return; }+ toast('Linked. Reading what it is running…');+ } catch {+ error.textContent = 'The pane could not reach Harness.';+ } finally {+ button.disabled = false;+ button.textContent = 'Link';+ }+ });++ $('view-fleet').addEventListener('click', () => { view = 'fleet'; render(); });+ $('view-projects').addEventListener('click', () => { view = 'projects'; render(); });+ $('view-activity').addEventListener('click', () => { view = 'activity'; render(); });+ $('motion').addEventListener('click', () => {+ paused = !paused;+ $('motion').setAttribute('aria-pressed', String(paused));+ $('motion').textContent = paused ? 'Resume motion' : 'Pause motion';+ render();+ });+ $('window-button').addEventListener('click', () => {+ const list = $('window-list'), open = list.hidden;+ list.innerHTML = WINDOWS.map(option => `<button class="menu-row" type="button" role="option" data-window="${option.id}" aria-selected="${option.id === windowId}">${option.label}</button>`).join('');+ list.hidden = !open;+ $('window-button').setAttribute('aria-expanded', String(open));+ });+ $('window-list').addEventListener('click', event => {+ const option = event.target.closest('[data-window]');+ if (!option) return;+ windowId = option.dataset.window;+ storage.write('machines:window', windowId);+ $('window-value').textContent = WINDOWS.find(w => w.id === windowId).label;+ $('window-list').hidden = true;+ $('window-button').setAttribute('aria-expanded', 'false');+ render();+ });+ document.addEventListener('keydown', event => { if (event.key === 'Escape') { selected = null; $('window-list').hidden = true; render(); } });+ window.addEventListener('resize', () => { if (view === 'fleet') { place(); draw(); } else render(); });++ $('window-value').textContent = (WINDOWS.find(w => w.id === windowId) ?? WINDOWS[1]).label;+ fetch('/api/snapshot').then(response => response.json()).then(consume).catch(() => { /* the stream will bring it */ });+ listen();+ requestAnimationFrame(animate);+ setInterval(status, 10_000);+})();diff --git a/store/agents/machines/viewer/index.html b/store/agents/machines/viewer/index.htmlnew file mode 100644index 000000000..f4796e6c3--- /dev/null+++ b/store/agents/machines/viewer/index.html@@ -0,0 +1,63 @@+<!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="light dark">+ <title>Machines · Your computers</title>+ <link rel="stylesheet" href="app.css">+ <script src="app.js" defer></script>+</head>+<body>+ <main id="app">+ <section class="workspace">+ <div class="main-column">+ <div class="view-toolbar">+ <div class="segmented" role="group" aria-label="View">+ <button id="view-fleet" type="button" aria-pressed="true">Fleet</button>+ <button id="view-projects" type="button" aria-pressed="false">Projects</button>+ <button id="view-activity" type="button" aria-pressed="false">Activity</button>+ </div>+ <div class="toolbar-selects">+ <div class="menu" id="window-menu" hidden>+ <button type="button" class="menu-button" id="window-button" aria-haspopup="listbox" aria-expanded="false">+ <span class="menu-kicker">Since</span><span class="menu-value" id="window-value">7 days</span><span class="menu-chevron" aria-hidden="true">▾</span>+ </button>+ <div class="menu-list" id="window-list" role="listbox" aria-label="Time window" hidden></div>+ </div>+ <button type="button" class="ghost" id="motion" aria-pressed="false">Pause motion</button>+ </div>+ </div>++ <div class="stage" id="stage">+ <canvas id="links" aria-hidden="true"></canvas>+ <div class="stage-heading">+ <span class="eyebrow">YOUR MACHINES</span>+ <span class="stage-subtitle" id="stage-subtitle">Looking for your computers.</span>+ </div>+ <div class="node-layer" id="nodes" aria-label="Machines"></div>+ <div class="stage-empty" id="stage-empty" hidden>+ <span class="empty-mark" aria-hidden="true">◍</span>+ <h1 id="empty-title">One computer so far.</h1>+ <p id="empty-message">Ask for another one and I will walk you through bringing it in.</p>+ </div>+ <div class="stage-foot">+ <span id="stage-legend">Lines are the links from this computer</span>+ </div>+ </div>++ <section class="board scrolls" id="projects" hidden aria-label="Projects across your machines"></section>+ <section class="board scrolls" id="activity" hidden aria-label="What your machines have been doing"></section>++ <div class="totals" id="totals"></div>+ <section class="log">+ <div class="section-heading"><h2>Recent</h2><span id="observed">Waiting for Harness</span></div>+ <div id="log-list" aria-live="polite"><div class="quiet">Nothing has changed here yet.</div></div>+ </section>+ </div>+ <aside class="inspector scrolls" id="inspector" aria-label="Details"></aside>+ </section>+ <div class="toast" id="toast" role="status" hidden></div>+ </main>+</body>+</html>