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