diff --git a/e2e/google_ai_studio_support.py b/e2e/google_ai_studio_support.py index 90f2ee851..f13d45ac4 100644 --- a/e2e/google_ai_studio_support.py +++ b/e2e/google_ai_studio_support.py @@ -11,25 +11,22 @@ from harness import Provider class GoogleAIStudioProvider(Provider): """Keep native endpoint, credential and catalog state on one provider route.""" - def __init__(self, script, *, key, model="gemini-fixture", pages=None, count=None): + def __init__(self, script, *, key, model="gemini-fixture", count=None): super().__init__(script, chunk_size=4, count=count) self.key = key self.model = model self.base_url = self.url + "/v1beta" - self.pages = ( - pages - if pages is not None - else { - "": { - "models": [ - { - "name": f"models/{model}", - "supportedGenerationMethods": ["generateContent"], - } - ] - } + # One page; the paging rules are a property in the extension's tests. + self.pages = { + "": { + "models": [ + { + "name": f"models/{model}", + "supportedGenerationMethods": ["generateContent"], + } + ] } - ) + } self.http_requests = [] self.catalog_requests = [] self.violations = [] diff --git a/e2e/google_ai_studio_test.py b/e2e/google_ai_studio_test.py index 7dc992b83..95c2468cd 100644 --- a/e2e/google_ai_studio_test.py +++ b/e2e/google_ai_studio_test.py @@ -1,9 +1,11 @@ """Native AI Studio auth and service semantics survive a real daemon turn. -Shared Gemini codec tests cannot catch a provider that uses bearer auth, skips -native model pages, counts only contents, or loses account identity on a Google -quota response. Model traffic uses per-test loopback provider routes. Native -Google environment accounts can be projected and pinned without contacting Google. +What only the assembled daemon shows: a saved key streaming a native tool turn +and counting the full request, the studio's model facts staying out of another +extension's picker, an environment account projected on /auth at Google's own +endpoint, and quota rotation sending each key to its own endpoint. Paging, key +selection and discovery, and refusal mapping are properties in the extension's +own tests. Model traffic uses per-test loopback provider routes. """ import json @@ -13,14 +15,12 @@ import urllib.parse from google_ai_studio_support import GoogleAIStudioProvider from harness import ( Albedo, - Provider, Reply, cell_output, exclusive, operation_id, python, text, - wait_until, ) MODEL = "gemini-fixture" @@ -34,16 +34,13 @@ class GoogleAIStudioTests(unittest.TestCase): script=None, *, key="studio-secret", - pages=None, count=None, prepare=None, - configured=True, ): provider = GoogleAIStudioProvider( script or (lambda _request: text("native answer")), key=key, model=MODEL, - pages=pages, count=count, ) self.addCleanup(provider.close) @@ -75,9 +72,7 @@ class GoogleAIStudioTests(unittest.TestCase): "model": MODEL, "protocol": "chat_completions", } - } - if configured - else {}, + }, prepare=offline, ).__enter__() self.addCleanup(app.__exit__, None, None, None) @@ -200,144 +195,6 @@ class GoogleAIStudioTests(unittest.TestCase): self.assert_public_secrets_absent(app, "studio-secret", session=session) self.assertEqual(provider.violations, []) - def test_native_model_pages_filter_non_generation_routes_and_deduplicate_ids(self): - token = "next page/+?" - last = "last page" - pages = { - "": { - "models": [ - { - "name": f"models/{MODEL}", - "supportedGenerationMethods": [ - "generateContent", - "countTokens", - ], - }, - { - "name": "models/embedding-fixture", - "supportedGenerationMethods": ["embedContent"], - }, - { - "name": "models/count-only", - "supportedGenerationMethods": ["countTokens"], - }, - ], - "nextPageToken": token, - }, - token: {"nextPageToken": last}, - last: { - "models": [ - { - "name": "models/gemini-fixture-latest", - "supportedGenerationMethods": ["generateContent"], - }, - { - "name": f"models/{MODEL}", - "supportedGenerationMethods": ["generateContent"], - }, - {"name": "models/no-generation-methods"}, - ] - }, - } - app, provider = self.start(pages=pages) - self.save_key(app, provider, "studio-secret") - query = urllib.parse.urlencode( - {"provider": "google-ai-studio", "endpoint": provider.base_url} - ) - models = self.read(app, "/models?" + query)["items"] - self.assertEqual( - [model["id"] for model in models], [MODEL, "gemini-fixture-latest"] - ) - self.assertEqual(provider.catalog_requests, ["", token, last]) - self.assertEqual(provider.violations, []) - - def test_catalog_only_sends_a_key_authorized_for_the_requested_endpoint(self): - def prepare(app): - app.env.pop("GEMINI_API_KEY", None) - app.env["GOOGLE_API_KEY"] = "configured-environment-key" - - app, _ = self.start(prepare=prepare) - other = GoogleAIStudioProvider( - lambda _request: text("unused"), - key="other-host-key", - model="gemini-other-endpoint", - ) - self.addCleanup(other.close) - query = urllib.parse.urlencode( - {"provider": "google-ai-studio", "endpoint": other.base_url} - ) - - def listed(): - return [row["id"] for row in self.read(app, "/models?" + query)["items"]] - - self.assertNotIn("gemini-other-endpoint", listed()) - self.assertEqual(other.http_requests, []) - # Connecting a provider can discover its key's endpoint before creating - # a profile. This must use that key, not the provider-wide environment key. - self.save_key(app, other, "other-host-key") - self.assertEqual(listed(), ["gemini-other-endpoint"]) - self.assertEqual(other.catalog_requests, [""]) - self.assertEqual(other.violations, []) - - def test_catalog_rejects_a_cursor_cycle_and_keeps_the_saved_list(self): - def page(model, next_token=None): - body = { - "models": [ - { - "name": f"models/{model}", - "supportedGenerationMethods": ["generateContent"], - } - ] - } - if next_token is not None: - body["nextPageToken"] = next_token - return body - - models_dev = Provider( - lambda _request: text("unused"), - catalog={"google": {"models": {MODEL: {"limit": {"context": 200000}}}}}, - ) - self.addCleanup(models_dev.close) - - def prepare(app): - app.write_extensions({"models": {"url": models_dev.url + "/models.json"}}) - - app, provider = self.start( - pages={"": page("gemini-native-only")}, prepare=prepare - ) - self.save_key(app, provider, "studio-secret") - query = urllib.parse.urlencode({"provider_profile": app.profile}) - - def listed(): - return [row["id"] for row in self.read(app, "/models?" + query)["items"]] - - session = app.session() - - def reload_studio(): - with app.api( - f"/sessions/{session}/reload", {"target": "models"} - ) as response: - catalogs = json.load(response)["models"] - return next( - row for row in catalogs if row["provider"] == "google-ai-studio" - ) - - # The picker may serve fallback IDs while its first fetch is in flight. - # Reload waits for the native list to be committed before we break it. - self.assertEqual(reload_studio()["state"], "refreshed") - self.assertEqual(listed(), ["gemini-native-only"]) - provider.pages = { - "": page("gemini-partial", "a"), - "a": page("gemini-partial", "b"), - "b": page("gemini-partial", "a"), - } - studio = reload_studio() - self.assertEqual(studio["state"], "failed") - self.assertIn("repeated a page token", studio["failure"]["detail"]) - self.assertEqual(provider.catalog_requests, ["", "", "a", "b"]) - self.assertEqual(listed(), ["gemini-native-only"]) - self.assertEqual(provider.violations, []) - def test_studio_endpoint_facts_do_not_leak_into_an_unrelated_model_picker(self): def prepare(app): # No credential permits default-host discovery; only this cached @@ -390,44 +247,6 @@ class GoogleAIStudioTests(unittest.TestCase): self.assertEqual(vertex["efforts"], []) self.assertEqual(provider.http_requests, []) - def test_custom_profile_does_not_send_native_environment_keys(self): - secret = "environment-studio-secret" - - def prepare(app): - app.env["GOOGLE_API_KEY"] = secret - app.env["GEMINI_API_KEY"] = "second-environment-studio-secret" - - app, provider = self.start(key=secret, prepare=prepare, configured=False) - query = urllib.parse.urlencode( - {"provider": "google-ai-studio", "endpoint": provider.base_url} - ) - - def listed(): - return [ - model["id"] for model in self.read(app, "/models?" + query)["items"] - ] - - self.assertEqual(listed(), [MODEL]) - app.profile = "studio" - self.patch_profile( - app, extension="google-ai-studio", endpoint=provider.base_url, model=MODEL - ) - self.assertEqual(listed(), [MODEL]) - session = app.session(name="unauthorized custom endpoint") - app.prompt(session, "say hello").close() - - def blocking_reason(): - return self.read(app, f"/sessions/{session}?tail=0")["status"][ - "blocking_reason" - ] - - wait_until(blocking_reason, 10, "custom profile did not report an auth blocker") - self.assertIn( - "Google AI Studio is not authenticated", blocking_reason()["detail"] - ) - self.assertEqual(provider.http_requests, []) - self.assert_public_secrets_absent(app, secret, session=session) - def test_environment_account_is_discovered_and_pinned_at_its_native_endpoint(self): secret = "native-projection-studio-secret" endpoint = "https://generativelanguage.googleapis.com/v1beta" @@ -459,54 +278,6 @@ class GoogleAIStudioTests(unittest.TestCase): self.assertEqual(provider.http_requests, []) self.assert_public_secrets_absent(app, secret) - def test_native_invalid_key_error_never_uses_an_unselected_sibling(self): - rejected = Reply( - "error", - status=400, - error_body={ - "error": { - "code": 400, - "message": "API key not valid. Please pass a valid API key.", - "status": "INVALID_ARGUMENT", - "details": [ - { - "@type": "type.googleapis.com/google.rpc.ErrorInfo", - "reason": "API_KEY_INVALID", - "domain": "googleapis.com", - } - ], - } - }, - ) - app, provider = self.start( - lambda _request: rejected, key="rejected-studio-secret" - ) - selected = self.save_key( - app, provider, "rejected-studio-secret", label="rejected" - ) - self.save_key(app, provider, "unselected-studio-secret", label="unselected") - self.patch_profile(app, account_id=selected["id"]) - session = app.session(name="rejected native key") - app.prompt(session, "say hello").close() - state = app.idle(session) - errors = [ - line["text"] - for line in state["activity"]["lines"] - if line["kind"] == "error" - ] - self.assertTrue(any("rejected this API key" in line for line in errors), errors) - self.assertEqual(len(provider.requests), 1) - [row] = self.requests(app, session) - self.assertEqual( - (row["outcome"], row["http_status"], row["account_id"]), - ("failed", 400, "rejected"), - ) - self.assertIn("API key not valid", row["failure"]["detail"]) - self.assert_public_secrets_absent( - app, "rejected-studio-secret", "unselected-studio-secret", session=session - ) - self.assertEqual(provider.violations, []) - def test_native_quota_rotates_explicit_keys_and_uses_the_account_endpoint(self): exhausted = Reply( "error", @@ -551,38 +322,6 @@ class GoogleAIStudioTests(unittest.TestCase): ) self.assertEqual(limited.violations + available.violations, []) - def test_interrupt_cancels_native_stream_and_the_session_can_continue(self): - app, provider = self.start(lambda _request: Reply("text", hang=True)) - self.save_key(app, provider, "studio-secret") - session = app.session(name="cancel native stream") - app.prompt(session, "wait for a reply").close() - wait_until( - lambda: len(provider.requests) == 1, 10, "native stream was not reached" - ) - state = self.read(app, f"/sessions/{session}?tail=0") - with app.api( - f"/sessions/{session}/interrupt", - { - "run_id": state["status"]["run_id"], - "through_input_order": state["input_order"], - }, - ) as response: - response.read() - app.idle(session, timeout=10) - [cancelled] = self.requests(app, session) - self.assertEqual(cancelled["outcome"], "failed") - self.assertEqual(cancelled["failure"]["detail"], "Cancelled") - self.assertEqual(len(provider.requests), 1) - provider.script = lambda _request: text("continued after cancellation") - app.prompt(session, "try again").close() - state = app.idle(session) - self.assertIn( - "continued after cancellation", json.dumps(state["activity"]["lines"]) - ) - self.assertEqual(self.requests(app, session)[-1]["outcome"], "completed") - self.assertEqual(len(provider.requests), 2) - self.assertEqual(provider.violations, []) - if __name__ == "__main__": unittest.main() diff --git a/extensions/google_ai_studio/gleam.toml b/extensions/google_ai_studio/gleam.toml index 361752f9e..301bbbbf1 100644 --- a/extensions/google_ai_studio/gleam.toml +++ b/extensions/google_ai_studio/gleam.toml @@ -18,3 +18,6 @@ albedo_sdk = { path = "../../packages/albedo_sdk" } [dev_dependencies] gleeunit = ">= 1.0.0 and < 2.0.0" +qcheck = ">= 1.0.5 and < 2.0.0" +albedo_property = { path = "../../packages/albedo_property" } +albedo_env = { path = "../../packages/albedo_env" } diff --git a/extensions/google_ai_studio/manifest.toml b/extensions/google_ai_studio/manifest.toml index 45e8f8c93..89f25dcbe 100644 --- a/extensions/google_ai_studio/manifest.toml +++ b/extensions/google_ai_studio/manifest.toml @@ -22,6 +22,7 @@ packages = [ { name = "albedo_openai", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_http", "albedo_json", "albedo_model", "albedo_model_stream", "albedo_sse", "gleam_json", "gleam_stdlib"], source = "local", path = "../../packages/albedo_openai" }, { name = "albedo_ports", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../../packages/albedo_ports" }, { name = "albedo_process", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_otp", "gleam_stdlib"], source = "local", path = "../../packages/albedo_process" }, + { name = "albedo_property", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_env", "albedo_protect", "gleam_erlang", "gleam_stdlib", "qcheck"], source = "local", path = "../../packages/albedo_property" }, { name = "albedo_protect", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../../packages/albedo_protect" }, { name = "albedo_sdk", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_clock", "albedo_env", "albedo_file", "albedo_http", "albedo_image", "albedo_json", "albedo_model", "albedo_model_stream", "albedo_oauth", "albedo_openai", "albedo_ports", "albedo_process", "albedo_protect", "albedo_sqlite", "albedo_web", "gleam_crypto", "gleam_erlang", "gleam_http", "gleam_json", "gleam_otp", "gleam_stdlib", "mist", "sqlight", "yamerl"], source = "local", path = "../../packages/albedo_sdk" }, { name = "albedo_sqlite", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_process", "esqlite", "gleam_erlang", "gleam_otp", "gleam_stdlib", "sqlight"], source = "local", path = "../../packages/albedo_sqlite" }, @@ -34,24 +35,31 @@ packages = [ { name = "gleam_http", version = "4.4.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_http", source = "hex", outer_checksum = "F065CE9941A7756ABBAEAE7F9F32A96CAD29DA3311A381DB2D926EA8E8C156DC" }, { name = "gleam_json", version = "3.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_json", source = "hex", outer_checksum = "44FDAA8847BE8FC48CA7A1C089706BD54BADCC4C45B237A992EDDF9F2CDB2836" }, { name = "gleam_otp", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "DE4CA6850842F0266EE95317A25DD6A0A0F20CDFAB7C0ADC2E63251D7C3C72EC" }, + { name = "gleam_regexp", version = "1.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_regexp", source = "hex", outer_checksum = "9C215C6CA84A5B35BB934A9B61A9A306EC743153BE2B0425A0D032E477B062A9" }, { name = "gleam_stdlib", version = "1.0.5", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "CEE5B6C076A85B45F60C585F4316C63EC8B7127C119D5738C3958A9C4D50404E" }, + { name = "gleam_yielder", version = "1.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_yielder", source = "hex", outer_checksum = "8E4E4ECFA7982859F430C57F549200C7749823C106759F4A19A78AEA6687717A" }, { name = "gleeunit", version = "1.11.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "EC31ABA74256AEA531EDF8169931D775BBB384FED0A8A1BDC4DD9354E3E21826" }, { name = "glisten", version = "9.0.1", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_otp", "gleam_stdlib", "logging"], otp_app = "glisten", source = "hex", outer_checksum = "7795AA50830656F3A0316A6B26595F893C83272DA901B3405E31339CAA31A10B" }, { name = "gramps", version = "6.0.1", build_tools = ["gleam"], requirements = ["gleam_crypto", "gleam_erlang", "gleam_http", "gleam_stdlib"], otp_app = "gramps", source = "hex", outer_checksum = "D55636072DEE173F6586A5679D3C02EC7A0DE3F8646B78C351B72908FF223DF7" }, { name = "hpack_erl", version = "0.3.0", build_tools = ["rebar3"], requirements = [], otp_app = "hpack", source = "hex", outer_checksum = "D6137D7079169D8C485C6962DFE261AF5B9EF60FBC557344511C1E65E3D95FB0" }, { name = "logging", version = "1.5.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "logging", source = "hex", outer_checksum = "BC5F18CE5DD9686100229FE5409BDC3DD5C46D5A7DF2F804AD2D8F0DD6C5060E" }, { name = "mist", version = "6.0.3", build_tools = ["gleam"], requirements = ["exception", "gleam_erlang", "gleam_http", "gleam_otp", "gleam_stdlib", "glisten", "gramps", "hpack_erl", "logging"], source = "local", path = "../../vendor/mist" }, + { name = "prng", version = "6.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "prng", source = "hex", outer_checksum = "7FE3879E13150248BD370469205ED07B9404DD90670FEBB8CD0E7643707C420E" }, + { name = "qcheck", version = "1.0.5", build_tools = ["gleam"], requirements = ["exception", "gleam_regexp", "gleam_stdlib", "gleam_yielder", "prng"], otp_app = "qcheck", source = "hex", outer_checksum = "D27C12074776EC95F082EE56E0FC74685506B6EE26176F194D10F0322A39AC11" }, { name = "sqlight", version = "1.2.0", build_tools = ["gleam"], requirements = ["esqlite", "gleam_stdlib"], otp_app = "sqlight", source = "hex", outer_checksum = "841768D0A81107EE2DB46B949354F284A68B2E8098315C28A1FE3C07D206C17A" }, { name = "yamerl", version = "0.10.0", build_tools = ["rebar3"], requirements = [], otp_app = "yamerl", source = "hex", outer_checksum = "346ADB2963F1051DC837A2364E4ACF6EB7D80097C0F53CBDC3046EC8EC4B4E6E" }, ] [requirements] +albedo_env = { path = "../../packages/albedo_env" } albedo_gemini = { path = "../../packages/albedo_gemini" } albedo_http = { path = "../../packages/albedo_http" } albedo_model = { path = "../../packages/albedo_model" } albedo_models_dev = { path = "../../packages/albedo_models_dev" } albedo_openai = { path = "../../packages/albedo_openai" } +albedo_property = { path = "../../packages/albedo_property" } albedo_sdk = { path = "../../packages/albedo_sdk" } gleam_json = { version = ">= 3.1.0 and < 4.0.0" } gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } gleeunit = { version = ">= 1.0.0 and < 2.0.0" } +qcheck = { version = ">= 1.0.5 and < 2.0.0" } diff --git a/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/accounts.gleam b/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/accounts.gleam index 70d6d0e5a..87a6c2bdc 100644 --- a/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/accounts.gleam +++ b/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/accounts.gleam @@ -65,25 +65,12 @@ pub fn select( list.filter(saved, fn(account) { base_url(key_accounts.endpoint(account)) == endpoint }) - let selected = list.filter(saved, key_accounts.selected) - let saved = case selected { - [] -> saved - _ -> selected - } + // Process environment keys serve only Google's own endpoint. let automatic = case endpoint == default_endpoint { True -> environment(source) False -> [] } - let candidates = list.append(saved, automatic) - let available = - list.filter(candidates, fn(account) { !key_accounts.limited(account) }) - let chosen = - list.first(list.append(available, candidates)) |> option.from_result - case chosen { - Some(account) -> key_accounts.remember(account, session) - None -> Nil - } - Ok(chosen) + Ok(key_accounts.choose_unbound(saved, automatic, session)) } } use chosen <- result.try(chosen) diff --git a/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/catalog.gleam b/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/catalog.gleam index 2a558cf07..22ffab41d 100644 --- a/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/catalog.gleam +++ b/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/catalog.gleam @@ -70,10 +70,37 @@ type Page { } fn fetch(endpoint: String, key: String) -> Result(List(String), String) { - pages(endpoint, key, [], []) + list_pages( + fn(url, headers) { + http.get_no_redirect( + url, + headers, + Timeouts(page_timeout_ms, page_timeout_ms), + ) + }, + endpoint, + key, + ) +} + +/// GETs a URL with headers, answering its status and body. +pub type Get = + fn(String, List(#(String, String))) -> Result(#(Int, BitArray), String) + +/// The generateContent model IDs `/models` lists across its pages, sorted +/// and without duplicates, read through `get`. A refused key, an unexpected +/// shape, a repeated page token, more than `max_pages` pages, or an empty +/// listing is an error, so the picker keeps its saved list. +pub fn list_pages( + get: Get, + endpoint: String, + key: String, +) -> Result(List(String), String) { + pages(get, endpoint, key, [], []) } fn pages( + get: Get, endpoint: String, key: String, tokens: List(String), @@ -88,11 +115,12 @@ fn pages( } ] |> uri.query_to_string - use #(status, body) <- result.try(http.get_no_redirect( - endpoint <> "/models?" <> query, - [#("x-goog-api-key", key), #("accept", "application/json")], - Timeouts(page_timeout_ms, page_timeout_ms), - )) + use #(status, body) <- result.try( + get(endpoint <> "/models?" <> query, [ + #("x-goog-api-key", key), + #("accept", "application/json"), + ]), + ) use <- bool.guard( status != 200, Error(case status { @@ -112,7 +140,7 @@ fn pages( case list.contains(tokens, next), list.length(ids) >= max_pages { True, _ -> Error("Google AI Studio /models repeated a page token") _, True -> Error("Google AI Studio /models exceeded its page limit") - False, False -> pages(endpoint, key, [next, ..tokens], ids) + False, False -> pages(get, endpoint, key, [next, ..tokens], ids) } _ -> { let ids = ids |> list.flatten |> list.sort(string.compare) |> list.unique diff --git a/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/wire.gleam b/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/wire.gleam index c92f2eb63..66e9800e5 100644 --- a/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/wire.gleam +++ b/extensions/google_ai_studio/src/albedo_ext_google_ai_studio/wire.gleam @@ -46,7 +46,7 @@ fn encode( None, client.max_event_bytes, True, - http_refusal, + refusal, )) } @@ -71,7 +71,7 @@ pub fn count( model_url(client, id) <> ":countTokens", [#("accept", "application/json"), ..headers(client)], ["totalTokens"], - http_refusal, + refusal, token_count.NotFound, ), body, @@ -98,9 +98,9 @@ fn model_id(model: String) -> Result(String, types.Error) { } } -// The Developer API can reject a key with HTTP 400 INVALID_ARGUMENT. Only -// Google's typed ErrorInfo distinguishes it from a malformed request. -fn http_refusal(status: Int, body: String) -> types.Error { +/// The Developer API can reject a key with HTTP 400 INVALID_ARGUMENT. Only +/// Google's typed ErrorInfo distinguishes it from a malformed request. +pub fn refusal(status: Int, body: String) -> types.Error { let error = gemini_refusal.http(status, body) case error { types.Refused(_, at, detail) -> { diff --git a/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/accounts_test.gleam b/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/accounts_test.gleam new file mode 100644 index 000000000..21ffb7179 --- /dev/null +++ b/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/accounts_test.gleam @@ -0,0 +1,246 @@ +//// Which key a plain AI Studio profile, one that names no account, sends. +//// The defects: a key saved for another endpoint sent to this one, which +//// leaks it and the conversation to another host; a process environment +//// key sent to a custom endpoint; the user's saved selection ignored; a +//// rate-limited key chosen while another is available; and GOOGLE_API_KEY +//// not preferred over GEMINI_API_KEY. Selection reads the settings files and +//// the process environment, so each case writes a scratch home. + +import albedo_env +import albedo_ext_google_ai_studio/accounts +import albedo_property +import albedo_sdk/key_accounts +import albedo_sdk/key_environment +import gleam/dynamic.{type Dynamic} +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{type Option, None, Some} +import qcheck.{type Generator} + +const native = "https://generativelanguage.googleapis.com/v1beta" + +const custom = "https://studio-proxy.test/v1beta" + +const other = "https://elsewhere.test/v1beta" + +type Saved { + Saved(key: String, endpoint: String, selected: Bool, limited: Bool) +} + +type Case { + Case(profile_endpoint: String, saved: List(Saved), google: Bool, gemini: Bool) +} + +pub fn a_plain_profile_sends_a_key_meant_for_its_endpoint_test() -> Nil { + use case_ <- albedo_property.run(150, case_()) + use home <- scratch(case_) + let got = + accounts.select(home, "studio", "session", key_environment.empty()) + |> option.from_result + |> option.map(key_accounts.key) + assert got == expected(case_) +} + +/// Model discovery for the profile's endpoint asks with a saved key for that +/// endpoint, the selected one first, else an environment key at Google's own +/// endpoint. A rate limit does not matter to a listing. +pub fn discovery_asks_only_with_a_key_for_its_endpoint_test() -> Nil { + use case_ <- albedo_property.run(150, case_()) + use home <- scratch(case_) + let endpoint = case case_.profile_endpoint { + "" -> native + other -> other + } + let saved = + list.filter(case_.saved, fn(saved) { + case saved.endpoint { + "" -> native + other -> other + } + == endpoint + }) + let want = case list.find(saved, fn(saved) { saved.selected }), saved { + Ok(saved), _ | _, [saved, ..] -> Some(saved.key) + _, [] -> + case endpoint == native, case_.google, case_.gemini { + True, True, _ -> Some("google-env") + True, False, True -> Some("gemini-env") + _, _, _ -> None + } + } + assert accounts.discovery_key(home, endpoint, key_environment.empty()) == want +} + +/// The rule in `accounts.select`: saved keys for the profile's endpoint, the +/// selected ones among them when any is selected, then the environment keys +/// at Google's own endpoint; the first not rate limited, else the first. +fn expected(case_: Case) -> Option(String) { + let endpoint = case case_.profile_endpoint { + "" -> native + other -> other + } + let saved = + list.filter(case_.saved, fn(saved) { + case saved.endpoint { + "" -> native + other -> other + } + == endpoint + }) + let saved = case list.filter(saved, fn(saved) { saved.selected }) { + [] -> saved + chosen -> chosen + } + let environment = case endpoint == native { + True -> + list.flatten([ + case case_.google { + True -> [Saved("google-env", "", False, False)] + False -> [] + }, + case case_.gemini { + True -> [Saved("gemini-env", "", False, False)] + False -> [] + }, + ]) + False -> [] + } + let candidates = list.append(saved, environment) + list.append(list.filter(candidates, fn(saved) { !saved.limited }), candidates) + |> list.first + |> option.from_result + |> option.map(fn(saved) { saved.key }) +} + +fn case_() -> Generator(Case) { + let endpoint = pick(["", native, custom, other]) + let saved = { + use endpoint <- qcheck.bind(endpoint) + use selected <- qcheck.bind(qcheck.bool()) + use limited <- qcheck.map(qcheck.bool()) + #(endpoint, selected, limited) + } + use profile_endpoint <- qcheck.bind(pick(["", custom])) + use saved <- qcheck.bind(qcheck.generic_list(saved, qcheck.bounded_int(0, 4))) + use google <- qcheck.bind(qcheck.bool()) + use gemini <- qcheck.map(qcheck.bool()) + let saved = + list.index_map(saved, fn(saved, i) { + Saved("saved-" <> int.to_string(i), saved.0, saved.1, saved.2) + }) + Case(profile_endpoint, saved, google, gemini) +} + +fn pick(choices: List(String)) -> Generator(String) { + qcheck.bounded_int(0, list.length(choices) - 1) + |> qcheck.map(fn(index) { + let assert Ok(choice) = list.drop(choices, index) |> list.first + choice + }) +} + +/// A home with one plain `studio` profile and the case's saved keys, and the +/// case's environment keys set for the duration of `run`. +fn scratch(case_: Case, run: fn(String) -> Nil) -> Nil { + let home = + "/tmp/albedo-studio-accounts-test-" + <> int.to_string(system_time()) + <> "-" + <> int.to_string(int.absolute_value(unique_integer())) + let _ = make_dir(home) + write( + home, + "config.json", + json.object([ + #("accountsVersion", json.int(2)), + #( + "providers", + json.object([ + #( + "studio", + json.object([ + #("extension", json.string("google-ai-studio")), + #("baseUrl", json.string(case_.profile_endpoint)), + ]), + ), + ]), + ), + ]), + ) + write( + home, + "creds.json", + json.object([ + #( + "accounts", + json.object([ + #( + "google-ai-studio", + json.array(case_.saved, fn(saved) { + json.object([ + #("_albedo_account_id", json.string(saved.key)), + #("type", json.string("key")), + #("apiKey", json.string(saved.key)), + #("endpoint", json.string(saved.endpoint)), + #("label", json.string(saved.key)), + #("selected", json.bool(saved.selected)), + #( + "limitedUntil", + json.int(case saved.limited { + True -> 4_102_444_800_000 + False -> 0 + }), + ), + ]) + }), + ), + ]), + ), + ]), + ) + let previous = #( + albedo_env.lookup("GOOGLE_API_KEY"), + albedo_env.lookup("GEMINI_API_KEY"), + ) + set("GOOGLE_API_KEY", case case_.google { + True -> Some("google-env") + False -> None + }) + set("GEMINI_API_KEY", case case_.gemini { + True -> Some("gemini-env") + False -> None + }) + run(home) + set("GOOGLE_API_KEY", previous.0) + set("GEMINI_API_KEY", previous.1) + let _ = del_dir_r(home) + Nil +} + +fn set(variable: String, value: Option(String)) -> Nil { + case value { + Some(value) -> albedo_env.set(variable, value) + None -> albedo_env.unset(variable) + } +} + +fn write(home: String, file: String, value: json.Json) -> Nil { + let _ = write_file(home <> "/" <> file, json.to_string(value)) + Nil +} + +@external(erlang, "erlang", "system_time") +fn system_time() -> Int + +@external(erlang, "erlang", "unique_integer") +fn unique_integer() -> Int + +@external(erlang, "file", "make_dir") +fn make_dir(path: String) -> Dynamic + +@external(erlang, "file", "write_file") +fn write_file(path: String, text: String) -> Dynamic + +@external(erlang, "file", "del_dir_r") +fn del_dir_r(path: String) -> Dynamic diff --git a/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/catalog_test.gleam b/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/catalog_test.gleam new file mode 100644 index 000000000..45c347f1e --- /dev/null +++ b/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/catalog_test.gleam @@ -0,0 +1,195 @@ +//// The Developer API's model listing, read page by page. The defects: a +//// model that cannot generate content offered in the picker, a duplicate +//// or unsorted list, a page dropped or read twice, a cursor cycle or an +//// endless chain followed past the page limit, a refused key or a broken +//// page taken as an empty catalog, and the key sent without its header. +//// A fake `get` serves generated pages; the oracle walks them by the rules +//// in `catalog.list_pages`'s documentation. + +import albedo_ext_google_ai_studio/catalog +import albedo_property +import gleam/bit_array +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/string +import qcheck.{type Generator} + +const endpoint = "https://generativelanguage.googleapis.com/v1beta" + +const key = "AIza-test-key" + +type Row { + Row(name: String, generates: Bool) +} + +type Page { + Page(status: Int, broken: Bool, rows: List(Row), next: Option(String)) +} + +pub fn listing_follows_the_pages_test() -> Nil { + use pages <- albedo_property.run(300, pages()) + let got = catalog.list_pages(serve(pages), endpoint, key) + case expected(pages) { + Some(ids) -> { + assert got == Ok(ids) + } + None -> + case got { + Error(_) -> Nil + Ok(ids) -> panic as { "expected a refusal, got " <> string.inspect(ids) } + } + } +} + +/// The IDs the pages list, or `None` when the listing must fail. +fn expected(pages: List(Page)) -> Option(List(String)) { + walk(pages, 0, [], 1, []) +} + +fn walk( + pages: List(Page), + index: Int, + requested: List(String), + fetched: Int, + ids: List(String), +) -> Option(List(String)) { + let assert Ok(page) = list.drop(pages, index) |> list.first + case page.status, page.broken { + 200, False -> { + let ids = + list.append( + ids, + list.filter_map(page.rows, fn(row) { + case row.generates, row.name { + False, _ | _, "" | _, "models/" -> Error(Nil) + True, "models/" <> id -> Ok(id) + True, id -> Ok(id) + } + }), + ) + case page.next { + None | Some("") -> + case list.unique(list.sort(ids, string.compare)) { + [] -> None + ids -> Some(ids) + } + Some(token) -> + case list.contains(requested, token) || fetched >= 5 { + True -> None + False -> + walk( + pages, + page_index(token), + [token, ..requested], + fetched + 1, + ids, + ) + } + } + } + _, _ -> None + } +} + +fn serve(pages: List(Page)) -> catalog.Get { + fn(url, headers) { + assert list.contains(headers, #("x-goog-api-key", key)) + let assert True = + string.starts_with(url, endpoint <> "/models?pageSize=1000") + as url + let index = case string.split(url, "pageToken=") { + [_, token] -> page_index(token) + _ -> 0 + } + let assert Ok(page) = list.drop(pages, index) |> list.first + let body = case page.broken { + True -> "{\"models\": [{\"name\": " + False -> encode(page) + } + Ok(#(page.status, bit_array.from_string(body))) + } +} + +fn page_index(token: String) -> Int { + let assert Ok(index) = int.parse(string.drop_start(token, 1)) + index +} + +fn encode(page: Page) -> String { + json.object([ + #( + "models", + json.array(page.rows, fn(row) { + json.object([ + #("name", json.string(row.name)), + #( + "supportedGenerationMethods", + json.array( + case row.generates { + True -> ["countTokens", "generateContent"] + False -> ["embedContent"] + }, + json.string, + ), + ), + ]) + }), + ), + ..case page.next { + Some(token) -> [#("nextPageToken", json.string(token))] + None -> [] + } + ]) + |> json.to_string +} + +/// One to seven pages. Page `i` points at page `i + 1`, or ends the listing, +/// or points back at a page already read, so cycles and long chains occur. +fn pages() -> Generator(List(Page)) { + use count <- qcheck.bind(qcheck.bounded_int(1, 7)) + use drafts <- qcheck.map(qcheck.fixed_length_list_from(page(), count)) + list.index_map(drafts, fn(draft, index) { + let #(page, link) = draft + let next = case index == count - 1, link { + True, 0 -> None + True, _ -> Some("") + False, 0 | False, 1 | False, 2 -> Some("p" <> int.to_string(index + 1)) + False, 3 -> None + False, _ -> Some("p" <> int.to_string(int.max(1, index))) + } + Page(..page, next:) + }) +} + +fn page() -> Generator(#(Page, Int)) { + use status <- qcheck.bind( + qcheck.from_weighted_generators(#(20, qcheck.return(200)), [ + #(1, qcheck.return(401)), + #(1, qcheck.return(500)), + ]), + ) + use broken <- qcheck.bind( + qcheck.from_weighted_generators(#(20, qcheck.return(False)), [ + #(1, qcheck.return(True)), + ]), + ) + use rows <- qcheck.bind(qcheck.generic_list(row(), qcheck.bounded_int(0, 4))) + use link <- qcheck.map(qcheck.bounded_int(0, 4)) + #(Page(status, broken, rows, None), link) +} + +fn row() -> Generator(Row) { + use id <- qcheck.bind(qcheck.bounded_int(0, 5)) + use form <- qcheck.bind(qcheck.bounded_int(0, 5)) + use generates <- qcheck.map(qcheck.bool()) + let id = "gemini-" <> int.to_string(id) + let name = case form { + 0 -> "" + 1 -> "models/" + 2 -> id + _ -> "models/" <> id + } + Row(name, generates) +} diff --git a/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/wire_test.gleam b/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/wire_test.gleam new file mode 100644 index 000000000..819db4ac0 --- /dev/null +++ b/extensions/google_ai_studio/test/albedo_ext_google_ai_studio/wire_test.gleam @@ -0,0 +1,32 @@ +//// How the Developer API's refusals read. Google can refuse a bad key with +//// HTTP 400 INVALID_ARGUMENT, which only its typed ErrorInfo tells apart +//// from a malformed request. The defects: a rejected key read as a bad +//// request, so /login is never suggested and rotation keeps the key, or a +//// malformed request read as a rejected key, so a good key is set aside. + +import albedo_ext_google_ai_studio/wire +import albedo_model as types + +fn body(reason: String) -> String { + "{\"error\":{\"code\":400,\"message\":\"API key not valid. Please pass a valid API key.\",\"status\":\"INVALID_ARGUMENT\",\"details\":[{\"@type\":\"type.googleapis.com/google.rpc.ErrorInfo\",\"reason\":\"" + <> reason + <> "\",\"domain\":\"googleapis.com\"}]}}" +} + +pub fn an_invalid_key_on_400_is_a_rejected_credential_test() -> Nil { + let assert types.Refused(types.CredentialRejected, _, _) = + wire.refusal(400, body("API_KEY_INVALID")) + Nil +} + +pub fn another_400_reason_is_not_a_rejected_credential_test() -> Nil { + let assert types.Refused(kind, _, _) = + wire.refusal(400, body("FIELD_VIOLATION")) + assert kind != types.CredentialRejected + let assert types.Refused(kind, _, _) = + wire.refusal( + 400, + "{\"error\":{\"code\":400,\"message\":\"API_KEY_INVALID in text only\",\"status\":\"INVALID_ARGUMENT\"}}", + ) + assert kind != types.CredentialRejected +} diff --git a/extensions/mistral/src/albedo_ext_mistral/accounts.gleam b/extensions/mistral/src/albedo_ext_mistral/accounts.gleam index 7b0cab9e0..b9552742a 100644 --- a/extensions/mistral/src/albedo_ext_mistral/accounts.gleam +++ b/extensions/mistral/src/albedo_ext_mistral/accounts.gleam @@ -56,25 +56,11 @@ pub fn select( let own = key_accounts.endpoint(account) own == "" || catalog.root(own) == endpoint }) - let selected = list.filter(saved, key_accounts.selected) - let saved = case selected { - [] -> saved - _ -> selected - } use environment <- result.try(key_accounts.environment_accounts( source, settings.endpoint, )) - let candidates = list.append(saved, environment) - let available = - list.filter(candidates, fn(account) { !key_accounts.limited(account) }) - let chosen = - list.first(list.append(available, candidates)) |> option.from_result - case chosen { - Some(account) -> key_accounts.remember(account, session) - None -> Nil - } - Ok(chosen) + Ok(key_accounts.choose_unbound(saved, environment, session)) } } use chosen <- result.try(chosen) diff --git a/packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam b/packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam index f17ce0260..709e67bb0 100644 --- a/packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/key_accounts.gleam @@ -185,6 +185,32 @@ pub fn stored(profile: Profile) -> Result(List(Account), String) { list.try_map(values, fn(value) { snapshot(profile, value) }) } +/// Choose for a session among a plain profile's candidates, one that names no +/// account: the saved keys the provider's endpoint policy accepts, then its +/// environment keys. The user's saved selection among them wins over the rest +/// of the saved keys, and an account not rate limited wins over a limited +/// one. The chosen account is remembered for the session, like `select`. +/// `None` when there are no candidates. +pub fn choose_unbound( + saved: List(Account), + environment: List(Account), + session: String, +) -> Option(Account) { + let saved = case list.filter(saved, selected) { + [] -> saved + chosen -> chosen + } + let candidates = list.append(saved, environment) + let available = list.filter(candidates, fn(account) { !limited(account) }) + case list.append(available, candidates) { + [] -> None + [account, ..] -> { + remember(account, session) + Some(account) + } + } +} + /// Environment candidates retain catalog discovery and their original values. pub fn environment_accounts( profile: Profile, diff --git a/robot-docs/auth.md b/robot-docs/auth.md index e8e5cbc70..e99507b6b 100644 --- a/robot-docs/auth.md +++ b/robot-docs/auth.md @@ -110,8 +110,12 @@ transport. Selection preserves inline profile keys, explicit account membership, and environment discovery. The shared `select` operation does not acquire saved sibling accounts for an unbound profile; provider-owned selection can have a -different policy. Session affinity is daemon-wide, as [rotation](#rotation) -describes. +different policy. Mistral and Google AI Studio take saved keys for an unbound +profile: each filters the saved keys and environment keys by its own endpoint +policy, then `choose_unbound` picks among them. The user's saved selection wins +over the other saved keys, and a key that is not rate limited wins over a +limited one. Use `choose_unbound` for such a policy rather than another copy of +that order. Session affinity is daemon-wide, as [rotation](#rotation) describes. Environment discovery reads the variables that the profile's account IDs name. OpenCode Go and Mistral also name their own variables. Other key stores ask a