baikai-claude 0.7.3.0 → 0.7.3.1
raw patch · 14 files changed
+1049/−900 lines, 14 filesdep +claude-hsdep +waidep +warpdep −claudedep ~baikaiPVP: major bump suggested
API removals or changes: PVP suggests a major version bump
Dependencies added: claude-hs, wai, warp
Dependencies removed: claude
Dependency ranges changed: baikai
API changes (from Hackage documentation)
- Baikai.Provider.Claude.Sse: buildRequest :: BaseUrl -> RequestHeaders -> Value -> Request
- Baikai.Provider.Claude.Internal.Request: mapRequest :: Model -> Context -> Options -> Either Text (CreateMessage, ThinkingTranslation)
+ Baikai.Provider.Claude.Internal.Request: mapRequest :: Model -> Context -> Options -> Either Text (MessageRequest, ThinkingTranslation)
- Baikai.Provider.Claude.Internal.Stream: translate :: Either BaikaiError MessageStreamEvent -> Assembler -> UTCTime -> ([AssistantMessageEvent], Assembler)
+ Baikai.Provider.Claude.Internal.Stream: translate :: Either BaikaiError StreamPayload -> Assembler -> UTCTime -> ([AssistantMessageEvent], Assembler)
- Baikai.Provider.Claude.Internal.Stream: type SseDriver = ClaudeCall -> ResponseMetadata -> IO () -> Either BaikaiError MessageStreamEvent -> IO () -> IO ()
+ Baikai.Provider.Claude.Internal.Stream: type SseDriver = ClaudeCall -> ResponseMetadata -> IO () -> Either BaikaiError StreamPayload -> IO () -> IO ()
- Baikai.Provider.Claude.Shape: streamRequestBody :: AnthropicMessagesCompat -> Context -> Options -> CreateMessage -> Value
+ Baikai.Provider.Claude.Shape: streamRequestBody :: AnthropicMessagesCompat -> Context -> Options -> MessageRequest -> Value
- Baikai.Provider.Claude.Sse: claudeSseStream :: ClientEnv -> Text -> Maybe Text -> CreateMessage -> (ResponseMetadata -> IO ()) -> (Either BaikaiError MessageStreamEvent -> IO ()) -> IO ()
+ Baikai.Provider.Claude.Sse: claudeSseStream :: BaseUrl -> Text -> Maybe Text -> MessageRequest -> (ResponseMetadata -> IO ()) -> (Either BaikaiError StreamPayload -> IO ()) -> IO ()
- Baikai.Provider.Claude.Sse: claudeSseStreamValue :: ClientEnv -> Text -> Maybe Text -> Value -> (ResponseMetadata -> IO ()) -> (Either BaikaiError MessageStreamEvent -> IO ()) -> IO ()
+ Baikai.Provider.Claude.Sse: claudeSseStreamValue :: BaseUrl -> Text -> Maybe Text -> Value -> (ResponseMetadata -> IO ()) -> (Either BaikaiError StreamPayload -> IO ()) -> IO ()
- Baikai.Provider.Claude.Sse: claudeSseStreamValueWithHeaders :: ClientEnv -> RequestHeaders -> Value -> (ResponseMetadata -> IO ()) -> (Either BaikaiError MessageStreamEvent -> IO ()) -> IO ()
+ Baikai.Provider.Claude.Sse: claudeSseStreamValueWithHeaders :: BaseUrl -> RequestHeaders -> Value -> (ResponseMetadata -> IO ()) -> (Either BaikaiError StreamPayload -> IO ()) -> IO ()
- Baikai.Provider.Claude.Sse: decodeFrame :: ByteString -> Either BaikaiError (Maybe MessageStreamEvent)
+ Baikai.Provider.Claude.Sse: decodeFrame :: ByteString -> Either BaikaiError (Maybe StreamPayload)
- Baikai.Provider.Claude.Sse: sseFromResponse :: Response BodyReader -> (ResponseMetadata -> IO ()) -> (Either BaikaiError MessageStreamEvent -> IO ()) -> IO ()
+ Baikai.Provider.Claude.Sse: sseFromResponse :: Response BodyReader -> (ResponseMetadata -> IO ()) -> (Either BaikaiError StreamPayload -> IO ()) -> IO ()
Files
- CHANGELOG.md +146/−0
- baikai-claude.cabal +7/−5
- src/Baikai/Provider/Claude/Api.hs +1/−1
- src/Baikai/Provider/Claude/Internal/Request.hs +97/−200
- src/Baikai/Provider/Claude/Internal/Stream.hs +97/−100
- src/Baikai/Provider/Claude/Shape.hs +3/−3
- src/Baikai/Provider/Claude/Sse.hs +119/−175
- src/Baikai/Provider/Claude/Transport.hs +2/−2
- test/FableContractsSpec.hs +264/−66
- test/LifecycleSpec.hs +47/−2
- test/Main.hs +7/−7
- test/ShapeSpec.hs +6/−6
- test/SseSpec.hs +130/−116
- test/ThinkingSpec.hs +123/−217
CHANGELOG.md view
@@ -7,6 +7,150 @@ ## [Unreleased] +## [baikai 0.11.0.0] - 2026-11-23++### Added++- Add `anthropic_claude_fable_5_2` on Claude Messages with adaptive thinking,+ client function tools, and structured output for eligible organizations.+ Standard rates per million tokens are $8 input, $40 output, $0.20 cache+ read, $10 five-minute cache write, and $16 one-hour cache write. Fast mode+ doubles those rates.+- Add `openai_gpt_6_2_astra` and `openai_gpt_6_2_sol` on OpenAI Responses+ with structured output, function tools, and Standard pricing for both+ cache durations and long-context requests.+- Add `openai_gpt_6_1_terra` on OpenAI Responses with explicit reasoning+ and cache compatibility, 30-minute and 12-hour cache-write prices, and+ whole-request pricing above 272,000 input tokens.++### Changed (breaking)++- `AssistantContent` changes its `Generic` representation to carry original+ Responses items. `AssistantText` and `AssistantToolCall` are bundled pattern+ synonyms. Existing persisted content still decodes.++### Fixed++- Apply the published long-context tier for GPT-5.6 Sol, its `gpt-5.6`+ alias, GPT-5.6 Terra, and GPT-5.6 Luna. Use the published one-hour write+ rates for eight Claude bindings that used the five-minute rate.++## [baikai-claude 0.7.3.1] - 2026-11-23++### Changed++- Use `claude-hs 0.1.0.0` for the Messages transport and require+ `baikai ^>=0.11.0.0`. Fable 5.2 tool continuations preserve signed+ thinking, including empty signed blocks.++### Fixed++- Reject unsupported assistant prefills before dispatch. Claude 4.5 accepts+ prefills with effective thinking off. Normal tool-result continuations+ preserve prior assistant history.++## [baikai-openai 0.7.4.0] - 2026-11-23++### Added++- Expose `Baikai.Provider.OpenAI.HookEvidence` for Codex app-server clients+ to verify a reviewed pre-tool handler and decode its completion outcome.+- Add scoped Codex batch completion with reviewed PreToolUse hooks and+ native denial evidence.++### Changed++- Require `baikai ^>=0.11.0.0` for persisted Responses replay.++### Fixed++- Preserve completed Responses message and function-call items in stateless+ history. GPT-6.2 keeps reusable system prompts at the head of the input+ across tool turns.++## [baikai-typesafe 0.1.0.2] - 2026-11-23++### Changed++- Build against `baikai ^>=0.11.0.0`.++## [baikai-trace-otel 0.4.1.2] - 2026-11-23++### Changed++- Build against `baikai ^>=0.11.0.0`.++## [baikai-effectful 0.5.0.1] - 2026-11-23++### Changed++- Build against `baikai ^>=0.11.0.0`.++## [baikai-kit 0.4.0.4] - 2026-11-23++### Changed++- Build against `baikai ^>=0.11.0.0`.++## [baikai-agent 0.3.0.0] - 2026-11-23++### Added++- `baikai agent review-codex-hooks` presents exact native declarations for+ approval. `baikai agent run --codex-hooks` reports denials from the+ checked app-server thread in the JSON result.++### Changed (breaking)++- `AgentCliCommand` gains `AgentReviewCodexHooks`. Add that case to+ exhaustive matches. The runner requires `baikai ^>=0.11.0.0` and+ `baikai-openai ^>=0.7.4.0`.++## [baikai-openai 0.7.3.1] - 2026-11-14++### Fixed++- Require `baikai ^>=0.10.1.1` in library and tests so new adapter consumers+ receive the Codex final-message correction.++## [baikai 0.10.1.1] - 2026-11-14++### Fixed++- `baikai`: the Codex batch parser returns the last completed agent message+ instead of concatenating complete messages, preserving structured JSON after+ intermediate commentary. Started and updated items cannot replace the final+ answer; usage and thread observations still cover the whole run ([BUG-2](docs/bug-reports/codex-concatenates-complete-agent-messages.md)).++## [baikai 0.10.1.0] - 2026-11-03++### Added++- `Baikai.Trace.withTraceFold` and `withTraceFoldWith` own tracing across the+ entire consumer fold; `withTraceList` and `withTraceListWith` collect events.+ A healthy sink receives abort evidence before cancellation propagates,+ including cancellation between stream steps.++### Fixed++- `withTrace`, `withTraceWith`, and the traced call in `runRequestWith` and+ `runRequestWithRegistry` now finalize synchronously on cancellation. Cleanup+ resumes an interrupted terminal drain within the same one-second budget,+ preserves the original exception, and never duplicates terminal evidence.+ General-stream abandonment keeps its garbage-collection-eventual contract.++## [baikai-effectful 0.5.0.0] - 2026-11-03++### Added++- `streamCollectTraced` delegates traced event collection to core with bounded+ cleanup on cancellation. Re-export `TraceSink` for operation signatures.++### Changed (breaking)++- `Baikai` gains `StreamCollectTraced`. Third-party interpreters must handle+ this constructor. The binding requires `baikai ^>=0.10.1`.+ ## [baikai 0.10.0.0] - 2026-10-25 ### Added@@ -108,6 +252,8 @@ - Layered job configuration accepts `thinking "none"` through the shared canonical parser, keeping explicit off distinct from an absent preference.+- The UTF-8 stdin test runs in a child process under an ASCII locale, avoiding+ shared-stdin descriptor races with parallel subprocess tests in the tarball. ### Changed
baikai-claude.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.4 name: baikai-claude-version: 0.7.3.0+version: 0.7.3.1 synopsis: Anthropic Claude providers for the baikai abstraction description: Anthropic backends for baikai: the Messages API over SSE, the claude -p batch@@ -72,13 +72,13 @@ autogen-modules: Paths_baikai_claude build-depends: aeson ^>=2.2,- baikai ^>=0.10.0,+ baikai ^>=0.11.0.0, base >=4.20 && <5, base16-bytestring ^>=1.0, base64-bytestring ^>=1.2, bytestring ^>=0.12, case-insensitive ^>=1.2,- claude ^>=1.5,+ claude-hs ==0.1.0.0, containers ^>=0.7, cradle ^>=0.0, cryptohash-sha256 ^>=0.11,@@ -126,12 +126,12 @@ build-depends: aeson,- baikai ^>=0.10.0,+ baikai ^>=0.11.0.0, baikai-claude, base >=4.20 && <5, bytestring, case-insensitive,- claude,+ claude-hs, containers, directory, filepath,@@ -152,6 +152,8 @@ time, tls, vector,+ wai,+ warp, if !os(windows) build-depends: unix ^>=2.8
src/Baikai/Provider/Claude/Api.hs view
@@ -66,7 +66,7 @@ -- -- Forks one worker thread per call that drives the local Claude SSE -- transport, pushing classified errors and typed--- 'Claude.V1.Messages.MessageStreamEvent' values onto a bounded+-- 'Claude.Streaming.StreamPayload' values onto a bounded -- 'Baikai.Provider.Internal.StreamWorker.FrameQueue'. The returned -- 'Stream' is a translator: it pulls raw events off that queue and emits -- zero or more 'AssistantMessageEvent' values per upstream event,
src/Baikai/Provider/Claude/Internal/Request.hs view
@@ -20,7 +20,7 @@ where import Baikai.CacheRetention (CacheRetention (..))-import Baikai.Compat (AnthropicMessagesCompat (..), AnthropicThinkingStyle (..))+import Baikai.Compat (AnthropicAssistantPrefillPolicy (..), AnthropicMessagesCompat (..), AnthropicThinkingStyle (..)) import Baikai.Content qualified as Content import Baikai.Context (Context (..)) import Baikai.Context qualified as Context@@ -38,16 +38,19 @@ import Baikai.Speed (Speed (..)) import Baikai.ThinkingLevel (ThinkingLevel (..), renderThinkingLevel, thinkingTokenBudget) import Baikai.Tool qualified as Tool-import Claude.V1.Messages qualified as Messages-import Claude.V1.Tool qualified as ClaudeTool+import Claude.Messages qualified as Messages import Control.Lens ((%~), (&), (.~), (^.)) import Crypto.Hash.SHA256 qualified as SHA256 import Data.Aeson ((.=)) import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap import Data.ByteString.Base16 qualified as Base16 import Data.ByteString.Base64 qualified as Base64 import Data.Char (isAlphaNum, isAscii) import Data.Generics.Labels ()+import Data.List (unsnoc)+import Data.List.NonEmpty (NonEmpty (..))+import Data.List.NonEmpty qualified as NonEmpty import Data.Maybe (catMaybes, fromMaybe) import Data.Text (Text) import Data.Text qualified as Text@@ -61,14 +64,7 @@ -- Request mapping: Context and Options onto the SDK's request record. -- ============================================================ --- | The wire wants an absent field for "no stop sequences", and--- 'Baikai.Options.stopSequences' says that with an empty list — the one--- representation, where @Nothing@ and @Just []@ used to be two.-nonEmptyStops :: [Text] -> Maybe (Vector.Vector Text)-nonEmptyStops [] = Nothing-nonEmptyStops xs = Just (Vector.fromList xs)---- | Map a baikai request onto the SDK's 'Messages.CreateMessage', and+-- | Map a baikai request onto the SDK's 'Messages.MessageRequest', and -- describe what the caller's reasoning-effort preference became on the -- way. --@@ -79,7 +75,7 @@ -- feed into it. A trace sink asked to re-derive it would have to -- reimplement every one of them. mapRequest ::- Model -> Context -> Options -> Either Text (Messages.CreateMessage, ThinkingTranslation)+ Model -> Context -> Options -> Either Text (Messages.MessageRequest, ThinkingTranslation) mapRequest m ctx opts = do either (Left . Error.message) pure (Context.refuseAssistantDataHistory ctx) case opts ^. #toolChoice of@@ -101,6 +97,7 @@ ) (ctx ^. #messages) msgs <- catMaybes <$> traverse mapMessage (Vector.toList (ctx ^. #messages))+ outputConfig <- traverse mkAnthropicOutputConfig (opts ^. #responseFormat) let compat = anthropicMessagesCompatFor m cap = m ^. #maxOutputTokens baseTokens = resolveBaseTokens m opts@@ -110,41 +107,48 @@ Just b -> clamp (baseTokens + b) Nothing -> clamp baseTokens cacheControlField = computeCacheControl compat (opts ^. #cacheRetention)- toolsVec = ctx ^. #tools- toolsField =- if Vector.null toolsVec- then Nothing- else Just (Vector.map (mkAnthropicTool compat) toolsVec)- toolChoiceField = case opts ^. #toolChoice of- Just Tool.ToolChoiceNone -> Nothing- Just tc -> Just (mkAnthropicToolChoice tc)- Nothing -> Nothing- outputConfigField = mergeEffort (effort plan) (fmap mkAnthropicOutputConfig (opts ^. #responseFormat))+ features =+ Messages.MessageFeatures+ (mergeEffort (effort plan) outputConfig)+ (field plan)+ cacheControlField+ (map mkAnthropicTool (Vector.toList (ctx ^. #tools)))+ (mkAnthropicToolChoice <$> (opts ^. #toolChoice))+ (fst (planSpeed compat (opts ^. #speed)))+ conversation =+ Messages.withConversationHistory msgs $+ Messages.EmptyConversation (m ^. #modelId) (Messages.SystemText <$> (ctx ^. #systemPrompt)) features+ controls =+ Messages.defaultRequestControls+ { Messages.temperature = sampling ^. #temperature,+ Messages.topP = sampling ^. #topP+ }+ case unsnoc msgs of+ Just (_, Messages.Message Messages.Assistant _)+ | rejectsAssistantPrefill compat.assistantPrefillPolicy (field plan) ->+ Left "This model with the effective thinking settings cannot end a request with an assistant prefill. End with a user turn or move the instruction to the system prompt. After a tool call, append the matching tool result."+ _ -> pure ()+ let limit = fromMaybe Messages.cacheOnly (Messages.maxTokens maxTokensField_) pure- ( Messages._CreateMessage- { Messages.model = m ^. #modelId,- Messages.messages = Vector.fromList msgs,- Messages.max_tokens = maxTokensField_,- Messages.system = fmap Messages.SystemPromptText (ctx ^. #systemPrompt),- Messages.temperature = sampling ^. #temperature,- Messages.top_p = sampling ^. #topP,- Messages.stop_sequences = nonEmptyStops (opts ^. #stopSequences),- Messages.tools = toolsField,- Messages.tool_choice = toolChoiceField,- Messages.cache_control = cacheControlField,- Messages.speed = fst (planSpeed compat (opts ^. #speed)),- Messages.thinking = field plan,- Messages.output_config = outputConfigField- },+ ( Messages.withRequestControls controls (Messages.MessageRequest conversation limit (opts ^. #stopSequences)), translation ) unsupportedForcedChoice :: Either Text () unsupportedForcedChoice = Left "This model does not support forced tool choice; use ToolChoiceAuto or ToolChoiceNone" +rejectsAssistantPrefill :: Maybe AnthropicAssistantPrefillPolicy -> Maybe Messages.Thinking -> Bool+rejectsAssistantPrefill Nothing _ = False+rejectsAssistantPrefill (Just AnthropicPrefillUnsupported) _ = True+rejectsAssistantPrefill (Just AnthropicPrefillRequiresThinkingOff) thinking =+ case thinking of+ Nothing -> False+ Just Messages.ThinkingDisabled -> False+ Just _ -> True+ -- | The sampling parameters that will reach the wire, after the compat -- record's gate. 'Nothing' means the field is omitted — the SDK encodes--- 'Messages.CreateMessage' with @omitNothingFields = True@, so a+-- 'Messages.MessageRequest' with @omitNothingFields = True@, so a -- 'Nothing' is genuinely absent from the request body rather than a -- JSON @null@ the provider would reject. data SamplingPlan = SamplingPlan@@ -269,50 +273,27 @@ describeThinkingFor m opts = snd (planThinking m opts) mergeEffort :: Maybe Text -> Maybe Messages.OutputConfig -> Maybe Messages.OutputConfig-mergeEffort Nothing cfg = cfg-mergeEffort (Just e) Nothing = Just (Messages.effortConfig e)-mergeEffort (Just e) (Just cfg) = Just cfg {Messages.effort = Just e}+mergeEffort Nothing config = config+mergeEffort (Just value) config =+ Just (Messages.OutputConfig (Just (Messages.VersionedEffort value)) (config >>= Messages.schema)) --- | Map a baikai 'ResponseFormat' onto the upstream Anthropic--- 'Messages.OutputConfig'. 'JsonSchema' forwards the schema--- verbatim via 'Messages.jsonSchemaConfig'. Anthropic's structured--- outputs are always schema-enforcing, so the baikai 'strict' flag--- has no wire analog and is dropped. 'JsonObject' (plain-JSON mode)--- has no native Anthropic equivalent — 'output_config' requires a--- schema — so it downgrades to a permissive @{"type":"object"}@--- schema, which still forces the model to emit a JSON object.-mkAnthropicOutputConfig :: ResponseFormat -> Messages.OutputConfig+mkAnthropicOutputConfig :: ResponseFormat -> Either Text Messages.OutputConfig mkAnthropicOutputConfig = \case- JsonSchema f -> Messages.jsonSchemaConfig f.schema- JsonObject ->- Messages.jsonSchemaConfig- (Aeson.object ["type" .= ("object" :: Text)])+ JsonSchema spec -> case spec.schema of+ Aeson.Object schema -> Right (Messages.OutputConfig Nothing (Just schema))+ _ -> Left "Anthropic Messages requires the output schema to be a JSON object"+ JsonObject -> Right (Messages.OutputConfig Nothing (Just (KeyMap.singleton "type" (Aeson.String "object")))) --- | Translate the call-time 'Baikai.CacheRetention' preference into--- the Anthropic SDK's @cache_control@ shape.------ 'CacheRetentionNone' (and 'Nothing') turn the field off entirely.--- 'CacheRetentionShort' uses the ephemeral marker with no TTL (the--- provider default). 'CacheRetentionLong' asks for the @"1h"@ TTL--- when the host advertises 'supportsLongCacheRetention'; otherwise it--- transparently downgrades to short retention. computeCacheControl :: AnthropicMessagesCompat -> Maybe CacheRetention -> Maybe Messages.CacheControl computeCacheControl _ Nothing = Nothing computeCacheControl _ (Just CacheRetentionNone) = Nothing-computeCacheControl _ (Just CacheRetentionShort) =- Just Messages.CacheControl {Messages.type_ = "ephemeral", Messages.ttl = Nothing}+computeCacheControl _ (Just CacheRetentionShort) = Just (Messages.Ephemeral Nothing) computeCacheControl compat (Just CacheRetentionLong)- | supportsLongCacheRetention compat =- Just- Messages.CacheControl- { Messages.type_ = "ephemeral",- Messages.ttl = Just (Messages.CacheTTLDuration "1h")- }- | otherwise =- Just Messages.CacheControl {Messages.type_ = "ephemeral", Messages.ttl = Nothing}+ | compat ^. #supportsLongCacheRetention = Just (Messages.Ephemeral (Just Messages.OneHour))+ | otherwise = Just (Messages.Ephemeral Nothing) -- | Translate the call-time 'Baikai.ThinkingLevel' preference into -- the Anthropic SDK's 'Messages.Thinking' shape.@@ -413,7 +394,7 @@ | thinkingStyle compat == AnthropicThinkingAdaptive = let e = adaptiveEffort lvl in ( ThinkingPlan- { field = Just (Messages.ThinkingAdaptiveWithDisplay Messages.ThinkingSummarized),+ { field = Just (Messages.Adaptive (Just Messages.Summarized)), effort = Just e, budget = Nothing },@@ -430,7 +411,7 @@ | otherwise = let b = thinkingTokenBudget lvl in ( ThinkingPlan- { field = Just Messages.ThinkingEnabled {Messages.budget_tokens = b},+ { field = Just (Messages.ManualBudget b Nothing), effort = Nothing, budget = Just b },@@ -504,34 +485,26 @@ -- The compat record is accepted at this layer for call-site -- consistency; per-tool @cache_control@ markers are applied by -- 'Baikai.Provider.Claude.Shape.injectToolCacheControl'.-mkAnthropicTool :: AnthropicMessagesCompat -> Tool.Tool -> ClaudeTool.ToolDefinition-mkAnthropicTool _compat t =- ClaudeTool.inlineTool- ( ClaudeTool.functionTool- (Tool.name t)- (Just (Tool.description t))- (Tool.parameters t)- )+mkAnthropicTool :: Tool.Tool -> Messages.Tool+mkAnthropicTool tool =+ case Tool.parameters tool of+ Aeson.Object schema -> Messages.CustomTool (Messages.ClientTool (Tool.name tool) (Just (Tool.description tool)) schema Nothing Nothing)+ schema ->+ Messages.VersionedTool (KeyMap.fromList ["name" .= Tool.name tool, "description" .= Tool.description tool, "input_schema" .= schema]) --- | Map a baikai 'Tool.ToolChoice' into the upstream Anthropic--- 'ClaudeTool.ToolChoice'. 'Tool.ToolChoiceNone' is handled by the--- raw request shaper because the SDK lacks a @none@ constructor.--- 'Tool.ToolChoiceRequired' maps to Anthropic's--- @any@ which is the closest equivalent ("must call some tool").-mkAnthropicToolChoice :: Tool.ToolChoice -> ClaudeTool.ToolChoice+mkAnthropicToolChoice :: Tool.ToolChoice -> Messages.ToolChoice mkAnthropicToolChoice = \case- Tool.ToolChoiceAuto -> ClaudeTool.ToolChoice_Auto- Tool.ToolChoiceRequired -> ClaudeTool.ToolChoice_Any- Tool.ToolChoiceSpecific n -> ClaudeTool.ToolChoice_Tool {ClaudeTool.name = n}- -- Unreachable in typed requests: ToolChoiceNone is injected by the shaper.- Tool.ToolChoiceNone -> ClaudeTool.ToolChoice_Auto+ Tool.ToolChoiceAuto -> Messages.AutoTool False+ Tool.ToolChoiceRequired -> Messages.AnyTool False+ Tool.ToolChoiceSpecific name -> Messages.NamedTool name False+ Tool.ToolChoiceNone -> Messages.NoTool -- | Anthropic enforces @[a-zA-Z0-9_-]@ on tool-call ids and caps their -- length at 64 characters. Callers may have used any naming convention, -- so the provider boundary normalizes here whenever an id is -- round-tripped back to Anthropic — both on assistant turn replay--- ('Messages.Content_Tool_Use') and on tool-result messages--- ('Messages.Content_Tool_Result').+-- ('Messages.InputToolUse') and on tool-result messages+-- ('Messages.InputToolResult'). -- -- An id that already satisfies the rule passes through byte for byte. -- That covers every id either provider actually mints — Anthropic's@@ -592,125 +565,54 @@ mapMessage :: Msg.Message -> Either Text (Maybe Messages.Message) mapMessage = \case Msg.UserMessage Msg.UserPayload {Msg.content = uc} ->- let blocks = Vector.mapMaybe userContentToBlock uc- in if Vector.null blocks- then- Left- "Anthropic Messages rejects a user turn with no content blocks; \- \this one had none, or only empty text"- else- Right- ( Just- Messages.Message- { Messages.role = Messages.User,- Messages.content = blocks,- Messages.cache_control = Nothing- }- )+ case NonEmpty.nonEmpty (Vector.toList (Vector.mapMaybe userContentToBlock uc)) of+ Nothing -> Left "Anthropic Messages rejects a user turn with no content blocks; this one had none, or only empty text"+ Just blocks -> Right (Just (Messages.Message Messages.User blocks)) Msg.AssistantMessage Msg.AssistantPayload {Msg.content = ac} ->- let blocks = Vector.mapMaybe assistantContentToBlock ac+ let blocks = Vector.toList (Vector.mapMaybe assistantContentToBlock ac) in case duplicateToolUseId blocks of- Just dup ->- Left ("duplicate tool_use id after normalisation: " <> dup)- Nothing- | Vector.null blocks -> Right Nothing- | otherwise ->- Right- ( Just- Messages.Message- { Messages.role = Messages.Assistant,- Messages.content = blocks,- Messages.cache_control = Nothing- }- )- Msg.ToolResultMessage- Msg.ToolResultPayload- { Msg.toolCallId = tid,- Msg.content = trc,- Msg.isError = err- } ->- case concatToolResultText trc of- Left unsupported -> Left unsupported- Right body ->- Right- ( Just- Messages.Message- { Messages.role = Messages.User,- Messages.content =- Vector.singleton- Messages.Content_Tool_Result- { Messages.tool_use_id = normalizeToolCallId tid,- Messages.content = nonEmpty body,- Messages.is_error = Just err- },- Messages.cache_control = Nothing- }- )+ Just dup -> Left ("duplicate tool_use id after normalisation: " <> dup)+ Nothing -> Right (Messages.Message Messages.Assistant <$> NonEmpty.nonEmpty blocks)+ Msg.ToolResultMessage Msg.ToolResultPayload {Msg.toolCallId = tid, Msg.content = trc, Msg.isError = err} -> do+ body <- concatToolResultText trc+ let payload = if Text.null body then Messages.EmptyToolResult else Messages.ToolResultText body+ block = Messages.InputToolResult (Messages.ToolResult (normalizeToolCallId tid) payload (Just err) Nothing)+ Right (Just (Messages.Message Messages.User (block :| []))) --- | The first @tool_use@ id that appears twice in one assistant turn,--- if any. Ids are already normalised at this point, so this catches the--- residual hash collision as well as a caller that reused an id.-duplicateToolUseId :: Vector Messages.Content -> Maybe Text-duplicateToolUseId = go [] . Vector.toList+-- | IDs have already been normalised, so this also catches collisions.+duplicateToolUseId :: [Messages.InputBlock] -> Maybe Text+duplicateToolUseId = go [] where go _ [] = Nothing- go seen (Messages.Content_Tool_Use {Messages.id = i} : rest)+ go seen (Messages.InputToolUse i _ _ _ : rest) | i `elem` seen = Just i | otherwise = go (i : seen) rest go seen (_ : rest) = go seen rest --- | An empty text block is dropped: Anthropic rejects--- @{"type":"text","text":""}@ outright, and an empty block carries--- nothing the model or the caller said.-userContentToBlock :: Content.UserContent -> Maybe Messages.Content+userContentToBlock :: Content.UserContent -> Maybe Messages.InputBlock userContentToBlock = \case Content.UserText (Content.TextContent t) | Text.null t -> Nothing- | otherwise ->- Just Messages.Content_Text {Messages.text = t, Messages.cache_control = Nothing}+ | otherwise -> Just (Messages.InputText t) Content.UserData v -> userContentToBlock (Content.UserText (Content.TextContent (Content.canonicalDataText v))) Content.UserImage img ->- Just- Messages.Content_Image- { Messages.source =- Messages.ImageSource- { Messages.type_ = "base64",- Messages.media_type = Content.mimeType img,- Messages.data_ = Text.decodeUtf8 (Base64.encode (Content.imageData img))- },- Messages.cache_control = Nothing- }+ Just (Messages.InputImage (Messages.Base64Image (Content.mimeType img) (Text.decodeUtf8 (Base64.encode (Content.imageData img))))) --- | As 'userContentToBlock' for empty text. Unsigned thinking is also--- dropped, because Anthropic rejects a thinking block whose signature--- is missing; a turn left with no blocks at all is then dropped--- entirely by 'mapMessage'.-assistantContentToBlock :: Content.AssistantContent -> Maybe Messages.Content+assistantContentToBlock :: Content.AssistantContent -> Maybe Messages.InputBlock assistantContentToBlock = \case Content.AssistantText (Content.TextContent t) | Text.null t -> Nothing+ | otherwise -> Just (Messages.InputText t)+ Content.AssistantThinking th+ | Content.redacted th ->+ Just (reasoning "redacted_thinking" ["data" .= Content.thinking th]) | otherwise ->- Just Messages.Content_Text {Messages.text = t, Messages.cache_control = Nothing}- Content.AssistantThinking th ->- if Content.redacted th- then Just Messages.Content_Redacted_Thinking {Messages.data_ = Content.thinking th}- else case Content.signature th of- Just sig ->- Just- Messages.Content_Thinking- { Messages.thinking = Content.thinking th,- Messages.signature = sig- }- Nothing -> Nothing+ (\sig -> reasoning "thinking" ["thinking" .= Content.thinking th, "signature" .= sig]) <$> Content.signature th Content.AssistantData _ -> Nothing Content.AssistantToolCall tc ->- Just- Messages.Content_Tool_Use- { Messages.id = normalizeToolCallId (Content.id_ tc),- Messages.name = Content.name tc,- Messages.input = Content.arguments tc,- Messages.caller = Nothing- }+ Just (Messages.InputToolUse (normalizeToolCallId (Content.id_ tc)) (Content.name tc) (Content.arguments tc) Nothing)+ where+ reasoning tag fields = Messages.VersionedBlock (KeyMap.fromList (("type" .= (tag :: Text)) : fields)) concatToolResultText :: Vector Content.ToolResultContent -> Either Text Text concatToolResultText =@@ -721,16 +623,11 @@ Content.ToolResultImage _ -> Left "Anthropic Messages cannot encode ToolResultImage blocks in tool-result messages" -nonEmpty :: Text -> Maybe Text-nonEmpty t- | Text.null t = Nothing- | otherwise = Just t- -- | One capability gate shared by wire mapping, headers and the describer. planSpeed :: AnthropicMessagesCompat -> Maybe Speed -> (Maybe Messages.Speed, [ThinkingAdjustment]) planSpeed compat = \case Nothing -> (Nothing, [])- Just SpeedStandard -> (Just Messages.SpeedStandard, [])+ Just SpeedStandard -> (Just Messages.Standard, []) Just SpeedFast- | compat ^. #supportsFastMode -> (Just Messages.SpeedFast, [])+ | compat ^. #supportsFastMode -> (Just Messages.Fast, []) | otherwise -> (Nothing, [FastModeDroppedUnsupportedModel])
src/Baikai/Provider/Claude/Internal/Stream.hs view
@@ -9,11 +9,11 @@ -- -- The Anthropic Messages streaming machinery: the SSE driver seam, the -- event assembler and the translator that turns the SDK's typed--- 'Claude.V1.Messages.MessageStreamEvent' values into baikai+-- 'Claude.Streaming.StreamPayload' values into baikai -- 'AssistantMessageEvent' values. The public entry points built on it -- live in "Baikai.Provider.Claude.Api". ----- Requests start as the SDK's typed 'Claude.V1.Messages.CreateMessage'+-- Requests start as the SDK's typed 'Claude.Messages.MessageRequest' -- value, then 'Baikai.Provider.Claude.Shape.streamRequestBody' patches -- the raw JSON body for tool-schema, @tool_choice@, and tool-cache -- compat before@@ -38,10 +38,11 @@ import Baikai.Error (BaikaiError, contentFiltered, invalidRequest, providerError) import Baikai.Evidence qualified as Ev import Baikai.Evidence.Build qualified as Build+import Baikai.Http (canonicalBaseUrl) import Baikai.Message qualified as Msg import Baikai.Model (Model, anthropicMessagesCompatFor) import Baikai.Options (Options (..))-import Baikai.Provider.Claude.Internal.ErrorClass (classifyErrorValue, classifyException)+import Baikai.Provider.Claude.Internal.ErrorClass (classifyException) import Baikai.Provider.Claude.Internal.Request (describeThinkingFor, mapRequest) import Baikai.Provider.Claude.Shape (streamRequestBody) import Baikai.Provider.Claude.Sse (claudeSseStreamValueWithHeaders)@@ -69,14 +70,14 @@ import Baikai.Url qualified as Url import Baikai.Usage qualified as Usage import Baikai.Usage.Normalize qualified as Normalize-import Claude.V1.Messages qualified as Messages+import Claude.Messages qualified as Messages+import Claude.Streaming qualified as Messages import Control.Applicative ((<|>)) import Control.Exception (SomeAsyncException (..), SomeException, fromException, throwIO, try) import Control.Lens ((%~), (&), (.~), (^.)) import Data.Aeson (Value) import Data.Aeson qualified as Aeson import Data.Aeson.KeyMap qualified as KeyMap-import Data.ByteString.Lazy qualified as BSL import Data.CaseInsensitive qualified as CI import Data.Generics.Labels () import Data.IORef (IORef, newIORef, readIORef, writeIORef)@@ -109,7 +110,7 @@ type SseDriver = ClaudeCall -> (Sse.ResponseMetadata -> IO ()) ->- (Either BaikaiError Messages.MessageStreamEvent -> IO ()) ->+ (Either BaikaiError Messages.StreamPayload -> IO ()) -> IO () -- | The production driver: a real HTTPS request through the cached@@ -117,7 +118,7 @@ liveSseDriver :: SseDriver liveSseDriver call = claudeSseStreamValueWithHeaders- (call ^. #clientEnv)+ (call ^. #transportBase) (call ^. #requestHeaders) (call ^. #requestBody) @@ -132,7 +133,7 @@ case setup of Left err -> Stream.fromList <$> immediateError m opts err Right call -> do- q <- newFrameQueue :: IO (FrameQueue (Either BaikaiError Messages.MessageStreamEvent))+ q <- newFrameQueue :: IO (FrameQueue (Either BaikaiError Messages.StreamPayload)) tref <- newIORef False mref <- newIORef Nothing startTime <- getCurrentTime@@ -142,7 +143,7 @@ -- separately by 'Transport.requestHeaders'. mkEvidence <- Build.prepareEvidenceAt- (Text.pack (Client.showBaseUrl (Client.baseUrl (call ^. #clientEnv))) <> "/v1/messages")+ (Text.pack (Client.showBaseUrl (call ^. #transportBase)) <> "/v1/messages") m opts Ev.TransportHttpApi@@ -181,7 +182,7 @@ -- | Per-call prepared values, including the shaped JSON request body -- passed to the local streaming transport. data ClaudeCall = ClaudeCall- { clientEnv :: !Client.ClientEnv,+ { transportBase :: !Client.BaseUrl, requestHeaders :: !RequestHeaders, timeoutMs :: !(Maybe Int), requestBody :: !Aeson.Value,@@ -226,22 +227,23 @@ case Url.baseUrlProblem url of Just problem -> pure (Left (invalidRequest ("Model.baseUrl is not usable: " <> problem)))- Nothing -> do- key <- Transport.resolveKey url opts- env <- Transport.getClientEnvCached url- let body = streamRequestBody compat ctx opts req- headers = Transport.requestHeaders key version compat ctx m opts- pure- ( Right- ClaudeCall- { clientEnv = env,- requestHeaders = headers,- timeoutMs = opts ^. #timeoutMs,- requestBody = body,- baseUrl = url,- thinking = translation- }- )+ Nothing -> case canonicalBaseUrl url of+ Left problem -> pure (Left (invalidRequest problem))+ Right transportUrl -> do+ key <- Transport.resolveKey url opts+ let body = streamRequestBody compat ctx opts req+ headers = Transport.requestHeaders key version compat ctx m opts+ pure+ ( Right+ ClaudeCall+ { transportBase = transportUrl,+ requestHeaders = headers,+ timeoutMs = opts ^. #timeoutMs,+ requestBody = body,+ baseUrl = url,+ thinking = translation+ }+ ) -- | Worker body: drive the SDK's typed callback, forwarding events onto -- the frame queue. Any synchronous exception is converted into a@@ -257,7 +259,7 @@ SseDriver -> ClaudeCall -> IORef (Maybe Sse.ResponseMetadata) ->- FrameQueue (Either BaikaiError Messages.MessageStreamEvent) ->+ FrameQueue (Either BaikaiError Messages.StreamPayload) -> IO () worker driver call metaRef q = do r <-@@ -274,7 +276,7 @@ -- | The streaming 'Stream' state. data ProducerState = ProducerState- { chan :: !(FrameQueue (Either BaikaiError Messages.MessageStreamEvent)),+ { chan :: !(FrameQueue (Either BaikaiError Messages.StreamPayload)), pending :: ![AssistantMessageEvent], assembler :: !Assembler, finished :: !Bool,@@ -630,7 +632,7 @@ } translate ::- Either BaikaiError Messages.MessageStreamEvent ->+ Either BaikaiError Messages.StreamPayload -> Assembler -> UTCTime -> ([AssistantMessageEvent], Assembler)@@ -645,7 +647,7 @@ Right ev -> translateEvent ev ass now translateEvent ::- Messages.MessageStreamEvent ->+ Messages.StreamPayload -> Assembler -> UTCTime -> ([AssistantMessageEvent], Assembler)@@ -656,7 +658,7 @@ -- failure arriving before this frame — a 401, a rate limit, an -- in-band error event, an EOF — still begins the stream the way the -- protocol says every stream begins.- Messages.Message_Start {Messages.message = mr} ->+ Messages.MessageStart mr -> let usage0 = anthroUsageToBaikai (mr ^. #usage) ass' = ass@@ -669,46 +671,42 @@ & #usage .~ usage0 & #usageReported .~ True in ([], ass')- Messages.Content_Block_Start {Messages.index = idx, Messages.content_block = block} ->+ Messages.ContentBlockStart idx block -> handleBlockStart (fromIntegral idx) block ass- Messages.Content_Block_Delta {Messages.index = idx, Messages.delta = d} ->+ Messages.ContentBlockDelta idx d -> handleBlockDelta (fromIntegral idx) d ass- Messages.Content_Block_Stop {Messages.index = idx} ->+ Messages.ContentBlockStop idx -> handleBlockStop (fromIntegral idx) ass- Messages.Message_Delta {Messages.message_delta = md, Messages.usage = su} ->- let stopR = mapStopReason (md ^. #stop_reason)+ Messages.MessageDelta md su ->+ let stopR = mapStopReason (md ^. #stopReason) u = ass ^. #usage -- @message_delta@ carries the call's final counts. Older models -- send only @output_tokens@; Claude 5 repeats the prompt-side -- classes too, which matters because a server-side tool run -- grows them after @message_start@. An absent field keeps what -- @message_start@ reported rather than zeroing it.- --- -- 'Messages.StreamUsage' has no 'GHC.Generics.Generic' instance,- -- so these are record dots rather than the generic-lens labels- -- used for 'Messages.Usage'. known category getter = case u ^. #availability of Just facts | category `Set.notMember` Usage.missingCategories facts -> Just (getter u) _ -> Nothing u' =- Usage.observeBilling (maybe [] (Set.toList . Usage.billingFacts) (u ^. #availability) <> toolBilling su.stream_server_tool_use) $+ Usage.observeBilling (maybe [] (Set.toList . Usage.billingFacts) (u ^. #availability) <> usageBilling (su ^. #usageEvidence)) $ Normalize.normalizeUsage Normalize.ExclusiveInput ( Normalize.ReportedUsage- (su.stream_input_tokens <|> known Usage.InputUsage Usage.inputTokens)- (Just su.output_tokens)- (su.stream_cache_read_input_tokens <|> known Usage.CacheReadUsage Usage.cacheReadTokens)- (su.stream_cache_creation_input_tokens <|> known Usage.CacheWriteUsage Usage.cacheWriteTokens)- ((Messages.thinking_tokens <$> su.stream_output_tokens_details) <|> (u ^. #reasoningTokens))+ ((su ^. #inputTokens) <|> known Usage.InputUsage Usage.inputTokens)+ ((su ^. #outputTokens) <|> known Usage.OutputUsage Usage.outputTokens)+ ((su ^. #cacheReadInputTokens) <|> known Usage.CacheReadUsage Usage.cacheReadTokens)+ ((su ^. #cacheCreationInputTokens) <|> known Usage.CacheWriteUsage Usage.cacheWriteTokens)+ (((su ^. #usageEvidence . #outputTokensDetails) >>= Messages.thinkingTokens) <|> (u ^. #reasoningTokens)) )- in ([], ass & #stopReason .~ stopR & #stopDetails .~ (md ^. #stop_details) & #usage .~ u' & #usageReported .~ True)- Messages.Message_Stop ->+ in ([], ass & #stopReason .~ stopR & #stopDetails .~ (md ^. #stopDetails) & #usage .~ u' & #usageReported .~ True)+ Messages.MessageStop -> let reason = ass ^. #stopReason -- A refusal is a filter: the content, not the transport, is -- the problem, and a caller can branch on the category. details = ass ^. #stopDetails- refusalCategory = details >>= (\d -> d.category)- explanation = details >>= (\d -> d.explanation)+ refusalCategory = details >>= \case Messages.RefusalDetails category _ _ -> category; _ -> Nothing+ explanation = details >>= \case Messages.RefusalDetails _ detail _ -> detail; _ -> Nothing refusal = contentFiltered ( "Anthropic refused to generate a response (stop_reason=refusal)"@@ -725,66 +723,58 @@ then EventError (errorTerminal Nothing (ass ^. #responseId) reason msg refusal) else EventDone (doneTerminal Nothing (ass ^. #responseId) reason msg) in ([terminalEvent], ass)- Messages.Error {Messages.error = errVal} ->- let (closeEvents, ass') = closeOpenBlocks ass- errText = renderAnthropicError errVal- mErr = classifyErrorValue errVal- msg = finalMessageOnError ass' now errText- errInfo = fromMaybe (providerError errText) mErr- in ( closeEvents- <> [EventError (errorTerminal Nothing (ass' ^. #responseId) Stop.ErrorReason msg errInfo)],- ass'- )+ Messages.UnknownEvent _ -> ([], ass) handleBlockStart :: Int ->- Messages.ContentBlock ->+ Messages.OutputBlock -> Assembler -> ([AssistantMessageEvent], Assembler)-handleBlockStart i block ass = case block of- Messages.ContentBlock_Text {} ->+handleBlockStart i block ass = case Messages.blockContent block of+ Messages.OutputText {} -> ( [TextStart IndexPayload {contentIndex = i}], ass & #textBuf %~ IntMap.insert i Text.empty )- Messages.ContentBlock_Thinking {} ->+ Messages.OutputThinking {} -> ( [ThinkingStart IndexPayload {contentIndex = i}], ass & #thinkBuf %~ IntMap.insert i Text.empty )- Messages.ContentBlock_Redacted_Thinking {Messages.data_ = payload} ->+ Messages.RedactedThinking payload -> ( [ThinkingStart IndexPayload {contentIndex = i}], ass & #redactedBuf %~ IntMap.insert i payload )- Messages.ContentBlock_Tool_Use {Messages.id = tid, Messages.name = tn} ->- ( [ToolCallStart IndexPayload {contentIndex = i}],- ass- & #toolArgsBuf %~ IntMap.insert i Text.empty- & #toolMeta %~ IntMap.insert i (tid, tn)- )- _ ->- -- Server-tool, code-execution-tool, unknown — pass-through with no events.- ([], ass)+ Messages.OutputToolUse tid tn _ -> startTool tid tn+ Messages.OutputToolUseWithCaller tid tn _ _ -> startTool tid tn+ _ -> ([], ass)+ where+ startTool tid tn =+ ( [ToolCallStart IndexPayload {contentIndex = i}],+ ass+ & #toolArgsBuf %~ IntMap.insert i Text.empty+ & #toolMeta %~ IntMap.insert i (tid, tn)+ ) handleBlockDelta :: Int ->- Messages.ContentBlockDelta ->+ Messages.BlockDelta -> Assembler -> ([AssistantMessageEvent], Assembler) handleBlockDelta i d ass = case d of- Messages.Delta_Text_Delta {Messages.text = t} ->+ Messages.TextDelta t -> if IntMap.member i (ass ^. #textBuf) then ( [TextDelta DeltaPayload {contentIndex = i, delta = t}], ass & #textBuf %~ IntMap.adjust (<> t) i ) else ([], ass)- Messages.Delta_Thinking_Delta {Messages.thinking = t} ->+ Messages.ThinkingDelta t -> if IntMap.member i (ass ^. #thinkBuf) then ( [ThinkingDelta DeltaPayload {contentIndex = i, delta = t}], ass & #thinkBuf %~ IntMap.adjust (<> t) i ) else ([], ass)- Messages.Delta_Signature_Delta {Messages.signature = sig} ->+ Messages.SignatureDelta sig -> -- Signatures are tail-end metadata on thinking blocks; they -- attach to the ThinkingEnd event's content build, not a public -- delta event.@@ -794,13 +784,14 @@ ass & #thinkSig %~ IntMap.insertWith (\new old -> old <> new) i sig ) else ([], ass)- Messages.Delta_Input_Json_Delta {Messages.partial_json = j} ->+ Messages.InputJsonDelta j -> if IntMap.member i (ass ^. #toolArgsBuf) then ( [ToolCallDelta DeltaPayload {contentIndex = i, delta = j}], ass & #toolArgsBuf %~ IntMap.adjust (<> j) i ) else ([], ass)+ _ -> ([], ass) handleBlockStop :: Int -> Assembler -> ([AssistantMessageEvent], Assembler)@@ -991,11 +982,6 @@ exceptionToError :: SomeException -> BaikaiError exceptionToError e = fromMaybe (classifyException e) (fromException e) -renderAnthropicError :: Value -> Text-renderAnthropicError v = case v of- Aeson.String t -> t- _ -> Text.decodeUtf8 (BSL.toStrict (Aeson.encode v))- -- | Map the Anthropic streaming 'Message_Start.message.usage' value -- into baikai's 'Usage' shape. Cache-related counters are populated -- where present; cost is left at zero (the terminal event@@ -1008,33 +994,44 @@ -- calculation uses the duration selected by the actual shaped request body. anthroUsageToBaikai :: Messages.Usage -> Usage.Usage anthroUsageToBaikai u =- Usage.observeBilling ([Usage.BillingServiceTier tier | Just tier <- [u ^. #service_tier]] <> [Usage.BillingSpeed speed | Just value <- [u ^. #speed], Aeson.String speed <- [Aeson.toJSON value]] <> toolBilling (u ^. #server_tool_use)) $+ Usage.observeBilling (usageBilling (u ^. #usageEvidence)) $ Normalize.normalizeUsage Normalize.ExclusiveInput ( Normalize.ReportedUsage- (Just (u ^. #input_tokens))- (Just (u ^. #output_tokens))- (u ^. #cache_read_input_tokens)- (u ^. #cache_creation_input_tokens)- (fmap (^. #thinking_tokens) (u ^. #output_tokens_details))+ (Just (u ^. #inputTokens))+ (Just (u ^. #outputTokens))+ (u ^. #cacheReadInputTokens)+ (u ^. #cacheCreationInputTokens)+ ((u ^. #usageEvidence . #outputTokensDetails) >>= Messages.thinkingTokens) ) --- Server-side tool products are outside the token-rate calculation.-toolBilling :: Maybe Messages.ServerToolUseUsage -> [Usage.BillingFact]-toolBilling Nothing = []-toolBilling (Just usage) = [Usage.BillingServerToolUse | fromMaybe 0 (usage ^. #web_search_requests) + fromMaybe 0 (usage ^. #tool_search_requests) > 0]+usageBilling :: Messages.UsageEvidence -> [Usage.BillingFact]+usageBilling evidence =+ [Usage.BillingServiceTier tier | Just tier <- [evidence ^. #serviceTier]]+ <> [Usage.BillingSpeed speed | Just value <- [evidence ^. #observedSpeed], Aeson.String speed <- [Aeson.toJSON value]]+ <> [Usage.BillingServerToolUse | Just counts <- [evidence ^. #serverToolCounts], hasServerTools counts]+ where+ hasServerTools counts =+ any+ (maybe False (> 0))+ [ counts ^. #webSearchRequests,+ counts ^. #toolSearchRequests,+ counts ^. #webFetchRequests,+ counts ^. #codeExecutionRequests+ ] mapStopReason :: Maybe Messages.StopReason -> Stop.StopReason mapStopReason = \case- Just Messages.End_Turn -> Stop.Stop- Just Messages.Max_Tokens -> Stop.Length- Just Messages.Stop_Sequence -> Stop.Stop- Just Messages.Tool_Use -> Stop.ToolUse+ Just Messages.EndTurn -> Stop.Stop+ Just Messages.MaxTokensReached -> Stop.Length+ Just Messages.StopSequence -> Stop.Stop+ Just Messages.ToolUse -> Stop.ToolUse -- The turn was suspended mid-flight (a long-running server-side tool) -- and Anthropic expects the caller to send the message back to -- continue it. Nothing failed, so this is a stop, not an error; -- baikai's 'Stop.StopReason' has no constructor that says "resume me".- Just Messages.Pause_Turn -> Stop.Stop+ Just Messages.PauseTurn -> Stop.Stop Just Messages.Refusal -> Stop.ErrorReason- Just Messages.Model_Context_Window_Exceeded -> Stop.Length+ Just Messages.ModelContextWindowExceeded -> Stop.Length+ Just (Messages.UnknownStopReason _) -> Stop.Stop Nothing -> Stop.Stop
src/Baikai/Provider/Claude/Shape.hs view
@@ -21,7 +21,7 @@ import Baikai.Context (Context, tools) import Baikai.Options (Options, cacheRetention, toolChoice) import Baikai.Tool qualified as Tool-import Claude.V1.Messages qualified as Messages+import Claude.Messages qualified as Messages import Data.Aeson (Value (..), (.=)) import Data.Aeson qualified as Aeson import Data.Aeson.Key qualified as AesonKey@@ -46,10 +46,10 @@ AnthropicMessagesCompat -> Context -> Options ->- Messages.CreateMessage ->+ Messages.MessageRequest -> Aeson.Value streamRequestBody compat ctx opts req =- shapeRequestBody compat ctx opts (Aeson.toJSON req {Messages.stream = Just True})+ mapObject (KeyMap.insert "stream" (Bool True)) (shapeRequestBody compat ctx opts (Aeson.toJSON req)) replaceToolSchemas :: Context -> Aeson.Value -> Aeson.Value replaceToolSchemas ctx
src/Baikai/Provider/Claude/Sse.hs view
@@ -5,34 +5,31 @@ -- sibling packages can reuse its pieces; it is not part of the public -- API and may change in /any/ release without a PVP major bump. ----- Local SSE transport for Anthropic Messages streams.------ The upstream @claude@ SDK exposes the right event decoder, but its--- non-2xx path collapses status, headers, and body into plain text. This--- wrapper keeps the SDK's request and SSE parsing shape while surfacing--- classified 'BaikaiError' values.+-- Adapt the Claude client stream and its response metadata to Baikai's+-- provider error contract. module Baikai.Provider.Claude.Sse ( claudeSseStream, claudeSseStreamValue, claudeSseStreamValueWithHeaders, sseFromResponse, decodeFrame,- buildRequest, ResponseMetadata (..), capturedHeaderNames, ) where -import Baikai.Error (BaikaiError, decodeError, httpError, parseHttpDate, retryAfterSecondsAt)-import Claude.V1.Messages qualified as Messages-import Control.Monad (foldM, when)+import Baikai.Error (BaikaiError, ErrorCategory (TransientError), decodeError, httpError, invalidRequest, parseHttpDate, providerError, retryAfterSecondsAt)+import Baikai.Error qualified as Error+import Baikai.Provider.Claude.Internal.ErrorClass (classifyErrorValue)+import Claude.Client qualified as Candidate+import Claude.Messages (MessageRequest)+import Claude.Streaming qualified as Candidate+import Control.Monad (when) import Data.Aeson qualified as Aeson-import Data.Aeson.KeyMap qualified as Aeson.Key import Data.ByteString qualified as SBS import Data.ByteString.Char8 qualified as S8 import Data.CaseInsensitive (CI) import Data.CaseInsensitive qualified as CI-import Data.Char (isSpace) import Data.IORef qualified as IORef import Data.Maybe (fromMaybe) import Data.Text (Text)@@ -45,6 +42,7 @@ import Network.HTTP.Types.Header (RequestHeaders) import Network.HTTP.Types.Status qualified as Status import Servant.Client qualified as Client+import System.IO.Unsafe (unsafePerformIO) -- | Response-level metadata captured once, before the first event. --@@ -95,23 +93,23 @@ -- once per SSE event — potentially thousands of times per call — and -- response-level data does not belong on that hot path. claudeSseStream ::- Client.ClientEnv ->+ Client.BaseUrl -> Text -> Maybe Text ->- Messages.CreateMessage ->+ MessageRequest -> (ResponseMetadata -> IO ()) ->- (Either BaikaiError Messages.MessageStreamEvent -> IO ()) ->+ (Either BaikaiError Candidate.StreamPayload -> IO ()) -> IO () claudeSseStream env apiKey anthropicVersion req =- claudeSseStreamValue env apiKey anthropicVersion (Aeson.toJSON req {Messages.stream = Just True})+ claudeSseStreamValue env apiKey anthropicVersion (Aeson.toJSON req) claudeSseStreamValue ::- Client.ClientEnv ->+ Client.BaseUrl -> Text -> Maybe Text -> Aeson.Value -> (ResponseMetadata -> IO ()) ->- (Either BaikaiError Messages.MessageStreamEvent -> IO ()) ->+ (Either BaikaiError Candidate.StreamPayload -> IO ()) -> IO () claudeSseStreamValue env apiKey anthropicVersion = claudeSseStreamValueWithHeaders env requestHeaders@@ -127,52 +125,84 @@ ] claudeSseStreamValueWithHeaders ::- Client.ClientEnv ->+ Client.BaseUrl -> RequestHeaders -> Aeson.Value -> (ResponseMetadata -> IO ()) ->- (Either BaikaiError Messages.MessageStreamEvent -> IO ()) ->+ (Either BaikaiError Candidate.StreamPayload -> IO ()) -> IO () claudeSseStreamValueWithHeaders env requestHeaders requestBody onMetadata onEvent = do- HTTP.withResponse (buildRequest (Client.baseUrl env) requestHeaders requestBody) (Client.manager env) $ \response ->- sseFromResponse response onMetadata onEvent+ let config =+ (Candidate.defaultClientConfig (fromMaybe "" (lookup "x-api-key" requestHeaders)))+ { Candidate.endpoint = Client.showBaseUrl env,+ Candidate.apiVersion = lookup "anthropic-version" requestHeaders,+ Candidate.timeoutMicros = Nothing+ }+ options =+ Candidate.RequestOptions+ (maybe [] (S8.split ',') (lookup "anthropic-beta" requestHeaders))+ (filter ((`notElem` ["x-api-key", "anthropic-version", "anthropic-beta", "accept", "content-type"]) . fst) requestHeaders)+ created <- Candidate.newClientWithPool candidatePool config+ sentMetadata <- IORef.newIORef False+ let publish meta = do+ alreadySent <- IORef.atomicModifyIORef' sentMetadata (\sent -> (True, sent))+ when (not alreadySent) (onMetadata (candidateMetadata meta))+ case created of+ Left err -> onEvent (Left (candidateError err))+ Right client -> do+ result <- Candidate.streamMessageValue client options requestBody $ \meta event -> do+ publish meta+ forwardPayload onEvent (Candidate.eventPayload event)+ pure Candidate.Continue+ case result of+ Right response -> publish (Candidate.metadata response)+ Left (Candidate.ApiStatusError meta _ detail) -> do+ publish meta+ now <- getCurrentTime+ let reference = fromMaybe now (parseHttpDate . decodeLenient =<< Candidate.responseDate meta)+ retryAfter = retryAfterSecondsAt reference . decodeLenient =<< Candidate.retryAfter meta+ onEvent (Left (httpError (Candidate.status meta) retryAfter detail))+ Left err -> do+ mapM_ publish (failureMetadata err)+ onEvent (Left (candidateError err)) --- | The exact request this transport sends.------ Pure and exported so that what goes on the wire — the method, the--- composed path, and the redirect policy — is assertable without opening--- a connection.------ The path is the base URL's path plus @/v1/messages@. The base URL--- reaching here has already been through--- 'Baikai.Http.canonicalBaseUrl', which strips a trailing @\/v1@--- segment, so a caller who writes the base URL the way every OpenAI SDK--- teaches it — @https:\/\/api.deepseek.com\/v1@ — gets one @\/v1@ here--- rather than two.-buildRequest :: Client.BaseUrl -> RequestHeaders -> Aeson.Value -> HTTP.Request-buildRequest base requestHeaders requestBody =- HTTP.defaultRequest- { HTTP.secure = case Client.baseUrlScheme base of- Client.Http -> False- Client.Https -> True,- HTTP.host = S8.pack (Client.baseUrlHost base),- HTTP.port = Client.baseUrlPort base,- HTTP.method = "POST",- HTTP.path = S8.pack (normalizePath (Client.baseUrlPath base) <> "/v1/messages"),- HTTP.requestHeaders = requestHeaders,- HTTP.requestBody = HTTP.RequestBodyLBS (Aeson.encode requestBody),- -- This POST has no legitimate redirect, and http-client's default- -- is to follow up to ten of them with every header intact — which- -- would re-send the credential to whatever host a Location names.- -- At zero the 3xx comes back untouched and 'sseFromResponse'- -- delivers it as the one in-band terminal error, carrying its- -- status.- HTTP.redirectCount = 0,- -- No per-response bound here: Options.timeoutMs is enforced around- -- the whole call by Transport.runWithTimeout.- HTTP.responseTimeout = HTTP.responseTimeoutNone- }+{-# NOINLINE candidatePool #-}+candidatePool :: Candidate.ClientPool+candidatePool = unsafePerformIO Candidate.newClientPool +candidateMetadata :: Candidate.ResponseMetadata -> ResponseMetadata+candidateMetadata meta =+ ResponseMetadata (Candidate.status meta) $+ [ (name, decodeLenient header)+ | (name, Just header) <-+ [ ("request-id", Candidate.requestId meta),+ ("x-request-id", Candidate.gatewayRequestId meta),+ ("cf-ray", Candidate.cloudflareRay meta)+ ]+ ]++failureMetadata :: Candidate.ClientError -> Maybe Candidate.ResponseMetadata+failureMetadata = \case+ Candidate.TransportError meta _ -> meta+ Candidate.DecodeError meta _ -> Just meta+ Candidate.StreamApiError meta _ -> Just meta+ _ -> Nothing++candidateError :: Candidate.ClientError -> BaikaiError+candidateError = \case+ Candidate.InvalidRequest detail -> invalidRequest detail+ Candidate.DecodeError _ "Stream ended before message_stop" -> providerError "claude stream ended without message_stop"+ Candidate.DecodeError _ detail -> decodeError detail+ Candidate.StreamApiError _ err -> classifyProviderError err+ Candidate.TransportError _ kind -> (providerError (Text.pack (show kind))) {Error.category = TransientError}+ err -> decodeError (Text.pack (show err))++classifyProviderError :: Candidate.ApiError -> BaikaiError+classifyProviderError err =+ let detail = Candidate.message err+ body = Aeson.object ["type" Aeson..= Candidate.errorType err, "message" Aeson..= detail]+ in fromMaybe (providerError detail) (classifyErrorValue body)+ -- | Consume an @http-client@ response as an Anthropic SSE stream. -- -- 'onMetadata' fires exactly once, before any event, on both the@@ -182,7 +212,7 @@ sseFromResponse :: HTTP.Response HTTP.BodyReader -> (ResponseMetadata -> IO ()) ->- (Either BaikaiError Messages.MessageStreamEvent -> IO ()) ->+ (Either BaikaiError Candidate.StreamPayload -> IO ()) -> IO () sseFromResponse response onMetadata onEvent = do let st = HTTP.responseStatus response@@ -201,126 +231,40 @@ retryAfter = retryAfterSecondsAt reference =<< headerText "Retry-After" onEvent (Left (httpError (Status.statusCode st) retryAfter bodyText)) else do- lineBufRef <- IORef.newIORef SBS.empty- eventBufRef <- IORef.newIORef ([] :: [SBS.ByteString])- let flushEvent = do- es <- IORef.atomicModifyIORef' eventBufRef (\buf -> ([], reverse buf))- case es of- [] -> pure False- _ -> do- let payload = S8.dropWhileEnd isSpace (S8.concat es)- if SBS.null payload- then -- An empty @data:@ line is a heartbeat, not a frame.- pure False- else case decodeFrame payload of- Left e -> onEvent (Left e) >> pure False- Right Nothing -> pure False- Right (Just ev) -> onEvent (Right ev) >> pure False-- handleLine line =- let l = stripCR line- in if S8.null l- then flushEvent- else- if "data:" `S8.isPrefixOf` l- then do- let d = S8.dropWhile (== ' ') (S8.drop 5 l)- IORef.modifyIORef' eventBufRef (d :)- pure False- else pure False-- loop = do- chunk <- HTTP.brRead (HTTP.responseBody response)- if SBS.null chunk- then do- pendingLine <- IORef.readIORef lineBufRef- when (not (SBS.null pendingLine)) $ do- _ <- handleLine pendingLine- IORef.writeIORef lineBufRef SBS.empty- _ <- flushEvent- pure ()- else do- prev <- IORef.readIORef lineBufRef- let combined = prev <> chunk- ls = S8.split '\n' combined- case unsnoc ls of- Nothing -> loop- Just (completeLines, lastLine) -> do- IORef.writeIORef lineBufRef lastLine- stop <- foldM (\acc ln -> if acc then pure True else handleLine ln) False completeLines- if stop then pure () else loop- loop---- | Decode one SSE frame.------ @Right Nothing@ is a frame this transport deliberately skips: an event--- @type@, or a @content_block_delta@ whose @delta.type@, that the SDK--- has no constructor for. The SDK decodes both with aeson's tagged-object--- encoding and no unknown-tag fallback, so an unrecognised tag is a--- decode /failure/ there — and a new frame type from Anthropic must not--- end an otherwise healthy stream. A frame of a __known__ type that--- still fails to decode is a genuine fault and stays a 'decodeError'.------ Both tag lists are copied from the SDK's @constructorTagModifier@--- tables in @Claude.V1.Messages@. A frame carrying no @type@ field at--- all is not "unknown" — it is malformed, and fails as before.-decodeFrame :: SBS.ByteString -> Either BaikaiError (Maybe Messages.MessageStreamEvent)-decodeFrame payload = case Aeson.eitherDecodeStrict payload of- Left err -> Left (decodeError (Text.pack err))- Right val- | frameIsUnknown val -> Right Nothing- | otherwise -> case Aeson.fromJSON val of- Aeson.Error err -> Left (decodeError (Text.pack err))- Aeson.Success ev -> Right (Just ev)---- | Whether this frame names a type the SDK has no constructor for.-frameIsUnknown :: Aeson.Value -> Bool-frameIsUnknown val = case val of- Aeson.Object o -> case Aeson.Key.lookup "type" o of- Just (Aeson.String "content_block_delta") ->- case Aeson.Key.lookup "delta" o of- Just (Aeson.Object d) -> case Aeson.Key.lookup "type" d of- Just (Aeson.String dt) -> dt `notElem` knownDeltaTypes- _ -> False- _ -> False- Just (Aeson.String t) -> t `notElem` knownEventTypes- _ -> False- _ -> False--knownEventTypes :: [Text]-knownEventTypes =- [ "message_start",- "content_block_start",- "content_block_delta",- "content_block_stop",- "message_delta",- "message_stop",- "ping",- "error"- ]--knownDeltaTypes :: [Text]-knownDeltaTypes =- [ "text_delta",- "input_json_delta",- "thinking_delta",- "signature_delta"- ]+ let header name = lookup name (HTTP.responseHeaders response)+ metadata =+ Candidate.ResponseMetadata+ { Candidate.requestId = header "request-id",+ Candidate.gatewayRequestId = header "x-request-id",+ Candidate.cloudflareRay = header "cf-ray",+ Candidate.status = Status.statusCode st,+ Candidate.retryAfter = header "retry-after",+ Candidate.responseDate = header "date"+ }+ result <- Candidate.consumeEventStream metadata (HTTP.brRead (HTTP.responseBody response)) $ \event -> do+ forwardPayload onEvent (Candidate.eventPayload event)+ pure Candidate.Continue+ case result of+ Left err -> onEvent (Left (candidateError err))+ Right _ -> pure () -normalizePath :: String -> String-normalizePath = \case- "" -> ""- p@('/' : _) -> p- p -> '/' : p+-- | Decode an individual recorded frame with the client codec.+decodeFrame :: SBS.ByteString -> Either BaikaiError (Maybe Candidate.StreamPayload)+decodeFrame payload = do+ raw <- either (Left . decodeError . Text.pack) Right (Aeson.eitherDecodeStrict payload)+ parsed <- either (Left . decodeError . Text.pack) Right (Candidate.decodeStreamEvent raw)+ case parsed of+ Left err -> Left (classifyProviderError err)+ Right event -> pure (knownPayload (Candidate.eventPayload event)) -stripCR :: SBS.ByteString -> SBS.ByteString-stripCR bs = case S8.unsnoc bs of- Just (initBs, '\r') -> initBs- _ -> bs+forwardPayload :: (Either BaikaiError Candidate.StreamPayload -> IO ()) -> Candidate.StreamPayload -> IO ()+forwardPayload send = mapM_ (send . Right) . knownPayload -unsnoc :: [a] -> Maybe ([a], a)-unsnoc [] = Nothing-unsnoc xs = Just (init xs, last xs)+knownPayload :: Candidate.StreamPayload -> Maybe Candidate.StreamPayload+knownPayload = \case+ Candidate.UnknownEvent _ -> Nothing+ Candidate.ContentBlockDelta _ (Candidate.UnknownDelta _ _) -> Nothing+ payload -> Just payload decodeLenient :: SBS.ByteString -> Text decodeLenient = Text.decodeUtf8With Text.lenientDecode
src/Baikai/Provider/Claude/Transport.hs view
@@ -26,7 +26,7 @@ import Baikai.Model (Model (..)) import Baikai.Options (Options (..)) import Baikai.Provider.Claude.Internal.Request (planSpeed)-import Claude.V1.Messages qualified as Messages+import Claude.Messages qualified as Messages import Control.Exception (throwIO) import Control.Lens ((^.)) import Crypto.Hash (Digest, SHA256)@@ -65,7 +65,7 @@ ] ) speedHeaders = case fst (planSpeed compat (opts ^. #speed)) of- Just Messages.SpeedFast -> [("anthropic-beta", "fast-mode-2026-02-01")]+ Just Messages.Fast -> [("anthropic-beta", "fast-mode-2026-02-01")] _ -> [] sessionHeaders = if sendSessionAffinityHeaders compat
test/FableContractsSpec.hs view
@@ -1,12 +1,14 @@+{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedRecordDot #-} module FableContractsSpec (tests) where import Baikai hiding (messages, model)-import Baikai.Models.Generated (anthropic_claude_fable_5_1, anthropic_claude_haiku_5_5, anthropic_claude_opus_5_5, anthropic_claude_sonnet_5_5)+import Baikai.Models.Generated (anthropic_claude_fable_5_1, anthropic_claude_fable_5_2, anthropic_claude_haiku_4_5, anthropic_claude_haiku_5_5, anthropic_claude_opus_5_5, anthropic_claude_sonnet_4_6, anthropic_claude_sonnet_5_5)+import Baikai.Provider.Claude.Api (claudeMessagesProvider, claudeMessagesStream) import Baikai.Provider.Claude.Internal.Request qualified as R-import Baikai.Provider.Claude.Internal.Stream (SseDriver, claudeMessagesStreamWith)-import Claude.V1.Messages qualified as C+import Baikai.Provider.Claude.Internal.Stream (claudeMessagesStreamWith)+import Claude.Streaming qualified as C import Contract (assertErrorContract) import Control.Lens ((&), (.~), (^.)) import Control.Monad (forM_)@@ -14,10 +16,16 @@ import Data.Aeson qualified as Aeson import Data.Aeson.Key (Key) import Data.Aeson.KeyMap qualified as KM-import Data.IORef (newIORef, readIORef, writeIORef)+import Data.ByteString (ByteString)+import Data.IORef (atomicModifyIORef', newIORef, readIORef, writeIORef)+import Data.Map.Strict qualified as Map import Data.Text (Text) import Data.Text qualified as T+import Data.Text.Encoding qualified as TextEncoding import Data.Vector qualified as V+import Network.HTTP.Types (status200)+import Network.Wai qualified as Wai+import Network.Wai.Handler.Warp (testWithApplication) import Streamly.Data.Stream qualified as Stream import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))@@ -27,6 +35,11 @@ testGroup "Fable contracts" [ summaryTests,+ prefillTests,+ legacySamplingVersion,+ candidateCompleteAndStream,+ structuredCompletion,+ testGroup "two consecutive tool rounds preserve signed and redacted thinking" (map signedReplayFixture fableModels), testCase "Opus 5.5 and Sonnet 5.5 reject forced tools and replay signed empty thinking" $ forM_ [anthropic_claude_opus_5_5, anthropic_claude_sonnet_5_5] $ \opus -> do opus.api @?= AnthropicMessages@@ -56,12 +69,13 @@ testCase "Haiku 5.5 forwards a forced tool choice with adaptive thinking" $ do (req, _) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest anthropic_claude_haiku_5_5 haikuContext haikuForcedOptions) Aeson.toJSON req @?= haikuForcedBody,- testCase "Haiku 5.5 drops temperature and records why" $ do- (req, translation) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest anthropic_claude_haiku_5_5 context (options & #temperature .~ Just 0.2))- field "temperature" (Aeson.toJSON req) @?= Nothing- translation ^. #adjustments @?= [SamplingDroppedUnsupportedModel ["temperature"]],+ testCase "Haiku 5.5 and Fable 5.2 drop temperature and record why" $+ forM_ [anthropic_claude_haiku_5_5, anthropic_claude_fable_5_2] $ \selected -> do+ (req, translation) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest selected context (options & #temperature .~ Just 0.2))+ field "temperature" (Aeson.toJSON req) @?= Nothing+ translation ^. #adjustments @?= [SamplingDroppedUnsupportedModel ["temperature"]], testCase "forced choices fail before the driver for complete and stream, including renamed models" $- forM_ [model, model & #modelId .~ "renamed-generation"] $ \m ->+ forM_ (fableModels <> [model & #modelId .~ "renamed-generation"]) $ \m -> forM_ [ToolChoiceRequired, ToolChoiceSpecific "lookup"] $ \choice -> do sent <- newIORef False let never _ _ _ = writeIORef sent True@@ -73,65 +87,39 @@ assertBool "useful correction" (maybe False (T.isInfixOf "ToolChoiceAuto" . (.message)) (responseError response)) readIORef sent >>= (@?= False), testCase "auto and none keep their exact wire meaning" $- forM_ [(ToolChoiceAuto, "auto"), (ToolChoiceNone, "none")] $ \(choice, expected) -> do- body <- newIORef Null- let capture call _ emit = writeIORef body (call ^. #requestBody) >> send finalTurn emit- _ <- streamingComplete (claudeMessagesStreamWith capture) model context (options & #toolChoice .~ Just choice)- raw <- readIORef body- (field "tool_choice" raw >>= field "type") @?= Just (String expected),+ forM_ fableModels $ \selected ->+ forM_ [(ToolChoiceAuto, "auto"), (ToolChoiceNone, "none")] $ \(choice, expected) -> do+ body <- newIORef Null+ let capture call _ emit = writeIORef body (call ^. #requestBody) >> send (textTurn selected ["done"]) emit+ _ <- streamingComplete (claudeMessagesStreamWith capture) selected context (options & #toolChoice .~ Just choice)+ raw <- readIORef body+ (field "tool_choice" raw >>= field "type") @?= Just (String expected), testCase "supporting compatibility retains required and named choice" $ forM_ [(ToolChoiceRequired, "any"), (ToolChoiceSpecific "lookup", "tool")] $ \(choice, expected) -> do let m = model & #modelId .~ "supporting-generation" & #compat .~ CompatAnthropicMessages (anthropicMessagesCompatFor model & #supportsForcedToolChoice .~ True) (req, _) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest m context (options & #toolChoice .~ Just choice)) (field "tool_choice" (Aeson.toJSON req) >>= field "type") @?= Just (String expected), testCase "unset effort is no preference and small caps never create a manual budget" $- forM_ [Nothing, Just ThinkingMinimal, Just ThinkingLow, Just ThinkingMedium, Just ThinkingHigh, Just ThinkingXHigh, Just ThinkingMax] $ \level -> do- let opts = options & #thinking .~ level & #maxTokens .~ Just 1- (req, translation) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest model context opts)- let raw = Aeson.toJSON req- field "max_tokens" raw @?= Just (Number 1)- translation @?= R.describeThinkingFor model opts- case level of- Nothing -> do- field "thinking" raw @?= Nothing- translation @?= noThinkingRequested- Just _ -> do- (field "thinking" raw >>= field "type") @?= Just (String "adaptive")- (field "thinking" raw >>= field "budget_tokens") @?= Nothing,+ forM_ fableModels $ \selected ->+ forM_ [Nothing, Just ThinkingMinimal, Just ThinkingLow, Just ThinkingMedium, Just ThinkingHigh, Just ThinkingXHigh, Just ThinkingMax] $ \level -> do+ let opts = options & #thinking .~ level & #maxTokens .~ Just 1+ (req, translation) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest selected context opts)+ let raw = Aeson.toJSON req+ field "max_tokens" raw @?= Just (Number 1)+ translation @?= R.describeThinkingFor selected opts+ case level of+ Nothing -> do+ field "thinking" raw @?= Nothing+ (field "output_config" raw >>= field "effort") @?= Nothing+ translation @?= noThinkingRequested+ Just _ -> do+ (field "thinking" raw >>= field "type") @?= Just (String "adaptive")+ (field "thinking" raw >>= field "budget_tokens") @?= Nothing, testCase "legacy serialized compat defaults to supporting forced choice" $ do let raw = case Aeson.toJSON defaultAnthropicMessagesCompat of Object o -> Object (KM.delete "supportsForcedToolChoice" o); v -> v case Aeson.fromJSON raw of Aeson.Success c -> (c :: AnthropicMessagesCompat).supportsForcedToolChoice @?= True Aeson.Error err -> assertFailure err,- testCase "two consecutive tool rounds preserve signed empty, visible and redacted thinking" $ do- requests <- newIORef ([] :: [Value])- executed <- newIORef ([] :: [Text])- let scripted call _ emit = do- previous <- readIORef requests- writeIORef requests (previous <> [call ^. #requestBody])- send (case length previous of 0 -> toolTurn "" "sig-one" "toolu_1" True; 1 -> toolTurn "visible summary" "sig-two" "toolu_2" False; _ -> finalTurn) emit- reg <- newProviderRegistryFrom [apiProvider AnthropicMessages (claudeMessagesStreamWith scripted)]- (history, response) <- runToolLoopWith reg 4 (\tc -> do xs <- readIORef executed; writeIORef executed (xs <> [tc.id_]); pure (toolResultText "found")) model context summaryOptions- response.message.content @?= V.singleton (AssistantText (TextContent "done"))- readIORef executed >>= (@?= ["toolu_1", "toolu_2"])- bodies <- readIORef requests- length bodies @?= 3- case bodies of- [first, second, third] -> do- let a = messages first; b = messages second; c = messages third- V.take (V.length a) b @?= a- V.take (V.length b) c @?= b- field "system" first @?= field "system" third- field "tools" first @?= field "tools" third- forM_ bodies $ \body -> (field "thinking" body >>= field "display") @?= Just (String "summarized")- contentAt 1 b @?= V.fromList [signed "" "sig-one", redactedItem, toolItem "toolu_1"]- contentAt 3 c @?= V.fromList [signed "visible summary" "sig-two", toolItem "toolu_2"]- field "tool_use_id" (contentAt 2 b V.! 0) @?= Just (String "toolu_1")- field "tool_use_id" (contentAt 4 c V.! 0) @?= Just (String "toolu_2")- persisted <- V.mapM persistThinking (history ^. #messages)- (req, _) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest model (history & #messages .~ persisted) summaryOptions)- messages (Aeson.toJSON req) @?= c- _ -> assertFailure "expected three requests", testCase "error cleanup retains completed signed thinking for persistence" $ do let partial _ _ emit = send (take 4 (toolTurn "" "sig-one" "toolu_1" False)) emit >> emit (Left (providerError "interrupted")) response <- streamingComplete (claudeMessagesStreamWith partial) model context options@@ -144,9 +132,204 @@ _ -> assertFailure "signed state was discarded on error" ] +structuredCompletion :: TestTree+structuredCompletion = testCase "Fable 5.2 registered completion delivers the structured answer" $ do+ requests <- newIORef ([] :: [Value])+ let schema =+ object+ [ "type" .= String "object",+ "properties" .= object ["answer" .= object ["type" .= String "string"]],+ "required" .= [String "answer"],+ "additionalProperties" .= False+ ]+ frames = textTurn anthropic_claude_fable_5_2 ["{\"answer\":", "\"pong\"}"]+ app req respond = do+ Wai.pathInfo req @?= ["v1", "messages"]+ body <- Wai.strictRequestBody req >>= either fail pure . Aeson.eitherDecode+ atomicModifyIORef' requests (\previous -> (previous <> [body], ()))+ respond (Wai.responseLBS status200 [("Content-Type", "text/event-stream")] (foldMap (\frame -> "data: " <> Aeson.encode frame <> "\n\n") frames))+ testWithApplication (pure app) $ \port -> do+ registry <- newProviderRegistryFrom [claudeMessagesProvider]+ let selected = anthropic_claude_fable_5_2 & #baseUrl .~ ("http://127.0.0.1:" <> T.pack (show port))+ configured = summaryOptions & #responseFormat .~ Just (JsonSchema (jsonSchemaFormat "answer" schema))+ response <- completeRequestWith registry selected (systemUser "Return JSON." "Give the answer pong.") configured+ responseError response @?= Nothing+ response.message.stopReason @?= Stop+ fmap observedModel response.evidence @?= Just (Observed "claude-fable-5-2")+ let decoded = Aeson.eitherDecodeStrict (TextEncoding.encodeUtf8 (flattenAssistantText (flattenAssistantBlocks response)))+ decoded @?= Right (object ["answer" .= String "pong"])+ readIORef requests >>= \case+ [body] -> do+ let output = field "output_config" body+ (output >>= field "effort") @?= Just (String "low")+ (output >>= field "format" >>= field "schema") @?= Just schema+ _ -> assertFailure "expected exactly one structured completion request"++signedReplayFixture :: Model -> TestTree+signedReplayFixture selected = testCase (T.unpack selected.modelId) $ do+ requests <- newIORef ([] :: [Value])+ executed <- newIORef ([] :: [Text])+ let respond request reply = do+ Wai.pathInfo request @?= ["v1", "messages"]+ lookup "x-api-key" (Wai.requestHeaders request) @?= Just "fable-contract-key"+ lookup "anthropic-version" (Wai.requestHeaders request) @?= Just "2023-06-01"+ body <- Wai.strictRequestBody request >>= either fail pure . Aeson.eitherDecode+ num <- atomicModifyIORef' requests (\previous -> (previous <> [body], length previous))+ let frames = case num of+ 0 -> toolTurnFor selected "" "sig-one" "toolu_1" True+ 1 -> toolTurnFor selected "visible summary" "sig-two" "toolu_2" False+ _ -> textTurn selected ["done"]+ reply (Wai.responseLBS status200 [("Content-Type", "text/event-stream"), ("request-id", "req_trial_tools")] (foldMap (\frame -> "data: " <> Aeson.encode frame <> "\n\n") frames))+ (history, response) <- testWithApplication (pure respond) $ \port -> do+ let liveModel = selected & #baseUrl .~ ("http://127.0.0.1:" <> T.pack (show port))+ liveOptions = summaryOptions & #toolChoice .~ Just ToolChoiceAuto & #apiKey .~ Just (ApiKeyLiteral "fable-contract-key")+ reg <- newProviderRegistryFrom [claudeMessagesProvider]+ runToolLoopWith reg 4 (\tc -> do xs <- readIORef executed; writeIORef executed (xs <> [tc.id_]); pure (toolResultText "found")) liveModel context liveOptions+ responseError response @?= Nothing+ response.message.stopReason @?= Stop+ fmap observedModel response.evidence @?= Just (Observed selected.modelId)+ response.message.content @?= V.singleton (AssistantText (TextContent "done"))+ readIORef executed >>= (@?= ["toolu_1", "toolu_2"])+ bodies <- readIORef requests+ length bodies @?= 3+ case bodies of+ [first, second, third] -> do+ let a = messages first+ b = messages second+ c = messages third+ V.take (V.length a) b @?= a+ V.take (V.length b) c @?= b+ forM_ bodies $ \body -> do+ field "model" body @?= Just (String selected.modelId)+ field "system" body @?= field "system" first+ field "tools" body @?= field "tools" first+ (field "thinking" body >>= field "display") @?= Just (String "summarized")+ (field "tool_choice" body >>= field "type") @?= Just (String "auto")+ contentAt 1 b @?= V.fromList [signed "" "sig-one", redactedItem, toolItem "toolu_1"]+ contentAt 3 c @?= V.fromList [signed "visible summary" "sig-two", toolItem "toolu_2"]+ field "tool_use_id" (contentAt 2 b V.! 0) @?= Just (String "toolu_1")+ field "tool_use_id" (contentAt 4 c V.! 0) @?= Just (String "toolu_2")+ persisted <- V.mapM persistThinking (history ^. #messages)+ (req, _) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest selected (history & #messages .~ persisted) summaryOptions)+ messages (Aeson.toJSON req) @?= c+ _ -> assertFailure "expected three requests"++prefillTests :: TestTree+prefillTests =+ testGroup+ "assistant prefills"+ [ testCase "restricted tails fail before credentials or the driver via registered stream and completion" $ do+ sent <- newIORef (0 :: Int)+ let never _ _ _ = atomicModifyIORef' sent (\n -> (n + 1, ()))+ produce = claudeMessagesStreamWith never+ opts = options & #apiKey .~ Just (ApiKeyEnvChain [])+ renamed = model & #modelId .~ "renamed-generation"+ registry <- newProviderRegistryFrom [claudeMessagesProvider & #stream .~ produce & #complete .~ streamingComplete produce]+ let restricted = [(m, textTail) | m <- fableModels <> [renamed]] <> [(model, addMessage emptyAssistant textTail), (model, toolTail), (model, signedTail)]+ cases = [(m, ctx, opts) | (m, ctx) <- restricted] <> [(anthropic_claude_haiku_4_5, textTail, opts & #thinking .~ Just ThinkingLow)]+ forM_ cases $ \(selected, ctx, configured) -> do+ events <- Stream.toList (streamRequestWith registry selected ctx configured)+ assertErrorContract events+ streamed <- streamingComplete (\_ _ _ -> Stream.fromList events) selected ctx configured+ completed <- completeRequestWith registry selected ctx configured+ forM_ [streamed, completed] $ \response -> do+ fmap (.category) (responseError response) @?= Just InvalidRequest+ assertBool "names the prefill and corrections" $+ maybe False (\err -> all (\hint -> hint `T.isInfixOf` err.message) ["assistant prefill", "user turn", "system prompt", "matching tool result"]) (responseError response)+ readIORef sent >>= (@?= 0),+ testCase "only the final mapped role matters" $ do+ afterTool <- appendToolResult context toolResponse (\_ -> pure (toolResultText "found"))+ forM_ [(addMessage emptyAssistant context, ["user"]), (addUser "Continue" textTail, ["user", "assistant", "user"]), (afterTool, ["user", "assistant", "user"])] $ \(ctx, expected) -> do+ raw <- mapped model ctx options+ V.toList (V.map (field "role") (messages raw)) @?= map (Just . String) expected,+ testCase "4.5 prefills are allowed with omitted, disabled or dropped thinking" $ do+ let haiku = anthropic_claude_haiku_4_5+ check selected opts thinking = do+ raw <- mapped selected textTail opts+ (field "thinking" raw >>= field "type") @?= thinking+ (messages raw V.!? 1 >>= field "role") @?= Just (String "assistant")+ check haiku options Nothing+ check haiku (options & #thinking .~ Just ThinkingNone) (Just (String "disabled"))+ check (haiku & #maxOutputTokens .~ 1024) (options & #maxTokens .~ Just 1024 & #thinking .~ Just ThinkingLow) Nothing,+ testCase "legacy serialized compat and auto detection preserve prefill pass-through" $ do+ let raw = case Aeson.toJSON defaultAnthropicMessagesCompat of+ Object o -> Object (KM.delete "assistantPrefillPolicy" o)+ value -> value+ case Aeson.fromJSON raw of+ Aeson.Error err -> assertFailure err+ Aeson.Success compat -> do+ compat.assistantPrefillPolicy @?= Nothing+ forM_ [CompatAnthropicMessages compat, CompatNone] $ \compatSetting -> do+ body <- mapped (model & #compat .~ compatSetting) textTail options+ (messages body V.!? 1 >>= field "role") @?= Just (String "assistant")+ ]+ where+ emptyAssistant = assistant ""+ textTail = addMessage (assistant "The answer is") context+ signedTail = addMessage (AssistantMessage (emptyResponse.message & #content .~ V.singleton signedBlock)) context+ signedBlock = AssistantThinking (emptyThinkingContent & #signature .~ Just "sig-one")+ toolResponse =+ emptyResponse+ & #message . #content .~ V.singleton (AssistantToolCall (ToolCall "toolu_1" "lookup" (object [])))+ & #message . #stopReason .~ ToolUse+ toolTail = addMessage (AssistantMessage toolResponse.message) context+ mapped selected ctx opts = either (\err -> assertFailure (T.unpack err) >> fail "mapRequest") (pure . Aeson.toJSON . fst) (R.mapRequest selected ctx opts)++legacySamplingVersion :: TestTree+legacySamplingVersion = testCase "the explicit current API version rejects sampling before dispatch" $ do+ captured <- newIORef ([] :: [(Maybe ByteString, Value)])+ let app request respond = do+ body <- Wai.strictRequestBody request >>= either fail pure . Aeson.eitherDecode+ let version = lookup "anthropic-version" (Wai.requestHeaders request)+ atomicModifyIORef' captured (\prior -> (prior <> [(version, body)], ()))+ respond (Wai.responseLBS status200 [("Content-Type", "text/event-stream")] (foldMap (\frame -> "data: " <> Aeson.encode frame <> "\n\n") finalTurn))+ testWithApplication (pure app) $ \port -> do+ let selected = anthropic_claude_sonnet_4_6 & #baseUrl .~ ("http://127.0.0.1:" <> T.pack (show port))+ configured = options & #temperature .~ Just 0.2+ current = configured & #headers .~ Map.singleton "anthropic-version" "2026-10-21"+ regularContext = systemUser "Policy" "Hello"+ registry <- newProviderRegistryFrom [claudeMessagesProvider]+ legacy <- completeRequestWith registry selected regularContext configured+ responseError legacy @?= Nothing+ rejected <- completeRequestWith registry selected regularContext current+ fmap (.category) (responseError rejected) @?= Just InvalidRequest+ assertBool "migration error names sampling" (maybe False (T.isInfixOf "sampling" . (.message)) (responseError rejected))+ readIORef captured >>= \case+ [(Just "2023-06-01", body)] -> field "temperature" body @?= Just (Number 0.2)+ _ -> assertFailure "only the legacy call should dispatch"++candidateCompleteAndStream :: TestTree+candidateCompleteAndStream = testCase "candidate HTTP complete and stream agree on the same transcript" $ do+ requests <- newIORef ([] :: [Value])+ let app req respond = do+ body <- Wai.strictRequestBody req >>= either fail pure . Aeson.eitherDecode+ atomicModifyIORef' requests (\previous -> (previous <> [body], ()))+ respond+ ( Wai.responseLBS+ status200+ [("Content-Type", "text/event-stream"), ("request-id", "req_compare")]+ (foldMap (\frame -> "data: " <> Aeson.encode frame <> "\n\n") finalTurn)+ )+ testWithApplication (pure app) $ \port -> do+ registry <- newProviderRegistryFrom [claudeMessagesProvider]+ let selected = model & #baseUrl .~ ("http://127.0.0.1:" <> T.pack (show port))+ configured = options & #apiKey .~ Just (ApiKeyLiteral "candidate-comparison-key")+ complete <- completeRequestWith registry selected context configured+ events <- Stream.toList (claudeMessagesStream selected context configured)+ streamed <- streamingComplete (\_ _ _ -> Stream.fromList events) selected context configured+ let expected = V.singleton (AssistantText (TextContent "done"))+ map (\reply -> reply ^. #message . #content) [complete, streamed] @?= [expected, expected]+ map responseError [complete, streamed] @?= [Nothing, Nothing]+ readIORef requests >>= \case+ [complete, streamed] -> complete @?= streamed+ received -> assertFailure ("expected two dispatches, got " <> show (length received))+ model :: Model model = anthropic_claude_fable_5_1 +fableModels :: [Model]+fableModels = [model, anthropic_claude_fable_5_2]+ -- | The one request plan 91 sends live to settle whether Haiku 5.5 accepts -- a forced tool choice alongside baikai's explicit adaptive thinking. The -- same JSON is saved as docs/validation/plan-91/forced-tool-choice-request.json.@@ -175,14 +358,18 @@ context :: Context context = systemUser "unchanged system" "look twice" & #tools .~ V.singleton (mkTool "lookup" "lookup" (object ["type" .= ("object" :: Text)])) -send :: [Value] -> (Either BaikaiError C.MessageStreamEvent -> IO ()) -> IO ()-send frames emit = forM_ frames $ \raw -> case Aeson.fromJSON raw of- Aeson.Error err -> assertFailure err- Aeson.Success ev -> emit (Right ev)+send :: [Value] -> (Either BaikaiError C.StreamPayload -> IO ()) -> IO ()+send frames emit = forM_ frames $ \raw -> case C.decodeStreamEvent raw of+ Left err -> assertFailure err+ Right (Left _) -> assertFailure "expected a successful stream event"+ Right (Right ev) -> emit (Right (C.eventPayload ev)) start :: Value-start = object ["type" .= ("message_start" :: Text), "message" .= object ["id" .= ("msg" :: Text), "type" .= ("message" :: Text), "role" .= ("assistant" :: Text), "model" .= ("claude-fable-5-1" :: Text), "content" .= ([] :: [Value]), "usage" .= object ["input_tokens" .= (5 :: Int), "output_tokens" .= (0 :: Int)]]]+start = startFor model +startFor :: Model -> Value+startFor selected = object ["type" .= ("message_start" :: Text), "message" .= object ["id" .= ("msg" :: Text), "type" .= ("message" :: Text), "role" .= ("assistant" :: Text), "model" .= selected.modelId, "content" .= ([] :: [Value]), "usage" .= object ["input_tokens" .= (5 :: Int), "output_tokens" .= (0 :: Int)]]]+ block :: Int -> Value -> Value block n b = object ["type" .= ("content_block_start" :: Text), "index" .= n, "content_block" .= b] @@ -202,8 +389,11 @@ toolItem ident = object ["type" .= ("tool_use" :: Text), "id" .= ident, "name" .= ("lookup" :: Text), "input" .= object []] toolTurn :: Text -> Text -> Text -> Bool -> [Value]-toolTurn text sig ident redacted =- [start, block 0 (signed "" "")]+toolTurn = toolTurnFor model++toolTurnFor :: Model -> Text -> Text -> Text -> Bool -> [Value]+toolTurnFor selected text sig ident redacted =+ [startFor selected, block 0 (signed "" "")] <> (if T.null text then [] else [object ["type" .= ("content_block_delta" :: Text), "index" .= (0 :: Int), "delta" .= object ["type" .= ("thinking_delta" :: Text), "thinking" .= text]]]) <> [object ["type" .= ("content_block_delta" :: Text), "index" .= (0 :: Int), "delta" .= object ["type" .= ("signature_delta" :: Text), "signature" .= sig]], stopBlock 0] <> (if redacted then [block 1 redactedItem, stopBlock 1] else [])@@ -211,8 +401,15 @@ <> end "tool_use" finalTurn :: [Value]-finalTurn = [start, block 0 (object ["type" .= ("text" :: Text), "text" .= ("" :: Text)]), object ["type" .= ("content_block_delta" :: Text), "index" .= (0 :: Int), "delta" .= object ["type" .= ("text_delta" :: Text), "text" .= ("done" :: Text)]], stopBlock 0] <> end "end_turn"+finalTurn = textTurn model ["done"] +textTurn :: Model -> [Text] -> [Value]+textTurn selected deltas =+ [startFor selected, block 0 (object ["type" .= String "text", "text" .= String ""])]+ <> [object ["type" .= String "content_block_delta", "index" .= (0 :: Int), "delta" .= object ["type" .= String "text_delta", "text" .= delta]] | delta <- deltas]+ <> [stopBlock 0]+ <> end "end_turn"+ field :: Key -> Value -> Maybe Value field k (Object o) = KM.lookup k o field _ _ = Nothing@@ -263,7 +460,8 @@ let actual = [t | AssistantThinking t <- V.toList (response ^. #message . #content)] length actual @?= length blocks -- Encrypted payloads and signed empty blocks remain usable history.- (req, _) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest model (emptyContext & #messages .~ V.singleton (AssistantMessage (response ^. #message))) summaryOptions)+ let history = addUser "Continue" (contextOf [AssistantMessage (response ^. #message)])+ (req, _) <- either (\e -> assertFailure (T.unpack e) >> fail "map") pure (R.mapRequest model history summaryOptions) contentAt 0 (messages (Aeson.toJSON req)) @?= V.fromList blocks, testCase "one visible block among empty and redacted blocks is a readable summary" $ do response <- completeFrames (blocksTurn [signed "" "empty", redactedItem, signed "visible" "visible-signature"]) summaryOptions
test/LifecycleSpec.hs view
@@ -14,6 +14,7 @@ import Baikai import Baikai.Models.Generated (anthropic_claude_haiku_4_5)+import Baikai.Provider.Claude.Api (claudeMessagesStream) import Baikai.Provider.Claude.Internal.Stream (SseDriver, claudeMessagesStreamWith) import Baikai.Provider.Claude.Sse (sseFromResponse) import Baikai.Provider.Internal.StreamWorker (frameQueueCapacity)@@ -25,9 +26,13 @@ import Data.CaseInsensitive qualified as CI import Data.Generics.Labels () import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)+import Data.Text qualified as Text+import GHC.Conc (BlockReason (BlockedOnSTM), ThreadStatus (ThreadBlocked), threadStatus) import Network.HTTP.Client.Internal qualified as HTTP-import Network.HTTP.Types.Status (mkStatus)+import Network.HTTP.Types.Status (mkStatus, status200) import Network.HTTP.Types.Version (http11)+import Network.Wai qualified as Wai+import Network.Wai.Handler.Warp (testWithApplication) import Streamly.Data.Stream qualified as Stream import System.Mem (performMajorGC) import System.Timeout (timeout)@@ -41,8 +46,48 @@ [ boundedReadTest, abandonedReleasesAfterGcTest, cancellationReleasesWithoutGcTest,- workerDeathCannotStrandTest+ workerDeathCannotStrandTest,+ candidateCancellation ]++candidateCancellation :: TestTree+candidateCancellation = testCase "candidate HTTP cancellation closes the actual socket" $ do+ closed <- newEmptyMVar+ ready <- newEmptyMVar+ done <- newEmptyMVar+ count <- newIORef (0 :: Int)+ let app request respond = do+ _ <- Wai.strictRequestBody request+ atomicModifyIORef' count (\n -> (n + 1, ()))+ respond $+ Wai.responseRaw+ ( \recv send -> do+ send ("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n" <> frameAt 0 <> frameAt 1 <> frameAt 2)+ recv >>= putMVar closed+ )+ (Wai.responseLBS status200 [] "")+ testWithApplication (pure app) $ \port -> do+ let fixtureModel = testModel & #baseUrl .~ ("http://127.0.0.1:" <> Text.pack (show port))+ signal event = do+ case event of+ TextDelta _ -> putMVar ready ()+ _ -> pure ()+ pure event+ run = Stream.toList (Stream.mapM signal (claudeMessagesStream fixtureModel (systemUser "System" "Prompt") testOptions))+ bracket (forkIO (try run >>= putMVar done)) (\tid -> throwTo tid ThreadKilled) $ \tid -> do+ timeout 5_000_000 (takeMVar ready) >>= (@?= Just ())+ let awaitDrain =+ threadStatus tid >>= \case+ ThreadBlocked BlockedOnSTM -> pure ()+ _ -> threadDelay 1000 >> awaitDrain+ timeout 5_000_000 awaitDrain >>= (@?= Just ())+ throwTo tid ThreadKilled+ result <- timeout 2_000_000 (takeMVar done)+ case result of+ Just (Left err) | Just ThreadKilled <- fromException (err :: SomeException) -> pure ()+ _ -> assertFailure "expected asynchronous cancellation"+ timeout 5_000_000 (takeMVar closed) >>= (@?= Just "")+ readIORef count >>= (@?= 1) -- | The bound alone stops the socket read: no garbage collection and no -- timer is involved. Before the frame queue the counter grew without
test/Main.hs view
@@ -18,7 +18,7 @@ import Baikai.Provider.Claude.Cli qualified as ClaudeCli import Baikai.Provider.Claude.Interactive import Baikai.Provider.Claude.Internal.Request (describeThinkingFor, mapRequest)-import Claude.V1.Messages qualified as Messages+import Claude.Messages qualified as Messages import CliCancellationSpec qualified import CliEvidenceSpec qualified import Contract (assertErrorContract)@@ -96,8 +96,8 @@ -- | A 'JsonSchema' on 'Options.responseFormat' maps onto Anthropic's -- native @output_config@, forwarding the schema 'Value' verbatim via--- 'Messages.jsonSchemaConfig'. Pure: 'mapRequest' is--- 'Either Text (Messages.CreateMessage, ThinkingTranslation)'.+-- 'Messages.OutputConfig'. Pure: 'mapRequest' is+-- 'Either Text (Messages.MessageRequest, ThinkingTranslation)'. responseFormatMappingTest :: TestTree responseFormatMappingTest = testCase "responseFormat JsonSchema maps onto Anthropic output_config" $ do@@ -125,8 +125,8 @@ case mapRequest model ctx opts of Left e -> assertFailure ("mapRequest failed: " <> Text.unpack e) Right (req, _) ->- req ^. #output_config- @?= Just (Messages.jsonSchemaConfig personSchema)+ req ^. #conversation . #features . #outputConfig+ @?= Just (Messages.OutputConfig Nothing (case personSchema of Aeson.Object schema -> Just schema; _ -> Nothing)) optionsMappingTest :: TestTree optionsMappingTest =@@ -146,8 +146,8 @@ case mapRequest model emptyContext opts of Left e -> assertFailure ("mapRequest failed: " <> Text.unpack e) Right (req, translation) -> do- Messages.top_p req @?= Just 0.9- Messages.stop_sequences req @?= Just (Vector.fromList ["END", "STOP"])+ Messages.topP (Messages.messageRequestControls req) @?= Just 0.9+ req ^. #stopSequences @?= ["END", "STOP"] -- seed, frequencyPenalty and presencePenalty have no Anthropic -- Messages field on any generation. They are dropped, but the -- drop is recorded rather than silent — the whole point of the
test/ShapeSpec.hs view
@@ -232,12 +232,12 @@ fastSpeedTests = testGroup "speed"- [ testCase "a fast-mode request on claude-opus-5 carries speed and the beta header" $ do- let m = Models.anthropic_claude_opus_5- opts = emptyOptions & #speed .~ Just SpeedFast- value <- shapedBody m emptyContext opts- lookupPath ["speed"] value @?= Just (String "fast")- lookup "anthropic-beta" (headers m opts) @?= Just "fast-mode-2026-02-01",+ [ testCase "a fast-mode request on Opus 5 and Fable 5.2 carries speed and the beta header" $+ forM_ [Models.anthropic_claude_opus_5, Models.anthropic_claude_fable_5_2] $ \m -> do+ let opts = emptyOptions & #speed .~ Just SpeedFast+ value <- shapedBody m emptyContext opts+ lookupPath ["speed"] value @?= Just (String "fast")+ lookup "anthropic-beta" (headers m opts) @?= Just "fast-mode-2026-02-01", testCase "a fast-mode request on claude-sonnet-5 omits speed and records the drop" $ do let m = Models.anthropic_claude_sonnet_5 opts = emptyOptions & #speed .~ Just SpeedFast
test/SseSpec.hs view
@@ -2,35 +2,36 @@ import Baikai import Baikai.Http qualified as Http-import Baikai.Models.Generated (anthropic_claude_fable_5_1, anthropic_claude_haiku_4_5, anthropic_claude_opus_5)+import Baikai.Models.Generated (anthropic_claude_fable_5_1, anthropic_claude_fable_5_2, anthropic_claude_haiku_4_5, anthropic_claude_opus_5)+import Baikai.Provider.Claude.Api (claudeMessagesProvider) import Baikai.Provider.Claude.Internal.Stream (Assembler, SseDriver, claudeMessagesStreamWith, emptyAssembler, translate) import Baikai.Provider.Claude.Sse ( ResponseMetadata,- buildRequest, claudeSseStreamValueWithHeaders, sseFromResponse, ) import Baikai.Usage qualified as Usage-import Claude.V1.Messages qualified as Messages+import Claude.Streaming qualified as Messages import Contract (assertErrorContract) import Control.Lens ((&), (.~), (^.)) import Control.Monad (forM_) import Data.Aeson qualified as Aeson import Data.ByteString (ByteString)-import Data.ByteString qualified as SBS import Data.ByteString.Char8 qualified as S8 import Data.ByteString.Lazy qualified as LBS import Data.CaseInsensitive qualified as CI import Data.Generics.Labels ()-import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef) import Data.Set qualified as Set import Data.Text qualified as Text import Data.Time.Clock (UTCTime) import Data.Vector (Vector) import Data.Vector qualified as Vector import Network.HTTP.Client.Internal qualified as HTTP-import Network.HTTP.Types.Status (mkStatus)+import Network.HTTP.Types.Status (mkStatus, status200, status302) import Network.HTTP.Types.Version (http11)+import Network.Wai qualified as Wai+import Network.Wai.Handler.Warp (testWithApplication) import Servant.Client qualified as Client import Streamly.Data.Stream qualified as Stream import Test.Tasty (TestTree, testGroup)@@ -98,7 +99,7 @@ sseFromResponse resp (\md -> modifyIORef' metaRef (<> [md])) (\ev -> modifyIORef' eventsRef (<> [ev])) events <- readIORef eventsRef case events of- [Right Messages.Message_Start {Messages.message = msg}, Right Messages.Message_Stop] ->+ [Right (Messages.MessageStart msg), Right Messages.MessageStop] -> msg ^. #id @?= "msg_1" other -> assertFailure ("expected message_start then message_stop, got: " <> show other), observationTests,@@ -191,6 +192,51 @@ response <- streamingComplete (claudeMessagesStreamWith (replayDriver 200 [] body)) anthropic_claude_opus_5 emptyContext (testOptions & #cacheRetention .~ Just CacheRetentionLong & #speed .~ Just SpeedFast) response ^. #message . #usage . #cost . #usd @?= expected response ^. #message . #usage . #cost . #basis . #estimateReasons @?= reasons,+ testCase "Fable 5.2 prices shaped cache writes and requires observed fast speed" $+ forM_ [(CacheRetentionShort, 1 / 100), (CacheRetentionLong, 2 / 125)] $ \(duration, standard) ->+ forM_ [(Just "standard", standard, Set.empty), (Just "fast", standard * 2, Set.empty), (Nothing, standard, Set.singleton SpeedNotReported)] $ \(observed, expected, reasons) -> do+ let usage = "{\"input_tokens\":0,\"output_tokens\":0,\"cache_read_input_tokens\":0,\"cache_creation_input_tokens\":1000,\"service_tier\":\"standard\"" <> maybe "" (\v -> ",\"speed\":\"" <> v <> "\"") observed <> "}"+ body = fable52UsageBody usage 0+ opts = testOptions & #cacheRetention .~ Just duration & #speed .~ Just SpeedFast+ registry <- fable52Registry body+ response <- completeRequestWith registry anthropic_claude_fable_5_2 (contextOf [user "Reply briefly."]) opts+ responseError response @?= Nothing+ let billed = response ^. #message . #usage+ billed ^. #cost . #usd @?= expected+ billed ^. #cost . #basis . #estimateReasons @?= reasons+ billed ^. #cacheReadTokens @?= 0+ fmap Usage.missingCategories (billed ^. #availability) @?= Just Set.empty,+ testCase "Fable 5.2 bills fresh input separately from reads and writes and preserves missing counters" $ do+ let body cacheRead = fable52UsageBody ("{\"input_tokens\":10,\"output_tokens\":0,\"cache_creation_input_tokens\":30,\"service_tier\":\"standard\"" <> cacheRead <> "}") 100+ forM_ [("", 0, Set.singleton Usage.CacheReadUsage, Set.singleton CacheReadUsageNotReported), (",\"cache_read_input_tokens\":0", 0, Set.empty, Set.empty), (",\"cache_read_input_tokens\":20", 20, Set.empty, Set.empty)] $ \(cacheRead, readTokens, missing, reasons) -> do+ registry <- fable52Registry (body cacheRead)+ response <- completeRequestWith registry anthropic_claude_fable_5_2 (contextOf [user "Reply briefly."]) (testOptions & #cacheRetention .~ Just CacheRetentionShort & #evidence .~ Just (evidenceRequest "fable52-usage"))+ responseError response @?= Nothing+ let billed = response ^. #message . #usage+ billed ^. #inputTokens @?= 10+ billed ^. #cacheReadTokens @?= readTokens+ billed ^. #cacheWriteTokens @?= 30+ billed ^. #outputTokens @?= 100+ billed ^. #totalTokens @?= 140 + readTokens+ fmap Usage.missingCategories (billed ^. #availability) @?= Just missing+ billed ^. #cost . #basis . #estimateReasons @?= reasons+ fmap (\e -> e ^. #usage) (response ^. #evidence) @?= Just (Observed billed),+ testCase "Fable 5.2 thinking alone can exhaust max_tokens" $ do+ registry <- fable52Registry fable52LengthBody+ response <- completeRequestWith registry anthropic_claude_fable_5_2 (contextOf [user "Reply briefly."]) testOptions+ responseError response @?= Nothing+ response ^. #message . #stopReason @?= Length+ case Vector.toList (flattenAssistantBlocks response) of+ [AssistantThinking thinking] -> thinking ^. #signature @?= Just "sig-length"+ _ -> assertFailure "expected only signed thinking",+ testCase "Fable 5.2 never dispatches the tool call truncated by max_tokens" $ do+ registry <- fable52Registry (fable52Start "{\"input_tokens\":4,\"output_tokens\":0}" : drop 1 cutOffToolBody)+ let ctx = contextOf [user "Search."] & #tools .~ Vector.singleton (mkTool "search" "Search" (Aeson.object []))+ dispatch _ = assertFailure "truncated arguments reached the dispatcher"+ (history, response) <- runToolLoopWith registry 4 dispatch anthropic_claude_fable_5_2 ctx testOptions+ responseError response @?= Nothing+ response ^. #message . #stopReason @?= Length+ history ^. #messages @?= ctx ^. #messages, testCase "Fable cache writes use the shaped duration including compatibility downgrades" $ do let fable = anthropic_claude_fable_5_1 downgraded = fable & #compat .~ CompatAnthropicMessages (anthropicMessagesCompatFor fable & #supportsLongCacheRetention .~ False)@@ -224,27 +270,21 @@ isRetryable be @?= False other -> assertFailure ("expected a terminal EventError, got: " <> show (take 1 other)), refusalDetailTests,- testCase "a mid-stream transport error closes open blocks before the terminal" $ do- -- The failure is injected through 'translate' rather than the- -- transport, because what is under test is the assembler's- -- Left path: a classified error arriving with a text block open.- (openEvents, ass) <- replayTranslate openTextBody- let (failEvents, _) = translate (Left (providerUnavailable "connection reset mid-stream")) ass testTime- assertBool- ("expected a text block to be open, got: " <> show openEvents)- (not (null [() | TextStart {} <- openEvents]))- case failEvents of- [TextEnd BlockEndPayload {contentIndex = 0, content = body}, EventError TerminalPayload {message = msg}] -> do+ testCase "early EOF closes open blocks before the terminal" $ do+ (events, _) <- replayTranslate openTextBody+ assertBool "the partial transcript opened a text block" (not (null [() | TextStart {} <- events]))+ case reverse events of+ EventError TerminalPayload {message = msg} : TextEnd BlockEndPayload {contentIndex = 0, content = body} : _ -> do body @?= "partial" [t | AssistantText (TextContent t) <- Vector.toList (messageBlocks msg)] @?= ["partial"]- other -> assertFailure ("expected TextEnd then EventError, got: " <> show other),+ other -> assertFailure ("expected TextEnd then EventError, got: " <> show (take 2 other)), testCase "an unknown event type is skipped without ending the stream" $ do events <- transportEvents 200- [ frameOf "{\"type\":\"message_stop\"}",- frameOf "{\"type\":\"message_checkpoint\",\"checkpoint\":\"abc\"}",- frameOf "{\"type\":\"ping\"}"+ [ frameOf "{\"type\":\"message_checkpoint\",\"checkpoint\":\"abc\"}",+ frameOf "{\"type\":\"ping\"}",+ frameOf "{\"type\":\"message_stop\"}" ] assertAllRight events length events @?= 2,@@ -252,9 +292,9 @@ events <- transportEvents 200- [ frameOf "{\"type\":\"message_stop\"}",- frameOf "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"citations_delta\",\"citation\":{}}}",- frameOf "{\"type\":\"ping\"}"+ [ frameOf "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"future_delta\"}}",+ frameOf "{\"type\":\"ping\"}",+ frameOf "{\"type\":\"message_stop\"}" ] assertAllRight events length events @?= 2,@@ -264,6 +304,32 @@ length events @?= 1 ] +fable52Registry :: [ByteString] -> IO ProviderRegistry+fable52Registry body =+ let produce = claudeMessagesStreamWith (replayDriver 200 [] body)+ in newProviderRegistryFrom [claudeMessagesProvider & #stream .~ produce & #complete .~ streamingComplete produce]++fable52Start :: ByteString -> ByteString+fable52Start usage =+ frameOf ("{\"type\":\"message_start\",\"message\":{\"id\":\"msg_fable52\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-fable-5-2\",\"usage\":" <> usage <> "}}")++fable52UsageBody :: ByteString -> Int -> [ByteString]+fable52UsageBody usage outputTokens =+ [ fable52Start usage,+ frameOf ("{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":" <> S8.pack (show outputTokens) <> "}}"),+ frameOf "{\"type\":\"message_stop\"}"+ ]++fable52LengthBody :: [ByteString]+fable52LengthBody =+ [ fable52Start "{\"input_tokens\":5,\"output_tokens\":0}",+ frameOf "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\",\"signature\":\"\"}}",+ frameOf "{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"sig-length\"}}",+ frameOf "{\"type\":\"content_block_stop\",\"index\":0}",+ frameOf "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"max_tokens\"},\"usage\":{\"output_tokens\":9}}",+ frameOf "{\"type\":\"message_stop\"}"+ ]+ -- | A stream that opens a tool call, streams half its arguments, and is -- cut off by the output cap. cutOffToolBody :: [ByteString]@@ -304,14 +370,14 @@ -- | The raw events the transport produced, with no assembler involved. transportEvents ::- Int -> [ByteString] -> IO [Either BaikaiError Messages.MessageStreamEvent]+ Int -> [ByteString] -> IO [Either BaikaiError Messages.StreamPayload] transportEvents status chunks = do eventsRef <- newIORef [] resp <- mkResponse status [] chunks sseFromResponse resp (const (pure ())) (\ev -> modifyIORef' eventsRef (<> [ev])) readIORef eventsRef -assertAllRight :: [Either BaikaiError Messages.MessageStreamEvent] -> Assertion+assertAllRight :: [Either BaikaiError Messages.StreamPayload] -> Assertion assertAllRight events = case [e | Left e <- events] of [] -> pure ()@@ -489,100 +555,46 @@ -- What goes on the wire -- -------------------------------------------------------------------- --- | The composed path and the redirect policy, asserted on the pure--- request rather than by opening a connection.------ The path cases are the base-URL convention: `Model.baseUrl` is the API--- root, baikai appends `/v1/messages` itself, and a trailing--- `/v1` is removed rather than doubled — which is why--- `https://api.deepseek.com/v1`, the spelling every OpenAI SDK teaches,--- does not request `/v1/v1/...`. requestShapeTests :: TestTree requestShapeTests =- testGroup- "the request this transport sends"- [ testCase "one version segment, whatever spelling the base URL used"- $ forM_- [ ("https://api.anthropic.com/v1", "/v1/messages"),- ("https://api.anthropic.com", "/v1/messages"),- ("https://gateway.test/anthropic", "/anthropic/v1/messages"),- ("https://gateway.test/anthropic/v1/", "/anthropic/v1/messages")- ]- $ \(url, expected) -> case Http.canonicalBaseUrl url of- Left problem -> assertFailure (Text.unpack (url <> " was refused: " <> problem))- Right base -> do- let request = buildRequest base [] (Aeson.object [])- (url, HTTP.path request) @?= (url, S8.pack expected),- testCase "the request never follows a redirect" $- case Http.canonicalBaseUrl "https://h.test" of- Left problem -> assertFailure (Text.unpack problem)- Right base -> do- let request = buildRequest base [] (Aeson.object [])- HTTP.redirectCount request @?= 0- HTTP.method request @?= "POST"- ]---- ----------------------------------------------------------------------- A 3xx is an error, not a hop--- --------------------------------------------------------------------+ testCase "the live POST uses one version segment across base URL spellings" $ do+ attempts <- newIORef []+ let app request respond = do+ modifyIORef' attempts (<> [(Wai.requestMethod request, Wai.rawPathInfo request)])+ respond (Wai.responseLBS status200 [("Content-Type", "text/event-stream")] "data: {\"type\":\"message_stop\"}\n\n")+ testWithApplication (pure app) $ \port -> do+ let local = "http://127.0.0.1:" <> Text.pack (show port)+ forM_ ["", "/v1", "/gateway", "/gateway/v1/"] $ \suffix -> do+ base <- either (fail . Text.unpack) pure (Http.canonicalBaseUrl (local <> suffix))+ events <- captureLiveFrames base+ assertAllRight events+ readIORef attempts >>= (@?= [("POST", "/v1/messages"), ("POST", "/v1/messages"), ("POST", "/gateway/v1/messages"), ("POST", "/gateway/v1/messages")]) --- | A 302 is delivered as the terminal error and no second connection is--- ever opened.------ @http-client@'s default is to follow up to ten redirects with every--- header intact, so before `redirectCount = 0` this test recorded a--- second connection — to whatever host the `Location` header named —--- carrying the caller's bearer token.------ The "server" is an in-process fake built from `managerRawConnection`,--- which is what lets the case observe /which hosts a connection was--- opened to/ directly, with no socket and no port. redirectTests :: TestTree redirectTests =- testGroup- "redirects"- [ testCase "a 302 is the terminal error and no second host is contacted" $ do- attemptsRef <- newIORef []- manager <- fakeRedirectingManager attemptsRef- case Http.canonicalBaseUrl "http://proxy.test" of- Left problem -> assertFailure (Text.unpack problem)- Right base -> do- let env = Client.mkClientEnv manager base- eventsRef <- newIORef []- metaRef <- newIORef []- claudeSseStreamValueWithHeaders- env- [("Authorization", "Bearer sk-test")]- (Aeson.object [])- (\md -> modifyIORef' metaRef (<> [md]))- (\ev -> modifyIORef' eventsRef (<> [ev]))- attempts <- readIORef attemptsRef- attempts @?= [("proxy.test", 80)]- events <- readIORef eventsRef- case events of- [Left e] -> httpStatus e @?= Just 302- other -> assertFailure ("expected one 302 error, got: " <> show other)- ]+ testCase "a 302 terminates without a second request" $ do+ attempts <- newIORef []+ let app request respond = do+ modifyIORef' attempts (<> [Wai.rawPathInfo request])+ respond (Wai.responseLBS status302 [("Location", "/redirect-target")] "")+ testWithApplication (pure app) $ \port -> do+ events <- captureLiveFrames (Client.BaseUrl Client.Http "127.0.0.1" port "")+ case events of+ [Left e] -> httpStatus e @?= Just 302+ other -> assertFailure ("expected one 302 error, got: " <> show other)+ readIORef attempts >>= (@?= ["/v1/messages"]) --- | A manager whose every connection answers one 302 pointing at another--- host, and records the host and port it was opened to.-fakeRedirectingManager :: IORef [(String, Int)] -> IO HTTP.Manager-fakeRedirectingManager attemptsRef =- HTTP.newManager- HTTP.defaultManagerSettings- { HTTP.managerRawConnection = pure open- }- where- open _ host portNumber = do- modifyIORef' attemptsRef (<> [(host, portNumber)])- remaining <- newIORef [redirectResponse]- HTTP.makeConnection- (atomicModifyIORef' remaining (\chunks -> case chunks of [] -> ([], SBS.empty); (c : cs) -> (cs, c)))- (\_ -> pure ())- (pure ())- redirectResponse =- S8.pack- "HTTP/1.1 302 Found\r\nLocation: http://evil.test/steal\r\nContent-Length: 0\r\n\r\n"+captureLiveFrames :: Client.BaseUrl -> IO [Either BaikaiError Messages.StreamPayload]+captureLiveFrames base = do+ events <- newIORef []+ let body = Aeson.object ["model" Aeson..= ("fixture" :: Text.Text), "max_tokens" Aeson..= (1 :: Int), "messages" Aeson..= ([] :: [Aeson.Value])]+ claudeSseStreamValueWithHeaders+ base+ [("x-api-key", "fixture-key"), ("anthropic-version", "2023-06-01")]+ body+ (const (pure ()))+ (\event -> modifyIORef' events (<> [event]))+ readIORef events refusalDetailTests :: TestTree refusalDetailTests =@@ -613,7 +625,9 @@ EventDone TerminalPayload {errorInfo = Nothing} : _ -> pure () other -> assertFailure (show other), testCase "blocking completion preserves the structured refusal" $ do- response <- streamingComplete (claudeMessagesStreamWith (replayDriver 200 [] (refusalWithDetails (detail (Just "bio") Nothing)))) testModel emptyContext testOptions+ registry <- fable52Registry (fable52Start "{\"input_tokens\":3,\"output_tokens\":0}" : drop 1 (refusalWithDetails (detail (Just "bio") Nothing)))+ response <- completeRequestWith registry anthropic_claude_fable_5_2 (contextOf [user "Reply briefly."]) testOptions+ fmap category (responseError response) @?= Just ContentFiltered fmap (\be -> be ^. #refusalCategory) (response ^. #errorInfo) @?= Just (Just "bio") ] where
test/ThinkingSpec.hs view
@@ -11,15 +11,17 @@ uncappedMaxTokensFloor, ) import Baikai.Provider.Claude.Internal.Stream (Assembler, emptyAssembler, translate)-import Claude.V1.Messages qualified as Messages+import Claude.Messages qualified as Messages+import Claude.Streaming qualified as Messages import Control.Lens ((&), (.~), (^.)) import Data.Aeson qualified as Aeson import Data.Aeson.KeyMap qualified as KeyMap-import Data.ByteString.Lazy qualified as BSL+import Data.Aeson.Types (Pair) import Data.Char qualified as Char import Data.Generics.Labels () import Data.IntMap.Strict qualified as IntMap import Data.List qualified as List+import Data.List.NonEmpty qualified as NonEmpty import Data.Text qualified as Text import Data.Time.Clock (UTCTime) import Data.Vector qualified as Vector@@ -75,6 +77,7 @@ anthropicModels = [ ("claude-fable-5", anthropic_claude_fable_5, AnthropicThinkingAdaptive, False, True, False), ("claude-fable-5-1", anthropic_claude_fable_5_1, AnthropicThinkingAdaptive, False, False, False),+ ("claude-fable-5-2", anthropic_claude_fable_5_2, AnthropicThinkingAdaptive, False, False, True), ("claude-haiku-4-5", anthropic_claude_haiku_4_5, AnthropicThinkingBudget, True, True, False), ("claude-haiku-5-5", anthropic_claude_haiku_5_5, AnthropicThinkingAdaptive, False, True, False), ("claude-opus-4-5", anthropic_claude_opus_4_5, AnthropicThinkingBudget, True, True, False),@@ -103,7 +106,7 @@ neverExceedsCapTests = [ testCase (name <> " " <> levelName <> " stays within catalog cap") $ do req <- requestFor model (emptyOptions & #thinking .~ Just level)- req ^. #max_tokens <= model ^. #maxOutputTokens+ requestMaxTokens req <= model ^. #maxOutputTokens @?= True | (name, model, _, _, _, _) <- anthropicModels, (levelName, level) <- thinkingLevels@@ -117,14 +120,14 @@ AnthropicThinkingBudget -> do let expectedBudget = thinkingTokenBudget level requestThinking req- @?= Just Messages.ThinkingEnabled {Messages.budget_tokens = expectedBudget}+ @?= Just (Messages.ManualBudget (expectedBudget) Nothing) assertBool "max_tokens leaves visible-output room beyond budget"- (req ^. #max_tokens > expectedBudget)+ (requestMaxTokens req > expectedBudget) AnthropicThinkingAdaptive -> do- requestThinking req @?= Just (Messages.ThinkingAdaptiveWithDisplay Messages.ThinkingSummarized)- req ^. #max_tokens @?= model ^. #maxOutputTokens- (req ^. #output_config >>= Messages.effort)+ requestThinking req @?= Just (Messages.Adaptive (Just Messages.Summarized))+ requestMaxTokens req @?= model ^. #maxOutputTokens+ (requestOutputConfig req >>= Messages.effort >>= encodedEffort) @?= adaptiveEffort level | (name, model, style, _, _, _) <- anthropicModels, (levelName, level) <- thinkingLevels@@ -216,7 +219,7 @@ opts = emptyOptions & #thinking .~ Just ThinkingMinimal req <- requestFor model opts requestThinking req @?= Nothing- req ^. #max_tokens @?= 1000+ requestMaxTokens req @?= 1000 t <- translationFor model opts t ^. #requested @?= Just ThinkingMinimal t ^. #mode @?= ThinkingModeUnsupported@@ -236,8 +239,8 @@ requestFor anthropic_claude_opus_4_7 (emptyOptions & #thinking .~ Just level)- requestThinking req @?= Just (Messages.ThinkingAdaptiveWithDisplay Messages.ThinkingSummarized)- (req ^. #output_config >>= Messages.effort) @?= Just expected+ requestThinking req @?= Just (Messages.Adaptive (Just Messages.Summarized))+ (requestOutputConfig req >>= Messages.effort >>= encodedEffort) @?= Just expected | (name, level, expected) <- [ ("xhigh is preserved", ThinkingXHigh, "xhigh"), ("max is preserved", ThinkingMax, "max")@@ -256,8 +259,8 @@ anthropic_claude_opus_5_5 emptyContext (emptyOptions & #thinking .~ Just ThinkingHigh)- requestThinking req @?= Just (Messages.ThinkingAdaptiveWithDisplay Messages.ThinkingSummarized)- (req ^. #output_config >>= Messages.effort) @?= Just "high"+ requestThinking req @?= Just (Messages.Adaptive (Just Messages.Summarized))+ (requestOutputConfig req >>= Messages.effort >>= encodedEffort) @?= Just "high" t ^. #mode @?= ThinkingModeAdaptive t ^. #effortText @?= Just "high" t ^. #adjustments @?= []@@ -275,10 +278,10 @@ anthropic_claude_haiku_4_5 (emptyOptions & #thinking .~ Just ThinkingMax) requestThinking req- @?= Just Messages.ThinkingEnabled {Messages.budget_tokens = 32768}+ @?= Just (Messages.ManualBudget (32768) Nothing) assertBool "max_tokens leaves visible-output room beyond the max thinking budget"- (req ^. #max_tokens > 32768)+ (requestMaxTokens req > 32768) explicitMaxTokensTest :: TestTree explicitMaxTokensTest =@@ -290,8 +293,8 @@ budget = thinkingTokenBudget ThinkingHigh req <- requestFor anthropic_claude_haiku_4_5 opts requestThinking req- @?= Just Messages.ThinkingEnabled {Messages.budget_tokens = budget}- req ^. #max_tokens @?= anthropic_claude_haiku_4_5 ^. #maxOutputTokens+ @?= Just (Messages.ManualBudget (budget) Nothing)+ requestMaxTokens req @?= anthropic_claude_haiku_4_5 ^. #maxOutputTokens handRolledUnclampedTest :: TestTree handRolledUnclampedTest =@@ -309,7 +312,7 @@ & #maxTokens .~ Just 100 expected = 100 + thinkingTokenBudget ThinkingLow req <- requestFor model opts- req ^. #max_tokens @?= expected+ requestMaxTokens req @?= expected tooSmallCapDropsThinkingTest :: TestTree tooSmallCapDropsThinkingTest =@@ -320,7 +323,7 @@ opts = emptyOptions & #thinking .~ Just ThinkingMinimal req <- requestFor model opts requestThinking req @?= Nothing- req ^. #max_tokens @?= 1000+ requestMaxTokens req @?= 1000 mergedOutputConfigTest :: TestTree mergedOutputConfigTest =@@ -333,10 +336,10 @@ & #thinking .~ Just level & #responseFormat .~ Just (JsonSchema (jsonSchemaFormat "answer" schema) {strict = True})- expected = (Messages.jsonSchemaConfig schema) {Messages.effort = Just word}+ expected = Messages.OutputConfig (Just (Messages.VersionedEffort word)) (asObject schema) req <- requestFor model opts- requestThinking req @?= Just (Messages.ThinkingAdaptiveWithDisplay Messages.ThinkingSummarized)- req ^. #output_config @?= Just expected+ requestThinking req @?= Just (Messages.Adaptive (Just Messages.Summarized))+ requestOutputConfig req @?= Just expected | (model, level, word) <- [ (anthropic_claude_opus_4_6, ThinkingMedium, "medium"), (anthropic_claude_opus_5_5, ThinkingHigh, "high")@@ -355,8 +358,8 @@ & #compat .~ CompatAnthropicMessages compat opts = emptyOptions & #thinking .~ Just ThinkingLow req <- requestFor model opts- requestThinking req @?= Just (Messages.ThinkingAdaptiveWithDisplay Messages.ThinkingSummarized)- (req ^. #output_config >>= Messages.effort) @?= Just "low"+ requestThinking req @?= Just (Messages.Adaptive (Just Messages.Summarized))+ (requestOutputConfig req >>= Messages.effort >>= encodedEffort) @?= Just "low" -- | 'ThinkingNone' against every catalog model, and the wire bytes it -- and the settings it sits beside produce.@@ -375,8 +378,8 @@ if anthropicMessagesCompatFor model ^. #supportsThinkingDisabled then do requestThinking req @?= Just Messages.ThinkingDisabled- (req ^. #output_config >>= Messages.effort) @?= Nothing- req ^. #max_tokens @?= model ^. #maxOutputTokens+ (requestOutputConfig req >>= Messages.effort >>= encodedEffort) @?= Nothing+ requestMaxTokens req @?= model ^. #maxOutputTokens t ^. #mode @?= ThinkingModeToggle t ^. #wireField @?= Just "thinking" t ^. #effortText @?= Nothing@@ -385,8 +388,8 @@ else do -- Anthropic rejects "disabled" here, so the least thinking -- the model can be asked for is adaptive at low effort.- requestThinking req @?= Just (Messages.ThinkingAdaptiveWithDisplay Messages.ThinkingSummarized)- (req ^. #output_config >>= Messages.effort) @?= Just "low"+ requestThinking req @?= Just (Messages.Adaptive (Just Messages.Summarized))+ (requestOutputConfig req >>= Messages.effort >>= encodedEffort) @?= Just "low" t ^. #mode @?= ThinkingModeAdaptive t ^. #adjustments @?= [EffortClamped ThinkingNone "low"] | (name, model, _, _, _, _) <- anthropicModels@@ -421,7 +424,7 @@ & #responseFormat .~ Just (JsonSchema (jsonSchemaFormat "answer" schema)) req <- requestFor anthropic_claude_haiku_5_5 opts requestThinking req @?= Just Messages.ThinkingDisabled- req ^. #output_config @?= Just (Messages.jsonSchemaConfig schema),+ requestOutputConfig req @?= Just (Messages.OutputConfig Nothing (asObject schema)), testCase "a budget-style host that rejects disabled omits the field and says so" $ do let model = anthropic_claude_haiku_4_5@@ -429,7 +432,7 @@ opts = emptyOptions & #thinking .~ Just ThinkingNone (req, t) <- mappedFor model emptyContext opts requestThinking req @?= Nothing- req ^. #max_tokens @?= model ^. #maxOutputTokens+ requestMaxTokens req @?= model ^. #maxOutputTokens t ^. #mode @?= ThinkingModeUnsupported t ^. #wireField @?= Nothing t ^. #adjustments @?= [EffortOmitted ThinkingNone],@@ -478,21 +481,36 @@ Aeson.Object o -> pure o other -> assertFailure ("request did not encode as an object: " <> show other) -requestFor :: Model -> Options -> IO Messages.CreateMessage+requestFor :: Model -> Options -> IO Messages.MessageRequest requestFor model opts = fst <$> mappedFor model emptyContext opts translationFor :: Model -> Options -> IO ThinkingTranslation translationFor model opts = snd <$> mappedFor model emptyContext opts mappedFor ::- Model -> Context -> Options -> IO (Messages.CreateMessage, ThinkingTranslation)+ Model -> Context -> Options -> IO (Messages.MessageRequest, ThinkingTranslation) mappedFor model ctx opts = case mapRequest model ctx opts of Left e -> assertFailure ("mapRequest failed: " <> Text.unpack e) Right mapped -> pure mapped -requestThinking :: Messages.CreateMessage -> Maybe Messages.Thinking-requestThinking Messages.CreateMessage {Messages.thinking = t} = t+requestThinking :: Messages.MessageRequest -> Maybe Messages.Thinking+requestThinking request = request ^. #conversation . #features . #thinking +requestMaxTokens :: Messages.MessageRequest -> Natural+requestMaxTokens request = Messages.maxTokensValue (request ^. #outputLimit)++requestOutputConfig :: Messages.MessageRequest -> Maybe Messages.OutputConfig+requestOutputConfig request = request ^. #conversation . #features . #outputConfig++encodedEffort :: Messages.Effort -> Maybe Text.Text+encodedEffort effort = case Aeson.toJSON effort of+ Aeson.String value -> Just value+ _ -> Nothing++asObject :: Aeson.Value -> Maybe Aeson.Object+asObject (Aeson.Object fields) = Just fields+asObject _ = Nothing+ adaptiveEffort :: ThinkingLevel -> Maybe Text.Text adaptiveEffort = \case ThinkingNone -> Just "low"@@ -529,12 +547,12 @@ t <- translationFor model opts if supported then do- Messages.temperature req @?= Just 0.2- Messages.top_p req @?= Just 0.9+ Messages.temperature (Messages.messageRequestControls req) @?= Just 0.2+ Messages.topP (Messages.messageRequestControls req) @?= Just 0.9 filter isSamplingAdjustment (t ^. #adjustments) @?= [] else do- Messages.temperature req @?= Nothing- Messages.top_p req @?= Nothing+ Messages.temperature (Messages.messageRequestControls req) @?= Nothing+ Messages.topP (Messages.messageRequestControls req) @?= Nothing filter isSamplingAdjustment (t ^. #adjustments) @?= [SamplingDroppedUnsupportedModel ["temperature", "top_p"]] | (name, model, _, supported, _, _) <- anthropicModels,@@ -547,7 +565,7 @@ let opts = emptyOptions & #temperature .~ Just 0.2 req <- requestFor anthropic_claude_sonnet_5 opts t <- translationFor anthropic_claude_sonnet_5 opts- Messages.temperature req @?= Nothing+ Messages.temperature (Messages.messageRequestControls req) @?= Nothing t ^. #mode @?= ThinkingModeAbsent t ^. #requested @?= Nothing t ^. #adjustments @?= [SamplingDroppedUnsupportedModel ["temperature"]],@@ -595,20 +613,20 @@ "a model with an unknown output cap sends the documented floor" [ testCase "hand-rolled model with unknown cap sends the 1024 floor" $ do req <- requestFor uncappedModel emptyOptions- req ^. #max_tokens @?= uncappedMaxTokensFloor,+ requestMaxTokens req @?= uncappedMaxTokensFloor, testCase "the floor leaves room for a thinking budget" $ do let opts = emptyOptions & #thinking .~ Just ThinkingLow req <- requestFor uncappedModel opts t <- translationFor uncappedModel opts- req ^. #max_tokens @?= uncappedMaxTokensFloor + thinkingTokenBudget ThinkingLow+ requestMaxTokens req @?= uncappedMaxTokensFloor + thinkingTokenBudget ThinkingLow requestThinking req- @?= Just Messages.ThinkingEnabled {Messages.budget_tokens = thinkingTokenBudget ThinkingLow}+ @?= Just (Messages.ManualBudget (thinkingTokenBudget ThinkingLow) Nothing) t ^. #adjustments @?= [], testCase "an explicit maxTokens of zero is forwarded as written" $ do -- The floor stands in for an unknown cap, not for a caller's -- own choice. Someone who wrote Just 0 gets 0. req <- requestFor uncappedModel (emptyOptions & #maxTokens .~ Just 0)- req ^. #max_tokens @?= 0+ requestMaxTokens req @?= 0 ] where uncappedModel =@@ -715,11 +733,12 @@ assertBool ("no character outside the alphabet: " <> Text.unpack i) (Text.all ok i) ok c = (Char.isAscii c && Char.isAlphaNum c) || c == '_' || c == '-' toolUseIds msgs =- [i | m <- Vector.toList msgs, Messages.Content_Tool_Use {Messages.id = i} <- Vector.toList (messageContent m)]+ [i | m <- Vector.toList msgs, Messages.InputToolUse i _ _ _ <- Vector.toList (messageContent m)] toolResultIds msgs = [ i | m <- Vector.toList msgs,- Messages.Content_Tool_Result {Messages.tool_use_id = i} <- Vector.toList (messageContent m)+ Messages.InputToolResult result <- Vector.toList (messageContent m),+ let i = Messages.toolUseId result ] -- | An assistant turn carrying exactly these blocks.@@ -748,12 +767,12 @@ requestMessages <$> requestForContext anthropic_claude_haiku_4_5 (contextOf msgs) emptyOptions messageRole :: Messages.Message -> Messages.Role-messageRole Messages.Message {Messages.role = r} = r+messageRole msg = msg ^. #role -- | What @claude@ 1.5.0 added to the Messages response and what baikai -- now reads off it. Each of these was unreadable before the bump: -- 'Messages.Usage' had no thinking-token breakdown,--- 'Messages.StreamUsage' carried only @output_tokens@, and+-- 'Messages.UsageUpdate' carried only @output_tokens@, and -- 'Messages.StopReason' had no @pause_turn@. claude15UsageTests :: TestTree claude15UsageTests =@@ -764,8 +783,7 @@ runClaudeEvents [ messageStartWith (startUsage 10)- { Messages.output_tokens_details =- Just Messages.OutputTokensDetails {Messages.thinking_tokens = 7}+ { Messages.usageEvidence = noUsageEvidence {Messages.outputTokensDetails = Just (Messages.OutputTokenDetails (Just 7))} } ] ass ^. #usage . #reasoningTokens @?= Just 7,@@ -779,13 +797,12 @@ runClaudeEvents [ messageStartWith (startUsage 10), messageDelta- (Just Messages.End_Turn)+ (Just Messages.EndTurn) (outputOnlyStreamUsage 12)- { Messages.stream_input_tokens = Just 40,- Messages.stream_cache_read_input_tokens = Just 5,- Messages.stream_cache_creation_input_tokens = Just 3,- Messages.stream_output_tokens_details =- Just Messages.OutputTokensDetails {Messages.thinking_tokens = 9}+ { Messages.inputTokens = Just 40,+ Messages.cacheReadInputTokens = Just 5,+ Messages.cacheCreationInputTokens = Just 3,+ Messages.usageEvidence = noUsageEvidence {Messages.outputTokensDetails = Just (Messages.OutputTokenDetails (Just 9))} } ] u = ass ^. #usage@@ -801,10 +818,10 @@ runClaudeEvents [ messageStartWith (startUsage 10)- { Messages.cache_read_input_tokens = Just 5,- Messages.cache_creation_input_tokens = Just 3+ { Messages.cacheReadInputTokens = Just 5,+ Messages.cacheCreationInputTokens = Just 3 },- messageDelta (Just Messages.End_Turn) (outputOnlyStreamUsage 12)+ messageDelta (Just Messages.EndTurn) (outputOnlyStreamUsage 12) ] u = ass ^. #usage u ^. #inputTokens @?= 10@@ -819,8 +836,8 @@ let (events, ass) = runClaudeEvents [ messageStart,- messageDelta (Just Messages.Pause_Turn) (outputOnlyStreamUsage 12),- Messages.Message_Stop+ messageDelta (Just Messages.PauseTurn) (outputOnlyStreamUsage 12),+ Messages.MessageStop ] ass ^. #stopReason @?= Stop case last events of@@ -872,20 +889,11 @@ req <- requestForContext anthropic_claude_haiku_4_5 ctx emptyOptions case Vector.toList (requestMessages req) of (assistantMsg : _) ->- BSL.toStrict (Aeson.encode (messageContent assistantMsg))- @?= BSL.toStrict- ( Aeson.encode- ( Vector.fromList- [ Messages.Content_Thinking- { Messages.thinking = "because therefore",- Messages.signature = "sig-final"- },- Messages.Content_Redacted_Thinking- { Messages.data_ = "ENCRYPTED=="- }- ]- )- )+ Aeson.toJSON (messageContent assistantMsg)+ @?= Aeson.toJSON+ [ responseBlock "thinking" ["thinking" Aeson..= ("because therefore" :: Text.Text), "signature" Aeson..= ("sig-final" :: Text.Text)],+ responseBlock "redacted_thinking" ["data" Aeson..= ("ENCRYPTED==" :: Text.Text)]+ ] _ -> assertFailure "mapped request contained no assistant message", testCase "signature-less non-redacted thinking is omitted on replay" $ do let msg =@@ -911,165 +919,63 @@ req <- requestForContext anthropic_claude_haiku_4_5 ctx emptyOptions case Vector.toList (requestMessages req) of [assistantMsg] ->- BSL.toStrict (Aeson.encode (messageContent assistantMsg))- @?= BSL.toStrict- ( Aeson.encode- ( Vector.singleton- Messages.Content_Text- { Messages.text = "visible",- Messages.cache_control = Nothing- }- )- )+ Aeson.toJSON (messageContent assistantMsg)+ @?= Aeson.toJSON [responseBlock "text" ["text" Aeson..= ("visible" :: Text.Text)]] _ -> assertFailure "expected exactly one mapped assistant message", testCase "unopened block deltas do not fabricate events or closed blocks" $ do let (events, ass) = runClaudeEvents- [ Messages.Content_Block_Delta- { Messages.index = 7,- Messages.delta = Messages.Delta_Thinking_Delta {Messages.thinking = "ghost"}- },- Messages.Content_Block_Delta- { Messages.index = 8,- Messages.delta = Messages.Delta_Input_Json_Delta {Messages.partial_json = "{\"x\""}- },- Messages.Content_Block_Stop {Messages.index = 8}+ [ Messages.ContentBlockDelta 7 (Messages.ThinkingDelta "ghost"),+ Messages.ContentBlockDelta 8 (Messages.InputJsonDelta "{\"x\""),+ Messages.ContentBlockStop 8 ] events @?= [] IntMap.null (ass ^. #closed) @?= True IntMap.null (ass ^. #toolArgsBuf) @?= True ] -signedAndRedactedStream :: [Messages.MessageStreamEvent]+signedAndRedactedStream :: [Messages.StreamPayload] signedAndRedactedStream = [ messageStart,- Messages.Content_Block_Start- { Messages.index = 0,- Messages.content_block = Messages.ContentBlock_Thinking {Messages.thinking = "", Messages.signature = ""}- },- Messages.Content_Block_Delta- { Messages.index = 0,- Messages.delta = Messages.Delta_Thinking_Delta {Messages.thinking = "because "}- },- Messages.Content_Block_Delta- { Messages.index = 0,- Messages.delta = Messages.Delta_Thinking_Delta {Messages.thinking = "therefore"}- },- Messages.Content_Block_Delta- { Messages.index = 0,- Messages.delta = Messages.Delta_Signature_Delta {Messages.signature = "sig-"}- },- Messages.Content_Block_Delta- { Messages.index = 0,- Messages.delta = Messages.Delta_Signature_Delta {Messages.signature = "final"}- },- Messages.Content_Block_Stop {Messages.index = 0},- Messages.Content_Block_Start- { Messages.index = 1,- Messages.content_block = Messages.ContentBlock_Redacted_Thinking {Messages.data_ = "ENCRYPTED=="}- },- Messages.Content_Block_Stop {Messages.index = 1},- Messages.Message_Delta- { Messages.message_delta =- Messages.MessageDelta- { Messages.stop_reason = Just Messages.End_Turn,- Messages.stop_sequence = Nothing,- Messages.stop_details = Nothing- },- Messages.usage = outputOnlyStreamUsage 12- },- Messages.Message_Stop+ Messages.ContentBlockStart 0 (parseBlock (responseBlock "thinking" ["thinking" Aeson..= ("" :: Text.Text), "signature" Aeson..= ("" :: Text.Text)])),+ Messages.ContentBlockDelta 0 (Messages.ThinkingDelta "because "),+ Messages.ContentBlockDelta 0 (Messages.ThinkingDelta "therefore"),+ Messages.ContentBlockDelta 0 (Messages.SignatureDelta "sig-"),+ Messages.ContentBlockDelta 0 (Messages.SignatureDelta "final"),+ Messages.ContentBlockStop 0,+ Messages.ContentBlockStart 1 (parseBlock (responseBlock "redacted_thinking" ["data" Aeson..= ("ENCRYPTED==" :: Text.Text)])),+ Messages.ContentBlockStop 1,+ messageDelta (Just Messages.EndTurn) (outputOnlyStreamUsage 12),+ Messages.MessageStop ]+ where+ parseBlock raw = case Aeson.fromJSON raw of+ Aeson.Success value -> value+ Aeson.Error err -> error err -messageStart :: Messages.MessageStreamEvent-messageStart =- Messages.Message_Start- { Messages.message =- Messages.MessageResponse- { Messages.id = "msg_test",- Messages.type_ = "message",- Messages.role = Messages.Assistant,- Messages.content = Vector.empty,- Messages.model = "claude-haiku-4-5",- Messages.stop_reason = Nothing,- Messages.stop_sequence = Nothing,- Messages.stop_details = Nothing,- Messages.usage = startUsage 10,- Messages.container = Nothing- }- }+responseBlock :: Text.Text -> [Pair] -> Aeson.Value+responseBlock tag fields = Aeson.object (("type" Aeson..= tag) : fields) --- | A @message_start@ usage reporting the given prompt tokens and--- nothing else. Refine it by record update rather than respelling ten--- fields; the ones this provider never reads — @inference_geo@,--- @service_tier@, @speed@, @iterations@ — stay 'Nothing' so a test says--- only what it means to say. The prompt count is an argument rather--- than an update because @input_tokens@ alone does not name one record--- in @claude@ 1.5.0, and a single-field update on it is ambiguous.+messageStart :: Messages.StreamPayload+messageStart = messageStartWith (startUsage 10)++noUsageEvidence :: Messages.UsageEvidence+noUsageEvidence = Messages.UsageEvidence Nothing Nothing Nothing Nothing Nothing Nothing+ startUsage :: Natural -> Messages.Usage-startUsage inputTokens =- Messages.Usage- { Messages.input_tokens = inputTokens,- Messages.output_tokens = 0,- Messages.cache_creation_input_tokens = Nothing,- Messages.cache_read_input_tokens = Nothing,- Messages.server_tool_use = Nothing,- Messages.inference_geo = Nothing,- Messages.output_tokens_details = Nothing,- Messages.service_tier = Nothing,- Messages.speed = Nothing,- Messages.iterations = Nothing- }+startUsage input = Messages.Usage input 0 Nothing Nothing Nothing Nothing noUsageEvidence --- | A @message_delta@ usage reporting output tokens and nothing else,--- which is everything a pre-Claude-5 generation sends. Refine it by--- record update to model a generation that also repeats the--- prompt-side counts.-outputOnlyStreamUsage :: Natural -> Messages.StreamUsage-outputOnlyStreamUsage n =- Messages.StreamUsage- { Messages.stream_input_tokens = Nothing,- Messages.output_tokens = n,- Messages.stream_cache_creation_input_tokens = Nothing,- Messages.stream_cache_read_input_tokens = Nothing,- Messages.stream_server_tool_use = Nothing,- Messages.stream_output_tokens_details = Nothing,- Messages.stream_iterations = Nothing- }+outputOnlyStreamUsage :: Natural -> Messages.UsageUpdate+outputOnlyStreamUsage n = Messages.UsageUpdate Nothing (Just n) Nothing Nothing Nothing Nothing noUsageEvidence --- | A @message_delta@ event carrying a stop reason and a usage.-messageDelta :: Maybe Messages.StopReason -> Messages.StreamUsage -> Messages.MessageStreamEvent-messageDelta reason su =- Messages.Message_Delta- { Messages.message_delta =- Messages.MessageDelta- { Messages.stop_reason = reason,- Messages.stop_sequence = Nothing,- Messages.stop_details = Nothing- },- Messages.usage = su- }+messageDelta :: Maybe Messages.StopReason -> Messages.UsageUpdate -> Messages.StreamPayload+messageDelta reason = Messages.MessageDelta (Messages.MessageUpdate reason Nothing Nothing Nothing) --- | A @message_start@ event whose usage is the caller's.-messageStartWith :: Messages.Usage -> Messages.MessageStreamEvent+messageStartWith :: Messages.Usage -> Messages.StreamPayload messageStartWith u =- Messages.Message_Start- { Messages.message =- Messages.MessageResponse- { Messages.id = "msg_test",- Messages.type_ = "message",- Messages.role = Messages.Assistant,- Messages.content = Vector.empty,- Messages.model = "claude-haiku-4-5",- Messages.stop_reason = Nothing,- Messages.stop_sequence = Nothing,- Messages.stop_details = Nothing,- Messages.usage = u,- Messages.container = Nothing- }- }+ Messages.MessageStart (Messages.MessageResponse "msg_test" "claude-haiku-4-5" Messages.Assistant [] Nothing Nothing u Nothing Nothing mempty) -runClaudeEvents :: [Messages.MessageStreamEvent] -> ([AssistantMessageEvent], Assembler)+runClaudeEvents :: [Messages.StreamPayload] -> ([AssistantMessageEvent], Assembler) runClaudeEvents = foldl' ( \(events, ass) ev ->@@ -1095,14 +1001,14 @@ EventError TerminalPayload {message = msg} -> msg _ -> error "last event was not terminal" -requestForContext :: Model -> Context -> Options -> IO Messages.CreateMessage+requestForContext :: Model -> Context -> Options -> IO Messages.MessageRequest requestForContext model ctx opts = fst <$> mappedFor model ctx opts -requestMessages :: Messages.CreateMessage -> Vector.Vector Messages.Message-requestMessages Messages.CreateMessage {Messages.messages = msgs} = msgs+requestMessages :: Messages.MessageRequest -> Vector.Vector Messages.Message+requestMessages request = Vector.fromList (Messages.conversationHistory (request ^. #conversation)) -messageContent :: Messages.Message -> Vector.Vector Messages.Content-messageContent Messages.Message {Messages.content = blocks} = blocks+messageContent :: Messages.Message -> Vector.Vector Messages.InputBlock+messageContent msg = Vector.fromList (NonEmpty.toList (msg ^. #content)) testTime :: UTCTime testTime = read "2026-07-03 12:00:00 UTC"