import { readFileSync } from "node:fs"; import { normalizeUsage, safeModelLabel, type NormalizedUsage } from "./usage.ts"; export interface OmniRouteConfig { /** Candidate base URLs ending in /v1, in order of preference. `AGENTHUB_OMNIROUTE_URL` replaces the list. */ urls: string[]; /** Used when `OMNIROUTE_API_KEY` is not set. */ api_key_file?: string; /** Hosts behind Cloudflare Access: only these get the two Access headers. */ access_hosts: string[]; cf_client_id_file?: string; cf_client_secret_file?: string; } /** No gateway by default: `omniroute.urls` in `.agenthub/config.json` (or AGENTHUB_OMNIROUTE_URL) names yours. */ export const DEFAULT_OMNIROUTE: OmniRouteConfig = { urls: [], access_hosts: [] }; export interface ToolCall { id: string; type: "function"; function: { name: string; arguments: string }; } export interface ChatMessage { role: "system" | "user" | "assistant" | "tool"; content: string | null; tool_calls?: ToolCall[]; tool_call_id?: string; /** Internal local-tool outcome, consumed by route normalization and omitted from provider transport. */ is_error?: boolean; } export interface ChatResult { /** Internal routing telemetry id, never part of a provider payload. */ routeDecision?: string; message: ChatMessage; /** Usage counters returned by the provider, when valid. No missing counter is inferred as zero. */ usage?: NormalizedUsage; /** Model named by the completed response, when the gateway reports it. */ servedModel?: string; /** Positive metadata only when the raw response identity required no normalization. */ servedModelExact?: true; /** `x-omniroute-provider` (direct path) */ provider?: string; } export interface ChatOptions { /** Refuse a changed/off-campus gateway immediately before transport. */ onCampusOnly?: boolean; signal?: AbortSignal; } const readSecret = (file?: string) => { try { return file ? readFileSync(file, "utf8").trim() : ""; } catch { return ""; } }; /** L3 client. Secrets are read here and go nowhere but request headers: never into logs, errors or return values. */ export class OmniRoute { private live: string | undefined; constructor( private readonly cfg: OmniRouteConfig = DEFAULT_OMNIROUTE, private readonly log: (line: string) => void = () => {}, ) {} apiKey(): string { return process.env.OMNIROUTE_API_KEY?.trim() || readSecret(this.cfg.api_key_file); } /** Is this URL behind Cloudflare Access, i.e. reached by leaving the campus network? */ isAccessHost(url: string): boolean { try { return this.cfg.access_hosts.includes(new URL(url).hostname); } catch { return true; // unparseable: not something to send PII to } } /** * Positively confirmed: a gateway answered and it is not behind Access. "Unknown" is not "on campus": with no healthy * candidate a later probe may land on the off-campus URL, so PII decisions use this, never `!offCampus()`. */ async onCampus(): Promise { const base = await this.base(); return !!base && !this.isAccessHost(base); } /** True when the live gateway is reached through Cloudflare Access, i.e. the traffic leaves the campus network. */ async offCampus(): Promise { const base = await this.base(); return !!base && this.cfg.access_hosts.includes(new URL(base).hostname); } /** Cloudflare Access headers, only for hosts that sit behind Access. */ accessHeaders(url: string): Record { if (!this.cfg.access_hosts.includes(new URL(url).hostname)) return {}; const id = readSecret(this.cfg.cf_client_id_file); const secret = readSecret(this.cfg.cf_client_secret_file); return id && secret ? { "CF-Access-Client-Id": id, "CF-Access-Client-Secret": secret } : {}; } /** * The most preferred candidate that answers `GET /models` with 2xx within 4 s (401 counts only when no key is * configured). Health paths differ per gateway (OmniRoute 3.8.50 has /healthz and /api/health, no /health); the * models route is what every OpenAI-compatible server has. Candidates are probed at the same time and picked in * list order: probing one after the other let a stalled first request over an idle VPN tunnel hand the choice to * the off-campus URL (seen live), and a 403 from Cloudflare Access must not pass for healthy. * Cached until a call fails at the network level. */ async base(): Promise { if (this.live) return this.live; const candidates = (process.env.AGENTHUB_OMNIROUTE_URL ? [process.env.AGENTHUB_OMNIROUTE_URL] : this.cfg.urls).map((u) => u.replace(/\/$/, "")); const key = this.apiKey(); const round = () => Promise.all( candidates.map((url) => fetch(`${url}/models`, { headers: { ...(key ? { authorization: `Bearer ${key}` } : {}), ...this.accessHeaders(url) }, signal: AbortSignal.timeout(4000) }).then( (r) => r.ok || (!key && r.status === 401), () => false, ), ), ); let results = await round(); // The first request over an idle VPN tunnel can stall past the timeout and work a second later (seen live, twice). if (candidates.length && !results.includes(true)) results = await round(); const url = candidates[results.indexOf(true)]; if (url) { this.log(`omniroute: using ${new URL(url).host}`); return (this.live = url); } this.log(candidates.length ? `omniroute: no candidate is healthy (${candidates.map((u) => new URL(u).host).join(", ")})` : "omniroute: no gateway configured (omniroute.urls in .agenthub/config.json, or AGENTHUB_OMNIROUTE_URL)"); return undefined; } /** Authenticated model inventory; upstream response bodies never enter diagnostics. */ async models(): Promise { const base = await this.base(); if (!base) throw new Error("no model gateway is configured or reachable (see ahub doctor)"); const key = this.apiKey(); if (!key) throw new Error("no OmniRoute API key (see ahub doctor)"); const response = await fetch(`${base}/models`, { headers: { authorization: `Bearer ${key}`, ...this.accessHeaders(base) }, signal: AbortSignal.timeout(4000) }); if (!response.ok) throw new Error(`model inventory failed: HTTP ${response.status}`); const body = await response.json() as { data?: { id?: unknown }[] }; if (!Array.isArray(body.data)) throw new Error("model inventory returned no model list"); return body.data.flatMap((m) => typeof m?.id === "string" ? [m.id] : []); } /** A listed model can still lack provider credentials: prove it accepts a minimal call before attaching. */ async checkModel(model: string, inventory?: string[]): Promise { if (!(inventory ?? await this.models()).includes(model)) throw new Error(`model ${model} is not served by the gateway`); try { await this.chat({ model, messages: [{ role: "user", content: "agent-hub model availability check: reply OK" }], max_tokens: 1 }, { signal: AbortSignal.timeout(10_000) }); } catch { throw new Error(`model ${model} is not usable (availability call failed; check gateway credentials and provider health)`); } } async chat(body: { model: string; messages: ChatMessage[]; tools?: unknown[]; max_tokens?: number; temperature?: number; reasoning_effort?: string }, opts: ChatOptions = {}): Promise { const base = await this.base(); if (!base) throw new Error("no model gateway is configured or reachable (omniroute.urls in .agenthub/config.json; see ahub doctor)"); if (opts.onCampusOnly && this.isAccessHost(base)) throw new Error("PII model calls require the confirmed campus gateway"); const headers: Record = { "content-type": "application/json" }; const key = this.apiKey(); if (!key) throw new Error("no OmniRoute API key (set OMNIROUTE_API_KEY or omniroute.api_key_file)"); Object.assign(headers, { authorization: `Bearer ${key}` }, this.accessHeaders(base)); let res: Response; try { res = await fetch(`${base}/chat/completions`, { method: "POST", headers, body: JSON.stringify({ ...body, messages: body.messages.map(({ is_error: _internalError, ...message }) => message), stream: false }), ...(opts.signal ? { signal: opts.signal } : {}), }); } catch (e) { this.live = undefined; // probe again next time: the VPN may have dropped throw e; } if (!res.ok) throw new Error(`model call failed: HTTP ${res.status} ${(await res.text()).slice(0, 300)}`); const json = (await res.json()) as { choices?: { message?: ChatMessage }[]; usage?: unknown; model?: unknown }; const message = json.choices?.[0]?.message; if (!message) throw new Error("model call returned no message"); const provider = res.headers.get("x-omniroute-provider") ?? undefined; const servedModel = safeModelLabel(json.model); const safeProvider = safeModelLabel(provider); const usage = normalizeUsage(json.usage); // reasoning_content and other extras are dropped here: only role, content and tool_calls travel on. return { message: { role: "assistant", content: message.content ?? null, ...(message.tool_calls?.length ? { tool_calls: message.tool_calls } : {}) }, ...(usage ? { usage } : {}), ...(safeProvider ? { provider: safeProvider } : {}), ...(servedModel ? { servedModel } : {}), ...(servedModel && json.model === servedModel ? { servedModelExact: true as const } : {}), }; } }