evalrouter 0.3.6__tar.gz → 0.3.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. {evalrouter-0.3.6 → evalrouter-0.3.7}/PKG-INFO +46 -6
  2. {evalrouter-0.3.6 → evalrouter-0.3.7}/README.md +45 -5
  3. {evalrouter-0.3.6 → evalrouter-0.3.7}/pyproject.toml +1 -1
  4. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/evalrouter_contracts/__init__.py +1 -1
  5. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/__init__.py +1 -1
  6. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/_account.py +340 -16
  7. evalrouter-0.3.7/src/kimpton_evalrouter/_artifacts.py +294 -0
  8. evalrouter-0.3.7/src/kimpton_evalrouter/_comparison.py +905 -0
  9. evalrouter-0.3.7/src/kimpton_evalrouter/_comparison_html.py +233 -0
  10. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/_guided.py +360 -84
  11. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/cli.py +408 -92
  12. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/render/picker.py +84 -20
  13. {evalrouter-0.3.6 → evalrouter-0.3.7}/LICENSE +0 -0
  14. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/evalrouter_contracts/bundle.py +0 -0
  15. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/evalrouter_contracts/components.py +0 -0
  16. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/evalrouter_contracts/models.py +0 -0
  17. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/evalrouter_contracts/protocol.py +0 -0
  18. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/evalrouter_contracts/py.typed +0 -0
  19. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/evalrouter_contracts/templates.py +0 -0
  20. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/evalrouter_contracts/validation.py +0 -0
  21. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/__main__.py +0 -0
  22. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/_boundary.py +0 -0
  23. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/_helpers.py +0 -0
  24. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/_listing.py +0 -0
  25. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/_resources.py +0 -0
  26. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/_transport.py +0 -0
  27. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/langsmith.py +0 -0
  28. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/py.typed +0 -0
  29. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/render/__init__.py +0 -0
  30. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/render/_console.py +0 -0
  31. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/render/_theme.py +0 -0
  32. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/render/_widgets.py +0 -0
  33. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/render/live.py +0 -0
  34. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/render/screens.py +0 -0
  35. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/render/tables.py +0 -0
  36. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/tracing.py +0 -0
  37. {evalrouter-0.3.6 → evalrouter-0.3.7}/src/kimpton_evalrouter/types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evalrouter
3
- Version: 0.3.6
3
+ Version: 0.3.7
4
4
  Summary: Typed Kimpton evaluation client and command-line interface
5
5
  License-Expression: LicenseRef-Kimpton-EvalRouter-SDK
6
6
  License-File: LICENSE
@@ -92,7 +92,7 @@ evalrouter run gpqa-diamond --model gpt-4o-mini
92
92
 
93
93
  `run` matches the benchmark and model by slug, name or ID, suggesting the
94
94
  closest names after a typo. It creates a free quote, shows the coverage,
95
- conservative estimate, spending cap and concurrency, and asks `Run it? [Y/n]`.
95
+ conservative estimate, spending cap and concurrency, and asks whether to start the run (Start run or Cancel).
96
96
  Only a yes starts paid work. It then follows progress and prints the scores,
97
97
  the change from your previous completed run of the same benchmark and model,
98
98
  and the report link. In a terminal, missing choices are asked for; run
@@ -111,8 +111,10 @@ submitted (`~/.local/state/evalrouter`, or `EVALROUTER_STATE_DIR`; identifiers
111
111
  only, never credentials). Repeating the same command after a dropped connection
112
112
  resumes that run instead of starting another; `--new` starts a separate one.
113
113
  Afterwards, `results`, `export --format html,json`, `wait` and `open` default to
114
- your last run and accept a unique run ID prefix. Watching a run survives brief
115
- API outages such as a 503 during a deployment.
114
+ your last run and accept a unique run ID prefix. `results --diff` also compares
115
+ with the previous run of the same benchmark and model; that takes a few more
116
+ requests, so plain `results` does not. Watching a run survives brief API
117
+ outages such as a 503 during a deployment.
116
118
 
117
119
  ## Lists
118
120
 
@@ -176,10 +178,48 @@ Inspect terminal status, coverage, errors and billing alongside scores. A sample
176
178
  is not a full-benchmark score. Exports refuse overwrite by default; use the
177
179
  result's integer `--version` for repeatable reports.
178
180
 
181
+ Every command that saves a file prints its full path. An explicit `--output`
182
+ file is used exactly and never replaced (exports accept `--overwrite`); a
183
+ directory, or no file name, gets a default such as `evalrouter-<run>.json` or
184
+ `evalrouter-bundle-<namespace>-<name>-<version>.zip`, moving to the next free
185
+ `-2`, `-3`... name instead of replacing anything. Add `--open` or `--reveal`
186
+ to open the saved file or show it in your file manager; nothing opens
187
+ otherwise, and a missing viewer never fails the command.
188
+
189
+ ### Comparing runs
190
+
191
+ ```sh
192
+ evalrouter compare RUN_ID RUN_ID --format html --output my-comparison
193
+ ```
194
+
195
+ `compare` takes 1 to 8 finished runs of the same benchmark version, dataset,
196
+ task population, task selection and output format in one workspace. Each run
197
+ must be a managed or connected model run; comparison, agent and environment
198
+ runs are refused, and so is a run whose export does not record one of these
199
+ identities. It downloads each run's JSON export again and saves
200
+ `comparison.json` and `sources/<run>.json` in a new private directory.
201
+ `comparison.json` holds each run's model identity (route, revision, protocol,
202
+ recorded limits, generation and routing settings), coverage, errors, its
203
+ frozen native summary with the headline's own denominator, and its settled
204
+ EvalRouter charge. A run that did not complete, or graded fewer tasks than
205
+ planned, is marked partial in `comparison.json` and in its own row of the
206
+ terminal table.
207
+
208
+ `sources/` keeps each export byte for byte, with its SHA-256 recorded. By
209
+ default every graded sample must carry its scored answer: the final completion
210
+ text for SOB, plus the per-sample metadata the export supplies (for SOB, the
211
+ response's token counts and finish reason). Exports do not contain complete
212
+ transcripts, reasoning, timings or per-attempt usage. Keep these files
213
+ private. Use `--without-raw` to archive runs whose answers have expired or
214
+ are withheld by the export policy. Different transports, limits or generation
215
+ settings are listed as warnings. Nothing is regraded, and no deltas,
216
+ intervals or winner are computed. `--output NAME.json` puts the sources in
217
+ `NAME-sources/`.
218
+
179
219
  ## Supported commands
180
220
 
181
221
  `catalog` (`--models`, `--slug` or `--environment`), `connections list/create/check/update/disable`,
182
- `quote`, `run`, `status`, `wait`, `cancel`, `results`, `export` and `open`.
222
+ `quote`, `run`, `status`, `wait`, `cancel`, `results`, `export`, `compare` and `open`.
183
223
  Repository qualification uses `agent-builds options/preview/create/list/status/cancel`.
184
224
  Authoring your own benchmark package uses `benchmark init/validate/bundle`.
185
225
  Run each command with `--help` for exact flags. A connected model's credential
@@ -218,7 +258,7 @@ stays thin (httpx and rich only). With pip, use `pip install 'evalrouter[benchma
218
258
  uv tool install --python 3.12 "evalrouter[benchmark]"
219
259
  evalrouter benchmark init ./my-benchmark --namespace example --name my-benchmark
220
260
  evalrouter benchmark validate ./my-benchmark
221
- evalrouter benchmark bundle ./my-benchmark --output my-benchmark.zip
261
+ evalrouter benchmark bundle ./my-benchmark # evalrouter-bundle-example-my-benchmark-<version>.zip
222
262
  ```
223
263
 
224
264
  Without the extra these three commands stop before reading your package and
@@ -72,7 +72,7 @@ evalrouter run gpqa-diamond --model gpt-4o-mini
72
72
 
73
73
  `run` matches the benchmark and model by slug, name or ID, suggesting the
74
74
  closest names after a typo. It creates a free quote, shows the coverage,
75
- conservative estimate, spending cap and concurrency, and asks `Run it? [Y/n]`.
75
+ conservative estimate, spending cap and concurrency, and asks whether to start the run (Start run or Cancel).
76
76
  Only a yes starts paid work. It then follows progress and prints the scores,
77
77
  the change from your previous completed run of the same benchmark and model,
78
78
  and the report link. In a terminal, missing choices are asked for; run
@@ -91,8 +91,10 @@ submitted (`~/.local/state/evalrouter`, or `EVALROUTER_STATE_DIR`; identifiers
91
91
  only, never credentials). Repeating the same command after a dropped connection
92
92
  resumes that run instead of starting another; `--new` starts a separate one.
93
93
  Afterwards, `results`, `export --format html,json`, `wait` and `open` default to
94
- your last run and accept a unique run ID prefix. Watching a run survives brief
95
- API outages such as a 503 during a deployment.
94
+ your last run and accept a unique run ID prefix. `results --diff` also compares
95
+ with the previous run of the same benchmark and model; that takes a few more
96
+ requests, so plain `results` does not. Watching a run survives brief API
97
+ outages such as a 503 during a deployment.
96
98
 
97
99
  ## Lists
98
100
 
@@ -156,10 +158,48 @@ Inspect terminal status, coverage, errors and billing alongside scores. A sample
156
158
  is not a full-benchmark score. Exports refuse overwrite by default; use the
157
159
  result's integer `--version` for repeatable reports.
158
160
 
161
+ Every command that saves a file prints its full path. An explicit `--output`
162
+ file is used exactly and never replaced (exports accept `--overwrite`); a
163
+ directory, or no file name, gets a default such as `evalrouter-<run>.json` or
164
+ `evalrouter-bundle-<namespace>-<name>-<version>.zip`, moving to the next free
165
+ `-2`, `-3`... name instead of replacing anything. Add `--open` or `--reveal`
166
+ to open the saved file or show it in your file manager; nothing opens
167
+ otherwise, and a missing viewer never fails the command.
168
+
169
+ ### Comparing runs
170
+
171
+ ```sh
172
+ evalrouter compare RUN_ID RUN_ID --format html --output my-comparison
173
+ ```
174
+
175
+ `compare` takes 1 to 8 finished runs of the same benchmark version, dataset,
176
+ task population, task selection and output format in one workspace. Each run
177
+ must be a managed or connected model run; comparison, agent and environment
178
+ runs are refused, and so is a run whose export does not record one of these
179
+ identities. It downloads each run's JSON export again and saves
180
+ `comparison.json` and `sources/<run>.json` in a new private directory.
181
+ `comparison.json` holds each run's model identity (route, revision, protocol,
182
+ recorded limits, generation and routing settings), coverage, errors, its
183
+ frozen native summary with the headline's own denominator, and its settled
184
+ EvalRouter charge. A run that did not complete, or graded fewer tasks than
185
+ planned, is marked partial in `comparison.json` and in its own row of the
186
+ terminal table.
187
+
188
+ `sources/` keeps each export byte for byte, with its SHA-256 recorded. By
189
+ default every graded sample must carry its scored answer: the final completion
190
+ text for SOB, plus the per-sample metadata the export supplies (for SOB, the
191
+ response's token counts and finish reason). Exports do not contain complete
192
+ transcripts, reasoning, timings or per-attempt usage. Keep these files
193
+ private. Use `--without-raw` to archive runs whose answers have expired or
194
+ are withheld by the export policy. Different transports, limits or generation
195
+ settings are listed as warnings. Nothing is regraded, and no deltas,
196
+ intervals or winner are computed. `--output NAME.json` puts the sources in
197
+ `NAME-sources/`.
198
+
159
199
  ## Supported commands
160
200
 
161
201
  `catalog` (`--models`, `--slug` or `--environment`), `connections list/create/check/update/disable`,
162
- `quote`, `run`, `status`, `wait`, `cancel`, `results`, `export` and `open`.
202
+ `quote`, `run`, `status`, `wait`, `cancel`, `results`, `export`, `compare` and `open`.
163
203
  Repository qualification uses `agent-builds options/preview/create/list/status/cancel`.
164
204
  Authoring your own benchmark package uses `benchmark init/validate/bundle`.
165
205
  Run each command with `--help` for exact flags. A connected model's credential
@@ -198,7 +238,7 @@ stays thin (httpx and rich only). With pip, use `pip install 'evalrouter[benchma
198
238
  uv tool install --python 3.12 "evalrouter[benchmark]"
199
239
  evalrouter benchmark init ./my-benchmark --namespace example --name my-benchmark
200
240
  evalrouter benchmark validate ./my-benchmark
201
- evalrouter benchmark bundle ./my-benchmark --output my-benchmark.zip
241
+ evalrouter benchmark bundle ./my-benchmark # evalrouter-bundle-example-my-benchmark-<version>.zip
202
242
  ```
203
243
 
204
244
  Without the extra these three commands stop before reading your package and
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "evalrouter"
7
- version = "0.3.6"
7
+ version = "0.3.7"
8
8
  description = "Typed Kimpton evaluation client and command-line interface"
9
9
  readme = "README.md"
10
10
  license = "LicenseRef-Kimpton-EvalRouter-SDK"
@@ -8,4 +8,4 @@ computes digests and refuses invalid packages; it never imports contributed
8
8
  code, opens a network connection, signs anything or carries operator state.
9
9
  """
10
10
 
11
- __version__ = "0.3.6"
11
+ __version__ = "0.3.7"
@@ -27,7 +27,7 @@ __all__ = [
27
27
  "WaitCancelled",
28
28
  "types",
29
29
  ]
30
- __version__ = "0.3.6"
30
+ __version__ = "0.3.7"
31
31
 
32
32
 
33
33
  class Client(_Transport):
@@ -24,9 +24,11 @@ from __future__ import annotations
24
24
  import base64
25
25
  import contextlib
26
26
  import getpass
27
+ import hashlib
27
28
  import json
28
29
  import os
29
30
  import re
31
+ import secrets
30
32
  import select
31
33
  import shutil
32
34
  import socket
@@ -578,7 +580,7 @@ def connect_target(base: str, device: dict) -> str:
578
580
  website = CONNECT_WEBSITES.get(urlsplit(base).netloc)
579
581
  code = device["user_code"]
580
582
  if website and re.fullmatch(r"[A-Za-z0-9]{4}-[A-Za-z0-9]{4}", code):
581
- return website + "/activate?" + urlencode({"code": code.upper()})
583
+ return website + "/device?" + urlencode({"code": code.upper()})
582
584
  return device.get("verification_uri_complete") or device["verification_uri"]
583
585
 
584
586
 
@@ -612,6 +614,297 @@ def _tokens(value, now: float) -> dict:
612
614
  }
613
615
 
614
616
 
617
+ #: The loopback redirect ports registered on the EvalRouter CLI Auth0 app, in
618
+ #: the order tried. Auth0 matches callback URLs exactly, port included.
619
+ LOOPBACK_PORTS = (47125, 47126, 47127)
620
+ LOOPBACK_SECONDS = 600
621
+
622
+ _AUTHORIZED_PAGE = (
623
+ "<!doctype html><html lang=en><meta charset=utf-8>"
624
+ "<meta name=viewport content='width=device-width,initial-scale=1'>"
625
+ "<title>EvalRouter CLI</title>"
626
+ "<body style='font:16px system-ui,sans-serif;display:grid;place-items:center;"
627
+ "min-height:90vh;margin:0;color:#111;background:#fff'>"
628
+ "<main style='max-width:26rem;padding:2rem;text-align:center'>"
629
+ "<p style='font-size:2rem;margin:0'>&#10003;</p>"
630
+ "<h1 style='font-size:1.5rem;margin:.5rem 0'>{title}</h1>"
631
+ "<p style='color:#555'>{message}</p></main></body></html>"
632
+ )
633
+
634
+
635
+ def _loopback_socket():
636
+ """Bind the first free registered port on 127.0.0.1 only, or return None."""
637
+ for port in LOOPBACK_PORTS:
638
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
639
+ try:
640
+ server.bind(("127.0.0.1", port))
641
+ server.listen(4)
642
+ return server, port
643
+ except OSError:
644
+ server.close()
645
+ return None
646
+
647
+
648
+ def _loopback_reply(connection, status: str, title: str, message: str) -> None:
649
+ body = _AUTHORIZED_PAGE.format(title=title, message=message).encode()
650
+ headers = (
651
+ f"HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\n"
652
+ f"Content-Length: {len(body)}\r\nCache-Control: no-store\r\n"
653
+ "Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'\r\n"
654
+ "Referrer-Policy: no-referrer\r\nConnection: close\r\n\r\n"
655
+ )
656
+ with contextlib.suppress(OSError):
657
+ connection.sendall(headers.encode() + body)
658
+
659
+
660
+ def _loopback_callback(server, port: int, state: str, deadline: float, clock) -> dict:
661
+ """Serve one-shot requests until the browser returns this sign-in's callback.
662
+
663
+ Only GET /callback with Host 127.0.0.1:<port> and the exact `state` counts;
664
+ anything else is answered and ignored, so a stray page cannot end sign-in.
665
+ """
666
+ from urllib.parse import parse_qs
667
+
668
+ while True:
669
+ remaining = deadline - clock()
670
+ if remaining <= 0:
671
+ raise ClientError("login_expired", "Sign-in timed out. Run `evalrouter login` again.")
672
+ server.settimeout(min(remaining, 1.0))
673
+ try:
674
+ connection, _ = server.accept()
675
+ except TimeoutError:
676
+ continue
677
+ with connection:
678
+ connection.settimeout(5)
679
+ try:
680
+ raw = connection.recv(8192).decode("latin-1")
681
+ except OSError:
682
+ continue
683
+ head = raw.split("\r\n\r\n", 1)[0].split("\r\n")
684
+ parts = head[0].split(" ")
685
+ host = next(
686
+ (
687
+ line.split(":", 1)[1].strip()
688
+ for line in head[1:]
689
+ if line.lower().startswith("host:")
690
+ ),
691
+ "",
692
+ )
693
+ if len(parts) != 3 or parts[0] != "GET" or host != f"127.0.0.1:{port}":
694
+ _loopback_reply(connection, "400 Bad Request", "Not available", "")
695
+ continue
696
+ path, _, query = parts[1].partition("?")
697
+ params = {k: v[0] for k, v in parse_qs(query, keep_blank_values=True).items()}
698
+ if path != "/callback" or params.get("state") != state:
699
+ _loopback_reply(connection, "404 Not Found", "Not found", "")
700
+ continue
701
+ if params.get("error"):
702
+ _loopback_reply(
703
+ connection,
704
+ "200 OK",
705
+ "Sign-in cancelled",
706
+ "Nothing was connected. You can close this tab.",
707
+ )
708
+ raise ClientError("login_denied", "Sign-in was cancelled in the browser.")
709
+ if not params.get("code"):
710
+ _loopback_reply(connection, "400 Bad Request", "Not available", "")
711
+ continue
712
+ _loopback_reply(
713
+ connection,
714
+ "200 OK",
715
+ "Authorized",
716
+ "EvalRouter CLI is signed in. You can close this tab and return to your terminal.",
717
+ )
718
+ return params
719
+
720
+
721
+ class LoginDeclined(ClientError):
722
+ """Escape (or Ctrl+C, ``quit``) at "Press Enter": nothing was opened or stored."""
723
+
724
+ def __init__(self, *, quit: bool = False):
725
+ super().__init__("login_cancelled", "Not signed in.")
726
+ self.quit = quit
727
+
728
+
729
+ def _confirm_browser(shown: list[str], link: str) -> None:
730
+ """gh-style "Press Enter to open LINK in your browser"; Escape declines.
731
+
732
+ The prompt line joins ``shown`` so it is erased with the other
733
+ instructions. On Escape or Ctrl+C the line is ended, everything shown is
734
+ erased and LoginDeclined raised (``quit`` for Ctrl+C), never a traceback.
735
+ """
736
+ from . import render
737
+ from .render import picker
738
+
739
+ plain = render.is_plain(sys.stderr)
740
+ bold, reset = ("", "") if plain else ("\x1b[1m", "\x1b[0m")
741
+ rest = f"to open {link} in your browser..."
742
+ sys.stderr.write(f"{bold}Press Enter{reset} {rest}")
743
+ sys.stderr.flush()
744
+ shown.append("Press Enter " + rest)
745
+ accepted, quit = False, False
746
+ try:
747
+ accepted = picker.press_enter()
748
+ sys.stderr.write("\n") # raw keys are not echoed
749
+ except (ImportError, OSError):
750
+ try:
751
+ input() # the person's Enter ends the line
752
+ accepted = True
753
+ except EOFError:
754
+ sys.stderr.write("\n")
755
+ except KeyboardInterrupt:
756
+ sys.stderr.write("\n")
757
+ quit = True
758
+ except KeyboardInterrupt:
759
+ sys.stderr.write("\n")
760
+ quit = True
761
+ sys.stderr.flush()
762
+ if not accepted:
763
+ _erase_lines(shown)
764
+ raise LoginDeclined(quit=quit)
765
+
766
+
767
+ def website_login(http: httpx.Client, base: str, config: dict, advertised: dict) -> str | None:
768
+ """The short evalrouter.ai sign-in page for this server, when it is live.
769
+
770
+ The page forwards to the Auth0 app the server advertises, so it is used
771
+ only when this CLI signs in with that same app (not an override), and
772
+ only after it answers as the sign-in page (older websites lack it).
773
+ """
774
+ website = CONNECT_WEBSITES.get(urlsplit(base).netloc)
775
+ advertised_host = str(
776
+ advertised.get("domain") or urlsplit(str(advertised.get("issuer") or "")).netloc
777
+ )
778
+ if not website or (
779
+ config["client_id"],
780
+ config["audience"],
781
+ urlsplit(config["issuer"]).netloc,
782
+ ) != (advertised.get("client_id"), advertised.get("audience"), advertised_host):
783
+ return None
784
+ try:
785
+ response = http.get(website + "/login/device", timeout=5)
786
+ error = response.json().get("error") if response.status_code == 400 else None
787
+ except (httpx.HTTPError, ValueError, AttributeError):
788
+ return None
789
+ ready = isinstance(error, dict) and error.get("code") == "invalid_cli_login"
790
+ return website + "/login/device" if ready else None
791
+
792
+
793
+ def _loopback_login(
794
+ http,
795
+ config,
796
+ *,
797
+ open_browser,
798
+ notice,
799
+ lead=None,
800
+ confirm=None,
801
+ website=None,
802
+ clock=time.monotonic,
803
+ wall=time.time,
804
+ ):
805
+ """Browser sign-in that returns straight to this terminal (RFC 8252 + PKCE).
806
+
807
+ The authorization code comes back to a one-shot listener on 127.0.0.1 and is
808
+ exchanged with the PKCE verifier that never leaves this process. Returns
809
+ tokens, or None when no registered port is free or the browser did not open,
810
+ so the caller falls back to the device code.
811
+ """
812
+ from . import render
813
+
814
+ bound = _loopback_socket()
815
+ if bound is None:
816
+ return None
817
+ server, port = bound
818
+ with server:
819
+ verifier = secrets.token_urlsafe(64)
820
+ challenge = (
821
+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
822
+ .rstrip(b"=")
823
+ .decode()
824
+ )
825
+ state = secrets.token_urlsafe(24)
826
+ redirect = f"http://127.0.0.1:{port}/callback"
827
+ url = (
828
+ config["issuer"]
829
+ + "authorize?"
830
+ + urlencode(
831
+ {
832
+ "response_type": "code",
833
+ "client_id": config["client_id"],
834
+ "redirect_uri": redirect,
835
+ "scope": " ".join(config["scopes"]),
836
+ "audience": config["audience"],
837
+ "state": state,
838
+ "code_challenge": challenge,
839
+ "code_challenge_method": "S256",
840
+ # Always choose the account: never silently reuse a browser
841
+ # session that may belong to another account.
842
+ "prompt": "login",
843
+ }
844
+ )
845
+ )
846
+ shown: list[str] = []
847
+ if confirm is not None:
848
+ for line in [lead] if lead else []:
849
+ shown.append(line)
850
+ notice(line)
851
+ # The authorize URL is hundreds of characters; the website's
852
+ # sign-in page (which forwards to it) is a readable link.
853
+ confirm(shown, website or urlsplit(url).netloc)
854
+ if website:
855
+ url = (
856
+ website
857
+ + "?"
858
+ + urlencode({"port": port, "state": state, "code_challenge": challenge})
859
+ )
860
+ opened = False
861
+ with contextlib.suppress(Exception):
862
+ opened = bool(open_browser(url))
863
+ if not opened:
864
+ _erase_lines(shown) # the device code follows, with its link
865
+ return None
866
+ if confirm is None:
867
+ for line in ([lead] if lead else []) + [
868
+ "Opened your browser to sign in or create an account.",
869
+ ]:
870
+ shown.append(line)
871
+ notice(line)
872
+ waiting = "Waiting for you to authorize in the browser (Ctrl+C: cancel)"
873
+ plain = render.is_plain(sys.stderr)
874
+ if plain:
875
+ shown.append(waiting + "...")
876
+ notice(waiting + "...")
877
+ status = (
878
+ contextlib.nullcontext()
879
+ if plain
880
+ else render.console_for(sys.stderr).status(waiting, spinner="dots")
881
+ )
882
+ with status:
883
+ params = _loopback_callback(server, port, state, clock() + LOOPBACK_SECONDS, clock)
884
+ try:
885
+ response = http.post(
886
+ config["token_endpoint"],
887
+ data={
888
+ "grant_type": "authorization_code",
889
+ "client_id": config["client_id"],
890
+ "code": params["code"],
891
+ "code_verifier": verifier,
892
+ "redirect_uri": redirect,
893
+ },
894
+ timeout=15,
895
+ )
896
+ except httpx.HTTPError:
897
+ raise ClientError("network_error", "Could not finish sign-in with Auth0.") from None
898
+ if not response.is_success:
899
+ raise ClientError("login_failed", "Sign-in failed. Run `evalrouter login` again.")
900
+ try:
901
+ tokens = _tokens(response.json(), wall())
902
+ except ValueError:
903
+ raise ClientError("login_failed", "Sign-in returned an unusable response.") from None
904
+ _erase_lines(shown)
905
+ return tokens
906
+
907
+
615
908
  class _RestartDeviceLogin(Exception):
616
909
  """The customer requested a new code; the pending request is abandoned."""
617
910
 
@@ -1251,7 +1544,9 @@ def _erase_lines(lines: list[str]) -> None:
1251
1544
  sys.stderr.flush()
1252
1545
 
1253
1546
 
1254
- def _compact_device_login(http, config, device, target, *, open_browser, notice, sleep, lead=None):
1547
+ def _compact_device_login(
1548
+ http, config, device, target, *, open_browser, notice, sleep, lead=None, confirm=None
1549
+ ):
1255
1550
  """The terminal sign-in: open the browser, show the code, wait with a spinner.
1256
1551
 
1257
1552
  Returns tokens, or None when the person asked for a new code. The steps
@@ -1271,22 +1566,27 @@ def _compact_device_login(http, config, device, target, *, open_browser, notice,
1271
1566
  if lead:
1272
1567
  notice(lead)
1273
1568
  host = urlsplit(config["issuer"]).netloc
1569
+ step = (
1570
+ f"Code {device['user_code']}: confirm it, sign in at {host} if asked,"
1571
+ ' then wait for "Device connected".'
1572
+ )
1573
+ if confirm is not None:
1574
+ notice("! " + step) # the code first, like gh; the browser opens on Enter
1575
+ confirm(shown, target)
1274
1576
  opened = False
1275
1577
  with contextlib.suppress(Exception):
1276
1578
  opened = bool(open_browser(target))
1277
- notice(
1278
- "Opened your browser to sign in or create an account."
1279
- if opened
1280
- else "Open this link to sign in or create an account:"
1281
- )
1282
- notice(
1283
- f" Code {device['user_code']}: confirm it, sign in at {host} if asked,"
1284
- ' then wait for "Device connected".'
1285
- )
1286
- if opened:
1287
- notice(f" Browser did not open? {target}")
1288
- else:
1289
- notice(f" {target}")
1579
+ if confirm is None:
1580
+ notice(
1581
+ "Opened your browser to sign in or create an account."
1582
+ if opened
1583
+ else "Open this link to sign in or create an account:"
1584
+ )
1585
+ notice(" " + step)
1586
+ elif not opened:
1587
+ notice("The browser did not open. Open the link above to continue.")
1588
+ if confirm is None: # the prompt already showed the link
1589
+ notice(f" Browser did not open? {target}" if opened else f" {target}")
1290
1590
  waiting = "Waiting for the browser (Enter: new code, Ctrl+C: cancel)"
1291
1591
  plain = render.is_plain(sys.stderr)
1292
1592
  status = (
@@ -1345,7 +1645,29 @@ def login(
1345
1645
  config = auth0_config(base, advertisement)
1346
1646
  interactive = _interactive() and not getattr(args, "json", False)
1347
1647
  compact = interactive and not getattr(args, "no_browser", False)
1348
- while True:
1648
+ tokens = None
1649
+ flow = os.environ.get("EVALROUTER_LOGIN_FLOW", "").lower()
1650
+ # Loopback needs its callback URLs registered on this server's Auth0
1651
+ # app; otherwise Auth0 shows a callback error in the browser. So it runs
1652
+ # only when the server advertises it (or EVALROUTER_LOGIN_FLOW=loopback).
1653
+ loopback = flow == "loopback" or (
1654
+ flow != "device" and advertisement.get("loopback_redirect") is True
1655
+ )
1656
+ # Ask before opening a browser (Enter; Escape declines), as gh and
1657
+ # Heroku do. Once is enough: a loopback fallback reuses the answer.
1658
+ confirm = _confirm_browser if compact else None
1659
+ if compact and loopback:
1660
+ tokens = _loopback_login(
1661
+ http,
1662
+ config,
1663
+ open_browser=open_browser,
1664
+ notice=notice,
1665
+ lead=getattr(args, "sign_in_reason", None),
1666
+ confirm=confirm,
1667
+ website=website_login(http, base, config, advertisement),
1668
+ )
1669
+ confirm = None
1670
+ while tokens is None:
1349
1671
  device = start_device_authorization(http, config)
1350
1672
  target = connect_target(base, device)
1351
1673
  if compact:
@@ -1358,7 +1680,9 @@ def login(
1358
1680
  notice=notice,
1359
1681
  sleep=sleep,
1360
1682
  lead=getattr(args, "sign_in_reason", None),
1683
+ confirm=confirm,
1361
1684
  )
1685
+ confirm = None # a new code opens the browser straight away
1362
1686
  if tokens is None:
1363
1687
  continue
1364
1688
  break