diff --git a/example/app/ai/OpenrouterDemo.cpp b/example/app/ai/OpenrouterDemo.cpp
index 6baa469..bf5b71e 100644
--- a/example/app/ai/OpenrouterDemo.cpp
+++ b/example/app/ai/OpenrouterDemo.cpp
@@ -1,13 +1,379 @@
#include "../AiDemos.hpp"
#include "../../fw/Router.hpp"
+#include "../../fw/Templates.hpp"
+#include "llm/error.h"
+#include "openrouter/call_plan.h"
+#include "openrouter/chat_params.h"
+#include "openrouter/chat_service.h"
+#include "openrouter/gateway.h"
+#include "openrouter/inference_services.h"
+#include "openrouter/model_ref.h"
namespace molo::example::app {
-// OpenRouter: routing, models, providers, generations, credits, keys, presets, plugins. Stub: the module agent fills this in.
+// OpenRouter over the real src/openrouter module. GET routes need no
+// credential. Every route that calls OpenRouter is a POST: 422 on bad input
+// first, then 503 not_configured without the needed key (OPENROUTER_API_KEY
+// for inference and reads, OPENROUTER_MANAGEMENT_KEY for management calls).
+// Chat, responses and messages cost money and every non-GET call of the
+// generic /ai/openrouter/call route can change an account: all of them are
+// dry runs unless the body says "confirm":true. Secrets are never echoed.
+
+namespace {
+
+namespace orr = openrouter;
+using Json = clients::body::Json;
+
+constexpr std::size_t kMaxBody = 256 * 1024;
+constexpr std::size_t kMaxShownBytes = 200 * 1024;
+
+const char kPage[] = R"ORPAGE({% extends "base.html" %}
+{% block content %}
+
OpenRouter
+One API for hundreds of models: routing, fallbacks, plugins, keys and usage.
+Paid and account-changing calls are dry runs until you tick confirm.
+Checking credentials...
+
+
+
+{% endblock %}
+)ORPAGE";
+
+fw::Response json_out(const Json& j, int status = 200) {
+ fw::Response res = fw::JsonResponse(j.dump(), status);
+ res.headers.set("Cache-Control", "no-store");
+ return res;
+}
+
+[[noreturn]] void bad(const std::string& why) { throw fw::HttpError(422, "validation_error", why); }
+
+[[noreturn]] void rethrow(const llm::ApiError& e) {
+ if (e.http_status() == 503 && e.type() == "NOT_CONFIGURED")
+ throw fw::HttpError(503, "not_configured", e.message());
+ if (e.http_status() == 400 && e.type() == "INVALID_ARGUMENT")
+ throw fw::HttpError(422, "validation_error", e.message());
+ throw fw::HttpError(502, "openrouter_error", e.type() + ": " + e.message());
+}
+
+template
+auto guarded(F&& f) -> decltype(f()) {
+ try {
+ return f();
+ } catch (const llm::ApiError& e) {
+ rethrow(e);
+ }
+}
+
+Json parse_body(const fw::Request& req) {
+ if (req.body.size() > kMaxBody) throw fw::HttpError(413, "payload_too_large", "body too large");
+ if (req.body.empty()) return Json::object();
+ try {
+ Json j = Json::parse(req.body);
+ if (!j.is_object()) bad("body must be a JSON object");
+ return j;
+ } catch (const clients::body::JsonError&) {
+ bad("body is not valid JSON");
+ }
+}
+
+std::string text(const Json& b, const char* key, bool required = false) {
+ const Json* v = b.find(key);
+ if (!v || v->is_null()) {
+ if (required) bad(std::string(key) + " is required");
+ return "";
+ }
+ if (!v->is_string()) bad(std::string(key) + " must be a string");
+ return v->as_string();
+}
+
+bool flag(const Json& b, const char* key) {
+ const Json* v = b.find(key);
+ if (!v || v->is_null()) return false;
+ if (!v->is_bool()) bad(std::string(key) + " must be true or false");
+ return v->as_bool();
+}
+
+Json object_of(const Json& b, const char* key) {
+ const Json* v = b.find(key);
+ if (!v || v->is_null()) return Json::object();
+ if (!v->is_object()) bad(std::string(key) + " must be a JSON object");
+ return *v;
+}
+
+Json dry_run(const std::string& what, const Json& planned) {
+ Json o = Json::object();
+ o.set("dry_run", Json(true));
+ o.set("would_send", Json(what));
+ o.set("request", planned);
+ o.set("hint", Json("send confirm:true to run it"));
+ return o;
+}
+
+// Redacts anything that could be a secret before it leaves the process.
+Json redact(const Json& j) {
+ if (j.is_object()) {
+ Json o = Json::object();
+ for (const auto& [k, v] : j.as_object()) {
+ bool secret = k == "key" || k == "value" || k == "api_key" || k == "subject_token" ||
+ k == "code_verifier";
+ o.set(k, secret && v.is_string() ? Json("***") : redact(v));
+ }
+ return o;
+ }
+ if (j.is_array()) {
+ Json a = Json::array();
+ for (const Json& v : j.as_array()) a.push(redact(v));
+ return a;
+ }
+ return j;
+}
+
+Json shown(const Json& j) {
+ Json r = redact(j);
+ std::string d = r.dump();
+ if (d.size() <= kMaxShownBytes) return r;
+ Json o = Json::object();
+ o.set("truncated", Json(true));
+ o.set("bytes", Json(static_cast(d.size())));
+ o.set("preview", Json(d.substr(0, 4096)));
+ return o;
+}
+
+Json planned_json(const orr::PlannedCall& p) {
+ Json o = Json::object();
+ o.set("call", Json(p.name()));
+ o.set("method", Json(p.spec->http));
+ o.set("target", Json(p.target()));
+ o.set("key", Json(p.spec->key));
+ if (p.has_body) o.set("body", shown(p.body));
+ return o;
+}
+
+orr::PathArgs path_args(const Json& b) {
+ orr::PathArgs a;
+ for (const auto& [k, v] : object_of(b, "args").as_object()) {
+ if (!v.is_string()) bad("args values must be strings");
+ a[k] = v.as_string();
+ }
+ return a;
+}
+
+orr::Query query_of(const Json& b) {
+ orr::Query q;
+ for (const auto& [k, v] : object_of(b, "query").as_object()) {
+ if (v.is_string()) q.add(k, v.as_string());
+ else if (v.is_number()) q.add(k, v.as_number());
+ else if (v.is_bool()) q.add(k, v.as_bool());
+ else bad("query values must be strings, numbers or booleans");
+ }
+ return q;
+}
+
+// Plans a table call from a request body: validation only, no credential.
+orr::PlannedCall plan_from(const Json& b) {
+ std::string name = text(b, "call", true);
+ Json body = object_of(b, "body");
+ bool has_body = b.find("body") && !b.find("body")->is_null();
+ return guarded([&] {
+ return orr::CallPlanner::plan(name, path_args(b), query_of(b), has_body ? &body : nullptr);
+ });
+}
+
+orr::ChatParams chat_from(const Json& b) {
+ std::string model = text(b, "model", true);
+ std::string prompt = text(b, "prompt", true);
+ if (prompt.size() > 16000) bad("prompt too long");
+ orr::ChatParams p = orr::ChatParams::simple(model, prompt);
+ p.max_tokens = 64; // the demo never asks for more
+ if (const Json* mt = b.find("max_tokens"); mt && !mt->is_null()) {
+ if (!mt->is_number() || mt->as_int() < 1 || mt->as_int() > 512) bad("max_tokens must be 1..512");
+ p.max_tokens = static_cast(mt->as_int());
+ }
+ if (const Json* pr = b.find("provider"); pr && !pr->is_null()) {
+ if (!pr->is_object()) bad("provider must be a JSON object");
+ p.provider = guarded([&] { return orr::ProviderPreferences::from_json(*pr); });
+ }
+ if (const Json* fb = b.find("models"); fb && !fb->is_null()) {
+ if (!fb->is_array()) bad("models must be an array");
+ for (const Json& m : fb->as_array()) {
+ if (!m.is_string()) bad("models must hold strings");
+ p.models.push_back(m.as_string());
+ }
+ }
+ guarded([&] { p.validate(); return 0; });
+ return p;
+}
+
+} // namespace
+
void register_ai_openrouter_demo(fw::Router& router, Services& services) {
- (void)router;
- (void)services;
+ auto gateway = orr::Gateway::from_env();
+ fw::Environment* env = services.templates.get();
+ services.templates->add_template("ai_openrouter.html", kPage);
+ services.add_feature("openrouter", "/ai/openrouter");
+
+ auto need_key = [gateway](orr::KeyKind kind) {
+ // Public routes also need the API key here: the demo never reaches the
+ // network without a credential.
+ if (kind == orr::KeyKind::kNone) kind = orr::KeyKind::kApi;
+ if (gateway->ready(kind)) return;
+ throw fw::HttpError(503, "not_configured",
+ std::string("set ") + (kind == orr::KeyKind::kManagement ? orr::kManagementKeyEnv : orr::kApiKeyEnv));
+ };
+
+ router.get("/ai/openrouter", "ai-openrouter-page", [env](fw::Request req) {
+ (void)req;
+ fw::TemplateCtx ctx;
+ ctx["title"] = std::string("OpenRouter");
+ return fw::Response(200, env->render("ai_openrouter.html", ctx), "text/html; charset=utf-8");
+ });
+
+ router.get("/ai/openrouter/status", "ai-openrouter-status", [gateway](fw::Request req) {
+ (void)req;
+ Json o = Json::object();
+ o.set("configured", Json(gateway->api_configured()));
+ o.set("management_configured", Json(gateway->management_configured()));
+ o.set("calls", Json(static_cast(orr::kCallCount)));
+ o.set("api_key_env", Json(orr::kApiKeyEnv));
+ o.set("management_key_env", Json(orr::kManagementKeyEnv));
+ return json_out(o);
+ });
+
+ // The spec-checked call table, for humans and for the page's call picker.
+ router.get("/ai/openrouter/calls", "ai-openrouter-calls", [](fw::Request req) {
+ (void)req;
+ Json arr = Json::array();
+ for (const orr::CallSpec& s : orr::kCalls) {
+ Json row = Json::object();
+ row.set("call", Json(s.name));
+ row.set("http", Json(s.http));
+ row.set("path", Json(s.path));
+ row.set("key", Json(s.key));
+ row.set("op", Json(s.op));
+ arr.push(row);
+ }
+ Json o = Json::object();
+ o.set("calls", arr);
+ return json_out(o);
+ });
+
+ // Validation only: shows the exact request a call would send. No network.
+ router.post("/ai/openrouter/plan", "ai-openrouter-plan", [](fw::Request req) {
+ Json b = parse_body(req);
+ return json_out(planned_json(plan_from(b)));
+ });
+
+ // Any table call. GET calls run; every other method is a dry run unless
+ // confirm:true. The credential kind follows the table row.
+ router.post("/ai/openrouter/call", "ai-openrouter-call", [gateway, need_key](fw::Request req) {
+ Json b = parse_body(req);
+ orr::PlannedCall plan = plan_from(b);
+ bool confirm = flag(b, "confirm");
+ const std::string fmt = plan.fmt();
+ if (fmt == "multipart") bad("upload files through the module API, not this route");
+ if (plan.spec->http != std::string("GET") && !confirm)
+ return json_out(dry_run(plan.name(), planned_json(plan)));
+ need_key(plan.key);
+ return guarded([&] {
+ if (fmt == "raw") {
+ llm::RawResponse raw = gateway->call_raw(plan);
+ Json o = Json::object();
+ o.set("bytes", Json(static_cast(raw.body.size())));
+ o.set("content_type", Json(raw.content_type));
+ return json_out(o);
+ }
+ return json_out(shown(gateway->call(plan)));
+ });
+ });
+
+ // Chat completion (costs money): dry run unless confirm:true.
+ router.post("/ai/openrouter/chat", "ai-openrouter-chat", [gateway, need_key](fw::Request req) {
+ Json b = parse_body(req);
+ orr::ChatParams params = chat_from(b);
+ if (!flag(b, "confirm")) return json_out(dry_run("chat", shown(params.to_json(false))));
+ need_key(orr::KeyKind::kApi);
+ return guarded([&] {
+ orr::ChatService chat(gateway);
+ orr::ChatResult r = chat.create(params);
+ Json o = Json::object();
+ o.set("id", Json(r.id));
+ o.set("model", Json(r.model));
+ o.set("provider", Json(r.provider));
+ o.set("text", Json(r.text()));
+ o.set("reasoning", Json(r.choices.empty() ? "" : r.first().reasoning));
+ o.set("finish_reason", Json(r.finish_reason()));
+ if (r.usage) {
+ Json u = Json::object();
+ u.set("input_tokens", Json(r.usage->input_tokens));
+ u.set("output_tokens", Json(r.usage->output_tokens));
+ u.set("total_tokens", Json(r.usage->total_tokens));
+ o.set("usage", u);
+ }
+ if (r.cost) o.set("cost_usd", Json(*r.cost));
+ return json_out(o);
+ });
+ });
+
+ // Responses (beta) and the Anthropic-compatible messages route: raw bodies, paid.
+ auto paid_raw = [gateway, need_key](const char* which) {
+ return [gateway, need_key, which](fw::Request req) {
+ Json b = parse_body(req);
+ Json body = object_of(b, "body");
+ bool is_messages = std::string(which) == "messages";
+ std::string call = is_messages ? "createMessages" : "createResponses";
+ orr::PlannedCall plan = guarded([&] { return orr::CallPlanner::plan(call, {}, {}, &body); });
+ if (!flag(b, "confirm")) return json_out(dry_run(call, planned_json(plan)));
+ need_key(orr::KeyKind::kApi);
+ return guarded([&] {
+ if (is_messages) return json_out(shown(orr::MessagesService(gateway).create(body)));
+ return json_out(shown(orr::ResponsesService(gateway).create(body)));
+ });
+ };
+ };
+ router.post("/ai/openrouter/responses", "ai-openrouter-responses", paid_raw("responses"));
+ router.post("/ai/openrouter/messages", "ai-openrouter-messages", paid_raw("messages"));
+
+ // Model variants: pure local parsing, no network.
+ router.post("/ai/openrouter/model-ref", "ai-openrouter-model-ref", [](fw::Request req) {
+ Json b = parse_body(req);
+ orr::ModelRef m = guarded([&] { return orr::ModelRef::parse(text(b, "model", true)); });
+ Json o = Json::object();
+ o.set("base", Json(m.base()));
+ o.set("request_id", Json(m.str()));
+ o.set("catalog_id", Json(m.catalog_id()));
+ o.set("catalog_variant", Json(m.catalog_variant()));
+ Json rv = Json::array();
+ for (const std::string& v : m.routing_variants()) rv.push(Json(v));
+ o.set("routing_variants", rv);
+ o.set("deprecated_variant", Json(m.uses_deprecated_variant()));
+ return json_out(o);
+ });
}
} // namespace molo::example::app
diff --git a/example/assets/ai_openrouter.js b/example/assets/ai_openrouter.js
new file mode 100644
index 0000000..cf967ee
--- /dev/null
+++ b/example/assets/ai_openrouter.js
@@ -0,0 +1,73 @@
+// OpenRouter page: thin client over /ai/openrouter/* (all limits server side).
+(function () {
+ "use strict";
+ var $ = function (id) { return document.getElementById(id); };
+ var out = $("or-out"), err = $("or-error");
+
+ function post(path, body) {
+ err.textContent = "";
+ out.textContent = "...";
+ return fetch(path, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }).then(function (res) {
+ return res.text().then(function (t) {
+ var j;
+ try { j = JSON.parse(t); } catch (e) { j = { message: t }; }
+ if (!res.ok) {
+ err.textContent = j.message || ("HTTP " + res.status);
+ out.textContent = "";
+ } else {
+ out.textContent = JSON.stringify(j, null, 2);
+ }
+ });
+ }).catch(function (e) { err.textContent = String(e); out.textContent = ""; });
+ }
+ function json(id) {
+ var v = $(id).value.trim();
+ if (!v) return {};
+ try { return JSON.parse(v); } catch (e) { err.textContent = "Not valid JSON: " + id; return null; }
+ }
+ function confirmed() { return $("or-confirm").checked; }
+
+ fetch("/ai/openrouter/status").then(function (r) { return r.json(); }).then(function (s) {
+ $("or-config").textContent = s.configured
+ ? "API key found" + (s.management_configured ? " and management key found." : "; no management key.")
+ : "No " + s.api_key_env + ": calls answer 503 until one is configured.";
+ });
+ fetch("/ai/openrouter/calls").then(function (r) { return r.json(); }).then(function (c) {
+ var sel = $("or-call");
+ c.calls.forEach(function (x) {
+ var o = document.createElement("option");
+ o.value = x.call;
+ o.textContent = x.http + " " + x.path + (x.key === "mgmt" ? " (management key)" : "");
+ sel.appendChild(o);
+ });
+ });
+
+ function callBody(confirm) {
+ var args = json("or-args"), query = json("or-query"), body = json("or-body");
+ if (args === null || query === null || body === null) return null;
+ var b = { call: $("or-call").value, args: args, query: query, confirm: confirm };
+ if ($("or-body").value.trim()) b.body = body;
+ return b;
+ }
+
+ $("or-chat").onclick = function () {
+ var p = json("or-provider");
+ if (p === null) return;
+ var b = { model: $("or-model").value.trim(), prompt: $("or-prompt").value, confirm: confirmed() };
+ if (Object.keys(p).length) b.provider = p;
+ post("/ai/openrouter/chat", b);
+ };
+ function read(call, query) {
+ post("/ai/openrouter/call", { call: call, query: query || {} });
+ }
+ $("or-models").onclick = function () { read("getModels", { limit: 20, sort: "newest" }); };
+ $("or-providers").onclick = function () { read("listProviders"); };
+ $("or-key").onclick = function () { read("getCurrentKey"); };
+ $("or-credits").onclick = function () { read("getCredits"); };
+ $("or-plan").onclick = function () { var b = callBody(false); if (b) post("/ai/openrouter/plan", b); };
+ $("or-send").onclick = function () { var b = callBody(confirmed()); if (b) post("/ai/openrouter/call", b); };
+})();
diff --git a/src/openrouter/SPEC.md b/src/openrouter/SPEC.md
new file mode 100644
index 0000000..ffdcfb4
--- /dev/null
+++ b/src/openrouter/SPEC.md
@@ -0,0 +1,147 @@
+# OpenRouter (src/openrouter)
+
+Namespace `molo::openrouter`. Whole public OpenRouter API
+(`https://openrouter.ai/api/v1`) over the shared `llm::ApiClient` foundation.
+Status 2026-10-24: implemented and locally tested; no OpenRouter key exists in
+this environment, so only unauthenticated routes were verified live.
+
+## Scope
+
+Chat completions (streaming incl. SSE heartbeats and mid-stream errors, tools,
+structured outputs, reasoning, usage and cost), legacy completions, the
+Responses API (beta), the Anthropic-compatible messages endpoint, routing
+(`provider` preferences, `models` fallbacks, `route`, model variants, plugins,
+server tools), models (list with every filter, one model, per-model endpoints,
+count, user models, ZDR endpoints, embedding / image / video model lists),
+providers, generation stats / content / feedback, key info, credits, activity
+and analytics, API key management, embeddings, rerank, images, video, audio
+(speech, transcription), batches, files and containers, presets, server tool
+registry and public datasets, guardrails, BYOK, workspaces and budgets,
+observability destinations, private endpoints, external users, organization
+settings, SCIM, vault secrets, OAuth (PKCE code exchange, authorization code
+creation, JWKS, workload token exchange), attribution headers, error semantics,
+`OpenrouterChatModel : llm::ChatModel`.
+
+## Module map (one class per concern)
+
+| File | Class | Concern |
+|---|---|---|
+| `calls.h` | `kCalls` | the ONE call table: 140 rows (139 spec operations + `POST /completions`) |
+| `call_plan` | `CallPlanner`, `Query`, `PlannedCall` | table-checked request planning; no network |
+| `gateway` | `Gateway`, `AnonymousClient`, `Attribution`, `Endpoint` | two keyed `ApiClient`s + keyless client, attribution headers |
+| `errors` | `ErrorBody`, `ErrorInfo` | envelope, typed `error_type`, 200-with-error shapes |
+| `model_ref` | `ModelRef` | `author/slug` + catalog (`:free :batch :thinking :extended`) and routing (`:nitro :floor :exacto :online`) variants |
+| `provider_preferences` | `ProviderPreferences` | order, only, ignore, allow_fallbacks, require_parameters, data_collection, zdr, quantizations, sort(+partition), max_price, preferred_max_latency / min_throughput, options |
+| `reasoning` | `ReasoningConfig` | `reasoning` object |
+| `plugins` | `Plugin` family | web, file-parser, response-healing, moderation, context-compression, auto-router, web-fetch, `RawPlugin` for the rest |
+| `server_tools` | `ServerTools` | function tools and `openrouter:*` server tools |
+| `chat_params` | `ChatParams`, `ResponseFormats` | validated `/chat/completions` body |
+| `chat_result`, `chat_stream` | `ChatResult`, `ChatStreamParser` | response and SSE folding |
+| `chat_service` | `ChatService` | chat + legacy completions, blocking and streaming |
+| `chat_model` | `OpenrouterChatModel` | neutral `ChatModel` |
+| `inference_services`, `stream_summary` | `ResponsesService`, `MessagesService`, stream parsers | Responses (beta) and Messages skins |
+| `models` | `ModelsService`, `ProvidersService`, `ModelFilter` | catalog |
+| `account` | `AccountService`, `GenerationService`, `KeysService` | key, credits, activity, generation stats, key management |
+| `admin` | guardrails, BYOK, workspaces, observability, private endpoints, directory, vault | management surface |
+| `platform` | embeddings, media, batches, files, presets, catalog, auth | the rest |
+| `pkce.cpp` | `PkcePair` | RFC 7636 S256 |
+
+## Credentials
+
+Two separate keys, two `ApiClient`s, never a fallback between them:
+`OPENROUTER_API_KEY` (inference and reads) and `OPENROUTER_MANAGEMENT_KEY`
+(rows with key `mgmt`). Public rows (key `none`: models, providers, counts,
+jwks, ...) go through a keyless client. Optional: `OPENROUTER_APP_URL`
+(`HTTP-Referer`, required for app attribution), `OPENROUTER_APP_TITLE`
+(`X-OpenRouter-Title` and legacy `X-Title`), `OPENROUTER_APP_CATEGORIES`
+(`X-OpenRouter-Categories`, at most 2), `OPENROUTER_BASE_URL` (https or
+loopback http only). Router metadata opt-in is `Attribution::router_metadata`
+(`X-OpenRouter-Metadata: enabled`).
+
+## Contracts
+
+- Every path, query parameter and body field goes through `CallPlanner` and
+ must be declared in `calls.h`; undeclared input is rejected before any I/O.
+- Ids are `Service::valid_id` checked (author may carry the alias marker `~`);
+ partner text (`{user}`) is 1..512 bytes, URL-encoded, `.` / `..` refused.
+- Caps live in `caps.h`; list walks (`ModelsService::list_all`) stop at
+ `kMaxModelPages` and report `truncated`.
+- Destructive calls are separate methods without defaults (`remove`,
+ `delete_*`, `unassign_*`); the demo adds a dry-run gate.
+- A top-level `error` on a 200 body and a choice with `finish_reason: "error"`
+ are thrown as `llm::ApiError` (type = `error_type` when sent, else the code).
+- Streaming: SSE comments (`: OPENROUTER PROCESSING`) are dropped by
+ `SseDecoder`; a mid-stream error is thrown after the chunks before it.
+- `Usage` maps prompt/completion/total, `prompt_tokens_details.cached_tokens`,
+ `completion_tokens_details.reasoning_tokens`; cost (USD) is on `ChatResult`.
+
+## Sources
+
+1. `https://openrouter.ai/openapi.json` (OpenAPI 3.1, info version 1.0.0,
+ fetched 2026-10-24): 139 operations, 919 schemas. Primary source.
+ Saved copy used for exploration only; the checker fetches it live.
+2. `https://openrouter.ai/docs/llms-full.txt` (docs plus generated SDK
+ references, 4.6 MB, 2026-10-24): errors guide (typed error codes, mid-stream
+ errors, 200-with-error), streaming guide (heartbeat comments), model
+ variants, plugins, app attribution, router metadata, reasoning.
+3. Live unauthenticated probes (below).
+
+Cross-checks: paths and fields come from (1) and the SDK reference pages in
+(2) (they are generated from the same document, so they are not independent
+for field lists); behavior (errors, SSE, variants, headers) comes from (2) and
+was checked against live responses where a key is not needed.
+
+## Verified against spec
+
+`python3 -I src/openrouter/tools/check_spec.py --probe` on 2026-10-24: 140
+rows checked (1 documented-only), 139 spec operations, 0 problems. The checker
+verifies method, path, operationId, public-vs-keyed (401 present), body
+fields (both directions), query parameters (both directions), multipart / form
+formats, and fails on any spec operation missing from the table.
+
+## Verified live (2026-10-24, no key)
+
+- `GET /models` 200, 469 models, `total_count` and `links.next` present;
+ pricing values are decimal strings; ids include `~alias/...` authors and
+ `:free` / `:batch` variants. `list_all` walk read the whole catalog and every
+ id parsed as a `ModelRef` (`MOLO_LIVE_NET=1 ./build/ai_test`).
+- `GET /providers` 200 (114 providers); `GET /models/count` 200;
+ `GET /models/openai/gpt-4o/endpoints` 200; `GET /model/openai/gpt-4o` 200;
+ `GET /embeddings/models`, `GET /endpoints/zdr` 200 without a key.
+- `GET /key`, `GET /credits`, `POST /chat/completions`, `POST /messages`,
+ `POST /completions` answer 401 `{"error":{"message":"No cookie auth
+ credentials found","code":401}}` (numeric code); `POST /auth/keys` with `{}`
+ answers 400 (public).
+
+## Unverified
+
+- Every authenticated response shape (chat, responses, messages, generation,
+ keys, admin lists) is taken from spec examples and docs, not seen.
+- `POST /completions` exists (401 live, docs list it under router metadata)
+ but is absent from the OpenAPI document; its field list in `calls.h` is the
+ OpenAI legacy set plus OpenRouter routing fields, inferred.
+- `reasoning.exclude` is documented but not in the spec schema; kept as sent.
+- Server tool `type` names beyond the spec's ten are accepted by form only.
+- The `grant_type` literal for `/oauth/token` (RFC 8693 URN) is the standard
+ value; the spec lists the field without an enum.
+- `models` fallback count: no vendor limit found, local ceiling 16.
+- Streaming of `/images` (`stream` field) is not parsed (raw body only).
+- Rows keyed `mgmt` follow the spec descriptions ("Management key required");
+ vault rows are keyed `api` per their securitySchemes.
+
+## Gaps
+
+- `llm::ApiError` carries no `error.metadata`, `Retry-After` or response
+ headers (foundation, `src/llm/error.h`); `describe()` works from status and
+ type only. Mid-stream and 200-with-error shapes keep full metadata via
+ `ErrorBody`.
+- `SseDecoder` drops comment lines, so heartbeats cannot be counted or
+ surfaced as progress (`src/llm/sse.cpp`).
+- `ai.mk` does not link `src/security` beyond Base64, so `pkce.cpp` carries
+ its own SHA-256 and reads `/dev/urandom`.
+- `reasoning_details` cannot round-trip through the neutral `llm::Message`;
+ tool loops with reasoning models need `ChatService` with raw messages.
+- Files upload takes the whole file in memory (`Caps` upload ceiling of the
+ foundation); no resumable upload.
+- Typed result classes exist for chat, models, endpoints, providers, key info,
+ credits, generation; other responses are returned as `Json`.
diff --git a/src/openrouter/account.cpp b/src/openrouter/account.cpp
new file mode 100644
index 0000000..57f4ac8
--- /dev/null
+++ b/src/openrouter/account.cpp
@@ -0,0 +1,287 @@
+#include "openrouter/account.h"
+
+#include
+
+#include "llm/error.h"
+#include "openrouter/caps.h"
+
+namespace molo::openrouter {
+
+namespace {
+
+[[noreturn]] void bad(const std::string& why) { throw llm::ApiError::invalid(kVendor, why); }
+
+const Json& data_of(const Json& doc) {
+ const Json* d = doc.is_object() ? doc.find("data") : nullptr;
+ if (!d || !d->is_object()) throw llm::ApiError(kVendor, 502, "BAD_RESPONSE", "response has no data object");
+ return *d;
+}
+
+std::string str(const Json& o, const char* k) {
+ const Json* v = o.is_object() ? o.find(k) : nullptr;
+ return v && v->is_string() ? v->as_string() : "";
+}
+double num(const Json& o, const char* k) {
+ const Json* v = o.is_object() ? o.find(k) : nullptr;
+ return v && v->is_number() ? v->as_number() : 0;
+}
+long integer(const Json& o, const char* k) { return static_cast(num(o, k)); }
+bool flag(const Json& o, const char* k) {
+ const Json* v = o.is_object() ? o.find(k) : nullptr;
+ return v && v->is_bool() && v->as_bool();
+}
+std::optional opt_num(const Json& o, const char* k) {
+ const Json* v = o.is_object() ? o.find(k) : nullptr;
+ if (v && v->is_number()) return v->as_number();
+ return std::nullopt;
+}
+
+bool is_hex(char c) {
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
+}
+
+void check_reset(const std::string& r) {
+ if (!r.empty() && r != "daily" && r != "weekly" && r != "monthly")
+ bad("limit_reset must be daily, weekly or monthly");
+}
+
+void check_limit_value(const std::optional& l) {
+ if (l && (!std::isfinite(*l) || *l < 0)) bad("limit must be a non-negative number");
+}
+
+} // namespace
+
+bool is_key_hash(const std::string& s) {
+ if (s.size() != 64) return false;
+ for (char c : s)
+ if (!is_hex(c)) return false;
+ return true;
+}
+
+bool is_uuid(const std::string& s) {
+ if (s.size() != 36) return false;
+ for (std::size_t i = 0; i < s.size(); ++i) {
+ if (i == 8 || i == 13 || i == 18 || i == 23) {
+ if (s[i] != '-') return false;
+ } else if (!is_hex(s[i])) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool is_iso_utc_seconds(const std::string& s) {
+ // 2027-12-31T23:59:59Z or 2027-12-31T23:59:59.123Z
+ if (s.size() < 20 || s.back() != 'Z') return false;
+ auto digit = [&](std::size_t i) { return s[i] >= '0' && s[i] <= '9'; };
+ for (std::size_t i : {0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18})
+ if (!digit(i)) return false;
+ if (s[4] != '-' || s[7] != '-' || s[10] != 'T' || s[13] != ':' || s[16] != ':') return false;
+ if (s.size() == 20) return true;
+ if (s[19] != '.' || s.size() < 22) return false;
+ for (std::size_t i = 20; i + 1 < s.size(); ++i)
+ if (!digit(i)) return false;
+ return true;
+}
+
+KeyInfo KeyInfo::parse(const Json& doc) {
+ const Json& d = data_of(doc);
+ KeyInfo k;
+ k.raw = d;
+ k.label = str(d, "label");
+ k.limit = opt_num(d, "limit");
+ k.limit_remaining = opt_num(d, "limit_remaining");
+ k.limit_reset = str(d, "limit_reset");
+ k.usage = num(d, "usage");
+ k.usage_daily = num(d, "usage_daily");
+ k.usage_weekly = num(d, "usage_weekly");
+ k.usage_monthly = num(d, "usage_monthly");
+ k.byok_usage = num(d, "byok_usage");
+ k.is_free_tier = flag(d, "is_free_tier");
+ k.is_management_key = flag(d, "is_management_key");
+ k.include_byok_in_limit = flag(d, "include_byok_in_limit");
+ k.expires_at = str(d, "expires_at");
+ k.creator_user_id = str(d, "creator_user_id");
+ k.workspace_id = str(d, "workspace_id");
+ if (const Json* v = d.find("free_model_daily_requests")) k.free_model_daily_requests = *v;
+ if (const Json* v = d.find("effective_budget")) k.effective_budget = *v;
+ if (const Json* v = d.find("budgets")) k.budgets = *v;
+ return k;
+}
+
+Credits Credits::parse(const Json& doc) {
+ const Json& d = data_of(doc);
+ Credits c;
+ c.total_credits = num(d, "total_credits");
+ c.total_usage = num(d, "total_usage");
+ return c;
+}
+
+void ActivityFilter::validate() const {
+ if (!date.empty()) {
+ bool ok = date.size() == 10 && date[4] == '-' && date[7] == '-';
+ for (std::size_t i = 0; ok && i < date.size(); ++i)
+ if (i != 4 && i != 7 && !(date[i] >= '0' && date[i] <= '9')) ok = false;
+ if (!ok) bad("date must be YYYY-MM-DD");
+ }
+ if (!api_key_hash.empty() && !is_key_hash(api_key_hash)) bad("api_key_hash must be a 64 character hex string");
+ if (user_id.size() > 128) bad("user_id too long");
+ if (!group_by.empty() && group_by != "workspace") bad("group_by must be workspace");
+ if (!workspace_id.empty() && !is_uuid(workspace_id)) bad("workspace_id must be a uuid");
+}
+
+Query ActivityFilter::to_query() const {
+ validate();
+ Query q;
+ q.add_if("date", date);
+ q.add_if("api_key_hash", api_key_hash);
+ q.add_if("user_id", user_id);
+ q.add_if("group_by", group_by);
+ q.add_if("workspace_id", workspace_id);
+ return q;
+}
+
+KeyInfo AccountService::key_info() const { return KeyInfo::parse(run("getCurrentKey")); }
+Credits AccountService::credits() const { return Credits::parse(run("getCredits")); }
+Json AccountService::activity(const ActivityFilter& f) const { return run("getUserActivity", {}, f.to_query()); }
+Json AccountService::analytics_meta() const { return run("getAnalyticsMeta"); }
+Json AccountService::analytics_query(const Json& body) const { return run("queryAnalytics", {}, {}, body); }
+
+GenerationInfo GenerationInfo::parse(const Json& doc) {
+ const Json& d = data_of(doc);
+ GenerationInfo g;
+ g.raw = d;
+ g.id = str(d, "id");
+ g.model = str(d, "model");
+ g.provider_name = str(d, "provider_name");
+ g.created_at = str(d, "created_at");
+ g.finish_reason = str(d, "finish_reason");
+ g.native_finish_reason = str(d, "native_finish_reason");
+ g.api_type = str(d, "api_type");
+ g.origin = str(d, "origin");
+ g.total_cost = num(d, "total_cost");
+ g.usage = num(d, "usage");
+ g.cache_discount = num(d, "cache_discount");
+ g.latency_ms = num(d, "latency");
+ g.generation_time_ms = num(d, "generation_time");
+ g.tokens_prompt = integer(d, "tokens_prompt");
+ g.tokens_completion = integer(d, "tokens_completion");
+ g.native_tokens_prompt = integer(d, "native_tokens_prompt");
+ g.native_tokens_completion = integer(d, "native_tokens_completion");
+ g.native_tokens_reasoning = integer(d, "native_tokens_reasoning");
+ g.native_tokens_cached = integer(d, "native_tokens_cached");
+ g.streamed = flag(d, "streamed");
+ g.cancelled = flag(d, "cancelled");
+ g.is_byok = flag(d, "is_byok");
+ if (const Json* v = d.find("provider_responses")) g.provider_responses = *v;
+ return g;
+}
+
+GenerationInfo GenerationService::get(const std::string& id) const {
+ check_id("generation", id);
+ return GenerationInfo::parse(run("getGeneration", {}, Query().add("id", id)));
+}
+
+Json GenerationService::content(const std::string& id) const {
+ check_id("generation", id);
+ return run("listGenerationContent", {}, Query().add("id", id));
+}
+
+Json GenerationService::feedback(const std::string& id, const std::string& category,
+ const std::string& comment) const {
+ check_id("generation", id);
+ static const char* const kCats[] = {"latency", "incoherence", "incorrect_response", "formatting",
+ "billing", "api_error", "other"};
+ bool ok = false;
+ for (const char* c : kCats)
+ if (category == c) ok = true;
+ if (!ok) bad("feedback category must be latency incoherence incorrect_response formatting billing api_error or other");
+ if (comment.size() > 1000) bad("feedback comment is at most 1000 characters");
+ Json b = Json::object();
+ b.set("generation_id", Json(id));
+ b.set("category", Json(category));
+ if (!comment.empty()) b.set("comment", Json(comment));
+ return run("submitGenerationFeedback", {}, {}, b);
+}
+
+void KeyDraft::validate() const {
+ if (name.empty() || name.size() > 256) bad("key name must be 1..256 characters");
+ check_limit_value(limit);
+ check_reset(limit_reset);
+ if (!expires_at.empty() && !is_iso_utc_seconds(expires_at)) bad("expires_at must be YYYY-MM-DDTHH:MM:SSZ");
+ if (!workspace_id.empty() && !is_uuid(workspace_id)) bad("workspace_id must be a uuid");
+ if (external_user.size() > 512) bad("external user too long");
+}
+
+Json KeyDraft::to_json() const {
+ validate();
+ Json b = Json::object();
+ b.set("name", Json(name));
+ if (limit) b.set("limit", Json(*limit));
+ if (!limit_reset.empty()) b.set("limit_reset", Json(limit_reset));
+ if (include_byok_in_limit) b.set("include_byok_in_limit", Json(*include_byok_in_limit));
+ if (!expires_at.empty()) b.set("expires_at", Json(expires_at));
+ if (!workspace_id.empty()) b.set("workspace_id", Json(workspace_id));
+ if (!creator_user_id.empty()) b.set("creator_user_id", Json(creator_user_id));
+ if (!external_user.empty()) {
+ Json e = Json::object();
+ e.set("user", Json(external_user));
+ b.set("external", e);
+ }
+ return b;
+}
+
+void KeyUpdate::validate() const {
+ if (name && (name->empty() || name->size() > 256)) bad("key name must be 1..256 characters");
+ check_limit_value(limit);
+ check_reset(limit_reset);
+ if (clear_limit_reset && !limit_reset.empty()) bad("limit_reset and clear_limit_reset together");
+ if (!workspace_id.empty() && !is_uuid(workspace_id)) bad("workspace_id must be a uuid");
+}
+
+Json KeyUpdate::to_json() const {
+ validate();
+ Json b = Json::object();
+ if (name) b.set("name", Json(*name));
+ if (disabled) b.set("disabled", Json(*disabled));
+ if (limit) b.set("limit", Json(*limit));
+ if (!limit_reset.empty()) b.set("limit_reset", Json(limit_reset));
+ if (clear_limit_reset) b.set("limit_reset", Json());
+ if (include_byok_in_limit) b.set("include_byok_in_limit", Json(*include_byok_in_limit));
+ if (!workspace_id.empty()) b.set("workspace_id", Json(workspace_id));
+ if (b.as_object().empty()) bad("nothing to update");
+ return b;
+}
+
+Json KeysService::list(std::optional offset, std::optional limit, bool include_disabled,
+ bool include_expired, const std::string& workspace_id) const {
+ if (offset && *offset < 0) bad("offset must be >= 0");
+ if (limit && (*limit < 1 || *limit > Caps::kMaxKeysLimit)) bad("limit must be 1..100");
+ if (!workspace_id.empty() && !is_uuid(workspace_id)) bad("workspace_id must be a uuid");
+ Query q;
+ if (offset) q.add("offset", *offset);
+ if (limit) q.add("limit", *limit);
+ if (include_disabled) q.add("include_disabled", true);
+ if (include_expired) q.add("include_expired", true);
+ q.add_if("workspace_id", workspace_id);
+ return run("listKeys", {}, q);
+}
+
+Json KeysService::get(const std::string& h) const {
+ if (!is_key_hash(h)) bad("key hash must be a 64 character hex string");
+ return run("getKey", {{"hash", h}});
+}
+
+Json KeysService::create(const KeyDraft& draft) const { return run("createKeys", {}, {}, draft.to_json()); }
+
+Json KeysService::update(const std::string& h, const KeyUpdate& u) const {
+ if (!is_key_hash(h)) bad("key hash must be a 64 character hex string");
+ return run("updateKeys", {{"hash", h}}, {}, u.to_json());
+}
+
+Json KeysService::remove(const std::string& h) const {
+ if (!is_key_hash(h)) bad("key hash must be a 64 character hex string");
+ return run("deleteKeys", {{"hash", h}});
+}
+
+} // namespace molo::openrouter
diff --git a/src/openrouter/account.h b/src/openrouter/account.h
new file mode 100644
index 0000000..7b58fa8
--- /dev/null
+++ b/src/openrouter/account.h
@@ -0,0 +1,153 @@
+#pragma once
+
+// Account and usage: GET /key (the calling key), GET /credits (management
+// key), GET /activity and the analytics routes (management key), generation
+// stats (GET /generation?id=, content, feedback), and API key management
+// (GET/POST /keys, GET/PATCH/DELETE /keys/{hash}; management key only).
+
+#include
+#include
+#include
+
+#include "openrouter/gateway.h"
+
+namespace molo::openrouter {
+
+struct KeyInfo {
+ std::string label;
+ std::optional limit; // USD, null: no limit
+ std::optional limit_remaining;
+ std::string limit_reset; // daily weekly monthly or ""
+ double usage = 0, usage_daily = 0, usage_weekly = 0, usage_monthly = 0; // USD
+ double byok_usage = 0;
+ bool is_free_tier = false;
+ bool is_management_key = false;
+ bool include_byok_in_limit = false;
+ std::string expires_at;
+ std::string creator_user_id;
+ std::string workspace_id;
+ Json free_model_daily_requests; // {limit, remaining, used}
+ Json effective_budget; // the budget that blocks first, or null
+ Json budgets; // every budget layer, enforcement order
+ Json raw;
+ static KeyInfo parse(const Json& doc); // doc is the response; reads `data`
+};
+
+struct Credits {
+ double total_credits = 0;
+ double total_usage = 0;
+ double remaining() const { return total_credits - total_usage; }
+ static Credits parse(const Json& doc);
+};
+
+// Query for GET /activity (last 30 days, grouped by endpoint).
+struct ActivityFilter {
+ std::string date; // YYYY-MM-DD, within the last 30 days
+ std::string api_key_hash; // SHA-256 hex
+ std::string user_id; // org member
+ std::string group_by; // "", workspace
+ std::string workspace_id; // uuid
+ void validate() const;
+ Query to_query() const;
+};
+
+class AccountService : public Endpoint {
+ public:
+ explicit AccountService(std::shared_ptr g) : Endpoint(std::move(g)) {}
+ KeyInfo key_info() const; // OPENROUTER_API_KEY
+ Credits credits() const; // OPENROUTER_MANAGEMENT_KEY
+ Json activity(const ActivityFilter& filter = {}) const; // management key
+ Json analytics_meta() const; // management key
+ Json analytics_query(const Json& body) const; // management key
+};
+
+struct GenerationInfo {
+ std::string id;
+ std::string model;
+ std::string provider_name;
+ std::string created_at;
+ std::string finish_reason;
+ std::string native_finish_reason;
+ std::string api_type;
+ std::string origin;
+ double total_cost = 0; // USD
+ double usage = 0;
+ double cache_discount = 0;
+ double latency_ms = 0;
+ double generation_time_ms = 0;
+ long tokens_prompt = 0, tokens_completion = 0;
+ long native_tokens_prompt = 0, native_tokens_completion = 0;
+ long native_tokens_reasoning = 0, native_tokens_cached = 0;
+ bool streamed = false;
+ bool cancelled = false;
+ bool is_byok = false;
+ Json provider_responses;
+ Json raw;
+ static GenerationInfo parse(const Json& doc); // reads `data`
+};
+
+class GenerationService : public Endpoint {
+ public:
+ explicit GenerationService(std::shared_ptr g) : Endpoint(std::move(g)) {}
+ // id is the "gen-..." id of a completion (ChatResult::id). Stats can lag the
+ // completion by a moment: a 404 right after the call is not a failure.
+ GenerationInfo get(const std::string& generation_id) const;
+ // Stored prompt, completion and error content; needs input/output logging.
+ Json content(const std::string& generation_id) const;
+ // categories: latency incoherence incorrect_response formatting billing api_error other.
+ // Uses the management key (per the spec text).
+ Json feedback(const std::string& generation_id, const std::string& category,
+ const std::string& comment = "") const;
+};
+
+// Body of POST /keys.
+struct KeyDraft {
+ std::string name; // required
+ std::optional limit; // USD
+ std::string limit_reset; // "", daily, weekly, monthly
+ std::optional include_byok_in_limit;
+ std::string expires_at; // YYYY-MM-DDTHH:MM:SSZ (seconds required)
+ std::string workspace_id; // uuid
+ std::string creator_user_id;
+ std::string external_user; // partner attribution
+ void validate() const;
+ Json to_json() const;
+};
+
+// Body of PATCH /keys/{hash}; only the set fields are sent.
+struct KeyUpdate {
+ std::optional name;
+ std::optional disabled;
+ std::optional limit;
+ std::string limit_reset; // "", daily, weekly, monthly
+ bool clear_limit_reset = false; // send limit_reset:null
+ std::optional include_byok_in_limit;
+ std::string workspace_id;
+ void validate() const;
+ Json to_json() const;
+};
+
+class KeysService : public Endpoint {
+ public:
+ // Keys are managed with OPENROUTER_MANAGEMENT_KEY, never the inference key.
+ explicit KeysService(std::shared_ptr g) : Endpoint(std::move(g), KeyKind::kManagement) {}
+ // limit 1..100 (vendor), offset >= 0.
+ Json list(std::optional offset = std::nullopt, std::optional limit = std::nullopt,
+ bool include_disabled = false, bool include_expired = false,
+ const std::string& workspace_id = "") const;
+ Json get(const std::string& key_hash) const;
+ // The response carries the new secret `key` exactly once. Callers must not log it.
+ Json create(const KeyDraft& draft) const;
+ Json update(const std::string& key_hash, const KeyUpdate& update) const;
+ // Irreversible. No default; the caller decides.
+ Json remove(const std::string& key_hash) const;
+};
+
+// True for a 64-character lowercase or uppercase hex string (SHA-256).
+bool is_key_hash(const std::string& s);
+// "YYYY-MM-DDTHH:MM:SS[.fff]Z" shape check (seconds required).
+bool is_iso_utc_seconds(const std::string& s);
+// UUID 8-4-4-4-12 hex shape check.
+bool is_uuid(const std::string& s);
+
+} // namespace molo::openrouter
diff --git a/src/openrouter/admin.cpp b/src/openrouter/admin.cpp
new file mode 100644
index 0000000..f974ea5
--- /dev/null
+++ b/src/openrouter/admin.cpp
@@ -0,0 +1,332 @@
+#include "openrouter/admin.h"
+
+#include "llm/error.h"
+#include "openrouter/account.h"
+#include "openrouter/caps.h"
+
+namespace molo::openrouter {
+
+namespace {
+
+[[noreturn]] void bad(const std::string& why) { throw llm::ApiError::invalid(kVendor, why); }
+
+Json string_list_body(const char* key, const std::vector& values, bool hashes = false) {
+ if (values.empty()) bad(std::string(key) + " must not be empty");
+ if (values.size() > Caps::kMaxBulkIds) bad(std::string(key) + " has too many entries");
+ Json a = Json::array();
+ for (const std::string& v : values) {
+ if (hashes ? !is_key_hash(v) : (v.empty() || v.size() > 256)) bad(std::string(key) + " has a malformed entry");
+ a.push(Json(v));
+ }
+ Json b = Json::object();
+ b.set(key, a);
+ return b;
+}
+
+void check_body(const Json& body, const char* what) {
+ if (!body.is_object() || body.as_object().empty()) bad(std::string(what) + " needs a non-empty JSON object");
+}
+
+Json secret_body(const std::string& value, const std::vector& hosts) {
+ if (value.empty() || value.size() > 65536) bad("secret value must be 1..65536 characters");
+ if (hosts.empty() || hosts.size() > 100) bad("secret hosts must hold 1..100 hostnames");
+ Json h = Json::array();
+ for (const std::string& host : hosts) {
+ if (host.empty() || host.size() > 254) bad("secret host must be 1..254 characters");
+ for (char c : host)
+ if (c == '/' || c == ':' || c == '*' || c == ' ') bad("secret host must be a bare hostname");
+ h.push(Json(host));
+ }
+ Json b = Json::object();
+ b.set("value", Json(value));
+ b.set("hosts", h);
+ return b;
+}
+
+} // namespace
+
+Query page_query(std::optional offset, std::optional limit, int max_limit) {
+ if (offset && *offset < 0) bad("offset must be >= 0");
+ if (limit && (*limit < 1 || *limit > max_limit)) bad("limit must be 1.." + std::to_string(max_limit));
+ Query q;
+ if (offset) q.add("offset", *offset);
+ if (limit) q.add("limit", *limit);
+ return q;
+}
+
+// --- guardrails ------------------------------------------------------------
+
+Json GuardrailsService::list(std::optional o, std::optional l, const std::string& ws) const {
+ Query q = page_query(o, l);
+ if (!ws.empty() && !is_uuid(ws)) bad("workspace_id must be a uuid");
+ q.add_if("workspace_id", ws);
+ return run("listGuardrails", {}, q);
+}
+Json GuardrailsService::get(const std::string& id) const { return run("getGuardrail", {{"id", id}}); }
+Json GuardrailsService::create(const Json& body) const {
+ check_body(body, "guardrail");
+ if (!body.has("name")) bad("guardrail needs a name");
+ return run("createGuardrail", {}, {}, body);
+}
+Json GuardrailsService::update(const std::string& id, const Json& body) const {
+ check_body(body, "guardrail update");
+ return run("updateGuardrail", {{"id", id}}, {}, body);
+}
+Json GuardrailsService::remove(const std::string& id) const { return run("deleteGuardrail", {{"id", id}}); }
+Json GuardrailsService::key_assignments(const std::string& id, std::optional o, std::optional l) const {
+ return run("listGuardrailKeyAssignments", {{"id", id}}, page_query(o, l));
+}
+Json GuardrailsService::assign_keys(const std::string& id, const std::vector& h) const {
+ return run("bulkAssignKeysToGuardrail", {{"id", id}}, {}, string_list_body("key_hashes", h, true));
+}
+Json GuardrailsService::unassign_keys(const std::string& id, const std::vector& h) const {
+ return run("bulkUnassignKeysFromGuardrail", {{"id", id}}, {}, string_list_body("key_hashes", h, true));
+}
+Json GuardrailsService::member_assignments(const std::string& id, std::optional o, std::optional l) const {
+ return run("listGuardrailMemberAssignments", {{"id", id}}, page_query(o, l));
+}
+Json GuardrailsService::assign_members(const std::string& id, const std::vector& u) const {
+ return run("bulkAssignMembersToGuardrail", {{"id", id}}, {}, string_list_body("member_user_ids", u));
+}
+Json GuardrailsService::unassign_members(const std::string& id, const std::vector& u) const {
+ return run("bulkUnassignMembersFromGuardrail", {{"id", id}}, {}, string_list_body("member_user_ids", u));
+}
+Json GuardrailsService::all_key_assignments(std::optional o, std::optional l) const {
+ return run("listKeyAssignments", {}, page_query(o, l));
+}
+Json GuardrailsService::all_member_assignments(std::optional o, std::optional l) const {
+ return run("listMemberAssignments", {}, page_query(o, l));
+}
+
+// --- BYOK ------------------------------------------------------------------
+
+Json ByokService::list(std::optional o, std::optional l, const std::string& ws,
+ const std::string& provider) const {
+ Query q = page_query(o, l);
+ if (!ws.empty() && !is_uuid(ws)) bad("workspace_id must be a uuid");
+ q.add_if("workspace_id", ws);
+ q.add_if("provider", provider);
+ return run("listBYOKKeys", {}, q);
+}
+Json ByokService::get(const std::string& id) const { return run("getBYOKKey", {{"id", id}}); }
+Json ByokService::create(const Json& body) const {
+ check_body(body, "BYOK credential");
+ if (!body.has("provider") || !body.has("key")) bad("BYOK credential needs provider and key");
+ return run("createBYOKKey", {}, {}, body);
+}
+Json ByokService::update(const std::string& id, const Json& body) const {
+ check_body(body, "BYOK update");
+ return run("updateBYOKKey", {{"id", id}}, {}, body);
+}
+Json ByokService::remove(const std::string& id) const { return run("deleteBYOKKey", {{"id", id}}); }
+
+// --- workspaces ------------------------------------------------------------
+
+bool WorkspacesService::valid_interval(const std::string& i) {
+ return i == "daily" || i == "weekly" || i == "monthly" || i == "lifetime";
+}
+Json WorkspacesService::list(std::optional o, std::optional l) const {
+ return run("listWorkspaces", {}, page_query(o, l));
+}
+Json WorkspacesService::get(const std::string& id) const { return run("getWorkspace", {{"id", id}}); }
+Json WorkspacesService::create(const Json& body) const {
+ check_body(body, "workspace");
+ if (!body.has("name") || !body.has("slug")) bad("workspace needs name and slug");
+ return run("createWorkspace", {}, {}, body);
+}
+Json WorkspacesService::update(const std::string& id, const Json& body) const {
+ check_body(body, "workspace update");
+ return run("updateWorkspace", {{"id", id}}, {}, body);
+}
+Json WorkspacesService::remove(const std::string& id, bool confirm_default) const {
+ Query q;
+ if (confirm_default) q.add("confirm_default_workspace_deletion", true);
+ return run("deleteWorkspace", {{"id", id}}, q);
+}
+Json WorkspacesService::members(const std::string& id, std::optional o, std::optional l) const {
+ return run("listWorkspaceMembers", {{"id", id}}, page_query(o, l));
+}
+Json WorkspacesService::add_members(const std::string& id, const std::vector& u) const {
+ return run("bulkAddWorkspaceMembers", {{"id", id}}, {}, string_list_body("user_ids", u));
+}
+Json WorkspacesService::remove_members(const std::string& id, const std::vector& u) const {
+ return run("bulkRemoveWorkspaceMembers", {{"id", id}}, {}, string_list_body("user_ids", u));
+}
+Json WorkspacesService::budgets(const std::string& ref) const {
+ return run("listWorkspaceBudgets", {{"workspace_ref", ref}});
+}
+Json WorkspacesService::budget(const std::string& ref, const std::string& interval) const {
+ if (!valid_interval(interval)) bad("interval must be daily weekly monthly or lifetime");
+ return run("getWorkspaceBudget", {{"workspace_ref", ref}, {"interval", interval}});
+}
+Json WorkspacesService::set_budget(const std::string& ref, const std::string& interval, double limit_usd,
+ std::optional include_byok) const {
+ if (!valid_interval(interval)) bad("interval must be daily weekly monthly or lifetime");
+ if (!(limit_usd > 0)) bad("limit_usd must be greater than 0");
+ Json b = Json::object();
+ b.set("limit_usd", Json(limit_usd));
+ if (include_byok) b.set("include_byok_in_budgets", Json(*include_byok));
+ return run("upsertWorkspaceBudget", {{"workspace_ref", ref}, {"interval", interval}}, {}, b);
+}
+Json WorkspacesService::remove_budget(const std::string& ref, const std::string& interval) const {
+ if (!valid_interval(interval)) bad("interval must be daily weekly monthly or lifetime");
+ return run("deleteWorkspaceBudget", {{"workspace_ref", ref}, {"interval", interval}});
+}
+
+// --- observability -----------------------------------------------------------
+
+Json ObservabilityService::list(std::optional o, std::optional l, const std::string& ws) const {
+ Query q = page_query(o, l);
+ if (!ws.empty() && !is_uuid(ws)) bad("workspace_id must be a uuid");
+ q.add_if("workspace_id", ws);
+ return run("listObservabilityDestinations", {}, q);
+}
+Json ObservabilityService::get(const std::string& id) const {
+ return run("getObservabilityDestination", {{"id", id}});
+}
+Json ObservabilityService::create(const Json& body) const {
+ check_body(body, "observability destination");
+ if (!body.has("type") || !body.has("name") || !body.has("config"))
+ bad("observability destination needs type, name and config");
+ return run("createObservabilityDestination", {}, {}, body);
+}
+Json ObservabilityService::update(const std::string& id, const Json& body) const {
+ check_body(body, "observability update");
+ return run("updateObservabilityDestination", {{"id", id}}, {}, body);
+}
+Json ObservabilityService::remove(const std::string& id) const {
+ return run("deleteObservabilityDestination", {{"id", id}});
+}
+
+// --- private endpoints ---------------------------------------------------------
+
+Json PrivateEndpointsService::list() const { return run("listPrivateEndpoints"); }
+Json PrivateEndpointsService::get(const std::string& id) const { return run("getPrivateEndpoint", {{"id", id}}); }
+Json PrivateEndpointsService::create(const Json& body) const {
+ check_body(body, "private endpoint");
+ return run("createPrivateEndpoint", {}, {}, body);
+}
+Json PrivateEndpointsService::update(const std::string& id, const Json& body) const {
+ check_body(body, "private endpoint update");
+ return run("updatePrivateEndpoint", {{"id", id}}, {}, body);
+}
+Json PrivateEndpointsService::remove(const std::string& id, bool draft_only) const {
+ Query q;
+ if (draft_only) q.add("draft_only", true);
+ return run("deletePrivateEndpoint", {{"id", id}}, q);
+}
+Json PrivateEndpointsService::activate(const std::string& id) const { return run("activatePrivateEndpoint", {{"id", id}}); }
+Json PrivateEndpointsService::enable(const std::string& id) const { return run("enablePrivateEndpoint", {{"id", id}}); }
+Json PrivateEndpointsService::disable(const std::string& id) const { return run("disablePrivateEndpoint", {{"id", id}}); }
+Json PrivateEndpointsService::set_pricing(const std::string& id, const Json& pricing) const {
+ check_body(pricing, "pricing");
+ Json b = Json::object();
+ b.set("pricing", pricing);
+ return run("updatePrivateEndpointPricing", {{"id", id}}, {}, b);
+}
+Json PrivateEndpointsService::validate(const std::string& id, const std::string& ws) const {
+ if (!ws.empty() && !is_uuid(ws)) bad("workspace_id must be a uuid");
+ if (ws.empty()) return run("validatePrivateEndpoint", {{"id", id}}, {}, Json::object());
+ Json b = Json::object();
+ b.set("workspace_id", Json(ws));
+ return run("validatePrivateEndpoint", {{"id", id}}, {}, b);
+}
+
+// --- directory ---------------------------------------------------------------------
+
+Json DirectoryService::external_users(std::optional o, std::optional l, const std::string& user,
+ bool include_inactive) const {
+ Query q = page_query(o, l);
+ q.add_if("user", user);
+ if (include_inactive) q.add("include_inactive", true);
+ return run("listExternalUsers", {}, q);
+}
+Json DirectoryService::external_user(const std::string& user) const { return run("getExternalUser", {{"user", user}}); }
+Json DirectoryService::register_external_user(const std::string& user) const {
+ if (user.empty() || user.size() > 512 || user.find('\0') != std::string::npos)
+ bad("external user must be 1..512 characters without NUL");
+ Json b = Json::object();
+ b.set("user", Json(user));
+ return run("createExternalUser", {}, {}, b);
+}
+Json DirectoryService::set_external_user_active(const std::string& user, bool active) const {
+ Json b = Json::object();
+ b.set("is_active", Json(active));
+ return run("updateExternalUser", {{"user", user}}, {}, b);
+}
+Json DirectoryService::deactivate_external_user(const std::string& user) const {
+ return run("deleteExternalUser", {{"user", user}});
+}
+Json DirectoryService::organization_members(std::optional o, std::optional l) const {
+ return run("listOrganizationMembers", {}, page_query(o, l));
+}
+Json DirectoryService::organization_settings() const { return run("getOrganizationSettings"); }
+Json DirectoryService::set_filtered_model_catalog(bool enabled) const {
+ Json b = Json::object();
+ b.set("is_filtered_model_catalog_enabled", Json(enabled));
+ return run("updateOrganizationSettings", {}, {}, b);
+}
+Json DirectoryService::scim_group_mappings(std::optional o, std::optional l) const {
+ return run("listScimGroupMappings", {}, page_query(o, l));
+}
+Json DirectoryService::scim_group_mapping(const std::string& id) const {
+ return run("getScimGroupMapping", {{"id", id}});
+}
+Json DirectoryService::create_scim_group_mapping(const Json& body) const {
+ check_body(body, "SCIM group mapping");
+ if (!body.has("scim_group_id") || !body.has("role")) bad("SCIM group mapping needs scim_group_id and role");
+ return run("createScimGroupMapping", {}, {}, body);
+}
+Json DirectoryService::update_scim_group_mapping(const std::string& id, const std::string& role) const {
+ if (role.empty()) bad("role must not be empty");
+ Json b = Json::object();
+ b.set("role", Json(role));
+ return run("updateScimGroupMapping", {{"id", id}}, {}, b);
+}
+Json DirectoryService::remove_scim_group_mapping(const std::string& id, bool keep_members) const {
+ Query q;
+ if (keep_members) q.add("keep_members", true);
+ return run("deleteScimGroupMapping", {{"id", id}}, q);
+}
+Json DirectoryService::scim_groups(std::optional o, std::optional l, const std::string& display_name,
+ const std::string& external_id) const {
+ Query q = page_query(o, l);
+ q.add_if("display_name", display_name);
+ q.add_if("external_id", external_id);
+ return run("listScimGroups", {}, q);
+}
+Json DirectoryService::start_scim_sync() const { return run("createScimSyncJob"); }
+Json DirectoryService::scim_sync_job(const std::string& id) const { return run("getScimSyncJob", {{"id", id}}); }
+
+// --- vault -----------------------------------------------------------------------------
+
+Json VaultService::secrets(std::optional o, std::optional l) const {
+ return run("listVaultSecrets", {}, page_query(o, l));
+}
+Json VaultService::put_secret(const std::string& name, const std::string& value,
+ const std::vector& hosts) const {
+ return run("storeVaultSecret", {{"name", name}}, {}, secret_body(value, hosts));
+}
+Json VaultService::delete_secret(const std::string& name) const { return run("deleteVaultSecret", {{"name", name}}); }
+Json VaultService::intern_secrets(const std::string& intern, std::optional o, std::optional l) const {
+ return run("listInternVaultSecrets", {{"internId", intern}}, page_query(o, l));
+}
+Json VaultService::intern_effective_secrets(const std::string& intern, std::optional o,
+ std::optional l) const {
+ return run("listInternEffectiveVaultSecrets", {{"internId", intern}}, page_query(o, l));
+}
+Json VaultService::intern_connections(const std::string& intern) const {
+ return run("listInternConnections", {{"internId", intern}});
+}
+Json VaultService::put_intern_secret(const std::string& intern, const std::string& name,
+ const std::string& value, const std::vector& hosts) const {
+ return run("storeInternVaultSecret", {{"internId", intern}, {"name", name}}, {}, secret_body(value, hosts));
+}
+Json VaultService::delete_intern_secret(const std::string& intern, const std::string& name) const {
+ return run("deleteInternVaultSecret", {{"internId", intern}, {"name", name}});
+}
+Json VaultService::copy_secrets_to_intern(const std::string& intern, const std::vector& names) const {
+ return run("copyVaultSecretsToIntern", {{"internId", intern}}, {}, string_list_body("names", names));
+}
+
+} // namespace molo::openrouter
diff --git a/src/openrouter/admin.h b/src/openrouter/admin.h
new file mode 100644
index 0000000..6212979
--- /dev/null
+++ b/src/openrouter/admin.h
@@ -0,0 +1,155 @@
+#pragma once
+
+// Management surface. All classes here use OPENROUTER_MANAGEMENT_KEY (the
+// separate management / provisioning key), except VaultService, which the
+// spec secures with the normal API key. Request bodies are JSON objects whose
+// top level keys are checked against the call table (calls.h); the large
+// nested shapes (guardrail content filters, observability destination
+// configs, private endpoint pricing) are passed through as given.
+//
+// Every class that can change or delete something exposes those calls as
+// separate explicit methods (create, update, remove, ...), never with a
+// default. The demo layer adds the dry-run gate.
+
+#include
+#include
+#include
+
+#include "openrouter/gateway.h"
+
+namespace molo::openrouter {
+
+// offset >= 0, limit 1..max_limit; throws llm::ApiError::invalid otherwise.
+Query page_query(std::optional offset, std::optional limit, int max_limit = 1000);
+
+class GuardrailsService : public Endpoint {
+ public:
+ explicit GuardrailsService(std::shared_ptr g) : Endpoint(std::move(g), KeyKind::kManagement) {}
+ Json list(std::optional offset = std::nullopt, std::optional limit = std::nullopt,
+ const std::string& workspace_id = "") const;
+ Json get(const std::string& id) const;
+ Json create(const Json& body) const; // name is required by the spec
+ Json update(const std::string& id, const Json& body) const;
+ Json remove(const std::string& id) const;
+ Json key_assignments(const std::string& id, std::optional offset = std::nullopt,
+ std::optional limit = std::nullopt) const;
+ Json assign_keys(const std::string& id, const std::vector& key_hashes) const;
+ Json unassign_keys(const std::string& id, const std::vector& key_hashes) const;
+ Json member_assignments(const std::string& id, std::optional offset = std::nullopt,
+ std::optional limit = std::nullopt) const;
+ Json assign_members(const std::string& id, const std::vector& user_ids) const;
+ Json unassign_members(const std::string& id, const std::vector& user_ids) const;
+ Json all_key_assignments(std::optional offset = std::nullopt, std::optional limit = std::nullopt) const;
+ Json all_member_assignments(std::optional offset = std::nullopt, std::optional limit = std::nullopt) const;
+};
+
+// BYOK: provider credentials you bring. create() sends a provider secret in
+// `key`; it is never echoed back and must never be logged.
+class ByokService : public Endpoint {
+ public:
+ explicit ByokService(std::shared_ptr g) : Endpoint(std::move(g), KeyKind::kManagement) {}
+ Json list(std::optional offset = std::nullopt, std::optional limit = std::nullopt,
+ const std::string& workspace_id = "", const std::string& provider = "") const;
+ Json get(const std::string& id) const;
+ Json create(const Json& body) const;
+ Json update(const std::string& id, const Json& body) const;
+ Json remove(const std::string& id) const;
+};
+
+class WorkspacesService : public Endpoint {
+ public:
+ explicit WorkspacesService(std::shared_ptr g) : Endpoint(std::move(g), KeyKind::kManagement) {}
+ Json list(std::optional offset = std::nullopt, std::optional limit = std::nullopt) const;
+ Json get(const std::string& id) const;
+ Json create(const Json& body) const;
+ Json update(const std::string& id, const Json& body) const;
+ // The default workspace is only deleted when confirm_default is true.
+ Json remove(const std::string& id, bool confirm_default) const;
+ Json members(const std::string& id, std::optional offset = std::nullopt,
+ std::optional limit = std::nullopt) const;
+ Json add_members(const std::string& id, const std::vector& user_ids) const;
+ Json remove_members(const std::string& id, const std::vector& user_ids) const;
+ Json budgets(const std::string& workspace_ref) const;
+ Json budget(const std::string& workspace_ref, const std::string& interval) const;
+ // interval: daily weekly monthly lifetime. limit_usd > 0.
+ Json set_budget(const std::string& workspace_ref, const std::string& interval, double limit_usd,
+ std::optional include_byok_in_budgets = std::nullopt) const;
+ Json remove_budget(const std::string& workspace_ref, const std::string& interval) const;
+ static bool valid_interval(const std::string& interval);
+};
+
+class ObservabilityService : public Endpoint {
+ public:
+ explicit ObservabilityService(std::shared_ptr g) : Endpoint(std::move(g), KeyKind::kManagement) {}
+ Json list(std::optional offset = std::nullopt, std::optional limit = std::nullopt,
+ const std::string& workspace_id = "") const;
+ Json get(const std::string& id) const;
+ Json create(const Json& body) const;
+ Json update(const std::string& id, const Json& body) const;
+ Json remove(const std::string& id) const;
+};
+
+class PrivateEndpointsService : public Endpoint {
+ public:
+ explicit PrivateEndpointsService(std::shared_ptr g) : Endpoint(std::move(g), KeyKind::kManagement) {}
+ Json list() const;
+ Json get(const std::string& id) const;
+ Json create(const Json& body) const;
+ Json update(const std::string& id, const Json& body) const;
+ Json remove(const std::string& id, bool draft_only) const;
+ Json activate(const std::string& id) const;
+ Json enable(const std::string& id) const;
+ Json disable(const std::string& id) const;
+ Json set_pricing(const std::string& id, const Json& pricing) const;
+ Json validate(const std::string& id, const std::string& workspace_id = "") const;
+};
+
+// End users (external users), organization and SCIM.
+class DirectoryService : public Endpoint {
+ public:
+ explicit DirectoryService(std::shared_ptr g) : Endpoint(std::move(g), KeyKind::kManagement) {}
+ // External users.
+ Json external_users(std::optional offset = std::nullopt, std::optional limit = std::nullopt,
+ const std::string& user = "", bool include_inactive = false) const;
+ Json external_user(const std::string& user) const;
+ Json register_external_user(const std::string& user) const;
+ Json set_external_user_active(const std::string& user, bool active) const;
+ Json deactivate_external_user(const std::string& user) const;
+ // Organization.
+ Json organization_members(std::optional offset = std::nullopt, std::optional limit = std::nullopt) const;
+ Json organization_settings() const;
+ Json set_filtered_model_catalog(bool enabled) const;
+ // SCIM.
+ Json scim_group_mappings(std::optional offset = std::nullopt, std::optional limit = std::nullopt) const;
+ Json scim_group_mapping(const std::string& id) const;
+ Json create_scim_group_mapping(const Json& body) const;
+ Json update_scim_group_mapping(const std::string& id, const std::string& role) const;
+ Json remove_scim_group_mapping(const std::string& id, bool keep_members) const;
+ Json scim_groups(std::optional offset = std::nullopt, std::optional limit = std::nullopt,
+ const std::string& display_name = "", const std::string& external_id = "") const;
+ Json start_scim_sync() const;
+ Json scim_sync_job(const std::string& id) const;
+};
+
+// Secrets vault for workspaces and interns. Secured with OPENROUTER_API_KEY.
+class VaultService : public Endpoint {
+ public:
+ explicit VaultService(std::shared_ptr g) : Endpoint(std::move(g)) {}
+ Json secrets(std::optional offset = std::nullopt, std::optional limit = std::nullopt) const;
+ // value: 1..65536 characters, hosts: 1..100 exact hostnames. The value is
+ // never returned and must never be logged.
+ Json put_secret(const std::string& name, const std::string& value,
+ const std::vector& hosts) const;
+ Json delete_secret(const std::string& name) const;
+ Json intern_secrets(const std::string& intern_id, std::optional offset = std::nullopt,
+ std::optional limit = std::nullopt) const;
+ Json intern_effective_secrets(const std::string& intern_id, std::optional offset = std::nullopt,
+ std::optional limit = std::nullopt) const;
+ Json intern_connections(const std::string& intern_id) const;
+ Json put_intern_secret(const std::string& intern_id, const std::string& name,
+ const std::string& value, const std::vector& hosts) const;
+ Json delete_intern_secret(const std::string& intern_id, const std::string& name) const;
+ Json copy_secrets_to_intern(const std::string& intern_id, const std::vector& names) const;
+};
+
+} // namespace molo::openrouter
diff --git a/src/openrouter/call_plan.cpp b/src/openrouter/call_plan.cpp
new file mode 100644
index 0000000..082b054
--- /dev/null
+++ b/src/openrouter/call_plan.cpp
@@ -0,0 +1,178 @@
+#include "openrouter/call_plan.h"
+
+#include
+#include
+#include
+#include
+
+#include "clients/url.h"
+#include "llm/api_client.h"
+#include "llm/error.h"
+#include "openrouter/caps.h"
+
+namespace molo::openrouter {
+
+namespace {
+
+[[noreturn]] void bad(const std::string& why) {
+ throw llm::ApiError::invalid(kVendor, why);
+}
+
+std::set split_fields(const char* fields, bool want_query) {
+ std::set out;
+ std::istringstream in(fields);
+ for (std::string f; in >> f;) {
+ if (f == "-") continue;
+ bool is_query = f.front() == '?';
+ if (is_query == want_query) out.insert(is_query ? f.substr(1) : f);
+ }
+ return out;
+}
+
+bool free_text_arg(const std::string& placeholder) {
+ // External user ids are partner-defined text; everything else is a slug,
+ // hash or uuid and goes through Service::valid_id.
+ return placeholder == "user";
+}
+
+} // namespace
+
+Query& Query::add(const std::string& name, const std::string& value) {
+ if (items_.size() >= Caps::kMaxQueryParams) bad("too many query parameters");
+ if (value.size() > Caps::kMaxQueryValueBytes) bad("query value too long: " + name);
+ items_.emplace_back(name, value);
+ return *this;
+}
+Query& Query::add(const std::string& name, long value) { return add(name, std::to_string(value)); }
+Query& Query::add(const std::string& name, double value) { return add(name, std::format("{}", value)); }
+Query& Query::add(const std::string& name, bool value) { return add(name, std::string(value ? "true" : "false")); }
+Query& Query::add_if(const std::string& name, const std::string& value) {
+ if (!value.empty()) add(name, value);
+ return *this;
+}
+
+const CallSpec* CallPlanner::find(std::string_view name) {
+ for (const CallSpec& s : kCalls)
+ if (name == s.name) return &s;
+ return nullptr;
+}
+
+const CallSpec& CallPlanner::spec(std::string_view name) {
+ const CallSpec* s = find(name);
+ if (!s) bad("unknown call: " + std::string(name));
+ return *s;
+}
+
+KeyKind CallPlanner::key_kind(const CallSpec& spec) {
+ if (std::strcmp(spec.key, "mgmt") == 0) return KeyKind::kManagement;
+ if (std::strcmp(spec.key, "none") == 0) return KeyKind::kNone;
+ return KeyKind::kApi;
+}
+
+clients::Method CallPlanner::method_of(const CallSpec& spec) {
+ if (!std::strcmp(spec.http, "GET")) return clients::Method::kGet;
+ if (!std::strcmp(spec.http, "POST")) return clients::Method::kPost;
+ if (!std::strcmp(spec.http, "PUT")) return clients::Method::kPut;
+ if (!std::strcmp(spec.http, "PATCH")) return clients::Method::kPatch;
+ if (!std::strcmp(spec.http, "DELETE")) return clients::Method::kDelete;
+ bad(std::string("bad method in table for ") + spec.name);
+}
+
+std::set CallPlanner::body_fields(const CallSpec& spec) {
+ return split_fields(spec.fields, false);
+}
+std::set CallPlanner::query_fields(const CallSpec& spec) {
+ return split_fields(spec.fields, true);
+}
+
+std::vector CallPlanner::placeholders(const std::string& tmpl) {
+ std::vector out;
+ std::size_t pos = 0;
+ while ((pos = tmpl.find('{', pos)) != std::string::npos) {
+ std::size_t end = tmpl.find('}', pos);
+ if (end == std::string::npos) break;
+ out.push_back(tmpl.substr(pos + 1, end - pos - 1));
+ pos = end + 1;
+ }
+ return out;
+}
+
+bool CallPlanner::accepts_field(std::string_view name, const std::string& field) {
+ const CallSpec* s = find(name);
+ return s && body_fields(*s).count(field) > 0;
+}
+
+PlannedCall CallPlanner::plan(std::string_view name, const PathArgs& args,
+ const Query& query, const Json* body) {
+ const CallSpec& s = spec(name);
+ PlannedCall out;
+ out.spec = &s;
+ out.method = method_of(s);
+ out.key = key_kind(s);
+
+ std::string path = s.path;
+ std::set used;
+ for (const std::string& ph : placeholders(s.path)) {
+ auto it = args.find(ph);
+ if (it == args.end()) bad("missing path argument: " + ph);
+ const std::string& value = it->second;
+ if (free_text_arg(ph)) {
+ // Partner text of 1..512 bytes; "." and ".." cannot be addressed by path.
+ if (value.empty() || value.size() > 512 || value == "." || value == ".." ||
+ value.find('\0') != std::string::npos)
+ bad("bad " + ph);
+ } else if (!llm::Service::valid_id(ph == "author" && value.rfind("~", 0) == 0
+ ? value.substr(1)
+ : value)) {
+ bad("bad " + ph + " id"); // author may carry the alias marker "~"
+ }
+ std::string token = "{" + ph + "}";
+ // valid_id characters are all path-safe; only free text is encoded.
+ path.replace(path.find(token), token.size(),
+ free_text_arg(ph) ? clients::Url::encode_component(value) : value);
+ used.insert(ph);
+ }
+ for (const auto& [k, v] : args) {
+ (void)v;
+ if (!used.count(k)) bad("unexpected path argument: " + k);
+ }
+ out.path = path;
+
+ std::set qf = query_fields(s);
+ std::string qs;
+ for (const auto& [k, v] : query.items()) {
+ if (!qf.count(k)) bad("query parameter not declared for " + std::string(name) + ": " + k);
+ if (v.empty()) bad("empty query value: " + k);
+ qs += (qs.empty() ? "?" : "&") + clients::Url::encode_component(k) + "=" +
+ clients::Url::encode_component(v);
+ }
+ out.query = qs;
+
+ std::set bf = body_fields(s);
+ if (body) {
+ if (bf.empty()) bad(std::string(name) + " takes no request body");
+ if (!body->is_object()) bad("request body must be a JSON object");
+ for (const auto& [k, v] : body->as_object()) {
+ (void)v;
+ if (!bf.count(k)) bad("body field not declared for " + std::string(name) + ": " + k);
+ }
+ out.has_body = true;
+ out.body = *body;
+ }
+ return out;
+}
+
+std::pair split_model_id(const std::string& model_id) {
+ std::size_t slash = model_id.find('/');
+ if (slash == std::string::npos || slash == 0 || slash + 1 >= model_id.size() ||
+ model_id.find('/', slash + 1) != std::string::npos)
+ bad("model id must look like author/slug");
+ std::string author = model_id.substr(0, slash);
+ std::string slug = model_id.substr(slash + 1);
+ if (!llm::Service::valid_id(author.rfind("~", 0) == 0 ? author.substr(1) : author) ||
+ !llm::Service::valid_id(slug))
+ bad("bad model id");
+ return {author, slug};
+}
+
+} // namespace molo::openrouter
diff --git a/src/openrouter/call_plan.h b/src/openrouter/call_plan.h
new file mode 100644
index 0000000..6fc70a8
--- /dev/null
+++ b/src/openrouter/call_plan.h
@@ -0,0 +1,87 @@
+#pragma once
+
+// CallPlanner: turns a call name from the table (calls.h) plus path
+// arguments, query arguments and a JSON body into a PlannedCall, and rejects
+// anything the table does not declare (unknown call, missing or malformed
+// path argument, undeclared query parameter, undeclared body field, body on a
+// call without one). Nothing here touches the network, so every request the
+// module can send is checkable against the spec-verified table.
+
+#include