sference-cli 0.1.6__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.6
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.6
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
  |---------|-------------|
@@ -160,7 +173,7 @@ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provid
160
173
 
161
174
  | Command | Description |
162
175
  |---------|-------------|
163
- | `sference responses create` | Create one response (`--model`, `--content`, optional `--wait`, `--poll-ms`, `--timeout-s`) |
176
+ | `sference responses create` | Create one response (`--model`, `--content`; `--background` submits async and returns immediately). The sync default blocks; if the server-side wait times out, the request is **cancelled** and the command fails — use `--background` + `sference responses result` for long requests |
164
177
  | `sference responses result` | Poll until terminal state (`--id`, `--poll-ms`) |
165
178
  | `sference responses tail` | Print completion events as JSONL via `GET /v1/responses/events` (optional `--stream-id` to scope to a stream; omit for non-stream completions). Flags: `--consumer`, `--from-latest`, `--no-checkpoint`, `--poll-ms` |
166
179
 
@@ -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
  |---------|-------------|
@@ -133,7 +146,7 @@ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provid
133
146
 
134
147
  | Command | Description |
135
148
  |---------|-------------|
136
- | `sference responses create` | Create one response (`--model`, `--content`, optional `--wait`, `--poll-ms`, `--timeout-s`) |
149
+ | `sference responses create` | Create one response (`--model`, `--content`; `--background` submits async and returns immediately). The sync default blocks; if the server-side wait times out, the request is **cancelled** and the command fails — use `--background` + `sference responses result` for long requests |
137
150
  | `sference responses result` | Poll until terminal state (`--id`, `--poll-ms`) |
138
151
  | `sference responses tail` | Print completion events as JSONL via `GET /v1/responses/events` (optional `--stream-id` to scope to a stream; omit for non-stream completions). Flags: `--consumer`, `--from-latest`, `--no-checkpoint`, `--poll-ms` |
139
152
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-cli"
3
- version = "0.1.6"
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.6",
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()