quotarouter 0.3.1__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.
@@ -0,0 +1,27 @@
1
+ """quotarouter — spend free monthly allowances first, route by remaining quota.
2
+
3
+ One provider-agnostic core:
4
+
5
+ from quotarouter import Router
6
+ router = Router()
7
+ result = router.run_search("query", limit=5) # -> RouteResult
8
+ payload = router.run_extract(["https://example.com/"]) # -> RouteResult as well
9
+ pinned = router.run_search("query", 5, stages=["exa"]) # one call, its own chain
10
+
11
+ Integrations live behind the core and stay optional:
12
+
13
+ quotarouter.integrations.hermes — Hermes Agent web provider (`web.search_backend`)
14
+ quotarouter.integrations.mcp — MCP server for any MCP client
15
+ quotarouter.cli — status / probe / route / chains / call / selftest / serve-mcp
16
+
17
+ Nothing here imports Hermes, so the package works in a plain Python process.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from .config import Settings, settings
23
+ from .routing import Router, RouteResult, format_failure
24
+
25
+ __version__ = "0.3.1"
26
+
27
+ __all__ = ["Router", "RouteResult", "Settings", "settings", "format_failure", "__version__"]
@@ -0,0 +1,10 @@
1
+ """`python -m quotarouter ...` — the CLI without needing the console script on `PATH`.
2
+
3
+ Every MCP client config in the README starts the server this way, so it has to exist: `python -m
4
+ quotarouter serve-mcp`. Without `__main__` that command fails with "cannot be directly executed".
5
+ """
6
+
7
+ from .cli import main
8
+
9
+ if __name__ == "__main__": # pragma: no cover - the module guard itself, not a behaviour
10
+ raise SystemExit(main())
quotarouter/alerts.py ADDED
@@ -0,0 +1,208 @@
1
+ """Tell a human when the chain degrades — with no monitoring stack and no dependencies.
2
+
3
+ A router that fails silently is worse than one that fails loudly: the agent answers from a
4
+ keyless tier for a week and nobody notices the paid key died. This module is the smallest
5
+ honest answer: three transports and a cooldown.
6
+
7
+ Enabled by configuring any ONE of them (all read through `QUOTAROUTER_*`):
8
+
9
+ QUOTAROUTER_ALERT_TELEGRAM=<bot token>:<chat id> # POST to the Bot API
10
+ QUOTAROUTER_ALERT_WEBHOOK=https://example/hook # POST {"text": ...}
11
+ QUOTAROUTER_ALERT_COMMAND="notify-send quotarouter {kind}" # argv, not shell
12
+ QUOTAROUTER_ALERT_COMMAND='sh -c '"'"'curl -s -d "$QUOTAROUTER_ALERT_TEXT" $HOOK'"'"''
13
+ # ^ the text arrives as an environment variable, so nothing from a vendor body is ever
14
+ # parsed as shell syntax.
15
+
16
+ Nothing configured means nothing sent — the default deployment stays quiet.
17
+
18
+ Two rules keep it useful instead of noisy:
19
+
20
+ * **A cooldown per kind** (default 900 s): a vendor that is down must not send one message per
21
+ call. `QUOTAROUTER_ALERT_COOLDOWN` changes it.
22
+ * **Delivery never breaks a call.** Every transport failure is logged and swallowed; a search
23
+ must not fail because a webhook is unreachable.
24
+
25
+ State (`<state>/alerts.json`, `{kind: last_sent_epoch}`) is on disk, so a restart does not
26
+ re-open the floodgates.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import logging
33
+ import os
34
+ import shlex
35
+ import subprocess
36
+ import threading
37
+ import time
38
+ from dataclasses import dataclass
39
+ from pathlib import Path
40
+ from typing import Any, Optional
41
+
42
+ from . import config, http_client
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ # Alert kinds. `no-stage` is the worst: nothing could serve. `keyless` means the paid chain is
47
+ # out and the answer came from an anonymous tier. `quota` means a vendor parked itself.
48
+ NO_STAGE = "no-stage"
49
+ KEYLESS = "keyless"
50
+ QUOTA = "quota"
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class AlertSettings:
55
+ telegram: str = ""
56
+ webhook: str = ""
57
+ command: str = ""
58
+ cooldown: float = 900.0
59
+
60
+ @property
61
+ def enabled(self) -> bool:
62
+ return bool(self.telegram or self.webhook or self.command)
63
+
64
+
65
+ def settings() -> AlertSettings:
66
+ """Read alert settings through the same env layer as everything else."""
67
+ cooldown_raw = config.env("ALERT_COOLDOWN") or "900"
68
+ try:
69
+ cooldown = float(cooldown_raw)
70
+ except ValueError:
71
+ cooldown = 900.0
72
+ return AlertSettings(
73
+ telegram=config.env("ALERT_TELEGRAM"),
74
+ webhook=config.env("ALERT_WEBHOOK"),
75
+ command=config.env("ALERT_COMMAND"),
76
+ cooldown=max(0.0, cooldown),
77
+ )
78
+
79
+
80
+ def _state_path() -> Path:
81
+ return config.settings().state_dir / "alerts.json"
82
+
83
+
84
+ def _read_state() -> dict[str, float]:
85
+ path = _state_path()
86
+ try:
87
+ data = json.loads(path.read_text(encoding="utf-8"))
88
+ except (OSError, ValueError):
89
+ return {}
90
+ if not isinstance(data, dict):
91
+ return {}
92
+ return {str(k): float(v) for k, v in data.items() if isinstance(v, (int, float))}
93
+
94
+
95
+ def _write_state(state: dict[str, float]) -> None:
96
+ path = _state_path()
97
+ try:
98
+ path.parent.mkdir(parents=True, exist_ok=True)
99
+ tmp = path.with_suffix(".tmp")
100
+ tmp.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
101
+ os.replace(tmp, path)
102
+ except OSError as exc:
103
+ logger.debug("quotarouter: could not store alert state: %s", exc)
104
+
105
+
106
+ def notify(kind: str, text: str, *, now: Optional[float] = None, force: bool = False,
107
+ extra: Optional[dict[str, Any]] = None, background: bool = False) -> bool:
108
+ """Send an alert unless the same kind is cooling down. Returns True when it was dispatched.
109
+
110
+ `background=True` hands delivery to a daemon thread: the router calls it from the end of a
111
+ real search, and a webhook that hangs for its ten-second timeout must not become a
112
+ ten-second search. The cooldown is recorded before dispatch, so a flood is impossible even
113
+ while the first message is still in flight — at the price of counting a failed delivery as
114
+ sent, which the log records.
115
+ """
116
+ settings_ = settings()
117
+ if not settings_.enabled:
118
+ return False
119
+ moment = time.time() if now is None else now
120
+ state = _read_state()
121
+ last = state.get(kind)
122
+ if not force and last is not None and moment - last < settings_.cooldown:
123
+ logger.debug("quotarouter: alert %s is cooling down (%.0fs of %.0fs)",
124
+ kind, moment - last, settings_.cooldown)
125
+ return False
126
+
127
+ body = text if not extra else f"{text}\n{json.dumps(extra, ensure_ascii=False, sort_keys=True)}"
128
+
129
+ def deliver() -> bool:
130
+ delivered = False
131
+ if settings_.telegram:
132
+ delivered |= _send_telegram(settings_.telegram, body)
133
+ if settings_.webhook:
134
+ delivered |= _send_webhook(settings_.webhook, body)
135
+ if settings_.command:
136
+ delivered |= _send_command(settings_.command, kind, body)
137
+ return delivered
138
+
139
+ if not background:
140
+ delivered = deliver()
141
+ if delivered:
142
+ state[kind] = moment
143
+ _write_state(state)
144
+ return delivered
145
+
146
+ state[kind] = moment
147
+ _write_state(state)
148
+ threading.Thread(target=deliver, name="quotarouter-alert", daemon=True).start()
149
+ return True
150
+
151
+
152
+ # --- transports -------------------------------------------------------------------------
153
+ def _send_telegram(target: str, text: str) -> bool:
154
+ """`<token>:<chat id>` — the Bot API expects the token in the path, so keep it out of logs."""
155
+ token, _, chat_id = target.partition(":")
156
+ if not token or not chat_id:
157
+ logger.warning("quotarouter: QUOTAROUTER_ALERT_TELEGRAM must be '<token>:<chat id>'")
158
+ return False
159
+ url = f"https://api.telegram.org/bot{token}/sendMessage"
160
+ return _post(url, {"chat_id": chat_id, "text": text[:4000], "disable_web_page_preview": True})
161
+
162
+
163
+ def _send_webhook(url: str, text: str) -> bool:
164
+ return _post(url, {"text": text})
165
+
166
+
167
+ def _post(url: str, payload: dict[str, Any]) -> bool:
168
+ try:
169
+ response = http_client.post(url, json=payload, timeout=10.0)
170
+ except Exception as exc: # a broken transport must never break the caller
171
+ logger.warning("quotarouter: alert transport failed: %s", exc)
172
+ return False
173
+ status = getattr(response, "status_code", 0)
174
+ if status >= 300:
175
+ logger.warning("quotarouter: alert transport answered HTTP %s", status)
176
+ return False
177
+ return True
178
+
179
+
180
+ def _send_command(template: str, kind: str, text: str) -> bool:
181
+ """Run a shell command with `{kind}` and `{text}` substituted.
182
+
183
+ Substitute into the whole string before `shlex.split`, so a `{text}` containing spaces
184
+ lands as several arguments: use `{kind}` in the command and keep the long text in the log,
185
+ or wrap it yourself (`sh -c 'curl -d "{text}" …'`).
186
+ """
187
+ flat = text.replace("\n", " ")
188
+ argv = template.replace("{kind}", shlex.quote(kind)).replace("{text}", shlex.quote(flat))
189
+ env = dict(os.environ, QUOTAROUTER_ALERT_TEXT=flat, QUOTAROUTER_ALERT_KIND=kind)
190
+ try:
191
+ done = subprocess.run(shlex.split(argv), capture_output=True, text=True, timeout=10,
192
+ env=env)
193
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
194
+ logger.warning("quotarouter: alert command failed: %s", exc)
195
+ return False
196
+ if done.returncode != 0:
197
+ logger.warning("quotarouter: alert command exited %s: %s", done.returncode,
198
+ (done.stderr or "").strip()[:200])
199
+ return False
200
+ return True
201
+
202
+
203
+ def reset_for_tests() -> None:
204
+ """Forget the cooldown state (tests only)."""
205
+ try:
206
+ _state_path().unlink()
207
+ except OSError:
208
+ pass
quotarouter/chains.py ADDED
@@ -0,0 +1,276 @@
1
+ """Named chains: what the operator wrote down, parsed once, validated once.
2
+
3
+ A chain is a *pair* of stage lists, not one list. The vendor that is cheapest for a query is not
4
+ the cheapest for a page (a search costs two Firecrawl credits, a page costs one, and Jina serves
5
+ pages for nothing), so `search` and `extract` are declared separately. A chain may also carry a
6
+ description, a budget and a strictness flag.
7
+
8
+ The file is TOML because Python 3.11 parses it in the standard library: a configuration format
9
+ should not be the reason to add a dependency.
10
+
11
+ [chains.free]
12
+ description = "Nothing that can cost money"
13
+ search = ["keenable", "exa", "firecrawl"]
14
+ extract = ["jina", "firecrawl"]
15
+ budget = "free"
16
+
17
+ Everything here is pure: a mapping in, immutable records out, no environment reads of its own.
18
+ The caller passes the resolver, so this module never has to know whether the setting came from
19
+ the process environment, a dotenv file or a host's own configuration.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+ import tomllib
26
+ from dataclasses import dataclass
27
+ from pathlib import Path
28
+ from typing import Any, Callable, Iterable, Mapping, Optional
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ #: The setting that names an alternative file, and the setting that carries a one-line shorthand.
33
+ #: The names callers pass to the resolver, which owns the ``QUOTAROUTER_`` prefix (see
34
+ #: ``config._env``). The full variable names appear only in messages.
35
+ SHORTHAND_SETTING = "CHAINS"
36
+ FILE_SETTING = "CHAINS_FILE"
37
+ #: Only for messages: a reader of the log needs the variable it can actually set.
38
+ SHORTHAND_ENV = "QUOTAROUTER_" + SHORTHAND_SETTING
39
+ DEFAULT_FILE = "~/.config/quotarouter/chains.toml"
40
+
41
+ #: Accepted chain-level budget values. `free` means "this chain does not spend money"; the
42
+ #: absence of a budget means "no restriction beyond the ledger".
43
+ BUDGET_FREE = "free"
44
+ BUDGETS = (BUDGET_FREE,)
45
+
46
+ ALLOWED_KEYS = frozenset({"description", "search", "extract", "budget", "max_cost_usd", "strict"})
47
+ CAPABILITIES = ("search", "extract")
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class ChainSpec:
52
+ """One named chain, as the operator declared it."""
53
+
54
+ name: str
55
+ search: tuple[str, ...] = ()
56
+ extract: tuple[str, ...] = ()
57
+ description: str = ""
58
+ budget: Optional[str] = None
59
+ max_cost_usd: Optional[float] = None
60
+ #: A non-strict chain continues into the default order once its own stages are exhausted.
61
+ #: Strict is the default: a name that silently grows a tail is not a name.
62
+ strict: bool = True
63
+
64
+ def stages_for(self, capability: str) -> tuple[str, ...]:
65
+ return self.search if capability == "search" else self.extract
66
+
67
+ def declares(self, capability: str) -> bool:
68
+ return bool(self.stages_for(capability))
69
+
70
+ def capabilities(self) -> tuple[str, ...]:
71
+ return tuple(c for c in CAPABILITIES if self.declares(c))
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class ChainProblem:
76
+ """One entry that did not survive parsing, and why. Reported, never fatal."""
77
+
78
+ entry: str
79
+ reason: str
80
+
81
+ def as_line(self) -> str:
82
+ return f"{self.entry}: {self.reason}"
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class ChainSet:
87
+ """Every chain this process knows about, plus what was dropped on the way in."""
88
+
89
+ specs: Mapping[str, ChainSpec]
90
+ problems: tuple[ChainProblem, ...] = ()
91
+ #: `file`, `shorthand` or `none` — the audit surface says which one was in force.
92
+ source: str = "none"
93
+ path: Optional[str] = None
94
+
95
+ def names(self) -> tuple[str, ...]:
96
+ return tuple(self.specs)
97
+
98
+ def get(self, name: str) -> Optional[ChainSpec]:
99
+ return self.specs.get(name)
100
+
101
+ def as_dict(self) -> dict[str, dict[str, Any]]:
102
+ """Machine-readable form for `status --json` and the protocol's status tool."""
103
+ return {
104
+ name: {
105
+ "search": list(spec.search),
106
+ "extract": list(spec.extract),
107
+ "description": spec.description,
108
+ "budget": spec.budget,
109
+ "max_cost_usd": spec.max_cost_usd,
110
+ "strict": spec.strict,
111
+ }
112
+ for name, spec in self.specs.items()
113
+ }
114
+
115
+
116
+ def _stage_list(value: Any, known: Iterable[str], where: str) -> tuple[tuple[str, ...], Optional[str]]:
117
+ """Normalise one stage list. Returns `(names, problem)` — at most one problem per list."""
118
+ if not isinstance(value, list):
119
+ return (), f"{where} must be a list of stage names"
120
+ known_set = set(known)
121
+ names: list[str] = []
122
+ for raw in value:
123
+ if not isinstance(raw, str) or not raw.strip():
124
+ return (), f"{where} contains a non-string entry"
125
+ name = raw.strip().lower()
126
+ if name not in known_set:
127
+ return (), (f"{where} names {name!r}, which is not a stage this build has "
128
+ f"({', '.join(sorted(known_set))})")
129
+ if name not in names: # a duplicate would dial the same vendor twice
130
+ names.append(name)
131
+ if not names:
132
+ return (), f"{where} is empty"
133
+ return tuple(names), None
134
+
135
+
136
+ def _parse_entry(name: str, table: Any, known: Iterable[str]) -> tuple[Optional[ChainSpec], Optional[str]]:
137
+ if not isinstance(table, dict):
138
+ return None, "a chain must be a table"
139
+ unknown = sorted(set(table) - ALLOWED_KEYS)
140
+ if unknown:
141
+ return None, f"unknown key(s) {', '.join(unknown)}; allowed: {', '.join(sorted(ALLOWED_KEYS))}"
142
+
143
+ lists: dict[str, tuple[str, ...]] = {}
144
+ for capability in CAPABILITIES:
145
+ if capability not in table:
146
+ continue
147
+ names, problem = _stage_list(table[capability], known, capability)
148
+ if problem:
149
+ return None, problem
150
+ lists[capability] = names
151
+ if not lists:
152
+ return None, "declares neither search nor extract stages"
153
+
154
+ description = table.get("description", "")
155
+ if not isinstance(description, str):
156
+ return None, "description must be a string"
157
+
158
+ budget = table.get("budget")
159
+ if budget is not None:
160
+ if not isinstance(budget, str) or budget.strip().lower() not in BUDGETS:
161
+ return None, f"budget must be one of {', '.join(BUDGETS)} (got {budget!r})"
162
+ budget = budget.strip().lower()
163
+
164
+ ceiling = table.get("max_cost_usd")
165
+ if ceiling is not None:
166
+ if isinstance(ceiling, bool) or not isinstance(ceiling, (int, float)) or ceiling < 0:
167
+ return None, f"max_cost_usd must be a non-negative number (got {ceiling!r})"
168
+ ceiling = float(ceiling)
169
+
170
+ strict = table.get("strict", True)
171
+ if not isinstance(strict, bool):
172
+ return None, f"strict must be true or false (got {strict!r})"
173
+
174
+ return ChainSpec(
175
+ name=name,
176
+ search=lists.get("search", ()),
177
+ extract=lists.get("extract", ()),
178
+ description=description,
179
+ budget=budget,
180
+ max_cost_usd=ceiling,
181
+ strict=strict,
182
+ ), None
183
+
184
+
185
+ def parse_document(data: Mapping[str, Any], known: Iterable[str]) -> ChainSet:
186
+ """Turn a parsed TOML document into chains, keeping every valid entry.
187
+
188
+ A configuration typo must never stop a service, and must never be silent either: the entry is
189
+ dropped with a reason that names it, and the rest of the file still works.
190
+ """
191
+ specs: dict[str, ChainSpec] = {}
192
+ problems: list[ChainProblem] = []
193
+
194
+ table = data.get("chains")
195
+ if table is None:
196
+ return ChainSet({}, (ChainProblem("chains", "the file has no [chains.*] tables"),), "file")
197
+ if not isinstance(table, dict):
198
+ return ChainSet({}, (ChainProblem("chains", "[chains] must be a table of tables"),), "file")
199
+
200
+ for name, entry in table.items():
201
+ spec, problem = _parse_entry(str(name), entry, known)
202
+ if spec is None:
203
+ problems.append(ChainProblem(f"chains.{name}", problem or "invalid"))
204
+ continue
205
+ specs[str(name)] = spec
206
+ return ChainSet(specs, tuple(problems), "file")
207
+
208
+
209
+ def parse_shorthand(value: str, known: Iterable[str]) -> ChainSet:
210
+ """One line, one list per name, applied to both capabilities.
211
+
212
+ Kept for a throwaway setup (`QUOTAROUTER_CHAINS="fast=exa,firecrawl"`). It cannot express a
213
+ pair of lists, so it does not try: the same list is offered to search and extract, and a stage
214
+ that cannot serve a capability is refused at call time like any other capability mismatch.
215
+ """
216
+ specs: dict[str, ChainSpec] = {}
217
+ problems: list[ChainProblem] = []
218
+ for segment in (part.strip() for part in value.split(";")):
219
+ if not segment:
220
+ continue
221
+ name, sep, raw_names = segment.partition("=")
222
+ name = name.strip().lower()
223
+ if not sep or not name or not raw_names.strip():
224
+ problems.append(ChainProblem(segment, "expected name=stage,stage"))
225
+ continue
226
+ names, problem = _stage_list(
227
+ [part.strip() for part in raw_names.split(",") if part.strip()], known, "stages")
228
+ if problem:
229
+ problems.append(ChainProblem(name, problem))
230
+ continue
231
+ specs[name] = ChainSpec(name=name, search=names, extract=names)
232
+ return ChainSet(specs, tuple(problems), "shorthand")
233
+
234
+
235
+ def load(resolve: Callable[[str], str], known: Iterable[str],
236
+ path: Optional[Path] = None) -> ChainSet:
237
+ """Read the chains this process will use: the shorthand if set, else the file, else nothing.
238
+
239
+ `resolve` reads a setting by name (the caller owns the environment and the dotenv fallback).
240
+ A missing file is not an error — it is the normal state of a fresh install. An unreadable or
241
+ unparsable one is reported once and leaves the default order in charge: a configuration
242
+ problem must not be an outage.
243
+ """
244
+ shorthand = (resolve(SHORTHAND_SETTING) or "").strip()
245
+ configured_path = path or Path(resolve(FILE_SETTING) or DEFAULT_FILE).expanduser()
246
+ if shorthand:
247
+ if configured_path.exists():
248
+ logger.warning(
249
+ "quotarouter: %s is set, so %s was ignored — the shorthand replaces the file",
250
+ SHORTHAND_ENV, configured_path,
251
+ )
252
+ loaded = parse_shorthand(shorthand, known)
253
+ return ChainSet(loaded.specs, loaded.problems, "shorthand", str(configured_path))
254
+
255
+ if not configured_path.exists():
256
+ return ChainSet({}, (), "none", str(configured_path))
257
+ try:
258
+ text = configured_path.read_text(encoding="utf-8")
259
+ except OSError as exc:
260
+ reason = "permission denied" if isinstance(exc, PermissionError) else str(exc)
261
+ logger.warning("quotarouter: cannot read %s (%s); using the default order",
262
+ configured_path, reason)
263
+ return ChainSet({}, (ChainProblem(str(configured_path), f"unreadable: {reason}"),),
264
+ "file", str(configured_path))
265
+ try:
266
+ data = tomllib.loads(text)
267
+ except tomllib.TOMLDecodeError as exc:
268
+ logger.warning("quotarouter: %s is not valid TOML (%s); using the default order",
269
+ configured_path, exc)
270
+ return ChainSet({}, (ChainProblem(str(configured_path), f"invalid TOML: {exc}"),),
271
+ "file", str(configured_path))
272
+
273
+ loaded = parse_document(data, known)
274
+ for problem in loaded.problems:
275
+ logger.warning("quotarouter: chain %s — %s", problem.entry, problem.reason)
276
+ return ChainSet(loaded.specs, loaded.problems, "file", str(configured_path))