sference-cli 0.1.8__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {sference_cli-0.1.8 → sference_cli-0.2.0}/PKG-INFO +21 -8
- {sference_cli-0.1.8 → sference_cli-0.2.0}/README.md +19 -6
- {sference_cli-0.1.8 → sference_cli-0.2.0}/pyproject.toml +2 -2
- sference_cli-0.2.0/sference_cli/_proxy_addon.py +134 -0
- sference_cli-0.2.0/sference_cli/_proxy_routing.py +223 -0
- {sference_cli-0.1.8 → sference_cli-0.2.0}/sference_cli/launch.py +74 -11
- sference_cli-0.2.0/sference_cli/proxy.py +265 -0
- {sference_cli-0.1.8 → sference_cli-0.2.0}/.gitignore +0 -0
- {sference_cli-0.1.8 → sference_cli-0.2.0}/LICENSE +0 -0
- {sference_cli-0.1.8 → sference_cli-0.2.0}/sference_cli/__init__.py +0 -0
- {sference_cli-0.1.8 → sference_cli-0.2.0}/sference_cli/main.py +0 -0
- {sference_cli-0.1.8 → sference_cli-0.2.0}/sference_cli/stream_cache.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sference-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: sference command-line interface
|
|
5
5
|
Project-URL: Homepage, https://sference.com
|
|
6
6
|
Project-URL: Repository, https://github.com/s-ference/sference
|
|
@@ -21,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
21
21
|
Classifier: Programming Language :: Python :: 3.13
|
|
22
22
|
Classifier: Topic :: Utilities
|
|
23
23
|
Requires-Python: >=3.10
|
|
24
|
-
Requires-Dist: sference-sdk>=0.
|
|
24
|
+
Requires-Dist: sference-sdk>=0.2.0
|
|
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` |
|
|
130
|
-
| `sference launch claude --dry-run` | Print
|
|
131
|
-
| `sference launch claude --model
|
|
132
|
-
| `sference launch claude --
|
|
133
|
-
| `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
|
-
|
|
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` |
|
|
103
|
-
| `sference launch claude --dry-run` | Print
|
|
104
|
-
| `sference launch claude --model
|
|
105
|
-
| `sference launch claude --
|
|
106
|
-
| `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
|
-
|
|
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.
|
|
3
|
+
version = "0.2.0"
|
|
4
4
|
description = "sference command-line interface"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.10"
|
|
@@ -23,7 +23,7 @@ classifiers = [
|
|
|
23
23
|
]
|
|
24
24
|
dependencies = [
|
|
25
25
|
"typer>=0.24.1",
|
|
26
|
-
"sference-sdk>=0.
|
|
26
|
+
"sference-sdk>=0.2.0",
|
|
27
27
|
]
|
|
28
28
|
|
|
29
29
|
[project.urls]
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""mitmproxy addon: route Sference models to api.sference.com, pass Claude through.
|
|
2
|
+
|
|
3
|
+
Loaded by ``mitmdump -s <this file>``. Runs inside mitmproxy's isolated tool
|
|
4
|
+
venv, which does NOT contain ``sference_cli`` — so we import the pure routing
|
|
5
|
+
helpers via a sibling path (the launcher extracts this file and
|
|
6
|
+
``_proxy_routing.py`` to the same temp dir), not via ``from sference_cli…``.
|
|
7
|
+
|
|
8
|
+
Config comes from env (set by the launcher):
|
|
9
|
+
SFERENCE_PROXY_MODELS JSON list of routable catalog ids (text-generation)
|
|
10
|
+
SFERENCE_API_KEY Sference API key (sent as x-api-key)
|
|
11
|
+
SFERENCE_BASE_URL Sference API origin, e.g. https://api.sference.com
|
|
12
|
+
|
|
13
|
+
Routing is a pure URL + auth rewrite; the request body passes through
|
|
14
|
+
byte-for-byte (Sference has a native /v1/messages endpoint) and the response is
|
|
15
|
+
already native Anthropic — no translation in either direction.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import sys
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from mitmproxy import ctx, http
|
|
26
|
+
|
|
27
|
+
# Sibling import: _proxy_routing.py sits next to this file in the temp dir.
|
|
28
|
+
sys.path.insert(0, os.path.dirname(str(Path(__file__).resolve())))
|
|
29
|
+
from _proxy_routing import ( # noqa: E402
|
|
30
|
+
BOOTSTRAP,
|
|
31
|
+
PASSTHROUGH,
|
|
32
|
+
SFERENCE,
|
|
33
|
+
decide_routing,
|
|
34
|
+
inject_models_into_bootstrap,
|
|
35
|
+
parse_models_env,
|
|
36
|
+
rewrite_request_for_sference,
|
|
37
|
+
strip_unsigned_thinking_blocks,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
SFERENCE_BASE_URL = os.environ.get("SFERENCE_BASE_URL", "https://api.sference.com").rstrip("/")
|
|
41
|
+
SFERENCE_API_KEY = os.environ.get("SFERENCE_API_KEY", "")
|
|
42
|
+
SFERENCE_MODELS = parse_models_env(os.environ.get("SFERENCE_PROXY_MODELS", ""))
|
|
43
|
+
|
|
44
|
+
# flow.id -> original model (for response handling — currently a no-op since
|
|
45
|
+
# the Sference response is already native Anthropic, but kept for clarity).
|
|
46
|
+
_sference_flows: dict[str, str] = {}
|
|
47
|
+
# flow.ids of bootstrap GETs whose response we post-process.
|
|
48
|
+
_bootstrap_flows: set[str] = set()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class SferenceRouter:
|
|
52
|
+
def request(self, flow: "http.HTTPFlow") -> None:
|
|
53
|
+
if flow.request is None:
|
|
54
|
+
return
|
|
55
|
+
host = flow.request.pretty_host
|
|
56
|
+
method = flow.request.method
|
|
57
|
+
path = flow.request.path
|
|
58
|
+
|
|
59
|
+
body: object = None
|
|
60
|
+
if method == "POST":
|
|
61
|
+
try:
|
|
62
|
+
body = json.loads(flow.request.get_text())
|
|
63
|
+
except Exception:
|
|
64
|
+
body = None
|
|
65
|
+
|
|
66
|
+
decision = decide_routing(host, method, path, body, SFERENCE_MODELS)
|
|
67
|
+
if decision == PASSTHROUGH:
|
|
68
|
+
# Anthropic rejects thinking blocks whose signature it can't verify,
|
|
69
|
+
# and Sference emits an empty one — so a session that switched away
|
|
70
|
+
# from a Sference model replays unsignable history and 400s. Claude
|
|
71
|
+
# Code recovers by stripping and resending; do it here instead and
|
|
72
|
+
# save the wasted upload + round-trip. Sference-bound requests keep
|
|
73
|
+
# the blocks (byte-for-byte passthrough).
|
|
74
|
+
if (
|
|
75
|
+
host == "api.anthropic.com"
|
|
76
|
+
and method == "POST"
|
|
77
|
+
and "/v1/messages" in (path or "")
|
|
78
|
+
):
|
|
79
|
+
body, dropped = strip_unsigned_thinking_blocks(body)
|
|
80
|
+
if dropped:
|
|
81
|
+
# set_text() recomputes content-length itself (correctly for
|
|
82
|
+
# any content-encoding); do NOT touch the header afterwards.
|
|
83
|
+
flow.request.set_text(json.dumps(body))
|
|
84
|
+
ctx.log.info(
|
|
85
|
+
f"sference: stripped {dropped} unsigned thinking block(s) "
|
|
86
|
+
"from Anthropic-bound request"
|
|
87
|
+
)
|
|
88
|
+
return
|
|
89
|
+
if decision == BOOTSTRAP:
|
|
90
|
+
_bootstrap_flows.add(flow.id)
|
|
91
|
+
return
|
|
92
|
+
# SFERENCE
|
|
93
|
+
model = body.get("model") if isinstance(body, dict) else None
|
|
94
|
+
ctx.log.info(f"sference: routing model={model!r} -> Sference")
|
|
95
|
+
_sference_flows[flow.id] = str(model)
|
|
96
|
+
new_url, set_headers, remove_headers = rewrite_request_for_sference(
|
|
97
|
+
flow.request.url, SFERENCE_BASE_URL, SFERENCE_API_KEY
|
|
98
|
+
)
|
|
99
|
+
flow.request.url = new_url
|
|
100
|
+
for key, value in set_headers.items():
|
|
101
|
+
flow.request.headers[key] = value
|
|
102
|
+
for key in remove_headers:
|
|
103
|
+
flow.request.headers.pop(key, None)
|
|
104
|
+
|
|
105
|
+
def response(self, flow: "http.HTTPFlow") -> None:
|
|
106
|
+
if flow.response is None:
|
|
107
|
+
return
|
|
108
|
+
if flow.id in _bootstrap_flows:
|
|
109
|
+
_bootstrap_flows.discard(flow.id)
|
|
110
|
+
self._inject_models(flow)
|
|
111
|
+
return
|
|
112
|
+
if flow.id in _sference_flows:
|
|
113
|
+
_sference_flows.pop(flow.id)
|
|
114
|
+
# Native Anthropic response: pass through untouched.
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
def _inject_models(self, flow: "http.HTTPFlow") -> None:
|
|
118
|
+
if flow.response.status_code != 200:
|
|
119
|
+
return
|
|
120
|
+
try:
|
|
121
|
+
body = json.loads(flow.response.get_text())
|
|
122
|
+
except Exception:
|
|
123
|
+
return
|
|
124
|
+
before = len(body.get("additional_model_options", []) if isinstance(body, dict) else [])
|
|
125
|
+
body = inject_models_into_bootstrap(body, SFERENCE_MODELS)
|
|
126
|
+
flow.response.set_text(json.dumps(body))
|
|
127
|
+
# Body length changed; drop stale framing so mitmproxy recomputes it.
|
|
128
|
+
flow.response.headers.pop("content-length", None)
|
|
129
|
+
flow.response.headers.pop("Content-Length", None)
|
|
130
|
+
after = len(body.get("additional_model_options", []) if isinstance(body, dict) else [])
|
|
131
|
+
ctx.log.info(f"sference: bootstrap injected {after - before} model(s) into /model picker")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
addons = [SferenceRouter()]
|
|
@@ -0,0 +1,223 @@
|
|
|
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
|
+
def inject_models_into_bootstrap(body: Any, sference_models: set[str]) -> Any:
|
|
185
|
+
"""Append Sference models to a bootstrap response's ``additional_model_options``.
|
|
186
|
+
|
|
187
|
+
Claude Code populates its ``/model`` picker from built-ins plus this array;
|
|
188
|
+
each entry's ``model`` is sent verbatim on ``/v1/messages``, which the addon
|
|
189
|
+
then routes to Sference. Best-effort: if the shape is wrong, return the body
|
|
190
|
+
unchanged rather than crashing (the picker is a nicety, not a requirement).
|
|
191
|
+
"""
|
|
192
|
+
if not isinstance(body, dict):
|
|
193
|
+
return body
|
|
194
|
+
options = body.get("additional_model_options")
|
|
195
|
+
if not isinstance(options, list):
|
|
196
|
+
options = []
|
|
197
|
+
existing = {o.get("model") for o in options if isinstance(o, dict)}
|
|
198
|
+
for model in sorted(sference_models):
|
|
199
|
+
if model in existing:
|
|
200
|
+
continue
|
|
201
|
+
options.append(
|
|
202
|
+
{
|
|
203
|
+
"model": model,
|
|
204
|
+
"name": f"[Sference] {model}",
|
|
205
|
+
"description": "Sference (routed via local proxy)",
|
|
206
|
+
"disabled_reason": None,
|
|
207
|
+
}
|
|
208
|
+
)
|
|
209
|
+
body["additional_model_options"] = options
|
|
210
|
+
return body
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def parse_models_env(raw: str) -> set[str]:
|
|
214
|
+
"""Parse the ``SFERENCE_PROXY_MODELS`` env var (JSON list) into a set."""
|
|
215
|
+
if not raw:
|
|
216
|
+
return set()
|
|
217
|
+
try:
|
|
218
|
+
data = json.loads(raw)
|
|
219
|
+
except json.JSONDecodeError:
|
|
220
|
+
return set()
|
|
221
|
+
if isinstance(data, list):
|
|
222
|
+
return {str(m) for m in data if isinstance(m, str) and m}
|
|
223
|
+
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
|
|
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=
|
|
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
|
|
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
|
|
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
|
-
|
|
354
|
-
|
|
355
|
-
|
|
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
|
-
|
|
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=
|
|
371
|
-
|
|
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,265 @@
|
|
|
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_models(base_url: str, api_key: str) -> set[str]:
|
|
55
|
+
"""Pull the live text-generation model list from GET {base_url}/v1/models.
|
|
56
|
+
|
|
57
|
+
Keeps the router in sync with what the account can serve, so a
|
|
58
|
+
deprecated/renamed model never slips through and 400s mid-session.
|
|
59
|
+
"""
|
|
60
|
+
api_root = _normalize_base_url(base_url) + "/v1"
|
|
61
|
+
req = urllib.request.Request(
|
|
62
|
+
f"{api_root}/models",
|
|
63
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
64
|
+
)
|
|
65
|
+
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
66
|
+
payload = json.loads(resp.read().decode("utf-8"))
|
|
67
|
+
return {
|
|
68
|
+
item["id"]
|
|
69
|
+
for item in payload.get("data", [])
|
|
70
|
+
if isinstance(item, dict)
|
|
71
|
+
and item.get("id")
|
|
72
|
+
and item.get("modality", "text_generation") == "text_generation"
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def pick_free_port() -> int:
|
|
77
|
+
"""Allocate an ephemeral port the OS guarantees is free at bind time."""
|
|
78
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
79
|
+
s.bind(("127.0.0.1", 0))
|
|
80
|
+
return s.getsockname()[1]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def port_in_use(port: int) -> bool:
|
|
84
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
85
|
+
s.settimeout(0.5)
|
|
86
|
+
return s.connect_ex(("127.0.0.1", port)) == 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def mitmproxy_available() -> bool:
|
|
90
|
+
"""mitmproxy is installed as a separate ``uv tool`` → ``mitmdump`` is on PATH."""
|
|
91
|
+
return shutil.which("mitmdump") is not None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _extract_addon_files() -> tuple[Path, Path]:
|
|
95
|
+
"""Extract the addon + routing helpers to a temp dir; return (tmpdir, addon_path).
|
|
96
|
+
|
|
97
|
+
Both files live in the same dir so the addon can ``from _proxy_routing import …``
|
|
98
|
+
via a sibling path (mitmproxy's venv has no ``sference_cli``).
|
|
99
|
+
"""
|
|
100
|
+
res = importlib.resources.files("sference_cli")
|
|
101
|
+
addon_src = (res / "_proxy_addon.py").read_text(encoding="utf-8")
|
|
102
|
+
routing_src = (res / "_proxy_routing.py").read_text(encoding="utf-8")
|
|
103
|
+
tmpdir = Path(tempfile.mkdtemp(prefix="sference_proxy_"))
|
|
104
|
+
(tmpdir / "_proxy_routing.py").write_text(routing_src, encoding="utf-8")
|
|
105
|
+
addon_path = tmpdir / "_proxy_addon.py"
|
|
106
|
+
addon_path.write_text(addon_src, encoding="utf-8")
|
|
107
|
+
return tmpdir, addon_path
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _wait_for_mitmproxy(proc: subprocess.Popen, port: int, log_file: Path) -> bool:
|
|
111
|
+
"""Wait for mitmproxy to bind the port; return False if it died."""
|
|
112
|
+
for _ in range(40):
|
|
113
|
+
if proc.poll() is not None:
|
|
114
|
+
typer.echo(f"ERROR: mitmproxy exited immediately (code {proc.returncode}).", err=True)
|
|
115
|
+
typer.echo(f"See {log_file} for the error.", err=True)
|
|
116
|
+
return False
|
|
117
|
+
if port_in_use(port):
|
|
118
|
+
return True
|
|
119
|
+
time.sleep(0.25)
|
|
120
|
+
typer.echo(f"ERROR: mitmproxy did not start listening on {port}. See {log_file}.", err=True)
|
|
121
|
+
return False
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _wait_for_ca_cert(timeout: float = 15.0) -> bool:
|
|
125
|
+
"""mitmproxy generates its CA on first run; wait for it to appear."""
|
|
126
|
+
if MITM_CA_CERT.exists():
|
|
127
|
+
return True
|
|
128
|
+
deadline = time.monotonic() + timeout
|
|
129
|
+
while time.monotonic() < deadline:
|
|
130
|
+
if MITM_CA_CERT.exists():
|
|
131
|
+
return True
|
|
132
|
+
time.sleep(0.5)
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def launch_claude_via_proxy(
|
|
137
|
+
*,
|
|
138
|
+
api_key: str,
|
|
139
|
+
base_url: str,
|
|
140
|
+
models: set[str],
|
|
141
|
+
claude_args: list[str],
|
|
142
|
+
dry_run: bool,
|
|
143
|
+
proxy_port: Optional[int] = None,
|
|
144
|
+
log_file: Optional[str] = None,
|
|
145
|
+
) -> None:
|
|
146
|
+
"""Start mitmproxy, then exec ``claude`` pointed at it. Blocks until claude exits."""
|
|
147
|
+
if not mitmproxy_available():
|
|
148
|
+
typer.echo(
|
|
149
|
+
"mitmproxy not found. Install it with: uv tool install mitmproxy\n"
|
|
150
|
+
"Or run Claude Code without the proxy: sference launch claude --no-anthropic",
|
|
151
|
+
err=True,
|
|
152
|
+
)
|
|
153
|
+
raise typer.Exit(code=1)
|
|
154
|
+
|
|
155
|
+
port = proxy_port or pick_free_port()
|
|
156
|
+
sference_base = _normalize_base_url(base_url)
|
|
157
|
+
log_path = Path(log_file) if log_file else DEFAULT_LOG_FILE
|
|
158
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
159
|
+
|
|
160
|
+
claude_bin = shutil.which("claude")
|
|
161
|
+
if claude_bin is None:
|
|
162
|
+
typer.echo(
|
|
163
|
+
"Claude Code CLI not found on PATH.\n"
|
|
164
|
+
"Install from https://docs.anthropic.com/en/docs/claude-code "
|
|
165
|
+
"and ensure the `claude` command is available.",
|
|
166
|
+
err=True,
|
|
167
|
+
)
|
|
168
|
+
raise typer.Exit(code=1)
|
|
169
|
+
|
|
170
|
+
if dry_run:
|
|
171
|
+
typer.echo(f"mitmproxy: mitmdump on 127.0.0.1:{port} (log: {log_path})")
|
|
172
|
+
typer.echo(f"Sference API: {sference_base}")
|
|
173
|
+
typer.echo(f"Models ({len(models)}): {', '.join(sorted(models))}")
|
|
174
|
+
typer.echo("apiKey: <redacted> (x-api-key, injected at launch)")
|
|
175
|
+
typer.echo(f"HTTPS_PROXY=http://127.0.0.1:{port}")
|
|
176
|
+
typer.echo(f"NODE_EXTRA_CA_CERTS={MITM_CA_CERT}")
|
|
177
|
+
typer.echo("ANTHROPIC_BASE_URL=<unset> (first-party detection stays on)")
|
|
178
|
+
typer.echo(f"allow_hosts={build_allow_hosts_regex(sference_base)} (only these hosts are TLS-intercepted)")
|
|
179
|
+
typer.echo(f"command: {claude_bin} {' '.join(claude_args)}".rstrip())
|
|
180
|
+
return
|
|
181
|
+
|
|
182
|
+
tmpdir, addon_path = _extract_addon_files()
|
|
183
|
+
mitm_env = {
|
|
184
|
+
**os.environ,
|
|
185
|
+
"SFERENCE_API_KEY": api_key,
|
|
186
|
+
"SFERENCE_BASE_URL": sference_base,
|
|
187
|
+
"SFERENCE_PROXY_MODELS": json.dumps(sorted(models)),
|
|
188
|
+
}
|
|
189
|
+
# Scope TLS interception to just the hosts we route. Without this, every
|
|
190
|
+
# tool Claude Code spawns (Bash → curl, gh, …) also goes through the proxy
|
|
191
|
+
# and fails TLS validation unless it trusts the mitmproxy CA. allow_hosts
|
|
192
|
+
# makes non-matching hosts pass through as raw TCP — no CA involvement.
|
|
193
|
+
allow_hosts = build_allow_hosts_regex(sference_base)
|
|
194
|
+
mitm_cmd = [
|
|
195
|
+
shutil.which("mitmdump"),
|
|
196
|
+
"-p", str(port),
|
|
197
|
+
"--listen-host", "127.0.0.1",
|
|
198
|
+
"--set", f"flow_detail={os.environ.get('FLOW_DETAIL', DEFAULT_FLOW_DETAIL)}",
|
|
199
|
+
"--set", f"allow_hosts={allow_hosts}",
|
|
200
|
+
"-s", str(addon_path),
|
|
201
|
+
]
|
|
202
|
+
|
|
203
|
+
log_fh = open(log_path, "w") # truncate: never tail stale lines from a prior run
|
|
204
|
+
mitm_proc = subprocess.Popen(
|
|
205
|
+
mitm_cmd, stdout=log_fh, stderr=subprocess.STDOUT, env=mitm_env
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
claude_proc: Optional[subprocess.Popen] = None
|
|
209
|
+
|
|
210
|
+
def _cleanup(*_args: object) -> None:
|
|
211
|
+
if claude_proc is not None:
|
|
212
|
+
try:
|
|
213
|
+
claude_proc.terminate()
|
|
214
|
+
except Exception:
|
|
215
|
+
pass
|
|
216
|
+
if mitm_proc.poll() is None:
|
|
217
|
+
mitm_proc.terminate()
|
|
218
|
+
try:
|
|
219
|
+
mitm_proc.wait(timeout=5)
|
|
220
|
+
except Exception:
|
|
221
|
+
mitm_proc.kill()
|
|
222
|
+
log_fh.close()
|
|
223
|
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
224
|
+
|
|
225
|
+
# Install signal handlers so Ctrl-C tears down both children (Unix only).
|
|
226
|
+
if sys.platform != "win32":
|
|
227
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
228
|
+
signal.signal(sig, lambda *_a: (_cleanup(), sys.exit(130))[1])
|
|
229
|
+
|
|
230
|
+
try:
|
|
231
|
+
typer.echo(f"Starting mitmproxy on 127.0.0.1:{port} (log: {log_path})...")
|
|
232
|
+
if not _wait_for_mitmproxy(mitm_proc, port, log_path):
|
|
233
|
+
raise typer.Exit(code=1)
|
|
234
|
+
|
|
235
|
+
if not _wait_for_ca_cert():
|
|
236
|
+
typer.echo(
|
|
237
|
+
f"ERROR: mitmproxy CA cert not found at {MITM_CA_CERT}. "
|
|
238
|
+
"Run `mitmdump` once standalone to generate it.",
|
|
239
|
+
err=True,
|
|
240
|
+
)
|
|
241
|
+
raise typer.Exit(code=1)
|
|
242
|
+
|
|
243
|
+
typer.echo(f"Proxy ready. Sference models in /model picker; Claude models pass through.")
|
|
244
|
+
typer.echo(f" HTTPS_PROXY=http://127.0.0.1:{port}")
|
|
245
|
+
typer.echo(f" NODE_EXTRA_CA_CERTS={MITM_CA_CERT}")
|
|
246
|
+
typer.echo("Launching Claude Code...")
|
|
247
|
+
|
|
248
|
+
claude_env = os.environ.copy()
|
|
249
|
+
claude_env["HTTPS_PROXY"] = f"http://127.0.0.1:{port}"
|
|
250
|
+
claude_env["NODE_EXTRA_CA_CERTS"] = str(MITM_CA_CERT)
|
|
251
|
+
claude_env.pop("ANTHROPIC_BASE_URL", None) # keep first-party detection on
|
|
252
|
+
|
|
253
|
+
claude_proc = subprocess.Popen(
|
|
254
|
+
[claude_bin, *claude_args],
|
|
255
|
+
env=claude_env,
|
|
256
|
+
stdin=sys.stdin,
|
|
257
|
+
stdout=sys.stdout,
|
|
258
|
+
stderr=sys.stderr,
|
|
259
|
+
)
|
|
260
|
+
claude_proc.wait()
|
|
261
|
+
exit_code = claude_proc.returncode
|
|
262
|
+
finally:
|
|
263
|
+
_cleanup()
|
|
264
|
+
|
|
265
|
+
raise typer.Exit(code=exit_code)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|