1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
|
package main
// The agent loop against Anthropic's Messages API.
//
// Where Gemini's Interactions API keeps the conversation on its server, the
// Messages API keeps nothing: every call sends the whole path from the root.
// That fits the tree better than it sounds. A node stores the blocks it sent
// and received, verbatim; the path to a node *is* the messages array, so there
// is no server id to lose and no replay case to get wrong. Branching from node
// 7 sends the path to node 7 plus the new prompt, and since every earlier
// request wrote a cache entry at its own end, that prefix is read from cache
// for as long as the entry lives.
//
// Two properties have to hold for that to work, and most of this file is
// about keeping them:
//
// - The bytes of an earlier request must not change. Prompt caching is by
// prefix, and so is the check on thinking signatures: a thinking block is
// only valid while the system prompt, the tools and every message before
// it are what they were when it was produced. So blocks are stored and
// resent exactly as received, foreign nodes are translated the same way
// every time, and nothing here depends on the time or on the order of a
// map.
// - Thinking blocks go back unchanged, including ones whose text is empty —
// on Claude 5 models the readable part is empty unless asked for, and the
// reasoning travels in the signature.
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
// anthropicURL is a variable only so tests can point it at a fake server.
var anthropicURL = "https://api.anthropic.com/v1/messages"
// anthropicMaxTokens bounds one call's output. Every model from Claude 4 on
// accepts at least this much, and with streaming there is no timeout reason
// to ask for less.
const anthropicMaxTokens = 32000
// ============================================================================
// Request
// ============================================================================
type anthropicRequest struct {
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
Stream bool `json:"stream"`
System []anthropicText `json:"system,omitempty"`
Tools []anthropicTool `json:"tools,omitempty"`
Messages []anthropicMessage `json:"messages"`
Thinking json.RawMessage `json:"thinking,omitempty"`
OutputConfig *anthropicOutCf `json:"output_config,omitempty"`
}
type anthropicText struct {
Type string `json:"type"`
Text string `json:"text"`
CacheControl *cacheControl `json:"cache_control,omitempty"`
}
type cacheControl struct {
Type string `json:"type"`
}
var ephemeral = &cacheControl{Type: "ephemeral"}
type anthropicTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"input_schema"`
}
type anthropicOutCf struct {
Effort string `json:"effort,omitempty"`
}
// anthropicMessage is one message of the conversation. Content holds raw
// blocks, so stored blocks go out byte for byte as they came in.
type anthropicMessage struct {
Role string `json:"role"`
Content []json.RawMessage `json:"content"`
}
// anthropicMCPTools are the MCP server's tools in Messages API shape,
// named and passed through as OpenCode does; see registerMCPTools. They
// follow OpenCode's own tools in every request.
var anthropicMCPTools []anthropicTool
// thinkingFor is the thinking configuration sent for a model: none, as
// OpenCode sends none. Claude 5 models think regardless, with the reasoning
// hidden (display "omitted") and carried in the signature; older models do
// not think unless asked, which is the price of looking like OpenCode.
func thinkingFor(model string) json.RawMessage {
return nil
}
// ============================================================================
// Building messages from the tree
// ============================================================================
// anthropicMessages renders a path as the messages array.
//
// Nodes Claude answered are sent as stored. Nodes another provider answered
// are translated through the neutral step view (see convert.go), without
// their reasoning. Consecutive blocks of one role become one message, tool
// calls left without results are removed — the API rejects both — and the
// result is deterministic, so the same path renders to the same bytes on
// every request.
func anthropicMessages(path []node) []anthropicMessage {
var msgs []anthropicMessage
add := func(role string, block json.RawMessage) {
if n := len(msgs); n > 0 && msgs[n-1].Role == role {
msgs[n-1].Content = append(msgs[n-1].Content, block)
return
}
msgs = append(msgs, anthropicMessage{Role: role, Content: []json.RawMessage{block}})
}
var ids toolIDs
for _, it := range replayPath(path) {
provider := providerOf(it.node.Model)
calls := 0
for _, sec := range it.sections() {
if provider == providerAnthropic {
for _, b := range sec.steps {
add(sec.role, b)
}
continue
}
for _, v := range viewSteps(provider, sec.role, sec.steps) {
var block json.RawMessage
switch v.Kind {
case kindUserInput, kindModelOutput:
// An empty text block is a 400; Gemini writes them.
if v.Text == "" {
continue
}
block = jsonObject("type", "text", "text", v.Text)
case kindFunctionCall:
input := v.Input
if input == nil {
input = map[string]any{}
}
block = jsonObject(
"type", "tool_use", "id", ids.call(v.ID, it.node.ID, calls),
"name", v.Name, "input", sortedJSON(input),
"caller", json.RawMessage(`{"type":"direct"}`),
)
calls++
case kindFunctionResult:
var isErr any
if v.IsError {
isErr = true
}
block = jsonObject(
"type", "tool_result", "tool_use_id", ids.result(v.ID),
"content", v.Text, "is_error", isErr,
)
default:
// Reasoning, and anything unrecognised, does not carry
// over to another provider.
continue
}
add(sec.role, block)
}
}
}
return repairToolPairs(msgs)
}
// repairToolPairs removes tool_use blocks that no tool_result answers and
// tool_results that answer nothing, and then any message left empty.
//
// A well-formed path has neither. They appear when a turn was interrupted
// between the model asking for a tool and the result being stored, or when a
// translated path has calls the other provider never matched, and the API
// rejects the whole request over one of them. Dropping the orphan loses
// nothing the model could use: a call with no answer says nothing.
//
// Removing blocks also merges what were separate messages, which is checked
// again at the end, so the result alternates as the API requires.
func repairToolPairs(msgs []anthropicMessage) []anthropicMessage {
uses := map[string]bool{}
results := map[string]bool{}
for _, m := range msgs {
for _, raw := range m.Content {
var b anthropicBlock
json.Unmarshal(raw, &b)
switch b.Type {
case "tool_use":
uses[b.ID] = true
case "tool_result":
results[b.ToolUseID] = true
}
}
}
var out []anthropicMessage
for _, m := range msgs {
var kept []json.RawMessage
for _, raw := range m.Content {
var b anthropicBlock
json.Unmarshal(raw, &b)
if b.Type == "tool_use" && !results[b.ID] {
continue
}
if b.Type == "tool_result" && !uses[b.ToolUseID] {
continue
}
kept = append(kept, raw)
}
if len(kept) == 0 {
continue
}
if n := len(out); n > 0 && out[n-1].Role == m.Role {
out[n-1].Content = append(out[n-1].Content, kept...)
continue
}
out = append(out, anthropicMessage{Role: m.Role, Content: kept})
}
return out
}
// ============================================================================
// The backend
// ============================================================================
// anthropicAuth supplies credentials and says what they require of a request.
type anthropicAuth interface {
// headers returns every header of a request, in the order they are
// sent; see rawPost for the few it adds itself.
headers(ctx context.Context) ([]header, error)
// refresh is called after a 401, to get credentials that are not stale.
refresh(ctx context.Context) error
// system is the system prompt such credentials require for a request
// with these messages; see oauthAuth.
system(msgs []anthropicMessage) []anthropicText
}
// anthropicBackend speaks the Messages API.
type anthropicBackend struct {
model string
auth anthropicAuth
effort string
// system is OpenCode's system text for this model and directory,
// computed once per session: it holds the date, and a prompt that
// changed at midnight would invalidate the cache and every thinking
// block after it.
system string
}
func (b *anthropicBackend) Model() string { return b.model }
// UserInput is a prompt as OpenCode sends it: JSON-quoted, with a trailing
// newline. That is what opencode-claude-auth's request transform leaves of a
// user message, and it is copied rather than understood.
func (b *anthropicBackend) UserInput(text string) []json.RawMessage {
return []json.RawMessage{jsonObject("type", "text", "text", string(marshalJS(text))+"\n")}
}
func (b *anthropicBackend) ToolResult(call functionCall, output string) json.RawMessage {
// hans' own tools report failure as "error: …"; saying so in the flag
// lets the model tell a failed read from a file that says "error".
var isErr any
if strings.HasPrefix(output, "error: ") {
isErr = true
}
return jsonObject("type", "tool_result", "tool_use_id", call.ID, "content", output, "is_error", isErr)
}
func (b *anthropicBackend) Call(ctx context.Context, st *store, parent *node, input []json.RawMessage, out sink) (callResult, error) {
var path []node
if parent != nil {
var err error
path, err = st.pathTo(parent.ID)
if err != nil {
return callResult{}, fmt.Errorf("read path: %w", err)
}
}
// The new input is one more node, so that when it carries the parent's
// tool results they are sent once; see replayPath.
path = append(path, node{Model: b.model, Input: input})
req := b.request(anthropicMessages(path))
var res callResult
var err error
for attempt := 0; ; attempt++ {
res, err = b.stream(ctx, req, out)
var he *anthropicHTTPError
if !errors.As(err, &he) || attempt >= 3 {
break
}
switch {
case he.status == http.StatusUnauthorized && attempt == 0:
out.note("\n[credentials rejected, refreshing]\n")
if rerr := b.auth.refresh(ctx); rerr != nil {
return callResult{}, fmt.Errorf("%w (refresh failed: %v)", err, rerr)
}
case he.status == http.StatusTooManyRequests || he.status == 529:
wait := he.retryAfter
if !he.hasRetryAfter {
wait = time.Duration(attempt+1) * 2 * time.Second
}
out.note("\n[%d, retrying in %s]\n", he.status, wait)
select {
case <-time.After(wait):
case <-ctx.Done():
return callResult{}, ctx.Err()
}
default:
return callResult{}, err
}
}
return res, err
}
// request assembles the request for a conversation, as OpenCode and the
// opencode-claude-auth plugin together would.
//
// OpenCode's system text (see opencode_prompt.go) becomes, by the plugin's
// hand, the first block of the first user message, and the system prompt
// is left to the billing line and the identity sentence (see oauthAuth).
// The billing line's checksum is over the user's own first message, which
// the plugin computes before it moves the instructions in, so the system
// text is computed here and the checksum from the messages without it.
func (b *anthropicBackend) request(msgs []anthropicMessage) anthropicRequest {
maxTokens := anthropicMaxTokens
if strings.HasPrefix(b.model, "claude-3") {
// Claude 3 models cap output far lower and reject the larger value.
maxTokens = 4096
}
req := anthropicRequest{
Model: b.model,
MaxTokens: maxTokens,
Stream: true,
Tools: append(opencodeTools(), anthropicMCPTools...),
Thinking: thinkingFor(b.model),
}
if b.effort != "" {
req.OutputConfig = &anthropicOutCf{Effort: b.effort}
}
req.System = b.auth.system(msgs)
// The first message is always the session's first prompt, a user turn.
// It is copied rather than modified, since msgs shares its slices with
// the caller.
if len(msgs) > 0 && msgs[0].Role == roleUser {
first := anthropicMessage{Role: roleUser}
first.Content = append([]json.RawMessage{jsonObject("type", "text", "text", b.system)}, msgs[0].Content...)
msgs = append([]anthropicMessage{first}, msgs[1:]...)
}
req.Messages = msgs
return req
}
// anthropicHTTPError is a non-200 answer, kept apart so Call can decide
// whether it is worth retrying.
type anthropicHTTPError struct {
status int
retryAfter time.Duration
// hasRetryAfter distinguishes "retry now" from "the server did not say".
hasRetryAfter bool
body string
}
func (e *anthropicHTTPError) Error() string {
return fmt.Sprintf("anthropic API status %d: %s", e.status, e.body)
}
// ============================================================================
// Streaming
// ============================================================================
type anthropicEvent struct {
Type string `json:"type"`
Index int `json:"index"`
Message json.RawMessage `json:"message"`
ContentBlock json.RawMessage `json:"content_block"`
Delta json.RawMessage `json:"delta"`
Usage *anthropicUsage `json:"usage"`
Error json.RawMessage `json:"error"`
}
type anthropicUsage struct {
InputTokens int `json:"input_tokens"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
CacheReadInputTokens int `json:"cache_read_input_tokens"`
OutputTokens int `json:"output_tokens"`
}
type anthropicDelta struct {
// StopDetails explains a refusal: which policy category, and why. It is
// what a user needs to know that the request was blocked by a classifier
// rather than declined by the model.
StopDetails *struct {
Category string `json:"category"`
Explanation string `json:"explanation"`
} `json:"stop_details"`
Type string `json:"type"`
Text string `json:"text"`
Thinking string `json:"thinking"`
Signature string `json:"signature"`
PartialJSON string `json:"partial_json"`
StopReason string `json:"stop_reason"`
}
// blockAccumulator builds one content block from its start event and deltas.
//
// The start event's block is kept whole and only the streamed fields are
// filled in, so a block type or field this code does not know survives into
// the stored node rather than being dropped — the API wants assistant turns
// back exactly as it sent them, and a serializer that drops what it does not
// recognise edits the prefix of every later turn.
type blockAccumulator struct {
block jsonFields
typ string
text strings.Builder
thinking strings.Builder
signature strings.Builder
json strings.Builder
streamed map[string]bool
}
func (acc *blockAccumulator) finish() (json.RawMessage, *functionCall, error) {
if acc.streamed["text"] {
acc.block = acc.block.set("text", acc.text.String())
}
if acc.streamed["thinking"] {
acc.block = acc.block.set("thinking", acc.thinking.String())
}
if acc.streamed["signature"] {
acc.block = acc.block.set("signature", acc.signature.String())
}
var call *functionCall
if acc.typ == "tool_use" {
// The input is kept as the model streamed it, compacted, rather
// than decoded and re-encoded: a map would come back sorted.
input := json.RawMessage(acc.json.String())
if len(input) == 0 {
input = acc.block.get("input")
}
if len(input) == 0 {
input = json.RawMessage("{}")
}
var compact bytes.Buffer
if err := json.Compact(&compact, input); err != nil {
return nil, nil, fmt.Errorf("tool input is not JSON: %w: %s", err, input)
}
args := map[string]any{}
json.Unmarshal(compact.Bytes(), &args)
acc.block = acc.block.set("input", json.RawMessage(compact.Bytes()))
// OpenCode sends every tool call back with the caller that made
// it; for a call the model made itself, that is "direct".
if acc.block.get("caller") == nil {
acc.block = acc.block.set("caller", json.RawMessage(`{"type":"direct"}`))
}
var id, name string
json.Unmarshal(acc.block.get("id"), &id)
json.Unmarshal(acc.block.get("name"), &name)
call = &functionCall{ID: id, Name: name, Args: args}
}
return acc.block.encode(), call, nil
}
func (b *anthropicBackend) stream(ctx context.Context, req anthropicRequest, out sink) (callResult, error) {
body := encodeRequest(req)
var result callResult
t0 := time.Now()
headers, err := b.auth.headers(ctx)
if err != nil {
return callResult{}, err
}
resp, err := rawPost(ctx, anthropicURL, headers, body)
if err != nil {
return callResult{}, fmt.Errorf("http request: %w", err)
}
result.uploadDone = time.Since(t0)
result.ttfb = result.uploadDone
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 8192))
he := &anthropicHTTPError{status: resp.StatusCode, body: string(msg)}
if s, err := strconv.Atoi(resp.Header.Get("retry-after")); err == nil {
he.retryAfter = time.Duration(s) * time.Second
he.hasRetryAfter = true
}
return callResult{}, he
}
l := &lanes{out: out}
accs := map[int]*blockAccumulator{}
var order []int
var usage anthropicUsage
var stopReason string
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 1024*1024), 16*1024*1024)
prevEvent := t0
stopped := false
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "data:") {
continue
}
data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
var ev anthropicEvent
if err := json.Unmarshal([]byte(data), &ev); err != nil {
return callResult{}, fmt.Errorf("decode SSE event: %w\nraw: %s", err, data)
}
if verbose {
now := time.Now()
l.enter(laneNone)
out.note(" [sse +%-7s Δ%-7s %s]\n",
now.Sub(t0).Round(time.Millisecond), now.Sub(prevEvent).Round(time.Millisecond), ev.Type)
prevEvent = now
}
switch ev.Type {
case "message_start":
var m struct {
Usage anthropicUsage `json:"usage"`
}
json.Unmarshal(ev.Message, &m)
usage = m.Usage
case "content_block_start":
acc := &blockAccumulator{streamed: map[string]bool{}}
fields, err := parseFields(ev.ContentBlock)
if err != nil {
return callResult{}, fmt.Errorf("decode content_block_start: %w", err)
}
acc.block = fields
json.Unmarshal(fields.get("type"), &acc.typ)
accs[ev.Index] = acc
order = append(order, ev.Index)
case "content_block_delta":
acc := accs[ev.Index]
if acc == nil {
return callResult{}, fmt.Errorf("delta for block %d, which never started", ev.Index)
}
var d anthropicDelta
json.Unmarshal(ev.Delta, &d)
switch d.Type {
case "text_delta":
acc.streamed["text"] = true
acc.text.WriteString(d.Text)
l.answer(d.Text)
case "thinking_delta":
acc.streamed["thinking"] = true
acc.thinking.WriteString(d.Thinking)
l.thinking(d.Thinking)
case "signature_delta":
acc.streamed["signature"] = true
acc.signature.WriteString(d.Signature)
case "input_json_delta":
acc.json.WriteString(d.PartialJSON)
}
case "message_delta":
var d anthropicDelta
json.Unmarshal(ev.Delta, &d)
stopReason = d.StopReason
if d.StopDetails != nil && d.StopDetails.Explanation != "" {
stopReason = fmt.Sprintf("%s (%s): %s", d.StopReason, d.StopDetails.Category, d.StopDetails.Explanation)
}
if ev.Usage != nil {
// The final usage repeats the input counts on newer
// models and omits them on older ones; take what is there.
usage.OutputTokens = ev.Usage.OutputTokens
if ev.Usage.InputTokens > 0 {
usage.InputTokens = ev.Usage.InputTokens
}
if ev.Usage.CacheReadInputTokens > 0 {
usage.CacheReadInputTokens = ev.Usage.CacheReadInputTokens
}
if ev.Usage.CacheCreationInputTokens > 0 {
usage.CacheCreationInputTokens = ev.Usage.CacheCreationInputTokens
}
}
case "message_stop":
stopped = true
case "error":
l.enter(laneNone)
return callResult{}, fmt.Errorf("anthropic error event: %s", ev.Error)
}
}
l.enter(laneNone)
if err := scanner.Err(); err != nil {
return callResult{}, fmt.Errorf("reading stream: %w", err)
}
if !stopped {
return callResult{}, fmt.Errorf("stream ended without message_stop")
}
for _, idx := range order {
block, call, err := accs[idx].finish()
if err != nil {
return callResult{}, err
}
result.steps = append(result.steps, block)
if call != nil {
result.calls = append(result.calls, *call)
}
}
in := usage.InputTokens + usage.CacheCreationInputTokens + usage.CacheReadInputTokens
result.usage = interactionUsage{
TotalInputTokens: in,
TotalCachedTokens: usage.CacheReadInputTokens,
TotalCacheWriteTokens: usage.CacheCreationInputTokens,
TotalOutputTokens: usage.OutputTokens,
TotalTokens: in + usage.OutputTokens,
}
switch strings.SplitN(stopReason, " ", 2)[0] {
case "end_turn", "tool_use", "stop_sequence", "":
default:
// max_tokens, refusal, model_context_window_exceeded: the answer is
// not the whole answer, and the node should say so.
result.stopReason = stopReason
result.calls = nil
}
result.total = time.Since(t0)
return result, nil
}
|