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