sference-cli 0.3.1__tar.gz → 0.3.2__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.3.2
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
 
@@ -156,6 +156,20 @@ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moons
156
156
 
157
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
+ #### `sference launch codex`
160
+
161
+ | Command | Description |
162
+ |---------|-------------|
163
+ | `sference launch codex` | Launch the [Codex CLI](https://developers.openai.com/codex/cli) against Sference's `/v1/responses` |
164
+ | `sference launch codex --dry-run` | Print provider config and command without launching Codex |
165
+ | `sference launch codex --model moonshotai/Kimi-K3` | Override catalog model |
166
+ | `sference launch codex -- exec "fix the bug"` | Forward Codex args (here: non-interactive `codex exec`) |
167
+ | `sference launch codex -- -c model_reasoning_effort=high` | Override the reasoning effort (default `medium`) |
168
+
169
+ 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.
170
+
171
+ **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).
172
+
159
173
  ### Batch
160
174
 
161
175
  | Command | Description |
@@ -177,6 +191,19 @@ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provid
177
191
  | `sference responses result` | Poll until terminal state (`--id`, `--poll-ms`) |
178
192
  | `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
193
 
194
+ ### Decisions (`/v1/decisions`)
195
+
196
+ | Command | Description |
197
+ |---------|-------------|
198
+ | `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 |
199
+
200
+ ```bash
201
+ sference decisions create --model Cloudflare/clef \
202
+ --state "I was charged twice, please refund me" \
203
+ --questions '{"route": {"type": "choice", "criteria": {"billing": "Payments", "support": "Other"}},
204
+ "refund": {"type": "noul"}}'
205
+ ```
206
+
180
207
  ### Stream (first-class streams API)
181
208
 
182
209
  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.
@@ -129,6 +129,20 @@ Uses `~/.sference/credentials.json` or `SFERENCE_API_KEY`. Default model: `moons
129
129
 
130
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
+ #### `sference launch codex`
133
+
134
+ | Command | Description |
135
+ |---------|-------------|
136
+ | `sference launch codex` | Launch the [Codex CLI](https://developers.openai.com/codex/cli) against Sference's `/v1/responses` |
137
+ | `sference launch codex --dry-run` | Print provider config and command without launching Codex |
138
+ | `sference launch codex --model moonshotai/Kimi-K3` | Override catalog model |
139
+ | `sference launch codex -- exec "fix the bug"` | Forward Codex args (here: non-interactive `codex exec`) |
140
+ | `sference launch codex -- -c model_reasoning_effort=high` | Override the reasoning effort (default `medium`) |
141
+
142
+ 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.
143
+
144
+ **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).
145
+
132
146
  ### Batch
133
147
 
134
148
  | Command | Description |
@@ -150,6 +164,19 @@ Requires the [Pi CLI](https://pi.dev/docs) on `PATH`. Writes a `sference` provid
150
164
  | `sference responses result` | Poll until terminal state (`--id`, `--poll-ms`) |
151
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` |
152
166
 
167
+ ### Decisions (`/v1/decisions`)
168
+
169
+ | Command | Description |
170
+ |---------|-------------|
171
+ | `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 |
172
+
173
+ ```bash
174
+ sference decisions create --model Cloudflare/clef \
175
+ --state "I was charged twice, please refund me" \
176
+ --questions '{"route": {"type": "choice", "criteria": {"billing": "Payments", "support": "Other"}},
177
+ "refund": {"type": "noul"}}'
178
+ ```
179
+
153
180
  ### Stream (first-class streams API)
154
181
 
155
182
  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.3.2"
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]
@@ -2,8 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import copy
5
6
  import json
6
7
  import os
8
+ import re
7
9
  import shutil
8
10
  import subprocess
9
11
  import sys
@@ -18,13 +20,16 @@ from .proxy import fetch_sference_model_entries, fetch_sference_models, launch_c
18
20
  DEFAULT_LAUNCH_MODEL = "zai-org/GLM-5.2"
19
21
  DEFAULT_API_BASE_URL = "https://api.sference.com"
20
22
 
21
- # Thinking-effort variants stamped on every Sference model entry in the opencode
22
- # config. The levels are a subset of OpenAI's ReasoningEffort enum that the platform
23
- # accepts (``reasoning_effort`` on chat completions); ``none`` disables thinking, the
24
- # rest enable it and each model's chat template decides what the level means. The AI
25
- # SDK openai-compatible provider forwards the variant's ``reasoningEffort`` option as
26
- # ``reasoning_effort`` in the request body. On models the catalog marks non-thinking
27
- # the effort is a server-side no-op, so stamping every fetched model is safe.
23
+ # Thinking-effort variants stamped on Sference model entries in the opencode config.
24
+ # The levels are a subset of OpenAI's ReasoningEffort enum that the platform accepts
25
+ # (``reasoning_effort`` on chat completions); ``none`` disables thinking, the rest
26
+ # enable it and each model's chat template decides what the level means.
27
+ #
28
+ # opencode merges a variant's keys straight into the model options, and the AI SDK
29
+ # openai-compatible provider forwards a top-level ``reasoningEffort`` option as
30
+ # ``reasoning_effort`` in the request body. So a variant is the flat
31
+ # ``{"reasoningEffort": level}`` — nesting it under ``"options"`` (as 0.3.1 did) leaves
32
+ # ``reasoningEffort`` unread and every variant sends the catalog default.
28
33
  OPENCODE_THINKING_VARIANTS = ("none", "medium", "high", "xhigh")
29
34
 
30
35
 
@@ -327,7 +332,48 @@ def _opencode_config_path() -> Path:
327
332
  return Path.home() / ".config" / "opencode" / "opencode.json"
328
333
 
329
334
 
330
- def _write_opencode_config(*, base_url: str, model: str, models: set[str]) -> Path:
335
+ def _thinks_always(entry: dict) -> bool:
336
+ """Whether *entry* is served by a checkpoint that cannot turn thinking off.
337
+
338
+ The GLM-5.3 family's chat template always opens a reasoning channel, so the API
339
+ rejects ``reasoning_effort: "none"`` for it with a 400. ``/v1/models`` carries no
340
+ field for that today, so mirror the API's own rule: the public id, then the id an
341
+ alias dispatches to (``zai-org/GLM-5.2`` is an alias served by GLM-5.3 weights).
342
+ """
343
+ ids = (entry.get("id") or "", entry.get("alias_of") or "")
344
+ return any("glm-5.3" in i.lower() for i in ids)
345
+
346
+
347
+ def _opencode_variants(entry: Optional[dict]) -> dict:
348
+ """The thinking-effort variants for one model entry (empty: no variants).
349
+
350
+ No entry (the model list could not be fetched, or the model was typed but not
351
+ returned) → every level but ``none``: an effort level is accepted by any thinking
352
+ model, while ``none`` 400s on one that cannot turn thinking off.
353
+ """
354
+ if entry is not None:
355
+ thinking = (entry.get("capabilities") or {}).get("thinking") or {}
356
+ if thinking.get("supported") is False:
357
+ return {}
358
+ levels = [
359
+ level
360
+ for level in OPENCODE_THINKING_VARIANTS
361
+ if level != "none" or (entry is not None and not _thinks_always(entry))
362
+ ]
363
+ return {level: {"reasoningEffort": level} for level in levels}
364
+
365
+
366
+ def _opencode_model_entry(model_id: str, entry: Optional[dict]) -> dict:
367
+ config: dict = {"name": model_id}
368
+ variants = _opencode_variants(entry)
369
+ if variants:
370
+ config["variants"] = variants
371
+ return config
372
+
373
+
374
+ def _write_opencode_config(
375
+ *, base_url: str, model: str, models: set[str], entries: Optional[dict[str, dict]] = None
376
+ ) -> Path:
331
377
  """Merge a ``sference`` OpenAI-compatible provider into the opencode config.
332
378
 
333
379
  Reads ``~/.config/opencode/opencode.json`` (creating it if absent), sets
@@ -340,9 +386,10 @@ def _write_opencode_config(*, base_url: str, model: str, models: set[str]) -> Pa
340
386
 
341
387
  All models in ``models`` are written to the provider's ``models`` block so
342
388
  they appear in opencode's model picker, each with the thinking-effort
343
- variants in ``OPENCODE_THINKING_VARIANTS`` (selectable as
344
- ``sference/<model>@<level>`` or via opencode's variant switcher; no variant
345
- means the server-side catalog default decides). ``model`` is the default —
389
+ variants that model accepts (``_opencode_variants``, from its ``/v1/models``
390
+ entry in ``entries``; selectable as ``sference/<model>@<level>`` or via
391
+ opencode's variant switcher; no variant means the server-side catalog
392
+ default decides). ``model`` is the default —
346
393
  set as the top-level ``model`` key so opencode uses Sference by default on
347
394
  startup.
348
395
 
@@ -379,13 +426,7 @@ def _write_opencode_config(*, base_url: str, model: str, models: set[str]) -> Pa
379
426
  "apiKey": "{env:SFERENCE_API_KEY}",
380
427
  },
381
428
  "models": {
382
- m: {
383
- "name": m,
384
- "variants": {
385
- level: {"options": {"reasoningEffort": level}}
386
- for level in OPENCODE_THINKING_VARIANTS
387
- },
388
- }
429
+ m: _opencode_model_entry(m, (entries or {}).get(m))
389
430
  for m in sorted(all_models)
390
431
  },
391
432
  }
@@ -427,12 +468,14 @@ def launch_opencode(
427
468
  # just the chosen model if the fetch fails (e.g. offline) so the launch
428
469
  # still works.
429
470
  try:
430
- fetched = fetch_sference_models(base_url, api_key)
471
+ entries = {e["id"]: e for e in fetch_sference_model_entries(base_url, api_key)}
431
472
  except Exception:
432
- fetched = set()
433
- models = fetched if fetched else set()
473
+ entries = {}
474
+ models = set(entries)
434
475
 
435
- config_path = _write_opencode_config(base_url=base_url, model=model, models=models)
476
+ config_path = _write_opencode_config(
477
+ base_url=base_url, model=model, models=models, entries=entries
478
+ )
436
479
  env = os.environ.copy()
437
480
  # The config references {env:SFERENCE_API_KEY}; inject the resolved key so
438
481
  # no secret is persisted to disk.
@@ -454,6 +497,256 @@ def launch_opencode(
454
497
  os.execvpe(opencode_bin, cmd, env)
455
498
 
456
499
 
500
+ def find_codex_executable() -> str | None:
501
+ return shutil.which("codex")
502
+
503
+
504
+ # Codex's own config may pin an effort Sference rejects (e.g. a level only
505
+ # OpenAI models accept), so the launcher always sets one. Forwarded
506
+ # ``-c model_reasoning_effort=...`` args come later on the command line and win.
507
+ CODEX_DEFAULT_REASONING_EFFORT = "medium"
508
+
509
+
510
+ def _toml_value(value: object) -> str:
511
+ """Render a ``codex -c key=value`` value; Codex parses the right-hand side as TOML.
512
+
513
+ A JSON string literal is a valid TOML basic string (and JSON ``true``/``false``
514
+ and integers are valid TOML), so ``json.dumps`` covers every value we pass.
515
+ """
516
+ return json.dumps(value)
517
+
518
+
519
+ # Fields of a Codex catalog entry that switch on modes Sference's /v1/responses
520
+ # cannot serve. Set on every generated entry, whatever the template says:
521
+ # responses-lite moves the tools into an ``additional_tools`` input item, a
522
+ # freeform ``apply_patch`` is a non-function (custom) tool, and websockets,
523
+ # hosted search and service tiers are OpenAI-only.
524
+ _CODEX_CATALOG_ENTRY_OVERRIDES: dict = {
525
+ "use_responses_lite": False,
526
+ "apply_patch_tool_type": None,
527
+ "prefer_websockets": False,
528
+ "supports_search_tool": False,
529
+ "service_tiers": [],
530
+ "additional_speed_tiers": [],
531
+ "default_service_tier": None,
532
+ "upgrade": None,
533
+ "availability_nux": None,
534
+ "visibility": "list",
535
+ }
536
+
537
+
538
+ def bundled_codex_catalog(codex_bin: str) -> Optional[list[dict]]:
539
+ """The model catalog shipped with the installed Codex, or None if unavailable.
540
+
541
+ Read from ``codex debug models --bundled`` at launch rather than vendored, so the
542
+ generated entries always match the schema of the Codex version being launched.
543
+ """
544
+ try:
545
+ proc = subprocess.run(
546
+ [codex_bin, "debug", "models", "--bundled"],
547
+ capture_output=True,
548
+ text=True,
549
+ timeout=30,
550
+ check=True,
551
+ )
552
+ models = json.loads(proc.stdout).get("models")
553
+ except (OSError, subprocess.SubprocessError, ValueError, AttributeError):
554
+ return None
555
+ return models if isinstance(models, list) else None
556
+
557
+
558
+ def codex_catalog_template(models: list[dict]) -> Optional[dict]:
559
+ """The first bundled entry Codex doesn't run in a GPT-only mode, or None."""
560
+ for entry in models:
561
+ if (
562
+ isinstance(entry, dict)
563
+ and not entry.get("use_responses_lite")
564
+ and not entry.get("tool_mode")
565
+ and not entry.get("multi_agent_version")
566
+ ):
567
+ return entry
568
+ return None
569
+
570
+
571
+ def build_codex_model_catalog(template: dict, entries: list[dict]) -> dict:
572
+ """A Codex ``model_catalog_json`` listing only the Sference models in ``entries``.
573
+
574
+ Without it Codex offers ``spawn_agent`` its bundled OpenAI models, and a sub-agent
575
+ started on one of them (e.g. ``gpt-6-luna``) sends Sference a model id and a
576
+ responses-lite request shape it cannot serve. Each entry is a copy of
577
+ ``template`` (Codex's own entry, for its base instructions and tool settings)
578
+ with the GPT-only modes switched off and the Sference model's name, context
579
+ window and image input filled in.
580
+ """
581
+ models = []
582
+ for priority, entry in enumerate(entries, start=1):
583
+ caps = entry.get("capabilities") or {}
584
+ image_in = bool((caps.get("image_input") or {}).get("supported", False))
585
+ name = entry.get("display_name") or entry["id"]
586
+ model = {
587
+ **copy.deepcopy(template),
588
+ **_CODEX_CATALOG_ENTRY_OVERRIDES,
589
+ "slug": entry["id"],
590
+ "display_name": name,
591
+ "description": f"{name} on Sference",
592
+ "input_modalities": ["text", "image"] if image_in else ["text"],
593
+ "priority": priority,
594
+ }
595
+ if entry.get("context_tokens"):
596
+ model["context_window"] = int(entry["context_tokens"])
597
+ model["max_context_window"] = int(entry["context_tokens"])
598
+ models.append(model)
599
+ return {"models": models}
600
+
601
+
602
+ def codex_catalog_path() -> Path:
603
+ return Path.home() / ".sference" / "codex" / "models.json"
604
+
605
+
606
+ def write_codex_catalog(catalog: dict) -> Path:
607
+ """Write the catalog atomically (concurrent launches share the path)."""
608
+ path = codex_catalog_path()
609
+ path.parent.mkdir(parents=True, exist_ok=True)
610
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
611
+ tmp.write_text(json.dumps(catalog), encoding="utf-8")
612
+ os.replace(tmp, path)
613
+ return path
614
+
615
+
616
+ def build_codex_overrides(
617
+ *, base_url: str, model: str, entry: Optional[dict], model_catalog: Optional[Path] = None
618
+ ) -> list[str]:
619
+ """``-c`` overrides that point Codex at Sference for this process only.
620
+
621
+ Passing the provider on the command line instead of editing
622
+ ``~/.codex/config.toml`` leaves the user's Codex setup untouched for normal
623
+ (OpenAI) sessions, and ``env_key`` keeps the API key off disk.
624
+
625
+ Codex speaks only the Responses wire API, served by Sference's
626
+ ``/v1/responses``, which takes function and ``namespace`` tools (Codex sends
627
+ sub-agents and MCP servers as namespaces) but no hosted tools, so Codex's
628
+ hosted ``web_search`` tool is switched off.
629
+
630
+ ``model_provider`` applies to the whole session, so sub-agents spawned with
631
+ ``spawn_agent`` also run on Sference. ``model_catalog`` (see
632
+ :func:`build_codex_model_catalog`) replaces Codex's OpenAI model list with the
633
+ Sference models, so a sub-agent either inherits ``model`` or picks another
634
+ Sference model.
635
+ """
636
+ overrides = {
637
+ "model_provider": "sference",
638
+ "model_providers.sference.name": "Sference",
639
+ "model_providers.sference.base_url": base_url,
640
+ "model_providers.sference.env_key": "SFERENCE_API_KEY",
641
+ "model_providers.sference.wire_api": "responses",
642
+ "model_reasoning_effort": CODEX_DEFAULT_REASONING_EFFORT,
643
+ "web_search": "disabled",
644
+ }
645
+ # Codex has no metadata for Sference models and falls back to a generic
646
+ # context window; give it the real one so auto-compaction fires in time.
647
+ if entry is not None and entry.get("context_tokens"):
648
+ overrides["model_context_window"] = int(entry["context_tokens"])
649
+ if model_catalog is not None:
650
+ overrides["model_catalog_json"] = str(model_catalog)
651
+ args: list[str] = []
652
+ for key, value in overrides.items():
653
+ args += ["-c", f"{key}={_toml_value(value)}"]
654
+ return [*args, "--model", model]
655
+
656
+
657
+ def _codex_config_path() -> Path:
658
+ home = os.environ.get("CODEX_HOME")
659
+ return Path(home) / "config.toml" if home else Path.home() / ".codex" / "config.toml"
660
+
661
+
662
+ def _codex_pins_subagent_model() -> bool:
663
+ """Whether the user's Codex config sets ``agents.default_subagent_model``.
664
+
665
+ That model is always an OpenAI id (Codex rejects anything off its own list),
666
+ and with the Sference provider it 400s every sub-agent. A line scan rather than
667
+ a TOML parse: ``tomllib`` needs Python 3.11 and this only drives a warning.
668
+ """
669
+ try:
670
+ text = _codex_config_path().read_text(encoding="utf-8")
671
+ except OSError:
672
+ return False
673
+ return re.search(r"^\s*(agents\.)?default_subagent_model\s*=", text, re.MULTILINE) is not None
674
+
675
+
676
+ def launch_codex(
677
+ *,
678
+ api_key: str,
679
+ base_url: str,
680
+ model: str,
681
+ codex_args: list[str],
682
+ dry_run: bool,
683
+ ) -> None:
684
+ codex_bin = find_codex_executable()
685
+ if codex_bin is None:
686
+ typer.echo(
687
+ "Codex CLI not found on PATH.\n"
688
+ "Install from https://developers.openai.com/codex/cli "
689
+ "(e.g. `npm i -g @openai/codex`) and ensure the `codex` command is available.",
690
+ err=True,
691
+ )
692
+ raise typer.Exit(code=1)
693
+
694
+ try:
695
+ entry_list = fetch_sference_model_entries(base_url, api_key)
696
+ except Exception:
697
+ entry_list = []
698
+ entries = {e["id"]: e for e in entry_list}
699
+
700
+ catalog: Optional[dict] = None
701
+ if entry_list:
702
+ bundled = bundled_codex_catalog(codex_bin)
703
+ template = codex_catalog_template(bundled) if bundled else None
704
+ if template is not None:
705
+ catalog = build_codex_model_catalog(template, entry_list)
706
+ else:
707
+ typer.echo(
708
+ "warning: could not read Codex's model catalog (`codex debug models --bundled`); "
709
+ "sub-agents may be offered OpenAI models that Sference cannot serve.",
710
+ err=True,
711
+ )
712
+
713
+ if _codex_pins_subagent_model():
714
+ typer.echo(
715
+ f"warning: {_codex_config_path()} sets agents.default_subagent_model, an OpenAI "
716
+ "model Sference cannot serve; sub-agents will fail. Remove it to have "
717
+ f"sub-agents inherit {model}.",
718
+ err=True,
719
+ )
720
+
721
+ env = os.environ.copy()
722
+ # model_providers.sference.env_key names this var; inject the resolved key
723
+ # so no secret is persisted to disk.
724
+ env["SFERENCE_API_KEY"] = api_key
725
+ # A dry run reports the catalog path without writing it.
726
+ catalog_path = None
727
+ if catalog is not None:
728
+ catalog_path = codex_catalog_path() if dry_run else write_codex_catalog(catalog)
729
+ overrides = build_codex_overrides(
730
+ base_url=base_url, model=model, entry=entries.get(model), model_catalog=catalog_path
731
+ )
732
+ cmd = [codex_bin, *overrides, *codex_args]
733
+
734
+ if dry_run:
735
+ typer.echo(f"base_url: {base_url}")
736
+ typer.echo("wire_api: responses (/v1/responses)")
737
+ typer.echo(f"model: {model}")
738
+ typer.echo("apiKey: $SFERENCE_API_KEY (injected at launch)")
739
+ if catalog is not None:
740
+ typer.echo(f"model_catalog_json: {catalog_path} ({len(catalog['models'])} Sference models)")
741
+ typer.echo(f"command: {' '.join(cmd)}")
742
+ return
743
+
744
+ if sys.platform == "win32":
745
+ raise SystemExit(subprocess.call(cmd, env=env))
746
+
747
+ os.execvpe(codex_bin, cmd, env)
748
+
749
+
457
750
  def register_launch_commands(app: typer.Typer) -> None:
458
751
  launch_app = typer.Typer(help="Launch external tools configured for Sference.", invoke_without_command=True)
459
752
 
@@ -706,4 +999,57 @@ def register_launch_commands(app: typer.Typer) -> None:
706
999
  dry_run=dry_run,
707
1000
  )
708
1001
 
1002
+ @launch_app.command(
1003
+ "codex",
1004
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
1005
+ help="Launch OpenAI Codex CLI with Sference Responses-API routing.",
1006
+ )
1007
+ def codex(
1008
+ ctx: typer.Context,
1009
+ model: Optional[str] = typer.Option(
1010
+ None,
1011
+ "--model",
1012
+ "-m",
1013
+ help=f"Catalog model id (default: {DEFAULT_LAUNCH_MODEL} or SFERENCE_MODEL).",
1014
+ ),
1015
+ base_url: Optional[str] = typer.Option(
1016
+ None,
1017
+ "--base-url",
1018
+ envvar="SFERENCE_BASE_URL",
1019
+ help=f"Sference API base URL (default: {DEFAULT_API_BASE_URL}).",
1020
+ ),
1021
+ dry_run: bool = typer.Option(
1022
+ False,
1023
+ "--dry-run",
1024
+ help="Print provider config and command without launching Codex.",
1025
+ ),
1026
+ ) -> None:
1027
+ """Run ``codex`` with Sference credentials.
1028
+
1029
+ Defines a ``sference`` model provider (``/v1/responses``) through
1030
+ ``codex -c`` overrides, so ``~/.codex/config.toml`` is never modified.
1031
+ The API key is injected via the ``SFERENCE_API_KEY`` env var. Unknown
1032
+ options and trailing args are forwarded to Codex, e.g.
1033
+ ``sference launch codex -- exec "fix the bug"`` or
1034
+ ``sference launch codex -- -c model_reasoning_effort=high``.
1035
+ """
1036
+ from sference_cli.main import _ensure_api_credential, _read_token
1037
+
1038
+ _ensure_api_credential()
1039
+ api_key = _read_token()
1040
+ if api_key is None:
1041
+ raise typer.Exit(code=1)
1042
+
1043
+ forwarded = list(ctx.args)
1044
+ if forwarded and forwarded[0] == "--":
1045
+ forwarded = forwarded[1:]
1046
+
1047
+ launch_codex(
1048
+ api_key=api_key,
1049
+ base_url=resolve_openai_base_url(base_url),
1050
+ model=resolve_launch_model(model),
1051
+ codex_args=forwarded,
1052
+ dry_run=dry_run,
1053
+ )
1054
+
709
1055
  app.add_typer(launch_app, name="launch")
@@ -42,12 +42,14 @@ stream_app = typer.Typer(help="Stream commands", invoke_without_command=True)
42
42
  responses_app = typer.Typer(help="Responses commands", invoke_without_command=True)
43
43
  models_app = typer.Typer(help="List models (GET /v1/models)", invoke_without_command=True)
44
44
  embeddings_app = typer.Typer(help="Embeddings commands", invoke_without_command=True)
45
+ decisions_app = typer.Typer(help="Realtime decisions (POST /v1/decisions)", invoke_without_command=True)
45
46
  app.add_typer(auth_app, name="auth")
46
47
  app.add_typer(batch_app, name="batch")
47
48
  app.add_typer(stream_app, name="stream")
48
49
  app.add_typer(responses_app, name="responses")
49
50
  app.add_typer(models_app, name="models")
50
51
  app.add_typer(embeddings_app, name="embeddings")
52
+ app.add_typer(decisions_app, name="decisions")
51
53
  register_launch_commands(app)
52
54
 
53
55
  CREDENTIALS_PATH = Path.home() / ".sference" / "credentials.json"
@@ -525,6 +527,73 @@ def embeddings_create(
525
527
  _print(resp.model_dump(), as_json or True)
526
528
 
527
529
 
530
+ def _read_json_option(raw: str, option: str) -> object:
531
+ """Parse a JSON option value; ``@path`` reads the file and ``@-`` reads stdin."""
532
+ if raw.startswith("@"):
533
+ source = raw[1:]
534
+ raw = sys.stdin.read() if source == "-" else Path(source).read_text(encoding="utf-8")
535
+ try:
536
+ return json.loads(raw)
537
+ except json.JSONDecodeError as exc:
538
+ typer.echo(f"{option} is not valid JSON: {exc}", err=True)
539
+ raise typer.Exit(code=1) from exc
540
+
541
+
542
+ def _format_answer(answer: dict) -> str:
543
+ kind = answer.get("type")
544
+ if kind == "choice":
545
+ return f"{answer['choice']} (confidence {answer['confidence']:.2f})"
546
+ if kind == "score":
547
+ return f"{answer['score']:.2f} (confidence {answer['confidence']:.2f})"
548
+ if kind == "noul":
549
+ return f"p(true)={answer['noul']:.2f}"
550
+ return json.dumps(answer)
551
+
552
+
553
+ @decisions_app.command("create")
554
+ def decisions_create(
555
+ model: str = typer.Option(..., "--model", help="Decisions model id (modality=decisions in `sference models`)."),
556
+ questions: str = typer.Option(
557
+ ...,
558
+ "--questions",
559
+ help='JSON object {name: {"type": "choice"|"score"|"noul", ...}}; @path reads a file, @- stdin.',
560
+ ),
561
+ state: Optional[str] = typer.Option(None, "--state", help="Text to decide about."),
562
+ state_json: Optional[str] = typer.Option(
563
+ None, "--state-json", help="State as a JSON value instead of text; @path reads a file, @- stdin."
564
+ ),
565
+ timeout: float = typer.Option(30.0, "--timeout", help="HTTP read timeout in seconds."),
566
+ base_url: str = typer.Option("https://api.sference.com"),
567
+ as_json: bool = typer.Option(False, "--json", help="Print the full POST /v1/decisions response."),
568
+ ) -> None:
569
+ """Answer up to 64 questions about one state in a single realtime call (POST /v1/decisions)."""
570
+ _ensure_api_credential()
571
+ if (state is None) == (state_json is None):
572
+ typer.echo("Pass exactly one of --state or --state-json.", err=True)
573
+ raise typer.Exit(code=1)
574
+ state_value = state if state is not None else _read_json_option(state_json, "--state-json")
575
+ parsed_questions = _read_json_option(questions, "--questions")
576
+ if not isinstance(parsed_questions, dict):
577
+ typer.echo("--questions must be a JSON object keyed by question name.", err=True)
578
+ raise typer.Exit(code=1)
579
+ client = _client(base_url, timeout=timeout)
580
+ try:
581
+ resp = _call_api(
582
+ lambda: client.create_decision(model=model, state=state_value, questions=parsed_questions)
583
+ )
584
+ except ValueError as exc:
585
+ typer.echo(f"Invalid --questions: {exc}", err=True)
586
+ raise typer.Exit(code=1) from exc
587
+ payload = resp.model_dump()
588
+ if as_json:
589
+ _print(payload, True)
590
+ return
591
+ width = max(len(name) for name in payload["answers"])
592
+ for name, answer in payload["answers"].items():
593
+ typer.echo(f"{name.ljust(width)} {_format_answer(answer)}")
594
+ typer.echo(f"input_tokens: {payload['usage']['input_tokens']}")
595
+
596
+
528
597
  @auth_app.command("login")
529
598
  def auth_login(
530
599
  api_key: Optional[str] = typer.Option(
File without changes
File without changes