//// The OpenCode client identity Zen's free tier asks for. //// //// Zen answers a `-free` model only for a request shaped like the one OpenCode //// ships: the user agent its binary launches with, its session and project //// headers, a session id in the shape it mints, streaming, and the tool names //// its agent sends (the last two belong to the wire module). A paid model goes //// out with the profile's own key and none of that. import albedo_bytes/digest import albedo_bytes/scalars import gleam/string /// OpenCode's binary launches with /// `--user-agent=opencode///`. The channel, /// version and artifact only have to name a release the gateway knows; a /// refusal that asks for a newer one is answered by raising the version. const opencode_channel = "latest" const opencode_version = "2.0.27" const opencode_artifact = "cli" /// The characters of a session id's tail, in OpenCode's order. const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" /// The user agent OpenCode's own binary sends. pub fn user_agent() -> String { "opencode/" <> opencode_channel <> "/" <> opencode_version <> "/" <> opencode_artifact } /// Whether `model`'s id says the free tier serves it. Zen also serves a few /// models free without saying so in the id, `big-pickle` among them; the /// extension covers those by using the free lane whenever a profile carries /// no credential. pub fn free(model: String) -> Bool { string.contains(model, "-free") } /// The session id for the session seeded by `seed`. Zen routes a conversation /// and finds its cached prefix by this id, so it is derived from the session /// rather than minted per request: one albedo session keeps one Zen session. /// /// The shape is OpenCode's, and the shape is what the gateway checks: `ses_`, /// twelve lowercase hex, then fourteen base62. OpenCode's twelve hex encode a /// millisecond clock and a per-millisecond counter, bitwise inverted, which /// leaves a counter of one ending in `ffe`. The gateway reads that counter /// back and refuses one outside its first sixty-four, so this id ends in /// `ffe` too. The clock half is not inspected, so a hash stands in for it. pub fn session(seed: String) -> String { let clock = digest.sha1(<>) |> digest.hex |> scalars.take(9) let tail = digest.sha256(<>) |> base62(14, "") "ses_" <> clock <> "ffe" <> tail } /// The project id OpenCode's requests carry: the SHA-1 of the directory it /// runs in, as forty lowercase hex characters. Albedo uses its home. pub fn project(home: String) -> String { digest.sha1(<>) |> digest.hex } /// The first `count` bytes of `bytes` as base62, one character per byte. A /// digest is already uniform, so mapping its bytes without rejection keeps /// the characters close to uniform. fn base62(bytes: BitArray, count: Int, acc: String) -> String { case count, bytes { 0, _ -> acc _, <> -> base62( rest, count - 1, acc <> scalars.drop(alphabet, byte % 62) |> scalars.take(1), ) _, _ -> acc } }