Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
6.1 kB 202 lines
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203// Copilot's and OpenCode Go's Claude routes serve a repeated history from// their prompt cache only when the request marks it, and the ledger records// what a call asked to cache from `cache_marks` rather than from the body.// The fake provider never checks the two agree, so this does.import albedo/harness/extensions/github_copilot/wire as copilotimport albedo/harness/extensions/opencode_go/wire as opencodeimport albedo/openai_apiimport albedo/openai_api/typesimport gleam/dynamic/decodeimport gleam/jsonimport gleam/listimport gleam/option.{type Option, None, Some}import gleam/resultimport gleam/string_tree.{type StringTree}
@external(erlang, "albedo_openai_transport", "materialize")fn materialize(body: StringTree) -> Result(String, String)
fn copilot_client() -> copilot.Client { copilot.client("https://api.githubcopilot.com", "token", "session")}
fn opencode_client() -> opencode.Client { opencode.client( "https://opencode.ai/inference/go/v1", "key", "session", "org", )}
fn tool(name: String) -> types.Tool { types.Tool(name, name, json.object([]), False)}
/// What `runtime.upstream` hands the wire: a request carrying the model's/// catalogued output ceiling.fn limited(request: types.Request) -> types.Request { types.Request( ..request, max_output_tokens: option.or(request.max_output_tokens, Some(64_000)), )}
fn requests() -> List(types.Request) { [ types.Request( "claude-haiku-5-5", Some("be brief"), [types.User("a"), types.Assistant("b"), types.User("c")], [tool("read"), tool("bash")], None, types.defaults, ), types.Request( "claude-haiku-5-5", None, [types.User("hi")], [], None, types.defaults, ), // The start every session shares ends a cached prefix of its own. types.Request( "claude-haiku-5-5", Some("shared prompt\n\nworkspace context"), [types.User("a")], [tool("read")], None, types.Options(..types.defaults, shared_instructions: 13), ), // A one-off request, such as a summary, asks for no cache write at all. types.Request( "claude-haiku-5-5", Some("summarize"), [types.User("a"), types.Assistant("b"), types.User("c")], [tool("read")], None, types.Options(..types.defaults, cache: False), ), ]}
/// A block's `cache_control` lease in seconds, when it carries one.fn marker_decoder() -> decode.Decoder(Option(Int)) { let ttl = { use ttl <- decode.optional_field("ttl", "5m", decode.string) decode.success(case ttl { "1h" -> 3600 _ -> 300 }) } decode.optional_field( "cache_control", None, decode.optional(ttl), decode.success, )}
fn optional_markers(field: String) -> decode.Decoder(List(Option(Int))) { decode.optional_field( field, [], decode.list(marker_decoder()), decode.success, )}
/// The cache breakpoints an encoded Messages body carries, named the way the/// ledger names them: a marker anywhere but the final block of the final turn/// matches no declared span, so a stray one fails the comparison.fn encoded_marks(text: String) -> Result(List(#(types.CacheSpan, Int)), Nil) { use value <- result.try( json.parse(text, decode.dynamic) |> result.replace_error(Nil), ) let markers = fn(field) { decode.run(value, optional_markers(field)) |> result.unwrap([]) |> option.values } use messages <- result.try( decode.run( value, decode.at( ["messages"], decode.list(decode.at(["content"], decode.list(marker_decoder()))), ), ) |> result.replace_error(Nil), ) let last_message = list.length(messages) - 1 let input = messages |> list.index_map(fn(blocks, at) { let last_block = list.length(blocks) - 1 list.index_map(blocks, fn(ttl, block) { case ttl { None -> [] Some(ttl) -> [ case at == last_message && block == last_block { True -> #(types.InputSpan(last_message), ttl) False -> #(types.InputSpan(-1), ttl) }, ] } }) }) |> list.flatten |> list.flatten Ok( list.flatten([ list.map(markers("tools"), fn(ttl) { #(types.ToolsSpan, ttl) }), case markers("system") { [shared, whole] -> [ #(types.SharedSystemSpan, shared), #(types.SystemSpan, whole), ] others -> list.map(others, fn(ttl) { #(types.SystemSpan, ttl) }) }, input, ]), )}
fn declared_marks( marks: List(types.CacheMark),) -> List(#(types.CacheSpan, Int)) { list.map(marks, fn(mark) { #(mark.through, mark.ttl_seconds) })}
fn body_text(exchange: openai_api.Exchange) -> String { let assert Ok(text) = materialize(exchange.body) text}
/// Copilot writes hour-long entries, as its Messages route was measured to,/// and the ledger must name exactly the breakpoints the body carries.pub fn copilot_messages_marks_match_the_body_test() -> Nil { use request <- list.each(requests()) let assert Ok(exchange) = copilot.encode_messages(copilot_client(), limited(request)) let assert Ok(encoded) = encoded_marks(body_text(exchange)) assert declared_marks(copilot.cache_marks(request)) == encoded assert list.all(encoded, fn(mark) { mark.1 == 3600 }) assert { encoded == [] } == !request.options.cache}
/// OpenCode Go keeps five-minute entries whatever lease it is asked for, so a/// marked request asks for the default one and the ledger records it.pub fn opencode_messages_marks_use_the_default_lease_test() -> Nil { use request <- list.each(requests()) let assert Ok(exchange) = opencode.encode_messages( opencode_client().connection, opencode.headers(opencode_client()), limited(request), ) let assert Ok(encoded) = encoded_marks(body_text(exchange)) assert declared_marks(opencode.cache_marks(request)) == encoded assert list.all(encoded, fn(mark) { mark.1 == 300 })}