margin-core 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.
- margin_core/__init__.py +68 -0
- margin_core/_fs.py +37 -0
- margin_core/agent.py +255 -0
- margin_core/config.py +184 -0
- margin_core/errors.py +49 -0
- margin_core/inputs.py +71 -0
- margin_core/llm/__init__.py +30 -0
- margin_core/llm/_chat_completions.py +34 -0
- margin_core/llm/_http.py +42 -0
- margin_core/llm/anthropic.py +80 -0
- margin_core/llm/base.py +338 -0
- margin_core/llm/catalog.py +126 -0
- margin_core/llm/factory.py +75 -0
- margin_core/llm/local.py +196 -0
- margin_core/llm/mock.py +85 -0
- margin_core/llm/openai.py +62 -0
- margin_core/llm/pricing.py +55 -0
- margin_core/loaders/__init__.py +53 -0
- margin_core/loaders/base.py +213 -0
- margin_core/loaders/filters.py +247 -0
- margin_core/loaders/git.py +176 -0
- margin_core/loaders/github.py +186 -0
- margin_core/loaders/local.py +163 -0
- margin_core/logging.py +20 -0
- margin_core/models.py +130 -0
- margin_core/py.typed +1 -0
- margin_core/registry.py +111 -0
- margin_core/reporting/__init__.py +6 -0
- margin_core/reporting/json_report.py +18 -0
- margin_core/reporting/markdown_report.py +84 -0
- margin_core/runner.py +27 -0
- margin_core-0.1.0.dist-info/METADATA +106 -0
- margin_core-0.1.0.dist-info/RECORD +35 -0
- margin_core-0.1.0.dist-info/WHEEL +4 -0
- margin_core-0.1.0.dist-info/licenses/LICENSE +21 -0
margin_core/llm/local.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Client for locally hosted models behind an OpenAI-compatible API.
|
|
2
|
+
|
|
3
|
+
Works with Ollama (default, ``http://localhost:11434``), LM Studio (``:1234``),
|
|
4
|
+
llama.cpp ``llama-server`` (``:8080``) and vLLM (``:8000``). Calls are free, so pricing is
|
|
5
|
+
zero and the budget cap never triggers; timeouts are longer because the first call may
|
|
6
|
+
have to load the model into memory.
|
|
7
|
+
|
|
8
|
+
OpenAI-compatible servers silently truncate prompts that exceed the model's context window.
|
|
9
|
+
For Ollama the window is read from ``/api/ps`` (an overflowing prompt is reported as exactly
|
|
10
|
+
the window size); for other servers a ratio heuristic catches gross truncation. Either way
|
|
11
|
+
the response carries a warning instead of failing.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
from typing import Any, ClassVar, Unpack
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
from margin_core.errors import LLMError, TransientLLMError
|
|
22
|
+
from margin_core.llm._chat_completions import chat_messages, parse_chat_completion
|
|
23
|
+
from margin_core.llm._http import post_json
|
|
24
|
+
from margin_core.llm.base import LLMClient, LLMClientOptions, LLMResponse, Message
|
|
25
|
+
from margin_core.llm.pricing import FREE
|
|
26
|
+
|
|
27
|
+
DEFAULT_BASE_URL = "http://localhost:11434"
|
|
28
|
+
|
|
29
|
+
# Fallback truncation heuristic for servers that do not report their context window. Code
|
|
30
|
+
# averages about 3 characters per token, so a reported count below 0.6 x (chars / 4) means
|
|
31
|
+
# a large share of the prompt was dropped.
|
|
32
|
+
TRUNCATION_RATIO = 0.6
|
|
33
|
+
MIN_CHARS_FOR_RATIO_CHECK = 4000
|
|
34
|
+
MAX_CONTEXT_PROBES = 3
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _normalize_base_url(base_url: str) -> str:
|
|
38
|
+
url = base_url.strip().rstrip("/")
|
|
39
|
+
return url[: -len("/v1")] if url.endswith("/v1") else url
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class LocalLLM(LLMClient):
|
|
43
|
+
"""Client for a local OpenAI-compatible server. Reads ``LOCAL_LLM_BASE_URL`` if set.
|
|
44
|
+
|
|
45
|
+
With ``structured_output=True`` (default), :meth:`complete_structured` requests
|
|
46
|
+
schema-constrained decoding via ``response_format``, which makes small models far more
|
|
47
|
+
reliable at emitting valid JSON. Disable it for servers that reject that field.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
provider: ClassVar[str] = "local"
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
model: str,
|
|
55
|
+
*,
|
|
56
|
+
base_url: str | None = None,
|
|
57
|
+
api_key: str | None = None,
|
|
58
|
+
structured_output: bool = True,
|
|
59
|
+
reasoning_effort: str | None = "none",
|
|
60
|
+
http_client: httpx.AsyncClient | None = None,
|
|
61
|
+
**options: Unpack[LLMClientOptions],
|
|
62
|
+
) -> None:
|
|
63
|
+
options.setdefault("pricing", FREE)
|
|
64
|
+
options.setdefault("timeout_s", 300.0)
|
|
65
|
+
options.setdefault("max_retries", 1)
|
|
66
|
+
super().__init__(model, **options)
|
|
67
|
+
self.base_url = _normalize_base_url(
|
|
68
|
+
base_url or os.environ.get("LOCAL_LLM_BASE_URL") or DEFAULT_BASE_URL
|
|
69
|
+
)
|
|
70
|
+
self._url = f"{self.base_url}/v1/chat/completions"
|
|
71
|
+
self._api_key = api_key # only for servers started with an API key (e.g. vLLM)
|
|
72
|
+
self.structured_output = structured_output
|
|
73
|
+
# Thinking models (e.g. qwen3.5) otherwise spend the whole output budget on hidden
|
|
74
|
+
# reasoning. "none" turns it off; other models ignore the field (verified 2026-10-19).
|
|
75
|
+
self.reasoning_effort = reasoning_effort or None
|
|
76
|
+
self._http_client = http_client
|
|
77
|
+
self._context_window: int | None = None
|
|
78
|
+
self._context_probes_left = MAX_CONTEXT_PROBES
|
|
79
|
+
|
|
80
|
+
async def context_window(self) -> int | None:
|
|
81
|
+
"""Context window of the loaded model (Ollama only), cached once known."""
|
|
82
|
+
if self._context_window is None and self._context_probes_left > 0:
|
|
83
|
+
self._context_probes_left -= 1
|
|
84
|
+
self._context_window = await self._probe_context_window()
|
|
85
|
+
return self._context_window
|
|
86
|
+
|
|
87
|
+
async def _probe_context_window(self) -> int | None:
|
|
88
|
+
url = f"{self.base_url}/api/ps"
|
|
89
|
+
try:
|
|
90
|
+
if self._http_client is not None:
|
|
91
|
+
response = await self._http_client.get(url, timeout=5.0)
|
|
92
|
+
else:
|
|
93
|
+
async with httpx.AsyncClient(timeout=5.0) as client:
|
|
94
|
+
response = await client.get(url)
|
|
95
|
+
except httpx.HTTPError:
|
|
96
|
+
self._context_probes_left = 0
|
|
97
|
+
return None
|
|
98
|
+
if response.status_code != 200:
|
|
99
|
+
self._context_probes_left = 0 # not Ollama; it will not start answering later
|
|
100
|
+
return None
|
|
101
|
+
try:
|
|
102
|
+
models = response.json().get("models") or []
|
|
103
|
+
except ValueError:
|
|
104
|
+
self._context_probes_left = 0
|
|
105
|
+
return None
|
|
106
|
+
names = {self.model, f"{self.model}:latest"}
|
|
107
|
+
for entry in models:
|
|
108
|
+
if isinstance(entry, dict) and (
|
|
109
|
+
entry.get("name") in names or entry.get("model") in names
|
|
110
|
+
):
|
|
111
|
+
window = entry.get("context_length")
|
|
112
|
+
return window if isinstance(window, int) and window > 0 else None
|
|
113
|
+
return None # model not loaded yet; probe again after a later call
|
|
114
|
+
|
|
115
|
+
async def _truncation_warning(self, prompt_chars: int, prompt_tokens: int) -> str | None:
|
|
116
|
+
window = await self.context_window()
|
|
117
|
+
if window is not None:
|
|
118
|
+
if prompt_tokens >= window:
|
|
119
|
+
return (
|
|
120
|
+
f"A prompt filled the local model's whole context window ({window} tokens) "
|
|
121
|
+
"and was probably truncated. Raise the window (Ollama: "
|
|
122
|
+
"OLLAMA_CONTEXT_LENGTH) or send less text."
|
|
123
|
+
)
|
|
124
|
+
return None
|
|
125
|
+
expected = prompt_chars / 4
|
|
126
|
+
if (
|
|
127
|
+
prompt_chars >= MIN_CHARS_FOR_RATIO_CHECK
|
|
128
|
+
and prompt_tokens < TRUNCATION_RATIO * expected
|
|
129
|
+
):
|
|
130
|
+
return (
|
|
131
|
+
"A prompt was probably truncated by the local LLM server (it counted far fewer "
|
|
132
|
+
"tokens than were sent). Raise the server's context window or send less text."
|
|
133
|
+
)
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
async def _complete_raw(
|
|
137
|
+
self,
|
|
138
|
+
messages: list[Message],
|
|
139
|
+
system: str | None,
|
|
140
|
+
max_tokens: int,
|
|
141
|
+
temperature: float | None,
|
|
142
|
+
json_schema: dict[str, Any] | None = None,
|
|
143
|
+
) -> LLMResponse:
|
|
144
|
+
payload: dict[str, Any] = {
|
|
145
|
+
"model": self.model,
|
|
146
|
+
"messages": chat_messages(messages, system),
|
|
147
|
+
"max_tokens": max_tokens,
|
|
148
|
+
}
|
|
149
|
+
if temperature is not None:
|
|
150
|
+
payload["temperature"] = temperature
|
|
151
|
+
if self.reasoning_effort is not None:
|
|
152
|
+
payload["reasoning_effort"] = self.reasoning_effort
|
|
153
|
+
if json_schema is not None and self.structured_output:
|
|
154
|
+
payload["response_format"] = {
|
|
155
|
+
"type": "json_schema",
|
|
156
|
+
"json_schema": {
|
|
157
|
+
"name": json_schema.get("title", "response"),
|
|
158
|
+
"schema": json_schema,
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else {}
|
|
162
|
+
try:
|
|
163
|
+
data = await post_json(
|
|
164
|
+
self._url,
|
|
165
|
+
headers=headers,
|
|
166
|
+
payload=payload,
|
|
167
|
+
timeout_s=self.timeout_s,
|
|
168
|
+
client=self._http_client,
|
|
169
|
+
)
|
|
170
|
+
except TransientLLMError as exc:
|
|
171
|
+
if isinstance(exc.__cause__, httpx.ConnectError):
|
|
172
|
+
# Not worth retrying: nothing is listening.
|
|
173
|
+
raise LLMError(
|
|
174
|
+
f"Cannot reach a local LLM server at {self.base_url}. Is it running? "
|
|
175
|
+
"(Ollama: `ollama serve`; or set LOCAL_LLM_BASE_URL)"
|
|
176
|
+
) from exc
|
|
177
|
+
raise
|
|
178
|
+
except LLMError as exc:
|
|
179
|
+
if "HTTP 404" in str(exc):
|
|
180
|
+
raise LLMError(
|
|
181
|
+
f"{exc}\nModel {self.model!r} may not be available locally "
|
|
182
|
+
f"(Ollama: `ollama pull {self.model}`)"
|
|
183
|
+
) from exc
|
|
184
|
+
raise
|
|
185
|
+
response = parse_chat_completion(data, self.model, "local LLM")
|
|
186
|
+
message = (data.get("choices") or [{}])[0].get("message") or {}
|
|
187
|
+
if not response.text and (message.get("reasoning") or message.get("reasoning_content")):
|
|
188
|
+
raise LLMError(
|
|
189
|
+
f"{self.model} spent its whole output on hidden reasoning and gave no answer. "
|
|
190
|
+
"Set LOCAL_LLM_REASONING_EFFORT=none (the default) or raise max_tokens."
|
|
191
|
+
)
|
|
192
|
+
prompt_chars = sum(len(m.content) for m in messages) + len(system or "")
|
|
193
|
+
warning = await self._truncation_warning(prompt_chars, response.input_tokens)
|
|
194
|
+
if warning:
|
|
195
|
+
response = response.model_copy(update={"warnings": [*response.warnings, warning]})
|
|
196
|
+
return response
|
margin_core/llm/mock.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Deterministic LLM client for tests. Never touches the network."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, ClassVar, Unpack
|
|
9
|
+
|
|
10
|
+
from margin_core.llm.base import LLMClient, LLMClientOptions, LLMResponse, Message
|
|
11
|
+
from margin_core.llm.pricing import FREE
|
|
12
|
+
|
|
13
|
+
Responder = Callable[[list[Message], str | None], str]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class MockCall:
|
|
18
|
+
"""A recorded call to :class:`MockLLM`."""
|
|
19
|
+
|
|
20
|
+
messages: list[Message]
|
|
21
|
+
system: str | None
|
|
22
|
+
max_tokens: int
|
|
23
|
+
json_schema: dict[str, Any] | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class MockLLM(LLMClient):
|
|
27
|
+
"""Returns canned responses.
|
|
28
|
+
|
|
29
|
+
``responses`` may be a sequence (consumed in order; an ``Exception`` item is raised
|
|
30
|
+
instead of returned) or a callable ``(messages, system) -> str``. With no responses,
|
|
31
|
+
the last user message is echoed back.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
provider: ClassVar[str] = "mock"
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
responses: Sequence[str | Exception] | Responder | None = None,
|
|
39
|
+
*,
|
|
40
|
+
model: str = "mock-model",
|
|
41
|
+
**options: Unpack[LLMClientOptions],
|
|
42
|
+
) -> None:
|
|
43
|
+
options.setdefault("pricing", FREE)
|
|
44
|
+
options.setdefault("backoff_base_s", 0.0)
|
|
45
|
+
super().__init__(model, **options)
|
|
46
|
+
self._responder: Responder | None = None
|
|
47
|
+
self._queue: list[str | Exception] = []
|
|
48
|
+
if callable(responses):
|
|
49
|
+
self._responder = responses
|
|
50
|
+
elif responses is not None:
|
|
51
|
+
self._queue = list(responses)
|
|
52
|
+
self.calls: list[MockCall] = []
|
|
53
|
+
|
|
54
|
+
async def _complete_raw(
|
|
55
|
+
self,
|
|
56
|
+
messages: list[Message],
|
|
57
|
+
system: str | None,
|
|
58
|
+
max_tokens: int,
|
|
59
|
+
temperature: float | None,
|
|
60
|
+
json_schema: dict[str, Any] | None = None,
|
|
61
|
+
) -> LLMResponse:
|
|
62
|
+
self.calls.append(
|
|
63
|
+
MockCall(
|
|
64
|
+
messages=list(messages),
|
|
65
|
+
system=system,
|
|
66
|
+
max_tokens=max_tokens,
|
|
67
|
+
json_schema=json_schema,
|
|
68
|
+
)
|
|
69
|
+
)
|
|
70
|
+
if self._responder is not None:
|
|
71
|
+
text = self._responder(messages, system)
|
|
72
|
+
elif self._queue:
|
|
73
|
+
item = self._queue.pop(0)
|
|
74
|
+
if isinstance(item, Exception):
|
|
75
|
+
raise item
|
|
76
|
+
text = item
|
|
77
|
+
else:
|
|
78
|
+
text = next((m.content for m in reversed(messages) if m.role == "user"), "")
|
|
79
|
+
prompt_chars = sum(len(m.content) for m in messages) + len(system or "")
|
|
80
|
+
return LLMResponse(
|
|
81
|
+
text=text,
|
|
82
|
+
model=self.model,
|
|
83
|
+
input_tokens=math.ceil(prompt_chars / 4),
|
|
84
|
+
output_tokens=math.ceil(len(text) / 4),
|
|
85
|
+
)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""OpenAI Chat Completions client (REST via httpx)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any, ClassVar, Unpack
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from margin_core.errors import LLMError
|
|
11
|
+
from margin_core.llm._chat_completions import chat_messages, parse_chat_completion
|
|
12
|
+
from margin_core.llm._http import post_json
|
|
13
|
+
from margin_core.llm.base import LLMClient, LLMClientOptions, LLMResponse, Message
|
|
14
|
+
|
|
15
|
+
DEFAULT_BASE_URL = "https://api.openai.com"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class OpenAILLM(LLMClient):
|
|
19
|
+
"""Client for OpenAI Chat Completions. Reads ``OPENAI_API_KEY`` if no key is given."""
|
|
20
|
+
|
|
21
|
+
provider: ClassVar[str] = "openai"
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
model: str,
|
|
26
|
+
*,
|
|
27
|
+
api_key: str | None = None,
|
|
28
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
29
|
+
http_client: httpx.AsyncClient | None = None,
|
|
30
|
+
**options: Unpack[LLMClientOptions],
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__(model, **options)
|
|
33
|
+
key = api_key or os.environ.get("OPENAI_API_KEY")
|
|
34
|
+
if not key:
|
|
35
|
+
raise LLMError("OpenAI API key missing: set OPENAI_API_KEY or pass api_key")
|
|
36
|
+
self._api_key = key
|
|
37
|
+
self._url = f"{base_url.rstrip('/')}/v1/chat/completions"
|
|
38
|
+
self._http_client = http_client
|
|
39
|
+
|
|
40
|
+
async def _complete_raw(
|
|
41
|
+
self,
|
|
42
|
+
messages: list[Message],
|
|
43
|
+
system: str | None,
|
|
44
|
+
max_tokens: int,
|
|
45
|
+
temperature: float | None,
|
|
46
|
+
json_schema: dict[str, Any] | None = None,
|
|
47
|
+
) -> LLMResponse:
|
|
48
|
+
payload: dict[str, Any] = {
|
|
49
|
+
"model": self.model,
|
|
50
|
+
"messages": chat_messages(messages, system),
|
|
51
|
+
"max_completion_tokens": max_tokens,
|
|
52
|
+
}
|
|
53
|
+
if temperature is not None:
|
|
54
|
+
payload["temperature"] = temperature
|
|
55
|
+
data = await post_json(
|
|
56
|
+
self._url,
|
|
57
|
+
headers={"Authorization": f"Bearer {self._api_key}"},
|
|
58
|
+
payload=payload,
|
|
59
|
+
timeout_s=self.timeout_s,
|
|
60
|
+
client=self._http_client,
|
|
61
|
+
)
|
|
62
|
+
return parse_chat_completion(data, self.model, "OpenAI")
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Per-model pricing used for cost tracking and budget enforcement.
|
|
2
|
+
|
|
3
|
+
Prices are USD per million tokens and are *estimates*: they go stale, so pass an explicit
|
|
4
|
+
:class:`ModelPricing` to a client when accuracy matters. Unknown models fall back to a
|
|
5
|
+
deliberately expensive price so budget caps err on the safe side.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, ConfigDict
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ModelPricing(BaseModel):
|
|
14
|
+
"""USD price per one million input/output tokens."""
|
|
15
|
+
|
|
16
|
+
model_config = ConfigDict(frozen=True)
|
|
17
|
+
|
|
18
|
+
input_per_mtok: float
|
|
19
|
+
output_per_mtok: float
|
|
20
|
+
|
|
21
|
+
def cost(self, input_tokens: int, output_tokens: int) -> float:
|
|
22
|
+
return (
|
|
23
|
+
input_tokens * self.input_per_mtok + output_tokens * self.output_per_mtok
|
|
24
|
+
) / 1_000_000
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
FREE = ModelPricing(input_per_mtok=0.0, output_per_mtok=0.0)
|
|
28
|
+
CONSERVATIVE_FALLBACK = ModelPricing(input_per_mtok=15.0, output_per_mtok=75.0)
|
|
29
|
+
|
|
30
|
+
# Matched by longest model-name prefix within a provider.
|
|
31
|
+
DEFAULT_PRICING: dict[str, dict[str, ModelPricing]] = {
|
|
32
|
+
"anthropic": {
|
|
33
|
+
"claude-opus": ModelPricing(input_per_mtok=15.0, output_per_mtok=75.0),
|
|
34
|
+
"claude-sonnet": ModelPricing(input_per_mtok=3.0, output_per_mtok=15.0),
|
|
35
|
+
"claude-haiku": ModelPricing(input_per_mtok=1.0, output_per_mtok=5.0),
|
|
36
|
+
},
|
|
37
|
+
"openai": {
|
|
38
|
+
"gpt-4o-mini": ModelPricing(input_per_mtok=0.15, output_per_mtok=0.6),
|
|
39
|
+
"gpt-4o": ModelPricing(input_per_mtok=2.5, output_per_mtok=10.0),
|
|
40
|
+
"gpt-4.1-nano": ModelPricing(input_per_mtok=0.1, output_per_mtok=0.4),
|
|
41
|
+
"gpt-4.1-mini": ModelPricing(input_per_mtok=0.4, output_per_mtok=1.6),
|
|
42
|
+
"gpt-4.1": ModelPricing(input_per_mtok=2.0, output_per_mtok=8.0),
|
|
43
|
+
},
|
|
44
|
+
"local": {"": FREE},
|
|
45
|
+
"mock": {"": FREE},
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def lookup_pricing(provider: str, model: str) -> ModelPricing:
|
|
50
|
+
"""Return pricing for ``model`` (longest prefix match), or a conservative fallback."""
|
|
51
|
+
table = DEFAULT_PRICING.get(provider, {})
|
|
52
|
+
matches = [prefix for prefix in table if model.startswith(prefix)]
|
|
53
|
+
if not matches:
|
|
54
|
+
return CONSERVATIVE_FALLBACK
|
|
55
|
+
return table[max(matches, key=len)]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Loaders turn a target (GitHub URL or local path) into a :class:`Workspace`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
|
|
7
|
+
from margin_core.errors import InvalidTargetError
|
|
8
|
+
from margin_core.loaders.base import (
|
|
9
|
+
FileInfo,
|
|
10
|
+
GitCommit,
|
|
11
|
+
GitInfo,
|
|
12
|
+
Loader,
|
|
13
|
+
LoaderLimits,
|
|
14
|
+
SkippedFile,
|
|
15
|
+
Workspace,
|
|
16
|
+
)
|
|
17
|
+
from margin_core.loaders.filters import FilterConfig
|
|
18
|
+
from margin_core.loaders.github import GitHubLoader, parse_github_url
|
|
19
|
+
from margin_core.loaders.local import LocalLoader
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"FileInfo",
|
|
23
|
+
"FilterConfig",
|
|
24
|
+
"GitCommit",
|
|
25
|
+
"GitHubLoader",
|
|
26
|
+
"GitInfo",
|
|
27
|
+
"Loader",
|
|
28
|
+
"LoaderLimits",
|
|
29
|
+
"LocalLoader",
|
|
30
|
+
"SkippedFile",
|
|
31
|
+
"Workspace",
|
|
32
|
+
"load_workspace",
|
|
33
|
+
"parse_github_url",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def load_workspace(
|
|
38
|
+
target: str,
|
|
39
|
+
*,
|
|
40
|
+
paths: Sequence[str] | None = None,
|
|
41
|
+
branch: str | None = None,
|
|
42
|
+
limits: LoaderLimits | None = None,
|
|
43
|
+
filters: FilterConfig | None = None,
|
|
44
|
+
) -> Workspace:
|
|
45
|
+
"""Pick the right loader for ``target`` and load it."""
|
|
46
|
+
stripped = target.strip()
|
|
47
|
+
if GitHubLoader.can_handle(stripped):
|
|
48
|
+
return await GitHubLoader(limits, filters).load(stripped, paths=paths, branch=branch)
|
|
49
|
+
if "://" in stripped or stripped.startswith("git@"):
|
|
50
|
+
raise InvalidTargetError(
|
|
51
|
+
f"Unsupported URL {target!r}: only https://github.com/<owner>/<repo> is allowed"
|
|
52
|
+
)
|
|
53
|
+
return await LocalLoader(limits, filters).load(stripped, paths=paths, branch=branch)
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Workspace abstraction produced by every loader."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from abc import ABC, abstractmethod
|
|
7
|
+
from collections.abc import Callable, Sequence
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from pathlib import Path, PurePosixPath
|
|
10
|
+
from types import TracebackType
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
|
|
13
|
+
|
|
14
|
+
from margin_core.errors import InvalidTargetError
|
|
15
|
+
from margin_core.logging import get_logger
|
|
16
|
+
|
|
17
|
+
logger = get_logger("loaders")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FileInfo(BaseModel):
|
|
21
|
+
"""A file kept in the workspace."""
|
|
22
|
+
|
|
23
|
+
path: str = Field(description="POSIX path relative to the workspace root.")
|
|
24
|
+
size: int
|
|
25
|
+
language: str | None = None
|
|
26
|
+
is_generated: bool = False
|
|
27
|
+
is_vendored: bool = False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SkippedFile(BaseModel):
|
|
31
|
+
"""A file or directory excluded from the workspace, and why."""
|
|
32
|
+
|
|
33
|
+
path: str
|
|
34
|
+
reason: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class GitCommit(BaseModel):
|
|
38
|
+
"""Commit metadata (no diffs)."""
|
|
39
|
+
|
|
40
|
+
sha: str
|
|
41
|
+
author_name: str
|
|
42
|
+
author_email: str
|
|
43
|
+
authored_at: datetime
|
|
44
|
+
committer_name: str
|
|
45
|
+
committer_email: str
|
|
46
|
+
committed_at: datetime
|
|
47
|
+
parents: list[str] = Field(default_factory=list)
|
|
48
|
+
message: str
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def subject(self) -> str:
|
|
52
|
+
return self.message.split("\n", 1)[0]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class GitInfo(BaseModel):
|
|
56
|
+
"""Access to a git repository's history, limited to the workspace being analysed.
|
|
57
|
+
|
|
58
|
+
``root`` is the repository's top level. ``prefix`` is the workspace root relative to it
|
|
59
|
+
(empty when they are the same). ``pathspecs`` restrict history to the analysed files; an
|
|
60
|
+
empty list means the whole repository.
|
|
61
|
+
|
|
62
|
+
Every query here uses name-only history. In blobless clones, options such as
|
|
63
|
+
``--numstat``, ``--stat`` or ``-p`` would download every historical blob.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
root: Path
|
|
67
|
+
head: str | None = None
|
|
68
|
+
branch: str | None = None
|
|
69
|
+
prefix: str = ""
|
|
70
|
+
pathspecs: list[str] = Field(default_factory=list)
|
|
71
|
+
|
|
72
|
+
async def commits(self, max_count: int | None = None) -> list[GitCommit]:
|
|
73
|
+
"""Commits reachable from HEAD that touch the analysed files, newest first."""
|
|
74
|
+
from margin_core.loaders.git import read_commits
|
|
75
|
+
|
|
76
|
+
if self.head is None:
|
|
77
|
+
return []
|
|
78
|
+
return await read_commits(self.root, max_count=max_count, pathspecs=self.pathspecs)
|
|
79
|
+
|
|
80
|
+
async def changed_files(self, max_count: int | None = None) -> dict[str, list[str]]:
|
|
81
|
+
"""Map of commit SHA to the workspace-relative files it changed (merges excluded)."""
|
|
82
|
+
from margin_core.loaders.git import read_changed_files
|
|
83
|
+
|
|
84
|
+
if self.head is None:
|
|
85
|
+
return {}
|
|
86
|
+
raw = await read_changed_files(self.root, pathspecs=self.pathspecs, max_count=max_count)
|
|
87
|
+
result: dict[str, list[str]] = {}
|
|
88
|
+
for sha, paths in raw:
|
|
89
|
+
result[sha] = [rel for p in paths if (rel := self.to_workspace_path(p)) is not None]
|
|
90
|
+
return result
|
|
91
|
+
|
|
92
|
+
async def file_history(self, max_count: int | None = None) -> dict[str, list[str]]:
|
|
93
|
+
"""Map of workspace-relative path to SHAs of commits that changed it, newest first."""
|
|
94
|
+
history: dict[str, list[str]] = {}
|
|
95
|
+
for sha, paths in (await self.changed_files(max_count)).items():
|
|
96
|
+
for path in paths:
|
|
97
|
+
history.setdefault(path, []).append(sha)
|
|
98
|
+
return history
|
|
99
|
+
|
|
100
|
+
def to_workspace_path(self, repo_path: str) -> str | None:
|
|
101
|
+
"""Convert a repository-relative path to a workspace-relative one (None if outside)."""
|
|
102
|
+
if not self.prefix:
|
|
103
|
+
return repo_path
|
|
104
|
+
lead = self.prefix + "/"
|
|
105
|
+
return repo_path[len(lead) :] if repo_path.startswith(lead) else None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class LoaderLimits(BaseModel):
|
|
109
|
+
"""Safety limits. Exceeding a hard limit raises ``LimitExceededError``."""
|
|
110
|
+
|
|
111
|
+
max_files: int = 10_000
|
|
112
|
+
max_file_size_bytes: int = 1_000_000 # larger files are skipped, not fatal
|
|
113
|
+
max_total_bytes: int = 100_000_000
|
|
114
|
+
max_repo_size_bytes: int = 500_000_000
|
|
115
|
+
clone_timeout_s: float = 180.0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class Workspace(BaseModel):
|
|
119
|
+
"""Files to analyse, independent of where they came from.
|
|
120
|
+
|
|
121
|
+
Use as a context manager (sync or async) so temporary clones are cleaned up.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
root: Path
|
|
125
|
+
source: str
|
|
126
|
+
files: list[FileInfo] = Field(default_factory=list)
|
|
127
|
+
skipped: list[SkippedFile] = Field(default_factory=list)
|
|
128
|
+
git: GitInfo | None = None
|
|
129
|
+
warnings: list[str] = Field(default_factory=list)
|
|
130
|
+
|
|
131
|
+
_cleanups: list[Callable[[], None]] = PrivateAttr(default_factory=list)
|
|
132
|
+
|
|
133
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
134
|
+
|
|
135
|
+
def abs_path(self, file: FileInfo | str) -> Path:
|
|
136
|
+
"""Absolute path of ``file``; refuses paths that escape the workspace root."""
|
|
137
|
+
rel = file.path if isinstance(file, FileInfo) else file
|
|
138
|
+
root = self.root.resolve()
|
|
139
|
+
full = (root / rel).resolve()
|
|
140
|
+
if full != root and root not in full.parents:
|
|
141
|
+
raise InvalidTargetError(f"Path escapes workspace root: {rel}")
|
|
142
|
+
return full
|
|
143
|
+
|
|
144
|
+
def read_text(self, file: FileInfo | str, max_bytes: int | None = None) -> str:
|
|
145
|
+
"""Read a file as UTF-8 (undecodable bytes replaced)."""
|
|
146
|
+
with self.abs_path(file).open("rb") as fh:
|
|
147
|
+
data = fh.read() if max_bytes is None else fh.read(max_bytes)
|
|
148
|
+
return data.decode("utf-8", errors="replace")
|
|
149
|
+
|
|
150
|
+
def exists(self, rel_path: str) -> bool:
|
|
151
|
+
"""Whether ``rel_path`` exists under the root, even inside filtered-out directories.
|
|
152
|
+
|
|
153
|
+
Symlinks are not followed, and paths that try to leave the root return ``False``.
|
|
154
|
+
"""
|
|
155
|
+
rel = PurePosixPath(rel_path.replace("\\", "/"))
|
|
156
|
+
if rel.is_absolute() or ".." in rel.parts:
|
|
157
|
+
return False
|
|
158
|
+
return os.path.lexists(self.root / rel)
|
|
159
|
+
|
|
160
|
+
def get_file(self, path: str) -> FileInfo | None:
|
|
161
|
+
return next((f for f in self.files if f.path == path), None)
|
|
162
|
+
|
|
163
|
+
def add_cleanup(self, fn: Callable[[], None]) -> None:
|
|
164
|
+
self._cleanups.append(fn)
|
|
165
|
+
|
|
166
|
+
def cleanup(self) -> None:
|
|
167
|
+
while self._cleanups:
|
|
168
|
+
fn = self._cleanups.pop()
|
|
169
|
+
try:
|
|
170
|
+
fn()
|
|
171
|
+
except Exception:
|
|
172
|
+
logger.warning("Workspace cleanup step failed", exc_info=True)
|
|
173
|
+
|
|
174
|
+
def __enter__(self) -> Workspace:
|
|
175
|
+
return self
|
|
176
|
+
|
|
177
|
+
def __exit__(
|
|
178
|
+
self,
|
|
179
|
+
exc_type: type[BaseException] | None,
|
|
180
|
+
exc: BaseException | None,
|
|
181
|
+
tb: TracebackType | None,
|
|
182
|
+
) -> None:
|
|
183
|
+
self.cleanup()
|
|
184
|
+
|
|
185
|
+
async def __aenter__(self) -> Workspace:
|
|
186
|
+
return self
|
|
187
|
+
|
|
188
|
+
async def __aexit__(
|
|
189
|
+
self,
|
|
190
|
+
exc_type: type[BaseException] | None,
|
|
191
|
+
exc: BaseException | None,
|
|
192
|
+
tb: TracebackType | None,
|
|
193
|
+
) -> None:
|
|
194
|
+
self.cleanup()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class Loader(ABC):
|
|
198
|
+
"""Turns a target (URL or path) into a :class:`Workspace`."""
|
|
199
|
+
|
|
200
|
+
@staticmethod
|
|
201
|
+
@abstractmethod
|
|
202
|
+
def can_handle(target: str) -> bool:
|
|
203
|
+
"""Whether this loader understands ``target``."""
|
|
204
|
+
|
|
205
|
+
@abstractmethod
|
|
206
|
+
async def load(
|
|
207
|
+
self,
|
|
208
|
+
target: str,
|
|
209
|
+
*,
|
|
210
|
+
paths: Sequence[str] | None = None,
|
|
211
|
+
branch: str | None = None,
|
|
212
|
+
) -> Workspace:
|
|
213
|
+
"""Load ``target``, optionally restricted to ``paths`` (relative to the root)."""
|