sference-cli 0.3.1__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.1
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
@@ -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.3.1
24
+ Requires-Dist: sference-sdk>=0.3.2
25
25
  Requires-Dist: typer>=0.24.1
26
26
  Description-Content-Type: text/markdown
27
27
 
@@ -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
142
 
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`).
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
 
@@ -156,6 +153,20 @@ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moons
156
153
 
157
154
  Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provider block to `~/.pi/agent/models.json` using pi's `openai-responses` API (the Sference `/v1/responses` endpoint) with `baseUrl`, `apiKey`, and the full list of Sference-provided models (fetched live from `GET /v1/models`), then execs `pi --provider sference --model <id> --models sference/**`. The `--models sference/**` flag scopes pi's `/model` picker (and Ctrl+P cycling) to Sference models only, so other configured providers are hidden by default (`**` is required because Sference model ids contain a slash and `*` would match nothing). All catalog models appear in the picker; `--model` selects the active one. Reasoning is driven by pi's native `reasoning.effort` (no per-model thinking-format config needed). If the catalog fetch fails (offline), only the chosen model is registered. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
158
155
 
156
+ #### `sference launch codex`
157
+
158
+ | Command | Description |
159
+ |---------|-------------|
160
+ | `sference launch codex` | Launch the [Codex CLI](https://developers.openai.com/codex/cli) against Sference's `/v1/responses` |
161
+ | `sference launch codex --dry-run` | Print provider config and command without launching Codex |
162
+ | `sference launch codex --model moonshotai/Kimi-K3` | Override catalog model |
163
+ | `sference launch codex -- exec "fix the bug"` | Forward Codex args (here: non-interactive `codex exec`) |
164
+ | `sference launch codex -- -c model_reasoning_effort=high` | Override the reasoning effort (default `medium`) |
165
+
166
+ Requires `codex` on `PATH`. The `sference` model provider is passed as `codex -c` overrides, so `~/.codex/config.toml` is never modified and your normal Codex sessions are unaffected; the API key reaches Codex through the `SFERENCE_API_KEY` env var, never on disk. The launcher disables Codex's hosted `web_search` tool (Sference's `/v1/responses` serves function tools, including Codex's `namespace` tool groups, but no hosted tools) and sets `model_context_window` from the live catalog so auto-compaction triggers at the model's real limit.
167
+
168
+ **Sub-agents and MCP servers** work: the Sference provider applies to the whole session, so agents Codex spawns run on Sference too. The launcher also writes `~/.sference/codex/models.json`, a Codex model catalog listing only the Sference models, and passes it as `model_catalog_json`. Without it Codex offers `spawn_agent` its own OpenAI models, and a sub-agent started on one of them fails. Each entry is built at launch from the catalog bundled with your Codex (`codex debug models --bundled`), so it always matches your Codex version; if that command is unavailable the launcher warns and starts without the catalog. An `agents.default_subagent_model` in your Codex config still pins sub-agents to an OpenAI model, which Sference cannot serve (the launcher warns about it).
169
+
159
170
  ### Batch
160
171
 
161
172
  | Command | Description |
@@ -177,6 +188,19 @@ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provid
177
188
  | `sference responses result` | Poll until terminal state (`--id`, `--poll-ms`) |
178
189
  | `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` |
179
190
 
191
+ ### Decisions (`/v1/decisions`)
192
+
193
+ | Command | Description |
194
+ |---------|-------------|
195
+ | `sference decisions create` | Answer up to 64 questions about one state in a single realtime call (`--model`, `--questions` JSON or `@file`, and `--state` text or `--state-json` JSON / `@file` / `@-`). Prints one line per answer; `--json` prints the full response |
196
+
197
+ ```bash
198
+ sference decisions create --model Cloudflare/clef \
199
+ --state "I was charged twice, please refund me" \
200
+ --questions '{"route": {"type": "choice", "criteria": {"billing": "Payments", "support": "Other"}},
201
+ "refund": {"type": "noul"}}'
202
+ ```
203
+
180
204
  ### Stream (first-class streams API)
181
205
 
182
206
  Long-lived **streams** are separate from **batches**: you create a stream, submit **responses** tied to it over time (`POST /v1/responses` with `metadata.stream_id`), and consume **completion events** with cursor-based pagination on **`GET /v1/responses/events`** (pass **`stream_id`** when scoping to a stream). Authenticate with your **secret API key** like other `/v1` calls.
@@ -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
115
 
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`).
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
 
@@ -129,6 +126,20 @@ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moons
129
126
 
130
127
  Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provider block to `~/.pi/agent/models.json` using pi's `openai-responses` API (the Sference `/v1/responses` endpoint) with `baseUrl`, `apiKey`, and the full list of Sference-provided models (fetched live from `GET /v1/models`), then execs `pi --provider sference --model <id> --models sference/**`. The `--models sference/**` flag scopes pi's `/model` picker (and Ctrl+P cycling) to Sference models only, so other configured providers are hidden by default (`**` is required because Sference model ids contain a slash and `*` would match nothing). All catalog models appear in the picker; `--model` selects the active one. Reasoning is driven by pi's native `reasoning.effort` (no per-model thinking-format config needed). If the catalog fetch fails (offline), only the chosen model is registered. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
131
128
 
129
+ #### `sference launch codex`
130
+
131
+ | Command | Description |
132
+ |---------|-------------|
133
+ | `sference launch codex` | Launch the [Codex CLI](https://developers.openai.com/codex/cli) against Sference's `/v1/responses` |
134
+ | `sference launch codex --dry-run` | Print provider config and command without launching Codex |
135
+ | `sference launch codex --model moonshotai/Kimi-K3` | Override catalog model |
136
+ | `sference launch codex -- exec "fix the bug"` | Forward Codex args (here: non-interactive `codex exec`) |
137
+ | `sference launch codex -- -c model_reasoning_effort=high` | Override the reasoning effort (default `medium`) |
138
+
139
+ Requires `codex` on `PATH`. The `sference` model provider is passed as `codex -c` overrides, so `~/.codex/config.toml` is never modified and your normal Codex sessions are unaffected; the API key reaches Codex through the `SFERENCE_API_KEY` env var, never on disk. The launcher disables Codex's hosted `web_search` tool (Sference's `/v1/responses` serves function tools, including Codex's `namespace` tool groups, but no hosted tools) and sets `model_context_window` from the live catalog so auto-compaction triggers at the model's real limit.
140
+
141
+ **Sub-agents and MCP servers** work: the Sference provider applies to the whole session, so agents Codex spawns run on Sference too. The launcher also writes `~/.sference/codex/models.json`, a Codex model catalog listing only the Sference models, and passes it as `model_catalog_json`. Without it Codex offers `spawn_agent` its own OpenAI models, and a sub-agent started on one of them fails. Each entry is built at launch from the catalog bundled with your Codex (`codex debug models --bundled`), so it always matches your Codex version; if that command is unavailable the launcher warns and starts without the catalog. An `agents.default_subagent_model` in your Codex config still pins sub-agents to an OpenAI model, which Sference cannot serve (the launcher warns about it).
142
+
132
143
  ### Batch
133
144
 
134
145
  | Command | Description |
@@ -150,6 +161,19 @@ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provid
150
161
  | `sference responses result` | Poll until terminal state (`--id`, `--poll-ms`) |
151
162
  | `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` |
152
163
 
164
+ ### Decisions (`/v1/decisions`)
165
+
166
+ | Command | Description |
167
+ |---------|-------------|
168
+ | `sference decisions create` | Answer up to 64 questions about one state in a single realtime call (`--model`, `--questions` JSON or `@file`, and `--state` text or `--state-json` JSON / `@file` / `@-`). Prints one line per answer; `--json` prints the full response |
169
+
170
+ ```bash
171
+ sference decisions create --model Cloudflare/clef \
172
+ --state "I was charged twice, please refund me" \
173
+ --questions '{"route": {"type": "choice", "criteria": {"billing": "Payments", "support": "Other"}},
174
+ "refund": {"type": "noul"}}'
175
+ ```
176
+
153
177
  ### Stream (first-class streams API)
154
178
 
155
179
  Long-lived **streams** are separate from **batches**: you create a stream, submit **responses** tied to it over time (`POST /v1/responses` with `metadata.stream_id`), and consume **completion events** with cursor-based pagination on **`GET /v1/responses/events`** (pass **`stream_id`** when scoping to a stream). Authenticate with your **secret API key** like other `/v1` calls.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-cli"
3
- version = "0.3.1"
3
+ version = "0.4.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.3.1",
26
+ "sference-sdk>=0.3.2",
27
27
  ]
28
28
 
29
29
  [project.urls]
@@ -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}