#include "../AiDemos.hpp" #include "../../fw/Router.hpp" #include "../../fw/Templates.hpp" #include "anthropic/admin/calls.h" #include "anthropic/admin/gateway.h" #include "anthropic/admin/reports.h" #include "anthropic/admin/request.h" #include "anthropic/admin/webhook.h" #include "llm/error.h" namespace molo::example::app { // Anthropic admin: Admin API (organization, users, invites, workspaces, keys, // service accounts, federation, RBAC, spend limits, plugins, webhooks, Claude // Tag), usage and cost reports, and the Managed Agents surface, over the real // src/anthropic/admin package. GET routes need no credential. Every route that // calls Anthropic is a POST: 503 not_configured without a credential, 422 on // bad input, 401 credential_rejected for a key of the wrong kind. Anything that // is not a read is a dry run unless the body says "confirm":true. namespace { namespace adm = anthropic::admin; using Json = clients::body::Json; constexpr std::size_t kMaxBody = 256 * 1024; const char kPage[] = R"ADMIN({% extends "base.html" %} {% block content %}

Anthropic admin

Organization, workspaces, keys, usage and cost reports, and Managed Agents. Reads run as is; every write or delete is a dry run until you tick confirm.

Checking credentials...

Organization

Usage and cost

Any call


{% endblock %} )ADMIN"; 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.type() == "NOT_CONFIGURED") throw fw::HttpError(503, "not_configured", e.message()); if (e.type() == "credential_rejected") throw fw::HttpError(e.http_status() == 403 ? 403 : 401, "credential_rejected", e.message()); if (e.type() == "INVALID_ARGUMENT") bad(e.message()); throw fw::HttpError(502, "anthropic_error", std::to_string(e.http_status()) + " " + 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& body, const char* key) { const Json* v = body.find(key); if (!v || v->is_null()) return ""; if (!v->is_string()) bad(std::string(key) + " must be a string"); return v->as_string(); } bool flag(const Json& body, const char* key) { const Json* v = body.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(); } std::vector strings(const Json& body, const char* key) { std::vector out; const Json* v = body.find(key); if (!v || v->is_null()) return out; if (!v->is_array()) bad(std::string(key) + " must be an array of strings"); for (const Json& s : v->as_array()) { if (!s.is_string()) bad(std::string(key) + " must be an array of strings"); out.push_back(s.as_string()); } return out; } const char* kind_name(adm::Kind k) { return k == adm::Kind::kRead ? "read" : k == adm::Kind::kWrite ? "write" : "destructive"; } const char* auth_name(adm::Auth a) { return a == adm::Auth::kAdmin ? "admin_key_or_oauth" : a == adm::Auth::kOAuth ? "oauth_token" : "api_key"; } // Looks a call up by its table name; "name" and "name+beta" forms share names, the // first row wins (the beta form carries a "beta" suffix in the name). const adm::CallSpec* find_call(const std::string& name) { for (std::size_t i = 0; i < adm::call_count(); ++i) if (name == adm::spec_at(i).name) return &adm::spec_at(i); return nullptr; } class AdminRoutes { public: explicit AdminRoutes(std::shared_ptr gateway) : gateway_(std::move(gateway)) {} Json status() const { Json o = Json::object(); Json lanes = Json::object(); for (const adm::LaneInfo& l : gateway_->lanes()) { Json s = Json::object(); s.set("env", Json(l.env)); s.set("state", Json(l.state == adm::LaneState::kReady ? "ready" : l.state == adm::LaneState::kMissing ? "missing" : "rejected")); if (!l.reason.empty()) s.set("reason", Json(l.reason)); lanes.set(adm::KeyRules::name_of(l.lane), s); } o.set("lanes", lanes); o.set("configured", Json(gateway_->ready(adm::Auth::kAdmin))); o.set("calls", Json(static_cast(adm::call_count()))); o.set("api_version", Json(adm::Gateway::kApiVersion)); return o; } Json calls() const { Json arr = Json::array(); for (std::size_t i = 0; i < adm::call_count(); ++i) { const adm::CallSpec& s = adm::spec_at(i); Json c = Json::object(); c.set("name", Json(s.name)); c.set("http", Json(s.http)); c.set("path", Json(s.path)); c.set("kind", Json(kind_name(s.kind))); c.set("credential", Json(auth_name(s.auth))); c.set("beta", Json(s.beta)); arr.push(c); } Json o = Json::object(); o.set("calls", arr); return o; } // Generic table-driven call: validate, dry-run non-reads, then send. fw::Response call(const fw::Request& req) const { Json b = parse_body(req); std::string name = text(b, "call"); if (name.empty()) bad("call is required"); const adm::CallSpec* spec = find_call(name); if (!spec) bad("unknown call " + name); if (spec->wire != adm::Wire::kJson) bad(name + " is a " + (spec->wire == adm::Wire::kSse ? "stream" : spec->wire == adm::Wire::kRaw ? "download" : "multipart upload") + " call and is not available here"); adm::Query query; if (const Json* q = b.find("query")) { if (!q->is_object()) bad("query must be a JSON object"); for (const auto& [k, v] : q->as_object()) { if (v.is_array()) { for (const Json& item : v.as_array()) { if (!item.is_string() && !item.is_number()) bad(k + " values must be strings or numbers"); query.add(k, item.is_string() ? item.as_string() : std::to_string(item.as_int())); } } else if (v.is_string()) { query.set(k, v.as_string()); } else if (v.is_number()) { query.set_int(k, v.as_int()); } else if (v.is_bool()) { query.set_bool(k, v.as_bool()); } else { bad(k + " must be a string, number, boolean or array"); } } } const Json* body = b.find("body"); if (body && !body->is_null() && !body->is_object()) bad("body must be a JSON object"); bool has_body = body && body->is_object() && !body->as_object().empty(); bool confirm = flag(b, "confirm"); adm::PreparedRequest p = guarded([&] { return adm::RequestBuilder::prepare(find_enum(spec), strings(b, "ids"), &query, (has_body || adm::RequestBuilder::names(spec->body).size() ? body : nullptr), gateway_->workspace_id()); }); if (spec->kind != adm::Kind::kRead && !confirm) { Json o = Json::object(); o.set("dry_run", Json(true)); o.set("would_send", Json(std::string(spec->http) + " " + p.target)); o.set("kind", Json(kind_name(spec->kind))); o.set("hint", Json("send confirm:true to run it")); return json_out(o); } return guarded([&] { auto client = gateway_->client_for(spec->auth); return json_out(client->request(p.method, p.target, p.body ? &*p.body : nullptr, p.headers)); }); } fw::Response organization(const fw::Request&) const { return guarded([&] { adm::PreparedRequest p = adm::RequestBuilder::prepare(adm::Call::kOrganizationRetrieve, {}, nullptr, nullptr); return json_out(gateway_->client_for(adm::Auth::kAdmin)->request(p.method, p.target, nullptr, p.headers)); }); } fw::Response report(const fw::Request& req, int which) const { Json b = parse_body(req); std::string start = text(b, "starting_at"); std::string ending = text(b, "ending_at"); std::string page = text(b, "page"); long limit = 0; if (const Json* l = b.find("limit")) { if (!l->is_number()) bad("limit must be a number"); limit = l->as_int(); } std::vector group = strings(b, "group_by"); return guarded([&] { adm::Query q; adm::Call c; if (which == 0) { adm::MessagesUsageQuery m; m.starting_at = start; m.ending_at = ending; m.limit = limit; m.page = page; m.group_by = group; std::string w = text(b, "bucket_width"); if (!w.empty()) m.bucket_width = w; q = m.to_query(); c = adm::Call::kUsageReportRetrieveMessages; } else if (which == 1) { adm::CostQuery m; m.starting_at = start; m.ending_at = ending; m.limit = limit; m.page = page; m.group_by = group; q = m.to_query(); c = adm::Call::kCostReportRetrieve; } else { adm::ClaudeCodeQuery m; m.starting_at = start; m.limit = limit; m.page = page; q = m.to_query(); c = adm::Call::kUsageReportRetrieveClaudeCode; } adm::PreparedRequest p = adm::RequestBuilder::prepare(c, {}, &q, nullptr); return json_out(gateway_->client_for(adm::Auth::kAdmin)->request(p.method, p.target, nullptr, p.headers)); }); } // Local: verifies a webhook signature; no credential involved. fw::Response verify_webhook(const fw::Request& req) const { Json b = parse_body(req); std::string key = text(b, "signing_key"), payload = text(b, "payload"); if (key.empty()) bad("signing_key is required"); if (payload.empty()) bad("payload is required"); std::map h{{"webhook-id", text(b, "webhook_id")}, {"webhook-timestamp", text(b, "webhook_timestamp")}, {"webhook-signature", text(b, "webhook_signature")}}; return guarded([&] { adm::WebhookVerifier v(key); std::string why; bool ok = v.verify(payload, h, static_cast(std::time(nullptr)), &why); Json o = Json::object(); o.set("valid", Json(ok)); if (!ok) o.set("reason", Json(why)); return json_out(o); }); } private: static adm::Call find_enum(const adm::CallSpec* spec) { return spec->call; } std::shared_ptr gateway_; }; } // namespace void register_ai_anthropicadmin_demo(fw::Router& router, Services& services) { auto gateway = adm::Gateway::from_env(); auto routes = std::make_shared(gateway); fw::Environment* env = services.templates.get(); services.templates->add_template("ai_anthropic_admin.html", kPage); services.add_feature("ai-anthropic-admin", "/ai/anthropic/admin"); router.get("/ai/anthropic/admin", "ai-anthropic-admin-page", [env](fw::Request) { fw::TemplateCtx ctx; ctx["title"] = std::string("Anthropic admin"); return fw::Response(200, env->render("ai_anthropic_admin.html", ctx), "text/html; charset=utf-8"); }); router.get("/ai/anthropic/admin/status", "ai-anthropic-admin-status", [routes](fw::Request) { return json_out(routes->status()); }); router.get("/ai/anthropic/admin/calls", "ai-anthropic-admin-calls", [routes](fw::Request) { return json_out(routes->calls()); }); router.post("/ai/anthropic/admin/call", "ai-anthropic-admin-call", [routes](fw::Request req) { return routes->call(req); }); router.post("/ai/anthropic/admin/organization", "ai-anthropic-admin-organization", [routes](fw::Request req) { return routes->organization(req); }); router.post("/ai/anthropic/admin/usage", "ai-anthropic-admin-usage", [routes](fw::Request req) { return routes->report(req, 0); }); router.post("/ai/anthropic/admin/cost", "ai-anthropic-admin-cost", [routes](fw::Request req) { return routes->report(req, 1); }); router.post("/ai/anthropic/admin/claude-code", "ai-anthropic-admin-claude-code", [routes](fw::Request req) { return routes->report(req, 2); }); router.post("/ai/anthropic/admin/webhook/verify", "ai-anthropic-admin-webhook-verify", [routes](fw::Request req) { return routes->verify_webhook(req); }); } } // namespace molo::example::app