From e38f673edc7428c0c836c39f40707cb681defb14 Mon Sep 17 00:00:00 2001 From: Claude Sonnet 5 Date: Fri, 3 Jul 2026 09:03:01 +0000 Subject: feat(provider): add native Anthropic Messages API adapter (Phase 2) Adds internal/provider/anthropic, the first genuinely new provider.Provider implementation on top of Phase 1's provider-neutral tool-use loop, alongside (not replacing) the existing Docker/CLI-subprocess ContainerRunner path for the "claude" agent type: - internal/provider/anthropic: translates the neutral ChatRequest/ChatResponse shape to/from Anthropic's Messages API content-block format (system as a top-level field, tool_use/tool_result blocks, no "tool" role -- tool results become user-role messages), with a per-model-prefix pricing table for CostUSD - internal/retry: IsRateLimitError additively extended to recognize Anthropic's rate_limit_error/overloaded_error/529 shapes - internal/config: RunnersConfig.Anthropic/AnthropicEnabled() gate - internal/cli/serve.go, run.go: register runners["anthropic"] as a NativeRunner when [providers.anthropic].api_key is set and enabled -- tracked as a distinct executions.agent="anthropic" budget bucket, separate from the CLI-subprocess "claude" runner even though both bill the same Anthropic account go build/vet/test -race all pass. No live Anthropic API key is available in this environment, so verification is via fake-httptest-server adapter tests (12 cases, incl. multi-turn tool_result round-trip and rate-limit error matching) plus a Pool/NativeRunner routing test proving agent.type: "anthropic" actually reaches the new provider. Live end-to-end verification against the real API is a follow-up once a key is configured. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01V1moSNCJRcP6kykA4tyUSs --- internal/executor/anthropic_routing_test.go | 87 +++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 internal/executor/anthropic_routing_test.go (limited to 'internal/executor') diff --git a/internal/executor/anthropic_routing_test.go b/internal/executor/anthropic_routing_test.go new file mode 100644 index 0000000..8794dd8 --- /dev/null +++ b/internal/executor/anthropic_routing_test.go @@ -0,0 +1,87 @@ +package executor + +import ( + "context" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "sync/atomic" + "testing" + + "github.com/thepeterstone/claudomator/internal/provider/anthropic" +) + +// TestPool_Submit_AnthropicAgentType_RoutesThroughAnthropicProvider is the +// NativeRunner-level confirmation (Phase 2 verification item 5) that a task +// with agent.type: "anthropic" is actually routed through the new +// internal/provider/anthropic.Provider when the pool is wired with an +// "anthropic" runner — exactly how internal/cli/serve.go and +// internal/cli/run.go register it from cfg.Providers["anthropic"] when a +// non-empty APIKey is configured. This exercises the full path: Pool.Submit +// -> execute() -> NativeRunner.Run() -> agentloop.Loop.Run() -> +// anthropic.Provider.Chat() -> HTTP POST to the (fake) Anthropic Messages +// API endpoint. +func TestPool_Submit_AnthropicAgentType_RoutesThroughAnthropicProvider(t *testing.T) { + var calls int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&calls, 1) + if r.URL.Path != "/v1/messages" { + t.Errorf("unexpected path %q", r.URL.Path) + } + if r.Header.Get("x-api-key") != "test-anthropic-key" { + t.Errorf("wrong x-api-key: %q", r.Header.Get("x-api-key")) + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{ + "content": [{"type": "text", "text": "## Summary\ndone"}], + "stop_reason": "end_turn", + "model": "claude-sonnet-5", + "usage": {"input_tokens": 12, "output_tokens": 4} + }`)) + })) + defer srv.Close() + + // Mirrors the exact construction in internal/cli/serve.go's + // cfg.Providers["anthropic"] wiring block: anthropic.New(apiKey, + // endpoint, timeout) wrapped in a NativeRunner registered under the + // "anthropic" runner-map key. + runners := map[string]Runner{ + "anthropic": &NativeRunner{ + Provider: anthropic.New("test-anthropic-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("anthropic-routing-1") + tk.Agent.Type = "anthropic" + tk.Agent.Model = "claude-sonnet-5" + 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 Anthropic server, got %d", got) + } + if result.Execution.Agent != "anthropic" { + t.Errorf("execution.Agent: want %q, got %q", "anthropic", result.Execution.Agent) + } + if result.Execution.TokensIn != 12 || result.Execution.TokensOut != 4 { + t.Errorf("tokens should come from the anthropic provider's usage: got in=%d out=%d", + result.Execution.TokensIn, result.Execution.TokensOut) + } +} -- cgit v1.2.3