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 if err := ValidateFastMode(c.Name(), req.FastMode); err != nil {
527 return nil, err
528 }
529 wire, err := c.buildRequest(req)
530 if err != nil {
531 return nil, err
532 }
533 body, err := json.Marshal(wire)
534 if err != nil {
535 return nil, err
536 }
537
538 // Optional debug dump: when $ZUT_DEBUG_ANTHROPIC is a file path
539 // we append every outgoing request body to it, one JSON object
540 // per line. Useful for diffing turn N vs turn N+1 to understand
541 // why the cache prefix isn't matching.
542 if dump := os.Getenv("ZUT_DEBUG_ANTHROPIC"); dump != "" {
543 if f, derr := os.OpenFile(dump, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600); derr == nil {
544 _, _ = f.Write(body)
545 _, _ = f.Write([]byte{'\n'})
546 _ = f.Close()
547 }
548 }
549
550 newReq := func() (*http.Request, error) {
551 httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/v1/messages", bytes.NewReader(body))
552 if err != nil {
553 return nil, err
554 }
555 httpReq.Header.Set("content-type", "application/json")
556 httpReq.Header.Set("anthropic-version", anthropicAPIVersion)
557 if c.oauthTok != "" {
558 // Claude-Code-shaped request: identical headers and values as the
559 // official CLI. Any drift triggers Anthropic's anti-abuse check and
560 // rate-limits (or outright blocks) the request.
561 httpReq.Header.Set("accept", "application/json")
562 httpReq.Header.Set("authorization", "Bearer "+c.oauthTok)
563 httpReq.Header.Set("anthropic-beta", "claude-code-20250219,oauth-2025-04-20,fine-grained-tool-streaming-2025-05-14")
564 httpReq.Header.Set("anthropic-dangerous-direct-browser-access", "true")
565 httpReq.Header.Set("user-agent", "claude-cli/"+claudeCodeVersion)
566 httpReq.Header.Set("x-app", "cli")
567 // Remove x-api-key entirely by NOT setting it.
568 } else {
569 httpReq.Header.Set("accept", "text/event-stream")
570 httpReq.Header.Set("x-api-key", c.apiKey)
571 }
572 // Extra headers (set by anthropic-messages-compatible third parties
573 // — kimi-coding's X-Msh-*, copilot's Editor-Plugin-Version, etc.).
574 // Applied last so callers can override defaults if they really need to.
575 for k, v := range c.headers {
576 httpReq.Header.Set(k, v)
577 }
578 return httpReq, nil
579 }
580
581 resp, err := doStreamWithRetry(ctx, c.http, newReq, req.Lifecycle)
582 if err != nil {
583 return nil, fmt.Errorf("anthropic: %w", err)
584 }
585 if resp.StatusCode != http.StatusOK {
586 b, _ := io.ReadAll(resp.Body)
587 resp.Body.Close()
588 return nil, fmt.Errorf("anthropic: http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
589 }
590
591 out := make(chan Event, 16)
592 go c.runStream(ctx, resp, req, out)
593 return out, nil
594}
595
596func (c *anthropicClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
597 defer close(out)
598 defer resp.Body.Close()
599
600 // Same lookup-by-actual-provider-id pattern as buildRequest, so cost
601 // calculation works for third-party Anthropic-Messages endpoints.
602 model, _ := FindModel(c.Name(), req.Model)
603 if model.ID == "" {
604 model, _ = FindModel("", req.Model)
605 }
606 out <- EventStart{Model: req.Model, Provider: c.Name()}
607
608 raw := make(chan sseEvent, 16)
609 go readSSE(resp.Body, raw)
610
611 // State for assembling the assistant message. Blocks are indexed
612 // by their `index` field from Anthropic so we can preserve the
613 // interleaved order the model emitted them in (text may come
614 // before OR after tool_use; mixing both happens frequently).
615 type blockEntry struct {
616 kind string // "text" | "tool_use"
617 textBuf strings.Builder
618 toolCall ToolCallBlock
619 toolArgs strings.Builder
620 }
621 var (
622 blocks = map[int]*blockEntry{}
623 blockOrder []int // insertion order of indexes
624 activeIdx = -1
625 usage Usage
626 stop = StopEnd
627 finalErr error
628 )
629 _ = activeIdx // read-only indicator used for legacy parity
630
631 registerBlock := func(idx int, kind string) *blockEntry {
632 if be, ok := blocks[idx]; ok {
633 return be
634 }
635 be := &blockEntry{kind: kind}
636 blocks[idx] = be
637 blockOrder = append(blockOrder, idx)
638 return be
639 }
640
641 assembleMsg := func() Message {
642 content := []Content{}
643 for _, idx := range blockOrder {
644 be := blocks[idx]
645 switch be.kind {
646 case "text":
647 if be.textBuf.Len() > 0 {
648 content = append(content, TextBlock{Text: be.textBuf.String()})
649 }
650 case "tool_use":
651 tc := be.toolCall
652 args := be.toolArgs.String()
653 if args == "" {
654 args = "{}"
655 }
656 tc.Arguments = json.RawMessage(args)
657 content = append(content, tc)
658 }
659 }
660 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
661 }
662
663 sendDone := func() {
664 usage.CostUSD = ComputeCost(model, usage)
665 out <- EventUsage{Usage: usage}
666 out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
667 }
668
669 for {
670 select {
671 case <-ctx.Done():
672 stop = StopAborted
673 finalErr = ctx.Err()
674 sendDone()
675 return
676 case ev, ok := <-raw:
677 if !ok {
678 sendDone()
679 return
680 }
681 // Parse event payload based on event: type.
682 var payload map[string]json.RawMessage
683 if err := json.Unmarshal([]byte(ev.Data), &payload); err != nil {
684 continue
685 }
686 switch ev.Event {
687 case "content_block_start":
688 var idx int
689 if b, ok := payload["index"]; ok {
690 _ = json.Unmarshal(b, &idx)
691 }
692 var block struct {
693 Type string `json:"type"`
694 ID string `json:"id"`
695 Name string `json:"name"`
696 Text string `json:"text"`
697 Input json.RawMessage `json:"input"`
698 }
699 if b, ok := payload["content_block"]; ok {
700 _ = json.Unmarshal(b, &block)
701 }
702 activeIdx = idx
703 switch block.Type {
704 case "tool_use":
705 name := block.Name
706 if c.oauthTok != "" {
707 name = fromClaudeCodeToolName(name, req.Tools)
708 }
709 be := registerBlock(idx, "tool_use")
710 be.toolCall = ToolCallBlock{ID: block.ID, Name: name}
711 out <- EventToolStart{ID: block.ID, Name: name}
712 case "text":
713 registerBlock(idx, "text")
714 case "thinking":
715 // not surfaced
716 }
717 case "content_block_delta":
718 var idx int
719 if b, ok := payload["index"]; ok {
720 _ = json.Unmarshal(b, &idx)
721 }
722 var d struct {
723 Type string `json:"type"`
724 Text string `json:"text"`
725 PartialJSON string `json:"partial_json"`
726 Thinking string `json:"thinking"`
727 }
728 if b, ok := payload["delta"]; ok {
729 _ = json.Unmarshal(b, &d)
730 }
731 switch d.Type {
732 case "text_delta":
733 if be, ok := blocks[idx]; ok && be.kind == "text" {
734 be.textBuf.WriteString(d.Text)
735 }
736 out <- EventTextDelta{Delta: d.Text}
737 case "input_json_delta":
738 if be, ok := blocks[idx]; ok && be.kind == "tool_use" {
739 be.toolArgs.WriteString(d.PartialJSON)
740 out <- EventToolArgs{ID: be.toolCall.ID, Delta: d.PartialJSON}
741 }
742 case "thinking_delta":
743 // Not surfaced in v1.
744 }
745 case "content_block_stop":
746 var idx int
747 if b, ok := payload["index"]; ok {
748 _ = json.Unmarshal(b, &idx)
749 }
750 if be, ok := blocks[idx]; ok && be.kind == "tool_use" {
751 out <- EventToolEnd{ID: be.toolCall.ID}
752 }
753 activeIdx = -1
754 case "message_start":
755 var m struct {
756 Message struct {
757 Usage struct {
758 InputTokens int `json:"input_tokens"`
759 OutputTokens int `json:"output_tokens"`
760 CacheReadInputTokens int `json:"cache_read_input_tokens"`
761 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
762 } `json:"usage"`
763 } `json:"message"`
764 }
765 _ = json.Unmarshal([]byte(ev.Data), &m)
766 // Anthropic sends cumulative values on message_start and
767 // again on message_delta (refreshed), so assign, don't
768 // accumulate. Accumulating doubles cache_creation_input
769 // which can be 50-70% of cost.
770 usage.InputTokens = m.Message.Usage.InputTokens
771 usage.OutputTokens = m.Message.Usage.OutputTokens
772 usage.CacheReadTokens = m.Message.Usage.CacheReadInputTokens
773 usage.CacheWriteTokens = m.Message.Usage.CacheCreationInputTokens
774 case "message_delta":
775 var m struct {
776 Delta struct {
777 StopReason string `json:"stop_reason"`
778 } `json:"delta"`
779 Usage struct {
780 InputTokens int `json:"input_tokens"`
781 OutputTokens int `json:"output_tokens"`
782 CacheReadInputTokens int `json:"cache_read_input_tokens"`
783 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
784 } `json:"usage"`
785 }
786 _ = json.Unmarshal([]byte(ev.Data), &m)
787 // Refresh usage from the latest cumulative totals
788 // Anthropic provides. Only apply non-zero fields in case
789 // a given delta only carries output tokens.
790 if m.Usage.InputTokens > 0 {
791 usage.InputTokens = m.Usage.InputTokens
792 }
793 if m.Usage.OutputTokens > 0 {
794 usage.OutputTokens = m.Usage.OutputTokens
795 }
796 if m.Usage.CacheReadInputTokens > 0 {
797 usage.CacheReadTokens = m.Usage.CacheReadInputTokens
798 }
799 if m.Usage.CacheCreationInputTokens > 0 {
800 usage.CacheWriteTokens = m.Usage.CacheCreationInputTokens
801 }
802 switch m.Delta.StopReason {
803 case "end_turn", "stop_sequence":
804 stop = StopEnd
805 case "max_tokens":
806 stop = StopLength
807 case "tool_use":
808 stop = StopToolUse
809 }
810 case "message_stop":
811 sendDone()
812 return
813 case "error":
814 var e struct {
815 Error struct {
816 Type string `json:"type"`
817 Message string `json:"message"`
818 } `json:"error"`
819 }
820 _ = json.Unmarshal([]byte(ev.Data), &e)
821 stop = StopError
822 finalErr = fmt.Errorf("anthropic %s: %s", e.Error.Type, e.Error.Message)
823 sendDone()
824 return
825 }
826 _ = activeIdx
827 }
828 }
829}