// The console talks to the hub directly (the hub sends permissive CORS headers). // Everything is the same REST surface the CLI uses — no hidden BFF layer. import type { Agent, AgentPresence, ApiKey, AuditEntry, BlackboardEntry, DeployPlan, Frame, GatewayStatus, Issuance, Meta, NamedInfo, ProbeResult, PresenceEntry, Run, Stats, Task, TaskEvent, Team, TeamMessage, } from "./types"; export const HUB_URL = (process.env.NEXT_PUBLIC_HUB_URL ?? "http://127.0.0.1:8100").replace( /\/$/, "", ); export const API_BASE = HUB_URL + "/api/v1"; const KEY_STORE = "agenthub.api_key"; const listeners = new Set<() => void>(); export function getApiKey(): string { if (typeof window === "undefined") return ""; return window.localStorage.getItem(KEY_STORE) ?? ""; } export function setApiKey(value: string): void { if (typeof window === "undefined") return; const key = value.trim(); if (key) window.localStorage.setItem(KEY_STORE, key); else window.localStorage.removeItem(KEY_STORE); listeners.forEach((notify) => notify()); } export function onApiKeyChange(notify: () => void): () => void { listeners.add(notify); return () => listeners.delete(notify); } export function authHeaders(): Record { const key = getApiKey(); return key ? { "X-API-Key": key } : {}; } export function wsUrl(topics: string[] = ["*.>"]): string { const base = HUB_URL.replace(/^http/, "ws"); const params = new URLSearchParams({ topics: topics.join(",") }); const key = getApiKey(); if (key) params.set("api_key", key); return base + "/api/v1/stream?" + params.toString(); } export class HubError extends Error { status: number; constructor(status: number, message: string) { super(message); this.status = status; this.name = "HubError"; } } const UNREACHABLE = (detail: string) => new HubError( 0, `连不上 hub(${HUB_URL}):${detail}。最常见的原因是 hub 正在重启——重启只有 1~2 秒,` + `但会同时打断正在跑的任务(表现为 ConnectorGone)。等它起来后重跑任务即可;` + `持续连不上就在 hub 机器上执行 curl ${HUB_URL}/healthz 看进程是否存活。` + `(内置浏览器和隐私类插件偶尔也会拦到其它端口的请求。)`, ); /** Short, safe preview of the stored key: enough to spot a bad paste, never the whole secret. */ export function describeKey(key: string = getApiKey()): string { if (!key) return "未配置"; if (key.length <= 10) return `${key.slice(0, 2)}…(${key.length} 位)`; return `${key.slice(0, 5)}…${key.slice(-4)}(${key.length} 位)`; } /** The hub's own key is generated as ah_; anything else is almost certainly another vendor's key. */ export function keyShapeWarning(key: string = getApiKey()): string { if (!key.trim() || /^ah_/.test(key.trim())) return ""; return "这个值不以 ah_ 开头,多半不是 AgentHub 的 Hub Key(qwen / DashScope 的 sk- 之类不能填在这里)。"; } async function failure(response: Response): Promise { let detail = response.statusText || "request failed"; try { const body = await response.json(); if (typeof body?.detail === "string") detail = body.detail; else if (body?.detail) detail = JSON.stringify(body.detail); } catch { /* not JSON: keep the status text */ } if (response.status === 403 && detail.includes("API key")) { detail += `。当前浏览器用的是 ${describeKey()}——去 hub 机器上取 data/hub-credentials.json 里的 api_key 重新粘贴。`; } return new HubError(response.status, detail); } /** A hub restart takes a couple of seconds; a read inside that window retries, not fails. */ const READ_BACKOFF_MS = [300, 900, 1800]; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); export async function hubFetch(path: string, init: RequestInit = {}): Promise { const request: RequestInit = { ...init, cache: "no-store", headers: { "content-type": "application/json", ...authHeaders(), ...(init.headers ?? {}) }, }; // Only reads repeat: re-sending a POST could enqueue the same task twice. const retries = (init.method ?? "GET").toUpperCase() === "GET" ? READ_BACKOFF_MS.length : 0; let response: Response | undefined; let lastError: unknown; for (let attempt = 0; ; attempt++) { try { response = await fetch(API_BASE + path, request); break; } catch (error) { // A rejected fetch never reached the hub, so there is no status to report. lastError = error; if (attempt >= retries) break; await sleep(READ_BACKOFF_MS[attempt]); } } if (!response) { throw UNREACHABLE(lastError instanceof Error ? lastError.message : String(lastError)); } if (response.status === 401) { throw new HubError(401, "未配置 API Key,或 Key 不对:点右上角「配置 API Key」"); } if (!response.ok) throw await failure(response); if (response.status === 204) return undefined as T; return (await response.json()) as T; } function query(params: Record): string { const search = new URLSearchParams(); Object.entries(params).forEach(([name, value]) => { if (value !== undefined && value !== "" && value !== false) search.set(name, String(value)); }); const text = search.toString(); return text ? "?" + text : ""; } const ref = (value: string) => encodeURIComponent(value); const get = (path: string) => hubFetch(path); const post = (path: string, body?: unknown) => hubFetch(path, { method: "POST", body: JSON.stringify(body ?? {}) }); const del = (path: string) => hubFetch(path, { method: "DELETE" }); const patch = (path: string, body: unknown) => hubFetch(path, { method: "PATCH", body: JSON.stringify(body) }); export interface TaskFilters { agent_id?: string; team_id?: string; run_id?: string; status?: string; limit?: number; } export const api = { meta: () => get("/meta"), stats: () => get("/stats"), presence: () => get("/presence"), playbooks: () => get("/playbooks"), audit: (params: { action?: string; limit?: number } = {}) => get("/audit" + query(params)), agents: () => get("/agents"), agent: (refValue: string) => get("/agents/" + ref(refValue)), /** 建 Agent;body 里带 issue_credential 时响应多一个 agent_token。 */ createAgent: (body: Record) => post("/agents", body), /** 签发 / 轮换 Agent 自己的凭证。 */ issueCredential: (refValue: string, graceSeconds = 0) => post("/agents/" + ref(refValue) + "/credentials", { grace_seconds: graceSeconds, }), /** 回看这台 Agent 现在的凭证明文(hub 那边存了一份可解开封存副本)。 */ revealCredential: (refValue: string) => get<{ agent_id: string; agent_name: string; installed: boolean; agent_token: string }>( "/agents/" + ref(refValue) + "/credentials", ), updateAgent: (refValue: string, body: Record) => patch("/agents/" + ref(refValue), body), deleteAgent: (refValue: string) => del<{ ok: boolean }>("/agents/" + ref(refValue)), probe: (refValue: string) => post("/agents/" + ref(refValue) + "/probe"), describe: (refValue: string) => post<{ ok: boolean; [k: string]: unknown }>("/agents/" + ref(refValue) + "/describe"), command: (refValue: string, command: string) => post<{ ok: boolean; [k: string]: unknown }>("/agents/" + ref(refValue) + "/command", { command, }), agentTasks: (refValue: string, limit = 50) => get("/agents/" + ref(refValue) + "/tasks" + query({ limit })), agentPresence: (refValue: string) => get("/agents/" + ref(refValue) + "/presence"), tasks: (filters: TaskFilters = {}) => get("/tasks" + query({ limit: 100, ...filters })), task: (id: string) => get("/tasks/" + ref(id)), taskEvents: (id: string) => get("/tasks/" + ref(id) + "/events"), taskRaw: (id: string) => get>("/tasks/" + ref(id) + "/raw"), createTask: (body: { prompt: string; agent_id?: string; team_id?: string; title?: string; session_key?: string; }) => post("/tasks", body), cancelTask: (id: string) => post<{ ok: boolean }>("/tasks/" + ref(id) + "/cancel"), teams: () => get("/teams"), team: (refValue: string) => get("/teams/" + ref(refValue)), createTeam: (body: Record) => post("/teams", body), updateTeam: (refValue: string, body: Record) => patch("/teams/" + ref(refValue), body), deleteTeam: (refValue: string) => del<{ ok: boolean }>("/teams/" + ref(refValue)), teamRuns: (refValue: string) => get("/teams/" + ref(refValue) + "/runs"), teamBlackboard: (refValue: string) => get("/teams/" + ref(refValue) + "/blackboard"), teamMessages: (refValue: string) => get("/teams/" + ref(refValue) + "/messages"), runTeam: (refValue: string, objective: string, spec: Record = {}) => post("/teams/" + ref(refValue) + "/runs", { objective, spec }), runs: (teamId = "") => get("/runs" + query({ team_id: teamId })), run: (id: string) => get("/runs/" + ref(id)), cancelRun: (id: string) => post<{ ok: boolean }>("/runs/" + ref(id) + "/cancel"), runTasks: (id: string) => get("/runs/" + ref(id) + "/tasks"), gatewayStatus: () => get("/gateway/status"), frames: (params: { limit?: number; kind?: string; agent_id?: string } = {}) => get("/gateway/frames" + query({ limit: 100, ...params })), purgeAgents: (olderThanDays: number) => post<{ removed: number }>("/gateway/purge", { older_than_days: olderThanDays }), keys: () => get("/keys"), createKey: (name: string, scope: "admin" | "read") => post("/keys", { name, scope }), revokeKey: (id: string) => del<{ ok: boolean }>("/keys/" + ref(id)), deployTemplates: () => get<{ kinds: NamedInfo[]; providers: string[] }>("/deploy/templates"), deployPlan: (body: Record) => post("/deploy/plan", body), /** 签过的配置,最近签的排在最前。 */ issuances: () => get("/deploy/issuances"), };