codeveto 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.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/ai/policy.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""The report ``ai`` section, AI findings and the verdict policy (SPEC 9.6).
|
|
2
|
+
|
|
3
|
+
Verdict policy for one pass (a deterministic veto always wins, since a
|
|
4
|
+
blocking finding makes the review ``vetoed`` whatever the issues say):
|
|
5
|
+
|
|
6
|
+
| Pass | ``blocking = true`` | ``required = true`` | otherwise |
|
|
7
|
+
| --- | --- | --- | --- |
|
|
8
|
+
| did not start | incomplete | incomplete | incomplete (``--ai-optional``: advisory) |
|
|
9
|
+
| ``failed`` | incomplete | incomplete | advisory issue |
|
|
10
|
+
| ``partial`` | incomplete | advisory issue | advisory issue |
|
|
11
|
+
| ``complete`` | - | - | - |
|
|
12
|
+
|
|
13
|
+
``--ai-optional`` only covers a pass that could not start (the extra is not
|
|
14
|
+
installed, no credentials, bad settings, the capability step failed, the
|
|
15
|
+
provider rejected the credentials, model or request before any packet
|
|
16
|
+
verified, the secrets pack is missing, or a harness responses document is
|
|
17
|
+
unusable or stale); it never overrides ``blocking`` or ``required``.
|
|
18
|
+
|
|
19
|
+
AI findings (verified, ``source: "ai"``, rule ``ai/<category>``): with
|
|
20
|
+
``blocking = true`` a ``high`` finding is a blocking ``error`` (unless
|
|
21
|
+
``fail_on = "never"``); ``medium`` is a ``warning`` and ``low`` a ``note``,
|
|
22
|
+
never blocking. With ``blocking = false`` nothing an AI says blocks:
|
|
23
|
+
``high`` and ``medium`` are warnings, ``low`` notes. The message is the title
|
|
24
|
+
and explanation, the hint is the suggestion, the snippet the cited (redacted)
|
|
25
|
+
line. A verified finding on the same line (path, side, line) as a rule finding
|
|
26
|
+
of the same category is merged into it (it counts as verified but is not
|
|
27
|
+
reported twice) only when the rule finding's effective severity is at least
|
|
28
|
+
the AI finding's and it blocks whenever the AI finding would, so a note never
|
|
29
|
+
absorbs a blocking AI veto. A rule finding's category is the first of its tags
|
|
30
|
+
that is an AI category, else by pack (secrets, security, agent, ci, deps:
|
|
31
|
+
security; tests: testing; hygiene: maintainability; everything else:
|
|
32
|
+
correctness).
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import hashlib
|
|
38
|
+
import json
|
|
39
|
+
from collections.abc import Iterable, Sequence
|
|
40
|
+
from typing import Any
|
|
41
|
+
|
|
42
|
+
from codeveto.ai.prompt import CATEGORIES
|
|
43
|
+
from codeveto.ai.runner import Pass
|
|
44
|
+
from codeveto.ai.verify import Verified
|
|
45
|
+
from codeveto.engine import MAX_SNIPPET_CHARS, Finding, Issue, normalize
|
|
46
|
+
from codeveto.report import ai_off
|
|
47
|
+
from codeveto.rules.base import Registry, Severity
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"AI_RULE_PREFIX",
|
|
51
|
+
"MAX_REJECTIONS",
|
|
52
|
+
"ai_findings",
|
|
53
|
+
"issues",
|
|
54
|
+
"rule_category",
|
|
55
|
+
"section",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
AI_RULE_PREFIX = "ai/"
|
|
59
|
+
MAX_REJECTIONS = 200
|
|
60
|
+
"""Most rejection records the report lists (``ai.rejected`` still counts all)."""
|
|
61
|
+
_PACK_CATEGORY = {
|
|
62
|
+
"secrets": "security",
|
|
63
|
+
"security": "security",
|
|
64
|
+
"agent": "security",
|
|
65
|
+
"ci": "security",
|
|
66
|
+
"deps": "security",
|
|
67
|
+
"tests": "testing",
|
|
68
|
+
"hygiene": "maintainability",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def rule_category(rule_id: str, registry: Registry | None = None) -> str:
|
|
73
|
+
"""The AI category a deterministic rule's findings belong to."""
|
|
74
|
+
entry = registry.get(rule_id) if registry is not None else None
|
|
75
|
+
if entry is not None:
|
|
76
|
+
for category in CATEGORIES:
|
|
77
|
+
if category in entry.meta.tags:
|
|
78
|
+
return category
|
|
79
|
+
return _PACK_CATEGORY.get(rule_id.split("/", 1)[0], "correctness")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _severity(level: str, blocking: bool, fail_on: str) -> tuple[str, bool]:
|
|
83
|
+
if level == "high":
|
|
84
|
+
return ("error", fail_on != "never") if blocking else ("warning", False)
|
|
85
|
+
return ("warning" if level == "medium" else "note"), False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _fingerprint(rule: str, path: str, side: str, text: str, index: int) -> str:
|
|
89
|
+
payload = json.dumps([rule, path, side, text, index], ensure_ascii=True)
|
|
90
|
+
return hashlib.sha256(payload.encode("ascii")).hexdigest()[:16]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def ai_findings(
|
|
94
|
+
verified: Iterable[Verified],
|
|
95
|
+
*,
|
|
96
|
+
blocking: bool,
|
|
97
|
+
fail_on: str,
|
|
98
|
+
rule_findings: Sequence[Finding] = (),
|
|
99
|
+
registry: Registry | None = None,
|
|
100
|
+
) -> tuple[list[dict[str, Any]], int]:
|
|
101
|
+
"""Report findings for verified AI findings, and how many were merged into rule findings."""
|
|
102
|
+
covered: dict[tuple[str, str, int | None, str], list[tuple[Severity, bool]]] = {}
|
|
103
|
+
for f in rule_findings:
|
|
104
|
+
key = (f.path, str(f.side), f.line, rule_category(f.rule, registry))
|
|
105
|
+
covered.setdefault(key, []).append((f.severity, f.blocking))
|
|
106
|
+
merged = 0
|
|
107
|
+
out: list[dict[str, Any]] = []
|
|
108
|
+
occurrences: dict[tuple[str, str, str], int] = {}
|
|
109
|
+
for v in sorted(verified, key=lambda v: (v.path, v.line, v.side, v.category)):
|
|
110
|
+
severity, blocks = _severity(v.severity, blocking, fail_on)
|
|
111
|
+
rank = Severity(severity)
|
|
112
|
+
rules = covered.get((v.path, v.side, v.line, v.category), ())
|
|
113
|
+
if any(level >= rank and (stops or not blocks) for level, stops in rules):
|
|
114
|
+
merged += 1 # the rule finding already says as much, at least as strongly
|
|
115
|
+
continue
|
|
116
|
+
rule = f"{AI_RULE_PREFIX}{v.category}"
|
|
117
|
+
text = normalize(v.text)
|
|
118
|
+
key = (rule, v.path, text)
|
|
119
|
+
index = occurrences.get(key, 0)
|
|
120
|
+
occurrences[key] = index + 1
|
|
121
|
+
out.append(
|
|
122
|
+
{
|
|
123
|
+
"fingerprint": _fingerprint(rule, v.path, v.side, text, index),
|
|
124
|
+
"rule": rule,
|
|
125
|
+
"severity": severity,
|
|
126
|
+
"blocking": blocks,
|
|
127
|
+
"path": v.path,
|
|
128
|
+
"old_path": v.old_path,
|
|
129
|
+
"side": v.side,
|
|
130
|
+
"line": v.line,
|
|
131
|
+
"end_line": None,
|
|
132
|
+
"column": None,
|
|
133
|
+
"message": f"{v.title.rstrip('.')}: {v.explanation}",
|
|
134
|
+
"hint": v.suggestion,
|
|
135
|
+
"snippet": v.text[:MAX_SNIPPET_CHARS],
|
|
136
|
+
"source": "ai",
|
|
137
|
+
"category": v.category,
|
|
138
|
+
}
|
|
139
|
+
)
|
|
140
|
+
return out, merged
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def section(run: Pass | None, *, provider: str | None = None) -> dict[str, Any]:
|
|
144
|
+
"""The report ``ai`` object for ``run`` (``status: off`` when there was no pass)."""
|
|
145
|
+
if run is None:
|
|
146
|
+
return ai_off(provider)
|
|
147
|
+
return {
|
|
148
|
+
"status": run.status,
|
|
149
|
+
"provider": run.provider,
|
|
150
|
+
"model": run.model,
|
|
151
|
+
"endpoint": run.endpoint,
|
|
152
|
+
"run_id": run.run_id,
|
|
153
|
+
"effort": run.effort,
|
|
154
|
+
"packets": [
|
|
155
|
+
{
|
|
156
|
+
"packet_id": p.packet_id,
|
|
157
|
+
"path": p.path,
|
|
158
|
+
"status": p.status,
|
|
159
|
+
"reason": p.reason,
|
|
160
|
+
"served_model": p.served_model,
|
|
161
|
+
}
|
|
162
|
+
for p in run.packets
|
|
163
|
+
],
|
|
164
|
+
"coverage": [{"path": path, "reason": reason} for path, reason in run.coverage],
|
|
165
|
+
"usage": _usage(run),
|
|
166
|
+
"verified": len(run.verified),
|
|
167
|
+
"rejected": len(run.rejections),
|
|
168
|
+
"rejections": [
|
|
169
|
+
{"packet_id": r.packet_id, "reason": r.reason, "detail": r.detail}
|
|
170
|
+
for r in run.rejections[:MAX_REJECTIONS]
|
|
171
|
+
],
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _usage(run: Pass) -> dict[str, int]:
|
|
176
|
+
usage = run.usage
|
|
177
|
+
return {
|
|
178
|
+
"input_tokens": usage.input_tokens,
|
|
179
|
+
"output_tokens": usage.output_tokens,
|
|
180
|
+
"cache_creation_input_tokens": usage.cache_creation_input_tokens,
|
|
181
|
+
"cache_read_input_tokens": usage.cache_read_input_tokens,
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _summary(run: Pass) -> str:
|
|
186
|
+
counts: dict[str, int] = {}
|
|
187
|
+
for p in run.packets:
|
|
188
|
+
if p.status != "verified":
|
|
189
|
+
counts[p.status] = counts.get(p.status, 0) + 1
|
|
190
|
+
parts = [f"{n} {status}" for status, n in sorted(counts.items())]
|
|
191
|
+
gaps = len({path for path, _ in run.gaps})
|
|
192
|
+
if gaps:
|
|
193
|
+
parts.append(f"{gaps} file(s) not fully packetized")
|
|
194
|
+
verified = len(run.packets) - sum(counts.values())
|
|
195
|
+
return f"{verified} of {len(run.packets)} packet(s) verified" + (
|
|
196
|
+
f" ({', '.join(parts)})" if parts else ""
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def issues(
|
|
201
|
+
run: Pass | None, *, blocking: bool, required: bool, optional: bool = False
|
|
202
|
+
) -> list[Issue]:
|
|
203
|
+
"""The issues a pass adds to the report (see the policy table in the module docstring)."""
|
|
204
|
+
if run is None or run.status in ("off", "complete"):
|
|
205
|
+
return []
|
|
206
|
+
name = run.provider
|
|
207
|
+
setting = "blocking" if blocking else "required" if required else None
|
|
208
|
+
if not run.started:
|
|
209
|
+
strict = blocking or required or not optional
|
|
210
|
+
message = f"AI pass ({name}) did not run: {run.problem}"
|
|
211
|
+
if not strict:
|
|
212
|
+
message += "; reviewed without AI (--ai-optional)"
|
|
213
|
+
elif optional and setting:
|
|
214
|
+
message += f"; --ai-optional does not apply because [ai] {setting} is set"
|
|
215
|
+
return [Issue("ai", message, incomplete=strict)]
|
|
216
|
+
if run.status == "failed":
|
|
217
|
+
detail = run.problem or _summary(run)
|
|
218
|
+
return [Issue("ai", f"AI pass ({name}) failed: {detail}", incomplete=blocking or required)]
|
|
219
|
+
detail = _summary(run)
|
|
220
|
+
if run.problem:
|
|
221
|
+
detail = f"{run.problem}; {detail}"
|
|
222
|
+
return [Issue("ai", f"AI pass ({name}) is partial: {detail}", incomplete=blocking)]
|
codeveto/ai/prompt.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""The fixed system prompt, the wire schema and the protocol constants (SPEC 9.2).
|
|
2
|
+
|
|
3
|
+
Both files ship in the package and are read as bytes, so their SHA-256 digests
|
|
4
|
+
(part of every ``packet_id``) are byte-stable. Nothing from the repository is
|
|
5
|
+
ever added to the system prompt; :func:`system_prompt` with
|
|
6
|
+
``embed_schema=True`` only appends the fixed wire schema (the OpenAI-compatible
|
|
7
|
+
``json_object`` and ``prompt`` response formats).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
from functools import cache
|
|
15
|
+
from importlib import resources
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"CATEGORIES",
|
|
20
|
+
"MAX_EXPLANATION_CHARS",
|
|
21
|
+
"MAX_FINDINGS_PER_PACKET",
|
|
22
|
+
"MAX_RESPONSE_BYTES",
|
|
23
|
+
"MAX_SUGGESTION_CHARS",
|
|
24
|
+
"MAX_TITLE_CHARS",
|
|
25
|
+
"PROTOCOL",
|
|
26
|
+
"SEVERITIES",
|
|
27
|
+
"canonical",
|
|
28
|
+
"prompt_sha256",
|
|
29
|
+
"schema_sha256",
|
|
30
|
+
"system_prompt",
|
|
31
|
+
"wire_schema",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
PROTOCOL = "codeveto-ai/1"
|
|
35
|
+
"""Version of the packet and response contract; part of every ``packet_id``."""
|
|
36
|
+
|
|
37
|
+
CATEGORIES: tuple[str, ...] = (
|
|
38
|
+
"correctness",
|
|
39
|
+
"security",
|
|
40
|
+
"reliability",
|
|
41
|
+
"concurrency",
|
|
42
|
+
"performance",
|
|
43
|
+
"compatibility",
|
|
44
|
+
"testing",
|
|
45
|
+
"maintainability",
|
|
46
|
+
)
|
|
47
|
+
SEVERITIES: tuple[str, ...] = ("high", "medium", "low")
|
|
48
|
+
|
|
49
|
+
MAX_FINDINGS_PER_PACKET = 8
|
|
50
|
+
MAX_TITLE_CHARS = 120
|
|
51
|
+
MAX_EXPLANATION_CHARS = 600
|
|
52
|
+
MAX_SUGGESTION_CHARS = 600
|
|
53
|
+
MAX_RESPONSE_BYTES = 256 * 1024
|
|
54
|
+
|
|
55
|
+
_PROMPT = "data/prompts/system.md"
|
|
56
|
+
_SCHEMA = "data/ai-wire.schema.json"
|
|
57
|
+
_SCHEMA_INTRO = (
|
|
58
|
+
"\n## Response schema\n\n"
|
|
59
|
+
"Your answer must be one JSON object that validates against this JSON Schema:\n\n"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@cache
|
|
64
|
+
def _bytes(name: str) -> bytes:
|
|
65
|
+
return resources.files("codeveto").joinpath(name).read_bytes()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def canonical(value: object) -> bytes:
|
|
69
|
+
"""Canonical JSON (sorted keys, no spaces, UTF-8, no NaN) for every digest."""
|
|
70
|
+
return json.dumps(
|
|
71
|
+
value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|
72
|
+
).encode("utf-8")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@cache
|
|
76
|
+
def _system(embed_schema: bool) -> str:
|
|
77
|
+
text = _bytes(_PROMPT).decode("utf-8")
|
|
78
|
+
if embed_schema:
|
|
79
|
+
schema = json.dumps(json.loads(_bytes(_SCHEMA)), indent=2, ensure_ascii=True)
|
|
80
|
+
text = f"{text}{_SCHEMA_INTRO}{schema}\n"
|
|
81
|
+
return text
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def system_prompt(*, embed_schema: bool = False) -> str:
|
|
85
|
+
"""The system prompt as shipped (plus the wire schema when ``embed_schema``)."""
|
|
86
|
+
return _system(embed_schema)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def wire_schema() -> dict[str, Any]:
|
|
90
|
+
"""The wire schema (a fresh copy each call)."""
|
|
91
|
+
return json.loads(_bytes(_SCHEMA))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def prompt_sha256() -> str:
|
|
95
|
+
"""SHA-256 of the shipped system prompt bytes."""
|
|
96
|
+
return hashlib.sha256(_bytes(_PROMPT)).hexdigest()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def schema_sha256() -> str:
|
|
100
|
+
"""SHA-256 of the shipped wire schema bytes."""
|
|
101
|
+
return hashlib.sha256(_bytes(_SCHEMA)).hexdigest()
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""AI provider adapters (SPEC 9.4) and the interface the runner uses.
|
|
2
|
+
|
|
3
|
+
A provider turns one :class:`Request` (a packet's JSON text, an output token
|
|
4
|
+
cap and a timeout) into one :class:`Outcome`. Providers never parse or trust
|
|
5
|
+
the model's answer; :mod:`codeveto.ai.verify` does. The optional SDKs are
|
|
6
|
+
imported inside the adapters' methods only, so CodeVeto runs without them;
|
|
7
|
+
a missing SDK is a :class:`ProviderUnavailable` naming the extra to install.
|
|
8
|
+
|
|
9
|
+
Outcome statuses:
|
|
10
|
+
|
|
11
|
+
- ``ok``: the model finished normally; ``text`` is its answer.
|
|
12
|
+
- ``truncated``: the output token cap was reached.
|
|
13
|
+
- ``refused``: the model or a safety system declined (``reason`` says how).
|
|
14
|
+
- ``unexpected_stop``: any other stop or finish reason.
|
|
15
|
+
- ``error``: this packet failed (rate limit, server error, connection,
|
|
16
|
+
timeout) after the SDK's own retries.
|
|
17
|
+
- ``abort``: the pass cannot continue (authentication, permission, unknown
|
|
18
|
+
model, a rejected request); ``reason`` is the one issue the report shows.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import ipaddress
|
|
24
|
+
import os
|
|
25
|
+
from collections.abc import Mapping
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Literal, Protocol
|
|
28
|
+
from urllib.parse import urlsplit
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"Endpoint",
|
|
32
|
+
"Outcome",
|
|
33
|
+
"OutcomeStatus",
|
|
34
|
+
"Provider",
|
|
35
|
+
"ProviderUnavailable",
|
|
36
|
+
"Request",
|
|
37
|
+
"Usage",
|
|
38
|
+
"check_base_url",
|
|
39
|
+
"create",
|
|
40
|
+
"loopback",
|
|
41
|
+
"usage_of",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
OutcomeStatus = Literal["ok", "truncated", "refused", "unexpected_stop", "error", "abort"]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ProviderUnavailable(Exception):
|
|
48
|
+
"""The pass cannot start (missing SDK or credentials, bad settings, capability check)."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True, slots=True)
|
|
52
|
+
class Usage:
|
|
53
|
+
input_tokens: int = 0
|
|
54
|
+
output_tokens: int = 0
|
|
55
|
+
cache_creation_input_tokens: int = 0
|
|
56
|
+
cache_read_input_tokens: int = 0
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def total_input(self) -> int:
|
|
60
|
+
return self.input_tokens + self.cache_creation_input_tokens + self.cache_read_input_tokens
|
|
61
|
+
|
|
62
|
+
def __add__(self, other: Usage) -> Usage:
|
|
63
|
+
return Usage(
|
|
64
|
+
self.input_tokens + other.input_tokens,
|
|
65
|
+
self.output_tokens + other.output_tokens,
|
|
66
|
+
self.cache_creation_input_tokens + other.cache_creation_input_tokens,
|
|
67
|
+
self.cache_read_input_tokens + other.cache_read_input_tokens,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True, slots=True)
|
|
72
|
+
class Request:
|
|
73
|
+
packet_id: str
|
|
74
|
+
message: str
|
|
75
|
+
max_tokens: int
|
|
76
|
+
timeout: float
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True, slots=True)
|
|
80
|
+
class Outcome:
|
|
81
|
+
status: OutcomeStatus
|
|
82
|
+
text: str | None = None
|
|
83
|
+
served_model: str | None = None
|
|
84
|
+
usage: Usage = Usage()
|
|
85
|
+
reason: str | None = None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class Provider(Protocol):
|
|
89
|
+
"""What the runner needs from a provider."""
|
|
90
|
+
|
|
91
|
+
name: str
|
|
92
|
+
model: str | None
|
|
93
|
+
endpoint: str | None
|
|
94
|
+
effort: str | None
|
|
95
|
+
|
|
96
|
+
def prepare(self) -> None:
|
|
97
|
+
"""Build the client and run the capability step; raise :class:`ProviderUnavailable`."""
|
|
98
|
+
|
|
99
|
+
def review(self, request: Request) -> Outcome:
|
|
100
|
+
"""Send one packet; never raise for API or network errors (return an outcome)."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def loopback(host: str) -> bool:
|
|
104
|
+
"""Is ``host`` exactly ``localhost`` or a literal loopback IP address?"""
|
|
105
|
+
if host == "localhost":
|
|
106
|
+
return True
|
|
107
|
+
try:
|
|
108
|
+
return ipaddress.ip_address(host).is_loopback
|
|
109
|
+
except ValueError:
|
|
110
|
+
return False
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True, slots=True)
|
|
114
|
+
class Endpoint:
|
|
115
|
+
"""A checked base URL: its host and the endpoint the report shows."""
|
|
116
|
+
|
|
117
|
+
url: str
|
|
118
|
+
host: str
|
|
119
|
+
shown: str # host, port and path, without scheme or user info
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def check_base_url(url: str) -> Endpoint:
|
|
123
|
+
"""Accept ``https://`` URLs, and ``http://`` only for loopback hosts.
|
|
124
|
+
|
|
125
|
+
Spaces, control characters, user info and a missing host are refused
|
|
126
|
+
(:class:`ProviderUnavailable`).
|
|
127
|
+
"""
|
|
128
|
+
if any(ord(c) <= 0x20 or ord(c) == 0x7F for c in url):
|
|
129
|
+
raise ProviderUnavailable("the AI base URL must not contain spaces or control characters")
|
|
130
|
+
try:
|
|
131
|
+
parts = urlsplit(url)
|
|
132
|
+
host = parts.hostname
|
|
133
|
+
port = parts.port
|
|
134
|
+
except ValueError:
|
|
135
|
+
raise ProviderUnavailable("the AI base URL is not a valid URL") from None
|
|
136
|
+
if parts.scheme not in ("https", "http") or not host:
|
|
137
|
+
raise ProviderUnavailable("the AI base URL must be an http(s) URL with a host")
|
|
138
|
+
if parts.username is not None or parts.password is not None or "@" in parts.netloc:
|
|
139
|
+
raise ProviderUnavailable("the AI base URL must not contain credentials")
|
|
140
|
+
if parts.scheme == "http" and not loopback(host):
|
|
141
|
+
raise ProviderUnavailable(
|
|
142
|
+
"the AI base URL uses http:// for a host that is not loopback; use https://"
|
|
143
|
+
)
|
|
144
|
+
shown = f"[{host}]" if ":" in host else host
|
|
145
|
+
if port is not None:
|
|
146
|
+
shown += f":{port}"
|
|
147
|
+
return Endpoint(url, host, shown + parts.path.rstrip("/"))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _count(value: object) -> int:
|
|
151
|
+
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def usage_of(**counts: object) -> Usage:
|
|
155
|
+
"""A :class:`Usage` from SDK counters (``None`` and junk count as 0)."""
|
|
156
|
+
return Usage(**{name: _count(value) for name, value in counts.items()})
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def create(
|
|
160
|
+
name: str,
|
|
161
|
+
settings: object,
|
|
162
|
+
*,
|
|
163
|
+
response_format: str | None = None,
|
|
164
|
+
environ: Mapping[str, str] | None = None,
|
|
165
|
+
) -> Provider:
|
|
166
|
+
"""The provider called ``name`` for the effective ``[ai]`` settings."""
|
|
167
|
+
env = os.environ if environ is None else environ
|
|
168
|
+
if name == "claude":
|
|
169
|
+
from codeveto.ai.providers.claude import ClaudeProvider
|
|
170
|
+
|
|
171
|
+
return ClaudeProvider(settings, environ=env)
|
|
172
|
+
if name == "openai":
|
|
173
|
+
from codeveto.ai.providers.openai_compat import OpenAIProvider
|
|
174
|
+
|
|
175
|
+
return OpenAIProvider(
|
|
176
|
+
settings, response_format=response_format or "json_schema", environ=env
|
|
177
|
+
)
|
|
178
|
+
raise ProviderUnavailable(f"unknown AI provider {name!r}")
|