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