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 fleet dispatcher and clipboard/file push between linked machines
bubu-duducbbb9aa6ffc1
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex fd08dd788..b58ccda38 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -186,6 +186,11 @@ const DEVICE_AGENT_NAME_MAX_BYTES = 39 // device project_t.name[40], including tconst DEVICE_ELLIPSIS = '…'export type Frame = Record<string, unknown>++/** A `clip_push` payload after validation (fleet/control.ts; first written by Fred Nix in the nixfred fork). */+export interface ClipPush { text?: string; file?: { name: string; base64: string }; from: string }+export const CLIP_TEXT_MAX = 1_000_000+export const CLIP_FILE_MAX_B64 = 34_000_000 // ~25 MB decodedtype OutboundEnvelope = Record<string, unknown>export interface LocalClientSink {@@ -556,6 +561,8 @@ export class BackendSocket {Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }>) | null = null/** Called on `dsh_remove` — cli.ts uninstalls the harness from this machine. */onDshRemove: ((id: string) => { ok: true } | { ok: false; error: string; detail: string }) | null = null+ /** A paired peer pushed text or a file to this machine's clipboard / drop folder (`harness clip push`). */+ onClipPush: ((push: ClipPush) => Promise<{ ok: true; detail: string } | { ok: false; error: string }>) | null = null/** Called on `remote_terminal_handoff` — cli.ts names the agent whose tile is that tmux pane, or null. */onTerminalHandoff: ((tmuxPane: string) => string | null) | null = null/** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */@@ -2563,6 +2570,21 @@ export class BackendSocket {return}+ case 'clip_push': {+ // Sealed end to end (a MACHINE_REQUESTS type), so only a paired peer reaches here. Sizes are+ // bounded before anything touches the clipboard or the disk.+ if (!this.onClipPush) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }+ const text = typeof payload.text === 'string' ? payload.text : undefined+ const file = payload.file && typeof payload.file === 'object' ? payload.file as { name?: unknown; base64?: unknown } : undefined+ if (text !== undefined && text.length > CLIP_TEXT_MAX) { reply(type, requestId, { error: 'CLIP_TOO_LARGE', detail: `text over ${CLIP_TEXT_MAX} chars` }); return }+ if (file && (typeof file.name !== 'string' || typeof file.base64 !== 'string' || file.base64.length > CLIP_FILE_MAX_B64)) { reply(type, requestId, { error: 'CLIP_TOO_LARGE', detail: `file over ${Math.round(CLIP_FILE_MAX_B64 * 3 / 4 / 1048576)} MB or malformed` }); return }+ if (text === undefined && !file) { reply(type, requestId, { error: 'CLIP_EMPTY' }); return }+ void this.onClipPush({ text, file: file ? { name: file.name as string, base64: file.base64 as string } : undefined, from: typeof payload.from === 'string' ? payload.from.slice(0, 64) : 'peer' })+ .then((out) => reply(type, requestId, out))+ .catch((error) => reply(type, requestId, { error: 'INTERNAL', detail: error instanceof Error ? error.message : String(error) }))+ return+ }+case 'dsh_remove': {// Uninstall a harness from THIS machine: the clone under ~/.harness/dsh goes (a linked// install loses only its link), the index forgets it, and a `dsh_list` after this nodiff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 00f20fe49..c1e023d70 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -468,7 +468,11 @@ Machine:whether this computer should take a job like thatharness subs [--force] | subs set <claude|codex|grok|kimi> <on|off>each AI plan's weekly use, banked against an even pace, and which to use next- harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop+ harness dispatch --machine=<id> --repo=<path there> [--engine=claude] [--branch=x] "brief"+ hand a bounded job to a linked machine; \`harness dispatches\` lists them+ harness clip push --machine=<id> [--file=<path>] [text]+ clipboard or a file (25 MB) to a linked machine, sealed end to end+ harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktopharness tui all of Harness in this terminal: swarms, panes, every machine (⌥O ⌥P ⌥N)harness new [agent] [@machine] [folder|name] [-- task]make a harness from a shell: \`harness new\` is claude here; see \`harness new -h\`@@ -3237,6 +3241,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {backend.runtimeProfileProvider = (session) => runtimeProfiles.selectedModel(session)backend.dshFrameProvider = dshFrameContextbackend.onDshRemove = (id) => removeDsh(id)+ backend.onClipPush = (push) => fleetControlRef ? fleetControlRef.clipReceive(push) : Promise.resolve({ ok: false as const, error: 'STARTING' })// `harness remote` names the tile it was typed in by its tmux pane; the registry knows whose it is.backend.onTerminalHandoff = (tmuxPane) => registry.advertised().find((session) => session.tmuxPane === tmuxPane@@ -4720,6 +4725,27 @@ async function runForeground(session: AuthSession | null): Promise<void> {},},)+ // The fleet dispatcher and clip push ride the same pool the window uses to reach a linked machine:+ // one E2EE-terminated session per machine, frames fanned out to whoever attached.+ fleetControl.setRelayLink(async (machineId) => {+ const listeners = new Set<(frame: { type: string; payload: Record<string, unknown> }) => void>()+ const sink = {+ sendFrame: (frame: Record<string, unknown>) => {+ const payload = (frame.payload && typeof frame.payload === 'object' ? frame.payload : {}) as Record<string, unknown>+ // The event correlator puts agentId on the frame and in the payload; keep it reachable either way.+ const shaped = { type: String(frame.type ?? ''), payload: typeof frame.agentId === 'string' && !payload.agentId ? { ...payload, agentId: frame.agentId } : payload }+ for (const cb of listeners) cb(shaped)+ return true+ },+ sendBinary: () => true,+ }+ const session = await relayPool.acquire(machineId, env.AUTONOMOUS_ENV, { type: 'machine_select', payload: { machineId } }, sink, () => { listeners.clear() })+ return {+ send: (frame) => session.send(frame as unknown as Record<string, unknown>),+ onFrame: (cb) => { listeners.add(cb); return () => { listeners.delete(cb) } },+ close: () => session.detach(),+ }+ })// Every machine and phone linked to this one, directly or through another member, trusts every other:// rosters are swapped over any session that opens, and pushed on whenever they change.groupSyncer = new GroupSyncer({@@ -8009,6 +8035,35 @@ async function fleetCommand(cmd: string, args: string[], flags: string[]): Promiif (action === 'spend-on') { action = 'spend-set'; body = { enabled: true } }break}+ case 'dispatch': {+ const brief = args.join(' ')+ if (!brief || !flag('machine') || !flag('repo')) { console.error('Usage: harness dispatch --machine=<machineId> --repo=</path/on/that/machine> [--engine=claude] [--branch=name] [--dsh=id] "brief"'); process.exit(1) }+ body = { machine: flag('machine'), repo: flag('repo'), engine: flag('engine') ?? 'claude', branch: flag('branch') ?? '', dsh: flag('dsh') ?? '', brief }+ break+ }+ case 'dispatches': break+ case 'clip': {+ // harness clip push --machine=<id> [--file=path] [text]; with neither text nor file, the local clipboard is sent.+ if (args[0] !== 'push' || !flag('machine')) { console.error('Usage: harness clip push --machine=<machineId> [--file=<path>] [text]'); process.exit(1) }+ action = 'clip-push'+ const filePath = flag('file')+ if (filePath) {+ const { readFileSync: rf, statSync: st } = await import('node:fs')+ if (st(filePath).size > 25 * 1024 * 1024) { console.error('✗ file is over 25 MB'); process.exit(1) }+ body = { machine: flag('machine'), file: { name: filePath.split('/').pop() ?? 'file', base64: rf(filePath).toString('base64') } }+ } else {+ let text = args.slice(1).join(' ')+ if (!text) {+ const { execFileSync } = await import('node:child_process')+ for (const [tool, a] of [['wl-paste', ['--no-newline']], ['xclip', ['-selection', 'clipboard', '-o']], ['pbpaste', []]] as Array<[string, string[]]>) {+ try { text = execFileSync(tool, a, { encoding: 'utf8', timeout: 3000 }); break } catch { /* next tool */ }+ }+ }+ if (!text) { console.error('✗ nothing to push: give text, --file, or put something on the clipboard'); process.exit(1) }+ body = { machine: flag('machine'), text }+ }+ break+ }case 'capabilities': breakcase 'placement': body = { needsGpu: flags.includes('--gpu'), interactive: flags.includes('--interactive'), minFreeVramMb: num('min-vram') ?? undefined }; breakcase 'subs': {@@ -9275,7 +9330,8 @@ switch (cmd) {case 'reset':resetCommand().catch(onError)break- case 'attention': case 'stop-all': case 'gate': case 'spend': case 'capabilities': case 'placement': case 'subs': case 'fleet':+ case 'attention': case 'stop-all': case 'gate': case 'spend': case 'capabilities': case 'placement': case 'subs':+ case 'dispatch': case 'dispatches': case 'clip': case 'fleet':fleetCommand(cmd, args, flags).catch(onError)breakcase 'status':diff --git a/cli/src/fleet/control.spec.ts b/cli/src/fleet/control.spec.tsindex d570a6f34..f1dc4e157 100644--- a/cli/src/fleet/control.spec.ts+++ b/cli/src/fleet/control.spec.ts@@ -88,6 +88,64 @@ describe('FleetControl', () => {expect(fleet.attention.get('a')?.state).toBe('idle')})+ it('dispatches a job over a relay link and reads the result off the worker text', async () => {+ type F = { type: string; payload: Record<string, unknown> }+ const sentFrames: F[] = []+ const link: { push: ((f: F) => void) | null } = { push: null }+ fleet.setRelayLink(async () => ({+ send: async (f) => {+ sentFrames.push(f)+ if (f.type === 'agent_create') setTimeout(() => link.push?.({ type: 'agent_create_result', payload: { requestId: f.payload.requestId, creationId: f.payload.creationId, agentId: 'remote-1' } }), 5)+ },+ onFrame: (cb) => { link.push = cb; return () => { link.push = null } },+ close: () => {},+ }))+ const rec = await fleet.dispatch('m-2', { machineId: 'm-2', brief: 'add a README badge', repo: '/srv/proj', engine: 'claude', branchName: 'badge' })+ expect(rec.finishedAt).toBeNull()+ await new Promise((r) => setTimeout(r, 40))+ expect(sentFrames[0]?.type).toBe('agent_create')+ expect(String(sentFrames[0]?.payload.prompt)).toContain('DISPATCH_RESULT:')+ link.push?.({ type: 'text_delta', payload: { agentId: 'remote-1', content: 'Done. DISPATCH_RESULT: {"branch":"badge","diffStat":"1 file changed","summary":"README badge added","ok":true}\n' } })+ link.push?.({ type: 'turn_ended', payload: { agentId: 'remote-1' } })+ await new Promise((r) => setTimeout(r, 40))+ const listed = (await fleet.command('dispatches', {}) as { dispatches: Array<typeof rec> }).dispatches+ expect(listed[0]?.agentId).toBe('remote-1')+ expect(listed[0]?.result).toMatchObject({ ok: true, branch: 'badge', summary: 'README badge added' })+ expect(listed[0]?.finishedAt).not.toBeNull()+ })++ it('receives a clip push: text to the clipboard, a file into the drop folder without overwriting', async () => {+ const clip: string[] = []+ const other = new FleetControl({ ...deps(), clipWrite: async (t) => { clip.push(t) }, dropDir: join(dir, 'drop') })+ expect(await other.clipReceive({ text: 'hello from vic', from: 'vic' })).toEqual({ ok: true, detail: '14 chars on the clipboard' })+ expect(clip).toEqual(['hello from vic'])+ const b64 = Buffer.from('payload').toString('base64')+ const first = await other.clipReceive({ file: { name: '../evil name.txt', base64: b64 }, from: 'vic' })+ const second = await other.clipReceive({ file: { name: '../evil name.txt', base64: b64 }, from: 'vic' })+ expect(first).toMatchObject({ ok: true, detail: join(dir, 'drop', 'evil name.txt') })+ expect(second).toMatchObject({ ok: true, detail: join(dir, 'drop', 'evil name-1.txt') })+ expect(readFileSync(join(dir, 'drop', 'evil name.txt'), 'utf8')).toBe('payload')+ expect(await other.clipReceive({ from: 'vic' })).toEqual({ ok: false, error: 'CLIP_EMPTY' })+ })++ it('pushes text to a linked machine and returns its reply', async () => {+ const link: { push: ((f: { type: string; payload: Record<string, unknown> }) => void) | null } = { push: null }+ const sentFrames: Array<{ type: string; payload: Record<string, unknown> }> = []+ fleet.setRelayLink(async () => ({+ send: async (f) => { sentFrames.push(f); setTimeout(() => link.push?.({ type: 'clip_push_result', payload: { requestId: f.payload.requestId, ok: true, detail: '5 chars on the clipboard' } }), 5) },+ onFrame: (cb) => { link.push = cb; return () => { link.push = null } },+ close: () => {},+ }))+ const out = await fleet.clipPush('m-2', { text: 'hello' })+ expect(out).toMatchObject({ ok: true, detail: '5 chars on the clipboard' })+ expect(sentFrames[0]).toMatchObject({ type: 'clip_push', payload: { text: 'hello', from: 'gus' } })+ })++ it('refuses dispatch and clip push before the relay pool exists', async () => {+ await expect(fleet.dispatch('m-2', { machineId: 'm-2', brief: 'x', repo: '/r', engine: 'claude', branchName: 'b' })).rejects.toThrow(/no relay link/)+ await expect(fleet.command('clip-push', { machine: 'm-2' })).rejects.toThrow(/needs machine and text or file/)+ })+it('exposes the local command surface', async () => {await expect(fleet.command('nope', {})).rejects.toThrow(/unknown fleet action/)const att = await fleet.command('attention', {}) as { agents: unknown[] }diff --git a/cli/src/fleet/control.ts b/cli/src/fleet/control.tsindex 979e6f3eb..dc9d28ba1 100644--- a/cli/src/fleet/control.ts+++ b/cli/src/fleet/control.ts@@ -11,9 +11,11 @@* spend submit → pause when caps are hit; ledger persisted per day, `harness spend`* caps GPU, load, power, heat, lid, toolchains; whether this machine should take a job* subs every AI plan's weekly use against an even pace, `harness subs`, `GET /api/subscriptions`+ * dispatch a bounded job to a linked machine over the daemon's own E2EE relay, `harness dispatch`+ * clip clipboard or a file to a linked machine, sealed end to end, `harness clip push`* commands the `harness <command>` local API behind `POST /api/fleet`*/-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, promises as fsp, readFileSync, renameSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { env } from '../config/env.js'import { AttentionTracker, summarizeAttention, type AttentionRow } from '../lib/attention.js'@@ -23,6 +25,7 @@ import { gateHookInstalled, installGateHook, uninstallGateHook } from '../lib/hoimport { decidePlacement, describeCapabilities, readMachineCapabilities, type MachineCapabilities, type PlacementRequest } from '../lib/machineCapabilities.js'import { describeSubscriptions, SubscriptionsService, type ProviderId } from './subscriptions/index.js'import { nodeSubscriptionsDeps } from './subscriptions/nodeDeps.js'+import { DISPATCH_RESULT_TYPE, createRemoteAgentBackend, jobPrompt, type DispatchResult, type JobSpec, type MachineLink, type WireFrame } from './remoteOrchestratorBackend.js'export interface FleetSessionLike {agentId: string@@ -49,6 +52,65 @@ export interface FleetControlDeps {tokenUsage: (s: FleetSessionLike) => { totalTokens: number | null } | nullhookPort: () => numbernow?: () => number+ /** Write to this machine's clipboard (default: wl-copy, xclip or pbcopy, whichever is present). */+ clipWrite?: (text: string) => Promise<void>+ /** Where pushed files land (default ~/Downloads/harness-drop or HARNESS_DROP_DIR). */+ dropDir?: string+}++/** A live, E2EE-terminated link to one linked machine, as the daemon's relay pool hands it out. */+export interface RelayLink {+ send(frame: WireFrame): Promise<void>+ onFrame(cb: (frame: WireFrame) => void): () => void+ close(): void+}++export interface DispatchRecord {+ id: string+ machineId: string+ job: JobSpec+ startedAt: number+ finishedAt: number | null+ agentId: string | null+ result: DispatchResult | null+ error: string | null+}++const DISPATCH_RESULT_RE = /DISPATCH_RESULT:\s*(\{[\s\S]*\})/++/**+ * Turn a relay link into the MachineLink the dispatcher library expects, and synthesize the+ * `dispatch_result` frame from the worker's own text: the remote agent prints one+ * `DISPATCH_RESULT: {json}` line, which arrives here as text_delta events; at turn_ended for that+ * agent the line is parsed and re-emitted as if the worker had sent a result frame. No new wire type,+ * no worker-side change, and the relay never sees the plaintext.+ */+export function machineLinkFromRelay(machineId: string, link: RelayLink): MachineLink & { close(): void } {+ const text = new Map<string, string>()+ const listeners = new Set<(f: WireFrame) => void>()+ const emit = (f: WireFrame): void => { for (const cb of listeners) cb(f) }+ const off = link.onFrame((frame) => {+ const p = frame.payload ?? {}+ const agentId = typeof p.agentId === 'string' ? p.agentId : ''+ if (frame.type === 'text_delta' && agentId && typeof p.content === 'string') {+ text.set(agentId, ((text.get(agentId) ?? '') + p.content).slice(-20_000))+ } else if (frame.type === 'turn_ended' && agentId) {+ const m = DISPATCH_RESULT_RE.exec(text.get(agentId) ?? '')+ text.delete(agentId)+ if (m) {+ let parsed: Record<string, unknown> = {}+ try { parsed = JSON.parse(m[1]!) as Record<string, unknown> } catch { parsed = { summary: 'DISPATCH_RESULT line was not valid JSON', ok: false } }+ emit({ type: DISPATCH_RESULT_TYPE, payload: { agentId, ...parsed } })+ }+ }+ emit(frame)+ })+ return {+ machineId,+ send: (frame) => { void link.send(frame) },+ onFrame: (cb) => { listeners.add(cb); return () => { listeners.delete(cb) } },+ close: () => { off(); link.close() },+ }}function readJson<T>(file: string): T | null {@@ -72,6 +134,11 @@ export class FleetControl {/** Subscription meters (ported from Burn Bar): weekly used, banked, reset, next plan to use. */readonly subs: SubscriptionsServiceprivate subsTimer: NodeJS.Timeout | null = null+ private relayLink: ((machineId: string) => Promise<RelayLink>) | null = null+ private readonly dispatches = new Map<string, DispatchRecord>()++ /** Installed by the daemon once its relay pool exists (it is built after this object). */+ setRelayLink(fn: (machineId: string) => Promise<RelayLink>): void { this.relayLink = fn }constructor(protected readonly deps: FleetControlDeps) {this.now = deps.now ?? Date.now@@ -211,6 +278,100 @@ export class FleetControl {return this.capabilities().then((caps) => ({ ...decidePlacement(caps, req), caps: describeCapabilities(caps) }))}+ // ── clipboard and file drop between paired machines ────────────────────────────────────────────++ private async clipWrite(text: string): Promise<void> {+ if (this.deps.clipWrite) return this.deps.clipWrite(text)+ const { spawn } = await import('node:child_process')+ const candidates: Array<[string, string[]]> = process.platform === 'darwin' ? [['pbcopy', []]] : [['wl-copy', []], ['xclip', ['-selection', 'clipboard']]]+ for (const [cmd, args] of candidates) {+ const ok = await new Promise<boolean>((resolve) => {+ const child = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] })+ child.on('error', () => resolve(false))+ child.on('exit', (code) => resolve(code === 0))+ child.stdin.end(text)+ })+ if (ok) return+ }+ throw new Error('no clipboard tool (wl-copy, xclip or pbcopy) worked')+ }++ /** A paired machine pushed text or a file here. Text goes to the clipboard; a file lands in the drop folder. */+ async clipReceive(push: { text?: string; file?: { name: string; base64: string }; from: string }): Promise<{ ok: true; detail: string } | { ok: false; error: string }> {+ try {+ if (push.file) {+ const dir = this.deps.dropDir ?? process.env.HARNESS_DROP_DIR ?? join(process.env.HOME ?? '/tmp', 'Downloads', 'harness-drop')+ await fsp.mkdir(dir, { recursive: true })+ // Basename only, then a conservative character set, then no leading dots: a name can never+ // climb out of the drop folder or hide as a dotfile.+ const base = push.file.name.split(/[\\/]/).filter(Boolean).pop() ?? 'file'+ const safe = base.replace(/[^\w.@ -]+/g, '_').replace(/^\.+/, '').slice(0, 120) || 'file'+ let target = join(dir, safe)+ for (let i = 1; existsSync(target); i += 1) target = join(dir, safe.replace(/(\.[^.]*)?$/, `-${i}$1`))+ await fsp.writeFile(target, Buffer.from(push.file.base64, 'base64'))+ console.log(`[clip] file from ${push.from} -> ${target}`)+ return { ok: true, detail: target }+ }+ if (push.text !== undefined) {+ await this.clipWrite(push.text)+ console.log(`[clip] text from ${push.from}: ${push.text.length} chars`)+ return { ok: true, detail: `${push.text.length} chars on the clipboard` }+ }+ return { ok: false, error: 'CLIP_EMPTY' }+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) }+ }+ }++ /** Push text or a file to a linked machine over the relay link; waits for its reply. */+ async clipPush(machineId: string, push: { text?: string; file?: { name: string; base64: string } }, timeoutMs = 15_000): Promise<Record<string, unknown>> {+ if (!this.relayLink) throw new Error('clip push is not available: no relay link')+ const link = await this.relayLink(machineId)+ const requestId = `clip-${this.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`+ try {+ const reply = new Promise<Record<string, unknown>>((resolve, reject) => {+ const timer = setTimeout(() => { off(); reject(new Error(`no reply from ${machineId} in ${timeoutMs} ms`)) }, timeoutMs)+ const off = link.onFrame((f) => {+ if (f.type === 'clip_push_result' && f.payload.requestId === requestId) { clearTimeout(timer); off(); resolve(f.payload) }+ })+ })+ await link.send({ type: 'clip_push', payload: { requestId, ...push, from: this.deps.machineName() } })+ const out = await reply+ console.log(`[clip] push to ${machineId}: ${push.file ? push.file.name : `${push.text?.length ?? 0} chars`} -> ${String(out.error ?? out.detail ?? 'ok')}`)+ return out+ } finally { link.close() }+ }++ // ── fleet dispatcher ───────────────────────────────────────────────────────────────────────────++ /** Hand a bounded job to a linked machine; returns at once with a record that fills in as it runs. */+ async dispatch(machineId: string, job: JobSpec): Promise<DispatchRecord> {+ if (!this.relayLink) throw new Error('dispatch is not available: no relay link')+ const id = `d-${this.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`+ job = { ...job, machineId }+ const record: DispatchRecord = { id, machineId, job, startedAt: this.now(), finishedAt: null, agentId: null, result: null, error: null }+ this.dispatches.set(id, record)+ console.log(`[dispatch] ${id} -> ${machineId}: ${job.brief.slice(0, 120)}`)+ void (async () => {+ let link: (MachineLink & { close(): void }) | null = null+ try {+ link = machineLinkFromRelay(machineId, await this.relayLink!(machineId))+ const backend = createRemoteAgentBackend(link, { now: this.now })+ const created = await backend.create({ engine: job.engine, cwd: job.repo, prompt: jobPrompt(job), branchName: job.branchName, ...(job.dsh ? { dsh: job.dsh } : {}) })+ record.agentId = created.agentId+ record.result = await backend.awaitResult(created.agentId, { timeoutMs: job.timeoutMs ?? 60 * 60 * 1000 })+ } catch (err) {+ record.error = err instanceof Error ? err.message : String(err)+ } finally {+ record.finishedAt = this.now()+ link?.close()+ console.log(`[dispatch] ${id} done: ${(record.error ?? record.result?.summary ?? '').slice(0, 300)}`)+ void fsp.appendFile(this.file('dispatches.jsonl'), JSON.stringify(record) + '\n').catch(() => {})+ }+ })()+ return record+ }+// ── panic stop ─────────────────────────────────────────────────────────────────────────────────async stopAll(exceptAgentId: string | null): Promise<{ cancelled: string[] }> {@@ -249,6 +410,18 @@ export class FleetControl {case 'capabilities': return { ...(await this.capabilities(0)), line: describeCapabilities(await this.capabilities()) }case 'placement': return this.placement(args as PlacementRequest)case 'subs': { const r = await this.subs.collect(args.force === true || args.force === 'true'); return { ...r, lines: describeSubscriptions(r) } }+ case 'dispatch': {+ const job: JobSpec = { machineId: str('machine'), brief: str('brief'), repo: str('repo'), engine: str('engine') || 'claude', branchName: str('branch') || `dispatch/${this.now().toString(36)}`, ...(str('dsh') ? { dsh: str('dsh') } : {}) }+ if (!job.brief || !job.repo || !str('machine')) throw new Error('dispatch needs machine, repo and brief')+ return this.dispatch(str('machine'), job)+ }+ case 'dispatches': return { dispatches: [...this.dispatches.values()].sort((a, b) => b.startedAt - a.startedAt) }+ case 'clip-push': {+ const file = args.file && typeof args.file === 'object' ? args.file as { name: string; base64: string } : undefined+ const text = typeof args.text === 'string' ? args.text : undefined+ if (!str('machine') || (!file && text === undefined)) throw new Error('clip-push needs machine and text or file')+ return this.clipPush(str('machine'), { ...(text !== undefined ? { text } : {}), ...(file ? { file } : {}) })+ }case 'subs-set': {const on = args.enabled === true || args.enabled === 'on' || args.enabled === 'true'await this.subs.setEnabled(str('id') as ProviderId, on)diff --git a/cli/src/fleet/remoteOrchestratorBackend.spec.ts b/cli/src/fleet/remoteOrchestratorBackend.spec.tsnew file mode 100644index 000000000..cf32cfe46--- /dev/null+++ b/cli/src/fleet/remoteOrchestratorBackend.spec.ts@@ -0,0 +1,109 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).++import { describe, expect, it, vi } from 'vitest'+import type { MachineCapabilities } from '../lib/machineCapabilities.js'+import { DISPATCH_RESULT_TYPE, createRemoteAgentBackend, dispatchJob, jobPrompt, placementFilter, type MachineLink, type WireFrame } from './remoteOrchestratorBackend.js'++function fakeLink(machineId = 'mind') {+ const sent: WireFrame[] = []+ const cbs = new Set<(f: WireFrame) => void>()+ const link: MachineLink = {+ machineId,+ send: (f) => { sent.push(f) },+ onFrame: (cb) => { cbs.add(cb); return () => { cbs.delete(cb) } },+ }+ return { link, sent, emit: (f: WireFrame) => { for (const cb of cbs) cb(f) } }+}++describe('createRemoteAgentBackend', () => {+ it('creates an agent over agent_create and correlates the result by requestId', async () => {+ const { link, sent, emit } = fakeLink()+ const b = createRemoteAgentBackend(link, { requestId: (() => { let i = 0; return () => `r${++i}` })() })+ const p = b.create({ engine: 'claude', cwd: '/w', prompt: 'do it', branchName: 'feat/x' })+ expect(sent[0]).toMatchObject({ type: 'agent_create', payload: { requestId: 'r2', creationId: 'r1', engine: 'claude', cwd: '/w', prompt: 'do it', branchName: 'feat/x' } })+ emit({ type: 'agent_create_result', payload: { requestId: 'r2', agentId: 'ag-9' } })+ await expect(p).resolves.toEqual({ agentId: 'ag-9' })+ await b.send('ag-9', 'more')+ await b.cancel('ag-9')+ expect(sent.slice(1)).toEqual([{ type: 'message', payload: { agentId: 'ag-9', content: 'more' } }, { type: 'cancel', payload: { agentId: 'ag-9' } }])+ b.close()+ })++ it('accepts a result echoing only creationId, and surfaces an error payload', async () => {+ const { link, emit } = fakeLink()+ const b = createRemoteAgentBackend(link, { requestId: (() => { let i = 0; return () => `r${++i}` })() })+ const p = b.create({ engine: 'codex', cwd: '/w', prompt: 'x' })+ emit({ type: 'agent_create_result', payload: { creationId: 'r1', id: 'ag-1' } })+ await expect(p).resolves.toEqual({ agentId: 'ag-1' })+ const p2 = b.create({ engine: 'codex', cwd: '/w', prompt: 'x' })+ emit({ type: 'agent_create_result', payload: { requestId: 'r4', error: 'ENGINE_MISSING' } })+ await expect(p2).rejects.toThrow('ENGINE_MISSING')+ b.close()+ })++ it('times out a create that never answers', async () => {+ vi.useFakeTimers()+ try {+ const { link } = fakeLink()+ const b = createRemoteAgentBackend(link, { timeoutMs: 50 })+ const p = b.create({ engine: 'claude', cwd: '/w', prompt: 'x' })+ const assertion = expect(p).rejects.toThrow('timed out after 50 ms')+ await vi.advanceTimersByTimeAsync(60)+ await assertion+ b.close()+ } finally { vi.useRealTimers() }+ })++ it('resolves awaitResult from a dispatch_result frame, before or after the wait starts', async () => {+ const { link, emit } = fakeLink()+ const b = createRemoteAgentBackend(link)+ emit({ type: DISPATCH_RESULT_TYPE, payload: { agentId: 'early', summary: 'done', branch: 'b', diffStat: '1 file' } })+ await expect(b.awaitResult('early')).resolves.toEqual({ agentId: 'early', summary: 'done', branch: 'b', diffStat: '1 file', ok: true })+ const late = b.awaitResult('late', { timeoutMs: 1000 })+ emit({ type: DISPATCH_RESULT_TYPE, payload: { agentId: 'late', summary: 'failed', ok: false } })+ await expect(late).resolves.toMatchObject({ ok: false, summary: 'failed' })+ b.close()+ })++ it('reads status through session_get and returns null on failure', async () => {+ const { link, emit, sent } = fakeLink()+ const b = createRemoteAgentBackend(link, { requestId: () => 'q1', timeoutMs: 20 })+ const p = b.agent('ag-1')+ expect(sent[0]).toEqual({ type: 'session_get', payload: { requestId: 'q1', agentId: 'ag-1' } })+ emit({ type: 'session_get_result', payload: { requestId: 'q1', status: 'active', summary: 's' } })+ await expect(p).resolves.toEqual({ status: 'active', summary: 's' })+ await expect(b.agent('ag-2')).resolves.toBeNull()+ b.close()+ })++ it('dispatchJob composes create, brief and result', async () => {+ const { link, sent, emit } = fakeLink('blu')+ const b = createRemoteAgentBackend(link, { requestId: () => 'k' })+ const p = dispatchJob(b, { brief: 'Add ring animation', repo: '/w/pulse', branchName: 'feat/rings', engine: 'claude', machineId: 'blu', timeoutMs: 5000 })+ expect(sent[0]!.payload.prompt).toBe(jobPrompt({ brief: 'Add ring animation', repo: '/w/pulse', branchName: 'feat/rings', engine: 'claude', machineId: 'blu' }))+ expect(String(sent[0]!.payload.prompt)).toContain('DISPATCH_RESULT:')+ emit({ type: 'agent_create_result', payload: { requestId: 'k', agentId: 'w1' } })+ emit({ type: DISPATCH_RESULT_TYPE, payload: { agentId: 'w1', summary: 'rings added', branch: 'feat/rings' } })+ await expect(p).resolves.toMatchObject({ agentId: 'w1', branch: 'feat/rings' })+ b.close()+ })+})++const caps = (over: Partial<MachineCapabilities> & { free?: number; util?: number }): MachineCapabilities => ({+ at: 0, hostname: 'h', cpu: { cores: 8, load1: 1, load5: 1 },+ gpus: over.free === undefined ? [] : [{ name: 'g', vramTotalMb: 12000, vramUsedMb: 12000 - over.free, utilizationPct: over.util ?? 0 }],+ power: { onAc: true, batteryPct: null }, thermal: { maxC: 50 }, lid: 'unknown', toolchains: {}, ...over,+})++describe('placementFilter', () => {+ it('drops machines that refuse the job and orders the rest by free VRAM then load', () => {+ const out = placementFilter([+ { machineId: 'vic', caps: caps({ free: 4000 }) },+ { machineId: 'gus', caps: caps({ free: 10000, util: 90 }) },+ { machineId: 'mind', caps: caps({ free: 20000 }) },+ { machineId: 'blu', caps: caps({}) },+ ], { needsGpu: true })+ expect(out.map((c) => c.machineId)).toEqual(['mind', 'vic'])+ expect(out[0]!.reasons).toEqual([])+ })+})diff --git a/cli/src/fleet/remoteOrchestratorBackend.ts b/cli/src/fleet/remoteOrchestratorBackend.tsnew file mode 100644index 000000000..931fabed5--- /dev/null+++ b/cli/src/fleet/remoteOrchestratorBackend.ts@@ -0,0 +1,183 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).++/**+ * The fleet dispatcher's building block: an orchestrator-shaped backend (create, send, cancel,+ * agent) that runs on ANOTHER linked machine over the existing E2EE relay session. It speaks the+ * wire types the daemon already has (`agent_create`, `message`, `cancel`, `session_get`) plus one+ * new one the worker side emits when a dispatched job finishes: `dispatch_result`.+ *+ * `MachineLink` is the seam: the daemon wires it to a RemoteRelayPool session; tests script it.+ */+import { decidePlacement, type MachineCapabilities, type PlacementRequest } from '../lib/machineCapabilities.js'++export interface WireFrame { type: string; payload: Record<string, unknown> }++export interface MachineLink {+ machineId: string+ send(frame: WireFrame): void+ onFrame(cb: (frame: WireFrame) => void): () => void+}++export interface RemoteCreateInput {+ engine: string+ cwd: string+ prompt: string+ dsh?: string+ branchName?: string+ creationId?: string+}++export interface DispatchResult {+ agentId: string+ branch?: string+ diffStat?: string+ summary: string+ ok: boolean+}++export interface RemoteAgentBackend {+ machineId: string+ create(input: RemoteCreateInput): Promise<{ agentId: string }>+ send(agentId: string, text: string): Promise<void>+ cancel(agentId: string): Promise<void>+ agent(agentId: string): Promise<{ status: string; summary?: string } | null>+ awaitResult(agentId: string, opts?: { timeoutMs?: number }): Promise<DispatchResult>+ close(): void+}++export interface BackendOptions {+ timeoutMs?: number+ requestId?: () => string+ now?: () => number+}++/** The worker side emits this when a dispatched agent reports done. Exported so the daemon reuses it. */+export const DISPATCH_RESULT_TYPE = 'dispatch_result'++class Timeout extends Error { constructor(what: string, ms: number) { super(`${what} timed out after ${ms} ms`) } }++export function createRemoteAgentBackend(link: MachineLink, opts: BackendOptions = {}): RemoteAgentBackend {+ const timeoutMs = opts.timeoutMs ?? 30_000+ let seq = 0+ const nextId = opts.requestId ?? (() => `rq-${link.machineId}-${++seq}`)+ const pending = new Map<string, { resolve: (p: Record<string, unknown>) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>()+ const results = new Map<string, DispatchResult>()+ const waiters = new Map<string, Array<(r: DispatchResult) => void>>()++ const off = link.onFrame((frame) => {+ if (frame.type === DISPATCH_RESULT_TYPE) {+ const p = frame.payload+ const agentId = String(p.agentId ?? '')+ if (!agentId) return+ const r: DispatchResult = {+ agentId, summary: String(p.summary ?? ''), ok: p.ok !== false,+ ...(typeof p.branch === 'string' ? { branch: p.branch } : {}),+ ...(typeof p.diffStat === 'string' ? { diffStat: p.diffStat } : {}),+ }+ results.set(agentId, r)+ for (const w of waiters.get(agentId) ?? []) w(r)+ waiters.delete(agentId)+ return+ }+ if (!frame.type.endsWith('_result')) return+ const rid = frame.payload.requestId+ const key = typeof rid === 'string' ? rid : typeof frame.payload.creationId === 'string' ? frame.payload.creationId : ''+ const p = key ? pending.get(key) : undefined+ if (!p) return+ pending.delete(key)+ clearTimeout(p.timer)+ if (typeof frame.payload.error === 'string') p.reject(new Error(`${frame.type}: ${frame.payload.error}`))+ else p.resolve(frame.payload)+ })++ const rpc = (type: string, payload: Record<string, unknown>, key: string): Promise<Record<string, unknown>> =>+ new Promise((resolve, reject) => {+ const timer = setTimeout(() => { pending.delete(key); reject(new Timeout(type, timeoutMs)) }, timeoutMs)+ pending.set(key, { resolve, reject, timer })+ link.send({ type, payload })+ })++ return {+ machineId: link.machineId,+ async create(input) {+ const creationId = input.creationId ?? nextId()+ const requestId = nextId()+ const payload: Record<string, unknown> = { requestId, creationId, engine: input.engine, cwd: input.cwd, prompt: input.prompt, ...(input.dsh ? { dsh: input.dsh } : {}), ...(input.branchName ? { branchName: input.branchName } : {}) }+ // Correlate by requestId first; a daemon that echoes only creationId still matches.+ const p = rpc('agent_create', payload, requestId)+ pending.set(creationId, pending.get(requestId)!)+ const res = await p+ pending.delete(creationId)+ const agentId = typeof res.agentId === 'string' ? res.agentId : typeof res.id === 'string' ? res.id : ''+ if (!agentId) throw new Error('agent_create_result carried no agentId')+ return { agentId }+ },+ async send(agentId, text) { link.send({ type: 'message', payload: { agentId, content: text } }) },+ async cancel(agentId) { link.send({ type: 'cancel', payload: { agentId } }) },+ async agent(agentId) {+ const requestId = nextId()+ try {+ const res = await rpc('session_get', { requestId, agentId }, requestId)+ const status = typeof res.status === 'string' ? res.status : 'unknown'+ return { status, ...(typeof res.summary === 'string' ? { summary: res.summary } : {}) }+ } catch { return null }+ },+ awaitResult(agentId, o = {}) {+ const done = results.get(agentId)+ if (done) return Promise.resolve(done)+ const ms = o.timeoutMs ?? timeoutMs+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ waiters.set(agentId, (waiters.get(agentId) ?? []).filter((w) => w !== onResult))+ reject(new Timeout(`dispatch_result for ${agentId}`, ms))+ }, ms)+ const onResult = (r: DispatchResult) => { clearTimeout(timer); resolve(r) }+ waiters.set(agentId, [...(waiters.get(agentId) ?? []), onResult])+ })+ },+ close() {+ off()+ for (const p of pending.values()) { clearTimeout(p.timer); p.reject(new Error('link closed')) }+ pending.clear()+ },+ }+}++export interface JobSpec {+ brief: string+ repo: string+ branchName: string+ engine: string+ machineId: string+ dsh?: string+ timeoutMs?: number+}++/** The worker-side brief: what the remote agent is told, and how it is told to report back. */+export function jobPrompt(job: JobSpec): string {+ return [+ `You are a dispatched worker on machine ${job.machineId}. Work only inside this worktree on branch ${job.branchName}.`,+ '', '## Brief', job.brief, '',+ '## When done',+ 'Commit your work on this branch. Then print exactly one line starting with DISPATCH_RESULT: followed by JSON',+ '{"summary": "<one paragraph: what changed, what is left, open questions>"}. Do not push.',+ ].join('\n')+}++export async function dispatchJob(backend: RemoteAgentBackend, job: JobSpec): Promise<DispatchResult> {+ const { agentId } = await backend.create({ engine: job.engine, cwd: job.repo, prompt: jobPrompt(job), branchName: job.branchName, ...(job.dsh ? { dsh: job.dsh } : {}) })+ return backend.awaitResult(agentId, { timeoutMs: job.timeoutMs ?? 60 * 60 * 1000 })+}++export interface Candidate { machineId: string; caps: MachineCapabilities }++/** Machines that can take the job, best first (most free VRAM, then lowest load). */+export function placementFilter(candidates: Candidate[], req: PlacementRequest): Array<Candidate & { reasons: string[] }> {+ const ok = candidates+ .map((c) => ({ ...c, ...decidePlacement(c.caps, req) }))+ .filter((c) => c.ok)+ .map(({ ok: _ok, ...c }) => c)+ const freeVram = (c: Candidate) => Math.max(0, ...c.caps.gpus.map((g) => g.vramTotalMb - g.vramUsedMb))+ const loadPerCore = (c: Candidate) => (c.caps.cpu.cores ? c.caps.cpu.load1 / c.caps.cpu.cores : 0)+ return ok.sort((a, b) => freeVram(b) - freeVram(a) || loadPerCore(a) - loadPerCore(b))+}diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex 0bb3cc505..d629ec927 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -18,7 +18,9 @@ const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'gr'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.-const MACHINE_REQUESTS = new Set(['agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', ...OWNER_COMMAND_TYPES])+// `clip_push`: clipboard and file drop between paired machines (fleet/control.ts) is user content, sealed+// the same way (core.ts itself is a pinned interop keystone and stays untouched).+const MACHINE_REQUESTS = new Set(['agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'clip_push', ...OWNER_COMMAND_TYPES])const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))/** The pair brain, machine to machine (daemons/BRAIN.md). A watch carries question text and recaps; the* writes (answer, send, stop, start, pause, resume) act on a harness through the owning machine's floor