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 // name overrides the default "anthropic" identity. Anthropic-Messages-
65 // compatible third-party endpoints (kimi-coding, fireworks, minimax,
66 // vercel-ai-gateway, etc.) set this so cost lookup / logging / image-
67 // stripping logic can route on a stable provider id.
68 name string
69
70 // headers carries extra request headers (e.g. Kimi Code's X-Msh-*).
71 headers map[string]string
72}
73
74// NewAnthropic creates an Anthropic client using an API key. baseURL may be empty.
75func NewAnthropic(apiKey, baseURL string) Client {
76 if baseURL == "" {
77 baseURL = anthropicDefaultBaseURL
78 }
79 return &anthropicClient{
80 apiKey: apiKey,
81 baseURL: strings.TrimRight(baseURL, "/"),
82 http: &http.Client{Timeout: 0},
83 }
84}
85
86// NewAnthropicOAuth creates an Anthropic client using a subscription OAuth access token.
87func NewAnthropicOAuth(accessToken, baseURL string) Client {
88 if baseURL == "" {
89 baseURL = anthropicDefaultBaseURL
90 }
91 return &anthropicClient{
92 oauthTok: accessToken,
93 baseURL: strings.TrimRight(baseURL, "/"),
94 http: &http.Client{Timeout: 0},
95 }
96}
97
98func (c *anthropicClient) Name() string {
99 if c.name != "" {
100 return c.name
101 }
102 return "anthropic"
103}
104
105// ---- wire types ----
106
107type anthTextBlock struct {
108 Type string `json:"type"` // "text"
109 Text string `json:"text"`
110 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
111}
112
113type anthImageSource struct {
114 Type string `json:"type"` // "base64"
115 MediaType string `json:"media_type"`
116 Data string `json:"data"`
117}
118
119type anthImageBlock struct {
120 Type string `json:"type"` // "image"
121 Source anthImageSource `json:"source"`
122 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
123}
124
125type anthToolUseBlock struct {
126 Type string `json:"type"` // "tool_use"
127 ID string `json:"id"`
128 Name string `json:"name"`
129 Input json.RawMessage `json:"input"`
130 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
131}
132
133type anthToolResultBlock struct {
134 Type string `json:"type"` // "tool_result"
135 ToolUseID string `json:"tool_use_id"`
136 Content json.RawMessage `json:"content"` // string or array of blocks
137 IsError bool `json:"is_error,omitempty"`
138 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
139}
140
141type anthCacheCtrl struct {
142 Type string `json:"type"` // "ephemeral"
143 TTL string `json:"ttl,omitempty"`
144}
145
146type anthMessage struct {
147 Role string `json:"role"`
148 Content []interface{} `json:"content"`
149}
150
151type anthSystemBlock struct {
152 Type string `json:"type"` // "text"
153 Text string `json:"text"`
154 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
155}
156
157type anthTool struct {
158 Name string `json:"name"`
159 Description string `json:"description,omitempty"`
160 InputSchema json.RawMessage `json:"input_schema"`
161 CacheControl *anthCacheCtrl `json:"cache_control,omitempty"`
162}
163
164type anthThinking struct {
165 // Type is "enabled" for budget-based thinking (Opus 4.6 and
166 // earlier) or "adaptive" for adaptive-thinking models (Opus 4.7+).
167 Type string `json:"type"`
168 // BudgetTokens is only sent for Type=="enabled". Adaptive models
169 // reject it (400), so it is omitted for them.
170 BudgetTokens int `json:"budget_tokens,omitempty"`
171}
172
173// anthOutputConfig carries the effort knob used by adaptive-thinking
174// models to control reasoning depth ("low"|"medium"|"high"|"xhigh").
175type anthOutputConfig struct {
176 Effort string `json:"effort,omitempty"`
177}
178
179type anthRequest struct {
180 Model string `json:"model"`
181 MaxTokens int `json:"max_tokens"`
182 System []anthSystemBlock `json:"system,omitempty"`
183 Messages []anthMessage `json:"messages"`
184 Tools []anthTool `json:"tools,omitempty"`
185 Temperature *float32 `json:"temperature,omitempty"`
186 Thinking *anthThinking `json:"thinking,omitempty"`
187 OutputConfig *anthOutputConfig `json:"output_config,omitempty"`
188 Stream bool `json:"stream"`
189}
190
191// usesAdaptiveThinking reports whether a model only supports the
192// adaptive thinking mode (Opus 4.7 and later, including Opus 5). These models reject
193// explicit thinking budgets and non-default sampling parameters. The
194// catalog flag is authoritative; the id-substring fallback catches
195// the same family when reached through an Anthropic-Messages-
196// compatible proxy whose catalog row predates the flag.
197func usesAdaptiveThinking(m Model) bool {
198 if m.AdaptiveThinking || m.AdaptiveThinkingCompat {
199 return true
200 }
201 id := strings.ToLower(m.ID)
202 for _, marker := range []string{"opus-4-7", "opus-4.7", "opus-4-8", "opus-4.8", "opus-5", "opus.5", "sonnet-5", "fable-5"} {
203 if strings.Contains(id, marker) {
204 return true
205 }
206 }
207 return false
208}
209
210// ---- request building ----
211
212func (c *anthropicClient) buildRequest(req Request) (*anthRequest, error) {
213 // Look up under the client's actual provider id, which may be "anthropic"
214 // (default) or a third party that speaks the Anthropic Messages API
215 // (kimi, fireworks, minimax, vercel-ai-gateway, ...). Falling back to a
216 // provider-agnostic lookup keeps things working for catalog-less
217 // configurations (e.g. user passes --model on an obscure third party).
218 m, err := FindModel(c.Name(), req.Model)
219 if err != nil {
220 if m2, err2 := FindModel("", req.Model); err2 == nil {
221 m = m2
222 err = nil
223 }
224 }
225 if err != nil {
226 return nil, err
227 }
228 maxTok := req.MaxTokens
229 if maxTok <= 0 {
230 maxTok = m.MaxOutput
231 }
232
233 reasoning := ClampReasoningForModel(m, req.Reasoning)
234 adaptive := usesAdaptiveThinking(m)
235 adaptiveEffort := adaptive && !m.AdaptiveThinkingCompat
236
237 out := &anthRequest{
238 Model: req.Model,
239 MaxTokens: maxTok,
240 Stream: true,
241 }
242 // Anthropic's adaptive-thinking models reject non-default sampling
243 // params. Compatible implementations may use the adaptive thinking type
244 // while continuing to support temperature.
245 if !adaptiveEffort {
246 out.Temperature = req.Temperature
247 }
248
249 system := req.SystemPrompt()
250
251 // System prompt assembly differs between api-key and OAuth modes.
252 // OAuth requests MUST begin with the Claude Code identity line or
253 // Anthropic rejects them (429 rate_limit_error with zero tokens used).
254 //
255 // Cache budget: anthropic caps cache_control to 4 breakpoints per
256 // request. We spend them on:
257 // 1. claude-code identity (OAuth only; stable forever)
258 // 2. user system prompt (changes per-session at most)
259 // 3. last tool definition (tools change rarely)
260 // 4. last message block (advances every turn)
261 //
262 // The identity line gets its OWN cache_control so the prefix
263 // [identity] is cacheable independently of the user system
264 // prompt. Without that, the cache prefix starts after block 2
265 // and any drift in the user prompt (e.g. the Current date
266 // line flipping at midnight) invalidates everything, including
267 // the 17 identity tokens we have to re-send every request
268 // forever.
269 if c.oauthTok != "" {
270 out.System = []anthSystemBlock{{
271 Type: "text",
272 Text: claudeCodeIdentity,
273 CacheControl: &anthCacheCtrl{Type: "ephemeral"},
274 }}
275 if system != "" {
276 out.System = append(out.System, anthSystemBlock{
277 Type: "text",
278 Text: system,
279 CacheControl: &anthCacheCtrl{Type: "ephemeral"},
280 })
281 }
282 } else if system != "" {
283 out.System = []anthSystemBlock{{
284 Type: "text",
285 Text: system,
286 CacheControl: &anthCacheCtrl{Type: "ephemeral"},
287 }}
288 }
289
290 if reasoning != "" && m.Reasoning {
291 if adaptive {
292 // Adaptive-thinking models decide when and how much to think and
293 // reject explicit budgets. Anthropic models also accept the
294 // output_config.effort extension; compatible implementations may not.
295 out.Thinking = &anthThinking{Type: "adaptive"}
296 if adaptiveEffort {
297 if effort := AnthropicAdaptiveEffort(reasoning); effort != "" {
298 out.OutputConfig = &anthOutputConfig{Effort: effort}
299 }
300 }
301 } else {
302 budget := anthropicReasoningBudget(reasoning)
303 if budget > 0 {
304 // Reasoning requires max_tokens > budget. Keep at least a small
305 // answer budget while respecting the model's advertised output cap.
306 const minAnswerTokens = 1024
307 if m.MaxOutput > minAnswerTokens && budget >= m.MaxOutput {
308 budget = m.MaxOutput - minAnswerTokens
309 }
310 out.Thinking = &anthThinking{Type: "enabled", BudgetTokens: budget}
311 if out.MaxTokens <= budget {
312 out.MaxTokens = budget + minAnswerTokens
313 if m.MaxOutput > 0 && out.MaxTokens > m.MaxOutput {
314 out.MaxTokens = m.MaxOutput
315 }
316 }
317 }
318 }
319 }
320
321 for _, t := range activeToolDefinitions(req.Tools, req.Messages) {
322 name := t.Name
323 if c.oauthTok != "" {
324 name = toClaudeCodeToolName(name)
325 }
326 out.Tools = append(out.Tools, anthTool{
327 Name: name,
328 Description: t.Description,
329 InputSchema: t.Schema,
330 })
331 }
332 // Cache the last tool definition (applies cache breakpoint to the whole tools array).
333 if n := len(out.Tools); n > 0 {
334 out.Tools[n-1].CacheControl = &anthCacheCtrl{Type: "ephemeral"}
335 }
336
337 // Convert messages. Anthropic's wire format has only "user" and
338 // "assistant" roles; tool_result blocks live inside user messages.
339 // Some image-capable providers (for example Gemini image generation)
340 // can emit assistant image blocks. Anthropic only accepts image blocks
341 // in user messages, so strip assistant-side images when switching
342 // providers mid-session. The saved-path TextBlock emitted beside the
343 // image keeps the artifact reachable in chat.
344 //
345 // CRITICAL: tool_result blocks go into their OWN new user
346 // message, they are NOT merged into the preceding user message.
347 // Merging would mutate the prior user message's content array
348 // between turn N and turn N+1: turn N caches the prefix ending at
349 // [user: "read sample.ts"], turn N+1 sends
350 // [user: "read sample.ts" + tool_result=...] which is a
351 // different block sequence, busting the cache prefix match.
352 // Anthropic's API happily accepts consecutive user messages, and
353 // emitting them separately keeps each message bit-stable across
354 // turns, so the cache prefix matches for the entire history up
355 // to the newest block.
356 req.Messages = RepairOrphanedToolResults(req.Messages)
357 for _, msg := range req.Messages {
358 renameTools := c.oauthTok != ""
359 switch msg.Role {
360 case RoleUser:
361 out.Messages = append(out.Messages, anthMessage{
362 Role: "user",
363 Content: convertAnthContent(msg.Content, renameTools),
364 })
365 case RoleTool:
366 out.Messages = append(out.Messages, anthMessage{
367 Role: "user",
368 Content: convertAnthContent(msg.Content, renameTools),
369 })
370 case RoleAssistant:
371 out.Messages = append(out.Messages, anthMessage{
372 Role: "assistant",
373 Content: convertAnthContent(filterAnthAssistantContent(msg.Content), renameTools),
374 })
375 }
376 }
377
378 // Tag the LAST user message with cache_control. Spends the 4th
379 // breakpoint. For prefixes under ~1024 tokens (Anthropic's
380 // minimum cacheable block size for Opus), no cache is written.
381 tagLastUserCache(out.Messages)
382
383 return out, nil
384}
385
386// tagLastUserCache marks the last block of the most recent user
387// message. One marker; combined with identity + systemPrompt +
388// last-tool, spends Anthropic's 4-breakpoint budget.
389func tagLastUserCache(msgs []anthMessage) {
390 for i := len(msgs) - 1; i >= 0; i-- {
391 if msgs[i].Role == "user" {
392 markLastBlockEphemeral(msgs[i].Content)
393 return
394 }
395 }
396}
397
398// markLastBlockEphemeral sets CacheControl on the last entry in blocks
399// regardless of whether it's a text, image, tool_use, or tool_result.
400// Each block type carries its own CacheControl pointer so we type-
401// switch + reassign the slice element.
402func markLastBlockEphemeral(blocks []interface{}) {
403 if len(blocks) == 0 {
404 return
405 }
406 i := len(blocks) - 1
407 cc := &anthCacheCtrl{Type: "ephemeral"}
408 switch v := blocks[i].(type) {
409 case anthTextBlock:
410 v.CacheControl = cc
411 blocks[i] = v
412 case anthImageBlock:
413 v.CacheControl = cc
414 blocks[i] = v
415 case anthToolUseBlock:
416 v.CacheControl = cc
417 blocks[i] = v
418 case anthToolResultBlock:
419 v.CacheControl = cc
420 blocks[i] = v
421 }
422}
423
424func anthropicReasoningBudget(level string) int {
425 return ReasoningBudget(level)
426}
427
428func filterAnthAssistantContent(blocks []Content) []Content {
429 filtered := make([]Content, 0, len(blocks))
430 for _, b := range blocks {
431 if _, ok := b.(ImageBlock); ok {
432 continue
433 }
434 filtered = append(filtered, b)
435 }
436 return filtered
437}
438
439func convertAnthContent(blocks []Content, renameTools bool) []interface{} {
440 out := make([]interface{}, 0, len(blocks))
441 for _, b := range blocks {
442 switch v := b.(type) {
443 case TextBlock:
444 if v.Text == "" {
445 continue
446 }
447 out = append(out, anthTextBlock{Type: "text", Text: v.Text})
448 case ImageBlock:
449 data, mime := anthShrinkImageBytesIfTooBig(v.Data, v.MimeType)
450 out = append(out, anthImageBlock{
451 Type: "image",
452 Source: anthImageSource{
453 Type: "base64",
454 MediaType: mime,
455 Data: base64.StdEncoding.EncodeToString(data),
456 },
457 })
458 case ToolCallBlock:
459 args := v.Arguments
460 if len(args) == 0 || !json.Valid(args) {
461 args = json.RawMessage("{}")
462 }
463 name := v.Name
464 if renameTools {
465 name = toClaudeCodeToolName(name)
466 }
467 out = append(out, anthToolUseBlock{
468 Type: "tool_use", ID: v.ID, Name: name, Input: args,
469 })
470 case ToolResultBlock:
471 // Flatten content to a string if all text; else array of blocks.
472 content, _ := anthBuildToolResultContent(v.Content)
473 out = append(out, anthToolResultBlock{
474 Type: "tool_result",
475 ToolUseID: v.CallID,
476 Content: content,
477 IsError: v.IsError,
478 })
479 }
480 }
481 return out
482}
483
484func anthBuildToolResultContent(blocks []Content) (json.RawMessage, error) {
485 onlyText := true
486 var sb strings.Builder
487 for _, b := range blocks {
488 if tb, ok := b.(TextBlock); ok {
489 if sb.Len() > 0 {
490 sb.WriteString("\n")
491 }
492 sb.WriteString(tb.Text)
493 } else {
494 onlyText = false
495 break
496 }
497 }
498 if onlyText {
499 if sb.Len() == 0 {
500 return json.Marshal("")
501 }
502 return json.Marshal(sb.String())
503 }
504 // Array form: text + image blocks.
505 arr := make([]interface{}, 0, len(blocks))
506 for _, b := range blocks {
507 switch v := b.(type) {
508 case TextBlock:
509 arr = append(arr, anthTextBlock{Type: "text", Text: v.Text})
510 case ImageBlock:
511 data, mime := anthShrinkImageBytesIfTooBig(v.Data, v.MimeType)
512 arr = append(arr, anthImageBlock{
513 Type: "image",
514 Source: anthImageSource{
515 Type: "base64",
516 MediaType: mime,
517 Data: base64.StdEncoding.EncodeToString(data),
518 },
519 })
520 }
521 }
522 return json.Marshal(arr)
523}
524
525// ---- streaming ----
526
527func (c *anthropicClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
528 if err := ValidateFastMode(c.Name(), req.FastMode); err != nil {
529 return nil, err
530 }
531 wire, err := c.buildRequest(req)
532 if err != nil {
533 return nil, err
534 }
535 body, err := json.Marshal(wire)
536 if err != nil {
537 return nil, err
538 }
539
540 // Optional debug dump: when $ZUT_DEBUG_ANTHROPIC is a file path
541 // we append every outgoing request body to it, one JSON object
542 // per line. Useful for diffing turn N vs turn N+1 to understand
543 // why the cache prefix isn't matching.
544 if dump := os.Getenv("ZUT_DEBUG_ANTHROPIC"); dump != "" {
545 if f, derr := os.OpenFile(dump, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600); derr == nil {
546 _, _ = f.Write(body)
547 _, _ = f.Write([]byte{'\n'})
548 _ = f.Close()
549 }
550 }
551
552 newReq := func() (*http.Request, error) {
553 httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/v1/messages", bytes.NewReader(body))
554 if err != nil {
555 return nil, err
556 }
557 httpReq.Header.Set("content-type", "application/json")
558 httpReq.Header.Set("anthropic-version", anthropicAPIVersion)
559 if c.oauthTok != "" {
560 // Claude-Code-shaped request: identical headers and values as the
561 // official CLI. Any drift triggers Anthropic's anti-abuse check and
562 // rate-limits (or outright blocks) the request.
563 httpReq.Header.Set("accept", "application/json")
564 httpReq.Header.Set("authorization", "Bearer "+c.oauthTok)
565 httpReq.Header.Set("anthropic-beta", "claude-code-20250219,oauth-2025-04-20,fine-grained-tool-streaming-2025-05-14")
566 httpReq.Header.Set("anthropic-dangerous-direct-browser-access", "true")
567 httpReq.Header.Set("user-agent", "claude-cli/"+claudeCodeVersion)
568 httpReq.Header.Set("x-app", "cli")
569 // Remove x-api-key entirely by NOT setting it.
570 } else {
571 httpReq.Header.Set("accept", "text/event-stream")
572 httpReq.Header.Set("x-api-key", c.apiKey)
573 }
574 // Extra headers (set by anthropic-messages-compatible third parties
575 // — kimi-coding's X-Msh-*, copilot's Editor-Plugin-Version, etc.).
576 // Applied last so callers can override defaults if they really need to.
577 for k, v := range c.headers {
578 httpReq.Header.Set(k, v)
579 }
580 return httpReq, nil
581 }
582
583 resp, err := doStreamWithRetry(ctx, c.http, newReq, req.Lifecycle)
584 if err != nil {
585 return nil, fmt.Errorf("anthropic: %w", err)
586 }
587 if resp.StatusCode != http.StatusOK {
588 b, _ := io.ReadAll(resp.Body)
589 resp.Body.Close()
590 return nil, fmt.Errorf("anthropic: http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
591 }
592
593 out := make(chan Event, 16)
594 go c.runStream(ctx, resp, req, out)
595 return out, nil
596}
597
598func (c *anthropicClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
599 defer close(out)
600 defer resp.Body.Close()
601
602 // Same lookup-by-actual-provider-id pattern as buildRequest, so cost
603 // calculation works for third-party Anthropic-Messages endpoints.
604 model, _ := FindModel(c.Name(), req.Model)
605 if model.ID == "" {
606 model, _ = FindModel("", req.Model)
607 }
608 out <- EventStart{Model: req.Model, Provider: c.Name()}
609
610 raw := make(chan sseEvent, 16)
611 go readSSE(resp.Body, raw)
612
613 // State for assembling the assistant message. Blocks are indexed
614 // by their `index` field from Anthropic so we can preserve the
615 // interleaved order the model emitted them in (text may come
616 // before OR after tool_use; mixing both happens frequently).
617 type blockEntry struct {
618 kind string // "text" | "tool_use"
619 textBuf strings.Builder
620 toolCall ToolCallBlock
621 toolArgs strings.Builder
622 }
623 var (
624 blocks = map[int]*blockEntry{}
625 blockOrder []int // insertion order of indexes
626 activeIdx = -1
627 usage Usage
628 stop = StopEnd
629 finalErr error
630 )
631 _ = activeIdx // read-only indicator used for legacy parity
632
633 registerBlock := func(idx int, kind string) *blockEntry {
634 if be, ok := blocks[idx]; ok {
635 return be
636 }
637 be := &blockEntry{kind: kind}
638 blocks[idx] = be
639 blockOrder = append(blockOrder, idx)
640 return be
641 }
642
643 assembleMsg := func() Message {
644 content := []Content{}
645 for _, idx := range blockOrder {
646 be := blocks[idx]
647 switch be.kind {
648 case "text":
649 if be.textBuf.Len() > 0 {
650 content = append(content, TextBlock{Text: be.textBuf.String()})
651 }
652 case "tool_use":
653 tc := be.toolCall
654 args := be.toolArgs.String()
655 if args == "" {
656 args = "{}"
657 }
658 tc.Arguments = json.RawMessage(args)
659 content = append(content, tc)
660 }
661 }
662 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
663 }
664
665 sendDone := func() {
666 usage.CostUSD = ComputeCost(model, usage)
667 out <- EventUsage{Usage: usage}
668 out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
669 }
670
671 for {
672 select {
673 case <-ctx.Done():
674 stop = StopAborted
675 finalErr = ctx.Err()
676 sendDone()
677 return
678 case ev, ok := <-raw:
679 if !ok {
680 sendDone()
681 return
682 }
683 if ev.Err != nil {
684 stop = StopError
685 finalErr = fmt.Errorf("read SSE: %w", ev.Err)
686 sendDone()
687 return
688 }
689 // Parse event payload based on event: type.
690 var payload map[string]json.RawMessage
691 if err := json.Unmarshal([]byte(ev.Data), &payload); err != nil {
692 continue
693 }
694 switch ev.Event {
695 case "content_block_start":
696 var idx int
697 if b, ok := payload["index"]; ok {
698 _ = json.Unmarshal(b, &idx)
699 }
700 var block struct {
701 Type string `json:"type"`
702 ID string `json:"id"`
703 Name string `json:"name"`
704 Text string `json:"text"`
705 Input json.RawMessage `json:"input"`
706 }
707 if b, ok := payload["content_block"]; ok {
708 _ = json.Unmarshal(b, &block)
709 }
710 activeIdx = idx
711 switch block.Type {
712 case "tool_use":
713 name := block.Name
714 if c.oauthTok != "" {
715 name = fromClaudeCodeToolName(name, req.Tools)
716 }
717 be := registerBlock(idx, "tool_use")
718 be.toolCall = ToolCallBlock{ID: block.ID, Name: name}
719 out <- EventToolStart{ID: block.ID, Name: name}
720 case "text":
721 registerBlock(idx, "text")
722 case "thinking":
723 // not surfaced
724 }
725 case "content_block_delta":
726 var idx int
727 if b, ok := payload["index"]; ok {
728 _ = json.Unmarshal(b, &idx)
729 }
730 var d struct {
731 Type string `json:"type"`
732 Text string `json:"text"`
733 PartialJSON string `json:"partial_json"`
734 Thinking string `json:"thinking"`
735 }
736 if b, ok := payload["delta"]; ok {
737 _ = json.Unmarshal(b, &d)
738 }
739 switch d.Type {
740 case "text_delta":
741 if be, ok := blocks[idx]; ok && be.kind == "text" {
742 be.textBuf.WriteString(d.Text)
743 }
744 out <- EventTextDelta{Delta: d.Text}
745 case "input_json_delta":
746 if be, ok := blocks[idx]; ok && be.kind == "tool_use" {
747 be.toolArgs.WriteString(d.PartialJSON)
748 out <- EventToolArgs{ID: be.toolCall.ID, Delta: d.PartialJSON}
749 }
750 case "thinking_delta":
751 // Not surfaced in v1.
752 }
753 case "content_block_stop":
754 var idx int
755 if b, ok := payload["index"]; ok {
756 _ = json.Unmarshal(b, &idx)
757 }
758 if be, ok := blocks[idx]; ok && be.kind == "tool_use" {
759 out <- EventToolEnd{ID: be.toolCall.ID}
760 }
761 activeIdx = -1
762 case "message_start":
763 var m struct {
764 Message struct {
765 Usage struct {
766 InputTokens int `json:"input_tokens"`
767 OutputTokens int `json:"output_tokens"`
768 CacheReadInputTokens int `json:"cache_read_input_tokens"`
769 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
770 } `json:"usage"`
771 } `json:"message"`
772 }
773 _ = json.Unmarshal([]byte(ev.Data), &m)
774 // Anthropic sends cumulative values on message_start and
775 // again on message_delta (refreshed), so assign, don't
776 // accumulate. Accumulating doubles cache_creation_input
777 // which can be 50-70% of cost.
778 usage.InputTokens = m.Message.Usage.InputTokens
779 usage.OutputTokens = m.Message.Usage.OutputTokens
780 usage.CacheReadTokens = m.Message.Usage.CacheReadInputTokens
781 usage.CacheWriteTokens = m.Message.Usage.CacheCreationInputTokens
782 case "message_delta":
783 var m struct {
784 Delta struct {
785 StopReason string `json:"stop_reason"`
786 } `json:"delta"`
787 Usage struct {
788 InputTokens int `json:"input_tokens"`
789 OutputTokens int `json:"output_tokens"`
790 CacheReadInputTokens int `json:"cache_read_input_tokens"`
791 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
792 } `json:"usage"`
793 }
794 _ = json.Unmarshal([]byte(ev.Data), &m)
795 // Refresh usage from the latest cumulative totals
796 // Anthropic provides. Only apply non-zero fields in case
797 // a given delta only carries output tokens.
798 if m.Usage.InputTokens > 0 {
799 usage.InputTokens = m.Usage.InputTokens
800 }
801 if m.Usage.OutputTokens > 0 {
802 usage.OutputTokens = m.Usage.OutputTokens
803 }
804 if m.Usage.CacheReadInputTokens > 0 {
805 usage.CacheReadTokens = m.Usage.CacheReadInputTokens
806 }
807 if m.Usage.CacheCreationInputTokens > 0 {
808 usage.CacheWriteTokens = m.Usage.CacheCreationInputTokens
809 }
810 switch m.Delta.StopReason {
811 case "end_turn", "stop_sequence":
812 stop = StopEnd
813 case "max_tokens":
814 stop = StopLength
815 case "tool_use":
816 stop = StopToolUse
817 }
818 case "message_stop":
819 sendDone()
820 return
821 case "error":
822 var e struct {
823 Error struct {
824 Type string `json:"type"`
825 Message string `json:"message"`
826 } `json:"error"`
827 }
828 _ = json.Unmarshal([]byte(ev.Data), &e)
829 stop = StopError
830 finalErr = fmt.Errorf("anthropic %s: %s", e.Error.Type, e.Error.Message)
831 sendDone()
832 return
833 }
834 _ = activeIdx
835 }
836 }
837}