sference-cli 0.2.2__tar.gz → 0.3.0__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.2
3
+ Version: 0.3.0
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.2
24
+ Requires-Dist: sference-sdk>=0.3.0
25
25
  Requires-Dist: typer>=0.24.1
26
26
  Description-Content-Type: text/markdown
27
27
 
@@ -154,7 +154,7 @@ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moons
154
154
  | `sference launch pi --model moonshotai/Kimi-K2.7-Code` | Override catalog model |
155
155
  | `sference launch pi -- /path/to/project` | Forward Pi args after `sference launch pi` |
156
156
 
157
- Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provider block to `~/.pi/agent/models.json` with `baseUrl`, `apiKey`, and the chosen `model`, then execs `pi --provider sference --model <id>`. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
157
+ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provider block to `~/.pi/agent/models.json` using pi's `openai-responses` API (the Sference `/v1/responses` endpoint) with `baseUrl`, `apiKey`, and the full list of Sference-provided models (fetched live from `GET /v1/models`), then execs `pi --provider sference --model <id> --models sference/**`. The `--models sference/**` flag scopes pi's `/model` picker (and Ctrl+P cycling) to Sference models only, so other configured providers are hidden by default (`**` is required because Sference model ids contain a slash and `*` would match nothing). All catalog models appear in the picker; `--model` selects the active one. Reasoning is driven by pi's native `reasoning.effort` (no per-model thinking-format config needed). If the catalog fetch fails (offline), only the chosen model is registered. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
158
158
 
159
159
  ### Batch
160
160
 
@@ -127,7 +127,7 @@ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moons
127
127
  | `sference launch pi --model moonshotai/Kimi-K2.7-Code` | Override catalog model |
128
128
  | `sference launch pi -- /path/to/project` | Forward Pi args after `sference launch pi` |
129
129
 
130
- Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provider block to `~/.pi/agent/models.json` with `baseUrl`, `apiKey`, and the chosen `model`, then execs `pi --provider sference --model <id>`. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
130
+ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provider block to `~/.pi/agent/models.json` using pi's `openai-responses` API (the Sference `/v1/responses` endpoint) with `baseUrl`, `apiKey`, and the full list of Sference-provided models (fetched live from `GET /v1/models`), then execs `pi --provider sference --model <id> --models sference/**`. The `--models sference/**` flag scopes pi's `/model` picker (and Ctrl+P cycling) to Sference models only, so other configured providers are hidden by default (`**` is required because Sference model ids contain a slash and `*` would match nothing). All catalog models appear in the picker; `--model` selects the active one. Reasoning is driven by pi's native `reasoning.effort` (no per-model thinking-format config needed). If the catalog fetch fails (offline), only the chosen model is registered. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
131
131
 
132
132
  ### Batch
133
133
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-cli"
3
- version = "0.2.2"
3
+ version = "0.3.0"
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.2",
26
+ "sference-sdk>=0.3.0",
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
@@ -13,7 +13,7 @@ from typing import Optional
13
13
 
14
14
  import typer
15
15
 
16
- from .proxy import fetch_sference_models, launch_claude_via_proxy
16
+ from .proxy import fetch_sference_model_entries, fetch_sference_models, launch_claude_via_proxy
17
17
 
18
18
  DEFAULT_LAUNCH_MODEL = "zai-org/GLM-5.2"
19
19
  DEFAULT_API_BASE_URL = "https://api.sference.com"
@@ -140,16 +140,108 @@ def _pi_models_json_path() -> Path:
140
140
  return Path.home() / ".pi" / "agent" / "models.json"
141
141
 
142
142
 
143
- def _write_pi_models_json(*, base_url: str, api_key: str, model: str) -> Path:
144
- """Write or update ``~/.pi/agent/models.json`` with a Sference provider."""
143
+ def _pi_model_config(entry: dict) -> dict:
144
+ """Map a ``GET /v1/models`` entry to a pi ProviderModelConfig.
145
+
146
+ The Sference provider uses pi's ``openai-responses`` API, so reasoning is
147
+ driven by pi's native ``reasoning.effort`` field — the Sference
148
+ ``/v1/responses`` endpoint accepts it directly and translates it to the
149
+ worker's ``enable_thinking`` / ``reasoning_effort``. No per-model
150
+ chat-completions ``thinkingFormat`` compat is needed (that was an
151
+ ``openai-completions`` concern; the Responses API has one native reasoning
152
+ knob). Reasoning/input come from ``capabilities``, cost from ``pricing``;
153
+ ``maxTokens`` is clamped to 16384 (pi's default cap).
154
+
155
+ Reasoning-capable models get a ``thinkingLevelMap`` exposing ``xhigh`` only
156
+ (Sference's ``/v1/responses`` accepts effort in ``(minimal,low,medium,high,
157
+ xhigh)`` and 400s on ``max``). ``max`` is deliberately omitted from the map
158
+ so a ``max`` selection clamps down to ``xhigh`` (pi's
159
+ ``clampThinkingLevel`` walks down to the nearest supported level) instead of
160
+ sending an effort the API rejects. ``high`` and below need no map entry — pi
161
+ passes the requested level through verbatim for unmapped levels.
162
+ """
163
+ caps = entry.get("capabilities") or {}
164
+ thinking = bool((caps.get("thinking") or {}).get("supported", False))
165
+ image_in = bool((caps.get("image_input") or {}).get("supported", False))
166
+ pricing = entry.get("pricing") or {}
167
+ context_tokens = entry.get("context_tokens")
168
+ context_window = context_tokens if context_tokens is not None else 128000
169
+ max_tokens = min(context_tokens if context_tokens is not None else 8192, 16384)
170
+ config = {
171
+ "id": entry["id"],
172
+ "name": entry.get("display_name") or entry["id"],
173
+ "reasoning": thinking,
174
+ "input": ["text", "image"] if image_in else ["text"],
175
+ "cost": {
176
+ "input": pricing.get("input_per_million_usd") or 0,
177
+ "output": pricing.get("output_per_million_usd") or 0,
178
+ "cacheRead": pricing.get("cached_input_per_million_usd") or 0,
179
+ "cacheWrite": 0,
180
+ },
181
+ "contextWindow": context_window,
182
+ "maxTokens": max_tokens,
183
+ }
184
+ if thinking:
185
+ # Expose only xhigh (the top Sference-supported effort). max is
186
+ # unsupported on the API (400), so omitting it lets pi clamp a ``max``
187
+ # selection down to xhigh instead of sending an effort that errors.
188
+ config["thinkingLevelMap"] = {"xhigh": "xhigh"}
189
+ return config
190
+
191
+
192
+ def _build_pi_models(*, base_url: str, api_key: str, model: str) -> list[dict]:
193
+ """Build the pi model config list for the sference provider.
194
+
195
+ Fetches the live catalog (GET {base_url}/models) and maps every
196
+ text-generation entry to a pi ProviderModelConfig with reasoning/input/
197
+ cost/context metadata and the per-model thinking wire format, so all
198
+ Sference-provided models appear in pi's ``/model`` picker — not just the one
199
+ passed to ``--model``.
200
+
201
+ The picker always mirrors the live catalog exactly: the list is rebuilt on
202
+ every run, so a model that was removed/deprecated from the catalog is
203
+ dropped rather than accumulated forever, and no model is injected that
204
+ isn't currently available from Sference. ``--model`` only selects the
205
+ active model for the launch; it is never added to the picker when absent
206
+ from a reachable catalog. The only exception is an unreachable catalog
207
+ (offline): we can't show what we can't fetch, so we register just ``model``
208
+ as a bare fallback so ``launch pi`` still works.
209
+ """
210
+ try:
211
+ entries = fetch_sference_model_entries(base_url, api_key)
212
+ except Exception:
213
+ typer.echo(
214
+ f"note: could not fetch model catalog from {base_url}/models; "
215
+ f"registered only --model {model}. The /model picker will show just "
216
+ "this model.",
217
+ err=True,
218
+ )
219
+ entries = []
220
+ fetched = False
221
+ else:
222
+ fetched = True
223
+ configs = [_pi_model_config(entry) for entry in entries]
224
+ if not fetched and model not in {c["id"] for c in configs}:
225
+ configs.append({"id": model, "name": model})
226
+ return configs
227
+
228
+
229
+ def _write_pi_models_json(*, base_url: str, api_key: str, models: list[dict]) -> Path:
230
+ """Write or update ``~/.pi/agent/models.json`` with a Sference provider.
231
+
232
+ ``models`` is the full list of pi ProviderModelConfig dicts to register —
233
+ the Sference-provided text-generation models from the live catalog (or just
234
+ the chosen model as an offline fallback). Existing providers other than
235
+ ``sference`` are preserved; only the ``sference`` block is overwritten.
236
+ """
145
237
  path = _pi_models_json_path()
146
238
  path.parent.mkdir(parents=True, exist_ok=True)
147
239
 
148
240
  provider = {
149
- "api": "openai-completions",
241
+ "api": "openai-responses",
150
242
  "baseUrl": base_url,
151
243
  "apiKey": api_key,
152
- "models": [{"id": model, "name": model}],
244
+ "models": models,
153
245
  }
154
246
 
155
247
  if path.exists():
@@ -188,15 +280,26 @@ def launch_pi(
188
280
  )
189
281
  raise typer.Exit(code=1)
190
282
 
191
- models_json = _write_pi_models_json(base_url=base_url, api_key=api_key, model=model)
283
+ models = _build_pi_models(base_url=base_url, api_key=api_key, model=model)
284
+ models_json = _write_pi_models_json(base_url=base_url, api_key=api_key, models=models)
192
285
  env = os.environ.copy()
193
286
  # Pi reads providers from ~/.pi/agent/models.json; no env vars needed.
194
- cmd = [pi_bin, "--provider", "sference", "--model", model, *pi_args]
287
+ # `--models sference/**` scopes the /model picker (and Ctrl+P cycling) to the
288
+ # Sference provider only, so built-in / other configured providers are hidden
289
+ # by default instead of cluttering the picker. Using `**` (globstar) is
290
+ # required: pi matches `--models` patterns against `provider/modelId`, and
291
+ # Sference model ids contain a slash (e.g. `zai-org/GLM-5.2`), so `sference/*`
292
+ # would match nothing (`*` does not cross `/`) and the picker would fall back
293
+ # to showing every configured provider.
294
+ cmd = [pi_bin, "--provider", "sference", "--model", model, "--models", "sference/**", *pi_args]
195
295
 
196
296
  if dry_run:
197
297
  typer.echo(f"Wrote provider 'sference' to {models_json}")
198
298
  typer.echo(f"baseUrl: {base_url}")
299
+ typer.echo("api: openai-responses (/v1/responses)")
199
300
  typer.echo(f"model: {model}")
301
+ typer.echo(f"models registered: {len(models)}")
302
+ typer.echo("model scope: sference/** (other providers hidden by default)")
200
303
  typer.echo("apiKey: <redacted>")
201
304
  typer.echo(f"command: {' '.join(cmd)}")
202
305
  return
@@ -400,12 +503,22 @@ def register_launch_commands(app: typer.Typer) -> None:
400
503
  Sference model). Unknown options and trailing args are forwarded to
401
504
  Claude Code, e.g. ``sference launch claude -p "fix the bug"``.
402
505
  """
403
- from sference_cli.main import _ensure_api_credential, _read_token
506
+ from sference_cli.main import (
507
+ CREDENTIALS_PATH,
508
+ _ensure_api_credential,
509
+ _read_device_credentials,
510
+ _read_token,
511
+ )
404
512
 
405
513
  _ensure_api_credential()
406
514
  api_key = _read_token()
407
515
  if api_key is None:
408
516
  raise typer.Exit(code=1)
517
+ # Device-flow (v2) credentials let the proxy refresh the 24 h access
518
+ # token mid-session; legacy API-key credentials have no refresh token.
519
+ # Skip when SFERENCE_API_KEY overrides the file — the env token is not
520
+ # the file's grant, and refreshing would swap identities mid-session.
521
+ device_creds = None if os.environ.get("SFERENCE_API_KEY") else _read_device_credentials()
409
522
 
410
523
  forwarded = list(ctx.args)
411
524
  if forwarded and forwarded[0] == "--":
@@ -454,6 +567,8 @@ def register_launch_commands(app: typer.Typer) -> None:
454
567
  claude_args=forwarded,
455
568
  dry_run=dry_run,
456
569
  proxy_port=proxy_port,
570
+ refresh_token=device_creds["refresh_token"] if device_creds else None,
571
+ credentials_path=str(CREDENTIALS_PATH) if device_creds else None,
457
572
  )
458
573
 
459
574
  @launch_app.command(
@@ -483,10 +598,22 @@ def register_launch_commands(app: typer.Typer) -> None:
483
598
  ) -> None:
484
599
  """Run ``pi`` with Sference credentials.
485
600
 
486
- Writes a ``sference`` provider block to ``~/.pi/agent/models.json`` with
487
- ``baseUrl``, ``apiKey``, and the chosen ``model``, then execs
488
- ``pi --provider sference --model <id>``. Unknown options and trailing args
489
- are forwarded to Pi, e.g. ``sference launch pi -- /path/to/project``.
601
+ Writes a ``sference`` provider block to ``~/.pi/agent/models.json`` using
602
+ pi's ``openai-responses`` API (the Sference ``/v1/responses`` endpoint)
603
+ with ``baseUrl``, ``apiKey``, and the full list of Sference-provided
604
+ models (fetched live from ``GET /v1/models``), then execs
605
+ ``pi --provider sference --model <id> --models sference/**``. The
606
+ ``--models sference/**`` flag scopes the ``/model`` picker (and Ctrl+P
607
+ cycling) to Sference models only, so other configured providers are
608
+ hidden by default. ``**`` (globstar) is required because pi matches
609
+ patterns against ``provider/modelId`` and Sference model ids contain a
610
+ slash; ``sference/*`` would match nothing and show every provider. The
611
+ picker mirrors the currently-available catalog exactly; ``--model``
612
+ selects the active one and is never injected into the picker when absent
613
+ from a reachable catalog. If the catalog fetch fails (offline), only the
614
+ chosen model is registered.
615
+ Unknown options and trailing args are forwarded to Pi, e.g.
616
+ ``sference launch pi -- /path/to/project``.
490
617
  """
491
618
  from sference_cli.main import _ensure_api_credential, _read_token
492
619
 
@@ -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)
@@ -51,8 +51,13 @@ def _normalize_base_url(raw: str) -> str:
51
51
  return raw
52
52
 
53
53
 
54
- def fetch_sference_models(base_url: str, api_key: str) -> set[str]:
55
- """Pull the live text-generation model list from GET {base_url}/v1/models.
54
+ def fetch_sference_model_entries(base_url: str, api_key: str) -> list[dict]:
55
+ """Pull the live text-generation model entries from GET {base_url}/v1/models.
56
+
57
+ Returns the raw ``data`` items — the OpenAI-compatible shape with Sference
58
+ extensions (``display_name``, ``capabilities``, ``context_tokens``,
59
+ ``pricing``) — filtered to ``modality == "text_generation"``. Callers that
60
+ only need ids should use :func:`fetch_sference_models`.
56
61
 
57
62
  Keeps the router in sync with what the account can serve, so a
58
63
  deprecated/renamed model never slips through and 400s mid-session.
@@ -64,13 +69,18 @@ def fetch_sference_models(base_url: str, api_key: str) -> set[str]:
64
69
  )
65
70
  with urllib.request.urlopen(req, timeout=15) as resp:
66
71
  payload = json.loads(resp.read().decode("utf-8"))
67
- return {
68
- item["id"]
72
+ return [
73
+ item
69
74
  for item in payload.get("data", [])
70
75
  if isinstance(item, dict)
71
76
  and item.get("id")
72
77
  and item.get("modality", "text_generation") == "text_generation"
73
- }
78
+ ]
79
+
80
+
81
+ def fetch_sference_models(base_url: str, api_key: str) -> set[str]:
82
+ """Ids of the text-generation models the account can serve (GET /v1/models)."""
83
+ return {item["id"] for item in fetch_sference_model_entries(base_url, api_key)}
74
84
 
75
85
 
76
86
  def pick_free_port() -> int:
@@ -92,16 +102,20 @@ def mitmproxy_available() -> bool:
92
102
 
93
103
 
94
104
  def _extract_addon_files() -> tuple[Path, Path]:
95
- """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).
96
106
 
97
- Both files live in the same dir so the addon can ``from _proxy_routing import …``
98
- 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.
99
111
  """
100
112
  res = importlib.resources.files("sference_cli")
101
113
  addon_src = (res / "_proxy_addon.py").read_text(encoding="utf-8")
102
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")
103
116
  tmpdir = Path(tempfile.mkdtemp(prefix="sference_proxy_"))
104
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")
105
119
  addon_path = tmpdir / "_proxy_addon.py"
106
120
  addon_path.write_text(addon_src, encoding="utf-8")
107
121
  return tmpdir, addon_path
@@ -142,8 +156,16 @@ def launch_claude_via_proxy(
142
156
  dry_run: bool,
143
157
  proxy_port: Optional[int] = None,
144
158
  log_file: Optional[str] = None,
159
+ refresh_token: Optional[str] = None,
160
+ credentials_path: Optional[str] = None,
145
161
  ) -> None:
146
- """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
+ """
147
169
  if not mitmproxy_available():
148
170
  typer.echo(
149
171
  "mitmproxy not found. Install it with: uv tool install mitmproxy\n"
@@ -172,6 +194,8 @@ def launch_claude_via_proxy(
172
194
  typer.echo(f"Sference API: {sference_base}")
173
195
  typer.echo(f"Models ({len(models)}): {', '.join(sorted(models))}")
174
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)")
175
199
  typer.echo(f"HTTPS_PROXY=http://127.0.0.1:{port}")
176
200
  typer.echo(f"NODE_EXTRA_CA_CERTS={MITM_CA_CERT}")
177
201
  typer.echo("ANTHROPIC_BASE_URL=<unset> (first-party detection stays on)")
@@ -186,6 +210,10 @@ def launch_claude_via_proxy(
186
210
  "SFERENCE_BASE_URL": sference_base,
187
211
  "SFERENCE_PROXY_MODELS": json.dumps(sorted(models)),
188
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
189
217
  # Scope TLS interception to just the hosts we route. Without this, every
190
218
  # tool Claude Code spawns (Bash → curl, gh, …) also goes through the proxy
191
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