From 667f01e50bc4e1b8232decc66f76a136a929d628 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Wed, 11 Nov 2026 07:32:40 -0500 Subject: [PATCH] fix(opencode-zen): choose the free lane for each request --- robot-docs/models.md | 10 ++ .../extensions/opencode_zen/extension.gleam | 32 ++----- .../extensions/opencode_zen/wire.gleam | 20 +++- .../albedo_opencode_zen_test_support.erl | 92 +++++++++++++++++++ test/harness/opencode_zen_test.gleam | 12 ++- 5 files changed, 138 insertions(+), 28 deletions(-) create mode 100644 test/harness/albedo_opencode_zen_test_support.erl diff --git a/robot-docs/models.md b/robot-docs/models.md index 1236363a7..3b5cc96ac 100644 --- a/robot-docs/models.md +++ b/robot-docs/models.md @@ -219,6 +219,16 @@ When an entry matches a catalogued model, `ModelInfo.context_tokens` becomes `co Antigravity is not on models.dev, and its model ids and required `model_enum` labels change server-side. The `antigravity` extension therefore contributes its own catalog. It asks Cloud Code Assist `fetchAvailableModels` which models the account can use, keeps the ids that the real client's agent picker shows, and caches them with their limits, labels, and the renames of retired ids in `$ALBEDO_HOME/antigravity.json`. The picker's list fetch (see [model lists](#model-lists)) rediscovers it, and requests refresh it in the background after 6 hours. A built-in table supplies each model's thinking control and serves as the list before the first discovery. A saved profile that names a retired id follows the backend's rename. The catalog answers lookups only for the Antigravity endpoint, so models.dev keeps answering for the same ids at other providers. +## OpenCode Zen requests + +`opencode_zen/extension.gleam` resolves the profile's endpoint and credential. +`opencode_zen/wire.gleam` chooses the lane for each request's model, including +requests sent through an already resolved upstream. A model id containing +`-free`, or any model on a profile with a blank credential, uses `Bearer public` +and OpenCode's reserved `bash`, `glob`, `grep`, and `read` fingerprint tools. +Other requests retain the resolved profile credential and their own tools. +Session and project identity remain stable across these requests. + ## contribute another catalog `extension.ModelsPlugin(ModelCatalog(lookup, list, reload))` is the catalog contract. `lookup(model, endpoint)` returns facts for one model; `list(provider, endpoint)` returns a `Listing` of the ids one catalog provider owns: `Local(ids)` for ids at hand, or `Remote(key, fetch, fallback)` for a list to ask a provider for, which the host caches (see [model lists](#model-lists)). `reload` refetches a file the catalog keeps besides its list, or is `None`. The first enabled catalog with an answer wins, so a private or offline catalog can be installed ahead of models.dev. A lookup for a profile (efforts, `/compact-at`, the picker's details) asks the catalog of the profile's own extension first: a claude profile has no base url, and Antigravity's catalog, earlier in the order, also lists Claude ids with fewer efforts and smaller limits. diff --git a/src/albedo/harness/extensions/opencode_zen/extension.gleam b/src/albedo/harness/extensions/opencode_zen/extension.gleam index 82fc4341c..13b641ec6 100644 --- a/src/albedo/harness/extensions/opencode_zen/extension.gleam +++ b/src/albedo/harness/extensions/opencode_zen/extension.gleam @@ -54,41 +54,26 @@ fn resolve( case string.trim(base_url) { "" -> Error("OpenCode Zen base URL is invalid") _ -> { - // Which identity the request wears is decided here, where the model is - // known: only a free-lane request asks for OpenCode's. - let free = free_lane(context.model, api_key) let client = wire.Client( - openai_api.client(types.ChatCompletions, base_url, case free { - True -> "public" - False -> api_key - }), + openai_api.client(types.ChatCompletions, base_url, api_key), native_session(context.session), native_project(context.home), native_user_agent(), ) - Ok(upstream(client, free)) + Ok(upstream(client)) } } } -/// Whether a request on `model` goes out on the free lane: one of the models -/// the lane serves, or any model at all on a profile carrying no credential, -/// since the free lane is the only one reachable without one. Zen serves a few -/// models free without saying so in the id — `big-pickle` is the one that does -/// today — and a paid model picked without a credential can only fail on the -/// credential anyway, which is what its 401 says. -pub fn free_lane(model: String, api_key: String) -> Bool { - native_free(model) || string.trim(api_key) == "" -} - -/// An upstream served by the shared OpenAI-compatible stream, shaped for the -/// free lane when it is a free-tier model. -fn upstream(client: wire.Client, free: Bool) -> extension.Upstream { +/// An upstream served by the shared OpenAI-compatible stream. `wire.stream` +/// chooses the lane for each request's model, so a request for another model +/// on this upstream still gets its own lane. +fn upstream(client: wire.Client) -> extension.Upstream { extension.Upstream( client.connection.base_url, client.connection.protocol, - fn(request, on_event) { wire.stream(client, free, request, on_event) }, + fn(request, on_event) { wire.stream(client, request, on_event) }, explain, fn() { None }, fn(_) { [] }, @@ -142,6 +127,3 @@ fn native_project(home: String) -> String @external(erlang, "albedo_opencode_zen", "user_agent") fn native_user_agent() -> String - -@external(erlang, "albedo_opencode_zen", "free") -fn native_free(model: String) -> Bool diff --git a/src/albedo/harness/extensions/opencode_zen/wire.gleam b/src/albedo/harness/extensions/opencode_zen/wire.gleam index 9f955acac..29cdcb798 100644 --- a/src/albedo/harness/extensions/opencode_zen/wire.gleam +++ b/src/albedo/harness/extensions/opencode_zen/wire.gleam @@ -30,10 +30,18 @@ pub type Client { /// Chat Completions request — and everything else on Chat Completions. pub fn stream( client: Client, - free: Bool, request: types.Request, on_event: fn(types.Event) -> types.Control, ) -> Result(types.Turn, types.Error) { + let free = free_lane(request.model, client.connection.api_key) + let client = case free { + True -> + Client( + ..client, + connection: types.Client(..client.connection, api_key: "public"), + ) + False -> client + } use _ <- result.try(openai_api.validate_client(client.connection)) use _ <- result.try( case @@ -93,6 +101,13 @@ pub fn stream( } } +/// Whether this request uses a free model or has no profile credential. +/// A credential-less profile keeps the free lane as its only fallback, even +/// when the requested model would normally require a paid credential. +pub fn free_lane(model: String, api_key: String) -> Bool { + native_free(model) || string.trim(api_key) == "" +} + /// Whether `model` is served on the Responses route. fn responses_only(model: String) -> Bool { string.starts_with(string.lowercase(string.trim(model)), "muse-spark-") @@ -155,3 +170,6 @@ fn headers(client: Client) -> List(#(String, String)) { #("x-opencode-project", client.project_id), ]) } + +@external(erlang, "albedo_opencode_zen", "free") +fn native_free(model: String) -> Bool diff --git a/test/harness/albedo_opencode_zen_test_support.erl b/test/harness/albedo_opencode_zen_test_support.erl new file mode 100644 index 000000000..9acaecf9f --- /dev/null +++ b/test/harness/albedo_opencode_zen_test_support.erl @@ -0,0 +1,92 @@ +%% A UI switch resolves a new upstream; this fixture exercises a retained one. +%% Only the HTTP boundary is fake. Resolution and streaming are production code. +-module(albedo_opencode_zen_test_support). +-export([reused_upstream_lanes/0]). + +reused_upstream_lanes() -> + {ok, _} = application:ensure_all_started(crypto), + Home = filename:join(os:getenv("TMPDIR", "/tmp"), + "zen-lanes-" ++ os:getpid() ++ "-" ++ integer_to_list(erlang:unique_integer([positive]))), + ok = file:make_dir(Home), + {ok, Listen} = gen_tcp:listen(0, [binary, {active, false}, {packet, http_bin}, + {ip, {127, 0, 0, 1}}]), + {ok, {_, Port}} = inet:sockname(Listen), + URL = iolist_to_binary(io_lib:format("http://127.0.0.1:~B/v1", [Port])), + Parent = self(), + Server = spawn_link(fun() -> serve(Listen, Parent) end), + try + %% Whitespace is an explicitly credential-less profile, independent of + %% any OPENCODE_* key in the test runner's environment. + Profiles = maps:from_list([{Name, #{<<"extension">> => <<"opencode-zen">>, + <<"baseUrl">> => URL, <<"apiKey">> => Key}} || {Name, Key} <- + [{<<"keyed">>, <<"fixture-paid-key">>}, {<<"keyless">>, <<" ">>}]]), + ok = file:write_file(filename:join(Home, "config.json"), + json:encode(#{<<"providers">> => Profiles})), + lists:foreach(fun({Profile, Resolved, Sends}) -> + Context = {model_context, unicode:characters_to_binary(Home), + <<"zen-lanes-session">>, Profile, <<"opencode-zen">>, Resolved, + chat_completions, none, false, none}, + {ok, Upstream} = 'albedo@harness@extension':upstream( + ['albedo@harness@extensions@opencode_zen@extension':extension()], Context), + Stream = element(4, Upstream), + lists:foreach(fun({Model, Key, Tools}) -> + Request = setelement(6, 'albedo@openai_api':request(Model, + [{user, <<"hello">>}]), {some, 1024}), + {ok, _} = Stream(Request, fun(_) -> continue end), + receive + {zen_request, Server, Headers, Body} -> + ExpectedAuth = <<"Bearer ", Key/binary>>, + ExpectedAuth = maps:get(<<"authorization">>, Headers), + Model = maps:get(<<"model">>, Body), + Names = [maps:get(<<"name">>, maps:get(<<"function">>, Tool)) + || Tool <- maps:get(<<"tools">>, Body, [])], + Tools = Names + after 5000 -> error(zen_request_not_received) + end + end, Sends) + end, [ + {<<"keyed">>, <<"fixture-free">>, [paid(), free()]}, + {<<"keyed">>, <<"paid-fixture">>, [free(), paid()]}, + {<<"keyless">>, <<"fixture-free">>, [keyless_paid(), free()]}, + {<<"keyless">>, <<"paid-fixture">>, [free(), keyless_paid()]} + ]), + true + after + unlink(Server), + exit(Server, shutdown), + gen_tcp:close(Listen), + file:del_dir_r(Home) + end. + +paid() -> {<<"paid-fixture">>, <<"fixture-paid-key">>, []}. +free() -> {<<"fixture-free">>, <<"public">>, tools()}. +keyless_paid() -> {<<"paid-fixture">>, <<"public">>, tools()}. +tools() -> [<<"bash">>, <<"glob">>, <<"grep">>, <<"read">>]. + +serve(Listen, Parent) -> + {ok, Socket} = gen_tcp:accept(Listen), + try + {ok, {http_request, 'POST', _, _}} = gen_tcp:recv(Socket, 0, 5000), + Headers = headers(Socket, #{}), + Length = binary_to_integer(maps:get(<<"content-length">>, Headers)), + ok = inet:setopts(Socket, [{packet, raw}]), + {ok, Body} = gen_tcp:recv(Socket, Length, 5000), + Parent ! {zen_request, self(), Headers, json:decode(Body)}, + Response = <<"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n">>, + ok = gen_tcp:send(Socket, [ + "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\nContent-Length: ", + integer_to_list(byte_size(Response)), "\r\n\r\n", Response]) + after gen_tcp:close(Socket) + end, + serve(Listen, Parent). + +headers(Socket, Acc) -> + case gen_tcp:recv(Socket, 0, 5000) of + {ok, http_eoh} -> Acc; + {ok, {http_header, _, Name, _, Value}} -> + Key = string:lowercase(case Name of + Atom when is_atom(Atom) -> atom_to_binary(Atom); + Binary -> Binary + end), + headers(Socket, Acc#{Key => Value}) + end. diff --git a/test/harness/opencode_zen_test.gleam b/test/harness/opencode_zen_test.gleam index 7bc12bfb8..48adf5aa1 100644 --- a/test/harness/opencode_zen_test.gleam +++ b/test/harness/opencode_zen_test.gleam @@ -6,8 +6,9 @@ //// `ffe`, and fourteen base62, a user agent naming an OpenCode release, and //// an agent request whose tool list carries OpenCode's own tool names — is //// pinned here instead. +//// The resolve/stream regression also sends another model on the same upstream, +//// which a UI model switch that resolves a fresh upstream would miss. -import albedo/harness/extensions/opencode_zen/extension import albedo/harness/extensions/opencode_zen/wire import albedo/openai_api/types import gleam/json @@ -35,7 +36,7 @@ fn request(tools: List(types.Tool)) -> types.Request { } fn native_free_lane(model: String, api_key: String) -> Bool { - extension.free_lane(model, api_key) + wire.free_lane(model, api_key) } fn named_tool(name: String) -> types.Tool { @@ -132,3 +133,10 @@ fn native_project(home: String) -> String @external(erlang, "albedo_opencode_zen", "free") fn native_free(model: String) -> Bool + +pub fn zen_reused_upstream_selects_the_lane_for_each_sent_model_test() -> Nil { + reused_upstream_lanes() |> should.be_true +} + +@external(erlang, "albedo_opencode_zen_test_support", "reused_upstream_lanes") +fn reused_upstream_lanes() -> Bool -- knotmirror 0.0.1