Something went wrong. Try again.
Codex-related libraries and tools
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
open! Hermetic
let ( let* ) = Result.bind
module F = Json.Value.Find
let count name json = match F.int [ name ] json with | Some n when n >= 0 -> Ok n | Some _ | None -> Fmt.error "codex usage: invalid %s" name
let usage json = let* input = count "input_tokens" json in let* cache_read = count "cached_input_tokens" json in let* output = count "output_tokens" json in if cache_read > input then Error "codex usage: cached input exceeds input" else Ok (Llm.Usage.v ~input:(input - cache_read) ~cache_read ~output ())
let event (total, steps) line = if String.trim line = "" then Ok (total, steps) else let* json = Result.map_error (fun e -> Fmt.str "codex event: %a" Json.Error.pp e) (Json.Value.of_string line) in match F.string [ "type" ] json with | None -> Error "codex event: missing type" | Some "turn.completed" -> ( match Json.Value.find [ "usage" ] json with | None -> Error "codex turn.completed: missing usage" | Some json -> let* u = usage json in Ok (Llm.Usage.add total u, steps + 1)) | Some _ -> Ok (total, steps)
let metrics lines = match List.fold_left (fun acc line -> let* acc = acc in event acc line) (Ok (Llm.Usage.zero, 0)) lines with | result -> result | exception Invalid_argument e -> Fmt.error "codex usage: %s" e
let failed kind message = Llm.Agent.Failed (Llm.Error.v ~kind message)
let stop ~status ~answer = match status with | Error why -> failed Llm.Error.Provider why | Ok () -> ( match answer with | None -> failed Llm.Error.Provider "codex produced no answer" | Some text -> ( match Json.Value.of_string text with | Ok json -> Llm.Agent.Answered json | Error e -> failed Llm.Error.Decode (Fmt.str "codex answer: %a" Json.Error.pp e)))
let environment bindings = let contains word name = let n = String.length word in let rec loop i = i + n <= String.length name && (String.sub name i n = word || loop (i + 1)) in loop 0 in let safe binding = match String.index_opt binding '=' with | None -> false | Some i -> let name = String.uppercase_ascii (String.sub binding 0 i) in not (List.exists (fun word -> contains word name) [ "KEY"; "TOKEN"; "SECRET"; "PASSWORD" ]) in Array.of_list (List.filter safe bindings)