sference-cli 0.3.2__py3-none-any.whl → 0.4.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/_discovery.py +97 -0
- sference_cli/device_auth.py +3 -4
- sference_cli/launch.py +120 -60
- {sference_cli-0.3.2.dist-info → sference_cli-0.4.0.dist-info}/METADATA +18 -21
- sference_cli-0.4.0.dist-info/RECORD +11 -0
- sference_cli/_proxy_addon.py +0 -242
- sference_cli/_proxy_routing.py +0 -234
- sference_cli/proxy.py +0 -291
- sference_cli-0.3.2.dist-info/RECORD +0 -13
- {sference_cli-0.3.2.dist-info → sference_cli-0.4.0.dist-info}/WHEEL +0 -0
- {sference_cli-0.3.2.dist-info → sference_cli-0.4.0.dist-info}/entry_points.txt +0 -0
- {sference_cli-0.3.2.dist-info → sference_cli-0.4.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Claude Code gateway model discovery support for ``sference launch claude``.
|
|
2
|
+
|
|
3
|
+
Claude Code populates ``/model`` from built-ins plus gateway discovery results
|
|
4
|
+
(``GET {ANTHROPIC_BASE_URL}/v1/models``), cached to
|
|
5
|
+
``~/.claude/cache/gateway-models.json``. Two client-side gates matter here:
|
|
6
|
+
|
|
7
|
+
* discovery only runs when ``CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1``
|
|
8
|
+
and the base URL is not api.anthropic.com;
|
|
9
|
+
* the live fetch keeps only ids containing "claude" or "anthropic" — Sference
|
|
10
|
+
catalog ids (``deepseek-ai/...``) match neither, so the fetch returns "0
|
|
11
|
+
usable models" and leaves the cache untouched. The picker then falls back to
|
|
12
|
+
whatever the cache already holds (verified on v2.1.302: the prime read is
|
|
13
|
+
gated only on the flag + base URL, not on credentials).
|
|
14
|
+
|
|
15
|
+
So the launcher primes the cache with the live catalog before exec'ing claude.
|
|
16
|
+
Stdlib-only so this module imports anywhere.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import tempfile
|
|
24
|
+
import time
|
|
25
|
+
import urllib.request
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
DISCOVERY_ENV_KEY = "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"
|
|
30
|
+
|
|
31
|
+
# Unknown (non-claude) model ids are believed to hold 200k tokens and
|
|
32
|
+
# auto-compact against that; Sference catalog models serve 1M. Disabling the
|
|
33
|
+
# unknown-model window enforcement lets CLAUDE_CODE_AUTO_COMPACT_WINDOW apply.
|
|
34
|
+
WINDOW_ENFORCEMENT_ENV_KEY = "CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT"
|
|
35
|
+
AUTO_COMPACT_WINDOW_ENV_KEY = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
|
|
36
|
+
DEFAULT_AUTO_COMPACT_WINDOW = "950000"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def fetch_sference_model_entries(base_url: str, api_key: str) -> list[dict[str, Any]]:
|
|
40
|
+
"""Pull the live text-generation model entries from GET {base_url}/v1/models."""
|
|
41
|
+
api_root = base_url.rstrip("/") + "/v1"
|
|
42
|
+
req = urllib.request.Request(
|
|
43
|
+
f"{api_root}/models",
|
|
44
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
45
|
+
)
|
|
46
|
+
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
47
|
+
payload = json.loads(resp.read().decode("utf-8"))
|
|
48
|
+
return [
|
|
49
|
+
item
|
|
50
|
+
for item in payload.get("data", [])
|
|
51
|
+
if isinstance(item, dict) and item.get("id") and item.get("modality", "text_generation") == "text_generation"
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def picker_cache_path() -> Path:
|
|
56
|
+
"""The discovery cache Claude Code primes its picker from (CLAUDE_CONFIG_DIR-aware)."""
|
|
57
|
+
config_dir = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
|
|
58
|
+
if config_dir:
|
|
59
|
+
return Path(config_dir) / "cache" / "gateway-models.json"
|
|
60
|
+
return Path.home() / ".claude" / "cache" / "gateway-models.json"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _picker_entry(item: dict[str, Any]) -> dict[str, str]:
|
|
64
|
+
entry = {"id": str(item["id"])}
|
|
65
|
+
name = str(item.get("display_name") or item["id"])
|
|
66
|
+
entry["display_name"] = name if "sference" in name.lower() else f"{name} via Sference"
|
|
67
|
+
ctx = item.get("context_tokens")
|
|
68
|
+
if isinstance(ctx, int) and ctx > 0:
|
|
69
|
+
entry["description"] = f"Sference inference — {ctx // 1000}k context"
|
|
70
|
+
else:
|
|
71
|
+
entry["description"] = "Sference inference"
|
|
72
|
+
return entry
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def prime_picker_cache(entries: list[dict[str, Any]], base_url: str) -> Path:
|
|
76
|
+
"""Write the picker cache atomically (temp+rename, 0600): a Claude Code
|
|
77
|
+
starting mid-prime must never read a torn file."""
|
|
78
|
+
models = [_picker_entry(item) for item in entries]
|
|
79
|
+
body = {
|
|
80
|
+
"baseUrl": base_url.rstrip("/"),
|
|
81
|
+
"fetchedAt": int(time.time() * 1000),
|
|
82
|
+
"models": models,
|
|
83
|
+
}
|
|
84
|
+
path = picker_cache_path()
|
|
85
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
86
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".gateway-models-", suffix=".tmp")
|
|
87
|
+
try:
|
|
88
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f: # mkstemp is already 0600
|
|
89
|
+
f.write(json.dumps(body) + "\n")
|
|
90
|
+
os.replace(tmp, path)
|
|
91
|
+
except BaseException:
|
|
92
|
+
try:
|
|
93
|
+
os.unlink(tmp)
|
|
94
|
+
except OSError:
|
|
95
|
+
pass
|
|
96
|
+
raise
|
|
97
|
+
return path
|
sference_cli/device_auth.py
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
"""Device-flow (RFC 8628) client for ``sference auth login`` and token refresh.
|
|
2
2
|
|
|
3
|
-
Stdlib-only (json, urllib, time) so this module imports in ANY venv —
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
expired device token mid-session. Keep it dependency-free.
|
|
3
|
+
Stdlib-only (json, urllib, time) so this module imports in ANY venv —
|
|
4
|
+
``sference launch claude`` refreshes the 24 h device token at launch so long
|
|
5
|
+
sessions start on a fresh grant. Keep it dependency-free.
|
|
7
6
|
|
|
8
7
|
Wire shapes come from the platform's device-flow endpoints (plan §4.3):
|
|
9
8
|
POST /v1/oauth/device_code -> {device_code, user_code, verification_uri, expires_in, interval}
|
sference_cli/launch.py
CHANGED
|
@@ -9,15 +9,27 @@ import re
|
|
|
9
9
|
import shutil
|
|
10
10
|
import subprocess
|
|
11
11
|
import sys
|
|
12
|
+
import time
|
|
12
13
|
import urllib.error
|
|
13
14
|
from pathlib import Path
|
|
14
15
|
from typing import Optional
|
|
15
16
|
|
|
16
17
|
import typer
|
|
17
18
|
|
|
18
|
-
from .
|
|
19
|
+
from ._discovery import (
|
|
20
|
+
AUTO_COMPACT_WINDOW_ENV_KEY,
|
|
21
|
+
DEFAULT_AUTO_COMPACT_WINDOW,
|
|
22
|
+
DISCOVERY_ENV_KEY,
|
|
23
|
+
WINDOW_ENFORCEMENT_ENV_KEY,
|
|
24
|
+
fetch_sference_model_entries,
|
|
25
|
+
prime_picker_cache,
|
|
26
|
+
)
|
|
19
27
|
|
|
20
28
|
DEFAULT_LAUNCH_MODEL = "zai-org/GLM-5.2"
|
|
29
|
+
# Claude Code's default request shape is thinking-disabled, which GLM-5.3-served
|
|
30
|
+
# models 400 on (verified vs the API). Kimi-K3 tolerates it and is the stronger
|
|
31
|
+
# coding model — claude-only default; the other launchers keep GLM-5.2.
|
|
32
|
+
CLAUDE_DEFAULT_LAUNCH_MODEL = "moonshotai/Kimi-K3"
|
|
21
33
|
DEFAULT_API_BASE_URL = "https://api.sference.com"
|
|
22
34
|
|
|
23
35
|
# Thinking-effort variants stamped on Sference model entries in the opencode config.
|
|
@@ -42,14 +54,14 @@ def resolve_api_base_url(explicit: Optional[str]) -> str:
|
|
|
42
54
|
return DEFAULT_API_BASE_URL
|
|
43
55
|
|
|
44
56
|
|
|
45
|
-
def resolve_launch_model(explicit: Optional[str]) -> str:
|
|
57
|
+
def resolve_launch_model(explicit: Optional[str], *, default: str = DEFAULT_LAUNCH_MODEL) -> str:
|
|
46
58
|
"""Default catalog model for ``launch`` subcommands (--model overrides)."""
|
|
47
59
|
if explicit:
|
|
48
60
|
return explicit
|
|
49
61
|
env = os.environ.get("SFERENCE_MODEL")
|
|
50
62
|
if env and env.strip():
|
|
51
63
|
return env.strip()
|
|
52
|
-
return
|
|
64
|
+
return default
|
|
53
65
|
|
|
54
66
|
|
|
55
67
|
def resolve_openai_base_url(explicit: Optional[str]) -> str:
|
|
@@ -93,6 +105,14 @@ def build_claude_env(
|
|
|
93
105
|
env["ANTHROPIC_SMALL_FAST_MODEL"] = model
|
|
94
106
|
# Claude Code prefers AUTH_TOKEN; drop API_KEY to avoid precedence confusion.
|
|
95
107
|
env.pop("ANTHROPIC_API_KEY", None)
|
|
108
|
+
# Gateway model discovery: the picker reads the primed cache (written
|
|
109
|
+
# before exec) without any further credential.
|
|
110
|
+
env[DISCOVERY_ENV_KEY] = "1"
|
|
111
|
+
# Sference catalog ids are "unknown" to Claude Code, which would clamp
|
|
112
|
+
# them to a 200k window; let the auto-compact window below apply instead
|
|
113
|
+
# (catalog models serve 1M).
|
|
114
|
+
env[WINDOW_ENFORCEMENT_ENV_KEY] = "1"
|
|
115
|
+
env.setdefault(AUTO_COMPACT_WINDOW_ENV_KEY, DEFAULT_AUTO_COMPACT_WINDOW)
|
|
96
116
|
if enable_tool_search:
|
|
97
117
|
env["ENABLE_TOOL_SEARCH"] = "true"
|
|
98
118
|
else:
|
|
@@ -100,11 +120,41 @@ def build_claude_env(
|
|
|
100
120
|
return env
|
|
101
121
|
|
|
102
122
|
|
|
123
|
+
def build_claude_settings_json(env: dict[str, str]) -> str:
|
|
124
|
+
"""The launcher's env block as a ``--settings`` JSON string.
|
|
125
|
+
|
|
126
|
+
Why not just the process env: a settings.json ``env`` entry (e.g. written
|
|
127
|
+
by sference-switch's ``claude on``) beats the process environment per key,
|
|
128
|
+
so a switch-managed machine would silently re-route the session through
|
|
129
|
+
the switch. ``--settings`` loads AFTER user settings and wins per key.
|
|
130
|
+
|
|
131
|
+
ANTHROPIC_AUTH_TOKEN is deliberately EXCLUDED: argv is visible to every
|
|
132
|
+
process on the machine (``ps``), and nothing in a settings.json env block
|
|
133
|
+
competes for that key — the process env carries it safely alone.
|
|
134
|
+
"""
|
|
135
|
+
keys = (
|
|
136
|
+
"ANTHROPIC_BASE_URL",
|
|
137
|
+
"ANTHROPIC_MODEL",
|
|
138
|
+
"ANTHROPIC_DEFAULT_OPUS_MODEL",
|
|
139
|
+
"ANTHROPIC_DEFAULT_SONNET_MODEL",
|
|
140
|
+
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
|
|
141
|
+
"ANTHROPIC_DEFAULT_FABLE_MODEL",
|
|
142
|
+
"CLAUDE_CODE_SUBAGENT_MODEL",
|
|
143
|
+
"ANTHROPIC_SMALL_FAST_MODEL",
|
|
144
|
+
DISCOVERY_ENV_KEY,
|
|
145
|
+
WINDOW_ENFORCEMENT_ENV_KEY,
|
|
146
|
+
AUTO_COMPACT_WINDOW_ENV_KEY,
|
|
147
|
+
"ENABLE_TOOL_SEARCH",
|
|
148
|
+
)
|
|
149
|
+
return json.dumps({"env": {k: env[k] for k in keys if k in env}})
|
|
150
|
+
|
|
151
|
+
|
|
103
152
|
def launch_claude_code(
|
|
104
153
|
*,
|
|
105
154
|
api_key: str,
|
|
106
155
|
base_url: str,
|
|
107
156
|
model: str,
|
|
157
|
+
model_entries: list[dict],
|
|
108
158
|
enable_tool_search: bool,
|
|
109
159
|
claude_args: list[str],
|
|
110
160
|
dry_run: bool,
|
|
@@ -125,7 +175,8 @@ def launch_claude_code(
|
|
|
125
175
|
model=model,
|
|
126
176
|
enable_tool_search=enable_tool_search,
|
|
127
177
|
)
|
|
128
|
-
|
|
178
|
+
settings_json = build_claude_settings_json(env)
|
|
179
|
+
cmd = [claude_bin, "--settings", settings_json, *claude_args]
|
|
129
180
|
|
|
130
181
|
if dry_run:
|
|
131
182
|
typer.echo(f"ANTHROPIC_BASE_URL={env['ANTHROPIC_BASE_URL']}")
|
|
@@ -139,11 +190,24 @@ def launch_claude_code(
|
|
|
139
190
|
):
|
|
140
191
|
typer.echo(f"{alias_var}={env[alias_var]}")
|
|
141
192
|
typer.echo("ANTHROPIC_AUTH_TOKEN=<redacted>")
|
|
193
|
+
typer.echo(f"{DISCOVERY_ENV_KEY}=1")
|
|
194
|
+
typer.echo(f"{WINDOW_ENFORCEMENT_ENV_KEY}=1")
|
|
195
|
+
typer.echo(f"{AUTO_COMPACT_WINDOW_ENV_KEY}={env[AUTO_COMPACT_WINDOW_ENV_KEY]}")
|
|
196
|
+
typer.echo(f"picker cache: {len(model_entries)} model(s) to prime")
|
|
142
197
|
if enable_tool_search:
|
|
143
198
|
typer.echo("ENABLE_TOOL_SEARCH=true")
|
|
144
|
-
typer.echo(f"
|
|
199
|
+
typer.echo(f"--settings {settings_json}")
|
|
200
|
+
typer.echo(f"command: {claude_bin} --settings <json> {' '.join(claude_args)}")
|
|
145
201
|
return
|
|
146
202
|
|
|
203
|
+
# Prime the picker's discovery cache before exec. Warn-only: a failed
|
|
204
|
+
# prime costs the /model entries, not the session.
|
|
205
|
+
try:
|
|
206
|
+
cache_path = prime_picker_cache(model_entries, base_url)
|
|
207
|
+
typer.echo(f"sference: /model picker cache primed ({len(model_entries)} model(s) -> {cache_path})", err=True)
|
|
208
|
+
except (OSError, ValueError, TypeError) as e:
|
|
209
|
+
typer.echo(f"sference: warning: could not prime the /model picker cache: {e}", err=True)
|
|
210
|
+
|
|
147
211
|
if sys.platform == "win32":
|
|
148
212
|
raise SystemExit(subprocess.call(cmd, env=env))
|
|
149
213
|
|
|
@@ -759,7 +823,7 @@ def register_launch_commands(app: typer.Typer) -> None:
|
|
|
759
823
|
@launch_app.command(
|
|
760
824
|
"claude",
|
|
761
825
|
context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
|
|
762
|
-
help="Launch Claude Code
|
|
826
|
+
help="Launch Claude Code against the Sference endpoint (gateway model discovery; no proxy).",
|
|
763
827
|
)
|
|
764
828
|
def claude(
|
|
765
829
|
ctx: typer.Context,
|
|
@@ -767,8 +831,7 @@ def register_launch_commands(app: typer.Typer) -> None:
|
|
|
767
831
|
None,
|
|
768
832
|
"--model",
|
|
769
833
|
"-m",
|
|
770
|
-
help="
|
|
771
|
-
f"{DEFAULT_LAUNCH_MODEL} or SFERENCE_MODEL).",
|
|
834
|
+
help=f"Pinned catalog model (default: {CLAUDE_DEFAULT_LAUNCH_MODEL} or SFERENCE_MODEL).",
|
|
772
835
|
),
|
|
773
836
|
base_url: Optional[str] = typer.Option(
|
|
774
837
|
None,
|
|
@@ -779,108 +842,105 @@ def register_launch_commands(app: typer.Typer) -> None:
|
|
|
779
842
|
no_anthropic: bool = typer.Option(
|
|
780
843
|
False,
|
|
781
844
|
"--no-anthropic",
|
|
782
|
-
help="
|
|
783
|
-
"(today's ANTHROPIC_BASE_URL env-var behavior; no hybrid routing, no /model picker).",
|
|
845
|
+
help="Deprecated no-op: the direct env-var mode is now the only mode.",
|
|
784
846
|
),
|
|
785
847
|
models: Optional[str] = typer.Option(
|
|
786
848
|
None,
|
|
787
849
|
"--models",
|
|
788
|
-
help="
|
|
789
|
-
"(default: live GET /v1/models). Ignored with --no-anthropic.",
|
|
850
|
+
help="Comma-separated catalog ids for the /model picker (default: live GET /v1/models).",
|
|
790
851
|
),
|
|
791
852
|
proxy_port: Optional[int] = typer.Option(
|
|
792
853
|
None,
|
|
793
854
|
"--proxy-port",
|
|
794
|
-
help="
|
|
855
|
+
help="Deprecated no-op: there is no proxy anymore.",
|
|
795
856
|
),
|
|
796
857
|
enable_tool_search: bool = typer.Option(
|
|
797
858
|
False,
|
|
798
859
|
"--enable-tool-search",
|
|
799
|
-
help="Set ENABLE_TOOL_SEARCH=true
|
|
800
|
-
"keeps first-party detection on, so tool search already works).",
|
|
860
|
+
help="Set ENABLE_TOOL_SEARCH=true.",
|
|
801
861
|
),
|
|
802
862
|
dry_run: bool = typer.Option(
|
|
803
863
|
False,
|
|
804
864
|
"--dry-run",
|
|
805
|
-
help="Print the
|
|
865
|
+
help="Print the env config and command without launching anything.",
|
|
806
866
|
),
|
|
807
867
|
) -> None:
|
|
808
868
|
"""Run ``claude`` with Sference credentials.
|
|
809
869
|
|
|
810
|
-
|
|
811
|
-
``
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
Sference model). Unknown options and trailing args are forwarded to
|
|
870
|
+
Points Claude Code at the Sference endpoint (native ``/v1/messages``)
|
|
871
|
+
via ``ANTHROPIC_BASE_URL`` and enables gateway model discovery: the
|
|
872
|
+
live catalog is primed into the picker cache before launch, so
|
|
873
|
+
``/model`` lists every Sference model the account can serve. No proxy,
|
|
874
|
+
no mitmproxy. Unknown options and trailing args are forwarded to
|
|
816
875
|
Claude Code, e.g. ``sference launch claude -p "fix the bug"``.
|
|
817
876
|
"""
|
|
818
877
|
from sference_cli.main import (
|
|
819
|
-
CREDENTIALS_PATH,
|
|
820
878
|
_ensure_api_credential,
|
|
821
879
|
_read_device_credentials,
|
|
822
880
|
_read_token,
|
|
881
|
+
_write_device_credentials,
|
|
823
882
|
)
|
|
824
883
|
|
|
825
884
|
_ensure_api_credential()
|
|
885
|
+
resolved_base = resolve_api_base_url(base_url)
|
|
886
|
+
# Device-flow (v2) credentials: refresh the 24 h access token at launch
|
|
887
|
+
# so long sessions start on a fresh grant. Skipped when SFERENCE_API_KEY
|
|
888
|
+
# overrides the file — the env token is not the file's grant, and
|
|
889
|
+
# refreshing would swap identities mid-session.
|
|
890
|
+
device_creds = None if os.environ.get("SFERENCE_API_KEY") else _read_device_credentials()
|
|
891
|
+
if device_creds and device_creds.get("refresh_token"):
|
|
892
|
+
try:
|
|
893
|
+
from sference_cli.device_auth import CLIENT_ID_SFERENCE_CLI, refresh_tokens
|
|
894
|
+
|
|
895
|
+
tokens = refresh_tokens(
|
|
896
|
+
resolved_base, CLIENT_ID_SFERENCE_CLI, device_creds["refresh_token"]
|
|
897
|
+
)
|
|
898
|
+
_write_device_credentials(tokens)
|
|
899
|
+
except Exception: # noqa: BLE001 (best-effort; the current token may still be valid)
|
|
900
|
+
# The launch proceeds on the file's token. When that token is
|
|
901
|
+
# already expired, a failed refresh means the session WILL 401 —
|
|
902
|
+
# say so now rather than mid-task.
|
|
903
|
+
if float(device_creds.get("expires_at") or 0) <= time.time():
|
|
904
|
+
typer.echo(
|
|
905
|
+
"warning: could not refresh the expired device token; re-run `sference auth login`",
|
|
906
|
+
err=True,
|
|
907
|
+
)
|
|
908
|
+
|
|
826
909
|
api_key = _read_token()
|
|
827
910
|
if api_key is None:
|
|
828
911
|
raise typer.Exit(code=1)
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
912
|
+
|
|
913
|
+
if no_anthropic:
|
|
914
|
+
typer.echo("note: --no-anthropic is deprecated; the direct env-var mode is now the only mode.", err=True)
|
|
915
|
+
if proxy_port is not None:
|
|
916
|
+
typer.echo("note: --proxy-port is deprecated; there is no proxy anymore.", err=True)
|
|
834
917
|
|
|
835
918
|
forwarded = list(ctx.args)
|
|
836
919
|
if forwarded and forwarded[0] == "--":
|
|
837
920
|
forwarded = forwarded[1:]
|
|
838
921
|
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
if no_anthropic:
|
|
842
|
-
launch_claude_code(
|
|
843
|
-
api_key=api_key,
|
|
844
|
-
base_url=resolved_base,
|
|
845
|
-
model=resolve_launch_model(model),
|
|
846
|
-
enable_tool_search=enable_tool_search,
|
|
847
|
-
claude_args=forwarded,
|
|
848
|
-
dry_run=dry_run,
|
|
849
|
-
)
|
|
850
|
-
return
|
|
851
|
-
|
|
852
|
-
if enable_tool_search:
|
|
853
|
-
typer.echo(
|
|
854
|
-
"note: --enable-tool-search is a no-op in proxy mode (first-party "
|
|
855
|
-
"detection is on, so tool search already works).",
|
|
856
|
-
err=True,
|
|
857
|
-
)
|
|
858
|
-
|
|
859
|
-
# Proxy mode: resolve the routable model set.
|
|
922
|
+
# Resolve the picker model set.
|
|
860
923
|
if models:
|
|
861
|
-
|
|
862
|
-
elif model:
|
|
863
|
-
model_set = {model}
|
|
924
|
+
model_entries = [{"id": m.strip()} for m in models.split(",") if m.strip()]
|
|
864
925
|
else:
|
|
865
926
|
try:
|
|
866
|
-
|
|
927
|
+
model_entries = fetch_sference_model_entries(resolved_base, api_key)
|
|
867
928
|
except (urllib.error.URLError, urllib.error.HTTPError, json.JSONDecodeError, KeyError) as e:
|
|
868
929
|
typer.echo(f"ERROR: could not fetch models from {resolved_base}/v1/models: {e}", err=True)
|
|
869
|
-
typer.echo("Pass --models
|
|
930
|
+
typer.echo("Pass --models explicitly to bypass the lookup.", err=True)
|
|
870
931
|
raise typer.Exit(code=1) from None
|
|
871
|
-
if not
|
|
932
|
+
if not model_entries:
|
|
872
933
|
typer.echo("ERROR: /v1/models returned no text-generation models for this account.", err=True)
|
|
873
934
|
raise typer.Exit(code=1)
|
|
874
935
|
|
|
875
|
-
|
|
936
|
+
launch_claude_code(
|
|
876
937
|
api_key=api_key,
|
|
877
938
|
base_url=resolved_base,
|
|
878
|
-
|
|
939
|
+
model=resolve_launch_model(model, default=CLAUDE_DEFAULT_LAUNCH_MODEL),
|
|
940
|
+
model_entries=model_entries,
|
|
941
|
+
enable_tool_search=enable_tool_search,
|
|
879
942
|
claude_args=forwarded,
|
|
880
943
|
dry_run=dry_run,
|
|
881
|
-
proxy_port=proxy_port,
|
|
882
|
-
refresh_token=device_creds["refresh_token"] if device_creds else None,
|
|
883
|
-
credentials_path=str(CREDENTIALS_PATH) if device_creds else None,
|
|
884
944
|
)
|
|
885
945
|
|
|
886
946
|
@launch_app.command(
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: sference-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.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
|
|
@@ -65,11 +65,13 @@ sference --help
|
|
|
65
65
|
|
|
66
66
|
## Authentication
|
|
67
67
|
|
|
68
|
-
1. **Interactive (browser):** `sference auth login`
|
|
69
|
-
2. **Non-interactive / CI:** `sference auth login --api-key 'sk_...'`
|
|
68
|
+
1. **Interactive (browser):** `sference auth login` signs in with the OAuth 2.0 device flow (RFC 8628). The CLI opens the console approval page and shows a short code; confirm it matches, approve the device, and the CLI finishes on its own. No API key is involved. Pass `--no-browser` on a remote or headless machine to print the URL and code instead.
|
|
69
|
+
2. **Non-interactive / CI:** `sference auth login --api-key 'sk_...'` saves an API key from **Console → API keys** without opening a browser.
|
|
70
70
|
3. **Environment variable:** `SFERENCE_API_KEY` overrides the saved credential file.
|
|
71
71
|
|
|
72
|
-
Credentials are stored in `~/.sference/credentials.json` unless `SFERENCE_API_KEY` is set.
|
|
72
|
+
Credentials are stored in `~/.sference/credentials.json` unless `SFERENCE_API_KEY` is set. A device login stores a 24 h access token and a 30 d rotating refresh token; the CLI refreshes the access token automatically when you run a command, and `sference launch claude` also refreshes it mid-session through its proxy. Codex, opencode, and Pi sessions run on the token issued at launch. Signed-in devices are listed, and can be revoked, under **Profile → Signed-in devices** in the console.
|
|
73
|
+
|
|
74
|
+
For local development, `--base-url` (or `SFERENCE_BASE_URL`) points the device flow at another API and `--console-url` (or `SFERENCE_CONSOLE_URL`) overrides the approval page the browser opens.
|
|
73
75
|
|
|
74
76
|
Verify the current credential:
|
|
75
77
|
|
|
@@ -108,7 +110,8 @@ sference responses tail --stream-id <stream_id>
|
|
|
108
110
|
|
|
109
111
|
| Variable | Purpose |
|
|
110
112
|
|----------|---------|
|
|
111
|
-
| `SFERENCE_API_KEY` | API key (or
|
|
113
|
+
| `SFERENCE_API_KEY` | API key (or access token); overrides `~/.sference/credentials.json` |
|
|
114
|
+
| `SFERENCE_CONSOLE_URL` | Console URL the device-flow approval page opens on (default: server-provided) |
|
|
112
115
|
| `SFERENCE_MODEL` | Default catalog model for `sference launch` (overrides built-in default) |
|
|
113
116
|
| `SFERENCE_STREAM_CACHE` | Optional path to the stream resumable-cache file (default `~/.sference/stream_cache.json`) |
|
|
114
117
|
| `SFERENCE_STREAM_CHECKPOINTS` | Optional path for **`responses tail`** event checkpoints (default `~/.sference/stream_checkpoints.json`) |
|
|
@@ -119,31 +122,25 @@ sference responses tail --stream-id <stream_id>
|
|
|
119
122
|
|
|
120
123
|
| Command | Description |
|
|
121
124
|
|---------|-------------|
|
|
122
|
-
| `sference auth login` |
|
|
125
|
+
| `sference auth login` | Sign in with the browser device flow (`--no-browser` prints the URL and code; `--api-key` saves an API key for CI) |
|
|
123
126
|
| `sference auth me` | Show current user (`--json` for machine-readable output) |
|
|
124
127
|
|
|
125
128
|
### Launch
|
|
126
129
|
|
|
127
|
-
#### `sference launch claude`
|
|
130
|
+
#### `sference launch claude`
|
|
128
131
|
|
|
129
|
-
|
|
132
|
+
`sference launch claude` points Claude Code at Sference's native `/v1/messages` endpoint via `ANTHROPIC_BASE_URL` and enables gateway model discovery: the live catalog is primed into Claude Code's picker cache before launch, so `/model` lists every Sference model the account can serve. No proxy, no mitmproxy.
|
|
130
133
|
|
|
131
134
|
| Command | Description |
|
|
132
|
-
|
|
133
|
-
| `sference launch claude` |
|
|
134
|
-
| `sference launch claude --dry-run` | Print the
|
|
135
|
-
| `sference launch claude --model zai-org/GLM-5.2` |
|
|
136
|
-
| `sference launch claude --models a,b` |
|
|
137
|
-
| `sference launch claude --
|
|
135
|
+
| --- | --- |
|
|
136
|
+
| `sference launch claude` | Launch Claude Code against Sference; catalog primed into `/model` |
|
|
137
|
+
| `sference launch claude --dry-run` | Print the env config + command without launching |
|
|
138
|
+
| `sference launch claude --model zai-org/GLM-5.2` | Pin a different default model |
|
|
139
|
+
| `sference launch claude --models a,b` | Override the primed picker set (default: live `GET /v1/models`) |
|
|
140
|
+
| `sference launch claude --enable-tool-search` | Set `ENABLE_TOOL_SEARCH=true` |
|
|
138
141
|
| `sference launch claude -- --model zai-org/GLM-5.2 -p "hi"` | Forward Claude Code flags/args after `--` |
|
|
139
|
-
| `sference launch claude --no-anthropic` | Disable the proxy; route everything directly to Sference via `ANTHROPIC_BASE_URL` (the previous behavior — no hybrid routing, no `/model` picker) |
|
|
140
|
-
| `sference launch claude --no-anthropic --enable-tool-search` | Direct mode: set `ENABLE_TOOL_SEARCH=true` on a custom host |
|
|
141
|
-
|
|
142
|
-
Proxy mode requires `mitmproxy` (`mitmdump` on `PATH`) and the [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code). The installer (`install.sh` / `install.ps1`) installs mitmproxy alongside the CLI; to add it to an existing install: `uv tool install mitmproxy`. If mitmproxy is missing, proxy mode errors with a `--no-anthropic` suggestion.
|
|
143
|
-
|
|
144
|
-
> **Security note:** the proxy uses mitmproxy's local CA cert (`~/.mitmproxy/mitmproxy-ca-cert.pem`), scoped to the Claude Code process via `NODE_EXTRA_CA_CERTS` — it is **not** added to system trust. The CA can sign certs for any host; only the Claude Code process trusts it for this session.
|
|
145
142
|
|
|
146
|
-
|
|
143
|
+
Requires only the [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code). Device-flow credentials are refreshed at launch so long sessions start on a fresh 24 h token. `--no-anthropic` and `--proxy-port` are accepted as deprecated no-ops for older scripts.
|
|
147
144
|
|
|
148
145
|
#### `sference launch pi`
|
|
149
146
|
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
sference_cli/__init__.py,sha256=HT7s9qkZsDqCScvYKsNTr7i8fo9NUtxgcuFUdVVp0mo,427
|
|
2
|
+
sference_cli/_discovery.py,sha256=3GrNHpghPAd8hxZNbtJcpu1kko7eW83FpkJspzasgyM,3909
|
|
3
|
+
sference_cli/device_auth.py,sha256=KwuQKN6dF6B_pSWd-TIBUCDaMF0Nx1OP8prRLSLno4I,6008
|
|
4
|
+
sference_cli/launch.py,sha256=upNup-vuwsnkGs7gSVcZSr3ili7es98tKO6bKVuggXc,44096
|
|
5
|
+
sference_cli/main.py,sha256=L0abiwrLU9ZDcJoBEkj56ZHawp7piKqt0IEYVZA8K-U,44566
|
|
6
|
+
sference_cli/stream_cache.py,sha256=dYzsHp2iWF2bj8JevVdThVaaCKjkztcUposNpRaZKzU,1943
|
|
7
|
+
sference_cli-0.4.0.dist-info/METADATA,sha256=-pVzGru06Tb0PvtjZqk_Rp5Wm7nNvYcr-HcUXza6B-w,16965
|
|
8
|
+
sference_cli-0.4.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
9
|
+
sference_cli-0.4.0.dist-info/entry_points.txt,sha256=JkFhzUu37Q6aUJ0P-FccUfzpi0rxrzH1vtvbLQyVTH0,52
|
|
10
|
+
sference_cli-0.4.0.dist-info/licenses/LICENSE,sha256=uvXIHt0k9gF7K4mnd0k9hPn1Eufh_Jy902l2y2WeU5s,11395
|
|
11
|
+
sference_cli-0.4.0.dist-info/RECORD,,
|
sference_cli/_proxy_addon.py
DELETED
|
@@ -1,242 +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,
|
|
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()]
|
sference_cli/_proxy_routing.py
DELETED
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
"""Pure routing helpers for the Sference↔Claude Code mitmproxy addon.
|
|
2
|
-
|
|
3
|
-
Stdlib-only (json, urllib) so this module imports in ANY venv — including
|
|
4
|
-
mitmproxy's isolated tool venv, which does NOT contain ``sference_cli``. The
|
|
5
|
-
addon (``_proxy_addon.py``) loads it via a sibling-path import after the
|
|
6
|
-
launcher extracts both files to a temp dir. Tests import it directly from the
|
|
7
|
-
``sference_cli`` package.
|
|
8
|
-
|
|
9
|
-
Design: Sference has a native Anthropic Messages endpoint at ``/v1/messages``
|
|
10
|
-
(``apps/api/sference_api/inference/anthropic_controller.py``; auth accepts
|
|
11
|
-
``x-api-key`` or ``Authorization: Bearer``). So routing is a pure URL + auth
|
|
12
|
-
rewrite — the request body is passed through byte-for-byte untranslated and
|
|
13
|
-
the response is already native Anthropic. No Anthropic↔OpenAI translation.
|
|
14
|
-
"""
|
|
15
|
-
|
|
16
|
-
from __future__ import annotations
|
|
17
|
-
|
|
18
|
-
import json
|
|
19
|
-
import re
|
|
20
|
-
from typing import Any
|
|
21
|
-
from urllib.parse import urlsplit, urlunsplit
|
|
22
|
-
|
|
23
|
-
# Decision labels returned by ``decide_routing``.
|
|
24
|
-
PASSTHROUGH = "passthrough" # leave untouched, goes to the real upstream
|
|
25
|
-
SFERENCE = "sference" # rewrite to the Sference /v1/messages endpoint
|
|
26
|
-
BOOTSTRAP = "bootstrap" # Claude Code /api/claude_cli/bootstrap — inject models
|
|
27
|
-
|
|
28
|
-
# Hosts the addon actually acts on. Everything else must bypass TLS
|
|
29
|
-
# interception (see build_allow_hosts_regex).
|
|
30
|
-
ANTHROPIC_API_HOST = "api.anthropic.com"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def build_allow_hosts_regex(sference_base_url: str) -> str:
|
|
34
|
-
"""Build the mitmproxy ``allow_hosts`` regex limiting interception to the
|
|
35
|
-
hosts this proxy needs to touch.
|
|
36
|
-
|
|
37
|
-
The launcher sets ``HTTPS_PROXY`` on the whole ``claude`` process, and
|
|
38
|
-
Claude Code passes its env through to every tool it spawns (Bash, curl,
|
|
39
|
-
gh, …). Without scoping, mitmproxy TLS-intercepts ALL of that traffic and
|
|
40
|
-
any tool that doesn't trust the mitmproxy CA (every non-Node binary: Go's
|
|
41
|
-
``gh``, system curl, etc.) fails with an x509 error — even for hosts we
|
|
42
|
-
never route.
|
|
43
|
-
|
|
44
|
-
mitmproxy's ``allow_hosts`` inverts that: connections to non-matching hosts
|
|
45
|
-
are passed through as raw TCP (``TCPLayer(ignore=True)``) with NO TLS
|
|
46
|
-
termination, so they neither break nor pollute the flow log. Only the
|
|
47
|
-
hosts we genuinely intercept — Anthropic's API (routing + bootstrap model
|
|
48
|
-
injection) and the Sference API (the rewrite target) — get terminated.
|
|
49
|
-
|
|
50
|
-
Returns a single alternation regex, e.g.
|
|
51
|
-
``^(api\\.anthropic\\.com|api\\.sference\\.com):\\d+$``.
|
|
52
|
-
|
|
53
|
-
The trailing ``:port`` is REQUIRED, not optional. mitmproxy's
|
|
54
|
-
``NextLayer._ignore_connection`` builds every candidate string as
|
|
55
|
-
``f"{host}:{port}"`` (from ``server.peername``, ``server.address``, the
|
|
56
|
-
HTTP Host header, and the TLS SNI) — it never tests a bare hostname. A
|
|
57
|
-
regex anchored ``^host$`` therefore matches nothing, every connection
|
|
58
|
-
counts as not-allowed, and the proxy silently degrades to raw TCP
|
|
59
|
-
passthrough for ALL traffic, including the hosts we need to intercept.
|
|
60
|
-
"""
|
|
61
|
-
hosts = {ANTHROPIC_API_HOST}
|
|
62
|
-
netloc = urlsplit(sference_base_url.rstrip("/")).netloc
|
|
63
|
-
host = netloc.split(":", 1)[0] # drop any port; mitmproxy appends its own
|
|
64
|
-
if host:
|
|
65
|
-
hosts.add(host)
|
|
66
|
-
return "^(" + "|".join(re.escape(h) for h in sorted(hosts)) + r"):\d+$"
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def decide_routing(
|
|
70
|
-
host: str,
|
|
71
|
-
method: str,
|
|
72
|
-
path: str,
|
|
73
|
-
body: Any,
|
|
74
|
-
sference_models: set[str],
|
|
75
|
-
) -> str:
|
|
76
|
-
"""Decide how to route a single request the addon sees.
|
|
77
|
-
|
|
78
|
-
``body`` is the parsed JSON of a POST body (or ``None`` if not JSON / not a
|
|
79
|
-
dict). ``sference_models`` is the set of catalog ids this account can serve
|
|
80
|
-
(live-fetched from ``GET /v1/models``). Returns one of ``PASSTHROUGH``,
|
|
81
|
-
``SFERENCE``, ``BOOTSTRAP``.
|
|
82
|
-
"""
|
|
83
|
-
if (host or "") != "api.anthropic.com":
|
|
84
|
-
return PASSTHROUGH
|
|
85
|
-
method = (method or "").upper()
|
|
86
|
-
if method == "GET" and "/api/claude_cli/bootstrap" in (path or ""):
|
|
87
|
-
return BOOTSTRAP
|
|
88
|
-
if method == "POST" and "/v1/messages" in (path or ""):
|
|
89
|
-
model = body.get("model") if isinstance(body, dict) else None
|
|
90
|
-
if isinstance(model, str) and model in sference_models:
|
|
91
|
-
return SFERENCE
|
|
92
|
-
return PASSTHROUGH
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
def strip_unsigned_thinking_blocks(body: Any) -> tuple[Any, int]:
|
|
96
|
-
"""Drop ``thinking`` blocks carrying an empty ``signature`` from a request body.
|
|
97
|
-
|
|
98
|
-
Returns ``(body, dropped_count)``; the body is mutated in place and also
|
|
99
|
-
returned for convenience.
|
|
100
|
-
|
|
101
|
-
Anthropic verifies the ``signature`` on every ``thinking`` block it is sent
|
|
102
|
-
and rejects the whole request with a 400 (``Invalid `signature` in
|
|
103
|
-
`thinking` block``) if one does not validate. Sference's ``/v1/messages``
|
|
104
|
-
emits ``signature: ""``, so once a Sference model has answered in a session,
|
|
105
|
-
every later request routed to *Anthropic* replays that unsignable history
|
|
106
|
-
and 400s.
|
|
107
|
-
|
|
108
|
-
Claude Code already recovers by stripping the thinking blocks and resending,
|
|
109
|
-
so this is not a correctness fix — it is a cost fix: it avoids re-uploading
|
|
110
|
-
a large request body (~180KB in practice) and burning a round-trip on every
|
|
111
|
-
turn after a model switch. We drop exactly what the client would have
|
|
112
|
-
dropped, one step earlier.
|
|
113
|
-
|
|
114
|
-
Only empty-signature blocks are removed; genuine Anthropic-minted
|
|
115
|
-
signatures are left untouched so real Claude reasoning still replays.
|
|
116
|
-
"""
|
|
117
|
-
if not isinstance(body, dict):
|
|
118
|
-
return body, 0
|
|
119
|
-
messages = body.get("messages")
|
|
120
|
-
if not isinstance(messages, list):
|
|
121
|
-
return body, 0
|
|
122
|
-
|
|
123
|
-
dropped = 0
|
|
124
|
-
for message in messages:
|
|
125
|
-
if not isinstance(message, dict):
|
|
126
|
-
continue
|
|
127
|
-
content = message.get("content")
|
|
128
|
-
# Content may be a plain string (no blocks to inspect).
|
|
129
|
-
if not isinstance(content, list):
|
|
130
|
-
continue
|
|
131
|
-
kept = [
|
|
132
|
-
block
|
|
133
|
-
for block in content
|
|
134
|
-
if not (
|
|
135
|
-
isinstance(block, dict)
|
|
136
|
-
and block.get("type") == "thinking"
|
|
137
|
-
and not block.get("signature")
|
|
138
|
-
)
|
|
139
|
-
]
|
|
140
|
-
# Never empty a message: Anthropic rejects a zero-length content array,
|
|
141
|
-
# which would turn a recoverable 400 into one we caused. Leaving the
|
|
142
|
-
# blocks in place costs us that request (Anthropic 400s on the bad
|
|
143
|
-
# signature and Claude Code retries, exactly as it did before this fix)
|
|
144
|
-
# rather than making things worse.
|
|
145
|
-
if kept and len(kept) != len(content):
|
|
146
|
-
dropped += len(content) - len(kept)
|
|
147
|
-
message["content"] = kept
|
|
148
|
-
return body, dropped
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
def _sference_origin(sference_base_url: str) -> str:
|
|
152
|
-
"""Normalize the Sference base URL to scheme + netloc (strip any ``/v1``).
|
|
153
|
-
|
|
154
|
-
The Anthropic request path (``/v1/messages``) is preserved verbatim, so the
|
|
155
|
-
base must contribute only the origin — otherwise we'd double the ``/v1``.
|
|
156
|
-
"""
|
|
157
|
-
parts = urlsplit(sference_base_url.rstrip("/"))
|
|
158
|
-
return f"{parts.scheme}://{parts.netloc}"
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
def rewrite_request_for_sference(
|
|
162
|
-
url: str,
|
|
163
|
-
sference_base_url: str,
|
|
164
|
-
api_key: str,
|
|
165
|
-
) -> tuple[str, dict[str, str], list[str]]:
|
|
166
|
-
"""Rewrite an Anthropic request URL + auth to hit the Sference endpoint.
|
|
167
|
-
|
|
168
|
-
Returns ``(new_url, headers_to_set, headers_to_remove)``. The request body
|
|
169
|
-
is NOT touched — Sference speaks native Anthropic Messages, so the body
|
|
170
|
-
passes through byte-for-byte. We swap the auth to the Sference API key
|
|
171
|
-
(via ``x-api-key``, which Sference reads natively) and drop any stale
|
|
172
|
-
Anthropic ``Authorization`` so it can't shadow the key.
|
|
173
|
-
"""
|
|
174
|
-
origin = _sference_origin(sference_base_url)
|
|
175
|
-
src = urlsplit(url)
|
|
176
|
-
# Keep the Anthropic path + query (e.g. /v1/messages?beta=true). Sference's
|
|
177
|
-
# controller accepts and ignores ?beta=true.
|
|
178
|
-
new_url = urlunsplit((src.scheme, urlsplit(origin).netloc, src.path, src.query, src.fragment))
|
|
179
|
-
headers_to_set = {"x-api-key": api_key}
|
|
180
|
-
headers_to_remove = ["authorization"]
|
|
181
|
-
return new_url, headers_to_set, headers_to_remove
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
# Claude-family display names for the models we route. The picker shows this
|
|
185
|
-
# instead of the raw catalog id so the entries read like first-party Claude
|
|
186
|
-
# models. Keyed by exact catalog id; unknown ids get the generic fallback.
|
|
187
|
-
MODEL_DESCRIPTIONS: dict[str, str] = {
|
|
188
|
-
"moonshotai/Kimi-K3": "Fable",
|
|
189
|
-
"zai-org/GLM-5.2": "Opus",
|
|
190
|
-
"deepseek-ai/DeepSeek-V4-Flash": "Sonnet",
|
|
191
|
-
}
|
|
192
|
-
DEFAULT_MODEL_DESCRIPTION = "Sference (routed via local proxy)"
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
def inject_models_into_bootstrap(body: Any, sference_models: set[str]) -> Any:
|
|
196
|
-
"""Append Sference models to a bootstrap response's ``additional_model_options``.
|
|
197
|
-
|
|
198
|
-
Claude Code populates its ``/model`` picker from built-ins plus this array;
|
|
199
|
-
each entry's ``model`` is sent verbatim on ``/v1/messages``, which the addon
|
|
200
|
-
then routes to Sference. Best-effort: if the shape is wrong, return the body
|
|
201
|
-
unchanged rather than crashing (the picker is a nicety, not a requirement).
|
|
202
|
-
"""
|
|
203
|
-
if not isinstance(body, dict):
|
|
204
|
-
return body
|
|
205
|
-
options = body.get("additional_model_options")
|
|
206
|
-
if not isinstance(options, list):
|
|
207
|
-
options = []
|
|
208
|
-
existing = {o.get("model") for o in options if isinstance(o, dict)}
|
|
209
|
-
for model in sorted(sference_models):
|
|
210
|
-
if model in existing:
|
|
211
|
-
continue
|
|
212
|
-
options.append(
|
|
213
|
-
{
|
|
214
|
-
"model": model,
|
|
215
|
-
"name": f"[Sference] {model}",
|
|
216
|
-
"description": MODEL_DESCRIPTIONS.get(model, DEFAULT_MODEL_DESCRIPTION),
|
|
217
|
-
"disabled_reason": None,
|
|
218
|
-
}
|
|
219
|
-
)
|
|
220
|
-
body["additional_model_options"] = options
|
|
221
|
-
return body
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
def parse_models_env(raw: str) -> set[str]:
|
|
225
|
-
"""Parse the ``SFERENCE_PROXY_MODELS`` env var (JSON list) into a set."""
|
|
226
|
-
if not raw:
|
|
227
|
-
return set()
|
|
228
|
-
try:
|
|
229
|
-
data = json.loads(raw)
|
|
230
|
-
except json.JSONDecodeError:
|
|
231
|
-
return set()
|
|
232
|
-
if isinstance(data, list):
|
|
233
|
-
return {str(m) for m in data if isinstance(m, str) and m}
|
|
234
|
-
return set()
|
sference_cli/proxy.py
DELETED
|
@@ -1,291 +0,0 @@
|
|
|
1
|
-
"""Launcher for the Sference↔Claude Code transparent proxy.
|
|
2
|
-
|
|
3
|
-
Spawns a local mitmproxy forward proxy (installed as a separate ``uv tool`` so
|
|
4
|
-
``mitmdump`` is on PATH), then launches ``claude`` with ``HTTPS_PROXY`` pointing
|
|
5
|
-
at it and ``ANTHROPIC_BASE_URL`` *unset* — so Claude Code's first-party
|
|
6
|
-
detection stays on, Sference models appear in the native ``/model`` picker, and
|
|
7
|
-
real Claude models pass through to Anthropic. Sference models are routed to
|
|
8
|
-
Sference's native ``/v1/messages`` endpoint with the body passed through
|
|
9
|
-
untranslated (see ``_proxy_routing.py``).
|
|
10
|
-
|
|
11
|
-
The mitmproxy addon (``_proxy_addon.py``) and the pure routing helpers
|
|
12
|
-
(``_proxy_routing.py``) are shipped as package resources and extracted to a
|
|
13
|
-
temp dir at runtime so the addon can import the helpers via a sibling path
|
|
14
|
-
(mitmproxy's venv has no ``sference_cli``).
|
|
15
|
-
"""
|
|
16
|
-
|
|
17
|
-
from __future__ import annotations
|
|
18
|
-
|
|
19
|
-
import importlib.resources
|
|
20
|
-
import json
|
|
21
|
-
import os
|
|
22
|
-
import shutil
|
|
23
|
-
import signal
|
|
24
|
-
import socket
|
|
25
|
-
import subprocess
|
|
26
|
-
import sys
|
|
27
|
-
import tempfile
|
|
28
|
-
import time
|
|
29
|
-
import urllib.error
|
|
30
|
-
import urllib.request
|
|
31
|
-
from pathlib import Path
|
|
32
|
-
from typing import Optional
|
|
33
|
-
|
|
34
|
-
import typer
|
|
35
|
-
|
|
36
|
-
from sference_cli._proxy_routing import build_allow_hosts_regex
|
|
37
|
-
|
|
38
|
-
MITM_CA_CERT = Path.home() / ".mitmproxy" / "mitmproxy-ca-cert.pem"
|
|
39
|
-
DEFAULT_FLOW_DETAIL = "1"
|
|
40
|
-
# Stable, discoverable log path (not the ephemeral temp dir, which is hard to find
|
|
41
|
-
# and gets cleared by OS housekeeping). Lives with the other sference state files.
|
|
42
|
-
DEFAULT_LOG_FILE = Path.home() / ".sference" / "claude_proxy.log"
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def _normalize_base_url(raw: str) -> str:
|
|
46
|
-
"""Return the API origin (scheme + netloc), accepting either
|
|
47
|
-
https://api.sference.com or https://api.sference.com/v1."""
|
|
48
|
-
raw = raw.rstrip("/")
|
|
49
|
-
if raw.endswith("/v1"):
|
|
50
|
-
raw = raw[: -len("/v1")]
|
|
51
|
-
return raw
|
|
52
|
-
|
|
53
|
-
|
|
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`.
|
|
61
|
-
|
|
62
|
-
Keeps the router in sync with what the account can serve, so a
|
|
63
|
-
deprecated/renamed model never slips through and 400s mid-session.
|
|
64
|
-
"""
|
|
65
|
-
api_root = _normalize_base_url(base_url) + "/v1"
|
|
66
|
-
req = urllib.request.Request(
|
|
67
|
-
f"{api_root}/models",
|
|
68
|
-
headers={"Authorization": f"Bearer {api_key}"},
|
|
69
|
-
)
|
|
70
|
-
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
71
|
-
payload = json.loads(resp.read().decode("utf-8"))
|
|
72
|
-
return [
|
|
73
|
-
item
|
|
74
|
-
for item in payload.get("data", [])
|
|
75
|
-
if isinstance(item, dict)
|
|
76
|
-
and item.get("id")
|
|
77
|
-
and item.get("modality", "text_generation") == "text_generation"
|
|
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)}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
def pick_free_port() -> int:
|
|
87
|
-
"""Allocate an ephemeral port the OS guarantees is free at bind time."""
|
|
88
|
-
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
89
|
-
s.bind(("127.0.0.1", 0))
|
|
90
|
-
return s.getsockname()[1]
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def port_in_use(port: int) -> bool:
|
|
94
|
-
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
95
|
-
s.settimeout(0.5)
|
|
96
|
-
return s.connect_ex(("127.0.0.1", port)) == 0
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
def mitmproxy_available() -> bool:
|
|
100
|
-
"""mitmproxy is installed as a separate ``uv tool`` → ``mitmdump`` is on PATH."""
|
|
101
|
-
return shutil.which("mitmdump") is not None
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
def _extract_addon_files() -> tuple[Path, Path]:
|
|
105
|
-
"""Extract the addon + its sibling imports to a temp dir; return (tmpdir, addon_path).
|
|
106
|
-
|
|
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.
|
|
111
|
-
"""
|
|
112
|
-
res = importlib.resources.files("sference_cli")
|
|
113
|
-
addon_src = (res / "_proxy_addon.py").read_text(encoding="utf-8")
|
|
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")
|
|
116
|
-
tmpdir = Path(tempfile.mkdtemp(prefix="sference_proxy_"))
|
|
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")
|
|
119
|
-
addon_path = tmpdir / "_proxy_addon.py"
|
|
120
|
-
addon_path.write_text(addon_src, encoding="utf-8")
|
|
121
|
-
return tmpdir, addon_path
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
def _wait_for_mitmproxy(proc: subprocess.Popen, port: int, log_file: Path) -> bool:
|
|
125
|
-
"""Wait for mitmproxy to bind the port; return False if it died."""
|
|
126
|
-
for _ in range(40):
|
|
127
|
-
if proc.poll() is not None:
|
|
128
|
-
typer.echo(f"ERROR: mitmproxy exited immediately (code {proc.returncode}).", err=True)
|
|
129
|
-
typer.echo(f"See {log_file} for the error.", err=True)
|
|
130
|
-
return False
|
|
131
|
-
if port_in_use(port):
|
|
132
|
-
return True
|
|
133
|
-
time.sleep(0.25)
|
|
134
|
-
typer.echo(f"ERROR: mitmproxy did not start listening on {port}. See {log_file}.", err=True)
|
|
135
|
-
return False
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
def _wait_for_ca_cert(timeout: float = 15.0) -> bool:
|
|
139
|
-
"""mitmproxy generates its CA on first run; wait for it to appear."""
|
|
140
|
-
if MITM_CA_CERT.exists():
|
|
141
|
-
return True
|
|
142
|
-
deadline = time.monotonic() + timeout
|
|
143
|
-
while time.monotonic() < deadline:
|
|
144
|
-
if MITM_CA_CERT.exists():
|
|
145
|
-
return True
|
|
146
|
-
time.sleep(0.5)
|
|
147
|
-
return False
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
def launch_claude_via_proxy(
|
|
151
|
-
*,
|
|
152
|
-
api_key: str,
|
|
153
|
-
base_url: str,
|
|
154
|
-
models: set[str],
|
|
155
|
-
claude_args: list[str],
|
|
156
|
-
dry_run: bool,
|
|
157
|
-
proxy_port: Optional[int] = None,
|
|
158
|
-
log_file: Optional[str] = None,
|
|
159
|
-
refresh_token: Optional[str] = None,
|
|
160
|
-
credentials_path: Optional[str] = None,
|
|
161
|
-
) -> None:
|
|
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
|
-
"""
|
|
169
|
-
if not mitmproxy_available():
|
|
170
|
-
typer.echo(
|
|
171
|
-
"mitmproxy not found. Install it with: uv tool install mitmproxy\n"
|
|
172
|
-
"Or run Claude Code without the proxy: sference launch claude --no-anthropic",
|
|
173
|
-
err=True,
|
|
174
|
-
)
|
|
175
|
-
raise typer.Exit(code=1)
|
|
176
|
-
|
|
177
|
-
port = proxy_port or pick_free_port()
|
|
178
|
-
sference_base = _normalize_base_url(base_url)
|
|
179
|
-
log_path = Path(log_file) if log_file else DEFAULT_LOG_FILE
|
|
180
|
-
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
181
|
-
|
|
182
|
-
claude_bin = shutil.which("claude")
|
|
183
|
-
if claude_bin is None:
|
|
184
|
-
typer.echo(
|
|
185
|
-
"Claude Code CLI not found on PATH.\n"
|
|
186
|
-
"Install from https://docs.anthropic.com/en/docs/claude-code "
|
|
187
|
-
"and ensure the `claude` command is available.",
|
|
188
|
-
err=True,
|
|
189
|
-
)
|
|
190
|
-
raise typer.Exit(code=1)
|
|
191
|
-
|
|
192
|
-
if dry_run:
|
|
193
|
-
typer.echo(f"mitmproxy: mitmdump on 127.0.0.1:{port} (log: {log_path})")
|
|
194
|
-
typer.echo(f"Sference API: {sference_base}")
|
|
195
|
-
typer.echo(f"Models ({len(models)}): {', '.join(sorted(models))}")
|
|
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)")
|
|
199
|
-
typer.echo(f"HTTPS_PROXY=http://127.0.0.1:{port}")
|
|
200
|
-
typer.echo(f"NODE_EXTRA_CA_CERTS={MITM_CA_CERT}")
|
|
201
|
-
typer.echo("ANTHROPIC_BASE_URL=<unset> (first-party detection stays on)")
|
|
202
|
-
typer.echo(f"allow_hosts={build_allow_hosts_regex(sference_base)} (only these hosts are TLS-intercepted)")
|
|
203
|
-
typer.echo(f"command: {claude_bin} {' '.join(claude_args)}".rstrip())
|
|
204
|
-
return
|
|
205
|
-
|
|
206
|
-
tmpdir, addon_path = _extract_addon_files()
|
|
207
|
-
mitm_env = {
|
|
208
|
-
**os.environ,
|
|
209
|
-
"SFERENCE_API_KEY": api_key,
|
|
210
|
-
"SFERENCE_BASE_URL": sference_base,
|
|
211
|
-
"SFERENCE_PROXY_MODELS": json.dumps(sorted(models)),
|
|
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
|
|
217
|
-
# Scope TLS interception to just the hosts we route. Without this, every
|
|
218
|
-
# tool Claude Code spawns (Bash → curl, gh, …) also goes through the proxy
|
|
219
|
-
# and fails TLS validation unless it trusts the mitmproxy CA. allow_hosts
|
|
220
|
-
# makes non-matching hosts pass through as raw TCP — no CA involvement.
|
|
221
|
-
allow_hosts = build_allow_hosts_regex(sference_base)
|
|
222
|
-
mitm_cmd = [
|
|
223
|
-
shutil.which("mitmdump"),
|
|
224
|
-
"-p", str(port),
|
|
225
|
-
"--listen-host", "127.0.0.1",
|
|
226
|
-
"--set", f"flow_detail={os.environ.get('FLOW_DETAIL', DEFAULT_FLOW_DETAIL)}",
|
|
227
|
-
"--set", f"allow_hosts={allow_hosts}",
|
|
228
|
-
"-s", str(addon_path),
|
|
229
|
-
]
|
|
230
|
-
|
|
231
|
-
log_fh = open(log_path, "w") # truncate: never tail stale lines from a prior run
|
|
232
|
-
mitm_proc = subprocess.Popen(
|
|
233
|
-
mitm_cmd, stdout=log_fh, stderr=subprocess.STDOUT, env=mitm_env
|
|
234
|
-
)
|
|
235
|
-
|
|
236
|
-
claude_proc: Optional[subprocess.Popen] = None
|
|
237
|
-
|
|
238
|
-
def _cleanup(*_args: object) -> None:
|
|
239
|
-
if claude_proc is not None:
|
|
240
|
-
try:
|
|
241
|
-
claude_proc.terminate()
|
|
242
|
-
except Exception:
|
|
243
|
-
pass
|
|
244
|
-
if mitm_proc.poll() is None:
|
|
245
|
-
mitm_proc.terminate()
|
|
246
|
-
try:
|
|
247
|
-
mitm_proc.wait(timeout=5)
|
|
248
|
-
except Exception:
|
|
249
|
-
mitm_proc.kill()
|
|
250
|
-
log_fh.close()
|
|
251
|
-
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
252
|
-
|
|
253
|
-
# Install signal handlers so Ctrl-C tears down both children (Unix only).
|
|
254
|
-
if sys.platform != "win32":
|
|
255
|
-
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
256
|
-
signal.signal(sig, lambda *_a: (_cleanup(), sys.exit(130))[1])
|
|
257
|
-
|
|
258
|
-
try:
|
|
259
|
-
if not _wait_for_mitmproxy(mitm_proc, port, log_path):
|
|
260
|
-
raise typer.Exit(code=1)
|
|
261
|
-
|
|
262
|
-
if not _wait_for_ca_cert():
|
|
263
|
-
typer.echo(
|
|
264
|
-
f"ERROR: mitmproxy CA cert not found at {MITM_CA_CERT}. "
|
|
265
|
-
"Run `mitmdump` once standalone to generate it.",
|
|
266
|
-
err=True,
|
|
267
|
-
)
|
|
268
|
-
raise typer.Exit(code=1)
|
|
269
|
-
|
|
270
|
-
# Quiet by default: one line. The full config (ports, proxy env, models)
|
|
271
|
-
# is available via --dry-run; the proxy detail is in the log file.
|
|
272
|
-
typer.echo("Launching Claude Code...")
|
|
273
|
-
|
|
274
|
-
claude_env = os.environ.copy()
|
|
275
|
-
claude_env["HTTPS_PROXY"] = f"http://127.0.0.1:{port}"
|
|
276
|
-
claude_env["NODE_EXTRA_CA_CERTS"] = str(MITM_CA_CERT)
|
|
277
|
-
claude_env.pop("ANTHROPIC_BASE_URL", None) # keep first-party detection on
|
|
278
|
-
|
|
279
|
-
claude_proc = subprocess.Popen(
|
|
280
|
-
[claude_bin, *claude_args],
|
|
281
|
-
env=claude_env,
|
|
282
|
-
stdin=sys.stdin,
|
|
283
|
-
stdout=sys.stdout,
|
|
284
|
-
stderr=sys.stderr,
|
|
285
|
-
)
|
|
286
|
-
claude_proc.wait()
|
|
287
|
-
exit_code = claude_proc.returncode
|
|
288
|
-
finally:
|
|
289
|
-
_cleanup()
|
|
290
|
-
|
|
291
|
-
raise typer.Exit(code=exit_code)
|
|
@@ -1,13 +0,0 @@
|
|
|
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=LC0oejPoJ5GEE8nfrCsHL1E-23WpwGeO_HmfRJhPxsg,41088
|
|
6
|
-
sference_cli/main.py,sha256=L0abiwrLU9ZDcJoBEkj56ZHawp7piKqt0IEYVZA8K-U,44566
|
|
7
|
-
sference_cli/proxy.py,sha256=SCMY_DcWyzcC4sQ7ck7gtEUMK8yjE_Mu6dy6AOmjNOc,11306
|
|
8
|
-
sference_cli/stream_cache.py,sha256=dYzsHp2iWF2bj8JevVdThVaaCKjkztcUposNpRaZKzU,1943
|
|
9
|
-
sference_cli-0.3.2.dist-info/METADATA,sha256=Huv6IvmzZaTTGt-ADIWX_xVb-AbBNyJ7MEKmXU77drI,17119
|
|
10
|
-
sference_cli-0.3.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
11
|
-
sference_cli-0.3.2.dist-info/entry_points.txt,sha256=JkFhzUu37Q6aUJ0P-FccUfzpi0rxrzH1vtvbLQyVTH0,52
|
|
12
|
-
sference_cli-0.3.2.dist-info/licenses/LICENSE,sha256=uvXIHt0k9gF7K4mnd0k9hPn1Eufh_Jy902l2y2WeU5s,11395
|
|
13
|
-
sference_cli-0.3.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|