sference-cli 0.3.2__tar.gz → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sference-cli
3
- Version: 0.3.2
3
+ Version: 0.4.0
4
4
  Summary: sference command-line interface
5
5
  Project-URL: Homepage, https://sference.com
6
6
  Project-URL: Repository, https://github.com/s-ference/sference
@@ -65,11 +65,13 @@ sference --help
65
65
 
66
66
  ## Authentication
67
67
 
68
- 1. **Interactive (browser):** `sference auth login` — opens the console login page, then prompts for an API key from **Console → API keys**.
69
- 2. **Non-interactive / CI:** `sference auth login --api-key 'sk_...'`
68
+ 1. **Interactive (browser):** `sference auth login` signs in with the OAuth 2.0 device flow (RFC 8628). The CLI opens the console approval page and shows a short code; confirm it matches, approve the device, and the CLI finishes on its own. No API key is involved. Pass `--no-browser` on a remote or headless machine to print the URL and code instead.
69
+ 2. **Non-interactive / CI:** `sference auth login --api-key 'sk_...'` saves an API key from **Console → API keys** without opening a browser.
70
70
  3. **Environment variable:** `SFERENCE_API_KEY` overrides the saved credential file.
71
71
 
72
- Credentials are stored in `~/.sference/credentials.json` unless `SFERENCE_API_KEY` is set.
72
+ Credentials are stored in `~/.sference/credentials.json` unless `SFERENCE_API_KEY` is set. A device login stores a 24 h access token and a 30 d rotating refresh token; the CLI refreshes the access token automatically when you run a command, and `sference launch claude` also refreshes it mid-session through its proxy. Codex, opencode, and Pi sessions run on the token issued at launch. Signed-in devices are listed, and can be revoked, under **Profile → Signed-in devices** in the console.
73
+
74
+ For local development, `--base-url` (or `SFERENCE_BASE_URL`) points the device flow at another API and `--console-url` (or `SFERENCE_CONSOLE_URL`) overrides the approval page the browser opens.
73
75
 
74
76
  Verify the current credential:
75
77
 
@@ -108,7 +110,8 @@ sference responses tail --stream-id <stream_id>
108
110
 
109
111
  | Variable | Purpose |
110
112
  |----------|---------|
111
- | `SFERENCE_API_KEY` | API key (or JWT); overrides `~/.sference/credentials.json` |
113
+ | `SFERENCE_API_KEY` | API key (or access token); overrides `~/.sference/credentials.json` |
114
+ | `SFERENCE_CONSOLE_URL` | Console URL the device-flow approval page opens on (default: server-provided) |
112
115
  | `SFERENCE_MODEL` | Default catalog model for `sference launch` (overrides built-in default) |
113
116
  | `SFERENCE_STREAM_CACHE` | Optional path to the stream resumable-cache file (default `~/.sference/stream_cache.json`) |
114
117
  | `SFERENCE_STREAM_CHECKPOINTS` | Optional path for **`responses tail`** event checkpoints (default `~/.sference/stream_checkpoints.json`) |
@@ -119,31 +122,25 @@ sference responses tail --stream-id <stream_id>
119
122
 
120
123
  | Command | Description |
121
124
  |---------|-------------|
122
- | `sference auth login` | Store an API key (optional `--api-key`, `--no-browser`) |
125
+ | `sference auth login` | Sign in with the browser device flow (`--no-browser` prints the URL and code; `--api-key` saves an API key for CI) |
123
126
  | `sference auth me` | Show current user (`--json` for machine-readable output) |
124
127
 
125
128
  ### Launch
126
129
 
127
- #### `sference launch claude` (default: transparent proxy)
130
+ #### `sference launch claude`
128
131
 
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.
132
+ `sference launch claude` points Claude Code at Sference's native `/v1/messages` endpoint via `ANTHROPIC_BASE_URL` and enables gateway model discovery: the live catalog is primed into Claude Code's picker cache before launch, so `/model` lists every Sference model the account can serve. No proxy, no mitmproxy.
130
133
 
131
134
  | Command | Description |
132
- |---------|-------------|
133
- | `sference launch claude` | 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) |
135
+ | --- | --- |
136
+ | `sference launch claude` | Launch Claude Code against Sference; catalog primed into `/model` |
137
+ | `sference launch claude --dry-run` | Print the env config + command without launching |
138
+ | `sference launch claude --model zai-org/GLM-5.2` | Pin a different default model |
139
+ | `sference launch claude --models a,b` | Override the primed picker set (default: live `GET /v1/models`) |
140
+ | `sference launch claude --enable-tool-search` | Set `ENABLE_TOOL_SEARCH=true` |
138
141
  | `sference launch claude -- --model zai-org/GLM-5.2 -p "hi"` | Forward Claude Code flags/args after `--` |
139
- | `sference launch claude --no-anthropic` | Disable the proxy; route everything directly to Sference via `ANTHROPIC_BASE_URL` (the previous behavior — no hybrid routing, no `/model` picker) |
140
- | `sference launch claude --no-anthropic --enable-tool-search` | Direct mode: set `ENABLE_TOOL_SEARCH=true` on a custom host |
141
-
142
- Proxy mode requires `mitmproxy` (`mitmdump` on `PATH`) and the [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code). The installer (`install.sh` / `install.ps1`) installs mitmproxy alongside the CLI; to add it to an existing install: `uv tool install mitmproxy`. If mitmproxy is missing, proxy mode errors with a `--no-anthropic` suggestion.
143
-
144
- > **Security note:** the proxy uses mitmproxy's local CA cert (`~/.mitmproxy/mitmproxy-ca-cert.pem`), scoped to the Claude Code process via `NODE_EXTRA_CA_CERTS` — it is **not** added to system trust. The CA can sign certs for any host; only the Claude Code process trusts it for this session.
145
142
 
146
- Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
143
+ Requires only the [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code). Device-flow credentials are refreshed at launch so long sessions start on a fresh 24 h token. `--no-anthropic` and `--proxy-port` are accepted as deprecated no-ops for older scripts.
147
144
 
148
145
  #### `sference launch pi`
149
146
 
@@ -38,11 +38,13 @@ sference --help
38
38
 
39
39
  ## Authentication
40
40
 
41
- 1. **Interactive (browser):** `sference auth login` — opens the console login page, then prompts for an API key from **Console → API keys**.
42
- 2. **Non-interactive / CI:** `sference auth login --api-key 'sk_...'`
41
+ 1. **Interactive (browser):** `sference auth login` signs in with the OAuth 2.0 device flow (RFC 8628). The CLI opens the console approval page and shows a short code; confirm it matches, approve the device, and the CLI finishes on its own. No API key is involved. Pass `--no-browser` on a remote or headless machine to print the URL and code instead.
42
+ 2. **Non-interactive / CI:** `sference auth login --api-key 'sk_...'` saves an API key from **Console → API keys** without opening a browser.
43
43
  3. **Environment variable:** `SFERENCE_API_KEY` overrides the saved credential file.
44
44
 
45
- Credentials are stored in `~/.sference/credentials.json` unless `SFERENCE_API_KEY` is set.
45
+ Credentials are stored in `~/.sference/credentials.json` unless `SFERENCE_API_KEY` is set. A device login stores a 24 h access token and a 30 d rotating refresh token; the CLI refreshes the access token automatically when you run a command, and `sference launch claude` also refreshes it mid-session through its proxy. Codex, opencode, and Pi sessions run on the token issued at launch. Signed-in devices are listed, and can be revoked, under **Profile → Signed-in devices** in the console.
46
+
47
+ For local development, `--base-url` (or `SFERENCE_BASE_URL`) points the device flow at another API and `--console-url` (or `SFERENCE_CONSOLE_URL`) overrides the approval page the browser opens.
46
48
 
47
49
  Verify the current credential:
48
50
 
@@ -81,7 +83,8 @@ sference responses tail --stream-id <stream_id>
81
83
 
82
84
  | Variable | Purpose |
83
85
  |----------|---------|
84
- | `SFERENCE_API_KEY` | API key (or JWT); overrides `~/.sference/credentials.json` |
86
+ | `SFERENCE_API_KEY` | API key (or access token); overrides `~/.sference/credentials.json` |
87
+ | `SFERENCE_CONSOLE_URL` | Console URL the device-flow approval page opens on (default: server-provided) |
85
88
  | `SFERENCE_MODEL` | Default catalog model for `sference launch` (overrides built-in default) |
86
89
  | `SFERENCE_STREAM_CACHE` | Optional path to the stream resumable-cache file (default `~/.sference/stream_cache.json`) |
87
90
  | `SFERENCE_STREAM_CHECKPOINTS` | Optional path for **`responses tail`** event checkpoints (default `~/.sference/stream_checkpoints.json`) |
@@ -92,31 +95,25 @@ sference responses tail --stream-id <stream_id>
92
95
 
93
96
  | Command | Description |
94
97
  |---------|-------------|
95
- | `sference auth login` | Store an API key (optional `--api-key`, `--no-browser`) |
98
+ | `sference auth login` | Sign in with the browser device flow (`--no-browser` prints the URL and code; `--api-key` saves an API key for CI) |
96
99
  | `sference auth me` | Show current user (`--json` for machine-readable output) |
97
100
 
98
101
  ### Launch
99
102
 
100
- #### `sference launch claude` (default: transparent proxy)
103
+ #### `sference launch claude`
101
104
 
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.
105
+ `sference launch claude` points Claude Code at Sference's native `/v1/messages` endpoint via `ANTHROPIC_BASE_URL` and enables gateway model discovery: the live catalog is primed into Claude Code's picker cache before launch, so `/model` lists every Sference model the account can serve. No proxy, no mitmproxy.
103
106
 
104
107
  | Command | Description |
105
- |---------|-------------|
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) |
108
+ | --- | --- |
109
+ | `sference launch claude` | Launch Claude Code against Sference; catalog primed into `/model` |
110
+ | `sference launch claude --dry-run` | Print the env config + command without launching |
111
+ | `sference launch claude --model zai-org/GLM-5.2` | Pin a different default model |
112
+ | `sference launch claude --models a,b` | Override the primed picker set (default: live `GET /v1/models`) |
113
+ | `sference launch claude --enable-tool-search` | Set `ENABLE_TOOL_SEARCH=true` |
111
114
  | `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
115
 
119
- Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
116
+ Requires only the [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code). Device-flow credentials are refreshed at launch so long sessions start on a fresh 24 h token. `--no-anthropic` and `--proxy-port` are accepted as deprecated no-ops for older scripts.
120
117
 
121
118
  #### `sference launch pi`
122
119
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-cli"
3
- version = "0.3.2"
3
+ version = "0.4.0"
4
4
  description = "sference command-line interface"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -0,0 +1,97 @@
1
+ """Claude Code gateway model discovery support for ``sference launch claude``.
2
+
3
+ Claude Code populates ``/model`` from built-ins plus gateway discovery results
4
+ (``GET {ANTHROPIC_BASE_URL}/v1/models``), cached to
5
+ ``~/.claude/cache/gateway-models.json``. Two client-side gates matter here:
6
+
7
+ * discovery only runs when ``CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1``
8
+ and the base URL is not api.anthropic.com;
9
+ * the live fetch keeps only ids containing "claude" or "anthropic" — Sference
10
+ catalog ids (``deepseek-ai/...``) match neither, so the fetch returns "0
11
+ usable models" and leaves the cache untouched. The picker then falls back to
12
+ whatever the cache already holds (verified on v2.1.302: the prime read is
13
+ gated only on the flag + base URL, not on credentials).
14
+
15
+ So the launcher primes the cache with the live catalog before exec'ing claude.
16
+ Stdlib-only so this module imports anywhere.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import tempfile
24
+ import time
25
+ import urllib.request
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ DISCOVERY_ENV_KEY = "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"
30
+
31
+ # Unknown (non-claude) model ids are believed to hold 200k tokens and
32
+ # auto-compact against that; Sference catalog models serve 1M. Disabling the
33
+ # unknown-model window enforcement lets CLAUDE_CODE_AUTO_COMPACT_WINDOW apply.
34
+ WINDOW_ENFORCEMENT_ENV_KEY = "CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT"
35
+ AUTO_COMPACT_WINDOW_ENV_KEY = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
36
+ DEFAULT_AUTO_COMPACT_WINDOW = "950000"
37
+
38
+
39
+ def fetch_sference_model_entries(base_url: str, api_key: str) -> list[dict[str, Any]]:
40
+ """Pull the live text-generation model entries from GET {base_url}/v1/models."""
41
+ api_root = base_url.rstrip("/") + "/v1"
42
+ req = urllib.request.Request(
43
+ f"{api_root}/models",
44
+ headers={"Authorization": f"Bearer {api_key}"},
45
+ )
46
+ with urllib.request.urlopen(req, timeout=15) as resp:
47
+ payload = json.loads(resp.read().decode("utf-8"))
48
+ return [
49
+ item
50
+ for item in payload.get("data", [])
51
+ if isinstance(item, dict) and item.get("id") and item.get("modality", "text_generation") == "text_generation"
52
+ ]
53
+
54
+
55
+ def picker_cache_path() -> Path:
56
+ """The discovery cache Claude Code primes its picker from (CLAUDE_CONFIG_DIR-aware)."""
57
+ config_dir = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
58
+ if config_dir:
59
+ return Path(config_dir) / "cache" / "gateway-models.json"
60
+ return Path.home() / ".claude" / "cache" / "gateway-models.json"
61
+
62
+
63
+ def _picker_entry(item: dict[str, Any]) -> dict[str, str]:
64
+ entry = {"id": str(item["id"])}
65
+ name = str(item.get("display_name") or item["id"])
66
+ entry["display_name"] = name if "sference" in name.lower() else f"{name} via Sference"
67
+ ctx = item.get("context_tokens")
68
+ if isinstance(ctx, int) and ctx > 0:
69
+ entry["description"] = f"Sference inference — {ctx // 1000}k context"
70
+ else:
71
+ entry["description"] = "Sference inference"
72
+ return entry
73
+
74
+
75
+ def prime_picker_cache(entries: list[dict[str, Any]], base_url: str) -> Path:
76
+ """Write the picker cache atomically (temp+rename, 0600): a Claude Code
77
+ starting mid-prime must never read a torn file."""
78
+ models = [_picker_entry(item) for item in entries]
79
+ body = {
80
+ "baseUrl": base_url.rstrip("/"),
81
+ "fetchedAt": int(time.time() * 1000),
82
+ "models": models,
83
+ }
84
+ path = picker_cache_path()
85
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
86
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".gateway-models-", suffix=".tmp")
87
+ try:
88
+ with os.fdopen(fd, "w", encoding="utf-8") as f: # mkstemp is already 0600
89
+ f.write(json.dumps(body) + "\n")
90
+ os.replace(tmp, path)
91
+ except BaseException:
92
+ try:
93
+ os.unlink(tmp)
94
+ except OSError:
95
+ pass
96
+ raise
97
+ return path
@@ -1,9 +1,8 @@
1
1
  """Device-flow (RFC 8628) client for ``sference auth login`` and token refresh.
2
2
 
3
- Stdlib-only (json, urllib, time) so this module imports in ANY venv — the
4
- mitmproxy addon (``_proxy_addon.py``) runs in mitmproxy's isolated tool venv
5
- without ``sference_cli`` installed and sibling-imports this file to refresh an
6
- expired device token mid-session. Keep it dependency-free.
3
+ Stdlib-only (json, urllib, time) so this module imports in ANY venv —
4
+ ``sference launch claude`` refreshes the 24 h device token at launch so long
5
+ sessions start on a fresh grant. Keep it dependency-free.
7
6
 
8
7
  Wire shapes come from the platform's device-flow endpoints (plan §4.3):
9
8
  POST /v1/oauth/device_code -> {device_code, user_code, verification_uri, expires_in, interval}
@@ -9,15 +9,27 @@ import re
9
9
  import shutil
10
10
  import subprocess
11
11
  import sys
12
+ import time
12
13
  import urllib.error
13
14
  from pathlib import Path
14
15
  from typing import Optional
15
16
 
16
17
  import typer
17
18
 
18
- from .proxy import fetch_sference_model_entries, fetch_sference_models, launch_claude_via_proxy
19
+ from ._discovery import (
20
+ AUTO_COMPACT_WINDOW_ENV_KEY,
21
+ DEFAULT_AUTO_COMPACT_WINDOW,
22
+ DISCOVERY_ENV_KEY,
23
+ WINDOW_ENFORCEMENT_ENV_KEY,
24
+ fetch_sference_model_entries,
25
+ prime_picker_cache,
26
+ )
19
27
 
20
28
  DEFAULT_LAUNCH_MODEL = "zai-org/GLM-5.2"
29
+ # Claude Code's default request shape is thinking-disabled, which GLM-5.3-served
30
+ # models 400 on (verified vs the API). Kimi-K3 tolerates it and is the stronger
31
+ # coding model — claude-only default; the other launchers keep GLM-5.2.
32
+ CLAUDE_DEFAULT_LAUNCH_MODEL = "moonshotai/Kimi-K3"
21
33
  DEFAULT_API_BASE_URL = "https://api.sference.com"
22
34
 
23
35
  # Thinking-effort variants stamped on Sference model entries in the opencode config.
@@ -42,14 +54,14 @@ def resolve_api_base_url(explicit: Optional[str]) -> str:
42
54
  return DEFAULT_API_BASE_URL
43
55
 
44
56
 
45
- def resolve_launch_model(explicit: Optional[str]) -> str:
57
+ def resolve_launch_model(explicit: Optional[str], *, default: str = DEFAULT_LAUNCH_MODEL) -> str:
46
58
  """Default catalog model for ``launch`` subcommands (--model overrides)."""
47
59
  if explicit:
48
60
  return explicit
49
61
  env = os.environ.get("SFERENCE_MODEL")
50
62
  if env and env.strip():
51
63
  return env.strip()
52
- return DEFAULT_LAUNCH_MODEL
64
+ return default
53
65
 
54
66
 
55
67
  def resolve_openai_base_url(explicit: Optional[str]) -> str:
@@ -93,6 +105,14 @@ def build_claude_env(
93
105
  env["ANTHROPIC_SMALL_FAST_MODEL"] = model
94
106
  # Claude Code prefers AUTH_TOKEN; drop API_KEY to avoid precedence confusion.
95
107
  env.pop("ANTHROPIC_API_KEY", None)
108
+ # Gateway model discovery: the picker reads the primed cache (written
109
+ # before exec) without any further credential.
110
+ env[DISCOVERY_ENV_KEY] = "1"
111
+ # Sference catalog ids are "unknown" to Claude Code, which would clamp
112
+ # them to a 200k window; let the auto-compact window below apply instead
113
+ # (catalog models serve 1M).
114
+ env[WINDOW_ENFORCEMENT_ENV_KEY] = "1"
115
+ env.setdefault(AUTO_COMPACT_WINDOW_ENV_KEY, DEFAULT_AUTO_COMPACT_WINDOW)
96
116
  if enable_tool_search:
97
117
  env["ENABLE_TOOL_SEARCH"] = "true"
98
118
  else:
@@ -100,11 +120,41 @@ def build_claude_env(
100
120
  return env
101
121
 
102
122
 
123
+ def build_claude_settings_json(env: dict[str, str]) -> str:
124
+ """The launcher's env block as a ``--settings`` JSON string.
125
+
126
+ Why not just the process env: a settings.json ``env`` entry (e.g. written
127
+ by sference-switch's ``claude on``) beats the process environment per key,
128
+ so a switch-managed machine would silently re-route the session through
129
+ the switch. ``--settings`` loads AFTER user settings and wins per key.
130
+
131
+ ANTHROPIC_AUTH_TOKEN is deliberately EXCLUDED: argv is visible to every
132
+ process on the machine (``ps``), and nothing in a settings.json env block
133
+ competes for that key — the process env carries it safely alone.
134
+ """
135
+ keys = (
136
+ "ANTHROPIC_BASE_URL",
137
+ "ANTHROPIC_MODEL",
138
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
139
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
140
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
141
+ "ANTHROPIC_DEFAULT_FABLE_MODEL",
142
+ "CLAUDE_CODE_SUBAGENT_MODEL",
143
+ "ANTHROPIC_SMALL_FAST_MODEL",
144
+ DISCOVERY_ENV_KEY,
145
+ WINDOW_ENFORCEMENT_ENV_KEY,
146
+ AUTO_COMPACT_WINDOW_ENV_KEY,
147
+ "ENABLE_TOOL_SEARCH",
148
+ )
149
+ return json.dumps({"env": {k: env[k] for k in keys if k in env}})
150
+
151
+
103
152
  def launch_claude_code(
104
153
  *,
105
154
  api_key: str,
106
155
  base_url: str,
107
156
  model: str,
157
+ model_entries: list[dict],
108
158
  enable_tool_search: bool,
109
159
  claude_args: list[str],
110
160
  dry_run: bool,
@@ -125,7 +175,8 @@ def launch_claude_code(
125
175
  model=model,
126
176
  enable_tool_search=enable_tool_search,
127
177
  )
128
- cmd = [claude_bin, *claude_args]
178
+ settings_json = build_claude_settings_json(env)
179
+ cmd = [claude_bin, "--settings", settings_json, *claude_args]
129
180
 
130
181
  if dry_run:
131
182
  typer.echo(f"ANTHROPIC_BASE_URL={env['ANTHROPIC_BASE_URL']}")
@@ -139,11 +190,24 @@ def launch_claude_code(
139
190
  ):
140
191
  typer.echo(f"{alias_var}={env[alias_var]}")
141
192
  typer.echo("ANTHROPIC_AUTH_TOKEN=<redacted>")
193
+ typer.echo(f"{DISCOVERY_ENV_KEY}=1")
194
+ typer.echo(f"{WINDOW_ENFORCEMENT_ENV_KEY}=1")
195
+ typer.echo(f"{AUTO_COMPACT_WINDOW_ENV_KEY}={env[AUTO_COMPACT_WINDOW_ENV_KEY]}")
196
+ typer.echo(f"picker cache: {len(model_entries)} model(s) to prime")
142
197
  if enable_tool_search:
143
198
  typer.echo("ENABLE_TOOL_SEARCH=true")
144
- typer.echo(f"command: {' '.join(cmd)}")
199
+ typer.echo(f"--settings {settings_json}")
200
+ typer.echo(f"command: {claude_bin} --settings <json> {' '.join(claude_args)}")
145
201
  return
146
202
 
203
+ # Prime the picker's discovery cache before exec. Warn-only: a failed
204
+ # prime costs the /model entries, not the session.
205
+ try:
206
+ cache_path = prime_picker_cache(model_entries, base_url)
207
+ typer.echo(f"sference: /model picker cache primed ({len(model_entries)} model(s) -> {cache_path})", err=True)
208
+ except (OSError, ValueError, TypeError) as e:
209
+ typer.echo(f"sference: warning: could not prime the /model picker cache: {e}", err=True)
210
+
147
211
  if sys.platform == "win32":
148
212
  raise SystemExit(subprocess.call(cmd, env=env))
149
213
 
@@ -759,7 +823,7 @@ def register_launch_commands(app: typer.Typer) -> None:
759
823
  @launch_app.command(
760
824
  "claude",
761
825
  context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
762
- help="Launch Claude Code with a local Sference proxy (default). Use --no-anthropic for the direct env-var mode.",
826
+ help="Launch Claude Code against the Sference endpoint (gateway model discovery; no proxy).",
763
827
  )
764
828
  def claude(
765
829
  ctx: typer.Context,
@@ -767,8 +831,7 @@ def register_launch_commands(app: typer.Typer) -> None:
767
831
  None,
768
832
  "--model",
769
833
  "-m",
770
- help="Proxy mode: catalog id to inject into the /model picker. --no-anthropic: the pinned model (default: "
771
- f"{DEFAULT_LAUNCH_MODEL} or SFERENCE_MODEL).",
834
+ help=f"Pinned catalog model (default: {CLAUDE_DEFAULT_LAUNCH_MODEL} or SFERENCE_MODEL).",
772
835
  ),
773
836
  base_url: Optional[str] = typer.Option(
774
837
  None,
@@ -779,108 +842,105 @@ def register_launch_commands(app: typer.Typer) -> None:
779
842
  no_anthropic: bool = typer.Option(
780
843
  False,
781
844
  "--no-anthropic",
782
- help="Disable the proxy and route everything directly to the Sference endpoint "
783
- "(today's ANTHROPIC_BASE_URL env-var behavior; no hybrid routing, no /model picker).",
845
+ help="Deprecated no-op: the direct env-var mode is now the only mode.",
784
846
  ),
785
847
  models: Optional[str] = typer.Option(
786
848
  None,
787
849
  "--models",
788
- help="Proxy mode: comma-separated catalog ids to route and inject into the picker "
789
- "(default: live GET /v1/models). Ignored with --no-anthropic.",
850
+ help="Comma-separated catalog ids for the /model picker (default: live GET /v1/models).",
790
851
  ),
791
852
  proxy_port: Optional[int] = typer.Option(
792
853
  None,
793
854
  "--proxy-port",
794
- help="Local mitmproxy port (default: auto-pick a free port). Proxy mode only.",
855
+ help="Deprecated no-op: there is no proxy anymore.",
795
856
  ),
796
857
  enable_tool_search: bool = typer.Option(
797
858
  False,
798
859
  "--enable-tool-search",
799
- help="Set ENABLE_TOOL_SEARCH=true (only meaningful with --no-anthropic; the proxy "
800
- "keeps first-party detection on, so tool search already works).",
860
+ help="Set ENABLE_TOOL_SEARCH=true.",
801
861
  ),
802
862
  dry_run: bool = typer.Option(
803
863
  False,
804
864
  "--dry-run",
805
- help="Print the proxy/env config and command without launching anything.",
865
+ help="Print the env config and command without launching anything.",
806
866
  ),
807
867
  ) -> None:
808
868
  """Run ``claude`` with Sference credentials.
809
869
 
810
- By default a local mitmproxy forward proxy routes Sference models to
811
- ``api.sference.com`` (native ``/v1/messages``, body untranslated) while
812
- Claude Code's first-party detection stays on — Sference models appear in
813
- the ``/model`` picker and real Claude models pass through to Anthropic.
814
- ``--no-anthropic`` switches to the direct env-var mode (everything to one
815
- Sference model). Unknown options and trailing args are forwarded to
870
+ Points Claude Code at the Sference endpoint (native ``/v1/messages``)
871
+ via ``ANTHROPIC_BASE_URL`` and enables gateway model discovery: the
872
+ live catalog is primed into the picker cache before launch, so
873
+ ``/model`` lists every Sference model the account can serve. No proxy,
874
+ no mitmproxy. Unknown options and trailing args are forwarded to
816
875
  Claude Code, e.g. ``sference launch claude -p "fix the bug"``.
817
876
  """
818
877
  from sference_cli.main import (
819
- CREDENTIALS_PATH,
820
878
  _ensure_api_credential,
821
879
  _read_device_credentials,
822
880
  _read_token,
881
+ _write_device_credentials,
823
882
  )
824
883
 
825
884
  _ensure_api_credential()
885
+ resolved_base = resolve_api_base_url(base_url)
886
+ # Device-flow (v2) credentials: refresh the 24 h access token at launch
887
+ # so long sessions start on a fresh grant. Skipped when SFERENCE_API_KEY
888
+ # overrides the file — the env token is not the file's grant, and
889
+ # refreshing would swap identities mid-session.
890
+ device_creds = None if os.environ.get("SFERENCE_API_KEY") else _read_device_credentials()
891
+ if device_creds and device_creds.get("refresh_token"):
892
+ try:
893
+ from sference_cli.device_auth import CLIENT_ID_SFERENCE_CLI, refresh_tokens
894
+
895
+ tokens = refresh_tokens(
896
+ resolved_base, CLIENT_ID_SFERENCE_CLI, device_creds["refresh_token"]
897
+ )
898
+ _write_device_credentials(tokens)
899
+ except Exception: # noqa: BLE001 (best-effort; the current token may still be valid)
900
+ # The launch proceeds on the file's token. When that token is
901
+ # already expired, a failed refresh means the session WILL 401 —
902
+ # say so now rather than mid-task.
903
+ if float(device_creds.get("expires_at") or 0) <= time.time():
904
+ typer.echo(
905
+ "warning: could not refresh the expired device token; re-run `sference auth login`",
906
+ err=True,
907
+ )
908
+
826
909
  api_key = _read_token()
827
910
  if api_key is None:
828
911
  raise typer.Exit(code=1)
829
- # Device-flow (v2) credentials let the proxy refresh the 24 h access
830
- # token mid-session; legacy API-key credentials have no refresh token.
831
- # Skip when SFERENCE_API_KEY overrides the file — the env token is not
832
- # the file's grant, and refreshing would swap identities mid-session.
833
- device_creds = None if os.environ.get("SFERENCE_API_KEY") else _read_device_credentials()
912
+
913
+ if no_anthropic:
914
+ typer.echo("note: --no-anthropic is deprecated; the direct env-var mode is now the only mode.", err=True)
915
+ if proxy_port is not None:
916
+ typer.echo("note: --proxy-port is deprecated; there is no proxy anymore.", err=True)
834
917
 
835
918
  forwarded = list(ctx.args)
836
919
  if forwarded and forwarded[0] == "--":
837
920
  forwarded = forwarded[1:]
838
921
 
839
- resolved_base = resolve_api_base_url(base_url)
840
-
841
- if no_anthropic:
842
- launch_claude_code(
843
- api_key=api_key,
844
- base_url=resolved_base,
845
- model=resolve_launch_model(model),
846
- enable_tool_search=enable_tool_search,
847
- claude_args=forwarded,
848
- dry_run=dry_run,
849
- )
850
- return
851
-
852
- if enable_tool_search:
853
- typer.echo(
854
- "note: --enable-tool-search is a no-op in proxy mode (first-party "
855
- "detection is on, so tool search already works).",
856
- err=True,
857
- )
858
-
859
- # Proxy mode: resolve the routable model set.
922
+ # Resolve the picker model set.
860
923
  if models:
861
- model_set = {m.strip() for m in models.split(",") if m.strip()}
862
- elif model:
863
- model_set = {model}
924
+ model_entries = [{"id": m.strip()} for m in models.split(",") if m.strip()]
864
925
  else:
865
926
  try:
866
- model_set = fetch_sference_models(resolved_base, api_key)
927
+ model_entries = fetch_sference_model_entries(resolved_base, api_key)
867
928
  except (urllib.error.URLError, urllib.error.HTTPError, json.JSONDecodeError, KeyError) as e:
868
929
  typer.echo(f"ERROR: could not fetch models from {resolved_base}/v1/models: {e}", err=True)
869
- typer.echo("Pass --models or --model explicitly to bypass the lookup.", err=True)
930
+ typer.echo("Pass --models explicitly to bypass the lookup.", err=True)
870
931
  raise typer.Exit(code=1) from None
871
- if not model_set:
932
+ if not model_entries:
872
933
  typer.echo("ERROR: /v1/models returned no text-generation models for this account.", err=True)
873
934
  raise typer.Exit(code=1)
874
935
 
875
- launch_claude_via_proxy(
936
+ launch_claude_code(
876
937
  api_key=api_key,
877
938
  base_url=resolved_base,
878
- models=model_set,
939
+ model=resolve_launch_model(model, default=CLAUDE_DEFAULT_LAUNCH_MODEL),
940
+ model_entries=model_entries,
941
+ enable_tool_search=enable_tool_search,
879
942
  claude_args=forwarded,
880
943
  dry_run=dry_run,
881
- proxy_port=proxy_port,
882
- refresh_token=device_creds["refresh_token"] if device_creds else None,
883
- credentials_path=str(CREDENTIALS_PATH) if device_creds else None,
884
944
  )
885
945
 
886
946
  @launch_app.command(