import { signAgentRequest } from "@crosscode/contracts/signing"; import type { AgentConfig, Keys } from "./config"; /** * Requests to the Hub. The agent only ever makes outgoing requests (it listens on nothing, * AGENT-1.0-PLAN ยง2 rule 1); every one after joining is signed with the server's Ed25519 key. */ export class HubRequestError extends Error { constructor(message: string, readonly status: number, readonly code: string | null) { super(message); } } export type Fetch = typeof fetch; export interface HubClient { post(path: string, body: unknown): Promise; put(path: string, body: Uint8Array, contentType: string): Promise; } const TIMEOUT_MS = 30_000; const UPLOAD_TIMEOUT_MS = 10 * 60_000; async function send(fetcher: Fetch, url: string, init: RequestInit, timeoutMs: number): Promise { let res: Response; try { res = await fetcher(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }); } catch (e) { throw new HubRequestError(`The Hub can't be reached: ${(e as Error).message}`, 0, "HUB_UNREACHABLE"); } if (res.status === 204) return null; let body: unknown; try { body = await res.json(); } catch { body = null; } if (!res.ok) { const b = (body ?? {}) as { message?: string; code?: string }; throw new HubRequestError(b.message || `The Hub answered ${res.status}`, res.status, b.code ?? null); } return body; } /** An unsigned request (only `join`, where the one-time token is the proof). */ export function postUnsigned(hubUrl: string, path: string, body: unknown, fetcher: Fetch = fetch): Promise { return send(fetcher, `${hubUrl.replace(/\/$/, "")}${path}`, { method: "POST", headers: { "content-type": "application/json", "user-agent": "crosscode-agent" }, body: JSON.stringify(body), }, TIMEOUT_MS); } export function hubClient(config: AgentConfig, keys: Keys, fetcher: Fetch = fetch): HubClient { const base = config.hubUrl.replace(/\/$/, ""); const signed = (raw: string | Uint8Array) => signAgentRequest({ serverId: config.serverId, privateKeyPem: keys.ed25519Pem, rawBody: raw }); return { post(path, body) { const raw = JSON.stringify(body); return send(fetcher, `${base}${path}`, { method: "POST", headers: { "content-type": "application/json", "user-agent": "crosscode-agent", ...signed(raw) }, body: raw, }, TIMEOUT_MS); }, put(path, body, contentType) { return send(fetcher, `${base}${path}`, { method: "PUT", headers: { "content-type": contentType, "user-agent": "crosscode-agent", ...signed(body) }, body, }, UPLOAD_TIMEOUT_MS); }, }; }