rb-context 0.4.5__py3-none-any.whl
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.
- rb_context/__init__.py +1 -0
- rb_context/_distribution.py +24 -0
- rb_context/_pyproject.toml +184 -0
- rb_context/cli.py +69 -0
- rb_context/commands/__init__.py +1 -0
- rb_context/commands/auth.py +74 -0
- rb_context/commands/config.py +87 -0
- rb_context/commands/describe.py +34 -0
- rb_context/commands/doctor.py +57 -0
- rb_context/commands/init.py +48 -0
- rb_context/commands/login.py +76 -0
- rb_context/commands/project.py +55 -0
- rb_context/commands/search.py +165 -0
- rb_context/commands/skill.py +138 -0
- rb_context/commands/status.py +35 -0
- rb_context/core/__init__.py +1 -0
- rb_context/core/data_files.py +20 -0
- rb_context/core/deps.py +165 -0
- rb_context/core/errors.py +243 -0
- rb_context/core/models.py +88 -0
- rb_context/core/opencli.py +285 -0
- rb_context/core/services.py +210 -0
- rb_context/core/skills.py +64 -0
- rb_context/core/version.py +89 -0
- rb_context/credentials/__init__.py +1 -0
- rb_context/credentials/health.py +178 -0
- rb_context/credentials/manager.py +119 -0
- rb_context/credentials/ninerouter.py +39 -0
- rb_context/data/SKILL.md +90 -0
- rb_context/data/__init__.py +1 -0
- rb_context/output/__init__.py +279 -0
- rb_context/output/human.py +34 -0
- rb_context/output/json.py +11 -0
- rb_context/providers/__init__.py +67 -0
- rb_context/providers/base.py +204 -0
- rb_context/providers/brave.py +102 -0
- rb_context/providers/exa.py +155 -0
- rb_context/providers/github.py +121 -0
- rb_context/providers/hackernews.py +62 -0
- rb_context/providers/http.py +125 -0
- rb_context/providers/serp.py +128 -0
- rb_context/providers/tavily.py +107 -0
- rb_context/providers/wikipedia.py +64 -0
- rb_context-0.4.5.dist-info/METADATA +182 -0
- rb_context-0.4.5.dist-info/RECORD +48 -0
- rb_context-0.4.5.dist-info/WHEEL +4 -0
- rb_context-0.4.5.dist-info/entry_points.txt +2 -0
- rb_context-0.4.5.dist-info/licenses/LICENSE +21 -0
rb_context/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The package: its modules are the CLI (`cli`), its commands, the output and the core they share."""
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""The distribution name and the tool namespace copier writes from its answers, because an editable install cannot map
|
|
2
|
+
this import package to its distribution at runtime.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
# Rendered by copier from the `dist_name` answer: the [project] name in
|
|
6
|
+
# pyproject.toml (`rb-<slug>`, the Standard, Technology), which may differ from this
|
|
7
|
+
# import package's name. importlib.metadata finds this package's version,
|
|
8
|
+
# summary and console script by it; an editable install (`uv sync`) can't be
|
|
9
|
+
# mapped from package to distribution at runtime, so it is written down here.
|
|
10
|
+
# tests/test_cli.py fails if it drifts from pyproject.toml.
|
|
11
|
+
DIST_NAME = "rb-context"
|
|
12
|
+
# The previous distribution name during a rename: an install made
|
|
13
|
+
# under it (not yet reinstalled) still finds its own version. Drop it once
|
|
14
|
+
# every machine has the new name.
|
|
15
|
+
DIST_NAME_LEGACY: str | None = None
|
|
16
|
+
# The command name (`cli_name`) as an identifier: the namespace of this tool's
|
|
17
|
+
# shared-database names (core/db.py) — table prefix `<TOOL>_`, env var
|
|
18
|
+
# `<TOOL>_DATABASE_URL`, Alembic table `alembic_version_<TOOL>`. Written down,
|
|
19
|
+
# not derived at runtime: a bare source run falls back to the package name,
|
|
20
|
+
# and a table name must never depend on how the tool was started.
|
|
21
|
+
TOOL = "context"
|
|
22
|
+
# The cli-generator release this project was generated or last updated from
|
|
23
|
+
# (copier's `_commit`), for `describe --json`; None for a project not made by copier.
|
|
24
|
+
TEMPLATE_VERSION: str | None = "v1.27.3"
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "rb-context"
|
|
3
|
+
# Version comes from the git tag vX.Y.Z (uv-dynamic-versioning) — never add `version =`.
|
|
4
|
+
dynamic = ["version"]
|
|
5
|
+
description = "Web context for LLMs through search providers (Exa, Tavily, Brave)."
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "bolandeu" }]
|
|
10
|
+
requires-python = ">=3.14"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"rb-credentials>=0.7.1,<1",
|
|
13
|
+
"typer>=0.27,<0.29",
|
|
14
|
+
"rich>=13.7",
|
|
15
|
+
"pydantic>=2.6",
|
|
16
|
+
"tomli-w>=1.0",
|
|
17
|
+
"platformdirs>=4.2",
|
|
18
|
+
"httpx[socks]>=0.27", # socks5-прокси из 9router (httpx берёт socksio)
|
|
19
|
+
"requests[socks]>=2.31", # то же для exa/tavily: PySocks
|
|
20
|
+
"packaging>=24.0",
|
|
21
|
+
"exa-py>=2.22",
|
|
22
|
+
"tavily-python>=0.8",
|
|
23
|
+
"keyring>=25.0",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.scripts]
|
|
27
|
+
context = "rb_context.cli:main"
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Repository = "https://homeserver.tailee01ab.ts.net:3000/bolandeu/context"
|
|
31
|
+
|
|
32
|
+
[build-system]
|
|
33
|
+
requires = ["hatchling", "uv-dynamic-versioning"]
|
|
34
|
+
build-backend = "hatchling.build"
|
|
35
|
+
|
|
36
|
+
[tool.hatch.version]
|
|
37
|
+
source = "uv-dynamic-versioning"
|
|
38
|
+
|
|
39
|
+
[tool.uv-dynamic-versioning]
|
|
40
|
+
vcs = "git"
|
|
41
|
+
style = "pep440"
|
|
42
|
+
fallback-version = "0.0.0"
|
|
43
|
+
|
|
44
|
+
[tool.uv]
|
|
45
|
+
# Rebuild the editable install when a commit or tag moves, so `--version` follows the tag.
|
|
46
|
+
cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
|
|
47
|
+
|
|
48
|
+
# Siblings resolve from disk: a version range in `dependencies` plus a `path` source, never an index.
|
|
49
|
+
[tool.uv.sources]
|
|
50
|
+
rb-credentials = { path = "../rb-credentials", editable = true }
|
|
51
|
+
rb-9router = { path = "../rb-9router", editable = true } # private, never published
|
|
52
|
+
|
|
53
|
+
[tool.hatch.build.targets.sdist]
|
|
54
|
+
# What a release must not carry: the agent's own files, the forge configs and the dev tooling. The wheel is
|
|
55
|
+
# narrow already (`packages = ["src/<pkg>"]`); this is about the sdist, which is otherwise a copy of the repo.
|
|
56
|
+
exclude = [
|
|
57
|
+
"/.agents",
|
|
58
|
+
"/.claude",
|
|
59
|
+
"/.claude-plugin",
|
|
60
|
+
"/.gitea",
|
|
61
|
+
"/.github",
|
|
62
|
+
"/docs",
|
|
63
|
+
"/scripts",
|
|
64
|
+
"/uv.lock",
|
|
65
|
+
"/AGENTS.md",
|
|
66
|
+
"/CLAUDE.md",
|
|
67
|
+
"/CODING_STANDARDS.md",
|
|
68
|
+
"/CONTEXT.md",
|
|
69
|
+
"/.copier-answers.yml",
|
|
70
|
+
"^\\.gitignore$",
|
|
71
|
+
"/.gitleaks.toml",
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
[tool.hatch.build.targets.wheel]
|
|
75
|
+
packages = ["src/rb_context"]
|
|
76
|
+
|
|
77
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
78
|
+
# The installed CLI reads [[tool.rb.external]] from here (core/deps.py).
|
|
79
|
+
"pyproject.toml" = "rb_context/_pyproject.toml"
|
|
80
|
+
|
|
81
|
+
[dependency-groups]
|
|
82
|
+
# Mutation testing, run now and then and before big releases — not in the gate:
|
|
83
|
+
# `uv run --group mutation mutmut run`, then `mutmut results` / `mutmut browse`.
|
|
84
|
+
# Needs fork(): macOS/Linux (WSL on Windows). Settings: [tool.mutmut] below.
|
|
85
|
+
mutation = ["mutmut>=3.3"]
|
|
86
|
+
dev = [
|
|
87
|
+
"jsonschema>=4.23",
|
|
88
|
+
"pytest>=8.0",
|
|
89
|
+
"pyyaml>=6.0", # .copier-answers.yml, the CI workflow, tests/contracts/*.yaml
|
|
90
|
+
"pytest-cov>=5.0",
|
|
91
|
+
"ruff>=0.6",
|
|
92
|
+
"syrupy>=4.8",
|
|
93
|
+
"ty>=0.0.80",
|
|
94
|
+
"rb-9router", # dev only: keys and proxies from 9router's local database (`--source 9router`)
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
# External (non-Python) dependencies — every CLI this tool runs (require_cli,
|
|
98
|
+
# shutil.which, subprocess with a literal program, npx). The gate checks this
|
|
99
|
+
# list against the code both ways; doctor and require_cli read it at runtime;
|
|
100
|
+
# the tools catalog reads it (the Standard, Technology).
|
|
101
|
+
# [[tool.rb.external]]
|
|
102
|
+
# name = "ffmpeg"
|
|
103
|
+
# required = true # false: the tool works without it (doctor stays healthy)
|
|
104
|
+
# min_version = "6.0" # optional
|
|
105
|
+
# check = "ffmpeg -version" # prints the version; default "<name> --version"
|
|
106
|
+
# why = "transcodes the downloaded videos"
|
|
107
|
+
# detect = false # run via an injected runner / absolute path the gate can't see
|
|
108
|
+
# dist = "rb-serp" # for one of our CLIs: its distribution (default rb-<name>)
|
|
109
|
+
# url = "https://github.com/bolandeu/serp" # its repo: DEPENDENCY_TOO_OLD then prints a pinned install
|
|
110
|
+
|
|
111
|
+
[[tool.rb.external]]
|
|
112
|
+
name = "serp"
|
|
113
|
+
required = false
|
|
114
|
+
min_version = "0.7.2"
|
|
115
|
+
why = "провайдер serp: выдача Яндекса/Google со сниппетами (`serp snippets --json`)"
|
|
116
|
+
dist = "rb-serp"
|
|
117
|
+
url = "https://github.com/bolandeu/serp"
|
|
118
|
+
|
|
119
|
+
# Where sysadmin's tool-updater installs this tool after its first tag. The
|
|
120
|
+
# installation is sysadmin's; this section only says where. homeserver: users
|
|
121
|
+
# to install for (empty = build and publish only); mac: install on the Mac.
|
|
122
|
+
# extras (optional): the extras to install with, e.g. extras = ["browser"].
|
|
123
|
+
[tool.rb.install]
|
|
124
|
+
homeserver = ["rbtools"]
|
|
125
|
+
mac = true
|
|
126
|
+
|
|
127
|
+
[tool.cli-generator]
|
|
128
|
+
# Where scripts/check_command_docstrings.py (called by the project's checks)
|
|
129
|
+
# looks for commands: a glob or a list of globs, relative to the repo root.
|
|
130
|
+
commands = ["src/rb_context/commands/*.py"]
|
|
131
|
+
# gate check (the gate): extras to install before ruff/ty/pytest.
|
|
132
|
+
# gate_extras = ["browser"]
|
|
133
|
+
|
|
134
|
+
[tool.pytest.ini_options]
|
|
135
|
+
# Only tests/: mutmut leaves a copy of the tree in mutants/.
|
|
136
|
+
testpaths = ["tests"]
|
|
137
|
+
addopts = "--cov --cov-report=term-missing:skip-covered"
|
|
138
|
+
# tests/test_help.py keeps help snapshots at tests/snapshots/help/<command>.txt
|
|
139
|
+
# (the Standard, Commands), not in syrupy's own `__snapshots__/<test file>/` layout, so
|
|
140
|
+
# syrupy warns it "can not relate" each file to its test. It can — by name.
|
|
141
|
+
filterwarnings = ["ignore:(?s).*Can not relate snapshot:UserWarning"]
|
|
142
|
+
|
|
143
|
+
[tool.mutmut]
|
|
144
|
+
source_paths = ["src/rb_context"]
|
|
145
|
+
also_copy = ["scripts/", "pyproject.toml"] # tests read them (test_scripts.py, the distribution checks)
|
|
146
|
+
pytest_add_cli_args = ["--no-cov"] # fail_under would kill every mutant
|
|
147
|
+
# only_mutate = ["*/core/normalize.py"] # one module at a time on a big tool
|
|
148
|
+
|
|
149
|
+
[tool.coverage.run]
|
|
150
|
+
source = ["src"]
|
|
151
|
+
# sysmon (default on 3.14) keeps a record per recompiled code object; Typer recompiles annotations on every invoke, so memory grows.
|
|
152
|
+
core = "ctrace"
|
|
153
|
+
|
|
154
|
+
[tool.coverage.report]
|
|
155
|
+
# The template ships at ~94%; keep the bar where it is instead of letting
|
|
156
|
+
# new commands land untested. Raise it, never lower it.
|
|
157
|
+
fail_under = 90
|
|
158
|
+
show_missing = true
|
|
159
|
+
|
|
160
|
+
[tool.ty.terminal]
|
|
161
|
+
# Only errors fail the gate; recent ty (>= 0.0.84) otherwise exits 1 on warnings too.
|
|
162
|
+
# Legacy code that can't be fixed yet: downgrade specific rules instead of
|
|
163
|
+
# ignoring them, e.g. [tool.ty.rules] possibly-unbound-attribute = "warn".
|
|
164
|
+
error-on-warning = false
|
|
165
|
+
|
|
166
|
+
[tool.ruff]
|
|
167
|
+
line-length = 120
|
|
168
|
+
|
|
169
|
+
[tool.ruff.lint]
|
|
170
|
+
select = ["E4", "E7", "E9", "F", "I", "UP", "B", "SIM", "RUF", "S", "T20", "TID251"]
|
|
171
|
+
# Тексты и комментарии на русском: кириллица — не «похожие символы».
|
|
172
|
+
ignore = ["RUF001", "RUF002", "RUF003"]
|
|
173
|
+
|
|
174
|
+
[tool.ruff.lint.per-file-ignores]
|
|
175
|
+
"tests/*" = ["S101", "T201", "TID251"] # assert is the point of a test; print in code strings; httpx for mocks
|
|
176
|
+
"scripts/*" = ["S603", "S607", "T201"] # subprocess with fixed argv lists (git, uv), no shell; scripts print to the console
|
|
177
|
+
"src/*/providers/*" = ["TID251"] # external APIs live here
|
|
178
|
+
|
|
179
|
+
[tool.ruff.lint.flake8-tidy-imports.banned-api]
|
|
180
|
+
"httpx".msg = "Call external APIs through providers/ (subclass providers.HttpProvider)."
|
|
181
|
+
|
|
182
|
+
[tool.ruff.lint.flake8-bugbear]
|
|
183
|
+
# Typer's `param: T = typer.Option(...)` style is a call in a default on purpose.
|
|
184
|
+
extend-immutable-calls = ["typer.Option", "typer.Argument"]
|
rb_context/cli.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""The root Typer app: global options, the command groups and the optional commands a generated package has, wired
|
|
2
|
+
together, and the console-script entry point.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from . import output
|
|
10
|
+
from .commands import auth, doctor, search
|
|
11
|
+
from .core.version import DEV_VERSION, cli_name, installed_version, optional_module, package_summary
|
|
12
|
+
|
|
13
|
+
_PACKAGE_NAME = __name__.split(".")[0]
|
|
14
|
+
# Optional parts (copier questions, dropped by _exclude): each one ships a module that registers its
|
|
15
|
+
# commands and global options. Probed at runtime, so this file needs no template logic.
|
|
16
|
+
PARTS = ("project", "skill", "describe", "db")
|
|
17
|
+
|
|
18
|
+
# A bare `<cli>` is the discovery entry point for humans and agents alike:
|
|
19
|
+
# name + version + description, then every command with the first line of
|
|
20
|
+
# its docstring. No `no_args_is_help` (that exits 2) — main_options() below
|
|
21
|
+
# prints this and exits 0. Shell completion stays enabled.
|
|
22
|
+
app = typer.Typer(
|
|
23
|
+
cls=output.RootGroup, # a usage error under --json is the error envelope
|
|
24
|
+
help=f"{cli_name()} {installed_version() or DEV_VERSION} — {package_summary() or 'веб-контекст для LLM'}",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
app.add_typer(auth.app, name="auth") # `auth status` in every CLI; login/logout only with credentials
|
|
28
|
+
app.command(name="doctor")(doctor.doctor)
|
|
29
|
+
app.command(name="search")(search.search)
|
|
30
|
+
for part in PARTS:
|
|
31
|
+
if module := optional_module(f"{_PACKAGE_NAME}.commands.{part}"):
|
|
32
|
+
module.register(app)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _version_callback(value: bool) -> None:
|
|
36
|
+
if not value:
|
|
37
|
+
return
|
|
38
|
+
typer.echo(installed_version() or DEV_VERSION)
|
|
39
|
+
raise typer.Exit()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@app.callback(invoke_without_command=True)
|
|
43
|
+
def main_options(
|
|
44
|
+
ctx: typer.Context,
|
|
45
|
+
json_output: bool = typer.Option(False, "--json", help="Emit machine-readable JSON output."),
|
|
46
|
+
quiet: bool = typer.Option(False, "--quiet", help="Suppress non-essential output."),
|
|
47
|
+
verbose: bool = typer.Option(False, "--verbose", help="Emit extra diagnostic output."),
|
|
48
|
+
non_interactive: bool = typer.Option(False, "--non-interactive", help="Never prompt; fail instead."),
|
|
49
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="Show what would happen without making changes."),
|
|
50
|
+
version: bool = typer.Option(
|
|
51
|
+
False, "--version", callback=_version_callback, is_eager=True, help="Show the version and exit."
|
|
52
|
+
),
|
|
53
|
+
) -> None:
|
|
54
|
+
ctx.ensure_object(dict) # a part's global option (--project) may have put its value here already
|
|
55
|
+
ctx.obj["json"] = json_output
|
|
56
|
+
ctx.obj["quiet"] = quiet
|
|
57
|
+
ctx.obj["verbose"] = verbose
|
|
58
|
+
ctx.obj["non_interactive"] = non_interactive
|
|
59
|
+
ctx.obj["dry_run"] = dry_run
|
|
60
|
+
output.configure_logging(verbose)
|
|
61
|
+
output.help_if_no_command(ctx)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def main() -> None:
|
|
65
|
+
app()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
main()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The commands of the CLI, one module per command or command group."""
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""The `auth` command group: `status` reports the health of the credentials of every provider, or an empty report when
|
|
2
|
+
the package has none.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import importlib
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
|
|
12
|
+
from .. import output, providers
|
|
13
|
+
from ..core.errors import InvalidArguments
|
|
14
|
+
from ..core.version import DEV_VERSION, cli_name, installed_version, module_exists, optional_module
|
|
15
|
+
|
|
16
|
+
# `auth status` exists in every CLI (the Standard, Health); a CLI
|
|
17
|
+
# generated without credentials (no credentials/ package, no commands/login.py)
|
|
18
|
+
# reports an empty `credentials` list and exits 0. Detected at runtime so this
|
|
19
|
+
# file needs no template logic — same approach as doctor.py.
|
|
20
|
+
_PACKAGE_NAME = __name__.split(".")[0]
|
|
21
|
+
_HAS_CREDENTIALS = module_exists(f"{_PACKAGE_NAME}.credentials.manager")
|
|
22
|
+
|
|
23
|
+
app = output.group("Ключи провайдеров (связка ключей ОС или env CONTEXT_<PROVIDER>_API_KEY).")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@app.command("status")
|
|
27
|
+
@output.guard
|
|
28
|
+
def auth_status(
|
|
29
|
+
ctx: typer.Context,
|
|
30
|
+
check: bool = typer.Option(
|
|
31
|
+
False, "--check", help="Also make one cheap read-only call per provider (10 s timeout) to prove each works."
|
|
32
|
+
),
|
|
33
|
+
provider: str | None = typer.Option(
|
|
34
|
+
None, "--provider", "-p", help="Report only this provider (default: all with keys: exa, tavily, brave)."
|
|
35
|
+
),
|
|
36
|
+
json_output: bool = output.JsonOption,
|
|
37
|
+
quiet: bool = output.QuietOption,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""Report every provider's credential: where it comes from and whether it works. Never prints values.
|
|
40
|
+
|
|
41
|
+
Without --check only presence is reported (status `unchecked` or `missing`).
|
|
42
|
+
exa is required, tavily and brave are optional; serp keeps its own keys
|
|
43
|
+
(`serp auth status`) and isn't listed (`--provider serp` is a usage error).
|
|
44
|
+
--check is free for exa (an empty /search request, rejected before billing)
|
|
45
|
+
and tavily (/usage, with the remaining credits as `quota`); brave has no free
|
|
46
|
+
call, so it makes one search.
|
|
47
|
+
Exits 0 when every required provider is ok/unchecked (an optional one may be
|
|
48
|
+
missing), 3 when any required provider has a problem or any credential is
|
|
49
|
+
invalid/expired, 2 on a usage error. The --json shape is a cross-tool contract:
|
|
50
|
+
`tool`, `version`, `checked_at`, `credentials[]` with `provider`, `required`,
|
|
51
|
+
`fields`, `source`, `source_ref`, `status`, `expires_at`, `quota`, `message`.
|
|
52
|
+
|
|
53
|
+
Example: {cli} auth status --check --json
|
|
54
|
+
"""
|
|
55
|
+
tool, version = cli_name(), installed_version() or DEV_VERSION
|
|
56
|
+
if not _HAS_CREDENTIALS:
|
|
57
|
+
if provider is not None:
|
|
58
|
+
raise InvalidArguments(f"Unknown provider '{provider}' ({tool} stores no credentials).")
|
|
59
|
+
checked_at = datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
|
60
|
+
payload = {"tool": tool, "version": version, "checked_at": checked_at, "credentials": []}
|
|
61
|
+
output.emit_report(ctx, payload, lambda _: output.human.echo(f"{tool} stores no credentials."), None)
|
|
62
|
+
return
|
|
63
|
+
health = importlib.import_module(f"{_PACKAGE_NAME}.credentials.health")
|
|
64
|
+
# Провайдер без ключей context (serp хранит свои сам) — такая же ошибка, как неизвестный.
|
|
65
|
+
with_keys = [cls for cls in providers.all_providers() if cls.credential_fields]
|
|
66
|
+
if provider is not None and not health.select(with_keys, provider):
|
|
67
|
+
raise InvalidArguments(f"Unknown provider '{provider}' (known: {', '.join(cls.name for cls in with_keys)}).")
|
|
68
|
+
payload, problem = health.status(tool, version, check=check, only=provider)
|
|
69
|
+
output.emit_report(ctx, payload, health.render, problem)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
if _login := optional_module(f"{_PACKAGE_NAME}.commands.login"):
|
|
73
|
+
app.command("login")(_login.login)
|
|
74
|
+
app.command("logout")(_login.logout)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""The `config` command group: show and change the project's config file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from .. import output
|
|
10
|
+
from ..core import services
|
|
11
|
+
from ..core.errors import InvalidArguments
|
|
12
|
+
from ..core.models import ProjectConfig
|
|
13
|
+
|
|
14
|
+
app = output.group("Manage project configuration.")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@app.command("list")
|
|
18
|
+
@output.guard
|
|
19
|
+
def list_config(
|
|
20
|
+
ctx: typer.Context,
|
|
21
|
+
json_output: bool = output.JsonOption,
|
|
22
|
+
quiet: bool = output.QuietOption,
|
|
23
|
+
) -> None:
|
|
24
|
+
"""List all configuration values.
|
|
25
|
+
|
|
26
|
+
Example: {cli} config list --json
|
|
27
|
+
"""
|
|
28
|
+
start = Path(ctx.obj.get("project") or Path.cwd())
|
|
29
|
+
root = services.require_project_root(start)
|
|
30
|
+
config = services.load_config(root)
|
|
31
|
+
data = config.model_dump()
|
|
32
|
+
output.emit_success(ctx, data, render_human=lambda d: output.human.key_values("Config", d))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@app.command("get")
|
|
36
|
+
@output.guard
|
|
37
|
+
def get_config(
|
|
38
|
+
ctx: typer.Context,
|
|
39
|
+
key: str = typer.Argument(..., help="Dotted config key, e.g. provider.name"),
|
|
40
|
+
json_output: bool = output.JsonOption,
|
|
41
|
+
quiet: bool = output.QuietOption,
|
|
42
|
+
) -> None:
|
|
43
|
+
"""Get a single configuration value.
|
|
44
|
+
|
|
45
|
+
Example: {cli} config get providers
|
|
46
|
+
"""
|
|
47
|
+
start = Path(ctx.obj.get("project") or Path.cwd())
|
|
48
|
+
root = services.require_project_root(start)
|
|
49
|
+
value: object = services.load_config(root).model_dump()
|
|
50
|
+
for part in key.split("."):
|
|
51
|
+
if not isinstance(value, dict) or part not in value:
|
|
52
|
+
raise InvalidArguments(f"Unknown config key '{key}'.")
|
|
53
|
+
value = value[part]
|
|
54
|
+
output.emit_success(
|
|
55
|
+
ctx, {"key": key, "value": value}, render_human=lambda d: output.human.echo(f"{d['key']} = {d['value']}")
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@app.command("set")
|
|
60
|
+
@output.guard
|
|
61
|
+
def set_config(
|
|
62
|
+
ctx: typer.Context,
|
|
63
|
+
key: str = typer.Argument(..., help="Dotted config key, e.g. provider.name"),
|
|
64
|
+
value: str = typer.Argument(..., help="New value (stored as a string)."),
|
|
65
|
+
json_output: bool = output.JsonOption,
|
|
66
|
+
quiet: bool = output.QuietOption,
|
|
67
|
+
) -> None:
|
|
68
|
+
"""Set a single, non-secret configuration value.
|
|
69
|
+
|
|
70
|
+
Example: {cli} config set providers exa,serp
|
|
71
|
+
"""
|
|
72
|
+
start = Path(ctx.obj.get("project") or Path.cwd())
|
|
73
|
+
root = services.require_project_root(start)
|
|
74
|
+
data = services.load_config(root).model_dump()
|
|
75
|
+
parts = key.split(".")
|
|
76
|
+
target = data
|
|
77
|
+
for part in parts[:-1]:
|
|
78
|
+
if not isinstance(target, dict) or part not in target:
|
|
79
|
+
raise InvalidArguments(f"Unknown config key '{key}'.")
|
|
80
|
+
target = target[part]
|
|
81
|
+
if not isinstance(target, dict) or parts[-1] not in target:
|
|
82
|
+
raise InvalidArguments(f"Unknown config key '{key}'.")
|
|
83
|
+
target[parts[-1]] = value
|
|
84
|
+
services.save_config(root, ProjectConfig.model_validate(data))
|
|
85
|
+
output.emit_success(
|
|
86
|
+
ctx, {"key": key, "value": value}, render_human=lambda d: output.human.echo(f"Set {d['key']} = {d['value']}")
|
|
87
|
+
)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""The `describe` command: the machine-readable description (OpenCLI document) of this CLI for agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from .. import output
|
|
10
|
+
from ..core import opencli
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@output.guard
|
|
14
|
+
def describe(
|
|
15
|
+
ctx: typer.Context,
|
|
16
|
+
json_output: bool = output.JsonOption,
|
|
17
|
+
quiet: bool = output.QuietOption,
|
|
18
|
+
verbose: bool = output.VerboseOption,
|
|
19
|
+
) -> None:
|
|
20
|
+
"""Print this CLI's machine-readable contract: an OpenCLI document (opencli.org).
|
|
21
|
+
|
|
22
|
+
Commands, options, arguments, exit codes, plus `x-rb-*` metadata: env vars,
|
|
23
|
+
tables, v1 views, data files, external programs. With --json it is the bare
|
|
24
|
+
document on one line (no {"ok": ...} envelope); without, the same indented.
|
|
25
|
+
|
|
26
|
+
Example: {cli} describe --json
|
|
27
|
+
"""
|
|
28
|
+
document = opencli.document(ctx.find_root().command)
|
|
29
|
+
typer.echo(json.dumps(document, ensure_ascii=False, indent=None if ctx.obj.get("json") else 2))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def register(root: typer.Typer) -> None:
|
|
33
|
+
"""Add `describe` to the CLI's root (the describe part, copier's include_describe)."""
|
|
34
|
+
root.command(name="describe")(describe)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""The `doctor` command: checks of this CLI's own setup, one line per check."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
|
|
7
|
+
from .. import output
|
|
8
|
+
from ..core import deps
|
|
9
|
+
from ..core.version import DEV_VERSION, installed_version, optional_module
|
|
10
|
+
from ..providers import all_providers
|
|
11
|
+
|
|
12
|
+
_PACKAGE_NAME = __name__.split(".")[0]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _quota_notes() -> str:
|
|
16
|
+
"""Warn about providers whose `auth status --check` spends free quota (for the detail of the `credential` check)."""
|
|
17
|
+
return "; ".join(
|
|
18
|
+
f"'auth status --check' тратит 1 запрос бесплатного лимита {cls.name} — не по расписанию"
|
|
19
|
+
for cls in all_providers()
|
|
20
|
+
if getattr(cls, "health_check_spends_quota", False)
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@output.guard
|
|
25
|
+
def doctor(
|
|
26
|
+
ctx: typer.Context,
|
|
27
|
+
json_output: bool = output.JsonOption,
|
|
28
|
+
quiet: bool = output.QuietOption,
|
|
29
|
+
verbose: bool = output.VerboseOption,
|
|
30
|
+
) -> None:
|
|
31
|
+
"""Диагностика: версия, проект, настройки, связка ключей, ключи провайдеров, внешние CLI (serp).
|
|
32
|
+
|
|
33
|
+
Always exits 0 — the report itself is the result; `healthy` says
|
|
34
|
+
whether every check passed.
|
|
35
|
+
|
|
36
|
+
Example: {cli} doctor --json
|
|
37
|
+
"""
|
|
38
|
+
checks: list[dict] = [{"name": "python", "ok": True}]
|
|
39
|
+
checks.append({"name": "cli_version", "ok": True, "detail": installed_version() or DEV_VERSION})
|
|
40
|
+
|
|
41
|
+
if project := optional_module(f"{_PACKAGE_NAME}.commands.project"): # include_project=false drops it
|
|
42
|
+
checks.extend(project.doctor_checks(ctx))
|
|
43
|
+
|
|
44
|
+
if credentials := optional_module(f"{_PACKAGE_NAME}.credentials.health"): # include_auth=false drops it
|
|
45
|
+
checks.extend(credentials.doctor_checks())
|
|
46
|
+
if notes := _quota_notes():
|
|
47
|
+
for check in checks:
|
|
48
|
+
if check["name"] == "credential":
|
|
49
|
+
check["detail"] = f"{check['detail']}; {notes}"
|
|
50
|
+
checks.extend(deps.doctor_checks()) # [[tool.rb.external]] in pyproject.toml
|
|
51
|
+
if db := optional_module(f"{_PACKAGE_NAME}.core.db"): # include_db=false drops it at generation time
|
|
52
|
+
checks.extend(db.doctor_checks())
|
|
53
|
+
|
|
54
|
+
all_ok = all(check["ok"] for check in checks)
|
|
55
|
+
output.emit_success(
|
|
56
|
+
ctx, {"healthy": all_ok, "checks": checks}, render_human=lambda data: output.human.render_doctor(data["checks"])
|
|
57
|
+
)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""The `init` command: create the project folder with its config file in the target directory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from .. import output
|
|
10
|
+
from ..core import services
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@output.guard
|
|
14
|
+
def init(
|
|
15
|
+
ctx: typer.Context,
|
|
16
|
+
name: str | None = typer.Option(None, "--name", help="Project name (defaults to directory name)."),
|
|
17
|
+
force: bool = typer.Option(False, "--force", help="Overwrite an already-initialized project's config."),
|
|
18
|
+
json_output: bool = output.JsonOption,
|
|
19
|
+
quiet: bool = output.QuietOption,
|
|
20
|
+
verbose: bool = output.VerboseOption,
|
|
21
|
+
) -> None:
|
|
22
|
+
"""Initialize a project: creates .{cli}/config.toml in the target directory.
|
|
23
|
+
|
|
24
|
+
Example: {cli} init --name demo
|
|
25
|
+
"""
|
|
26
|
+
target = Path(ctx.obj.get("project") or Path.cwd()).resolve()
|
|
27
|
+
|
|
28
|
+
if not force and services.find_project_root(target) == target:
|
|
29
|
+
output.vecho(ctx, f"Found existing config at {services.config_path(target)}")
|
|
30
|
+
config = services.load_config(target)
|
|
31
|
+
output.emit_success(
|
|
32
|
+
ctx,
|
|
33
|
+
{"project": config.name, "path": str(target), "already_initialized": True},
|
|
34
|
+
render_human=lambda data: output.human.echo(
|
|
35
|
+
f"Already initialized in {data['path']} (use --force to reset)."
|
|
36
|
+
),
|
|
37
|
+
)
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
project_name = name or target.name
|
|
41
|
+
config = services.init_project(target, project_name)
|
|
42
|
+
output.emit_success(
|
|
43
|
+
ctx,
|
|
44
|
+
{"project": config.name, "path": str(target), "already_initialized": False},
|
|
45
|
+
render_human=lambda data: output.human.key_values(
|
|
46
|
+
f"Initialized project in {data['path']}", {"name": data["project"]}
|
|
47
|
+
),
|
|
48
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""`auth login` / `auth logout` — only in CLIs generated with credentials (include_auth).
|
|
2
|
+
|
|
3
|
+
`commands/auth.py` registers these into the `auth` group when this module
|
|
4
|
+
exists; `auth status` is there in every CLI (the Standard, Health).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from .. import output
|
|
12
|
+
from ..core.errors import InvalidArguments
|
|
13
|
+
from ..credentials import manager as credentials
|
|
14
|
+
from ..providers import SerpProvider, provider_class, providers_help
|
|
15
|
+
|
|
16
|
+
ProviderOption = typer.Option(..., "--provider", "-p", help=f"Провайдер. Доступны: {providers_help()}.")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _require_api_key_provider(provider: str) -> None:
|
|
20
|
+
if not provider_class(provider).needs_api_key:
|
|
21
|
+
if provider == SerpProvider.name:
|
|
22
|
+
raise InvalidArguments(f"Ключи {provider} хранит сам {provider}: '{provider} auth login'.")
|
|
23
|
+
raise InvalidArguments(f"Провайдеру {provider} ключ не нужен.")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@output.guard
|
|
27
|
+
def login(
|
|
28
|
+
ctx: typer.Context,
|
|
29
|
+
provider: str = ProviderOption,
|
|
30
|
+
non_interactive: bool = output.NonInteractiveOption,
|
|
31
|
+
json_output: bool = output.JsonOption,
|
|
32
|
+
quiet: bool = output.QuietOption,
|
|
33
|
+
) -> None:
|
|
34
|
+
"""Сохранить API-ключ провайдера в связку ключей ОС.
|
|
35
|
+
|
|
36
|
+
Ключ берётся из CONTEXT_<PROVIDER>_API_KEY (например CONTEXT_EXA_API_KEY),
|
|
37
|
+
если переменная задана, иначе спрашивается. С --non-interactive и без
|
|
38
|
+
переменной — ошибка, а не вопрос. Провайдерам без ключа (hackernews,
|
|
39
|
+
wikipedia) и serp (ключи хранит сам serp) — INVALID_ARGUMENTS.
|
|
40
|
+
|
|
41
|
+
Example: {cli} auth login --provider exa
|
|
42
|
+
"""
|
|
43
|
+
_require_api_key_provider(provider)
|
|
44
|
+
secret = credentials.read_secret_from_env(provider)
|
|
45
|
+
if secret is None:
|
|
46
|
+
if ctx.obj.get("non_interactive") or non_interactive:
|
|
47
|
+
raise InvalidArguments(
|
|
48
|
+
f"No credential found in environment for provider '{provider}' and --non-interactive was set."
|
|
49
|
+
)
|
|
50
|
+
secret = typer.prompt(f"Enter API key for '{provider}'", hide_input=True)
|
|
51
|
+
credentials.store_secret(provider, secret)
|
|
52
|
+
output.emit_success(
|
|
53
|
+
ctx,
|
|
54
|
+
{"provider": provider},
|
|
55
|
+
render_human=lambda d: output.human.echo(f"Stored credential for '{d['provider']}'."),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@output.guard
|
|
60
|
+
def logout(
|
|
61
|
+
ctx: typer.Context,
|
|
62
|
+
provider: str = ProviderOption,
|
|
63
|
+
json_output: bool = output.JsonOption,
|
|
64
|
+
quiet: bool = output.QuietOption,
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Удалить API-ключ провайдера из связки ключей ОС.
|
|
67
|
+
|
|
68
|
+
Example: {cli} auth logout --provider exa
|
|
69
|
+
"""
|
|
70
|
+
_require_api_key_provider(provider)
|
|
71
|
+
credentials.delete_secret(provider)
|
|
72
|
+
output.emit_success(
|
|
73
|
+
ctx,
|
|
74
|
+
{"provider": provider},
|
|
75
|
+
render_human=lambda d: output.human.echo(f"Removed credential for '{d['provider']}'."),
|
|
76
|
+
)
|