Skip to content

feat: Decode Anthropic Messages replies to pivot events - #1970

Merged
huang195 merged 3 commits into
rossoctl:mainfrom
huang195:feat/anthropic-server-1965-pP2
Nov 18, 2026
Merged

huang195 merged 3 commits into
rossoctl:mainfrom
huang195:feat/anthropic-server-1965-pP2

Conversation

@huang195

Copy link
Copy Markdown
Member

What changed

This PR adds NewReplyDecoder to the anthropic-messages protocol (rules S13-S15 of #1965). The decoder reads a streamed or a not-streamed Anthropic reply and gives pivot events.

  • A stream gives start, the kept blocks, usage, and then stop. Usage comes before stop, because each reply encoder ends at stop.
  • A server-tool block and its deltas give no event and use no pivot index. The raw capture keeps them.
  • A thinking block with no text and a signature goes to the agent.
  • A stream with no message_stop ends with a 502 error.
  • A stream error event gets its status from its type.
  • A non-2xx body that does not have Anthropic's error shape gives api_error with its first 200 bytes. The cut is at a rune start.

No route changes. The router picks a target only when the target has a request encoder, and this protocol has none yet. P3 adds it.

How it was tested

  • cd core && GOWORK=off go test ./translate/anthropic/ passes.
  • 17 fixtures in core/translate/testdata/responses-anthropic/reply/. Each .sse fixture is also fed with a split at every byte boundary, and one byte at a time.
  • Each .json fixture gives the same events as its .sse twin, except for the split of the deltas.
  • The fixtures are hand-written. We did not compare them with real Anthropic stream bytes.

Size

  • Counted: 901 lines (672 of Go code and tests, 229 of hand-written fixtures).
  • Exempt: 273 lines (the plan document).

Review findings that are not fixed

These findings are minor. No route uses this decoder in this PR, so none of them can change a live reply before P3.

  • decode_reply.go:172-178 (failEvent) and lines 289-292: a stream error event, or a 2xx not-streamed "type":"error" body, with an empty error.type gives EventError{Status: 500, ErrorType: ""}. The agent-side encoder then sends "type":"". The Chat decoder checks the type against a known set. Suggestion: use api_error when the type is empty. No test covers this case.
  • decode_reply.go:281-287: stop_reason is passed on with no check. Anthropic also sends stop_sequence, pause_turn and model_context_window_exceeded. pivot.Event.StopReason documents only end_turn, max_tokens, tool_use and refusal. responses/reply.go terminal maps each unknown reason to response.completed. Thus pause_turn (an incomplete server-tool turn) and model_context_window_exceeded (a cut-off reply) get to Codex as a complete reply. The plan does not name these values. A possible map: model_context_window_exceeded to max_tokens.
  • decode_reply.go:286 and lines 298-321: a stream with message_stop but no message_start, or a kept block with no content_block_stop before message_stop, gives usage and stop with no EventStart or no EventBlockStop. The reply encoders expect a balanced event list. A real Anthropic server does not send this, so the risk is low. No test covers it.
  • decode_reply.go:314-316: in a not-streamed body, a tool_use block with no input member gives no DeltaInputJSON. A block with "input":null gives the delta null. Anthropic always sends an object, so this is only hardening. Decision 16 fills {} on the encode side, but the decode side has no matching rule.
  • Scope: the commit does all of Task T3 and nothing more. All 17 named fixtures exist, and each planned test exists. The 3 extra tests (_StreamErrorStatus, _StartTextAndUsage, _BadJSON) stay inside the decisions of T3.
  • decode_reply.go:43 and line 251: wireBlock reads text, thinking, signature, data, id and name for each block before openBlock skips a server-tool block (S13). A wrong JSON type in any typed field (id, model, text, index, stop_reason, or a usage token count such as 2.0) fails the whole event or body with a 502. Blocks that the decoder skips also cause this. A probe sent content_block_start {"type":"web_search_tool_result","data":5}, and the whole stream failed. Suggestion: decode the block as RawMessage and read type first, or decode only the fields of the four kinds that the decoder keeps. This becomes live in P3.
  • decode_reply.go:252 and line 301: a JSON type mismatch gets the message "not valid JSON", but the JSON is valid. Probe values that ended the reply with this message: usage output_tokens 12.5 or "12", stop_reason 3, index "0", text 5, tool_use id 7, error.message 5, and "error":"boom". Suggestion: say that Cortex cannot read the event, or add the error text, so that an operator can find the field.
  • decode_reply.go:344 (httpError): a non-2xx body without Anthropic's error shape always gets api_error. chat/reply.go uses pivot.ErrorType(d.status) for this case, and the T3 interfaces list pivot.ErrorType as consumed, but this code does not call it. With it, an HTML 429 from a proxy gives rate_limit_error and a 401 gives authentication_error. To make 529 give overloaded_error, map it through errorStatus too. Also, an Anthropic-shaped body whose error.message is a number falls back to api_error and the raw body, so the decoder loses rate_limit_error.
  • decode_reply.go:77: an error event with a string error ("error":"overloaded"), or with a message that is not a string, gives 502 "not valid JSON", and the server's status and text are lost. A 2xx body {"type":"error","error":{"message":5}} fails the same way. Suggestion: fall back to api_error with the raw text, as httpError does for non-2xx bodies.

For a human after review

These steps need a real Anthropic API key and a live Codex session. They need P2 and P3 (all of T2-T6) merged or checked out and installed. Do not run them in this workflow.

  1. Configure a server with only api: {anthropic-messages: /v1/messages} for https://api.anthropic.com, and route Codex to it (agentop server use <name> --agent codex).
  2. Run Codex for at least 3 turns with tool calls. Put the session id and the turn count in the P3 PR body.
  3. In that session, check that cache_read_input_tokens is above 0 from turn 2 (S12). If it stays at 0, report it in the PR.
  4. Check that turn 2 and later get no 400 about thinking blocks (feat: Translation hub: decode OpenAI Responses requests and encode Responses replies, so Codex can use any Chat Completions server #1964 R14 and S6). If they do, report the error message in the PR.

Part of #1965

Assisted-By: Claude (Anthropic AI) noreply@anthropic.com

…ub (rossoctl#1965)

Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com>
Signed-off-by: Hai Huang <huang195@gmail.com>
…t details

The estimate for T2-T6 is more than 2,000 counted lines. P2 now has the
reply decoder (T3). P3 has the encoder, the goldens, the resend tests and
the docs, with parent P2. The encoder must not merge before the reply
decoder, because translate.Target selects a protocol that has only a
request encoder.

The reply goldens use goldenName. The listener test builds its own
request, because postCodex sets no query and no Authorization header.

Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com>
Signed-off-by: Hai Huang <huang195@gmail.com>
Add NewReplyDecoder to the anthropic-messages protocol (rules S13-S15
of rossoctl#1965). The decoder reads a streamed or a not-streamed reply and
gives pivot events:

- The stream gives start, the kept blocks, usage, then stop. The usage
  comes before stop, because each reply encoder ends at stop.
- A server-tool block and its deltas give no event and use no pivot
  index. The raw capture keeps them.
- A thinking block with no text and a signature goes to the agent.
- A stream with no message_stop ends with a 502 error.
- A stream error event gets its status from its type.
- A non-2xx body that is not Anthropic's error shape gives api_error
  with its first 200 bytes, cut at a rune start.

No route changes: the router picks a target only when the target has
a request encoder, and this protocol has none yet.

Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com>
Signed-off-by: Hai Huang <huang195@gmail.com>
@huang195
huang195 requested a review from a team as a code owner November 18, 2026 18:20
@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 15 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: da28f27c-9a6a-42e3-819d-c5ba4d2eb9de
Commits

Reviewing files that changed from the base of the PR and between e6307d3 and cb84418.

Files selected for processing: 21

  • core/translate/anthropic/decode_reply.go
  • core/translate/anthropic/decode_reply_test.go
  • core/translate/anthropic/protocol.go
  • core/translate/testdata/responses-anthropic/reply/error_429_rate_limit.json
  • core/translate/testdata/responses-anthropic/reply/error_529_overloaded.json
  • core/translate/testdata/responses-anthropic/reply/max_tokens.json
  • core/translate/testdata/responses-anthropic/reply/max_tokens.sse
  • core/translate/testdata/responses-anthropic/reply/redacted_thinking.json
  • core/translate/testdata/responses-anthropic/reply/redacted_thinking.sse
  • core/translate/testdata/responses-anthropic/reply/refusal.json
  • core/translate/testdata/responses-anthropic/reply/refusal.sse
  • core/translate/testdata/responses-anthropic/reply/server_tool.json
  • core/translate/testdata/responses-anthropic/reply/server_tool.sse
  • core/translate/testdata/responses-anthropic/reply/stream_error.sse
  • core/translate/testdata/responses-anthropic/reply/text.json
  • core/translate/testdata/responses-anthropic/reply/text.sse
  • core/translate/testdata/responses-anthropic/reply/thinking_signature.json
  • core/translate/testdata/responses-anthropic/reply/thinking_signature.sse
  • core/translate/testdata/responses-anthropic/reply/two_tools.json
  • core/translate/testdata/responses-anthropic/reply/two_tools.sse
  • docs/superpowers/plans/2026-11-18-anthropic-server-1965.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions github-actions Bot added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 18, 2026

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The reply decoder follows S13-S15 and plan decisions 5-13. I ran it on Anthropic-shaped inputs that are not in the fixtures, and each one decoded correctly. The inputs covered the current message_start usage (cache_creation, service_tier, server_tool_use: null, container: null), interleaved thinking with thinking_delta and signature_delta, a streamed server_tool_use with input_json_delta followed by web_search_tool_result (both skipped with no index gap), citations_delta on a text block (skipped), a tool_use with an empty partial_json (the Responses encoder fills {}), message_delta with context_management and null stop_reason or usage, CRLF line ends, data: with no space, a trailing [DONE], and an error event with details: null and request_id. I also ran the fixtures end to end through translate.Reply("responses", "anthropic-messages", ...), and Codex-shaped output came out right. That output covered function-call argument deltas, the cortex1: reasoning item that carries only a signature, a skipped server-tool block, refusal to incomplete/content_filter, and the stream error to 529. go test ./translate/..., go test -race ./translate/anthropic/, go vet and gofmt are clean. No route uses the decoder yet: Target still requires a RequestEncoder. My two comments below are small and do not block merge.

I agree with the open findings in the PR body. Two of them become live in P3, so it would be good to fix them there: the stop_reason pass-through (model_context_window_exceeded reaching Codex as completed), and the typed wireBlock fields that are decoded before a server-tool block is skipped.

Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (translate/anthropic reply decoder, tests, fixtures), Docs (plan)
Agent/IDE config (.claude/.vscode): none
Commits: 3 commits, all signed-off: yes
CI status: passing

d.failEvent(m.Error)
return
}
d.emit(pivot.Event{Kind: pivot.EventStart, ID: m.ID, Model: m.Model})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: whole treats any 2xx JSON value that is not an error as a complete reply. A body of {} or null (for example from a proxy or a misrouted endpoint) gives start, usage{0}, stop end_turn, so the agent sees an empty but successful turn. The stream path refuses this case (decision 8, msgEndedEarly), but the not-streamed path has no matching guard. Consider requiring m.Type == "message" and otherwise failing with 502 api_error (for example "the inference server sent a reply that is not an Anthropic message"). Probe: decodeAll(200, false, "{}") and decodeAll(200, false, "null") both give [start, usage, stop end_turn].

var errorStatus = map[string]int{
"invalid_request_error": 400, "authentication_error": 401, "permission_error": 403,
"not_found_error": 404, "request_too_large": 413, "rate_limit_error": 429,
"overloaded_error": 529,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Anthropic's error list also has billing_error (402) and timeout_error (504). Today a stream error event with either type gets status 500. Adding them to the map would keep the status faithful. If you want the map to stay equal to decision 9, it could instead go in the plan's open items for P3.

@huang195
huang195 merged commit 24967f0 into rossoctl:main Nov 18, 2026
40 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 18, 2026
@huang195
huang195 deleted the feat/anthropic-server-1965-pP2 branch November 18, 2026 19:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants