1package provider
2
3import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "fmt"
9 "io"
10 "net/http"
11 "os"
12 "strings"
13 "time"
14)
15
16const anthropicDefaultBaseURL = "https://api.anthropic.com"
17const anthropicAPIVersion = "2023-06-01"
18
19// Stealth identity used when talking to Anthropic via subscription OAuth.
20// These values mimic the official Claude Code CLI so Anthropic's edge
21// accepts the request; diverging from them causes 429 rate_limit_error
22// or 403 on the very first request.
23const (
24 claudeCodeVersion = "2.1.75"
25 claudeCodeIdentity = "You are Claude Code, Anthropic's official CLI for Claude."
26)
27
28// Claude Code's canonical tool casing. When running under OAuth we must
29// advertise tool names that match this list (case-insensitive lookup),
30// because Anthropic's backend cross-checks them.
31var claudeCodeToolNames = map[string]string{
32 "read": "Read",
33 "write": "Write",
34 "edit": "Edit",
35 "bash": "Bash",
36 "grep": "Grep",
37 "glob": "Glob",
38}
39
40func toClaudeCodeToolName(name string) string {
41 if cc, ok := claudeCodeToolNames[strings.ToLower(name)]; ok {
42 return cc
43 }
44 return name
45}
46
47func fromClaudeCodeToolName(name string, tools []Tool) string {
48 lower := strings.ToLower(name)
49 for _, t := range tools {
50 if strings.ToLower(t.Name) == lower {
51 return t.Name
52 }
53 }
54 return name
55}
56
57// anthropicClient implements Client against the Anthropic Messages API.
58type anthropicClient struct {
59 apiKey string
60 baseURL string
61 oauthTok string // when non-empty, send Bearer auth instead of x-api-key
62 http *http.Client
63}
64
65// NewAnthropic creates an Anthropic client using an API key. baseURL may be empty.
66func NewAnthropic(apiKey, baseURL string) Client {
67 if baseURL == "" {
68 baseURL = anthropicDefaultBaseURL
69 }
70 return &anthropicClient{
71 apiKey: apiKey,
72 baseURL: strings.TrimRight(baseURL, "/"),
73 http: &http.Client{Timeout: 0},
74 }
75}
76
77// NewAnthropicOAuth creates an Anthropic client using a subscription OAuth access token.
78func NewAnthropicOAuth(accessToken, baseURL string) Client {
79 if baseURL == "" {
80 baseURL = anthropicDefaultBaseURL
81 }
82 return &anthropicClient{
83 oauthTok: accessToken,
84 baseURL: strings.TrimRight(baseURL, "/"),
85 http: &http.Client{Timeout: 0},
86 }
87}
88
89func (c *anthropicClient) Name() string { return "anthropic" }
90
91// ---- wire types ----
92
93type anthTextBlock struct {
94 Type string `json:"type"` // "text"
95 Text string `json:"text"`
96 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
97}
98
99type anthImageSource struct {
100 Type string `json:"type"` // "base64"
101 MediaType string `json:"media_type"`
102 Data string `json:"data"`
103}
104
105type anthImageBlock struct {
106 Type string `json:"type"` // "image"
107 Source anthImageSource `json:"source"`
108 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
109}
110
111type anthToolUseBlock struct {
112 Type string `json:"type"` // "tool_use"
113 ID string `json:"id"`
114 Name string `json:"name"`
115 Input json.RawMessage `json:"input"`
116 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
117}
118
119type anthToolResultBlock struct {
120 Type string `json:"type"` // "tool_result"
121 ToolUseID string `json:"tool_use_id"`
122 Content json.RawMessage `json:"content"` // string or array of blocks
123 IsError bool `json:"is_error,omitempty"`
124 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
125}
126
127type anthCacheCtrl struct {
128 Type string `json:"type"` // "ephemeral"
129 TTL string `json:"ttl,omitempty"`
130}
131
132type anthMessage struct {
133 Role string `json:"role"`
134 Content []interface{} `json:"content"`
135}
136
137type anthSystemBlock struct {
138 Type string `json:"type"` // "text"
139 Text string `json:"text"`
140 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
141}
142
143type anthTool struct {
144 Name string `json:"name"`
145 Description string `json:"description,omitempty"`
146 InputSchema json.RawMessage `json:"input_schema"`
147 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
148}
149
150type anthThinking struct {
151 Type string `json:"type"` // "enabled"
152 BudgetTokens int `json:"budget_tokens"`
153}
154
155type anthRequest struct {
156 Model string `json:"model"`
157 MaxTokens int `json:"max_tokens"`
158 System []anthSystemBlock `json:"system,omitempty"`
159 Messages []anthMessage `json:"messages"`
160 Tools []anthTool `json:"tools,omitempty"`
161 Temperature *float32 `json:"temperature,omitempty"`
162 Thinking *anthThinking `json:"thinking,omitempty"`
163 Stream bool `json:"stream"`
164}
165
166// ---- request building ----
167
168func (c *anthropicClient) buildRequest(req Request) (*anthRequest, error) {
169 m, err := FindModel("anthropic", req.Model)
170 if err != nil {
171 return nil, err
172 }
173 maxTok := req.MaxTokens
174 if maxTok <= 0 {
175 maxTok = m.MaxOutput
176 }
177
178 out := &anthRequest{
179 Model: req.Model,
180 MaxTokens: maxTok,
181 Temperature: req.Temperature,
182 Stream: true,
183 }
184
185 // System prompt assembly differs between api-key and OAuth modes.
186 // OAuth requests MUST begin with the Claude Code identity line or
187 // Anthropic rejects them (429 rate_limit_error with zero tokens used).
188 //
189 // Cache budget: anthropic caps cache_control to 4 breakpoints per
190 // request. We spend them on:
191 // 1. claude-code identity (OAuth only; stable forever)
192 // 2. user system prompt (changes per-session at most)
193 // 3. last tool definition (tools change rarely)
194 // 4. last message block (advances every turn)
195 //
196 // The identity line gets its OWN cache_control so the prefix
197 // [identity] is cacheable independently of the user system
198 // prompt. Without that, the cache prefix starts after block 2
199 // and any drift in the user prompt (e.g. the Current date
200 // line flipping at midnight) invalidates everything, including
201 // the 17 identity tokens we have to re-send every request
202 // forever.
203 if c.oauthTok != "" {
204 out.System = []anthSystemBlock{{
205 Type: "text",
206 Text: claudeCodeIdentity,
207 CacheControl: &anthCacheCtrl{Type: "ephemeral"},
208 }}
209 if req.System != "" {
210 out.System = append(out.System, anthSystemBlock{
211 Type: "text",
212 Text: req.System,
213 CacheControl: &anthCacheCtrl{Type: "ephemeral"},
214 })
215 }
216 } else if req.System != "" {
217 out.System = []anthSystemBlock{{
218 Type: "text",
219 Text: req.System,
220 CacheControl: &anthCacheCtrl{Type: "ephemeral"},
221 }}
222 }
223
224 if req.Reasoning != "" && m.Reasoning {
225 budget := anthropicReasoningBudget(req.Reasoning)
226 if budget > 0 {
227 out.Thinking = &anthThinking{Type: "enabled", BudgetTokens: budget}
228 // Reasoning requires max_tokens > budget.
229 if out.MaxTokens <= budget {
230 out.MaxTokens = budget + 4096
231 }
232 }
233 }
234
235 for _, t := range req.Tools {
236 name := t.Name
237 if c.oauthTok != "" {
238 name = toClaudeCodeToolName(name)
239 }
240 out.Tools = append(out.Tools, anthTool{
241 Name: name,
242 Description: t.Description,
243 InputSchema: t.Schema,
244 })
245 }
246 // Cache the last tool definition (applies cache breakpoint to the whole tools array).
247 if n := len(out.Tools); n > 0 {
248 out.Tools[n-1].CacheControl = &anthCacheCtrl{Type: "ephemeral"}
249 }
250
251 // Convert messages. Anthropic's wire format has only "user" and
252 // "assistant" roles; tool_result blocks live inside user messages.
253 //
254 // CRITICAL: tool_result blocks go into their OWN new user
255 // message, they are NOT merged into the preceding user message.
256 // Merging would mutate the prior user message's content array
257 // between turn N and turn N+1: turn N caches the prefix ending at
258 // [user: "read sample.ts"], turn N+1 sends
259 // [user: "read sample.ts" + tool_result=...] which is a
260 // different block sequence, busting the cache prefix match.
261 // Anthropic's API happily accepts consecutive user messages, and
262 // emitting them separately keeps each message bit-stable across
263 // turns, so the cache prefix matches for the entire history up
264 // to the newest block.
265 for _, msg := range req.Messages {
266 renameTools := c.oauthTok != ""
267 switch msg.Role {
268 case RoleUser:
269 out.Messages = append(out.Messages, anthMessage{
270 Role: "user",
271 Content: convertAnthContent(msg.Content, renameTools),
272 })
273 case RoleTool:
274 out.Messages = append(out.Messages, anthMessage{
275 Role: "user",
276 Content: convertAnthContent(msg.Content, renameTools),
277 })
278 case RoleAssistant:
279 out.Messages = append(out.Messages, anthMessage{
280 Role: "assistant",
281 Content: convertAnthContent(msg.Content, renameTools),
282 })
283 }
284 }
285
286 // Tag the LAST user message with cache_control. Spends the 4th
287 // breakpoint. For prefixes under ~1024 tokens (Anthropic's
288 // minimum cacheable block size for Opus), no cache is written.
289 tagLastUserCache(out.Messages)
290
291 return out, nil
292}
293
294// tagLastUserCache marks the last block of the most recent user
295// message. One marker; combined with identity + systemPrompt +
296// last-tool, spends Anthropic's 4-breakpoint budget.
297func tagLastUserCache(msgs []anthMessage) {
298 for i := len(msgs) - 1; i >= 0; i-- {
299 if msgs[i].Role == "user" {
300 markLastBlockEphemeral(msgs[i].Content)
301 return
302 }
303 }
304}
305
306// markLastBlockEphemeral sets CacheControl on the last entry in blocks
307// regardless of whether it's a text, image, tool_use, or tool_result.
308// Each block type carries its own CacheControl pointer so we type-
309// switch + reassign the slice element.
310func markLastBlockEphemeral(blocks []interface{}) {
311 if len(blocks) == 0 {
312 return
313 }
314 i := len(blocks) - 1
315 cc := &anthCacheCtrl{Type: "ephemeral"}
316 switch v := blocks[i].(type) {
317 case anthTextBlock:
318 v.CacheControl = cc
319 blocks[i] = v
320 case anthImageBlock:
321 v.CacheControl = cc
322 blocks[i] = v
323 case anthToolUseBlock:
324 v.CacheControl = cc
325 blocks[i] = v
326 case anthToolResultBlock:
327 v.CacheControl = cc
328 blocks[i] = v
329 }
330}
331
332func anthropicReasoningBudget(level string) int {
333 switch strings.ToLower(level) {
334 case "low":
335 return 2048
336 case "medium":
337 return 8192
338 case "high":
339 return 16384
340 default:
341 return 0
342 }
343}
344
345func convertAnthContent(blocks []Content, renameTools bool) []interface{} {
346 out := make([]interface{}, 0, len(blocks))
347 for _, b := range blocks {
348 switch v := b.(type) {
349 case TextBlock:
350 if v.Text == "" {
351 continue
352 }
353 out = append(out, anthTextBlock{Type: "text", Text: v.Text})
354 case ImageBlock:
355 data, mime := anthShrinkImageBytesIfTooBig(v.Data, v.MimeType)
356 out = append(out, anthImageBlock{
357 Type: "image",
358 Source: anthImageSource{
359 Type: "base64",
360 MediaType: mime,
361 Data: base64.StdEncoding.EncodeToString(data),
362 },
363 })
364 case ToolCallBlock:
365 args := v.Arguments
366 if len(args) == 0 {
367 args = json.RawMessage("{}")
368 }
369 name := v.Name
370 if renameTools {
371 name = toClaudeCodeToolName(name)
372 }
373 out = append(out, anthToolUseBlock{
374 Type: "tool_use", ID: v.ID, Name: name, Input: args,
375 })
376 case ToolResultBlock:
377 // Flatten content to a string if all text; else array of blocks.
378 content, _ := anthBuildToolResultContent(v.Content)
379 out = append(out, anthToolResultBlock{
380 Type: "tool_result",
381 ToolUseID: v.CallID,
382 Content: content,
383 IsError: v.IsError,
384 })
385 }
386 }
387 return out
388}
389
390func anthBuildToolResultContent(blocks []Content) (json.RawMessage, error) {
391 onlyText := true
392 var sb strings.Builder
393 for _, b := range blocks {
394 if tb, ok := b.(TextBlock); ok {
395 if sb.Len() > 0 {
396 sb.WriteString("\n")
397 }
398 sb.WriteString(tb.Text)
399 } else {
400 onlyText = false
401 break
402 }
403 }
404 if onlyText {
405 if sb.Len() == 0 {
406 return json.Marshal("")
407 }
408 return json.Marshal(sb.String())
409 }
410 // Array form: text + image blocks.
411 arr := make([]interface{}, 0, len(blocks))
412 for _, b := range blocks {
413 switch v := b.(type) {
414 case TextBlock:
415 arr = append(arr, anthTextBlock{Type: "text", Text: v.Text})
416 case ImageBlock:
417 data, mime := anthShrinkImageBytesIfTooBig(v.Data, v.MimeType)
418 arr = append(arr, anthImageBlock{
419 Type: "image",
420 Source: anthImageSource{
421 Type: "base64",
422 MediaType: mime,
423 Data: base64.StdEncoding.EncodeToString(data),
424 },
425 })
426 }
427 }
428 return json.Marshal(arr)
429}
430
431// ---- streaming ----
432
433func (c *anthropicClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
434 wire, err := c.buildRequest(req)
435 if err != nil {
436 return nil, err
437 }
438 body, err := json.Marshal(wire)
439 if err != nil {
440 return nil, err
441 }
442
443 // Optional debug dump: when $ZOT_DEBUG_ANTHROPIC is a file path
444 // we append every outgoing request body to it, one JSON object
445 // per line. Useful for diffing turn N vs turn N+1 to understand
446 // why the cache prefix isn't matching.
447 if dump := os.Getenv("ZOT_DEBUG_ANTHROPIC"); dump != "" {
448 if f, derr := os.OpenFile(dump, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600); derr == nil {
449 _, _ = f.Write(body)
450 _, _ = f.Write([]byte{'\n'})
451 _ = f.Close()
452 }
453 }
454
455 httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/v1/messages", bytes.NewReader(body))
456 if err != nil {
457 return nil, err
458 }
459 httpReq.Header.Set("content-type", "application/json")
460 httpReq.Header.Set("anthropic-version", anthropicAPIVersion)
461 if c.oauthTok != "" {
462 // Claude-Code-shaped request: identical headers and values as the
463 // official CLI. Any drift triggers Anthropic's anti-abuse check and
464 // rate-limits (or outright blocks) the request.
465 httpReq.Header.Set("accept", "application/json")
466 httpReq.Header.Set("authorization", "Bearer "+c.oauthTok)
467 httpReq.Header.Set("anthropic-beta", "claude-code-20250219,oauth-2025-04-20,fine-grained-tool-streaming-2025-05-14")
468 httpReq.Header.Set("anthropic-dangerous-direct-browser-access", "true")
469 httpReq.Header.Set("user-agent", "claude-cli/"+claudeCodeVersion)
470 httpReq.Header.Set("x-app", "cli")
471 // Remove x-api-key entirely by NOT setting it.
472 } else {
473 httpReq.Header.Set("accept", "text/event-stream")
474 httpReq.Header.Set("x-api-key", c.apiKey)
475 }
476
477 resp, err := c.http.Do(httpReq)
478 if err != nil {
479 return nil, fmt.Errorf("anthropic: %w", err)
480 }
481 if resp.StatusCode != http.StatusOK {
482 b, _ := io.ReadAll(resp.Body)
483 resp.Body.Close()
484 return nil, fmt.Errorf("anthropic: http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
485 }
486
487 out := make(chan Event, 16)
488 go c.runStream(ctx, resp, req, out)
489 return out, nil
490}
491
492func (c *anthropicClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
493 defer close(out)
494 defer resp.Body.Close()
495
496 model, _ := FindModel("anthropic", req.Model)
497 out <- EventStart{Model: req.Model, Provider: "anthropic"}
498
499 raw := make(chan sseEvent, 16)
500 go readSSE(resp.Body, raw)
501
502 // State for assembling the assistant message. Blocks are indexed
503 // by their `index` field from Anthropic so we can preserve the
504 // interleaved order the model emitted them in (text may come
505 // before OR after tool_use; mixing both happens frequently).
506 type blockEntry struct {
507 kind string // "text" | "tool_use"
508 textBuf strings.Builder
509 toolCall ToolCallBlock
510 toolArgs strings.Builder
511 }
512 var (
513 blocks = map[int]*blockEntry{}
514 blockOrder []int // insertion order of indexes
515 activeIdx = -1
516 usage Usage
517 stop StopReason = StopEnd
518 finalErr error
519 )
520 _ = activeIdx // read-only indicator used for legacy parity
521
522 registerBlock := func(idx int, kind string) *blockEntry {
523 if be, ok := blocks[idx]; ok {
524 return be
525 }
526 be := &blockEntry{kind: kind}
527 blocks[idx] = be
528 blockOrder = append(blockOrder, idx)
529 return be
530 }
531
532 assembleMsg := func() Message {
533 content := []Content{}
534 for _, idx := range blockOrder {
535 be := blocks[idx]
536 switch be.kind {
537 case "text":
538 if be.textBuf.Len() > 0 {
539 content = append(content, TextBlock{Text: be.textBuf.String()})
540 }
541 case "tool_use":
542 tc := be.toolCall
543 args := be.toolArgs.String()
544 if args == "" {
545 args = "{}"
546 }
547 tc.Arguments = json.RawMessage(args)
548 content = append(content, tc)
549 }
550 }
551 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
552 }
553
554 sendDone := func() {
555 usage.CostUSD = ComputeCost(model, usage)
556 out <- EventUsage{Usage: usage}
557 out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
558 }
559
560 for {
561 select {
562 case <-ctx.Done():
563 stop = StopAborted
564 finalErr = ctx.Err()
565 sendDone()
566 return
567 case ev, ok := <-raw:
568 if !ok {
569 sendDone()
570 return
571 }
572 // Parse event payload based on event: type.
573 var payload map[string]json.RawMessage
574 if err := json.Unmarshal([]byte(ev.Data), &payload); err != nil {
575 continue
576 }
577 switch ev.Event {
578 case "content_block_start":
579 var idx int
580 if b, ok := payload["index"]; ok {
581 _ = json.Unmarshal(b, &idx)
582 }
583 var block struct {
584 Type string `json:"type"`
585 ID string `json:"id"`
586 Name string `json:"name"`
587 Text string `json:"text"`
588 Input json.RawMessage `json:"input"`
589 }
590 if b, ok := payload["content_block"]; ok {
591 _ = json.Unmarshal(b, &block)
592 }
593 activeIdx = idx
594 switch block.Type {
595 case "tool_use":
596 name := block.Name
597 if c.oauthTok != "" {
598 name = fromClaudeCodeToolName(name, req.Tools)
599 }
600 be := registerBlock(idx, "tool_use")
601 be.toolCall = ToolCallBlock{ID: block.ID, Name: name}
602 out <- EventToolStart{ID: block.ID, Name: name}
603 case "text":
604 registerBlock(idx, "text")
605 case "thinking":
606 // not surfaced
607 }
608 case "content_block_delta":
609 var idx int
610 if b, ok := payload["index"]; ok {
611 _ = json.Unmarshal(b, &idx)
612 }
613 var d struct {
614 Type string `json:"type"`
615 Text string `json:"text"`
616 PartialJSON string `json:"partial_json"`
617 Thinking string `json:"thinking"`
618 }
619 if b, ok := payload["delta"]; ok {
620 _ = json.Unmarshal(b, &d)
621 }
622 switch d.Type {
623 case "text_delta":
624 if be, ok := blocks[idx]; ok && be.kind == "text" {
625 be.textBuf.WriteString(d.Text)
626 }
627 out <- EventTextDelta{Delta: d.Text}
628 case "input_json_delta":
629 if be, ok := blocks[idx]; ok && be.kind == "tool_use" {
630 be.toolArgs.WriteString(d.PartialJSON)
631 out <- EventToolArgs{ID: be.toolCall.ID, Delta: d.PartialJSON}
632 }
633 case "thinking_delta":
634 // Not surfaced in v1.
635 }
636 case "content_block_stop":
637 var idx int
638 if b, ok := payload["index"]; ok {
639 _ = json.Unmarshal(b, &idx)
640 }
641 if be, ok := blocks[idx]; ok && be.kind == "tool_use" {
642 out <- EventToolEnd{ID: be.toolCall.ID}
643 }
644 activeIdx = -1
645 case "message_start":
646 var m struct {
647 Message struct {
648 Usage struct {
649 InputTokens int `json:"input_tokens"`
650 OutputTokens int `json:"output_tokens"`
651 CacheReadInputTokens int `json:"cache_read_input_tokens"`
652 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
653 } `json:"usage"`
654 } `json:"message"`
655 }
656 _ = json.Unmarshal([]byte(ev.Data), &m)
657 // Anthropic sends cumulative values on message_start and
658 // again on message_delta (refreshed), so assign, don't
659 // accumulate. Accumulating doubles cache_creation_input
660 // which can be 50-70% of cost.
661 usage.InputTokens = m.Message.Usage.InputTokens
662 usage.OutputTokens = m.Message.Usage.OutputTokens
663 usage.CacheReadTokens = m.Message.Usage.CacheReadInputTokens
664 usage.CacheWriteTokens = m.Message.Usage.CacheCreationInputTokens
665 case "message_delta":
666 var m struct {
667 Delta struct {
668 StopReason string `json:"stop_reason"`
669 } `json:"delta"`
670 Usage struct {
671 InputTokens int `json:"input_tokens"`
672 OutputTokens int `json:"output_tokens"`
673 CacheReadInputTokens int `json:"cache_read_input_tokens"`
674 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
675 } `json:"usage"`
676 }
677 _ = json.Unmarshal([]byte(ev.Data), &m)
678 // Refresh usage from the latest cumulative totals
679 // Anthropic provides. Only apply non-zero fields in case
680 // a given delta only carries output tokens.
681 if m.Usage.InputTokens > 0 {
682 usage.InputTokens = m.Usage.InputTokens
683 }
684 if m.Usage.OutputTokens > 0 {
685 usage.OutputTokens = m.Usage.OutputTokens
686 }
687 if m.Usage.CacheReadInputTokens > 0 {
688 usage.CacheReadTokens = m.Usage.CacheReadInputTokens
689 }
690 if m.Usage.CacheCreationInputTokens > 0 {
691 usage.CacheWriteTokens = m.Usage.CacheCreationInputTokens
692 }
693 switch m.Delta.StopReason {
694 case "end_turn", "stop_sequence":
695 stop = StopEnd
696 case "max_tokens":
697 stop = StopLength
698 case "tool_use":
699 stop = StopToolUse
700 }
701 case "message_stop":
702 sendDone()
703 return
704 case "error":
705 var e struct {
706 Error struct {
707 Type string `json:"type"`
708 Message string `json:"message"`
709 } `json:"error"`
710 }
711 _ = json.Unmarshal([]byte(ev.Data), &e)
712 stop = StopError
713 finalErr = fmt.Errorf("anthropic %s: %s", e.Error.Type, e.Error.Message)
714 sendDone()
715 return
716 }
717 _ = activeIdx
718 }
719 }
720}