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