diff --git a/.env.example b/.env.example index 10590f3..f980a97 100644 --- a/.env.example +++ b/.env.example @@ -68,6 +68,13 @@ MODEL_NAME=google/gemini-2.5-flash # OMNIJEV_BASE=Qwen/Qwen3.5-0.8B # the Qwen3.5 backbone of the same size # OMNIJEV_PROMPT=full # full: text state + goal + rules; short: goal + ask over the screenshot +# ---- GLiDE (behind --model glide; hosted Fastino or a local /v1/systemone server) ---- +# GLIDE_URL=http://127.0.0.1:8000 # local glide.server; wins over hosted Fastino when set +# FASTINO_API_KEY= # hosted https://api.fastino.ai/v1/systemone, used only when GLIDE_URL is unset +# GLIDE_MODEL=fastino/GLiDE # or a GLiDE model id you deployed. Omitting it on the wire is 422 +# GLIDE_API_KEY= # when a local server expects X-API-Key +# GLIDE_TIMEOUT_S=30 # per decision, including transport / 502 / 504 and Fastino 425 / 429 / 503 retries + # ---- Optional Cua-S1 4B ---- # uv sync --extra cua-four-b (separate from the Laya demo). # CUA_S1_VARIANT=4b diff --git a/CHANGELOG.md b/CHANGELOG.md index 37b99a8..1ccb475 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); ver ## Unreleased +### Added + +- `--model glide`: [GLiDE](https://arxiv.org/abs/2611.26509) as a **served** System One client against hosted + Fastino (`FASTINO_API_KEY`, `POST https://api.fastino.ai/v1/systemone`) or a local `glide.server` (`GLIDE_URL`). + Request `model` defaults to `fastino/GLiDE` (`GLIDE_MODEL`). Posts choice/noul; screenshots travel as GLiDE + `state` `image_url` data-URL parts (JPEG/PNG/GIF/WebP, max 4), not Clef `images` or OneJev `media`. Hosted + evals send `store: false`. `score` questions are unsupported on our interface. Weights use the Fastino + Community License and are not vendored. Contract tests use a fake HTTP server; live Fastino / GPU + qualification is not claimed (#129). + ## 0.4.0 - 2026-11-13 ### Added diff --git a/NOTICE b/NOTICE index d66d358..227dd49 100644 --- a/NOTICE +++ b/NOTICE @@ -23,3 +23,5 @@ This product includes software developed by third parties: Beurer-Kellner, Marc Fischer, and Florian Tramèr). Full license text: THIRD_PARTY_LICENSES.md - s1a/decision_models/onejev.py: HTTP client for OneJev / qev (OmniJev/OneJev), Apache-2.0; the weights and server are not vendored. Details: THIRD_PARTY_LICENSES.md +- s1a/decision_models/glide.py: HTTP client for Fastino GLiDE; the weights are under the Fastino + Community License and are not vendored. Details: THIRD_PARTY_LICENSES.md diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index ac25900..f37d51c 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -126,3 +126,12 @@ OneJev and its serving code are Apache License 2.0 (Copyright OmniJev Team). Thi vendor OneJev weights, training code, or the `qev`/`flide` packages; install and run them separately per the model card. The unrelated PyPI package named `qev` is not the OneJev server — install from the OneJev GitHub repository as the model card instructs. + +## Fastino GLiDE + +The `--model glide` adapter (`s1a/decision_models/glide.py`) talks to Fastino GLiDE through the hosted +API (`POST https://api.fastino.ai/v1/systemone`) or a local `glide.server`. GLiDE weights (for example +[fastino/GLiDE-27B](https://huggingface.co/fastino/GLiDE-27B)) are under the Fastino Community License, +not Apache-2.0. This repository does not vendor GLiDE weights, training code, or the `glide` serving +package; use the hosted API or install and run a local server separately per the model card and +https://docs.fastino.ai/inference/systemone. diff --git a/docs/agents.md b/docs/agents.md index 087cf1a..c1256d4 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -17,12 +17,12 @@ hook of a running agent. The injection guard rail fails closed: a decision error | `blackjack` | tool | payoff per hand (RLCard) | `s1a run blackjack --model jev --rethink off --episodes 100` | | `injection_guard` | rail | precision and recall on a labelled injection set | `s1a run injection_guard` | -Every tool agent takes `--model jev|clm|laya|laya-served|cua|llm|random|rule`, `--rethink on|off`, `--episodes N`, `--seed S`, +Every tool agent takes `--model jev|clm|laya|laya-served|cua|glide|llm|random|rule`, `--rethink on|off`, `--episodes N`, `--seed S`, `--max-steps` and `--timeout`, and writes a Harbor-shaped job folder under `evals/results//`. A browser agent -takes `--model jev|clm|laya|laya-served|cua|omnijev|onejev|llm`, `--goal` and the same `--rethink` flag. +takes `--model jev|clm|laya|laya-served|cua|omnijev|onejev|glide|llm`, `--goal` and the same `--rethink` flag. The desktop agent adds `--rethink-attempts` and `--rethink-timeout` and stalls after 3 actions without observed progress. The browser front takes the same three names; `docs/browser-front.md` decision 19 describes its branch. A rail takes -`--model jev|clm|laya|laya-served`, the models that answer `noul`. +`--model jev|clm|laya|laya-served|glide`, the models that answer `noul`. `uv run python -m evals.table evals/results` aggregates every job folder per eval and model into one table. Every `run` prints one JSON object on stdout and nothing else there; `s1a-mcp` serves the same agents over stdio diff --git a/docs/architecture.md b/docs/architecture.md index 09e67a9..021e88a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -51,10 +51,11 @@ validation; `docs/decision-models.md`), `s1a/decision_models/wire.py` (the HTTP | `cua` | [Cua-S1 Nano](https://huggingface.co/cua-ai/cua-s1-nano-0.1) (`cua-ai/cua-s1-nano-0.1`, 855K) | in process, `uv sync --extra cua`; no key | a 256-byte context (header, goal, state, then rules), 96 bytes per option | | `omnijev` | [OmniJev](https://github.com/tinnel123666888/OmniJev) (Qwen3.5 VL, 0.8B by default, 2B or 4B) | in process, browser agents only, `uv sync --extra omnijev` and a clone named by `OMNIJEV_REPO`; no key; a GPU for useful speed | a viewport screenshot per tick, plus the text state (recent actions first, page text capped at 2,000 characters) | | `onejev` | [OneJev](https://github.com/OmniJev/OneJev) (0.8B–27B, Apache-2.0) via `qev`/`flide` | served HTTP, browser agents only; `ONEJEV_URL`; no cloud key | a viewport screenshot per tick as `media` with `` in state | +| `glide` | [GLiDE](https://arxiv.org/abs/2611.26509) (Fastino Community License) | served HTTP: `GLIDE_URL` (local `/v1/systemone`) or hosted Fastino (`FASTINO_API_KEY`); `GLIDE_MODEL` defaults to `fastino/GLiDE` | text state; optional screenshots as GLiDE `state` image parts (max 4). No `score` questions on our interface. Hosted evals send `store: false` | | `random`, `rule` | the tool front's two baselines | in process | the candidates | | `llm` | the chat model | for the comparison columns | the transcript | -`decision_models.build_model(model_name)` builds the first six; `llm` is not a decision model. +`decision_models.build_model(model_name)` builds every `--model` name except `llm`, which is not a decision model. ## Entry points @@ -64,17 +65,17 @@ the first import of both, routes the harness logs to files under `runs/logs` bef MCP stdio protocol only. Every `run` prints one JSON object on stdout: a tool agent's series summary with its `job_dir`, a browser agent's -answer, a rail's evaluation. A browser agent takes `--model jev|laya|cua|omnijev|onejev|llm`; its policy switches are run-time flags: +answer, a rail's evaluation. A browser agent takes `--model jev|laya|cua|omnijev|onejev|glide|llm`; its policy switches are run-time flags: `--batch on|off`, `--prefetch on|off`, `--goal-values on|off`. `s1a-mcp` serves the same agents to an MCP host over stdio, one Runner for the server's lifetime and one run at a time. `uv run python -m evals.table evals/results` aggregates every job folder per eval and model into one table. `scripts/showcase.sh` plays one visual episode per eval and model outside the matrix and `python -m evals.replay` renders a pair side by side, with a GIF; see `evals/README.md`. -Every tool agent, `desktop` included, takes `--model jev|laya|cua|llm|random|rule`, `--rethink on|off`, +Every tool agent, `desktop` included, takes `--model jev|laya|cua|glide|llm|random|rule`, `--rethink on|off`, `--episodes N`, `--seed S`, `--max-steps`, `--timeout` and `--headed`, and writes a Harbor-shaped job folder under -`evals/results//`. Every browser agent takes `--model jev|laya|cua|omnijev|onejev|llm` and `--goal`. A rail takes -`--model jev|laya`, the two models that answer `noul`. `decide` and `probe` take `--model jev|laya|cua`. On a browser +`evals/results//`. Every browser agent takes `--model jev|laya|cua|omnijev|onejev|glide|llm` and `--goal`. A rail takes +`--model jev|laya|glide`, the models that answer `noul`. `decide` and `probe` take `--model jev|laya|cua|glide`. On a browser agent `laya` needs `LAYA_MAX_LEN` raised to the page's size; `cua` reads a 256-byte context (header, goal, state, then rules) and 96 bytes per option, a baseline on any page. Exit codes: 0 for a finished run, including one whose JSON has `ok: false`; 1 for a run, key, model or file error, one line on stderr; 2 for a usage error (an unknown diff --git a/docs/capabilities.md b/docs/capabilities.md index f427af6..7745896 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -17,6 +17,7 @@ For issue trackers and serving support, see [System1-Omni model tracker #83](htt | LAYA (`--model laya-served`; served checkpoint/revision is reported by the endpoint) | Text | `choice`, `noul` | Tool, browser, rails, `decide`/`probe`, MCP | Agents HTTP client can connect directly to a Laya worker or through System1-Omni `omni-jev` at `/v1/systemone` | Historical direct-worker and Omni-front MPS ticket-router measurements are recorded below (90 decisions/configuration, 63 correct each); historical CPU served request replay is separate and is not task-success evidence. Other hardware/checkpoints unverified. | | OmniJev (`--model omnijev`; default `tinnel123/OmniJev-0.8B@v1.1` on `Qwen/Qwen3.5-0.8B`; configurable 2B/4B) | Screenshot plus text state/context | `choice`, `noul` | Browser front via `s1a run` and MCP `run_agent`; direct `build_model()` factory path. Not registered in tool/rails, CLI `decide`/`probe`, or MCP `decide` | In-process OmniJev clone via `MSO1.system_one`; no System1-Omni served vision path | Historical A100 80 GB 4B runs, Windows 11 CPU 0.8B runs, and A40 46 GB 4B runs are detailed below. They do not establish broad task success; current-main reproduction unverified. | | OneJev (`--model onejev`; default request id `OmniJev/OneJev1.6-4B`; set `ONEJEV_MODEL`) | Screenshot(s) plus text state/context via TypeSafe `media` / `` | `choice`, `noul` | Browser front via `s1a run` and MCP `run_agent`; direct `build_model()` factory path. Not registered in tool/rails, CLI `decide`/`probe`, or MCP `decide` | HTTP client to `qev`/`flide` at `ONEJEV_URL` (`POST /v1/systemone` + `media`) | Contract tests use a fake HTTP server. Live GPU / GGUF hardware validation **not recorded in this checkout** (#88). | +| GLiDE (`--model glide`; default request id `fastino/GLiDE`; set `GLIDE_MODEL`) | Text state; optional screenshots as GLiDE `state` `image_url` data-URL parts (JPEG/PNG/GIF/WebP, max 4) | `choice`, `noul`; Fastino also defines `score`, but Agents has no corresponding question type | Tool, browser, rails, `decide`/`probe`, MCP | HTTP `POST /v1/systemone` to hosted Fastino (`FASTINO_API_KEY`) or a local `glide.server` (`GLIDE_URL`). Hosted evals send `store: false`. Weights are Fastino Community License, not Apache-2.0, and are not vendored | **Adapter wired** only: contract tests use a fake HTTP server. Live Fastino / local-GPU qualification **not recorded in this checkout** (#129). Do not treat Fastino's or Artificial Analysis Decision Index figures as Agents results. | | Cua-S1 Nano (`cua-ai/cua-s1-nano-0.1/text`, `--model cua`, default variant) | Text | `choice` only | Tool/browser paths where registered; no screenshot input | In-process `cua_s1.nano.NanoScorer` | No real Nano inference artifact found in this checkout. **CPU/GPU/MPS unverified here.** | | Cua-S1 4B 0.2 text adapter (`Qwen/Qwen3.5-4B` + `cua-ai/cua-s1-4b-0.2/text`, `CUA_S1_VARIANT=4b`, `CUA_S1_MODALITY=text`) | Text | `choice` only | Tool decisions and text-only client paths; desktop option grounding is implemented | In-process Transformers/PEFT scorer | Contract tests use a fake scorer; real checkpoint/device validation **not present in this checkout**. | | Cua-S1 4B 0.2 multimodal adapter (`Qwen/Qwen3.5-4B` + `cua-ai/cua-s1-4b-0.2/multimodal`, variant `4b`) | One current screenshot plus text task/context | `choice` only; maximum 26 options in text and multimodal modes; multimodal requires exactly one screenshot | Screenshot-dependent desktop decision adapter; this does not itself complete the Omni capture/execute bridge | In-process Transformers/PEFT scorer with screenshot passed as a temporary file | Contract tests use a fake scorer; separate historical external evidence reports a bounded MPS fixture run (see below). Current-main reproduction and CUDA validation remain unverified. | diff --git a/docs/configuration.md b/docs/configuration.md index e03db7c..630afba 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -57,6 +57,11 @@ Variables can be exported in your shell or placed in a `.env` file at the root o | `ONEJEV_MODEL` | `onejev` model | `OmniJev/OneJev1.6-4B` | Model id sent in the `/v1/systemone` body (checkpoint the server loaded, e.g. `OmniJev/OneJev1.6-0.8B`). | | `ONEJEV_API_KEY` | `onejev` model | *(unset)* | Bearer token when the server expects one; loopback `qev`/`flide` usually needs none. | | `ONEJEV_TIMEOUT_S` | `onejev` model | `30` | Deadline per decision in seconds, the one refused-connection / 502 / 504 retry included. A finite number above 0. Raise for large checkpoints or a cold load. | +| `GLIDE_URL` | `glide` model | *(unset)* | Base URL of a local `glide.server`, e.g. `http://127.0.0.1:8000`. Wins over hosted Fastino when set. | +| `FASTINO_API_KEY` | `glide` model | *(unset)* | Fastino API key, sent as `X-API-Key`, used when `GLIDE_URL` is unset. Required for the hosted path. | +| `GLIDE_MODEL` | `glide` model | `fastino/GLiDE` | Model id sent in the `/v1/systemone` body (or a GLiDE id you deployed). The hosted response echoes the engine name as `glide`. | +| `GLIDE_API_KEY` | `glide` model | *(unset)* | `X-API-Key` when a local server expects one; loopback `glide.server` usually needs none. | +| `GLIDE_TIMEOUT_S` | `glide` model | `30` | Deadline per decision in seconds, including the transport / 502 / 504 retry and bounded Fastino `425` / `429` / `503` retries (`Retry-After`). A finite number above 0. Fastino recommends a 300 s read timeout if you wait out a cold model; raise this accordingly. | | `CUA_DRIVER_BIN` | `desktop` agent | `cua-driver` | Path to the `cua-driver` executable on Windows or macOS when not located on `PATH`. | | `CUA_DRIVER_PERMISSION_MODE` | `desktop` agent | `standard` | Permission mode passed to `cua-driver mcp` (`standard`, or `bounded` for restricted capability manifests). | | `HF_HOME` | Hugging Face runtime | `~/.cache/huggingface` | Cache directory where Laya and Cua-S1 checkpoints are downloaded on first run. | diff --git a/docs/decision-models.md b/docs/decision-models.md index 0ca3c5b..5517ee2 100644 --- a/docs/decision-models.md +++ b/docs/decision-models.md @@ -101,6 +101,30 @@ ONEJEV_URL=http://127.0.0.1:8000 ONEJEV_TIMEOUT_S=60 \ This is a setup recipe only. Capability registration and stub-server contract tests do **not** establish task success rates or hardware validation; see [capabilities.md](capabilities.md). +### Served GLiDE + +`glide` is registered in `build_model()` and on the tool, browser, rails, `decide`/`probe` and MCP fronts. Point +`GLIDE_URL` at a local [`glide.server`](https://huggingface.co/fastino/GLiDE-27B), or set `FASTINO_API_KEY` for +the [hosted Fastino API](https://docs.fastino.ai/inference/systemone). `GLIDE_MODEL` defaults to `fastino/GLiDE`. +The existing Jev question builder is reused (`instructions` as a JSON object, which Fastino accepts). Browser +element rows in choice `criteria` are flattened to description strings. Hosted requests send `store: false`. +Screenshots become `state` `image_url` data-URL parts (max 4; JPEG/PNG/GIF/WebP); a text observation still runs. +`score` questions are unsupported on our interface. The weights are under the Fastino Community License and are +not vendored. Example (not run in CI; needs a Fastino key or a local server, and is not a qualification record): + +```bash +# local server, as on the GLiDE-27B model card +# python -m glide.server --model /models/GLiDE-27B --port 8000 +GLIDE_URL=http://127.0.0.1:8000 uv run s1a probe path/to/cases.jsonl --model glide + +# hosted Fastino +FASTINO_API_KEY=... uv run s1a probe path/to/cases.jsonl --model glide +``` + +The capability matrix distinguishes this **adapter wiring** from qualification on a named checkpoint and path: +no live Fastino or GPU run is recorded in this checkout, and published Decision Index / Artificial Analysis +numbers are not Agents results. + ### Served JEV-VL `jev-vl-served` is registered in the browser front and `build_model()`. It sends the observation's text state, diff --git a/s1a/browser/browse.py b/s1a/browser/browse.py index 81adfed..0ae2f3b 100644 --- a/s1a/browser/browse.py +++ b/s1a/browser/browse.py @@ -49,6 +49,7 @@ "cua", "omnijev", "onejev", + "glide", "llm", ) # a decision model over HTTP or in process, or the chat model RUNS_DIR = HOME / "runs" / "browser" @@ -254,7 +255,7 @@ async def browse( workspace = str(logs_dir / "workspace") # the harness scaffolds SOUL.md, memory/ and friends here, not in the cwd instance = BrowserInstanceConfig(launch_args=browser_launch_args(headless)) match model_name: - case "jev" | "jev-vl-served" | "clm" | "laya" | "laya-served" | "cua" | "omnijev" | "onejev": + case "jev" | "jev-vl-served" | "clm" | "laya" | "laya-served" | "cua" | "omnijev" | "onejev" | "glide": if decision_model is None: raise RuntimeError(f"--model {model_name} needs a decision model") slot_model = BrowserDecisionModel( @@ -321,7 +322,7 @@ def parser(spec: BrowserAgentSpec) -> argparse.ArgumentParser: "--model", choices=BROWSER_MODEL_NAMES, required=True, - help="who decides each browser step: jev, jev-vl-served, clm, laya-served or onejev (over HTTP; jev-vl-served and onejev require a screenshot), laya, cua or omnijev (in process; omnijev reads a screenshot), or llm (the chat model in MODEL_NAME)", + help="who decides each browser step: jev, jev-vl-served, clm, laya-served, onejev or glide (over HTTP; jev-vl-served and onejev require a screenshot), laya, cua or omnijev (in process; omnijev reads a screenshot), or llm (the chat model in MODEL_NAME)", ) build.add_argument( "--goal", default=spec.goal, required=spec.goal is None, help="the task; the spec's goal when it has one" diff --git a/s1a/cli.py b/s1a/cli.py index 6a868f8..a907a0f 100644 --- a/s1a/cli.py +++ b/s1a/cli.py @@ -25,6 +25,7 @@ "laya", "laya-served", "cua", + "glide", ) # the decision models that answer one question on their own: no env, no rule, no chance @@ -40,7 +41,7 @@ def parser() -> argparse.ArgumentParser: run.add_argument("flags", nargs=argparse.REMAINDER) decide = commands.add_parser( "decide", - help="one choice question to a decision model: jev, clm or laya-served over HTTP, or laya and cua in process", + help="one choice question to a decision model: jev, clm, laya-served or glide over HTTP, or laya and cua in process", ) decide.add_argument("--state", required=True, help="a JSON object, or @path to a file holding one") decide.add_argument( @@ -55,7 +56,7 @@ def parser() -> argparse.ArgumentParser: "--model", choices=DECIDE_MODEL_NAMES, default="jev", - help="who answers: jev, clm or laya-served over HTTP, laya and cua in process", + help="who answers: jev, clm, laya-served or glide over HTTP, laya and cua in process", ) fit = commands.add_parser("probe", help="the fit probe: hand-written choice cases from a JSONL file") fit.add_argument( @@ -67,7 +68,7 @@ def parser() -> argparse.ArgumentParser: "--model", choices=DECIDE_MODEL_NAMES, default="jev", - help="who answers: jev, clm or laya-served over HTTP, laya and cua in process", + help="who answers: jev, clm, laya-served or glide over HTTP, laya and cua in process", ) fit.add_argument( "--order", diff --git a/s1a/decision_models/__init__.py b/s1a/decision_models/__init__.py index b3bdab2..6ec3e3e 100644 --- a/s1a/decision_models/__init__.py +++ b/s1a/decision_models/__init__.py @@ -11,6 +11,7 @@ from s1a.decision_models.baselines import RandomModel, Rule, RuleModel from s1a.decision_models.cua import CuaS1Model from s1a.decision_models.factory import DECISION_MODEL_NAMES, build_model +from s1a.decision_models.glide import GlideModel from s1a.decision_models.fakes import ScriptedModel, ScriptedTransport from s1a.decision_models.jev import JevModel, jev_question from s1a.decision_models.laya import LayaModel @@ -57,6 +58,7 @@ "Noul", "NoulQuestion", "OmniJevModel", + "GlideModel", "OneJevModel", "Observation", "Question", diff --git a/s1a/decision_models/factory.py b/s1a/decision_models/factory.py index ea1cf33..551a516 100644 --- a/s1a/decision_models/factory.py +++ b/s1a/decision_models/factory.py @@ -14,6 +14,7 @@ from s1a.decision_models.jev_vl_served import ServedJevVLModel from s1a.decision_models.laya import LayaModel from s1a.decision_models.omnijev import OmniJevModel +from s1a.decision_models.glide import GlideModel from s1a.decision_models.onejev import OneJevModel from s1a.decision_models.served import ServedLayaModel @@ -26,6 +27,7 @@ "cua", "omnijev", "onejev", + "glide", "random", "rule", ) # the names that build a decision model; ``llm`` is not one @@ -55,6 +57,8 @@ def build_model(model_name: str, *, seed: int = 0, rule: tuple[str, Rule] | None return OmniJevModel.from_env() # the OmniJev import happens inside; it decides over a screenshot case "onejev": return OneJevModel.from_env() # OneJev/qev over HTTP with media; screenshot required + case "glide": + return GlideModel.from_env() # Fastino GLiDE or local glide.server; images optional case "random": return RandomModel(seed) case "rule": diff --git a/s1a/decision_models/glide.py b/s1a/decision_models/glide.py new file mode 100644 index 0000000..1e7ab74 --- /dev/null +++ b/s1a/decision_models/glide.py @@ -0,0 +1,401 @@ +# coding: utf-8 +"""GLiDE served over HTTP: hosted Fastino or a local ``glide.server``. + +GLiDE (https://arxiv.org/abs/2611.26509) is a family of decision models that score typed questions in one +forward pass. Hosted inference is ``POST https://api.fastino.ai/v1/systemone`` with model id ``fastino/GLiDE``; +a local server (``python -m glide.server``) speaks the same path. This adapter never loads weights. Weights are +under the Fastino Community License, not Apache-2.0, and are not vendored. ``score`` questions are out of scope: +Agents has no ``ScoreQuestion``. +""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import logging +import math +import os +import time +import uuid +from collections.abc import Awaitable, Callable +from datetime import datetime, timezone + +import httpx + +from openjiuwen.core.common.exception.codes import StatusCode +from openjiuwen.core.common.exception.errors import build_error + +from s1a.decision_models.base import DecisionModel +from s1a.decision_models.jev import jev_question +from s1a.decision_models.omnijev import omnijev_option +from s1a.decision_models.served import parse_server_timing +from s1a.decision_models.types import ChoiceQuestion, Image, Json, Observation, Question, Reply, Usage + +logger = logging.getLogger(__name__) + +HOSTED_GLIDE_URL = "https://api.fastino.ai/v1/systemone" +DEFAULT_GLIDE_MODEL = "fastino/GLiDE" +GLIDE_TIMEOUT_S = 30.0 +MAX_GLIDE_IMAGES = 4 # official Fastino limit +MAX_GLIDE_IMAGE_BYTES = 3_932_160 # 3.75 MiB raw; 5 MiB of base64 in a data URL +MAX_TRANSIENT_RETRIES = 5 # 425 / 429 / 503, within the decision deadline +DEFAULT_WARMUP_RETRY_S = 30.0 # Fastino's default when a 425 has no Retry-After +DEFAULT_TRANSIENT_RETRY_S = 1.0 +_MEDIA_TYPES = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp"}) +_RETRIED_TRANSPORT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.RemoteProtocolError, httpx.ReadError) +_RETRIED_STATUSES = frozenset({502, 504}) +_TRANSIENT_STATUSES = frozenset({425, 429, 503}) +_NOT_UP_HOSTED = "the Fastino GLiDE API needs a valid FASTINO_API_KEY; see https://docs.fastino.ai/inference/systemone" +_NOT_UP_LOCAL = ( + "a GLiDE server listens at /v1/systemone once the checkpoint is loaded; start it per " + "https://huggingface.co/fastino/GLiDE-27B and point GLIDE_URL at it" +) + + +def retry_after_s(response: httpx.Response, *, default: float) -> float: + """Seconds to wait before the next attempt: ``Retry-After`` as a delay, or ``default`` when missing or unusable.""" + raw = response.headers.get("Retry-After") or response.headers.get("retry-after") + if raw is None or not str(raw).strip(): + return default + try: + delay = float(str(raw).strip()) + except ValueError: + return default + if not math.isfinite(delay) or delay < 0: + return default + return delay + + +def glide_image(image: Image) -> tuple[Json, Json]: + """One GLiDE ``state`` image part (inline data URL) and the digest the step record keeps instead of the bytes. + + Official Fastino schema: ``{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,..."}}``. + Remote URLs are not used: the local server does not fetch them, and a data URL works on both paths. + """ + if image.media_type not in _MEDIA_TYPES: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=f"glide cannot send media type {image.media_type!r}; use JPEG, PNG, GIF or WebP", + ) + if not image.data: + raise build_error(StatusCode.MODEL_CALL_FAILED, error_msg="glide cannot send an empty screenshot") + if len(image.data) > MAX_GLIDE_IMAGE_BYTES: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=( + f"glide accepts at most {MAX_GLIDE_IMAGE_BYTES} bytes per image per the Fastino limit, " + f"not {len(image.data)}" + ), + ) + data_uri = f"data:{image.media_type};base64,{base64.b64encode(image.data).decode('ascii')}" + part: Json = {"type": "image_url", "image_url": {"url": data_uri}} + record: Json = { + "sha256": hashlib.sha256(image.data).hexdigest(), + "media_type": image.media_type, + "bytes": len(image.data), + } + return part, record + + +def glide_images(images: tuple[Image, ...]) -> tuple[list[Json], list[Json]]: + """Every screenshot as a state part, or a call failure past Fastino's max of four.""" + if len(images) > MAX_GLIDE_IMAGES: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=f"glide accepts at most {MAX_GLIDE_IMAGES} images per the Fastino limit, not {len(images)}", + ) + parts: list[Json] = [] + records: list[Json] = [] + for image in images: + part, record = glide_image(image) + parts.append(part) + records.append(record) + return parts, records + + +def glide_question(question: Question) -> Json: + """Choice / noul in Fastino's System One shape, reused from ``jev_question``. + + Fastino accepts ``instructions`` as a non-empty string or a non-empty JSON object, so the existing Jev + object (``goal`` / ``operation`` / ``rules``, or ``{question: ...}`` for noul) is sent as-is when it is + non-empty. An empty instructions object is mapped to a short fallback string (Fastino rejects empty + instructions with 422). Choice ``criteria`` values that are not already strings (browser element rows) + are flattened with ``omnijev_option``, because Fastino documents criteria as option keys to descriptions. + """ + body = jev_question(question) + instructions = body.get("instructions") + if instructions == {} or instructions is None or instructions == "": + fallback = "Which option comes next?" if isinstance(question, ChoiceQuestion) else "Does this hold?" + if isinstance(question, ChoiceQuestion) and question.goal: + fallback = question.goal + body["instructions"] = fallback + criteria = body.get("criteria") + if isinstance(criteria, dict): + body["criteria"] = { + key: value if isinstance(value, str) else omnijev_option(value) for key, value in criteria.items() + } + return body + + +def glide_state(observation: Observation) -> Json | str | list[Json]: + """Text state as-is, or a part array when the observation has screenshots. + + Fastino's image layout is ``state`` parts, not Clef's ``images`` array and not OneJev's ``media``. A dict + or other non-string state is sent as a compact-JSON text part so the array only mixes text parts with + ``image_url`` parts, as the official docs describe. + """ + if not observation.images: + return observation.state + parts, _records = glide_images(observation.images) + state = observation.state + if isinstance(state, str): + text = state + else: + text = json.dumps(state, ensure_ascii=False, separators=(",", ":")) + prefix: list[Json] = [{"type": "text", "text": text}] if text else [] + return [*prefix, *parts] + + +def glide_payload(body: object) -> Json: + """The System One decision object, or a call failure when ``answers`` is missing or not an object.""" + if not isinstance(body, dict) or not isinstance(body.get("answers"), dict): + raise build_error(StatusCode.MODEL_CALL_FAILED, error_msg="glide returned no answers object") + return body + + +class GlideClient: + """HTTP to one GLiDE endpoint: one deadline per decision, transport / 502 / 504 plus Fastino 425 / 429 / 503.""" + + def __init__( + self, + *, + url: str, + endpoint: str, + api_key: str | None = None, + timeout_s: float = GLIDE_TIMEOUT_S, + transport: httpx.AsyncBaseTransport | None = None, + clock: Callable[[], float] = time.monotonic, + sleeper: Callable[[float], Awaitable[None]] | None = None, + path: str = "local", + ) -> None: + if not math.isfinite(timeout_s) or timeout_s <= 0: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg=f"timeout_s must be a finite number above 0, not {timeout_s!r}", + ) + self.url = url.rstrip("/") + self.endpoint = endpoint + self.path = path + self._timeout_s = timeout_s + self._clock = clock + self._sleeper = sleeper or asyncio.sleep + self._not_up = _NOT_UP_HOSTED if path == "hosted" else _NOT_UP_LOCAL + headers = {"X-API-Key": api_key} if api_key else {} + self._client = httpx.AsyncClient(timeout=timeout_s, headers=headers, transport=transport) + + async def decide(self, body: Json, request_id: str) -> tuple[Json, int, dict[str, str]]: + """One decision: the payload, its round trip in ms and the response headers.""" + headers = {"X-Request-Id": request_id} + deadline = self._clock() + self._timeout_s + retried = False + transient = 0 + while True: + remaining = deadline - self._clock() + if remaining <= 0: + raise self._no_answer(None) + started = time.perf_counter() + post = self._client.post(self.endpoint, json=body, headers=headers, timeout=remaining) + try: + response = await asyncio.wait_for(post, remaining) + except TimeoutError as exc: + raise self._no_answer(exc) from exc + except _RETRIED_TRANSPORT as exc: + if not retried: + retried = True + continue + if isinstance(exc, httpx.ConnectError): + raise build_error( + StatusCode.MODEL_CALL_FAILED, + cause=exc, + error_msg=f"no served GLiDE at {self.url}: {self._not_up}", + ) from exc + raise build_error( + StatusCode.MODEL_CALL_FAILED, + cause=exc, + error_msg=f"served GLiDE unreachable at {self.url}: {exc}", + ) from exc + except httpx.HTTPError as exc: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + cause=exc, + error_msg=f"served GLiDE call failed at {self.url}: {exc}", + ) from exc + ms = round((time.perf_counter() - started) * 1000) + if response.status_code in _RETRIED_STATUSES and not retried: + retried = True + continue + if response.status_code in _TRANSIENT_STATUSES and transient < MAX_TRANSIENT_RETRIES: + default = DEFAULT_WARMUP_RETRY_S if response.status_code == 425 else DEFAULT_TRANSIENT_RETRY_S + delay = retry_after_s(response, default=default) + if deadline - self._clock() - delay <= 0: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=(f"served GLiDE failed (HTTP {response.status_code}): {response.text[:200].strip()}"), + ) + transient += 1 + await self._sleeper(delay) + continue + if response.is_error: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=f"served GLiDE failed (HTTP {response.status_code}): {response.text[:200].strip()}", + ) + try: + raw = response.json() + except ValueError as exc: + raise build_error( + StatusCode.MODEL_CALL_FAILED, cause=exc, error_msg="served GLiDE returned a malformed body" + ) from exc + return glide_payload(raw), ms, dict(response.headers) + + def _no_answer(self, cause: Exception | None) -> Exception: + return build_error( + StatusCode.MODEL_CALL_FAILED, + cause=cause, + error_msg=f"no answer from served GLiDE at {self.url} within {self._timeout_s:g} s; {self._not_up}", + ) + + async def close(self) -> None: + await self._client.aclose() + + +class GlideModel(DecisionModel): + """GLiDE behind Fastino or ``/v1/systemone``: choice and noul; images when the observation has them.""" + + name = "glide" + supports_images = True + deterministic = True + bills_input_tokens = False # do not price GLiDE at Jev's rate; Fastino has its own list price + + def __init__(self, client: GlideClient, *, model: str = DEFAULT_GLIDE_MODEL) -> None: + if not model.strip(): + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg="GLIDE_MODEL must be a non-empty model id, e.g. fastino/GLiDE", + ) + self._client = client + self._model = model + self._served_at: str | None = None + + @property + def model(self) -> str: + return self._model + + async def warm(self) -> None: + self._served_at = datetime.now(timezone.utc).isoformat(timespec="seconds") + + def _served_by(self) -> Json: + return { + "url": self._client.url, + "path": self._client.path, + "checkpoint": self._model, + "source": self._client.path, + "read_at": self._served_at, + } + + async def _decide(self, observation: Observation, questions: dict[str, Question]) -> Reply: + body: Json = { + "model": self._model, + "state": glide_state(observation), + "questions": {name: glide_question(question) for name, question in questions.items()}, + } + if self._client.path == "hosted": + body["store"] = False + records: list[Json] = [] + if observation.images: + _parts, records = glide_images(observation.images) + if self._served_at is None: + await self.warm() + request_id = uuid.uuid4().hex + payload, ms, headers = await self._client.decide(body, request_id) + answers = payload["answers"] + lower = {key.lower(): value for key, value in headers.items()} + raw: Json = { + **payload, + "url": self._client.url, + "request_id": request_id, + "served_by": self._served_by(), + "server_timing": parse_server_timing(lower.get("server-timing")), + } + if lower.get("x-fastino-data-retention"): + raw["data_retention"] = lower["x-fastino-data-retention"] + if lower.get("x-fastino-request-id"): + raw["fastino_request_id"] = lower["x-fastino-request-id"] + if records: + raw["sent_images"] = records + return Reply( + answers={name: answers[name] for name in questions if name in answers}, + latency_ms=ms, + usage=Usage.from_payload(payload.get("usage")), + model=str(payload.get("model") or self._model), + raw=raw, + ) + + async def close(self) -> None: + await self._client.close() + + @classmethod + def from_env(cls) -> "GlideModel": + """``GLIDE_URL`` (local ``/v1/systemone``) or ``FASTINO_API_KEY`` (hosted Fastino). + + ``GLIDE_URL`` wins when both a local URL and ``FASTINO_API_KEY`` are set. ``GLIDE_MODEL`` defaults to + ``fastino/GLiDE``. Optional ``GLIDE_API_KEY`` for a local server that expects ``X-API-Key``. + ``GLIDE_TIMEOUT_S`` is the per-decision deadline (default 30 s). Hosted requests send ``store: false``. + """ + model = (os.getenv("GLIDE_MODEL") or DEFAULT_GLIDE_MODEL).strip() + if not model: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg="GLIDE_MODEL must be a non-empty model id, e.g. fastino/GLiDE", + ) + try: + timeout_s = float(os.getenv("GLIDE_TIMEOUT_S") or GLIDE_TIMEOUT_S) + except ValueError as exc: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, cause=exc, error_msg="GLIDE_TIMEOUT_S must be a number" + ) from exc + if not math.isfinite(timeout_s) or timeout_s <= 0: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg="GLIDE_TIMEOUT_S must be a finite number above 0", + ) + url = (os.getenv("GLIDE_URL") or "").strip() + if url: + base = url.rstrip("/") + client = GlideClient( + url=base, + endpoint=f"{base}/v1/systemone", + api_key=(os.getenv("GLIDE_API_KEY") or os.getenv("FASTINO_API_KEY") or "").strip() or None, + timeout_s=timeout_s, + path="local", + ) + return cls(client, model=model) + key = (os.getenv("FASTINO_API_KEY") or "").strip() + if not key: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg=( + "--model glide needs GLIDE_URL (local /v1/systemone, e.g. http://127.0.0.1:8000) or " + "FASTINO_API_KEY (hosted https://api.fastino.ai/v1/systemone)" + ), + ) + client = GlideClient( + url=HOSTED_GLIDE_URL, + endpoint=HOSTED_GLIDE_URL, + api_key=key, + timeout_s=timeout_s, + path="hosted", + ) + return cls(client, model=model) diff --git a/s1a/mcp_server.py b/s1a/mcp_server.py index 53013ff..da6374a 100644 --- a/s1a/mcp_server.py +++ b/s1a/mcp_server.py @@ -31,7 +31,7 @@ "constraint puzzles or free-text generation. list_agents gives every agent's flags: a browser agent takes " "--model jev --goal '...' and needs a chat-model key (OPENAI_API_KEY or LLM_API_KEY plus MODEL_NAME), a Jev key " "(TYPESAFE_API_KEY or OPENROUTER_API_KEY) and Node for @playwright/mcp; a tool agent takes --model, --rethink and " - "--episodes; a rail takes --labelled-set. decide accepts model jev (default), clm, laya, cua or laya-served; local models " + "--episodes; a rail takes --labelled-set. decide accepts model jev (default), clm, laya, cua, laya-served or glide; local models " "need their optional extra and no Jev key, laya-served needs LAYA_SERVED_URL. run_agent reports progress per " "episode or browser step when the request carries a progressToken." ) @@ -182,12 +182,12 @@ async def decide( state: dict[str, Any], options: dict[str, str], rules: str, - model: Literal["jev", "clm", "laya", "laya-served", "cua"] = "jev", + model: Literal["jev", "clm", "laya", "laya-served", "cua", "glide"] = "jev", ) -> Decision: """One choice question: the chosen key, probabilities, confidence (= max p) and decision latency in ms. - Use jev over HTTP (default), laya/cua locally after installing the matching extra, or laya-served against a - running Laya server (LAYA_SERVED_URL). Local model loading + Use jev over HTTP (default), laya/cua locally after installing the matching extra, laya-served against a + running Laya server (LAYA_SERVED_URL), or glide against Fastino or a local GLiDE server. Local model loading is excluded from the reported latency. """ async with _one_at_a_time(f"decide ({model})"): diff --git a/s1a/rails.py b/s1a/rails.py index 29278cf..cd530bc 100644 --- a/s1a/rails.py +++ b/s1a/rails.py @@ -31,7 +31,7 @@ from s1a.spec import Json, RailSpec, Verdict QUESTION = "check" -RAIL_MODEL_NAMES = ("jev", "clm", "laya", "laya-served") +RAIL_MODEL_NAMES = ("jev", "clm", "laya", "laya-served", "glide") BANDS = ("allow", "uncertain", "act", "failure") # a labelled-set row's outcome; failure: the decision itself failed @@ -266,7 +266,7 @@ def parser(spec: RailSpec) -> argparse.ArgumentParser: "--model", choices=RAIL_MODEL_NAMES, default="jev", - help="who answers the question: jev, clm or laya-served over HTTP, laya in process", + help="who answers the question: jev, clm, laya-served or glide over HTTP, laya in process", ) return build diff --git a/s1a/tool/loop.py b/s1a/tool/loop.py index 6c687f4..9216a19 100644 --- a/s1a/tool/loop.py +++ b/s1a/tool/loop.py @@ -28,7 +28,7 @@ from s1a.tool.rethink import RethinkRail from s1a.tool.models import ACT_TOOL, OBSERVE_TOOL, EvalState, ToolDecisionModel -MODEL_NAMES = ("jev", "clm", "llm", "random", "rule", "laya", "laya-served", "cua") +MODEL_NAMES = ("jev", "clm", "llm", "random", "rule", "laya", "laya-served", "cua", "glide") EVAL_PROMPT = ( "You play a game through two tools. Call observe first. Then call act with exactly one of the candidate keys the " "last tool result offered, one act per turn, until done is true. Then reply with one line: the final score." @@ -144,7 +144,7 @@ def build_slot_model( if chat is None: raise RuntimeError("--model llm needs the chat model: OPENAI_API_KEY or LLM_API_KEY, and MODEL_NAME") return chat - case "jev" | "clm" | "laya" | "laya-served" | "cua" | "random" | "rule": + case "jev" | "clm" | "laya" | "laya-served" | "cua" | "glide" | "random" | "rule": if decision_model is None: raise RuntimeError(f"--model {model_name} needs a decision model") return ToolDecisionModel(env, state, rules=rules, decision_model=decision_model, fallback=chat) diff --git a/s1a/tool/series.py b/s1a/tool/series.py index 42e59f2..420a79a 100644 --- a/s1a/tool/series.py +++ b/s1a/tool/series.py @@ -96,7 +96,7 @@ async def play(spec: ToolAgentSpec, args: argparse.Namespace, *, results_dir: Pa limits = RecoveryLimits(max_attempts=attempts, timeout_s=float(rethink_timeout)) if args.model == "llm": raise RuntimeError("bounded rethink needs a decision model; --model llm cannot use it") - shared = build_model(args.model) if args.model in ("jev", "clm", "laya", "laya-served", "cua") else None + shared = build_model(args.model) if args.model in ("jev", "clm", "laya", "laya-served", "cua", "glide") else None run = await asyncio.to_thread(spec.series, args) # question fetches, game file parsing: seconds of blocking I/O if args.model == "rule": shared = build_model("rule", rule=run.baseline) diff --git a/tests/test_browse.py b/tests/test_browse.py index 37365df..813ea42 100644 --- a/tests/test_browse.py +++ b/tests/test_browse.py @@ -61,7 +61,7 @@ def test_a_timeout_or_max_steps_at_or_below_zero_is_a_usage_error(self) -> None: def test_the_model_flag_takes_a_decision_model_or_the_chat_model(self) -> None: self.assertEqual( browse.BROWSER_MODEL_NAMES, - ("jev", "jev-vl-served", "clm", "laya", "laya-served", "cua", "omnijev", "onejev", "llm"), + ("jev", "jev-vl-served", "clm", "laya", "laya-served", "cua", "omnijev", "onejev", "glide", "llm"), ) for model_name in browse.BROWSER_MODEL_NAMES: self.assertEqual(browse.parser(SPEC).parse_args(["--model", model_name, "--goal", "x"]).model, model_name) diff --git a/tests/test_decision_models_factory.py b/tests/test_decision_models_factory.py index cc51ab6..7d0b2d0 100644 --- a/tests/test_decision_models_factory.py +++ b/tests/test_decision_models_factory.py @@ -46,7 +46,19 @@ def test_every_name_builds_its_class(self) -> None: self.assertEqual(rule.name, "always-inc") self.assertEqual( DECISION_MODEL_NAMES, - ("jev", "jev-vl-served", "clm", "laya", "laya-served", "cua", "omnijev", "onejev", "random", "rule"), + ( + "jev", + "jev-vl-served", + "clm", + "laya", + "laya-served", + "cua", + "omnijev", + "onejev", + "glide", + "random", + "rule", + ), ) def test_the_errors(self) -> None: diff --git a/tests/test_decision_models_glide.py b/tests/test_decision_models_glide.py new file mode 100644 index 0000000..d771e47 --- /dev/null +++ b/tests/test_decision_models_glide.py @@ -0,0 +1,524 @@ +# coding: utf-8 +"""``glide`` served client: contract tests against a fake HTTP server (no Fastino / GPU).""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import os +from typing import Any +from unittest import IsolatedAsyncioTestCase, TestCase +from unittest.mock import patch + +import httpx +from openjiuwen.core.common.exception.codes import StatusCode +from openjiuwen.core.common.exception.errors import BaseError + +import decision_model_contract as contract +from s1a.decision_models import ChoiceQuestion, DecisionModel, Image, Observation, build_model +from s1a.decision_models.glide import ( + DEFAULT_GLIDE_MODEL, + HOSTED_GLIDE_URL, + MAX_GLIDE_IMAGE_BYTES, + GlideClient, + GlideModel, + glide_image, + glide_images, + glide_payload, + glide_question, + glide_state, + retry_after_s, +) + +SCREEN = Image(b"\x89PNG\r\n\x1a\n" + b"\x00" * 24, media_type="image/png") +URL = "http://glide.test" + + +def _choice_answer(question: dict[str, Any]) -> dict[str, Any]: + keys = list(question["criteria"]) + if not keys: + return {"type": "choice", "choice": "", "probabilities": {}, "confidence": 0.0} + if len(keys) == 1: + probabilities = {keys[0]: 1.0} + else: + rest = 0.2 / (len(keys) - 1) + probabilities = {key: (0.8 if i == 0 else rest) for i, key in enumerate(keys)} + return {"type": "choice", "choice": keys[0], "probabilities": probabilities, "confidence": probabilities[keys[0]]} + + +def _noul_answer(_question: dict[str, Any]) -> dict[str, Any]: + return {"type": "noul", "noul": 0.65, "confidence": 0.3} + + +def _decision_body(request: httpx.Request) -> dict[str, Any]: + body = json.loads(request.content) + answers = {} + for name, question in body["questions"].items(): + answers[name] = _noul_answer(question) if question["type"] == "noul" else _choice_answer(question) + return { + "model": "glide", + "answers": answers, + "usage": {"input_tokens": 12, "output_tokens": 0}, + } + + +class Server: + """Scripted local ``/v1/systemone``, or the hosted Fastino endpoint. + + Rejects unsupported top-level fields the way Fastino's 422 would. + """ + + allowed = frozenset({"model", "state", "questions", "store"}) + + def __init__(self, *, script: list[Any] | None = None, reject_extra: bool = True) -> None: + self.script = list(script or []) + self.reject_extra = reject_extra + self.decisions: list[httpx.Request] = [] + + def answer(self, request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + extra = sorted(set(body) - self.allowed) + if self.reject_extra and extra: + return httpx.Response(422, json={"detail": f"unsupported fields: {extra}"}) + return httpx.Response(200, json=_decision_body(request)) + + def handler(self, request: httpx.Request) -> httpx.Response: + self.decisions.append(request) + if self.script: + step = self.script.pop(0) + if isinstance(step, Exception): + raise step + if callable(step): + return step(request) + return step + return self.answer(request) + + +def make_local(server: Server, *, timeout_s: float = 5.0, model: str = DEFAULT_GLIDE_MODEL) -> GlideModel: + client = GlideClient( + url=URL + "/", + endpoint=URL + "/v1/systemone", + timeout_s=timeout_s, + transport=httpx.MockTransport(server.handler), + path="local", + ) + return GlideModel(client, model=model) + + +def make_hosted(server: Server, *, timeout_s: float = 5.0, model: str = DEFAULT_GLIDE_MODEL) -> GlideModel: + client = GlideClient( + url=HOSTED_GLIDE_URL, + endpoint=HOSTED_GLIDE_URL, + api_key="fast_sk_test", + timeout_s=timeout_s, + transport=httpx.MockTransport(server.handler), + path="hosted", + ) + return GlideModel(client, model=model) + + +class TestGlideContract(contract.DecisionModelContract, IsolatedAsyncioTestCase): + def make(self) -> DecisionModel: + return make_local(Server()) + + def make_scripted(self, answers: list[dict[str, Any]]) -> DecisionModel: + script = [ + httpx.Response(200, json={"model": "glide", "answers": a, "usage": {"input_tokens": 8}}) for a in answers + ] + return make_local(Server(script=script)) + + +class TestRequestBody(IsolatedAsyncioTestCase): + async def test_text_path_posts_systemone_without_images_media_or_store(self) -> None: + server = Server() + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK, "check": contract.CHECK}) + request = server.decisions[0] + self.assertEqual(request.url, httpx.URL(URL + "/v1/systemone")) + self.assertNotIn("X-API-Key", request.headers) + self.assertNotIn("Authorization", request.headers) + self.assertIn("X-Request-Id", request.headers) + body = json.loads(request.content) + self.assertEqual(body["model"], DEFAULT_GLIDE_MODEL) + self.assertEqual(body["state"], contract.OBSERVATION.state) + self.assertNotIn("store", body) + self.assertNotIn("images", body) + self.assertNotIn("media", body) + self.assertNotIn("videos", body) + self.assertEqual(set(body), {"model", "state", "questions"}) + self.assertEqual(body["questions"]["pick"]["type"], "choice") + self.assertEqual(body["questions"]["check"]["type"], "noul") + self.assertIsInstance(body["questions"]["pick"]["instructions"], dict) + self.assertIsInstance(body["questions"]["check"]["instructions"], dict) + + async def test_hosted_sends_api_key_and_store_false(self) -> None: + server = Server() + decision = await make_hosted(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + request = server.decisions[0] + self.assertEqual(str(request.url), HOSTED_GLIDE_URL) + self.assertEqual(request.headers["X-API-Key"], "fast_sk_test") + self.assertNotIn("Authorization", request.headers) + body = json.loads(request.content) + self.assertEqual(body["store"], False) + self.assertEqual(set(body), {"model", "state", "questions", "store"}) + self.assertEqual(decision.model, "glide") + self.assertEqual(decision.raw["served_by"]["path"], "hosted") + self.assertEqual(decision.usage.input_tokens, 12) + + async def test_images_are_state_parts_not_clef_or_onejev_layout(self) -> None: + server = Server() + pictured = Observation({"task": "Pay the invoice"}, images=(SCREEN,)) + await make_local(server).decide_many(pictured, {"pick": contract.PICK}) + body = json.loads(server.decisions[0].content) + self.assertNotIn("images", body) + self.assertNotIn("media", body) + state = body["state"] + self.assertIsInstance(state, list) + self.assertEqual( + state[0], {"type": "text", "text": json.dumps({"task": "Pay the invoice"}, separators=(",", ":"))} + ) + part = state[1] + self.assertEqual(part["type"], "image_url") + url = part["image_url"]["url"] + self.assertTrue(url.startswith("data:image/png;base64,")) + self.assertEqual(base64.b64decode(url.split(",", 1)[1]), SCREEN.data) + + async def test_string_state_with_images_keeps_a_text_part(self) -> None: + server = Server() + pictured = Observation("a receipt", images=(SCREEN,)) + await make_local(server).decide_many(pictured, {"pick": contract.PICK}) + state = json.loads(server.decisions[0].content)["state"] + self.assertEqual(state[0], {"type": "text", "text": "a receipt"}) + self.assertEqual(state[1]["type"], "image_url") + + async def test_provenance_fields_and_no_image_bytes_in_raw(self) -> None: + pictured = Observation({"task": "Pay the invoice"}, images=(SCREEN,)) + decision = await make_local(Server()).decide_many(pictured, {"pick": contract.PICK}) + self.assertEqual(decision.raw["url"], URL) + self.assertIsInstance(decision.raw["request_id"], str) + self.assertEqual(decision.raw["served_by"]["path"], "local") + self.assertEqual(decision.raw["served_by"]["checkpoint"], DEFAULT_GLIDE_MODEL) + self.assertEqual(decision.raw["sent_images"][0]["bytes"], len(SCREEN.data)) + dumped = json.dumps(decision.raw) + self.assertNotIn(base64.b64encode(SCREEN.data).decode("ascii"), dumped) + + async def test_hosted_records_fastino_headers(self) -> None: + def with_headers(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json=_decision_body(request), + headers={"X-Fastino-Data-Retention": "not-stored", "X-Fastino-Request-Id": "fn-1"}, + ) + + decision = await make_hosted(Server(script=[with_headers])).decide_many( + contract.OBSERVATION, {"pick": contract.PICK} + ) + self.assertEqual(decision.raw["data_retention"], "not-stored") + self.assertEqual(decision.raw["fastino_request_id"], "fn-1") + + async def test_browser_element_row_becomes_a_description_string(self) -> None: + server = Server() + question = ChoiceQuestion( + {"12": {"element": "[12] Where from?", "current_value": "Zurich", "role": "combobox"}}, + goal="book a flight", + ) + await make_local(server).decide_many(contract.OBSERVATION, {"click_target": question}) + asked = json.loads(server.decisions[0].content)["questions"]["click_target"] + self.assertEqual(asked["criteria"], {"12": "Where from? = Zurich"}) + self.assertEqual(asked["instructions"]["goal"], "book a flight") + + +class TestFailures(IsolatedAsyncioTestCase): + async def test_too_many_images_is_a_call_failure(self) -> None: + pictured = Observation("x", images=tuple(SCREEN for _ in range(5))) + with self.assertRaises(BaseError) as caught: + await make_local(Server()).decide_many(pictured, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("at most 4", str(caught.exception)) + + async def test_transport_error_is_a_call_failure(self) -> None: + server = Server(script=[httpx.ConnectError("refused"), httpx.ConnectError("refused")]) + with self.assertRaises(BaseError) as caught: + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("glide", str(caught.exception).lower()) + + async def test_malformed_answers_object_is_a_call_failure(self) -> None: + server = Server(script=[httpx.Response(200, json={"model": "x", "answers": "nope"})]) + with self.assertRaises(BaseError) as caught: + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("answers", str(caught.exception).lower()) + + async def test_http_error_is_a_call_failure(self) -> None: + server = Server(script=[httpx.Response(500, text="boom")]) + with self.assertRaises(BaseError) as caught: + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("500", str(caught.exception)) + + async def test_422_on_extra_fields_is_a_call_failure(self) -> None: + server = Server(script=[httpx.Response(422, json={"detail": "unsupported field: foo"})]) + with self.assertRaises(BaseError) as caught: + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("422", str(caught.exception)) + + +class TestFastinoRetries(IsolatedAsyncioTestCase): + async def test_425_429_503_retry_after_zero_then_succeed(self) -> None: + for status in (425, 429, 503): + with self.subTest(status=status): + sleeps: list[float] = [] + + async def sleeper(delay: float, recorded=sleeps) -> None: + recorded.append(delay) + + def first_then_ok(status=status): + calls = {"n": 0} + + def handler(request: httpx.Request) -> httpx.Response: + calls["n"] += 1 + if calls["n"] == 1: + return httpx.Response( + status, json={"error": {"code": "model_warming"}}, headers={"Retry-After": "0"} + ) + return httpx.Response(200, json=_decision_body(request)) + + return handler + + client = GlideClient( + url=URL, + endpoint=URL + "/v1/systemone", + timeout_s=5.0, + transport=httpx.MockTransport(first_then_ok()), + sleeper=sleeper, + path="hosted", + ) + self.addAsyncCleanup(client.close) + payload, _ms, _headers = await client.decide( + { + "model": DEFAULT_GLIDE_MODEL, + "questions": {"pick": {"type": "choice", "criteria": {"hit": "Hit"}, "instructions": "x"}}, + }, + "rid", + ) + self.assertIn("answers", payload) + self.assertEqual(sleeps, [0.0]) + + async def test_exhausted_budget_skips_425_retry(self) -> None: + now = 0.0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal now + now += 2.0 + return httpx.Response(425, json={"error": {"code": "model_warming"}}, headers={"Retry-After": "30"}) + + client = GlideClient( + url=URL, + endpoint=URL + "/v1/systemone", + timeout_s=2.0, + transport=httpx.MockTransport(handler), + clock=lambda: now, + path="hosted", + ) + self.addAsyncCleanup(client.close) + with self.assertRaises(BaseError) as caught: + await client.decide({"questions": {}}, "warm") + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("425", str(caught.exception)) + + +class TestDecisionDeadline(IsolatedAsyncioTestCase): + async def test_retry_uses_remaining_budget_for_httpx_and_wait_for(self) -> None: + for failure in (httpx.ConnectError("refused"), httpx.Response(502), httpx.Response(504)): + with self.subTest(failure=failure): + now = 0.0 + requests = [] + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal now + requests.append(request) + if len(requests) == 1: + now += 1.25 + if isinstance(failure, Exception): + raise failure + return failure + return httpx.Response(200, json={"answers": {}}) + + client = GlideClient( + url=URL, + endpoint=URL + "/v1/systemone", + timeout_s=2.0, + transport=httpx.MockTransport(handler), + clock=lambda: now, + path="local", + ) + self.addAsyncCleanup(client.close) + with patch("s1a.decision_models.glide.asyncio.wait_for", wraps=asyncio.wait_for) as wait_for: + await client.decide({"questions": {}}, "same-request") + self.assertEqual([call.args[1] for call in wait_for.call_args_list], [2.0, 0.75]) + for request, timeout in zip(requests, (2.0, 0.75), strict=True): + self.assertEqual(set(request.extensions["timeout"].values()), {timeout}) + self.assertEqual(request.headers["X-Request-Id"], "same-request") + + async def test_exhausted_budget_prevents_retry(self) -> None: + for failure in (httpx.ConnectError("refused"), httpx.Response(502), httpx.Response(504)): + with self.subTest(failure=failure): + now = 0.0 + requests = [] + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal now + requests.append(request) + now += 2.0 + if isinstance(failure, Exception): + raise failure + return failure + + client = GlideClient( + url=URL, + endpoint=URL + "/v1/systemone", + timeout_s=2.0, + transport=httpx.MockTransport(handler), + clock=lambda: now, + path="local", + ) + self.addAsyncCleanup(client.close) + with self.assertRaises(BaseError) as caught: + await client.decide({"questions": {}}, "exhausted") + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("within 2 s", str(caught.exception)) + self.assertEqual(len(requests), 1) + + async def test_stalled_retry_is_cancelled_at_remaining_deadline(self) -> None: + now = 0.0 + attempts = 0 + stopped = asyncio.Event() + + async def handler(request: httpx.Request) -> httpx.Response: + nonlocal now, attempts + attempts += 1 + if attempts == 1: + now = 0.99 + raise httpx.ConnectError("refused", request=request) + try: + await asyncio.Event().wait() + finally: + stopped.set() + raise AssertionError("stalled retry was not cancelled") + + client = GlideClient( + url=URL, + endpoint=URL + "/v1/systemone", + timeout_s=1.0, + transport=httpx.MockTransport(handler), + clock=lambda: now, + path="local", + ) + self.addAsyncCleanup(client.close) + with patch("s1a.decision_models.glide.asyncio.wait_for", wraps=asyncio.wait_for) as wait_for: + with self.assertRaises(BaseError) as caught: + await client.decide({"questions": {}}, "stalled") + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIsInstance(caught.exception.__cause__, TimeoutError) + self.assertAlmostEqual(wait_for.call_args_list[1].args[1], 0.01) + self.assertEqual(attempts, 2) + self.assertTrue(stopped.is_set()) + + +class TestMappingHelpers(TestCase): + def test_payload_requires_an_answers_object(self) -> None: + inner = {"model": "glide", "answers": {"pick": {"noul": 0.2}}, "usage": {"input_tokens": 1}} + self.assertEqual(glide_payload(inner), inner) + with self.assertRaises(BaseError): + glide_payload({"model": "glide"}) + with self.assertRaises(BaseError): + glide_payload({"answers": "nope"}) + + def test_image_rejects_empty_unknown_types_and_oversize(self) -> None: + with self.assertRaises(BaseError): + glide_image(Image(b"", media_type="image/png")) + with self.assertRaises(BaseError): + glide_image(Image(b"x", media_type="image/tiff")) + with self.assertRaises(BaseError): + glide_images((SCREEN,) * 5) + huge = Image(b"x" * (MAX_GLIDE_IMAGE_BYTES + 1), media_type="image/png") + with self.assertRaises(BaseError) as caught: + glide_image(huge) + self.assertIn(str(MAX_GLIDE_IMAGE_BYTES), str(caught.exception)) + + def test_gif_is_accepted(self) -> None: + part, record = glide_image(Image(b"GIF89a", media_type="image/gif")) + self.assertEqual(part["type"], "image_url") + self.assertTrue(part["image_url"]["url"].startswith("data:image/gif;base64,")) + self.assertEqual(record["bytes"], 6) + + def test_question_keeps_jev_instruction_objects(self) -> None: + asked = glide_question(ChoiceQuestion({"a": "A"}, goal="g", rules="r")) + self.assertEqual(asked["type"], "choice") + self.assertEqual(asked["instructions"], {"goal": "g", "rules": "r"}) + self.assertEqual(asked["criteria"], {"a": "A"}) + + def test_empty_instructions_become_a_string(self) -> None: + asked = glide_question(ChoiceQuestion({"a": "A"})) + self.assertIsInstance(asked["instructions"], str) + self.assertTrue(asked["instructions"]) + + def test_text_state_without_images_is_unchanged(self) -> None: + self.assertEqual(glide_state(contract.OBSERVATION), contract.OBSERVATION.state) + + def test_retry_after_parses_seconds_and_falls_back(self) -> None: + self.assertEqual(retry_after_s(httpx.Response(425, headers={"Retry-After": "12"}), default=30.0), 12.0) + self.assertEqual(retry_after_s(httpx.Response(425), default=30.0), 30.0) + self.assertEqual(retry_after_s(httpx.Response(425, headers={"Retry-After": "nope"}), default=30.0), 30.0) + + +class TestFromEnv(TestCase): + def test_missing_url_and_key_is_a_config_error(self) -> None: + with patch.dict(os.environ, {"GLIDE_URL": "", "FASTINO_API_KEY": "", "GLIDE_API_KEY": ""}, clear=False): + os.environ.pop("GLIDE_URL", None) + os.environ.pop("FASTINO_API_KEY", None) + os.environ.pop("GLIDE_API_KEY", None) + with self.assertRaises(BaseError) as caught: + GlideModel.from_env() + self.assertEqual(caught.exception.status, StatusCode.MODEL_SERVICE_CONFIG_ERROR) + self.assertIn("GLIDE_URL", str(caught.exception)) + self.assertIn("FASTINO_API_KEY", str(caught.exception)) + + def test_build_model_glide_from_local_url(self) -> None: + with patch.dict(os.environ, {"GLIDE_URL": "http://127.0.0.1:8000", "GLIDE_TIMEOUT_S": "5"}): + model = build_model("glide") + self.addCleanup(lambda: asyncio.run(model.close())) + self.assertIsInstance(model, GlideModel) + self.assertEqual(model.name, "glide") + self.assertEqual(model.model, DEFAULT_GLIDE_MODEL) + self.assertTrue(model.supports_images) + self.assertTrue(model.deterministic) + self.assertEqual(model._client.path, "local") + self.assertEqual(model._client.endpoint, "http://127.0.0.1:8000/v1/systemone") + + def test_build_model_glide_from_hosted_key(self) -> None: + with patch.dict(os.environ, {"GLIDE_URL": "", "FASTINO_API_KEY": "fast_sk_secret"}, clear=False): + os.environ.pop("GLIDE_URL", None) + model = build_model("glide") + self.addCleanup(lambda: asyncio.run(model.close())) + self.assertIsInstance(model, GlideModel) + self.assertEqual(model._client.path, "hosted") + self.assertEqual(model._client.endpoint, HOSTED_GLIDE_URL) + + def test_local_url_wins_over_hosted_key(self) -> None: + with patch.dict(os.environ, {"GLIDE_URL": "http://127.0.0.1:8000", "FASTINO_API_KEY": "fast_sk_secret"}): + model = GlideModel.from_env() + self.addCleanup(lambda: asyncio.run(model.close())) + self.assertEqual(model._client.path, "local") + + def test_custom_model_id_and_bad_timeout_are_handled(self) -> None: + with patch.dict(os.environ, {"GLIDE_URL": "http://127.0.0.1:8000", "GLIDE_MODEL": "fastino/GLiDE-deployed"}): + model = GlideModel.from_env() + self.addCleanup(lambda: asyncio.run(model.close())) + self.assertEqual(model.model, "fastino/GLiDE-deployed") + with patch.dict(os.environ, {"GLIDE_URL": "http://127.0.0.1:8000", "GLIDE_TIMEOUT_S": "0"}): + with self.assertRaises(BaseError) as caught: + GlideModel.from_env() + self.assertEqual(caught.exception.status, StatusCode.MODEL_SERVICE_CONFIG_ERROR) diff --git a/tests/test_glide_registration.py b/tests/test_glide_registration.py new file mode 100644 index 0000000..294a5bf --- /dev/null +++ b/tests/test_glide_registration.py @@ -0,0 +1,104 @@ +# coding: utf-8 +"""``glide`` is registered on the text fronts, the browser front, and the model factory.""" + +from __future__ import annotations + +import json +import os +import tempfile +import typing +from pathlib import Path +from unittest import IsolatedAsyncioTestCase, TestCase, mock + +from s1a import cli, mcp_server, rails +from s1a.browser import browse +from s1a.browser.decision_model import BrowserPolicy +from s1a.decision_models import DECISION_MODEL_NAMES, build_model +from s1a.decision_models.fakes import ScriptedModel +from s1a.spec import BrowserAgentSpec, Budget +from s1a.tool import loop, series + + +def spec() -> BrowserAgentSpec: + return BrowserAgentSpec( + name="fixture", + description="A browser fixture", + rules="Choose an offered action", + language="en", + budget=Budget(max_steps=2, timeout_s=10, stall_after=0), + goal="Open the fixture", + ) + + +class TestGlideRegistration(TestCase): + def test_factory_and_fronts_offer_the_backend(self) -> None: + self.assertIn("glide", DECISION_MODEL_NAMES) + self.assertIn("glide", browse.BROWSER_MODEL_NAMES) + self.assertIn("glide", cli.DECIDE_MODEL_NAMES) + self.assertIn("glide", loop.MODEL_NAMES) + self.assertIn("glide", rails.RAIL_MODEL_NAMES) + decide_model = typing.get_type_hints( + mcp_server.decide.__wrapped__ if hasattr(mcp_server.decide, "__wrapped__") else mcp_server.decide + )["model"] + self.assertIn("glide", typing.get_args(decide_model)) + args = browse.parser(spec()).parse_args(["--model", "glide"]) + self.assertEqual(args.model, "glide") + + +class TestGlideEntrypoints(IsolatedAsyncioTestCase): + async def test_factory_builds_the_served_model_from_the_environment(self) -> None: + with mock.patch.dict(os.environ, {"GLIDE_URL": "http://127.0.0.1:8000", "GLIDE_TIMEOUT_S": "5"}): + model = build_model("glide") + try: + self.assertEqual(type(model).__name__, "GlideModel") + self.assertEqual(model.name, "glide") + self.assertEqual(model.model, "fastino/GLiDE") + self.assertTrue(model.supports_images) + self.assertTrue(model.deterministic) + finally: + await model.close() + + async def test_browser_routes_the_backend_to_the_decision_model_slot(self) -> None: + decision_model = ScriptedModel() + decision_model.name = "glide" + slot = mock.MagicMock() + slot.report.return_value = {"jev_input_tokens": 0, "decisions": 1} + slot.ticks = [] + final = json.dumps({"status": "DONE", "answer": "Fixture answer"}) + with ( + mock.patch.object(browse, "CountingModel") as counting, + mock.patch.object(browse, "BrowserDecisionModel", return_value=slot) as slot_class, + mock.patch.object(browse, "create_browser_agent") as create_agent, + mock.patch.object( + browse, + "run_task", + new=mock.AsyncMock(return_value={"ok": True, "final": final, "error": None}), + ) as run_task, + mock.patch.object(browse, "usage_summary", return_value={"decisions": 1}), + ): + with tempfile.TemporaryDirectory() as directory: + answer = await browse.browse( + spec(), + BrowserPolicy(prefetch_values=False, batch_actions=False, goal_value_cache=False), + model_name="glide", + goal="Open the fixture", + timeout_s=10, + max_steps=2, + logs_dir=Path(directory), + headless=True, + chat=mock.MagicMock(), + decision_model=decision_model, + ) + self.assertTrue((Path(directory) / "decision_ticks.json").is_file()) + self.assertIs(slot_class.call_args.args[2], counting.return_value) + self.assertIs(slot_class.call_args.kwargs["decision_model"], decision_model) + self.assertEqual(slot_class.call_args.kwargs["max_steps"], 2) + self.assertIs(create_agent.call_args.args[0], slot) + run_task.assert_awaited_once() + self.assertEqual(answer["final"], "Fixture answer") + + +class TestSeriesSharesTheModel(TestCase): + def test_series_treats_glide_as_a_shared_decision_model(self) -> None: + source = Path(series.__file__).read_text(encoding="utf-8") + self.assertIn('("jev", "clm", "laya", "laya-served", "cua", "glide")', source) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 024e29a..5bb7d71 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -162,7 +162,7 @@ async def test_decide_advertises_optional_model_choices(self) -> None: async with create_connected_server_and_client_session(mcp_server.server) as session: tools = await session.list_tools() schema = next(tool.inputSchema for tool in tools.tools if tool.name == "decide") - self.assertEqual(schema["properties"]["model"]["enum"], ["jev", "clm", "laya", "laya-served", "cua"]) + self.assertEqual(schema["properties"]["model"]["enum"], ["jev", "clm", "laya", "laya-served", "cua", "glide"]) self.assertEqual(schema["properties"]["model"]["default"], "jev") self.assertNotIn("model", schema["required"]) @@ -259,7 +259,7 @@ async def test_list_agents_names_every_front_with_its_flags(self) -> None: flags = {name: {row["flag"]: row for row in rows[name]["flags"]} for name in ("game2048", "flights")} self.assertEqual( (flags["game2048"]["--model"]["required"], flags["game2048"]["--model"]["choices"]), - (True, ["jev", "clm", "llm", "random", "rule", "laya", "laya-served", "cua"]), + (True, ["jev", "clm", "llm", "random", "rule", "laya", "laya-served", "cua", "glide"]), ) max_steps = str(agents.load("game2048").budget.max_steps) self.assertEqual(