sference-cli 0.1.9__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.9 → sference_cli-0.2.0}/PKG-INFO +2 -2
- {sference_cli-0.1.9 → sference_cli-0.2.0}/pyproject.toml +2 -2
- {sference_cli-0.1.9 → sference_cli-0.2.0}/sference_cli/_proxy_addon.py +21 -0
- {sference_cli-0.1.9 → sference_cli-0.2.0}/sference_cli/_proxy_routing.py +97 -0
- {sference_cli-0.1.9 → sference_cli-0.2.0}/sference_cli/proxy.py +14 -1
- {sference_cli-0.1.9 → sference_cli-0.2.0}/.gitignore +0 -0
- {sference_cli-0.1.9 → sference_cli-0.2.0}/LICENSE +0 -0
- {sference_cli-0.1.9 → sference_cli-0.2.0}/README.md +0 -0
- {sference_cli-0.1.9 → sference_cli-0.2.0}/sference_cli/__init__.py +0 -0
- {sference_cli-0.1.9 → sference_cli-0.2.0}/sference_cli/launch.py +0 -0
- {sference_cli-0.1.9 → sference_cli-0.2.0}/sference_cli/main.py +0 -0
- {sference_cli-0.1.9 → 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
|
|
|
@@ -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]
|
|
@@ -34,6 +34,7 @@ from _proxy_routing import ( # noqa: E402
|
|
|
34
34
|
inject_models_into_bootstrap,
|
|
35
35
|
parse_models_env,
|
|
36
36
|
rewrite_request_for_sference,
|
|
37
|
+
strip_unsigned_thinking_blocks,
|
|
37
38
|
)
|
|
38
39
|
|
|
39
40
|
SFERENCE_BASE_URL = os.environ.get("SFERENCE_BASE_URL", "https://api.sference.com").rstrip("/")
|
|
@@ -64,6 +65,26 @@ class SferenceRouter:
|
|
|
64
65
|
|
|
65
66
|
decision = decide_routing(host, method, path, body, SFERENCE_MODELS)
|
|
66
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
|
+
)
|
|
67
88
|
return
|
|
68
89
|
if decision == BOOTSTRAP:
|
|
69
90
|
_bootstrap_flows.add(flow.id)
|
|
@@ -16,6 +16,7 @@ the response is already native Anthropic. No Anthropic↔OpenAI translation.
|
|
|
16
16
|
from __future__ import annotations
|
|
17
17
|
|
|
18
18
|
import json
|
|
19
|
+
import re
|
|
19
20
|
from typing import Any
|
|
20
21
|
from urllib.parse import urlsplit, urlunsplit
|
|
21
22
|
|
|
@@ -24,6 +25,46 @@ PASSTHROUGH = "passthrough" # leave untouched, goes to the real upstream
|
|
|
24
25
|
SFERENCE = "sference" # rewrite to the Sference /v1/messages endpoint
|
|
25
26
|
BOOTSTRAP = "bootstrap" # Claude Code /api/claude_cli/bootstrap — inject models
|
|
26
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
|
+
|
|
27
68
|
|
|
28
69
|
def decide_routing(
|
|
29
70
|
host: str,
|
|
@@ -51,6 +92,62 @@ def decide_routing(
|
|
|
51
92
|
return PASSTHROUGH
|
|
52
93
|
|
|
53
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
|
+
|
|
54
151
|
def _sference_origin(sference_base_url: str) -> str:
|
|
55
152
|
"""Normalize the Sference base URL to scheme + netloc (strip any ``/v1``).
|
|
56
153
|
|
|
@@ -33,8 +33,13 @@ from typing import Optional
|
|
|
33
33
|
|
|
34
34
|
import typer
|
|
35
35
|
|
|
36
|
+
from sference_cli._proxy_routing import build_allow_hosts_regex
|
|
37
|
+
|
|
36
38
|
MITM_CA_CERT = Path.home() / ".mitmproxy" / "mitmproxy-ca-cert.pem"
|
|
37
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"
|
|
38
43
|
|
|
39
44
|
|
|
40
45
|
def _normalize_base_url(raw: str) -> str:
|
|
@@ -149,7 +154,8 @@ def launch_claude_via_proxy(
|
|
|
149
154
|
|
|
150
155
|
port = proxy_port or pick_free_port()
|
|
151
156
|
sference_base = _normalize_base_url(base_url)
|
|
152
|
-
log_path = Path(log_file) if log_file else
|
|
157
|
+
log_path = Path(log_file) if log_file else DEFAULT_LOG_FILE
|
|
158
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
153
159
|
|
|
154
160
|
claude_bin = shutil.which("claude")
|
|
155
161
|
if claude_bin is None:
|
|
@@ -169,6 +175,7 @@ def launch_claude_via_proxy(
|
|
|
169
175
|
typer.echo(f"HTTPS_PROXY=http://127.0.0.1:{port}")
|
|
170
176
|
typer.echo(f"NODE_EXTRA_CA_CERTS={MITM_CA_CERT}")
|
|
171
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)")
|
|
172
179
|
typer.echo(f"command: {claude_bin} {' '.join(claude_args)}".rstrip())
|
|
173
180
|
return
|
|
174
181
|
|
|
@@ -179,11 +186,17 @@ def launch_claude_via_proxy(
|
|
|
179
186
|
"SFERENCE_BASE_URL": sference_base,
|
|
180
187
|
"SFERENCE_PROXY_MODELS": json.dumps(sorted(models)),
|
|
181
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)
|
|
182
194
|
mitm_cmd = [
|
|
183
195
|
shutil.which("mitmdump"),
|
|
184
196
|
"-p", str(port),
|
|
185
197
|
"--listen-host", "127.0.0.1",
|
|
186
198
|
"--set", f"flow_detail={os.environ.get('FLOW_DETAIL', DEFAULT_FLOW_DETAIL)}",
|
|
199
|
+
"--set", f"allow_hosts={allow_hosts}",
|
|
187
200
|
"-s", str(addon_path),
|
|
188
201
|
]
|
|
189
202
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|