// Shared helpers for DeepSeek probes. Key from process.env.DEEPSEEK_API_KEY (never logged). import { mkdirSync, writeFileSync } from "node:fs"; import * as zlib from "node:zlib"; import OpenAI from "openai"; export const BASE = "https://api.deepseek.com"; export const KEY = process.env.DEEPSEEK_API_KEY ?? ""; if (!KEY) { console.error("DEEPSEEK_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 client = new OpenAI({ apiKey: KEY, baseURL: BASE, timeout: 300_000, maxRetries: 0 }); export const MODELS = ["deepseek-v4-flash", "deepseek-v4-pro", "deepseek-v4-flash-vision-exp"]; export function save(name: string, data: unknown) { writeFileSync(`${OUT}${name}`, JSON.stringify(data, null, 2)); console.log(`saved out/${name}`); } export function pickHeaders(h: Headers) { const out: Record = {}; h.forEach((v, k) => { if (/ratelimit|request-id|x-request|retry-after|content-type|server|date|cf-ray|x-ds|x-deepseek|via|alt-svc/i.test(k)) out[k] = v; }); return out; } /** Raw request; returns status, selected headers, parsed body. */ export async function raw(path: string, init: RequestInit & { key?: string; base?: string } = {}) { const { key, base, ...rest } = init; const res = await fetch(`${base ?? BASE}${path}`, { ...rest, headers: { "Content-Type": "application/json", Authorization: `Bearer ${key ?? KEY}`, ...(rest.headers ?? {}) }, }); const text = await res.text(); let body: unknown = text; try { body = JSON.parse(text); } catch {} return { status: res.status, headers: pickHeaders(res.headers), body }; } /** Raw SSE POST; returns parsed data events + raw comment lines (keep-alive). */ 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}` }, body: JSON.stringify(payload), }); const headers = pickHeaders(res.headers); 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: any[] = []; 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); for (const line of block.split("\n")) { if (line.startsWith(":")) comments.push(line); else if (line.startsWith("data:")) { const d = line.slice(5).trim(); if (d === "[DONE]") events.push("[DONE]"); else { try { events.push(JSON.parse(d)); } catch { events.push({ unparsed: d }); } } } else if (line.trim()) comments.push("??" + line); } } } return { status: res.status, headers, events, comments }; } export function errInfo(e: any) { return { status: e?.status, message: e?.message, error: e?.error ?? e?.response?.data ?? null }; } /** 32x32 RGB PNG (red/blue checker) as data URL, generated with zlib. */ export function pngDataUrl(w = 32, h = 32) { const crcTable = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })(); const crc = (buf: Buffer) => { let c = 0xffffffff; for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }; const chunk = (type: string, data: Buffer) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); }; const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; const rows: Buffer[] = []; for (let y = 0; y < h; y++) { const row = Buffer.alloc(1 + w * 3); row[0] = 0; for (let x = 0; x < w; x++) { const red = ((x >> 3) + (y >> 3)) % 2 === 0; row[1 + x * 3] = red ? 220 : 30; row[2 + x * 3] = 30; row[3 + x * 3] = red ? 30 : 220; } rows.push(row); } const idat = zlib.deflateSync(Buffer.concat(rows)); const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0))]); return `data:image/png;base64,${png.toString("base64")}`; }