sference-cli 0.2.2__py3-none-any.whl → 0.3.0__py3-none-any.whl
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.
- sference_cli/_proxy_addon.py +114 -6
- sference_cli/device_auth.py +153 -0
- sference_cli/launch.py +139 -12
- sference_cli/main.py +264 -47
- sference_cli/proxy.py +37 -9
- {sference_cli-0.2.2.dist-info → sference_cli-0.3.0.dist-info}/METADATA +4 -4
- sference_cli-0.3.0.dist-info/RECORD +13 -0
- {sference_cli-0.2.2.dist-info → sference_cli-0.3.0.dist-info}/WHEEL +1 -1
- sference_cli-0.2.2.dist-info/RECORD +0 -12
- {sference_cli-0.2.2.dist-info → sference_cli-0.3.0.dist-info}/entry_points.txt +0 -0
- {sference_cli-0.2.2.dist-info → sference_cli-0.3.0.dist-info}/licenses/LICENSE +0 -0
sference_cli/_proxy_addon.py
CHANGED
|
@@ -2,17 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
Loaded by ``mitmdump -s <this file>``. Runs inside mitmproxy's isolated tool
|
|
4
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`` to the same temp dir), not via
|
|
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…``.
|
|
7
8
|
|
|
8
9
|
Config comes from env (set by the launcher):
|
|
9
|
-
SFERENCE_PROXY_MODELS
|
|
10
|
-
SFERENCE_API_KEY
|
|
11
|
-
SFERENCE_BASE_URL
|
|
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)
|
|
12
15
|
|
|
13
16
|
Routing is a pure URL + auth rewrite; the request body passes through
|
|
14
17
|
byte-for-byte (Sference has a native /v1/messages endpoint) and the response is
|
|
15
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.
|
|
16
25
|
"""
|
|
17
26
|
|
|
18
27
|
from __future__ import annotations
|
|
@@ -20,11 +29,13 @@ from __future__ import annotations
|
|
|
20
29
|
import json
|
|
21
30
|
import os
|
|
22
31
|
import sys
|
|
32
|
+
import time
|
|
23
33
|
from pathlib import Path
|
|
24
34
|
|
|
25
35
|
from mitmproxy import ctx, http
|
|
26
36
|
|
|
27
|
-
# Sibling
|
|
37
|
+
# Sibling imports: _proxy_routing.py and device_auth.py sit next to this file
|
|
38
|
+
# in the temp dir.
|
|
28
39
|
sys.path.insert(0, os.path.dirname(str(Path(__file__).resolve())))
|
|
29
40
|
from _proxy_routing import ( # noqa: E402
|
|
30
41
|
BOOTSTRAP,
|
|
@@ -36,10 +47,13 @@ from _proxy_routing import ( # noqa: E402
|
|
|
36
47
|
rewrite_request_for_sference,
|
|
37
48
|
strip_unsigned_thinking_blocks,
|
|
38
49
|
)
|
|
50
|
+
from device_auth import CLIENT_ID_SFERENCE_CLI, DeviceAuthError, refresh_tokens # noqa: E402
|
|
39
51
|
|
|
40
52
|
SFERENCE_BASE_URL = os.environ.get("SFERENCE_BASE_URL", "https://api.sference.com").rstrip("/")
|
|
41
53
|
SFERENCE_API_KEY = os.environ.get("SFERENCE_API_KEY", "")
|
|
42
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", "")
|
|
43
57
|
|
|
44
58
|
# flow.id -> original model (for response handling — currently a no-op since
|
|
45
59
|
# the Sference response is already native Anthropic, but kept for clarity).
|
|
@@ -48,6 +62,76 @@ _sference_flows: dict[str, str] = {}
|
|
|
48
62
|
_bootstrap_flows: set[str] = set()
|
|
49
63
|
|
|
50
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
|
+
|
|
51
135
|
class SferenceRouter:
|
|
52
136
|
def request(self, flow: "http.HTTPFlow") -> None:
|
|
53
137
|
if flow.request is None:
|
|
@@ -111,9 +195,33 @@ class SferenceRouter:
|
|
|
111
195
|
return
|
|
112
196
|
if flow.id in _sference_flows:
|
|
113
197
|
_sference_flows.pop(flow.id)
|
|
198
|
+
if flow.response.status_code == 401:
|
|
199
|
+
self._maybe_refresh_and_replay(flow)
|
|
114
200
|
# Native Anthropic response: pass through untouched.
|
|
115
201
|
return
|
|
116
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
|
+
|
|
117
225
|
def _inject_models(self, flow: "http.HTTPFlow") -> None:
|
|
118
226
|
if flow.response.status_code != 200:
|
|
119
227
|
return
|
|
@@ -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
|
sference_cli/launch.py
CHANGED
|
@@ -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
|
|
144
|
-
"""
|
|
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-
|
|
241
|
+
"api": "openai-responses",
|
|
150
242
|
"baseUrl": base_url,
|
|
151
243
|
"apiKey": api_key,
|
|
152
|
-
"models":
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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``
|
|
487
|
-
|
|
488
|
-
``
|
|
489
|
-
|
|
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
|
|
sference_cli/main.py
CHANGED
|
@@ -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 .
|
|
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
|
-
|
|
50
|
-
#
|
|
51
|
-
#
|
|
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(
|
|
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
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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).
|
|
141
|
-
"
|
|
142
|
-
"
|
|
143
|
-
"
|
|
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="
|
|
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
|
|
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:
|
|
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
|
-
|
|
386
|
-
|
|
387
|
-
|
|
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 {
|
|
601
|
+
typer.echo(f"Opening {approve_url} in your browser...")
|
|
391
602
|
try:
|
|
392
|
-
webbrowser.open(
|
|
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
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
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(
|
|
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)
|
sference_cli/proxy.py
CHANGED
|
@@ -51,8 +51,13 @@ def _normalize_base_url(raw: str) -> str:
|
|
|
51
51
|
return raw
|
|
52
52
|
|
|
53
53
|
|
|
54
|
-
def
|
|
55
|
-
"""Pull the live text-generation model
|
|
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
|
|
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 +
|
|
105
|
+
"""Extract the addon + its sibling imports to a temp dir; return (tmpdir, addon_path).
|
|
96
106
|
|
|
97
|
-
|
|
98
|
-
via a sibling path (mitmproxy's
|
|
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,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: sference-cli
|
|
3
|
-
Version: 0.
|
|
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.
|
|
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
|
|
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
|
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
sference_cli/__init__.py,sha256=HT7s9qkZsDqCScvYKsNTr7i8fo9NUtxgcuFUdVVp0mo,427
|
|
2
|
+
sference_cli/_proxy_addon.py,sha256=KUR5K9QCAVXXv01TjyNYZ6vS4QuL0OK-elNh6Q-DNjY,10650
|
|
3
|
+
sference_cli/_proxy_routing.py,sha256=9buDBfCBsnplxraIONFSEHyAJJuMcli8OXyImaErhgE,9922
|
|
4
|
+
sference_cli/device_auth.py,sha256=RYPOQWOF24kuHw-ZC0pvOZ_9yJ7P3I6EC9lHlvmJHss,6092
|
|
5
|
+
sference_cli/launch.py,sha256=plM2U2WWYRxox9pXq-25_QIEsldoGgZIH3GhUkTrQkE,26510
|
|
6
|
+
sference_cli/main.py,sha256=9iSK1zYNx_omkU2yBTaM5bU4bQRdmXDWJ2rbQHmI4E8,41394
|
|
7
|
+
sference_cli/proxy.py,sha256=SCMY_DcWyzcC4sQ7ck7gtEUMK8yjE_Mu6dy6AOmjNOc,11306
|
|
8
|
+
sference_cli/stream_cache.py,sha256=dYzsHp2iWF2bj8JevVdThVaaCKjkztcUposNpRaZKzU,1943
|
|
9
|
+
sference_cli-0.3.0.dist-info/METADATA,sha256=OxPPP3ockrtZ53zCc42v5w_O0yGYbagBe2MfyizAwOs,14566
|
|
10
|
+
sference_cli-0.3.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
11
|
+
sference_cli-0.3.0.dist-info/entry_points.txt,sha256=JkFhzUu37Q6aUJ0P-FccUfzpi0rxrzH1vtvbLQyVTH0,52
|
|
12
|
+
sference_cli-0.3.0.dist-info/licenses/LICENSE,sha256=uvXIHt0k9gF7K4mnd0k9hPn1Eufh_Jy902l2y2WeU5s,11395
|
|
13
|
+
sference_cli-0.3.0.dist-info/RECORD,,
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
sference_cli/__init__.py,sha256=HT7s9qkZsDqCScvYKsNTr7i8fo9NUtxgcuFUdVVp0mo,427
|
|
2
|
-
sference_cli/_proxy_addon.py,sha256=Fg36mJQfjOILTa9nXNvY-2QFwHGeoAdjuSut9y9lyOc,5551
|
|
3
|
-
sference_cli/_proxy_routing.py,sha256=9buDBfCBsnplxraIONFSEHyAJJuMcli8OXyImaErhgE,9922
|
|
4
|
-
sference_cli/launch.py,sha256=-uFn_PrGqZmE-29jN92-Qyf0IiHCQU2mTjxdxUxRQbM,19604
|
|
5
|
-
sference_cli/main.py,sha256=pDOcJSf9Afk-2crYtyvfJ8rW4bSrJ_D4hK5tjApKifw,32785
|
|
6
|
-
sference_cli/proxy.py,sha256=f_4S-OemgPPxK6bScUFQ2M4mUr93dTSXHb7afQqKwTw,9826
|
|
7
|
-
sference_cli/stream_cache.py,sha256=dYzsHp2iWF2bj8JevVdThVaaCKjkztcUposNpRaZKzU,1943
|
|
8
|
-
sference_cli-0.2.2.dist-info/METADATA,sha256=FnVxZafSR_JeZEob6Ox9Xj2KaTmJZifFfBKbVddXsFI,13912
|
|
9
|
-
sference_cli-0.2.2.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
10
|
-
sference_cli-0.2.2.dist-info/entry_points.txt,sha256=JkFhzUu37Q6aUJ0P-FccUfzpi0rxrzH1vtvbLQyVTH0,52
|
|
11
|
-
sference_cli-0.2.2.dist-info/licenses/LICENSE,sha256=uvXIHt0k9gF7K4mnd0k9hPn1Eufh_Jy902l2y2WeU5s,11395
|
|
12
|
-
sference_cli-0.2.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|