diff --git a/example/app/ai/MetaDemo.cpp b/example/app/ai/MetaDemo.cpp
index 1f594f6..e1555e2 100644
--- a/example/app/ai/MetaDemo.cpp
+++ b/example/app/ai/MetaDemo.cpp
@@ -1,13 +1,474 @@
#include "../AiDemos.hpp"
#include "../../fw/Router.hpp"
+#include "../../fw/Templates.hpp"
+#include "meta/calls.h"
+#include "meta/check.h"
+#include "meta/response_input.h"
+#include "meta/catalog.h"
+#include "meta/chat_completions.h"
+#include "meta/chat_model.h"
+#include "meta/client.h"
+#include "meta/files.h"
+#include "meta/images.h"
+#include "meta/messages.h"
+#include "meta/models.h"
+#include "meta/muse_code.h"
+#include "meta/responses.h"
+#include "meta/sam.h"
+#include "meta/speech.h"
+#include "security/crypto/Base64.h"
namespace molo::example::app {
-// Meta Model API (Muse Spark and the Muse family). Stub: the module agent fills this in.
+// Meta Model API (api.meta.ai/v1: Muse Spark, Muse Wonder, Muse Image, Muse
+// Voice Transcribe, SAM 3.1) and the Muse Code session protocol, over the
+// real src/meta module. GET routes need no credential and make no upstream
+// call. Every route that calls Meta is a POST: 422 on bad input first, then
+// 503 not_configured without META_API_KEY / MODEL_API_KEY. Paid and
+// destructive calls (images, segmentation, transcription, deletes, spawning
+// muse) are dry runs unless the body says "confirm":true.
+
+namespace {
+
+namespace mt = meta;
+using Json = clients::body::Json;
+
+constexpr std::size_t kMaxBody = 8 * 1024 * 1024;
+
+const char kPage[] = R"META({% extends "base.html" %}
+{% block content %}
+
Meta Model API
+Muse Spark and Muse Wonder (Responses, Chat Completions, Messages), Muse Image,
+Muse Voice Transcribe, SAM 3.1, files, models, and the Muse Code session protocol.
+Paid and destructive calls stay dry runs until you tick confirm.
+Checking credentials...
+
+
+
+{% endblock %}
+)META";
+
+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.type() == "INVALID_ARGUMENT") throw fw::HttpError(422, "validation_error", e.message());
+ throw fw::HttpError(502, "meta_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();
+}
+
+std::optional number(const Json& b, const char* key) {
+ const Json* v = b.find(key);
+ if (!v || v->is_null()) return std::nullopt;
+ if (!v->is_number()) bad(std::string(key) + " must be a number");
+ return v->as_number();
+}
+
+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 dry_run(const char* what, const std::string& target) {
+ Json o = Json::object();
+ o.set("dry_run", Json(true));
+ o.set(what, Json(target));
+ o.set("hint", Json("send confirm:true to run it"));
+ return o;
+}
+
+void need_key(const std::shared_ptr& c) {
+ if (!c->configured()) throw fw::HttpError(503, "not_configured", "set META_API_KEY or MODEL_API_KEY");
+}
+
+mt::ResponseRequest response_from(const Json& b) {
+ mt::ResponseRequest r;
+ r.model = text(b, "model", true);
+ const Json* in = b.find("input");
+ if (!in || !(in->is_string() || in->is_array())) bad("input must be a string or an array");
+ r.input = *in;
+ r.instructions = text(b, "instructions");
+ r.previous_response_id = text(b, "previous_response_id");
+ r.reasoning_effort = text(b, "reasoning_effort");
+ if (auto n = number(b, "max_output_tokens")) r.max_output_tokens = static_cast(*n);
+ if (auto t = number(b, "temperature")) r.temperature = *t;
+ if (flag(b, "web_search")) r.tools.push_back(mt::ToolBuilder::web_search());
+ return r;
+}
+
+} // namespace
+
void register_ai_meta_demo(fw::Router& router, Services& services) {
- (void)router;
- (void)services;
+ auto client = mt::MetaClient::from_env();
+ fw::Environment* env = services.templates.get();
+ services.templates->add_template("ai_meta.html", kPage);
+ services.add_feature("ai-meta", "/ai/meta");
+
+ router.get("/ai/meta", "ai-meta-page", [env](fw::Request req) {
+ (void)req;
+ fw::TemplateCtx ctx;
+ ctx["title"] = std::string("Meta Model API");
+ return fw::Response(200, env->render("ai_meta.html", ctx), "text/html; charset=utf-8");
+ });
+
+ router.get("/ai/meta/status", "ai-meta-status", [client](fw::Request req) {
+ (void)req;
+ Json o = Json::object();
+ o.set("configured", Json(client->configured()));
+ o.set("base_url", Json(mt::MetaEndpoints::kBaseUrl));
+ o.set("key_env", Json(std::string(mt::MetaEndpoints::kKeyEnv) + " or " + mt::MetaEndpoints::kAltKeyEnv));
+ o.set("calls", Json(static_cast(mt::call_count())));
+ Json models = Json::array();
+ for (std::size_t i = 0; i < mt::ModelCatalog::size(); ++i) {
+ const mt::ModelInfo& m = mt::ModelCatalog::at(i);
+ Json row = Json::object();
+ row.set("id", Json(m.id));
+ row.set("family", Json(m.family));
+ row.set("kind", Json(mt::ModelCatalog::kind_name(m.kind)));
+ row.set("hosted", Json(m.hosted));
+ row.set("note", Json(m.note));
+ models.push(row);
+ }
+ o.set("models", models);
+ return json_out(o);
+ });
+
+ router.get("/ai/meta/calls", "ai-meta-calls", [](fw::Request req) {
+ (void)req;
+ Json arr = Json::array();
+ for (std::size_t i = 0; i < mt::call_count(); ++i) {
+ const mt::CallSpec& s = mt::spec_at(i);
+ Json row = Json::object();
+ row.set("http", Json(s.http_method));
+ row.set("path", Json(s.path));
+ row.set("operation", Json(s.operation));
+ arr.push(row);
+ }
+ Json o = Json::object();
+ o.set("calls", arr);
+ return json_out(o);
+ });
+
+ router.post("/ai/meta/responses", "ai-meta-responses", [client](fw::Request req) {
+ Json body = parse_body(req);
+ mt::ResponseRequest r = response_from(body);
+ return guarded([&] {
+ r.validate();
+ need_key(client);
+ mt::ResponseResult res = mt::ResponsesService(client).create(r);
+ Json o = Json::object();
+ o.set("id", Json(res.id()));
+ o.set("status", Json(res.status()));
+ o.set("output_text", Json(res.output_text()));
+ o.set("usage", res.body.find("usage") ? *res.body.find("usage") : Json::object());
+ return json_out(o);
+ });
+ });
+
+ router.post("/ai/meta/responses/count", "ai-meta-responses-count", [client](fw::Request req) {
+ mt::ResponseRequest r = response_from(parse_body(req));
+ return guarded([&] {
+ r.validate();
+ need_key(client);
+ Json o = Json::object();
+ o.set("input_tokens", Json(static_cast(mt::ResponsesService(client).count_input_tokens(r))));
+ return json_out(o);
+ });
+ });
+
+ auto id_route = [&](const char* path, const char* name, int mode) {
+ router.post(path, name, [client, mode](fw::Request req) {
+ Json body = parse_body(req);
+ std::string id = text(body, "id", true);
+ bool confirm = flag(body, "confirm");
+ return guarded([&] {
+ mt::Check::segment("id", id);
+ if (mode == 2 && !confirm) return json_out(dry_run("delete", id));
+ need_key(client);
+ mt::ResponsesService svc(client);
+ Json out = mode == 0 ? svc.retrieve(id).body : mode == 1 ? svc.cancel(id) : svc.remove(id);
+ return json_out(out);
+ });
+ });
+ };
+ id_route("/ai/meta/responses/get", "ai-meta-responses-get", 0);
+ id_route("/ai/meta/responses/cancel", "ai-meta-responses-cancel", 1);
+ id_route("/ai/meta/responses/delete", "ai-meta-responses-delete", 2);
+
+ router.post("/ai/meta/chat", "ai-meta-chat", [client](fw::Request req) {
+ Json body = parse_body(req);
+ mt::ChatCompletionRequest r;
+ r.model = text(body, "model", true);
+ r.messages = {mt::ChatMessage::user(text(body, "message", true))};
+ r.reasoning_effort = text(body, "reasoning_effort");
+ if (auto n = number(body, "max_completion_tokens")) r.max_completion_tokens = static_cast(*n);
+ return guarded([&] {
+ r.validate();
+ need_key(client);
+ Json out = mt::ChatCompletionsService(client).create(r);
+ llm::ChatResponse cr = mt::MetaChatModel::from_chat(out);
+ Json o = Json::object();
+ o.set("text", Json(cr.text()));
+ o.set("finish_reason", Json(cr.finish_reason));
+ o.set("total_tokens", Json(cr.usage.total_tokens));
+ return json_out(o);
+ });
+ });
+
+ router.post("/ai/meta/messages", "ai-meta-messages", [client](fw::Request req) {
+ Json body = parse_body(req);
+ mt::MessageRequest r;
+ r.model = text(body, "model", true);
+ r.messages = {mt::AnthropicBlock::message_text("user", text(body, "message", true))};
+ r.max_tokens = static_cast(number(body, "max_tokens").value_or(0));
+ return guarded([&] {
+ r.validate();
+ need_key(client);
+ Json out = mt::MessagesService(client).create(r);
+ Json o = Json::object();
+ o.set("text", Json(mt::MessagesService::text_of(out)));
+ o.set("stop_reason", Json(mt::JsonX::str(out, "stop_reason")));
+ return json_out(o);
+ });
+ });
+
+ router.post("/ai/meta/models", "ai-meta-models", [client](fw::Request req) {
+ Json body = parse_body(req);
+ std::string id = text(body, "id");
+ return guarded([&] {
+ if (!id.empty()) mt::Check::model_id(id);
+ need_key(client);
+ mt::ModelsService svc(client);
+ Json arr = Json::array();
+ if (id.empty()) {
+ for (const auto& m : svc.list()) {
+ Json row = Json::object();
+ row.set("id", Json(m.id));
+ row.set("created", Json(static_cast(m.created)));
+ arr.push(row);
+ }
+ } else {
+ auto m = svc.retrieve(id);
+ Json row = Json::object();
+ row.set("id", Json(m.id));
+ row.set("created", Json(static_cast(m.created)));
+ arr.push(row);
+ }
+ Json o = Json::object();
+ o.set("models", arr);
+ return json_out(o);
+ });
+ });
+
+ router.post("/ai/meta/files", "ai-meta-files", [client](fw::Request req) {
+ Json body = parse_body(req);
+ std::string action = text(body, "action", true);
+ if (action != "list" && action != "get" && action != "delete") bad("action must be list, get or delete");
+ std::string id = text(body, "id");
+ if (action != "list" && id.empty()) bad("id is required");
+ bool confirm = flag(body, "confirm");
+ return guarded([&] {
+ if (!id.empty()) mt::Check::segment("id", id);
+ if (action == "delete" && !confirm) return json_out(dry_run("delete", id));
+ need_key(client);
+ mt::FilesService svc(client);
+ Json o = Json::object();
+ if (action == "list") {
+ mt::FileList l = svc.list_all(text(body, "purpose"), 100, text(body, "order"));
+ Json arr = Json::array();
+ for (const auto& f : l.files) {
+ Json row = Json::object();
+ row.set("id", Json(f.id));
+ row.set("filename", Json(f.filename));
+ row.set("bytes", Json(static_cast(f.bytes)));
+ arr.push(row);
+ }
+ o.set("files", arr);
+ o.set("truncated", Json(l.truncated));
+ } else if (action == "get") {
+ mt::FileObject f = svc.retrieve(id);
+ o.set("id", Json(f.id));
+ o.set("filename", Json(f.filename));
+ o.set("status", Json(f.status));
+ } else {
+ o = svc.remove(id);
+ }
+ return json_out(o);
+ });
+ });
+
+ router.post("/ai/meta/images", "ai-meta-images", [client](fw::Request req) {
+ Json body = parse_body(req);
+ mt::ImageRequest r;
+ r.prompt = text(body, "prompt", true);
+ r.size = text(body, "size");
+ if (auto n = number(body, "n")) r.n = static_cast(*n);
+ r.reasoning_strength = text(body, "reasoning_strength");
+ bool confirm = flag(body, "confirm");
+ return guarded([&] {
+ r.validate(false);
+ if (!confirm) return json_out(dry_run("prompt", r.prompt));
+ need_key(client);
+ mt::ImageResult res = mt::ImagesService(client).generate(r);
+ Json o = Json::object();
+ o.set("images", Json(static_cast(res.data.size())));
+ o.set("output_format", Json(res.output_format));
+ if (!res.data.empty()) o.set("first_b64_prefix", Json(res.data[0].b64_json.substr(0, 64)));
+ return json_out(o);
+ });
+ });
+
+ router.post("/ai/meta/segment", "ai-meta-segment", [client](fw::Request req) {
+ Json body = parse_body(req);
+ mt::SamRequest s;
+ std::string phrase = text(body, "prompt", true);
+ s.image_url = text(body, "image_url");
+ s.video_url = text(body, "video_url");
+ s.include_confidence = flag(body, "include_confidence");
+ s.mask_encoding = text(body, "mask_encoding");
+ bool confirm = flag(body, "confirm");
+ return guarded([&] {
+ s.prompt = mt::SamPrompt::concept_text(phrase);
+ mt::ResponseRequest rr = s.to_response_request();
+ rr.validate(true);
+ if (!confirm) return json_out(dry_run("prompt", s.prompt));
+ need_key(client);
+ mt::ResponseAccumulator acc = mt::ResponsesService(client).stream(rr);
+ auto frames = mt::SamOutput::parse(acc.text());
+ Json o = Json::object();
+ o.set("frames", Json(static_cast(frames.size())));
+ o.set("records", Json(static_cast(mt::SamOutput::record_count(frames))));
+ return json_out(o);
+ });
+ });
+
+ router.post("/ai/meta/transcribe", "ai-meta-transcribe", [client](fw::Request req) {
+ Json body = parse_body(req);
+ std::string b64 = text(body, "audio_b64", true);
+ std::string wav;
+ if (!security::crypto::Base64::decode(b64, wav)) bad("audio_b64 is not valid base64");
+ mt::SpeechOptions o;
+ o.mode = text(body, "mode");
+ bool confirm = flag(body, "confirm");
+ return guarded([&] {
+ o.validate();
+ mt::WavInfo info = mt::WavInfo::parse(wav);
+ if (!confirm) return json_out(dry_run("duration_ms", std::to_string(info.duration_ms)));
+ need_key(client);
+ mt::TranscribeResult r = mt::TranscribeService(client).transcribe(o, wav);
+ Json out = Json::object();
+ out.set("transcript", Json(r.transcript));
+ out.set("turns", Json(static_cast(r.turns.size())));
+ return json_out(out);
+ });
+ });
+
+ // GET /status is unauthenticated upstream; still a POST here (it leaves the host).
+ router.post("/ai/meta/platform", "ai-meta-platform", [](fw::Request req) {
+ (void)req;
+ return guarded([&] {
+ mt::ServiceStatus st = mt::StatusService(mt::MetaClient::unauthenticated()).get();
+ Json o = Json::object();
+ o.set("is_alive", Json(st.is_alive));
+ o.set("service_status", Json(st.service_status));
+ return json_out(o);
+ });
+ });
+
+ router.post("/ai/meta/code", "ai-meta-code", [](fw::Request req) {
+ Json body = parse_body(req);
+ bool confirm = flag(body, "confirm");
+ bool available = mt::ProcessTransport::binary_available("muse");
+ if (!confirm) {
+ Json o = dry_run("command", "muse serve");
+ o.set("muse_on_path", Json(available));
+ return json_out(o);
+ }
+ if (!available) throw fw::HttpError(503, "not_configured", "the muse binary is not on PATH");
+ return guarded([&] {
+ mt::MspClient c(std::make_unique());
+ Json init = c.initialize("moloapp-demo", "0.1");
+ Json o = Json::object();
+ o.set("schema_fingerprint", Json(c.schema_fingerprint()));
+ o.set("server", init.find("serverInfo") ? *init.find("serverInfo") : Json::object());
+ c.close();
+ return json_out(o);
+ });
+ });
}
} // namespace molo::example::app
diff --git a/example/assets/ai_meta.js b/example/assets/ai_meta.js
new file mode 100644
index 0000000..23f0880
--- /dev/null
+++ b/example/assets/ai_meta.js
@@ -0,0 +1,51 @@
+(function () {
+ var $ = function (id) { return document.getElementById(id); };
+ var samples = {
+ "responses": '{"model":"muse-spark-1.3","input":"Say hi in five words.","reasoning_effort":"low"}',
+ "responses/count": '{"model":"muse-spark-1.3","input":"How many tokens?"}',
+ "responses/get": '{"id":"resp_..."}',
+ "responses/cancel": '{"id":"resp_..."}',
+ "responses/delete": '{"id":"resp_..."}',
+ "chat": '{"model":"muse-spark-1.3","message":"Hello"}',
+ "messages": '{"model":"muse-spark-1.3","message":"Hello","max_tokens":256}',
+ "models": '{}',
+ "files": '{"action":"list"}',
+ "images": '{"prompt":"a red fox in snow","n":1}',
+ "segment": '{"prompt":"yellow school bus","image_url":"https://example.com/bus.jpg"}',
+ "transcribe": '{"audio_b64":"","mode":"ENDPOINTING"}',
+ "platform": '{}',
+ "code": '{}'
+ };
+ function show(text, isError) {
+ $("meta-out").textContent = text;
+ $("meta-error").textContent = isError ? "Request failed" : "";
+ }
+ function send() {
+ var route = $("meta-route").value;
+ var body;
+ try { body = JSON.parse($("meta-body").value || "{}"); } catch (e) { show("Body is not valid JSON", true); return; }
+ if ($("meta-confirm").checked) body.confirm = true;
+ $("meta-send").disabled = true;
+ fetch("/ai/meta/" + route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
+ .then(function (r) { return r.text().then(function (t) { return { ok: r.ok, t: t }; }); })
+ .then(function (r) {
+ var pretty = r.t;
+ try { pretty = JSON.stringify(JSON.parse(r.t), null, 2); } catch (e) { /* keep text */ }
+ show(pretty, !r.ok);
+ })
+ .catch(function () { show("Network error", true); })
+ .then(function () { $("meta-send").disabled = false; });
+ }
+ fetch("/ai/meta/status").then(function (r) { return r.json(); }).then(function (s) {
+ $("meta-config").textContent = s.configured ? "Credential found (" + s.key_env + ")." : "No credential: set " + s.key_env + ". Reads and dry runs still work.";
+ var box = $("meta-models");
+ box.textContent = "";
+ s.models.forEach(function (m) {
+ var p = document.createElement("div");
+ p.textContent = m.id + " - " + m.family + (m.hosted ? "" : " (self-hosted)") + ": " + m.note;
+ box.appendChild(p);
+ });
+ }).catch(function () { $("meta-config").textContent = "Status unavailable."; });
+ $("meta-route").addEventListener("change", function () { $("meta-body").value = samples[$("meta-route").value] || "{}"; });
+ $("meta-send").addEventListener("click", send);
+})();
diff --git a/src/meta/SPEC.md b/src/meta/SPEC.md
new file mode 100644
index 0000000..1b2b82d
--- /dev/null
+++ b/src/meta/SPEC.md
@@ -0,0 +1,202 @@
+# Meta Model API (`src/meta`, namespace `molo::meta`)
+
+Status: implemented 2026-10-24. Scope is the Meta Model API at
+`https://api.meta.ai/v1` (docs `https://dev.meta.ai/docs`): Muse Spark and
+Muse Wonder text models, Muse Image, Muse Voice Transcribe, Segment Anything
+Model 3.1, files, models, status, and the Muse Code agent protocol. It is NOT
+the older Llama API (`llama.developer.meta.com`); nothing here targets it.
+`developer.meta.com/ai` redirects (302) to `dev.meta.ai`, so the blog-era
+material is the same site.
+
+Credential: `META_API_KEY`, or `MODEL_API_KEY` (the docs' own name), read
+through `llm::Config::get`. Keys look like `LLM_{id}_{secret}`. Bearer auth.
+
+## Module map (one concern per file)
+
+| File | Concern |
+|---|---|
+| `caps.h` | every ceiling and documented limit, with the source marked |
+| `calls.h/.cpp` | the ONE call table (20 operations), `path_for` |
+| `catalog.h/.cpp` | static model table: context, prices, rate limits, `max` effort |
+| `client.h/.cpp` | `MetaClient` (ApiClient factory, key lookup), `RetryPolicy`, `call_with_retry` |
+| `check.h/.cpp`, `schema_check.h/.cpp` | local validation; JSON Schema pre-flight (depth, size, recursion, strict) |
+| `response_input.*` | Responses input items and tools (`ResponseInput`, `ToolBuilder`) |
+| `response_request.*` | `ResponseRequest` body + rules |
+| `response_events.*` | 27 stream event names, `ResponseAccumulator` |
+| `responses.*` | create, stream, retrieve, retrieve_stream, remove, cancel, count_input_tokens |
+| `chat_completions.*` | Chat Completions request, service, chunk accumulator |
+| `messages.*` | Anthropic-compatible Messages: create, stream, count_tokens |
+| `files.*` | upload (multipart), list page + capped walk, retrieve, content, remove |
+| `images.*` | Muse Image generate / edit (JSON and multipart) / stream |
+| `speech.*` | `/asr/transcribe` (JSON, SSE, text) and `/asr/realtime` WebSocket session |
+| `sam.*`, `sam_mask.cpp` | SAM 3.1 prompts, request, output parser, mask decoder |
+| `models.*` | models list/retrieve, unauthenticated status |
+| `usage.*` | usage across the 3 shapes, cost from the catalog, `x-ratelimit-*` |
+| `chat_model.*` | `MetaChatModel : llm::ChatModel` (Responses or Chat Completions) |
+| `muse_code.*`, `muse_code_spec.*` | Muse Session Protocol client (stdio JSON-RPC) and its vocabulary |
+| `tools/check_spec.py` | spec checker (see Verified against spec) |
+
+## Surface
+
+- Responses: create, stream (typed events), retrieve, streaming retrieve of a
+ background response, delete (explicit, destructive), cancel, count input
+ tokens. Reasoning continuity both ways: `previous_response_id`, or
+ `store:false` + `include:["reasoning.encrypted_content"]` + replayed
+ `reasoning` items. Tools: function, `web_search`, `tool_search`, `computer`,
+ plus `custom` and `namespace` (prose only). Structured output via
+ `text.format`. Vision/video/audio/file inputs via `ResponseInput`.
+- Chat Completions: messages, tools, `response_format`, `reasoning_effort`,
+ streaming with usage. Rejected locally: `n>1`, `stop`, `logit_bias`,
+ `prediction`, `verbosity`, `web_search_options`, `modalities`, `logprobs`,
+ `max_output_tokens`, `text`.
+- Messages: Anthropic blocks, thinking (`adaptive`/`enabled`, never disabled),
+ `output_config`, tools (`custom`, `web_search`, `tool_search`), stream events,
+ count_tokens. Rejected locally: `stop_sequences`, `top_k`, `container`,
+ `inference_geo`.
+- Files: upload with `purpose` and `expires_after[...]` before the file part,
+ list (limit 1..1000, order validated because the server answers a plain-text
+ 400), capped page walk that reports `truncated`, retrieve, content, delete.
+- Images: `/images/generations`, `/images/edits` (JSON `images[]` and
+ multipart `image[N]`), `tool_enablement`, SSE `*.completed` events.
+- Speech: WAV pre-check (RIFF PCM mono 16-bit, 16/24 kHz, <=10 min, <=32 MB),
+ `request` JSON part + `audio`, `Accept` selects JSON / event stream / text;
+ realtime session over `google::live::WsClient` with the credential in the
+ handshake frame, `endStream`, close codes 1000/1008/1011/1013.
+- SAM 3.1: `SamPrompt` (concept; box/point object prompts per the output
+ grammar), `SamRequest` -> `ResponseRequest` (`metadata` strings
+ `propagation_direction`, `include_confidence`, `mask_encoding`),
+ `SamOutput::parse`, `SamMask::decode` for `one_bit` (`!`) and `lossless`
+ (`~`).
+- Models, status, usage, rate limits, retry policy.
+- Muse Code: see below.
+
+## Muse Code
+
+Muse Code is a coding agent product, but it has a public programmatic
+surface: the Muse Session Protocol (MSP), JSON-RPC 2.0, one JSON object per
+line on the stdio of `muse serve` (frame limit 10 MiB). It is not an HTTP API
+of `api.meta.ai`. `MspClient` implements the handshake (`initialize`, then the
+`initialized` notification), request/response correlation, a bounded
+notification queue (4096, drops are counted), answers to the two
+server-initiated requests (`approval/request`, `userInput/request`) with an
+empty receipt, error kinds from the schema (37 codes), and shortcuts for
+`session/start`, `turn/start`, `turn/cancel`, `model/list`. `request()` takes
+any of the 70 schema methods. `ProcessTransport` spawns `muse serve`;
+`ILineTransport` keeps the client testable without the binary. The binary is
+not installed here, so nothing was run against a live host.
+
+## Contracts and caps
+
+- Every id is validated before a path is built (`Check::segment`); deletes
+ (`ResponsesService::remove`, `FilesService::remove`) are explicit methods
+ with no default and no retry.
+- Local rules mirror the docs: `max_output_tokens>=16`, `temperature` 0..2,
+ `top_p` in (0,1], penalties -2..2, effort `minimal..max` (`none` rejected,
+ `max` only `muse-wonder-1.0` and `muse-spark-1.3`), `background` XOR
+ `stream`, `reasoning.encrypted_content` XOR `previous_response_id`,
+ `truncation` only `disabled`, background body under 1 MiB, function names
+ `[A-Za-z0-9_.-]` with at most one dot, `call_id` 1..64, safety identifier
+ <=64, schema depth<=10, <=5000 properties, <=120000 chars, no recursion, strict
+ subset rules, `tool_choice` only `auto`.
+- Caps live in `caps.h`: inputs 4096, tools 256, list pages 20, stream events
+ 1,000,000, realtime events 100,000, audio frame 1 MiB, retries 5 with
+ 500 ms base and a 30 s cap, SAM lines/records/mask pixels, MSP queue.
+- `ApiClient` upload cap is 512 MiB (vendor allows 1 GiB).
+- Errors are the foundation `ApiError` (`type` is Meta's category such as
+ `invalid_request_error`; `NotConfiguredError` names `META_API_KEY`).
+ `RetryPolicy`: 429/500/502/503 retry with backoff+jitter, 504 never.
+
+## Sources
+
+1. Docs site, Markdown pages listed by `https://dev.meta.ai/llms.txt`
+ (154 pages, `last-modified: Fri, 23 Oct 2026 23:30:05 GMT`, etag
+ `a179472f87650128af185a2718d84c76`): overview, quickstart, protocols/*,
+ api-reference/* (operation pages and schemas pages), models, pricing and
+ rate limits, error handling, file handling, token counting, reasoning,
+ structured output, tool calling, search grounding, speech to text, image
+ generation, media segmentation, `sam/*`, muse-code/*, open-weight pages.
+2. `muse-code-sdk` (the `meta-models` org on the code host, MIT):
+ `schema/msp/stable/msp.schema.json` (fingerprint
+ `sha256:cfdb6d2525601b9bac76584ccb0610ab3a5539b5e4f51141f079b99b39fcb4e0`,
+ host version 1.4.12), recorded transcripts, Rust/TS/Python SDK sources.
+3. `meta-sam` (same org): Python parser `_mask_codec.py` (mask codec ported)
+ and `conformance/cases/*.json` (a captured live API stream among them).
+4. Live unauthenticated probes, 2026-10-24 (below).
+
+No OpenAPI document and no vendor SDK for the Model API exist: Meta tells
+you to use the OpenAI SDK (Responses, Chat Completions) and the Anthropic SDK
+(Messages) with a changed base URL. Where only prose exists the module says so
+under Unverified. Cross-check: every path and body field was read in both the
+operation page and the schemas page; behaviour rules were read in the guide
+pages and the error-handling page.
+
+## Verified against spec
+
+`python3 -I src/meta/tools/check_spec.py` (stdlib only, fetches the docs):
+20 calls (path heading, query parameters, request schema fields, response
+schema present), 27 Responses stream events equal to the
+`ResponseStreamEvent` union, every documented operation present in the table
+(no exclusion list), catalog models/prices/rpm present on the models and
+pricing pages, and the Muse Code vocabulary (70 methods, 45 notifications, 2
+server requests, 37 error codes) equal to the stable MSP schema.
+Result 2026-10-24: `OK`. A mutated row (renamed query parameter and path)
+fails as expected.
+
+## Verified live
+
+Unauthenticated, 2026-10-24, `https://api.meta.ai/v1`:
+- host resolves, HTTP/2, TLS verifies.
+- `GET /status` -> 200 `{"is_alive":true,"service_status":"operational","service_message":"","updated_at":"","model_statuses":[]}`; a bogus bearer is ignored.
+- `GET`/`POST` on `/models`, `/models/{id}`, `/files`, `/files/{id}`,
+ `/responses`, `/responses/{id}`, `/responses/input_tokens`,
+ `/chat/completions`, `/images/generations`, `/images/edits` -> 401
+ `{"error":{"code":"invalid_api_key","message":"Unauthorized","param":null,"type":"authentication_error"}}`.
+- `/messages`, `/messages/count_tokens` -> 401
+ `{"error":{"message":"Unauthorized","type":"authentication_error"},"type":"error"}` (Anthropic envelope).
+- Authentication is checked before routing: an unknown path also answers 401.
+- `POST /asr/transcribe` without multipart -> 415 `unsupported_media_type` with a
+ `sessionId`; `GET` -> 404 with an empty body.
+- `wss://api.meta.ai/v1/asr/realtime`: upgrade answers 101; with no handshake
+ frame the server sends `{"type":"error","message":"Handshake timeout",...,"errorType":"invalid_request_error"}`.
+- The opt-in live test (`MOLO_LIVE_NET=1`) re-runs the status and 401 probes
+ through the module and, with a key, lists models (read only). Paid paths
+ (images, SAM, transcription, completions) have no live test in this round:
+ no key exists.
+
+## Unverified
+
+- Every success body below the documented schemas was only checked against the
+ docs examples, never against a live keyed call: no key exists.
+- The `GET /status` model_statuses array element shape (live probe returned
+ `[]`; the docs give no schema for `StatusResponse`).
+- `image_generation_call` output items (documented in prose, absent from the
+ Responses schema union): `result` is read nowhere in code.
+- `custom` and `namespace` tool shapes (prose only).
+- A verbatim Responses SSE transcript is not published: the stream fold test
+ uses event names and fields from the schemas with a constructed order.
+- The empty-object receipt for `approval/request` / `userInput/request`
+ (schema `RequestReceipt` lists no fields).
+- MSP requests other than the handshake were never run against a `muse` host.
+- Mask decoding is verified against two vendor conformance cases (one lossless,
+ one `one_bit`), not against live output.
+- Realtime WebSocket beyond the handshake timeout error was not driven.
+- Retry-After and `code`/`param` of error bodies (see Gaps).
+
+## Gaps
+
+- `llm::ApiError` keeps only `type` (preferring Meta's category) and drops the
+ error `code` (`model_not_found`, `invalid_api_key`, `payload_too_large`...),
+ `param` and the `Retry-After` header. Owner: `src/llm/error.cpp`
+ (foundation, not editable here). `RetryPolicy` therefore works from the status
+ only.
+- `ApiClient::stream` is POST-only; streaming retrieve is read whole, then
+ decoded. `ApiClient` cannot send an unauthenticated request; `/status` sends
+ a placeholder bearer (`MetaClient::kPlaceholderKey`).
+- `MetaChatModel::stream` cannot return the encrypted reasoning for replay
+ (`ChatChunk` has no signature field); use `generate` or `previous_response_id`
+ for reasoning continuity across streamed turns.
+- Batch API, fine-tuning and embeddings do not exist on this platform per the
+ docs; nothing is implemented for them.
+- Muse Spark Open and Muse Glimmer are open weights with no Model API surface;
+ they are in the catalog only. Self-hosted serving is out of scope.
+- Realtime audio pacing (real time or 1008) is the caller's job.
diff --git a/src/meta/calls.cpp b/src/meta/calls.cpp
new file mode 100644
index 0000000..9866632
--- /dev/null
+++ b/src/meta/calls.cpp
@@ -0,0 +1,65 @@
+#include "meta/calls.h"
+
+#include
+
+#include "llm/api_client.h"
+
+namespace molo::meta {
+
+// CALLS-BEGIN (parsed by tools/check_spec.py; one row per line)
+static const CallSpec kCalls[] = {
+ {Call::kResponsesCreate, "POST", "/responses", "responses/create-response", "responses", "CreateResponse", "Response", "model,input,instructions,previous_response_id,store,stream,background,max_output_tokens,max_tool_calls,temperature,top_p,frequency_penalty,presence_penalty,reasoning,text,tools,parallel_tool_calls,include,truncation,metadata,safety_identifier,prompt_cache_key,prompt_cache_retention,service_tier", ""},
+ {Call::kResponsesRetrieve, "GET", "/responses/{response_id}", "responses/retrieve-response", "responses", "", "Response", "", "stream,starting_after"},
+ {Call::kResponsesDelete, "DELETE", "/responses/{response_id}", "responses/delete-response", "responses", "", "DeleteResponseResponse", "", ""},
+ {Call::kResponsesCancel, "POST", "/responses/{response_id}/cancel", "responses/cancel-response", "responses", "", "CancelResponseResponse", "", ""},
+ {Call::kResponsesInputTokens, "POST", "/responses/input_tokens", "responses/count-input-tokens", "responses", "TokenCountsBody", "TokenCountsResource", "model,input,instructions,previous_response_id,tools,parallel_tool_calls,reasoning,text,truncation", ""},
+ {Call::kChatCompletionsCreate, "POST", "/chat/completions", "chat-completions/create-chat-completion", "chat-completions", "CreateChatCompletionRequest", "CreateChatCompletionResponse", "model,messages,temperature,top_p,frequency_penalty,presence_penalty,max_completion_tokens,stream,stream_options,reasoning_effort,seed,prompt_cache_retention,safety_identifier,prompt_cache_key,tools,tool_choice,parallel_tool_calls,response_format,metadata,service_tier,user", ""},
+ {Call::kMessagesCreate, "POST", "/messages", "messages/create-message", "messages", "AnthropicMessageRequest", "AnthropicMessage", "model,messages,max_tokens,system,tools,tool_choice,metadata,temperature,top_p,thinking,service_tier,output_config,stream,cache_control,context_management", ""},
+ {Call::kMessagesCountTokens, "POST", "/messages/count_tokens", "messages/count-tokens", "messages", "AnthropicCountTokensRequest", "AnthropicCountTokensResponse", "model,messages,system,tools,tool_choice,metadata,temperature,top_p,thinking,output_config", ""},
+ {Call::kFilesUpload, "POST", "/files", "files/upload-file", "files", "CreateFileRequest", "FileObject", "file,purpose,expires_after", ""},
+ {Call::kFilesList, "GET", "/files", "files/list-files", "files", "", "ListFilesResponse", "", "purpose,limit,order,after"},
+ {Call::kFilesRetrieve, "GET", "/files/{file_id}", "files/retrieve-file", "files", "", "FileObject", "", ""},
+ {Call::kFilesContent, "GET", "/files/{file_id}/content", "files/retrieve-file-content", "files", "", "", "", ""},
+ {Call::kFilesDelete, "DELETE", "/files/{file_id}", "files/delete-file", "files", "", "DeleteFileResponse", "", ""},
+ {Call::kImagesGenerate, "POST", "/images/generations", "images/create-image", "images", "CreateImageRequest", "ImagesResponse", "model,prompt,n,size,response_format,moderation,output_format,reasoning_strength,user,stream,tool_enablement", ""},
+ {Call::kImagesEdit, "POST", "/images/edits", "images/edit-image", "images", "EditImageBodyJsonParam", "ImagesResponse", "model,prompt,images,n,size,response_format,output_format,reasoning_strength,moderation,stream,user,tool_enablement", ""},
+ {Call::kModelsList, "GET", "/models", "models/list-models", "models", "", "ListModelsResponse", "", ""},
+ {Call::kModelsRetrieve, "GET", "/models/{model}", "models/retrieve-model", "models", "", "Model", "", ""},
+ {Call::kStatus, "GET", "/status", "status", "", "", "", "", ""},
+ {Call::kAsrTranscribe, "POST", "/asr/transcribe", "voice/transcribe", "voice", "TranscribeRequest", "TranscribeResponse", "model,audioEncoding,mode,keywords,languageBias,partialMode,emitAudioProgress", "sessionId"},
+ {Call::kAsrRealtime, "WS", "/asr/realtime", "voice/realtime", "voice", "RealtimeHandshakeRequest", "RealtimeHandshakeResponse", "authorization,audioEncoding,model,mode,partialMode,emitAudioProgress,keywords,languageBias", "sessionId"},
+};
+// CALLS-END
+
+const CallSpec& spec_of(Call call) {
+ for (const CallSpec& s : kCalls)
+ if (s.call == call) return s;
+ throw llm::ApiError::invalid("meta", "unknown call");
+}
+
+std::size_t call_count() { return sizeof(kCalls) / sizeof(kCalls[0]); }
+
+const CallSpec& spec_at(std::size_t index) {
+ if (index >= call_count()) throw llm::ApiError::invalid("meta", "call index out of range");
+ return kCalls[index];
+}
+
+clients::Method method_of(Call call) {
+ const char* m = spec_of(call).http_method;
+ if (!std::strcmp(m, "POST")) return clients::Method::kPost;
+ if (!std::strcmp(m, "DELETE")) return clients::Method::kDelete;
+ if (!std::strcmp(m, "GET")) return clients::Method::kGet;
+ throw llm::ApiError::invalid("meta", "call is not an HTTP request");
+}
+
+std::string path_for(Call call, const std::string& id) {
+ std::string path = spec_of(call).path;
+ std::size_t open = path.find('{');
+ if (open == std::string::npos) return path;
+ if (!llm::Service::valid_id(id)) throw llm::ApiError::invalid("meta", "bad id for " + path);
+ std::size_t close = path.find('}', open);
+ path.replace(open, close - open + 1, id);
+ return path;
+}
+
+} // namespace molo::meta
diff --git a/src/meta/calls.h b/src/meta/calls.h
new file mode 100644
index 0000000..fd55783
--- /dev/null
+++ b/src/meta/calls.h
@@ -0,0 +1,48 @@
+#pragma once
+
+// The ONE table of Meta Model API calls this module makes. Every row is
+// checked against the published docs by tools/check_spec.py (the docs are
+// prose plus schema tables, there is no OpenAPI document). Code builds every
+// path from this table, never from a literal.
+
+#include
+#include
+
+#include "clients/request.h"
+
+namespace molo::meta {
+
+enum class Call {
+ kResponsesCreate, kResponsesRetrieve, kResponsesDelete, kResponsesCancel,
+ kResponsesInputTokens,
+ kChatCompletionsCreate,
+ kMessagesCreate, kMessagesCountTokens,
+ kFilesUpload, kFilesList, kFilesRetrieve, kFilesContent, kFilesDelete,
+ kImagesGenerate, kImagesEdit,
+ kModelsList, kModelsRetrieve,
+ kStatus,
+ kAsrTranscribe, kAsrRealtime,
+};
+
+struct CallSpec {
+ Call call;
+ const char* http_method; // GET POST DELETE, or WS for the realtime socket
+ const char* path; // template under the base URL, "{id}" placeholders
+ const char* operation; // docs page slug under /docs/api-reference/
+ const char* schema_group; // docs schemas page: /docs/api-reference//schemas
+ const char* request_schema; // schema name in the group, "" when no body
+ const char* response_schema; // schema name, "" when raw bytes or a socket
+ const char* body_fields; // comma list: request body fields we send
+ const char* query_params; // comma list: query parameters we send
+};
+
+const CallSpec& spec_of(Call call);
+std::size_t call_count();
+const CallSpec& spec_at(std::size_t index);
+clients::Method method_of(Call call);
+
+// Fills the first "{...}" placeholder of the call's path with `id` after
+// validating it as a single path segment. Throws llm::ApiError::invalid.
+std::string path_for(Call call, const std::string& id = "");
+
+} // namespace molo::meta
diff --git a/src/meta/caps.h b/src/meta/caps.h
new file mode 100644
index 0000000..67aa4aa
--- /dev/null
+++ b/src/meta/caps.h
@@ -0,0 +1,58 @@
+#pragma once
+
+// Static ceilings and documented limits for the Meta Model API module. Every
+// value is a constant you can read; nothing is autotuned. Documented vendor
+// limits are marked "docs"; the rest are our own floors and ceilings.
+
+#include
+
+namespace molo::meta {
+
+struct MetaCaps {
+ // Request shaping (docs: error-handling, protocols/responses).
+ static constexpr int kMinOutputTokens = 16; // docs: max_output_tokens minimum
+ static constexpr std::size_t kMaxInputItems = 4096; // ours
+ static constexpr std::size_t kMaxTools = 256; // ours (matches llm::Caps)
+ static constexpr std::size_t kMaxIdBytes = 256; // ours
+ static constexpr std::size_t kMaxCallIdBytes = 64; // docs: call_id 1..64
+ static constexpr std::size_t kMaxSafetyIdBytes = 64; // docs
+ static constexpr std::size_t kMaxModelBytes = 128; // ours
+ static constexpr std::size_t kMaxPromptBytes = 4u * 1024u * 1024u; // ours
+ static constexpr std::size_t kMaxBackgroundBodyBytes = 1048576; // docs: 1 MiB
+ static constexpr std::size_t kMaxInlineBytes = 50000000; // docs: 50 MB inline media
+ static constexpr std::size_t kMaxImageCount = 50; // docs: 50 images per request
+ static constexpr int kMaxImagesPerCall = 10; // docs: n 1..10
+ static constexpr std::size_t kMaxMetadataPairs = 16; // ours
+ // Files (docs: file-handling). The vendor allows 1 GiB; llm::Caps stops at 512 MiB.
+ static constexpr std::size_t kMaxUploadBytes = 512u * 1024u * 1024u;
+ static constexpr long kMinExpireSeconds = 3600; // docs
+ static constexpr long kMaxExpireSeconds = 2592000; // docs
+ static constexpr int kListPageLimit = 1000; // ours (docs allow 10000)
+ static constexpr std::size_t kMaxListPages = 20; // ours
+ // Speech (docs: speech-to-text).
+ static constexpr std::size_t kMaxTranscribeBytes = 32u * 1000u * 1000u; // docs: 32 MB
+ static constexpr long kMaxTranscribeMs = 10L * 60L * 1000L; // docs: 10 minutes
+ static constexpr std::size_t kMaxKeywords = 256; // ours
+ static constexpr int kRealtimeHandshakeMs = 10000; // docs: first frame within 10 s
+ static constexpr int kConnectTimeoutMs = 10000; // ours
+ static constexpr int kRealtimeIdleMs = 30000; // ours
+ static constexpr std::size_t kMaxRealtimeAudioFrame = 1u * 1024u * 1024u; // ours
+ static constexpr std::size_t kMaxRealtimeEvents = 100000; // ours
+ static constexpr std::size_t kMaxStreamEvents = 1000000; // ours: events folded per HTTP stream
+ // Retry (docs: pricing-rate-limits, error-handling).
+ static constexpr int kMaxRetries = 5;
+ static constexpr int kBackoffBaseMs = 500; // docs: start near 500 ms
+ static constexpr int kBackoffCapMs = 30000; // ours
+ // Segmentation output parsing.
+ static constexpr std::size_t kMaxSamLines = 100000; // ours
+ static constexpr std::size_t kMaxSamRecords = 1000000; // ours
+ static constexpr std::size_t kMaxMaskPixels = 64u * 1024u * 1024u; // ours
+ // Muse Code session protocol (MSP).
+ static constexpr std::size_t kMspFrameLimit = 10485760; // MSP transcript manifest: frameLimitBytes
+ static constexpr std::size_t kMspMaxPending = 64; // ours
+ static constexpr std::size_t kMspMaxQueued = 4096; // ours
+ static constexpr int kMspRequestTimeoutMs = 120000; // ours
+ static constexpr int kMspSpawnTimeoutMs = 10000; // ours
+};
+
+} // namespace molo::meta
diff --git a/src/meta/catalog.cpp b/src/meta/catalog.cpp
new file mode 100644
index 0000000..6d41f0c
--- /dev/null
+++ b/src/meta/catalog.cpp
@@ -0,0 +1,64 @@
+#include "meta/catalog.h"
+
+namespace molo::meta {
+
+// CATALOG-BEGIN (parsed by tools/check_spec.py; one row per line)
+// id, family, kind, hosted, contributor, supports_max, context, cached, input, output, other_price, rpm, tpm, note
+static const ModelInfo kModels[] = {
+ {"muse-wonder-1.0", "Muse Wonder", ModelKind::kText, true, false, true, 1048576, 0.20, 4.00, 20.00, "", 3000, 4000000, "preview; Standard mode only on Model API"},
+ {"muse-spark-1.3", "Muse Spark", ModelKind::kText, true, false, true, 1048576, 0.15, 1.25, 4.25, "", 3000, 4000000, "recommended for new work"},
+ {"muse-spark-1.2", "Muse Spark", ModelKind::kText, true, false, false, 1048576, 0.15, 1.25, 4.25, "", 3000, 4000000, "previous version"},
+ {"muse-spark-1.1", "Muse Spark", ModelKind::kText, true, false, false, 1048576, 0.15, 1.25, 4.25, "", 3000, 4000000, "original version, Standard mode only"},
+ {"muse-spark-1.3-contributor", "Muse Spark", ModelKind::kText, true, true, false, 1048576, 0.002, 0.10, 0.20, "", 150, 3000000, "Contributor mode: content may train Meta models"},
+ {"muse-spark-1.2-contributor", "Muse Spark", ModelKind::kText, true, true, false, 1048576, 0.002, 0.10, 0.20, "", 150, 3000000, "Contributor mode: content may train Meta models"},
+ {"muse-image-1.0", "Muse Image", ModelKind::kImage, true, false, false, 0, 0, 0, 0, "$0.01 per generated image", 150, 0, "generation and editing"},
+ {"muse-voice-transcribe-1.0", "Muse Voice Transcribe", ModelKind::kSpeech, true, false, false, 0, 0, 0, 0, "$0.18 per hour of audio", 0, 0, "256 concurrent streams, 16000 streams per hour"},
+ {"sam-3.1", "Segment Anything Model", ModelKind::kSegmenter, true, false, false, 0, 0, 0, 0, "$2.50 per 1000 images, $0.20 per 1000 video frames", 3000, 0, "video bills at least 50 frames"},
+ {"muse-spark-open", "Muse Spark Open", ModelKind::kOpenWeight, false, false, false, 0, 0, 0, 0, "open weights, self-hosted", 0, 0, "816B MoE, 42B active; no Model API"},
+ {"muse-glimmer", "Muse Glimmer", ModelKind::kOpenWeight, false, false, false, 0, 0, 0, 0, "open weights, self-hosted", 0, 0, "distilled from Muse Spark; no Model API"},
+};
+// CATALOG-END
+
+std::size_t ModelCatalog::size() { return sizeof(kModels) / sizeof(kModels[0]); }
+
+const ModelInfo& ModelCatalog::at(std::size_t index) { return kModels[index % size()]; }
+
+const ModelInfo* ModelCatalog::find(const std::string& id) {
+ for (const ModelInfo& m : kModels)
+ if (id == m.id) return &m;
+ return nullptr;
+}
+
+bool ModelCatalog::is_text_model(const std::string& id) {
+ const ModelInfo* m = find(id);
+ return m && m->kind == ModelKind::kText;
+}
+
+bool ModelCatalog::accepts_max_effort(const std::string& id) {
+ const ModelInfo* m = find(id);
+ return m && m->supports_max;
+}
+
+const char* ModelCatalog::kind_name(ModelKind kind) {
+ switch (kind) {
+ case ModelKind::kText: return "text";
+ case ModelKind::kImage: return "image";
+ case ModelKind::kSpeech: return "speech";
+ case ModelKind::kSegmenter: return "segmentation";
+ case ModelKind::kOpenWeight: return "open-weight";
+ }
+ return "unknown";
+}
+
+const std::vector& ReasoningEfforts::accepted() {
+ static const std::vector v = {"minimal", "low", "medium", "high", "xhigh", "max"};
+ return v;
+}
+
+bool ReasoningEfforts::valid(const std::string& value) {
+ for (const std::string& e : accepted())
+ if (e == value) return true;
+ return false;
+}
+
+} // namespace molo::meta
diff --git a/src/meta/catalog.h b/src/meta/catalog.h
new file mode 100644
index 0000000..eddd416
--- /dev/null
+++ b/src/meta/catalog.h
@@ -0,0 +1,58 @@
+#pragma once
+
+// Static catalog of the Meta models named by the docs (models, pricing and
+// rate-limit pages). It is a specification table: request validation reads
+// it (for example which models accept reasoning effort "max") and the demo
+// prints it. It is NOT the live model list: ask ModelsService for that.
+
+#include
+#include
+#include
+
+namespace molo::meta {
+
+enum class ModelKind {
+ kText, // Muse Wonder, Muse Spark: Responses, Chat Completions, Messages
+ kImage, // Muse Image: Responses, Images
+ kSpeech, // Muse Voice Transcribe: ASR file and realtime
+ kSegmenter, // Segment Anything Model 3.1: Responses
+ kOpenWeight, // Muse Spark Open, Muse Glimmer: self-hosted, no Model API
+};
+
+struct ModelInfo {
+ const char* id;
+ const char* family; // "Muse Wonder", "Muse Spark", ...
+ ModelKind kind;
+ bool hosted; // callable on api.meta.ai
+ bool contributor; // Contributor mode variant (content may train models)
+ bool supports_max; // reasoning effort "max"
+ long context_tokens; // 0 when not applicable
+ double cached_per_m; // USD per 1M cached input tokens, 0 when n/a
+ double input_per_m; // USD per 1M input tokens, 0 when n/a
+ double output_per_m; // USD per 1M output tokens, 0 when n/a
+ const char* other_price; // non-token pricing, "" when token priced
+ long rpm; // requests per minute, 0 = none documented
+ long tpm; // tokens per minute, 0 = none documented
+ const char* note;
+};
+
+class ModelCatalog {
+ public:
+ static std::size_t size();
+ static const ModelInfo& at(std::size_t index);
+ // nullptr when the id is not in the docs.
+ static const ModelInfo* find(const std::string& id);
+ static bool is_text_model(const std::string& id);
+ // True when the id is a documented text model that accepts "max".
+ static bool accepts_max_effort(const std::string& id);
+ static const char* kind_name(ModelKind kind);
+};
+
+// Documented reasoning efforts. "none" is documented as rejected by Muse
+// models, so it is listed separately and never offered.
+struct ReasoningEfforts {
+ static const std::vector& accepted(); // minimal..max
+ static bool valid(const std::string& value);
+};
+
+} // namespace molo::meta
diff --git a/src/meta/chat_completions.cpp b/src/meta/chat_completions.cpp
new file mode 100644
index 0000000..752d39b
--- /dev/null
+++ b/src/meta/chat_completions.cpp
@@ -0,0 +1,293 @@
+#include "meta/chat_completions.h"
+
+#include "meta/calls.h"
+#include "meta/caps.h"
+#include "meta/check.h"
+#include "meta/schema_check.h"
+
+namespace molo::meta {
+
+namespace {
+Json msg(const char* role, const Json& content) {
+ Json o = Json::object();
+ o.set("role", Json(role));
+ o.set("content", content);
+ return o;
+}
+Json part(const char* type) {
+ Json o = Json::object();
+ o.set("type", Json(type));
+ return o;
+}
+} // namespace
+
+Json ChatMessage::developer(const std::string& t) { return msg("developer", Json(t)); }
+Json ChatMessage::system(const std::string& t) { return msg("system", Json(t)); }
+Json ChatMessage::user(const std::string& t) { return msg("user", Json(t)); }
+
+Json ChatMessage::user_parts(const std::vector& parts) {
+ Json a = Json::array();
+ for (const Json& p : parts) a.push(p);
+ return msg("user", a);
+}
+
+Json ChatMessage::assistant(const std::string& t) { return msg("assistant", Json(t)); }
+
+Json ChatMessage::assistant_tool_calls(const std::string& t, const std::vector& calls) {
+ Json m = msg("assistant", t.empty() ? Json() : Json(t));
+ Json a = Json::array();
+ for (const Json& c : calls) a.push(c);
+ m.set("tool_calls", a);
+ return m;
+}
+
+Json ChatMessage::tool_result(const std::string& id, const std::string& content) {
+ Check::call_id(id);
+ Json m = msg("tool", Json(content));
+ m.set("tool_call_id", Json(id));
+ return m;
+}
+
+Json ChatMessage::text_part(const std::string& t) {
+ Json p = part("text");
+ p.set("text", Json(t));
+ return p;
+}
+
+Json ChatMessage::image_part(const std::string& url, const std::string& detail) {
+ Check::non_empty("image url", url);
+ if (!detail.empty()) Check::one_of("detail", detail, {"auto", "low", "high"});
+ Json p = part("image_url");
+ Json i = Json::object();
+ i.set("url", Json(url));
+ JsonX::set_if(i, "detail", detail);
+ p.set("image_url", i);
+ return p;
+}
+
+Json ChatMessage::video_part(const std::string& url, double fps) {
+ Check::non_empty("video url", url);
+ Json p = part("video_url");
+ Json v = Json::object();
+ v.set("url", Json(url));
+ if (fps > 0) v.set("fps", Json(fps));
+ p.set("video_url", v);
+ return p;
+}
+
+Json ChatMessage::file_part(const std::string& filename, const std::string& data_url,
+ const std::string& file_id) {
+ if (data_url.empty() && file_id.empty()) Check::fail("file part needs file_data or file_id");
+ Json p = part("file");
+ Json f = Json::object();
+ JsonX::set_if(f, "filename", filename);
+ JsonX::set_if(f, "file_data", data_url);
+ if (!file_id.empty()) {
+ Check::segment("file_id", file_id);
+ f.set("file_id", Json(file_id));
+ }
+ p.set("file", f);
+ return p;
+}
+
+Json ChatMessage::audio_part(const std::string& format, const std::string& b64) {
+ Check::one_of("format", format, {"wav", "mp3"});
+ Check::non_empty("audio data", b64);
+ Json p = part("input_audio");
+ Json a = Json::object();
+ a.set("data", Json(b64));
+ a.set("format", Json(format));
+ p.set("input_audio", a);
+ return p;
+}
+
+Json ChatMessage::tool_call(const std::string& id, const std::string& name,
+ const std::string& arguments) {
+ Check::call_id(id);
+ Check::function_name(name);
+ Json c = Json::object();
+ c.set("id", Json(id));
+ c.set("type", Json("function"));
+ Json f = Json::object();
+ f.set("name", Json(name));
+ f.set("arguments", Json(arguments.empty() ? "{}" : arguments));
+ c.set("function", f);
+ return c;
+}
+
+Json ChatMessage::function_tool(const std::string& name, const std::string& description,
+ const Json& parameters, bool strict) {
+ Check::function_name(name);
+ if (parameters.is_object()) SchemaCheck::check(parameters, strict);
+ Json f = Json::object();
+ f.set("name", Json(name));
+ JsonX::set_if(f, "description", description);
+ f.set("parameters", parameters.is_object() ? parameters : Json::object());
+ if (strict) f.set("strict", Json(true));
+ Json t = Json::object();
+ t.set("type", Json("function"));
+ t.set("function", f);
+ return t;
+}
+
+Json ChatCompletionRequest::format_json_object() {
+ Json f = Json::object();
+ f.set("type", Json("json_object"));
+ return f;
+}
+
+Json ChatCompletionRequest::format_json_schema(const std::string& name, const Json& schema,
+ bool strict, const std::string& description) {
+ Check::non_empty("name", name);
+ SchemaCheck::check(schema, strict);
+ Json js = Json::object();
+ js.set("name", Json(name));
+ js.set("schema", schema);
+ if (strict) js.set("strict", Json(true));
+ JsonX::set_if(js, "description", description);
+ Json f = Json::object();
+ f.set("type", Json("json_schema"));
+ f.set("json_schema", js);
+ return f;
+}
+
+void ChatCompletionRequest::validate() const {
+ Check::model_id(model);
+ if (messages.empty() || messages.size() > MetaCaps::kMaxInputItems)
+ Check::fail("messages needs 1.." + std::to_string(MetaCaps::kMaxInputItems) + " entries");
+ for (const Json& m : messages) {
+ Check::one_of("message role", JsonX::str(m, "role"),
+ {"developer", "system", "user", "assistant", "tool"});
+ }
+ if (tools.size() > MetaCaps::kMaxTools) Check::fail("too many tools");
+ for (const Json& t : tools) {
+ if (JsonX::str(t, "type") != "function")
+ Check::fail("chat completions accepts function tools only (custom tools are Responses-only)");
+ if (const Json* f = JsonX::obj(t, "function")) Check::function_name(JsonX::str(*f, "name"));
+ }
+ if (max_completion_tokens && *max_completion_tokens < 1)
+ Check::fail("max_completion_tokens must be positive");
+ if (temperature) Check::temperature(*temperature);
+ if (top_p) Check::top_p(*top_p);
+ if (frequency_penalty) Check::penalty("frequency_penalty", *frequency_penalty);
+ if (presence_penalty) Check::penalty("presence_penalty", *presence_penalty);
+ Check::reasoning_effort(model, reasoning_effort);
+ Check::safety_identifier(safety_identifier);
+ Check::prompt_cache_retention(prompt_cache_retention);
+ if (!service_tier.empty())
+ Check::one_of("service_tier", service_tier, {"auto", "default", "flex", "scale", "priority"});
+ if (metadata.size() > MetaCaps::kMaxMetadataPairs) Check::fail("too many metadata pairs");
+ if (response_format.is_object()) {
+ std::string type = JsonX::str(response_format, "type");
+ Check::one_of("response_format.type", type, {"text", "json_object", "json_schema"});
+ if (type == "json_schema") {
+ const Json* js = JsonX::obj(response_format, "json_schema");
+ const Json* s = js ? JsonX::obj(*js, "schema") : nullptr;
+ if (!s) Check::fail("response_format json_schema needs json_schema.schema");
+ SchemaCheck::check(*s, JsonX::flag(*js, "strict"));
+ }
+ }
+ // Fields the docs reject on this endpoint must not arrive through `extra`.
+ if (extra.is_object())
+ for (const char* banned : {"n", "stop", "logit_bias", "prediction", "verbosity",
+ "web_search_options", "modalities", "audio", "logprobs", "text",
+ "max_output_tokens"})
+ if (extra.has(banned)) Check::fail(std::string(banned) + " is rejected by chat completions");
+}
+
+Json ChatCompletionRequest::to_json(bool stream) const {
+ validate();
+ Json b = Json::object();
+ b.set("model", Json(model));
+ Json m = Json::array();
+ for (const Json& x : messages) m.push(x);
+ b.set("messages", m);
+ if (!tools.empty()) {
+ Json t = Json::array();
+ for (const Json& x : tools) t.push(x);
+ b.set("tools", t);
+ }
+ if (response_format.is_object()) b.set("response_format", response_format);
+ JsonX::set_if(b, "reasoning_effort", reasoning_effort);
+ if (max_completion_tokens) b.set("max_completion_tokens", Json(*max_completion_tokens));
+ if (temperature) b.set("temperature", Json(*temperature));
+ if (top_p) b.set("top_p", Json(*top_p));
+ if (frequency_penalty) b.set("frequency_penalty", Json(*frequency_penalty));
+ if (presence_penalty) b.set("presence_penalty", Json(*presence_penalty));
+ if (seed) b.set("seed", Json(*seed));
+ if (parallel_tool_calls) b.set("parallel_tool_calls", Json(*parallel_tool_calls));
+ JsonX::set_if(b, "safety_identifier", safety_identifier);
+ JsonX::set_if(b, "prompt_cache_key", prompt_cache_key);
+ JsonX::set_if(b, "prompt_cache_retention", prompt_cache_retention);
+ JsonX::set_if(b, "service_tier", service_tier);
+ if (!metadata.empty()) {
+ Json md = Json::object();
+ for (const auto& [k, v] : metadata) md.set(k, Json(v));
+ b.set("metadata", md);
+ }
+ if (stream) {
+ b.set("stream", Json(true));
+ if (include_usage) {
+ Json so = Json::object();
+ so.set("include_usage", Json(true));
+ b.set("stream_options", so);
+ }
+ }
+ JsonX::merge(b, extra);
+ return b;
+}
+
+void ChatChunkAccumulator::feed(const Json& chunk) {
+ id_ = JsonX::str(chunk, "id", id_);
+ model_ = JsonX::str(chunk, "model", model_);
+ if (const Json* u = JsonX::obj(chunk, "usage")) {
+ usage_ = MetaUsage::from_chat(*u);
+ has_usage_ = true;
+ }
+ const Json* choices = JsonX::arr(chunk, "choices");
+ if (!choices || choices->as_array().empty()) return;
+ const Json& c = choices->as_array()[0];
+ std::string fr = JsonX::str(c, "finish_reason");
+ if (!fr.empty()) finish_reason_ = fr;
+ const Json* d = JsonX::obj(c, "delta");
+ if (!d) return;
+ text_ += JsonX::str(*d, "content");
+ reasoning_ += JsonX::str(*d, "reasoning_content");
+ if (const Json* tcs = JsonX::arr(*d, "tool_calls"))
+ for (const Json& tc : tcs->as_array()) {
+ long idx = JsonX::num(tc, "index", 0);
+ ChatToolCallState* st = nullptr;
+ for (ChatToolCallState& s : calls_)
+ if (s.index == idx) st = &s;
+ if (!st) {
+ calls_.push_back({});
+ st = &calls_.back();
+ st->index = idx;
+ }
+ st->id = JsonX::str(tc, "id", st->id);
+ if (const Json* f = JsonX::obj(tc, "function")) {
+ st->name = JsonX::str(*f, "name", st->name);
+ st->arguments += JsonX::str(*f, "arguments");
+ }
+ }
+}
+
+Json ChatCompletionsService::create(const ChatCompletionRequest& request) {
+ Json body = request.to_json(false);
+ return client_->post(path_for(Call::kChatCompletionsCreate), body);
+}
+
+ChatChunkAccumulator ChatCompletionsService::stream(const ChatCompletionRequest& request,
+ const ChunkSink& sink) {
+ Json body = request.to_json(true);
+ ChatChunkAccumulator acc;
+ std::size_t seen = 0;
+ client_->stream(path_for(Call::kChatCompletionsCreate), body, [&](const llm::SseEvent& e) {
+ if (++seen > MetaCaps::kMaxStreamEvents) return false;
+ acc.feed(e.data);
+ return sink ? sink(e.data) : true;
+ });
+ return acc;
+}
+
+} // namespace molo::meta
diff --git a/src/meta/chat_completions.h b/src/meta/chat_completions.h
new file mode 100644
index 0000000..652bdc3
--- /dev/null
+++ b/src/meta/chat_completions.h
@@ -0,0 +1,114 @@
+#pragma once
+
+// POST /chat/completions: the OpenAI-compatible messages-array endpoint for
+// the Muse Spark and Muse Wonder text models. It does not carry reasoning
+// across turns (reasoning_content is redacted for external keys); use the
+// Responses API for that. Rules enforced before any traffic (docs:
+// protocols/chat-completions): n is always 1, stop / logit_bias / prediction /
+// verbosity / web_search_options / modalities are not offered, tool_choice is
+// only "auto", reasoning_effort "none" is rejected, response_format and tools
+// pass the schema pre-flight.
+
+#include
+#include
+#include
+#include
+
+#include "llm/api_client.h"
+#include "meta/jsonx.h"
+#include "meta/usage.h"
+
+namespace molo::meta {
+
+class ChatMessage {
+ public:
+ static Json developer(const std::string& text);
+ static Json system(const std::string& text); // same level as developer
+ static Json user(const std::string& text);
+ static Json user_parts(const std::vector& parts);
+ static Json assistant(const std::string& text);
+ static Json assistant_tool_calls(const std::string& text, const std::vector& tool_calls);
+ static Json tool_result(const std::string& tool_call_id, const std::string& content);
+ // Content parts.
+ static Json text_part(const std::string& text);
+ static Json image_part(const std::string& url, const std::string& detail = "");
+ static Json video_part(const std::string& url, double fps = 0);
+ static Json file_part(const std::string& filename, const std::string& file_data_url,
+ const std::string& file_id = "");
+ static Json audio_part(const std::string& format, const std::string& base64_data);
+ // {id, type:"function", function:{name, arguments}}
+ static Json tool_call(const std::string& id, const std::string& name,
+ const std::string& arguments_json);
+ // Tool definition: {type:"function", function:{name, description, parameters, strict}}
+ static Json function_tool(const std::string& name, const std::string& description,
+ const Json& parameters, bool strict = false);
+};
+
+struct ChatCompletionRequest {
+ std::string model;
+ std::vector messages;
+ std::vector tools;
+ Json response_format; // null, or {type: json_object | json_schema, json_schema:{...}}
+ std::string reasoning_effort; // minimal..max
+ std::optional max_completion_tokens;
+ std::optional temperature;
+ std::optional top_p;
+ std::optional frequency_penalty;
+ std::optional presence_penalty;
+ std::optional seed;
+ std::optional parallel_tool_calls;
+ std::string safety_identifier;
+ std::string prompt_cache_key;
+ std::string prompt_cache_retention;
+ std::string service_tier;
+ bool include_usage = true; // stream_options.include_usage when streaming
+ std::vector> metadata;
+ Json extra;
+
+ void validate() const;
+ Json to_json(bool stream = false) const;
+
+ static Json format_json_object();
+ static Json format_json_schema(const std::string& name, const Json& schema, bool strict = false,
+ const std::string& description = "");
+};
+
+struct ChatToolCallState {
+ long index = 0;
+ std::string id, name, arguments;
+};
+
+// Folds chat.completion.chunk objects into text, reasoning_content, tool calls,
+// finish_reason and usage.
+class ChatChunkAccumulator {
+ public:
+ void feed(const Json& chunk);
+ const std::string& text() const { return text_; }
+ const std::string& reasoning() const { return reasoning_; }
+ const std::string& finish_reason() const { return finish_reason_; }
+ const std::string& id() const { return id_; }
+ const std::string& model() const { return model_; }
+ const std::vector& tool_calls() const { return calls_; }
+ bool has_usage() const { return has_usage_; }
+ MetaUsage usage() const { return usage_; }
+
+ private:
+ std::string text_, reasoning_, finish_reason_, id_, model_;
+ std::vector calls_;
+ MetaUsage usage_;
+ bool has_usage_ = false;
+};
+
+class ChatCompletionsService : public llm::Service {
+ public:
+ using ChunkSink = std::function; // false: stop
+
+ explicit ChatCompletionsService(std::shared_ptr client)
+ : llm::Service(std::move(client)) {}
+
+ Json create(const ChatCompletionRequest& request);
+ ChatChunkAccumulator stream(const ChatCompletionRequest& request,
+ const ChunkSink& sink = nullptr);
+};
+
+} // namespace molo::meta
diff --git a/src/meta/chat_model.cpp b/src/meta/chat_model.cpp
new file mode 100644
index 0000000..c80403d
--- /dev/null
+++ b/src/meta/chat_model.cpp
@@ -0,0 +1,285 @@
+#include "meta/chat_model.h"
+
+#include