diff --git a/example/app/agent/AdkDemo.cpp b/example/app/agent/AdkDemo.cpp index 4188f28..14dcc7d 100644 --- a/example/app/agent/AdkDemo.cpp +++ b/example/app/agent/AdkDemo.cpp @@ -1,13 +1,213 @@ #include "../AgentDemos.hpp" #include "../../fw/Router.hpp" +#include "../../fw/Templates.hpp" +#include "google/adk/ap2.h" +#include "google/adk/caps.h" +#include "google/adk/direct_model.h" +#include "google/adk/error.h" +#include "google/adk/garden.h" +#include "google/adk/runner.h" +#include "google/adk/studio.h" +#include "google/credentials.h" +#include "google/generative.h" namespace molo::example::app { -// Agent Platform: adk. Stub: the module agent fills this in. +// Agent Platform: Agent Development Kit (src/google/adk). Pages and the +// catalog work without a credential; /agent/adk/run is the one route that +// calls Google (503 google_not_configured without a key). + +namespace { + +using clients::body::Json; +namespace adk = google::adk; + +const char kAdkPage[] = R"ADK({% extends "base.html" %} +{% block content %} +

Agent Development Kit

+

Run a Garden template as an agent on Gemini, or export and +import an agent definition. Caps: 12 model calls, 24 tool calls, 60 s per turn.

+
+ + + + +

+
+ +{% endblock %} +)ADK"; + +Json parse_body(const fw::Request& req) { + try { + Json doc = Json::parse(req.body); + if (!doc.is_object()) throw std::runtime_error("object expected"); + return doc; + } catch (const std::exception&) { + throw fw::HttpError(422, "validation_error", "body must be a JSON object"); + } +} + +std::string text_of(const Json& doc, const char* key) { + const Json* v = doc.find(key); + return v && v->is_string() ? v->as_string() : ""; +} + +template +auto guarded(F&& f) -> decltype(f()) { + try { + return f(); + } catch (const adk::AdkError& e) { + if (e.code() == "invalid_argument") + throw fw::HttpError(422, "validation_error", e.message()); + throw fw::HttpError(502, "adk_error", e.message()); + } catch (const google::GoogleError& e) { + if (e.http_status() == 503 && e.status() == "NOT_CONFIGURED") + throw fw::HttpError(503, "google_not_configured", e.message()); + if (e.service().empty() && e.status() == "INVALID_ARGUMENT") + throw fw::HttpError(422, "validation_error", e.message()); + throw fw::HttpError(502, "google_error", e.status() + ": " + e.message()); + } +} + +fw::Response json_out(const Json& doc, int status = 200) { + fw::Response res = fw::JsonResponse(doc.dump(), status); + res.headers.set("Cache-Control", "no-store"); + return res; +} + +// The single local tool the demo agents get: deterministic, no network. +std::shared_ptr word_count_tool() { + Json text = Json::object(); + text.set("type", Json("string")); + Json props = Json::object(); + props.set("text", text); + Json req = Json::array(); + req.push(Json("text")); + Json schema = Json::object(); + schema.set("type", Json("object")); + schema.set("properties", props); + schema.set("required", req); + return std::make_shared( + "word_count", "Count the words in a text", schema, + [](const Json& args, adk::ToolContext&) { + const std::string& s = args.find("text")->as_string(); + long n = 0; + bool in = false; + for (char c : s) { + bool space = c == ' ' || c == '\n' || c == '\t'; + if (!space && !in) ++n; + in = !space; + } + Json out = Json::object(); + out.set("words", Json(n)); + return out; + }); +} + +} // namespace + void register_agent_adk_demo(fw::Router& router, Services& services) { - (void)router; - (void)services; + if (!services.google) services.google = google::GoogleClient::from_env(); + auto gclient = services.google; + fw::Environment* env = services.templates.get(); + env->add_template("adk.html", kAdkPage); + services.add_feature("agent-adk", "/agent/adk"); + + auto registry = std::make_shared(); + registry->add(word_count_tool()); + auto sessions = std::make_shared(); + + router.get("/agent/adk", "agent-adk-page", [env](fw::Request) { + fw::TemplateCtx ctx; + ctx["title"] = std::string("Agent Development Kit"); + return fw::Response(200, env->render("adk.html", ctx), "text/html; charset=utf-8"); + }); + + router.get("/agent/adk/status", "agent-adk-status", [gclient](fw::Request) { + using C = adk::AdkCaps; + Json caps = Json::object(); + caps.set("max_steps", Json(C::kMaxSteps)); + caps.set("max_tool_calls", Json(C::kMaxToolCalls)); + caps.set("max_wall_clock_ms", Json(C::kMaxWallClockMs)); + caps.set("max_sub_agents", Json(static_cast(C::kMaxSubAgents))); + caps.set("max_loop_iterations", Json(C::kMaxLoopIterations)); + Json out = Json::object(); + out.set("configured", Json(gclient->configured())); + out.set("model", Json(google::Generative::default_model())); + out.set("caps", caps); + out.set("templates", Json(static_cast(adk::AgentGarden::templates().size()))); + return json_out(out); + }); + + router.get("/agent/adk/garden", "agent-adk-garden", [](fw::Request) { + return json_out(adk::AgentGarden::catalog_json()); + }); + + // {"prompt": "...", "template": "invoice_processing", "cid": "optional"} + router.post("/agent/adk/run", "agent-adk-run", + [gclient, registry, sessions](fw::Request req) { + Json in = parse_body(req); + std::string prompt = text_of(in, "prompt"); + std::string tmpl = text_of(in, "template"); + std::string cid = text_of(in, "cid"); + if (tmpl.empty()) tmpl = "financial_analysis"; + if (cid.empty()) cid = "demo"; + return guarded([&] { + if (prompt.empty() || prompt.size() > 2000) + throw adk::AdkError::invalid("prompt must be 1..2000 characters"); + std::shared_ptr agent = adk::AgentGarden::instantiate(tmpl, *registry); + if (!gclient->configured()) throw google::NotConfiguredError("generativelanguage"); + bool express = google::Credentials::env().rfind("AQ.", 0) == 0; + auto model = std::make_shared( + gclient, google::Generative::default_model(), + express ? google::endpoints::vertex_generative() + : google::endpoints::generative()); + adk::Runner runner(model, sessions); + return json_out(runner.run(agent, cid, prompt).to_json()); + }); + }); + + // {"template": "invoice_processing"} -> the Agent Studio definition. + router.post("/agent/adk/export", "agent-adk-export", [registry](fw::Request req) { + Json in = parse_body(req); + return guarded([&] { + auto agent = adk::AgentGarden::instantiate(text_of(in, "template"), *registry); + Json out = Json::object(); + out.set("definition", adk::AgentDefinition::to_json(*agent)); + out.set("yaml", Json(adk::AgentDefinition::to_yaml(*agent))); + return json_out(out); + }); + }); + + // The body is an agent definition; answers its normalized re-export. + router.post("/agent/adk/import", "agent-adk-import", [registry](fw::Request req) { + return guarded([&] { + auto agent = adk::AgentDefinition::from_text(req.body, *registry); + return json_out(adk::AgentDefinition::to_json(*agent)); + }); + }); + + // {"intent": {...}, "cart": {...}, "payment": {...}} (cart and payment optional) + router.post("/agent/adk/ap2/validate", "agent-adk-ap2", [](fw::Request req) { + Json in = parse_body(req); + return guarded([&] { + const Json* i = in.find("intent"); + if (!i) throw adk::AdkError::invalid("intent is required"); + auto intent = adk::ap2::IntentMandate::from_json(*i); + intent.validate(); + if (const Json* c = in.find("cart")) { + auto cart = adk::ap2::CartMandate::from_json(*c); + cart.validate_against(intent); + if (const Json* p = in.find("payment")) + adk::ap2::PaymentMandate::from_json(*p).validate_against(cart); + } + Json out = Json::object(); + out.set("valid", Json(true)); + return json_out(out); + }); + }); } } // namespace molo::example::app diff --git a/example/assets/agent_adk.js b/example/assets/agent_adk.js new file mode 100644 index 0000000..f84b83f --- /dev/null +++ b/example/assets/agent_adk.js @@ -0,0 +1,25 @@ +(function () { + var select = document.getElementById("adk-template"); + var out = document.getElementById("adk-out"); + function show(res) { + return res.json().then(function (j) { out.textContent = JSON.stringify(j, null, 2); }); + } + function post(path, body) { + return fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body) }).then(show).catch(function (e) { out.textContent = String(e); }); + } + fetch("/agent/adk/garden").then(function (r) { return r.json(); }).then(function (j) { + j.templates.forEach(function (t) { + var o = document.createElement("option"); + o.value = t.id; o.textContent = t.title; select.appendChild(o); + }); + }); + document.getElementById("adk-run").addEventListener("click", function () { + out.textContent = "Running..."; + post("/agent/adk/run", { template: select.value, + prompt: document.getElementById("adk-prompt").value }); + }); + document.getElementById("adk-export").addEventListener("click", function () { + post("/agent/adk/export", { template: select.value }); + }); +})(); diff --git a/src/google/adk/SPEC.md b/src/google/adk/SPEC.md new file mode 100644 index 0000000..4e47cf8 --- /dev/null +++ b/src/google/adk/SPEC.md @@ -0,0 +1,185 @@ +# Agent Development Kit (ADK) in C++ - Specification + +Owned directory: `src/google/adk/`. Namespace `molo::google::adk`. Depends on +the Google foundation (`LanguageModel`, `GenerateRequest`, `GoogleClient`, +`valid_segment`) and `molo::clients`. It does not depend on the models, +sessions or runtime modules: it ships its own `DirectModel`, session and +memory seams. + +Google's ADK is an open-source framework (Python, TypeScript, Go, Java). +This module is a C++ implementation of its concepts, not a port of its API. + +## 1. Module map + +| File | Concern | +|---|---| +| `caps.h` | Static ceilings (`AdkCaps`) | +| `error.h` | `AdkError` (codes: invalid_argument, budget, tool, protocol, upstream) | +| `tool.h/.cpp` | `Tool` interface, `FunctionTool` (lambda + JSON schema, argument validation), `exit_loop` | +| `session.h/.cpp` | `SessionService` / `MemoryService` interfaces + bounded in-memory defaults | +| `agent.h/.cpp` | `BaseAgent`, `Agent` (LLM agent, tools, sub-agents, transfer), `SequentialAgent`, `ParallelAgent`, `LoopAgent`, `Budget`, `RunContext` | +| `runner.h/.cpp` | `Runner` (one turn, hard caps, sessions), `load_memory` tool | +| `direct_model.h/.cpp` | `DirectModel : LanguageModel` over `GoogleClient`; the declared-call table | +| `remote_http.h/.cpp` | Bounded HTTP helper for MCP / A2A | +| `mcp.h/.cpp` | MCP client over streamable HTTP; remote tools become ADK tools | +| `a2a.h/.cpp` | A2A client: agent card, SendMessage, GetTask; remote agent as a tool | +| `studio.h/.cpp` | Agent Studio style export / import (`AgentDefinition`, `ToolRegistry`) | +| `garden.h/.cpp` | Agent Garden template catalog (local) | +| `ap2.h/.cpp` | AP2 mandate types and validation (local) | +| `trigger.h/.cpp` | Batch and event-driven trigger interfaces + dispatcher | +| `tools/check_discovery.py` | Discovery check for the declared Google calls | + +## 2. Static caps (see caps.h) + +| Knob | Value | +|---|---| +| Model calls per turn | 12 | +| Tool calls per turn | 24 | +| Wall clock per turn | 60 s (checked before each model and tool call; a call in flight is bounded by the HTTP client timeout) | +| Function calls in one model reply | 8 | +| Agent transfers per turn | 4 | +| Sub-agents per agent / graph depth | 16 / 6 | +| Tools per agent | 32 | +| Loop iterations / parallel branches | 10 / 8 | +| User input | 8000 characters | +| Tool result | 32768 bytes (larger becomes an error response) | +| History sent to the model | 40 contents | +| Sessions in memory / events per session | 1000 / 200 (oldest evicted) | +| Session state keys / bytes per value | 64 / 8192 | +| Memory entries / results per search | 1000 / 10 | +| MCP pages / tools; HTTP body | 10 / 128; 1 MiB | +| A2A text | 8000 characters | +| Trigger queue / batch per dispatch | 1000 / 50 | +| Cached thought signatures | 512 | + +`RunLimits` may lower the first three, never raise them (validated). + +## 3. Contracts + +- Agents and tool names match `[A-Za-z_][A-Za-z0-9_]*`, 1..64. Session, user + and trigger ids use `valid_segment`. All checked before any model call. +- Runner loop (`Agent::run`): build request (instruction rendered with + `{key}` state substitution, history, input, tool declarations, plus + `transfer_to_agent` when the agent has sub-agents or a parent), call the + model, execute function calls, send function responses, repeat until a + text answer. Tool failures and unknown tools return `{"error": ...}` to the + model; budget errors are never swallowed. +- A cap hit does not throw: `RunResult.stop_reason` is one of `completed`, + `max_steps`, `max_tool_calls`, `timeout`, `max_transfers`, + `max_calls_per_step`, and the events so far are saved. Model errors + (`GoogleError`) propagate and leave the session unchanged. +- Workflow agents: Sequential (same input to each, data flows through + `output_key` state), Parallel (one thread per branch, model must be + thread safe, state and events merge in declaration order), Loop (until + `exit_loop` or `max_iterations`). Routing is LLM transfer between a + parent and its sub-agents. +- Agent Studio definition: ADK Agent Config fields (`agent_class`, `name`, + `model`, `description`, `instruction`, `tools: [{name}]`, `sub_agents`) + plus `output_key` and `max_iterations`. Sub-agents are inlined; a + `config_path` reference is rejected. Definitions name tools, never carry + code; import resolves names through a `ToolRegistry`. +- `DirectModel` request body is `GenerateRequest::to_json()`. Gemini 3 + rejects a replayed `functionCall` part without its `thoughtSignature`; the + shared `Part` type has no such field, so `DirectModel` caches signatures by + function name plus args and restores them on replay (foundation gap). +- Triggers are local interfaces; Agent Runtime's BigQuery / Pub/Sub + triggers belong to the runtime module. + +## 4. Declared Google calls + +One table, `kDirectCalls` in `direct_model.h`: + +| Discovery service / version | rpc id | Method | Path | +|---|---|---|---| +| generativelanguage v1beta | models.generateContent | POST | `v1beta/models/{m}:generateContent` | +| generativelanguage v1beta | models.streamGenerateContent | POST | `v1beta/models/{m}:streamGenerateContent` (`?alt=sse`) | +| aiplatform v1 | publishers.models.generateContent | POST | `v1/publishers/{p}/models/{m}:generateContent` | +| aiplatform v1 | publishers.models.streamGenerateContent | POST | `v1/publishers/{p}/models/{m}:streamGenerateContent` | + +Request fields emitted: `contents`, `systemInstruction`, `tools`, `toolConfig`, +`generationConfig`, `safetySettings`; Part field `thoughtSignature`. +The ADK makes no other Google call. MCP and A2A are not Google APIs. + +## 5. Verified against discovery + +`python3 -I src/google/adk/tools/check_discovery.py` fetches the Discovery +documents and fails when a declared method id, verb, flat path, request field +or Part field is absent. Run 2026-10-24: PASS for all four rows and all +fields (generativelanguage v1beta, aiplatform v1). +Not in discovery by nature: MCP, A2A, AP2 (no Google REST resource). + +## 6. Verified live (2026-10-24, express key, no cloud resource touched) + +`MOLO_LIVE_NET=1 GOOGLE_API_KEY=... build/google_test` (tests `adk_live.*`; +loud SKIP otherwise): + +- `DirectModel` + `Runner` + `FunctionTool` against the real model over + `aiplatform.googleapis.com/v1/publishers/google/models/gemini-3.5-flash:generateContent` + (thinkingBudget 0, maxOutputTokens 200): the model called `get_weather`, + received the function response, and answered using it (2 steps, 1 tool + call, HTTP 200). This run first failed with 400 INVALID_ARGUMENT + "missing a thought_signature"; the signature cache fixed it. +- Multi-agent transfer: router agent called `transfer_to_agent`, the + `math_helper` sub-agent answered; `RunResult.author` was `math_helper`. The + arithmetic result is the model's and is not asserted (one run said 142 for + 12 x 12). +- MCP: initialize, `tools/list` against the public unauthenticated + `https://mcp.deepwiki.com/mcp` (replies as `text/event-stream`), tools + mapped to ADK tools. `tools/call` was not run live. +- Project-scoped path and OAuth-only calls: not exercised (no OAuth token + here); the ADK does not need them. + +## 7. Sources + +- docs.cloud.google.com/gemini-enterprise-agent-platform/build/adk (overview; + names ADK languages, workflow vs agent-coordinated orchestration) +- .../build/agent-garden (library of prebuilt samples on GitHub; RAG named) +- .../agent-studio/overview (prompt and model workspace; no export schema) +- adk.dev/agents/config/ (Agent Config YAML: agent_class, model, name, + description, instruction, tools, sub_agents with config_path) +- modelcontextprotocol.io/specification/2025-06-18/server/tools (tools/list, + tools/call, inputSchema, content, isError, nextCursor) +- a2a-protocol.org/latest/specification/ (AgentCard fields, SendMessage, + GetTask, Task, Message, Part, TaskState, `/.well-known/agent-card.json`) +- ap2-protocol.org specification summary via search (Intent, Cart, Payment + mandates) +- Discovery documents: generativelanguage.googleapis.com and + aiplatform.googleapis.com (`$discovery/rest`), ai.google.dev thought + signatures page (named in the live 400 error). + +## 8. Unverified + +- A2A JSON-RPC wire strings: the fetched 1.0 spec text shows operation names + `SendMessage` / `GetTask` and `ROLE_USER` / `TASK_STATE_*`; vendor docs + show 1.0 binding using those PascalCase methods and 0.3 using `message/send` + and `tasks/get`. Both dialects are implemented and selectable; the 1.0 + JSON-RPC result wrapping (`{task}` / `{message}`) is parsed tolerantly. No + public A2A endpoint was found to test; A2A is spec-verified only, with + scripted peers in tests. +- MCP `tools/call` and the initialize handshake against servers that require + `Mcp-Session-Id` (header handling follows the spec text, untested live). + MCP inputSchema is passed to Gemini unchanged; Gemini may reject JSON Schema + keywords outside its OpenAPI subset. +- ADK config: `output_key` and `max_iterations` field names, and tool entries + as `{name}` only (no `args`), were not confirmed on the config page. +- Agent Garden: no template schema or API is published; the four templates + (code modernization, financial analysis, economic research, invoice + processing) and their instructions are local. The Garden page names none of + those four. +- AP2: field names of all three mandates are local; only the mandate roles + were read. No signing or verification exists. +- Agent Studio export / import: the overview page describes no export format; + the format here is the ADK Agent Config subset. + +## 9. Gaps + +- `Part` lacks `thoughtSignature` (foundation, `gemini_types.h`); worked + around in `DirectModel`. A custom `LanguageModel` that replays calls must + do the same. +- YAML input is not parsed (JSON only); YAML is emitted. +- Streaming is exposed by `DirectModel::stream` but the runner loop uses + `generate`. +- Parallel branches need a thread-safe `LanguageModel`; `DirectModel` is. +- No OAuth refresh, no persistence beyond memory (sessions module owns that). +- MCP: no resources, prompts or SSE server push; A2A: no streaming, push + notifications or cancel. diff --git a/src/google/adk/a2a.cpp b/src/google/adk/a2a.cpp new file mode 100644 index 0000000..a0d89a1 --- /dev/null +++ b/src/google/adk/a2a.cpp @@ -0,0 +1,221 @@ +#include "google/adk/a2a.h" + +#include +#include + +#include "google/adk/caps.h" +#include "google/adk/error.h" + +namespace molo::google::adk { + +using clients::body::Json; + +namespace { + +std::string str(const Json& o, const char* key) { + const Json* v = o.is_object() ? o.find(key) : nullptr; + return v && v->is_string() ? v->as_string() : ""; +} + +std::string parts_text(const Json& holder) { + std::string out; + const Json* parts = holder.is_object() ? holder.find("parts") : nullptr; + if (!parts || !parts->is_array()) return out; + for (const Json& p : parts->as_array()) { + std::string t = str(p, "text"); + if (t.empty()) continue; + if (!out.empty()) out += "\n"; + out += t; + } + return out; +} + +std::string normalize_state(std::string s) { + if (s.rfind("TASK_STATE_", 0) == 0) s.erase(0, 11); + for (char& c : s) c = c == '_' ? '-' : static_cast(std::tolower(static_cast(c))); + return s; +} + +class A2aTool : public Tool { + public: + A2aTool(std::shared_ptr client, std::string name, std::string description) + : client_(std::move(client)), name_(std::move(name)), description_(std::move(description)) {} + const std::string& name() const override { return name_; } + FunctionDeclaration declaration() const override { + Json text = Json::object(); + text.set("type", Json("string")); + Json props = Json::object(); + props.set("text", text); + Json req = Json::array(); + req.push(Json("text")); + Json schema = Json::object(); + schema.set("type", Json("object")); + schema.set("properties", props); + schema.set("required", req); + FunctionDeclaration d; + d.name = name_; + d.description = description_; + d.parameters = schema; + return d; + } + Json call(const Json& args, ToolContext&) override { + const Json* t = args.find("text"); + if (!t || !t->is_string()) throw AdkError::invalid("text is required"); + A2aTask task = client_->send_message(t->as_string()); + if (task.state == "failed" || task.state == "rejected" || task.state == "canceled") + throw AdkError("tool", "remote agent " + task.state); + Json out = Json::object(); + out.set("state", Json(task.state)); + out.set("text", Json(task.text)); + out.set("task_id", Json(task.id)); + return out; + } + + private: + std::shared_ptr client_; + std::string name_; + std::string description_; +}; + +} // namespace + +bool A2aTask::terminal() const { + return state == "completed" || state == "failed" || state == "canceled" || + state == "rejected" || state == "message"; +} + +A2aClient::A2aClient(std::shared_ptr http, std::string base_url, + A2aDialect dialect) + : http_(std::move(http)), base_url_(std::move(base_url)), dialect_(dialect) { + if (!http_) throw AdkError::invalid("A2aClient needs an http helper"); + if (!RemoteHttp::valid_url(base_url_)) throw AdkError::invalid("invalid A2A url"); + while (!base_url_.empty() && base_url_.back() == '/') base_url_.pop_back(); + endpoint_ = base_url_; +} + +A2aCard A2aClient::fetch_card() { + RemoteReply reply = http_->get(base_url_ + card_path()); + Json doc; + try { + doc = Json::parse(reply.body); + } catch (const std::exception& e) { + throw AdkError("protocol", std::string("unreadable agent card: ") + e.what()); + } + if (!doc.is_object() || str(doc, "name").empty()) + throw AdkError("protocol", "agent card has no name"); + A2aCard card; + card.raw = doc; + card.name = str(doc, "name"); + card.description = str(doc, "description"); + card.version = str(doc, "version"); + card.endpoint = str(doc, "url"); + if (const Json* si = doc.find("supportedInterfaces"); si && si->is_array()) + for (const Json& i : si->as_array()) + if (!str(i, "url").empty()) { + card.endpoint = str(i, "url"); + break; + } + if (const Json* caps = doc.find("capabilities"); caps && caps->is_object()) + if (const Json* s = caps->find("streaming"); s && s->is_bool()) card.streaming = s->as_bool(); + if (const Json* sk = doc.find("skills"); sk && sk->is_array()) + for (const Json& s : sk->as_array()) + card.skills.push_back({str(s, "id"), str(s, "name"), str(s, "description")}); + if (!card.endpoint.empty()) { + if (!RemoteHttp::valid_url(card.endpoint)) + throw AdkError("protocol", "agent card endpoint is not an http(s) url"); + endpoint_ = card.endpoint; + } + return card; +} + +Json A2aClient::rpc(const std::string& method, Json params) { + Json req = Json::object(); + req.set("jsonrpc", Json("2.0")); + req.set("id", Json(next_id_++)); + req.set("method", Json(method)); + req.set("params", std::move(params)); + RemoteReply reply = http_->post_json(endpoint_, req); + Json doc; + try { + doc = Json::parse(reply.body); + } catch (const std::exception& e) { + throw AdkError("protocol", std::string("unreadable A2A reply: ") + e.what()); + } + if (!doc.is_object()) throw AdkError("protocol", "A2A reply is not an object"); + if (const Json* err = doc.find("error"); err && err->is_object()) + throw AdkError("protocol", "A2A error: " + str(*err, "message")); + const Json* result = doc.find("result"); + if (!result || !result->is_object()) throw AdkError("protocol", "A2A reply has no result"); + return *result; +} + +A2aTask A2aClient::parse_task(const Json& wrapped) const { + const Json* result = &wrapped; + if (const Json* t = wrapped.find("task"); t && t->is_object()) result = t; + else if (const Json* m = wrapped.find("message"); m && m->is_object()) result = m; + A2aTask task; + task.raw = *result; + task.context_id = str(*result, "contextId"); + if (result->has("status")) { + task.id = str(*result, "id"); + const Json& status = *result->find("status"); + task.state = normalize_state(str(status, "state")); + if (const Json* arts = result->find("artifacts"); arts && arts->is_array()) + for (const Json& a : arts->as_array()) { + std::string t = parts_text(a); + if (t.empty()) continue; + if (!task.text.empty()) task.text += "\n"; + task.text += t; + } + if (task.text.empty()) + if (const Json* m = status.find("message")) task.text = parts_text(*m); + } else if (result->has("parts")) { + task.id = str(*result, "taskId"); + task.state = "message"; + task.text = parts_text(*result); + } else { + throw AdkError("protocol", "A2A result is neither a task nor a message"); + } + if (task.text.size() > AdkCaps::kMaxA2aTextChars) task.text.resize(AdkCaps::kMaxA2aTextChars); + return task; +} + +A2aTask A2aClient::send_message(const std::string& text, const std::string& context_id) { + if (text.empty()) throw AdkError::invalid("empty message"); + if (text.size() > AdkCaps::kMaxA2aTextChars) + throw AdkError::invalid("message over " + std::to_string(AdkCaps::kMaxA2aTextChars) + + " characters"); + bool v1 = dialect_ == A2aDialect::kV1; + Json part = Json::object(); + part.set("text", Json(text)); + if (!v1) part.set("kind", Json("text")); + Json parts = Json::array(); + parts.push(part); + Json message = Json::object(); + message.set("messageId", Json("adk-" + std::to_string(next_id_))); + message.set("role", Json(v1 ? "ROLE_USER" : "user")); + message.set("parts", parts); + if (!v1) message.set("kind", Json("message")); + if (!context_id.empty()) message.set("contextId", Json(context_id)); + Json params = Json::object(); + params.set("message", message); + return parse_task(rpc(v1 ? "SendMessage" : "message/send", params)); +} + +A2aTask A2aClient::get_task(const std::string& task_id) { + if (task_id.empty() || task_id.size() > 256) throw AdkError::invalid("invalid task id"); + Json params = Json::object(); + params.set("id", Json(task_id)); + Json result = rpc(dialect_ == A2aDialect::kV1 ? "GetTask" : "tasks/get", params); + A2aTask task = parse_task(result); + if (task.state == "message") throw AdkError("protocol", "GetTask returned a message"); + return task; +} + +std::shared_ptr A2aClient::as_tool(const std::string& name, + const std::string& description) { + if (!valid_identifier(name)) throw AdkError::invalid("invalid tool name"); + return std::make_shared(shared_from_this(), name, description); +} + +} // namespace molo::google::adk diff --git a/src/google/adk/a2a.h b/src/google/adk/a2a.h new file mode 100644 index 0000000..9108d01 --- /dev/null +++ b/src/google/adk/a2a.h @@ -0,0 +1,77 @@ +#pragma once + +// A2A (Agent2Agent) client over JSON-RPC: fetch the agent card from +// /.well-known/agent-card.json, send a message, get a task. The spec has two +// wire dialects in the wild: 1.0 (PascalCase methods SendMessage / GetTask, +// ROLE_USER, TASK_STATE_* strings, no "kind") and 0.3 (message/send, +// tasks/get, "user", "kind":"text"). The dialect is explicit, default 1.0. + +#include +#include +#include + +#include "clients/body/json.h" +#include "google/adk/remote_http.h" +#include "google/adk/tool.h" + +namespace molo::google::adk { + +enum class A2aDialect { kV1, kV03 }; + +struct A2aSkill { + std::string id; + std::string name; + std::string description; +}; + +struct A2aCard { + std::string name; + std::string description; + std::string version; + std::string endpoint; // JSON-RPC URL: supportedInterfaces[0].url or url + bool streaming = false; + std::vector skills; + clients::body::Json raw; +}; + +struct A2aTask { + std::string id; + std::string context_id; + // Normalized lowercase with dashes: submitted, working, completed, + // failed, canceled, rejected, input-required, auth-required; "message" + // when the peer answered with a plain message. + std::string state; + std::string text; // Artifact text, else status message text, capped + clients::body::Json raw; + bool terminal() const; +}; + +class A2aClient : public std::enable_shared_from_this { + public: + A2aClient(std::shared_ptr http, std::string base_url, + A2aDialect dialect = A2aDialect::kV1); + + A2aCard fetch_card(); + A2aTask send_message(const std::string& text, const std::string& context_id = ""); + A2aTask get_task(const std::string& task_id); + + // A remote agent as an ADK tool taking {"text": string}. The client must + // be owned by a shared_ptr. + std::shared_ptr as_tool(const std::string& name, + const std::string& description); + + static const char* card_path() { return "/.well-known/agent-card.json"; } + const std::string& endpoint() const { return endpoint_; } + + private: + clients::body::Json rpc(const std::string& method, clients::body::Json params); + A2aTask parse_task(const clients::body::Json& result) const; + + std::shared_ptr http_; + std::string base_url_; + std::string endpoint_; + A2aDialect dialect_; + int next_id_ = 1; +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/agent.cpp b/src/google/adk/agent.cpp new file mode 100644 index 0000000..9077659 --- /dev/null +++ b/src/google/adk/agent.cpp @@ -0,0 +1,337 @@ +#include "google/adk/agent.h" + +#include + +#include "google/adk/caps.h" +#include "google/adk/error.h" + +namespace molo::google::adk { + +using clients::body::Json; + +namespace { + +struct DepthGuard { + explicit DepthGuard(RunContext& c) : ctx(c) { + if (ctx.depth >= AdkCaps::kMaxAgentDepth) + throw AdkError::invalid("agent graph deeper than the depth cap"); + ++ctx.depth; + } + ~DepthGuard() { --ctx.depth; } + RunContext& ctx; +}; + +Json as_object(Json v) { + if (v.is_object()) return v; + Json o = Json::object(); + o.set("result", std::move(v)); + return o; +} + +} // namespace + +// ---- Budget --------------------------------------------------------------- + +Budget::Budget(int max_steps, int max_tool_calls, int wall_clock_ms) + : max_steps_(max_steps), + max_tools_(max_tool_calls), + deadline_(std::chrono::steady_clock::now() + + std::chrono::milliseconds(wall_clock_ms)) {} + +void Budget::check_time() const { + if (std::chrono::steady_clock::now() > deadline_) + throw AdkError("budget", "timeout"); +} + +void Budget::charge_step() { + check_time(); + if (steps_.fetch_add(1) >= max_steps_) throw AdkError("budget", "max_steps"); +} + +void Budget::charge_tool() { + check_time(); + if (tools_.fetch_add(1) >= max_tools_) + throw AdkError("budget", "max_tool_calls"); +} + +// ---- RunContext ----------------------------------------------------------- + +RunContext RunContext::fork() const { + RunContext r{model, budget}; + r.state = state; + r.history = history; + r.depth = depth; + r.transfers = transfers; + return r; +} + +void RunContext::merge(RunContext& branch) { + for (auto& e : branch.events) events.push_back(std::move(e)); + if (branch.state.is_object()) + for (const auto& [k, v] : branch.state.as_object()) state.set(k, v); + if (branch.escalate) escalate = true; +} + +// ---- BaseAgent ------------------------------------------------------------ + +BaseAgent::BaseAgent(std::string name, std::string description) + : name_(std::move(name)), description_(std::move(description)) { + if (!valid_identifier(name_)) + throw AdkError::invalid("agent name must match [A-Za-z_][A-Za-z0-9_]*"); +} + +void BaseAgent::add_sub_agent(std::shared_ptr agent) { + if (!agent) throw AdkError::invalid("null sub-agent"); + if (subs_.size() >= AdkCaps::kMaxSubAgents) + throw AdkError::invalid("sub-agent count over the cap"); + if (agent->parent_) throw AdkError::invalid("agent already has a parent"); + for (const auto& s : subs_) + if (s->name() == agent->name()) + throw AdkError::invalid("duplicate sub-agent name: " + agent->name()); + agent->parent_ = this; + subs_.push_back(std::move(agent)); +} + +BaseAgent* BaseAgent::find(const std::string& name) { + if (name_ == name) return this; + for (auto& s : subs_) + if (BaseAgent* hit = s->find(name)) return hit; + return nullptr; +} + +// ---- Agent ---------------------------------------------------------------- + +Agent::Agent(Config config) + : BaseAgent(config.name, config.description), config_(std::move(config)) { + if (config_.instruction.size() > AdkCaps::kMaxInstructionBytes) + throw AdkError::invalid("instruction over the byte cap"); + if (config_.tools.size() > AdkCaps::kMaxToolsPerAgent) + throw AdkError::invalid("tool count over the cap"); + for (const auto& t : config_.tools) { + if (!t) throw AdkError::invalid("null tool"); + if (t->name() == transfer_tool_name()) + throw AdkError::invalid("tool name is reserved: transfer_to_agent"); + } +} + +Tool* Agent::find_tool(const std::string& name) const { + for (const auto& t : config_.tools) + if (t->name() == name) return t.get(); + return nullptr; +} + +std::string Agent::render_instruction(const std::string& text, const Json& state) { + std::string out; + for (std::size_t i = 0; i < text.size();) { + if (text[i] == '{') { + std::size_t end = text.find('}', i); + if (end != std::string::npos) { + std::string key = text.substr(i + 1, end - i - 1); + if (valid_identifier(key) && state.is_object()) { + if (const Json* v = state.find(key)) { + out += v->is_string() ? v->as_string() : v->dump(); + i = end + 1; + continue; + } + } + } + } + out += text[i++]; + } + return out; +} + +FunctionDeclaration Agent::transfer_declaration() const { + Json names = Json::array(); + std::string help; + auto add = [&](const BaseAgent& a) { + names.push(Json(a.name())); + help += " " + a.name() + (a.description().empty() ? "" : " (" + a.description() + ");"); + }; + for (const auto& s : subs_) add(*s); + if (parent_) add(*parent_); + Json agent_name = Json::object(); + agent_name.set("type", Json("string")); + agent_name.set("enum", names); + Json props = Json::object(); + props.set("agent_name", agent_name); + Json req = Json::array(); + req.push(Json("agent_name")); + Json schema = Json::object(); + schema.set("type", Json("object")); + schema.set("properties", props); + schema.set("required", req); + FunctionDeclaration d; + d.name = transfer_tool_name(); + d.description = "Hand the conversation to another agent. Targets:" + help; + d.parameters = schema; + return d; +} + +Content Agent::transfer(RunContext& ctx, const Content& input, const Json& args) { + const Json* n = args.find("agent_name"); + BaseAgent* target = nullptr; + if (n && n->is_string()) { + for (const auto& s : subs_) + if (s->name() == n->as_string()) target = s.get(); + if (!target && parent_ && parent_->name() == n->as_string()) target = parent_; + } + if (!target) throw AdkError("tool", "unknown transfer target"); + if (++ctx.transfers > AdkCaps::kMaxTransfers) + throw AdkError("budget", "max_transfers"); + return target->run(ctx, input); +} + +Content Agent::run(RunContext& ctx, const Content& input) { + DepthGuard depth(ctx); + GenerateRequest req; + req.model = config_.model; + req.config = config_.generate; + std::string instruction = render_instruction(config_.instruction, ctx.state); + if (!instruction.empty()) { + Content sys; + sys.parts.push_back(Part::of_text(instruction)); + req.system = sys; + } + req.contents = ctx.history; + req.contents.push_back(input); + + molo::google::Tool decl; + for (const auto& t : config_.tools) decl.functions.push_back(t->declaration()); + bool can_transfer = config_.allow_transfer && (!subs_.empty() || parent_); + if (can_transfer) decl.functions.push_back(transfer_declaration()); + if (!decl.functions.empty()) req.tools.push_back(decl); + + for (;;) { + ctx.budget.charge_step(); + GenerateResponse resp = ctx.model.generate(req); + std::vector calls = resp.function_calls(); + + if (calls.empty()) { + std::string text = resp.text(); + Content out = Content::model(text); + ctx.events.push_back({name_, out, true}); + if (!config_.output_key.empty()) ctx.state.set(config_.output_key, Json(text)); + return out; + } + if (calls.size() > static_cast(AdkCaps::kMaxCallsPerStep)) + throw AdkError("budget", "max_calls_per_step"); + + Content model_turn = resp.candidates.front().content; + model_turn.role = "model"; + req.contents.push_back(model_turn); + ctx.events.push_back({name_, model_turn, false}); + + Content replies; + replies.role = "user"; + for (const FunctionCall& call : calls) { + if (can_transfer && call.name == transfer_tool_name()) { + try { + return transfer(ctx, input, call.args); + } catch (const AdkError& e) { + if (e.code() == "budget") throw; + Json err = Json::object(); + err.set("error", Json(e.message())); + replies.parts.push_back(Part::of_response({call.name, err, call.id})); + continue; + } + } + ctx.budget.charge_tool(); + Json result; + Tool* tool = find_tool(call.name); + if (!tool) { + result = Json::object(); + result.set("error", Json("unknown tool: " + call.name)); + } else { + try { + bool escalate = false; + ToolContext tc{ctx.state, name_, escalate}; + result = as_object(tool->call(call.args, tc)); + if (escalate) ctx.escalate = true; + } catch (const AdkError& e) { + if (e.code() == "budget") throw; + result = Json::object(); + result.set("error", Json(e.message())); + } catch (const std::exception& e) { + result = Json::object(); + result.set("error", Json(std::string(e.what()))); + } + if (result.dump().size() > AdkCaps::kMaxToolResultBytes) { + result = Json::object(); + result.set("error", Json("tool result over " + + std::to_string(AdkCaps::kMaxToolResultBytes) + + " bytes")); + } + } + replies.parts.push_back(Part::of_response({call.name, result, call.id})); + } + ctx.events.push_back({name_, replies, false}); + req.contents.push_back(replies); + } +} + +// ---- Workflow agents ------------------------------------------------------ + +Content SequentialAgent::run(RunContext& ctx, const Content& input) { + DepthGuard depth(ctx); + Content last = Content::model(""); + for (const auto& s : subs_) last = s->run(ctx, input); + return last; +} + +Content ParallelAgent::run(RunContext& ctx, const Content& input) { + DepthGuard depth(ctx); + if (subs_.size() > AdkCaps::kMaxParallelBranches) + throw AdkError::invalid("parallel branches over the cap"); + std::vector branches; + branches.reserve(subs_.size()); + for (std::size_t i = 0; i < subs_.size(); ++i) branches.push_back(ctx.fork()); + std::vector> futures; + for (std::size_t i = 0; i < subs_.size(); ++i) + futures.push_back(std::async(std::launch::async, [&, i] { + return subs_[i]->run(branches[i], input); + })); + std::vector outs(subs_.size()); + std::exception_ptr first; + for (std::size_t i = 0; i < futures.size(); ++i) { + try { + outs[i] = futures[i].get(); + } catch (...) { + if (!first) first = std::current_exception(); + } + } + if (first) std::rethrow_exception(first); + std::string text; + for (std::size_t i = 0; i < subs_.size(); ++i) { + ctx.merge(branches[i]); + if (!text.empty()) text += "\n\n"; + text += subs_[i]->name() + ": " + outs[i].text(); + } + return Content::model(text); +} + +LoopAgent::LoopAgent(std::string name, std::string description, int max_iterations) + : BaseAgent(std::move(name), std::move(description)), + max_iterations_(max_iterations) { + if (max_iterations_ < 1 || max_iterations_ > AdkCaps::kMaxLoopIterations) + throw AdkError::invalid("max_iterations outside 1.." + + std::to_string(AdkCaps::kMaxLoopIterations)); +} + +Content LoopAgent::run(RunContext& ctx, const Content& input) { + DepthGuard depth(ctx); + Content last = Content::model(""); + for (int i = 0; i < max_iterations_; ++i) { + for (const auto& s : subs_) { + last = s->run(ctx, input); + if (ctx.escalate) break; + } + if (ctx.escalate) { + ctx.escalate = false; // Consumed by this loop, not by an outer one. + break; + } + } + return last; +} + +} // namespace molo::google::adk diff --git a/src/google/adk/agent.h b/src/google/adk/agent.h new file mode 100644 index 0000000..4242d06 --- /dev/null +++ b/src/google/adk/agent.h @@ -0,0 +1,156 @@ +#pragma once + +// Agents of the ADK. BaseAgent is the tree node; Agent is the LLM agent +// (instruction, model, tools, sub-agents, transfer); SequentialAgent, +// ParallelAgent and LoopAgent are workflow agents that run their +// sub-agents without a model of their own. +// +// Agents share data through session state: an Agent with output_key stores +// its final text under that key, and instructions may reference state with +// {key}. Parent pointers are raw: the parent owns its children, so a child +// must not outlive its parent. + +#include +#include +#include +#include +#include + +#include "clients/body/json.h" +#include "google/adk/session.h" +#include "google/adk/tool.h" +#include "google/gemini_types.h" + +namespace molo::google::adk { + +// Per-turn budget shared by the whole agent graph, parallel branches +// included. Throws AdkError("budget", reason) with reason one of +// max_steps, max_tool_calls, timeout. The wall clock is checked before every +// model call and tool call; it cannot interrupt a call in flight (the HTTP +// client timeout bounds that). +class Budget { + public: + Budget(int max_steps, int max_tool_calls, int wall_clock_ms); + void charge_step(); + void charge_tool(); + void check_time() const; + int steps() const { return steps_.load(); } + int tool_calls() const { return tools_.load(); } + + private: + int max_steps_; + int max_tools_; + std::chrono::steady_clock::time_point deadline_; + std::atomic steps_{0}; + std::atomic tools_{0}; +}; + +struct RunContext { + RunContext(LanguageModel& m, Budget& b) : model(m), budget(b) {} + LanguageModel& model; + Budget& budget; + clients::body::Json state = clients::body::Json::object(); + std::vector events; // Appended during this turn. + std::vector history; // Prior turns (text only). + int depth = 0; + int transfers = 0; + bool escalate = false; // Set by exit_loop. + + // A copy with empty events and the same budget, for a parallel branch. + RunContext fork() const; + // Appends the branch's events and copies its state keys over ours. + void merge(RunContext& branch); +}; + +class BaseAgent { + public: + BaseAgent(std::string name, std::string description); + virtual ~BaseAgent() = default; + + const std::string& name() const { return name_; } + const std::string& description() const { return description_; } + const std::vector>& sub_agents() const { return subs_; } + BaseAgent* parent() const { return parent_; } + + // Names must be unique among siblings; at most kMaxSubAgents. + void add_sub_agent(std::shared_ptr agent); + // Depth-first search of this node and its descendants. + BaseAgent* find(const std::string& name); + + virtual std::string kind() const = 0; + virtual Content run(RunContext& context, const Content& input) = 0; + + protected: + std::string name_; + std::string description_; + std::vector> subs_; + BaseAgent* parent_ = nullptr; +}; + +class Agent : public BaseAgent { + public: + struct Config { + std::string name; + std::string description; + std::string model; // e.g. "gemini-2.5-flash" + std::string instruction; + std::vector> tools; + std::string output_key; // Empty: do not write state. + GenerateConfig generate; + bool allow_transfer = true; // Expose transfer_to_agent when linked. + }; + explicit Agent(Config config); + + const Config& config() const { return config_; } + std::string kind() const override { return "LlmAgent"; } + Content run(RunContext& context, const Content& input) override; + + // Name of the built-in transfer function. + static const char* transfer_tool_name() { return "transfer_to_agent"; } + // {key} substitution from state (strings raw, others as JSON); unknown + // keys stay literal. + static std::string render_instruction(const std::string& text, + const clients::body::Json& state); + + private: + Tool* find_tool(const std::string& name) const; + FunctionDeclaration transfer_declaration() const; + Content transfer(RunContext& context, const Content& input, + const clients::body::Json& args); + + Config config_; +}; + +class SequentialAgent : public BaseAgent { + public: + using BaseAgent::BaseAgent; + std::string kind() const override { return "SequentialAgent"; } + // Every sub-agent sees the original input; they pass data through state + // (output_key). The result is the last sub-agent's answer. + Content run(RunContext& context, const Content& input) override; +}; + +class ParallelAgent : public BaseAgent { + public: + using BaseAgent::BaseAgent; + std::string kind() const override { return "ParallelAgent"; } + // One thread per branch (at most kMaxParallelBranches). The model must be + // safe to call concurrently. Events and state merge in declaration order. + // Result: "name: text" blocks joined by blank lines. + Content run(RunContext& context, const Content& input) override; +}; + +class LoopAgent : public BaseAgent { + public: + LoopAgent(std::string name, std::string description, int max_iterations); + int max_iterations() const { return max_iterations_; } + std::string kind() const override { return "LoopAgent"; } + // Runs the sub-agents in order, up to max_iterations times, stopping when + // a tool sets escalate (exit_loop). + Content run(RunContext& context, const Content& input) override; + + private: + int max_iterations_; +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/ap2.cpp b/src/google/adk/ap2.cpp new file mode 100644 index 0000000..facea32 --- /dev/null +++ b/src/google/adk/ap2.cpp @@ -0,0 +1,172 @@ +#include "google/adk/ap2.h" + +#include "google/adk/error.h" +#include "google/resource.h" + +namespace molo::google::adk::ap2 { + +using clients::body::Json; + +namespace { + +void need_id(const std::string& id, const char* what) { + if (!valid_segment(id)) throw AdkError::invalid(std::string("invalid ") + what); +} + +void need_currency(const std::string& c) { + if (c.size() != 3) throw AdkError::invalid("currency must be 3 uppercase letters"); + for (char ch : c) + if (ch < 'A' || ch > 'Z') throw AdkError::invalid("currency must be 3 uppercase letters"); +} + +std::string str(const Json& o, const char* key) { + const Json* v = o.is_object() ? o.find(key) : nullptr; + return v && v->is_string() ? v->as_string() : ""; +} +long num(const Json& o, const char* key) { + const Json* v = o.is_object() ? o.find(key) : nullptr; + return v && v->is_number() ? v->as_int() : 0; +} + +} // namespace + +void IntentMandate::validate() const { + need_id(id, "intent id"); + if (description.empty() || description.size() > 1000) + throw AdkError::invalid("intent description must be 1..1000 characters"); + if (merchants.size() > 50) throw AdkError::invalid("over 50 merchants"); + if (max_amount_minor < 1) throw AdkError::invalid("max_amount_minor must be positive"); + need_currency(currency); +} + +Json IntentMandate::to_json() const { + Json o = Json::object(); + o.set("id", Json(id)); + o.set("description", Json(description)); + Json m = Json::array(); + for (const auto& s : merchants) m.push(Json(s)); + o.set("merchants", m); + o.set("max_amount_minor", Json(max_amount_minor)); + o.set("currency", Json(currency)); + o.set("expires_at", Json(expires_at)); + o.set("signature", Json(signature)); + return o; +} + +IntentMandate IntentMandate::from_json(const Json& d) { + IntentMandate m; + m.id = str(d, "id"); + m.description = str(d, "description"); + if (const Json* a = d.find("merchants"); a && a->is_array()) + for (const Json& s : a->as_array()) + if (s.is_string()) m.merchants.push_back(s.as_string()); + m.max_amount_minor = num(d, "max_amount_minor"); + m.currency = str(d, "currency"); + m.expires_at = str(d, "expires_at"); + m.signature = str(d, "signature"); + return m; +} + +void CartMandate::validate() const { + need_id(id, "cart id"); + need_id(intent_id, "intent id"); + if (merchant.empty() || merchant.size() > 200) throw AdkError::invalid("invalid merchant"); + if (items.empty() || items.size() > 50) throw AdkError::invalid("cart needs 1..50 items"); + need_currency(currency); + long sum = 0; + for (const CartItem& i : items) { + if (i.sku.empty() || i.sku.size() > 128) throw AdkError::invalid("invalid sku"); + if (i.quantity < 1 || i.quantity > 1000) throw AdkError::invalid("quantity outside 1..1000"); + if (i.unit_amount_minor < 0) throw AdkError::invalid("negative unit amount"); + sum += static_cast(i.quantity) * i.unit_amount_minor; + } + if (sum != total_minor) throw AdkError::invalid("total_minor does not equal the item sum"); +} + +void CartMandate::validate_against(const IntentMandate& intent) const { + validate(); + if (intent_id != intent.id) throw AdkError::invalid("cart belongs to another intent"); + if (currency != intent.currency) throw AdkError::invalid("currency differs from the intent"); + if (total_minor > intent.max_amount_minor) throw AdkError::invalid("cart total exceeds the intent cap"); + if (!intent.merchants.empty()) { + bool ok = false; + for (const auto& m : intent.merchants) ok = ok || m == merchant; + if (!ok) throw AdkError::invalid("merchant not allowed by the intent"); + } +} + +Json CartMandate::to_json() const { + Json o = Json::object(); + o.set("id", Json(id)); + o.set("intent_id", Json(intent_id)); + o.set("merchant", Json(merchant)); + Json arr = Json::array(); + for (const CartItem& i : items) { + Json it = Json::object(); + it.set("sku", Json(i.sku)); + it.set("label", Json(i.label)); + it.set("quantity", Json(i.quantity)); + it.set("unit_amount_minor", Json(i.unit_amount_minor)); + arr.push(it); + } + o.set("items", arr); + o.set("total_minor", Json(total_minor)); + o.set("currency", Json(currency)); + o.set("signature", Json(signature)); + return o; +} + +CartMandate CartMandate::from_json(const Json& d) { + CartMandate m; + m.id = str(d, "id"); + m.intent_id = str(d, "intent_id"); + m.merchant = str(d, "merchant"); + if (const Json* a = d.find("items"); a && a->is_array()) + for (const Json& i : a->as_array()) + m.items.push_back({str(i, "sku"), str(i, "label"), static_cast(num(i, "quantity")), + num(i, "unit_amount_minor")}); + m.total_minor = num(d, "total_minor"); + m.currency = str(d, "currency"); + m.signature = str(d, "signature"); + return m; +} + +void PaymentMandate::validate() const { + need_id(id, "payment id"); + need_id(cart_id, "cart id"); + if (payment_method_token.empty() || payment_method_token.size() > 512) + throw AdkError::invalid("payment_method_token must be 1..512 characters"); + if (amount_minor < 1) throw AdkError::invalid("amount_minor must be positive"); + need_currency(currency); +} + +void PaymentMandate::validate_against(const CartMandate& cart) const { + validate(); + if (cart_id != cart.id) throw AdkError::invalid("payment belongs to another cart"); + if (currency != cart.currency) throw AdkError::invalid("currency differs from the cart"); + if (amount_minor != cart.total_minor) throw AdkError::invalid("amount differs from the cart total"); +} + +Json PaymentMandate::to_json() const { + Json o = Json::object(); + o.set("id", Json(id)); + o.set("cart_id", Json(cart_id)); + o.set("payment_method_token", Json(payment_method_token)); + o.set("amount_minor", Json(amount_minor)); + o.set("currency", Json(currency)); + o.set("signature", Json(signature)); + return o; +} + +PaymentMandate PaymentMandate::from_json(const Json& d) { + PaymentMandate m; + m.id = str(d, "id"); + m.cart_id = str(d, "cart_id"); + m.payment_method_token = str(d, "payment_method_token"); + m.amount_minor = num(d, "amount_minor"); + m.currency = str(d, "currency"); + m.signature = str(d, "signature"); + return m; +} + +} // namespace molo::google::adk::ap2 diff --git a/src/google/adk/ap2.h b/src/google/adk/ap2.h new file mode 100644 index 0000000..cc2b006 --- /dev/null +++ b/src/google/adk/ap2.h @@ -0,0 +1,69 @@ +#pragma once + +// Agent Payments Protocol (AP2) message types: IntentMandate, CartMandate, +// PaymentMandate. LOCAL types: only the three mandate names and their roles +// were read (ap2-protocol.org spec summary); field names are this module's +// own and are listed under Unverified in SPEC.md. No signing, no payment +// network calls: `signature` is an opaque string the caller supplies. +// Amounts are integer minor units (cents) to avoid floating point money. + +#include +#include + +#include "clients/body/json.h" + +namespace molo::google::adk::ap2 { + +struct IntentMandate { + std::string id; + std::string description; // What the user wants the agent to buy + std::vector merchants; // Allowed merchants, empty: any + long max_amount_minor = 0; + std::string currency; // ISO 4217, three uppercase letters + std::string expires_at; // RFC 3339 timestamp, as given + std::string signature; + + void validate() const; // Throws AdkError (invalid_argument) + clients::body::Json to_json() const; + static IntentMandate from_json(const clients::body::Json& doc); +}; + +struct CartItem { + std::string sku; + std::string label; + int quantity = 1; + long unit_amount_minor = 0; +}; + +struct CartMandate { + std::string id; + std::string intent_id; + std::string merchant; + std::vector items; + long total_minor = 0; + std::string currency; + std::string signature; + + // Items 1..50, quantities 1..1000, and total equals the item sum. + void validate() const; + // Also checks the cart against its intent (currency, merchant, cap). + void validate_against(const IntentMandate& intent) const; + clients::body::Json to_json() const; + static CartMandate from_json(const clients::body::Json& doc); +}; + +struct PaymentMandate { + std::string id; + std::string cart_id; + std::string payment_method_token; // Opaque token, never a card number + long amount_minor = 0; + std::string currency; + std::string signature; + + void validate() const; + void validate_against(const CartMandate& cart) const; + clients::body::Json to_json() const; + static PaymentMandate from_json(const clients::body::Json& doc); +}; + +} // namespace molo::google::adk::ap2 diff --git a/src/google/adk/caps.h b/src/google/adk/caps.h new file mode 100644 index 0000000..24057af --- /dev/null +++ b/src/google/adk/caps.h @@ -0,0 +1,53 @@ +#pragma once + +// Static ceilings for the Agent Development Kit. Never autotuned. Every +// loop, list, size and wait in this module is bounded by one of these. + +#include + +namespace molo::google::adk { + +struct AdkCaps { + // Runner budget per turn (whole agent graph, parallel branches included). + static constexpr int kMaxSteps = 12; // model calls + static constexpr int kMaxToolCalls = 24; // tool invocations + static constexpr int kMaxWallClockMs = 60000; // checked between steps + static constexpr int kMaxCallsPerStep = 8; // function calls in one reply + static constexpr int kMaxTransfers = 4; // agent transfers per turn + + // Graph shape. + static constexpr std::size_t kMaxSubAgents = 16; + static constexpr int kMaxAgentDepth = 6; + static constexpr std::size_t kMaxToolsPerAgent = 32; + static constexpr int kMaxLoopIterations = 10; + static constexpr std::size_t kMaxParallelBranches = 8; + static constexpr std::size_t kMaxNameChars = 64; + static constexpr std::size_t kMaxInstructionBytes = 16384; + + // Sizes. + static constexpr std::size_t kMaxInputChars = 8000; + static constexpr std::size_t kMaxToolResultBytes = 32768; + static constexpr std::size_t kMaxHistoryContents = 40; + static constexpr std::size_t kMaxHttpBodyBytes = 1024u * 1024u; + static constexpr std::size_t kMaxDefinitionBytes = 64u * 1024u; + + // Sessions and memory (in-memory defaults). + static constexpr std::size_t kMaxSessions = 1000; + static constexpr std::size_t kMaxEventsPerSession = 200; + static constexpr std::size_t kMaxStateKeys = 64; + static constexpr std::size_t kMaxStateValueBytes = 8192; + static constexpr std::size_t kMaxMemoryEntries = 1000; + static constexpr std::size_t kMaxMemoryResults = 10; + + // Protocol clients. + static constexpr int kMaxMcpPages = 10; + static constexpr std::size_t kMaxMcpTools = 128; + static constexpr std::size_t kMaxA2aTextChars = 8000; + static constexpr std::size_t kMaxThoughtSignatures = 512; // DirectModel cache + + // Triggers. + static constexpr std::size_t kMaxTriggerBatch = 50; + static constexpr std::size_t kMaxTriggerQueue = 1000; +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/direct_model.cpp b/src/google/adk/direct_model.cpp new file mode 100644 index 0000000..a0d2d3c --- /dev/null +++ b/src/google/adk/direct_model.cpp @@ -0,0 +1,97 @@ +#include "google/adk/direct_model.h" + +#include "google/adk/caps.h" +#include "google/resource.h" + +namespace molo::google::adk { + +using clients::body::Json; + +DirectModel::DirectModel(std::shared_ptr client, + std::string default_model, ServiceEndpoint endpoint) + : client_(std::move(client)), + default_model_(std::move(default_model)), + endpoint_(std::move(endpoint)) { + if (!client_) throw GoogleError::invalid("DirectModel needs a client"); + if (!valid_segment(default_model_)) + throw GoogleError::invalid("invalid default model id"); +} + +std::string DirectModel::model_path(const GenerateRequest& request) const { + const std::string& m = request.model.empty() ? default_model_ : request.model; + if (!valid_segment(m)) throw GoogleError::invalid("invalid model id"); + return "/models/" + m; +} + +namespace { +std::string call_key(const Json& call) { + const Json* n = call.find("name"); + const Json* a = call.find("args"); + return (n && n->is_string() ? n->as_string() : "") + "\n" + + (a ? a->dump() : "{}"); +} +} // namespace + +void DirectModel::remember_signatures(const Json& response) { + const Json* cands = response.find("candidates"); + if (!cands || !cands->is_array()) return; + std::lock_guard lock(mutex_); + for (const Json& c : cands->as_array()) { + const Json* content = c.find("content"); + const Json* parts = content ? content->find("parts") : nullptr; + if (!parts || !parts->is_array()) continue; + for (const Json& p : parts->as_array()) { + const Json* call = p.find("functionCall"); + const Json* sig = p.find("thoughtSignature"); + if (!call || !sig || !sig->is_string()) continue; + std::string key = call_key(*call); + if (!signatures_.count(key)) signature_order_.push_back(key); + signatures_[key] = sig->as_string(); + while (signature_order_.size() > AdkCaps::kMaxThoughtSignatures) { + signatures_.erase(signature_order_.front()); + signature_order_.pop_front(); + } + } + } +} + +Json DirectModel::restore_signatures(Json body) { + Json* contents = body.is_object() && body.has("contents") + ? &body.as_object().find("contents")->second + : nullptr; + if (!contents || !contents->is_array()) return body; + std::lock_guard lock(mutex_); + for (Json& content : contents->as_array()) { + if (!content.is_object() || !content.as_object().count("parts")) continue; + Json& parts = content.as_object().find("parts")->second; + if (!parts.is_array()) continue; + for (Json& p : parts.as_array()) { + if (!p.is_object() || p.has("thoughtSignature")) continue; + auto call = p.as_object().find("functionCall"); + if (call == p.as_object().end()) continue; + auto sig = signatures_.find(call_key(call->second)); + if (sig != signatures_.end()) p.set("thoughtSignature", Json(sig->second)); + } + } + return body; +} + +GenerateResponse DirectModel::generate(const GenerateRequest& request) { + std::string path = model_path(request) + ":generateContent"; + Json raw = client_->post_json(endpoint_, path, restore_signatures(request.to_json())); + remember_signatures(raw); + return GenerateResponse::from_json(raw); +} + +void DirectModel::stream( + const GenerateRequest& request, + const std::function& on_chunk) { + client_->stream_json( + endpoint_, model_path(request) + ":streamGenerateContent?alt=sse", + restore_signatures(request.to_json()), [&](const Json& event) { + remember_signatures(event); + return on_chunk(GenerateResponse::from_json(event)); + }); +} + +} // namespace molo::google::adk diff --git a/src/google/adk/direct_model.h b/src/google/adk/direct_model.h new file mode 100644 index 0000000..5e32082 --- /dev/null +++ b/src/google/adk/direct_model.h @@ -0,0 +1,74 @@ +#pragma once + +// DirectModel: a private LanguageModel over GoogleClient so the ADK needs no +// other agent-platform module. POST models/{m}:generateContent and +// :streamGenerateContent?alt=sse against one ServiceEndpoint (default: the +// Gemini API; pass endpoints::vertex_generative() for express keys). + +#include +#include +#include +#include +#include + +#include "google/client.h" +#include "google/gemini_types.h" + +namespace molo::google::adk { + +// Every Google call this module makes, in one table. tools/check_discovery.py +// parses the rows between the markers and fails when Google's Discovery +// document lacks the method, the HTTP verb or the flat path, or when a +// request field name is missing from the request schema. +struct DirectCall { + const char* service; // Discovery service host prefix + const char* version; // Discovery version + const char* rpc; // Discovery method id + const char* http; // HTTP verb + const char* flat_path; // Discovery flatPath template (path after the host) +}; +// DISCOVERY-TABLE-BEGIN +inline constexpr DirectCall kDirectCalls[] = { + {"generativelanguage", "v1beta", "models.generateContent", "POST", "v1beta/models/{modelsId}:generateContent"}, + {"generativelanguage", "v1beta", "models.streamGenerateContent", "POST", "v1beta/models/{modelsId}:streamGenerateContent"}, + {"aiplatform", "v1", "publishers.models.generateContent", "POST", "v1/publishers/{publishersId}/models/{modelsId}:generateContent"}, + {"aiplatform", "v1", "publishers.models.streamGenerateContent", "POST", "v1/publishers/{publishersId}/models/{modelsId}:streamGenerateContent"}, +}; +// Top-level request fields GenerateRequest::to_json may emit; each must exist +// in both request schemas above. +inline constexpr const char* kDirectRequestFields[] = { + "contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "safetySettings", +}; +inline constexpr const char* kDirectPartFields[] = {"thoughtSignature"}; // on Part +// DISCOVERY-TABLE-END + +class DirectModel : public LanguageModel { + public: + // default_model is used when a request names no model. + DirectModel(std::shared_ptr client, std::string default_model, + ServiceEndpoint endpoint = endpoints::generative()); + + GenerateResponse generate(const GenerateRequest& request) override; + void stream(const GenerateRequest& request, + const std::function& on_chunk) override; + + private: + std::string model_path(const GenerateRequest& request) const; + // Gemini 3 rejects a replayed functionCall part that lacks the + // thoughtSignature it was issued with, and the shared Part type does not + // carry that field (foundation gap). We keep the signature of every + // functionCall we receive, keyed by name plus args, and put it back on the + // matching part when the call is replayed. Bounded FIFO. + void remember_signatures(const clients::body::Json& response); + clients::body::Json restore_signatures(clients::body::Json body); + + std::mutex mutex_; + std::map signatures_; + std::deque signature_order_; + + std::shared_ptr client_; + std::string default_model_; + ServiceEndpoint endpoint_; +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/error.h b/src/google/adk/error.h new file mode 100644 index 0000000..e6e4d06 --- /dev/null +++ b/src/google/adk/error.h @@ -0,0 +1,33 @@ +#pragma once + +// One error type for the ADK. `code` is machine readable: +// invalid_argument bad input, rejected before any work +// budget a runner cap was hit (steps, tool calls, wall clock) +// tool a tool failed +// protocol a remote MCP / A2A peer answered something unusable +// upstream a remote peer answered a non-2xx status + +#include +#include + +namespace molo::google::adk { + +class AdkError : public std::runtime_error { + public: + AdkError(std::string code, const std::string& message) + : std::runtime_error("molo::google::adk: " + code + ": " + message), + code_(std::move(code)), + message_(message) {} + const std::string& code() const noexcept { return code_; } + const std::string& message() const noexcept { return message_; } + static AdkError invalid(const std::string& m) { return {"invalid_argument", m}; } + + private: + std::string code_; + std::string message_; +}; + +// Agent and tool names: [A-Za-z_][A-Za-z0-9_]*, 1..64 chars. +bool valid_identifier(const std::string& name); + +} // namespace molo::google::adk diff --git a/src/google/adk/garden.cpp b/src/google/adk/garden.cpp new file mode 100644 index 0000000..ae3fc2c --- /dev/null +++ b/src/google/adk/garden.cpp @@ -0,0 +1,110 @@ +#include "google/adk/garden.h" + +#include "google/adk/error.h" + +namespace molo::google::adk { + +using clients::body::Json; + +namespace { + +GardenTemplate make(const std::string& id, const std::string& title, + const std::string& description, const std::string& instruction, + std::vector tools) { + Json def = Json::object(); + def.set("agent_class", Json("LlmAgent")); + def.set("name", Json(id)); + def.set("description", Json(description)); + def.set("model", Json("gemini-2.5-flash")); + def.set("instruction", Json(instruction)); + Json t = Json::array(); + for (const auto& n : tools) { + Json item = Json::object(); + item.set("name", Json(n)); + t.push(item); + } + def.set("tools", t); + return {id, title, description, def, std::move(tools)}; +} + +std::vector build() { + return { + make("code_modernization", "Code modernization", + "Reviews legacy code and proposes a staged migration.", + "You modernize legacy code. Read the code the user supplies, list the " + "outdated constructs, propose a staged migration with the smallest safe " + "step first, and show the changed code. Never claim a test passed unless " + "a tool ran it.", + {"read_source", "run_tests"}), + make("financial_analysis", "Financial analysis", + "Analyses figures the user provides and explains the result.", + "You are a financial analyst. Use only numbers the user or a tool " + "provided. Show the formula for every ratio, state assumptions, and flag " + "missing data instead of estimating it.", + {"calculate"}), + make("economic_research", "Economic research", + "Summarizes economic questions with sources named.", + "You research economic questions. Separate established data from " + "interpretation, name the source of every figure, and say plainly when " + "no source was supplied.", + {"search_documents"}), + make("invoice_processing", "Invoice processing", + "Extracts structured fields from invoice text.", + "You process invoices. Extract supplier, invoice number, date, currency, " + "line items and totals as JSON. Check that line items sum to the total " + "and report any mismatch. Never invent a field that is not in the text.", + {"validate_invoice"}), + }; +} + +} // namespace + +const std::vector& AgentGarden::templates() { + static const std::vector all = build(); + return all; +} + +const GardenTemplate* AgentGarden::find(const std::string& id) { + for (const auto& t : templates()) + if (t.id == id) return &t; + return nullptr; +} + +std::shared_ptr AgentGarden::instantiate( + const std::string& id, const ToolRegistry& registry, + std::vector* missing_tools) { + const GardenTemplate* t = find(id); + if (!t) throw AdkError::invalid("unknown garden template: " + id); + Json def = t->definition; + Json kept = Json::array(); + for (const Json& item : def.find("tools")->as_array()) { + const std::string& n = item.find("name")->as_string(); + if (registry.find(n)) { + kept.push(item); + } else if (missing_tools) { + missing_tools->push_back(n); + } + } + def.set("tools", kept); + return AgentDefinition::from_json(def, registry); +} + +Json AgentGarden::catalog_json() { + Json arr = Json::array(); + for (const auto& t : templates()) { + Json o = Json::object(); + o.set("id", Json(t.id)); + o.set("title", Json(t.title)); + o.set("description", Json(t.description)); + Json tools = Json::array(); + for (const auto& n : t.suggested_tools) tools.push(Json(n)); + o.set("suggested_tools", tools); + arr.push(o); + } + Json out = Json::object(); + out.set("templates", arr); + out.set("source", Json("local")); + return out; +} + +} // namespace molo::google::adk diff --git a/src/google/adk/garden.h b/src/google/adk/garden.h new file mode 100644 index 0000000..b8aacff --- /dev/null +++ b/src/google/adk/garden.h @@ -0,0 +1,40 @@ +#pragma once + +// Agent Garden catalog: a LOCAL template list for the four use cases named +// in the platform announcement (code modernization, financial analysis, +// economic research, invoice processing). Google's Agent Garden page +// describes a sample library on GitHub; it publishes no API and no template +// schema, so the instructions and tool names here are this module's own. + +#include +#include +#include + +#include "clients/body/json.h" +#include "google/adk/agent.h" +#include "google/adk/studio.h" + +namespace molo::google::adk { + +struct GardenTemplate { + std::string id; // [a-z_]+ + std::string title; + std::string description; + clients::body::Json definition; // AgentDefinition document (tools by name) + std::vector suggested_tools; // Names a host should register +}; + +class AgentGarden { + public: + static const std::vector& templates(); + static const GardenTemplate* find(const std::string& id); + // Builds the agent; tools named by the template that the registry lacks + // are skipped (reported in missing_tools when non-null), so a template + // works without host tools as a plain instruction-only agent. + static std::shared_ptr instantiate( + const std::string& id, const ToolRegistry& registry, + std::vector* missing_tools = nullptr); + static clients::body::Json catalog_json(); +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/mcp.cpp b/src/google/adk/mcp.cpp new file mode 100644 index 0000000..fa5c3ea --- /dev/null +++ b/src/google/adk/mcp.cpp @@ -0,0 +1,197 @@ +#include "google/adk/mcp.h" + +#include "google/adk/caps.h" +#include "google/adk/error.h" + +namespace molo::google::adk { + +using clients::body::Json; + +namespace { + +std::string str(const Json& o, const char* key) { + const Json* v = o.find(key); + return v && v->is_string() ? v->as_string() : ""; +} + +std::string sanitize(const std::string& name) { + std::string out; + for (char c : name) { + bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '_'; + out += ok ? c : '_'; + } + if (!out.empty() && out[0] >= '0' && out[0] <= '9') out = "_" + out; + if (out.size() > AdkCaps::kMaxNameChars) out.resize(AdkCaps::kMaxNameChars); + return out; +} + +// Finds the JSON-RPC response with `id` in an SSE body. +Json parse_sse(const std::string& body, int id) { + std::size_t pos = 0; + while (pos < body.size()) { + std::size_t end = body.find('\n', pos); + if (end == std::string::npos) end = body.size(); + std::string line = body.substr(pos, end - pos); + pos = end + 1; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.rfind("data:", 0) != 0) continue; + std::string data = line.substr(5); + if (!data.empty() && data[0] == ' ') data.erase(0, 1); + try { + Json doc = Json::parse(data); + const Json* got = doc.find("id"); + if (got && got->is_number() && got->as_int() == id) return doc; + } catch (const std::exception&) { + continue; // Not JSON: keep scanning. + } + } + throw AdkError("protocol", "no JSON-RPC response in the event stream"); +} + +class McpTool : public Tool { + public: + McpTool(std::shared_ptr client, McpToolInfo info) + : client_(std::move(client)), + info_(std::move(info)), + exposed_(sanitize(info_.name)) {} + const std::string& name() const override { return exposed_; } + FunctionDeclaration declaration() const override { + FunctionDeclaration d; + d.name = exposed_; + d.description = info_.description.empty() ? info_.title : info_.description; + d.parameters = info_.input_schema; + return d; + } + Json call(const Json& args, ToolContext&) override { + FunctionTool::validate(info_.input_schema, args); + McpResult r = client_->call_tool(info_.name, args); + if (r.is_error) throw AdkError("tool", r.text); + Json out = Json::object(); + out.set("text", Json(r.text)); + if (!r.structured.is_null()) out.set("structured", r.structured); + return out; + } + + private: + std::shared_ptr client_; + McpToolInfo info_; + std::string exposed_; +}; + +} // namespace + +McpClient::McpClient(std::shared_ptr http, std::string url) + : http_(std::move(http)), url_(std::move(url)) { + if (!http_) throw AdkError::invalid("McpClient needs an http helper"); + if (!RemoteHttp::valid_url(url_)) throw AdkError::invalid("invalid MCP url"); +} + +std::map McpClient::request_headers() const { + std::map h{ + {"Accept", "application/json, text/event-stream"}}; + if (initialized_) h["MCP-Protocol-Version"] = kProtocolVersion; + if (!session_id_.empty()) h["Mcp-Session-Id"] = session_id_; + return h; +} + +Json McpClient::rpc(const std::string& method, Json params) { + int id = next_id_++; + Json req = Json::object(); + req.set("jsonrpc", Json("2.0")); + req.set("id", Json(id)); + req.set("method", Json(method)); + req.set("params", std::move(params)); + RemoteReply reply = http_->post_json(url_, req, request_headers()); + if (auto sid = reply.headers.get("Mcp-Session-Id")) session_id_ = *sid; + Json doc; + try { + std::string ct = reply.headers.get_or("Content-Type", ""); + doc = ct.find("text/event-stream") != std::string::npos + ? parse_sse(reply.body, id) + : Json::parse(reply.body); + } catch (const AdkError&) { + throw; + } catch (const std::exception& e) { + throw AdkError("protocol", std::string("unreadable MCP reply: ") + e.what()); + } + if (!doc.is_object()) throw AdkError("protocol", "MCP reply is not an object"); + if (const Json* err = doc.find("error"); err && err->is_object()) + throw AdkError("protocol", "MCP error " + + (err->has("code") ? std::to_string(err->find("code")->as_int()) + : std::string("?")) + + ": " + str(*err, "message")); + const Json* result = doc.find("result"); + if (!result || !result->is_object()) throw AdkError("protocol", "MCP reply has no result"); + return *result; +} + +void McpClient::notify(const std::string& method) { + Json req = Json::object(); + req.set("jsonrpc", Json("2.0")); + req.set("method", Json(method)); + http_->post_json(url_, req, request_headers()); +} + +void McpClient::initialize() { + Json client = Json::object(); + client.set("name", Json("moloapp-adk")); + client.set("version", Json("1")); + Json params = Json::object(); + params.set("protocolVersion", Json(kProtocolVersion)); + params.set("capabilities", Json::object()); + params.set("clientInfo", client); + rpc("initialize", params); + initialized_ = true; + notify("notifications/initialized"); +} + +std::vector McpClient::list_tools() { + std::vector out; + std::string cursor; + for (int page = 0; page < AdkCaps::kMaxMcpPages; ++page) { + Json params = Json::object(); + if (!cursor.empty()) params.set("cursor", Json(cursor)); + Json result = rpc("tools/list", params); + const Json* tools = result.find("tools"); + if (!tools || !tools->is_array()) throw AdkError("protocol", "tools/list has no tools array"); + for (const Json& t : tools->as_array()) { + if (!t.is_object() || str(t, "name").empty()) continue; + if (out.size() >= AdkCaps::kMaxMcpTools) return out; + McpToolInfo info{str(t, "name"), str(t, "title"), str(t, "description"), Json()}; + if (const Json* s = t.find("inputSchema")) info.input_schema = *s; + out.push_back(std::move(info)); + } + cursor = str(result, "nextCursor"); + if (cursor.empty()) break; + } + return out; +} + +McpResult McpClient::call_tool(const std::string& name, const Json& args) { + if (name.empty()) throw AdkError::invalid("empty tool name"); + Json params = Json::object(); + params.set("name", Json(name)); + params.set("arguments", args.is_object() ? args : Json::object()); + Json result = rpc("tools/call", params); + McpResult r; + if (const Json* c = result.find("content"); c && c->is_array()) + for (const Json& item : c->as_array()) + if (item.is_object() && str(item, "type") == "text") { + if (!r.text.empty()) r.text += "\n"; + r.text += str(item, "text"); + } + if (const Json* s = result.find("structuredContent")) r.structured = *s; + if (const Json* e = result.find("isError"); e && e->is_bool()) r.is_error = e->as_bool(); + return r; +} + +std::vector> McpClient::tools() { + std::vector> out; + auto self = shared_from_this(); + for (McpToolInfo& info : list_tools()) + out.push_back(std::make_shared(self, std::move(info))); + return out; +} + +} // namespace molo::google::adk diff --git a/src/google/adk/mcp.h b/src/google/adk/mcp.h new file mode 100644 index 0000000..12d2d7c --- /dev/null +++ b/src/google/adk/mcp.h @@ -0,0 +1,62 @@ +#pragma once + +// MCP (Model Context Protocol) client over streamable HTTP: JSON-RPC 2.0 +// POSTs to one endpoint URL, replies as application/json or as a +// text/event-stream carrying the JSON-RPC response. Remote tools become ADK +// tools through McpClient::tools(). + +#include +#include +#include + +#include "clients/body/json.h" +#include "google/adk/remote_http.h" +#include "google/adk/tool.h" + +namespace molo::google::adk { + +struct McpToolInfo { + std::string name; + std::string title; + std::string description; + clients::body::Json input_schema; // JSON Schema, passed to Gemini as is +}; + +struct McpResult { + std::string text; // Text content items joined by newlines + clients::body::Json structured; // structuredContent, null when absent + bool is_error = false; +}; + +class McpClient : public std::enable_shared_from_this { + public: + static constexpr const char* kProtocolVersion = "2025-06-18"; + + McpClient(std::shared_ptr http, std::string url); + + // initialize + notifications/initialized. Keeps Mcp-Session-Id if sent. + void initialize(); + // tools/list, following nextCursor for at most kMaxMcpPages pages and + // kMaxMcpTools tools. + std::vector list_tools(); + McpResult call_tool(const std::string& name, const clients::body::Json& args); + // list_tools() wrapped as ADK tools. Exposed names are sanitized to + // [A-Za-z0-9_]; a tool whose result has isError becomes a tool error. + std::vector> tools(); + + const std::string& url() const { return url_; } + const std::string& session_id() const { return session_id_; } + + private: + clients::body::Json rpc(const std::string& method, clients::body::Json params); + void notify(const std::string& method); + std::map request_headers() const; + + std::shared_ptr http_; + std::string url_; + std::string session_id_; + bool initialized_ = false; + int next_id_ = 1; +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/remote_http.cpp b/src/google/adk/remote_http.cpp new file mode 100644 index 0000000..58807b7 --- /dev/null +++ b/src/google/adk/remote_http.cpp @@ -0,0 +1,55 @@ +#include "google/adk/remote_http.h" + +#include "google/adk/caps.h" +#include "google/adk/error.h" + +namespace molo::google::adk { + +RemoteHttp::RemoteHttp(std::shared_ptr http, + std::map headers) + : http_(std::move(http)), headers_(std::move(headers)) { + if (!http_) throw AdkError::invalid("RemoteHttp needs a client"); +} + +bool RemoteHttp::valid_url(const std::string& url) { + bool scheme = url.rfind("http://", 0) == 0 || url.rfind("https://", 0) == 0; + if (!scheme || url.size() > 2048) return false; + for (char c : url) + if (c <= ' ' || c == 0x7f) return false; + return url.size() > url.find("//") + 2; // A host must follow the scheme. +} + +RemoteReply RemoteHttp::finish(const std::string& url, clients::ClientRequest req) { + for (const auto& [k, v] : headers_) req.header(k, v); + clients::ClientResponse res; + try { + res = http_->send_blocking(std::move(req)); + } catch (const std::exception& e) { + throw AdkError("upstream", "request failed: " + std::string(e.what())); + } + if (!res.is_success()) + throw AdkError("upstream", "HTTP " + std::to_string(res.status()) + " from " + url); + if (res.body().size() > AdkCaps::kMaxHttpBodyBytes) + throw AdkError("protocol", "response over the body cap"); + return {res.status(), res.headers(), res.body()}; +} + +RemoteReply RemoteHttp::post_json(const std::string& url, + const clients::body::Json& body, + const std::map& extra) { + if (!valid_url(url)) throw AdkError::invalid("invalid url"); + clients::ClientRequest req = clients::ClientRequest::post(url); + req.json(body); + for (const auto& [k, v] : extra) req.header(k, v); + return finish(url, std::move(req)); +} + +RemoteReply RemoteHttp::get(const std::string& url, + const std::map& extra) { + if (!valid_url(url)) throw AdkError::invalid("invalid url"); + clients::ClientRequest req = clients::ClientRequest::get(url); + for (const auto& [k, v] : extra) req.header(k, v); + return finish(url, std::move(req)); +} + +} // namespace molo::google::adk diff --git a/src/google/adk/remote_http.h b/src/google/adk/remote_http.h new file mode 100644 index 0000000..c8443ac --- /dev/null +++ b/src/google/adk/remote_http.h @@ -0,0 +1,45 @@ +#pragma once + +// Thin bounded HTTP helper for the MCP and A2A clients: absolute http(s) +// URLs only, response body capped, non-2xx and transport failures mapped to +// AdkError ("upstream"). Runs over any clients::Client (MockTransport in +// tests). + +#include +#include +#include + +#include "clients/body/json.h" +#include "clients/client.h" + +namespace molo::google::adk { + +struct RemoteReply { + int status = 0; + clients::HeaderMap headers; + std::string body; +}; + +class RemoteHttp { + public: + // headers are sent on every request (e.g. Authorization). They are never + // echoed into errors. + explicit RemoteHttp(std::shared_ptr http, + std::map headers = {}); + + RemoteReply post_json(const std::string& url, const clients::body::Json& body, + const std::map& extra = {}); + RemoteReply get(const std::string& url, + const std::map& extra = {}); + + // True for an absolute http:// or https:// URL without whitespace. + static bool valid_url(const std::string& url); + + private: + RemoteReply finish(const std::string& url, clients::ClientRequest request); + + std::shared_ptr http_; + std::map headers_; +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/runner.cpp b/src/google/adk/runner.cpp new file mode 100644 index 0000000..b04ed39 --- /dev/null +++ b/src/google/adk/runner.cpp @@ -0,0 +1,149 @@ +#include "google/adk/runner.h" + +#include "google/adk/caps.h" +#include "google/adk/error.h" +#include "google/resource.h" + +namespace molo::google::adk { + +using clients::body::Json; + +void RunLimits::validate() const { + auto check = [](int v, int cap, const char* what) { + if (v < 1 || v > cap) + throw AdkError::invalid(std::string(what) + " outside 1.." + std::to_string(cap)); + }; + check(max_steps, AdkCaps::kMaxSteps, "max_steps"); + check(max_tool_calls, AdkCaps::kMaxToolCalls, "max_tool_calls"); + check(wall_clock_ms, AdkCaps::kMaxWallClockMs, "wall_clock_ms"); +} + +Json RunResult::to_json() const { + Json o = Json::object(); + o.set("text", Json(text)); + o.set("author", Json(author)); + o.set("stop_reason", Json(stop_reason)); + o.set("steps", Json(steps)); + o.set("tool_calls", Json(tool_calls)); + Json ev = Json::array(); + for (const Event& e : events) ev.push(e.to_json()); + o.set("events", ev); + o.set("state", state); + return o; +} + +Runner::Runner(std::shared_ptr model, + std::shared_ptr sessions, + std::shared_ptr memory, RunLimits limits) + : model_(std::move(model)), + sessions_(std::move(sessions)), + memory_(std::move(memory)), + limits_(limits) { + if (!model_) throw AdkError::invalid("runner needs a model"); + if (!sessions_) throw AdkError::invalid("runner needs a session service"); + limits_.validate(); +} + +RunResult Runner::run(const std::shared_ptr& root, + const std::string& session_id, + const std::string& user_text, const std::string& user_id) { + if (!root) throw AdkError::invalid("no agent"); + if (user_text.empty()) throw AdkError::invalid("empty input"); + if (user_text.size() > AdkCaps::kMaxInputChars) + throw AdkError::invalid("input over " + std::to_string(AdkCaps::kMaxInputChars) + + " characters"); + Session session; + if (auto existing = sessions_->get(session_id)) { + session = *existing; + } else { + session = sessions_->create(session_id, user_id); + } + + Budget budget(limits_.max_steps, limits_.max_tool_calls, limits_.wall_clock_ms); + RunContext ctx{*model_, budget}; + ctx.state = session.state; + // History: user turns and final answers, newest kMaxHistoryContents. + for (const Event& e : session.events) { + if (e.author == "user") { + ctx.history.push_back(e.content); + } else if (e.final) { + Content c = e.content; + c.role = "model"; + ctx.history.push_back(std::move(c)); + } + } + if (ctx.history.size() > AdkCaps::kMaxHistoryContents) + ctx.history.erase(ctx.history.begin(), + ctx.history.end() - AdkCaps::kMaxHistoryContents); + + Content input = Content::user(user_text); + Event user_event{"user", input, false}; + + RunResult result; + try { + Content out = root->run(ctx, input); + result.text = out.text(); + // The author is the agent that wrote the last final event. + for (auto it = ctx.events.rbegin(); it != ctx.events.rend(); ++it) + if (it->final) { + result.author = it->author; + break; + } + } catch (const AdkError& e) { + if (e.code() != "budget") throw; + result.stop_reason = e.message(); + } + result.steps = budget.steps() > limits_.max_steps ? limits_.max_steps : budget.steps(); + result.tool_calls = budget.tool_calls() > limits_.max_tool_calls + ? limits_.max_tool_calls + : budget.tool_calls(); + result.events.push_back(user_event); + for (Event& e : ctx.events) result.events.push_back(std::move(e)); + + session.state = ctx.state; + for (const Event& e : result.events) session.events.push_back(e); + sessions_->save(session); + result.state = ctx.state; + return result; +} + +void Runner::remember(const std::string& session_id) { + if (!memory_) throw AdkError::invalid("no memory service configured"); + auto s = sessions_->get(session_id); + if (!s) throw AdkError::invalid("unknown session: " + session_id); + memory_->add_session(*s); +} + +std::shared_ptr make_load_memory_tool(std::shared_ptr memory, + std::string user_id) { + Json query = Json::object(); + query.set("type", Json("string")); + Json props = Json::object(); + props.set("query", query); + Json req = Json::array(); + req.push(Json("query")); + Json schema = Json::object(); + schema.set("type", Json("object")); + schema.set("properties", props); + schema.set("required", req); + return std::make_shared( + "load_memory", "Search long-term memory for past conversation snippets.", + schema, + [memory = std::move(memory), user_id = std::move(user_id)]( + const Json& args, ToolContext&) { + Json out = Json::object(); + Json items = Json::array(); + for (const MemoryEntry& m : + memory->search(user_id, args.find("query")->as_string(), + AdkCaps::kMaxMemoryResults)) { + Json item = Json::object(); + item.set("author", Json(m.author)); + item.set("text", Json(m.text)); + items.push(item); + } + out.set("memories", items); + return out; + }); +} + +} // namespace molo::google::adk diff --git a/src/google/adk/runner.h b/src/google/adk/runner.h new file mode 100644 index 0000000..9db6951 --- /dev/null +++ b/src/google/adk/runner.h @@ -0,0 +1,67 @@ +#pragma once + +// Runner: executes one user turn against an agent tree over a +// LanguageModel (function calling loop lives in Agent::run). Hard caps per +// turn: model calls, tool calls, wall clock (AdkCaps). A cap hit does not +// throw: the result carries stop_reason and whatever events were produced. +// Model errors (GoogleError) propagate and the session is left unchanged. + +#include +#include +#include + +#include "google/adk/agent.h" +#include "google/adk/caps.h" +#include "google/adk/session.h" + +namespace molo::google::adk { + +struct RunLimits { + int max_steps = AdkCaps::kMaxSteps; + int max_tool_calls = AdkCaps::kMaxToolCalls; + int wall_clock_ms = AdkCaps::kMaxWallClockMs; + // Throws AdkError (invalid_argument) when any value is below 1 or above its cap. + void validate() const; +}; + +struct RunResult { + std::string text; + std::string author; // Agent that produced the final answer. + // completed | max_steps | max_tool_calls | timeout | max_transfers | + // max_calls_per_step + std::string stop_reason = "completed"; + int steps = 0; + int tool_calls = 0; + std::vector events; // This turn only, user event first. + clients::body::Json state; // Session state after the turn. + clients::body::Json to_json() const; +}; + +class Runner { + public: + Runner(std::shared_ptr model, + std::shared_ptr sessions, + std::shared_ptr memory = nullptr, RunLimits limits = {}); + + // Creates the session on first use. Validates ids and text (1..kMaxInputChars). + RunResult run(const std::shared_ptr& root, + const std::string& session_id, const std::string& user_text, + const std::string& user_id = "user"); + + // Copies the session into the memory service (explicit, never implicit). + void remember(const std::string& session_id); + + const RunLimits& limits() const { return limits_; } + + private: + std::shared_ptr model_; + std::shared_ptr sessions_; + std::shared_ptr memory_; + RunLimits limits_; +}; + +// Tool that searches the memory service for one user ("load_memory"). +std::shared_ptr make_load_memory_tool(std::shared_ptr memory, + std::string user_id); + +} // namespace molo::google::adk diff --git a/src/google/adk/session.cpp b/src/google/adk/session.cpp new file mode 100644 index 0000000..c682756 --- /dev/null +++ b/src/google/adk/session.cpp @@ -0,0 +1,130 @@ +#include "google/adk/session.h" + +#include +#include +#include + +#include "google/adk/caps.h" +#include "google/adk/error.h" +#include "google/resource.h" + +namespace molo::google::adk { + +using clients::body::Json; + +Json Event::to_json() const { + Json o = Json::object(); + o.set("author", Json(author)); + o.set("content", content.to_json()); + o.set("final", Json(final)); + return o; +} + +Session InMemorySessionService::create(const std::string& id, + const std::string& user_id) { + if (!valid_segment(id)) throw AdkError::invalid("invalid session id"); + if (!valid_segment(user_id)) throw AdkError::invalid("invalid user id"); + std::lock_guard lock(mutex_); + if (sessions_.count(id)) throw AdkError::invalid("session exists: " + id); + while (sessions_.size() >= AdkCaps::kMaxSessions && !order_.empty()) { + sessions_.erase(order_.front()); + order_.erase(order_.begin()); + } + Session s; + s.id = id; + s.user_id = user_id; + sessions_[id] = s; + order_.push_back(id); + return s; +} + +std::optional InMemorySessionService::get(const std::string& id) { + std::lock_guard lock(mutex_); + auto it = sessions_.find(id); + if (it == sessions_.end()) return std::nullopt; + return it->second; +} + +void InMemorySessionService::save(const Session& session) { + if (!session.state.is_object()) throw AdkError::invalid("state must be an object"); + if (session.state.as_object().size() > AdkCaps::kMaxStateKeys) + throw AdkError::invalid("session state over key cap"); + for (const auto& [k, v] : session.state.as_object()) + if (v.dump().size() > AdkCaps::kMaxStateValueBytes) + throw AdkError::invalid("session state value over byte cap: " + k); + std::lock_guard lock(mutex_); + auto it = sessions_.find(session.id); + if (it == sessions_.end()) throw AdkError::invalid("unknown session: " + session.id); + it->second = session; + auto& ev = it->second.events; + if (ev.size() > AdkCaps::kMaxEventsPerSession) + ev.erase(ev.begin(), ev.begin() + (ev.size() - AdkCaps::kMaxEventsPerSession)); +} + +bool InMemorySessionService::remove(const std::string& id) { + std::lock_guard lock(mutex_); + order_.erase(std::remove(order_.begin(), order_.end(), id), order_.end()); + return sessions_.erase(id) > 0; +} + +std::size_t InMemorySessionService::size() const { + std::lock_guard lock(mutex_); + return sessions_.size(); +} + +namespace { +std::set words(const std::string& text) { + std::set out; + std::string cur; + for (char ch : text) { + if (std::isalnum(static_cast(ch))) { + cur += static_cast(std::tolower(static_cast(ch))); + } else { + if (cur.size() > 2) out.insert(cur); + cur.clear(); + } + } + if (cur.size() > 2) out.insert(cur); + return out; +} +} // namespace + +void InMemoryMemoryService::add_session(const Session& session) { + std::lock_guard lock(mutex_); + for (const Event& e : session.events) { + if (!(e.author == "user" || e.final)) continue; + std::string text = e.content.text(); + if (text.empty()) continue; + entries_.push_back({session.user_id, session.id, e.author, text}); + } + if (entries_.size() > AdkCaps::kMaxMemoryEntries) + entries_.erase(entries_.begin(), + entries_.begin() + (entries_.size() - AdkCaps::kMaxMemoryEntries)); +} + +std::vector InMemoryMemoryService::search( + const std::string& user_id, const std::string& query, std::size_t limit) { + limit = std::min(limit, AdkCaps::kMaxMemoryResults); + std::set q = words(query); + std::vector> scored; + std::lock_guard lock(mutex_); + for (const MemoryEntry& e : entries_) { + if (e.user_id != user_id) continue; + std::size_t score = 0; + for (const std::string& w : words(e.text)) score += q.count(w); + if (score > 0) scored.push_back({score, &e}); + } + std::stable_sort(scored.begin(), scored.end(), + [](const auto& a, const auto& b) { return a.first > b.first; }); + std::vector out; + for (std::size_t i = 0; i < scored.size() && i < limit; ++i) + out.push_back(*scored[i].second); + return out; +} + +std::size_t InMemoryMemoryService::size() const { + std::lock_guard lock(mutex_); + return entries_.size(); +} + +} // namespace molo::google::adk diff --git a/src/google/adk/session.h b/src/google/adk/session.h new file mode 100644 index 0000000..6587de2 --- /dev/null +++ b/src/google/adk/session.h @@ -0,0 +1,91 @@ +#pragma once + +// Session and memory seams of the ADK, with bounded in-memory defaults. +// These are local interfaces: the ADK does not depend on the sessions +// module (Agent Sessions / Memory Bank); an adapter over that module can +// implement the same interfaces later. + +#include +#include +#include +#include +#include +#include + +#include "clients/body/json.h" +#include "google/gemini_types.h" + +namespace molo::google::adk { + +struct Event { + std::string author; // "user" or an agent name + Content content; + bool final = false; // A final answer of an agent (kept in history) + clients::body::Json to_json() const; +}; + +struct Session { + std::string id; + std::string user_id; + clients::body::Json state = clients::body::Json::object(); + std::vector events; +}; + +class SessionService { + public: + virtual ~SessionService() = default; + virtual Session create(const std::string& id, const std::string& user_id) = 0; + virtual std::optional get(const std::string& id) = 0; + virtual void save(const Session& session) = 0; + virtual bool remove(const std::string& id) = 0; +}; + +// Bounded: kMaxSessions (oldest created evicted), kMaxEventsPerSession +// (oldest dropped), kMaxStateKeys and kMaxStateValueBytes on save. +class InMemorySessionService : public SessionService { + public: + Session create(const std::string& id, const std::string& user_id) override; + std::optional get(const std::string& id) override; + void save(const Session& session) override; + bool remove(const std::string& id) override; + std::size_t size() const; + + private: + mutable std::mutex mutex_; + std::map sessions_; + std::vector order_; // creation order for eviction +}; + +struct MemoryEntry { + std::string user_id; + std::string session_id; + std::string author; + std::string text; +}; + +class MemoryService { + public: + virtual ~MemoryService() = default; + // Stores the text of the session's user and final agent events. + virtual void add_session(const Session& session) = 0; + virtual std::vector search(const std::string& user_id, + const std::string& query, + std::size_t limit) = 0; +}; + +// Keyword overlap ranking, no embeddings. Bounded by kMaxMemoryEntries +// (oldest dropped) and kMaxMemoryResults per search. +class InMemoryMemoryService : public MemoryService { + public: + void add_session(const Session& session) override; + std::vector search(const std::string& user_id, + const std::string& query, + std::size_t limit) override; + std::size_t size() const; + + private: + mutable std::mutex mutex_; + std::vector entries_; +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/studio.cpp b/src/google/adk/studio.cpp new file mode 100644 index 0000000..55430c6 --- /dev/null +++ b/src/google/adk/studio.cpp @@ -0,0 +1,147 @@ +#include "google/adk/studio.h" + +#include "google/adk/caps.h" +#include "google/adk/error.h" + +namespace molo::google::adk { + +using clients::body::Json; + +ToolRegistry::ToolRegistry() { add(make_exit_loop_tool()); } + +void ToolRegistry::add(std::shared_ptr tool) { + if (!tool) throw AdkError::invalid("null tool"); + tools_[tool->name()] = std::move(tool); +} + +std::shared_ptr ToolRegistry::find(const std::string& name) const { + auto it = tools_.find(name); + return it == tools_.end() ? nullptr : it->second; +} + +std::vector ToolRegistry::names() const { + std::vector out; + for (const auto& [k, v] : tools_) out.push_back(k); + return out; +} + +namespace { + +std::string str(const Json& o, const char* key) { + const Json* v = o.find(key); + if (!v) return ""; + if (!v->is_string()) throw AdkError::invalid(std::string(key) + " must be a string"); + return v->as_string(); +} + +std::shared_ptr build(const Json& doc, const ToolRegistry& registry, + int depth, int& count) { + if (depth > AdkCaps::kMaxAgentDepth) throw AdkError::invalid("definition deeper than the depth cap"); + if (++count > 64) throw AdkError::invalid("definition has over 64 agents"); + if (!doc.is_object()) throw AdkError::invalid("agent definition must be an object"); + std::string cls = str(doc, "agent_class"); + if (cls.empty()) cls = "LlmAgent"; + std::string name = str(doc, "name"); + std::string description = str(doc, "description"); + + std::shared_ptr agent; + if (cls == "LlmAgent" || cls == "Agent") { + Agent::Config cfg; + cfg.name = name; + cfg.description = description; + cfg.model = str(doc, "model"); + cfg.instruction = str(doc, "instruction"); + cfg.output_key = str(doc, "output_key"); + if (const Json* tools = doc.find("tools")) { + if (!tools->is_array()) throw AdkError::invalid("tools must be an array"); + for (const Json& t : tools->as_array()) { + std::string tn = t.is_string() ? t.as_string() : str(t, "name"); + auto tool = registry.find(tn); + if (!tool) throw AdkError::invalid("unknown tool: " + tn); + cfg.tools.push_back(tool); + } + } + agent = std::make_shared(std::move(cfg)); + } else if (cls == "SequentialAgent") { + agent = std::make_shared(name, description); + } else if (cls == "ParallelAgent") { + agent = std::make_shared(name, description); + } else if (cls == "LoopAgent") { + int iters = 3; + if (const Json* m = doc.find("max_iterations")) { + if (!m->is_number()) throw AdkError::invalid("max_iterations must be a number"); + iters = static_cast(m->as_int()); + } + agent = std::make_shared(name, description, iters); + } else { + throw AdkError::invalid("unsupported agent_class: " + cls); + } + + if (const Json* subs = doc.find("sub_agents")) { + if (!subs->is_array()) throw AdkError::invalid("sub_agents must be an array"); + for (const Json& s : subs->as_array()) { + if (s.is_object() && s.has("config_path") && !s.has("name")) + throw AdkError::invalid("config_path references are not supported, inline the sub-agent"); + agent->add_sub_agent(build(s, registry, depth + 1, count)); + } + } + return agent; +} + +} // namespace + +Json AgentDefinition::to_json(const BaseAgent& agent) { + Json o = Json::object(); + o.set("agent_class", Json(agent.kind())); + o.set("name", Json(agent.name())); + if (!agent.description().empty()) o.set("description", Json(agent.description())); + if (const auto* a = dynamic_cast(&agent)) { + const Agent::Config& c = a->config(); + if (!c.model.empty()) o.set("model", Json(c.model)); + if (!c.instruction.empty()) o.set("instruction", Json(c.instruction)); + if (!c.output_key.empty()) o.set("output_key", Json(c.output_key)); + if (!c.tools.empty()) { + Json tools = Json::array(); + for (const auto& t : c.tools) { + Json item = Json::object(); + item.set("name", Json(t->name())); + tools.push(item); + } + o.set("tools", tools); + } + } else if (const auto* l = dynamic_cast(&agent)) { + o.set("max_iterations", Json(l->max_iterations())); + } + if (!agent.sub_agents().empty()) { + Json subs = Json::array(); + for (const auto& s : agent.sub_agents()) subs.push(to_json(*s)); + o.set("sub_agents", subs); + } + return o; +} + +std::string AgentDefinition::to_yaml(const BaseAgent& agent) { + return clients::body::yaml_dump(to_json(agent)); +} + +std::shared_ptr AgentDefinition::from_json(const Json& doc, + const ToolRegistry& registry) { + int count = 0; + return build(doc, registry, 1, count); +} + +std::shared_ptr AgentDefinition::from_text(const std::string& text, + const ToolRegistry& registry) { + if (text.size() > AdkCaps::kMaxDefinitionBytes) + throw AdkError::invalid("definition over " + std::to_string(AdkCaps::kMaxDefinitionBytes) + + " bytes"); + Json doc; + try { + doc = Json::parse(text); + } catch (const std::exception& e) { + throw AdkError::invalid(std::string("definition is not valid JSON: ") + e.what()); + } + return from_json(doc, registry); +} + +} // namespace molo::google::adk diff --git a/src/google/adk/studio.h b/src/google/adk/studio.h new file mode 100644 index 0000000..a752ccc --- /dev/null +++ b/src/google/adk/studio.h @@ -0,0 +1,45 @@ +#pragma once + +// Agent Studio export / import of an agent definition. The format follows +// ADK's Agent Config (agent_class, name, model, description, instruction, +// tools [{name}], sub_agents) with two local rules: sub_agents are inlined +// objects (config_path references are rejected loudly) and workflow agents +// carry max_iterations. A definition names tools; behavior comes from the +// ToolRegistry at import time, so a definition never contains code. + +#include +#include +#include + +#include "clients/body/json.h" +#include "google/adk/agent.h" + +namespace molo::google::adk { + +class ToolRegistry { + public: + ToolRegistry(); // Pre-registers exit_loop. + void add(std::shared_ptr tool); // Replaces a tool of the same name. + std::shared_ptr find(const std::string& name) const; + std::vector names() const; + std::size_t size() const { return tools_.size(); } + + private: + std::map> tools_; +}; + +class AgentDefinition { + public: + static clients::body::Json to_json(const BaseAgent& agent); + // Block-style YAML of the same document (clients::body::yaml_dump). + static std::string to_yaml(const BaseAgent& agent); + + // Validates class, names, tool names, counts, depth before building. + static std::shared_ptr from_json(const clients::body::Json& doc, + const ToolRegistry& registry); + // Parses JSON text (at most kMaxDefinitionBytes) then from_json. + static std::shared_ptr from_text(const std::string& text, + const ToolRegistry& registry); +}; + +} // namespace molo::google::adk diff --git a/src/google/adk/tool.cpp b/src/google/adk/tool.cpp new file mode 100644 index 0000000..fe4aa7b --- /dev/null +++ b/src/google/adk/tool.cpp @@ -0,0 +1,89 @@ +#include "google/adk/tool.h" + +#include "google/adk/caps.h" +#include "google/adk/error.h" + +namespace molo::google::adk { + +using clients::body::Json; + +bool valid_identifier(const std::string& name) { + if (name.empty() || name.size() > AdkCaps::kMaxNameChars) return false; + for (std::size_t i = 0; i < name.size(); ++i) { + char c = name[i]; + bool alpha = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; + bool digit = c >= '0' && c <= '9'; + if (!(alpha || (digit && i > 0))) return false; + } + return true; +} + +FunctionTool::FunctionTool(std::string name, std::string description, + Json schema, Fn fn) + : name_(std::move(name)), + description_(std::move(description)), + schema_(std::move(schema)), + fn_(std::move(fn)) { + if (!valid_identifier(name_)) + throw AdkError::invalid("tool name must match [A-Za-z_][A-Za-z0-9_]*"); + if (!fn_) throw AdkError::invalid("tool function is empty"); + if (!schema_.is_null() && !schema_.is_object()) + throw AdkError::invalid("tool schema must be an object or null"); +} + +FunctionDeclaration FunctionTool::declaration() const { + FunctionDeclaration d; + d.name = name_; + d.description = description_; + d.parameters = schema_; + return d; +} + +namespace { +bool type_matches(const std::string& type, const Json& v) { + if (type == "string") return v.is_string(); + if (type == "number") return v.is_number(); + if (type == "integer") + return v.is_number() && v.as_number() == static_cast(v.as_int()); + if (type == "boolean") return v.is_bool(); + if (type == "object") return v.is_object(); + if (type == "array") return v.is_array(); + return true; // Unknown type names are not enforced. +} +} // namespace + +void FunctionTool::validate(const Json& schema, const Json& args) { + if (schema.is_null()) return; + if (!args.is_object()) throw AdkError::invalid("arguments must be an object"); + if (const Json* req = schema.find("required"); req && req->is_array()) + for (const Json& k : req->as_array()) + if (k.is_string() && !args.has(k.as_string())) + throw AdkError::invalid("missing required argument: " + k.as_string()); + const Json* props = schema.find("properties"); + if (!props || !props->is_object()) return; + for (const auto& [key, def] : props->as_object()) { + const Json* v = args.find(key); + if (!v) continue; + const Json* t = def.find("type"); + if (t && t->is_string() && !type_matches(t->as_string(), *v)) + throw AdkError::invalid("argument " + key + " must be " + t->as_string()); + } +} + +Json FunctionTool::call(const Json& args, ToolContext& context) { + validate(schema_, args); + return fn_(args, context); +} + +std::shared_ptr make_exit_loop_tool() { + return std::make_shared( + "exit_loop", "Call when the task is done to stop the surrounding loop.", + Json(), [](const Json&, ToolContext& ctx) { + ctx.escalate = true; + Json out = Json::object(); + out.set("ok", Json(true)); + return out; + }); +} + +} // namespace molo::google::adk diff --git a/src/google/adk/tool.h b/src/google/adk/tool.h new file mode 100644 index 0000000..4554623 --- /dev/null +++ b/src/google/adk/tool.h @@ -0,0 +1,62 @@ +#pragma once + +// Tool seam of the ADK. A Tool has a Gemini function declaration and a +// call(). FunctionTool builds one from a lambda plus a JSON schema and +// validates arguments (required keys, basic types) before the lambda runs. + +#include +#include +#include + +#include "clients/body/json.h" +#include "google/gemini_types.h" + +namespace molo::google::adk { + +// What a tool may touch during one call. +struct ToolContext { + clients::body::Json& state; // Session state (object), shared per turn. + std::string agent; // Name of the calling agent. + bool& escalate; // Set true to end the enclosing LoopAgent. +}; + +class Tool { + public: + virtual ~Tool() = default; + virtual const std::string& name() const = 0; + virtual FunctionDeclaration declaration() const = 0; + // Throws AdkError on failure; the agent turns that into a function + // response {"error": "..."} so the model can recover. + virtual clients::body::Json call(const clients::body::Json& args, + ToolContext& context) = 0; +}; + +class FunctionTool : public Tool { + public: + using Fn = std::function; + // schema: OpenAPI-subset object schema, or null for no parameters. + FunctionTool(std::string name, std::string description, + clients::body::Json schema, Fn fn); + + const std::string& name() const override { return name_; } + FunctionDeclaration declaration() const override; + clients::body::Json call(const clients::body::Json& args, + ToolContext& context) override; + + // Checks required keys and the primitive type of declared properties + // (string, number, integer, boolean, object, array). Throws AdkError. + static void validate(const clients::body::Json& schema, + const clients::body::Json& args); + + private: + std::string name_; + std::string description_; + clients::body::Json schema_; + Fn fn_; +}; + +// Built-in: ends the enclosing LoopAgent ("exit_loop"). +std::shared_ptr make_exit_loop_tool(); + +} // namespace molo::google::adk diff --git a/src/google/adk/tools/check_discovery.py b/src/google/adk/tools/check_discovery.py new file mode 100644 index 0000000..6d67307 --- /dev/null +++ b/src/google/adk/tools/check_discovery.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Fails when a Google call declared in direct_model.h is not in Discovery. + +Reads the table between DISCOVERY-TABLE-BEGIN / END in direct_model.h, fetches +https://.googleapis.com/$discovery/rest?version= (no auth), and +checks: method id exists, HTTP verb matches, flatPath matches, and every +declared request field exists in the method's request schema. +Usage: python3 -I src/google/adk/tools/check_discovery.py +""" +import json +import os +import re +import sys +import urllib.request + +HEADER = os.path.join(os.path.dirname(__file__), "..", "direct_model.h") + + +def parse_table(): + text = open(HEADER).read() + block = text.split("DISCOVERY-TABLE-BEGIN")[1].split("DISCOVERY-TABLE-END")[0] + calls = re.findall(r'\{"(\w+)", "(\w+)", "([\w.]+)", "(\w+)", "([^"]+)"\}', block) + req = block.split("kDirectRequestFields")[1].split("};")[0] + part = block.split("kDirectPartFields")[1].split("};")[0] + return calls, re.findall(r'"(\w+)"', req), re.findall(r'"(\w+)"', part) + + +def methods(doc): + out = {} + + def walk(res, path): + for k, v in res.get("resources", {}).items(): + walk(v, path + [k]) + for k, m in res.get("methods", {}).items(): + out[".".join(path + [k])] = m + + walk(doc, []) + return out + + +def main(): + calls, fields, part_fields = parse_table() + if not calls or not fields or not part_fields: + print("FAIL: empty declared table") + return 1 + cache, failures = {}, 0 + for service, version, rpc, http, flat in calls: + key = (service, version) + if key not in cache: + url = f"https://{service}.googleapis.com/$discovery/rest?version={version}" + with urllib.request.urlopen(url, timeout=60) as r: + doc = json.load(r) + cache[key] = (doc, methods(doc)) + doc, table = cache[key] + m = table.get(rpc) + if not m: + print(f"FAIL {service} {version}: no method {rpc}") + failures += 1 + continue + if m["httpMethod"] != http or m.get("flatPath") != flat: + print(f"FAIL {rpc}: discovery says {m['httpMethod']} {m.get('flatPath')}") + failures += 1 + continue + schema = doc["schemas"][m["request"]["$ref"]]["properties"] + for f in fields: + if f not in schema: + print(f"FAIL {rpc}: request schema has no field {f}") + failures += 1 + part = [v for k, v in doc["schemas"].items() if k.endswith("Part") and "properties" in v] + for f in part_fields: + if not any(f in v["properties"] for v in part): + print(f"FAIL {service} {version}: Part schema has no field {f}") + failures += 1 + print(f"ok {service} {version} {rpc} {http} {flat}") + print("PASS" if not failures else f"{failures} failure(s)") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/google/adk/trigger.cpp b/src/google/adk/trigger.cpp new file mode 100644 index 0000000..84a1b63 --- /dev/null +++ b/src/google/adk/trigger.cpp @@ -0,0 +1,75 @@ +#include "google/adk/trigger.h" + +#include + +#include "google/adk/caps.h" +#include "google/adk/error.h" + +namespace molo::google::adk { + +namespace { +std::vector take(std::deque& q, std::size_t n) { + std::vector out; + while (!q.empty() && out.size() < n) { + out.push_back(std::move(q.front())); + q.pop_front(); + } + return out; +} +} // namespace + +bool QueueTrigger::push(TriggerEvent event) { + std::lock_guard lock(mutex_); + if (queue_.size() >= AdkCaps::kMaxTriggerQueue) { + ++dropped_; + return false; + } + queue_.push_back(std::move(event)); + return true; +} + +std::vector QueueTrigger::poll(std::size_t max_events) { + std::lock_guard lock(mutex_); + return take(queue_, max_events); +} + +std::size_t QueueTrigger::dropped() const { + std::lock_guard lock(mutex_); + return dropped_; +} + +std::size_t QueueTrigger::pending() const { + std::lock_guard lock(mutex_); + return queue_.size(); +} + +BatchTrigger::BatchTrigger(std::vector events) { + if (events.size() > AdkCaps::kMaxTriggerQueue) + throw AdkError::invalid("batch over the trigger queue cap"); + for (auto& e : events) queue_.push_back(std::move(e)); +} + +std::vector BatchTrigger::poll(std::size_t max_events) { + std::lock_guard lock(mutex_); + return take(queue_, max_events); +} + +std::vector TriggerDispatcher::dispatch(Trigger& trigger, + std::size_t max_events) { + max_events = std::min(max_events, AdkCaps::kMaxTriggerBatch); + std::vector out; + for (TriggerEvent& e : trigger.poll(max_events)) { + DispatchOutcome o; + o.event_id = e.id; + try { + o.result = runner_->run(agent_, e.id, e.payload, "trigger"); + o.ok = true; + } catch (const std::exception& ex) { + o.error = ex.what(); + } + out.push_back(std::move(o)); + } + return out; +} + +} // namespace molo::google::adk diff --git a/src/google/adk/trigger.h b/src/google/adk/trigger.h new file mode 100644 index 0000000..f2fd53b --- /dev/null +++ b/src/google/adk/trigger.h @@ -0,0 +1,76 @@ +#pragma once + +// Batch and event-driven triggers as plain local interfaces. The Agent +// Runtime triggers (BigQuery, Pub/Sub) belong to the runtime module; this +// seam only says "something produced work for an agent". A Trigger yields +// events; TriggerDispatcher runs one agent turn per event with hard caps. + +#include +#include +#include +#include +#include + +#include "google/adk/runner.h" + +namespace molo::google::adk { + +struct TriggerEvent { + std::string id; // Used as the session id: [A-Za-z0-9._-], 1..128 + std::string payload; // Becomes the user message +}; + +class Trigger { + public: + virtual ~Trigger() = default; + // Returns at most max_events pending events and removes them. + virtual std::vector poll(std::size_t max_events) = 0; +}; + +// Event-driven: a producer pushes, the dispatcher polls. Bounded queue; +// push returns false (and counts a drop) when full. +class QueueTrigger : public Trigger { + public: + bool push(TriggerEvent event); + std::vector poll(std::size_t max_events) override; + std::size_t dropped() const; + std::size_t pending() const; + + private: + mutable std::mutex mutex_; + std::deque queue_; + std::size_t dropped_ = 0; +}; + +// Batch: a fixed list of inputs handed out in slices. +class BatchTrigger : public Trigger { + public: + explicit BatchTrigger(std::vector events); + std::vector poll(std::size_t max_events) override; + + private: + std::mutex mutex_; + std::deque queue_; +}; + +struct DispatchOutcome { + std::string event_id; + bool ok = false; + std::string error; // Set when !ok + RunResult result; +}; + +class TriggerDispatcher { + public: + TriggerDispatcher(std::shared_ptr runner, std::shared_ptr agent) + : runner_(std::move(runner)), agent_(std::move(agent)) {} + // One poll of at most max_events (capped at kMaxTriggerBatch). A failing + // event is reported in its outcome and does not stop the rest. + std::vector dispatch(Trigger& trigger, std::size_t max_events); + + private: + std::shared_ptr runner_; + std::shared_ptr agent_; +}; + +} // namespace molo::google::adk diff --git a/tests/example/agent/adk/page_test.cpp b/tests/example/agent/adk/page_test.cpp new file mode 100644 index 0000000..0ae6060 --- /dev/null +++ b/tests/example/agent/adk/page_test.cpp @@ -0,0 +1,24 @@ +// Routes: GET /agent/adk, /agent/adk/status, /agent/adk/garden +#include "support/GoogleRig.hpp" + +using namespace molo::example::test; + +int main() { + GoogleRig none(false); + Fixture f(none.client); + auto page = f.client->get("/agent/adk"); + check(page.status == 200, "page 200 without a credential"); + check(contains(page.body, "agent_adk.js") && contains(page.body, "adk-run"), "page has the runner UI"); + auto st = f.client->get("/agent/adk/status"); + check(st.status == 200 && contains(st.body, "\"configured\":false"), "status shows not configured"); + check(contains(st.body, "\"max_steps\":12") && contains(st.body, "\"max_tool_calls\":24"), "caps shown"); + auto g = f.client->get("/agent/adk/garden"); + check(g.status == 200, "garden 200"); + for (const char* id : {"code_modernization", "financial_analysis", "economic_research", "invoice_processing"}) + check(contains(g.body, id), std::string("garden lists ") + id); + check(none.mock->send_count() == 0, "side effect: no upstream traffic"); + check(f.client->post("/agent/adk").status == 405, "post page is 405"); + check(f.client->post("/agent/adk/garden").status == 405, "post garden is 405"); + check(f.client->get("/agent/adk/run").status == 405, "get run is 405"); + return finish("agent/adk page"); +} diff --git a/tests/example/agent/adk/run_test.cpp b/tests/example/agent/adk/run_test.cpp new file mode 100644 index 0000000..b02d977 --- /dev/null +++ b/tests/example/agent/adk/run_test.cpp @@ -0,0 +1,29 @@ +// Route: POST /agent/adk/run (validation and credential gate; the model call +// itself is proven live in the google suite, not scripted here) +#include "support/GoogleRig.hpp" + +using namespace molo::example::test; + +int main() { + GoogleRig none(false); + Fixture f(none.client); + auto post = [&](const std::string& body) { + return f.client->post("/agent/adk/run", body, "application/json"); + }; + auto ok = post("{\"prompt\":\"total of 2 and 3?\",\"template\":\"financial_analysis\"}"); + check(ok.status == 503 && contains(ok.body, "google_not_configured"), "no credential is a loud 503"); + check(post("not json").status == 422, "bad json is 422"); + check(post("{\"prompt\":\"\"}").status == 422, "empty prompt is 422"); + check(post("{\"prompt\":\"" + std::string(2001, 'x') + "\"}").status == 422, "prompt over cap is 422"); + check(post("{\"prompt\":\"hi\",\"template\":\"nope\"}").status == 422, "unknown template is 422"); + check(none.mock->send_count() == 0, "side effect: nothing sent without a credential"); + + GoogleRig keyed; + Fixture g(keyed.client); + check(g.client->post("/agent/adk/run", "{\"prompt\":\"\"}", "application/json").status == 422, + "validation also runs with a credential"); + check(g.client->post("/agent/adk/run", "{\"prompt\":\"hi\",\"cid\":\"bad id!\"}", "application/json").status == 422, + "bad session id is 422"); + check(keyed.mock->send_count() == 0, "rejected input never reached Google"); + return finish("agent/adk run"); +} diff --git a/tests/example/agent/adk/studio_test.cpp b/tests/example/agent/adk/studio_test.cpp new file mode 100644 index 0000000..98a31bb --- /dev/null +++ b/tests/example/agent/adk/studio_test.cpp @@ -0,0 +1,40 @@ +// Routes: POST /agent/adk/export, /agent/adk/import, /agent/adk/ap2/validate +#include "support/GoogleRig.hpp" + +using namespace molo::example::test; + +int main() { + GoogleRig none(false); + Fixture f(none.client); + auto post = [&](const std::string& path, const std::string& body) { + return f.client->post(path, body, "application/json"); + }; + auto ex = post("/agent/adk/export", "{\"template\":\"invoice_processing\"}"); + check(ex.status == 200 && contains(ex.body, "\"agent_class\":\"LlmAgent\"") && + contains(ex.body, "invoice_processing"), + "export returns the definition"); + check(contains(ex.body, "\"yaml\":"), "export includes yaml"); + check(post("/agent/adk/export", "{\"template\":\"nope\"}").status == 422, "unknown template is 422"); + + std::string def = "{\"agent_class\":\"SequentialAgent\",\"name\":\"flow\",\"sub_agents\":[" + "{\"name\":\"a\",\"model\":\"m\",\"instruction\":\"x\",\"tools\":[{\"name\":\"word_count\"}]}]}"; + auto im = post("/agent/adk/import", def); + check(im.status == 200 && contains(im.body, "\"word_count\""), "import round-trips a known tool"); + check(post("/agent/adk/import", "{\"name\":\"a\",\"tools\":[{\"name\":\"ghost\"}]}").status == 422, + "unknown tool is 422"); + check(post("/agent/adk/import", "{\"name\":\"a\",\"agent_class\":\"Evil\"}").status == 422, "bad class is 422"); + check(post("/agent/adk/import", "oops").status == 422, "bad json is 422"); + + std::string intent = "{\"id\":\"i1\",\"description\":\"sleeve\",\"max_amount_minor\":5000,\"currency\":\"EUR\"}"; + std::string cart = "{\"id\":\"c1\",\"intent_id\":\"i1\",\"merchant\":\"m\",\"items\":[" + "{\"sku\":\"s\",\"quantity\":2,\"unit_amount_minor\":1500}],\"total_minor\":3000,\"currency\":\"EUR\"}"; + check(post("/agent/adk/ap2/validate", "{\"intent\":" + intent + ",\"cart\":" + cart + "}").status == 200, + "valid mandate chain is 200"); + std::string bad_cart = cart.substr(0, cart.find("3000,")) + "9999," + cart.substr(cart.find("3000,") + 5); + check(post("/agent/adk/ap2/validate", "{\"intent\":" + intent + ",\"cart\":" + bad_cart + "}").status == 422, + "cart total mismatch is 422"); + check(post("/agent/adk/ap2/validate", "{}").status == 422, "missing intent is 422"); + check(f.client->get("/agent/adk/export").status == 405, "get export is 405"); + check(none.mock->send_count() == 0, "none of these routes call Google"); + return finish("agent/adk studio"); +} diff --git a/tests/src/google/adk/fake_model.h b/tests/src/google/adk/fake_model.h new file mode 100644 index 0000000..69d5af1 --- /dev/null +++ b/tests/src/google/adk/fake_model.h @@ -0,0 +1,72 @@ +#pragma once + +// Scripted LanguageModel for ADK tests: replies come from a queue (or a +// repeat reply), every request is recorded. Thread-safe for ParallelAgent. + +#include +#include +#include +#include +#include + +#include "clients/body/json.h" +#include "google/gemini_types.h" + +namespace adk_test { + +using molo::clients::body::Json; +using molo::google::GenerateRequest; +using molo::google::GenerateResponse; + +inline GenerateResponse text_reply(const std::string& text) { + return GenerateResponse::from_json(Json::parse( + "{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":" + + Json(text).dump() + "}]}}]}")); +} + +inline GenerateResponse call_reply(const std::string& name, const std::string& args_json) { + return GenerateResponse::from_json(Json::parse( + "{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"functionCall\":{\"name\":\"" + + name + "\",\"args\":" + args_json + "}}]}}]}")); +} + +class FakeModel : public molo::google::LanguageModel { + public: + void push(GenerateResponse r) { queue_.push_back(std::move(r)); } + // Returned forever once the queue is empty. + void repeat(GenerateResponse r) { repeat_ = std::move(r); has_repeat_ = true; } + void delay_ms(int ms) { delay_ = ms; } + + GenerateResponse generate(const GenerateRequest& request) override { + std::lock_guard lock(mutex_); + seen_.push_back(request); + if (delay_ > 0) std::this_thread::sleep_for(std::chrono::milliseconds(delay_)); + if (!queue_.empty()) { + GenerateResponse r = std::move(queue_.front()); + queue_.pop_front(); + return r; + } + if (has_repeat_) return repeat_; + return text_reply("(fake model queue empty)"); + } + void stream(const GenerateRequest& request, + const std::function& on_chunk) override { + on_chunk(generate(request)); + } + + std::vector seen() { + std::lock_guard lock(mutex_); + return seen_; + } + std::size_t calls() { return seen().size(); } + + private: + std::mutex mutex_; + std::deque queue_; + GenerateResponse repeat_; + bool has_repeat_ = false; + int delay_ = 0; + std::vector seen_; +}; + +} // namespace adk_test diff --git a/tests/src/google/adk/test_adk_core.cpp b/tests/src/google/adk/test_adk_core.cpp new file mode 100644 index 0000000..dfea429 --- /dev/null +++ b/tests/src/google/adk/test_adk_core.cpp @@ -0,0 +1,353 @@ +// ADK core: agents, tools, runner caps, multi-agent graph, sessions, memory. +// Local logic against a fake LanguageModel; no Google traffic. +#include + +#include "framework.h" +#include "fake_model.h" +#include "google/adk/agent.h" +#include "google/adk/error.h" +#include "google/adk/runner.h" +#include "google/adk/session.h" +#include "google/adk/tool.h" + +using namespace molo::google; +using namespace molo::google::adk; +using AdkTool = molo::google::adk::Tool; +using adk_test::call_reply; +using adk_test::FakeModel; +using adk_test::text_reply; +using molo::clients::body::Json; + +namespace { + +std::shared_ptr weather_tool(int* counter = nullptr) { + Json city = Json::object(); + city.set("type", Json("string")); + Json props = Json::object(); + props.set("city", city); + Json req = Json::array(); + req.push(Json("city")); + Json schema = Json::object(); + schema.set("type", Json("object")); + schema.set("properties", props); + schema.set("required", req); + return std::make_shared( + "get_weather", "Weather for a city", schema, + [counter](const Json& args, ToolContext&) { + if (counter) ++*counter; + Json out = Json::object(); + out.set("city", *args.find("city")); + out.set("temp_c", Json(21)); + return out; + }); +} + +std::shared_ptr llm(const std::string& name, std::vector> tools = {}, + const std::string& instruction = "Be brief.", + const std::string& output_key = "") { + Agent::Config c; + c.name = name; + c.model = "m"; + c.instruction = instruction; + c.tools = std::move(tools); + c.output_key = output_key; + return std::make_shared(std::move(c)); +} + +struct Rig { + std::shared_ptr model = std::make_shared(); + std::shared_ptr sessions = std::make_shared(); + std::shared_ptr memory = std::make_shared(); + Runner runner(RunLimits l = {}) { return Runner(model, sessions, memory, l); } +}; + +} // namespace + +TEST(adk, function_calling_loop) { + Rig r; + int calls = 0; + r.model->push(call_reply("get_weather", "{\"city\":\"Utrecht\"}")); + r.model->push(text_reply("It is 21 C in Utrecht.")); + Runner runner = r.runner(); + RunResult res = runner.run(llm("root", {weather_tool(&calls)}), "s1", "weather in Utrecht?"); + ASSERT_EQ(calls, 1); + ASSERT_EQ(res.text, "It is 21 C in Utrecht."); + ASSERT_EQ(res.stop_reason, "completed"); + ASSERT_EQ(res.steps, 2); + ASSERT_EQ(res.tool_calls, 1); + ASSERT_EQ(res.author, "root"); + // Second request carries the model's call and our function response. + auto seen = r.model->seen(); + ASSERT_EQ(seen.size(), 2u); + ASSERT_EQ(seen[0].tools.size(), 1u); + ASSERT_EQ(seen[0].tools[0].functions[0].name, "get_weather"); + ASSERT_EQ(seen[1].contents.size(), 3u); + const Part& fr = seen[1].contents[2].parts[0]; + ASSERT_TRUE(fr.function_response.has_value()); + ASSERT_EQ(fr.function_response->response.find("temp_c")->as_int(), 21); +} + +TEST(adk, tool_errors_go_back_to_the_model) { + Rig r; + r.model->push(call_reply("get_weather", "{}")); // missing required arg + r.model->push(call_reply("get_weather", "{\"city\":5}")); // wrong type + r.model->push(call_reply("nope", "{}")); // unknown tool + r.model->push(text_reply("done")); + Runner runner = r.runner(); + RunResult res = runner.run(llm("root", {weather_tool()}), "s", "go"); + ASSERT_EQ(res.text, "done"); + auto seen = r.model->seen(); + auto err = [&](std::size_t i) { + return seen[i].contents.back().parts[0].function_response->response.dump(); + }; + ASSERT_TRUE(err(1).find("missing required argument: city") != std::string::npos); + ASSERT_TRUE(err(2).find("must be string") != std::string::npos); + ASSERT_TRUE(err(3).find("unknown tool: nope") != std::string::npos); +} + +TEST(adk, step_cap_stops_a_runaway_loop) { + Rig r; + r.model->repeat(call_reply("get_weather", "{\"city\":\"x\"}")); + RunLimits l; + l.max_steps = 3; + Runner runner = r.runner(l); + RunResult res = runner.run(llm("root", {weather_tool()}), "s", "loop"); + ASSERT_EQ(res.stop_reason, "max_steps"); + ASSERT_EQ(r.model->calls(), 3u); +} + +TEST(adk, tool_call_cap) { + Rig r; + r.model->repeat(call_reply("get_weather", "{\"city\":\"x\"}")); + RunLimits l; + l.max_tool_calls = 2; + Runner runner = r.runner(l); + RunResult res = runner.run(llm("root", {weather_tool()}), "s", "loop"); + ASSERT_EQ(res.stop_reason, "max_tool_calls"); + ASSERT_EQ(res.tool_calls, 2); +} + +TEST(adk, wall_clock_cap) { + Rig r; + r.model->delay_ms(30); + r.model->repeat(call_reply("get_weather", "{\"city\":\"x\"}")); + RunLimits l; + l.wall_clock_ms = 50; + Runner runner = r.runner(l); + RunResult res = runner.run(llm("root", {weather_tool()}), "s", "loop"); + ASSERT_EQ(res.stop_reason, "timeout"); +} + +TEST(adk, limits_and_input_validation) { + Rig r; + RunLimits big; + big.max_steps = AdkCaps::kMaxSteps + 1; + ASSERT_THROW(r.runner(big), AdkError); + RunLimits zero; + zero.wall_clock_ms = 0; + ASSERT_THROW(r.runner(zero), AdkError); + Runner runner = r.runner(); + auto a = llm("root"); + ASSERT_THROW(runner.run(a, "s", ""), AdkError); + ASSERT_THROW(runner.run(a, "s", std::string(AdkCaps::kMaxInputChars + 1, 'x')), AdkError); + ASSERT_THROW(runner.run(a, "bad id/../", "hi"), AdkError); + ASSERT_EQ(r.model->calls(), 0u); // rejected before any model call + ASSERT_THROW(llm("bad name"), AdkError); + ASSERT_THROW(llm("root", {weather_tool(), weather_tool(), nullptr}), AdkError); +} + +TEST(adk, too_many_calls_in_one_reply) { + Rig r; + std::string parts; + for (int i = 0; i < AdkCaps::kMaxCallsPerStep + 1; ++i) + parts += std::string(i ? "," : "") + "{\"functionCall\":{\"name\":\"get_weather\",\"args\":{\"city\":\"a\"}}}"; + r.model->push(GenerateResponse::from_json(Json::parse( + "{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[" + parts + "]}}]}"))); + Runner runner = r.runner(); + ASSERT_EQ(runner.run(llm("root", {weather_tool()}), "s", "x").stop_reason, "max_calls_per_step"); +} + +TEST(adk, tool_result_size_cap) { + Rig r; + auto big = std::make_shared("big", "", Json(), [](const Json&, ToolContext&) { + Json o = Json::object(); + o.set("blob", Json(std::string(AdkCaps::kMaxToolResultBytes + 10, 'x'))); + return o; + }); + r.model->push(call_reply("big", "{}")); + r.model->push(text_reply("ok")); + Runner runner = r.runner(); + runner.run(llm("root", {big}), "s", "x"); + auto seen = r.model->seen(); + ASSERT_TRUE(seen[1].contents.back().parts[0].function_response->response.dump().find( + "over 32768 bytes") != std::string::npos); +} + +TEST(adk, sequential_shares_state_and_templates_instructions) { + Rig r; + auto seq = std::make_shared("pipeline", ""); + seq->add_sub_agent(llm("writer", {}, "Write.", "draft")); + seq->add_sub_agent(llm("editor", {}, "Edit this: {draft} (missing {nokey})")); + r.model->push(text_reply("first draft")); + r.model->push(text_reply("final text")); + Runner runner = r.runner(); + RunResult res = runner.run(seq, "s", "topic"); + ASSERT_EQ(res.text, "final text"); + ASSERT_EQ(res.author, "editor"); + ASSERT_EQ(res.state.find("draft")->as_string(), "first draft"); + auto seen = r.model->seen(); + ASSERT_EQ(seen[1].system->parts[0].text, "Edit this: first draft (missing {nokey})"); +} + +TEST(adk, parallel_runs_all_branches_and_merges) { + Rig r; + auto par = std::make_shared("fanout", ""); + par->add_sub_agent(llm("a", {}, "A", "ka")); + par->add_sub_agent(llm("b", {}, "B", "kb")); + r.model->repeat(text_reply("same")); + Runner runner = r.runner(); + RunResult res = runner.run(par, "s", "go"); + ASSERT_EQ(r.model->calls(), 2u); + ASSERT_EQ(res.text, "a: same\n\nb: same"); + ASSERT_TRUE(res.state.has("ka") && res.state.has("kb")); + ASSERT_THROW(par->add_sub_agent(llm("a")), AdkError); // duplicate name +} + +TEST(adk, loop_exits_on_tool_and_on_cap) { + { + Rig r; + auto loop = std::make_shared("refine", "", 5); + loop->add_sub_agent(llm("worker", {make_exit_loop_tool()})); + r.model->push(text_reply("try 1")); + r.model->push(call_reply("exit_loop", "{}")); + r.model->push(text_reply("good enough")); + Runner runner = r.runner(); + RunResult res = runner.run(loop, "s", "go"); + ASSERT_EQ(res.text, "good enough"); + ASSERT_EQ(r.model->calls(), 3u); + } + { + Rig r; + auto loop = std::make_shared("refine", "", 3); + loop->add_sub_agent(llm("worker")); + r.model->repeat(text_reply("again")); + Runner runner = r.runner(); + runner.run(loop, "s", "go"); + ASSERT_EQ(r.model->calls(), 3u); + } + ASSERT_THROW(LoopAgent("l", "", 0), AdkError); + ASSERT_THROW(LoopAgent("l", "", AdkCaps::kMaxLoopIterations + 1), AdkError); +} + +TEST(adk, transfer_to_sub_agent_and_caps) { + Rig r; + auto root = llm("router", {}, "Route."); + root->add_sub_agent(llm("billing")); + root->add_sub_agent(llm("support")); + r.model->push(call_reply("transfer_to_agent", "{\"agent_name\":\"billing\"}")); + r.model->push(text_reply("billing answer")); + Runner runner = r.runner(); + RunResult res = runner.run(root, "s", "invoice question"); + ASSERT_EQ(res.text, "billing answer"); + ASSERT_EQ(res.author, "billing"); + auto seen = r.model->seen(); + // The router offered the transfer function with both targets; the sub-agent + // got the original user message. + ASSERT_EQ(seen[0].tools[0].functions[0].name, "transfer_to_agent"); + ASSERT_EQ(seen[1].contents.back().text(), "invoice question"); +} + +TEST(adk, unknown_transfer_target_is_a_tool_error_and_pingpong_is_capped) { + { + Rig r; + auto root = llm("router"); + root->add_sub_agent(llm("billing")); + r.model->push(call_reply("transfer_to_agent", "{\"agent_name\":\"ghost\"}")); + r.model->push(text_reply("handled myself")); + Runner runner = r.runner(); + ASSERT_EQ(runner.run(root, "s", "x").text, "handled myself"); + } + { + Rig r; + auto root = llm("a"); + root->add_sub_agent(llm("b")); + // a hands to b, b hands back to its parent a, forever. + r.model->repeat(call_reply("transfer_to_agent", "{\"agent_name\":\"b\"}")); + RunLimits l; + Runner runner = r.runner(l); + RunResult res = runner.run(root, "s", "x"); + ASSERT_TRUE(res.stop_reason == "max_transfers" || res.stop_reason == "max_steps"); + } +} + +TEST(adk, graph_shape_caps) { + auto root = llm("root"); + for (std::size_t i = 0; i < AdkCaps::kMaxSubAgents; ++i) + root->add_sub_agent(llm("s" + std::to_string(i))); + ASSERT_THROW(root->add_sub_agent(llm("one_too_many")), AdkError); + // Depth: a chain deeper than kMaxAgentDepth is refused at run time. + Rig r; + r.model->repeat(text_reply("x")); + std::shared_ptr top = std::make_shared("d0", ""); + BaseAgent* cur = top.get(); + for (int i = 1; i <= AdkCaps::kMaxAgentDepth; ++i) { + auto next = std::make_shared("d" + std::to_string(i), ""); + BaseAgent* raw = next.get(); + cur->add_sub_agent(next); + cur = raw; + } + Runner runner = r.runner(); + ASSERT_THROW(runner.run(top, "s", "x"), AdkError); +} + +TEST(adk, session_history_persists_and_is_bounded) { + Rig r; + r.model->repeat(text_reply("ok")); + Runner runner = r.runner(); + auto a = llm("root"); + runner.run(a, "s", "first"); + runner.run(a, "s", "second"); + auto seen = r.model->seen(); + // Turn two sees: user "first", model "ok", user "second". + ASSERT_EQ(seen[1].contents.size(), 3u); + ASSERT_EQ(seen[1].contents[0].text(), "first"); + ASSERT_EQ(seen[1].contents[1].role, "model"); + + InMemorySessionService svc; + for (std::size_t i = 0; i < AdkCaps::kMaxSessions + 5; ++i) + svc.create("id" + std::to_string(i), "u"); + ASSERT_EQ(svc.size(), AdkCaps::kMaxSessions); + ASSERT_FALSE(svc.get("id0").has_value()); // oldest evicted + Session s = *svc.get("id10"); + for (std::size_t i = 0; i < AdkCaps::kMaxEventsPerSession + 20; ++i) + s.events.push_back({"user", Content::user("m"), false}); + svc.save(s); + ASSERT_EQ(svc.get("id10")->events.size(), AdkCaps::kMaxEventsPerSession); + s.state.set("big", Json(std::string(AdkCaps::kMaxStateValueBytes + 1, 'x'))); + ASSERT_THROW(svc.save(s), AdkError); + ASSERT_THROW(svc.create("id10", "u"), AdkError); + ASSERT_THROW(svc.create("bad id", "u"), AdkError); +} + +TEST(adk, memory_service_ranks_and_scopes_by_user) { + Rig r; + r.model->repeat(text_reply("Your favourite colour is green.")); + Runner runner = r.runner(); + auto a = llm("root"); + runner.run(a, "m1", "My favourite colour is green", "alice"); + runner.remember("m1"); + runner.run(a, "m2", "Unrelated pasta recipe", "bob"); + runner.remember("m2"); + auto hits = r.memory->search("alice", "what colour do I like", 5); + ASSERT_TRUE(!hits.empty()); + ASSERT_TRUE(hits[0].text.find("green") != std::string::npos); + ASSERT_TRUE(r.memory->search("alice", "pasta recipe", 5).empty()); + ASSERT_TRUE(!r.memory->search("bob", "pasta recipe", 5).empty()); + // The load_memory tool reaches the same data. + r.model->push(call_reply("load_memory", "{\"query\":\"favourite colour\"}")); + r.model->push(text_reply("green")); + runner.run(llm("mem", {make_load_memory_tool(r.memory, "alice")}), "m3", "what do I like?", "alice"); + auto seen = r.model->seen(); + ASSERT_TRUE(seen.back().contents.back().parts[0].function_response->response.dump().find( + "green") != std::string::npos); +} diff --git a/tests/src/google/adk/test_adk_misc.cpp b/tests/src/google/adk/test_adk_misc.cpp new file mode 100644 index 0000000..6733845 --- /dev/null +++ b/tests/src/google/adk/test_adk_misc.cpp @@ -0,0 +1,443 @@ +// ADK: Agent Studio definitions, Garden catalog, AP2 types, triggers, +// DirectModel request construction, MCP / A2A protocol clients, live checks. +// MCP and A2A are not Google APIs: their scripted peers follow the primary +// specs (see adk/SPEC.md Sources). No scripted Google replies appear here. +#include +#include +#include + +#include "framework.h" +#include "fake_model.h" +#include "clients/transports/http_transport.h" +#include "clients/transports/mock_transport.h" +#include "google/adk/a2a.h" +#include "google/adk/error.h" +#include "google/adk/ap2.h" +#include "google/adk/direct_model.h" +#include "google/adk/garden.h" +#include "google/adk/mcp.h" +#include "google/adk/runner.h" +#include "google/adk/studio.h" +#include "google/adk/trigger.h" +#include "google/credentials.h" +#include "google/generative.h" + +using namespace molo::google; +using namespace molo::google::adk; +using AdkTool = molo::google::adk::Tool; +using adk_test::call_reply; +using adk_test::FakeModel; +using adk_test::text_reply; +using molo::clients::ClientResponse; +using molo::clients::HeaderMap; +using molo::clients::Method; +using molo::clients::body::Json; +using molo::clients::transports::MockTransport; + +namespace { + +ClientResponse ok_json(const std::string& body, const char* ctype = "application/json") { + HeaderMap h; + h.set("Content-Type", ctype); + return ClientResponse(200, h, body); +} + +struct Peer { + MockTransport* mock; + std::shared_ptr http; + Peer() { + auto t = std::make_unique(); + mock = t.get(); + http = std::make_shared( + std::make_shared(std::move(t))); + } +}; + +std::shared_ptr llm(const std::string& name, std::vector> tools = {}) { + Agent::Config c; + c.name = name; + c.model = "m"; + c.instruction = "Do the thing."; + c.tools = std::move(tools); + return std::make_shared(std::move(c)); +} + +std::shared_ptr echo_tool(const std::string& name) { + return std::make_shared(name, "echo", Json(), [](const Json&, ToolContext&) { + return Json::object(); + }); +} + +} // namespace + +// ---- Studio ----------------------------------------------------------------- + +TEST(adk_studio, export_import_round_trip) { + ToolRegistry reg; + reg.add(echo_tool("lookup")); + auto root = llm("root", {reg.find("lookup")}); + auto seq = std::make_shared("flow", "runs in order"); + seq->add_sub_agent(llm("a")); + auto loop = std::make_shared("loop", "", 4); + loop->add_sub_agent(llm("b", {reg.find("exit_loop")})); + seq->add_sub_agent(loop); + root->add_sub_agent(seq); + + Json doc = AgentDefinition::to_json(*root); + ASSERT_EQ(doc.find("agent_class")->as_string(), "LlmAgent"); + ASSERT_EQ(doc.find("tools")->as_array()[0].find("name")->as_string(), "lookup"); + auto copy = AgentDefinition::from_text(doc.dump(), reg); + ASSERT_EQ(AgentDefinition::to_json(*copy).dump(), doc.dump()); + ASSERT_TRUE(copy->find("b") != nullptr); + ASSERT_EQ(dynamic_cast(copy->find("loop"))->max_iterations(), 4); + ASSERT_TRUE(AgentDefinition::to_yaml(*root).find("agent_class") != std::string::npos); +} + +TEST(adk_studio, rejects_bad_definitions_loudly) { + ToolRegistry reg; + ASSERT_THROW(AgentDefinition::from_text("not json", reg), AdkError); + ASSERT_THROW(AgentDefinition::from_text("{\"name\":\"x\",\"agent_class\":\"EvilAgent\"}", reg), AdkError); + ASSERT_THROW(AgentDefinition::from_text("{\"name\":\"bad name\"}", reg), AdkError); + ASSERT_THROW(AgentDefinition::from_text("{\"name\":\"x\",\"tools\":[{\"name\":\"ghost\"}]}", reg), AdkError); + ASSERT_THROW(AgentDefinition::from_text( + "{\"name\":\"x\",\"sub_agents\":[{\"config_path\":\"y.yaml\"}]}", reg), AdkError); + ASSERT_THROW(AgentDefinition::from_text("{\"name\":\"l\",\"agent_class\":\"LoopAgent\",\"max_iterations\":99}", reg), + AdkError); + ASSERT_THROW(AgentDefinition::from_text(std::string(AdkCaps::kMaxDefinitionBytes + 1, ' '), reg), AdkError); +} + +// ---- Garden ----------------------------------------------------------------- + +TEST(adk_garden, four_templates_instantiate_with_or_without_tools) { + ASSERT_EQ(AgentGarden::templates().size(), 4u); + for (const char* id : {"code_modernization", "financial_analysis", "economic_research", "invoice_processing"}) + ASSERT_TRUE(AgentGarden::find(id) != nullptr); + ToolRegistry reg; + std::vector missing; + auto bare = AgentGarden::instantiate("invoice_processing", reg, &missing); + ASSERT_EQ(missing.size(), 1u); + ASSERT_TRUE(dynamic_cast(bare.get())->config().tools.empty()); + reg.add(echo_tool("validate_invoice")); + auto full = AgentGarden::instantiate("invoice_processing", reg); + ASSERT_EQ(dynamic_cast(full.get())->config().tools.size(), 1u); + ASSERT_THROW(AgentGarden::instantiate("nope", reg), AdkError); + ASSERT_EQ(AgentGarden::catalog_json().find("templates")->as_array().size(), 4u); +} + +// ---- AP2 -------------------------------------------------------------------- + +TEST(adk_ap2, mandate_chain_validation) { + ap2::IntentMandate intent; + intent.id = "int-1"; + intent.description = "Buy a laptop sleeve"; + intent.merchants = {"shop.example"}; + intent.max_amount_minor = 5000; + intent.currency = "EUR"; + intent.validate(); + + ap2::CartMandate cart; + cart.id = "cart-1"; + cart.intent_id = "int-1"; + cart.merchant = "shop.example"; + cart.items = {{"sku1", "Sleeve", 2, 1500}}; + cart.total_minor = 3000; + cart.currency = "EUR"; + cart.validate_against(intent); + + ap2::PaymentMandate pay; + pay.id = "pay-1"; + pay.cart_id = "cart-1"; + pay.payment_method_token = "tok_abc"; + pay.amount_minor = 3000; + pay.currency = "EUR"; + pay.validate_against(cart); + + ap2::CartMandate round = ap2::CartMandate::from_json(Json::parse(cart.to_json().dump())); + ASSERT_EQ(round.to_json().dump(), cart.to_json().dump()); + + cart.total_minor = 2999; + ASSERT_THROW(cart.validate(), AdkError); // total != item sum + cart.total_minor = 3000; + cart.merchant = "evil.example"; + ASSERT_THROW(cart.validate_against(intent), AdkError); + cart.merchant = "shop.example"; + intent.max_amount_minor = 2000; + ASSERT_THROW(cart.validate_against(intent), AdkError); + pay.amount_minor = 1; + ASSERT_THROW(pay.validate_against(cart), AdkError); + intent.currency = "eur"; + ASSERT_THROW(intent.validate(), AdkError); +} + +// ---- Triggers --------------------------------------------------------------- + +TEST(adk_trigger, batch_and_event_dispatch_with_caps) { + auto model = std::make_shared(); + model->repeat(text_reply("handled")); + auto runner = std::make_shared(model, std::make_shared()); + TriggerDispatcher dispatcher(runner, llm("worker")); + + BatchTrigger batch({{"job1", "a"}, {"job2", "b"}, {"bad id!", "c"}}); + auto out = dispatcher.dispatch(batch, 10); + ASSERT_EQ(out.size(), 3u); + ASSERT_TRUE(out[0].ok && out[1].ok); + ASSERT_FALSE(out[2].ok); // a bad id fails alone, the rest ran + ASSERT_EQ(out[0].result.text, "handled"); + + QueueTrigger queue; + for (std::size_t i = 0; i < AdkCaps::kMaxTriggerQueue; ++i) ASSERT_TRUE(queue.push({"e" + std::to_string(i), "x"})); + ASSERT_FALSE(queue.push({"overflow", "x"})); + ASSERT_EQ(queue.dropped(), 1u); + auto first = dispatcher.dispatch(queue, 100000); // capped to kMaxTriggerBatch + ASSERT_EQ(first.size(), AdkCaps::kMaxTriggerBatch); +} + +// ---- DirectModel (request construction only) -------------------------------- + +TEST(adk_direct, validates_before_network_and_fields_match_declared_table) { + auto transport = std::make_unique(); + MockTransport* mock = transport.get(); + auto client = std::make_shared(std::move(transport), Credentials::api_key("k")); + DirectModel model(client, "gemini-test"); + GenerateRequest bad; + bad.model = "../evil"; + bad.contents.push_back(Content::user("hi")); + ASSERT_THROW(model.generate(bad), GoogleError); + ASSERT_EQ(mock->send_count(), 0u); + ASSERT_THROW(DirectModel(client, "a/b"), GoogleError); + + // Every top-level key the request builder can emit is a declared field + // (tools/check_discovery.py proves those exist in Google's schemas). + GenerateRequest full; + full.system = Content::user("sys"); + full.contents.push_back(Content::user("hi")); + molo::google::Tool t; + t.functions.push_back({"f", "d", Json()}); + full.tools.push_back(t); + full.tool_mode = "AUTO"; + full.config.temperature = 0.5; + full.safety.push_back({"HARM_CATEGORY_HARASSMENT", "BLOCK_NONE"}); + Json body = full.to_json(); + for (const auto& [key, v] : body.as_object()) { + bool declared = false; + for (const char* f : kDirectRequestFields) declared = declared || key == f; + ASSERT_TRUE(declared); + } + ASSERT_EQ(body.as_object().size(), 6u); +} + +// ---- MCP -------------------------------------------------------------------- + +TEST(adk_mcp, handshake_list_call_and_tool_adapter) { + Peer p; + p.mock->expect_response(Method::kPost, "/mcp", + ok_json("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{}}}")); + p.mock->expect_status(Method::kPost, "/mcp", 202); + p.mock->expect_response(Method::kPost, "/mcp", + ok_json("{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"tools\":[{\"name\":\"get-weather\",\"description\":\"d\"," + "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\"}}," + "\"required\":[\"location\"]}}],\"nextCursor\":\"p2\"}}")); + p.mock->expect_response(Method::kPost, "/mcp", + ok_json("data: {\"jsonrpc\":\"2.0\",\"id\":3,\"result\":{\"tools\":[{\"name\":\"ping\",\"inputSchema\":{\"type\":\"object\"}}]}}\n\n", + "text/event-stream")); + p.mock->expect_response(Method::kPost, "/mcp", + ok_json("{\"jsonrpc\":\"2.0\",\"id\":4,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"72F\"}],\"isError\":false}}")); + p.mock->expect_response(Method::kPost, "/mcp", + ok_json("{\"jsonrpc\":\"2.0\",\"id\":5,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"boom\"}],\"isError\":true}}")); + auto mcp = std::make_shared(p.http, "https://mcp.example.com/mcp"); + mcp->initialize(); + auto tools = mcp->tools(); + ASSERT_EQ(tools.size(), 2u); + ASSERT_EQ(tools[0]->name(), "get_weather"); // sanitized for Gemini + ASSERT_EQ(tools[0]->declaration().parameters.find("required")->as_array().size(), 1u); + bool esc = false; + Json state = Json::object(); + ToolContext tc{state, "a", esc}; + Json args = Json::object(); + args.set("location", Json("NYC")); + ASSERT_EQ(tools[0]->call(args, tc).find("text")->as_string(), "72F"); + ASSERT_THROW(tools[0]->call(args, tc), AdkError); // isError -> tool error + ASSERT_THROW(tools[0]->call(Json::object(), tc), AdkError); // schema check, no request + auto seen = p.mock->seen(); + ASSERT_EQ(seen.size(), 6u); + ASSERT_TRUE(seen[0].body.find("\"method\":\"initialize\"") != std::string::npos); + ASSERT_TRUE(seen[2].body.find("\"method\":\"tools/list\"") != std::string::npos); + ASSERT_TRUE(seen[3].body.find("\"cursor\":\"p2\"") != std::string::npos); + ASSERT_TRUE(seen[4].body.find("\"name\":\"get-weather\"") != std::string::npos); + ASSERT_EQ(seen[2].headers.get_or("MCP-Protocol-Version", ""), "2025-06-18"); +} + +TEST(adk_mcp, errors_and_url_validation) { + Peer p; + ASSERT_THROW(McpClient(p.http, "ftp://x"), AdkError); + ASSERT_THROW(McpClient(p.http, "not a url"), AdkError); + p.mock->expect_response(Method::kPost, "/mcp", + ok_json("{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32602,\"message\":\"Unknown tool\"}}")); + McpClient mcp(p.http, "https://mcp.example.com/mcp"); + ASSERT_THROW(mcp.call_tool("x", Json::object()), AdkError); + p.mock->expect_status(Method::kPost, "/mcp", 403, "no"); + try { + mcp.list_tools(); + FAIL("403 must throw"); + } catch (const AdkError& e) { + ASSERT_EQ(e.code(), "upstream"); + } +} + +// ---- A2A -------------------------------------------------------------------- + +TEST(adk_a2a, card_send_get_in_both_dialects) { + { + Peer p; + p.mock->expect_response(Method::kGet, "/.well-known/agent-card.json", + ok_json("{\"name\":\"Invoicer\",\"description\":\"d\",\"version\":\"1\"," + "\"supportedInterfaces\":[{\"url\":\"https://a2a.example.com/rpc\",\"protocolBinding\":\"JSONRPC\"}]," + "\"capabilities\":{\"streaming\":true},\"skills\":[{\"id\":\"s1\",\"name\":\"Extract\"}]}")); + p.mock->expect_response(Method::kPost, "/rpc", + ok_json("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"task\":{\"id\":\"t1\",\"contextId\":\"c1\"," + "\"status\":{\"state\":\"TASK_STATE_COMPLETED\"}," + "\"artifacts\":[{\"parts\":[{\"text\":\"total 42\"}]}]}}}")); + p.mock->expect_response(Method::kPost, "/rpc", + ok_json("{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"id\":\"t1\",\"status\":{\"state\":\"TASK_STATE_INPUT_REQUIRED\"," + "\"message\":{\"parts\":[{\"text\":\"which currency?\"}]}}}}")); + auto a2a = std::make_shared(p.http, "https://a2a.example.com/"); + A2aCard card = a2a->fetch_card(); + ASSERT_EQ(card.name, "Invoicer"); + ASSERT_TRUE(card.streaming); + ASSERT_EQ(card.skills.size(), 1u); + ASSERT_EQ(a2a->endpoint(), "https://a2a.example.com/rpc"); + A2aTask t = a2a->send_message("invoice please"); + ASSERT_EQ(t.state, "completed"); + ASSERT_TRUE(t.terminal()); + ASSERT_EQ(t.text, "total 42"); + A2aTask g = a2a->get_task("t1"); + ASSERT_EQ(g.state, "input-required"); + ASSERT_EQ(g.text, "which currency?"); + auto seen = p.mock->seen(); + ASSERT_TRUE(seen[1].body.find("\"method\":\"SendMessage\"") != std::string::npos); + ASSERT_TRUE(seen[1].body.find("ROLE_USER") != std::string::npos); + ASSERT_TRUE(seen[2].body.find("\"method\":\"GetTask\"") != std::string::npos); + } + { + Peer p; + p.mock->expect_response(Method::kPost, "/", + ok_json("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"kind\":\"message\",\"role\":\"agent\"," + "\"messageId\":\"m\",\"parts\":[{\"kind\":\"text\",\"text\":\"hello\"}]}}")); + auto a2a = std::make_shared(p.http, "https://old.example.com", A2aDialect::kV03); + A2aTask t = a2a->send_message("hi"); + ASSERT_EQ(t.state, "message"); + ASSERT_EQ(t.text, "hello"); + auto seen = p.mock->seen(); + ASSERT_TRUE(seen[0].body.find("\"method\":\"message/send\"") != std::string::npos); + ASSERT_TRUE(seen[0].body.find("\"kind\":\"text\"") != std::string::npos); + } +} + +TEST(adk_a2a, validation_and_tool_adapter) { + Peer p; + auto a2a = std::make_shared(p.http, "https://a2a.example.com"); + ASSERT_THROW(a2a->send_message(""), AdkError); + ASSERT_THROW(a2a->send_message(std::string(AdkCaps::kMaxA2aTextChars + 1, 'x')), AdkError); + ASSERT_THROW(a2a->get_task(""), AdkError); + ASSERT_THROW(a2a->as_tool("bad name", "d"), AdkError); + ASSERT_THROW(A2aClient(p.http, "javascript:alert(1)"), AdkError); + ASSERT_EQ(p.mock->send_count(), 0u); + auto tool = a2a->as_tool("remote_invoicer", "Remote agent"); + ASSERT_EQ(tool->declaration().name, "remote_invoicer"); +} + +// ---- Live (opt-in) ---------------------------------------------------------- +// MOLO_LIVE_NET=1 plus GOOGLE_API_KEY. An express key (AQ.) uses the Vertex +// publisher endpoint, anything else the Gemini API. Calls are few and small. + +namespace { +bool live_ready(const char* name) { + if (!std::getenv("MOLO_LIVE_NET") || Credentials::env().empty()) { + std::cout << "SKIP " << name << " (set MOLO_LIVE_NET=1 and GOOGLE_API_KEY)\n"; + return false; + } + return true; +} + +std::shared_ptr live_model() { + auto client = std::make_shared( + std::make_unique(), + Credentials::from_env()); + bool express = Credentials::env().rfind("AQ.", 0) == 0; + return std::make_shared( + client, Generative::default_model(), + express ? endpoints::vertex_generative() : endpoints::generative()); +} + +std::shared_ptr live_agent(const std::string& name, const std::string& instruction, + std::vector> tools) { + Agent::Config c; + c.name = name; + c.instruction = instruction; + c.tools = std::move(tools); + c.generate.thinking_budget = 0; + c.generate.max_output_tokens = 200; + return std::make_shared(std::move(c)); +} +} // namespace + +TEST(adk_live, function_calling_loop_against_the_real_model) { + if (!live_ready("adk_live.function_calling_loop_against_the_real_model")) return; + int calls = 0; + Json city = Json::object(); + city.set("type", Json("string")); + Json props = Json::object(); + props.set("city", city); + Json req = Json::array(); + req.push(Json("city")); + Json schema = Json::object(); + schema.set("type", Json("object")); + schema.set("properties", props); + schema.set("required", req); + auto tool = std::make_shared("get_weather", "Current weather for a city", schema, + [&calls](const Json&, ToolContext&) { + ++calls; + Json o = Json::object(); + o.set("temp_c", Json(17)); + o.set("sky", Json("drizzle")); + return o; + }); + Runner runner(live_model(), std::make_shared()); + RunResult r = runner.run( + live_agent("weather", "Use get_weather for weather questions; answer in one sentence.", {tool}), + "live1", "What is the weather in Utrecht right now?"); + std::cout << " live answer (" << r.steps << " steps, " << r.tool_calls << " tool calls): " << r.text << "\n"; + ASSERT_EQ(r.stop_reason, "completed"); + ASSERT_EQ(calls, 1); + ASSERT_TRUE(r.text.find("17") != std::string::npos); +} + +TEST(adk_live, transfer_between_agents_against_the_real_model) { + if (!live_ready("adk_live.transfer_between_agents_against_the_real_model")) return; + auto root = live_agent("router", + "You only route. For any question about numbers call transfer_to_agent with agent_name math_helper.", {}); + root->add_sub_agent(live_agent("math_helper", "Answer the math question with just the number.", {})); + Runner runner(live_model(), std::make_shared()); + RunResult r = runner.run(root, "live2", "What is 12 times 12?"); + std::cout << " live answer by " << r.author << ": " << r.text << "\n"; + ASSERT_EQ(r.stop_reason, "completed"); + ASSERT_EQ(r.author, "math_helper"); + ASSERT_FALSE(r.text.empty()); // The arithmetic itself is the model's, not asserted. +} + +TEST(adk_live, mcp_client_against_a_public_server) { + if (!std::getenv("MOLO_LIVE_NET")) { + std::cout << "SKIP adk_live.mcp_client_against_a_public_server (set MOLO_LIVE_NET=1)\n"; + return; + } + // DeepWiki's public, unauthenticated, read-only MCP endpoint (replies as SSE). + auto http = std::make_shared(std::make_shared( + std::make_unique())); + auto mcp = std::make_shared(http, "https://mcp.deepwiki.com/mcp"); + mcp->initialize(); + auto tools = mcp->tools(); + std::cout << " live MCP tools: " << tools.size() << " first: " + << (tools.empty() ? "" : tools[0]->name()) << "\n"; + ASSERT_TRUE(!tools.empty()); + ASSERT_TRUE(!tools[0]->declaration().parameters.is_null()); +}