sference-cli 0.2.1__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sference-cli
3
- Version: 0.2.1
3
+ Version: 0.2.3
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.2.1
24
+ Requires-Dist: sference-sdk>=0.2.3
25
25
  Requires-Dist: typer>=0.24.1
26
26
  Description-Content-Type: text/markdown
27
27
 
@@ -154,7 +154,7 @@ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moons
154
154
  | `sference launch pi --model moonshotai/Kimi-K2.7-Code` | Override catalog model |
155
155
  | `sference launch pi -- /path/to/project` | Forward Pi args after `sference launch pi` |
156
156
 
157
- Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provider block to `~/.pi/agent/models.json` with `baseUrl`, `apiKey`, and the chosen `model`, then execs `pi --provider sference --model <id>`. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
157
+ 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
158
 
159
159
  ### Batch
160
160
 
@@ -127,7 +127,7 @@ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moons
127
127
  | `sference launch pi --model moonshotai/Kimi-K2.7-Code` | Override catalog model |
128
128
  | `sference launch pi -- /path/to/project` | Forward Pi args after `sference launch pi` |
129
129
 
130
- Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provider block to `~/.pi/agent/models.json` with `baseUrl`, `apiKey`, and the chosen `model`, then execs `pi --provider sference --model <id>`. Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moonshotai/Kimi-K2.7-Code` (override with `--model` or `SFERENCE_MODEL`).
130
+ 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
131
 
132
132
  ### Batch
133
133
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-cli"
3
- version = "0.2.1"
3
+ version = "0.2.3"
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.2.1",
26
+ "sference-sdk>=0.2.3",
27
27
  ]
28
28
 
29
29
  [project.urls]
@@ -181,6 +181,17 @@ def rewrite_request_for_sference(
181
181
  return new_url, headers_to_set, headers_to_remove
182
182
 
183
183
 
184
+ # Claude-family display names for the models we route. The picker shows this
185
+ # instead of the raw catalog id so the entries read like first-party Claude
186
+ # models. Keyed by exact catalog id; unknown ids get the generic fallback.
187
+ MODEL_DESCRIPTIONS: dict[str, str] = {
188
+ "moonshotai/Kimi-K3": "Fable",
189
+ "zai-org/GLM-5.2": "Opus",
190
+ "deepseek-ai/DeepSeek-V4-Flash": "Sonnet",
191
+ }
192
+ DEFAULT_MODEL_DESCRIPTION = "Sference (routed via local proxy)"
193
+
194
+
184
195
  def inject_models_into_bootstrap(body: Any, sference_models: set[str]) -> Any:
185
196
  """Append Sference models to a bootstrap response's ``additional_model_options``.
186
197
 
@@ -202,7 +213,7 @@ def inject_models_into_bootstrap(body: Any, sference_models: set[str]) -> Any:
202
213
  {
203
214
  "model": model,
204
215
  "name": f"[Sference] {model}",
205
- "description": "Sference (routed via local proxy)",
216
+ "description": MODEL_DESCRIPTIONS.get(model, DEFAULT_MODEL_DESCRIPTION),
206
217
  "disabled_reason": None,
207
218
  }
208
219
  )
@@ -13,9 +13,9 @@ from typing import Optional
13
13
 
14
14
  import typer
15
15
 
16
- from .proxy import fetch_sference_models, launch_claude_via_proxy
16
+ from .proxy import fetch_sference_model_entries, fetch_sference_models, launch_claude_via_proxy
17
17
 
18
- DEFAULT_LAUNCH_MODEL = "moonshotai/Kimi-K2.7-Code"
18
+ DEFAULT_LAUNCH_MODEL = "zai-org/GLM-5.2"
19
19
  DEFAULT_API_BASE_URL = "https://api.sference.com"
20
20
 
21
21
 
@@ -140,16 +140,108 @@ def _pi_models_json_path() -> Path:
140
140
  return Path.home() / ".pi" / "agent" / "models.json"
141
141
 
142
142
 
143
- def _write_pi_models_json(*, base_url: str, api_key: str, model: str) -> Path:
144
- """Write or update ``~/.pi/agent/models.json`` with a Sference provider."""
143
+ def _pi_model_config(entry: dict) -> dict:
144
+ """Map a ``GET /v1/models`` entry to a pi ProviderModelConfig.
145
+
146
+ The Sference provider uses pi's ``openai-responses`` API, so reasoning is
147
+ driven by pi's native ``reasoning.effort`` field — the Sference
148
+ ``/v1/responses`` endpoint accepts it directly and translates it to the
149
+ worker's ``enable_thinking`` / ``reasoning_effort``. No per-model
150
+ chat-completions ``thinkingFormat`` compat is needed (that was an
151
+ ``openai-completions`` concern; the Responses API has one native reasoning
152
+ knob). Reasoning/input come from ``capabilities``, cost from ``pricing``;
153
+ ``maxTokens`` is clamped to 16384 (pi's default cap).
154
+
155
+ Reasoning-capable models get a ``thinkingLevelMap`` exposing ``xhigh`` only
156
+ (Sference's ``/v1/responses`` accepts effort in ``(minimal,low,medium,high,
157
+ xhigh)`` and 400s on ``max``). ``max`` is deliberately omitted from the map
158
+ so a ``max`` selection clamps down to ``xhigh`` (pi's
159
+ ``clampThinkingLevel`` walks down to the nearest supported level) instead of
160
+ sending an effort the API rejects. ``high`` and below need no map entry — pi
161
+ passes the requested level through verbatim for unmapped levels.
162
+ """
163
+ caps = entry.get("capabilities") or {}
164
+ thinking = bool((caps.get("thinking") or {}).get("supported", False))
165
+ image_in = bool((caps.get("image_input") or {}).get("supported", False))
166
+ pricing = entry.get("pricing") or {}
167
+ context_tokens = entry.get("context_tokens")
168
+ context_window = context_tokens if context_tokens is not None else 128000
169
+ max_tokens = min(context_tokens if context_tokens is not None else 8192, 16384)
170
+ config = {
171
+ "id": entry["id"],
172
+ "name": entry.get("display_name") or entry["id"],
173
+ "reasoning": thinking,
174
+ "input": ["text", "image"] if image_in else ["text"],
175
+ "cost": {
176
+ "input": pricing.get("input_per_million_usd") or 0,
177
+ "output": pricing.get("output_per_million_usd") or 0,
178
+ "cacheRead": pricing.get("cached_input_per_million_usd") or 0,
179
+ "cacheWrite": 0,
180
+ },
181
+ "contextWindow": context_window,
182
+ "maxTokens": max_tokens,
183
+ }
184
+ if thinking:
185
+ # Expose only xhigh (the top Sference-supported effort). max is
186
+ # unsupported on the API (400), so omitting it lets pi clamp a ``max``
187
+ # selection down to xhigh instead of sending an effort that errors.
188
+ config["thinkingLevelMap"] = {"xhigh": "xhigh"}
189
+ return config
190
+
191
+
192
+ def _build_pi_models(*, base_url: str, api_key: str, model: str) -> list[dict]:
193
+ """Build the pi model config list for the sference provider.
194
+
195
+ Fetches the live catalog (GET {base_url}/models) and maps every
196
+ text-generation entry to a pi ProviderModelConfig with reasoning/input/
197
+ cost/context metadata and the per-model thinking wire format, so all
198
+ Sference-provided models appear in pi's ``/model`` picker — not just the one
199
+ passed to ``--model``.
200
+
201
+ The picker always mirrors the live catalog exactly: the list is rebuilt on
202
+ every run, so a model that was removed/deprecated from the catalog is
203
+ dropped rather than accumulated forever, and no model is injected that
204
+ isn't currently available from Sference. ``--model`` only selects the
205
+ active model for the launch; it is never added to the picker when absent
206
+ from a reachable catalog. The only exception is an unreachable catalog
207
+ (offline): we can't show what we can't fetch, so we register just ``model``
208
+ as a bare fallback so ``launch pi`` still works.
209
+ """
210
+ try:
211
+ entries = fetch_sference_model_entries(base_url, api_key)
212
+ except Exception:
213
+ typer.echo(
214
+ f"note: could not fetch model catalog from {base_url}/models; "
215
+ f"registered only --model {model}. The /model picker will show just "
216
+ "this model.",
217
+ err=True,
218
+ )
219
+ entries = []
220
+ fetched = False
221
+ else:
222
+ fetched = True
223
+ configs = [_pi_model_config(entry) for entry in entries]
224
+ if not fetched and model not in {c["id"] for c in configs}:
225
+ configs.append({"id": model, "name": model})
226
+ return configs
227
+
228
+
229
+ def _write_pi_models_json(*, base_url: str, api_key: str, models: list[dict]) -> Path:
230
+ """Write or update ``~/.pi/agent/models.json`` with a Sference provider.
231
+
232
+ ``models`` is the full list of pi ProviderModelConfig dicts to register —
233
+ the Sference-provided text-generation models from the live catalog (or just
234
+ the chosen model as an offline fallback). Existing providers other than
235
+ ``sference`` are preserved; only the ``sference`` block is overwritten.
236
+ """
145
237
  path = _pi_models_json_path()
146
238
  path.parent.mkdir(parents=True, exist_ok=True)
147
239
 
148
240
  provider = {
149
- "api": "openai-completions",
241
+ "api": "openai-responses",
150
242
  "baseUrl": base_url,
151
243
  "apiKey": api_key,
152
- "models": [{"id": model, "name": model}],
244
+ "models": models,
153
245
  }
154
246
 
155
247
  if path.exists():
@@ -188,15 +280,26 @@ def launch_pi(
188
280
  )
189
281
  raise typer.Exit(code=1)
190
282
 
191
- models_json = _write_pi_models_json(base_url=base_url, api_key=api_key, model=model)
283
+ models = _build_pi_models(base_url=base_url, api_key=api_key, model=model)
284
+ models_json = _write_pi_models_json(base_url=base_url, api_key=api_key, models=models)
192
285
  env = os.environ.copy()
193
286
  # Pi reads providers from ~/.pi/agent/models.json; no env vars needed.
194
- cmd = [pi_bin, "--provider", "sference", "--model", model, *pi_args]
287
+ # `--models sference/**` scopes the /model picker (and Ctrl+P cycling) to the
288
+ # Sference provider only, so built-in / other configured providers are hidden
289
+ # by default instead of cluttering the picker. Using `**` (globstar) is
290
+ # required: pi matches `--models` patterns against `provider/modelId`, and
291
+ # Sference model ids contain a slash (e.g. `zai-org/GLM-5.2`), so `sference/*`
292
+ # would match nothing (`*` does not cross `/`) and the picker would fall back
293
+ # to showing every configured provider.
294
+ cmd = [pi_bin, "--provider", "sference", "--model", model, "--models", "sference/**", *pi_args]
195
295
 
196
296
  if dry_run:
197
297
  typer.echo(f"Wrote provider 'sference' to {models_json}")
198
298
  typer.echo(f"baseUrl: {base_url}")
299
+ typer.echo("api: openai-responses (/v1/responses)")
199
300
  typer.echo(f"model: {model}")
301
+ typer.echo(f"models registered: {len(models)}")
302
+ typer.echo("model scope: sference/** (other providers hidden by default)")
200
303
  typer.echo("apiKey: <redacted>")
201
304
  typer.echo(f"command: {' '.join(cmd)}")
202
305
  return
@@ -215,23 +318,27 @@ def _opencode_config_path() -> Path:
215
318
  return Path.home() / ".config" / "opencode" / "opencode.json"
216
319
 
217
320
 
218
- def _write_opencode_config(*, base_url: str, model: str) -> Path:
321
+ def _write_opencode_config(*, base_url: str, model: str, models: set[str]) -> Path:
219
322
  """Merge a ``sference`` OpenAI-compatible provider into the opencode config.
220
323
 
221
324
  Reads ``~/.config/opencode/opencode.json`` (creating it if absent), sets
222
325
  ``provider.sference`` to a block pointing at the Sference OpenAI-compatible
223
326
  endpoint (``/v1/chat/completions``), and writes it back. The user's existing
224
- config — other providers, keybinds, theme, default ``model`` — is preserved;
225
- only ``provider.sference`` is (over)written. If the existing file is not
327
+ config — other providers, keybinds, theme — is preserved; only
328
+ ``provider.sference`` is (over)written. If the existing file is not
226
329
  valid JSON, we refuse to clobber it rather than silently destroying the
227
330
  user's opencode config.
228
331
 
332
+ All models in ``models`` are written to the provider's ``models`` block so
333
+ they appear in opencode's model picker. ``model`` is the default — set as
334
+ the top-level ``model`` key so opencode uses Sference by default on startup.
335
+
229
336
  The API key is referenced as ``{env:SFERENCE_API_KEY}`` so no secret is
230
337
  stored on disk; ``launch_opencode`` injects the resolved key into the
231
338
  opencode process env at exec time. opencode splits ``provider/model`` on
232
- the first slash, so a model id like ``moonshotai/Kimi-K2.7-Code`` is passed
233
- as ``--model sference/moonshotai/Kimi-K2.7-Code`` and resolves to provider
234
- ``sference`` + model id ``moonshotai/Kimi-K2.7-Code``.
339
+ the first slash, so a model id like ``zai-org/GLM-5.2`` is passed
340
+ as ``--model sference/zai-org/GLM-5.2`` and resolves to provider
341
+ ``sference`` + model id ``zai-org/GLM-5.2``.
235
342
  """
236
343
  path = _opencode_config_path()
237
344
  if path.exists():
@@ -250,6 +357,7 @@ def _write_opencode_config(*, base_url: str, model: str) -> Path:
250
357
  data = {}
251
358
 
252
359
  data.setdefault("provider", {})
360
+ all_models = models | {model}
253
361
  data["provider"]["sference"] = {
254
362
  "npm": "@ai-sdk/openai-compatible",
255
363
  "name": "Sference",
@@ -258,9 +366,13 @@ def _write_opencode_config(*, base_url: str, model: str) -> Path:
258
366
  "apiKey": "{env:SFERENCE_API_KEY}",
259
367
  },
260
368
  "models": {
261
- model: {"name": model},
369
+ m: {"name": m}
370
+ for m in sorted(all_models)
262
371
  },
263
372
  }
373
+ # Set Sference as the default model so opencode uses it on startup without
374
+ # the user having to select it in the picker.
375
+ data["model"] = f"sference/{model}"
264
376
 
265
377
  path.parent.mkdir(parents=True, exist_ok=True)
266
378
  with path.open("w", encoding="utf-8") as fh:
@@ -291,7 +403,17 @@ def launch_opencode(
291
403
  )
292
404
  raise typer.Exit(code=1)
293
405
 
294
- config_path = _write_opencode_config(base_url=base_url, model=model)
406
+ # Fetch all available text-generation models from /v1/models so they all
407
+ # appear in opencode's model picker, not just the default. Falls back to
408
+ # just the chosen model if the fetch fails (e.g. offline) so the launch
409
+ # still works.
410
+ try:
411
+ fetched = fetch_sference_models(base_url, api_key)
412
+ except Exception:
413
+ fetched = set()
414
+ models = fetched if fetched else set()
415
+
416
+ config_path = _write_opencode_config(base_url=base_url, model=model, models=models)
295
417
  env = os.environ.copy()
296
418
  # The config references {env:SFERENCE_API_KEY}; inject the resolved key so
297
419
  # no secret is persisted to disk.
@@ -302,6 +424,7 @@ def launch_opencode(
302
424
  typer.echo(f"Wrote provider 'sference' to {config_path}")
303
425
  typer.echo(f"baseURL: {base_url}")
304
426
  typer.echo(f"model: {model}")
427
+ typer.echo(f"models in picker: {len(models) + 1}")
305
428
  typer.echo("apiKey: {env:SFERENCE_API_KEY} (injected at launch)")
306
429
  typer.echo(f"command: {' '.join(cmd)}")
307
430
  return
@@ -463,10 +586,22 @@ def register_launch_commands(app: typer.Typer) -> None:
463
586
  ) -> None:
464
587
  """Run ``pi`` with Sference credentials.
465
588
 
466
- Writes a ``sference`` provider block to ``~/.pi/agent/models.json`` with
467
- ``baseUrl``, ``apiKey``, and the chosen ``model``, then execs
468
- ``pi --provider sference --model <id>``. Unknown options and trailing args
469
- are forwarded to Pi, e.g. ``sference launch pi -- /path/to/project``.
589
+ Writes a ``sference`` provider block to ``~/.pi/agent/models.json`` using
590
+ pi's ``openai-responses`` API (the Sference ``/v1/responses`` endpoint)
591
+ with ``baseUrl``, ``apiKey``, and the full list of Sference-provided
592
+ models (fetched live from ``GET /v1/models``), then execs
593
+ ``pi --provider sference --model <id> --models sference/**``. The
594
+ ``--models sference/**`` flag scopes the ``/model`` picker (and Ctrl+P
595
+ cycling) to Sference models only, so other configured providers are
596
+ hidden by default. ``**`` (globstar) is required because pi matches
597
+ patterns against ``provider/modelId`` and Sference model ids contain a
598
+ slash; ``sference/*`` would match nothing and show every provider. The
599
+ picker mirrors the currently-available catalog exactly; ``--model``
600
+ selects the active one and is never injected into the picker when absent
601
+ from a reachable catalog. If the catalog fetch fails (offline), only the
602
+ chosen model is registered.
603
+ Unknown options and trailing args are forwarded to Pi, e.g.
604
+ ``sference launch pi -- /path/to/project``.
470
605
  """
471
606
  from sference_cli.main import _ensure_api_credential, _read_token
472
607
 
@@ -51,8 +51,13 @@ def _normalize_base_url(raw: str) -> str:
51
51
  return raw
52
52
 
53
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.
54
+ def fetch_sference_model_entries(base_url: str, api_key: str) -> list[dict]:
55
+ """Pull the live text-generation model entries from GET {base_url}/v1/models.
56
+
57
+ Returns the raw ``data`` items — the OpenAI-compatible shape with Sference
58
+ extensions (``display_name``, ``capabilities``, ``context_tokens``,
59
+ ``pricing``) — filtered to ``modality == "text_generation"``. Callers that
60
+ only need ids should use :func:`fetch_sference_models`.
56
61
 
57
62
  Keeps the router in sync with what the account can serve, so a
58
63
  deprecated/renamed model never slips through and 400s mid-session.
@@ -64,13 +69,18 @@ def fetch_sference_models(base_url: str, api_key: str) -> set[str]:
64
69
  )
65
70
  with urllib.request.urlopen(req, timeout=15) as resp:
66
71
  payload = json.loads(resp.read().decode("utf-8"))
67
- return {
68
- item["id"]
72
+ return [
73
+ item
69
74
  for item in payload.get("data", [])
70
75
  if isinstance(item, dict)
71
76
  and item.get("id")
72
77
  and item.get("modality", "text_generation") == "text_generation"
73
- }
78
+ ]
79
+
80
+
81
+ def fetch_sference_models(base_url: str, api_key: str) -> set[str]:
82
+ """Ids of the text-generation models the account can serve (GET /v1/models)."""
83
+ return {item["id"] for item in fetch_sference_model_entries(base_url, api_key)}
74
84
 
75
85
 
76
86
  def pick_free_port() -> int:
File without changes
File without changes