packages feed

baikai-openai 0.7.3.1 → 0.7.4.0

raw patch · 16 files changed

+1281/−25 lines, 16 filesdep ~baikaiPVP ok

version bump matches the API change (PVP)

Dependency ranges changed: baikai

API changes (from Hackage documentation)

+ Baikai.Provider.OpenAI.Agent: runCodexAgentWithHooks :: CodexAgentConfig -> AgentRunRequest -> CodexHooks -> IO (Either Text CodexHookTurn)
+ Baikai.Provider.OpenAI.Cli: completeReviewedCodexCli :: ReviewedCodexThread -> Context -> Options -> IO (Either Text CodexHookTurn)
+ Baikai.Provider.OpenAI.Cli: withReviewedCodexCli :: CodexCliConfig -> Model -> [FilePath] -> CodexHooks -> (ReviewedCodexThread -> IO a) -> IO (Either Text a)
+ Baikai.Provider.OpenAI.HookEvidence: Blocked :: HookOutcome
+ Baikai.Provider.OpenAI.HookEvidence: CodexPreToolUse :: !Text -> !Text -> !Text -> !HookOutcome -> CodexPreToolUse
+ Baikai.Provider.OpenAI.HookEvidence: Completed :: HookOutcome
+ Baikai.Provider.OpenAI.HookEvidence: Failed :: HookOutcome
+ Baikai.Provider.OpenAI.HookEvidence: Stopped :: HookOutcome
+ Baikai.Provider.OpenAI.HookEvidence: [outcome] :: CodexPreToolUse -> !HookOutcome
+ Baikai.Provider.OpenAI.HookEvidence: [runId] :: CodexPreToolUse -> !Text
+ Baikai.Provider.OpenAI.HookEvidence: [threadId] :: CodexPreToolUse -> !Text
+ Baikai.Provider.OpenAI.HookEvidence: [turnId] :: CodexPreToolUse -> !Text
+ Baikai.Provider.OpenAI.HookEvidence: data CodexPreToolUse
+ Baikai.Provider.OpenAI.HookEvidence: data HookOutcome
+ Baikai.Provider.OpenAI.HookEvidence: instance GHC.Classes.Eq Baikai.Provider.OpenAI.HookEvidence.CodexPreToolUse
+ Baikai.Provider.OpenAI.HookEvidence: instance GHC.Classes.Eq Baikai.Provider.OpenAI.HookEvidence.HookOutcome
+ Baikai.Provider.OpenAI.HookEvidence: instance GHC.Internal.Show.Show Baikai.Provider.OpenAI.HookEvidence.CodexPreToolUse
+ Baikai.Provider.OpenAI.HookEvidence: instance GHC.Internal.Show.Show Baikai.Provider.OpenAI.HookEvidence.HookOutcome
+ Baikai.Provider.OpenAI.HookEvidence: parsePreToolUseCompletion :: Value -> Parser (Maybe CodexPreToolUse)
+ Baikai.Provider.OpenAI.HookEvidence: requireReviewedPreToolUseHook :: Text -> Text -> Value -> Parser ()
+ Baikai.Provider.OpenAI.Responses.Request: replayableOutputItem :: AssistantContent -> Value -> Bool
+ Baikai.Provider.OpenAI.ReviewedHooks: CodexHookReview :: !Text -> !Text -> !Maybe Text -> !Text -> !Int -> !Maybe Text -> CodexHookReview
+ Baikai.Provider.OpenAI.ReviewedHooks: CodexHookTurn :: !Text -> ![CodexPreToolUse] -> CodexHookTurn
+ Baikai.Provider.OpenAI.ReviewedHooks: [answer] :: CodexHookTurn -> !Text
+ Baikai.Provider.OpenAI.ReviewedHooks: [blockedHooks] :: CodexHookTurn -> ![CodexPreToolUse]
+ Baikai.Provider.OpenAI.ReviewedHooks: [nativeCommand] :: CodexHookReview -> !Text
+ Baikai.Provider.OpenAI.ReviewedHooks: [nativeHash] :: CodexHookReview -> !Text
+ Baikai.Provider.OpenAI.ReviewedHooks: [nativeKey] :: CodexHookReview -> !Text
+ Baikai.Provider.OpenAI.ReviewedHooks: [nativeMatcher] :: CodexHookReview -> !Maybe Text
+ Baikai.Provider.OpenAI.ReviewedHooks: [nativeStatusMessage] :: CodexHookReview -> !Maybe Text
+ Baikai.Provider.OpenAI.ReviewedHooks: [nativeTimeoutSec] :: CodexHookReview -> !Int
+ Baikai.Provider.OpenAI.ReviewedHooks: data CodexHookReview
+ Baikai.Provider.OpenAI.ReviewedHooks: data CodexHookTurn
+ Baikai.Provider.OpenAI.ReviewedHooks: data CodexHooks
+ Baikai.Provider.OpenAI.ReviewedHooks: data ReviewedCodexThread
+ Baikai.Provider.OpenAI.ReviewedHooks: instance GHC.Classes.Eq Baikai.Provider.OpenAI.ReviewedHooks.CodexHookReview
+ Baikai.Provider.OpenAI.ReviewedHooks: instance GHC.Classes.Eq Baikai.Provider.OpenAI.ReviewedHooks.CodexHookTurn
+ Baikai.Provider.OpenAI.ReviewedHooks: instance GHC.Internal.Exception.Type.Exception Baikai.Provider.OpenAI.ReviewedHooks.HookPolicyError
+ Baikai.Provider.OpenAI.ReviewedHooks: instance GHC.Internal.Show.Show Baikai.Provider.OpenAI.ReviewedHooks.CodexHookReview
+ Baikai.Provider.OpenAI.ReviewedHooks: instance GHC.Internal.Show.Show Baikai.Provider.OpenAI.ReviewedHooks.CodexHookTurn
+ Baikai.Provider.OpenAI.ReviewedHooks: instance GHC.Internal.Show.Show Baikai.Provider.OpenAI.ReviewedHooks.HookPolicyError
+ Baikai.Provider.OpenAI.ReviewedHooks: parseCodexHooks :: ByteString -> Either Text CodexHooks
+ Baikai.Provider.OpenAI.ReviewedHooks: reviewCodexHooks :: FilePath -> FilePath -> CodexHooks -> ([CodexHookReview] -> IO Bool) -> IO (Either Text Bool)
+ Baikai.Provider.OpenAI.ReviewedHooks: reviewCodexHooksInTerminal :: FilePath -> FilePath -> FilePath -> IO (Either Text Bool)
+ Baikai.Provider.OpenAI.ReviewedHooks: runReviewedCodexTurn :: ReviewedCodexThread -> Text -> Maybe Text -> Maybe Value -> IO (Either Text CodexHookTurn)
+ Baikai.Provider.OpenAI.ReviewedHooks: withReviewedCodexHooks :: FilePath -> FilePath -> AgentCapability -> Maybe Text -> [FilePath] -> Maybe Text -> CodexHooks -> (ReviewedCodexThread -> IO a) -> IO (Either Text a)

Files

CHANGELOG.md view
@@ -7,6 +7,105 @@  ## [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
baikai-openai.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.4 name: baikai-openai-version: 0.7.3.1+version: 0.7.4.0 synopsis: OpenAI providers for the baikai abstraction description:   OpenAI-compatible backends for baikai: Chat Completions over SSE against OpenAI and@@ -60,6 +60,7 @@     Baikai.Provider.OpenAI.Agent     Baikai.Provider.OpenAI.Api     Baikai.Provider.OpenAI.Cli+    Baikai.Provider.OpenAI.HookEvidence     Baikai.Provider.OpenAI.Interactive     Baikai.Provider.OpenAI.Internal.Cache     Baikai.Provider.OpenAI.Internal.ErrorClass@@ -70,6 +71,7 @@     Baikai.Provider.OpenAI.Responses.Assembler     Baikai.Provider.OpenAI.Responses.Request     Baikai.Provider.OpenAI.Responses.Stream+    Baikai.Provider.OpenAI.ReviewedHooks     Baikai.Provider.OpenAI.Shape     Baikai.Provider.OpenAI.Sse     Baikai.Provider.OpenAI.Transport@@ -78,7 +80,7 @@   autogen-modules: Paths_baikai_openai   build-depends:     aeson ^>=2.2,-    baikai ^>=0.10.1.1,+    baikai ^>=0.11.0.0,     base >=4.20 && <5,     base64-bytestring ^>=1.2,     bytestring ^>=0.12,@@ -116,6 +118,7 @@     EndpointModels     ErrorClassSpec     EvidenceSpec+    HookEvidenceSpec     LifecycleSpec     MidStreamSpec     NativeCacheSpec@@ -123,6 +126,7 @@     ReasoningSpec     ResponsesAssemblerSpec     ResponsesEvidenceSpec+    ResponsesReplayProbe     ResponsesSpec     ResponsesStreamSpec     ResponsesTransportSpec@@ -133,7 +137,7 @@    build-depends:     aeson,-    baikai ^>=0.10.1.1,+    baikai ^>=0.11.0.0,     baikai-openai,     base >=4.20 && <5,     bytestring,
src/Baikai/Provider/OpenAI/Agent.hs view
@@ -19,6 +19,7 @@     defaultCodexAgentConfig,     codexAgentCommand,     codexAgentThinking,+    runCodexAgentWithHooks,   ) where @@ -38,6 +39,12 @@     noThinkingRequested,   ) import Baikai.Prelude+import Baikai.Provider.OpenAI.ReviewedHooks+  ( CodexHookTurn,+    CodexHooks,+    runReviewedCodexTurn,+    withReviewedCodexHooks,+  ) import Baikai.ThinkingLevel (ThinkingLevel, renderThinkingLevel) import Data.Generics.Labels () import Data.Text qualified as Text@@ -114,6 +121,22 @@             },           codexAgentThinking req         )++-- | Use an ephemeral app-server thread for a caller's reviewed hooks.+-- Apply the operator's ceiling before calling, as with 'codexAgentCommand'.+-- The caller owns printing and timeout. This transport produces one final+-- answer and native hook evidence.+runCodexAgentWithHooks :: CodexAgentConfig -> AgentRunRequest -> CodexHooks -> IO (Either Text CodexHookTurn)+runCodexAgentWithHooks cfg req hooks+  | req ^. #provider /= AgentCodex = pure (Left "Reviewed Codex hooks require a Codex request.")+  | not (null (req ^. #safety . #allowedTools)) = pure (Left "Codex does not support a tool allow-list.")+  | not (null (cfg ^. #extraArgs <> req ^. #safety . #providerArgs)) = pure (Left "A reviewed Codex run does not accept raw exec flags.")+  | not (cfg ^. #ephemeral) = pure (Left "A reviewed Codex run must be ephemeral.")+  | otherwise = do+      result <-+        withReviewedCodexHooks (cfg ^. #executable) (req ^. #workingDir) (req ^. #safety . #capability) (req ^. #modelId) (req ^. #extraDirs) Nothing hooks $ \session ->+          runReviewedCodexTurn session (req ^. #prompt) (renderThinkingLevel <$> req ^. #effort) Nothing+      pure (result >>= id)  -- | What the request's reasoning effort became on the @codex exec@ -- command line.
src/Baikai/Provider/OpenAI/Cli.hs view
@@ -43,10 +43,13 @@     codexCliThinking,     defaultCodexCliConfig,     codexCliProvider,+    withReviewedCodexCli,+    completeReviewedCodexCli,     register,   ) where +import Baikai.Agent (AgentCapability (AgentEditWorkspace)) import Baikai.Api (Api (..)) import Baikai.Content (AssistantContent (..), TextContent (..)) import Baikai.Context (Context)@@ -59,6 +62,13 @@ import Baikai.Options (Options) import Baikai.Provider.Cli.Internal qualified as Internal import Baikai.Provider.Cli.Process.Internal (withOwnedProcess, withOwnedWorker)+import Baikai.Provider.OpenAI.ReviewedHooks+  ( CodexHookTurn,+    CodexHooks,+    ReviewedCodexThread,+    runReviewedCodexTurn,+    withReviewedCodexHooks,+  ) import Baikai.Provider.Registry   ( ApiProvider (..),     apiProviderWith,@@ -86,7 +96,7 @@ import GHC.Generics (Generic) import Streamly.Data.Stream (Stream) import Streamly.Data.Stream qualified as Stream-import System.Directory (getTemporaryDirectory, removeFile)+import System.Directory (getCurrentDirectory, getTemporaryDirectory, removeFile) import System.Exit (ExitCode (..)) import System.IO (Handle, hClose, openBinaryTempFile) import System.Process qualified as P@@ -134,6 +144,41 @@     & #describeThinking .~ (\_ opts -> codexCliThinking opts)     & #strengthCeiling .~ Ev.declaredStrength OpenAICompletionsCli     & #structuredOutput .~ declaredStructuredOutput OpenAICompletionsCli++-- | Open a reviewed, workspace-write Codex batch session. Callers with a+-- preparatory mutation can perform it inside the callback, after native+-- hook review has been checked and before sending the completion prompt.+-- Raw exec flags are specific to the legacy transport.+withReviewedCodexCli ::+  CodexCliConfig ->+  Model ->+  [FilePath] ->+  CodexHooks ->+  (ReviewedCodexThread -> IO a) ->+  IO (Either Text a)+withReviewedCodexCli cfg model dirs hooks use+  | not (cfg ^. #ephemeral) = pure (Left "A reviewed Codex batch session must be ephemeral.")+  | otherwise = case cfg ^. #extraArgs of+      [] -> launch Nothing+      ["-c", option] | Just skills <- Text.stripPrefix "skills.config=" option -> launch (Just skills)+      _ -> pure (Left "A reviewed Codex batch session accepts only the skills.config override.")+  where+    launch skills = do+      cwd <- maybe getCurrentDirectory pure (cfg ^. #workingDir)+      let selected = Text.strip (model ^. #modelId)+      withReviewedCodexHooks (cfg ^. #executable) cwd AgentEditWorkspace (if Text.null selected then Nothing else Just selected) dirs skills hooks use++-- | Complete a request in a reviewed session and preserve native denial+-- evidence alongside the final answer. The caller decides how a reported+-- denial affects the result of its own operation.+completeReviewedCodexCli ::+  ReviewedCodexThread ->+  Context ->+  Options ->+  IO (Either Text CodexHookTurn)+completeReviewedCodexCli session ctx opts = do+  either Control.Exception.throwIO pure (Context.refuseAssistantDataHistory ctx)+  runReviewedCodexTurn session (codexCliPrompt ctx) (renderThinkingLevel <$> opts ^. #thinking) (requestedSchema opts)  modelArgs :: Model -> [String] modelArgs m = case Text.strip (m ^. #modelId) of
+ src/Baikai/Provider/OpenAI/HookEvidence.hs view
@@ -0,0 +1,90 @@+-- | Read per-call evidence from the Codex app-server v2 notification stream.+-- Use this on a subscribed thread. The @codex exec --json@ transport has a+-- different schema and omits blocked pre-tool calls. A caller must verify+-- that its hooks are active with @hooks/list@ before starting the turn.+module Baikai.Provider.OpenAI.HookEvidence+  ( CodexPreToolUse (..),+    HookOutcome (..),+    requireReviewedPreToolUseHook,+    parsePreToolUseCompletion,+  )+where++import Control.Monad (filterM, unless)+import Data.Aeson (Object, Value, withObject, withText, (.:))+import Data.Aeson.Types (Parser)+import Data.Text (Text)++-- | A hook that completed normally can leave the tool decision to Codex.+-- Failed and stopped hooks require separate handling by a policy consumer.+data HookOutcome = Completed | Blocked | Failed | Stopped+  deriving stock (Eq, Show)++-- | The run identifier is opaque. Codex 0.171 exposes neither the command+-- arguments nor a separate tool-call identifier in this notification.+data CodexPreToolUse = CodexPreToolUse+  { threadId :: !Text,+    turnId :: !Text,+    runId :: !Text,+    outcome :: !HookOutcome+  }+  deriving stock (Eq, Show)++-- | Check one required synchronous command gate in the result of @hooks/list@+-- for the active thread. Supply the key and normalized hash from the reviewed+-- policy. Check every required gate before sending @turn/start@. This reads+-- the native review state and never grants trust or changes configuration.+requireReviewedPreToolUseHook :: Text -> Text -> Value -> Parser ()+requireReviewedPreToolUseHook key reviewedHash = withObject "hooks/list result" $ \result -> do+  rows <- result .: "data"+  row <- case rows of+    [entry] -> pure entry+    _ -> fail "expected the hook inventory for one thread"+  errors <- row .: "errors"+  unless (null (errors :: [Value])) (fail "Codex reported hook inventory errors")+  hooks <- row .: "hooks"+  matches <- filterM (fmap (== key) . (.: "key")) (hooks :: [Object])+  hook <- case matches of+    [match] -> pure match+    _ -> fail "expected one matching hook in the active thread"+  source <- hook .: "source"+  event <- hook .: "eventName"+  handler <- hook .: "handlerType"+  unless+    ((source, event, handler) == (("sessionFlags", "preToolUse", "command") :: (Text, Text, Text)))+    (fail "expected a thread-supplied PreToolUse command hook")+  enabled <- hook .: "enabled"+  async <- hook .: "async"+  unless (enabled && not async) (fail "the required hook must be enabled and synchronous")+  trust <- hook .: "trustStatus"+  current <- hook .: "currentHash"+  unless+    (trust == ("trusted" :: Text) && current == reviewedHash)+    (fail "the required hook needs review for its current declaration")++-- | Parse one app-server notification. Unrelated notifications yield+-- 'Nothing'. A malformed pre-tool completion or unknown terminal status+-- yields a parse error. An empty stream supplies no evidence of coverage.+parsePreToolUseCompletion :: Value -> Parser (Maybe CodexPreToolUse)+parsePreToolUseCompletion = withObject "app-server notification" $ \notification -> do+  method <- notification .: "method"+  if method /= ("hook/completed" :: Text)+    then pure Nothing+    else do+      params <- notification .: "params"+      run <- params .: "run"+      event <- run .: "eventName"+      if event /= ("preToolUse" :: Text)+        then pure Nothing+        else do+          thread <- params .: "threadId"+          turn <- params .: "turnId"+          identifier <- run .: "id"+          status <- run .: "status" >>= withText "preToolUse status" parseStatus+          pure (Just (CodexPreToolUse thread turn identifier status))+  where+    parseStatus "completed" = pure Completed+    parseStatus "blocked" = pure Blocked+    parseStatus "failed" = pure Failed+    parseStatus "stopped" = pure Stopped+    parseStatus _ = fail "unknown or nonterminal preToolUse completion status"
src/Baikai/Provider/OpenAI/Responses/Assembler.hs view
@@ -18,7 +18,7 @@  import Baikai.Api (Api (OpenAIResponses)) import Baikai.Content qualified as C-import Baikai.Provider.OpenAI.Responses.Request (validateReplayItems)+import Baikai.Provider.OpenAI.Responses.Request (replayableOutputItem, validateReplayItems) import Baikai.StopReason (StopReason (..)) import Baikai.Stream.Event qualified as E import Control.Monad (foldM, unless)@@ -266,8 +266,15 @@   let txt = T.concat (IM.elems item.parts)    in case item.kind of         "reasoning" -> C.AssistantThinking (C.ThinkingContent txt Nothing False (fmap (C.ThinkingReplay OpenAIResponses m . V.singleton) item.snapshot))-        "function_call" -> C.AssistantToolCall (C.ToolCall item.callId item.functionName (if final && completedStatus item.snapshot then C.toolArgumentsFromText txt else String txt))-        _ -> C.AssistantText (C.TextContent txt)+        "function_call" -> withReplay (C.AssistantToolCall (C.ToolCall item.callId item.functionName (if final && completedStatus item.snapshot then C.toolArgumentsFromText txt else String txt)))+        _ -> withReplay (C.AssistantText (C.TextContent txt))+  where+    withReplay block+      | final,+        Just raw <- item.snapshot,+        replayableOutputItem block raw =+          C.withOutputItemReplay (C.OutputItemReplay OpenAIResponses m raw) block+      | otherwise = block  completedStatus :: Maybe Value -> Bool completedStatus (Just (Object o)) = case KM.lookup "status" o of
src/Baikai/Provider/OpenAI/Responses/Request.hs view
@@ -12,6 +12,7 @@     describeThinking,     validateReplay,     validateReplayItems,+    replayableOutputItem,   ) where @@ -74,15 +75,23 @@   unless (length ids == length (nub ids)) (Left "Responses history contains duplicate item IDs")   choice <- toolChoiceFields ctx opts   cache <- Cache.responsesCachePlan m opts-  let marked = cache.markPrefix && maybe False (not . Text.null) ctx.systemPrompt-      prefix = [object ["role" .= ("developer" :: Text), "content" .= [object ["type" .= ("input_text" :: Text), "text" .= text, "prompt_cache_breakpoint" .= object ["mode" .= ("explicit" :: Text)]]]] | marked, Just text <- [ctx.systemPrompt]]+  let prefix =+        [ object ["role" .= String "developer", "content" .= [part]]+        | cache.markPrefix || compat.systemPromptInInput,+          Just text <- [ctx.systemPrompt],+          not (Text.null text),+          let part =+                object $+                  ["type" .= String "input_text", "text" .= text]+                    <> ["prompt_cache_breakpoint" .= object ["mode" .= String "explicit"] | cache.markPrefix]+        ]   let (reasoning, translation) = thinkingFields m opts       cap = fromMaybe m.maxOutputTokens opts.maxTokens       base =         Aeson.toJSON           R._CreateResponse             { R.model = SDK.Model m.modelId,-              R.instructions = if marked then Nothing else ctx.systemPrompt,+              R.instructions = if null prefix then ctx.systemPrompt else Nothing,               R.store = Just False,               R.stream = Just True,               R.include = Just (V.singleton "reasoning.encrypted_content"),@@ -167,7 +176,13 @@     let output = (if p.isError then "[error] " else "") <> Text.concat (V.toList parts)     pure [Aeson.toJSON R.Item_Input_Function_Call_Output {R.id = Nothing, R.call_id = p.toolCallId, R.output = output, R.status = Nothing}]   where-    assistantItem = \case+    assistantItem block+      | Just state <- C.outputItemReplay block = do+          unless (normaliseApi state.outputReplayApi == OpenAIResponses && state.outputReplayModel == m.modelId) (Left "Responses output replay belongs to another API or model")+          unless (replayableOutputItem block state.outputReplayItem) (Left "Responses output replay does not match its text or function call")+          pure [state.outputReplayItem]+      | otherwise = projectedItem block+    projectedItem = \case       C.AssistantData _ -> Left "Cannot replay AssistantData evidence"       C.AssistantText t -> pure [object ["role" .= ("assistant" :: Text), "content" .= t.text]]       C.AssistantToolCall tc -> do@@ -222,3 +237,38 @@     item _ = Left "Malformed Responses reasoning replay: expected reasoning type, id, encrypted_content and summary"     summaryPart (Object o) = KM.lookup "type" o == Just (String "summary_text") && case KM.lookup "text" o of Just (String _) -> True; _ -> False     summaryPart _ = False++-- | Validate the original item against the visible text or dispatched tool+-- call without re-encoding the provider's fields. A message can contain+-- multiple parts, and the call ID is independent of the output item ID.+replayableOutputItem :: C.AssistantContent -> Value -> Bool+replayableOutputItem block (Object item) =+  case KM.lookup "id" item of+    Just (String ident) | not (Text.null ident), complete -> matches block+    _ -> False+  where+    complete = case KM.lookup "status" item of+      Nothing -> True+      Just (String "completed") -> True+      _ -> False+    matches (C.AssistantText t)+      | KM.lookup "type" item == Just (String "message"),+        KM.lookup "role" item == Just (String "assistant"),+        Just (Array parts) <- KM.lookup "content" item =+          fmap (Text.concat . V.toList) (traverse visiblePart parts) == Just t.text+    matches (C.AssistantToolCall tc)+      | KM.lookup "type" item == Just (String "function_call"),+        not (Text.null tc.id_ || Text.null tc.name || C.isCutOffToolCall tc),+        KM.lookup "call_id" item == Just (String tc.id_),+        KM.lookup "name" item == Just (String tc.name),+        Just (String raw) <- KM.lookup "arguments" item =+          C.toolArgumentsFromText raw == tc.arguments+    matches _ = False+    visiblePart (Object part) = case KM.lookup "type" part of+      Just (String "output_text") -> textValue (KM.lookup "text" part)+      Just (String "refusal") -> textValue (KM.lookup "refusal" part)+      _ -> Nothing+    visiblePart _ = Nothing+    textValue (Just (String t)) = Just t+    textValue _ = Nothing+replayableOutputItem _ _ = False
+ src/Baikai/Provider/OpenAI/ReviewedHooks.hs view
@@ -0,0 +1,501 @@+-- | Read and review invocation-local Codex hooks with the native app-server.+-- A policy-bearing caller should keep the preflighted thread alive until its+-- turn finishes, so configuration changes cannot swap the verified handlers.+module Baikai.Provider.OpenAI.ReviewedHooks+  ( CodexHooks,+    parseCodexHooks,+    CodexHookReview (..),+    reviewCodexHooks,+    reviewCodexHooksInTerminal,+    withReviewedCodexHooks,+    ReviewedCodexThread,+    CodexHookTurn (..),+    runReviewedCodexTurn,+  )+where++import Baikai.Agent (AgentCapability (..))+import Baikai.Provider.Cli.Process.Internal (withOwnedProcess)+import Baikai.Provider.OpenAI.HookEvidence+  ( CodexPreToolUse (..),+    HookOutcome (..),+    parsePreToolUseCompletion,+    requireReviewedPreToolUseHook,+  )+import Control.Concurrent.MVar (MVar, newMVar, tryTakeMVar)+import Control.Exception (Exception, IOException, catch, throwIO, try)+import Control.Monad (unless, void, when)+import Data.Aeson (Object, Value (..), encode, object, withObject, (.:), (.:?), (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Parser, parseEither)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import Data.ByteString.Lazy qualified as LBS+import Data.IORef (IORef, atomicModifyIORef', newIORef)+import Data.List (nub)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.IO qualified as TextIO+import System.Directory (canonicalizePath, doesFileExist, makeAbsolute)+import System.IO (Handle, hFlush, hIsTerminalDevice, stderr, stdin)+import System.Process qualified as Process+import System.Timeout (timeout)++data CodexHooks = CodexHooks !Value ![HookDeclaration]++data HookDeclaration = HookDeclaration+  { matcher :: !(Maybe Text),+    command :: !Text,+    timeoutSec :: !(Maybe Int),+    statusMessage :: !(Maybe Text)+  }++-- | Accept only a native hooks file with synchronous PreToolUse command+-- handlers. Keep the provider input in memory after parsing.+parseCodexHooks :: BS.ByteString -> Either Text CodexHooks+parseCodexHooks bytes = do+  value <- either (const (Left "Codex hooks file must contain valid JSON.")) Right (Aeson.eitherDecodeStrict' bytes)+  runParser parse value+  where+    parse = withObject "Codex hooks file" $ \file -> do+      onlyKeys ["hooks"] file+      hooks <- file .: "hooks"+      onlyKeys ["PreToolUse"] hooks+      groups <- hooks .: "PreToolUse" :: Parser [Value]+      declarations <- concat <$> traverse parseGroup groups+      when (null declarations) (fail "PreToolUse must contain at least one handler")+      pure (CodexHooks (Object hooks) declarations)++    parseGroup = withObject "PreToolUse entry" $ \entry -> do+      onlyKeys ["matcher", "hooks"] entry+      match <- entry .:? "matcher"+      handlers <- entry .: "hooks" :: Parser [Value]+      when (null handlers) (fail "PreToolUse entry must contain at least one handler")+      traverse (parseHandler match) handlers++    parseHandler match = withObject "PreToolUse handler" $ \handler -> do+      onlyKeys ["type", "command", "async", "timeout", "statusMessage"] handler+      kind <- handler .: "type"+      asynchronous <- handler .:? "async"+      unless (kind == ("command" :: Text) && asynchronous /= Just True) $+        fail "expected a synchronous command handler"+      cmd <- handler .: "command"+      when (Text.null (Text.strip cmd) || Text.any (== '\0') cmd) $+        fail "expected a nonblank command without NUL characters"+      seconds <- handler .:? "timeout"+      when (any (<= 0) seconds) (fail "hook timeout must be positive")+      HookDeclaration match cmd seconds <$> handler .:? "statusMessage"++    onlyKeys allowed obj =+      unless (all (`elem` allowed) (KeyMap.keys obj)) $+        fail "contains an unsupported field"++data CodexHookReview = CodexHookReview+  { nativeKey :: !Text,+    nativeHash :: !Text,+    nativeMatcher :: !(Maybe Text),+    nativeCommand :: !Text,+    nativeTimeoutSec :: !Int,+    nativeStatusMessage :: !(Maybe Text)+  }+  deriving stock (Eq, Show)++data Rpc = Rpc !Handle !Handle !(IORef Int)++data ReviewedCodexThread = ReviewedCodexThread !Rpc !Text !(MVar ())++-- | A completed, attributed turn. An empty block list is positive+-- evidence that this turn reported no blocks. A failed or interrupted+-- turn, or a failed/stopped gate, returns an error instead.+data CodexHookTurn = CodexHookTurn+  { answer :: !Text,+    blockedHooks :: ![CodexPreToolUse]+  }+  deriving stock (Eq, Show)++newtype HookPolicyError = HookPolicyError Text+  deriving stock (Show)++instance Exception HookPolicyError++-- | Review the exact effective native declarations. The callback implements+-- the operator interaction. A declined review or a file changed while the+-- operator was deciding leaves the trust store untouched.+reviewCodexHooks ::+  FilePath ->+  FilePath ->+  CodexHooks ->+  ([CodexHookReview] -> IO Bool) ->+  IO (Either Text Bool)+reviewCodexHooks executable cwd hooks confirm = runHookAction $+  withAppServer executable cwd Nothing $ \rpc -> do+    thread <- startThread rpc cwd AgentReadOnly Nothing [] hooks+    inventory <- rpcRequest rpc "hooks/list" (object ["threadId" .= thread])+    rows <- parseOrFail (parseInventory hooks) inventory+    let pending = [entry | (trust, entry) <- rows, trust /= "trusted"]+    if null pending+      then pure True+      else do+        accepted <- confirm pending+        when accepted $ do+          -- Use the same native config write as the Codex TUI. It merges+          -- only the exact reviewed entries into the user's hook state.+          let trust = object [Key.fromText (nativeKey row) .= object ["trusted_hash" .= nativeHash row] | row <- pending]+          void $+            rpcRequest rpc "config/batchWrite" $+              object+                [ "edits" .= [object ["keyPath" .= ("hooks.state" :: Text), "value" .= trust, "mergeStrategy" .= ("upsert" :: Text)]],+                  "reloadUserConfig" .= True+                ]+        pure accepted++-- | Present Codex's native review in the caller's terminal and require an+-- explicit answer before writing trust. The file must stay unchanged while+-- the operator reads the prompt.+reviewCodexHooksInTerminal :: FilePath -> FilePath -> FilePath -> IO (Either Text Bool)+reviewCodexHooksInTerminal executable cwd requested = do+  interactive <- hIsTerminalDevice stdin+  visible <- hIsTerminalDevice stderr+  if interactive && visible+    then do+      path <- makeAbsolute requested+      bytes <- readFileBytes path+      case bytes of+        Left err -> pure (Left err)+        Right original -> case parseCodexHooks original of+          Left err -> pure (Left err)+          Right hooks -> reviewCodexHooks executable cwd hooks (confirm path original)+    else pure (Left "Codex hooks must be reviewed in a terminal.")+  where+    readFileBytes path = do+      result <- try @IOException $ do+        exists <- doesFileExist path+        unless exists (ioError (userError "expected a file"))+        BS.readFile path+      pure (either (const (Left ("Cannot read Codex hooks file " <> quoted path <> "."))) Right result)+    quoted :: (Show a) => a -> Text+    quoted = Text.pack . show+    confirm path original pending = do+      TextIO.hPutStrLn stderr ("Review Codex hooks in " <> quoted path <> " for " <> quoted cwd <> ".")+      TextIO.hPutStrLn stderr "Reviewed commands can run outside the sandbox. Codex reviews the declaration and does not fingerprint scripts it invokes."+      mapM_ display pending+      TextIO.hPutStr stderr "Type yes to trust these declarations: "+      hFlush stderr+      reply <- try @IOException (TextIO.hGetLine stdin)+      if either (const False) (== "yes") reply+        then do+          current <- readFileBytes path+          case current of+            Right latest | latest == original -> pure True+            _ -> TextIO.hPutStrLn stderr "The hooks file changed during review. Open the updated file and try again." >> pure False+        else pure False+    display entry = do+      TextIO.hPutStrLn stderr ("  Matcher " <> maybe "all tools" quoted (nativeMatcher entry))+      TextIO.hPutStrLn stderr ("  Command " <> quoted (nativeCommand entry))+      TextIO.hPutStrLn stderr ("  Timeout " <> quoted (nativeTimeoutSec entry) <> " seconds")+      maybe (pure ()) (TextIO.hPutStrLn stderr . ("  Status " <>) . quoted) (nativeStatusMessage entry)++-- | Preflight a single thread before giving the application access to it.+-- No review state is written here. The caller supplies the native sandbox,+-- working directory, model, extra writable directories and optional TOML+-- value for the provider's skills.config setting.+withReviewedCodexHooks ::+  FilePath ->+  FilePath ->+  AgentCapability ->+  Maybe Text ->+  [FilePath] ->+  Maybe Text ->+  CodexHooks ->+  (ReviewedCodexThread -> IO a) ->+  IO (Either Text a)+withReviewedCodexHooks executable cwd sandbox model dirs skills hooks use = runHookAction $+  withAppServer executable cwd skills $ \rpc -> do+    thread <- startThread rpc cwd sandbox model dirs hooks+    inventory <- rpcRequest rpc "hooks/list" (object ["threadId" .= thread])+    rows <- parseOrFail (parseInventory hooks) inventory+    unless (all ((== "trusted") . fst) rows) $+      policyError "Codex requires review for the current hooks."+    mapM_ (\(_, row) -> parseOrFail (requireReviewedPreToolUseHook (nativeKey row) (nativeHash row)) inventory) rows+    once <- newMVar ()+    use (ReviewedCodexThread rpc thread once)++-- | Run one prompt in the preflighted thread. Consume the native stream+-- until the matching terminal event, preserving refusals even on success.+-- The owning process scope cleans up on cancellation.+runReviewedCodexTurn ::+  ReviewedCodexThread ->+  Text ->+  Maybe Text ->+  Maybe Value ->+  IO (Either Text CodexHookTurn)+runReviewedCodexTurn (ReviewedCodexThread rpc thread once) prompt effort schema = runHookAction $ do+  available <- tryTakeMVar once+  unless (available == Just ()) (policyError "This reviewed Codex thread has already started a turn.")+  let input = [object ["type" .= ("text" :: Text), "text" .= prompt, "text_elements" .= ([] :: [Value])]]+      params = object ["threadId" .= thread, "input" .= input, "effort" .= effort, "outputSchema" .= schema]+  (turn, pending) <- beginTurn params+  collect turn Set.empty [] pending+  where+    beginTurn params = do+      received <- timeout 30000000 $ do+        requestId <- sendRequest rpc "turn/start" params+        let await pending = do+              message <- rpcRead rpc+              case KeyMap.lookup "id" message of+                Just observed+                  | observed == requestId,+                    not (KeyMap.member "method" message),+                    Just result <- KeyMap.lookup "result" message -> do+                      turn <- parseOrFail (withObject "turn/start result" $ \obj -> obj .: "turn" >>= (.: "id")) result+                      pure (turn, reverse pending)+                Nothing -> await (message : pending)+                _ -> policyError "Codex could not start the reviewed turn."+        await []+      maybe (policyError "Timed out while starting the reviewed Codex turn.") pure received++    collect turn running blocks inbox = do+      (message, rest) <- case inbox of+        [] -> (,[]) <$> rpcRead rpc+        first : remaining -> pure (first, remaining)+      event <- parseOrFail parseTurnEvent (Object message)+      case event of+        Nothing -> collect turn running blocks rest+        Just (EventHookStart owner turnId identifier)+          | owner == thread && turnId == turn ->+              if Set.member identifier running+                then policyError "Codex reported a duplicate PreToolUse start."+                else collect turn (Set.insert identifier running) blocks rest+        Just (EventHookFinish completion)+          | threadId completion == thread && turnId completion == turn -> do+              let identifier = runId completion+              unless (Set.member identifier running) (policyError "Codex reported a PreToolUse completion without its start.")+              let remaining = Set.delete identifier running+              case outcome completion of+                Completed -> collect turn remaining blocks rest+                Blocked -> collect turn remaining (completion : blocks) rest+                Failed -> policyError "A Codex PreToolUse hook failed. Inspect the workspace and retry with a working gate."+                Stopped -> policyError "A Codex PreToolUse hook stopped before it could complete."+        Just (EventTurnEnd owner turnId status items)+          | owner == thread && turnId == turn -> do+              unless (status == "completed" && Set.null running) $+                policyError "Codex ended the turn without complete hook evidence."+              answers <- traverse (parseOrFail parseAnswer) items+              case reverse [answerText | Just answerText <- answers] of+                final : _ -> pure (CodexHookTurn final (reverse blocks))+                [] -> policyError "Codex finished without a final assistant message."+        Just (EventCommandDeclined owner turnId identifier)+          | owner == thread && turnId == turn ->+              policyError ("Codex declined command item " <> identifier <> ". Inspect the workspace and policy before retrying.")+        _ -> collect turn running blocks rest++    parseAnswer = withObject "item" $ \item -> do+      kind <- item .: "type"+      if kind == ("agentMessage" :: Text)+        then Just <$> item .: "text"+        else pure Nothing++data TurnEvent+  = EventHookStart !Text !Text !Text+  | EventHookFinish !CodexPreToolUse+  | EventTurnEnd !Text !Text !Text ![Value]+  | EventCommandDeclined !Text !Text !Text++parseTurnEvent :: Value -> Parser (Maybe TurnEvent)+parseTurnEvent = withObject "app-server event" $ \message -> do+  when (KeyMap.member "id" message) (fail "unexpected request during reviewed Codex turn")+  method <- message .: "method" :: Parser Text+  case method of+    "hook/completed" -> fmap EventHookFinish <$> parsePreToolUseCompletion (Object message)+    "hook/started" -> do+      params <- message .: "params"+      run <- params .: "run"+      event <- run .: "eventName"+      if event == ("preToolUse" :: Text)+        then Just <$> (EventHookStart <$> params .: "threadId" <*> params .: "turnId" <*> run .: "id")+        else pure Nothing+    "turn/completed" -> do+      params <- message .: "params"+      turn <- params .: "turn"+      Just <$> (EventTurnEnd <$> params .: "threadId" <*> turn .: "id" <*> turn .: "status" <*> turn .: "items")+    "item/completed" -> do+      params <- message .: "params"+      item <- params .: "item"+      kind <- item .: "type" :: Parser Text+      status <- item .:? "status" :: Parser (Maybe Text)+      if kind `elem` ["commandExecution", "fileChange"] && status == Just "declined"+        then Just <$> (EventCommandDeclined <$> params .: "threadId" <*> params .: "turnId" <*> item .: "id")+        else pure Nothing+    _ -> pure Nothing++parseInventory :: CodexHooks -> Value -> Parser [(Text, CodexHookReview)]+parseInventory (CodexHooks _ declarations) = withObject "hooks/list result" $ \result -> do+  rows <- result .: "data"+  row <- case rows of+    [entry] -> pure entry+    _ -> fail "expected one thread's hook inventory"+  errors <- row .: "errors"+  warnings <- row .: "warnings"+  unless (null (errors :: [Value]) && null (warnings :: [Value])) $+    fail "Codex reported hook inventory diagnostics"+  hooks <- row .: "hooks"+  let supplied = filter ((== Just (String "sessionFlags")) . KeyMap.lookup "source") hooks+  unless (length supplied == length declarations) $+    fail "effective hook inventory differs from the supplied file"+  observed <- traverse checkHook (zip declarations supplied)+  unless (Set.size (Set.fromList (map (nativeKey . snd) observed)) == length observed) $+    fail "Codex returned duplicate hook keys"+  pure observed+  where+    checkHook (expected, hook) = do+      event <- hook .: "eventName"+      handler <- hook .: "handlerType"+      enabled <- hook .: "enabled"+      async <- hook .: "async"+      trust <- hook .: "trustStatus"+      unless ((event, handler) == (("preToolUse", "command") :: (Text, Text)) && enabled && not async) $+        fail "expected an enabled synchronous PreToolUse command"+      unless (trust `elem` (["trusted", "untrusted", "modified"] :: [Text])) $+        fail "Codex reported an unsupported hook review state"+      review <-+        CodexHookReview+          <$> hook .: "key"+          <*> hook .: "currentHash"+          <*> hook .:? "matcher"+          <*> hook .: "command"+          <*> hook .: "timeoutSec"+          <*> hook .:? "statusMessage"+      unless+        ( nativeMatcher review == matcher expected+            && nativeCommand review == command expected+            && maybe True (== nativeTimeoutSec review) (timeoutSec expected)+            && nativeStatusMessage review == statusMessage expected+        )+        (fail "effective hook declaration differs from the supplied file")+      pure (trust, review)++startThread :: Rpc -> FilePath -> AgentCapability -> Maybe Text -> [FilePath] -> CodexHooks -> IO Text+startThread rpc cwd capability model dirs (CodexHooks hooks _) = do+  let wantsExtraRoots = capability == AgentEditWorkspace && not (null dirs)+  requestedRoots <- if wantsExtraRoots then traverse canonicalizePath dirs else pure []+  existingRoots <-+    if wantsExtraRoots+      then rpcRequest rpc "config/read" (object ["cwd" .= cwd, "includeLayers" .= False]) >>= parseOrFail parseWritableRoots+      else pure []+  let config =+        object $+          [ "hooks" .= hooks,+            -- The stable protocol's turn evidence covers this thread.+            "features" .= object ["multi_agent" .= False, "multi_agent_v2" .= False]+          ]+            <> [ "sandbox_workspace_write" .= object ["writable_roots" .= nub (existingRoots <> requestedRoots)]+               | wantsExtraRoots+               ]+  result <-+    rpcRequest rpc "thread/start" $+      object+        [ "cwd" .= cwd,+          "ephemeral" .= True,+          "sandbox" .= (sandbox :: Text),+          "approvalPolicy" .= ("never" :: Text),+          "model" .= model,+          "config" .= config+        ]+  (thread, actualRoots) <- parseOrFail checkThread result+  canonicalRoots <- if wantsExtraRoots then traverse canonicalizePath actualRoots else pure []+  unless (all (`elem` canonicalRoots) requestedRoots) $+    policyError "Codex did not give the reviewed session access to all requested directories."+  pure thread+  where+    (sandbox, effective) = case capability of+      AgentReadOnly -> ("read-only", "readOnly")+      AgentEditWorkspace -> ("workspace-write", "workspaceWrite")+      AgentFullAccess -> ("danger-full-access", "dangerFullAccess")++    parseWritableRoots = withObject "config/read result" $ \obj -> do+      current <- obj .: "config"+      workspace <- current .:? "sandbox_workspace_write"+      maybe (pure []) (fmap (maybe [] id) . (.:? "writable_roots")) workspace++    checkThread = withObject "thread/start result" $ \obj -> do+      policy <- obj .: "approvalPolicy"+      sandboxResult <- obj .: "sandbox"+      mode <- sandboxResult .: "type"+      unless ((policy, mode) == (("never", effective) :: (Text, Text))) $+        fail "Codex did not establish the requested sandbox and unattended approval policy"+      thread <- obj .: "thread" >>= (.: "id")+      roots <- sandboxResult .:? "writableRoots"+      pure (thread, maybe [] id roots)++runHookAction :: IO a -> IO (Either Text a)+runHookAction action =+  (either (\(HookPolicyError message) -> Left message) Right <$> try action)+    `catch` \(_ :: IOException) -> pure (Left "Could not communicate with the Codex app-server. Check that codex is on PATH and supports hooks/list.")++withAppServer :: FilePath -> FilePath -> Maybe Text -> (Rpc -> IO a) -> IO a+withAppServer executable cwd skills use =+  withOwnedProcess spec $ \mInput mOutput _ _ -> case (mInput, mOutput) of+    (Just input, Just output) -> do+      rpc <- Rpc input output <$> newIORef 0+      void $+        rpcRequest rpc "initialize" $+          object ["clientInfo" .= object ["name" .= ("baikai" :: Text), "version" .= ("1" :: Text)]]+      rpcSend rpc (object ["method" .= ("initialized" :: Text)])+      use rpc+    _ -> policyError "Could not open Codex app-server streams."+  where+    spec =+      (Process.proc executable (["app-server", "--stdio"] <> maybe [] (\value -> ["-c", "skills.config=" <> Text.unpack value]) skills))+        { Process.cwd = Just cwd,+          Process.std_in = Process.CreatePipe,+          Process.std_out = Process.CreatePipe,+          Process.std_err = Process.NoStream+        }++rpcSend :: Rpc -> Value -> IO ()+rpcSend (Rpc input _ _) value = do+  LBS.hPut input (encode value <> "\n")+  hFlush input++rpcRead :: Rpc -> IO Object+rpcRead (Rpc _ output _) = do+  line <- BS8.hGetLine output+  case Aeson.decodeStrict' line of+    Just (Object message) -> pure message+    _ -> policyError "Received an invalid message from the Codex app-server."++rpcRequest :: Rpc -> Text -> Value -> IO Value+rpcRequest rpc method params = do+  response <- timeout 30000000 $ do+    requestId <- sendRequest rpc method params+    waitForResponse requestId+  maybe (policyError ("Timed out waiting for Codex " <> method <> ".")) pure response+  where+    waitForResponse requestId = do+      message <- rpcRead rpc+      case KeyMap.lookup "id" message of+        Nothing -> waitForResponse requestId+        Just observed+          | observed == requestId,+            not (KeyMap.member "method" message),+            Just result <- KeyMap.lookup "result" message ->+              pure result+        _ -> policyError ("Codex could not complete " <> method <> ".")++sendRequest :: Rpc -> Text -> Value -> IO Value+sendRequest rpc@(Rpc _ _ counter) method params = do+  requestId <- atomicModifyIORef' counter (\previous -> let next = previous + 1 in (next, next))+  rpcSend rpc (object ["id" .= requestId, "method" .= method, "params" .= params])+  pure (Aeson.toJSON requestId)++runParser :: (Value -> Parser a) -> Value -> Either Text a+runParser parser = either (Left . Text.pack) Right . parseEither parser++parseOrFail :: (Value -> Parser a) -> Value -> IO a+parseOrFail parser = either policyError pure . runParser parser++policyError :: Text -> IO a+policyError = throwIO . HookPolicyError
+ test/HookEvidenceSpec.hs view
@@ -0,0 +1,67 @@+module HookEvidenceSpec (tests) where++import Baikai.Provider.OpenAI.HookEvidence+import Data.Aeson (Value (Bool, Object, String), object, (.=))+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (parseEither)+import Data.Either (isLeft)+import Data.Text (Text)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, testCase, (@?=))++tests :: TestTree+tests =+  testGroup+    "app-server pre-tool evidence"+    [ testCase "check the reviewed gate within the thread's inventory" $+        verify (inventory [gate]) @?= Right (),+      testCase "missing, duplicate and partial inventories fail" $ do+        assertBool "missing" (isLeft (verify (inventory [])))+        assertBool "ambiguous" (isLeft (verify (inventory [gate, gate])))+        assertBool "inventory error" (isLeft (verify (object ["data" .= [object ["errors" .= [True], "hooks" .= [gate]]]]))),+      testCase "only the exact reviewed and executable session gate qualifies" $+        mapM_+          (\(key, val) -> assertBool (show key) (isLeft (verify (inventory [KeyMap.insert key val gate]))))+          [ ("currentHash", String "changed"),+            ("trustStatus", String "untrusted"),+            ("trustStatus", String "modified"),+            ("source", String "user"),+            ("handlerType", String "prompt"),+            ("eventName", String "postToolUse"),+            ("enabled", Bool False),+            ("async", Bool True)+          ],+      testCase "structured denial survives a successful turn" $+        parse (hook "preToolUse" "blocked") @?= Right (Just (CodexPreToolUse "t" "u" "r" Blocked)),+      testCase "exit 7 is ordinary command failure" $+        parse (object ["method" .= ("item/completed" :: Text), "params" .= object ["item" .= object ["status" .= ("failed" :: Text), "exitCode" .= (7 :: Int)]]]) @?= Right Nothing,+      testCase "a different hook can also report blocked" $+        parse (hook "postToolUse" "blocked") @?= Right Nothing,+      testCase "hook failure, stop and completion are distinct" $+        traverse (parse . hook "preToolUse") ["failed", "stopped", "completed"]+          @?= Right [Just (CodexPreToolUse "t" "u" "r" x) | x <- [Failed, Stopped, Completed]],+      testCase "unknown or malformed evidence cannot be treated as success" $ do+        assertBool "unexpected status" (isLeft (parse (hook "preToolUse" "running")))+        assertBool "missing run" (isLeft (parse (object ["method" .= ("hook/completed" :: Text), "params" .= object []])))+    ]+  where+    verify = parseEither (requireReviewedPreToolUseHook "gate" "digest")+    inventory hooks = object ["data" .= [object ["errors" .= ([] :: [Value]), "hooks" .= (map Object hooks)]]]+    gate =+      KeyMap.fromList+        [ ("key", String "gate"),+          ("currentHash", String "digest"),+          ("source", String "sessionFlags"),+          ("eventName", String "preToolUse"),+          ("handlerType", String "command"),+          ("trustStatus", String "trusted"),+          ("enabled", Bool True),+          ("async", Bool False)+        ]+    parse = parseEither parsePreToolUseCompletion+    hook :: Text -> Text -> Value+    hook event status =+      object+        [ "method" .= ("hook/completed" :: Text),+          "params" .= object ["threadId" .= ("t" :: Text), "turnId" .= ("u" :: Text), "run" .= object ["id" .= ("r" :: Text), "eventName" .= event, "status" .= status]]+        ]
test/Main.hs view
@@ -44,6 +44,7 @@ import DataInputSpec qualified import ErrorClassSpec qualified import EvidenceSpec qualified+import HookEvidenceSpec qualified import LifecycleSpec qualified import MidStreamSpec qualified import NativeCacheSpec qualified@@ -53,6 +54,7 @@ import ReasoningSpec qualified import ResponsesAssemblerSpec qualified import ResponsesEvidenceSpec qualified+import ResponsesReplayProbe qualified import ResponsesSpec qualified import ResponsesStreamSpec qualified import ResponsesTransportSpec qualified@@ -109,12 +111,14 @@         CliEvidenceSpec.tests,         ErrorClassSpec.tests,         EvidenceSpec.tests,+        HookEvidenceSpec.tests,         LifecycleSpec.tests,         MidStreamSpec.tests,         PublicSurfaceSpec.tests,         ReasoningSpec.tests,         ResponsesAssemblerSpec.tests,         ResponsesEvidenceSpec.tests,+        ResponsesReplayProbe.tests,         ResponsesSpec.tests,         ResponsesStreamSpec.tests,         ResponsesTransportSpec.tests,
test/NativeCacheSpec.hs view
@@ -38,6 +38,22 @@         forM_ [(272000, 17 / 250), (272001, 272001 / 2000000)] $ \(count, expected) -> do           let u = observeBilling [BillingServiceTier "default"] (zeroUsage & #cacheWriteTokens .~ count & #totalTokens .~ count)           (Cache.cacheCost (Just CacheRetentionLong) m u).usd @?= expected,+      testCase "GPT-6.2 Standard cache duration rates use the full input tier" $+        forM_ [(Models.openai_gpt_6_2_astra, 8, 40, 0.4, 10, 20), (Models.openai_gpt_6_2_sol, 2, 10, 0.1, 2.5, 5)] $ \(m, input, output, readRate, shortRate, longRate) ->+          forM_ [(CacheRetentionShort, shortRate), (CacheRetentionLong, longRate)] $ \(duration, writeRate) ->+            forM_ [(272000, 1, 1), (272001, 2, 1.5)] $ \(totalInput, inputFactor, outputFactor) -> do+              let payload = object ["input_tokens" .= (totalInput :: Int), "output_tokens" .= (100 :: Int), "input_tokens_details" .= object ["cached_tokens" .= (1000 :: Int), "cache_write_tokens" .= (2000 :: Int)]]+              normalized <- maybe (assertFailure "missing usage") pure (Billing.readUsage Billing.ResponsesUsage payload)+              let u = observeBilling [BillingServiceTier "default"] normalized+                  bill = Cache.cacheCost (Just duration) m u+              (u.inputTokens, u.cacheReadTokens, u.cacheWriteTokens, u.totalTokens) @?= (fromIntegral totalInput - 3000, 1000, 2000, fromIntegral totalInput + 100)+              bill.breakdown+                @?= CostBreakdown+                  (fromIntegral (totalInput - 3000) * input * inputFactor / 1000000)+                  (100 * output * outputFactor / 1000000)+                  (1000 * readRate * inputFactor / 1000000)+                  (2000 * writeRate * inputFactor / 1000000)+              bill.basis.estimateReasons @?= Set.empty,       testCase "Responses preserves exactly one identical prefix across fresh questions" $ do         a <- mapped (systemUser "private prefix" "first") short         b <- mapped (systemUser "private prefix" "second") short
test/ResponsesAssemblerSpec.hs view
@@ -2,6 +2,7 @@  module ResponsesAssemblerSpec (tests) where +import Baikai.Api (Api (OpenAIResponses)) import Baikai.Content qualified as C import Baikai.Provider.OpenAI.Responses.Assembler qualified as A import Baikai.StopReason (StopReason (..))@@ -41,7 +42,9 @@         A.terminalReason s @?= Just ToolUse         A.assembledContent s           @?= V.fromList-            [C.AssistantToolCall (C.ToolCall "call_a" "lookup" (object ["a" .= (1 :: Int)])), C.AssistantToolCall (C.ToolCall "call_b" "lookup" (object ["b" .= (2 :: Int)]))]+            [ replayedCall "item_a" "call_a" "a" 1 "{\"a\":1}",+              replayedCall "item_b" "call_b" "b" 2 "{\"b\":2}"+            ]         [n | E.ToolCallStart (E.IndexPayload n) <- events] @?= [0, 1]         [n | E.ToolCallEnd (E.ToolCallEndPayload n _) <- events] @?= [0, 1]         assertBool "second block waits for first end" (case drop 2 events of E.ToolCallEnd _ : E.ToolCallStart _ : _ -> True; _ -> False),@@ -151,3 +154,9 @@  reasoning :: Value reasoning = object ["type" .= ("reasoning" :: Text), "id" .= ("rs" :: Text), "summary" .= ([] :: [Value]), "encrypted_content" .= ("opaque" :: Text), "future_field" .= object ["keep" .= True]]++replayedCall :: Text -> Text -> Key -> Int -> Text -> C.AssistantContent+replayedCall ident cid key n raw =+  C.withOutputItemReplay+    (C.OutputItemReplay OpenAIResponses "configured-model" (call ident cid raw "completed"))+    (C.AssistantToolCall (C.ToolCall cid "lookup" (object [key .= n])))
test/ResponsesEvidenceSpec.hs view
@@ -11,11 +11,14 @@ import Baikai.Trace (withTraceStreamWith) import Baikai.Trace.Event qualified as Trace import Baikai.Trace.Sink (TraceSink (..))+import Control.Concurrent (forkFinally, killThread) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)-import Control.Exception (bracket, finally)+import Control.Exception (AsyncException (ThreadKilled), bracket, finally, fromException) import Control.Lens ((&), (.~))+import Control.Monad (forM_) import Data.Aeson (Value (..), object, (.=)) import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KM import Data.ByteString (ByteString) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as LBS@@ -43,6 +46,15 @@         ev.providerRequestId @?= Observed "req-wire"         ev.responseId @?= Observed "response-wire"         ev.requestCommitment @?= commitmentDigest body+        ev.requestConfiguration @?= configurationDigest body+        case configurationProjection body of+          Object config -> do+            KM.lookup "instructions" config @?= Nothing+            case KM.lookup "input" config of+              Just (Array parts) ->+                (parts V.!? 0) @?= Just (object ["role" .= String "developer", "type" .= Null, "chars" .= (30 :: Int)])+              _ -> assertFailure "missing shaped input"+          _ -> assertFailure "missing shaped configuration"         ev.strength @?= EvidenceModelObserved         ev.usage @?= Unobserved         case V.toList response.message.content of@@ -55,13 +67,14 @@         b <- proof split         a.responseCommitment @?= b.responseCommitment         split.message.content @?= whole.message.content,-      testCase "minimal effort is refused before transport with strict evidence" $ do-        (response, body) <- replay 200 [wire success] (strictOptions & #thinking .~ Just ThinkingMinimal)-        assertBool "strict adjustment refused" (responseError response /= Nothing)-        body @?= Null-        ev <- proof response-        ev.status @?= CallFailed-        ev.observedModel @?= Unobserved,+      testCase "none and minimal are refused before transport with strict evidence" $+        forM_ [ThinkingNone, ThinkingMinimal] $ \effort -> do+          (response, body) <- replay 200 [wire success] (strictOptions & #thinking .~ Just effort)+          assertBool "strict adjustment refused" (responseError response /= Nothing)+          body @?= Null+          ev <- proof response+          ev.status @?= CallFailed+          ev.observedModel @?= Unobserved,       testCase "local request validation still produces a strict evidence record" $ do         (response, body) <- replay 200 [wire success] (strictOptions & #seed .~ Just 7)         assertBool "unsupported option refused" (responseError response /= Nothing)@@ -103,18 +116,26 @@         ev.responseId @?= Unobserved         ev.usage @?= Unobserved,       testCase "strict trace cancellation records one abort and releases the worker" $ do+        ready <- newEmptyMVar         closed <- newEmptyMVar         forever <- newEmptyMVar         captured <- newIORef ([] :: [Trace.TraceEvent])         recorded <- newEmptyMVar-        let blocked _ _ _ _ emit = (emit (Right added) >> emit (Right deltaFrame) >> takeMVar forever) `finally` putMVar closed ()+        outcome <- newEmptyMVar+        let blocked _ _ _ _ emit =+              (emit (Right added) >> emit (Right deltaFrame) >> putMVar ready () >> takeMVar forever)+                `finally` putMVar closed ()             save () e = do               atomicModifyIORef' captured (\xs -> (e : xs, ()))               case e of Trace.CallEvidence {} -> putMVar recorded (); _ -> pure ()             sink = TraceSink (Fold.foldlM' save (pure ()))         reg <- registryFor blocked-        result <- timeout 100000 (Stream.toList (withTraceStreamWith reg sink openai_gpt_6_astra emptyContext strictOptions))-        assertBool "consumer was cancelled" (case result of Nothing -> True; _ -> False)+        let collect = Stream.toList (withTraceStreamWith reg sink openai_gpt_6_astra emptyContext strictOptions)+        bracket (forkFinally collect (putMVar outcome)) killThread $ \consumer -> do+          timeout 2000000 (takeMVar ready) >>= (@?= Just ())+          killThread consumer+          result <- timeout 2000000 (takeMVar outcome)+          fmap (either fromException (const Nothing)) result @?= Just (Just ThreadKilled)         timeout 1000000 (takeMVar closed) >>= (@?= Just ())         timeout 1000000 (takeMVar recorded) >>= (@?= Just ())         events <- readIORef captured@@ -136,7 +157,8 @@ replay status chunks opts = do   sent <- newIORef Null   reg <- registryFor (byteDriver sent status chunks)-  response <- completeRequestWith reg openai_gpt_6_astra emptyContext opts+  let m = openai_gpt_6_astra & #compat .~ CompatOpenAIResponses (openaiResponsesCompatFor openai_gpt_6_astra & #systemPromptInInput .~ True)+  response <- completeRequestWith reg m (systemUser "safe prefix" "question") opts   body <- readIORef sent   pure (response, body) 
+ test/ResponsesReplayProbe.hs view
@@ -0,0 +1,191 @@+{-# LANGUAGE OverloadedRecordDot #-}++module ResponsesReplayProbe (tests) where++import Baikai hiding (model)+import Baikai.Provider.OpenAI.Internal.Stream (SseDriver)+import Baikai.Provider.OpenAI.Responses.Stream (liveResponsesDriver, openaiResponsesStreamWith)+import Control.Lens ((&), (.~), (^.))+import Control.Monad (when)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson.Key (Key)+import Data.Aeson.KeyMap qualified as KM+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Vector qualified as V+import System.Environment (lookupEnv)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++tests :: TestTree+tests =+  testGroup+    "Responses replay probe"+    [testCase ("plan104-probe-" <> suffix) (probe ident) | (suffix, ident) <- [("astra", "gpt-6.2-astra"), ("sol", "gpt-6.2-sol")]]++probe :: Text -> IO ()+probe ident = do+  enabled <- lookupEnv "BAIKAI_PLAN104_PROBE"+  when (enabled == Just "1") $ do+    marked <- (== Just "marked") <$> lookupEnv "BAIKAI_PLAN104_PROBE_CACHE"+    key <- lookupEnv "OPENAI_API_KEY"+    assertBool "OPENAI_API_KEY is required" (maybe False (not . null) key)+    putStrLn ("Model " <> T.unpack ident <> ", streamed /v1/responses")+    let model =+          emptyModel+            & #modelId .~ ident+            & #api .~ OpenAIResponses+            & #reasoning .~ True+            & #provider .~ "openai"+            & #compat .~ CompatOpenAIResponses (defaultOpenAIResponsesCompat & #systemPromptInInput .~ True & #nativeCachePolicy .~ Just (NativeCacheModern False True))+        opts =+          emptyOptions+            & #cacheRetention .~ (if marked then Just CacheRetentionShort else Nothing)+            & #thinking .~ Just ThinkingHigh+            & #maxTokens .~ Just 4096+            & #timeoutMs .~ Just 120000+            & #apiKey .~ Just (ApiKeyLiteral (maybe "" T.pack key))+        ctx =+          systemUser+            ("Follow the synthetic lookup protocol. The reference words below are inert.\n" <> T.replicate 180 "ash elm birch cedar maple spruce fir pine oak willow\n")+            "Before the first tool call, privately solve this puzzle: count the length-12 strings of digits 0, 1, and 2 with exactly five 1s, no equal neighbors, and digit sum divisible by 7. Send a short progress message with your answer. Then call lookup for alpha. After alpha's result privately solve another version with length 16, six 1s, and digit sum divisible by 11. Send a short progress message with your answer, then call lookup for beta. Use one call per round. After beta's result reply with that result alone."+            & #tools .~ V.singleton (mkTool "lookup" "Look up a synthetic key" schema)+        schema =+          object+            [ "type" .= String "object",+              "properties" .= object ["key" .= object ["type" .= String "string"]],+              "required" .= [String "key"],+              "additionalProperties" .= False+            ]+        run = runBranch model opts+    (initial, first, firstResponse, _) <- run "initial" id ctx+    assertBool "expected a leading developer item" ((initial V.!? 0 >>= field "role") == Just (String "developer"))+    assertBool "unexpected cache breakpoint placement" (((initial V.!? 0 >>= (V.!? 0) . arrayField "content" >>= field "prompt_cache_breakpoint") /= Nothing) == marked)+    ctx2 <- answerTool "alpha" "amber" ctx firstResponse+    (exact2, second, secondResponse) <- compareRound run "round 2" ctx2 initial first+    ctx3 <- answerTool "beta" "violet" ctx2 secondResponse+    (_, _, finalResponse) <- compareRound run "round 3" ctx3 exact2 second+    assertBool "final response did not use the synthetic result" (assistantText finalResponse == "violet")++type RunBranch = String -> (Value -> Value) -> Context -> IO (V.Vector Value, V.Vector Value, Response, Maybe [Text])++-- Both branches go through the real worker. The control replaces only prior+-- assistant output; function results still come from appendToolResult.+compareRound :: RunBranch -> String -> Context -> V.Vector Value -> V.Vector Value -> IO (V.Vector Value, V.Vector Value, Response)+compareRound run label ctx prefix output = do+  let reasoning = V.filter ((== Just (String "reasoning")) . field "type") output+  assertBool "expected a new reasoning item in the preceding round" (not (V.null reasoning))+  (projected, _, _, adapterRemovals) <- run (label <> " adapter") id ctx+  assertBool "history changed the preceding caller prefix" (V.take 2 projected == V.take 2 prefix)+  let exact = prefix <> output <> V.drop (V.length projected - 1) projected+  putStrLn (label <> " replay comparison " <> show (comparison exact projected))+  (original, originalOutput, originalResponse, originalRemovals) <- run (label <> " original") (setInput exact) ctx+  assertBool "registered adapter changed a prior output item" (projected == original)+  assertBool "provider removed submitted reasoning" (all (maybe True null) [adapterRemovals, originalRemovals])+  when (any (== Nothing) [adapterRemovals, originalRemovals]) $ do+    let edited = exact V.// [(1, object ["role" .= String "user", "content" .= String "Edited synthetic prefix. Continue the lookup protocol."])]+    (_, _, _, calibration) <- run (label <> " edited prefix") (setInput edited) ctx+    assertBool "reasoning-removal diagnostic could not be calibrated" (maybe False (elem "prefix_mismatch") calibration)+  pure (original, originalOutput, originalResponse)++-- Intentionally report only counts and equality flags.+comparison :: V.Vector Value -> V.Vector Value -> [(String, Bool)]+comparison original projected =+  [ ("count", V.length original == V.length projected),+    ("typesInOrder", map (field "type") left == map (field "type") right),+    ("itemIDs", map (field "id") left == map (field "id") right),+    ("contentParts", map (field "content") left == map (field "content") right),+    ("phase", map (field "phase") left == map (field "phase") right),+    ("argumentStrings", map (field "arguments") left == map (field "arguments") right),+    ("reasoningItems", reasoning left == reasoning right),+    ("input", original == projected)+  ]+  where+    left = V.toList original+    right = V.toList projected+    reasoning = filter ((== Just (String "reasoning")) . field "type")++runBranch :: Model -> Options -> RunBranch+runBranch model opts label patch ctx = do+  requestRef <- newIORef Null+  terminalRef <- newIORef Null+  let capture :: SseDriver+      capture env headers body meta emit = do+        let wire = patch body+        writeIORef requestRef wire+        liveResponsesDriver env headers wire meta $ \frame -> do+          case frame of+            Right value+              | field "type" value == Just (String "response.completed") ->+                  writeIORef terminalRef (maybe Null id (field "response" value))+            _ -> pure ()+          emit frame+  reg <- newProviderRegistryFrom [apiProvider OpenAIResponses (openaiResponsesStreamWith capture)]+  response <- completeRequestWith reg model ctx opts+  request <- readIORef requestRef+  terminal <- readIORef terminalRef+  assertBool "probe must use stateless history" (field "store" request == Just (Bool False) && field "previous_response_id" request == Nothing)+  let input = arrayField "input" request+  removals <- summarize (T.unpack model.modelId <> " " <> label) input terminal+  case responseError response of+    Just err -> assertFailure (label <> ": " <> show (err ^. #category) <> " " <> show (err ^. #httpStatus))+    Nothing -> assertBool (label <> " did not complete") (terminal /= Null)+  pure (input, arrayField "output" terminal, response, removals)++summarize :: String -> V.Vector Value -> Value -> IO (Maybe [Text])+summarize label input terminal = do+  let reasoningIds = [ident | item <- V.toList input, field "type" item == Just (String "reasoning"), Just ident <- [field "id" item]]+      diagnostics = field "input_transformations" terminal+      removals = case diagnostics of+        Just (Array entries) ->+          Just+            [ if reason `elem` knownReasons then reason else "unknown"+            | item <- V.toList entries,+              field "id" item `elem` map Just reasoningIds,+              let reason = case field "reason" item of Just (String t) -> t; _ -> "unknown"+            ]+        _ -> Nothing+      knownReasons = ["organization_mismatch", "end_user_mismatch", "model_mismatch", "prefix_mismatch", "turn_boundary"]+      counts = [V.length (V.filter ((== Just (String kind)) . field "type") (arrayField "output" terminal)) | kind <- ["reasoning", "message", "function_call"]]+      usage = field "usage" terminal+      inputTokens = usage >>= field "input_tokens"+      cachedTokens = usage >>= field "input_tokens_details" >>= field "cached_tokens"+  putStrLn $+    label+      <> ": submitted reasoning "+      <> show (length reasoningIds)+      <> ", diagnostics present "+      <> show (diagnostics /= Nothing)+      <> ", matched removal reasons "+      <> show removals+      <> ", output counts (reasoning, message, call) "+      <> show counts+      <> ", input tokens "+      <> show inputTokens+      <> ", cached tokens "+      <> show cachedTokens+  pure removals++answerTool :: Text -> Text -> Context -> Response -> IO Context+answerTool key result ctx response = do+  length [() | AssistantToolCall _ <- V.toList response.message.content] @?= 1+  appendToolResult ctx response $ \call -> do+    assertBool "unexpected synthetic tool invocation" (call.name == "lookup" && call.arguments == object ["key" .= key])+    pure (toolResultText result)++assistantText :: Response -> Text+assistantText resp = T.concat [t | AssistantText (TextContent t) <- V.toList resp.message.content]++field :: Key -> Value -> Maybe Value+field k (Object fields) = KM.lookup k fields+field _ _ = Nothing++arrayField :: Key -> Value -> V.Vector Value+arrayField k value = case field k value of+  Just (Array xs) -> xs+  _ -> V.empty++setInput :: V.Vector Value -> Value -> Value+setInput input (Object props) = Object (KM.insert "input" (Array input) props)+setInput _ body = body
test/ResponsesSpec.hs view
@@ -3,7 +3,7 @@ module ResponsesSpec (tests) where  import Baikai hiding (model, schema)-import Baikai.Models.Generated (openai_gpt_6_1_sol, openai_gpt_6_astra, openai_gpt_6_luna, openai_gpt_6_sol)+import Baikai.Models.Generated (openai_gpt_6_1_sol, openai_gpt_6_2_astra, openai_gpt_6_2_sol, openai_gpt_6_astra, openai_gpt_6_luna, openai_gpt_6_sol) import Baikai.Provider.OpenAI.Responses.Request qualified as R import Control.Lens ((&), (.~)) import Control.Monad (forM_)@@ -44,6 +44,47 @@           items !! 1 @?= reasoningItem           field "call_id" (items !! 2) @?= Just (String "call_7")           field "call_id" (items !! 3) @?= Just (String "call_7"),+      testCase "both GPT-6.2 bindings put reusable instructions first with default or marked caching" $+        forM_ [openai_gpt_6_2_astra, openai_gpt_6_2_sol] $ \m -> do+          m.api @?= OpenAIResponses+          let ctx = systemUser "stable" "question"+              developer fields = object ["role" .= String "developer", "content" .= [object (["type" .= String "input_text", "text" .= String "stable"] <> fields)]]+              sample = emptyOptions & #temperature .~ Just 0.5 & #topP .~ Just 0.8+          forM_ [ThinkingNone, ThinkingMinimal] $ \effort -> do+            ordinary <- mapped m ctx (sample & #thinking .~ Just effort)+            field "instructions" ordinary.requestBody @?= Nothing+            field "temperature" ordinary.requestBody @?= Nothing+            field "top_p" ordinary.requestBody @?= Nothing+            field "reasoning" ordinary.requestBody @?= Just (object ["effort" .= String "low"])+            ordinary.translation.adjustments @?= [EffortClamped effort "low", SamplingDroppedUnsupportedModel ["temperature", "top_p"]]+            take 1 (inputItems ordinary) @?= [developer []]+          forM_ [(CacheRetentionShort, "30m"), (CacheRetentionLong, "12h")] $ \(duration, ttl) -> do+            marked <- mapped m ctx (emptyOptions & #cacheRetention .~ Just duration)+            field "instructions" marked.requestBody @?= Nothing+            field "prompt_cache_options" marked.requestBody @?= Just (object ["ttl" .= String ttl])+            take 1 (inputItems marked) @?= [developer ["prompt_cache_breakpoint" .= object ["mode" .= String "explicit"]]]+          absent <- mapped m (contextOf [user "question"]) emptyOptions+          field "instructions" absent.requestBody @?= Nothing+          map (field "role") (inputItems absent) @?= [Just (String "user")],+      testCase "legacy compatibility JSON retains top-level default instructions" $ do+        let old = object ["supportsSamplingParameters" .= True, "supportsLongCacheRetention" .= True, "supportsPromptCacheOptions" .= False]+        compat <- either assertFailure pure (Aeson.eitherDecode (Aeson.encode old))+        compat @?= defaultOpenAIResponsesCompat+        req <- mapped (model & #compat .~ CompatOpenAIResponses compat) (systemUser "legacy" "question") emptyOptions+        field "instructions" req.requestBody @?= Just (String "legacy")+        map (field "role") (inputItems req) @?= [Just (String "user")],+      testCase "generated GPT-6.2 routes strict answer schemas through text.format" $+        forM_ [openai_gpt_6_2_astra, openai_gpt_6_2_sol] $ \m -> do+          let pong =+                object+                  [ "type" .= String "object",+                    "properties" .= object ["answer" .= object ["type" .= String "string", "enum" .= [String "pong"]]],+                    "required" .= [String "answer"],+                    "additionalProperties" .= False+                  ]+              opts = emptyOptions & #responseFormat .~ Just (JsonSchema (jsonSchemaFormat "pong_answer" pong & #strict .~ True))+          req <- mapped m (contextOf [user "answer"]) opts+          field "text" req.requestBody @?= Just (object ["format" .= object ["type" .= String "json_schema", "name" .= String "pong_answer", "schema" .= pong, "strict" .= True]]),       testCase "stateless request carries text, image, system, cap and metadata" $ do         let ctx =               (systemUser "system instruction" "hello")
test/ResponsesStreamSpec.hs view
@@ -12,8 +12,11 @@ import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Exception (finally) import Control.Lens ((&), (.~), (^.))+import Control.Monad (forM_) import Data.Aeson (Value (..), object, (.=))+import Data.Aeson qualified as Aeson import Data.Aeson.KeyMap qualified as KM+import Data.Aeson.Types (parseEither) import Data.IORef (newIORef, readIORef, writeIORef) import Data.Set qualified as Set import Data.Text (Text)@@ -135,6 +138,71 @@                 _ -> assertFailure "missing function output"             _ -> assertFailure "missing input"           _ -> assertFailure "expected two requests",+      testCase "persisted history retains the entire input prefix over two tool rounds" $ do+        sent <- newIORef []+        let m = model & #compat .~ CompatOpenAIResponses (defaultOpenAIResponsesCompat & #systemPromptInInput .~ True)+            firstCall = toolItem "fc_1" "call_1" "{ \"key\" : 1 }"+            secondCall = toolItem "fc_2" "call_2" "{ \"key\" : 2 }"+            progress = object ["type" .= String "message", "id" .= String "msg_progress", "role" .= String "assistant", "status" .= String "completed", "phase" .= String "commentary", "content" .= [part "working", part " on it"]]+            reasoning = object ["type" .= String "reasoning", "id" .= String "rs_2", "summary" .= ([] :: [Value]), "encrypted_content" .= String "opaque"]+            initial = systemUser "stable" "find it" & #tools .~ V.singleton (mkTool "lookup" "lookup" (object ["type" .= String "object"]))+            step output context = do+              let stream = openaiResponsesStreamWith $ \_ _ body _ emit -> do+                    previous <- readIORef sent+                    writeIORef sent (previous <> [body])+                    emit (Right (terminalOutput output))+              response <- streamingComplete stream m context options+              either assertFailure pure (parseEither responseFromJSON (responseToJSON response))+            append expected ctx response =+              appendToolResult ctx response $ \tc -> do+                tc.id_ @?= expected+                pure (toolResultText ("result-" <> expected))+        first <- step [progress, firstCall] initial+        progressBlock <- case V.toList first.message.content of+          [block@(AssistantText (TextContent "working on it")), AssistantToolCall _] -> pure block+          _ -> assertFailure "missing text and function call"+        fmap (.outputReplayItem) (outputItemReplay progressBlock) @?= Just progress+        ctx2 <- append "call_1" initial first+        second <- step [reasoning, secondCall] ctx2+        ctx3 <- append "call_2" ctx2 second+        final <- step [item "hello"] ctx3+        final.message.stopReason @?= Stop+        requests <- readIORef sent+        case map requestInput requests of+          [a, b, c] -> do+            b @?= a <> [progress, firstCall, toolOutput "call_1"]+            c @?= b <> [reasoning, secondCall, toolOutput "call_2"]+          _ -> assertFailure "expected three requests",+      testCase "inconsistent or foreign output replay is refused before transport" $ do+        let raw = toolItem "item" "call" "{ \"key\": 1 }"+            scope = OutputItemReplay OpenAIResponses model.modelId raw+            tool = AssistantToolCall (ToolCall "call" "lookup" (object ["key" .= Number 1]))+            edited = AssistantToolCall (ToolCall "call" "lookup" (object ["key" .= Number 2]))+            forbidden _ _ _ _ _ = assertFailure "driver must not run"+        forM_ [(scope, edited), (scope {outputReplayApi = AnthropicMessages}, tool), (scope {outputReplayModel = "foreign"}, tool), (scope {outputReplayItem = Null}, tool)] $ \(state, block) -> do+          let ctx = addResponse (emptyResponse & #message . #content .~ V.singleton (withOutputItemReplay state block)) emptyContext+          assertBool "Show must omit the provider item" (show (withOutputItemReplay state block) == show block)+          failed <- streamingComplete (openaiResponsesStreamWith forbidden) model ctx options+          fmap (^. #category) (responseError failed) @?= Just InvalidRequest,+      testCase "legacy assistant blocks decode without output replay and keep their wire shapes" $ do+        let text = object ["type" .= String "assistant_text", "data" .= object ["text" .= String "legacy"]]+            call = object ["type" .= String "assistant_tool_call", "data" .= object ["id" .= String "old_call", "name" .= String "lookup", "arguments" .= object []]]+        blocks <- either assertFailure pure (Aeson.eitherDecode (Aeson.encode [text, call]))+        map outputItemReplay blocks @?= [Nothing, Nothing]+        Aeson.toJSON blocks @?= Aeson.toJSON [text, call],+      testCase "refusal, incomplete response and provider failure keep their terminal classifications" $ do+        let partial = object ["type" .= String "function_call", "id" .= String "fc_partial", "call_id" .= String "call_partial", "name" .= String "lookup", "arguments" .= String "{}", "status" .= String "incomplete"]+            started = object ["type" .= String "response.output_item.added", "output_index" .= Number 0, "item" .= partial]+            incomplete = object ["type" .= String "response.incomplete", "response" .= object ["output" .= [partial], "incomplete_details" .= object ["reason" .= String "max_output_tokens"]]]+            failed = object ["type" .= String "response.failed", "response" .= object ["error" .= object ["code" .= String "rate_limit_exceeded", "message" .= String "busy"]]]+            refusal = terminalOutput [object ["type" .= String "message", "id" .= String "msg_refusal", "role" .= String "assistant", "status" .= String "completed", "content" .= [object ["type" .= String "refusal", "refusal" .= String "declined"]]]]+        forM_ [([refusal], Stop, Nothing), ([started, incomplete], Length, Nothing), ([started, failed], ErrorReason, Just RateLimited)] $ \(frames, reason, category) -> do+          dispatched <- newIORef False+          reg <- newProviderRegistryFrom [apiProvider OpenAIResponses (openaiResponsesStreamWith (driver frames))]+          (_, response) <- runToolLoopWith reg 3 (const (writeIORef dispatched True >> pure (toolResultText "unexpected"))) model emptyContext options+          readIORef dispatched >>= (@?= False)+          response.message.stopReason @?= reason+          fmap (^. #category) (responseError response) @?= category,       testCase "evidence commits to the exact outgoing request and observed header" $ do         sent <- newIORef Null         let capturing _ _ body meta emit = do@@ -191,3 +259,22 @@  usageStarted :: Value usageStarted = object ["type" .= ("response.created" :: Text), "response" .= object ["id" .= ("resp_usage" :: Text), "usage" .= object ["input_tokens" .= (15000 :: Int), "input_tokens_details" .= object ["cached_tokens" .= (12000 :: Int)]]]]++part :: Text -> Value+part t = object ["type" .= String "output_text", "text" .= t, "annotations" .= ([] :: [Value])]++toolItem :: Text -> Text -> Text -> Value+toolItem ident call args =+  object ["type" .= String "function_call", "id" .= ident, "call_id" .= call, "name" .= String "lookup", "arguments" .= args, "status" .= String "completed"]++toolOutput :: Text -> Value+toolOutput call = object ["type" .= String "function_call_output", "call_id" .= call, "output" .= ("result-" <> call)]++terminalOutput :: [Value] -> Value+terminalOutput items = object ["type" .= String "response.completed", "response" .= object ["output" .= items]]++requestInput :: Value -> [Value]+requestInput (Object obj) = case KM.lookup "input" obj of+  Just (Array xs) -> V.toList xs+  _ -> []+requestInput _ = []