sference-cli 0.1.8__tar.gz → 0.1.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sference-cli
3
- Version: 0.1.8
3
+ Version: 0.1.9
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.1.8
24
+ Requires-Dist: sference-sdk>=0.1.9
25
25
  Requires-Dist: typer>=0.24.1
26
26
  Description-Content-Type: text/markdown
27
27
 
@@ -124,15 +124,28 @@ sference responses tail --stream-id <stream_id>
124
124
 
125
125
  ### Launch
126
126
 
127
+ #### `sference launch claude` (default: transparent proxy)
128
+
129
+ By default, `sference launch claude` starts a local [mitmproxy](https://mitmproxy.org) forward proxy and launches Claude Code with `HTTPS_PROXY` pointing at it (and `ANTHROPIC_BASE_URL` *unset*, so Claude Code's first-party detection stays on). Sference models are routed to Sference's native `/v1/messages` endpoint (body passed through untranslated) and appear in Claude Code's `/model` picker; real Claude models pass through to Anthropic. Hybrid routing — use both Sference and Claude models in one session.
130
+
127
131
  | Command | Description |
128
132
  |---------|-------------|
129
- | `sference launch claude` | Launch Claude Code with Sference API routing (`ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_MODEL`) |
130
- | `sference launch claude --dry-run` | Print env + command without starting Claude Code |
131
- | `sference launch claude --model moonshotai/Kimi-K2.7-Code` | Override catalog model |
132
- | `sference launch claude --enable-tool-search` | Set `ENABLE_TOOL_SEARCH=true` on custom hosts |
133
- | `sference launch claude --resume` | Forward Claude Code flags/args after `sference launch claude` |
133
+ | `sference launch claude` | Start the proxy and launch Claude Code (default). Sference models appear in `/model`; Claude models pass through. |
134
+ | `sference launch claude --dry-run` | Print the proxy config + command without launching |
135
+ | `sference launch claude --model zai-org/GLM-5.2` | Inject this model into the `/model` picker (default: live `GET /v1/models`) |
136
+ | `sference launch claude --models a,b` | Inject a comma-separated set of models into the picker |
137
+ | `sference launch claude --proxy-port 8082` | Use a fixed local mitmproxy port (default: auto-pick) |
138
+ | `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
+
146
+ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
134
147
 
135
- Requires the [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) on `PATH`. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
148
+ #### `sference launch pi`
136
149
 
137
150
  | Command | Description |
138
151
  |---------|-------------|
@@ -97,15 +97,28 @@ sference responses tail --stream-id <stream_id>
97
97
 
98
98
  ### Launch
99
99
 
100
+ #### `sference launch claude` (default: transparent proxy)
101
+
102
+ By default, `sference launch claude` starts a local [mitmproxy](https://mitmproxy.org) forward proxy and launches Claude Code with `HTTPS_PROXY` pointing at it (and `ANTHROPIC_BASE_URL` *unset*, so Claude Code's first-party detection stays on). Sference models are routed to Sference's native `/v1/messages` endpoint (body passed through untranslated) and appear in Claude Code's `/model` picker; real Claude models pass through to Anthropic. Hybrid routing — use both Sference and Claude models in one session.
103
+
100
104
  | Command | Description |
101
105
  |---------|-------------|
102
- | `sference launch claude` | Launch Claude Code with Sference API routing (`ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_MODEL`) |
103
- | `sference launch claude --dry-run` | Print env + command without starting Claude Code |
104
- | `sference launch claude --model moonshotai/Kimi-K2.7-Code` | Override catalog model |
105
- | `sference launch claude --enable-tool-search` | Set `ENABLE_TOOL_SEARCH=true` on custom hosts |
106
- | `sference launch claude --resume` | Forward Claude Code flags/args after `sference launch claude` |
106
+ | `sference launch claude` | Start the proxy and launch Claude Code (default). Sference models appear in `/model`; Claude models pass through. |
107
+ | `sference launch claude --dry-run` | Print the proxy config + command without launching |
108
+ | `sference launch claude --model zai-org/GLM-5.2` | Inject this model into the `/model` picker (default: live `GET /v1/models`) |
109
+ | `sference launch claude --models a,b` | Inject a comma-separated set of models into the picker |
110
+ | `sference launch claude --proxy-port 8082` | Use a fixed local mitmproxy port (default: auto-pick) |
111
+ | `sference launch claude -- --model zai-org/GLM-5.2 -p "hi"` | Forward Claude Code flags/args after `--` |
112
+ | `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) |
113
+ | `sference launch claude --no-anthropic --enable-tool-search` | Direct mode: set `ENABLE_TOOL_SEARCH=true` on a custom host |
114
+
115
+ 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.
116
+
117
+ > **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.
118
+
119
+ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
107
120
 
108
- Requires the [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) on `PATH`. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
121
+ #### `sference launch pi`
109
122
 
110
123
  | Command | Description |
111
124
  |---------|-------------|
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-cli"
3
- version = "0.1.8"
3
+ version = "0.1.9"
4
4
  description = "sference command-line interface"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -23,7 +23,7 @@ classifiers = [
23
23
  ]
24
24
  dependencies = [
25
25
  "typer>=0.24.1",
26
- "sference-sdk>=0.1.8",
26
+ "sference-sdk>=0.1.9",
27
27
  ]
28
28
 
29
29
  [project.urls]
@@ -0,0 +1,113 @@
1
+ """mitmproxy addon: route Sference models to api.sference.com, pass Claude through.
2
+
3
+ Loaded by ``mitmdump -s <this file>``. Runs inside mitmproxy's isolated tool
4
+ venv, which does NOT contain ``sference_cli`` — so we import the pure routing
5
+ helpers via a sibling path (the launcher extracts this file and
6
+ ``_proxy_routing.py`` to the same temp dir), not via ``from sference_cli…``.
7
+
8
+ Config comes from env (set by the launcher):
9
+ SFERENCE_PROXY_MODELS JSON list of routable catalog ids (text-generation)
10
+ SFERENCE_API_KEY Sference API key (sent as x-api-key)
11
+ SFERENCE_BASE_URL Sference API origin, e.g. https://api.sference.com
12
+
13
+ Routing is a pure URL + auth rewrite; the request body passes through
14
+ byte-for-byte (Sference has a native /v1/messages endpoint) and the response is
15
+ already native Anthropic — no translation in either direction.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ from mitmproxy import ctx, http
26
+
27
+ # Sibling import: _proxy_routing.py sits next to this file in the temp dir.
28
+ sys.path.insert(0, os.path.dirname(str(Path(__file__).resolve())))
29
+ from _proxy_routing import ( # noqa: E402
30
+ BOOTSTRAP,
31
+ PASSTHROUGH,
32
+ SFERENCE,
33
+ decide_routing,
34
+ inject_models_into_bootstrap,
35
+ parse_models_env,
36
+ rewrite_request_for_sference,
37
+ )
38
+
39
+ SFERENCE_BASE_URL = os.environ.get("SFERENCE_BASE_URL", "https://api.sference.com").rstrip("/")
40
+ SFERENCE_API_KEY = os.environ.get("SFERENCE_API_KEY", "")
41
+ SFERENCE_MODELS = parse_models_env(os.environ.get("SFERENCE_PROXY_MODELS", ""))
42
+
43
+ # flow.id -> original model (for response handling — currently a no-op since
44
+ # the Sference response is already native Anthropic, but kept for clarity).
45
+ _sference_flows: dict[str, str] = {}
46
+ # flow.ids of bootstrap GETs whose response we post-process.
47
+ _bootstrap_flows: set[str] = set()
48
+
49
+
50
+ class SferenceRouter:
51
+ def request(self, flow: "http.HTTPFlow") -> None:
52
+ if flow.request is None:
53
+ return
54
+ host = flow.request.pretty_host
55
+ method = flow.request.method
56
+ path = flow.request.path
57
+
58
+ body: object = None
59
+ if method == "POST":
60
+ try:
61
+ body = json.loads(flow.request.get_text())
62
+ except Exception:
63
+ body = None
64
+
65
+ decision = decide_routing(host, method, path, body, SFERENCE_MODELS)
66
+ if decision == PASSTHROUGH:
67
+ return
68
+ if decision == BOOTSTRAP:
69
+ _bootstrap_flows.add(flow.id)
70
+ return
71
+ # SFERENCE
72
+ model = body.get("model") if isinstance(body, dict) else None
73
+ ctx.log.info(f"sference: routing model={model!r} -> Sference")
74
+ _sference_flows[flow.id] = str(model)
75
+ new_url, set_headers, remove_headers = rewrite_request_for_sference(
76
+ flow.request.url, SFERENCE_BASE_URL, SFERENCE_API_KEY
77
+ )
78
+ flow.request.url = new_url
79
+ for key, value in set_headers.items():
80
+ flow.request.headers[key] = value
81
+ for key in remove_headers:
82
+ flow.request.headers.pop(key, None)
83
+
84
+ def response(self, flow: "http.HTTPFlow") -> None:
85
+ if flow.response is None:
86
+ return
87
+ if flow.id in _bootstrap_flows:
88
+ _bootstrap_flows.discard(flow.id)
89
+ self._inject_models(flow)
90
+ return
91
+ if flow.id in _sference_flows:
92
+ _sference_flows.pop(flow.id)
93
+ # Native Anthropic response: pass through untouched.
94
+ return
95
+
96
+ def _inject_models(self, flow: "http.HTTPFlow") -> None:
97
+ if flow.response.status_code != 200:
98
+ return
99
+ try:
100
+ body = json.loads(flow.response.get_text())
101
+ except Exception:
102
+ return
103
+ before = len(body.get("additional_model_options", []) if isinstance(body, dict) else [])
104
+ body = inject_models_into_bootstrap(body, SFERENCE_MODELS)
105
+ flow.response.set_text(json.dumps(body))
106
+ # Body length changed; drop stale framing so mitmproxy recomputes it.
107
+ flow.response.headers.pop("content-length", None)
108
+ flow.response.headers.pop("Content-Length", None)
109
+ after = len(body.get("additional_model_options", []) if isinstance(body, dict) else [])
110
+ ctx.log.info(f"sference: bootstrap injected {after - before} model(s) into /model picker")
111
+
112
+
113
+ addons = [SferenceRouter()]
@@ -0,0 +1,126 @@
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
+ from typing import Any
20
+ from urllib.parse import urlsplit, urlunsplit
21
+
22
+ # Decision labels returned by ``decide_routing``.
23
+ PASSTHROUGH = "passthrough" # leave untouched, goes to the real upstream
24
+ SFERENCE = "sference" # rewrite to the Sference /v1/messages endpoint
25
+ BOOTSTRAP = "bootstrap" # Claude Code /api/claude_cli/bootstrap — inject models
26
+
27
+
28
+ def decide_routing(
29
+ host: str,
30
+ method: str,
31
+ path: str,
32
+ body: Any,
33
+ sference_models: set[str],
34
+ ) -> str:
35
+ """Decide how to route a single request the addon sees.
36
+
37
+ ``body`` is the parsed JSON of a POST body (or ``None`` if not JSON / not a
38
+ dict). ``sference_models`` is the set of catalog ids this account can serve
39
+ (live-fetched from ``GET /v1/models``). Returns one of ``PASSTHROUGH``,
40
+ ``SFERENCE``, ``BOOTSTRAP``.
41
+ """
42
+ if (host or "") != "api.anthropic.com":
43
+ return PASSTHROUGH
44
+ method = (method or "").upper()
45
+ if method == "GET" and "/api/claude_cli/bootstrap" in (path or ""):
46
+ return BOOTSTRAP
47
+ if method == "POST" and "/v1/messages" in (path or ""):
48
+ model = body.get("model") if isinstance(body, dict) else None
49
+ if isinstance(model, str) and model in sference_models:
50
+ return SFERENCE
51
+ return PASSTHROUGH
52
+
53
+
54
+ def _sference_origin(sference_base_url: str) -> str:
55
+ """Normalize the Sference base URL to scheme + netloc (strip any ``/v1``).
56
+
57
+ The Anthropic request path (``/v1/messages``) is preserved verbatim, so the
58
+ base must contribute only the origin — otherwise we'd double the ``/v1``.
59
+ """
60
+ parts = urlsplit(sference_base_url.rstrip("/"))
61
+ return f"{parts.scheme}://{parts.netloc}"
62
+
63
+
64
+ def rewrite_request_for_sference(
65
+ url: str,
66
+ sference_base_url: str,
67
+ api_key: str,
68
+ ) -> tuple[str, dict[str, str], list[str]]:
69
+ """Rewrite an Anthropic request URL + auth to hit the Sference endpoint.
70
+
71
+ Returns ``(new_url, headers_to_set, headers_to_remove)``. The request body
72
+ is NOT touched — Sference speaks native Anthropic Messages, so the body
73
+ passes through byte-for-byte. We swap the auth to the Sference API key
74
+ (via ``x-api-key``, which Sference reads natively) and drop any stale
75
+ Anthropic ``Authorization`` so it can't shadow the key.
76
+ """
77
+ origin = _sference_origin(sference_base_url)
78
+ src = urlsplit(url)
79
+ # Keep the Anthropic path + query (e.g. /v1/messages?beta=true). Sference's
80
+ # controller accepts and ignores ?beta=true.
81
+ new_url = urlunsplit((src.scheme, urlsplit(origin).netloc, src.path, src.query, src.fragment))
82
+ headers_to_set = {"x-api-key": api_key}
83
+ headers_to_remove = ["authorization"]
84
+ return new_url, headers_to_set, headers_to_remove
85
+
86
+
87
+ def inject_models_into_bootstrap(body: Any, sference_models: set[str]) -> Any:
88
+ """Append Sference models to a bootstrap response's ``additional_model_options``.
89
+
90
+ Claude Code populates its ``/model`` picker from built-ins plus this array;
91
+ each entry's ``model`` is sent verbatim on ``/v1/messages``, which the addon
92
+ then routes to Sference. Best-effort: if the shape is wrong, return the body
93
+ unchanged rather than crashing (the picker is a nicety, not a requirement).
94
+ """
95
+ if not isinstance(body, dict):
96
+ return body
97
+ options = body.get("additional_model_options")
98
+ if not isinstance(options, list):
99
+ options = []
100
+ existing = {o.get("model") for o in options if isinstance(o, dict)}
101
+ for model in sorted(sference_models):
102
+ if model in existing:
103
+ continue
104
+ options.append(
105
+ {
106
+ "model": model,
107
+ "name": f"[Sference] {model}",
108
+ "description": "Sference (routed via local proxy)",
109
+ "disabled_reason": None,
110
+ }
111
+ )
112
+ body["additional_model_options"] = options
113
+ return body
114
+
115
+
116
+ def parse_models_env(raw: str) -> set[str]:
117
+ """Parse the ``SFERENCE_PROXY_MODELS`` env var (JSON list) into a set."""
118
+ if not raw:
119
+ return set()
120
+ try:
121
+ data = json.loads(raw)
122
+ except json.JSONDecodeError:
123
+ return set()
124
+ if isinstance(data, list):
125
+ return {str(m) for m in data if isinstance(m, str) and m}
126
+ return set()
@@ -7,11 +7,14 @@ import os
7
7
  import shutil
8
8
  import subprocess
9
9
  import sys
10
+ import urllib.error
10
11
  from pathlib import Path
11
12
  from typing import Optional
12
13
 
13
14
  import typer
14
15
 
16
+ from .proxy import fetch_sference_models, launch_claude_via_proxy
17
+
15
18
  DEFAULT_LAUNCH_MODEL = "moonshotai/Kimi-K2.7-Code"
16
19
  DEFAULT_API_BASE_URL = "https://api.sference.com"
17
20
 
@@ -321,7 +324,7 @@ def register_launch_commands(app: typer.Typer) -> None:
321
324
  @launch_app.command(
322
325
  "claude",
323
326
  context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
324
- help="Launch Claude Code with Sference API routing.",
327
+ help="Launch Claude Code with a local Sference proxy (default). Use --no-anthropic for the direct env-var mode.",
325
328
  )
326
329
  def claude(
327
330
  ctx: typer.Context,
@@ -329,7 +332,8 @@ def register_launch_commands(app: typer.Typer) -> None:
329
332
  None,
330
333
  "--model",
331
334
  "-m",
332
- help=f"Catalog model id (default: {DEFAULT_LAUNCH_MODEL} or SFERENCE_MODEL).",
335
+ help="Proxy mode: catalog id to inject into the /model picker. --no-anthropic: the pinned model (default: "
336
+ f"{DEFAULT_LAUNCH_MODEL} or SFERENCE_MODEL).",
333
337
  ),
334
338
  base_url: Optional[str] = typer.Option(
335
339
  None,
@@ -337,22 +341,44 @@ def register_launch_commands(app: typer.Typer) -> None:
337
341
  envvar="SFERENCE_BASE_URL",
338
342
  help=f"Sference API base URL (default: {DEFAULT_API_BASE_URL}).",
339
343
  ),
344
+ no_anthropic: bool = typer.Option(
345
+ False,
346
+ "--no-anthropic",
347
+ help="Disable the proxy and route everything directly to the Sference endpoint "
348
+ "(today's ANTHROPIC_BASE_URL env-var behavior; no hybrid routing, no /model picker).",
349
+ ),
350
+ models: Optional[str] = typer.Option(
351
+ None,
352
+ "--models",
353
+ help="Proxy mode: comma-separated catalog ids to route and inject into the picker "
354
+ "(default: live GET /v1/models). Ignored with --no-anthropic.",
355
+ ),
356
+ proxy_port: Optional[int] = typer.Option(
357
+ None,
358
+ "--proxy-port",
359
+ help="Local mitmproxy port (default: auto-pick a free port). Proxy mode only.",
360
+ ),
340
361
  enable_tool_search: bool = typer.Option(
341
362
  False,
342
363
  "--enable-tool-search",
343
- help="Set ENABLE_TOOL_SEARCH=true for Claude Code on a custom API host.",
364
+ help="Set ENABLE_TOOL_SEARCH=true (only meaningful with --no-anthropic; the proxy "
365
+ "keeps first-party detection on, so tool search already works).",
344
366
  ),
345
367
  dry_run: bool = typer.Option(
346
368
  False,
347
369
  "--dry-run",
348
- help="Print env and command without launching Claude Code.",
370
+ help="Print the proxy/env config and command without launching anything.",
349
371
  ),
350
372
  ) -> None:
351
373
  """Run ``claude`` with Sference credentials.
352
374
 
353
- Uses ``~/.sference/credentials.json`` or ``SFERENCE_API_KEY``. Unknown options
354
- and trailing args are forwarded to Claude Code, e.g.
355
- ``sference launch claude --resume`` or ``sference launch claude -p "fix the bug"``.
375
+ By default a local mitmproxy forward proxy routes Sference models to
376
+ ``api.sference.com`` (native ``/v1/messages``, body untranslated) while
377
+ Claude Code's first-party detection stays on — Sference models appear in
378
+ the ``/model`` picker and real Claude models pass through to Anthropic.
379
+ ``--no-anthropic`` switches to the direct env-var mode (everything to one
380
+ Sference model). Unknown options and trailing args are forwarded to
381
+ Claude Code, e.g. ``sference launch claude -p "fix the bug"``.
356
382
  """
357
383
  from sference_cli.main import _ensure_api_credential, _read_token
358
384
 
@@ -365,13 +391,50 @@ def register_launch_commands(app: typer.Typer) -> None:
365
391
  if forwarded and forwarded[0] == "--":
366
392
  forwarded = forwarded[1:]
367
393
 
368
- launch_claude_code(
394
+ resolved_base = resolve_api_base_url(base_url)
395
+
396
+ if no_anthropic:
397
+ launch_claude_code(
398
+ api_key=api_key,
399
+ base_url=resolved_base,
400
+ model=resolve_launch_model(model),
401
+ enable_tool_search=enable_tool_search,
402
+ claude_args=forwarded,
403
+ dry_run=dry_run,
404
+ )
405
+ return
406
+
407
+ if enable_tool_search:
408
+ typer.echo(
409
+ "note: --enable-tool-search is a no-op in proxy mode (first-party "
410
+ "detection is on, so tool search already works).",
411
+ err=True,
412
+ )
413
+
414
+ # Proxy mode: resolve the routable model set.
415
+ if models:
416
+ model_set = {m.strip() for m in models.split(",") if m.strip()}
417
+ elif model:
418
+ model_set = {model}
419
+ else:
420
+ typer.echo(f"Fetching routable models from {resolved_base}/v1/models ...")
421
+ try:
422
+ model_set = fetch_sference_models(resolved_base, api_key)
423
+ except (urllib.error.URLError, urllib.error.HTTPError, json.JSONDecodeError, KeyError) as e:
424
+ typer.echo(f"ERROR: could not fetch models from {resolved_base}/v1/models: {e}", err=True)
425
+ typer.echo("Pass --models or --model explicitly to bypass the lookup.", err=True)
426
+ raise typer.Exit(code=1) from None
427
+ if not model_set:
428
+ typer.echo("ERROR: /v1/models returned no text-generation models for this account.", err=True)
429
+ raise typer.Exit(code=1)
430
+
431
+ launch_claude_via_proxy(
369
432
  api_key=api_key,
370
- base_url=resolve_api_base_url(base_url),
371
- model=resolve_launch_model(model),
372
- enable_tool_search=enable_tool_search,
433
+ base_url=resolved_base,
434
+ models=model_set,
373
435
  claude_args=forwarded,
374
436
  dry_run=dry_run,
437
+ proxy_port=proxy_port,
375
438
  )
376
439
 
377
440
  @launch_app.command(
@@ -0,0 +1,252 @@
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
+ MITM_CA_CERT = Path.home() / ".mitmproxy" / "mitmproxy-ca-cert.pem"
37
+ DEFAULT_FLOW_DETAIL = "1"
38
+
39
+
40
+ def _normalize_base_url(raw: str) -> str:
41
+ """Return the API origin (scheme + netloc), accepting either
42
+ https://api.sference.com or https://api.sference.com/v1."""
43
+ raw = raw.rstrip("/")
44
+ if raw.endswith("/v1"):
45
+ raw = raw[: -len("/v1")]
46
+ return raw
47
+
48
+
49
+ def fetch_sference_models(base_url: str, api_key: str) -> set[str]:
50
+ """Pull the live text-generation model list from GET {base_url}/v1/models.
51
+
52
+ Keeps the router in sync with what the account can serve, so a
53
+ deprecated/renamed model never slips through and 400s mid-session.
54
+ """
55
+ api_root = _normalize_base_url(base_url) + "/v1"
56
+ req = urllib.request.Request(
57
+ f"{api_root}/models",
58
+ headers={"Authorization": f"Bearer {api_key}"},
59
+ )
60
+ with urllib.request.urlopen(req, timeout=15) as resp:
61
+ payload = json.loads(resp.read().decode("utf-8"))
62
+ return {
63
+ item["id"]
64
+ for item in payload.get("data", [])
65
+ if isinstance(item, dict)
66
+ and item.get("id")
67
+ and item.get("modality", "text_generation") == "text_generation"
68
+ }
69
+
70
+
71
+ def pick_free_port() -> int:
72
+ """Allocate an ephemeral port the OS guarantees is free at bind time."""
73
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
74
+ s.bind(("127.0.0.1", 0))
75
+ return s.getsockname()[1]
76
+
77
+
78
+ def port_in_use(port: int) -> bool:
79
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
80
+ s.settimeout(0.5)
81
+ return s.connect_ex(("127.0.0.1", port)) == 0
82
+
83
+
84
+ def mitmproxy_available() -> bool:
85
+ """mitmproxy is installed as a separate ``uv tool`` → ``mitmdump`` is on PATH."""
86
+ return shutil.which("mitmdump") is not None
87
+
88
+
89
+ def _extract_addon_files() -> tuple[Path, Path]:
90
+ """Extract the addon + routing helpers to a temp dir; return (tmpdir, addon_path).
91
+
92
+ Both files live in the same dir so the addon can ``from _proxy_routing import …``
93
+ via a sibling path (mitmproxy's venv has no ``sference_cli``).
94
+ """
95
+ res = importlib.resources.files("sference_cli")
96
+ addon_src = (res / "_proxy_addon.py").read_text(encoding="utf-8")
97
+ routing_src = (res / "_proxy_routing.py").read_text(encoding="utf-8")
98
+ tmpdir = Path(tempfile.mkdtemp(prefix="sference_proxy_"))
99
+ (tmpdir / "_proxy_routing.py").write_text(routing_src, encoding="utf-8")
100
+ addon_path = tmpdir / "_proxy_addon.py"
101
+ addon_path.write_text(addon_src, encoding="utf-8")
102
+ return tmpdir, addon_path
103
+
104
+
105
+ def _wait_for_mitmproxy(proc: subprocess.Popen, port: int, log_file: Path) -> bool:
106
+ """Wait for mitmproxy to bind the port; return False if it died."""
107
+ for _ in range(40):
108
+ if proc.poll() is not None:
109
+ typer.echo(f"ERROR: mitmproxy exited immediately (code {proc.returncode}).", err=True)
110
+ typer.echo(f"See {log_file} for the error.", err=True)
111
+ return False
112
+ if port_in_use(port):
113
+ return True
114
+ time.sleep(0.25)
115
+ typer.echo(f"ERROR: mitmproxy did not start listening on {port}. See {log_file}.", err=True)
116
+ return False
117
+
118
+
119
+ def _wait_for_ca_cert(timeout: float = 15.0) -> bool:
120
+ """mitmproxy generates its CA on first run; wait for it to appear."""
121
+ if MITM_CA_CERT.exists():
122
+ return True
123
+ deadline = time.monotonic() + timeout
124
+ while time.monotonic() < deadline:
125
+ if MITM_CA_CERT.exists():
126
+ return True
127
+ time.sleep(0.5)
128
+ return False
129
+
130
+
131
+ def launch_claude_via_proxy(
132
+ *,
133
+ api_key: str,
134
+ base_url: str,
135
+ models: set[str],
136
+ claude_args: list[str],
137
+ dry_run: bool,
138
+ proxy_port: Optional[int] = None,
139
+ log_file: Optional[str] = None,
140
+ ) -> None:
141
+ """Start mitmproxy, then exec ``claude`` pointed at it. Blocks until claude exits."""
142
+ if not mitmproxy_available():
143
+ typer.echo(
144
+ "mitmproxy not found. Install it with: uv tool install mitmproxy\n"
145
+ "Or run Claude Code without the proxy: sference launch claude --no-anthropic",
146
+ err=True,
147
+ )
148
+ raise typer.Exit(code=1)
149
+
150
+ port = proxy_port or pick_free_port()
151
+ sference_base = _normalize_base_url(base_url)
152
+ log_path = Path(log_file) if log_file else Path(tempfile.gettempdir()) / "sference_claude_proxy.log"
153
+
154
+ claude_bin = shutil.which("claude")
155
+ if claude_bin is None:
156
+ typer.echo(
157
+ "Claude Code CLI not found on PATH.\n"
158
+ "Install from https://docs.anthropic.com/en/docs/claude-code "
159
+ "and ensure the `claude` command is available.",
160
+ err=True,
161
+ )
162
+ raise typer.Exit(code=1)
163
+
164
+ if dry_run:
165
+ typer.echo(f"mitmproxy: mitmdump on 127.0.0.1:{port} (log: {log_path})")
166
+ typer.echo(f"Sference API: {sference_base}")
167
+ typer.echo(f"Models ({len(models)}): {', '.join(sorted(models))}")
168
+ typer.echo("apiKey: <redacted> (x-api-key, injected at launch)")
169
+ typer.echo(f"HTTPS_PROXY=http://127.0.0.1:{port}")
170
+ typer.echo(f"NODE_EXTRA_CA_CERTS={MITM_CA_CERT}")
171
+ typer.echo("ANTHROPIC_BASE_URL=<unset> (first-party detection stays on)")
172
+ typer.echo(f"command: {claude_bin} {' '.join(claude_args)}".rstrip())
173
+ return
174
+
175
+ tmpdir, addon_path = _extract_addon_files()
176
+ mitm_env = {
177
+ **os.environ,
178
+ "SFERENCE_API_KEY": api_key,
179
+ "SFERENCE_BASE_URL": sference_base,
180
+ "SFERENCE_PROXY_MODELS": json.dumps(sorted(models)),
181
+ }
182
+ mitm_cmd = [
183
+ shutil.which("mitmdump"),
184
+ "-p", str(port),
185
+ "--listen-host", "127.0.0.1",
186
+ "--set", f"flow_detail={os.environ.get('FLOW_DETAIL', DEFAULT_FLOW_DETAIL)}",
187
+ "-s", str(addon_path),
188
+ ]
189
+
190
+ log_fh = open(log_path, "w") # truncate: never tail stale lines from a prior run
191
+ mitm_proc = subprocess.Popen(
192
+ mitm_cmd, stdout=log_fh, stderr=subprocess.STDOUT, env=mitm_env
193
+ )
194
+
195
+ claude_proc: Optional[subprocess.Popen] = None
196
+
197
+ def _cleanup(*_args: object) -> None:
198
+ if claude_proc is not None:
199
+ try:
200
+ claude_proc.terminate()
201
+ except Exception:
202
+ pass
203
+ if mitm_proc.poll() is None:
204
+ mitm_proc.terminate()
205
+ try:
206
+ mitm_proc.wait(timeout=5)
207
+ except Exception:
208
+ mitm_proc.kill()
209
+ log_fh.close()
210
+ shutil.rmtree(tmpdir, ignore_errors=True)
211
+
212
+ # Install signal handlers so Ctrl-C tears down both children (Unix only).
213
+ if sys.platform != "win32":
214
+ for sig in (signal.SIGINT, signal.SIGTERM):
215
+ signal.signal(sig, lambda *_a: (_cleanup(), sys.exit(130))[1])
216
+
217
+ try:
218
+ typer.echo(f"Starting mitmproxy on 127.0.0.1:{port} (log: {log_path})...")
219
+ if not _wait_for_mitmproxy(mitm_proc, port, log_path):
220
+ raise typer.Exit(code=1)
221
+
222
+ if not _wait_for_ca_cert():
223
+ typer.echo(
224
+ f"ERROR: mitmproxy CA cert not found at {MITM_CA_CERT}. "
225
+ "Run `mitmdump` once standalone to generate it.",
226
+ err=True,
227
+ )
228
+ raise typer.Exit(code=1)
229
+
230
+ typer.echo(f"Proxy ready. Sference models in /model picker; Claude models pass through.")
231
+ typer.echo(f" HTTPS_PROXY=http://127.0.0.1:{port}")
232
+ typer.echo(f" NODE_EXTRA_CA_CERTS={MITM_CA_CERT}")
233
+ typer.echo("Launching Claude Code...")
234
+
235
+ claude_env = os.environ.copy()
236
+ claude_env["HTTPS_PROXY"] = f"http://127.0.0.1:{port}"
237
+ claude_env["NODE_EXTRA_CA_CERTS"] = str(MITM_CA_CERT)
238
+ claude_env.pop("ANTHROPIC_BASE_URL", None) # keep first-party detection on
239
+
240
+ claude_proc = subprocess.Popen(
241
+ [claude_bin, *claude_args],
242
+ env=claude_env,
243
+ stdin=sys.stdin,
244
+ stdout=sys.stdout,
245
+ stderr=sys.stderr,
246
+ )
247
+ claude_proc.wait()
248
+ exit_code = claude_proc.returncode
249
+ finally:
250
+ _cleanup()
251
+
252
+ raise typer.Exit(code=exit_code)
File without changes
File without changes