diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,15 @@
+# Changelog
+
+## 0.1.0.0 (2026-11-20)
+
+### New Features
+
+- `Claude.Client` provides a reusable HTTP client with per-request beta headers, response request IDs, and typed transport, HTTP, and decoding errors.
+- `Claude.Messages` and `Claude.Messages.Features` support synchronous messages and token counting, with structured outputs, thinking, prompt caching, citations, and client and server tools.
+- `Claude.Messages` supports compaction, container reuse, server-side fallbacks, and continuation helpers for carrying typed tool results and response evidence across turns.
+- `Claude.Streaming` delivers typed server-sent events incrementally and lets callers stop the stream from the event callback.
+- `Claude.Batches` submits, retrieves, lists, and cancels message batches and consumes JSON Lines results incrementally.
+
+### Other Changes
+
+- Include a runnable Messages example and document request controls, supported API versions, and continuation behavior.
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Nadeem Bitar
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,21 @@
+# claude-hs
+
+Haskell client for the direct [Anthropic Messages API](https://platform.claude.com/docs/en/api/messages/create), using API version 2026-10-21.
+
+```bash
+nix develop --no-write-lock-file -c cabal update
+nix develop --no-write-lock-file -c cabal build all
+nix develop --no-write-lock-file -c cabal test all --test-show-details=direct
+```
+
+The loopback tests use synthetic credentials. To run the [example](example/Main.hs) against Anthropic, supply `ANTHROPIC_API_KEY` in the environment and run `nix develop -c cabal run claude-message-example`.
+
+Create a `Client` once and share it across calls to reuse connections. `defaultClientConfig` uses `https://api.anthropic.com` and a 60-second HTTP response timeout. `RequestOptions` carries beta flags and additional metadata headers. Authentication, API version and framing headers are reserved. A `Response` carries the request ID where the server provides one. A `ClientError` distinguishes transport failures, HTTP status failures and JSON decoding errors. Applications own retry decisions.
+
+See [Messages coverage](docs/messages-coverage.md) for request options, model restrictions and continuation behavior.
+
+Use `Claude.Streaming.streamMessage` for SSE. The callback receives typed events synchronously and returns `Continue` or `Stop`. Inspect the terminal result for provider completion or caller stop. Keep partial output in the callback if the caller needs it after a stream failure.
+
+Use `Claude.Batches` to submit, retrieve, list and cancel asynchronous batches. `consumeBatchResults` reads JSON Lines incrementally from the configured origin. Correlate outcomes with the original custom IDs.
+
+The [downstream trial](https://github.com/shinzui/claude-hs/blob/master/integration/consumers/README.md) contains the Baikai adapter patch, fixtures and pinned Cabal configuration for Baikai, Shikumi and Shikigami.
diff --git a/claude-hs.cabal b/claude-hs.cabal
new file mode 100644
--- /dev/null
+++ b/claude-hs.cabal
@@ -0,0 +1,97 @@
+cabal-version: 3.4
+name: claude-hs
+version: 0.1.0.0
+synopsis: Client for the Anthropic Claude Messages API
+description: Typed client for the direct Anthropic Messages API.
+category: Network
+license: MIT
+license-file: LICENSE
+author: Nadeem Bitar
+maintainer: Nadeem Bitar
+homepage: https://github.com/shinzui/claude-hs
+bug-reports: https://github.com/shinzui/claude-hs/issues
+build-type: Simple
+tested-with: ghc ==9.12.4
+extra-doc-files:
+  CHANGELOG.md
+  README.md
+  docs/messages-coverage.md
+
+source-repository head
+  type: git
+  location: https://github.com/shinzui/claude-hs
+
+common common
+  default-language: GHC2024
+  default-extensions:
+    DeriveAnyClass
+    DuplicateRecordFields
+    OverloadedLabels
+    OverloadedStrings
+
+  ghc-options: -Wall
+  build-depends: base >=4.21 && <5
+
+library
+  import: common
+  hs-source-dirs: src
+  exposed-modules:
+    Claude.Batches
+    Claude.Client
+    Claude.Messages
+    Claude.Messages.Features
+    Claude.Streaming
+
+  other-modules:
+    Claude.Internal.Http
+    Claude.Internal.Request
+    Claude.Internal.Sse
+    Claude.Messages.Usage
+
+  build-depends:
+    aeson >=2.2 && <2.4,
+    bytestring >=0.12 && <0.13,
+    containers >=0.7 && <0.9,
+    generic-lens >=2.2 && <2.4,
+    http-client >=0.7.18 && <0.8,
+    http-client-tls >=0.3.6 && <0.5,
+    http-types >=0.12 && <0.13,
+    lens >=5.2 && <5.4,
+    text >=2.1 && <2.2,
+    time >=1.12 && <1.17,
+    transformers >=0.6 && <0.7,
+
+executable claude-message-example
+  import: common
+  hs-source-dirs: example
+  main-is: Main.hs
+  build-depends:
+    bytestring,
+    claude-hs,
+    text,
+
+test-suite claude-hs-test
+  import: common
+  type: exitcode-stdio-1.0
+  hs-source-dirs: test
+  main-is: Main.hs
+  other-modules:
+    BatchesSpec
+    FeaturesSpec
+    MessagesSpec
+    StreamingSpec
+    Support.Server
+
+  ghc-options: -threaded
+  build-depends:
+    aeson,
+    bytestring,
+    claude-hs,
+    containers,
+    generic-lens,
+    http-types,
+    lens,
+    text,
+    time,
+    wai >=3.2 && <3.3,
+    warp >=3.3 && <3.6,
diff --git a/docs/messages-coverage.md b/docs/messages-coverage.md
new file mode 100644
--- /dev/null
+++ b/docs/messages-coverage.md
@@ -0,0 +1,76 @@
+# Messages coverage
+
+Wire fixtures use synthetic values sampled from the direct API documentation on 2026-11-20. The default `anthropic-version` is `2026-10-21`. The selected version rejects `temperature`, `top_p` and `top_k` even at their defaults. Audit legacy request builders for those keys before migrating. [API version migration](https://platform.claude.com/docs/en/api/migration-2026-10-21)
+
+- **Synchronous Messages and token counting.** Both accept text and URL or base64 images, structured output configuration, thinking, tools, caching and speed. The count request projects the input fields and excludes the output limit and stop sequences. [Create](https://platform.claude.com/docs/en/api/messages/create), [Count tokens](https://platform.claude.com/docs/en/api/messages/count_tokens)
+- **Structured output.** Set `OutputConfig (Just High) (Just schema)` for JSON Schema and independent effort. Read the result with `responseText` and check `stopReason` before decoding it into an application type. A refusal or truncation can leave the result outside the schema. Use document citations in a separate request since the API rejects citations with structured output. [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
+- **Strict client tools.** `CustomTool` accepts an input schema and the strict flag. Set tool choice independently. Return results with `InputToolResult` and the original tool ID. Run the tool in the application. [Strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use)
+- **Thinking.** `Adaptive` supports summarized, omitted and updates display. Updates requires `thinking-display-updates-2026-08-18`. Manual budgets, disabled mode, between-tools mode and effort values depend on the selected model. Replay original signed blocks, empty signed blocks and redacted blocks in the same provider and model conversation. [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking)
+- **Prompt caching.** Use top-level automatic caching or explicit breakpoints on system blocks, inputs and tools. Breakpoints support default, five-minute and one-hour TTLs. Read creation and read token counts from the response when present. [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
+- **Citations and web search.** Use `PlainTextDocument` with citations enabled. Returned text exposes character, page, block and web locations. The typed web search tool supports versions `20250305`, `20260209` and `20260318`. Dynamic filtering on later versions is model-dependent. Use `VersionedTool` for other tools or extended options. Output blocks retain unknown tagged values and opaque search evidence. [Citations](https://platform.claude.com/docs/en/build-with-claude/citations), [Web search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)
+- **Fast mode.** Set `speed = Just Fast` for supported models. Supply `fast-mode-2026-02-01` in `RequestOptions` where required. [Fast mode](https://platform.claude.com/docs/en/build-with-claude/fast-mode)
+
+Refresh fixtures by comparing the dated endpoint documentation and migration guide with the captured wire shape. Use synthetic model output, signatures, keys and encrypted citation indices. Compare semantic JSON and run the loopback suite from the locked shell.
+
+**Streaming migration.** `streamMessageValue` accepts a provider-shaped Messages object, validates its model, history and output limit, and owns the stream flag. With `apiVersion = Just "2026-10-21"` it reports removed sampling settings before dispatch. Compatibility callers with a supported old host or model may explicitly configure `Just "2023-06-01"` until they can migrate the setting. The direct client uses `2026-10-21` by default.
+
+**Batch results.** Read JSON Lines with the configured client origin and typed batch ID. The request uses the binary result media type. [Message Batch results](https://platform.claude.com/docs/en/api/messages/batches/results) and [Anthropic Python client](https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/resources/messages/batches.py)
+
+## Request controls and tools
+
+| Capability | Contract and fixture |
+|---|---|
+| Empty history and sampling | On `2023-06-01`, construct `EmptyConversation` or set `temperature`, `topP` and `topK` with `withRequestControls` on eligible models. `requestControlsRoundtrip` captures empty SSE and legacy sampling, and verifies independent pre-dispatch rejection on `2026-10-21`. Use `conversationHistory` and `withConversationHistory` with either conversation constructor. |
+| Metadata and inference geography | `advancedRequestRoundtrip` captures `metadata` and `inference_geo` on create. |
+| Compaction | `Compaction` builds an edit for `compact_20260112`, including instructions, token trigger and pause behavior. Configure the `compact-2026-01-12` beta in request options. `advancedRequestRoundtrip` captures the nested edit. |
+| Container reuse | `containerId` places the returned ID on a generation request. `advancedRequestRoundtrip` captures the top-level ID, caller tag and tool ID. |
+| Fallback configuration | `DefaultFallbacks` or `FallbackModels` selects server-side fallback with `server-side-fallback-2026-07-01` on eligible models. `advancedRequestRoundtrip` captures the ordered model settings. |
+| Mid-conversation system turns | Use `Message System` with text, `ToolAddition` or `ToolRemoval` for eligible models. Tool changes use the `inline-tools-2026-09-15` or platform-specific beta. The fixture captures system role and both reference tags. |
+| Deferred tools and tool search | Set `ConfiguredTool` with `ToolLoading` and include a `ToolSearchTool`. The fixture captures both pinned BM25 and regex variants and `defer_loading`. |
+| Programmatic tool calling | Supply `CodeExecutionTool` and configure matching `AllowCodeExecution` for compatible client tools. Use the model-supported version of the tool and preserve its caller and container on continuation. |
+| Token counting and batches | The count projection drops generation controls and keeps model, messages, system, cache, schema, thinking, speed and tools. Batches embed the synchronous body and use its validation. The fixtures capture both projections and reject removed sampling in batch params on the current version. |
+| JSON migration | `MessageRequest` decodes supported serialized requests and preserves tagged input and tool objects. Use `VersionedBlock` and `VersionedTool` for provider extensions. |
+
+See [mid-conversation system messages](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages), [tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool), [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), and [fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback).
+
+## Response and continuation evidence
+
+| Capability | Representation and fixture |
+|---|---|
+| Stop evidence | `ModelContextWindowExceeded` and `Refusal` are distinct stop reasons. `StopDetails` retains optional category, explanation and recommended model with an open unknown variant. `unaryEvidence` and `advancedEvidence` exercise create and SSE, and batch success uses the same unary decoder. |
+| Billing evidence | `UsageEvidence` includes geography, service tier, speed, output token breakdown, server-tool counters and iterations. `applyUsageUpdate` applies cumulative deltas without clearing missing values. `advancedEvidence` checks an explicit zero and retains unknown server-tool fields and iteration metadata. |
+| Programmatic continuation | `continueMessage` reuses the response container and carries ordered server calls, tool search references, code execution results and the programmatic caller into the next request. `advancedContinuation` verifies the exact second POST on `2026-10-21`. |
+| Fallback continuation | Send the original model, tool configuration and `server-side-fallback-2026-07-01`. `fallbackContinuation` shows the marker stays in place. The helper retains text and paired server-tool work before a mid-stream fallback, and discards pre-handoff thinking and client calls. |
+| Opaque response evidence | `responseJSON`, `blockJSON` and `eventJSON` keep the received provider objects. The documented continuation helper omits unknown block tags. Use `assistantContinuation` or `VersionedBlock` with a provider contract that admits an extension. |
+| Error categories | `apiErrorCategory` maps provider error tags to an open enumeration. HTTP status, transport, stream and JSON decode failures keep their existing `ClientError` alternatives. |
+
+The documented tool-search replay includes its result and references. Documented code execution replay can include a completed tool result. The programmatic continuation fixture preserves both, alongside the pending call and container. [Tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool), [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), [fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback).
+
+For an eligible model, combine the programmatic caller with deferred tool search.
+Keep the same tool list on later requests and pass the result of `continueMessage`
+to `createMessage` with the original client and request options.
+
+```haskell
+import Claude.Messages
+import Data.Aeson (Value (String))
+import Data.Aeson.KeyMap qualified as KeyMap
+
+lookupFeatures :: MessageFeatures
+lookupFeatures =
+  defaultMessageFeatures
+    { tools =
+        [ CodeExecutionTool CodeExecution20260120 Nothing,
+          ToolSearchTool BM25Search20251119 Nothing,
+          ConfiguredTool
+            (ClientTool "lookup" (Just "Look up a catalog entry") schema Nothing Nothing)
+            (ToolLoading (Just True) (Just [AllowDirect, AllowCodeExecution CodeExecution20260120]))
+        ]
+    }
+  where
+    schema = KeyMap.singleton "type" (String "object")
+```
+
+For unary prompt cache pre-warming, use `cacheOnly` as the output limit and
+copy the prompt and cache settings from the generation request. The
+`cachePrewarm` fixture verifies a zero-token unary body and pre-dispatch
+rejection of the same limit for streams and batches. [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
diff --git a/example/Main.hs b/example/Main.hs
new file mode 100644
--- /dev/null
+++ b/example/Main.hs
@@ -0,0 +1,18 @@
+module Main (main) where
+
+import Claude.Client
+import Claude.Messages
+import Data.ByteString.Char8 qualified as BS
+import Data.List.NonEmpty (NonEmpty (..))
+import System.Environment (getEnv)
+
+main :: IO ()
+main = do
+  key <- BS.pack <$> getEnv "ANTHROPIC_API_KEY"
+  client <- newClient (defaultClientConfig key) >>= either (fail . show) pure
+  limit <- maybe (fail "Expected a positive output limit") pure (maxTokens 256)
+  let prompt = Message User (InputText "Name three colors." :| [])
+      request = MessageRequest (Conversation "claude-sonnet-4-6" (prompt :| []) Nothing defaultMessageFeatures) limit []
+  createMessage client defaultRequestOptions request >>= \case
+    Left err -> fail (show err)
+    Right (Response _ result) -> print result
diff --git a/src/Claude/Batches.hs b/src/Claude/Batches.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Batches.hs
@@ -0,0 +1,252 @@
+-- | Asynchronous Message Batches and scoped JSON Lines result consumption.
+module Claude.Batches
+  ( BatchId,
+    batchId,
+    batchIdText,
+    CustomId,
+    mkCustomId,
+    customIdText,
+    BatchItem (..),
+    Batch (..),
+    ProcessingStatus (..),
+    RequestCounts (..),
+    BatchPage (..),
+    BatchCursor (..),
+    BatchListOptions (..),
+    BatchResult (..),
+    BatchOutcome (..),
+    createBatch,
+    retrieveBatch,
+    listBatches,
+    cancelBatch,
+    consumeBatchResults,
+  )
+where
+
+import Claude.Client
+import Claude.Internal.Http (decodeResponse, jsonRequest, redactApiError, runRequest)
+import Claude.Internal.Request qualified as Request
+import Claude.Messages (MessageRequest, MessageResponse)
+import Control.Lens ((^.))
+import Control.Monad.IO.Class (liftIO)
+import Control.Monad.Trans.Except (throwE)
+import Data.Aeson (FromJSON (..), ToJSON (..), object, withObject, withText, (.:), (.:?), (.=))
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.ByteString.Char8 qualified as BSC
+import Data.ByteString.Lazy qualified as LBS
+import Data.Char (isAlphaNum, isAscii)
+import Data.Generics.Labels ()
+import Data.List.NonEmpty (NonEmpty)
+import Data.List.NonEmpty qualified as NonEmpty
+import Data.Set qualified as Set
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Data.Text.Encoding (encodeUtf8)
+import Data.Time (UTCTime)
+import GHC.Generics (Generic)
+import Network.HTTP.Types (Query)
+import Numeric.Natural (Natural)
+
+newtype BatchId = BatchId Text
+  deriving stock (Eq, Ord, Show)
+
+batchId :: Text -> Maybe BatchId
+batchId text
+  | validId text = Just (BatchId text)
+  | otherwise = Nothing
+
+batchIdText :: BatchId -> Text
+batchIdText (BatchId text) = text
+
+instance FromJSON BatchId where
+  parseJSON = withText "batch ID" $ maybe (fail "invalid batch ID") pure . batchId
+
+newtype CustomId = CustomId Text
+  deriving stock (Eq, Ord, Show)
+  deriving newtype (ToJSON)
+
+mkCustomId :: Text -> Maybe CustomId
+mkCustomId text
+  | validId text && Text.length text <= 64 = Just (CustomId text)
+  | otherwise = Nothing
+
+customIdText :: CustomId -> Text
+customIdText (CustomId text) = text
+
+instance FromJSON CustomId where
+  parseJSON = withText "custom ID" $ maybe (fail "invalid custom ID") pure . mkCustomId
+
+validId :: Text -> Bool
+validId text =
+  not (Text.null text) && Text.all (\c -> isAscii c && (isAlphaNum c || c == '-' || c == '_')) text
+
+data BatchItem = BatchItem
+  { customId :: !CustomId,
+    params :: !MessageRequest
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance ToJSON BatchItem where
+  toJSON item = object ["custom_id" .= (item ^. #customId), "params" .= (item ^. #params)]
+
+data ProcessingStatus = InProgress | Canceling | Ended | UnknownProcessingStatus !Text
+  deriving stock (Eq, Show)
+
+instance FromJSON ProcessingStatus where
+  parseJSON =
+    withText "processing_status" $
+      pure . \case
+        "in_progress" -> InProgress
+        "canceling" -> Canceling
+        "ended" -> Ended
+        other -> UnknownProcessingStatus other
+
+data RequestCounts = RequestCounts
+  { processing :: !Natural,
+    succeeded :: !Natural,
+    errored :: !Natural,
+    canceled :: !Natural,
+    expired :: !Natural
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON RequestCounts where
+  parseJSON = withObject "batch request counts" $ \o ->
+    RequestCounts <$> o .: "processing" <*> o .: "succeeded" <*> o .: "errored" <*> o .: "canceled" <*> o .: "expired"
+
+data Batch = Batch
+  { id :: !BatchId,
+    processingStatus :: !ProcessingStatus,
+    requestCounts :: !RequestCounts,
+    createdAt :: !UTCTime,
+    expiresAt :: !UTCTime,
+    endedAt :: !(Maybe UTCTime),
+    cancelInitiatedAt :: !(Maybe UTCTime),
+    archivedAt :: !(Maybe UTCTime),
+    resultsUrl :: !(Maybe Text)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON Batch where
+  parseJSON = withObject "batch" $ \o ->
+    Batch
+      <$> o .: "id"
+      <*> o .: "processing_status"
+      <*> o .: "request_counts"
+      <*> o .: "created_at"
+      <*> o .: "expires_at"
+      <*> o .:? "ended_at"
+      <*> o .:? "cancel_initiated_at"
+      <*> o .:? "archived_at"
+      <*> o .:? "results_url"
+
+data BatchPage = BatchPage
+  { batches :: ![Batch],
+    firstId :: !(Maybe BatchId),
+    lastId :: !(Maybe BatchId),
+    hasMore :: !Bool
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON BatchPage where
+  parseJSON = withObject "batch page" $ \o ->
+    BatchPage <$> o .: "data" <*> o .:? "first_id" <*> o .:? "last_id" <*> o .: "has_more"
+
+data BatchCursor = After !BatchId | Before !BatchId
+  deriving stock (Eq, Show)
+
+data BatchListOptions = BatchListOptions
+  { cursor :: !(Maybe BatchCursor),
+    limit :: !(Maybe Natural)
+  }
+  deriving stock (Eq, Show, Generic)
+
+data BatchResult = BatchResult
+  { customId :: !CustomId,
+    outcome :: !BatchOutcome
+  }
+  deriving stock (Eq, Generic)
+
+data BatchOutcome
+  = BatchSucceeded !MessageResponse
+  | BatchErrored !ApiError
+  | BatchCanceled
+  | BatchExpired
+  deriving stock (Eq)
+
+instance FromJSON BatchResult where
+  parseJSON = withObject "batch result line" $ \o ->
+    BatchResult <$> o .: "custom_id" <*> o .: "result"
+
+instance FromJSON BatchOutcome where
+  parseJSON = withObject "batch outcome" $ \o ->
+    o .: "type" >>= \case
+      "succeeded" -> BatchSucceeded <$> o .: "message"
+      "errored" -> do
+        envelope <- o .: "error"
+        BatchErrored <$> withObject "error envelope" (.: "error") envelope
+      "canceled" -> pure BatchCanceled
+      "expired" -> pure BatchExpired
+      (_ :: Text) -> fail "unknown batch outcome"
+
+batchRoot :: ByteString
+batchRoot = "/v1/messages/batches"
+
+batchRoute :: BatchId -> ByteString
+batchRoute ident = batchRoot <> "/" <> encodeUtf8 (batchIdText ident)
+
+createBatch :: Client -> RequestOptions -> NonEmpty BatchItem -> IO (Either ClientError (Response Batch))
+createBatch client options items
+  | Set.size ids /= NonEmpty.length items = pure (Left (InvalidRequest "Batch custom IDs must be unique"))
+  | otherwise = case traverse (Request.validateMessages client Request.Batch . toJSON . (^. #params)) items of
+      Left err -> pure (Left err)
+      Right _ -> jsonRequest client "POST" batchRoot [] options (Just (object ["requests" .= items]))
+  where
+    ids = Set.fromList (map (^. #customId) (NonEmpty.toList items))
+
+retrieveBatch :: Client -> RequestOptions -> BatchId -> IO (Either ClientError (Response Batch))
+retrieveBatch client options ident = jsonRequest client "GET" (batchRoute ident) [] options Nothing
+
+listBatches :: Client -> RequestOptions -> BatchListOptions -> IO (Either ClientError (Response BatchPage))
+listBatches client options page
+  | any (\n -> n < 1 || n > 1000) (page ^. #limit) = pure (Left (InvalidRequest "Batch list limit must be between 1 and 1000"))
+  | otherwise = jsonRequest client "GET" batchRoot query options Nothing
+  where
+    query :: Query
+    query = case page ^. #cursor of
+      Just (After ident) -> ("after_id", Just (encodeUtf8 (batchIdText ident))) : limits
+      Just (Before ident) -> ("before_id", Just (encodeUtf8 (batchIdText ident))) : limits
+      Nothing -> limits
+    limits = [("limit", Just (BSC.pack (show n))) | Just n <- [page ^. #limit]]
+
+cancelBatch :: Client -> RequestOptions -> BatchId -> IO (Either ClientError (Response Batch))
+cancelBatch client options ident = jsonRequest client "POST" (batchRoute ident <> "/cancel") [] options Nothing
+
+-- | Deliver each result before reading the next line. Correlate by custom ID.
+-- An HTTP or decoding failure may follow already delivered results.
+-- The documented endpoint is constructed from the batch ID on the client origin.
+consumeBatchResults ::
+  Client ->
+  RequestOptions ->
+  BatchId ->
+  (BatchResult -> IO ()) ->
+  IO (Either ClientError (Response ()))
+consumeBatchResults client options ident consume =
+  runRequest client "GET" (batchRoute ident <> "/results") [] options "application/binary" Nothing $ \meta readBody -> do
+    let deliver fragments = do
+          result <- either throwE pure (decodeResponse meta (LBS.fromChunks (reverse fragments)))
+          liftIO $ consume $ case result of
+            BatchResult requestId_ (BatchErrored err) -> BatchResult requestId_ (BatchErrored (redactApiError client err))
+            other -> other
+        feed fragments chunk
+          | BS.null chunk = do
+              next <- readBody
+              if BS.null next
+                then if null fragments then pure () else deliver fragments
+                else feed fragments next
+          | otherwise = case BS.break (== 10) chunk of
+              (prefix, rest)
+                | BS.null rest -> feed (prefix : fragments) BS.empty
+                | otherwise -> deliver (prefix : fragments) >> feed [] (BS.drop 1 rest)
+    feed [] BS.empty
diff --git a/src/Claude/Client.hs b/src/Claude/Client.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Client.hs
@@ -0,0 +1,22 @@
+-- | Configuration and results shared by the Claude HTTP endpoints.
+module Claude.Client
+  ( Client,
+    ClientPool,
+    newClientPool,
+    newClientWithPool,
+    ClientConfig (..),
+    defaultClientConfig,
+    newClient,
+    RequestOptions (..),
+    defaultRequestOptions,
+    Response (..),
+    ResponseMetadata (..),
+    ApiError (..),
+    ApiErrorCategory (..),
+    apiErrorCategory,
+    ClientError (..),
+    TransportFailure (..),
+  )
+where
+
+import Claude.Internal.Http
diff --git a/src/Claude/Internal/Http.hs b/src/Claude/Internal/Http.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Internal/Http.hs
@@ -0,0 +1,302 @@
+module Claude.Internal.Http
+  ( Client,
+    ClientPool,
+    newClientPool,
+    newClientWithPool,
+    ClientConfig (..),
+    defaultClientConfig,
+    newClient,
+    RequestOptions (..),
+    defaultRequestOptions,
+    Response (..),
+    ResponseMetadata (..),
+    ApiError (..),
+    ApiErrorCategory (..),
+    apiErrorCategory,
+    ClientError (..),
+    TransportFailure (..),
+    BodyReader,
+    runRequest,
+    jsonRequest,
+    decodeResponse,
+    redactApiError,
+    clientApiVersion,
+  )
+where
+
+import Control.Exception (bracket, try)
+import Control.Lens ((^.))
+import Control.Monad.Trans.Except (ExceptT (..), runExceptT, throwE)
+import Data.Aeson (FromJSON (..), Value, eitherDecode, encode, withObject, (.:))
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.ByteString.Lazy qualified as LBS
+import Data.Generics.Labels ()
+import Data.Maybe (isJust)
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Data.Text.Encoding (decodeUtf8Lenient)
+import GHC.Generics (Generic)
+import Network.HTTP.Client qualified as HTTP
+import Network.HTTP.Client.TLS (tlsManagerSettings)
+import Network.HTTP.Types (HeaderName, Method, Query, RequestHeaders, hAccept, hContentType, renderQuery, statusCode)
+
+data Client = Client !HTTP.Manager !HTTP.Request
+
+-- | A connection pool that can be shared by clients with different credentials.
+newtype ClientPool = ClientPool HTTP.Manager
+
+newClientPool :: IO ClientPool
+newClientPool = ClientPool <$> HTTP.newManager tlsManagerSettings {HTTP.managerRetryableException = const False}
+
+data ClientConfig = ClientConfig
+  { apiKey :: !ByteString,
+    endpoint :: !String,
+    timeoutMicros :: !(Maybe Int),
+    apiVersion :: !(Maybe ByteString)
+  }
+  deriving stock (Generic)
+
+defaultClientConfig :: ByteString -> ClientConfig
+defaultClientConfig key = ClientConfig key "https://api.anthropic.com" (Just 60000000) (Just "2026-10-21")
+
+newClient :: ClientConfig -> IO (Either ClientError Client)
+newClient config = newClientPool >>= flip newClientWithPool config
+
+newClientWithPool :: ClientPool -> ClientConfig -> IO (Either ClientError Client)
+newClientWithPool (ClientPool manager) config
+  | BS.null (config ^. #apiKey) = pure (Left (InvalidRequest "An API key is required"))
+  | maybe False (<= 0) (config ^. #timeoutMicros) = pure (Left (InvalidRequest "The response timeout must be positive"))
+  | otherwise = do
+      parsed <- try (HTTP.parseRequest (config ^. #endpoint))
+      case parsed of
+        Left (_ :: HTTP.HttpException) -> pure (Left (InvalidRequest "Invalid HTTP endpoint"))
+        Right base
+          | not (BS.null (HTTP.queryString base)) || isJust (lookup "authorization" (HTTP.requestHeaders base)) ->
+              pure (Left (InvalidRequest "The endpoint must use a host and optional path prefix"))
+          | otherwise ->
+              pure . Right . Client manager $
+                base
+                  { HTTP.redirectCount = 0,
+                    HTTP.checkResponse = \_ _ -> pure (),
+                    HTTP.cookieJar = Nothing,
+                    HTTP.responseTimeout = maybe HTTP.responseTimeoutNone HTTP.responseTimeoutMicro (config ^. #timeoutMicros),
+                    HTTP.requestHeaders =
+                      [("x-api-key", config ^. #apiKey)]
+                        <> [("anthropic-version", version) | Just version <- [config ^. #apiVersion]]
+                  }
+
+data RequestOptions = RequestOptions
+  { betaFeatures :: ![ByteString],
+    extraHeaders :: !RequestHeaders
+  }
+  deriving stock (Generic)
+
+defaultRequestOptions :: RequestOptions
+defaultRequestOptions = RequestOptions [] []
+
+data ResponseMetadata = ResponseMetadata
+  { requestId :: !(Maybe ByteString),
+    retryAfter :: !(Maybe ByteString),
+    status :: !Int,
+    gatewayRequestId :: !(Maybe ByteString),
+    cloudflareRay :: !(Maybe ByteString),
+    responseDate :: !(Maybe ByteString)
+  }
+  deriving stock (Eq, Generic)
+
+data Response a = Response
+  { metadata :: !ResponseMetadata,
+    value :: !a
+  }
+  deriving stock (Eq, Generic)
+
+data ApiError = ApiError
+  { errorType :: !Text,
+    message :: !Text
+  }
+  deriving stock (Eq, Generic)
+
+instance FromJSON ApiError where
+  parseJSON = withObject "API error" $ \o -> ApiError <$> o .: "type" <*> o .: "message"
+
+data ApiErrorCategory
+  = InvalidRequestError
+  | AuthenticationError
+  | PermissionError
+  | NotFoundError
+  | RequestTooLargeError
+  | RateLimitError
+  | InternalApiError
+  | OverloadedError
+  | UnknownApiError !Text
+  deriving stock (Eq, Show)
+
+apiErrorCategory :: ApiError -> ApiErrorCategory
+apiErrorCategory (ApiError kind _) = case kind of
+  "invalid_request_error" -> InvalidRequestError
+  "authentication_error" -> AuthenticationError
+  "permission_error" -> PermissionError
+  "not_found_error" -> NotFoundError
+  "request_too_large" -> RequestTooLargeError
+  "rate_limit_error" -> RateLimitError
+  "api_error" -> InternalApiError
+  "overloaded_error" -> OverloadedError
+  other -> UnknownApiError other
+
+data TransportFailure = ConnectTimeout | ReadTimeout | ConnectionFailed | Disconnected | HttpFailure
+  deriving stock (Eq, Show)
+
+data ClientError
+  = InvalidRequest !Text
+  | TransportError !(Maybe ResponseMetadata) !TransportFailure
+  | ApiStatusError !ResponseMetadata !(Maybe ApiError) !Text
+  | DecodeError !ResponseMetadata !Text
+  | StreamApiError !ResponseMetadata !ApiError
+  deriving stock (Eq)
+
+-- Keep request headers, provider-controlled values and decode input out of logs.
+instance Show ClientError where
+  show = \case
+    InvalidRequest _ -> "InvalidRequest"
+    TransportError _ kind -> "TransportError " <> show kind
+    ApiStatusError meta _ _ -> "ApiStatusError " <> show (meta ^. #status)
+    DecodeError meta _ -> "DecodeError (HTTP " <> show (meta ^. #status) <> ")"
+    StreamApiError _ _ -> "StreamApiError"
+
+type BodyReader = ExceptT ClientError IO ByteString
+
+runRequest ::
+  Client ->
+  Method ->
+  ByteString ->
+  Query ->
+  RequestOptions ->
+  ByteString ->
+  Maybe Value ->
+  (ResponseMetadata -> BodyReader -> ExceptT ClientError IO a) ->
+  IO (Either ClientError (Response a))
+runRequest client@(Client manager base) method route query options accept body consume
+  | any ((`elem` reservedHeaders) . fst) (options ^. #extraHeaders) =
+      pure (Left (InvalidRequest "A request header is owned by the client"))
+  | otherwise = bracket (try (HTTP.responseOpen request manager)) close $ \case
+      Left exc -> pure (Left (TransportError Nothing (classify exc)))
+      Right response -> runExceptT $ do
+        let headers = HTTP.responseHeaders response
+            meta =
+              ResponseMetadata
+                (lookup "request-id" headers)
+                (lookup "retry-after" headers)
+                (statusCode (HTTP.responseStatus response))
+                (lookup "x-request-id" headers)
+                (lookup "cf-ray" headers)
+                (lookup "date" headers)
+            readBody = ExceptT $ either (Left . TransportError (Just meta) . classify) Right <$> try (HTTP.brRead (HTTP.responseBody response))
+        if meta ^. #status >= 200 && meta ^. #status < 300
+          then Response meta <$> consume meta readBody
+          else do
+            -- The status and request ID remain available if the peer cuts off the error body.
+            decoded <- ExceptT $ Right <$> runExceptT (collectErrorBody readBody)
+            let bodyBytes = either (const LBS.empty) id decoded
+            throwE (ApiStatusError meta (apiErrorFromBody client bodyBytes) (redactText client (decodeUtf8Lenient (LBS.toStrict bodyBytes))))
+  where
+    request =
+      base
+        { HTTP.method = method,
+          HTTP.path = BS.dropWhileEnd (== 47) (HTTP.path base) <> route,
+          HTTP.queryString = renderQuery True query,
+          HTTP.requestHeaders =
+            HTTP.requestHeaders base
+              <> [(hAccept, accept)]
+              <> [(hContentType, "application/json") | isJust body]
+              <> [("anthropic-beta", BS.intercalate "," betas) | let betas = options ^. #betaFeatures, not (null betas)]
+              <> options ^. #extraHeaders,
+          HTTP.requestBody = maybe (HTTP.RequestBodyBS "") (HTTP.RequestBodyLBS . encode) body
+        }
+    close = either (const (pure ())) HTTP.responseClose
+
+reservedHeaders :: [HeaderName]
+reservedHeaders =
+  [ "x-api-key",
+    "authorization",
+    "proxy-authorization",
+    "anthropic-version",
+    "anthropic-beta",
+    "host",
+    "content-length",
+    "transfer-encoding",
+    "connection",
+    "expect",
+    "upgrade",
+    "te",
+    "trailer",
+    hAccept,
+    hContentType
+  ]
+
+classify :: HTTP.HttpException -> TransportFailure
+classify (HTTP.HttpExceptionRequest _ exc) = case exc of
+  HTTP.ConnectionTimeout -> ConnectTimeout
+  HTTP.ResponseTimeout -> ReadTimeout
+  HTTP.ConnectionFailure _ -> ConnectionFailed
+  HTTP.NoResponseDataReceived -> Disconnected
+  HTTP.ConnectionClosed -> Disconnected
+  HTTP.ResponseBodyTooShort _ _ -> Disconnected
+  _ -> HttpFailure
+classify _ = HttpFailure
+
+clientApiVersion :: Client -> Maybe ByteString
+clientApiVersion (Client _ base) = lookup "anthropic-version" (HTTP.requestHeaders base)
+
+redactApiError :: Client -> ApiError -> ApiError
+redactApiError client (ApiError kind detail) = ApiError (redactText client kind) (redactText client detail)
+
+redactText :: Client -> Text -> Text
+redactText (Client _ base) text =
+  if Text.null key then text else Text.replace key "[redacted]" text
+  where
+    key = maybe "" decodeUtf8Lenient (lookup "x-api-key" (HTTP.requestHeaders base))
+
+apiErrorFromBody :: Client -> LBS.ByteString -> Maybe ApiError
+apiErrorFromBody client body = do
+  ErrorEnvelope err <- either (const Nothing) Just (eitherDecode body)
+  pure (redactApiError client err)
+
+newtype ErrorEnvelope = ErrorEnvelope ApiError
+
+instance FromJSON ErrorEnvelope where
+  parseJSON = withObject "error envelope" $ \o -> ErrorEnvelope <$> o .: "error"
+
+collectBody :: BodyReader -> ExceptT ClientError IO LBS.ByteString
+collectBody readBody = go []
+  where
+    go chunks = do
+      chunk <- readBody
+      if BS.null chunk then pure (LBS.fromChunks (reverse chunks)) else go (chunk : chunks)
+
+collectErrorBody :: BodyReader -> ExceptT ClientError IO LBS.ByteString
+collectErrorBody readBody = go (65536 :: Int) []
+  where
+    go remaining chunks
+      | remaining == 0 = pure (LBS.fromChunks (reverse chunks))
+      | otherwise = do
+          chunk <- BS.take remaining <$> readBody
+          if BS.null chunk
+            then pure (LBS.fromChunks (reverse chunks))
+            else go (remaining - BS.length chunk) (chunk : chunks)
+
+decodeResponse :: (FromJSON a) => ResponseMetadata -> LBS.ByteString -> Either ClientError a
+decodeResponse meta = either (Left . DecodeError meta . Text.pack) Right . eitherDecode
+
+jsonRequest ::
+  (FromJSON a) =>
+  Client ->
+  Method ->
+  ByteString ->
+  Query ->
+  RequestOptions ->
+  Maybe Value ->
+  IO (Either ClientError (Response a))
+jsonRequest client method route query options body =
+  runRequest client method route query options "application/json" body $ \meta readBody ->
+    collectBody readBody >>= either throwE pure . decodeResponse meta
diff --git a/src/Claude/Internal/Request.hs b/src/Claude/Internal/Request.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Internal/Request.hs
@@ -0,0 +1,54 @@
+-- | Validate the envelope shared by typed requests and the streaming bridge.
+module Claude.Internal.Request (MessagesEndpoint (..), validateMessages) where
+
+import Claude.Internal.Http (Client, ClientError (..), clientApiVersion)
+import Control.Monad (when)
+import Data.Aeson (Object, Value (..), withObject, (.:))
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.Aeson.Types (Parser, parseEither)
+import Data.Foldable (traverse_)
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Numeric.Natural (Natural)
+
+data MessagesEndpoint = Create | Stream | Count | Batch
+  deriving stock (Eq)
+
+validateMessages :: Client -> MessagesEndpoint -> Value -> Either ClientError Object
+validateMessages client endpoint =
+  either (Left . InvalidRequest . Text.pack) Right . parseEither (withObject "Messages request" validate)
+  where
+    current = clientApiVersion client == Just "2026-10-21"
+    validate fields = do
+      model <- fields .: "model"
+      when (Text.null model) (fail "Messages require a model ID")
+      when (endpoint /= Count) $ do
+        limit <- fields .: "max_tokens"
+        when ((limit :: Natural) == 0 && endpoint /= Create) (fail "Streaming and batches require positive max_tokens")
+      history <- fields .: "messages" :: Parser [Value]
+      when current $ do
+        when (null history) (fail "Messages require a nonempty conversation")
+        case filter (`KeyMap.member` fields) ["temperature", "top_p", "top_k"] of
+          [] -> pure ()
+          removed -> fail ("2026-10-21 removed sampling fields: " <> show removed)
+        traverse_ (withObject "history message" validateTurn) history
+      pure fields
+
+validateTurn :: Object -> Parser ()
+validateTurn turn = do
+  role <- turn .: "role" :: Parser Text
+  content <- turn .: "content" :: Parser Value
+  case content of
+    Array blocks -> traverse_ (withObject "history block" (validateBlock role)) blocks
+    String _ -> pure ()
+    _ -> fail "Message content must be a string or array"
+
+validateBlock :: Text -> Object -> Parser ()
+validateBlock role block = do
+  tag <- block .: "type" :: Parser Text
+  when (role == "assistant" && tag == "document") $
+    fail "2026-10-21 requires documents in user messages"
+  when (role == "user" && tag == "text") $
+    case KeyMap.lookup "citations" block of
+      Just (Array citations) | not (null citations) -> fail "2026-10-21 disallows citations in user messages"
+      _ -> pure ()
diff --git a/src/Claude/Internal/Sse.hs b/src/Claude/Internal/Sse.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Internal/Sse.hs
@@ -0,0 +1,58 @@
+-- | Incremental, byte-oriented SSE framing.
+module Claude.Internal.Sse (foldEvents) where
+
+import Claude.Internal.Http (BodyReader, ClientError)
+import Control.Monad.Trans.Except (ExceptT)
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.ByteString.Char8 qualified as BSC
+import Data.Char (isSpace)
+
+-- | A handler may finish early with a value. A trailing incomplete event
+-- never dispatches. The consumer decides what EOF means for the protocol.
+foldEvents ::
+  BodyReader ->
+  (Maybe ByteString -> ByteString -> ExceptT ClientError IO (Maybe a)) ->
+  ExceptT ClientError IO (Maybe a)
+foldEvents readBody handle = feed initialFrame [] BS.empty
+  where
+    feed frame pieces chunk
+      | BS.null chunk = do
+          next <- readBody
+          if BS.null next then pure Nothing else feed frame pieces next
+      | otherwise = case BS.break (== 10) chunk of
+          (prefix, rest)
+            | BS.null rest -> feed frame (prefix : pieces) BS.empty
+            | otherwise -> do
+                let line = BS.concat (reverse (prefix : pieces))
+                result <- acceptLine frame (BS.dropWhileEnd (== 13) line)
+                case result of
+                  Left done -> pure (Just done)
+                  Right updated -> feed updated [] (BS.drop 1 rest)
+    acceptLine frame line
+      | BS.null line = case frame of
+          Frame _ [] -> pure (Right initialFrame)
+          Frame name parts ->
+            let payload = BS.intercalate "\n" (reverse parts)
+             in if BSC.all isSpace payload
+                  then pure (Right initialFrame)
+                  else do
+                    result <- handle name payload
+                    pure (maybe (Right initialFrame) Left result)
+      | otherwise = pure (Right (addField frame line))
+
+data Frame = Frame !(Maybe ByteString) ![ByteString]
+
+initialFrame :: Frame
+initialFrame = Frame Nothing []
+
+addField :: Frame -> ByteString -> Frame
+addField frame@(Frame name parts) line =
+  case BS.break (== 58) line of
+    ("event", suffix) -> Frame (Just (fieldValue suffix)) parts
+    ("data", suffix) -> Frame name (fieldValue suffix : parts)
+    _ -> frame
+  where
+    fieldValue suffix = case BS.drop 1 suffix of
+      value | Just (32, rest) <- BS.uncons value -> rest
+      value -> value
diff --git a/src/Claude/Messages.hs b/src/Claude/Messages.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Messages.hs
@@ -0,0 +1,444 @@
+-- | Synchronous Messages and input token counting.
+module Claude.Messages
+  ( MessageRequest (..),
+    withRequestControls,
+    messageRequestControls,
+    CountRequest (..),
+    Conversation (..),
+    conversationHistory,
+    withConversationHistory,
+    Message (..),
+    Role (..),
+    InputBlock (..),
+    ImageSource (..),
+    module Claude.Messages.Features,
+    assistantContinuation,
+    continueMessage,
+    responseText,
+    MessageResponse (..),
+    ContainerInfo (..),
+    StopDetails (..),
+    UsageEvidence (..),
+    OutputTokenDetails (..),
+    ServerToolCounts (..),
+    UsageIteration (..),
+    StopReason (..),
+    Usage (..),
+    TokenCount (..),
+    MaxTokens,
+    maxTokens,
+    maxTokensValue,
+    cacheOnly,
+    createMessage,
+    countTokens,
+  )
+where
+
+import Claude.Client (Client, ClientError, RequestOptions, Response)
+import Claude.Internal.Http (jsonRequest)
+import Claude.Internal.Request (MessagesEndpoint (Count, Create), validateMessages)
+import Claude.Messages.Features
+import Claude.Messages.Usage (OutputTokenDetails (..), ServerToolCounts (..), UsageEvidence (..), UsageIteration (..))
+import Control.Applicative ((<|>))
+import Control.Lens ((&), (.~), (^.))
+import Data.Aeson (FromJSON (..), Key, Object, ToJSON (..), Value (..), object, withObject, withText, (.!=), (.:), (.:?), (.=))
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.Aeson.Types (Pair, Parser)
+import Data.Generics.Labels ()
+import Data.List.NonEmpty (NonEmpty)
+import Data.List.NonEmpty qualified as NonEmpty
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Data.Time (UTCTime)
+import GHC.Generics (Generic)
+import Numeric.Natural (Natural)
+
+data Role = User | Assistant | System
+  deriving stock (Eq, Show)
+
+instance ToJSON Role where
+  toJSON User = "user"
+  toJSON Assistant = "assistant"
+  toJSON System = "system"
+
+instance FromJSON Role where
+  parseJSON = withText "role" $ \case
+    "user" -> pure User
+    "assistant" -> pure Assistant
+    "system" -> pure System
+    _ -> fail "expected user, assistant or system"
+
+data ImageSource = Base64Image !Text !Text | ImageUrl !Text
+  deriving stock (Eq, Show)
+
+instance ToJSON ImageSource where
+  toJSON (Base64Image media bytes) = object ["type" .= ("base64" :: Text), "media_type" .= media, "data" .= bytes]
+  toJSON (ImageUrl url) = object ["type" .= ("url" :: Text), "url" .= url]
+
+data InputBlock
+  = InputText !Text
+  | InputImage !ImageSource
+  | InputDocument !Document
+  | InputToolResult !ToolResult
+  | CachedText !Text !CacheControl
+  | CachedImage !ImageSource !CacheControl
+  | InputToolUse !Text !Text !Value !(Maybe ToolCaller)
+  | ToolAddition !ToolChangeReference !(Maybe CacheControl)
+  | ToolRemoval !ToolChangeReference !(Maybe CacheControl)
+  | InputFallback !FallbackMarker
+  | ReplayBlock !OutputBlock
+  | VersionedBlock !Object
+  deriving stock (Eq, Show)
+
+instance ToJSON InputBlock where
+  toJSON = \case
+    InputText body -> object ["type" .= ("text" :: Text), "text" .= body]
+    InputImage source -> object ["type" .= ("image" :: Text), "source" .= source]
+    InputDocument doc -> toJSON doc
+    InputToolResult result -> toJSON result
+    CachedText body cache -> object ["type" .= ("text" :: Text), "text" .= body, "cache_control" .= cache]
+    CachedImage source cache -> object ["type" .= ("image" :: Text), "source" .= source, "cache_control" .= cache]
+    InputToolUse ident name_ input caller ->
+      object (["type" .= ("tool_use" :: Text), "id" .= ident, "name" .= name_, "input" .= input] <> optional "caller" caller)
+    ToolAddition tool cache -> toolChange "tool_addition" tool cache
+    ToolRemoval tool cache -> toolChange "tool_removal" tool cache
+    InputFallback marker -> toJSON marker
+    ReplayBlock block -> blockJSON block
+    VersionedBlock block -> toJSON block
+    where
+      toolChange tag tool cache = object (["type" .= (tag :: Text), "tool" .= tool] <> optional "cache_control" cache)
+
+data Message
+  = Message
+      { role :: !Role,
+        content :: !(NonEmpty InputBlock)
+      }
+  | CachedMessage
+      { role :: !Role,
+        content :: !(NonEmpty InputBlock),
+        messageCacheControl :: !CacheControl
+      }
+  deriving stock (Eq, Show, Generic)
+
+instance ToJSON Message where
+  toJSON msg =
+    object
+      ( ["role" .= (msg ^. #role), "content" .= (msg ^. #content)] <> case msg of
+          CachedMessage _ _ cache -> ["cache_control" .= cache]
+          Message {} -> []
+      )
+
+instance FromJSON Message where
+  parseJSON = withObject "history message" $ \o -> do
+    sender <- o .: "role"
+    raw <- o .: "content"
+    let blocks = withObject "input block" (pure . VersionedBlock)
+    content_ <- (fmap (NonEmpty.singleton . InputText) (parseJSON raw)) <|> (parseJSON raw >>= traverse blocks)
+    cache <- o .:? "cache_control"
+    pure (maybe (Message sender content_) (CachedMessage sender content_) cache)
+
+data Conversation
+  = Conversation
+      { model :: !Text,
+        messages :: !(NonEmpty Message),
+        system :: !(Maybe SystemPrompt),
+        features :: !MessageFeatures
+      }
+  | EmptyConversation
+      { model :: !Text,
+        system :: !(Maybe SystemPrompt),
+        features :: !MessageFeatures
+      }
+  deriving stock (Eq, Show, Generic)
+
+-- | A total history accessor for both current and legacy conversations.
+conversationHistory :: Conversation -> [Message]
+conversationHistory (Conversation _ history _ _) = NonEmpty.toList history
+conversationHistory (EmptyConversation {}) = []
+
+withConversationHistory :: [Message] -> Conversation -> Conversation
+withConversationHistory history convo =
+  case NonEmpty.nonEmpty history of
+    Just turns -> Conversation (convo ^. #model) turns (convo ^. #system) (convo ^. #features)
+    Nothing -> EmptyConversation (convo ^. #model) (convo ^. #system) (convo ^. #features)
+
+newtype MaxTokens = MaxTokens Natural
+  deriving stock (Eq, Show)
+  deriving newtype (ToJSON)
+
+maxTokens :: Natural -> Maybe MaxTokens
+maxTokens 0 = Nothing
+maxTokens n = Just (MaxTokens n)
+
+maxTokensValue :: MaxTokens -> Natural
+maxTokensValue (MaxTokens value) = value
+
+-- | Populate the prompt cache without generating output in unary Messages.
+cacheOnly :: MaxTokens
+cacheOnly = MaxTokens 0
+
+data MessageRequest
+  = MessageRequest
+      { conversation :: !Conversation,
+        outputLimit :: !MaxTokens,
+        stopSequences :: ![Text]
+      }
+  | MessageRequestWithControls
+      { conversation :: !Conversation,
+        outputLimit :: !MaxTokens,
+        stopSequences :: ![Text],
+        requestControls :: !RequestControls
+      }
+  deriving stock (Eq, Show, Generic)
+
+withRequestControls :: RequestControls -> MessageRequest -> MessageRequest
+withRequestControls controls request =
+  MessageRequestWithControls (request ^. #conversation) (request ^. #outputLimit) (request ^. #stopSequences) controls
+
+messageRequestControls :: MessageRequest -> RequestControls
+messageRequestControls = \case
+  MessageRequestWithControls _ _ _ controls -> controls
+  MessageRequest {} -> defaultRequestControls
+
+newtype CountRequest = CountRequest Conversation
+  deriving stock (Eq, Show)
+
+conversationFields :: Conversation -> [Pair]
+conversationFields convo =
+  ["model" .= (convo ^. #model), "messages" .= conversationHistory convo]
+    <> optional "system" (convo ^. #system)
+    <> optional "output_config" (opts ^. #outputConfig)
+    <> optional "thinking" (opts ^. #thinking)
+    <> optional "cache_control" (opts ^. #cacheControl)
+    <> ["tools" .= offered | let offered = opts ^. #tools, not (null offered)]
+    <> optional "tool_choice" (opts ^. #toolChoice)
+    <> optional "speed" (opts ^. #speed)
+  where
+    opts = convo ^. #features
+
+optional :: (ToJSON a) => Key -> Maybe a -> [Pair]
+optional key = maybe [] (\item -> [key .= item])
+
+generationFields :: RequestControls -> [Pair]
+generationFields controls =
+  optional "temperature" (controls ^. #temperature)
+    <> optional "top_p" (controls ^. #topP)
+    <> optional "top_k" (controls ^. #topK)
+    <> optional "metadata" (controls ^. #metadata)
+    <> optional "container" (controls ^. #containerId)
+    <> optional "context_management" (fmap (\edits -> object ["edits" .= edits]) (controls ^. #contextManagement))
+    <> optional "inference_geo" (controls ^. #inferenceGeo)
+    <> optional "fallbacks" (controls ^. #fallbacks)
+
+instance ToJSON MessageRequest where
+  toJSON request =
+    object $
+      ["max_tokens" .= (request ^. #outputLimit)]
+        <> conversationFields (request ^. #conversation)
+        <> generationFields (messageRequestControls request)
+        <> ["stop_sequences" .= stops | let stops = request ^. #stopSequences, not (null stops)]
+
+instance ToJSON CountRequest where
+  toJSON (CountRequest convo) = object (conversationFields convo)
+
+parseConversation :: Object -> Parser Conversation
+parseConversation o = do
+  model_ <- o .: "model"
+  history <- o .: "messages"
+  system_ <- o .:? "system"
+  features_ <-
+    MessageFeatures
+      <$> o .:? "output_config"
+      <*> o .:? "thinking"
+      <*> o .:? "cache_control"
+      <*> (o .:? "tools" .!= [])
+      <*> o .:? "tool_choice"
+      <*> o .:? "speed"
+  pure $ case NonEmpty.nonEmpty history of
+    Just turns -> Conversation model_ turns system_ features_
+    Nothing -> EmptyConversation model_ system_ features_
+
+instance FromJSON CountRequest where
+  parseJSON = withObject "count request" (fmap CountRequest . parseConversation)
+
+instance FromJSON MessageRequest where
+  parseJSON = withObject "Messages request" $ \o -> do
+    convo <- parseConversation o
+    limit <- MaxTokens <$> o .: "max_tokens"
+    stops <- o .:? "stop_sequences" .!= []
+    context <- o .:? "context_management" >>= traverse (withObject "context management" (.: "edits"))
+    controls <-
+      RequestControls
+        <$> o .:? "temperature"
+        <*> o .:? "top_p"
+        <*> o .:? "top_k"
+        <*> o .:? "metadata"
+        <*> o .:? "container"
+        <*> pure context
+        <*> o .:? "inference_geo"
+        <*> o .:? "fallbacks"
+    let request = MessageRequest convo limit stops
+    pure (if controls == defaultRequestControls then request else withRequestControls controls request)
+
+data StopReason = EndTurn | MaxTokensReached | StopSequence | ToolUse | PauseTurn | Refusal | ModelContextWindowExceeded | UnknownStopReason !Text
+  deriving stock (Eq, Show)
+
+instance FromJSON StopReason where
+  parseJSON =
+    withText "stop_reason" $
+      pure . \case
+        "end_turn" -> EndTurn
+        "max_tokens" -> MaxTokensReached
+        "stop_sequence" -> StopSequence
+        "tool_use" -> ToolUse
+        "pause_turn" -> PauseTurn
+        "refusal" -> Refusal
+        "model_context_window_exceeded" -> ModelContextWindowExceeded
+        other -> UnknownStopReason other
+
+data Usage = Usage
+  { inputTokens :: !Natural,
+    outputTokens :: !Natural,
+    cacheCreationInputTokens :: !(Maybe Natural),
+    cacheReadInputTokens :: !(Maybe Natural),
+    cacheCreation :: !(Maybe Object),
+    serverToolUse :: !(Maybe Object),
+    usageEvidence :: !UsageEvidence
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON Usage where
+  parseJSON = withObject "usage" $ \o ->
+    Usage
+      <$> o .: "input_tokens"
+      <*> o .: "output_tokens"
+      <*> o .:? "cache_creation_input_tokens"
+      <*> o .:? "cache_read_input_tokens"
+      <*> o .:? "cache_creation"
+      <*> o .:? "server_tool_use"
+      <*> parseJSON (Object o)
+
+data MessageResponse = MessageResponse
+  { id :: !Text,
+    model :: !Text,
+    role :: !Role,
+    content :: ![OutputBlock],
+    stopReason :: !(Maybe StopReason),
+    stopSequence :: !(Maybe Text),
+    usage :: !Usage,
+    stopDetails :: !(Maybe StopDetails),
+    container :: !(Maybe ContainerInfo),
+    responseJSON :: !Object
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON MessageResponse where
+  parseJSON = withObject "message" $ \o ->
+    MessageResponse
+      <$> o .: "id"
+      <*> o .: "model"
+      <*> o .: "role"
+      <*> o .: "content"
+      <*> o .:? "stop_reason"
+      <*> o .:? "stop_sequence"
+      <*> o .: "usage"
+      <*> o .:? "stop_details"
+      <*> o .:? "container"
+      <*> pure o
+
+instance ToJSON MessageResponse where
+  toJSON = Object . responseJSON
+
+data StopDetails
+  = RefusalDetails
+      { category :: !(Maybe Text),
+        explanation :: !(Maybe Text),
+        recommendedModel :: !(Maybe Text)
+      }
+  | UnknownStopDetails !Text !Object
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON StopDetails where
+  parseJSON = withObject "stop details" $ \o ->
+    o .: "type" >>= \case
+      "refusal" -> RefusalDetails <$> o .:? "category" <*> o .:? "explanation" <*> o .:? "recommended_model"
+      tag -> pure (UnknownStopDetails tag o)
+
+data ContainerInfo = ContainerInfo
+  { containerIdentifier :: !Text,
+    expiresAt :: !UTCTime
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON ContainerInfo where
+  parseJSON = withObject "container" $ \o -> ContainerInfo <$> o .: "id" <*> o .: "expires_at"
+
+-- | Replay this history only against its originating provider and model.
+assistantContinuation :: MessageResponse -> Maybe Message
+assistantContinuation response = do
+  if response ^. #role == Assistant then pure () else Nothing
+  blocks <- NonEmpty.nonEmpty (response ^. #content)
+  pure (Message Assistant (fmap ReplayBlock blocks))
+
+-- | Append provider history and a user turn to the original request, reusing
+-- the returned container. Use only with the original provider and model
+-- configuration, including the original tools and fallback settings.
+continueMessage :: MessageRequest -> MessageResponse -> NonEmpty InputBlock -> Maybe MessageRequest
+continueMessage request response next = do
+  let original = request ^. #conversation
+      controls = messageRequestControls request
+      retained = replayableHistory (response ^. #content)
+  assistant <- assistantContinuation (response & #content .~ retained)
+  let history = conversationHistory original <> [assistant, Message User next]
+      updated = request {conversation = withConversationHistory history original}
+  pure $ case response ^. #container of
+    Nothing -> updated
+    Just info -> withRequestControls (controls {containerId = Just (containerIdentifier info)}) updated
+
+-- Before the last handoff the service accepts text and completed server calls.
+-- The marker itself must remain in place relative to both models' output.
+replayableHistory :: [OutputBlock] -> [OutputBlock]
+replayableHistory blocks =
+  case break isFallback (reverse blocks) of
+    (_, []) -> filter supported blocks
+    (after, marker : before) -> filter beforeFallback (reverse before) <> [marker] <> filter supported (reverse after)
+  where
+    isFallback block = case blockContent block of
+      OutputFallback _ -> True
+      _ -> False
+    supported block = case blockContent block of
+      UnknownBlock _ -> False
+      _ -> True
+    beforeFallback block = case blockContent block of
+      OutputText {} -> True
+      OutputFallback _ -> True
+      ServerToolUse ident _ _ -> any ((== Just (String ident)) . wireToolId) blocks
+      WebSearchToolResult {} -> True
+      OutputCodeExecutionResult {} -> True
+      OutputToolSearchResult {} -> True
+      _ -> False
+    wireToolId block = case blockJSON block of
+      Object fields -> KeyMap.lookup "tool_use_id" fields
+      _ -> Nothing
+
+responseText :: MessageResponse -> Text
+responseText response =
+  Text.concat [body | block <- response ^. #content, OutputText body _ <- [blockContent block]]
+
+newtype TokenCount = TokenCount {inputTokens :: Natural}
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON TokenCount where
+  parseJSON = withObject "token count" $ \o -> TokenCount <$> o .: "input_tokens"
+
+createMessage :: Client -> RequestOptions -> MessageRequest -> IO (Either ClientError (Response MessageResponse))
+createMessage client options request =
+  case validateMessages client Create (toJSON request) of
+    Left err -> pure (Left err)
+    Right fields -> jsonRequest client "POST" "/v1/messages" [] options (Just (Object fields))
+
+countTokens :: Client -> RequestOptions -> CountRequest -> IO (Either ClientError (Response TokenCount))
+countTokens client options request =
+  case validateMessages client Count (toJSON request) of
+    Left err -> pure (Left err)
+    Right fields -> jsonRequest client "POST" "/v1/messages/count_tokens" [] options (Just (Object fields))
diff --git a/src/Claude/Messages/Features.hs b/src/Claude/Messages/Features.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Messages/Features.hs
@@ -0,0 +1,632 @@
+-- | Request options and content variants shared by Messages and SSE.
+module Claude.Messages.Features
+  ( MessageFeatures (..),
+    defaultMessageFeatures,
+    RequestControls (..),
+    defaultRequestControls,
+    Compaction (..),
+    Fallbacks (..),
+    FallbackModel (..),
+    OutputConfig (..),
+    Effort (..),
+    Speed (..),
+    Thinking (..),
+    ThinkingDisplay (..),
+    CacheControl (..),
+    CacheTTL (..),
+    SystemPrompt (..),
+    SystemBlock (..),
+    Document (..),
+    Tool (..),
+    ClientTool (..),
+    ToolLoading (..),
+    AllowedCaller (..),
+    ToolCaller (..),
+    ToolSearch (..),
+    CodeExecutionVersion (..),
+    ToolChangeReference (..),
+    WebSearch (..),
+    WebSearchVersion (..),
+    ToolChoice (..),
+    ToolResult (..),
+    ToolResultContent (..),
+    Citation (..),
+    CitationLocation (..),
+    WebSearchOutcome (..),
+    WebSearchResult (..),
+    OutputBlock,
+    BlockContent (..),
+    ToolSearchOutcome (..),
+    CodeExecutionOutcome (..),
+    FallbackMarker (..),
+    blockContent,
+    blockJSON,
+  )
+where
+
+import Control.Applicative ((<|>))
+import Control.Lens ((^.))
+import Data.Aeson (FromJSON (..), Key, Object, ToJSON (..), Value (..), object, withArray, withObject, withText, (.!=), (.:), (.:?), (.=))
+import Data.Aeson.Types (Pair, Parser)
+import Data.Foldable (toList)
+import Data.Generics.Labels ()
+import Data.Map.Strict (Map)
+import Data.Text (Text)
+import GHC.Generics (Generic)
+import Numeric.Natural (Natural)
+
+-- | Options accepted by both Messages and count_tokens.
+data MessageFeatures = MessageFeatures
+  { outputConfig :: !(Maybe OutputConfig),
+    thinking :: !(Maybe Thinking),
+    cacheControl :: !(Maybe CacheControl),
+    tools :: ![Tool],
+    toolChoice :: !(Maybe ToolChoice),
+    speed :: !(Maybe Speed)
+  }
+  deriving stock (Eq, Show, Generic)
+
+defaultMessageFeatures :: MessageFeatures
+defaultMessageFeatures = MessageFeatures Nothing Nothing Nothing [] Nothing Nothing
+
+-- | Generation controls are excluded from the token-count projection.
+data RequestControls = RequestControls
+  { temperature :: !(Maybe Double),
+    topP :: !(Maybe Double),
+    topK :: !(Maybe Natural),
+    metadata :: !(Maybe (Map Text Text)),
+    containerId :: !(Maybe Text),
+    contextManagement :: !(Maybe [Compaction]),
+    inferenceGeo :: !(Maybe Text),
+    fallbacks :: !(Maybe Fallbacks)
+  }
+  deriving stock (Eq, Show, Generic)
+
+defaultRequestControls :: RequestControls
+defaultRequestControls = RequestControls Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
+
+data Compaction = Compaction
+  { instructions :: !(Maybe Text),
+    pauseAfterCompaction :: !(Maybe Bool),
+    inputTokensTrigger :: !(Maybe Natural)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance ToJSON Compaction where
+  toJSON (Compaction instructions_ pause trigger) =
+    tagged "compact_20260112" $
+      optional "instructions" instructions_
+        <> optional "pause_after_compaction" pause
+        <> ["trigger" .= tagged "input_tokens" ["value" .= tokens] | Just tokens <- [trigger]]
+
+data Fallbacks = DefaultFallbacks | FallbackModels ![FallbackModel]
+  deriving stock (Eq, Show)
+
+data FallbackModel = FallbackModel
+  { model :: !Text,
+    fallbackMaxTokens :: !(Maybe Natural),
+    outputConfig :: !(Maybe OutputConfig),
+    speed :: !(Maybe Speed),
+    thinking :: !(Maybe Thinking)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance ToJSON Fallbacks where
+  toJSON DefaultFallbacks = "default"
+  toJSON (FallbackModels models) = toJSON models
+
+instance ToJSON FallbackModel where
+  toJSON (FallbackModel ident limit output speed_ thinking_) =
+    object $
+      ["model" .= ident]
+        <> optional "max_tokens" limit
+        <> optional "output_config" output
+        <> optional "speed" speed_
+        <> optional "thinking" thinking_
+
+data Speed = Standard | Fast | VersionedSpeed !Text
+  deriving stock (Eq, Show)
+
+instance ToJSON Speed where
+  toJSON Standard = "standard"
+  toJSON Fast = "fast"
+  toJSON (VersionedSpeed value) = toJSON value
+
+data Effort = Low | Medium | High | ExtraHigh | Maximum | VersionedEffort !Text
+  deriving stock (Eq, Show)
+
+instance ToJSON Effort where
+  toJSON Low = "low"
+  toJSON Medium = "medium"
+  toJSON High = "high"
+  toJSON ExtraHigh = "xhigh"
+  toJSON Maximum = "max"
+  toJSON (VersionedEffort value) = toJSON value
+
+data OutputConfig = OutputConfig
+  { effort :: !(Maybe Effort),
+    schema :: !(Maybe Object)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance ToJSON OutputConfig where
+  toJSON opts =
+    object $
+      optional "effort" (opts ^. #effort)
+        <> ["format" .= tagged "json_schema" ["schema" .= schema_] | Just schema_ <- [opts ^. #schema]]
+
+data Thinking = Adaptive !(Maybe ThinkingDisplay) | ManualBudget !Natural !(Maybe ThinkingDisplay) | ThinkingDisabled | BetweenTools
+  deriving stock (Eq, Show)
+
+data ThinkingDisplay = Summarized | Omitted | Updates
+  deriving stock (Eq, Show)
+
+instance ToJSON Thinking where
+  toJSON (Adaptive display) = tagged "adaptive" (optional "display" display)
+  toJSON (ManualBudget tokens display) = tagged "enabled" (("budget_tokens" .= tokens) : optional "display" display)
+  toJSON ThinkingDisabled = tagged "disabled" []
+  toJSON BetweenTools = tagged "between_tools" []
+
+instance ToJSON ThinkingDisplay where
+  toJSON Summarized = "summarized"
+  toJSON Omitted = "omitted"
+  toJSON Updates = "updates"
+
+newtype CacheControl = Ephemeral (Maybe CacheTTL)
+  deriving stock (Eq, Show)
+
+data CacheTTL = FiveMinutes | OneHour
+  deriving stock (Eq, Show)
+
+instance ToJSON CacheControl where
+  toJSON (Ephemeral ttl) = tagged "ephemeral" (optional "ttl" ttl)
+
+instance ToJSON CacheTTL where
+  toJSON FiveMinutes = "5m"
+  toJSON OneHour = "1h"
+
+data SystemPrompt = SystemText !Text | SystemBlocks ![SystemBlock]
+  deriving stock (Eq, Show)
+
+data SystemBlock = SystemBlock
+  { text :: !Text,
+    cacheControl :: !(Maybe CacheControl)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance ToJSON SystemPrompt where
+  toJSON (SystemText text_) = toJSON text_
+  toJSON (SystemBlocks blocks) = toJSON blocks
+
+instance ToJSON SystemBlock where
+  toJSON block = tagged "text" (("text" .= (block ^. #text)) : optional "cache_control" (block ^. #cacheControl))
+
+data Document = PlainTextDocument
+  { text :: !Text,
+    title :: !(Maybe Text),
+    context :: !(Maybe Text),
+    citationsEnabled :: !Bool,
+    cacheControl :: !(Maybe CacheControl)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance ToJSON Document where
+  toJSON doc =
+    tagged "document" $
+      [ "source" .= tagged "text" ["media_type" .= ("text/plain" :: Text), "data" .= (doc ^. #text)],
+        "citations" .= object ["enabled" .= (doc ^. #citationsEnabled)]
+      ]
+        <> optional "title" (doc ^. #title)
+        <> optional "context" (doc ^. #context)
+        <> optional "cache_control" (doc ^. #cacheControl)
+
+data Tool
+  = CustomTool !ClientTool
+  | ConfiguredTool !ClientTool !ToolLoading
+  | WebSearchTool !WebSearch
+  | ToolSearchTool !ToolSearch !(Maybe CacheControl)
+  | CodeExecutionTool !CodeExecutionVersion !(Maybe CacheControl)
+  | VersionedTool !Object
+  deriving stock (Eq, Show)
+
+data ClientTool = ClientTool
+  { name :: !Text,
+    description :: !(Maybe Text),
+    inputSchema :: !Object,
+    strict :: !(Maybe Bool),
+    cacheControl :: !(Maybe CacheControl)
+  }
+  deriving stock (Eq, Show, Generic)
+
+data ToolLoading = ToolLoading
+  { deferLoading :: !(Maybe Bool),
+    allowedCallers :: !(Maybe [AllowedCaller])
+  }
+  deriving stock (Eq, Show, Generic)
+
+data AllowedCaller = AllowDirect | AllowCodeExecution !CodeExecutionVersion | AllowVersionedCaller !Text
+  deriving stock (Eq, Show)
+
+data ToolCaller = DirectCaller | CodeExecutionCaller !CodeExecutionVersion !Text | VersionedCaller !Text !Object
+  deriving stock (Eq, Show)
+
+data ToolSearch = RegexSearch20251119 | BM25Search20251119
+  deriving stock (Eq, Show)
+
+data CodeExecutionVersion = CodeExecution20250825 | CodeExecution20260120
+  deriving stock (Eq, Show)
+
+codeExecutionTag :: CodeExecutionVersion -> Text
+codeExecutionTag CodeExecution20250825 = "code_execution_20250825"
+codeExecutionTag CodeExecution20260120 = "code_execution_20260120"
+
+instance ToJSON AllowedCaller where
+  toJSON AllowDirect = "direct"
+  toJSON (AllowCodeExecution version_) = toJSON (codeExecutionTag version_)
+  toJSON (AllowVersionedCaller name_) = toJSON name_
+
+instance ToJSON ToolCaller where
+  toJSON DirectCaller = tagged "direct" []
+  toJSON (CodeExecutionCaller version_ ident) = tagged (codeExecutionTag version_) ["tool_id" .= ident]
+  toJSON (VersionedCaller _ fields) = Object fields
+
+data ToolChangeReference
+  = ToolReference !Text
+  | MCPToolReference !Text !Text
+  | MCPToolsetReference !Text
+  deriving stock (Eq, Show)
+
+instance ToJSON ToolChangeReference where
+  toJSON (ToolReference name_) = tagged "tool_reference" ["name" .= name_]
+  toJSON (MCPToolReference server name_) = tagged "mcp_tool_reference" ["server_name" .= server, "name" .= name_]
+  toJSON (MCPToolsetReference server) = tagged "mcp_toolset_reference" ["server_name" .= server]
+
+data WebSearch = WebSearch
+  { version :: !WebSearchVersion,
+    maxUses :: !(Maybe Natural),
+    cacheControl :: !(Maybe CacheControl)
+  }
+  deriving stock (Eq, Show, Generic)
+
+data WebSearchVersion = WebSearch20250305 | WebSearch20260209 | WebSearch20260318
+  deriving stock (Eq, Show)
+
+instance ToJSON Tool where
+  toJSON (CustomTool tool) = object (clientToolFields tool)
+  toJSON (ConfiguredTool tool (ToolLoading deferred callers)) =
+    object (clientToolFields tool <> optional "defer_loading" deferred <> optional "allowed_callers" callers)
+  toJSON (WebSearchTool tool) =
+    tagged versionTag $
+      ["name" .= ("web_search" :: Text)]
+        <> optional "max_uses" (tool ^. #maxUses)
+        <> optional "cache_control" (tool ^. #cacheControl)
+    where
+      versionTag = case tool ^. #version of
+        WebSearch20250305 -> "web_search_20250305"
+        WebSearch20260209 -> "web_search_20260209"
+        WebSearch20260318 -> "web_search_20260318"
+  toJSON (ToolSearchTool search cache) =
+    tagged versionTag (["name" .= name_] <> optional "cache_control" cache)
+    where
+      (versionTag, name_) = case search of
+        RegexSearch20251119 -> ("tool_search_tool_regex_20251119", "tool_search_tool_regex" :: Text)
+        BM25Search20251119 -> ("tool_search_tool_bm25_20251119", "tool_search_tool_bm25")
+  toJSON (CodeExecutionTool version_ cache) =
+    tagged (codeExecutionTag version_) (["name" .= ("code_execution" :: Text)] <> optional "cache_control" cache)
+  toJSON (VersionedTool tool) = toJSON tool
+
+clientToolFields :: ClientTool -> [Pair]
+clientToolFields tool =
+  ["name" .= (tool ^. #name), "input_schema" .= (tool ^. #inputSchema)]
+    <> optional "description" (tool ^. #description)
+    <> optional "strict" (tool ^. #strict)
+    <> optional "cache_control" (tool ^. #cacheControl)
+
+data ToolChoice = AutoTool !Bool | AnyTool !Bool | NamedTool !Text !Bool | NoTool
+  deriving stock (Eq, Show)
+
+instance ToJSON ToolChoice where
+  toJSON (AutoTool noParallel) = tagged "auto" ["disable_parallel_tool_use" .= noParallel | noParallel]
+  toJSON (AnyTool noParallel) = tagged "any" ["disable_parallel_tool_use" .= noParallel | noParallel]
+  toJSON (NamedTool name_ noParallel) =
+    tagged "tool" (("name" .= name_) : ["disable_parallel_tool_use" .= noParallel | noParallel])
+  toJSON NoTool = tagged "none" []
+
+data ToolResultContent = ToolResultText !Text | ToolResultBlocks ![Object] | EmptyToolResult
+  deriving stock (Eq, Show)
+
+data ToolResult = ToolResult
+  { toolUseId :: !Text,
+    content :: !ToolResultContent,
+    isError :: !(Maybe Bool),
+    cacheControl :: !(Maybe CacheControl)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance ToJSON ToolResultContent where
+  toJSON (ToolResultText text_) = toJSON text_
+  toJSON (ToolResultBlocks blocks) = toJSON blocks
+  toJSON EmptyToolResult = Null
+
+instance ToJSON ToolResult where
+  toJSON result =
+    tagged "tool_result" $
+      ["tool_use_id" .= (result ^. #toolUseId)]
+        <> ["content" .= payload | let payload = result ^. #content, payload /= EmptyToolResult]
+        <> optional "is_error" (result ^. #isError)
+        <> optional "cache_control" (result ^. #cacheControl)
+
+data Citation = Citation
+  { location :: !CitationLocation,
+    citationJSON :: !Value
+  }
+  deriving stock (Eq, Show, Generic)
+
+data CitationLocation
+  = CharacterRange !Text !Natural !(Maybe Text) !Natural !Natural
+  | PageRange !Text !Natural !(Maybe Text) !Natural !Natural
+  | BlockRange !Text !Natural !(Maybe Text) !Natural !Natural
+  | WebLocation !Text !Text !(Maybe Text) !Text
+  | UnknownCitation !Text
+  deriving stock (Eq, Show)
+
+instance FromJSON Citation where
+  parseJSON raw = withObject "citation" decode raw
+    where
+      decode o = do
+        tag <- o .: "type"
+        let document constructor start end =
+              constructor
+                <$> o .: "cited_text"
+                <*> o .: "document_index"
+                <*> o .:? "document_title"
+                <*> o .: start
+                <*> o .: end
+        observed <- case tag of
+          "char_location" -> document CharacterRange "start_char_index" "end_char_index"
+          "page_location" -> document PageRange "start_page_number" "end_page_number"
+          "content_block_location" -> document BlockRange "start_block_index" "end_block_index"
+          "web_search_result_location" ->
+            WebLocation <$> o .: "cited_text" <*> o .: "url" <*> o .:? "title" <*> o .: "encrypted_index"
+          other -> pure (UnknownCitation other)
+        pure (Citation observed raw)
+
+data WebSearchOutcome = WebSearchResults ![WebSearchResult] | WebSearchError !Text
+  deriving stock (Eq, Show)
+
+data WebSearchResult
+  = SearchResult
+      { url :: !Text,
+        title :: !Text,
+        encryptedContent :: !Text,
+        pageAge :: !(Maybe Text)
+      }
+  | UnknownSearchResult !Text !Value
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON WebSearchResult where
+  parseJSON raw =
+    withObject
+      "search result"
+      ( \o ->
+          o .: "type" >>= \case
+            "web_search_result" -> SearchResult <$> o .: "url" <*> o .: "title" <*> o .: "encrypted_content" <*> o .:? "page_age"
+            tag -> pure (UnknownSearchResult tag raw)
+      )
+      raw
+
+instance FromJSON WebSearchOutcome where
+  parseJSON raw = case raw of
+    Array _ -> withArray "search results" (fmap WebSearchResults . traverse parseJSON . toList) raw
+    _ ->
+      withObject
+        "search error"
+        ( \o -> do
+            tag <- o .: "type"
+            if (tag :: Text) == "web_search_tool_result_error"
+              then WebSearchError <$> o .: "error_code"
+              else fail "expected web_search_tool_result_error"
+        )
+        raw
+
+-- | The decoded view and original provider object travel together.
+-- Replay uses the original JSON, retaining fields that this version cannot interpret.
+data OutputBlock = OutputBlock
+  { blockContent :: !BlockContent,
+    blockJSON :: !Value
+  }
+  deriving stock (Eq, Show, Generic)
+
+data BlockContent
+  = OutputText !Text !(Maybe [Citation])
+  | OutputThinking !Text !Text
+  | RedactedThinking !Text
+  | OutputToolUse !Text !Text !Value
+  | OutputToolUseWithCaller !Text !Text !Value !ToolCaller
+  | ServerToolUse !Text !Text !Value
+  | WebSearchToolResult !Text !WebSearchOutcome
+  | OutputToolSearchResult !Text !ToolSearchOutcome
+  | OutputCodeExecutionResult !Text !CodeExecutionOutcome
+  | OutputFallback !FallbackMarker
+  | UnknownBlock !Text
+  deriving stock (Eq, Show)
+
+instance FromJSON OutputBlock where
+  parseJSON raw = withObject "content block" decode raw
+    where
+      decode o = do
+        tag <- o .: "type"
+        let tool constructor = constructor <$> o .: "id" <*> o .: "name" <*> o .: "input"
+        observed <- case tag of
+          "text" -> OutputText <$> o .: "text" <*> o .:? "citations"
+          "thinking" -> OutputThinking <$> o .: "thinking" <*> o .: "signature"
+          "redacted_thinking" -> RedactedThinking <$> o .: "data"
+          "tool_use" -> do
+            caller <- o .:? "caller"
+            case caller of
+              Nothing -> tool OutputToolUse
+              Just origin -> tool (\ident name_ input -> OutputToolUseWithCaller ident name_ input origin)
+          "server_tool_use" -> tool ServerToolUse
+          "web_search_tool_result" -> WebSearchToolResult <$> o .: "tool_use_id" <*> o .: "content"
+          "tool_search_tool_result" -> OutputToolSearchResult <$> o .: "tool_use_id" <*> o .: "content"
+          "code_execution_tool_result" -> executionResult o
+          "bash_code_execution_tool_result" -> executionResult o
+          "text_editor_code_execution_tool_result" -> executionResult o
+          "fallback" -> OutputFallback <$> parseJSON raw
+          other -> pure (UnknownBlock other)
+        pure (OutputBlock observed raw)
+
+instance ToJSON OutputBlock where
+  toJSON = blockJSON
+
+instance FromJSON ToolCaller where
+  parseJSON = withObject "tool caller" $ \o ->
+    o .: "type" >>= \case
+      "direct" -> pure DirectCaller
+      "code_execution_20250825" -> CodeExecutionCaller CodeExecution20250825 <$> o .: "tool_id"
+      "code_execution_20260120" -> CodeExecutionCaller CodeExecution20260120 <$> o .: "tool_id"
+      tag -> pure (VersionedCaller tag o)
+
+data ToolSearchOutcome = ToolSearchMatches ![Text] | ToolSearchFailed !Text | UnknownToolSearchOutcome !Text !Object
+  deriving stock (Eq, Show)
+
+instance FromJSON ToolSearchOutcome where
+  parseJSON = withObject "tool search result" $ \o ->
+    let references = o .: "tool_references" >>= traverse (withObject "tool reference" (.: "tool_name"))
+        failed = ToolSearchFailed <$> o .: "error_code"
+     in o .: "type" >>= \case
+          "tool_search_result" -> ToolSearchMatches <$> references
+          "tool_search_tool_search_result" -> ToolSearchMatches <$> references
+          "error" -> failed
+          "tool_search_tool_result_error" -> failed
+          tag -> pure (UnknownToolSearchOutcome tag o)
+
+data CodeExecutionOutcome
+  = CodeExecutionCompleted !Text !Text !Int ![Value]
+  | CodeExecutionFailed !Text
+  | UnknownCodeExecutionOutcome !Text !Object
+  deriving stock (Eq, Show)
+
+instance FromJSON CodeExecutionOutcome where
+  parseJSON = withObject "code execution result" $ \o ->
+    let completed = CodeExecutionCompleted <$> o .: "stdout" <*> o .: "stderr" <*> o .: "return_code" <*> o .: "content"
+        failed = CodeExecutionFailed <$> o .: "error_code"
+     in o .: "type" >>= \case
+          "code_execution_result" -> completed
+          "bash_code_execution_result" -> completed
+          "code_execution_tool_result_error" -> failed
+          "bash_code_execution_tool_result_error" -> failed
+          "text_editor_code_execution_tool_result_error" -> failed
+          tag -> pure (UnknownCodeExecutionOutcome tag o)
+
+executionResult :: Object -> Parser BlockContent
+executionResult o = OutputCodeExecutionResult <$> o .: "tool_use_id" <*> o .: "content"
+
+data FallbackMarker = FallbackMarker
+  { fromModel :: !Text,
+    toModel :: !Text,
+    triggerType :: !Text,
+    category :: !(Maybe Text)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON FallbackMarker where
+  parseJSON = withObject "fallback marker" $ \o -> do
+    from <- o .: "from" >>= withObject "source model" (.: "model")
+    to <- o .: "to" >>= withObject "fallback model" (.: "model")
+    trigger <- o .: "trigger"
+    withObject "fallback trigger" (\t -> FallbackMarker from to <$> t .: "type" <*> t .:? "category") trigger
+
+instance ToJSON FallbackMarker where
+  toJSON (FallbackMarker from to trigger reason) =
+    tagged "fallback" ["from" .= object ["model" .= from], "to" .= object ["model" .= to], "trigger" .= tagged trigger (optional "category" reason)]
+
+tagged :: Text -> [Pair] -> Value
+tagged tag fields = object (("type" .= tag) : fields)
+
+optional :: (ToJSON a) => Key -> Maybe a -> [Pair]
+optional key = maybe [] (\item -> [key .= item])
+
+instance FromJSON Speed where
+  parseJSON = withText "speed" $ \case
+    "standard" -> pure Standard
+    "fast" -> pure Fast
+    other -> pure (VersionedSpeed other)
+
+instance FromJSON Effort where
+  parseJSON = withText "effort" $ \case
+    "low" -> pure Low
+    "medium" -> pure Medium
+    "high" -> pure High
+    "xhigh" -> pure ExtraHigh
+    "max" -> pure Maximum
+    other -> pure (VersionedEffort other)
+
+instance FromJSON OutputConfig where
+  parseJSON = withObject "output config" $ \o -> do
+    format <- o .:? "format"
+    schema_ <- traverse (withObject "output format" (.: "schema")) format
+    OutputConfig <$> o .:? "effort" <*> pure schema_
+
+instance FromJSON Thinking where
+  parseJSON = withObject "thinking" $ \o ->
+    (o .: "type" :: Parser Text) >>= \case
+      "adaptive" -> Adaptive <$> o .:? "display"
+      "enabled" -> ManualBudget <$> o .: "budget_tokens" <*> o .:? "display"
+      "disabled" -> pure ThinkingDisabled
+      "between_tools" -> pure BetweenTools
+      _ -> fail "unknown thinking mode"
+
+instance FromJSON ThinkingDisplay where
+  parseJSON = withText "thinking display" $ \case
+    "summarized" -> pure Summarized
+    "omitted" -> pure Omitted
+    "updates" -> pure Updates
+    _ -> fail "unknown thinking display"
+
+instance FromJSON CacheControl where
+  parseJSON = withObject "cache control" $ \o ->
+    (o .: "type" :: Parser Text) >>= \case
+      "ephemeral" -> Ephemeral <$> o .:? "ttl"
+      _ -> fail "unknown cache control"
+
+instance FromJSON CacheTTL where
+  parseJSON = withText "cache TTL" $ \case
+    "5m" -> pure FiveMinutes
+    "1h" -> pure OneHour
+    _ -> fail "unknown cache TTL"
+
+instance FromJSON SystemPrompt where
+  parseJSON raw = (SystemText <$> parseJSON raw) <|> (SystemBlocks <$> parseJSON raw)
+
+instance FromJSON SystemBlock where
+  parseJSON = withObject "system block" $ \o -> SystemBlock <$> o .: "text" <*> o .:? "cache_control"
+
+instance FromJSON Tool where
+  parseJSON = withObject "tool definition" (pure . VersionedTool)
+
+instance FromJSON ToolChoice where
+  parseJSON = withObject "tool choice" $ \o -> do
+    noParallel <- o .:? "disable_parallel_tool_use" .!= False
+    (o .: "type" :: Parser Text) >>= \case
+      "auto" -> pure (AutoTool noParallel)
+      "any" -> pure (AnyTool noParallel)
+      "tool" -> NamedTool <$> o .: "name" <*> pure noParallel
+      "none" -> pure NoTool
+      _ -> fail "unknown tool choice"
+
+instance FromJSON Compaction where
+  parseJSON = withObject "context management edit" $ \o -> do
+    trigger <- o .:? "trigger"
+    threshold <- traverse (withObject "compaction trigger" (.: "value")) trigger
+    (o .: "type" :: Parser Text) >>= \case
+      "compact_20260112" -> Compaction <$> o .:? "instructions" <*> o .:? "pause_after_compaction" <*> pure threshold
+      _ -> fail "unknown context management edit"
+
+instance FromJSON Fallbacks where
+  parseJSON (String "default") = pure DefaultFallbacks
+  parseJSON raw = FallbackModels <$> parseJSON raw
+
+instance FromJSON FallbackModel where
+  parseJSON = withObject "fallback model" $ \o ->
+    FallbackModel <$> o .: "model" <*> o .:? "max_tokens" <*> o .:? "output_config" <*> o .:? "speed" <*> o .:? "thinking"
diff --git a/src/Claude/Messages/Usage.hs b/src/Claude/Messages/Usage.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Messages/Usage.hs
@@ -0,0 +1,104 @@
+-- | Billing evidence shared by complete messages and cumulative stream deltas.
+module Claude.Messages.Usage
+  ( UsageEvidence (..),
+    ServerToolCounts (..),
+    OutputTokenDetails (..),
+    UsageIteration (..),
+    mergeUsageEvidence,
+  )
+where
+
+import Claude.Messages.Features (Speed)
+import Control.Applicative ((<|>))
+import Data.Aeson (FromJSON (..), Object, withObject, (.:), (.:?))
+import Data.Text (Text)
+import GHC.Generics (Generic)
+import Numeric.Natural (Natural)
+
+data UsageEvidence = UsageEvidence
+  { inferenceGeography :: !(Maybe Text),
+    serviceTier :: !(Maybe Text),
+    observedSpeed :: !(Maybe Speed),
+    outputTokensDetails :: !(Maybe OutputTokenDetails),
+    iterations :: !(Maybe [UsageIteration]),
+    serverToolCounts :: !(Maybe ServerToolCounts)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON UsageEvidence where
+  parseJSON = withObject "usage evidence" $ \o ->
+    UsageEvidence
+      <$> o .:? "inference_geo"
+      <*> o .:? "service_tier"
+      <*> o .:? "speed"
+      <*> o .:? "output_tokens_details"
+      <*> o .:? "iterations"
+      <*> o .:? "server_tool_use"
+
+data ServerToolCounts = ServerToolCounts
+  { webSearchRequests :: !(Maybe Natural),
+    webFetchRequests :: !(Maybe Natural),
+    toolSearchRequests :: !(Maybe Natural),
+    codeExecutionRequests :: !(Maybe Natural)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON ServerToolCounts where
+  parseJSON = withObject "server tool counts" $ \o ->
+    ServerToolCounts
+      <$> o .:? "web_search_requests"
+      <*> o .:? "web_fetch_requests"
+      <*> o .:? "tool_search_requests"
+      <*> o .:? "code_execution_requests"
+
+newtype OutputTokenDetails = OutputTokenDetails
+  { thinkingTokens :: Maybe Natural
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON OutputTokenDetails where
+  parseJSON = withObject "output token details" $ \o -> OutputTokenDetails <$> o .:? "thinking_tokens"
+
+data UsageIteration = UsageIteration
+  { iterationType :: !Text,
+    iterationModel :: !(Maybe Text),
+    iterationInputTokens :: !(Maybe Natural),
+    iterationOutputTokens :: !(Maybe Natural),
+    iterationCacheCreationInputTokens :: !(Maybe Natural),
+    iterationCacheReadInputTokens :: !(Maybe Natural),
+    iterationJSON :: !Object
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON UsageIteration where
+  parseJSON = withObject "usage iteration" $ \o ->
+    UsageIteration
+      <$> o .: "type"
+      <*> o .:? "model"
+      <*> o .:? "input_tokens"
+      <*> o .:? "output_tokens"
+      <*> o .:? "cache_creation_input_tokens"
+      <*> o .:? "cache_read_input_tokens"
+      <*> pure o
+
+mergeUsageEvidence :: UsageEvidence -> UsageEvidence -> UsageEvidence
+mergeUsageEvidence old new =
+  UsageEvidence
+    { inferenceGeography = inferenceGeography new <|> inferenceGeography old,
+      serviceTier = serviceTier new <|> serviceTier old,
+      observedSpeed = observedSpeed new <|> observedSpeed old,
+      outputTokensDetails = mergeWith mergeOutput (outputTokensDetails old) (outputTokensDetails new),
+      iterations = iterations new <|> iterations old,
+      serverToolCounts = mergeWith mergeTools (serverToolCounts old) (serverToolCounts new)
+    }
+  where
+    mergeWith merge (Just previous) (Just latest) = Just (merge previous latest)
+    mergeWith _ previous latest = latest <|> previous
+    mergeOutput previous latest = OutputTokenDetails (thinkingTokens latest <|> thinkingTokens previous)
+    mergeTools previous latest =
+      ServerToolCounts
+        { webSearchRequests = webSearchRequests latest <|> webSearchRequests previous,
+          webFetchRequests = webFetchRequests latest <|> webFetchRequests previous,
+          toolSearchRequests = toolSearchRequests latest <|> toolSearchRequests previous,
+          codeExecutionRequests = codeExecutionRequests latest <|> codeExecutionRequests previous
+        }
diff --git a/src/Claude/Streaming.hs b/src/Claude/Streaming.hs
new file mode 100644
--- /dev/null
+++ b/src/Claude/Streaming.hs
@@ -0,0 +1,222 @@
+-- | Deliver Messages events as they arrive on a scoped HTTP connection.
+module Claude.Streaming
+  ( streamMessage,
+    streamMessageValue,
+    decodeStreamEvent,
+    consumeEventStream,
+    StreamControl (..),
+    StreamEnd (..),
+    StreamEvent (..),
+    StreamPayload (..),
+    BlockDelta (..),
+    MessageUpdate (..),
+    UsageUpdate (..),
+    applyUsageUpdate,
+  )
+where
+
+import Claude.Client
+import Claude.Internal.Http (BodyReader, decodeResponse, redactApiError, runRequest)
+import Claude.Internal.Request qualified as Request
+import Claude.Internal.Sse (foldEvents)
+import Claude.Messages
+import Claude.Messages.Usage (mergeUsageEvidence)
+import Control.Applicative ((<|>))
+import Control.Monad.IO.Class (liftIO)
+import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
+import Data.Aeson (FromJSON (..), Object, Value (..), toJSON, withObject, (.:), (.:?))
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.Aeson.Types (parseEither)
+import Data.ByteString (ByteString)
+import Data.ByteString.Lazy qualified as LBS
+import Data.Maybe (fromMaybe)
+import Data.Text (Text)
+import Data.Text.Encoding (encodeUtf8)
+import GHC.Generics (Generic)
+import Numeric.Natural (Natural)
+
+data StreamControl = Continue | Stop
+  deriving stock (Eq, Show)
+
+data StreamEnd = Finished | Stopped
+  deriving stock (Eq, Show)
+
+data StreamEvent = StreamEvent
+  { eventPayload :: !StreamPayload,
+    eventJSON :: !Value
+  }
+  deriving stock (Eq, Show, Generic)
+
+data StreamPayload
+  = MessageStart !MessageResponse
+  | ContentBlockStart !Natural !OutputBlock
+  | ContentBlockDelta !Natural !BlockDelta
+  | ContentBlockStop !Natural
+  | MessageDelta !MessageUpdate !UsageUpdate
+  | MessageStop
+  | Ping
+  | UnknownEvent !Text
+  deriving stock (Eq, Show)
+
+data BlockDelta
+  = TextDelta !Text
+  | InputJsonDelta !Text
+  | CitationDelta !Citation
+  | ThinkingDelta !Text
+  | SignatureDelta !Text
+  | UnknownDelta !Text !Value
+  deriving stock (Eq, Show)
+
+data MessageUpdate = MessageUpdate
+  { stopReason :: !(Maybe StopReason),
+    stopSequence :: !(Maybe Text),
+    stopDetails :: !(Maybe StopDetails),
+    updatedContainer :: !(Maybe ContainerInfo)
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON MessageUpdate where
+  parseJSON = withObject "message delta" $ \o -> MessageUpdate <$> o .:? "stop_reason" <*> o .:? "stop_sequence" <*> o .:? "stop_details" <*> o .:? "container"
+
+-- | The provider reports cumulative counters. Missing counters leave
+-- earlier observations in effect.
+data UsageUpdate = UsageUpdate
+  { inputTokens :: !(Maybe Natural),
+    outputTokens :: !(Maybe Natural),
+    cacheCreationInputTokens :: !(Maybe Natural),
+    cacheReadInputTokens :: !(Maybe Natural),
+    serverToolUse :: !(Maybe Object),
+    cacheCreation :: !(Maybe Object),
+    usageEvidence :: !UsageEvidence
+  }
+  deriving stock (Eq, Show, Generic)
+
+instance FromJSON UsageUpdate where
+  parseJSON = withObject "stream usage" $ \o ->
+    UsageUpdate
+      <$> o .:? "input_tokens"
+      <*> o .:? "output_tokens"
+      <*> o .:? "cache_creation_input_tokens"
+      <*> o .:? "cache_read_input_tokens"
+      <*> o .:? "server_tool_use"
+      <*> o .:? "cache_creation"
+      <*> parseJSON (Object o)
+
+-- | Apply a cumulative update while retaining each unreported counter.
+applyUsageUpdate :: Usage -> UsageUpdate -> Usage
+applyUsageUpdate previous update = case (previous, update) of
+  (Usage input output written read_ cache tools evidence, UsageUpdate input' output' written' read' tools' cache' evidence') ->
+    Usage
+      (fromMaybe input input')
+      (fromMaybe output output')
+      (written' <|> written)
+      (read' <|> read_)
+      (mergeObjects cache cache')
+      (mergeObjects tools tools')
+      (mergeUsageEvidence evidence evidence')
+  where
+    mergeObjects (Just old) (Just new) = Just (KeyMap.union new old)
+    mergeObjects old new = new <|> old
+
+instance FromJSON BlockDelta where
+  parseJSON raw =
+    withObject
+      "content block delta"
+      ( \o ->
+          o .: "type" >>= \case
+            "text_delta" -> TextDelta <$> o .: "text"
+            "input_json_delta" -> InputJsonDelta <$> o .: "partial_json"
+            "citations_delta" -> CitationDelta <$> o .: "citation"
+            "thinking_delta" -> ThinkingDelta <$> o .: "thinking"
+            "signature_delta" -> SignatureDelta <$> o .: "signature"
+            tag -> pure (UnknownDelta tag raw)
+      )
+      raw
+
+data FrameEvent = FrameEvent !Text !(Either ApiError StreamPayload) !Value
+
+instance FromJSON FrameEvent where
+  parseJSON raw = withObject "stream event" decode raw
+    where
+      decode o = do
+        tag <- o .: "type"
+        observed <- case tag of
+          "error" -> Left <$> o .: "error"
+          _ ->
+            Right <$> case tag of
+              "message_start" -> MessageStart <$> o .: "message"
+              "content_block_start" -> ContentBlockStart <$> o .: "index" <*> o .: "content_block"
+              "content_block_delta" -> ContentBlockDelta <$> o .: "index" <*> o .: "delta"
+              "content_block_stop" -> ContentBlockStop <$> o .: "index"
+              "message_delta" -> MessageDelta <$> o .: "delta" <*> o .: "usage"
+              "message_stop" -> pure MessageStop
+              "ping" -> pure Ping
+              other -> pure (UnknownEvent other)
+        pure (FrameEvent tag observed raw)
+
+-- | Decode a recorded JSON event with the same codec used by 'streamMessage'.
+-- The inner error is a provider error event. The outer error describes an
+-- invalid event object.
+decodeStreamEvent :: Value -> Either String (Either ApiError StreamEvent)
+decodeStreamEvent raw = do
+  FrameEvent _ payload original <- parseEither parseJSON raw
+  pure (fmap (\event -> StreamEvent event original) payload)
+
+-- | The callback runs synchronously. 'Stop' releases the response without
+-- waiting for EOF. An observed @message_stop@ ends the operation as 'Finished'.
+-- Callback exceptions and cancellation propagate after cleanup.
+streamMessage ::
+  Client ->
+  RequestOptions ->
+  MessageRequest ->
+  (ResponseMetadata -> StreamEvent -> IO StreamControl) ->
+  IO (Either ClientError (Response StreamEnd))
+streamMessage client options request =
+  streamMessageValue client options (toJSON request)
+
+-- | Bridge an existing versioned Messages encoder. Require the common request
+-- envelope and preserve its fields, taking ownership of the stream flag.
+streamMessageValue ::
+  Client ->
+  RequestOptions ->
+  Value ->
+  (ResponseMetadata -> StreamEvent -> IO StreamControl) ->
+  IO (Either ClientError (Response StreamEnd))
+streamMessageValue client options body consume =
+  case Request.validateMessages client Request.Stream body of
+    Left err -> pure (Left err)
+    Right fields ->
+      runRequest client "POST" "/v1/messages" [] options "text/event-stream" (Just (Object (KeyMap.insert "stream" (Bool True) fields))) $ \meta readBody ->
+        consumeSse meta (redactApiError client) readBody (consume meta)
+
+-- | Consume an already acquired SSE body with the live stream decoder.
+-- The caller owns the reader and its lifetime. Errors carry the supplied
+-- metadata, and caller exceptions propagate.
+consumeEventStream ::
+  ResponseMetadata ->
+  IO ByteString ->
+  (StreamEvent -> IO StreamControl) ->
+  IO (Either ClientError StreamEnd)
+consumeEventStream meta readBody consume =
+  runExceptT (consumeSse meta (\err -> err) (liftIO readBody) consume)
+
+consumeSse ::
+  ResponseMetadata ->
+  (ApiError -> ApiError) ->
+  BodyReader ->
+  (StreamEvent -> IO StreamControl) ->
+  ExceptT ClientError IO StreamEnd
+consumeSse meta protect readBody consume = do
+  final <- foldEvents readBody $ \eventName payload -> do
+    FrameEvent tag decoded raw <- either throwE pure (decodeResponse meta (LBS.fromStrict payload))
+    if maybe False (\name -> name /= "" && name /= encodeUtf8 tag) eventName
+      then throwE (DecodeError meta "SSE event name differs from the JSON type")
+      else case decoded of
+        Left err -> throwE (StreamApiError meta (protect err))
+        Right event -> do
+          decision <- liftIO (consume (StreamEvent event raw))
+          pure $ case (event, decision) of
+            (MessageStop, _) -> Just Finished
+            (_, Stop) -> Just Stopped
+            _ -> Nothing
+  maybe (throwE (DecodeError meta "Stream ended before message_stop")) pure final
diff --git a/test/BatchesSpec.hs b/test/BatchesSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/BatchesSpec.hs
@@ -0,0 +1,165 @@
+module BatchesSpec (run) where
+
+import Claude.Batches
+import Claude.Client
+import Claude.Messages (OutputTokenDetails (..), RequestControls (..), StopDetails (..), defaultRequestControls, responseText, withRequestControls)
+import Control.Concurrent (newEmptyMVar, putMVar, takeMVar)
+import Control.Lens ((^.))
+import Control.Monad (void)
+import Data.Aeson (Value (..), eitherDecode, encode, object, toJSON, (.=))
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.ByteString.Builder (lazyByteString)
+import Data.ByteString.Lazy qualified as LBS
+import Data.Generics.Labels ()
+import Data.IORef (modifyIORef', newIORef, readIORef)
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.Text (Text)
+import Data.Time (UTCTime)
+import FeaturesSpec (enrichedConversation, enrichedOptions, thinkingBlock)
+import MessagesSpec (messageWithEvidence, sampleRequest)
+import Network.HTTP.Types (status200)
+import Network.Wai qualified as Wai
+import Support.Server
+
+run :: IO ()
+run = do
+  lifecycle
+  incrementalResults
+  putStrLn "Batches: enriched submission, cursors, cancellation and incremental mixed outcomes passed"
+
+withBatchId :: (BatchId -> IO a) -> IO a
+withBatchId action = maybe (fail "invalid fixture batch ID") action (batchId "msgbatch_fixture")
+
+lifecycle :: IO ()
+lifecycle = withBatchId $ \ident -> do
+  requests <- newIORef []
+  request <- withRequestControls defaultRequestControls {containerId = Just "container_batch", inferenceGeo = Just "us"} <$> sampleRequest enrichedConversation
+  a <- maybe (fail "invalid alpha ID") pure (mkCustomId "alpha")
+  b <- maybe (fail "invalid beta ID") pure (mkCustomId "beta")
+  let running = batchFixture "in_progress" False
+      canceling = batchFixture "canceling" True
+      ended = batchFixture "ended" True
+      itemJson itemId = object ["custom_id" .= (itemId :: Text), "params" .= toJSON request]
+      app req send = do
+        body <- Wai.strictRequestBody req
+        case (Wai.requestMethod req, Wai.pathInfo req) of
+          ("POST", ["v1", "messages", "batches"]) -> do
+            assertEqual "enriched params" (Right (object ["requests" .= [itemJson "alpha", itemJson "beta"]])) (eitherDecode body)
+            assertEqual "shared beta header" (Just "fast-mode-2026-02-01") (lookup "anthropic-beta" (Wai.requestHeaders req))
+            send (json status200 [] running)
+          ("GET", ["v1", "messages", "batches", "msgbatch_fixture"]) ->
+            send (json status200 [] ended)
+          ("GET", ["v1", "messages", "batches"]) -> do
+            modifyIORef' requests (<> [Wai.queryString req])
+            send (json status200 [] (object ["data" .= [running], "has_more" .= True, "first_id" .= batchIdText ident, "last_id" .= batchIdText ident]))
+          ("POST", ["v1", "messages", "batches", "msgbatch_fixture", "cancel"]) ->
+            send (json status200 [] canceling)
+          route -> fail ("Unexpected batch route " <> show route)
+  withClient app $ \client -> do
+    Response _ created <- createBatch client enrichedOptions (BatchItem a request :| [BatchItem b request]) >>= expectRight
+    assertEqual "running batch" (ident, InProgress, Nothing, Nothing) (created ^. #id, created ^. #processingStatus, created ^. #resultsUrl, created ^. #endedAt)
+    assertEqual "decoded ISO timestamp" (read "2026-11-20 19:35:56.25 UTC" :: UTCTime) (created ^. #createdAt)
+    mapM_
+      ( \cursor_ -> do
+          Response _ page <- listBatches client defaultRequestOptions (BatchListOptions (Just cursor_) (Just 7)) >>= expectRight
+          assertEqual "cursor metadata" (True, Just ident, Just ident, [created]) (page ^. #hasMore, page ^. #firstId, page ^. #lastId, page ^. #batches)
+      )
+      [After ident, Before ident]
+    Response _ cancelingBatch <- cancelBatch client defaultRequestOptions ident >>= expectRight
+    assertEqual "cancel requested" Canceling (cancelingBatch ^. #processingStatus)
+    assert "cancel timestamp" (cancelingBatch ^. #cancelInitiatedAt /= Nothing)
+    Response _ final <- retrieveBatch client defaultRequestOptions ident >>= expectRight
+    assertEqual "fresh status" Ended (final ^. #processingStatus)
+    assertEqual "final request counts" (RequestCounts 0 1 1 1 1) (final ^. #requestCounts)
+  readIORef requests
+    >>= assertEqual
+      "pagination query in both directions"
+      [[("after_id", Just "msgbatch_fixture"), ("limit", Just "7")], [("before_id", Just "msgbatch_fixture"), ("limit", Just "7")]]
+  let noDispatch = withClient (\_ _ -> fail "Invalid batch dispatched")
+  noDispatch $ \client -> do
+    createBatch client defaultRequestOptions (BatchItem a request :| [BatchItem a request]) >>= \case
+      Left (InvalidRequest _) -> pure ()
+      _ -> fail "Expected duplicate ID error"
+    listBatches client defaultRequestOptions (BatchListOptions Nothing (Just 0)) >>= \case
+      Left (InvalidRequest _) -> pure ()
+      _ -> fail "Expected out-of-range list limit"
+  assertEqual "invalid custom ID" Nothing (mkCustomId "bad/id")
+
+batchFixture :: Text -> Bool -> Value
+batchFixture state cancelRequested =
+  object
+    [ "id" .= ("msgbatch_fixture" :: Text),
+      "type" .= ("message_batch" :: Text),
+      "created_at" .= ("2026-11-20T19:35:56.25Z" :: Text),
+      "expires_at" .= ("2026-11-21T19:35:56Z" :: Text),
+      "processing_status" .= state,
+      "ended_at" .= (if state == "ended" then String "2026-11-20T19:36:56Z" else Null),
+      "cancel_initiated_at" .= (if cancelRequested then String "2026-11-20T19:36:01Z" else Null),
+      "archived_at" .= Null,
+      "results_url" .= (if state == "ended" then String "https://off-origin.invalid/results.jsonl" else Null),
+      "request_counts"
+        .= object
+          [ "processing" .= (if state == "ended" then 0 :: Int else 4),
+            "succeeded" .= done,
+            "errored" .= done,
+            "canceled" .= done,
+            "expired" .= done
+          ]
+    ]
+  where
+    done = if state == "ended" then 1 :: Int else 0
+
+incrementalResults :: IO ()
+incrementalResults = withBatchId $ \ident -> do
+  let outcome custom tag fields = encode (object ["custom_id" .= (custom :: Text), "result" .= object (("type" .= (tag :: Text)) : fields)])
+      first = outcome "delta" "expired" []
+      second = outcome "gamma" "canceled" []
+      third =
+        outcome
+          "beta"
+          "errored"
+          ["error" .= object ["type" .= ("error" :: Text), "error" .= object ["type" .= ("overloaded_error" :: Text), "message" .= ("echo loopback-secret" :: Text)]]]
+      fourth =
+        outcome
+          "alpha"
+          "succeeded"
+          [ "message"
+              .= withBlocks messageWithEvidence [thinkingBlock "" "batch-signature", object ["type" .= ("text" :: Text), "text" .= ("café" :: Text)]]
+          ]
+      exercise malformed = do
+        gate <- newEmptyMVar
+        results <- newIORef []
+        let app req send = do
+              assertEqual "configured results route" ("GET", "/v1/messages/batches/msgbatch_fixture/results") (Wai.requestMethod req, Wai.rawPathInfo req)
+              assertEqual "results accept" (Just "application/binary") (lookup "accept" (Wai.requestHeaders req))
+              send $ Wai.responseStream status200 [("request-id", "req_batch"), ("content-type", "application/x-jsonlines")] $ \write flush -> do
+                write (lazyByteString (LBS.take 9 first)) >> flush
+                write (lazyByteString (LBS.drop 9 first <> "\r\n")) >> flush
+                takeMVar gate
+                let rest = if malformed then "malformed\n" else second <> "\n" <> third <> "\n" <> fourth
+                write (lazyByteString rest)
+                flush
+        withClient app $ \client -> do
+          result <- consumeBatchResults client defaultRequestOptions ident $ \item -> do
+            modifyIORef' results (item :)
+            if customIdText (item ^. #customId) == "delta" then putMVar gate () else pure ()
+          if malformed
+            then case result of
+              Left (DecodeError meta _) -> assertEqual "malformed line request ID" (Just "req_batch") (meta ^. #requestId)
+              _ -> fail "Expected malformed JSON line"
+            else void (expectRight result)
+        reverse <$> readIORef results
+  good <- exercise False
+  assertEqual "results correlate by custom ID" ["delta", "gamma", "beta", "alpha"] (map (customIdText . (^. #customId)) good)
+  case map (^. #outcome) good of
+    [BatchExpired, BatchCanceled, BatchErrored (ApiError "overloaded_error" "echo [redacted]"), BatchSucceeded result] -> do
+      assertEqual "batch message uses shared response codec" "café" (responseText result)
+      assertEqual "batch stop details" (Just (RefusalDetails (Just "other") (Just "declined") Nothing)) (result ^. #stopDetails)
+      assertEqual "batch reasoning" (Just (OutputTokenDetails (Just 5))) (result ^. #usage . #usageEvidence . #outputTokensDetails)
+    _ -> fail "Expected all four batch outcomes"
+  partial <- exercise True
+  assertEqual "first line delivered before later failure" ["delta"] (map (customIdText . (^. #customId)) partial)
+
+withBlocks :: Value -> [Value] -> Value
+withBlocks (Object fields) blocks = Object (KeyMap.insert "content" (toJSON blocks) fields)
+withBlocks other _ = other
diff --git a/test/FeaturesSpec.hs b/test/FeaturesSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/FeaturesSpec.hs
@@ -0,0 +1,289 @@
+module FeaturesSpec (run, enrichedConversation, enrichedOptions, thinkingBlock, redactedBlock, webCitation) where
+
+import Claude.Client
+import Claude.Messages
+import Control.Lens ((^.))
+import Data.Aeson (Key, Object, Value (..), object, toJSON, (.=))
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.Generics.Labels ()
+import Data.IORef (atomicModifyIORef', newIORef, readIORef)
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.Text (Text)
+import MessagesSpec (baseConversation, messageFixture, sampleRequest)
+import Network.HTTP.Types (status200)
+import Network.Wai qualified as Wai
+import Support.Server
+
+schemaFixture :: Object
+schemaFixture = KeyMap.fromList ["type" .= ("object" :: Text), "additionalProperties" .= False]
+
+toolFixture :: Tool
+toolFixture = CustomTool (ClientTool "lookup" (Just "Look up a color") schemaFixture (Just True) (Just (Ephemeral (Just FiveMinutes))))
+
+enrichedConversation :: Conversation
+enrichedConversation =
+  baseConversation
+    { system = Just (SystemBlocks [SystemBlock "Cite the supplied material." (Just (Ephemeral (Just OneHour)))]),
+      features =
+        defaultMessageFeatures
+          { thinking = Just (Adaptive (Just Omitted)),
+            cacheControl = Just (Ephemeral Nothing),
+            tools = [toolFixture],
+            toolChoice = Just (AutoTool True),
+            speed = Just Fast
+          }
+    }
+
+enrichedOptions :: RequestOptions
+enrichedOptions = defaultRequestOptions {betaFeatures = ["fast-mode-2026-02-01"]}
+
+thinkingBlock :: Text -> Text -> Value
+thinkingBlock summary signature =
+  object ["type" .= ("thinking" :: Text), "thinking" .= summary, "signature" .= signature, "provider_state" .= True]
+
+redactedBlock :: Value
+redactedBlock = object ["type" .= ("redacted_thinking" :: Text), "data" .= ("ciphertext" :: Text)]
+
+toolUseBlock :: Text -> Value
+toolUseBlock toolId =
+  object ["type" .= ("tool_use" :: Text), "id" .= toolId, "name" .= ("lookup" :: Text), "input" .= object []]
+
+run :: IO ()
+run = do
+  schemaAndToolIndependence
+  consecutiveToolRounds
+  citationsAndSearch
+  malformedKnownBlock
+  putStrLn "Features: structured output, tool continuation, cache and citation fixtures passed"
+
+schemaAndToolIndependence :: IO ()
+schemaAndToolIndependence = do
+  let schema = OutputConfig (Just High) (Just schemaFixture)
+      schemaConvo = baseConversation {features = defaultMessageFeatures {outputConfig = Just schema}}
+      toolConvo = baseConversation {features = defaultMessageFeatures {tools = [toolFixture], toolChoice = Just (NamedTool "lookup" False)}}
+      bothConvo = enrichedConversation {features = (enrichedConversation ^. #features) {outputConfig = Just schema}}
+  schemaRequest <- sampleRequest schemaConvo
+  toolsRequest <- sampleRequest toolConvo
+  bothRequest <- sampleRequest bothConvo
+  let expectedOutput =
+        object
+          [ "effort" .= ("high" :: Text),
+            "format" .= object ["type" .= ("json_schema" :: Text), "schema" .= schemaFixture]
+          ]
+      expectedTool =
+        object
+          [ "name" .= ("lookup" :: Text),
+            "description" .= ("Look up a color" :: Text),
+            "input_schema" .= schemaFixture,
+            "strict" .= True,
+            "cache_control" .= object ["type" .= ("ephemeral" :: Text), "ttl" .= ("5m" :: Text)]
+          ]
+      app req send = do
+        body <- requestJson req
+        let check expected key = assertEqual "request field" expected (field key body)
+        case lookup "x-case" (Wai.requestHeaders req) of
+          Just "schema" -> do
+            check (Just expectedOutput) "output_config"
+            check Nothing "tools"
+            check Nothing "tool_choice"
+          Just "count" -> do
+            assertEqual "count path" "/v1/messages/count_tokens" (Wai.rawPathInfo req)
+            check (Just expectedOutput) "output_config"
+            check Nothing "max_tokens"
+          Just "tool" -> do
+            check Nothing "output_config"
+            check (Just (toJSON [expectedTool])) "tools"
+            check (Just (object ["type" .= ("tool" :: Text), "name" .= ("lookup" :: Text)])) "tool_choice"
+          Just "both" -> do
+            check (Just expectedOutput) "output_config"
+            check (Just (toJSON [expectedTool])) "tools"
+            check (Just (toJSON Fast)) "speed"
+            assertEqual "fast-mode beta" (Just "fast-mode-2026-02-01") (lookup "anthropic-beta" (Wai.requestHeaders req))
+          _ -> fail "Unknown fixture"
+        if Wai.rawPathInfo req == "/v1/messages/count_tokens"
+          then send (json status200 [] (object ["input_tokens" .= (17 :: Int)]))
+          else send (json status200 [] (putField "stop_reason" "refusal" (messageFixture [textBlock "{\"ok\":true}" []])))
+  withClient app $ \client -> do
+    let options tag = enrichedOptions {extraHeaders = [("x-case", tag)]}
+    Response _ refused <- createMessage client (options "schema") schemaRequest >>= expectRight
+    assertEqual "refusal remains a successful HTTP response" (Just Refusal) (refused ^. #stopReason)
+    assertEqual "structured output text" "{\"ok\":true}" (responseText refused)
+    _ <- createMessage client (options "tool") toolsRequest >>= expectRight
+    _ <- createMessage client (options "both") bothRequest >>= expectRight
+    Response _ counted <- countTokens client (options "count") (CountRequest schemaConvo) >>= expectRight
+    assertEqual "count with schema" (TokenCount 17) counted
+
+consecutiveToolRounds :: IO ()
+consecutiveToolRounds = do
+  call <- newIORef (0 :: Int)
+  request <- sampleRequest enrichedConversation
+  let first = [thinkingBlock "" "signature-1", toolUseBlock "toolu_1"]
+      second = [thinkingBlock "visible" "signature-2", redactedBlock, toolUseBlock "toolu_2"]
+      historyPrefix = conversationHistory enrichedConversation
+      toolReply toolId = Message User (InputToolResult (ToolResult toolId (ToolResultText "green") Nothing Nothing) :| [])
+      resultJson toolId =
+        object
+          [ "role" .= ("user" :: Text),
+            "content" .= [object ["type" .= ("tool_result" :: Text), "tool_use_id" .= toolId, "content" .= ("green" :: Text)]]
+          ]
+      historyWith blocks toolId =
+        [object ["role" .= ("assistant" :: Text), "content" .= blocks], resultJson (toolId :: Text)]
+      expectedHistory = map toJSON (historyPrefix)
+      app req send = do
+        number <- atomicModifyIORef' call (\n -> (n + 1, n))
+        body <- requestJson req
+        assertEqual "adaptive omitted display" (Just (object ["type" .= ("adaptive" :: Text), "display" .= ("omitted" :: Text)])) (field "thinking" body)
+        assertEqual
+          "cached system"
+          ( Just
+              ( toJSON
+                  [ object
+                      [ "type" .= ("text" :: Text),
+                        "text" .= ("Cite the supplied material." :: Text),
+                        "cache_control" .= object ["type" .= ("ephemeral" :: Text), "ttl" .= ("1h" :: Text)]
+                      ]
+                  ]
+              )
+          )
+          (field "system" body)
+        assertEqual "automatic cache" (Just (object ["type" .= ("ephemeral" :: Text)])) (field "cache_control" body)
+        let respond blocks = send (json status200 [] (putField "stop_reason" "tool_use" (messageFixture blocks)))
+        case number of
+          0 -> respond first
+          1 -> do
+            assertEqual "first continuation" (Just (toJSON (expectedHistory <> historyWith first "toolu_1"))) (field "messages" body)
+            respond second
+          _ -> do
+            assertEqual "two consecutive continuations" (Just (toJSON (expectedHistory <> historyWith first "toolu_1" <> historyWith second "toolu_2"))) (field "messages" body)
+            send (json status200 [] (messageFixture [textBlock "green" []]))
+      go client history = do
+        let updated = request {conversation = withConversationHistory history enrichedConversation}
+        Response _ result <- createMessage client enrichedOptions updated >>= expectRight
+        pure result
+  withClient app $ \client -> do
+    firstResponse <- go client historyPrefix
+    firstAssistant <- maybe (fail "missing first continuation") pure (assistantContinuation firstResponse)
+    let secondHistory = historyPrefix <> [firstAssistant, toolReply "toolu_1"]
+    secondResponse <- go client secondHistory
+    secondAssistant <- maybe (fail "missing second continuation") pure (assistantContinuation secondResponse)
+    lastResponse <- go client (secondHistory <> [secondAssistant, toolReply "toolu_2"])
+    assertEqual "two-tool continuation result" "green" (responseText lastResponse)
+  readIORef call >>= assertEqual "tool-round dispatch count" 3
+  assertEqual
+    "manual thinking budget"
+    (object ["type" .= ("enabled" :: Text), "budget_tokens" .= (1024 :: Int)])
+    (toJSON (ManualBudget 1024 Nothing))
+  assertEqual "thinking disabled" (object ["type" .= ("disabled" :: Text)]) (toJSON ThinkingDisabled)
+
+webCitation :: Value
+webCitation =
+  object
+    [ "type" .= ("web_search_result_location" :: Text),
+      "cited_text" .= ("forest" :: Text),
+      "url" .= ("https://example.test/report" :: Text),
+      "title" .= ("Report" :: Text),
+      "encrypted_index" .= ("encrypted-index" :: Text)
+    ]
+
+citationsAndSearch :: IO ()
+citationsAndSearch = do
+  let citation =
+        object
+          [ "type" .= ("char_location" :: Text),
+            "cited_text" .= ("forest" :: Text),
+            "document_index" .= (0 :: Int),
+            "document_title" .= ("Report" :: Text),
+            "start_char_index" .= (2 :: Int),
+            "end_char_index" .= (8 :: Int)
+          ]
+      searchHit =
+        object
+          [ "type" .= ("web_search_result" :: Text),
+            "url" .= ("https://example.test/report" :: Text),
+            "title" .= ("Report" :: Text),
+            "encrypted_content" .= ("encrypted-hit" :: Text),
+            "page_age" .= ("today" :: Text)
+          ]
+      searchCall =
+        object
+          [ "type" .= ("server_tool_use" :: Text),
+            "id" .= ("srvtoolu_1" :: Text),
+            "name" .= ("web_search" :: Text),
+            "input" .= object ["query" .= ("forests" :: Text)]
+          ]
+      searchResult = object ["type" .= ("web_search_tool_result" :: Text), "tool_use_id" .= ("srvtoolu_1" :: Text), "content" .= [searchHit]]
+      searchError =
+        object
+          [ "type" .= ("web_search_tool_result" :: Text),
+            "tool_use_id" .= ("srvtoolu_2" :: Text),
+            "content" .= object ["type" .= ("web_search_tool_result_error" :: Text), "error_code" .= ("overloaded" :: Text)]
+          ]
+      future = object ["type" .= ("future_tool_result" :: Text), "content" .= True]
+      blocks = [searchCall, searchResult, searchError, textBlock "document" [citation], textBlock "web" [webCitation], future]
+      document = PlainTextDocument "A forest" (Just "Report") Nothing True Nothing
+      convo =
+        (withConversationHistory [Message User (InputDocument document :| [])] baseConversation)
+          { features = defaultMessageFeatures {tools = [WebSearchTool (WebSearch WebSearch20250305 (Just 2) Nothing)]}
+          }
+      reply =
+        putField
+          "usage"
+          ( object
+              [ "input_tokens" .= (17 :: Int),
+                "output_tokens" .= (8 :: Int),
+                "cache_creation_input_tokens" .= (4 :: Int),
+                "cache_read_input_tokens" .= (6 :: Int)
+              ]
+          )
+          (messageFixture blocks)
+      app req send = do
+        body <- requestJson req
+        assertEqual "versioned web search" (Just (toJSON [object ["type" .= ("web_search_20250305" :: Text), "name" .= ("web_search" :: Text), "max_uses" .= (2 :: Int)]])) (field "tools" body)
+        case lookup "x-case" (Wai.requestHeaders req) of
+          Just "replay" -> do
+            let expected = object ["role" .= ("assistant" :: Text), "content" .= blocks]
+            assert "assistant evidence in replay" (maybe False (contains expected) (field "messages" body))
+          _ -> assertEqual "document and enabled citations" (Just (toJSON (conversationHistory convo))) (field "messages" body)
+        send (json status200 [] reply)
+  request <- sampleRequest convo
+  withClient app $ \client -> do
+    Response _ result <- createMessage client defaultRequestOptions request >>= expectRight
+    let counters = result ^. #usage
+    assertEqual "cache counters" (Just 4, Just 6) (counters ^. #cacheCreationInputTokens, counters ^. #cacheReadInputTokens)
+    case map blockContent (result ^. #content) of
+      [ ServerToolUse "srvtoolu_1" "web_search" _,
+        WebSearchToolResult "srvtoolu_1" (WebSearchResults [SearchResult _ _ "encrypted-hit" (Just "today")]),
+        WebSearchToolResult "srvtoolu_2" (WebSearchError "overloaded"),
+        OutputText "document" (Just [Citation (CharacterRange "forest" 0 (Just "Report") 2 8) _]),
+        OutputText "web" (Just [Citation (WebLocation "forest" "https://example.test/report" (Just "Report") "encrypted-index") _]),
+        UnknownBlock "future_tool_result"
+        ] -> pure ()
+      _ -> fail "Expected typed document, web and future response blocks"
+    resumed <- maybe (fail "missing search continuation") pure (assistantContinuation result)
+    let replay = request {conversation = withConversationHistory (conversationHistory convo <> [resumed, Message User (InputText "Summarize" :| [])]) convo}
+    _ <- createMessage client (defaultRequestOptions {extraHeaders = [("x-case", "replay")]}) replay >>= expectRight
+    pure ()
+  where
+    contains needle (Array fields) = needle `elem` fields
+    contains _ _ = False
+
+malformedKnownBlock :: IO ()
+malformedKnownBlock = do
+  request <- sampleRequest baseConversation
+  let malformed = object ["type" .= ("thinking" :: Text), "thinking" .= ("" :: Text)]
+      app _ send = send (json status200 [] (messageFixture [malformed]))
+  withClient app $ \client ->
+    createMessage client defaultRequestOptions request >>= \case
+      Left (DecodeError _ _) -> pure ()
+      _ -> fail "Missing signature should produce a decode error"
+
+textBlock :: Text -> [Value] -> Value
+textBlock body cites = object ["type" .= ("text" :: Text), "text" .= body, "citations" .= cites]
+
+field :: Key -> Value -> Maybe Value
+field key (Object o) = KeyMap.lookup key o
+field _ _ = Nothing
+
+putField :: Key -> Value -> Value -> Value
+putField key item (Object o) = Object (KeyMap.insert key item o)
+putField _ _ raw = raw
diff --git a/test/Main.hs b/test/Main.hs
new file mode 100644
--- /dev/null
+++ b/test/Main.hs
@@ -0,0 +1,9 @@
+module Main (main) where
+
+import BatchesSpec qualified
+import FeaturesSpec qualified
+import MessagesSpec qualified
+import StreamingSpec qualified
+
+main :: IO ()
+main = MessagesSpec.run >> FeaturesSpec.run >> StreamingSpec.run >> BatchesSpec.run
diff --git a/test/MessagesSpec.hs b/test/MessagesSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/MessagesSpec.hs
@@ -0,0 +1,426 @@
+module MessagesSpec (run, baseConversation, messageFixture, messageWithEvidence, sampleRequest) where
+
+import Claude.Batches (BatchItem (..), createBatch, mkCustomId)
+import Claude.Client
+import Claude.Messages
+import Claude.Streaming qualified as Claude
+import Control.Lens ((^.))
+import Control.Monad (void, when)
+import Data.Aeson (Key, Value (..), eitherDecode, encode, object, toJSON, (.=))
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.Aeson.Types (Pair)
+import Data.Generics.Labels ()
+import Data.IORef (atomicModifyIORef', modifyIORef', newIORef, readIORef)
+import Data.List (isInfixOf)
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.Map.Strict qualified as Map
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Network.HTTP.Types (status200, status302, status429, status502)
+import Network.Wai qualified as Wai
+import Support.Server
+
+baseConversation :: Conversation
+baseConversation = Conversation "candidate-model" (Message User (InputText "Hello" :| []) :| []) Nothing defaultMessageFeatures
+
+sampleRequest :: Conversation -> IO MessageRequest
+sampleRequest convo = maybe (fail "internal fixture limit") (\limit -> pure (MessageRequest convo limit [])) (maxTokens 256)
+
+messageFixture :: [Value] -> Value
+messageFixture blocks =
+  object
+    [ "id" .= ("msg_1" :: Text),
+      "type" .= ("message" :: Text),
+      "model" .= ("candidate-model" :: Text),
+      "role" .= ("assistant" :: Text),
+      "content" .= blocks,
+      "stop_reason" .= ("end_turn" :: Text),
+      "stop_sequence" .= (Nothing :: Maybe Text),
+      "usage" .= object ["input_tokens" .= (17 :: Int), "output_tokens" .= (8 :: Int)]
+    ]
+
+run :: IO ()
+run = do
+  textRoundtrip
+  tokensRoundtrip
+  failureCases
+  requestControlsRoundtrip
+  cachePrewarm
+  advancedRequestRoundtrip
+  advancedContinuation
+  fallbackContinuation
+  unaryEvidence
+  putStrLn "Messages: text, session headers, token count and failure fixtures passed"
+
+textRoundtrip :: IO ()
+textRoundtrip = do
+  request <- sampleRequest baseConversation
+  let future = object ["type" .= ("future" :: Text), "state" .= True]
+      options = defaultRequestOptions {betaFeatures = ["beta-one", "beta-two"], extraHeaders = [("x-session-affinity", "session-7")]}
+      app req send = do
+        assertEqual "method" "POST" (Wai.requestMethod req)
+        assertEqual "path" "/v1/messages" (Wai.rawPathInfo req)
+        assertEqual "key" (Just "loopback-secret") (lookup "x-api-key" (Wai.requestHeaders req))
+        assertEqual "version" (Just "2026-10-21") (lookup "anthropic-version" (Wai.requestHeaders req))
+        assertEqual "betas" (Just "beta-one,beta-two") (lookup "anthropic-beta" (Wai.requestHeaders req))
+        assertEqual "session affinity" (Just "session-7") (lookup "x-session-affinity" (Wai.requestHeaders req))
+        requestJson req
+          >>= assertEqual
+            "body"
+            ( object
+                [ "model" .= ("candidate-model" :: Text),
+                  "max_tokens" .= (256 :: Int),
+                  "messages"
+                    .= [ object
+                           [ "role" .= ("user" :: Text),
+                             "content" .= [object ["type" .= ("text" :: Text), "text" .= ("Hello" :: Text)]]
+                           ]
+                       ]
+                ]
+            )
+        send (json status200 [("request-id", "req_1")] (messageFixture [object ["type" .= ("text" :: Text), "text" .= ("Hi" :: Text)], future]))
+  withClient app $ \client -> do
+    Response meta response <- createMessage client options request >>= expectRight
+    assertEqual "request ID" (Just "req_1") (requestId meta)
+    let MessageResponse messageId modelId sender blocks reason matchedStop counters _ _ _ = response
+    assertEqual "typed message metadata" ("msg_1", "candidate-model", Assistant, Just EndTurn, Nothing, Usage 17 8 Nothing Nothing Nothing Nothing (UsageEvidence Nothing Nothing Nothing Nothing Nothing Nothing)) (messageId, modelId, sender, reason, matchedStop, counters)
+    assertEqual "typed blocks" [OutputText "Hi" Nothing, UnknownBlock "future"] (map blockContent blocks)
+    assertEqual "unknown block payload" [future] (drop 1 (map blockJSON blocks))
+    createMessage client (options {extraHeaders = [("HOST", "wrong-host")]}) request >>= \case
+      Left (InvalidRequest _) -> pure ()
+      _ -> fail "Host override must be rejected"
+
+tokensRoundtrip :: IO ()
+tokensRoundtrip = do
+  let history =
+        Message User (InputText "First" :| [])
+          :| [ Message Assistant (InputText "Welcome" :| []),
+               Message User (InputImage (Base64Image "image/png" "aW1hZ2U=") :| [InputImage (ImageUrl "https://example.test/image.png")])
+             ]
+      convo = Conversation "candidate-model" history (Just (SystemText "Use the image.")) defaultMessageFeatures
+      app req send = do
+        assertEqual "count method" "POST" (Wai.requestMethod req)
+        assertEqual "count path" "/v1/messages/count_tokens" (Wai.rawPathInfo req)
+        requestJson req
+          >>= assertEqual
+            "count body"
+            ( object
+                [ "model" .= ("candidate-model" :: Text),
+                  "messages"
+                    .= [ turn "user" [text "First"],
+                         turn "assistant" [text "Welcome"],
+                         turn
+                           "user"
+                           [ image ["type" .= ("base64" :: Text), "media_type" .= ("image/png" :: Text), "data" .= ("aW1hZ2U=" :: Text)],
+                             image ["type" .= ("url" :: Text), "url" .= ("https://example.test/image.png" :: Text)]
+                           ]
+                       ],
+                  "system" .= ("Use the image." :: Text)
+                ]
+            )
+        send (json status200 [] (object ["input_tokens" .= (17 :: Int)]))
+  withClient app $ \client -> do
+    Response _ result <- countTokens client defaultRequestOptions (CountRequest convo) >>= expectRight
+    assertEqual "input tokens" (TokenCount 17) result
+  where
+    text body = object ["type" .= ("text" :: Text), "text" .= (body :: Text)]
+    image source = object ["type" .= ("image" :: Text), "source" .= object source]
+
+failureCases :: IO ()
+failureCases = do
+  request <- sampleRequest baseConversation
+  calls <- newIORef (0 :: Int)
+  let app req send = do
+        _ <- Wai.strictRequestBody req
+        modifyIORef' calls (+ 1)
+        case lookup "x-fixture" (Wai.requestHeaders req) of
+          Just "rate-limit" ->
+            send
+              ( json
+                  status429
+                  [("request-id", "req_rate"), ("retry-after", "3")]
+                  ( object
+                      ["error" .= object ["type" .= ("rate_limit_error" :: Text), "message" .= ("Echo loopback-secret" :: Text)]]
+                  )
+              )
+          Just "invalid-json" -> send (Wai.responseLBS status200 [("request-id", "req_decode")] "invalid")
+          Just "redirect" -> send (Wai.responseLBS status302 [("location", "/other-origin")] "")
+          Just "disconnect" -> send (Wai.responseRaw (\_ _ -> pure ()) (Wai.responseLBS status502 [] ""))
+          _ -> send (Wai.responseLBS status502 [] "Bad gateway")
+  withClient app $ \client -> do
+    let call fixture = createMessage client (defaultRequestOptions {extraHeaders = [("x-fixture", fixture)]}) request
+    call "rate-limit" >>= \case
+      Left err@(ApiStatusError meta (Just (ApiError "rate_limit_error" detail)) excerpt) -> do
+        assertEqual "retry metadata" (Just "req_rate", Just "3", 429) (requestId meta, retryAfter meta, status meta)
+        assert "redacted HTTP body" (not ("loopback-secret" `Text.isInfixOf` excerpt))
+        assertEqual "redacted detail" "Echo [redacted]" detail
+        assert "secret absent from Show" (not ("loopback-secret" `isInfixOf` show err))
+      _ -> fail "Expected structured rate limit"
+    call "gateway" >>= \case
+      Left (ApiStatusError (ResponseMetadata Nothing Nothing 502 _ _ _) Nothing "Bad gateway") -> pure ()
+      _ -> fail "Expected non-JSON status error"
+    call "invalid-json" >>= \case
+      Left (DecodeError (ResponseMetadata (Just "req_decode") Nothing 200 _ _ _) _) -> pure ()
+      _ -> fail "Expected JSON decode failure"
+    call "redirect" >>= \case
+      Left (ApiStatusError (ResponseMetadata _ _ 302 _ _ _) Nothing _) -> pure ()
+      _ -> fail "Expected redirect to be returned as HTTP failure"
+    call "disconnect" >>= \case
+      Left (TransportError _ Disconnected) -> pure ()
+      Left err -> fail ("Expected disconnected request, got " <> show err)
+      Right _ -> fail "Disconnected request succeeded"
+  readIORef calls >>= assertEqual "one dispatch per operation" 5
+
+requestControlsRoundtrip :: IO ()
+requestControlsRoundtrip = do
+  empty <- sampleRequest (EmptyConversation "claude-sonnet-4-6" Nothing defaultMessageFeatures)
+  filled <- sampleRequest (Conversation "claude-sonnet-4-6" (Message User (InputText "Hello" :| []) :| []) Nothing defaultMessageFeatures)
+  let tuning = defaultRequestControls {temperature = Just 0.2, topP = Just 0.7, topK = Just 15}
+      emptyJSON = object ["model" .= ("claude-sonnet-4-6" :: Text), "max_tokens" .= (256 :: Int), "messages" .= ([] :: [Value]), "stream" .= True]
+      samplingJSON = object ["model" .= ("claude-sonnet-4-6" :: Text), "max_tokens" .= (256 :: Int), "messages" .= [userHello], "temperature" .= (0.2 :: Double), "top_p" .= (0.7 :: Double), "top_k" .= (15 :: Int)]
+      legacy = (defaultClientConfig "loopback-secret") {apiVersion = Just "2023-06-01"}
+      opts = defaultRequestOptions
+  withClientConfig legacy (capture emptyJSON sseStop) $ \client ->
+    void $ Claude.streamMessage client opts empty (\_ _ -> pure Claude.Continue) >>= expectRight
+  withClientConfig legacy (capture samplingJSON (json status200 [] (messageFixture []))) $ \client ->
+    void $ createMessage client opts (withRequestControls tuning filled) >>= expectRight
+  calls <- newIORef (0 :: Int)
+  withClient (\_ send -> modifyIORef' calls (+ 1) >> send sseStop) $ \client -> do
+    invalid "nonempty" =<< Claude.streamMessage client opts empty (\_ _ -> pure Claude.Continue)
+    invalid "sampling" =<< Claude.streamMessage client opts (withRequestControls tuning filled) (\_ _ -> pure Claude.Continue)
+    invalid "sampling" =<< createMessage client opts (withRequestControls tuning filled)
+    invalid "nonempty" =<< countTokens client opts (CountRequest (conversation empty))
+    ident <- maybe (fail "invalid test ID") pure (mkCustomId "example")
+    invalid "sampling" =<< createBatch client opts (BatchItem ident (withRequestControls tuning filled) :| [])
+  readIORef calls >>= assertEqual "invalid requests never dispatched" 0
+  where
+    invalid fragment = \case
+      Left (InvalidRequest detail) -> assert "validation detail" (fragment `Text.isInfixOf` detail)
+      _ -> fail "expected InvalidRequest"
+
+advancedRequestRoundtrip :: IO ()
+advancedRequestRoundtrip = do
+  let schema = KeyMap.fromList ["type" .= ("object" :: Text)]
+      tool = ClientTool "lookup" Nothing schema Nothing Nothing
+      toolFeatures =
+        defaultMessageFeatures
+          { tools = [CodeExecutionTool CodeExecution20250825 Nothing, ToolSearchTool BM25Search20251119 Nothing, ToolSearchTool RegexSearch20251119 Nothing, ConfiguredTool tool (ToolLoading (Just True) (Just [AllowDirect, AllowCodeExecution CodeExecution20250825])), CustomTool (ClientTool "old_lookup" Nothing schema Nothing Nothing)]
+          }
+      toolCall = InputToolUse "toolu_1" "lookup" (object []) (Just (CodeExecutionCaller CodeExecution20250825 "srvtoolu_1"))
+      systemChange = Message System (ToolAddition (ToolReference "lookup") Nothing :| [ToolRemoval (ToolReference "old_lookup") Nothing])
+      convo = Conversation "claude-opus-4-8" (Message User (InputText "Hello" :| []) :| [systemChange, Message Assistant (toolCall :| []), Message User (InputToolResult (ToolResult "toolu_1" (ToolResultText "result") Nothing Nothing) :| [])]) Nothing toolFeatures
+      controls =
+        defaultRequestControls
+          { containerId = Just "container_1",
+            metadata = Just (Map.singleton "user_id" "user_1"),
+            contextManagement = Just [Compaction (Just "Keep names") (Just True) (Just 100000)],
+            inferenceGeo = Just "us",
+            fallbacks = Just (FallbackModels [FallbackModel "claude-sonnet-4-6" (Just 128) Nothing Nothing Nothing])
+          }
+      opts = defaultRequestOptions {betaFeatures = ["inline-tools-2026-09-15", "compact-2026-01-12", "server-side-fallback-2026-07-01"]}
+      history =
+        [ userHello,
+          turn "system" [tagged "tool_addition" ["tool" .= tagged "tool_reference" ["name" .= ("lookup" :: Text)]], tagged "tool_removal" ["tool" .= tagged "tool_reference" ["name" .= ("old_lookup" :: Text)]]],
+          turn "assistant" [tagged "tool_use" ["id" .= ("toolu_1" :: Text), "name" .= ("lookup" :: Text), "input" .= object [], "caller" .= tagged "code_execution_20250825" ["tool_id" .= ("srvtoolu_1" :: Text)]]],
+          turn "user" [tagged "tool_result" ["tool_use_id" .= ("toolu_1" :: Text), "content" .= ("result" :: Text)]]
+        ]
+      toolsJSON =
+        [ tagged "code_execution_20250825" ["name" .= ("code_execution" :: Text)],
+          tagged "tool_search_tool_bm25_20251119" ["name" .= ("tool_search_tool_bm25" :: Text)],
+          tagged "tool_search_tool_regex_20251119" ["name" .= ("tool_search_tool_regex" :: Text)],
+          object ["name" .= ("lookup" :: Text), "input_schema" .= object ["type" .= ("object" :: Text)], "defer_loading" .= True, "allowed_callers" .= (["direct", "code_execution_20250825"] :: [Text])],
+          object ["name" .= ("old_lookup" :: Text), "input_schema" .= object ["type" .= ("object" :: Text)]]
+        ]
+      promptFields = ["model" .= ("claude-opus-4-8" :: Text), "messages" .= history, "tools" .= toolsJSON]
+      expected =
+        object $
+          promptFields
+            <> [ "max_tokens" .= (256 :: Int),
+                 "stop_sequences" .= (["done"] :: [Text]),
+                 "container" .= ("container_1" :: Text),
+                 "metadata" .= object ["user_id" .= ("user_1" :: Text)],
+                 "context_management" .= object ["edits" .= [tagged "compact_20260112" ["instructions" .= ("Keep names" :: Text), "pause_after_compaction" .= True, "trigger" .= tagged "input_tokens" ["value" .= (100000 :: Int)]]]],
+                 "inference_geo" .= ("us" :: Text),
+                 "fallbacks" .= [object ["model" .= ("claude-sonnet-4-6" :: Text), "max_tokens" .= (128 :: Int)]]
+               ]
+      app req send = do
+        assertEqual "advanced beta header" (Just "inline-tools-2026-09-15,compact-2026-01-12,server-side-fallback-2026-07-01") (lookup "anthropic-beta" (Wai.requestHeaders req))
+        case Wai.rawPathInfo req of
+          "/v1/messages" -> capture expected (json status200 [] (messageFixture [])) req send
+          "/v1/messages/count_tokens" -> capture (object promptFields) (json status200 [] (object ["input_tokens" .= (10 :: Int)])) req send
+          _ -> fail "unexpected request route"
+  base <- sampleRequest convo
+  let request = withRequestControls controls base {stopSequences = ["done"]}
+  withClient app $ \client -> do
+    _ <- createMessage client opts request >>= expectRight
+    void $ countTokens client opts (CountRequest convo) >>= expectRight
+  decoded <- expectRight (eitherDecode (encode expected))
+  assertEqual "advanced request JSON decode and re-encode" expected (toJSON (decoded :: MessageRequest))
+
+capture :: Value -> Wai.Response -> Wai.Application
+capture expected reply req send = requestJson req >>= assertEqual "captured request" expected >> send reply
+
+sseStop :: Wai.Response
+sseStop = Wai.responseLBS status200 [("content-type", "text/event-stream")] "data: {\"type\":\"message_stop\"}\n\n"
+
+turn :: Text -> [Value] -> Value
+turn sender blocks = object ["role" .= sender, "content" .= blocks]
+
+tagged :: Text -> [Pair] -> Value
+tagged tag fields = object (("type" .= tag) : fields)
+
+userHello :: Value
+userHello = turn "user" [tagged "text" ["text" .= ("Hello" :: Text)]]
+
+advancedContinuation :: IO ()
+advancedContinuation = do
+  let schema = KeyMap.singleton "type" (String "object")
+      features_ =
+        defaultMessageFeatures
+          { tools =
+              [ ToolSearchTool BM25Search20251119 Nothing,
+                CodeExecutionTool CodeExecution20260120 Nothing,
+                ConfiguredTool (ClientTool "lookup" Nothing schema Nothing Nothing) (ToolLoading (Just True) (Just [AllowDirect, AllowCodeExecution CodeExecution20260120]))
+              ]
+          }
+      serverCall ident name_ = tagged "server_tool_use" ["id" .= (ident :: Text), "name" .= (name_ :: Text), "input" .= object []]
+      search =
+        tagged
+          "tool_search_tool_result"
+          ["tool_use_id" .= ("srvtoolu_search" :: Text), "content" .= tagged "tool_search_tool_search_result" ["tool_references" .= [tagged "tool_reference" ["tool_name" .= ("lookup" :: Text)]]]]
+      code =
+        tagged
+          "code_execution_tool_result"
+          ["tool_use_id" .= ("srvtoolu_done" :: Text), "content" .= tagged "code_execution_result" ["stdout" .= ("done" :: Text), "stderr" .= ("" :: Text), "return_code" .= (0 :: Int), "content" .= ([] :: [Value])]]
+      tool =
+        tagged
+          "tool_use"
+          [ "id" .= ("toolu_1" :: Text),
+            "name" .= ("lookup" :: Text),
+            "input" .= object [],
+            "caller" .= tagged "code_execution_20260120" ["tool_id" .= ("srvtoolu_pending" :: Text), "future_caller_field" .= True],
+            "future_tool_field" .= (1 :: Int)
+          ]
+      unknown = tagged "future_only" ["passed_through" .= True]
+      knownBlocks = [serverCall "srvtoolu_search" "tool_search_tool_bm25", search, serverCall "srvtoolu_done" "code_execution", code, serverCall "srvtoolu_pending" "code_execution", tool]
+      blocks = knownBlocks <> [unknown]
+      toolResult = InputToolResult (ToolResult "toolu_1" (ToolResultText "result") Nothing Nothing)
+      resultJson = tagged "tool_result" ["tool_use_id" .= ("toolu_1" :: Text), "content" .= ("result" :: Text)]
+      container_ = object ["id" .= ("container_1" :: Text), "expires_at" .= ("2026-11-20T23:30:00Z" :: Text)]
+      fixture = addField "container" container_ $ addField "stop_reason" "tool_use" $ messageFixture blocks
+      conversation_ = Conversation "claude-opus-5-5" (Message User (InputText "Hello" :| []) :| []) Nothing features_
+      opts = defaultRequestOptions
+  request <- sampleRequest conversation_
+  twoTurns opts request fixture (toolResult :| []) $ \initial result outgoing -> do
+    assertEqual "exact opaque provider observations" fixture (toJSON result)
+    case map blockContent (result ^. #content) of
+      [ServerToolUse {}, OutputToolSearchResult _ (ToolSearchMatches ["lookup"]), ServerToolUse {}, OutputCodeExecutionResult _ (CodeExecutionCompleted "done" "" 0 []), ServerToolUse {}, OutputToolUseWithCaller "toolu_1" "lookup" _ (CodeExecutionCaller CodeExecution20260120 "srvtoolu_pending"), UnknownBlock "future_only"] -> pure ()
+      _ -> fail "missing typed continuation evidence"
+    assertEqual
+      "second request history and container"
+      (addField "container" "container_1" (addField "messages" (toJSON [userHello, turn "assistant" knownBlocks, turn "user" [resultJson]]) initial))
+      outgoing
+
+fallbackContinuation :: IO ()
+fallbackContinuation = do
+  let textBlock body = tagged "text" ["text" .= (body :: Text)]
+      marker =
+        tagged
+          "fallback"
+          [ "from" .= object ["model" .= ("claude-fable-5" :: Text)],
+            "to" .= object ["model" .= ("claude-opus-4-8" :: Text)],
+            "trigger" .= tagged "refusal" ["category" .= ("other" :: Text)]
+          ]
+      suffix = textBlock "Fallback text"
+      fixture = addField "model" "claude-opus-4-8" (messageFixture [marker, suffix])
+      opts = defaultRequestOptions {betaFeatures = ["server-side-fallback-2026-07-01"]}
+      conversation_ = Conversation "claude-fable-5" (Message User (InputText "Hello" :| []) :| []) Nothing defaultMessageFeatures
+  request <- withRequestControls defaultRequestControls {fallbacks = Just DefaultFallbacks} <$> sampleRequest conversation_
+  let explicit = Message Assistant (InputFallback (FallbackMarker "claude-fable-5" "claude-opus-4-8" "refusal" (Just "other")) :| [InputText "Fallback text"])
+  assertEqual "typed fallback history" (turn "assistant" [marker, suffix]) (toJSON explicit)
+  twoTurns opts request fixture (InputText "Continue" :| []) $ \initial result outgoing -> do
+    case map blockContent (result ^. #content) of
+      [OutputFallback (FallbackMarker "claude-fable-5" "claude-opus-4-8" "refusal" (Just "other")), OutputText {}] -> pure ()
+      _ -> fail "missing fallback identity"
+    assertEqual
+      "fallback keeps model, settings and marker order"
+      (addField "messages" (toJSON [userHello, turn "assistant" [marker, suffix], turn "user" [textBlock "Continue"]]) initial)
+      outgoing
+
+twoTurns ::
+  RequestOptions ->
+  MessageRequest ->
+  Value ->
+  NonEmpty InputBlock ->
+  (Value -> MessageResponse -> Value -> IO ()) ->
+  IO ()
+twoTurns options request fixture followUp check = do
+  requests <- newIORef []
+  let app req send = do
+        assertEqual "continuation version" (Just "2026-10-21") (lookup "anthropic-version" (Wai.requestHeaders req))
+        when (not (null (betaFeatures options))) $
+          assertEqual "fallback beta" (Just "server-side-fallback-2026-07-01") (lookup "anthropic-beta" (Wai.requestHeaders req))
+        body <- requestJson req
+        subsequent <- atomicModifyIORef' requests (\prior -> (prior <> [body], not (null prior)))
+        send (json status200 [] (if subsequent then messageFixture [] else fixture))
+  withClient app $ \client -> do
+    Response _ decoded <- createMessage client options request >>= expectRight
+    next <- maybe (fail "missing continuation") pure (continueMessage request decoded followUp)
+    _ <- createMessage client options next >>= expectRight
+    readIORef requests >>= \case
+      [initial, outgoing] -> check initial decoded outgoing
+      _ -> fail "expected exactly two requests"
+
+addField :: Key -> Value -> Value -> Value
+addField key value (Object fields) = Object (KeyMap.insert key value fields)
+addField _ _ value = value
+
+messageWithEvidence :: Value
+messageWithEvidence =
+  addField "stop_reason" "refusal" $
+    addField "stop_details" (tagged "refusal" ["category" .= ("other" :: Text), "explanation" .= ("declined" :: Text)]) $
+      addField
+        "usage"
+        ( object
+            [ "input_tokens" .= (17 :: Int),
+              "output_tokens" .= (8 :: Int),
+              "service_tier" .= ("priority" :: Text),
+              "speed" .= ("fast" :: Text),
+              "output_tokens_details" .= object ["thinking_tokens" .= (5 :: Int)]
+            ]
+        )
+        (messageFixture [])
+
+unaryEvidence :: IO ()
+unaryEvidence = do
+  request <- sampleRequest baseConversation
+  let app req send =
+        let result = case lookup "x-case" (Wai.requestHeaders req) of
+              Just "malformed" -> addField "stop_details" (tagged "refusal" ["explanation" .= True]) messageWithEvidence
+              _ -> messageWithEvidence
+         in send (json status200 [] result)
+  withClient app $ \client -> do
+    Response _ result <- createMessage client defaultRequestOptions request >>= expectRight
+    assertEqual "unary stop details" (Just (RefusalDetails (Just "other") (Just "declined") Nothing)) (result ^. #stopDetails)
+    assertEqual "unary reasoning" (Just (OutputTokenDetails (Just 5))) (result ^. #usage . #usageEvidence . #outputTokensDetails)
+    assertEqual "provider JSON" messageWithEvidence (toJSON result)
+    createMessage client defaultRequestOptions {extraHeaders = [("x-case", "malformed")]} request >>= \case
+      Left (DecodeError _ _) -> pure ()
+      _ -> fail "expected malformed stop details to fail decoding"
+
+cachePrewarm :: IO ()
+cachePrewarm = do
+  let request = MessageRequest baseConversation cacheOnly []
+      expected = object ["model" .= ("candidate-model" :: Text), "max_tokens" .= (0 :: Int), "messages" .= [userHello]]
+      fixture = addField "stop_reason" "max_tokens" (messageFixture [])
+      app = capture expected (json status200 [] fixture)
+  withClient app $ \client -> do
+    Response _ result <- createMessage client defaultRequestOptions request >>= expectRight
+    assertEqual "cache-only stop" (Just MaxTokensReached) (result ^. #stopReason)
+    Claude.streamMessage client defaultRequestOptions request (\_ _ -> pure Claude.Continue) >>= \case
+      Left (InvalidRequest _) -> pure ()
+      _ -> fail "cache-only request must be unary"
+    ident <- maybe (fail "invalid test ID") pure (mkCustomId "cache-only")
+    createBatch client defaultRequestOptions (BatchItem ident request :| []) >>= \case
+      Left (InvalidRequest _) -> pure ()
+      _ -> fail "cache-only request cannot be batched"
diff --git a/test/StreamingSpec.hs b/test/StreamingSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/StreamingSpec.hs
@@ -0,0 +1,369 @@
+module StreamingSpec (run) where
+
+import Claude.Client
+import Claude.Messages
+import Claude.Streaming
+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar, threadDelay)
+import Control.Exception (bracket, try)
+import Control.Lens ((&), (.~), (^.))
+import Control.Monad (forM_, void)
+import Data.Aeson (Key, Value (..), eitherDecode, eitherDecodeStrict, encode, object, toJSON, (.=))
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.ByteString.Builder (byteString)
+import Data.ByteString.Char8 qualified as BSC
+import Data.ByteString.Lazy qualified as LBS
+import Data.Generics.Labels ()
+import Data.IORef (modifyIORef', newIORef, readIORef)
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.Text (Text)
+import Data.Text.Encoding (encodeUtf8)
+import FeaturesSpec (thinkingBlock, webCitation)
+import MessagesSpec (baseConversation, messageFixture, sampleRequest)
+import Network.HTTP.Types (status200)
+import Network.Wai qualified as Wai
+import Numeric (showHex)
+import Support.Server
+
+run :: IO ()
+run = do
+  gatedRelease
+  fragmentedEvents
+  streamToolContinuation
+  advancedEvidence
+  streamFailures
+  legacyBridge
+  putStrLn "Streaming: delivery, cancellation, framing, continuation and failure fixtures passed"
+
+event :: Text -> [(Key, Value)] -> Value
+event tag fields = object (("type" .= tag) : fields)
+
+frame :: Value -> ByteString
+frame payload = "data: " <> LBS.toStrict (encode payload) <> "\n\n"
+
+messageStart :: Value
+messageStart = event "message_start" ["message" .= messageFixture []]
+
+textDelta :: Int -> Text -> Value
+textDelta index value = event "content_block_delta" ["index" .= index, "delta" .= event "text_delta" ["text" .= value]]
+
+blockStart :: Int -> Value -> Value
+blockStart index value = event "content_block_start" ["index" .= index, "content_block" .= value]
+
+blockDelta :: Int -> Value -> Value
+blockDelta index value = event "content_block_delta" ["index" .= index, "delta" .= value]
+
+blockStop :: Int -> Value
+blockStop index = event "content_block_stop" ["index" .= index]
+
+messageStop :: Value
+messageStop = event "message_stop" []
+
+sse :: ByteString -> Wai.Response
+sse body = Wai.responseLBS status200 [("content-type", "text/event-stream"), ("request-id", "req_stream")] (LBS.fromStrict body)
+
+gatedRelease :: IO ()
+gatedRelease = forM_ (["stop", "exception", "cancel", "finish"] :: [String]) $ \mode -> do
+  entered <- newEmptyMVar
+  released <- newEmptyMVar
+  allowFinish <- newEmptyMVar
+  never <- newEmptyMVar
+  request <- sampleRequest baseConversation
+  let app req send = do
+        sent <- requestJson req
+        assertEqual "stream request" (addStreamFlag (toJSON request)) sent
+        assertEqual "stream accept" (Just "text/event-stream") (lookup "accept" (Wai.requestHeaders req))
+        send $
+          Wai.responseRaw
+            ( \recv write -> do
+                write "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\nRequest-Id: req_gated\r\n\r\n"
+                write (httpChunk (frame messageStart))
+                if mode == "finish" then takeMVar allowFinish >> write (httpChunk (frame messageStop)) else pure ()
+                recv >>= putMVar released
+            )
+            (sse "")
+      checkStart meta streamEvent = do
+        assertEqual "stream correlation" (Just "req_gated") (meta ^. #requestId)
+        case streamEvent ^. #eventPayload of
+          MessageStart _ -> putMVar entered ()
+          MessageStop -> pure ()
+          _ -> fail "Unexpected event"
+  withClient app $ \client -> do
+    let streaming = streamMessage client defaultRequestOptions request
+    case mode of
+      "stop" -> do
+        Response _ terminal <- streaming (\meta ev -> checkStart meta ev >> pure Stop) >>= expectRight
+        assertEqual "caller stopped" Stopped terminal
+        takeMVar entered
+      "exception" -> do
+        result <- try (streaming (\meta ev -> checkStart meta ev >> ioError (userError "callback failure")))
+        case result of
+          Left (_ :: IOError) -> takeMVar entered
+          Right _ -> fail "Callback exception did not propagate"
+      "cancel" -> do
+        finished <- newEmptyMVar
+        bracket
+          (forkFinally (void (streaming (\meta ev -> checkStart meta ev >> takeMVar never))) (putMVar finished))
+          killThread
+          ( \tid -> do
+              takeMVar entered
+              killThread tid
+              takeMVar finished >>= \case
+                Left _ -> pure ()
+                Right () -> fail "Expected cancellation"
+          )
+      _ -> do
+        Response _ terminal <-
+          streaming
+            ( \meta ev -> do
+                checkStart meta ev
+                case ev ^. #eventPayload of
+                  MessageStart _ -> putMVar allowFinish ()
+                  _ -> pure ()
+                pure Continue
+            )
+            >>= expectRight
+        assertEqual "provider finished" Finished terminal
+    takeMVar released >>= assertEqual ("socket released after " <> mode) BS.empty
+  where
+    httpChunk bytes = BSC.pack (showHex (BS.length bytes) "") <> "\r\n" <> bytes <> "\r\n"
+    addStreamFlag (Object fields) = Object (KeyMap.insert "stream" (Bool True) fields)
+    addStreamFlag raw = raw
+
+fragmentedEvents :: IO ()
+fragmentedEvents = do
+  request <- sampleRequest baseConversation
+  let futureDelta = event "future_delta" ["unknown" .= True]
+      transcript =
+        ": comment\r\nevent: message_start\r\ndata: "
+          <> LBS.toStrict (encode messageStart)
+          <> "\r\n\r\nevent: ping\ndata: {\ndata: \"type\": \"ping\"}\n\n"
+          <> BS.concat
+            ( map
+                frame
+                [ blockStart 0 (event "text" ["text" .= ("" :: Text)]),
+                  textDelta 0 "café",
+                  blockDelta 0 (event "citations_delta" ["citation" .= webCitation]),
+                  blockStop 0,
+                  blockStart 1 (thinkingBlock "" ""),
+                  blockDelta 1 (event "thinking_delta" ["thinking" .= ("summary" :: Text)]),
+                  blockDelta 1 (event "signature_delta" ["signature" .= ("opaque-signature" :: Text)]),
+                  blockDelta 1 futureDelta,
+                  blockStop 1,
+                  event "future_event" ["v" .= True],
+                  event
+                    "message_delta"
+                    [ "delta" .= object ["stop_reason" .= ("end_turn" :: Text), "stop_sequence" .= Null],
+                      "usage" .= object ["input_tokens" .= (20 :: Int), "output_tokens" .= (9 :: Int), "cache_read_input_tokens" .= (5 :: Int)]
+                    ],
+                  messageStop
+                ]
+            )
+      check split = do
+        seen <- newIORef []
+        let app req send = do
+              _ <- Wai.strictRequestBody req
+              if split
+                then send $ Wai.responseStream status200 [] $ \write flush ->
+                  BS.foldr (\byte next -> write (byteString (BS.singleton byte)) >> flush >> threadDelay 100 >> next) (pure ()) transcript
+                else send (sse transcript)
+        withClient app $ \client -> do
+          Response _ terminal <-
+            streamMessage
+              client
+              defaultRequestOptions
+              request
+              (\_ item -> modifyIORef' seen (item :) >> pure Continue)
+              >>= expectRight
+          assertEqual "finished fragmented stream" Finished terminal
+          reverse <$> readIORef seen
+  whole <- check False
+  split <- check True
+  assertEqual "single byte fragments" whole split
+  case map (^. #eventPayload) split of
+    [ MessageStart _,
+      Ping,
+      ContentBlockStart 0 _,
+      ContentBlockDelta 0 (TextDelta "café"),
+      ContentBlockDelta 0 (CitationDelta (Citation (WebLocation _ _ _ "encrypted-index") _)),
+      ContentBlockStop 0,
+      ContentBlockStart 1 _,
+      ContentBlockDelta 1 (ThinkingDelta "summary"),
+      ContentBlockDelta 1 (SignatureDelta "opaque-signature"),
+      ContentBlockDelta 1 (UnknownDelta "future_delta" _),
+      ContentBlockStop 1,
+      UnknownEvent "future_event",
+      MessageDelta (MessageUpdate (Just EndTurn) Nothing Nothing Nothing) (UsageUpdate (Just 20) (Just 9) Nothing (Just 5) Nothing Nothing (UsageEvidence Nothing Nothing Nothing Nothing Nothing Nothing)),
+      MessageStop
+      ] -> pure ()
+    _ -> fail "unexpected event or delta sequence"
+
+streamToolContinuation :: IO ()
+streamToolContinuation = do
+  request <- sampleRequest baseConversation
+  let unsigned = thinkingBlock "" ""
+      signed = thinkingBlock "" "signature-stream"
+      toolId = "tool_stream" :: Text
+      tool input = event "tool_use" ["id" .= toolId, "name" .= ("lookup" :: Text), "input" .= input]
+      finalInput = object ["value" .= ("green" :: Text)]
+      transcript =
+        BS.concat
+          ( map
+              frame
+              [ messageStart,
+                blockStart 0 unsigned,
+                blockDelta 0 (event "signature_delta" ["signature" .= ("signature-stream" :: Text)]),
+                blockStop 0,
+                blockStart 1 (tool (object [])),
+                blockDelta 1 (event "input_json_delta" ["partial_json" .= ("{\"value\":" :: Text)]),
+                blockDelta 1 (event "input_json_delta" ["partial_json" .= ("\"green\"}" :: Text)]),
+                blockStop 1,
+                messageStop
+              ]
+          )
+      app req send = do
+        body <- requestJson req
+        if lookup "accept" (Wai.requestHeaders req) == Just "text/event-stream"
+          then send (sse transcript)
+          else do
+            let expectedMessages =
+                  toJSON
+                    [ toJSON (Message User (InputText "Hello" :| [])),
+                      object ["role" .= ("assistant" :: Text), "content" .= [signed, tool finalInput]],
+                      object ["role" .= ("user" :: Text), "content" .= [event "tool_result" ["tool_use_id" .= toolId, "content" .= ("done" :: Text)]]]
+                    ]
+            assertEqual
+              "HTTP replay of signed stream tool turn"
+              (Just expectedMessages)
+              ( case body of
+                  Object fields -> KeyMap.lookup "messages" fields
+                  _ -> Nothing
+              )
+            send (json status200 [] (messageFixture []))
+  withClient app $ \client -> do
+    seen <- newIORef []
+    _ <-
+      streamMessage
+        client
+        defaultRequestOptions
+        request
+        (\_ ev -> modifyIORef' seen ((ev ^. #eventPayload) :) >> pure Continue)
+        >>= expectRight
+    events <- reverse <$> readIORef seen
+    case events of
+      [ MessageStart starting,
+        ContentBlockStart 0 first,
+        ContentBlockDelta 0 (SignatureDelta signature),
+        ContentBlockStop 0,
+        ContentBlockStart 1 second,
+        ContentBlockDelta 1 (InputJsonDelta prefix),
+        ContentBlockDelta 1 (InputJsonDelta suffix),
+        ContentBlockStop 1,
+        MessageStop
+        ] -> do
+          input <- expectRight (eitherDecodeStrict (encodeUtf8 (prefix <> suffix)))
+          thinking <- parseBlock "signature" (String signature) first
+          called <- parseBlock "input" input second
+          let updated = starting & #content .~ [thinking, called]
+          reply <- maybe (fail "missing stream continuation") pure (assistantContinuation updated)
+          let toolResult = Message User (InputToolResult (ToolResult toolId (ToolResultText "done") Nothing Nothing) :| [])
+              continued = request {conversation = withConversationHistory (conversationHistory baseConversation <> [reply, toolResult]) baseConversation}
+          void (createMessage client defaultRequestOptions continued >>= expectRight)
+      _ -> fail "Unexpected continuation transcript"
+  where
+    parseBlock :: Key -> Value -> OutputBlock -> IO OutputBlock
+    parseBlock key item block = case blockJSON block of
+      Object fields -> expectRight (eitherDecode (encode (Object (KeyMap.insert key item fields))))
+      _ -> fail "Expected a block object"
+
+streamFailures :: IO ()
+streamFailures = do
+  request <- sampleRequest baseConversation
+  let malformed = event "content_block_delta" ["index" .= (0 :: Int), "delta" .= event "signature_delta" []]
+      apiError = event "error" ["error" .= object ["type" .= ("overloaded_error" :: Text), "message" .= ("Retry later loopback-secret" :: Text)]]
+      exercise payload verify = withClient (\_ send -> send (sse (frame messageStart <> payload))) $ \client ->
+        streamMessage client defaultRequestOptions request (\_ _ -> pure Continue) >>= verify
+      decodeFailure = \case
+        Left (DecodeError meta _) -> assertEqual "decode failure correlation" (Just "req_stream") (meta ^. #requestId)
+        _ -> fail "Expected stream decode failure"
+  exercise "" decodeFailure
+  exercise (frame malformed) decodeFailure
+  exercise (frame apiError) $ \case
+    Left (StreamApiError meta (ApiError "overloaded_error" detail)) -> do
+      assertEqual "stream error correlation" (Just "req_stream") (meta ^. #requestId)
+      assertEqual "stream error redaction" "Retry later [redacted]" detail
+    _ -> fail "Expected a typed in-stream API error"
+  withClient (\_ _ -> fail "Incompatible request dispatched") $ \client -> do
+    let legacy = case toJSON request of
+          Object fields -> Object (KeyMap.insert "temperature" (toJSON (0.5 :: Double)) fields)
+          raw -> raw
+    streamMessageValue client defaultRequestOptions legacy (\_ _ -> pure Continue) >>= \case
+      Left (InvalidRequest _) -> pure ()
+      _ -> fail "Expected local failure for removed sampling"
+
+legacyBridge :: IO ()
+legacyBridge = do
+  let config = (defaultClientConfig "loopback-secret") {apiVersion = Just "2023-06-01"}
+      request = object ["model" .= ("legacy-model" :: Text), "max_tokens" .= (10 :: Int), "messages" .= ([] :: [Value]), "temperature" .= (0.5 :: Double)]
+      app req send = do
+        assertEqual "configured legacy API version" (Just "2023-06-01") (lookup "anthropic-version" (Wai.requestHeaders req))
+        requestJson req >>= \case
+          Object fields -> do
+            assertEqual "legacy sampling value" (Just (toJSON (0.5 :: Double))) (KeyMap.lookup "temperature" fields)
+            assertEqual "legacy empty history" (Just (toJSON ([] :: [Value]))) (KeyMap.lookup "messages" fields)
+          _ -> fail "Expected legacy request object"
+        send (sse (frame messageStart <> frame messageStop))
+  withClientConfig config app $ \client -> do
+    Response _ terminal <- streamMessageValue client defaultRequestOptions request (\_ _ -> pure Continue) >>= expectRight
+    assertEqual "legacy stream completed" Finished terminal
+
+advancedEvidence :: IO ()
+advancedEvidence = do
+  request <- sampleRequest baseConversation
+  let refusal = event "refusal" ["category" .= ("other" :: Text), "explanation" .= ("declined" :: Text)]
+      initialUsage =
+        object
+          [ "input_tokens" .= (17 :: Int),
+            "output_tokens" .= (1 :: Int),
+            "speed" .= ("fast" :: Text),
+            "service_tier" .= ("priority" :: Text),
+            "inference_geo" .= ("us" :: Text),
+            "cache_creation_input_tokens" .= (4 :: Int),
+            "cache_read_input_tokens" .= (5 :: Int),
+            "server_tool_use" .= object ["web_search_requests" .= (3 :: Int), "tool_search_requests" .= (2 :: Int), "extension" .= True]
+          ]
+      iteration = event "fallback_message" ["model" .= ("served-model" :: Text), "output_tokens" .= (19 :: Int), "extension" .= True]
+      patch = object ["output_tokens" .= (19 :: Int), "cache_read_input_tokens" .= (0 :: Int), "output_tokens_details" .= object ["thinking_tokens" .= (12 :: Int)], "iterations" .= [iteration], "server_tool_use" .= object ["tool_search_requests" .= (0 :: Int)]]
+      start = event "message_start" ["message" .= replace "usage" initialUsage (messageFixture [])]
+      delta reason details counters = event "message_delta" ["delta" .= object ["stop_reason" .= (reason :: Text), "stop_details" .= details], "usage" .= counters]
+      exhausted = delta "model_context_window_exceeded" Null patch
+      refused = delta "refusal" refusal (object ["unrecognised" .= True])
+      failedCode = event "code_execution_tool_result" ["tool_use_id" .= ("srvtoolu_1" :: Text), "content" .= event "code_execution_tool_result_error" ["error_code" .= ("invalid_tool_input" :: Text)]]
+      app _ send = send (sse (foldMap frame [start, blockStart 0 failedCode, blockStop 0, exhausted, refused, messageStop]))
+  withClient app $ \client -> do
+    seen <- newIORef []
+    _ <- streamMessage client defaultRequestOptions request (\_ entry -> modifyIORef' seen (entry :) >> pure Continue) >>= expectRight
+    reverse <$> readIORef seen >>= \case
+      [ StreamEvent (MessageStart first) _,
+        StreamEvent (ContentBlockStart 0 block) _,
+        StreamEvent (ContentBlockStop 0) _,
+        StreamEvent (MessageDelta context update) _,
+        StreamEvent (MessageDelta final missing) raw,
+        StreamEvent MessageStop _
+        ] -> do
+          assertEqual "typed code error" (OutputCodeExecutionResult "srvtoolu_1" (CodeExecutionFailed "invalid_tool_input")) (blockContent block)
+          assertEqual "context length distinct from refusal" (Just ModelContextWindowExceeded) (context ^. #stopReason)
+          assertEqual "refusal category, explanation and reason" (Just Refusal, Just (RefusalDetails (Just "other") (Just "declined") Nothing)) (final ^. #stopReason, final ^. #stopDetails)
+          assertEqual "raw delta" refused raw
+          let totals = applyUsageUpdate (applyUsageUpdate (first ^. #usage) update) missing
+              evidence = totals ^. #usageEvidence
+          assertEqual "cumulative usage and explicit zero" (17, 19, Just 4, Just 0) (totals ^. #inputTokens, totals ^. #outputTokens, totals ^. #cacheCreationInputTokens, totals ^. #cacheReadInputTokens)
+          assertEqual "pricing observations" (Just Fast, Just "priority", Just "us", Just (OutputTokenDetails (Just 12))) (evidence ^. #observedSpeed, evidence ^. #serviceTier, evidence ^. #inferenceGeography, evidence ^. #outputTokensDetails)
+          assertEqual "incremental server tool counts" (Just (ServerToolCounts (Just 3) Nothing (Just 0) Nothing)) (evidence ^. #serverToolCounts)
+          assertEqual "retained tool usage extensions" (Just (Bool True)) (totals ^. #serverToolUse >>= KeyMap.lookup "extension")
+          assertEqual "final fallback iterations" (Just [("fallback_message", Just "served-model", Just (Bool True))]) ((map (\i -> (iterationType i, iterationModel i, KeyMap.lookup "extension" (iterationJSON i)))) <$> (evidence ^. #iterations))
+      _ -> fail "expected advanced evidence transcript"
+  where
+    replace name value (Object fields) = Object (KeyMap.insert name value fields)
+    replace _ _ other = other
diff --git a/test/Support/Server.hs b/test/Support/Server.hs
new file mode 100644
--- /dev/null
+++ b/test/Support/Server.hs
@@ -0,0 +1,45 @@
+module Support.Server
+  ( withClient,
+    withClientConfig,
+    json,
+    requestJson,
+    assertEqual,
+    assert,
+    expectRight,
+    within,
+  )
+where
+
+import Claude.Client
+import Data.Aeson (Value, eitherDecode, encode)
+import Network.HTTP.Types (ResponseHeaders, Status)
+import Network.Wai qualified as Wai
+import Network.Wai.Handler.Warp qualified as Warp
+import System.Timeout (timeout)
+
+withClient :: Wai.Application -> (Client -> IO a) -> IO a
+withClient = withClientConfig (defaultClientConfig "loopback-secret")
+
+withClientConfig :: ClientConfig -> Wai.Application -> (Client -> IO a) -> IO a
+withClientConfig config app run = Warp.testWithApplication (pure app) $ \port -> do
+  client <- newClient config {endpoint = "http://127.0.0.1:" <> show port}
+  expectRight client >>= within . run
+
+json :: Status -> ResponseHeaders -> Value -> Wai.Response
+json status headers = Wai.responseLBS status (("content-type", "application/json") : headers) . encode
+
+requestJson :: Wai.Request -> IO Value
+requestJson req = Wai.strictRequestBody req >>= expectRight . eitherDecode
+
+assertEqual :: (Eq a, Show a) => String -> a -> a -> IO ()
+assertEqual name expected actual =
+  assert (name <> ": expected " <> show expected <> ", got " <> show actual) (expected == actual)
+
+assert :: String -> Bool -> IO ()
+assert name passed = if passed then pure () else fail name
+
+expectRight :: (Show e) => Either e a -> IO a
+expectRight = either (fail . show) pure
+
+within :: IO a -> IO a
+within action = timeout 10000000 action >>= maybe (fail "Fixture exceeded its deadline") pure
