agenthub/frontend/lib/api.ts

259 lines
10 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// 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<string, string> {
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_<token>; 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<HubError> {
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<T>(path: string, init: RequestInit = {}): Promise<T> {
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, string | number | boolean | undefined>): 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 = <T>(path: string) => hubFetch<T>(path);
const post = <T>(path: string, body?: unknown) =>
hubFetch<T>(path, { method: "POST", body: JSON.stringify(body ?? {}) });
const del = <T>(path: string) => hubFetch<T>(path, { method: "DELETE" });
const patch = <T>(path: string, body: unknown) =>
hubFetch<T>(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>("/meta"),
stats: () => get<Stats>("/stats"),
presence: () => get<PresenceEntry[]>("/presence"),
playbooks: () => get<NamedInfo[]>("/playbooks"),
audit: (params: { action?: string; limit?: number } = {}) =>
get<AuditEntry[]>("/audit" + query(params)),
agents: () => get<Agent[]>("/agents"),
agent: (refValue: string) => get<Agent>("/agents/" + ref(refValue)),
/** 建 Agent;body 里带 issue_credential 时响应多一个 agent_token。 */
createAgent: (body: Record<string, unknown>) =>
post<Agent & { agent_token?: string }>("/agents", body),
/** 签发 / 轮换 Agent 自己的凭证。 */
issueCredential: (refValue: string, graceSeconds = 0) =>
post<Agent & { agent_token: string }>("/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<string, unknown>) =>
patch<Agent>("/agents/" + ref(refValue), body),
deleteAgent: (refValue: string) => del<{ ok: boolean }>("/agents/" + ref(refValue)),
probe: (refValue: string) => post<ProbeResult>("/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<Task[]>("/agents/" + ref(refValue) + "/tasks" + query({ limit })),
agentPresence: (refValue: string) => get<AgentPresence>("/agents/" + ref(refValue) + "/presence"),
tasks: (filters: TaskFilters = {}) => get<Task[]>("/tasks" + query({ limit: 100, ...filters })),
task: (id: string) => get<Task>("/tasks/" + ref(id)),
taskEvents: (id: string) => get<TaskEvent[]>("/tasks/" + ref(id) + "/events"),
taskRaw: (id: string) => get<Record<string, unknown>>("/tasks/" + ref(id) + "/raw"),
createTask: (body: {
prompt: string;
agent_id?: string;
team_id?: string;
title?: string;
session_key?: string;
}) => post<Task>("/tasks", body),
cancelTask: (id: string) => post<{ ok: boolean }>("/tasks/" + ref(id) + "/cancel"),
teams: () => get<Team[]>("/teams"),
team: (refValue: string) => get<Team>("/teams/" + ref(refValue)),
createTeam: (body: Record<string, unknown>) => post<Team>("/teams", body),
updateTeam: (refValue: string, body: Record<string, unknown>) =>
patch<Team>("/teams/" + ref(refValue), body),
deleteTeam: (refValue: string) => del<{ ok: boolean }>("/teams/" + ref(refValue)),
teamRuns: (refValue: string) => get<Run[]>("/teams/" + ref(refValue) + "/runs"),
teamBlackboard: (refValue: string) =>
get<BlackboardEntry[]>("/teams/" + ref(refValue) + "/blackboard"),
teamMessages: (refValue: string) => get<TeamMessage[]>("/teams/" + ref(refValue) + "/messages"),
runTeam: (refValue: string, objective: string, spec: Record<string, unknown> = {}) =>
post<Run>("/teams/" + ref(refValue) + "/runs", { objective, spec }),
runs: (teamId = "") => get<Run[]>("/runs" + query({ team_id: teamId })),
run: (id: string) => get<Run>("/runs/" + ref(id)),
cancelRun: (id: string) => post<{ ok: boolean }>("/runs/" + ref(id) + "/cancel"),
runTasks: (id: string) => get<Task[]>("/runs/" + ref(id) + "/tasks"),
gatewayStatus: () => get<GatewayStatus>("/gateway/status"),
frames: (params: { limit?: number; kind?: string; agent_id?: string } = {}) =>
get<Frame[]>("/gateway/frames" + query({ limit: 100, ...params })),
purgeAgents: (olderThanDays: number) =>
post<{ removed: number }>("/gateway/purge", { older_than_days: olderThanDays }),
keys: () => get<ApiKey[]>("/keys"),
createKey: (name: string, scope: "admin" | "read") => post<ApiKey>("/keys", { name, scope }),
revokeKey: (id: string) => del<{ ok: boolean }>("/keys/" + ref(id)),
deployTemplates: () =>
get<{ kinds: NamedInfo[]; providers: string[] }>("/deploy/templates"),
deployPlan: (body: Record<string, unknown>) => post<DeployPlan>("/deploy/plan", body),
/** 签过的配置,最近签的排在最前。 */
issuances: () => get<Issuance[]>("/deploy/issuances"),
};