Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

14.5 KB
Raw Blame
/**
 * The daemon, over the loopback bridge Harness already serves (copied from Harness Monitor's lib/bridge.mjs:
 * a package installs alone, so each carries its own).
 *
 * This talks only to the daemon's `/api/local-ws`, over its private socket (localDaemon.mjs); Harness owns pairing, encryption
 * and every remote machine behind it. The handshake is the one the Grid harness uses — `machine_select`,
 * wait for `connected`, then typed request/reply frames whose answer is `<type>_result` carrying the
 * same `requestId`. Nothing here reaches the network. The one credential this file touches is the
 * daemon's own local one (`localCredentialHeaders`), shown only to that loopback bridge.
 *
 * Memories asks each machine for what its agents remember (`memory_snapshot`) and hands it the person's
 * About You (`memory_about_put`) and the person's on/off choice (`memory_deliver`). Writes are never
 * automatically retried after a lost reply.
 */

import { randomUUID } from 'node:crypto'
import { execFile } from 'node:child_process'
import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
import { DaemonWebSocket, daemonSocketPath } from './localDaemon.mjs'

const exec = promisify(execFile)

export const DEFAULT_BRIDGE = 'ws://127.0.0.1:18473/api/local-ws'

/**
 * The headers every request to the daemon's loopback API carries: its local credential, or none.
 *
 * Since Harness 0.4.21 the loopback port (REST and `/api/local-ws`) answers 401 to a process that does
 * not show `X-Harness-Local: <credential>`, the 0600 `hook-credential` file in Harness's data folder
 * (`ADAPTER_DATA_DIR`, default `~/.harness/cli/data`) — so only the OS user Harness runs as gets in.
 * Read with the CLI's own checks (cli/src/lib/hookAuth.ts `readHookCredential`): a folder that is ours
 * and nobody else can write, a 0600 regular file of ours, a 43-character base64url value. Anything else
 * is no credential and no header (the CLI also tightens a 0755 folder; a reader leaves it alone).
 * The same function, by the same name, is in every Store package that talks to the daemon.
 */
export function localCredentialHeaders(env = process.env) {
  // Where a socket can be, and on Windows, where the daemon's pipe is the way, nothing carries the credential: a holder of the
  // TCP port would hear it (localDaemon.mjs; on Windows the Team account's daemon can hold it from boot, audit W1).
  if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return {}
  const dir = env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')
  const uid = typeof process.getuid === 'function' ? process.getuid() : null
  const opened = []
  try {
    const folder = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
    opened.push(folder)
    const where = fstatSync(folder)
    if (!where.isDirectory() || (uid !== null && where.uid !== uid) || (where.mode & 0o022) !== 0) return {}
    const file = openSync(join(dir, 'hook-credential'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
    opened.push(file)
    const stat = fstatSync(file)
    if (!stat.isFile() || stat.size > 128 || (uid !== null && stat.uid !== uid) || (stat.mode & 0o777) !== 0o600) return {}
    const value = readFileSync(file, 'utf8').trim()
    return /^[A-Za-z0-9_-]{43}$/.test(value) ? { 'X-Harness-Local': value } : {}
  } catch {
    return {}
  } finally {
    for (const fd of opened) closeSync(fd)
  }
}

const CREDENTIAL_REFUSED = "Harness refused this process's local credential. Run Memories as the same OS user as Harness."

/** Whether the daemon behind a bridge socket that would not open refused the credential: a WebSocket
 *  cannot report the 401, so the same headers are shown once over plain HTTP, which can. */
async function credentialRefused(url, headers, env = process.env) {
  // Over the socket or the pipe no credential is shown, and the port may be anyone's: there is nothing to ask it.
  if (process.platform === 'win32' || daemonSocketPath(65_535, env)) return false
  try {
    const answer = await fetch(url.replace(/^ws:/, 'http:'), { headers, signal: AbortSignal.timeout(2000) })
    await answer.body?.cancel()
    return answer.status === 401
  } catch {
    return false
  }
}

export function bridgeUrl(env = process.env) {
  const url = new URL(env.MEMORIES_BRIDGE_URL || env.HPS_BRIDGE_URL || DEFAULT_BRIDGE)
  if (url.protocol !== 'ws:' || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
    || url.pathname !== '/api/local-ws' || url.username || url.password || url.search || url.hash) {
    throw new Error('The Harness bridge must be its local WebSocket endpoint.')
  }
  return url.href
}

/** Every machine this daemon can reach, the current one flagged, and — when the list could not be
 *  read — why. `harness` not on PATH is reported as unavailable; no registry guesses enable actions.
 *  The command runs from the home folder, never from this package's
 *  directory: a package update swaps that directory out from under a running viewer, and a CLI
 *  started in a directory that no longer exists fails in a way that reads exactly like a dead daemon. */
export async function machinesReport(env = process.env) {
  try {
    const { stdout } = await exec('harness', ['machines', '--json'], { timeout: 20_000, maxBuffer: 512 * 1024, env, cwd: homedir() })
    const machines = stdout.split('\n').filter(Boolean).map((line) => { try { return JSON.parse(line) } catch { return null } })
      .filter((row) => row && typeof row.machineId === 'string')
      .map((row) => ({
        machineId: row.machineId,
        name: String(row.name || row.hostname || row.machineId).slice(0, 240),
        current: row.current === true,
        online: row.status === 'running',
      }))
    return { machines, error: null }
  } catch (error) {
    const detail = error?.code === 'ENOENT'
      ? 'the `harness` command is not on PATH'
      : `the \`harness machines\` command failed${error?.stderr ? `: ${String(error.stderr).trim().split('\n')[0].slice(0, 200)}` : error?.message ? `: ${String(error.message).slice(0, 200)}` : ''}`
    return { machines: [], error: detail }
  }
}

/** The machine list alone, for callers that only need the rows. */
export async function machines(env = process.env) {
  return (await machinesReport(env)).machines
}

/**
 * One bridge socket per machine, opened on first use and kept for the next call.
 *
 * Behind a `machine_select` on this bridge, Harness dials its relay to that machine, runs an
 * encryption handshake and — until recently — negotiated a WebRTC channel; opening a socket per poll
 * threw all of that away every few seconds, for every machine, from every pane. So the select happens
 * once, and a poll is one `agents_list` frame on a socket that already exists. A socket that closes,
 * errors, or stops answering is dropped; the next call opens a fresh one.
 *
 * Any failure — no daemon, an unlinked machine, a timeout — arrives as an Error whose message is a
 * sentence a person can act on, because these end up in a pane header and a CLI's stderr rather than
 * a log nobody reads.
 */
const sessions = new Map() // WebSocketImpl -> Map<machineId, session>; keyed by impl so a test's scripted socket is its own world

function sessionsFor(WebSocketImpl) {
  let byMachine = sessions.get(WebSocketImpl)
  if (!byMachine) { byMachine = new Map(); sessions.set(WebSocketImpl, byMachine) }
  return byMachine
}

function openSession(machineId, { env, timeoutMs, WebSocketImpl, forceReconnect = false }) {
  const byMachine = sessionsFor(WebSocketImpl)
  const url = bridgeUrl(env)
  const headers = localCredentialHeaders(env)
  const socket = new WebSocketImpl(url, { headers, env })
  const pending = new Map()
  let closed = null
  let opened = false
  let refusal = null // the credential check under way after a socket that never opened
  const session = { socket, pending, ready: null, close: null }
  const fail = (message) => {
    closed ??= new Error(message)
    if (byMachine.get(machineId) === session) byMachine.delete(machineId)
    for (const [, entry] of pending) { clearTimeout(entry.deadline); entry.reject(closed) }
    pending.clear()
    try { socket.close() } catch { /* already gone */ }
  }
  session.close = () => fail('The Harness bridge closed the connection.')

  session.ready = new Promise((resolve, reject) => {
    const deadline = setTimeout(() => { const m = 'The Harness daemon did not answer on the local bridge. Is Harness running?'; fail(m); reject(new Error(m)) }, Math.min(timeoutMs, 15_000))
    // `forceReconnect` tells Harness the session it kept for this machine is dead (the machine's own
    // Harness restarted under it) and must be dialled fresh rather than handed back once more.
    socket.addEventListener('open', () => { opened = true; socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, relayIsolation: true, tool: true, ...(forceReconnect ? { forceReconnect: true } : {}) } })) })
    socket.addEventListener('error', () => {
      clearTimeout(deadline)
      const m = 'Could not open the local Harness bridge. Start Harness and try again.'
      if (opened) { fail(m); reject(new Error(m)); return }
      refusal = credentialRefused(url, headers, env).then((refused) => { const why = refused ? CREDENTIAL_REFUSED : m; fail(why); reject(new Error(why)) })
    })
    socket.addEventListener('close', (event) => {
      if (refusal) return // the error above answers, once it knows whether the credential was refused
      clearTimeout(deadline)
      const message = event?.code === 4404
        ? 'Link this machine in Harness ▸ Machines to see its memories.'
        : 'The Harness bridge closed the connection.'
      fail(message); reject(new Error(message))
    })
    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 }
      const { type, payload = {} } = frame
      if (type === 'connected') { clearTimeout(deadline); resolve(); return }
      if (['error', 'connection_error', 'local_protocol_error', 'machine_link_required'].includes(type)) {
        const message = 'That machine is unavailable or needs linking in Harness ▸ Machines.'
        fail(message); reject(new Error(message)); return
      }
      const entry = pending.get(payload.requestId)
      if (!entry || type !== `${entry.type}_result`) return
      pending.delete(payload.requestId)
      clearTimeout(entry.deadline)
      if (payload.error) entry.reject(Object.assign(new Error(String(payload.detail || payload.error)), { code: payload.error }))
      else entry.resolve(payload)
    })
  })
  session.ready.catch(() => {})

  session.rpc = (type, payload = {}, { callTimeoutMs = timeoutMs } = {}) => new Promise((resolve, reject) => {
    if (closed) { reject(closed); return }
    const requestId = randomUUID()
    const deadline = setTimeout(() => {
      pending.delete(requestId)
      const error = new Error(`The daemon did not answer ${type} in time.`)
      error.timedOut = true
      reject(error)
    }, callTimeoutMs)
    pending.set(requestId, { type, resolve, reject, deadline })
    try { socket.send(JSON.stringify({ type, payload: { ...payload, requestId } })) }
    catch { pending.delete(requestId); clearTimeout(deadline); reject(closed ?? new Error('The Harness bridge closed the connection.')) }
  })

  byMachine.set(machineId, session)
  return session
}

/** The kept session for `machineId`, opening one if there is none. */
async function bridgeSession(machineId, { env = process.env, timeoutMs = 20_000, WebSocketImpl = DaemonWebSocket, forceReconnect = false } = {}) {
  if (!WebSocketImpl) throw new Error('Node 22 or newer is required to reach the Harness bridge.')
  const existing = sessionsFor(WebSocketImpl).get(machineId)
  const session = existing ?? openSession(machineId, { env, timeoutMs, WebSocketImpl, forceReconnect })
  await session.ready
  return { session, reused: session === existing }
}

/**
 * One socket, one machine, however many calls the caller needs, then closed — for a one-off job
 * that must not share the kept session (a script, a test). `fn` receives `rpc(type, payload)`.
 */
export async function withBridge(machineId, fn, { env = process.env, timeoutMs = 20_000, WebSocketImpl = DaemonWebSocket } = {}) {
  if (!WebSocketImpl) throw new Error('Node 22 or newer is required to reach the Harness bridge.')
  // Its own world, never the shared map: a fresh key that nothing else will look up.
  const own = class extends WebSocketImpl {}
  const session = openSession(machineId, { env, timeoutMs, WebSocketImpl: own })
  try {
    await session.ready
    return await fn(session.rpc)
  } finally {
    session.close()
    sessions.delete(own)
  }
}

/** The fleet as the daemon sees it, for one machine — on the kept session. A kept socket that has
 *  gone quiet (the daemon behind it restarted without closing it) is dropped and the read retried
 *  ONCE on a fresh one before the machine is reported silent. */
export async function listInventory(machineId, options = {}) {
  const ask = async ({ session }) => {
    const reply = await session.rpc('agents_list', { includeStopped: true, monitor: true })
    return { agents: Array.isArray(reply.agents) ? reply.agents : [],
      shared: Array.isArray(reply.sharedResources) ? reply.sharedResources : [], sampledAt: reply.sampledAt ?? null }
  }
  const first = await bridgeSession(machineId, options)
  try {
    return await ask(first)
  } catch (error) {
    if (!error?.timedOut) throw error
    first.session.close()
    if (!first.reused) throw error
    const second = await bridgeSession(machineId, { ...options, forceReconnect: true })
    try { return await ask(second) } catch (again) { if (again?.timedOut) second.session.close(); throw again }
  }
}

export async function listAgents(machineId, options = {}) {
  return (await listInventory(machineId, options)).agents
}

/** A single owner RPC. Only reads above reconnect/retry; callers reconcile uncertain writes by receipt. */
export async function request(machineId, type, payload = {}, options = {}) {
  const { session } = await bridgeSession(machineId, options)
  return session.rpc(type, payload, { callTimeoutMs: options.timeoutMs ?? 30_000 })
}

/** Drop every kept bridge session (the pane is closing). */
export function closeBridges() {
  for (const byMachine of sessions.values()) for (const session of [...byMachine.values()]) session.close()
  sessions.clear()
}