sference-cli 0.1.6__tar.gz → 0.1.8__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.1.6
3
+ Version: 0.1.8
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.1.6
24
+ Requires-Dist: sference-sdk>=0.1.8
25
25
  Requires-Dist: typer>=0.24.1
26
26
  Description-Content-Type: text/markdown
27
27
 
@@ -160,7 +160,7 @@ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provid
160
160
 
161
161
  | Command | Description |
162
162
  |---------|-------------|
163
- | `sference responses create` | Create one response (`--model`, `--content`, optional `--wait`, `--poll-ms`, `--timeout-s`) |
163
+ | `sference responses create` | Create one response (`--model`, `--content`; `--background` submits async and returns immediately). The sync default blocks; if the server-side wait times out, the request is **cancelled** and the command fails — use `--background` + `sference responses result` for long requests |
164
164
  | `sference responses result` | Poll until terminal state (`--id`, `--poll-ms`) |
165
165
  | `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` |
166
166
 
@@ -133,7 +133,7 @@ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provid
133
133
 
134
134
  | Command | Description |
135
135
  |---------|-------------|
136
- | `sference responses create` | Create one response (`--model`, `--content`, optional `--wait`, `--poll-ms`, `--timeout-s`) |
136
+ | `sference responses create` | Create one response (`--model`, `--content`; `--background` submits async and returns immediately). The sync default blocks; if the server-side wait times out, the request is **cancelled** and the command fails — use `--background` + `sference responses result` for long requests |
137
137
  | `sference responses result` | Poll until terminal state (`--id`, `--poll-ms`) |
138
138
  | `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` |
139
139
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-cli"
3
- version = "0.1.6"
3
+ version = "0.1.8"
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.1.6",
26
+ "sference-sdk>=0.1.8",
27
27
  ]
28
28
 
29
29
  [project.urls]
@@ -35,8 +35,8 @@ def resolve_launch_model(explicit: Optional[str]) -> str:
35
35
  return DEFAULT_LAUNCH_MODEL
36
36
 
37
37
 
38
- def resolve_openai_base_url_for_pi(explicit: Optional[str]) -> str:
39
- """OpenAI-compatible base URL with ``/v1`` for Pi ``models.json``."""
38
+ def resolve_openai_base_url(explicit: Optional[str]) -> str:
39
+ """OpenAI-compatible base URL with ``/v1`` for tool config files (Pi, opencode)."""
40
40
  base = resolve_api_base_url(explicit)
41
41
  base = base.rstrip("/")
42
42
  if base.endswith("/v1"):
@@ -63,6 +63,17 @@ def build_claude_env(
63
63
  env["ANTHROPIC_BASE_URL"] = base_url
64
64
  env["ANTHROPIC_AUTH_TOKEN"] = api_key
65
65
  env["ANTHROPIC_MODEL"] = model
66
+ # Subagents and background calls resolve model aliases (opus/sonnet/haiku/fable)
67
+ # independently of ANTHROPIC_MODEL; pin every alias to the catalog model so no
68
+ # request goes out with a claude-* model id the API can't serve.
69
+ env["ANTHROPIC_DEFAULT_OPUS_MODEL"] = model
70
+ env["ANTHROPIC_DEFAULT_SONNET_MODEL"] = model
71
+ env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] = model
72
+ env["ANTHROPIC_DEFAULT_FABLE_MODEL"] = model
73
+ env["CLAUDE_CODE_SUBAGENT_MODEL"] = model
74
+ # Deprecated alias for ANTHROPIC_DEFAULT_HAIKU_MODEL; still read by older
75
+ # Claude Code versions, and a user-set value would leak a claude-* id.
76
+ env["ANTHROPIC_SMALL_FAST_MODEL"] = model
66
77
  # Claude Code prefers AUTH_TOKEN; drop API_KEY to avoid precedence confusion.
67
78
  env.pop("ANTHROPIC_API_KEY", None)
68
79
  if enable_tool_search:
@@ -102,6 +113,14 @@ def launch_claude_code(
102
113
  if dry_run:
103
114
  typer.echo(f"ANTHROPIC_BASE_URL={env['ANTHROPIC_BASE_URL']}")
104
115
  typer.echo(f"ANTHROPIC_MODEL={env['ANTHROPIC_MODEL']}")
116
+ for alias_var in (
117
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
118
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
119
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
120
+ "ANTHROPIC_DEFAULT_FABLE_MODEL",
121
+ "CLAUDE_CODE_SUBAGENT_MODEL",
122
+ ):
123
+ typer.echo(f"{alias_var}={env[alias_var]}")
105
124
  typer.echo("ANTHROPIC_AUTH_TOKEN=<redacted>")
106
125
  if enable_tool_search:
107
126
  typer.echo("ENABLE_TOOL_SEARCH=true")
@@ -185,6 +204,111 @@ def launch_pi(
185
204
  os.execvpe(pi_bin, cmd, env)
186
205
 
187
206
 
207
+ def find_opencode_executable() -> str | None:
208
+ return shutil.which("opencode")
209
+
210
+
211
+ def _opencode_config_path() -> Path:
212
+ return Path.home() / ".config" / "opencode" / "opencode.json"
213
+
214
+
215
+ def _write_opencode_config(*, base_url: str, model: str) -> Path:
216
+ """Merge a ``sference`` OpenAI-compatible provider into the opencode config.
217
+
218
+ Reads ``~/.config/opencode/opencode.json`` (creating it if absent), sets
219
+ ``provider.sference`` to a block pointing at the Sference OpenAI-compatible
220
+ endpoint (``/v1/chat/completions``), and writes it back. The user's existing
221
+ config — other providers, keybinds, theme, default ``model`` — is preserved;
222
+ only ``provider.sference`` is (over)written. If the existing file is not
223
+ valid JSON, we refuse to clobber it rather than silently destroying the
224
+ user's opencode config.
225
+
226
+ The API key is referenced as ``{env:SFERENCE_API_KEY}`` so no secret is
227
+ stored on disk; ``launch_opencode`` injects the resolved key into the
228
+ opencode process env at exec time. opencode splits ``provider/model`` on
229
+ the first slash, so a model id like ``moonshotai/Kimi-K2.7-Code`` is passed
230
+ as ``--model sference/moonshotai/Kimi-K2.7-Code`` and resolves to provider
231
+ ``sference`` + model id ``moonshotai/Kimi-K2.7-Code``.
232
+ """
233
+ path = _opencode_config_path()
234
+ if path.exists():
235
+ with path.open("r", encoding="utf-8") as fh:
236
+ try:
237
+ data = json.load(fh)
238
+ except json.JSONDecodeError:
239
+ typer.echo(
240
+ f"Could not parse existing opencode config at {path} as JSON.\n"
241
+ "Refusing to overwrite your opencode config. Fix or remove the "
242
+ "file and re-run.",
243
+ err=True,
244
+ )
245
+ raise typer.Exit(code=1)
246
+ else:
247
+ data = {}
248
+
249
+ data.setdefault("provider", {})
250
+ data["provider"]["sference"] = {
251
+ "npm": "@ai-sdk/openai-compatible",
252
+ "name": "Sference",
253
+ "options": {
254
+ "baseURL": base_url,
255
+ "apiKey": "{env:SFERENCE_API_KEY}",
256
+ },
257
+ "models": {
258
+ model: {"name": model},
259
+ },
260
+ }
261
+
262
+ path.parent.mkdir(parents=True, exist_ok=True)
263
+ with path.open("w", encoding="utf-8") as fh:
264
+ json.dump(data, fh, indent=2)
265
+ fh.write("\n")
266
+ try:
267
+ os.chmod(path, 0o600)
268
+ except OSError:
269
+ pass
270
+
271
+ return path
272
+
273
+
274
+ def launch_opencode(
275
+ *,
276
+ api_key: str,
277
+ base_url: str,
278
+ model: str,
279
+ opencode_args: list[str],
280
+ dry_run: bool,
281
+ ) -> None:
282
+ opencode_bin = find_opencode_executable()
283
+ if opencode_bin is None:
284
+ typer.echo(
285
+ "opencode not found on PATH.\n"
286
+ "Install from https://opencode.ai/docs and ensure the `opencode` command is available.",
287
+ err=True,
288
+ )
289
+ raise typer.Exit(code=1)
290
+
291
+ config_path = _write_opencode_config(base_url=base_url, model=model)
292
+ env = os.environ.copy()
293
+ # The config references {env:SFERENCE_API_KEY}; inject the resolved key so
294
+ # no secret is persisted to disk.
295
+ env["SFERENCE_API_KEY"] = api_key
296
+ cmd = [opencode_bin, "--model", f"sference/{model}", *opencode_args]
297
+
298
+ if dry_run:
299
+ typer.echo(f"Wrote provider 'sference' to {config_path}")
300
+ typer.echo(f"baseURL: {base_url}")
301
+ typer.echo(f"model: {model}")
302
+ typer.echo("apiKey: {env:SFERENCE_API_KEY} (injected at launch)")
303
+ typer.echo(f"command: {' '.join(cmd)}")
304
+ return
305
+
306
+ if sys.platform == "win32":
307
+ raise SystemExit(subprocess.call(cmd, env=env))
308
+
309
+ os.execvpe(opencode_bin, cmd, env)
310
+
311
+
188
312
  def register_launch_commands(app: typer.Typer) -> None:
189
313
  launch_app = typer.Typer(help="Launch external tools configured for Sference.", invoke_without_command=True)
190
314
 
@@ -295,10 +419,63 @@ def register_launch_commands(app: typer.Typer) -> None:
295
419
 
296
420
  launch_pi(
297
421
  api_key=api_key,
298
- base_url=resolve_openai_base_url_for_pi(base_url),
422
+ base_url=resolve_openai_base_url(base_url),
299
423
  model=resolve_launch_model(model),
300
424
  pi_args=forwarded,
301
425
  dry_run=dry_run,
302
426
  )
303
427
 
428
+ @launch_app.command(
429
+ "opencode",
430
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
431
+ help="Launch opencode with Sference OpenAI-compatible routing.",
432
+ )
433
+ def opencode(
434
+ ctx: typer.Context,
435
+ model: Optional[str] = typer.Option(
436
+ None,
437
+ "--model",
438
+ "-m",
439
+ help=f"Catalog model id (default: {DEFAULT_LAUNCH_MODEL} or SFERENCE_MODEL).",
440
+ ),
441
+ base_url: Optional[str] = typer.Option(
442
+ None,
443
+ "--base-url",
444
+ envvar="SFERENCE_BASE_URL",
445
+ help=f"Sference API base URL (default: {DEFAULT_API_BASE_URL}).",
446
+ ),
447
+ dry_run: bool = typer.Option(
448
+ False,
449
+ "--dry-run",
450
+ help="Print provider config and command without launching opencode.",
451
+ ),
452
+ ) -> None:
453
+ """Run ``opencode`` with Sference credentials.
454
+
455
+ Merges a ``sference`` provider (OpenAI-compatible, ``/v1/chat/completions``)
456
+ into ``~/.config/opencode/opencode.json`` and execs
457
+ ``opencode --model sference/<id>``. The API key is injected via the
458
+ ``SFERENCE_API_KEY`` env var (referenced as ``{env:SFERENCE_API_KEY}`` in
459
+ the config, so no secret is written to disk). Unknown options and trailing
460
+ args are forwarded to opencode, e.g. ``sference launch opencode --prompt "..."``.
461
+ """
462
+ from sference_cli.main import _ensure_api_credential, _read_token
463
+
464
+ _ensure_api_credential()
465
+ api_key = _read_token()
466
+ if api_key is None:
467
+ raise typer.Exit(code=1)
468
+
469
+ forwarded = list(ctx.args)
470
+ if forwarded and forwarded[0] == "--":
471
+ forwarded = forwarded[1:]
472
+
473
+ launch_opencode(
474
+ api_key=api_key,
475
+ base_url=resolve_openai_base_url(base_url),
476
+ model=resolve_launch_model(model),
477
+ opencode_args=forwarded,
478
+ dry_run=dry_run,
479
+ )
480
+
304
481
  app.add_typer(launch_app, name="launch")
@@ -109,6 +109,13 @@ def _call_api(fn: Callable[[], _T]) -> _T:
109
109
  )
110
110
  raise typer.Exit(code=1) from None
111
111
  typer.echo(err, err=True)
112
+ if err.startswith(("504:", "408:")):
113
+ typer.echo(
114
+ "The synchronous wait timed out and the request was cancelled. "
115
+ "For long-running requests, resubmit with --background and fetch "
116
+ "the result with `sference responses result --id <id>`.",
117
+ err=True,
118
+ )
112
119
  raise typer.Exit(code=1) from None
113
120
 
114
121
 
@@ -138,6 +145,13 @@ def _get_batch_or_missing(client: SferenceClient, batch_id: str) -> Any | None:
138
145
  )
139
146
  raise typer.Exit(code=1) from None
140
147
  typer.echo(err, err=True)
148
+ if err.startswith(("504:", "408:")):
149
+ typer.echo(
150
+ "The synchronous wait timed out and the request was cancelled. "
151
+ "For long-running requests, resubmit with --background and fetch "
152
+ "the result with `sference responses result --id <id>`.",
153
+ err=True,
154
+ )
141
155
  raise typer.Exit(code=1) from None
142
156
 
143
157
 
@@ -431,7 +445,12 @@ def responses_create(
431
445
  background: bool = typer.Option(
432
446
  False,
433
447
  "--background/--no-background",
434
- help="Submit asynchronously and return immediately. Default blocks until the response is terminal (matches POST /v1/responses).",
448
+ help=(
449
+ "Submit asynchronously and return immediately; fetch later with "
450
+ "`sference responses result`. Default blocks until the response is "
451
+ "terminal; if the server-side sync wait times out the request is "
452
+ "cancelled and the command fails — use --background for long requests."
453
+ ),
435
454
  ),
436
455
  timeout: float = typer.Option(
437
456
  600.0,
File without changes
File without changes