feat(clients): google foundation for the agent platform: all-verb client, streaming, typed Gemini content, operations

GoogleClient gets every verb and stream_json (SSE and plain JSON), typed
Content/Part/Tool/GenerateRequest with the LanguageModel seam, CloudContext
resource names, long-running operation polling and pagination, OAuth bearer
tokens via GOOGLE_ACCESS_TOKEN. Example scaffold: one stub per agent module
under example/app/agent, wildcard builds, locust excludes /voice /google
/agent. plans/16-agent-platform.md splits the work into nine modules.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-24 04:12:52 +02:00
co-authored by Claude Sonnet 5.5
parent 837de58136
commit 6d744a433f
32 changed files with 1536 additions and 22 deletions
+263
View File
@@ -0,0 +1,263 @@
// Foundation shared by every agent-platform module: all-verb client,
// streaming decoder, typed Gemini content, resource names, operations,
// pagination.
#include <memory>
#include "framework.h"
#include "clients/transports/mock_transport.h"
#include "google/client.h"
#include "google/credentials.h"
#include "google/gemini_types.h"
#include "google/operation.h"
#include "google/resource.h"
#include "google/stream_decoder.h"
using namespace molo::google;
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(const std::string& body, int status = 200) {
HeaderMap h;
h.set("Content-Type", "application/json");
return ClientResponse(status, h, body);
}
struct Rig {
MockTransport* mock;
std::shared_ptr<GoogleClient> client;
Rig() {
auto t = std::make_unique<MockTransport>();
mock = t.get();
client = std::make_shared<GoogleClient>(std::move(t), Credentials::bearer("tok"));
}
};
const ServiceEndpoint kEp = endpoints::custom("t", "https://example.googleapis.com/v1");
} // namespace
TEST(foundation, all_verbs_and_bearer) {
Rig r;
r.mock->expect_response(Method::kGet, "/v1/a", ok("{\"v\":1}"));
r.mock->expect_response(Method::kPatch, "/v1/a", ok("{\"v\":2}"));
r.mock->expect_response(Method::kDelete, "/v1/a", ok("{}"));
ASSERT_EQ(r.client->get_json(kEp, "/a").find("v")->as_int(), 1);
Json body = Json::object();
body.set("x", Json(1));
ASSERT_EQ(r.client->patch_json(kEp, "/a", body).find("v")->as_int(), 2);
r.client->delete_json(kEp, "/a");
auto seen = r.mock->seen();
ASSERT_EQ(seen.size(), 3u);
ASSERT_EQ(seen[0].headers.get_or("Authorization", ""), "Bearer tok");
ASSERT_EQ(seen[1].body, "{\"x\":1}");
r.mock->verify();
}
TEST(foundation, stream_sse_chunked_and_early_stop) {
std::vector<std::string> got;
StreamDecoder d("t", [&](const Json& e) {
got.push_back(e.dump());
return got.size() < 2;
});
ASSERT_TRUE(d.feed("data: {\"a\":1}\n"));
ASSERT_TRUE(d.feed("\ndata: {\"a\":"));
ASSERT_FALSE(d.feed("2}\r\n\r\ndata: {\"a\":3}\n\n")); // sink stops after the 2nd
d.finish();
ASSERT_EQ(got.size(), 2u);
ASSERT_EQ(got[1], "{\"a\":2}");
}
TEST(foundation, stream_plain_json_forms) {
std::vector<std::string> got;
StreamDecoder obj("t", [&](const Json& e) { got.push_back(e.dump()); return true; });
obj.feed("{\"k\":");
obj.feed("1}");
obj.finish();
ASSERT_EQ(got.size(), 1u);
got.clear();
StreamDecoder arr("t", [&](const Json& e) { got.push_back(e.dump()); return true; });
arr.feed("[{\"a\":1},{\"a\":2}]");
arr.finish();
ASSERT_EQ(got.size(), 2u);
}
TEST(foundation, stream_errors) {
StreamDecoder bad("t", [](const Json&) { return true; });
bad.feed("{\"error\":{\"code\":403,\"message\":\"no\",\"status\":\"PERMISSION_DENIED\"}}");
try {
bad.finish();
FAIL("expected GoogleError");
} catch (const GoogleError& e) {
ASSERT_EQ(e.status(), "PERMISSION_DENIED");
ASSERT_EQ(e.http_status(), 403);
}
StreamDecoder sse("t", [](const Json&) { return true; });
ASSERT_THROW(sse.feed("data: {\"error\":{\"message\":\"x\"}}\n\n"), GoogleError);
StreamDecoder cap("t", [](const Json&) { return true; });
cap.feed("{");
ASSERT_THROW(cap.feed(std::string(StreamDecoder::kMaxBytes, 'x')), GoogleError);
}
TEST(foundation, stream_json_through_client) {
Rig r;
r.mock->expect_response(
Method::kPost, "/v1/m:streamGenerateContent",
ok("data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"a\"}]}}]}\n\n"
"data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"b\"}]}}]}\n\n"));
std::string text;
r.client->stream_json(kEp, "/m:streamGenerateContent?alt=sse", Json::object(),
[&](const Json& e) {
text += GenerateResponse::from_json(e).text();
return true;
});
ASSERT_EQ(text, "ab");
}
TEST(foundation, gemini_types_roundtrip) {
GenerateRequest req;
req.system = Content::user("be brief");
req.contents.push_back(Content::user("hi"));
Content call;
call.role = "model";
FunctionCall fc;
fc.name = "get_weather";
fc.args.set("city", Json("Utrecht"));
call.parts.push_back(Part::of_call(fc));
req.contents.push_back(call);
Content resp;
resp.role = "user";
FunctionResponse fr;
fr.name = "get_weather";
fr.response.set("temp", Json(12));
resp.parts.push_back(Part::of_response(fr));
req.contents.push_back(resp);
Tool tool;
FunctionDeclaration decl;
decl.name = "get_weather";
decl.description = "weather";
tool.functions.push_back(decl);
req.tools.push_back(tool);
req.tool_mode = "ANY";
req.config.thinking_budget = 0;
req.config.temperature = 0.5;
req.config.voice_name = "Kore";
Json j = req.to_json();
ASSERT_EQ(j.find("systemInstruction")->find("role"), nullptr);
ASSERT_EQ(j.find("contents")->as_array().size(), 3u);
ASSERT_EQ(j.find("tools")->as_array()[0].find("functionDeclarations")->as_array()[0]
.find("name")->as_string(), "get_weather");
ASSERT_EQ(j.find("toolConfig")->find("functionCallingConfig")->find("mode")->as_string(), "ANY");
ASSERT_EQ(j.find("generationConfig")->find("thinkingConfig")->find("thinkingBudget")->as_int(), 0);
ASSERT_EQ(j.find("generationConfig")->find("speechConfig")->find("voiceConfig")
->find("prebuiltVoiceConfig")->find("voiceName")->as_string(), "Kore");
// Round trip a part with binary data.
Part blob = Part::of_inline("audio/wav", std::string("\x00\x01\xff", 3));
Part back = Part::from_json(Json::parse(blob.to_json().dump()));
ASSERT_TRUE(back.inline_data.has_value());
ASSERT_EQ(back.inline_data->data, std::string("\x00\x01\xff", 3));
}
TEST(foundation, generate_response_parse) {
Json doc = Json::parse(
"{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"hi\"},"
"{\"functionCall\":{\"name\":\"f\",\"args\":{\"a\":1}}}]},\"finishReason\":\"STOP\"}],"
"\"usageMetadata\":{\"promptTokenCount\":3,\"candidatesTokenCount\":4,"
"\"totalTokenCount\":7,\"thoughtsTokenCount\":2},\"modelVersion\":\"v\"}");
GenerateResponse r = GenerateResponse::from_json(doc);
ASSERT_EQ(r.text(), "hi");
ASSERT_EQ(r.function_calls().size(), 1u);
ASSERT_EQ(r.function_calls()[0].name, "f");
ASSERT_EQ(r.usage.total_tokens, 7);
ASSERT_EQ(r.candidates[0].finish_reason, "STOP");
}
TEST(foundation, cloud_context_names) {
CloudContext c;
c.project = "my-proj";
c.location = "europe-west4";
ASSERT_EQ(c.parent(), "projects/my-proj/locations/europe-west4");
ASSERT_EQ(c.child("reasoningEngines", "e1"),
"projects/my-proj/locations/europe-west4/reasoningEngines/e1");
ASSERT_THROW(c.child("reasoningEngines", "../x"), GoogleError);
ASSERT_THROW(c.child("reasoningEngines", ""), GoogleError);
CloudContext bad;
ASSERT_THROW(bad.parent(), GoogleError);
bad.project = "UPPER/case";
ASSERT_THROW(bad.parent(), GoogleError);
ASSERT_EQ(endpoints::aiplatform("europe-west4").base_url,
"https://europe-west4-aiplatform.googleapis.com/v1");
ASSERT_EQ(endpoints::aiplatform("global").base_url,
"https://aiplatform.googleapis.com/v1");
ASSERT_EQ(endpoints::aiplatform_beta("us-central1").base_url,
"https://us-central1-aiplatform.googleapis.com/v1beta1");
ASSERT_THROW(endpoints::aiplatform("evil.com/x"), GoogleError);
}
TEST(foundation, wait_operation_polls_and_fails) {
Rig r;
r.mock->expect_response(Method::kGet, "/v1/projects/p/operations/1",
ok("{\"name\":\"projects/p/operations/1\",\"done\":false}"));
r.mock->expect_response(Method::kGet, "/v1/projects/p/operations/1",
ok("{\"name\":\"projects/p/operations/1\",\"done\":true,"
"\"response\":{\"id\":\"e1\"}}"));
int sleeps = 0;
Operation op = wait_operation(*r.client, kEp, "projects/p/operations/1",
[&](std::chrono::milliseconds) { ++sleeps; });
ASSERT_TRUE(op.done);
ASSERT_EQ(sleeps, 1);
ASSERT_EQ(op.response.find("id")->as_string(), "e1");
Rig f;
f.mock->expect_response(Method::kGet, "/v1/projects/p/operations/2",
ok("{\"done\":true,\"error\":{\"code\":3,\"message\":\"bad\"}}"));
try {
wait_operation(*f.client, kEp, "projects/p/operations/2", [](auto) {});
FAIL("expected GoogleError");
} catch (const GoogleError& e) {
ASSERT_EQ(e.status(), "OPERATION_FAILED");
}
ASSERT_THROW(wait_operation(*f.client, kEp, "../etc", [](auto) {}), GoogleError);
}
TEST(foundation, wait_operation_caps) {
Rig r;
r.mock->expect(
[] {
molo::clients::transports::MockExpectation e;
e.method = Method::kGet;
e.path = "/v1/projects/p/operations/9";
e.response = ok("{\"done\":false}");
e.times = 1000;
return e;
}());
int sleeps = 0;
try {
wait_operation(*r.client, kEp, "projects/p/operations/9",
[&](std::chrono::milliseconds) { ++sleeps; });
FAIL("expected DEADLINE_EXCEEDED");
} catch (const GoogleError& e) {
ASSERT_EQ(e.status(), "DEADLINE_EXCEEDED");
}
ASSERT_TRUE(sleeps > 100 && sleeps <= 400);
}
TEST(foundation, list_all_follows_pages) {
Rig r;
r.mock->expect_response(Method::kGet, "/v1/things",
ok("{\"things\":[1,2],\"nextPageToken\":\"t2\"}"));
r.mock->expect_response(Method::kGet, "/v1/things",
ok("{\"things\":[3]}"));
Json all = list_all(*r.client, kEp, "/things", "things");
ASSERT_EQ(all.as_array().size(), 3u);
ASSERT_TRUE(r.mock->seen()[1].target.find("pageToken=t2") != std::string::npos);
}
TEST(foundation, access_token_beats_key) {
setenv("GOOGLE_ACCESS_TOKEN", "ya29.token", 1);
setenv("GOOGLE_API_KEY", "AQ.key", 1);
ASSERT_EQ(std::string(Credentials::from_env()->scheme()), "bearer");
unsetenv("GOOGLE_ACCESS_TOKEN");
ASSERT_EQ(std::string(Credentials::from_env()->scheme()), "apikey");
unsetenv("GOOGLE_API_KEY");
}