From 1f203a7ac0efad15ec3fc0a4c5b335ad7073a52f Mon Sep 17 00:00:00 2001 From: Claude Sonnet 5 Date: Fri, 3 Jul 2026 22:33:22 +0000 Subject: feat(provider): add native Google Gemini API adapter (Phase 4) Adds internal/provider/google, the second native cloud adapter (following internal/provider/anthropic's pattern) on top of Phase 1's provider-neutral tool-use loop, wired to a Docker-sandboxed NativeRunner under agent.type: "google" -- a separate execution path and budget bucket from the existing CLI-subprocess "gemini" ContainerRunner, which is untouched. Wire-format research (the highest-risk part of this adapter): Gemini's multi-turn function-calling shape was resolved by cross-referencing the REST API reference's own generateContent example against the go-genai SDK's struct tags on GitHub -- both agree on functionCall/functionResponse parts keyed by "name" (with an optional "id" for round-tripping ToolCall.ID), with the response fed back inside a "user"-role Content (Gemini has no tool/function role, mirroring Anthropic's lack of one). A separate fetched source (the function-calling guide page) was deliberately discarded as a reference for this shape -- it documents a different, newer "Interactions API" whose call_id/type:"function_result" structure doesn't fit the contents/parts/candidates shape used everywhere else. - internal/provider/google: request/response translation, systemInstruction handling, role mapping (assistant->model, tool-results->user role), per-model-prefix pricing table (2.5 Pro/Flash/Flash-Lite, 2.0, 1.5 tiers) - internal/retry: IsRateLimitError additively extended for RESOURCE_EXHAUSTED - internal/config: RunnersConfig.Google/GoogleEnabled() - internal/cli/serve.go, run.go: runners["google"] construction mirroring the Anthropic wiring exactly (Docker sandbox default) - docs/api-keys-setup.md: Google marked wired-up, budget-bucket/disable/ verify guidance added matching the Anthropic section go build/vet/test -race all pass. No live Gemini API key available in this environment; verified via fake-httptest-server adapter tests (plain text, tool-use round-trip, multi-turn tool-result, rate-limit error matching) plus a Pool/NativeRunner routing test. Live E2E is a follow-up once a key is configured, same as Phase 2's Anthropic adapter. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01V1moSNCJRcP6kykA4tyUSs --- internal/executor/google_routing_test.go | 89 ++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 internal/executor/google_routing_test.go (limited to 'internal/executor') diff --git a/internal/executor/google_routing_test.go b/internal/executor/google_routing_test.go new file mode 100644 index 0000000..9690a4b --- /dev/null +++ b/internal/executor/google_routing_test.go @@ -0,0 +1,89 @@ +package executor + +import ( + "context" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync/atomic" + "testing" + + "github.com/thepeterstone/claudomator/internal/provider/google" +) + +// TestPool_Submit_GoogleAgentType_RoutesThroughGoogleProvider is the +// NativeRunner-level confirmation (Phase 4 verification item 5) that a task +// with agent.type: "google" is actually routed through the new +// internal/provider/google.Provider when the pool is wired with a "google" +// runner — exactly how internal/cli/serve.go and internal/cli/run.go +// register it from cfg.Providers["google"] when a non-empty APIKey is +// configured. This exercises the full path: Pool.Submit -> execute() -> +// NativeRunner.Run() -> agentloop.Loop.Run() -> google.Provider.Chat() -> +// HTTP POST to the (fake) Gemini generateContent API endpoint. Mirrors +// internal/executor/anthropic_routing_test.go. +func TestPool_Submit_GoogleAgentType_RoutesThroughGoogleProvider(t *testing.T) { + var calls int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&calls, 1) + if !strings.Contains(r.URL.Path, ":generateContent") { + t.Errorf("unexpected path %q", r.URL.Path) + } + if r.URL.Query().Get("key") != "test-google-key" { + t.Errorf("wrong key query param: %q", r.URL.Query().Get("key")) + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": [{"text": "## Summary\ndone"}]}, + "finishReason": "STOP" + }], + "usageMetadata": {"promptTokenCount": 12, "candidatesTokenCount": 4, "totalTokenCount": 16} + }`)) + })) + defer srv.Close() + + // Mirrors the exact construction in internal/cli/serve.go's + // cfg.Providers["google"] wiring block: google.New(apiKey, endpoint, + // timeout) wrapped in a NativeRunner registered under the "google" + // runner-map key. + runners := map[string]Runner{ + "google": &NativeRunner{ + Provider: google.New("test-google-key", srv.URL, 0), + Logger: slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})), + LogDir: t.TempDir(), + }, + } + + store := testStore(t) + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + pool := NewPool(2, runners, store, logger) + + tk := makeTask("google-routing-1") + tk.Agent.Type = "google" + tk.Agent.Model = "gemini-2.5-flash" + tk.Agent.SkipPlanning = true + if err := store.CreateTask(tk); err != nil { + t.Fatalf("CreateTask: %v", err) + } + + if err := pool.Submit(context.Background(), tk); err != nil { + t.Fatalf("Submit: %v", err) + } + + result := <-pool.Results() + if result.Err != nil { + t.Fatalf("expected no error, got: %v", result.Err) + } + if got := atomic.LoadInt32(&calls); got != 1 { + t.Fatalf("expected exactly 1 call to the fake Gemini server, got %d", got) + } + if result.Execution.Agent != "google" { + t.Errorf("execution.Agent: want %q, got %q", "google", result.Execution.Agent) + } + if result.Execution.TokensIn != 12 || result.Execution.TokensOut != 4 { + t.Errorf("tokens should come from the google provider's usage: got in=%d out=%d", + result.Execution.TokensIn, result.Execution.TokensOut) + } +} -- cgit v1.2.3