Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(init): a logged-in Claude Code, Codex or OpenCode is offered with its quota and time, never spent unasked (#4247)

Raghav Chamadiya994b6a5c6819
diff --git a/docs/agent/CLAUDE_CODE_PROVIDER.md b/docs/agent/CLAUDE_CODE_PROVIDER.md
index ad43ca7c4..400180838 100644
--- a/docs/agent/CLAUDE_CODE_PROVIDER.md
+++ b/docs/agent/CLAUDE_CODE_PROVIDER.md
@@ -101,9 +101,9 @@ repowise init --provider claude_cli --model claude-opus-5-5
Each page is a full CLI process, and subscription limits are per account.
Serializing makes a 68-page wiki take about an hour; too much concurrency trips
-the account limit and fails the run. The provider bounds itself to **4**
-concurrent processes, and `init` caps `--concurrency` at 4 for CLI-backed
-providers. Override with:
+the account limit and fails the run. The provider runs at most **4** CLI
+processes at a time, whatever `--concurrency` says; a lower `--concurrency`
+still lowers it. Override with:
```bash
REPOWISE_CLAUDE_CLI_CONCURRENCY=2 repowise generate --unwritten
@@ -117,6 +117,28 @@ Budget roughly **9k output tokens and a few minutes per page**, drawn from the
same limits as your interactive Claude Code sessions. On a large repo, prefer
`--path` to scope a run rather than regenerating everything.
+### Detected, never picked for you
+
+`repowise init` reads `claude auth status` (and `codex login status`,
+`opencode auth list`) to see how each CLI is billed. The interactive picker
+shows that in place of a price, for example "Claude team plan: uses your plan
+quota, about 14 model calls, 4 at a time, about 4 min" (one minute per call
+per process). A non-interactive run (`--yes`) never switches to one: it stays
+free and prints one line naming the command that would use it, Claude Code
+first. A CLI signed in without a paid plan, or with no stored credentials, is
+still listed but never recommended. Codex signed in through ChatGPT is listed
+in the picker but not offered, because its status cannot show whether the plan
+is active; Codex with an API key is offered, billed per token.
+
+### Running from inside Claude Code
+
+An agent in a Claude Code session can run `repowise init --provider
+claude_cli`; the nested `claude -p` calls work. Repowise removes the parent
+session's markers (`CLAUDECODE`, `CLAUDE_CODE_SESSION_ID`, the session's
+messaging socket and token, and similar) from the child's environment, so the
+child does not try to report back to the parent session. Auth and backend
+settings such as `CLAUDE_CODE_USE_BEDROCK` pass through unchanged.
+
### Reasoning
Claude Code's `--effort` flag maps directly to `low`, `medium`, `high`, `xhigh`,
diff --git a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
index 2cafe3ffc..0abee9199 100644
--- a/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/generate_cmd/command.py
@@ -120,11 +120,8 @@ def _make_gate(dry_run: bool, embedder: str | None = None):
dry_run: bool,
decisions: Any = None,
) -> bool:
- from repowise.cli.commands.init_cmd.generation import (
- cost_gate_blocks,
- embedding_note,
- format_cost,
- )
+ from repowise.cli.commands.init_cmd.generation import cost_gate_blocks, embedding_note
+ from repowise.cli.cost_gate import spend_phrase
from repowise.cli.providers.embedders import resolve_embedding_model
from repowise.core.cost_estimator import estimate_cost
@@ -152,7 +149,7 @@ def _make_gate(dry_run: bool, embedder: str | None = None):
if est is not None:
_print_page_line(cost_plans, f" with [cyan]{provider.model_name}[/cyan]")
print_lane_estimate(decisions, provider)
- console.print(f"Estimated [bold]{format_cost(est)}[/bold].")
+ console.print(f"{spend_phrase(est)}.")
embedding = embedding_note(est)
if embedding:
console.print(f"[dim]{embedding}[/dim]")
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py b/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py
index c1125011a..dedbc154b 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_generate.py
@@ -8,6 +8,7 @@ from typing import Any
from rich.table import Table
+from repowise.cli.cost_gate import spend_phrase
from repowise.cli.helpers import console, load_config, warn
from repowise.cli.ui import BRAND, VALUE, print_phase_header
from repowise.cli.ui.mode_names import INDEX_ONLY
@@ -20,7 +21,6 @@ from .generation import (
cost_gate_declined,
embedding_note,
estimate_generation,
- format_cost,
page_type_label,
run_repo_generation,
structural_page_summary,
@@ -163,6 +163,19 @@ def _run_deterministic_generation_phase(
return embedder
+def _local_server_overloaded(provider_name: str, concurrency: int) -> bool:
+ """A local model server (Ollama) at high concurrency, which can time out.
+
+ An agent CLI bounds its own process count (its estimate says so), so it
+ never needs the advice to lower --concurrency.
+ """
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+ spec = PROVIDER_SPECS.get(provider_name)
+ is_local_server = spec is not None and spec.local and not spec.agent
+ return is_local_server and concurrency > 4
+
+
def _print_generation_plan(
est: Any, result: Any, provider: Any, *, concurrency: int, onboarding: bool
) -> None:
@@ -199,11 +212,7 @@ def _print_generation_plan(
lang_parts = [f"{lang} {pct:.0%}" for lang, pct in lang_items]
console.print(f" Languages: {', '.join(lang_parts)}")
- # Warn when a local provider runs with default concurrency
- from repowise.core.providers.llm.specs import PROVIDER_SPECS
-
- spec = PROVIDER_SPECS.get(provider.provider_name)
- if spec is not None and spec.local and concurrency > 4:
+ if _local_server_overloaded(provider.provider_name, concurrency):
warn(
f" {provider.provider_name} is a local provider "
f"running with concurrency={concurrency}. "
@@ -291,7 +300,7 @@ def _run_generation_phase(
concept_n = concept_page_count(plans)
console.print(
f" Writing [bold]{concept_n:,}[/bold] subsystem pages with "
- f"[{VALUE}]{provider.model_name}[/]. Estimated [bold]{format_cost(est)}[/bold]."
+ f"[{VALUE}]{provider.model_name}[/]. {spend_phrase(est, concurrency)}."
)
structural = structural_page_summary(plans)
if structural:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py b/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
index 17d4d43f4..12b546342 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_prepare.py
@@ -35,7 +35,11 @@ from repowise.core.docs_mode import resolve_docs_mode
from repowise.core.generation.styles import resolve_style
from ._options import InitOptions, InitRun
-from ._provider import announce_index_only, resolve_docs_provider
+from ._provider import (
+ announce_index_only,
+ note_subscription_cli,
+ resolve_docs_provider,
+)
from ._questions import _ask_questions
from .persistence import effective_run_mode_for_resume
@@ -218,6 +222,7 @@ def _resolve_provider_stage(run: InitRun) -> None:
announce_index_only(run)
else:
resolve_docs_provider(run)
+ note_subscription_cli(run)
def _prepare_single_repo(opts: InitOptions, repo_path: Path, start: float) -> InitRun | None:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_provider.py b/packages/cli/src/repowise/cli/commands/init_cmd/_provider.py
index c62309202..056a32c74 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_provider.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_provider.py
@@ -71,6 +71,26 @@ def _resolve_or_fall_back(run: InitRun) -> None:
console.print(f" [dim]{exc}[/dim]")
+def note_subscription_cli(run: InitRun) -> None:
+ """Name a logged-in Claude Code / Codex / OpenCode on a run no model writes.
+
+ Never switches the run to it: a subscription is spent only when asked for
+ with --provider. Interactive runs got the picker instead, and a configured
+ provider is already a choice.
+ """
+ if run.is_interactive or run.opts.provider_name or run.config.get("provider"):
+ return
+ if not (run.opts.index_only or run.no_provider):
+ return
+ from repowise.cli.ui.subscription import logged_in_agent_providers, subscription_note
+
+ offered = {n: auth for n, auth in logged_in_agent_providers().items() if auth.offer}
+ first = next(iter(offered), None)
+ note = subscription_note(tuple(offered), offered[first]) if first else None
+ if note:
+ console.print(f" [dim]{note}[/dim]")
+
+
def _print_provider_summary(run: InitRun) -> None:
provider = run.provider
if not run.is_interactive and not run.no_provider:
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_questions.py b/packages/cli/src/repowise/cli/commands/init_cmd/_questions.py
index b450229fe..25a7e0f91 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_questions.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_questions.py
@@ -16,12 +16,14 @@ from repowise.cli.ui import (
interactive_generate_docs_toggle,
interactive_mode_select,
interactive_provider_config_select,
+ model_call_count,
print_banner,
print_scan_summary,
prompt_wiki_style,
quick_repo_scan,
should_offer_fast_mode,
)
+from repowise.cli.ui.subscription import SubscriptionContext
from ._options import InitRun
@@ -65,16 +67,28 @@ def _ask_mode(run: InitRun) -> None:
run.opts = replace(run.opts, index_only=not run.generate_docs)
-def _ask_provider(run: InitRun) -> None:
- """Provider selection, only when docs will be generated."""
+def _ask_provider(run: InitRun, scan_info: Any = None) -> None:
+ """Provider selection, only when docs will be generated.
+
+ The scan's file count sizes the estimate shown beside a subscription CLI,
+ from the same pre-index plan the server quotes.
+ """
+ from repowise.core.cost_estimator import approximate_generation_plan
+
opts = run.opts
+ files = getattr(scan_info, "total_files", 0)
+ plans = approximate_generation_plan(files, onboarding=opts.onboarding) if files else []
selection = interactive_provider_config_select(
console,
opts.model,
opts.reasoning,
repo_path=run.repo_path,
save_key=opts.save_key,
- prefer=agent_providers_set_up(run.repo_path),
+ subscription=SubscriptionContext(
+ prefer=agent_providers_set_up(run.repo_path),
+ model_calls=model_call_count(plans),
+ concurrency=opts.concurrency,
+ ),
)
run.opts = replace(
opts,
@@ -149,7 +163,7 @@ def _ask_questions(run: InitRun) -> None:
# ``is_interactive`` can have been cleared by an unanswerable menu, in
# which case every remaining question here is unanswerable too.
if run.generate_docs and run.is_interactive:
- _ask_provider(run)
+ _ask_provider(run, scan_info)
if run.customize:
adv = interactive_advanced_config(
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index b287e324b..37cd62a45 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -20,6 +20,7 @@ from typing import Any
from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
from repowise.cli._setup import setup_logging_silence
+from repowise.cli.cost_gate import spend_phrase
from repowise.cli.editor_integrations.defaults import (
get_default_disabled_project_files,
get_default_integration_overrides,
@@ -85,7 +86,6 @@ from .generation import (
cost_gate_declined,
embedding_note,
estimate_generation,
- format_cost,
run_repo_generation,
structural_page_summary,
)
@@ -150,7 +150,7 @@ def _run_workspace_generation(
# a dozen times, which makes plain text easier to miss, not harder.
console.print(
f" Writing [bold]{concept_page_count(plans):,}[/bold] subsystem pages with "
- f"[{VALUE}]{provider.model_name}[/]. Estimated [bold]{format_cost(est)}[/bold]."
+ f"[{VALUE}]{provider.model_name}[/]. {spend_phrase(est, concurrency)}."
)
structural = structural_page_summary(plans)
if structural:
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index 31d763919..28a3e74fc 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -87,6 +87,7 @@ def _gate_cost(
format_cost,
structural_page_summary,
)
+ from repowise.cli.cost_gate import spend_phrase
from repowise.cli.providers.embedders import resolve_embedding_model
from repowise.core.cost_estimator import build_generation_plan, estimate_cost
@@ -104,7 +105,7 @@ def _gate_cost(
return
pages = sum(p.count for p in plans)
- console.print(f"Estimated: [bold]{pages}[/bold] pages, [bold]{format_cost(est)}[/bold].")
+ console.print(f"[bold]{pages}[/bold] pages. {spend_phrase(est, config.max_concurrency)}.")
structural = structural_page_summary(plans)
if structural:
console.print(f" [dim]{structural}[/dim]")
diff --git a/packages/cli/src/repowise/cli/cost_gate.py b/packages/cli/src/repowise/cli/cost_gate.py
index c023af7ca..f026bc700 100644
--- a/packages/cli/src/repowise/cli/cost_gate.py
+++ b/packages/cli/src/repowise/cli/cost_gate.py
@@ -130,6 +130,26 @@ def cost_gate_blocks(est: Any, *, yes: bool, message: str) -> bool:
return not confirm_cost_gate(message, estimated_usd=est.estimated_cost_usd)
+def spend_phrase(est: Any, concurrency: int | None = None) -> str:
+ """``Estimated $1.20 USD``, or for a subscription CLI its quota and time.
+
+ A subscription seat prices at $0.00 per token, which reads as free; what
+ it really spends is plan usage and wall time, so that is what it shows.
+ *concurrency* is the run's ``--concurrency``; ``None`` means the CLI's own
+ process limit decides.
+ """
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+ spec = PROVIDER_SPECS.get(getattr(est, "provider_name", "") or "")
+ if spec is not None and spec.agent:
+ from repowise.cli.ui.subscription import model_call_count, subscription_estimate
+
+ calls = model_call_count(est.plans)
+ text = subscription_estimate(spec.name, calls, concurrency)
+ return text[0].upper() + text[1:]
+ return f"Estimated [bold]{format_cost(est)}[/bold]"
+
+
def format_cost(est: Any) -> str:
"""Render an estimate as a human-readable USD string (range when known)."""
if est.cost_range is not None:
diff --git a/packages/cli/src/repowise/cli/ui/__init__.py b/packages/cli/src/repowise/cli/ui/__init__.py
index a7a97ce90..e8d3cb8c2 100644
--- a/packages/cli/src/repowise/cli/ui/__init__.py
+++ b/packages/cli/src/repowise/cli/ui/__init__.py
@@ -57,6 +57,7 @@ _LAZY: dict[str, str] = {
"key_value_table": "brand",
"load_dotenv": "env_persistence",
"mini": "mascot",
+ "model_call_count": "subscription",
"print_analysis_summary": "result_panels",
"print_banner": "brand",
"print_files_written": "result_panels",
@@ -67,6 +68,7 @@ _LAZY: dict[str, str] = {
"prompt_file_page_volume": "mode_selection",
"prompt_wiki_style": "mode_selection",
"quick_repo_scan": "repo_scanner",
+ "ready_agent_providers": "subscription",
"should_offer_fast_mode": "mode_selection",
}
diff --git a/packages/cli/src/repowise/cli/ui/model_tier.py b/packages/cli/src/repowise/cli/ui/model_tier.py
new file mode 100644
index 000000000..e4a4336ad
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/model_tier.py
@@ -0,0 +1,55 @@
+"""Whether a model name reads as a flagship tier, for the picker's cost note."""
+
+from __future__ import annotations
+
+import re
+
+# Checked before the flagship tokens: a cheap-tier marker wins even when the
+# family name is a flagship one, so `gpt-5.4-nano` is not mistaken for `gpt-5`.
+_BUDGET_MODEL_TOKENS = (
+ "nano",
+ # OpenAI's 5.6 budget tier carries no cheap-tier word in its name, and
+ # `gpt-5` matches it as flagship. Without this, accepting the default
+ # printed a note advising the user to switch to a cheaper model than the
+ # one they were already on.
+ "luna",
+ "mini",
+ "lite",
+ "haiku",
+ "small",
+ "tiny",
+ "flash",
+ r"\d+b", # 8b, 3b, 270m-style parameter-count tags
+)
+
+_FLAGSHIP_MODEL_TOKENS = (
+ "opus",
+ "gpt-4o",
+ "gpt-5",
+ "gpt-6",
+ "pro",
+ "sonnet",
+ "ultra",
+ "o1",
+ "o3",
+ "o4",
+)
+
+
+def _matches_token(model: str, tokens: tuple[str, ...]) -> bool:
+ """True if any token appears in ``model`` as a whole dash/dot-delimited word.
+
+ Substring matching is wrong here: ``gemini`` contains ``mini`` and
+ ``gpt-5.4-nano`` contains ``gpt-5``.
+ """
+ return any(re.search(rf"(?<![a-z0-9]){tok}(?![a-z])", model) for tok in tokens)
+
+
+def is_flagship_model(model: str) -> bool:
+ """Heuristic: True if the model name suggests a flagship-tier model."""
+ if not model:
+ return False
+ m = model.lower().rsplit("/", 1)[-1]
+ if _matches_token(m, _BUDGET_MODEL_TOKENS):
+ return False
+ return _matches_token(m, _FLAGSHIP_MODEL_TOKENS)
diff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.py
index baa1bbc19..7a9123736 100644
--- a/packages/cli/src/repowise/cli/ui/provider_selection.py
+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import functools
import os
-import re
import socket
from collections.abc import Callable
from dataclasses import dataclass
@@ -17,8 +16,10 @@ from rich.prompt import Prompt
from rich.table import Table
from repowise.cli.errors import reasoned_error
+from repowise.cli.ui import subscription as subscription_module
from repowise.cli.ui.brand import BRAND, BRAND_STYLE, OK, VALUE, WARN
from repowise.cli.ui.env_persistence import _save_key_to_dotenv
+from repowise.cli.ui.model_tier import is_flagship_model
from repowise.cli.ui.openai_compatible import (
discover_models as _discover_openai_compatible_models,
)
@@ -28,6 +29,12 @@ from repowise.cli.ui.openai_compatible import (
from repowise.cli.ui.openai_compatible import (
prompt_setup as _prompt_openai_compatible_setup_values,
)
+from repowise.cli.ui.subscription import (
+ CliAuth,
+ SubscriptionContext,
+ logged_in_agent_providers,
+ subscription_estimate,
+)
from repowise.core.agents.identity import get_identity, identity_for_provider
from repowise.core.providers.llm.base import ProviderModelOption
from repowise.core.providers.llm.specs import PROVIDER_SPECS, ProviderSpec
@@ -52,6 +59,9 @@ _PROVIDER_ENV: dict[str, str] = {
name: spec.required_envs[0] for name, spec in _PICKER_SPECS.items() if spec.required_envs
}
+# No repo preference and no estimate: the picker as other commands show it.
+_NO_SUBSCRIPTION = SubscriptionContext()
+
_OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434"
# The OpenAI adapter is also the generic adapter for local gateways. Keep the
# official endpoint as the prompt default, while letting a user replace it
@@ -77,18 +87,6 @@ class ProviderSelection:
reasoning: ReasoningMode = "auto"
-def _agent_cli_status(name: str) -> tuple[bool, bool]:
- """``(installed, ready)`` for the agent CLI behind provider *name*.
-
- Ready means signed in where the CLI can say so cheaply, else installed:
- an unauthenticated CLI without such a query surfaces on first use.
- """
- agent = identity_for_provider(name)
- if agent is None or not agent.is_installed():
- return False, False
- return True, agent.is_logged_in()
-
-
def agent_providers_set_up(repo_path: Path | None) -> tuple[str, ...]:
"""Agent-CLI providers whose agent is set up as a target here, in picker order.
@@ -165,38 +163,48 @@ def _detect_ollama_status() -> bool:
return False
-def _detect_provider_status() -> dict[str, str]:
+def _detect_provider_status(repo_path: Path | None = None) -> dict[str, str | CliAuth]:
"""Return {provider: what makes it ready} for providers that can be used now.
- The value is the env var carrying the key for the hosted providers, and a
- short description of the out-of-band credential for the local ones. Only
- truthiness is load-bearing; the value is for debugging.
+ Ordered like auto-detection, so the first entry is what ``--yes`` would
+ run: keyed providers first, read from the same process env, repo
+ ``.repowise/.env`` and stored keys, then keys for providers auto-detection
+ skips, then logged-in agent CLIs, then a reachable Ollama. An agent CLI's
+ value is its :class:`CliAuth`, how it is billed; the rest are for debugging.
"""
- status: dict[str, str] = {}
- openai_base_url = (os.environ.get("OPENAI_BASE_URL") or "").rstrip("/")
- openai_has_key = bool((os.environ.get("OPENAI_API_KEY") or "").strip())
+ from repowise.core.providers.llm.resolve import (
+ credentialed_providers,
+ repo_getenv,
+ resolve_api_key,
+ )
+
+ status: dict[str, str | CliAuth] = {}
+ ollama_up = _detect_ollama_status()
+ base_url = (repo_getenv(repo_path)("OPENAI_BASE_URL") or "").rstrip("/")
+ keyed = credentialed_providers(repo_path)
+ for prov in keyed:
+ # An Ollama named by OLLAMA_BASE_URL but not answering is shown as not
+ # ready, the honest state, even though --yes would still try it.
+ if prov not in _PICKER_SPECS or (prov == "ollama" and not ollama_up):
+ continue
+ if prov == "openai" and base_url not in ("", _OPENAI_DEFAULT_BASE_URL):
+ status[_OPENAI_COMPATIBLE_CHOICE] = _PROVIDER_ENV[prov]
+ else:
+ status[prov] = _PROVIDER_ENV.get(prov) or ollama_base_url()
for prov, spec in _PICKER_SPECS.items():
- env_var = _PROVIDER_ENV.get(prov, "")
- if spec.agent:
- if _agent_cli_status(prov)[1]:
- status[prov] = "agent CLI"
- elif prov == "ollama":
- if _detect_ollama_status():
- status[prov] = ollama_base_url()
- elif prov == "openai":
- if openai_has_key and openai_base_url in ("", _OPENAI_DEFAULT_BASE_URL):
- status[prov] = env_var
- elif openai_has_key and openai_base_url:
- status[_OPENAI_COMPATIBLE_CHOICE] = env_var
- elif any(os.environ.get(name) for name in spec.api_key_envs):
- status[prov] = env_var
+ if prov not in keyed and not spec.agent and resolve_api_key(prov, repo_path)[0]:
+ status[prov] = _PROVIDER_ENV[prov]
+ status.update(logged_in_agent_providers())
+ if ollama_up:
+ status.setdefault("ollama", ollama_base_url())
return status
def _agent_cli_setup_lines(name: str) -> list[str]:
agent = identity_for_provider(name)
assert agent is not None, name
- installed, _ = _agent_cli_status(name)
+ # Through the module, so one patch of the probe reaches detection and this.
+ installed, _ = subscription_module.agent_cli_status(name)
problem = (
f"{agent.display_name} CLI is on PATH but not logged in."
if installed
@@ -259,15 +267,17 @@ def _interactive_provider_name(
*,
repo_path: Path | None = None,
save_key: bool = True,
- prefer: tuple[str, ...] = (),
+ subscription: SubscriptionContext = _NO_SUBSCRIPTION,
) -> str:
"""Show provider table, handle selection + inline key entry + save.
The first ready provider in *prefer* (see :func:`agent_providers_set_up`)
- becomes the default. Returns the chosen provider name.
+ becomes the default, else the one auto-detection would pick. With
+ *model_calls*, a ready agent CLI is shown with its quota and time
+ estimate. Returns the chosen provider name.
"""
providers = list(_PROVIDER_CHOICES) # gemini first
- detected = _detect_provider_status()
+ detected = _detect_provider_status(repo_path)
# --- provider table ---
table = Table(
@@ -300,6 +310,18 @@ def _interactive_provider_name(
console.print()
console.print(table)
+ # A subscription run costs quota and time, not dollars: say how it is
+ # billed and how much.
+ for prov, how in detected.items():
+ if not isinstance(how, CliAuth):
+ continue
+ text = how.billing
+ if subscription.model_calls:
+ text = subscription_estimate(
+ prov, subscription.model_calls, subscription.concurrency, how.billing
+ )
+ caveat = "" if how.offer else ", not recommended"
+ console.print(f" [dim]{prov}: {text}{caveat}.[/dim]")
console.print(
" [dim]mock is flag-only (writes placeholder pages): repowise init --provider mock[/dim]"
)
@@ -307,14 +329,12 @@ def _interactive_provider_name(
# --- selection ---
valid_choices = [str(i) for i in range(1, len(providers) + 1)]
- # Default: first detected provider, or gemini (index 1)
- default_idx = "1"
- for idx, prov in enumerate(providers, 1):
- if prov in detected:
- default_idx = str(idx)
- break
+ # Detection order is auto-detection's, so the default is what --yes runs.
+ # A CLI that reports no plan or credentials is never the default.
+ offered = [p for p, how in detected.items() if not isinstance(how, CliAuth) or how.offer]
+ default_idx = str(providers.index(offered[0]) + 1) if offered else "1"
# The CLI of the agent set up here outranks a key: it is the user's own login.
- recommended = next((name for name in prefer if name in detected), None)
+ recommended = next((name for name in subscription.prefer if name in offered), None)
if recommended is not None:
default_idx = str(providers.index(recommended) + 1)
agent = identity_for_provider(recommended)
@@ -358,7 +378,7 @@ def _interactive_provider_name(
model_flag,
repo_path=repo_path,
save_key=save_key,
- prefer=prefer,
+ subscription=subscription,
)
env_var = _PROVIDER_ENV[chosen]
signup_url = _PICKER_SPECS[chosen].signup_url
@@ -381,7 +401,7 @@ def _interactive_provider_name(
model_flag,
repo_path=repo_path,
save_key=save_key,
- prefer=prefer,
+ subscription=subscription,
)
if chosen == "openai" and repo_path is not None:
@@ -631,7 +651,7 @@ def interactive_provider_config_select(
*,
repo_path: Path | None = None,
save_key: bool = True,
- prefer: tuple[str, ...] = (),
+ subscription: SubscriptionContext = _NO_SUBSCRIPTION,
) -> ProviderSelection:
"""Show provider/model/reasoning selection for interactive init.
@@ -643,7 +663,7 @@ def interactive_provider_config_select(
model_flag,
repo_path=repo_path,
save_key=save_key,
- prefer=prefer,
+ subscription=subscription,
)
if chosen == _OPENAI_COMPATIBLE_CHOICE:
return _interactive_openai_compatible_select(
@@ -681,7 +701,7 @@ def interactive_provider_config_select(
repo_path=repo_path,
)
- if not model_flag and _is_flagship_model(selected.model):
+ if not model_flag and is_flagship_model(selected.model):
console.print(
f" [{WARN}]Note:[/] [dim]'{selected.model}' works, but flash-lite / haiku / "
"nano produce equivalent docs at ~10x lower cost on most repos.[/]"
@@ -710,57 +730,6 @@ def interactive_provider_select(
return selection.provider_name, selection.model
-# Checked before the flagship tokens: a cheap-tier marker wins even when the
-# family name is a flagship one, so `gpt-5.4-nano` is not mistaken for `gpt-5`.
-_BUDGET_MODEL_TOKENS = (
- "nano",
- # OpenAI's 5.6 budget tier carries no cheap-tier word in its name, and
- # `gpt-5` matches it as flagship. Without this, accepting the default
- # printed a note advising the user to switch to a cheaper model than the
- # one they were already on.
- "luna",
- "mini",
- "lite",
- "haiku",
- "small",
- "tiny",
- "flash",
- r"\d+b", # 8b, 3b, 270m-style parameter-count tags
-)
-
-_FLAGSHIP_MODEL_TOKENS = (
- "opus",
- "gpt-4o",
- "gpt-5",
- "gpt-6",
- "pro",
- "sonnet",
- "ultra",
- "o1",
- "o3",
- "o4",
-)
-
-
-def _matches_token(model: str, tokens: tuple[str, ...]) -> bool:
- """True if any token appears in ``model`` as a whole dash/dot-delimited word.
-
- Substring matching is wrong here: ``gemini`` contains ``mini`` and
- ``gpt-5.4-nano`` contains ``gpt-5``.
- """
- return any(re.search(rf"(?<![a-z0-9]){tok}(?![a-z])", model) for tok in tokens)
-
-
-def _is_flagship_model(model: str) -> bool:
- """Heuristic: True if the model name suggests a flagship-tier model."""
- if not model:
- return False
- m = model.lower().rsplit("/", 1)[-1]
- if _matches_token(m, _BUDGET_MODEL_TOKENS):
- return False
- return _matches_token(m, _FLAGSHIP_MODEL_TOKENS)
-
-
def _prompt_api_key(
console: Console,
provider: str,
diff --git a/packages/cli/src/repowise/cli/ui/subscription.py b/packages/cli/src/repowise/cli/ui/subscription.py
new file mode 100644
index 000000000..2254261df
--- /dev/null
+++ b/packages/cli/src/repowise/cli/ui/subscription.py
@@ -0,0 +1,257 @@
+"""Own-subscription providers: a logged-in Claude Code, Codex or OpenCode CLI.
+
+Detected and offered, never picked on the user's behalf: the picker shows them
+with a time and quota estimate, and a run that writes no documentation names
+the one it found. Detection lives here so the picker, that note and the init
+plan screen all ask the same question.
+"""
+
+from __future__ import annotations
+
+import importlib
+import json
+import math
+import re
+import subprocess
+from collections.abc import Callable, Iterable
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+
+from repowise.core.agents.identity import CLAUDE_CODE, CODEX, OPENCODE, identity_for_provider
+from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+#: Agent-CLI providers, in picker order.
+AGENT_PROVIDERS: tuple[str, ...] = tuple(
+ spec.name
+ for spec in sorted(PROVIDER_SPECS.values(), key=lambda s: s.picker_rank or 0)
+ if spec.agent and spec.picker_rank is not None
+)
+
+# One page is one CLI process and a full model turn. A serialized 68-page run
+# took about an hour (docs/agent/CLAUDE_CODE_PROVIDER.md), so a minute a call
+# is the planning figure. Rough on purpose: it sizes the wait, not a deadline.
+SECONDS_PER_CALL = 60
+
+
+@dataclass(frozen=True)
+class SubscriptionContext:
+ """What the picker needs to offer an agent CLI.
+
+ *prefer*: agent CLIs set up in this repo, the first ready one becomes the
+ default (see ``agent_providers_set_up``). *model_calls* and *concurrency*
+ size the quota and time estimate; no estimate is shown without calls.
+ """
+
+ prefer: tuple[str, ...] = ()
+ model_calls: int | None = None
+ concurrency: int = 10
+
+
+@dataclass(frozen=True)
+class CliAuth:
+ """How a signed-in agent CLI is billed, as far as its status command says.
+
+ *billing* is what the user is told; it never claims the run is free.
+ *offer* is False when the CLI reports no paid plan or no credentials: it
+ stays selectable in the picker, but nothing recommends it.
+ """
+
+ billing: str
+ offer: bool = True
+
+
+def _unknown(label: str) -> CliAuth:
+ return CliAuth(f"{label} login; it runs on whatever that login is billed to")
+
+
+def _claude_auth(out: str) -> CliAuth | None:
+ try:
+ data = json.loads(out)
+ except ValueError:
+ return _unknown("Claude Code")
+ if not isinstance(data, dict) or not data.get("loggedIn"):
+ return None
+ backend = data.get("apiProvider")
+ if backend and backend != "firstParty":
+ return CliAuth(f"runs through {backend}: billed to that cloud account")
+ method = str(data.get("authMethod") or "")
+ if method == "claude.ai":
+ plan = data.get("subscriptionType")
+ if plan and plan != "free":
+ return CliAuth(f"Claude {plan} plan: uses your plan quota")
+ return CliAuth("signed in without a paid Claude plan", offer=False)
+ if "key" in method.lower() or method == "console":
+ return CliAuth("API key: billed per token")
+ return _unknown("Claude Code")
+
+
+def _codex_auth(out: str) -> CliAuth | None:
+ text = out.lower()
+ if "not logged in" in text:
+ return None
+ if "chatgpt" in text:
+ # The CLI cannot say whether that ChatGPT plan still includes Codex, and
+ # a lapsed plan stays signed in, so this login is picker-only.
+ return CliAuth(
+ "signed in with ChatGPT: uses that plan's Codex quota, if the plan is active",
+ offer=False,
+ )
+ if "api key" in text:
+ return CliAuth("API key: billed per token")
+ return _unknown("Codex CLI")
+
+
+_ANSI = re.compile(r"\x1b\[[0-9;]*m")
+
+
+def _opencode_auth(out: str) -> CliAuth | None:
+ found = re.search(r"(\d+)\s+credentials?", _ANSI.sub("", out))
+ if found is None:
+ return _unknown("OpenCode")
+ if found.group(1) == "0":
+ return CliAuth(
+ "no stored credentials: runs on whatever provider its own config names",
+ offer=False,
+ )
+ return CliAuth("runs on the provider its stored credentials name, billed there")
+
+
+# Per agent: a status command that answers without a model call, and how to
+# read it. OpenCode has no login query, but ``auth list`` counts credentials.
+_AUTH_PROBES: dict[str, tuple[tuple[str, ...], Callable[[str], CliAuth | None]]] = {
+ CLAUDE_CODE.slug: (CLAUDE_CODE.login_check, _claude_auth),
+ CODEX.slug: (CODEX.login_check, _codex_auth),
+ OPENCODE.slug: (("auth", "list"), _opencode_auth),
+}
+
+
+def agent_cli_auth(name: str) -> CliAuth | None:
+ """How the agent CLI behind *name* is signed in; ``None`` when it is not."""
+ agent = identity_for_provider(name)
+ command = agent.which() if agent is not None else None
+ if command is None:
+ return None
+ probe = _AUTH_PROBES.get(agent.slug)
+ if probe is None:
+ return None
+ args, parse = probe
+ try:
+ # DEVNULL: an inherited Windows console stdin can block until the timeout.
+ result = subprocess.run(
+ [command, *args],
+ stdin=subprocess.DEVNULL,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=10,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ if result.returncode != 0:
+ return None
+ return parse(f"{result.stdout}\n{result.stderr}".strip())
+
+
+def agent_cli_status(name: str) -> tuple[bool, bool]:
+ """``(installed, signed in)`` for the agent CLI behind provider *name*."""
+ agent = identity_for_provider(name)
+ if agent is None or not agent.is_installed():
+ return False, False
+ return True, agent_cli_auth(name) is not None
+
+
+def logged_in_agent_providers() -> dict[str, CliAuth]:
+ """Signed-in agent CLIs and how each is billed, in picker order.
+
+ Each status check is a short subprocess, so they run side by side.
+ """
+ with ThreadPoolExecutor(max_workers=len(AGENT_PROVIDERS) or 1) as pool:
+ auths = list(pool.map(agent_cli_auth, AGENT_PROVIDERS))
+ return {
+ name: auth for name, auth in zip(AGENT_PROVIDERS, auths, strict=True) if auth is not None
+ }
+
+
+def ready_agent_providers() -> tuple[str, ...]:
+ """Signed-in agent CLIs worth offering, in picker order (Claude Code first)."""
+ return tuple(name for name, auth in logged_in_agent_providers().items() if auth.offer)
+
+
+def process_limit(provider_name: str) -> int:
+ """How many CLI processes *provider_name* runs at once."""
+ spec = PROVIDER_SPECS[provider_name]
+ cls = getattr(importlib.import_module(spec.module_path), spec.class_name)
+ return int(cls.process_limit())
+
+
+def model_call_count(plans: Iterable[object]) -> int:
+ """Model calls a generation plan makes: one per page a model writes."""
+ from repowise.core.cost_estimator import STRUCTURAL_PAGE_TYPES
+
+ return sum(
+ int(getattr(plan, "count", 0))
+ for plan in plans
+ if getattr(plan, "page_type", None) not in STRUCTURAL_PAGE_TYPES
+ )
+
+
+def subscription_estimate(
+ provider_name: str,
+ model_calls: int,
+ concurrency: int | None = None,
+ billing: str | None = None,
+) -> str:
+ """``uses your Claude Code login, about 14 model calls, 4 at a time, about 4 min``.
+
+ What a subscription run costs is quota and time, not dollars, so this is
+ what stands where an API provider shows its price. *concurrency* is the
+ run's ``--concurrency``; the CLI's own process limit caps it. *billing*
+ (from :func:`agent_cli_auth`) replaces the generic login note.
+ """
+ limit = process_limit(provider_name)
+ parallel = max(1, min(concurrency, limit) if concurrency else limit)
+ minutes = max(1, math.ceil(math.ceil(model_calls / parallel) * SECONDS_PER_CALL / 60))
+ calls = "call" if model_calls == 1 else "calls"
+ return (
+ f"{billing or PROVIDER_SPECS[provider_name].note}, "
+ f"about {model_calls:,} model {calls}, "
+ f"{parallel} at a time, about {minutes:,} min"
+ )
+
+
+def subscription_note(ready: tuple[str, ...], auth: CliAuth | None = None) -> str | None:
+ """One line naming the first ready subscription CLI and the command that uses it.
+
+ For a run that writes no documentation with a model: it never switches
+ the run to the CLI, it says how to and how that CLI is billed. *auth* is
+ probed when not given.
+ """
+ if not ready:
+ return None
+ name = ready[0]
+ agent = identity_for_provider(name)
+ if agent is None:
+ return None
+ auth = auth or agent_cli_auth(name)
+ billing = auth.billing if auth is not None else PROVIDER_SPECS[name].note
+ return (
+ f"{agent.display_name} is signed in ({billing}). Run [bold]repowise update "
+ f"--full --provider {name}[/bold] to have it write the documentation."
+ )
+
+
+__all__ = [
+ "AGENT_PROVIDERS",
+ "SECONDS_PER_CALL",
+ "CliAuth",
+ "SubscriptionContext",
+ "agent_cli_auth",
+ "agent_cli_status",
+ "logged_in_agent_providers",
+ "model_call_count",
+ "process_limit",
+ "ready_agent_providers",
+ "subscription_estimate",
+ "subscription_note",
+]
diff --git a/packages/core/src/repowise/core/providers/llm/agent_cli.py b/packages/core/src/repowise/core/providers/llm/agent_cli.py
index 580660b2c..d8bc9260a 100644
--- a/packages/core/src/repowise/core/providers/llm/agent_cli.py
+++ b/packages/core/src/repowise/core/providers/llm/agent_cli.py
@@ -231,12 +231,15 @@ class AgentCliProvider(BaseProvider):
return candidate
return self.stdout_error(stdout) or f"{self.command_label} exited with {returncode}"
+ @classmethod
+ def process_limit(cls) -> int:
+ """How many CLI processes run at once, whatever ``--concurrency`` says."""
+ return resolve_concurrency(cls.concurrency_env, cls.provider_name)
+
def _get_semaphore(self) -> asyncio.Semaphore:
loop = asyncio.get_running_loop()
if self._semaphore_loop is not loop:
- self._semaphore = asyncio.Semaphore(
- resolve_concurrency(self.concurrency_env, self.provider_name)
- )
+ self._semaphore = asyncio.Semaphore(self.process_limit())
self._semaphore_loop = loop
return self._semaphore # type: ignore[return-value]
diff --git a/packages/core/src/repowise/core/providers/llm/claude_cli.py b/packages/core/src/repowise/core/providers/llm/claude_cli.py
index 5f5da7779..2a524fad1 100644
--- a/packages/core/src/repowise/core/providers/llm/claude_cli.py
+++ b/packages/core/src/repowise/core/providers/llm/claude_cli.py
@@ -23,6 +23,7 @@ from __future__ import annotations
import contextlib
import json
+import os
import tempfile
from collections.abc import Iterator
from pathlib import Path
@@ -63,6 +64,25 @@ _TOOLLESS_SYSTEM_INSTRUCTION = (
"Answer the user directly in a single response."
)
+# Run from inside a Claude Code session (an agent calling ``repowise init``),
+# the child inherits the parent's session id and its IPC socket and token, so
+# the child's SessionEnd hooks try to reach the parent session and fail. Only
+# the markers of that one session go: auth and backend settings
+# (CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_OAUTH_TOKEN, ...) still pass through.
+_PARENT_SESSION_VARS = frozenset(
+ {
+ "CLAUDECODE",
+ "CLAUDE_PID",
+ "CLAUDE_CODE_ENTRYPOINT",
+ "CLAUDE_CODE_EXECPATH",
+ "CLAUDE_CODE_SESSION_ID",
+ "CLAUDE_CODE_CHILD_SESSION",
+ "CLAUDE_CODE_SESSION_ATTENDED",
+ "CLAUDE_CODE_MESSAGING_SOCKET",
+ "CLAUDE_CODE_MESSAGING_TOKEN",
+ }
+)
+
_SUPPORTED_REASONING_MODES: tuple[ReasoningMode, ...] = (
"auto",
"low",
@@ -227,6 +247,9 @@ class ClaudeCliProvider(AgentCliProvider):
log.warning("claude_cli.reasoning.unsupported", requested=mode, using="auto")
return cmd
+ def subprocess_env(self) -> dict[str, str]:
+ return {k: v for k, v in os.environ.items() if k not in _PARENT_SESSION_VARS}
+
@contextlib.contextmanager
def working_dir(self) -> Iterator[str]:
# One directory per call avoids both CLAUDE.md discovery and state
diff --git a/packages/core/src/repowise/core/providers/llm/resolve.py b/packages/core/src/repowise/core/providers/llm/resolve.py
index a1057a0e7..372e37f88 100644
--- a/packages/core/src/repowise/core/providers/llm/resolve.py
+++ b/packages/core/src/repowise/core/providers/llm/resolve.py
@@ -450,15 +450,28 @@ def _base_url_steps(ctx: _Context, chosen: str) -> list[Step]:
return steps
-def _autodetect(ctx: _Context) -> str | None:
+def _credentialed(ctx: _Context) -> Iterable[str]:
keys = ctx.global_config.get("keys")
stored = keys if isinstance(keys, Mapping) else {}
for name in PROVIDER_AUTODETECT_ORDER:
if not ctx.counts(name):
continue
if provider_credentials_present(name, ctx.getenv) or _clean(stored.get(name)):
- return name
- return None
+ yield name
+
+
+def _autodetect(ctx: _Context) -> str | None:
+ return next(iter(_credentialed(ctx)), None)
+
+
+def credentialed_providers(repo_path: Path | str | None = None) -> tuple[str, ...]:
+ """Every provider auto-detection could pick for *repo_path*, in its order.
+
+ The same keys and order :func:`resolve_llm` reads (process env, the repo's
+ ``.env``, stored keys), so a picker that defaults to the first of these
+ agrees with what ``--yes`` would run.
+ """
+ return tuple(_credentialed(_context(repo_path, _Layer("flag", None, None), None, None)))
def resolve_api_key(
@@ -648,6 +661,7 @@ __all__ = [
"base_url_trusted",
"cached_read",
"clear_cache",
+ "credentialed_providers",
"first_found",
"forget_cached",
"found",
diff --git a/packages/core/src/repowise/core/providers/llm/specs.py b/packages/core/src/repowise/core/providers/llm/specs.py
index 2cc4ff58d..c2609922c 100644
--- a/packages/core/src/repowise/core/providers/llm/specs.py
+++ b/packages/core/src/repowise/core/providers/llm/specs.py
@@ -252,7 +252,7 @@ _SPECS: tuple[ProviderSpec, ...] = (
),
ProviderSpec(
name="claude_cli",
- picker_rank=7,
+ picker_rank=6,
impl=f"{_LLM}.claude_cli:ClaudeCliProvider",
label="Claude Code (Local CLI)",
default_model="claude_cli/claude-haiku-5-5",
@@ -271,7 +271,7 @@ _SPECS: tuple[ProviderSpec, ...] = (
),
ProviderSpec(
name="codex_cli",
- picker_rank=6,
+ picker_rank=7,
impl=f"{_LLM}.codex_cli:CodexCliProvider",
label="Codex (Local CLI)",
default_model="codex_cli/default",
diff --git a/tests/unit/cli/test_init_agent_backend.py b/tests/unit/cli/test_init_agent_backend.py
index c4d1fd980..be79a9a4f 100644
--- a/tests/unit/cli/test_init_agent_backend.py
+++ b/tests/unit/cli/test_init_agent_backend.py
@@ -12,6 +12,7 @@ from rich.console import Console
from repowise.cli.agent_targets import registry
from repowise.cli.commands.init_cmd.command import _interactive_gate
from repowise.cli.ui import provider_selection as ui
+from repowise.cli.ui.subscription import SubscriptionContext
from repowise.core.agents.identity import identity_for_target_id
@@ -36,7 +37,7 @@ def _default_pick(
monkeypatch: Any, detected: dict[str, str], prefer: tuple[str, ...]
) -> tuple[str, str]:
"""The provider the picker offers as its default, and what it printed."""
- monkeypatch.setattr(ui, "_detect_provider_status", lambda: detected)
+ monkeypatch.setattr(ui, "_detect_provider_status", lambda *_a: detected)
seen: dict[str, str] = {}
def ask(*_a: object, default: str, **_k: object) -> str:
@@ -45,7 +46,9 @@ def _default_pick(
monkeypatch.setattr(ui.Prompt, "ask", ask)
buf = io.StringIO()
- ui._interactive_provider_name(Console(file=buf, width=120), None, prefer=prefer)
+ ui._interactive_provider_name(
+ Console(file=buf, width=120), None, subscription=SubscriptionContext(prefer=prefer)
+ )
return ui._PROVIDER_CHOICES[int(seen["default"]) - 1], buf.getvalue()
@@ -119,14 +122,14 @@ def test_opencode_reason_does_not_claim_a_login(monkeypatch: Any) -> None:
def test_setup_text_for_a_missing_opencode_claims_no_login(monkeypatch: Any) -> None:
- monkeypatch.setattr(ui, "_agent_cli_status", lambda _name: (False, False))
+ monkeypatch.setattr("repowise.cli.ui.subscription.agent_cli_status", lambda _name: (False, False))
text = " ".join(ui._agent_cli_setup_lines("opencode"))
assert "uses your opencode CLI setup" in text
assert "login" not in text
def test_setup_text_for_claude_names_the_auth_login(monkeypatch: Any) -> None:
- monkeypatch.setattr(ui, "_agent_cli_status", lambda _name: (True, False))
+ monkeypatch.setattr("repowise.cli.ui.subscription.agent_cli_status", lambda _name: (True, False))
text = " ".join(ui._agent_cli_setup_lines("claude_cli"))
assert "uses your Claude Code login" in text
assert "claude auth login" in text
diff --git a/tests/unit/cli/test_init_ux.py b/tests/unit/cli/test_init_ux.py
index 0e8aa194b..543a7c3ad 100644
--- a/tests/unit/cli/test_init_ux.py
+++ b/tests/unit/cli/test_init_ux.py
@@ -151,14 +151,14 @@ def test_ollama_is_ready_when_the_endpoint_answers(monkeypatch: Any) -> None:
"""It takes no API key, so reachability is the only question worth asking."""
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: True)
- monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
+ monkeypatch.setattr("repowise.cli.ui.subscription.agent_cli_auth", lambda _name: None)
assert provider_selection._detect_provider_status()["ollama"] == "http://localhost:11434"
def test_ollama_is_not_ready_when_nothing_is_listening(monkeypatch: Any) -> None:
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)
- monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
+ monkeypatch.setattr("repowise.cli.ui.subscription.agent_cli_auth", lambda _name: None)
assert "ollama" not in provider_selection._detect_provider_status()
@@ -257,7 +257,7 @@ def test_the_keyless_providers_get_setup_help_instead_of_a_key_prompt() -> None:
def test_selecting_an_unreachable_ollama_never_prompts_for_a_key(monkeypatch: Any) -> None:
console, buf = _console()
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)
- monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
+ monkeypatch.setattr("repowise.cli.ui.subscription.agent_cli_auth", lambda _name: None)
def boom(*_args: object, **_kwargs: object) -> str:
raise AssertionError("ollama has no API key to prompt for")
@@ -268,7 +268,7 @@ def test_selecting_an_unreachable_ollama_never_prompts_for_a_key(monkeypatch: An
# follows the ollama help, openai is configured so the run can terminate.
renders: list[int] = []
- def detect() -> dict[str, str]:
+ def detect(*_a: object) -> dict[str, str]:
renders.append(1)
return {} if len(renders) == 1 else {"openai": "OPENAI_API_KEY"}
@@ -348,7 +348,7 @@ def test_explicit_openai_setup_prompts_for_url_when_key_is_already_set(
def test_provider_status_separates_official_and_custom_openai(monkeypatch: Any) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "router-secret")
monkeypatch.setenv("OPENAI_BASE_URL", "http://localhost:20128/v1")
- monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
+ monkeypatch.setattr("repowise.cli.ui.subscription.agent_cli_auth", lambda _name: None)
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)
custom_status = provider_selection._detect_provider_status()
@@ -366,7 +366,7 @@ def test_official_openai_reuses_key_from_previous_custom_setup(
) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "existing-secret")
monkeypatch.setenv("OPENAI_BASE_URL", "http://localhost:20128/v1")
- monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
+ monkeypatch.setattr("repowise.cli.ui.subscription.agent_cli_auth", lambda _name: None)
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)
openai_idx = str(provider_selection._PROVIDER_CHOICES.index("openai") + 1)
monkeypatch.setattr(provider_selection.Prompt, "ask", lambda *_a, **_k: openai_idx)
@@ -395,7 +395,7 @@ def test_custom_gateway_picker_discovers_model_and_persists_setup(
) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "")
monkeypatch.setenv("OPENAI_BASE_URL", "")
- monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda: {})
+ monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda *_a: {})
monkeypatch.setattr(
provider_selection,
"_discover_openai_compatible_models",
@@ -446,7 +446,7 @@ def test_custom_gateway_picker_allows_manual_model_when_discovery_fails(
monkeypatch.setenv("REPOWISE_NO_SAVE_KEY", "")
monkeypatch.setenv("OPENAI_API_KEY", "")
monkeypatch.setenv("OPENAI_BASE_URL", "")
- monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda: {})
+ monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda *_a: {})
monkeypatch.setattr(
provider_selection,
"_discover_openai_compatible_models",
@@ -481,7 +481,7 @@ def test_custom_gateway_no_save_key_still_persists_endpoint(
monkeypatch.setenv("REPOWISE_NO_SAVE_KEY", "")
monkeypatch.setenv("OPENAI_API_KEY", "")
monkeypatch.setenv("OPENAI_BASE_URL", "")
- monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda: {})
+ monkeypatch.setattr(provider_selection, "_detect_provider_status", lambda *_a: {})
provider_idx = str(
provider_selection._PROVIDER_CHOICES.index(provider_selection._OPENAI_COMPATIBLE_CHOICE) + 1
)
@@ -515,8 +515,8 @@ def test_picker_rows_keep_their_order() -> None:
"deepseek",
"kimi",
"edenai",
- "codex_cli",
"claude_cli",
+ "codex_cli",
"opencode",
"ollama",
"openrouter",
diff --git a/tests/unit/cli/test_subscription_providers.py b/tests/unit/cli/test_subscription_providers.py
new file mode 100644
index 000000000..607facc4c
--- /dev/null
+++ b/tests/unit/cli/test_subscription_providers.py
@@ -0,0 +1,277 @@
+"""Own-subscription providers are detected and offered, never picked for the user."""
+
+from __future__ import annotations
+
+import io
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from rich.console import Console
+
+from repowise.cli.commands.init_cmd import _provider
+from repowise.cli.cost_gate import spend_phrase
+from repowise.cli.ui import provider_selection as ui
+from repowise.cli.ui import subscription
+from repowise.core.cost_estimator import approximate_generation_plan, estimate_cost
+from repowise.core.providers.llm import resolve
+from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+_KEYS = tuple(
+ var for spec in PROVIDER_SPECS.values() for var in (*spec.api_key_envs, *spec.base_url_envs)
+)
+
+
[email protected](autouse=True)
+def _no_keys(monkeypatch: Any, tmp_path: Path) -> None:
+ for var in (*_KEYS, "REPOWISE_PROVIDER", "REPOWISE_CLAUDE_CLI_CONCURRENCY"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("REPOWISE_CONFIG_DIR", str(tmp_path / "global"))
+ monkeypatch.setattr(ui, "_detect_ollama_status", lambda: False)
+ resolve.clear_cache()
+
+
+_PLAN = subscription.CliAuth("Claude team plan: uses your plan quota")
+
+
+def _logged_in(monkeypatch: Any, *names: str, auth: Any = _PLAN) -> None:
+ monkeypatch.setattr(subscription, "agent_cli_auth", lambda name: auth if name in names else None)
+
+
+def _default_pick(monkeypatch: Any, repo: Path | None = None, **kwargs: Any) -> tuple[str, str]:
+ seen: dict[str, str] = {}
+
+ def ask(*_a: object, default: str, **_k: object) -> str:
+ seen["default"] = default
+ return default
+
+ monkeypatch.setattr(ui.Prompt, "ask", ask)
+ buf = io.StringIO()
+ ui._interactive_provider_name(Console(file=buf, width=160), None, repo_path=repo, **kwargs)
+ return ui._PROVIDER_CHOICES[int(seen["default"]) - 1], buf.getvalue()
+
+
+# -- detection ----------------------------------------------------------------
+
+
+def test_ready_agent_providers_lists_only_logged_in_clis(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "claude_cli")
+ assert subscription.ready_agent_providers() == ("claude_cli",)
+ _logged_in(monkeypatch)
+ assert subscription.ready_agent_providers() == ()
+
+
+def test_picker_and_note_share_one_detection(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "codex_cli", "claude_cli")
+ detected = ui._detect_provider_status()
+ assert [p for p in detected if PROVIDER_SPECS[p].agent] == list(
+ subscription.ready_agent_providers()
+ )
+
+
+# -- picker: same keys and order as auto-detection ------------------------------
+
+
+def test_picker_default_matches_autodetect_order(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch)
+ monkeypatch.setenv("GEMINI_API_KEY", "g")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "a")
+ assert resolve.resolve_llm(None).provider == "anthropic"
+ assert _default_pick(monkeypatch)[0] == "anthropic"
+
+
+def test_picker_reads_repo_env_and_stored_keys(monkeypatch: Any, tmp_path: Path) -> None:
+ _logged_in(monkeypatch)
+ repo = tmp_path / "repo"
+ (repo / ".repowise").mkdir(parents=True)
+ (repo / ".repowise" / ".env").write_text("DEEPSEEK_API_KEY=d\n", encoding="utf-8")
+ stored = tmp_path / "global" / "provider_config.json"
+ stored.parent.mkdir(parents=True)
+ stored.write_text(json.dumps({"keys": {"kimi": "k"}}), encoding="utf-8")
+
+ detected = ui._detect_provider_status(repo)
+
+ assert list(detected) == ["deepseek", "kimi"]
+ assert _default_pick(monkeypatch, repo)[0] == "deepseek"
+
+
+def test_a_key_outranks_a_logged_in_cli_without_a_preference(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "claude_cli")
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
+ assert _default_pick(monkeypatch)[0] == "openai"
+
+
+def test_picker_shows_quota_and_time_for_a_logged_in_cli(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "claude_cli")
+ _chosen, out = _default_pick(
+ monkeypatch, subscription=subscription.SubscriptionContext(model_calls=14, concurrency=10)
+ )
+ assert "claude_cli: Claude team plan: uses your plan quota, about 14 model calls, 4 at a time" in out
+ assert "about 4 min" in out
+ assert "$0.00" not in out
+
+
+def test_picker_without_an_estimate_prints_no_quota_line(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "claude_cli")
+ assert "model calls" not in _default_pick(monkeypatch)[1]
+
+
+# -- the estimate ---------------------------------------------------------------
+
+
+def test_estimate_divides_calls_by_the_process_limit(monkeypatch: Any) -> None:
+ text = subscription.subscription_estimate("claude_cli", 40, 10)
+ assert "about 40 model calls, 4 at a time, about 10 min" in text
+ monkeypatch.setenv("REPOWISE_CLAUDE_CLI_CONCURRENCY", "8")
+ assert "8 at a time, about 5 min" in subscription.subscription_estimate("claude_cli", 40, 10)
+ # A lower --concurrency still lowers it.
+ assert "2 at a time, about 20 min" in subscription.subscription_estimate("claude_cli", 40, 2)
+
+
+def test_spend_phrase_prices_api_providers_and_estimates_subscriptions() -> None:
+ plans = approximate_generation_plan(50)
+ calls = subscription.model_call_count(plans)
+ cli = spend_phrase(estimate_cost(plans, "claude_cli", "claude_cli/claude-haiku-5-5"), 10)
+ assert cli.startswith("Uses your Claude Code login")
+ assert f"about {calls} model calls" in cli
+ assert "$" not in cli
+ assert spend_phrase(estimate_cost(plans, "gemini", "gemini-3.5-flash-lite")).startswith(
+ "Estimated"
+ )
+
+
+# -- the --yes note -------------------------------------------------------------
+
+
+def _run(**overrides: Any) -> SimpleNamespace:
+ opts = SimpleNamespace(provider_name=overrides.pop("provider_name", None), index_only=True)
+ fields: dict[str, Any] = {"is_interactive": False, "config": {}, "no_provider": False}
+ return SimpleNamespace(opts=opts, **{**fields, **overrides})
+
+
+def _note(monkeypatch: Any, run: SimpleNamespace) -> str:
+ buf = io.StringIO()
+ monkeypatch.setattr(_provider, "console", Console(file=buf, width=200))
+ _provider.note_subscription_cli(run)
+ return buf.getvalue()
+
+
+def test_yes_run_names_the_logged_in_cli_and_stays_free(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "claude_cli")
+ out = _note(monkeypatch, _run())
+ assert "Claude Code is signed in (Claude team plan: uses your plan quota)" in out
+ assert "repowise update --full --provider claude_cli" in out
+
+
+ "overrides",
+ [
+ {"provider_name": "gemini"},
+ {"is_interactive": True},
+ {"config": {"provider": "openai"}},
+ ],
+)
+def test_note_is_quiet_when_the_user_already_chose(monkeypatch: Any, overrides: dict) -> None:
+ _logged_in(monkeypatch, "claude_cli")
+ assert _note(monkeypatch, _run(**overrides)) == ""
+
+
+def test_note_is_quiet_when_a_model_writes_the_docs(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "claude_cli")
+ run = _run()
+ run.opts.index_only = False
+ assert _note(monkeypatch, run) == ""
+
+
+def test_note_is_quiet_without_a_logged_in_cli(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch)
+ assert _note(monkeypatch, _run()) == ""
+
+
+def test_claude_code_is_named_before_codex(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "codex_cli", "claude_cli")
+ assert subscription.ready_agent_providers()[0] == "claude_cli"
+ assert "Claude Code is signed in" in _note(monkeypatch, _run())
+
+
+def test_a_cli_without_a_plan_is_listed_but_never_offered(monkeypatch: Any) -> None:
+ _logged_in(monkeypatch, "opencode", auth=subscription.CliAuth("no plan", offer=False))
+ assert subscription.ready_agent_providers() == ()
+ assert _note(monkeypatch, _run()) == ""
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
+ chosen, out = _default_pick(
+ monkeypatch, subscription=subscription.SubscriptionContext(prefer=("opencode",))
+ )
+ assert chosen == "openai"
+ assert "opencode: no plan, not recommended" in out
+
+
+# -- what each CLI's status command says ------------------------------------------
+
+
+def _claude(**fields: Any) -> str:
+ return json.dumps({"loggedIn": True, "apiProvider": "firstParty", **fields})
+
+
+ ("name", "output", "billing", "offer"),
+ [
+ ("claude_cli", _claude(authMethod="claude.ai", subscriptionType="max"),
+ "Claude max plan: uses your plan quota", True),
+ ("claude_cli", _claude(authMethod="claude.ai", subscriptionType=None),
+ "signed in without a paid Claude plan", False),
+ ("claude_cli", _claude(authMethod="api_key"), "API key: billed per token", True),
+ ("claude_cli", _claude(authMethod="claude.ai", apiProvider="bedrock"),
+ "runs through bedrock: billed to that cloud account", True),
+ ("claude_cli", "not json", "Claude Code login; it runs on whatever that login is "
+ "billed to", True),
+ ("codex_cli", "Logged in using ChatGPT",
+ "signed in with ChatGPT: uses that plan's Codex quota, if the plan is active", False),
+ ("codex_cli", "Logged in using an API key - sk-proj-***", "API key: billed per token",
+ True),
+ ("codex_cli", "Logged in somehow", "Codex CLI login; it runs on whatever that login "
+ "is billed to", True),
+ ("opencode", "\x1b[0m\u250c Credentials\n\u2514 0 credentials",
+ "no stored credentials: runs on whatever provider its own config names", False),
+ ("opencode", "\u2514 2 credentials",
+ "runs on the provider its stored credentials name, billed there", True),
+ ],
+)
+def test_status_output_maps_to_billing(
+ monkeypatch: Any, name: str, output: str, billing: str, offer: bool
+) -> None:
+ import subprocess
+
+ from repowise.core.agents.identity import AgentIdentity
+
+ monkeypatch.setattr(AgentIdentity, "which", lambda self: self.executable)
+ monkeypatch.setattr(
+ subprocess, "run", lambda args, **_k: subprocess.CompletedProcess(args, 0, output, "")
+ )
+ assert subscription.agent_cli_auth(name) == subscription.CliAuth(billing, offer)
+
+
+ ("name", "returncode", "output"),
+ [
+ ("claude_cli", 1, _claude(loggedIn=False)),
+ ("claude_cli", 0, json.dumps({"loggedIn": False})),
+ ("codex_cli", 1, "Not logged in"),
+ ],
+)
+def test_signed_out_cli_is_not_detected(
+ monkeypatch: Any, name: str, returncode: int, output: str
+) -> None:
+ import subprocess
+
+ from repowise.core.agents.identity import AgentIdentity
+
+ monkeypatch.setattr(AgentIdentity, "which", lambda self: self.executable)
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda args, **_k: subprocess.CompletedProcess(args, returncode, output, ""),
+ )
+ assert subscription.agent_cli_auth(name) is None
diff --git a/tests/unit/cli/test_ui_codex.py b/tests/unit/cli/test_ui_codex.py
index 719d459a2..41525b611 100644
--- a/tests/unit/cli/test_ui_codex.py
+++ b/tests/unit/cli/test_ui_codex.py
@@ -1,20 +1,47 @@
from __future__ import annotations
+import subprocess
from typing import Any
from repowise.cli.ui import provider_selection as ui
from repowise.core.agents.identity import AgentIdentity
-def test_detect_provider_status_requires_codex_login(monkeypatch: Any) -> None:
- monkeypatch.setattr(AgentIdentity, "is_installed", lambda self: True)
- monkeypatch.setattr(AgentIdentity, "is_logged_in", lambda self: self.slug != "codex")
+def _codex_says(monkeypatch: Any, returncode: int, text: str) -> None:
+ """Every agent CLI on PATH; only codex answers its status command."""
+ monkeypatch.setattr(AgentIdentity, "which", lambda self: self.executable)
+
+ def run(args: list[str], **_k: Any) -> subprocess.CompletedProcess[str]:
+ if args[0] == "codex":
+ return subprocess.CompletedProcess(args, returncode, text, "")
+ return subprocess.CompletedProcess(args, 1, "", "")
+
+ monkeypatch.setattr(subprocess, "run", run)
+
+def test_detect_provider_status_requires_codex_login(monkeypatch: Any) -> None:
+ _codex_says(monkeypatch, 1, "Not logged in")
assert "codex_cli" not in ui._detect_provider_status()
def test_detect_provider_status_accepts_authenticated_codex(monkeypatch: Any) -> None:
- monkeypatch.setattr(AgentIdentity, "is_installed", lambda self: True)
- monkeypatch.setattr(AgentIdentity, "is_logged_in", lambda self: True)
+ _codex_says(monkeypatch, 0, "Logged in using ChatGPT")
+ assert "codex_cli" in ui._detect_provider_status()
+
+def test_codex_through_chatgpt_is_picker_only(monkeypatch: Any) -> None:
+ """A lapsed ChatGPT plan stays signed in, so this login is never recommended."""
+ from repowise.cli.ui import subscription
+
+ _codex_says(monkeypatch, 0, "Logged in using ChatGPT")
assert "codex_cli" in ui._detect_provider_status()
+ assert "codex_cli" not in subscription.ready_agent_providers()
+ auth = subscription.agent_cli_auth("codex_cli")
+ assert auth is not None and not auth.offer
+
+
+def test_codex_with_an_api_key_is_offered(monkeypatch: Any) -> None:
+ from repowise.cli.ui import subscription
+
+ _codex_says(monkeypatch, 0, "Logged in using an API key - sk-proj-***")
+ assert subscription.ready_agent_providers() == ("codex_cli",)
diff --git a/tests/unit/cli/test_ui_reasoning.py b/tests/unit/cli/test_ui_reasoning.py
index 1259ac409..cfcdc608d 100644
--- a/tests/unit/cli/test_ui_reasoning.py
+++ b/tests/unit/cli/test_ui_reasoning.py
@@ -80,9 +80,9 @@ def test_interactive_provider_config_select_uses_model_reasoning_options(
monkeypatch: Any,
) -> None:
monkeypatch.setattr(
- provider_selection, "_detect_provider_status", lambda: {"gemini": "GEMINI_API_KEY"}
+ provider_selection, "_detect_provider_status", lambda *_a: {"gemini": "GEMINI_API_KEY"}
)
- monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
+ monkeypatch.setattr("repowise.cli.ui.subscription.agent_cli_auth", lambda _name: None)
monkeypatch.setattr(
provider_selection,
"_provider_model_options",
diff --git a/tests/unit/test_providers/test_agent_cli_contract.py b/tests/unit/test_providers/test_agent_cli_contract.py
index 40ea7587d..658132b91 100644
--- a/tests/unit/test_providers/test_agent_cli_contract.py
+++ b/tests/unit/test_providers/test_agent_cli_contract.py
@@ -83,7 +83,8 @@ BACKENDS = [
tokens=(140, 40, 30),
books_cost=True,
repo_flag=None,
- env=None,
+ # A filtered copy of the parent env (nested-session markers removed).
+ env={},
),
Backend(
CodexCliProvider,
diff --git a/tests/unit/test_providers/test_claude_cli_provider.py b/tests/unit/test_providers/test_claude_cli_provider.py
index 21662aaea..5d9d34f8f 100644
--- a/tests/unit/test_providers/test_claude_cli_provider.py
+++ b/tests/unit/test_providers/test_claude_cli_provider.py
@@ -642,3 +642,19 @@ def test_resolves_through_the_registry(claude_on_path):
provider = get_provider("claude_cli")
assert provider.provider_name == "claude_cli"
assert provider.model_name == "claude_cli/claude-haiku-5-5"
+
+
+def test_nested_session_markers_are_stripped(claude_on_path, monkeypatch):
+ """Run from inside Claude Code, the child must not inherit the parent session."""
+ for name in ("CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CLAUDE_CODE_MESSAGING_TOKEN"):
+ monkeypatch.setenv(name, "parent")
+ monkeypatch.setenv("CLAUDE_CODE_USE_BEDROCK", "1")
+ monkeypatch.setenv("ANTHROPIC_MODEL", "keep")
+
+ env = ClaudeCliProvider().subprocess_env()
+
+ assert "CLAUDECODE" not in env
+ assert "CLAUDE_CODE_SESSION_ID" not in env
+ assert "CLAUDE_CODE_MESSAGING_TOKEN" not in env
+ assert env["CLAUDE_CODE_USE_BEDROCK"] == "1"
+ assert env["ANTHROPIC_MODEL"] == "keep"
diff --git a/tests/unit/test_providers/test_llm_resolve.py b/tests/unit/test_providers/test_llm_resolve.py
index ffff5dda0..db4f5679c 100644
--- a/tests/unit/test_providers/test_llm_resolve.py
+++ b/tests/unit/test_providers/test_llm_resolve.py
@@ -357,3 +357,16 @@ def test_writers_retry_while_a_reader_holds_the_file(tmp_path, monkeypatch, writ
resolve.update_global_config(lambda config: config.update(active_provider="kimi"))
assert resolve.read_global_config()["active_provider"] == "kimi"
assert len(refusals) == 3
+
+
+def test_credentialed_providers_follow_autodetect_order_across_sources(tmp_path, monkeypatch):
+ repo = _repo(tmp_path, env="GEMINI_API_KEY=g\n")
+ _global(tmp_path, keys={"openai": "sk-stored"})
+ monkeypatch.setenv("DEEPSEEK_API_KEY", "d")
+ # Process env, the repo .env and a stored key all count, in one order.
+ assert resolve.credentialed_providers(repo) == ("openai", "gemini", "deepseek")
+ assert resolve_llm(repo).provider == resolve.credentialed_providers(repo)[0]
+
+
+def test_credentialed_providers_never_list_an_agent_cli(tmp_path):
+ assert resolve.credentialed_providers(_repo(tmp_path)) == ()