import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign } from "node:crypto" import { mkdir, readFile, writeFile } from "node:fs/promises" import { homedir, hostname } from "node:os" import { join } from "node:path" import { z } from "zod" import { computerCallSchema } from "@super/nova/computer-use" import { computerDeviceMessage } from "@super/nova/computer-device" import { desktopAuth } from "../desktop-auth" import { LocalComputer } from "./computer" import { localComputerLink, type LinkedComputerIdentity } from "./computer-link-store" const identitySchema = z.object({ publicId: z.string().uuid(), privateKey: z.string().max(4096) }).strict() const responseSchema = z.object({ deviceId: z.string(), enabled: z.boolean(), requests: z.array(z.object({ id: z.string(), runId: z.string(), call: z.unknown().transform((value) => computerCallSchema.parse(value)), expiresAt: z.string() })).max(8) }) export class DesktopComputerAgent { private readonly computer: Pick private cancellation = new AbortController() private accountCancellation = new AbortController() private task: Promise | undefined private account: string | null = null private identity: z.infer | null = null private state: "enabled" | "disabled" | "error" | "permission-required" = "disabled" private seen = new Map() private readonly origin: string constructor(private readonly options: { home?: string; origin?: string; displayName?: string; pollMs?: number readToken?: typeof desktopAuth.token; readIdentity?: typeof desktopAuth.identity readLinkedIdentity?: () => Promise fetcher?: (url: string, init: RequestInit) => Promise; computer?: Pick } = {}) { this.computer = options.computer ?? new LocalComputer() const url = new URL(options.origin ?? process.env.NOVA_WEB_URL ?? "https://nova.supercodeai.tech") if (url.origin !== url.href.replace(/\/$/, "") || url.username || url.password || (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))) throw new Error("Invalid Nova origin") this.origin = url.origin } start() { if (this.task) return if (this.cancellation.signal.aborted) this.cancellation = new AbortController() this.task = (async () => { while (!this.cancellation.signal.aborted) { try { await this.tick() } catch { /* Offline hosts reconnect without executing or replaying actions. */ } if (this.cancellation.signal.aborted) break await new Promise((resolve) => { const done = () => { clearTimeout(timer); this.cancellation.signal.removeEventListener("abort", done); resolve() } const timer = setTimeout(done, this.options.pollMs ?? 2000) this.cancellation.signal.addEventListener("abort", done, { once: true }) }) } })() } async disconnect() { this.accountCancellation.abort() this.accountCancellation = new AbortController() this.account = null this.identity = null this.state = "disabled" this.seen.clear() await this.computer.disable() } async stop() { this.cancellation.abort(); await this.disconnect(); await this.task; this.task = undefined } private async loadIdentity(account: string) { const directory = join(this.options.home ?? homedir(), ".nova", "desktop", "computers") await mkdir(directory, { recursive: true, mode: 0o700 }) const file = join(directory, `${account}.json`) try { return identitySchema.parse(JSON.parse(await readFile(file, "utf8"))) } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error } const key = generateKeyPairSync("ed25519") const identity = { publicId: randomUUID(), privateKey: key.privateKey.export({ format: "pem", type: "pkcs8" }).toString() } try { await writeFile(file, JSON.stringify(identity), { mode: 0o600, flag: "wx" }) } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error return identitySchema.parse(JSON.parse(await readFile(file, "utf8"))) } return identity } async tick() { const linked = await this.options.readLinkedIdentity?.() const token = linked ? undefined : (await (this.options.readToken ?? desktopAuth.token)())?.access_token const owner = token ? await (this.options.readIdentity ?? desktopAuth.identity)() : null if (!linked && (!token || !owner)) { if (this.account) await this.disconnect(); return } const account = linked ? `linked:${linked.publicId}` : createHash("sha256").update(JSON.stringify([owner!.issuer, owner!.subject])).digest("hex") if (account !== this.account) { await this.disconnect() this.identity = linked ?? await this.loadIdentity(account) this.account = account } const identity = this.identity! const signal = AbortSignal.any([this.cancellation.signal, this.accountCancellation.signal]) const privateKey = createPrivateKey(identity.privateKey) const publicKey = createPublicKey(privateKey).export({ type: "spki", format: "der" }).toString("base64url") const request = async (operation: "heartbeat" | "claim" | "complete", payload: unknown) => { signal.throwIfAborted() if (linked) { if ((await this.options.readLinkedIdentity?.())?.publicId !== linked.publicId) throw new Error("Computer link changed") } else if ((await (this.options.readToken ?? desktopAuth.token)())?.access_token !== token) throw new Error("Desktop account changed") const timestamp = Date.now() const nonce = randomBytes(32).toString("base64url") const signature = sign(null, computerDeviceMessage(operation, identity.publicId, publicKey, timestamp, nonce, payload), privateKey).toString("base64url") const response = await (this.options.fetcher ?? fetch)(`${this.origin}/api/desktop/nova/computer/${linked ? "linked-device" : "device"}`, { method: "POST", headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), "Content-Type": "application/json" }, body: JSON.stringify({ operation, publicId: identity.publicId, publicKey, timestamp, nonce, payload, signature }), signal: AbortSignal.any([signal, AbortSignal.timeout(12_000)]), redirect: "error", cache: "no-store", }) if (!response.ok) { if (linked && [401, 409].includes(response.status)) { await this.computer.disable(); this.state = "disabled" } throw new Error("Desktop computer connection unavailable") } const text = await response.text() if (text.length > 70_000) throw new Error("Computer response exceeds limit") return JSON.parse(text) } const response = responseSchema.parse(await request("heartbeat", { displayName: (this.options.displayName ?? hostname()).slice(0, 100), state: this.state })) signal.throwIfAborted() if (!response.enabled) { await this.computer.disable() this.state = "disabled" return } if (!this.computer.status().enabled) { try { await this.computer.enable() const check = await this.computer.call({ tool: "list_apps", args: {} }, signal) if (!check.successful) throw new Error("Cua unavailable") this.state = "enabled" } catch { this.state = this.computer.status().permissions?.accessibility === false ? "permission-required" : "error"; await this.computer.disable(); return } } for (const row of response.requests) { signal.throwIfAborted() for (const [id, deadline] of this.seen) if (deadline <= Date.now()) this.seen.delete(id) if (this.seen.has(row.id)) continue const expiresAt = Date.parse(row.expiresAt) if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) continue this.seen.set(row.id, expiresAt) const claim = await request("claim", { id: row.id, runId: row.runId }) if (claim.ok !== true || expiresAt <= Date.now()) continue let result: unknown let checking: Promise | undefined const monitor = setInterval(() => { if (checking) return checking = (async () => { try { const heartbeat = responseSchema.parse(await request("heartbeat", { displayName: (this.options.displayName ?? hostname()).slice(0, 100), state: this.state })) if (!heartbeat.enabled) { await this.computer.disable(); this.state = "disabled" } } catch { /* Deadline and local sign-out still cancel this action. */ } })().finally(() => { checking = undefined }) }, 1000) try { result = await this.computer.call(row.call, AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, expiresAt - Date.now()))])) } catch { result = { successful: false, error: "Cua action failed or was interrupted. Its effect may be uncertain; inspect the computer before retrying." } } finally { clearInterval(monitor); await checking } await request("complete", { id: row.id, runId: row.runId, result }) } } } export const desktopComputer = new DesktopComputerAgent({ readLinkedIdentity: () => localComputerLink.read() })