sference-cli 0.2.3__tar.gz → 0.3.1__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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: sference-cli
3
- Version: 0.2.3
3
+ Version: 0.3.1
4
4
  Summary: sference command-line interface
5
5
  Project-URL: Homepage, https://sference.com
6
6
  Project-URL: Repository, https://github.com/s-ference/sference
@@ -21,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.12
21
21
  Classifier: Programming Language :: Python :: 3.13
22
22
  Classifier: Topic :: Utilities
23
23
  Requires-Python: >=3.10
24
- Requires-Dist: sference-sdk>=0.2.3
24
+ Requires-Dist: sference-sdk>=0.3.1
25
25
  Requires-Dist: typer>=0.24.1
26
26
  Description-Content-Type: text/markdown
27
27
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-cli"
3
- version = "0.2.3"
3
+ version = "0.3.1"
4
4
  description = "sference command-line interface"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -23,7 +23,7 @@ classifiers = [
23
23
  ]
24
24
  dependencies = [
25
25
  "typer>=0.24.1",
26
- "sference-sdk>=0.2.3",
26
+ "sference-sdk>=0.3.1",
27
27
  ]
28
28
 
29
29
  [project.urls]
@@ -0,0 +1,242 @@
1
+ """mitmproxy addon: route Sference models to api.sference.com, pass Claude through.
2
+
3
+ Loaded by ``mitmdump -s <this file>``. Runs inside mitmproxy's isolated tool
4
+ venv, which does NOT contain ``sference_cli`` — so we import the pure routing
5
+ helpers via a sibling path (the launcher extracts this file,
6
+ ``_proxy_routing.py`` and ``device_auth.py`` to the same temp dir), not via
7
+ ``from sference_cli…``.
8
+
9
+ Config comes from env (set by the launcher):
10
+ SFERENCE_PROXY_MODELS JSON list of routable catalog ids (text-generation)
11
+ SFERENCE_API_KEY Sference access token (sent as x-api-key)
12
+ SFERENCE_BASE_URL Sference API origin, e.g. https://api.sference.com
13
+ SFERENCE_REFRESH_TOKEN device-flow refresh token (optional; enables 401 refresh)
14
+ SFERENCE_CREDENTIALS_PATH ~/.sference/credentials.json (optional; refresh target)
15
+
16
+ Routing is a pure URL + auth rewrite; the request body passes through
17
+ byte-for-byte (Sference has a native /v1/messages endpoint) and the response is
18
+ already native Anthropic — no translation in either direction.
19
+
20
+ Device-flow access tokens live 24 h, so a long Claude session can outlive its
21
+ token. When a Sference-routed request comes back 401 and a refresh token is
22
+ configured, the addon refreshes (re-reading the credentials file first — a
23
+ sibling CLI/proxy may already have rotated it), persists the rotated pair,
24
+ and replays the request once with the new token.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import os
31
+ import sys
32
+ import time
33
+ from pathlib import Path
34
+
35
+ from mitmproxy import ctx, http
36
+
37
+ # Sibling imports: _proxy_routing.py and device_auth.py sit next to this file
38
+ # in the temp dir.
39
+ sys.path.insert(0, os.path.dirname(str(Path(__file__).resolve())))
40
+ from _proxy_routing import ( # noqa: E402
41
+ BOOTSTRAP,
42
+ PASSTHROUGH,
43
+ SFERENCE,
44
+ decide_routing,
45
+ inject_models_into_bootstrap,
46
+ parse_models_env,
47
+ rewrite_request_for_sference,
48
+ strip_unsigned_thinking_blocks,
49
+ )
50
+ from device_auth import CLIENT_ID_SFERENCE_CLI, DeviceAuthError, refresh_tokens # noqa: E402
51
+
52
+ SFERENCE_BASE_URL = os.environ.get("SFERENCE_BASE_URL", "https://api.sference.com").rstrip("/")
53
+ SFERENCE_API_KEY = os.environ.get("SFERENCE_API_KEY", "")
54
+ SFERENCE_MODELS = parse_models_env(os.environ.get("SFERENCE_PROXY_MODELS", ""))
55
+ SFERENCE_REFRESH_TOKEN = os.environ.get("SFERENCE_REFRESH_TOKEN", "")
56
+ SFERENCE_CREDENTIALS_PATH = os.environ.get("SFERENCE_CREDENTIALS_PATH", "")
57
+
58
+ # flow.id -> original model (for response handling — currently a no-op since
59
+ # the Sference response is already native Anthropic, but kept for clarity).
60
+ _sference_flows: dict[str, str] = {}
61
+ # flow.ids of bootstrap GETs whose response we post-process.
62
+ _bootstrap_flows: set[str] = set()
63
+
64
+
65
+ def _read_file_credentials() -> dict:
66
+ """Best-effort read of the v2 credentials file; {} on any problem."""
67
+ if not SFERENCE_CREDENTIALS_PATH:
68
+ return {}
69
+ try:
70
+ data = json.loads(Path(SFERENCE_CREDENTIALS_PATH).read_text(encoding="utf-8"))
71
+ except Exception:
72
+ return {}
73
+ return data if isinstance(data, dict) else {}
74
+
75
+
76
+ def _write_file_credentials(access_token: str, refresh_token: str, expires_in: float) -> None:
77
+ """Persist the rotated pair (0700 dir / 0600 file, matching the CLI)."""
78
+ if not SFERENCE_CREDENTIALS_PATH:
79
+ return
80
+ path = Path(SFERENCE_CREDENTIALS_PATH)
81
+ try:
82
+ path.parent.mkdir(parents=True, exist_ok=True)
83
+ payload = json.dumps(
84
+ {
85
+ "access_token": access_token,
86
+ "refresh_token": refresh_token,
87
+ "expires_at": time.time() + float(expires_in),
88
+ }
89
+ )
90
+ # Standard CLI credential storage: the user's own tokens in their own
91
+ # home dir (dir 0700, file 0600) — the same pattern gh/aws/gcloud use,
92
+ # not a server-side secret store.
93
+ path.write_text(payload, encoding="utf-8") # codeql[py/clear-text-storage-sensitive-data]
94
+ os.chmod(path, 0o600)
95
+ except OSError as exc:
96
+ ctx.log.warn(f"sference: could not persist refreshed credentials: {exc}")
97
+
98
+
99
+ def _refresh_access_token() -> str | None:
100
+ """Return a fresh access token, or None when refresh is impossible/failed.
101
+
102
+ Re-reads the credentials file BEFORE refreshing: a sibling CLI command or
103
+ proxy may already have rotated the grant (refresh tokens are single-use —
104
+ presenting a rotated-out one revokes the whole grant server-side). Only
105
+ when the file still holds OUR refresh token do we rotate it ourselves.
106
+ """
107
+ global SFERENCE_API_KEY, SFERENCE_REFRESH_TOKEN
108
+
109
+ file_creds = _read_file_credentials()
110
+ file_access = file_creds.get("access_token")
111
+ file_refresh = file_creds.get("refresh_token")
112
+ if isinstance(file_access, str) and file_access and file_access != SFERENCE_API_KEY:
113
+ # Someone else refreshed since we launched; adopt the file's token.
114
+ ctx.log.info("sference: adopted fresher access token from credentials file")
115
+ SFERENCE_API_KEY = file_access
116
+ if isinstance(file_refresh, str) and file_refresh:
117
+ SFERENCE_REFRESH_TOKEN = file_refresh
118
+ return file_access
119
+
120
+ refresh_token = file_refresh if isinstance(file_refresh, str) and file_refresh else SFERENCE_REFRESH_TOKEN
121
+ if not refresh_token:
122
+ return None
123
+ try:
124
+ tokens = refresh_tokens(SFERENCE_BASE_URL, CLIENT_ID_SFERENCE_CLI, refresh_token)
125
+ except DeviceAuthError as exc:
126
+ ctx.log.warn(f"sference: token refresh failed ({exc.description}); re-run `sference auth login`")
127
+ return None
128
+ SFERENCE_API_KEY = str(tokens["access_token"])
129
+ SFERENCE_REFRESH_TOKEN = str(tokens["refresh_token"])
130
+ _write_file_credentials(SFERENCE_API_KEY, SFERENCE_REFRESH_TOKEN, float(tokens["expires_in"]))
131
+ ctx.log.info("sference: refreshed the device access token after a 401")
132
+ return SFERENCE_API_KEY
133
+
134
+
135
+ class SferenceRouter:
136
+ def request(self, flow: "http.HTTPFlow") -> None:
137
+ if flow.request is None:
138
+ return
139
+ host = flow.request.pretty_host
140
+ method = flow.request.method
141
+ path = flow.request.path
142
+
143
+ body: object = None
144
+ if method == "POST":
145
+ try:
146
+ body = json.loads(flow.request.get_text())
147
+ except Exception:
148
+ body = None
149
+
150
+ decision = decide_routing(host, method, path, body, SFERENCE_MODELS)
151
+ if decision == PASSTHROUGH:
152
+ # Anthropic rejects thinking blocks whose signature it can't verify,
153
+ # and Sference emits an empty one — so a session that switched away
154
+ # from a Sference model replays unsignable history and 400s. Claude
155
+ # Code recovers by stripping and resending; do it here instead and
156
+ # save the wasted upload + round-trip. Sference-bound requests keep
157
+ # the blocks (byte-for-byte passthrough).
158
+ if (
159
+ host == "api.anthropic.com"
160
+ and method == "POST"
161
+ and "/v1/messages" in (path or "")
162
+ ):
163
+ body, dropped = strip_unsigned_thinking_blocks(body)
164
+ if dropped:
165
+ # set_text() recomputes content-length itself (correctly for
166
+ # any content-encoding); do NOT touch the header afterwards.
167
+ flow.request.set_text(json.dumps(body))
168
+ ctx.log.info(
169
+ f"sference: stripped {dropped} unsigned thinking block(s) "
170
+ "from Anthropic-bound request"
171
+ )
172
+ return
173
+ if decision == BOOTSTRAP:
174
+ _bootstrap_flows.add(flow.id)
175
+ return
176
+ # SFERENCE
177
+ model = body.get("model") if isinstance(body, dict) else None
178
+ ctx.log.info(f"sference: routing model={model!r} -> Sference")
179
+ _sference_flows[flow.id] = str(model)
180
+ new_url, set_headers, remove_headers = rewrite_request_for_sference(
181
+ flow.request.url, SFERENCE_BASE_URL, SFERENCE_API_KEY
182
+ )
183
+ flow.request.url = new_url
184
+ for key, value in set_headers.items():
185
+ flow.request.headers[key] = value
186
+ for key in remove_headers:
187
+ flow.request.headers.pop(key, None)
188
+
189
+ def response(self, flow: "http.HTTPFlow") -> None:
190
+ if flow.response is None:
191
+ return
192
+ if flow.id in _bootstrap_flows:
193
+ _bootstrap_flows.discard(flow.id)
194
+ self._inject_models(flow)
195
+ return
196
+ if flow.id in _sference_flows:
197
+ _sference_flows.pop(flow.id)
198
+ if flow.response.status_code == 401:
199
+ self._maybe_refresh_and_replay(flow)
200
+ # Native Anthropic response: pass through untouched.
201
+ return
202
+
203
+ def _maybe_refresh_and_replay(self, flow: "http.HTTPFlow") -> None:
204
+ """On a Sference 401, refresh the device token and replay the request once.
205
+
206
+ Guards: only with a refresh token configured (device-flow credentials),
207
+ only once per flow (a replayed request that 401s again surfaces the 401
208
+ to the client), and only when the mitmproxy version supports replay.
209
+ """
210
+ if not SFERENCE_REFRESH_TOKEN and not SFERENCE_CREDENTIALS_PATH:
211
+ return
212
+ if flow.metadata.get("sference_auth_retried"):
213
+ return
214
+ if not hasattr(flow, "replay"):
215
+ ctx.log.warn("sference: 401 but this mitmproxy version cannot replay flows")
216
+ return
217
+ new_token = _refresh_access_token()
218
+ if not new_token:
219
+ return
220
+ flow.metadata["sference_auth_retried"] = True
221
+ flow.request.headers["x-api-key"] = new_token
222
+ ctx.log.info("sference: replaying request with refreshed token")
223
+ flow.replay()
224
+
225
+ def _inject_models(self, flow: "http.HTTPFlow") -> None:
226
+ if flow.response.status_code != 200:
227
+ return
228
+ try:
229
+ body = json.loads(flow.response.get_text())
230
+ except Exception:
231
+ return
232
+ before = len(body.get("additional_model_options", []) if isinstance(body, dict) else [])
233
+ body = inject_models_into_bootstrap(body, SFERENCE_MODELS)
234
+ flow.response.set_text(json.dumps(body))
235
+ # Body length changed; drop stale framing so mitmproxy recomputes it.
236
+ flow.response.headers.pop("content-length", None)
237
+ flow.response.headers.pop("Content-Length", None)
238
+ after = len(body.get("additional_model_options", []) if isinstance(body, dict) else [])
239
+ ctx.log.info(f"sference: bootstrap injected {after - before} model(s) into /model picker")
240
+
241
+
242
+ addons = [SferenceRouter()]
@@ -0,0 +1,153 @@
1
+ """Device-flow (RFC 8628) client for ``sference auth login`` and token refresh.
2
+
3
+ Stdlib-only (json, urllib, time) so this module imports in ANY venv — the
4
+ mitmproxy addon (``_proxy_addon.py``) runs in mitmproxy's isolated tool venv
5
+ without ``sference_cli`` installed and sibling-imports this file to refresh an
6
+ expired device token mid-session. Keep it dependency-free.
7
+
8
+ Wire shapes come from the platform's device-flow endpoints (plan §4.3):
9
+ POST /v1/oauth/device_code -> {device_code, user_code, verification_uri, expires_in, interval}
10
+ POST /v1/oauth/token -> {access_token, token_type, expires_in, refresh_token}
11
+ or 400 {error, error_description} (RFC 6749 shape)
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ from collections.abc import Callable
21
+ from typing import Any
22
+
23
+ # Registered on the platform; unknown client_ids get invalid_client.
24
+ CLIENT_ID_SFERENCE_CLI = "sference-cli"
25
+
26
+ GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code"
27
+ GRANT_TYPE_REFRESH_TOKEN = "refresh_token"
28
+
29
+ # Refresh this far ahead of expiry so a token never dies mid-request.
30
+ EXPIRY_SKEW_SECONDS = 60
31
+
32
+
33
+ class DeviceAuthError(Exception):
34
+ """A device-flow call failed. ``error`` is the RFC 6749 code when the
35
+ server sent one (``invalid_grant``, ``expired_token``, …), else a local
36
+ label (``network_error``, ``http_<status>``)."""
37
+
38
+ def __init__(self, error: str, description: str) -> None:
39
+ super().__init__(f"{error}: {description}")
40
+ self.error = error
41
+ self.description = description
42
+
43
+
44
+ def post_json(url: str, payload: dict[str, Any], timeout: float = 15.0) -> tuple[int, dict[str, Any]]:
45
+ """POST a JSON body; return ``(status, parsed_json)`` for ANY status.
46
+
47
+ The device-flow endpoints signal pending/slow_down/expired via 400 bodies,
48
+ so HTTP errors are data, not exceptions. Network failures raise
49
+ :class:`DeviceAuthError` — the caller cannot distinguish statuses it never
50
+ received.
51
+ """
52
+ req = urllib.request.Request(
53
+ url,
54
+ data=json.dumps(payload).encode("utf-8"),
55
+ headers={"Content-Type": "application/json", "Accept": "application/json"},
56
+ method="POST",
57
+ )
58
+ try:
59
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
60
+ raw = resp.read().decode("utf-8")
61
+ return resp.status, json.loads(raw) if raw else {}
62
+ except urllib.error.HTTPError as exc:
63
+ raw = exc.read().decode("utf-8", errors="replace")
64
+ try:
65
+ return exc.code, json.loads(raw) if raw else {}
66
+ except json.JSONDecodeError:
67
+ return exc.code, {}
68
+ except (urllib.error.URLError, OSError) as exc:
69
+ raise DeviceAuthError("network_error", str(exc)) from exc
70
+
71
+
72
+ def _api_root(base_url: str) -> str:
73
+ root = base_url.rstrip("/")
74
+ if root.endswith("/v1"):
75
+ root = root[: -len("/v1")]
76
+ return root + "/v1"
77
+
78
+
79
+ def start_device_login(base_url: str, client_id: str, device_label: str | None = None) -> dict[str, Any]:
80
+ """POST /v1/oauth/device_code; return the parsed DeviceCodeResponse."""
81
+ payload: dict[str, Any] = {"client_id": client_id}
82
+ if device_label:
83
+ payload["device_label"] = device_label
84
+ status, body = post_json(f"{_api_root(base_url)}/oauth/device_code", payload)
85
+ if status != 200:
86
+ raise DeviceAuthError(
87
+ str(body.get("error") or f"http_{status}"),
88
+ str(body.get("error_description") or f"device_code request failed ({status})"),
89
+ )
90
+ return body
91
+
92
+
93
+ def poll_for_tokens(
94
+ base_url: str,
95
+ client_id: str,
96
+ device_code: str,
97
+ *,
98
+ interval: float,
99
+ expires_in: float,
100
+ sleep: Callable[[float], None] = time.sleep,
101
+ monotonic: Callable[[], float] = time.monotonic,
102
+ ) -> dict[str, Any]:
103
+ """Poll /v1/oauth/token until the user approves; return the token response.
104
+
105
+ Honors the RFC 8628 pacing contract: ``authorization_pending`` waits
106
+ ``interval``; ``slow_down`` adds 5 s to it (the server also enforces pacing
107
+ via ``last_polled_at`` — a client that ignores slow_down gets 400s).
108
+ ``sleep``/``monotonic`` are injectable for tests.
109
+ """
110
+ url = f"{_api_root(base_url)}/oauth/token"
111
+ deadline = monotonic() + expires_in
112
+ wait = interval
113
+ while True:
114
+ status, body = post_json(
115
+ url,
116
+ {"grant_type": GRANT_TYPE_DEVICE_CODE, "client_id": client_id, "device_code": device_code},
117
+ )
118
+ if status == 200:
119
+ return body
120
+ error = str(body.get("error") or f"http_{status}")
121
+ description = str(body.get("error_description") or f"token poll failed ({status})")
122
+ if error == "authorization_pending":
123
+ if monotonic() + wait > deadline:
124
+ raise DeviceAuthError("expired_token", "device code expired before approval")
125
+ sleep(wait)
126
+ continue
127
+ if error == "slow_down":
128
+ wait += 5
129
+ if monotonic() + wait > deadline:
130
+ raise DeviceAuthError("expired_token", "device code expired before approval")
131
+ sleep(wait)
132
+ continue
133
+ raise DeviceAuthError(error, description)
134
+
135
+
136
+ def refresh_tokens(base_url: str, client_id: str, refresh_token: str) -> dict[str, Any]:
137
+ """POST /v1/oauth/token with grant_type=refresh_token; return the token response.
138
+
139
+ The server rotates on every refresh: the returned ``refresh_token`` REPLACES
140
+ the presented one, and presenting a rotated-out token revokes the whole
141
+ grant (reuse detection). Callers must persist the new pair atomically —
142
+ see ``main._write_device_credentials``.
143
+ """
144
+ status, body = post_json(
145
+ f"{_api_root(base_url)}/oauth/token",
146
+ {"grant_type": GRANT_TYPE_REFRESH_TOKEN, "client_id": client_id, "refresh_token": refresh_token},
147
+ )
148
+ if status != 200:
149
+ raise DeviceAuthError(
150
+ str(body.get("error") or f"http_{status}"),
151
+ str(body.get("error_description") or f"refresh failed ({status})"),
152
+ )
153
+ return body
@@ -18,6 +18,15 @@ from .proxy import fetch_sference_model_entries, fetch_sference_models, launch_c
18
18
  DEFAULT_LAUNCH_MODEL = "zai-org/GLM-5.2"
19
19
  DEFAULT_API_BASE_URL = "https://api.sference.com"
20
20
 
21
+ # Thinking-effort variants stamped on every Sference model entry in the opencode
22
+ # config. The levels are a subset of OpenAI's ReasoningEffort enum that the platform
23
+ # accepts (``reasoning_effort`` on chat completions); ``none`` disables thinking, the
24
+ # rest enable it and each model's chat template decides what the level means. The AI
25
+ # SDK openai-compatible provider forwards the variant's ``reasoningEffort`` option as
26
+ # ``reasoning_effort`` in the request body. On models the catalog marks non-thinking
27
+ # the effort is a server-side no-op, so stamping every fetched model is safe.
28
+ OPENCODE_THINKING_VARIANTS = ("none", "medium", "high", "xhigh")
29
+
21
30
 
22
31
  def resolve_api_base_url(explicit: Optional[str]) -> str:
23
32
  if explicit:
@@ -330,8 +339,12 @@ def _write_opencode_config(*, base_url: str, model: str, models: set[str]) -> Pa
330
339
  user's opencode config.
331
340
 
332
341
  All models in ``models`` are written to the provider's ``models`` block so
333
- they appear in opencode's model picker. ``model`` is the default — set as
334
- the top-level ``model`` key so opencode uses Sference by default on startup.
342
+ they appear in opencode's model picker, each with the thinking-effort
343
+ variants in ``OPENCODE_THINKING_VARIANTS`` (selectable as
344
+ ``sference/<model>@<level>`` or via opencode's variant switcher; no variant
345
+ means the server-side catalog default decides). ``model`` is the default —
346
+ set as the top-level ``model`` key so opencode uses Sference by default on
347
+ startup.
335
348
 
336
349
  The API key is referenced as ``{env:SFERENCE_API_KEY}`` so no secret is
337
350
  stored on disk; ``launch_opencode`` injects the resolved key into the
@@ -366,7 +379,13 @@ def _write_opencode_config(*, base_url: str, model: str, models: set[str]) -> Pa
366
379
  "apiKey": "{env:SFERENCE_API_KEY}",
367
380
  },
368
381
  "models": {
369
- m: {"name": m}
382
+ m: {
383
+ "name": m,
384
+ "variants": {
385
+ level: {"options": {"reasoningEffort": level}}
386
+ for level in OPENCODE_THINKING_VARIANTS
387
+ },
388
+ }
370
389
  for m in sorted(all_models)
371
390
  },
372
391
  }
@@ -503,12 +522,22 @@ def register_launch_commands(app: typer.Typer) -> None:
503
522
  Sference model). Unknown options and trailing args are forwarded to
504
523
  Claude Code, e.g. ``sference launch claude -p "fix the bug"``.
505
524
  """
506
- from sference_cli.main import _ensure_api_credential, _read_token
525
+ from sference_cli.main import (
526
+ CREDENTIALS_PATH,
527
+ _ensure_api_credential,
528
+ _read_device_credentials,
529
+ _read_token,
530
+ )
507
531
 
508
532
  _ensure_api_credential()
509
533
  api_key = _read_token()
510
534
  if api_key is None:
511
535
  raise typer.Exit(code=1)
536
+ # Device-flow (v2) credentials let the proxy refresh the 24 h access
537
+ # token mid-session; legacy API-key credentials have no refresh token.
538
+ # Skip when SFERENCE_API_KEY overrides the file — the env token is not
539
+ # the file's grant, and refreshing would swap identities mid-session.
540
+ device_creds = None if os.environ.get("SFERENCE_API_KEY") else _read_device_credentials()
512
541
 
513
542
  forwarded = list(ctx.args)
514
543
  if forwarded and forwarded[0] == "--":
@@ -557,6 +586,8 @@ def register_launch_commands(app: typer.Typer) -> None:
557
586
  claude_args=forwarded,
558
587
  dry_run=dry_run,
559
588
  proxy_port=proxy_port,
589
+ refresh_token=device_creds["refresh_token"] if device_creds else None,
590
+ credentials_path=str(CREDENTIALS_PATH) if device_creds else None,
560
591
  )
561
592
 
562
593
  @launch_app.command(
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  import json
4
4
  import logging
5
5
  import os
6
+ import platform
6
7
  import sys
7
8
  import time
8
9
  import webbrowser
@@ -19,7 +20,15 @@ from sference_cli import __version__ as _CLI_VERSION
19
20
  from sference_sdk.checkpoint import clear_checkpoint, load_checkpoint, save_checkpoint
20
21
 
21
22
  from . import stream_cache as stream_cache_mod
22
- from .launch import register_launch_commands
23
+ from .device_auth import (
24
+ CLIENT_ID_SFERENCE_CLI,
25
+ EXPIRY_SKEW_SECONDS,
26
+ DeviceAuthError,
27
+ poll_for_tokens,
28
+ refresh_tokens,
29
+ start_device_login,
30
+ )
31
+ from .launch import register_launch_commands, resolve_api_base_url
23
32
 
24
33
  _T = TypeVar("_T")
25
34
 
@@ -43,43 +52,203 @@ register_launch_commands(app)
43
52
 
44
53
  CREDENTIALS_PATH = Path.home() / ".sference" / "credentials.json"
45
54
 
46
- DEFAULT_CONSOLE_URL = "https://app.sference.com"
47
55
 
48
-
49
- def _write_token(token: str) -> None:
50
- # The credential file holds an API key; keep it owner-only (0700 dir / 0600 file)
51
- # so other local users cannot read it. chmod is a no-op on Windows.
56
+ def _write_credentials_payload(payload: dict) -> None:
57
+ # The credential file holds an API key or OAuth tokens; keep it owner-only
58
+ # (0700 dir / 0600 file) so other local users cannot read it. chmod is a
59
+ # no-op on Windows.
52
60
  CREDENTIALS_PATH.parent.mkdir(parents=True, exist_ok=True)
53
61
  try:
54
62
  os.chmod(CREDENTIALS_PATH.parent, 0o700)
55
63
  except OSError:
56
64
  pass
57
- CREDENTIALS_PATH.write_text(json.dumps({"token": token}), encoding="utf-8")
65
+ CREDENTIALS_PATH.write_text(json.dumps(payload), encoding="utf-8")
58
66
  try:
59
67
  os.chmod(CREDENTIALS_PATH, 0o600)
60
68
  except OSError:
61
69
  pass
62
70
 
63
71
 
64
- def _read_token() -> str | None:
65
- env = os.environ.get("SFERENCE_API_KEY")
66
- if env:
67
- return env.strip() or None
72
+ def _write_token(token: str) -> None:
73
+ _write_credentials_payload({"token": token})
74
+
75
+
76
+ def _write_device_credentials(tokens: dict) -> None:
77
+ """Persist a device-flow token response (v2 credentials).
78
+
79
+ Stores an absolute ``expires_at`` (not the wire ``expires_in``) so readers
80
+ never have to know when the file was written. The refresh token rotates on
81
+ every refresh — the file must always hold the newest pair.
82
+ """
83
+ _write_credentials_payload(
84
+ {
85
+ "access_token": tokens["access_token"],
86
+ "refresh_token": tokens["refresh_token"],
87
+ "expires_at": time.time() + float(tokens["expires_in"]),
88
+ }
89
+ )
90
+
91
+
92
+ def _read_credentials_file() -> dict | None:
68
93
  if not CREDENTIALS_PATH.exists():
69
94
  return None
70
95
  try:
71
96
  payload = json.loads(CREDENTIALS_PATH.read_text(encoding="utf-8"))
72
- tok = payload.get("token")
73
- return tok.strip() if isinstance(tok, str) else None
74
97
  except Exception:
75
98
  return None
99
+ return payload if isinstance(payload, dict) else None
100
+
101
+
102
+ def _device_flow_base_url() -> str:
103
+ return resolve_api_base_url(None)
104
+
105
+
106
+ def _read_device_credentials() -> dict | None:
107
+ """v2 credentials ``{access_token, refresh_token, expires_at}``, refreshing first.
108
+
109
+ Returns None when the file holds no usable device grant (legacy ``{"token"}``
110
+ shape, malformed, or the refresh failed — e.g. the grant was revoked, which
111
+ is also how reuse detection surfaces here). A successful refresh rewrites
112
+ the file with the rotated pair before returning.
113
+ """
114
+ payload = _read_credentials_file()
115
+ if payload is None:
116
+ return None
117
+ access_token = payload.get("access_token")
118
+ refresh_token = payload.get("refresh_token")
119
+ expires_at = payload.get("expires_at")
120
+ if not isinstance(access_token, str) or not isinstance(refresh_token, str):
121
+ return None
122
+ if not isinstance(expires_at, (int, float)):
123
+ return None
124
+ if time.time() < expires_at - EXPIRY_SKEW_SECONDS:
125
+ return {"access_token": access_token, "refresh_token": refresh_token, "expires_at": expires_at}
126
+ try:
127
+ tokens = refresh_tokens(_device_flow_base_url(), CLIENT_ID_SFERENCE_CLI, refresh_token)
128
+ except DeviceAuthError as exc:
129
+ typer.echo(
130
+ f"Device login could not be refreshed ({exc.description}).\n"
131
+ "Run `sference auth login` to sign in again.",
132
+ err=True,
133
+ )
134
+ return None
135
+ _write_device_credentials(tokens)
136
+ return _read_credentials_file()
137
+
138
+
139
+ _warned: set[str] = set()
140
+
141
+
142
+ def _warn_once(message: str) -> None:
143
+ """Credential resolution runs several times per command; say it once."""
144
+ if message not in _warned:
145
+ _warned.add(message)
146
+ typer.echo(message, err=True)
147
+
148
+
149
+ def _has_device_grant() -> bool:
150
+ """Whether the file holds a device pair — checked without refreshing it."""
151
+ payload = _read_credentials_file()
152
+ if payload is None:
153
+ return False
154
+ return isinstance(payload.get("access_token"), str) and isinstance(payload.get("refresh_token"), str)
155
+
156
+
157
+ def _env_api_key() -> str | None:
158
+ env = os.environ.get("SFERENCE_API_KEY")
159
+ return env.strip() if env and env.strip() else None
160
+
161
+
162
+ # Set once a refresh has proved the grant is gone, so the rest of the command
163
+ # stops presenting a credential the server has already rejected.
164
+ _device_grant_dead = False
165
+
166
+
167
+ def _recover_from_unauthorized() -> str | None:
168
+ """SDK 401 hook: the access token was rejected — try to replace it.
169
+
170
+ The cached token is used until it nears expiry, so a grant revoked (or
171
+ reuse-detected) server-side is invisible locally until something 401s. That
172
+ is the moment to refresh: either the token had simply gone stale and the
173
+ grant is fine, or the refresh fails and the grant really is dead — in which
174
+ case an API key, if the caller has one, is the credential to continue on.
175
+ """
176
+ global _device_grant_dead
177
+ if _device_grant_dead or not _has_device_grant():
178
+ return None
179
+ payload = _read_credentials_file() or {}
180
+ refresh_token = payload.get("refresh_token")
181
+ if not isinstance(refresh_token, str):
182
+ return None
183
+ try:
184
+ tokens = refresh_tokens(_device_flow_base_url(), CLIENT_ID_SFERENCE_CLI, refresh_token)
185
+ except DeviceAuthError as exc:
186
+ _device_grant_dead = True
187
+ _warn_once(
188
+ f"This device is no longer signed in ({exc.description}).\n"
189
+ "Run `sference auth login` to sign in again."
190
+ )
191
+ env_key = _env_api_key()
192
+ if env_key is not None:
193
+ _warn_once("Continuing with SFERENCE_API_KEY.")
194
+ return env_key
195
+ _write_device_credentials(tokens)
196
+ return str(tokens["access_token"])
197
+
76
198
 
199
+ def _read_token() -> str | None:
200
+ """Resolve the credential to send, device login first.
201
+
202
+ `sference auth login` is the CLI's own way in, so a signed-in device beats
203
+ ``SFERENCE_API_KEY``: an sk_ key is meant for non-interactive product
204
+ integrations (litellm, CI) that never run the device flow. The env var used
205
+ to win outright, which meant a key left over in a shell silently swallowed a
206
+ login the user had just completed — including the validation step right
207
+ after it, which then reported a bare 401.
208
+ """
209
+ env_key = _env_api_key()
77
210
 
78
- def _client(base_url: Optional[str] = None, *, timeout: float | None = None) -> SferenceClient:
211
+ if _has_device_grant() and not _device_grant_dead:
212
+ if env_key is not None:
213
+ _warn_once(
214
+ "Note: SFERENCE_API_KEY is set, but this device is signed in — using the "
215
+ "device login. Unset SFERENCE_API_KEY to use the API key instead."
216
+ )
217
+ creds = _read_device_credentials()
218
+ if creds is not None:
219
+ return creds["access_token"]
220
+ # The grant is gone (revoked, expired, reuse-detected). _read_device_credentials
221
+ # has already said so; fall through so a usable key still works.
222
+ if env_key is not None:
223
+ return env_key
224
+ payload = _read_credentials_file()
225
+ if payload is None:
226
+ return None
227
+ tok = payload.get("token") # legacy API-key shape (CI / --api-key)
228
+ return tok.strip() if isinstance(tok, str) and tok.strip() else None
229
+
230
+
231
+ # The client the running command built. One invocation runs one command and
232
+ # builds one client, so this is unambiguous — it is what _call_api re-credentials
233
+ # when a device token turns out to be stale.
234
+ _active_client: SferenceClient | None = None
235
+
236
+
237
+ def _client(
238
+ base_url: Optional[str] = None,
239
+ *,
240
+ timeout: float | None = None,
241
+ token: Optional[str] = None,
242
+ ) -> SferenceClient:
243
+ """Build a client. ``token`` pins the credential instead of resolving one —
244
+ used right after a login, which must validate what it just minted rather
245
+ than whatever ``_read_token`` would pick."""
79
246
  env_base_url = os.environ.get("SFERENCE_BASE_URL")
80
247
  if env_base_url and (base_url is None or base_url == "https://api.sference.com"):
81
248
  base_url = env_base_url
82
- return SferenceClient(base_url=base_url, api_key=_read_token(), timeout=timeout)
249
+ global _active_client
250
+ _active_client = SferenceClient(base_url=base_url, api_key=token or _read_token(), timeout=timeout)
251
+ return _active_client
83
252
 
84
253
 
85
254
  def _ensure_api_credential() -> None:
@@ -100,13 +269,28 @@ def _call_api(fn: Callable[[], _T]) -> _T:
100
269
  except ApiError as exc:
101
270
  err = str(exc)
102
271
  if err.startswith("401:"):
103
- typer.echo(
104
- "Unauthorized (401). Create a key in Console → API Keys (while signed in), then run:\n"
105
- " sference auth login --api-key 'sk_...'\n"
106
- "If SFERENCE_API_KEY is set, it overrides ~/.sference/credentials.json.\n"
107
- "If you already saved a key, it may be revoked or not registered for this API/database.",
108
- err=True,
109
- )
272
+ # The cached access token is used until it nears expiry, so a grant
273
+ # refreshed, revoked or reuse-detected server-side surfaces only
274
+ # here. Retrying is safe because a 401 means the handler never ran,
275
+ # so nothing can be repeated — this is not a general-purpose retry.
276
+ replacement = _recover_from_unauthorized()
277
+ if replacement and _active_client is not None:
278
+ _active_client.set_api_key(replacement)
279
+ try:
280
+ return fn()
281
+ except ApiError as retry_exc:
282
+ err = str(retry_exc)
283
+ if err.startswith("401:"):
284
+ # A dead grant has already been explained by the recovery step, in
285
+ # more specific terms than this generic hint — don't say it twice.
286
+ if not _device_grant_dead:
287
+ typer.echo(
288
+ "Unauthorized (401). Run `sference auth login` to sign in again.\n"
289
+ "CI/non-interactive: sference auth login --api-key 'sk_...' "
290
+ "(create a key in Console → API Keys while signed in).\n"
291
+ "SFERENCE_API_KEY is used only when this device is not signed in.",
292
+ err=True,
293
+ )
110
294
  raise typer.Exit(code=1) from None
111
295
  typer.echo(err, err=True)
112
296
  if err.startswith(("504:", "408:")):
@@ -137,10 +321,10 @@ def _get_batch_or_missing(client: SferenceClient, batch_id: str) -> Any | None:
137
321
  return None
138
322
  if err.startswith("401:"):
139
323
  typer.echo(
140
- "Unauthorized (401). Create a key in Console → API Keys (while signed in), then run:\n"
141
- " sference auth login --api-key 'sk_...'\n"
142
- "If SFERENCE_API_KEY is set, it overrides ~/.sference/credentials.json.\n"
143
- "If you already saved a key, it may be revoked or not registered for this API/database.",
324
+ "Unauthorized (401). Run `sference auth login` to sign in again.\n"
325
+ "CI/non-interactive: sference auth login --api-key 'sk_...' "
326
+ "(create a key in Console → API Keys while signed in).\n"
327
+ "SFERENCE_API_KEY is used only when this device is not signed in.",
144
328
  err=True,
145
329
  )
146
330
  raise typer.Exit(code=1) from None
@@ -354,15 +538,27 @@ def auth_login(
354
538
  "--validate/--no-validate",
355
539
  help="Validate the credential by calling GET /v1/auth/me and print the authenticated user.",
356
540
  ),
541
+ base_url: Optional[str] = typer.Option(
542
+ None,
543
+ "--base-url",
544
+ envvar="SFERENCE_BASE_URL",
545
+ help="Sference API base URL for the device flow (default: https://api.sference.com).",
546
+ ),
357
547
  console_url: Optional[str] = typer.Option(
358
548
  None,
359
549
  "--console-url",
360
550
  envvar="SFERENCE_CONSOLE_URL",
361
- help="Console base URL for the browser step (default: https://app.sference.com).",
551
+ help="Override the console URL the browser opens (default: the server-provided verification URI).",
362
552
  ),
363
- no_browser: bool = typer.Option(False, "--no-browser", help="Do not open a browser; print the URL and prompt only."),
553
+ no_browser: bool = typer.Option(False, "--no-browser", help="Do not open a browser; print the URL and code only."),
364
554
  ) -> None:
365
- """Authenticate: store an API key for API requests (Baseten-style: optional --api-key for non-interactive)."""
555
+ """Authenticate this device: approve a code in the console (RFC 8628 device flow).
556
+
557
+ Interactive subscribers never handle an API key: the CLI holds a 24 h access
558
+ token plus a 30 d rotating refresh token in ~/.sference/credentials.json and
559
+ refreshes it automatically. ``--api-key`` keeps the non-interactive path
560
+ (CI) unchanged.
561
+ """
366
562
  if api_key is not None:
367
563
  key = api_key.strip()
368
564
  if not key:
@@ -371,7 +567,7 @@ def auth_login(
371
567
  _write_token(key)
372
568
  typer.echo(f"Credentials saved to {CREDENTIALS_PATH}")
373
569
  if validate:
374
- client = _client(None)
570
+ client = _client(None, token=key)
375
571
  me = _call_api(client.get_me)
376
572
  if as_json:
377
573
  _print(me, True)
@@ -382,31 +578,52 @@ def auth_login(
382
578
  typer.echo(f"Authenticated. {me}")
383
579
  return
384
580
 
385
- base = (console_url or DEFAULT_CONSOLE_URL).rstrip("/")
386
- login_url = f"{base}/login"
387
- api_keys_url = f"{base}/api-keys"
581
+ api_base = resolve_api_base_url(base_url)
582
+ try:
583
+ device_label = platform.node() or None
584
+ except Exception:
585
+ device_label = None
586
+ try:
587
+ start = start_device_login(api_base, CLIENT_ID_SFERENCE_CLI, device_label)
588
+ except DeviceAuthError as exc:
589
+ typer.echo(f"Could not start device login ({exc.description}).", err=True)
590
+ raise typer.Exit(code=1) from None
591
+
592
+ user_code = str(start["user_code"])
593
+ verification_uri = str(start["verification_uri"])
594
+ if console_url:
595
+ # Local dev / port-forwards: point the browser at the overridden console
596
+ # rather than the server-configured one.
597
+ verification_uri = f"{console_url.rstrip('/')}/device"
598
+ approve_url = f"{verification_uri}?code={user_code}"
388
599
 
389
600
  if not no_browser:
390
- typer.echo(f"Opening {login_url} in your browser...")
601
+ typer.echo(f"Opening {approve_url} in your browser...")
391
602
  try:
392
- webbrowser.open(login_url)
603
+ webbrowser.open(approve_url)
393
604
  except Exception:
394
605
  typer.echo("Could not open the browser automatically.")
395
-
396
- typer.echo("")
397
- typer.echo("After signing in:")
398
- typer.echo(f" 1. Open {api_keys_url}")
399
- typer.echo(" 2. Create an API key")
400
- typer.echo(" 3. Paste it below")
401
606
  typer.echo("")
402
- token = typer.prompt("API key", hide_input=True)
403
- if not token.strip():
404
- typer.echo("No API key provided.", err=True)
405
- raise typer.Exit(code=1)
406
- _write_token(token.strip())
607
+ typer.echo(f"Approve this device at: {approve_url}")
608
+ typer.echo(f"Code: {user_code}")
609
+ typer.echo("Waiting for approval...")
610
+
611
+ try:
612
+ tokens = poll_for_tokens(
613
+ api_base,
614
+ CLIENT_ID_SFERENCE_CLI,
615
+ str(start["device_code"]),
616
+ interval=float(start["interval"]),
617
+ expires_in=float(start["expires_in"]),
618
+ )
619
+ except DeviceAuthError as exc:
620
+ typer.echo(f"Device login failed ({exc.description}).", err=True)
621
+ raise typer.Exit(code=1) from None
622
+
623
+ _write_device_credentials(tokens)
407
624
  typer.echo(f"Credentials saved to {CREDENTIALS_PATH}")
408
625
  if validate:
409
- client = _client(None)
626
+ client = _client(api_base, token=str(tokens["access_token"]))
410
627
  me = _call_api(client.get_me)
411
628
  if as_json:
412
629
  _print(me, True)
@@ -102,16 +102,20 @@ def mitmproxy_available() -> bool:
102
102
 
103
103
 
104
104
  def _extract_addon_files() -> tuple[Path, Path]:
105
- """Extract the addon + routing helpers to a temp dir; return (tmpdir, addon_path).
105
+ """Extract the addon + its sibling imports to a temp dir; return (tmpdir, addon_path).
106
106
 
107
- Both files live in the same dir so the addon can ``from _proxy_routing import …``
108
- via a sibling path (mitmproxy's venv has no ``sference_cli``).
107
+ All three files live in the same dir so the addon can ``from _proxy_routing
108
+ import …`` / ``from device_auth import …`` via a sibling path (mitmproxy's
109
+ venv has no ``sference_cli``). ``device_auth.py`` is stdlib-only for exactly
110
+ this reason.
109
111
  """
110
112
  res = importlib.resources.files("sference_cli")
111
113
  addon_src = (res / "_proxy_addon.py").read_text(encoding="utf-8")
112
114
  routing_src = (res / "_proxy_routing.py").read_text(encoding="utf-8")
115
+ device_auth_src = (res / "device_auth.py").read_text(encoding="utf-8")
113
116
  tmpdir = Path(tempfile.mkdtemp(prefix="sference_proxy_"))
114
117
  (tmpdir / "_proxy_routing.py").write_text(routing_src, encoding="utf-8")
118
+ (tmpdir / "device_auth.py").write_text(device_auth_src, encoding="utf-8")
115
119
  addon_path = tmpdir / "_proxy_addon.py"
116
120
  addon_path.write_text(addon_src, encoding="utf-8")
117
121
  return tmpdir, addon_path
@@ -152,8 +156,16 @@ def launch_claude_via_proxy(
152
156
  dry_run: bool,
153
157
  proxy_port: Optional[int] = None,
154
158
  log_file: Optional[str] = None,
159
+ refresh_token: Optional[str] = None,
160
+ credentials_path: Optional[str] = None,
155
161
  ) -> None:
156
- """Start mitmproxy, then exec ``claude`` pointed at it. Blocks until claude exits."""
162
+ """Start mitmproxy, then exec ``claude`` pointed at it. Blocks until claude exits.
163
+
164
+ ``refresh_token``/``credentials_path`` come from device-flow (v2)
165
+ credentials: the addon refreshes the 24 h access token on a 401 and rewrites
166
+ the credentials file, so long sessions survive token expiry. Legacy API-key
167
+ credentials pass neither and 401s pass through untouched.
168
+ """
157
169
  if not mitmproxy_available():
158
170
  typer.echo(
159
171
  "mitmproxy not found. Install it with: uv tool install mitmproxy\n"
@@ -182,6 +194,8 @@ def launch_claude_via_proxy(
182
194
  typer.echo(f"Sference API: {sference_base}")
183
195
  typer.echo(f"Models ({len(models)}): {', '.join(sorted(models))}")
184
196
  typer.echo("apiKey: <redacted> (x-api-key, injected at launch)")
197
+ if refresh_token:
198
+ typer.echo("refreshToken: <redacted> (addon refreshes the 24h access token on 401)")
185
199
  typer.echo(f"HTTPS_PROXY=http://127.0.0.1:{port}")
186
200
  typer.echo(f"NODE_EXTRA_CA_CERTS={MITM_CA_CERT}")
187
201
  typer.echo("ANTHROPIC_BASE_URL=<unset> (first-party detection stays on)")
@@ -196,6 +210,10 @@ def launch_claude_via_proxy(
196
210
  "SFERENCE_BASE_URL": sference_base,
197
211
  "SFERENCE_PROXY_MODELS": json.dumps(sorted(models)),
198
212
  }
213
+ if refresh_token:
214
+ mitm_env["SFERENCE_REFRESH_TOKEN"] = refresh_token
215
+ if credentials_path:
216
+ mitm_env["SFERENCE_CREDENTIALS_PATH"] = credentials_path
199
217
  # Scope TLS interception to just the hosts we route. Without this, every
200
218
  # tool Claude Code spawns (Bash → curl, gh, …) also goes through the proxy
201
219
  # and fails TLS validation unless it trusts the mitmproxy CA. allow_hosts
@@ -1,134 +0,0 @@
1
- """mitmproxy addon: route Sference models to api.sference.com, pass Claude through.
2
-
3
- Loaded by ``mitmdump -s <this file>``. Runs inside mitmproxy's isolated tool
4
- venv, which does NOT contain ``sference_cli`` — so we import the pure routing
5
- helpers via a sibling path (the launcher extracts this file and
6
- ``_proxy_routing.py`` to the same temp dir), not via ``from sference_cli…``.
7
-
8
- Config comes from env (set by the launcher):
9
- SFERENCE_PROXY_MODELS JSON list of routable catalog ids (text-generation)
10
- SFERENCE_API_KEY Sference API key (sent as x-api-key)
11
- SFERENCE_BASE_URL Sference API origin, e.g. https://api.sference.com
12
-
13
- Routing is a pure URL + auth rewrite; the request body passes through
14
- byte-for-byte (Sference has a native /v1/messages endpoint) and the response is
15
- already native Anthropic — no translation in either direction.
16
- """
17
-
18
- from __future__ import annotations
19
-
20
- import json
21
- import os
22
- import sys
23
- from pathlib import Path
24
-
25
- from mitmproxy import ctx, http
26
-
27
- # Sibling import: _proxy_routing.py sits next to this file in the temp dir.
28
- sys.path.insert(0, os.path.dirname(str(Path(__file__).resolve())))
29
- from _proxy_routing import ( # noqa: E402
30
- BOOTSTRAP,
31
- PASSTHROUGH,
32
- SFERENCE,
33
- decide_routing,
34
- inject_models_into_bootstrap,
35
- parse_models_env,
36
- rewrite_request_for_sference,
37
- strip_unsigned_thinking_blocks,
38
- )
39
-
40
- SFERENCE_BASE_URL = os.environ.get("SFERENCE_BASE_URL", "https://api.sference.com").rstrip("/")
41
- SFERENCE_API_KEY = os.environ.get("SFERENCE_API_KEY", "")
42
- SFERENCE_MODELS = parse_models_env(os.environ.get("SFERENCE_PROXY_MODELS", ""))
43
-
44
- # flow.id -> original model (for response handling — currently a no-op since
45
- # the Sference response is already native Anthropic, but kept for clarity).
46
- _sference_flows: dict[str, str] = {}
47
- # flow.ids of bootstrap GETs whose response we post-process.
48
- _bootstrap_flows: set[str] = set()
49
-
50
-
51
- class SferenceRouter:
52
- def request(self, flow: "http.HTTPFlow") -> None:
53
- if flow.request is None:
54
- return
55
- host = flow.request.pretty_host
56
- method = flow.request.method
57
- path = flow.request.path
58
-
59
- body: object = None
60
- if method == "POST":
61
- try:
62
- body = json.loads(flow.request.get_text())
63
- except Exception:
64
- body = None
65
-
66
- decision = decide_routing(host, method, path, body, SFERENCE_MODELS)
67
- if decision == PASSTHROUGH:
68
- # Anthropic rejects thinking blocks whose signature it can't verify,
69
- # and Sference emits an empty one — so a session that switched away
70
- # from a Sference model replays unsignable history and 400s. Claude
71
- # Code recovers by stripping and resending; do it here instead and
72
- # save the wasted upload + round-trip. Sference-bound requests keep
73
- # the blocks (byte-for-byte passthrough).
74
- if (
75
- host == "api.anthropic.com"
76
- and method == "POST"
77
- and "/v1/messages" in (path or "")
78
- ):
79
- body, dropped = strip_unsigned_thinking_blocks(body)
80
- if dropped:
81
- # set_text() recomputes content-length itself (correctly for
82
- # any content-encoding); do NOT touch the header afterwards.
83
- flow.request.set_text(json.dumps(body))
84
- ctx.log.info(
85
- f"sference: stripped {dropped} unsigned thinking block(s) "
86
- "from Anthropic-bound request"
87
- )
88
- return
89
- if decision == BOOTSTRAP:
90
- _bootstrap_flows.add(flow.id)
91
- return
92
- # SFERENCE
93
- model = body.get("model") if isinstance(body, dict) else None
94
- ctx.log.info(f"sference: routing model={model!r} -> Sference")
95
- _sference_flows[flow.id] = str(model)
96
- new_url, set_headers, remove_headers = rewrite_request_for_sference(
97
- flow.request.url, SFERENCE_BASE_URL, SFERENCE_API_KEY
98
- )
99
- flow.request.url = new_url
100
- for key, value in set_headers.items():
101
- flow.request.headers[key] = value
102
- for key in remove_headers:
103
- flow.request.headers.pop(key, None)
104
-
105
- def response(self, flow: "http.HTTPFlow") -> None:
106
- if flow.response is None:
107
- return
108
- if flow.id in _bootstrap_flows:
109
- _bootstrap_flows.discard(flow.id)
110
- self._inject_models(flow)
111
- return
112
- if flow.id in _sference_flows:
113
- _sference_flows.pop(flow.id)
114
- # Native Anthropic response: pass through untouched.
115
- return
116
-
117
- def _inject_models(self, flow: "http.HTTPFlow") -> None:
118
- if flow.response.status_code != 200:
119
- return
120
- try:
121
- body = json.loads(flow.response.get_text())
122
- except Exception:
123
- return
124
- before = len(body.get("additional_model_options", []) if isinstance(body, dict) else [])
125
- body = inject_models_into_bootstrap(body, SFERENCE_MODELS)
126
- flow.response.set_text(json.dumps(body))
127
- # Body length changed; drop stale framing so mitmproxy recomputes it.
128
- flow.response.headers.pop("content-length", None)
129
- flow.response.headers.pop("Content-Length", None)
130
- after = len(body.get("additional_model_options", []) if isinstance(body, dict) else [])
131
- ctx.log.info(f"sference: bootstrap injected {after - before} model(s) into /model picker")
132
-
133
-
134
- addons = [SferenceRouter()]
File without changes
File without changes
File without changes