// Runpod as Idle's provider, over Runpod's REST API v2 (https://docs.runpod.io/api-reference-v2/overview). // Written from the published reference; it has never been run against the live API (see the README). // // GET /v2/catalog/gpus?include=AVAILABILITY&product=POD&cloud=SECURE prices and stock // POST /v2/pods one pod on one GPU type // GET /v2/pods/{id} status and the direct SSH address // DELETE /v2/pods/{id} terminate (204; 404 means already gone) // GET /v2/pods?limit=1000 every pod of the account // // How a renter gets in. Runpod's SSH proxy (ssh.runpod.io) only accepts the keys registered on the Runpod // account, which is Idle's account, not the renter's. So Idle never uses the proxy: it publishes the pod's // 22/tcp port and passes the renter's keys in the PUBLIC_KEY environment variable, which Runpod's official // images write to authorized_keys. The renter connects straight to the pod's sshd (`ssh.direct` in the API). // That needs a public IP, which is why pods are created on the SECURE cloud only. import { connect } from "node:net"; import { ProviderError } from "./provider.mjs"; export const RUNPOD_API = "https://api.runpod.io/v2"; /** The one image every Idle machine runs: a Runpod official image, so sshd starts from PUBLIC_KEY. */ export const RUNPOD_IMAGE = "runpod/pytorch:1.0.2-cu1281-torch280-ubuntu2404"; export const RUNPOD_CLOUD = "SECURE"; /** Container disk in GB. It is wiped when the pod ends; nothing persists between rentals. */ export const DISK_GB = 50; /** Runpod bills the container disk of a running pod on top of the GPU: 0.10 USD per GB per month. */ export const DISK_USD_PER_GB_MONTH = 0.1; const HOURS_PER_MONTH = 730; /** Idle's GPU ids (rates.mjs) and the Runpod GPU type each one is. */ export const GPU_TYPES = { "rtx-4090": "NVIDIA GeForce RTX 4090", "rtx-5090": "NVIDIA GeForce RTX 5090", l40s: "NVIDIA L40S", a100: "NVIDIA A100-SXM4-80GB", h100: "NVIDIA H100 80GB HBM3", h200: "NVIDIA H200", b200: "NVIDIA B200", }; /** True when something at host:port greets like an SSH server within `ms`. */ export function sshAnswers(host, port, ms = 3000) { return new Promise((resolve) => { const s = connect({ host, port }); const done = (ok) => { s.destroy(); resolve(ok); }; s.setTimeout(ms, () => done(false)); s.once("error", () => done(false)); s.once("data", (b) => done(b.toString("latin1").startsWith("SSH-"))); }); } /** * @param {{apiKey:string, fetch?:typeof fetch, base?:string, probe?:(host:string, port:number)=>Promise, * timeoutMs?:number}} o */ export function createRunpodProvider(o) { if (!o?.apiKey) throw new Error("RUNPOD_API_KEY is not set"); const f = o.fetch ?? fetch; const base = (o.base ?? RUNPOD_API).replace(/\/$/, ""); const probe = o.probe ?? sshAnswers; const timeoutMs = o.timeoutMs ?? 12_000; /** One call. Returns {status, json}; throws ProviderError for anything `accept` does not list. */ async function call(method, path, body, accept = [200]) { let r; try { r = await f(base + path, { method, headers: { Authorization: "Bearer " + o.apiKey, ...(body ? { "Content-Type": "application/json" } : {}) }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(timeoutMs), }); } catch (e) { throw new ProviderError("provider", "The GPU provider did not answer.", String(e?.message ?? e)); } let json = null; if (r.status !== 204) { try { json = await r.json(); } catch { json = null; } } if (accept.includes(r.status)) return { status: r.status, json }; const detail = `${method} ${path} answered ${r.status}: ${json?.detail ?? json?.title ?? "no detail"}`; // Runpod's own table for POST /v2/pods: 400 is a rule broken or no capacity for this GPU, 402 is the // provider account out of balance, 401/403 the key, 429 the rate limit. if (r.status === 400 && method === "POST") throw new ProviderError("no-capacity", "No machine of this GPU type could be placed right now.", detail); if (r.status === 402) throw new ProviderError("provider-funds", "The GPU provider refused the request.", detail); if (r.status === 401 || r.status === 403) throw new ProviderError("provider-auth", "The GPU provider refused the request.", detail); if (r.status === 409) throw new ProviderError("no-capacity", "The provider account is at its limit of machines.", detail); if (r.status === 429) throw new ProviderError("rate-limited", "The GPU provider is rate limiting. Try again in a moment.", detail); throw new ProviderError("provider", "The GPU provider answered with an error.", detail); } const diskPerHour = (DISK_GB * DISK_USD_PER_GB_MONTH) / HOURS_PER_MONTH; return { name: "runpod", real: true, async listGpus() { const { json } = await call("GET", `/catalog/gpus?include=AVAILABILITY&product=POD&cloud=${RUNPOD_CLOUD}`); const byId = new Map((json?.gpus ?? []).map((g) => [g.id, g])); const out = []; for (const [id, type] of Object.entries(GPU_TYPES)) { const g = byId.get(type); if (!g || !(g.price?.secure > 0)) continue; const stock = g.secure === false ? "none" : String(g.availability ?? "NONE").toLowerCase(); out.push({ id, name: g.name, vramGb: g.memory, // What one running pod costs Idle per hour: the GPU plus its container disk, rounded up to the micro-dollar. usdPerHour: Math.ceil((g.price.secure + diskPerHour) * 1e6 - 1e-6) / 1e6, available: stock === "none" ? 0 : 1, stock, }); } return out; }, async create({ gpuId, sshPublicKeys, name }) { const type = GPU_TYPES[gpuId]; if (!type) throw new ProviderError("provider", "Unknown GPU.", "no Runpod type for " + gpuId); if (!Array.isArray(sshPublicKeys) || sshPublicKeys.length === 0) throw new ProviderError("provider", "A machine needs an SSH key.", "no key given"); const keys = sshPublicKeys.join("\n"); const { json } = await call( "POST", "/pods", { name, image: RUNPOD_IMAGE, cloud: RUNPOD_CLOUD, gpu: { id: type, count: 1 }, disk: DISK_GB, ports: ["22/tcp"], // The renter's keys, one per line. PUBLIC_KEY is what the API reference and the official images use; // SSH_PUBLIC_KEY is the name the SSH guide gives for a per-pod override. Setting it in the request // also keeps `startSsh` from injecting the keys of Idle's own Runpod account. env: { PUBLIC_KEY: keys, SSH_PUBLIC_KEY: keys }, startSsh: true, }, [201], ); if (!json?.id) throw new ProviderError("provider", "The GPU provider answered with an error.", "pod created without an id"); return { providerId: json.id }; }, async get(providerId) { const { status, json: pod } = await call("GET", "/pods/" + encodeURIComponent(providerId), null, [200, 404]); if (status === 404 || !pod) return { status: "gone", ssh: null, startedAt: null }; const startedAt = pod.startedAt ? Date.parse(pod.startedAt) : null; // EXITED and ERROR pods still exist and still bill their disk: for Idle they are gone, and get terminated. if (pod.status === "TERMINATED" || pod.status === "EXITED" || pod.status === "ERROR") return { status: "gone", ssh: null, startedAt }; const d = pod.ssh?.direct; if (pod.status !== "RUNNING" || !d?.host || !d?.port) return { status: "starting", ssh: null, startedAt }; const ssh = { host: d.host, port: d.port, user: d.username ?? "root" }; return (await probe(ssh.host, ssh.port)) ? { status: "running", ssh, startedAt } : { status: "starting", ssh: null, startedAt }; }, async terminate(providerId) { await call("DELETE", "/pods/" + encodeURIComponent(providerId), null, [204, 404]); }, async list() { const out = []; let cursor = null; for (let page = 0; page < 20; page++) { const { json } = await call("GET", "/pods?limit=1000" + (cursor ? "&cursor=" + encodeURIComponent(cursor) : "")); for (const p of json?.pods ?? []) out.push({ providerId: p.id, name: p.name, createdAt: p.createdAt ? Date.parse(p.createdAt) : 0 }); if (!json?.pagination?.hasNextPage || !json.pagination.nextCursor) break; cursor = json.pagination.nextCursor; } return out; }, }; }