// Shared helpers for OpenRouter probes. Key comes from process.env.OPENROUTER_API_KEY (never logged). import { mkdirSync, writeFileSync } from "node:fs"; import OpenAI from "openai"; export const BASE = "https://openrouter.ai/api/v1"; export const KEY = process.env.OPENROUTER_API_KEY ?? ""; if (!KEY) { console.error("OPENROUTER_API_KEY missing (run: set -a; . ./.env; set +a)"); process.exit(1); } export const OUT = new URL("./out/", import.meta.url).pathname; mkdirSync(OUT, { recursive: true }); export const APP_HEADERS = { "HTTP-Referer": "https://www.polyllm.io", "X-Title": "PolyLLM research" }; export const client = new OpenAI({ apiKey: KEY, baseURL: BASE, timeout: 120_000, maxRetries: 0, defaultHeaders: APP_HEADERS, }); export function save(name: string, data: unknown) { writeFileSync(`${OUT}${name}`, JSON.stringify(data, null, 2)); console.log(`saved out/${name}`); } const HEADER_RE = /ratelimit|request-id|x-request|retry-after|content-type|server|date|cf-ray|x-openrouter|x-or-/i; /** Raw request; returns status, selected headers, and parsed body (never echoes the key). */ export async function raw(path: string, init: RequestInit & { key?: string } = {}) { const { key, ...rest } = init; const res = await fetch(`${BASE}${path}`, { ...rest, headers: { "Content-Type": "application/json", Authorization: `Bearer ${key ?? KEY}`, ...APP_HEADERS, ...(rest.headers ?? {}), }, }); const text = await res.text(); let body: unknown = text; try { body = JSON.parse(text); } catch {} const headers: Record = {}; res.headers.forEach((v, k) => { if (HEADER_RE.test(k)) headers[k] = v; }); return { status: res.status, headers, body }; } /** Raw SSE POST; returns parsed data events plus every comment line (": OPENROUTER PROCESSING"). */ export async function rawSSE(path: string, payload: unknown, key?: string) { const res = await fetch(`${BASE}${path}`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${key ?? KEY}`, ...APP_HEADERS }, body: JSON.stringify(payload), }); const headers: Record = {}; res.headers.forEach((v, k) => { if (HEADER_RE.test(k)) headers[k] = v; }); if (!res.ok || !res.body) { const text = await res.text(); let body: unknown = text; try { body = JSON.parse(text); } catch {} return { status: res.status, headers, error: body, events: [] as any[], comments: [] as string[] }; } const reader = res.body.getReader(); const dec = new TextDecoder(); let buf = ""; const events: { event?: string; data: any; raw?: string }[] = []; const comments: string[] = []; for (;;) { const { value, done } = await reader.read(); if (done) break; buf += dec.decode(value, { stream: true }); let idx; while ((idx = buf.indexOf("\n\n")) >= 0) { const block = buf.slice(0, idx); buf = buf.slice(idx + 2); let ev: string | undefined; const datas: string[] = []; for (const line of block.split("\n")) { if (line.startsWith(":")) comments.push(line); else if (line.startsWith("event:")) ev = line.slice(6).trim(); else if (line.startsWith("data:")) datas.push(line.slice(5).trim()); } if (!datas.length) continue; const d = datas.join("\n"); if (d === "[DONE]") { events.push({ event: ev, data: "[DONE]" }); continue; } try { events.push({ event: ev, data: JSON.parse(d) }); } catch { events.push({ event: ev, data: null, raw: d }); } } } return { status: res.status, headers, events, comments }; } export function short(s: unknown, n = 300) { const t = typeof s === "string" ? s : JSON.stringify(s) ?? String(s); return t.length > n ? t.slice(0, n) + "…" : t; }