Skip to content

feat: convert between all four API formats - #36

Merged
fylorn merged 4 commits into
mainfrom
feat/any-to-any
Sep 17, 2026
Merged

fylorn merged 4 commits into
mainfrom
feat/any-to-any

Conversation

@fylorn

@fylorn fylorn commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Why

Ships in 0.4.0 together with #35.

ThinkWatch Lite should let any client use any upstream: Claude Code on an OpenAI or Gemini account, Codex CLI on Claude, Gemini CLI on a Chat-compatible relay. Until now the gateway converted exactly one direction (Anthropic client → OpenAI Chat upstream), and everything else was passthrough only.

The enterprise gateway was the planned source, but its inbound converters keep plain text only (tools, images and thinking are dropped silently), it has no Gemini inbound and no stream conversion toward clients. Core's own converter was the most complete one, so this change generalizes it rather than porting.

What changes

tw-dialect: one intermediate representation, four formats

  • ir.rs: request, response and stream-event types shared by all formats, plus Dropped (field paths in the client's own request) and Rejection.
  • anthropic/, chat/, responses/, gemini/: each has request decode/encode, whole-response decode/encode, and a stream parser and writer.
  • convert.rs: decode once, encode per target; Session converts whole responses, streams (StreamConverter), stream-to-whole (Collector), whole-to-stream, and upstream error bodies. strip_carried removes signatures a conversion wrote before a passthrough hop.
  • Field mappings were written against the current official SDK type definitions (anthropic-sdk-python, openai-python, google-genai as of 2026-09-16). Notable points:
    • Claude 4.6+ gets thinking: adaptive + output_config.effort; older Claude and Anthropic-compatible endpoints get enabled + budget_tokens (the two are mutually exclusive by model). The official endpoint gets no temperature/top_p/top_k.
    • Responses targets get strict: false on function tools, store: false, and include: ["reasoning.encrypted_content"] when reasoning is on. Custom (freeform) tools and namespace tools round-trip for Codex.
    • Gemini targets use parametersJsonSchema, thinkingLevel on Gemini 3, and the documented synthetic thoughtSignature on function calls from foreign history.
    • Requests that depend on server-side state (previous_response_id, conversation, item_reference, compaction, cachedContent) are refused with an explanation.
    • Reasoning signatures travel in the client's own signature field with a tw1. prefix, so they return to the vendor that issued them.
  • tests/matrix.rs: 4 × 4 clients × upstreams, each through whole, streamed (cut into 7-byte pieces) and collected responses, checking text, tool calls, stop reason and usage including cache hits.

Gateway

  • client_api::read decodes the request once; routing facts come from the IR (RequestFacts::from_request), so rules work for every client format. Gemini clients previously routed with an empty model.
  • Per hop: rule set applies to the IR for conversions and uses each format's field names in passthrough; outbound redaction now runs on the converted body (it used to start from the original body, so converted requests went out unredacted).
  • Headers: client-format headers are dropped when converting, anthropic-version is added for Anthropic targets, path and query come from the conversion.
  • Anthropic requires max_tokens. When the client did not set one, the model's output limit from the price table is used; tw-pricing now parses max_output_tokens from the LiteLLM dataset and keeps it through price sheets. A name-based guess remains for models the table does not know.
  • Responses: streams convert as they flow; whole bodies, upstream errors and whole-to-stream are converted at the end; a broken converted stream ends in the client's format.
  • Only generation converts. count_tokens, embeddings and compaction go to same-format upstreams only; count_tokens used to be rewritten into a paid chat completion.
  • /v1/models lists every model for every client format.
  • Usage sniffing reads Gemini usageMetadata (Gemini traffic was unmetered) and subtracts cached tokens for Responses and Chat (cache hits were billed at the input price).

Store, API, dry run

  • requests.translated (schema 12) keeps the conversion of the hop that served the request; HistoryRow.translated exposes it.
  • DryRunResult.converted lists candidates whose protocol differs from the client format.

Tool-call inspection in every format

  • toolwall used to understand Anthropic streams only, so Chat, Responses and Gemini streams were never inspected, whether passthrough or converted. It now also reads Chat tool-call fragments, Responses function/custom tool calls (deltas, completed items, WebSocket frames) and Gemini function calls, plus response text for the injection check. The cut point is computed on the bytes the client receives, as before; a cut converted stream ends in the client's error format.

Tests

cargo fmt --check, cargo clippy --workspace --all-targets -D warnings, cargo test --workspace and ./scripts/smoke.sh pass locally. New: tw-dialect unit tests per format, tests/matrix.rs, tw-gateway/tests/conversion.rs (headers, Gemini paths, error conversion, count_tokens guard, signature stripping, redaction after conversion, a converted stream cut by the firewall), recorder and dry-run tests. Replay fixtures were updated by hand for the new token estimate, which no longer counts base64 image data or JSON structure strings.

🤖 Generated with Claude Code

Base automatically changed from feat/slugs-and-written-copy to main September 17, 2026 13:52
fylorn and others added 4 commits September 17, 2026 21:53
Any client format can now use any upstream protocol: Anthropic Messages,
OpenAI Chat Completions, OpenAI Responses and Gemini generateContent.

tw-dialect is rebuilt around an intermediate representation. Each format
has a decoder and an encoder for requests, whole responses and streams,
so the 12 cross-format directions share one implementation per format
instead of one per pair. Field mappings follow the current official SDK
type definitions (Anthropic adaptive thinking and output_config.effort,
OpenAI reasoning effort up to max, Responses namespace and custom tools,
Gemini parametersJsonSchema and thinkingLevel). Anything without a
counterpart is reported as a field path of the client request. Requests
that depend on server-side state (previous_response_id, conversation,
item_reference, compaction, cachedContent) are refused rather than
answered without their context. Reasoning signatures are carried in the
client's own signature field with a tw1. prefix so the next turn can hand
them back to the vendor that issued them. A 4x4 matrix test runs every
pair through whole, streamed and collected responses.

Gateway wiring:
- the request is decoded once; routing facts come from the IR, so rules on
  model, tools, images and thinking work for every client format (Gemini
  clients used to route with an empty model)
- rule `set` rewrites apply to the IR for converted requests and use each
  format's own field names in passthrough
- outbound redaction now applies to the converted body; before, conversion
  started from the original body and sent secrets unredacted
- dialect-specific client headers are dropped and anthropic-version is added
  when converting to Anthropic; path and query come from the conversion
- upstream error bodies are converted to the client's error shape, a whole
  response is written as a stream when the client asked for one, and a
  broken stream ends in the client's format
- calls other than generation (count_tokens, embeddings, compaction) are only
  sent to same-format upstreams; count_tokens used to be rewritten into a
  paid chat completion
- passthrough strips reasoning signatures that a conversion wrote
- /v1/models lists every model for every client format

Usage sniffing reads Gemini usageMetadata and subtracts cached tokens from
Responses and Chat inputs, so Gemini traffic is no longer unmetered and
cache hits are no longer billed at the input price.

The store records the conversion that served a request (schema 12), the
history API returns it, and dry runs list candidates that would convert.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The tool-call firewall only understood Anthropic streams, so Chat,
Responses and Gemini streams were not inspected at all, whether they were
passthrough or converted. With conversion, a dangerous call from an
untrusted relay reached a Chat or Codex client untouched.

The wall still reads the bytes the client is about to receive, frame by
frame, so the cut point is computed the same way. It now also recognizes
Chat tool-call fragments, Responses function and custom tool calls (deltas,
completed items, and WebSocket frames) and Gemini function calls, plus
response text for the injection check. "Incomplete is harmless" holds in
all four: Anthropic waits for content_block_stop, Chat for the end of the
stream, Codex for output_item.done, and a Gemini call arrives in a single
frame that is not forwarded.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
When a request is converted to Anthropic, max_tokens is required. If the
client did not set one, the gateway used a guess by model name. The price
table (LiteLLM's dataset) already carries max_output_tokens for each model;
it is now parsed, kept through price sheets, and used first. The name-based
guess remains only for models the table does not know.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@fylorn
fylorn merged commit c76dc86 into main Sep 17, 2026
1 check passed
@fylorn
fylorn deleted the feat/any-to-any branch September 17, 2026 14:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant