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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349"""Perplexity is a model provider over its Agent API and a web search backendover its Search API, on one API key.
What only the running daemon wires together stays here: the Agent API outputceiling that the catalog gives an Anthropic model, a lasting limit attributedto an environment key the daemon never saves, and a key saved through`/auth/keys` authenticating the Search API, whose answers become the search'ssources. The Agent API body, priority tier, refusals and model list are checkedat the wire (extensions/perplexity/test/albedo_ext_perplexity/wire_test.gleam).
The search order and the saved key are global, so the class is exclusive."""
import astimport jsonimport threadingimport unittestfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from harness import ( Albedo, Provider, daemon_resource, exclusive, exclusive_class, operation_id, python, quota_error, text,)
MODEL = "openai/gpt-5.6-sol"
KEY = "pplx-fixture-key"
AGENT_MODELS = {"data": [{"id": MODEL}, {"id": "perplexity/kimi-k3"}]}
# What models.dev knows about the ids the Agent API lists, under each trainer's# own namespace: this is where the output ceilings in the tests come from.MODELS_DEV = { "openai": { "id": "openai", "name": "OpenAI", "models": { "gpt-5.6-sol": { "id": "gpt-5.6-sol", "limit": {"context": 272000, "output": 128000}, } }, }, # models.dev's own namespaces for the same endpoint. Its list is staler than # the Agent API's (a retired id here, a missing one below), so the picker # answering from these instead of the API is exactly what the ordering test # catches. "perplexity": { "id": "perplexity", "name": "Perplexity", "models": { "sonar-retired": { "id": "sonar-retired", "limit": {"context": 128000, "output": 8192}, } }, }, "perplexity-agent": { "id": "perplexity-agent", "name": "Perplexity Agent", "api": "https://api.perplexity.ai/v1", "env": ["PERPLEXITY_API_KEY"], "models": { "sonar-retired": { "id": "sonar-retired", "limit": {"context": 128000, "output": 8192}, } }, }, "anthropic": { "id": "anthropic", "name": "Anthropic", "models": { "claude-sonnet-5": { "id": "claude-sonnet-5", "limit": {"context": 200000, "output": 32000}, "reasoning_options": [ {"type": "effort", "values": ["low", "medium", "high"]} ], } }, },}
RESULTS = [ { "title": "Gleam one", "url": "https://gleam.run/news/one", "snippet": " the first page's text\n", "date": "2026-08-01", "last_updated": "2026-08-02", }, {"title": None, "url": "https://example.com/two", "snippet": "", "date": None}, {"title": "duplicate", "url": "https://gleam.run/news/one", "snippet": "again"},]
SEARCH = ( "r = await web_search('latest gleam release', limit=2)\n" "print(repr([r.answer, [(s.title, s.url, s.snippet, s.published)" " for s in r.sources]]))\n")
FAILING = ( "try:\n" " await web_search('latest gleam release')\n" "except Exception as error:\n" " print('raised:', error)\n")
class FakeSearch: """Answers /search with RESULTS and records what each request sent."""
def __init__(self): self.requests = [] owner = self
class Handler(BaseHTTPRequestHandler): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) owner.requests.append((self.path, self.headers["authorization"], body)) payload = json.dumps({"results": RESULTS, "id": "fixture"}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload)
def log_message(self, format, *args): pass
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) self.url = f"http://127.0.0.1:{self.server.server_address[1]}" threading.Thread(target=self.server.serve_forever, daemon=True).start()
def close(self): self.server.shutdown() self.server.server_close()
def scripting(replies): """Answers each request with the next scripted reply."""
def reply(request): return replies.pop(0) if replies else text("done")
return reply
@exclusive_classclass PerplexityTests(unittest.TestCase): def setUp(self): self.search = daemon_resource("search", FakeSearch) self.search.requests.clear()
def start(self, replies, *, key=True, prepare=None): provider = Provider( scripting(list(replies)), catalog=AGENT_MODELS, ) self.addCleanup(provider.close) profile = { "extension": "perplexity", "baseUrl": provider.url, "model": MODEL, "protocol": "responses", } if key: profile["apiKey"] = KEY
def offline(app): (app.home / "models.json").write_text(json.dumps(MODELS_DEV)) app.write_extensions({"perplexity": {"searchEndpoint": self.search.url}}) if prepare: prepare(app)
app = Albedo(provider, providers={"perplexity": profile}, prepare=offline) app.__enter__() self.addCleanup(app.__exit__, None, None, None) return app, provider
def put_key(self, app, endpoint="https://api.perplexity.ai/v1"): """Saves a key account the way /login does, and returns its id.""" account = operation_id() with app.api( f"/auth/keys/{account}", { "provider": "perplexity", "endpoint": endpoint, "api_key": KEY, "label": "fixture", }, method="PUT", ) as response: saved = json.load(response) self.assertEqual(saved["kind"], "key") return account
def ask(self, app, prompt="hello"): session = app.session() app.prompt(session, prompt).close() app.idle(session) return session
def output(self, app, session): """What the last python cell printed.""" results = [ json.loads(part["value"]) for entry in app.history(session)["items"] if entry["kind"] == "tool_result" and entry["tool"]["name"] == "python" for part in entry["content"] if part["kind"] == "json" and part["field"] == "result" ] return results[-1]["output"]
def test_an_anthropic_model_gets_the_cap_its_agent_api_requires(self): app, provider = self.start([text("capped")]) # Perplexity answers 400 to an anthropic/* request without a cap, so # that family gets its model's published maximum instead. route = "/settings/providers" with app.api(route) as response: revision = response.headers["ETag"] with app.api( route, {"profiles": {app.profile: {"model": "anthropic/claude-sonnet-5"}}}, method="PATCH", headers={ "If-Match": revision, "Content-Type": "application/merge-patch+json", }, ) as response: json.load(response) self.ask(app) body = provider.requests[0]["request"] self.assertEqual(body["model"], "anthropic/claude-sonnet-5") # Exactly what models.dev publishes for that model: a wrong field would # still be a positive number. self.assertEqual(body["max_output_tokens"], 32000)
# exclusive: the daemon environment and profile have no saved key @exclusive def test_direct_environment_fallback_attributes_a_lasting_limit(self): def prepare(app): app.env["PERPLEXITY_API_KEY"] = " environment-fixture-key "
app, provider = self.start([quota_error()], key=False, prepare=prepare) session = self.ask(app) self.assertEqual(len(provider.requests), 1) self.assertEqual( provider.requests[0]["authorization"], "Bearer environment-fixture-key" ) with app.api(f"/sessions/{session}/requests") as response: rows = json.load(response)["items"] self.assertEqual(rows[-1]["http_status"], 429) self.assertEqual(rows[-1]["account_id"], "$PERPLEXITY_API_KEY") # The loopback endpoint cannot discover the catalog variable, which is # why this request takes the direct fallback. A catalog-endpoint profile # makes that same environment account visible in the auth projection. route = "/settings/providers" with app.api(route) as response: revision = response.headers["ETag"] with app.api( route, { "profiles": { "env-observer": { "extension": "perplexity", "endpoint": "https://api.perplexity.ai/v1", "model": MODEL, "protocol": "responses", } } }, method="PATCH", headers={"If-Match": revision}, ) as response: response.read() with app.api("/auth") as response: accounts = json.load(response)["accounts"] account = next(row for row in accounts if row["id"] == "env:PERPLEXITY_API_KEY") self.assertIsNotNone(account["limited_until"]) for name in ("creds.json", "config.json"): path = app.home / name self.assertNotIn( "environment-fixture-key", path.read_text() if path.exists() else "" )
# exclusive: prepares its own web-search settings @exclusive def test_search_answers_with_the_search_apis_sources(self): def prepare(app): (app.home / "models.json").write_text(json.dumps(MODELS_DEV)) app.write_extensions( { "perplexity": {"searchEndpoint": self.search.url}, "web-search": { "order": ["perplexity"], "off": ["codex", "claude", "antigravity", "exa"], }, } )
# The session runs on the harness's own profile: the Search API's key # belongs to the perplexity extension, not to whichever model answers. provider = Provider(scripting([python(FAILING)]), catalog=AGENT_MODELS) self.addCleanup(provider.close) app = Albedo(provider, prepare=prepare) app.__enter__() self.addCleanup(app.__exit__, None, None, None) session = app.session() # No key yet: the search names what is missing instead of reaching out. app.prompt(session, "search without a key").close() app.idle(session) self.assertEqual(self.search.requests, []) self.assertIn("Perplexity needs an API key", self.output(app, session)) self.put_key(app) provider.script = scripting([python(SEARCH)]) app.prompt(session, "search").close() app.idle(session) path, authorization, body = self.search.requests[-1] self.assertEqual(path, "/search") self.assertEqual(authorization, f"Bearer {KEY}") self.assertEqual(body["query"], "latest gleam release") self.assertEqual(body["max_results"], 2) self.assertGreater(body["max_tokens_per_page"], 0) # One source per url, cut to the limit, with the page's own text. self.assertEqual( ast.literal_eval(self.output(app, session).splitlines()[0]), [ "", [ ( "Gleam one", "https://gleam.run/news/one", "the first page's text", "2026-08-01", ), ("https://example.com/two", "https://example.com/two", "", None), ], ], )