codebaton 0.1.0__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.
codebaton/config.py ADDED
@@ -0,0 +1,316 @@
1
+ """Load and validate router.yaml and model_routing.yaml.
2
+
3
+ Neither file may hold secrets. API keys come from env vars or the OS keychain;
4
+ any key that looks like a credential is rejected at load time.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+ from pathlib import Path
12
+ from typing import Any, Literal
13
+
14
+ import yaml
15
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
16
+
17
+ Profile = Literal["overnight", "per_session", "strict"]
18
+ Tier = Literal["haiku", "sonnet", "opus"]
19
+ TIER_ORDER: tuple[Tier, ...] = ("haiku", "sonnet", "opus")
20
+
21
+ ROUTER_FILE = "router.yaml"
22
+ MODEL_ROUTING_FILE = "model_routing.yaml"
23
+ STATE_DIR = ".codebaton"
24
+
25
+ _SECRET_KEY = re.compile(r"(api[_-]?key|secret|token|password|passwd|credential)", re.IGNORECASE)
26
+
27
+
28
+ class ConfigError(ValueError):
29
+ """Raised when a config file is missing, malformed or contains secrets."""
30
+
31
+
32
+ class _Strict(BaseModel):
33
+ model_config = ConfigDict(extra="forbid")
34
+
35
+
36
+ class UsageConfig(_Strict):
37
+ """How to read a provider's usage. ``reader`` is a built-in name or ``module:Class``."""
38
+
39
+ reader: str | None = None # default chosen from the provider name
40
+ path: str | None = None # override log / cache location (tests, non-default installs)
41
+ window_hours: float = 5.0 # how long a rate-limited provider stays exhausted
42
+ # Both agents report a short (5 h) and a long (weekly) window. "max" uses whichever is
43
+ # higher, since hitting either one blocks work.
44
+ window: Literal["short", "long", "max"] = "max"
45
+ # Manual fallback: how many runs fit in one window.
46
+ manual_runs_per_window: int = 20
47
+
48
+
49
+ class ProviderConfig(_Strict):
50
+ name: str
51
+ cap_percent: float = Field(ge=0, le=100)
52
+ adapter: str | None = None # built-in name or module:Class; defaults to ``name``
53
+ usage: UsageConfig = Field(default_factory=UsageConfig)
54
+ timeout_seconds: int = 3600
55
+
56
+ @property
57
+ def adapter_name(self) -> str:
58
+ return self.adapter or self.name
59
+
60
+
61
+ class OllamaConfig(_Strict):
62
+ """Local models via Ollama. Interactive launcher only in v0 (no headless routing)."""
63
+
64
+ enabled: bool = True
65
+ model: str | None = None # None = first installed model
66
+ # agent: runs through Codex's agent (edits code; first reply takes ~1 min on a laptop
67
+ # because Codex sends ~47K tokens of instructions). chat: plain `ollama run`
68
+ # conversation, answers in seconds, cannot edit files.
69
+ mode: Literal["agent", "chat"] = "agent"
70
+
71
+
72
+ class RouterConfig(_Strict):
73
+ providers: list[ProviderConfig] = Field(min_length=1)
74
+ profile: Profile = "per_session"
75
+ executor: str = "local"
76
+ # Bash commands an agent may run without asking under overnight/per_session.
77
+ allowed_commands: list[str] = Field(
78
+ default_factory=lambda: [
79
+ "git status",
80
+ "git diff",
81
+ "git log",
82
+ "ls",
83
+ "pytest",
84
+ "uv run",
85
+ "ruff",
86
+ "mypy",
87
+ ]
88
+ )
89
+ # Deterministic gates run after a task (e.g. ["uv run pytest -q"]). Empty = no gates.
90
+ gates: list[str] = Field(default_factory=list)
91
+ git_checkpoint: bool = True
92
+ # Extra permissions, off by default; users opt in per project. The strict profile and
93
+ # an org policy's `deny` list override them.
94
+ allow_web: bool = False # Claude WebFetch/WebSearch; Codex live web search + network
95
+ allow_push: bool = False # let agents run `git push`
96
+ allow_all_commands: bool = False # Claude may run any shell command, not just the list
97
+ # This many points before a threshold, the agent is asked once for a full handoff.
98
+ warn_margin_percent: float = Field(default=5, ge=0, le=50)
99
+ ollama: OllamaConfig | None = None
100
+
101
+ @field_validator("providers")
102
+ @classmethod
103
+ def _unique_names(cls, v: list[ProviderConfig]) -> list[ProviderConfig]:
104
+ names = [p.name for p in v]
105
+ if len(names) != len(set(names)):
106
+ raise ValueError("provider names must be unique")
107
+ return v
108
+
109
+
110
+ class TierRule(_Strict):
111
+ task_types: list[str] = Field(default_factory=list)
112
+
113
+
114
+ class ForceOpus(_Strict):
115
+ paths: list[str] = Field(default_factory=list)
116
+ keywords: list[str] = Field(default_factory=list)
117
+
118
+
119
+ class ProviderTier(_Strict):
120
+ model: str
121
+ reasoning_effort: str | None = None
122
+
123
+
124
+ class ModelRoutingConfig(_Strict):
125
+ default_tier: Tier = "opus"
126
+ tiers: dict[Tier, TierRule] = Field(default_factory=dict)
127
+ force_opus_if: ForceOpus = Field(default_factory=ForceOpus)
128
+ override_flag: str = "--model"
129
+ classifier: Literal["rules_then_haiku", "rules_only"] = "rules_then_haiku"
130
+ min_confidence_to_downgrade: float = Field(default=0.85, ge=0, le=1)
131
+ # Phrases that identify a task type from plain English. Matched case-insensitively.
132
+ task_type_keywords: dict[str, list[str]] = Field(default_factory=dict)
133
+ # provider -> tier -> native model. Codex tier keys: light/medium/top.
134
+ provider_tiers: dict[str, dict[str, ProviderTier]] = Field(default_factory=dict)
135
+
136
+
137
+ def _reject_secrets(node: Any, where: str) -> None:
138
+ if isinstance(node, dict):
139
+ for key, value in node.items():
140
+ if isinstance(key, str) and _SECRET_KEY.search(key):
141
+ raise ConfigError(
142
+ f"{where}: key '{key}' looks like a secret. Put credentials in env vars "
143
+ "or the OS keychain, never in config files."
144
+ )
145
+ _reject_secrets(value, where)
146
+ elif isinstance(node, list):
147
+ for item in node:
148
+ _reject_secrets(item, where)
149
+
150
+
151
+ def _load_yaml(path: Path) -> dict[str, Any]:
152
+ if not path.exists():
153
+ raise ConfigError(f"{path} not found. Run 'codebaton init' first.")
154
+ try:
155
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
156
+ except yaml.YAMLError as exc:
157
+ raise ConfigError(f"{path}: invalid YAML: {exc}") from exc
158
+ if not isinstance(data, dict):
159
+ raise ConfigError(f"{path}: top level must be a mapping")
160
+ _reject_secrets(data, str(path))
161
+ return data
162
+
163
+
164
+ def load_router_config(path: Path) -> RouterConfig:
165
+ try:
166
+ return RouterConfig.model_validate(_load_yaml(path))
167
+ except ValueError as exc:
168
+ if isinstance(exc, ConfigError):
169
+ raise
170
+ raise ConfigError(f"{path}: {exc}") from exc
171
+
172
+
173
+ def load_model_routing(path: Path) -> ModelRoutingConfig:
174
+ if not path.exists():
175
+ return default_model_routing()
176
+ try:
177
+ return ModelRoutingConfig.model_validate(_load_yaml(path))
178
+ except ValueError as exc:
179
+ if isinstance(exc, ConfigError):
180
+ raise
181
+ raise ConfigError(f"{path}: {exc}") from exc
182
+
183
+
184
+ def default_model_routing() -> ModelRoutingConfig:
185
+ return ModelRoutingConfig.model_validate(
186
+ {
187
+ "default_tier": "opus",
188
+ "tiers": {
189
+ "haiku": {
190
+ "task_types": ["write_tests", "docs", "formatting", "file_search", "rename"]
191
+ },
192
+ "sonnet": {
193
+ # "question": general questions / explanations, labelled by the classifier.
194
+ "task_types": [
195
+ "small_feature",
196
+ "bug_fix_single_file",
197
+ "refactor_small",
198
+ "question",
199
+ ]
200
+ },
201
+ "opus": {
202
+ "task_types": [
203
+ "architecture",
204
+ "security",
205
+ "data_migration",
206
+ "multi_file_change",
207
+ "debugging_unknown",
208
+ ]
209
+ },
210
+ },
211
+ "force_opus_if": {
212
+ "paths": ["src/codebaton/core/policy.py", "**/auth/**", "**/migrations/**"],
213
+ "keywords": ["security", "auth", "migration", "delete", "production"],
214
+ },
215
+ "task_type_keywords": {
216
+ "write_tests": [
217
+ "write tests",
218
+ "write test",
219
+ "add tests",
220
+ "add unit tests",
221
+ "add a test",
222
+ "unit tests for",
223
+ ],
224
+ "docs": ["docstring", "update the readme", "write docs", "documentation"],
225
+ "formatting": ["format the code", "reformat", "fix formatting"],
226
+ "file_search": ["find the file", "where is", "locate"],
227
+ "rename": ["rename"],
228
+ },
229
+ "provider_tiers": {
230
+ "claude_code": {
231
+ "haiku": {"model": "haiku"},
232
+ "sonnet": {"model": "sonnet"},
233
+ "opus": {"model": "opus"},
234
+ },
235
+ },
236
+ }
237
+ )
238
+
239
+
240
+ # -- organisation policy ----------------------------------------------------------------------
241
+
242
+ ORG_POLICY_ENV = "CODEBATON_POLICY"
243
+ ORG_POLICY_PATH = Path("/etc/codebaton/policy.yaml")
244
+ PROFILE_STRICTNESS: dict[str, int] = {"overnight": 0, "per_session": 1, "strict": 2}
245
+ DENY_SWITCHES = {"web": "allow_web", "push": "allow_push", "all_commands": "allow_all_commands"}
246
+
247
+
248
+ class OrgPolicy(_Strict):
249
+ """Machine-wide rules an organisation deploys (e.g. via MDM); projects cannot loosen them.
250
+
251
+ Read from ``$CODEBATON_POLICY`` if set, otherwise ``/etc/codebaton/policy.yaml``.
252
+ """
253
+
254
+ minimum_profile: Profile | None = None
255
+ deny: list[Literal["web", "push", "all_commands"]] = Field(default_factory=list)
256
+ allowed_agents: list[str] | None = None # provider names from router.yaml, plus "ollama"
257
+ require_checkpoints: bool = False
258
+ max_cap_percent: float | None = Field(default=None, gt=0, le=100)
259
+
260
+
261
+ def org_policy_path() -> Path | None:
262
+ env = os.environ.get(ORG_POLICY_ENV)
263
+ if env:
264
+ return Path(env) # set explicitly: it must exist (a missing file is an error)
265
+ return ORG_POLICY_PATH if ORG_POLICY_PATH.exists() else None
266
+
267
+
268
+ def load_org_policy() -> tuple[OrgPolicy, Path] | None:
269
+ path = org_policy_path()
270
+ if path is None:
271
+ return None
272
+ try:
273
+ return OrgPolicy.model_validate(_load_yaml(path)), path
274
+ except ValueError as exc:
275
+ if isinstance(exc, ConfigError):
276
+ raise
277
+ raise ConfigError(f"{path}: {exc}") from exc
278
+
279
+
280
+ def apply_org_policy(config: RouterConfig, policy: OrgPolicy) -> tuple[RouterConfig, list[str]]:
281
+ """Return the config with the policy enforced, plus a note for each rule that changed it."""
282
+ data = config.model_dump()
283
+ notes: list[str] = []
284
+ minimum = policy.minimum_profile
285
+ if minimum and PROFILE_STRICTNESS[config.profile] < PROFILE_STRICTNESS[minimum]:
286
+ data["profile"] = minimum
287
+ notes.append(f"profile raised to {minimum}")
288
+ for item in policy.deny:
289
+ key = DENY_SWITCHES[item]
290
+ if data[key]:
291
+ data[key] = False
292
+ notes.append(f"{item} denied")
293
+ if policy.require_checkpoints and not data["git_checkpoint"]:
294
+ data["git_checkpoint"] = True
295
+ notes.append("checkpoints required")
296
+ if policy.allowed_agents is not None:
297
+ allowed = set(policy.allowed_agents)
298
+ kept = [p for p in data["providers"] if p["name"] in allowed]
299
+ removed = [p["name"] for p in data["providers"] if p["name"] not in allowed]
300
+ if not kept:
301
+ raise ConfigError(
302
+ "The organisation policy allows none of the agents in router.yaml "
303
+ f"(allowed: {', '.join(sorted(allowed))})."
304
+ )
305
+ data["providers"] = kept
306
+ if removed:
307
+ notes.append(f"not allowed: {', '.join(removed)}")
308
+ if data["ollama"] and data["ollama"]["enabled"] and "ollama" not in allowed:
309
+ data["ollama"]["enabled"] = False
310
+ notes.append("not allowed: ollama")
311
+ if policy.max_cap_percent is not None:
312
+ for provider in data["providers"]:
313
+ if provider["cap_percent"] > policy.max_cap_percent:
314
+ provider["cap_percent"] = policy.max_cap_percent
315
+ notes.append(f"{provider['name']} threshold capped at {policy.max_cap_percent:g}%")
316
+ return RouterConfig.model_validate(data), notes
File without changes
@@ -0,0 +1,42 @@
1
+ """Append-only JSONL audit log of every routing decision, approval and provider call."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ # Redact anything shaped like a credential before it reaches disk.
12
+ _SECRET_VALUE = re.compile(
13
+ r"(sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|"
14
+ r"xox[abp]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16}|eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+)"
15
+ )
16
+
17
+
18
+ def redact(value: Any) -> Any:
19
+ if isinstance(value, str):
20
+ return _SECRET_VALUE.sub("[REDACTED]", value)
21
+ if isinstance(value, dict):
22
+ return {k: redact(v) for k, v in value.items()}
23
+ if isinstance(value, list | tuple):
24
+ return [redact(v) for v in value]
25
+ return value
26
+
27
+
28
+ class AuditLog:
29
+ def __init__(self, path: Path) -> None:
30
+ self.path = path
31
+
32
+ def record(self, event: str, **fields: Any) -> None:
33
+ entry = {"ts": datetime.now(UTC).isoformat(timespec="seconds"), "event": event}
34
+ entry.update(redact(fields))
35
+ self.path.parent.mkdir(parents=True, exist_ok=True)
36
+ with self.path.open("a", encoding="utf-8") as fh:
37
+ fh.write(json.dumps(entry, default=str) + "\n")
38
+
39
+ def read(self) -> list[dict[str, Any]]:
40
+ if not self.path.exists():
41
+ return []
42
+ return [json.loads(line) for line in self.path.read_text("utf-8").splitlines() if line]
@@ -0,0 +1,117 @@
1
+ """Budget manager: percent used per provider, with manual fallback and exhaustion marks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ from collections.abc import Callable, Mapping
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from codebaton.config import ProviderConfig
12
+ from codebaton.core.usage_cache import UsageCache
13
+ from codebaton.plugins.base import UsageReader, UsageReading, UsageWindow
14
+ from codebaton.plugins.usage.manual import ManualCounter
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class ProviderUsage:
19
+ name: str
20
+ percent: float
21
+ cap_percent: float
22
+ source: str
23
+ note: str
24
+ exhausted: bool
25
+
26
+ @property
27
+ def under_cap(self) -> bool:
28
+ return not self.exhausted and self.percent < self.cap_percent
29
+
30
+
31
+ class BudgetManager:
32
+ def __init__(
33
+ self,
34
+ providers: list[ProviderConfig],
35
+ readers: Mapping[str, UsageReader | None],
36
+ state_dir: Path,
37
+ now: Callable[[], float] = time.time,
38
+ usage_cache: UsageCache | None = None,
39
+ ) -> None:
40
+ self.providers = {p.name: p for p in providers}
41
+ self.readers = readers
42
+ self.state_dir = state_dir
43
+ self.now = now
44
+ self.usage_cache = usage_cache
45
+
46
+ @property
47
+ def _exhausted_file(self) -> Path:
48
+ return self.state_dir / "exhausted.json"
49
+
50
+ def _manual(self, provider: ProviderConfig) -> ManualCounter:
51
+ return ManualCounter(
52
+ self.state_dir / "manual_budget.json",
53
+ provider.name,
54
+ provider.usage.manual_runs_per_window,
55
+ now=self.now,
56
+ )
57
+
58
+ def _load_exhausted(self) -> dict[str, float]:
59
+ try:
60
+ data = json.loads(self._exhausted_file.read_text(encoding="utf-8"))
61
+ except (OSError, json.JSONDecodeError):
62
+ return {}
63
+ return {k: float(v) for k, v in data.items()} if isinstance(data, dict) else {}
64
+
65
+ def mark_exhausted(self, name: str) -> float:
66
+ """Mark a provider exhausted for one usage window. Returns the expiry time."""
67
+ until = self.now() + self.providers[name].usage.window_hours * 3600
68
+ data = self._load_exhausted()
69
+ data[name] = until
70
+ self.state_dir.mkdir(parents=True, exist_ok=True)
71
+ self._exhausted_file.write_text(json.dumps(data), encoding="utf-8")
72
+ return until
73
+
74
+ def is_exhausted(self, name: str) -> bool:
75
+ return self._load_exhausted().get(name, 0.0) > self.now()
76
+
77
+ def record_run(self, name: str) -> None:
78
+ self._manual(self.providers[name]).record_run()
79
+
80
+ def record_usage(self, name: str, windows: dict[str, UsageWindow]) -> None:
81
+ """Save usage a provider reported with a reply, so the next reading is real."""
82
+ if not windows:
83
+ return
84
+ # Write where this provider's reader looks (its own cache), else the shared one.
85
+ cache = getattr(self.readers.get(name), "cache", None)
86
+ target = cache if isinstance(cache, UsageCache) else self.usage_cache
87
+ if target is not None:
88
+ target.save(name, windows)
89
+
90
+ def usage(self, name: str) -> ProviderUsage:
91
+ provider = self.providers[name]
92
+ reader = self.readers.get(name)
93
+ reading: UsageReading | None = None
94
+ if reader is not None:
95
+ try:
96
+ reading = reader.used(provider.usage.window_hours)
97
+ except Exception as exc: # a broken reader must never stop routing
98
+ reading = UsageReading(None, "error", f"usage reader failed: {exc}")
99
+ note = ""
100
+ if reading is None or reading.percent is None:
101
+ why = reading.note if reading else "no usage reader for this provider"
102
+ fallback = self._manual(provider).used(provider.usage.window_hours)
103
+ note = f"manual fallback ({why}); {fallback.note}"
104
+ reading = UsageReading(fallback.percent, "manual", note)
105
+ exhausted = self.is_exhausted(name)
106
+ return ProviderUsage(
107
+ name=name,
108
+ percent=100.0 if exhausted else float(reading.percent or 0.0),
109
+ cap_percent=provider.cap_percent,
110
+ source=reading.source,
111
+ note=("rate-limited: exhausted until window resets; " if exhausted else "")
112
+ + reading.note,
113
+ exhausted=exhausted,
114
+ )
115
+
116
+ def all_usage(self) -> list[ProviderUsage]:
117
+ return [self.usage(name) for name in self.providers]