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.
@@ -0,0 +1,163 @@
1
+ """Load a local directory (or a single file) into a :class:`Workspace`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ from collections.abc import Sequence
8
+ from pathlib import Path, PurePosixPath
9
+
10
+ from margin_core.errors import InvalidTargetError, LimitExceededError
11
+ from margin_core.loaders.base import FileInfo, Loader, LoaderLimits, SkippedFile, Workspace
12
+ from margin_core.loaders.filters import (
13
+ HEAD_BYTES,
14
+ FilterConfig,
15
+ classify_content,
16
+ classify_path,
17
+ detect_language,
18
+ ignored_dir_reason,
19
+ )
20
+ from margin_core.loaders.git import detect_git
21
+
22
+
23
+ def _normalize_scopes(paths: Sequence[str] | None) -> list[str] | None:
24
+ if not paths:
25
+ return None
26
+ scopes: list[str] = []
27
+ for raw in paths:
28
+ p = PurePosixPath(raw.replace("\\", "/"))
29
+ if p.is_absolute() or ".." in p.parts:
30
+ raise InvalidTargetError(
31
+ f"Restricted paths must be relative and inside the root: {raw}"
32
+ )
33
+ text = str(p).strip("/")
34
+ scopes.append("" if text == "." else text)
35
+ return scopes
36
+
37
+
38
+ def _file_in_scope(rel: str, scopes: list[str] | None) -> bool:
39
+ if scopes is None:
40
+ return True
41
+ return any(s == "" or rel == s or rel.startswith(s + "/") for s in scopes)
42
+
43
+
44
+ def _dir_in_scope(rel: str, scopes: list[str] | None) -> bool:
45
+ """True if ``rel`` is inside a scope or is an ancestor of one (must descend)."""
46
+ if scopes is None:
47
+ return True
48
+ return any(
49
+ s == "" or rel == s or rel.startswith(s + "/") or s.startswith(rel + "/") for s in scopes
50
+ )
51
+
52
+
53
+ class LocalLoader(Loader):
54
+ """Walks a directory without following symlinks, applying filters and limits."""
55
+
56
+ def __init__(
57
+ self, limits: LoaderLimits | None = None, filters: FilterConfig | None = None
58
+ ) -> None:
59
+ self.limits = limits or LoaderLimits()
60
+ self.filters = filters or FilterConfig()
61
+
62
+ @staticmethod
63
+ def can_handle(target: str) -> bool:
64
+ return Path(target).expanduser().exists()
65
+
66
+ async def load(
67
+ self,
68
+ target: str,
69
+ *,
70
+ paths: Sequence[str] | None = None,
71
+ branch: str | None = None,
72
+ ) -> Workspace:
73
+ ws = await asyncio.to_thread(self.load_sync, target, paths=paths)
74
+ if branch:
75
+ ws.warnings.append("'branch' is ignored for local paths")
76
+ return ws
77
+
78
+ def load_sync(
79
+ self, target: str, *, paths: Sequence[str] | None = None, source: str | None = None
80
+ ) -> Workspace:
81
+ root = Path(target).expanduser()
82
+ if not root.exists():
83
+ raise InvalidTargetError(f"Path does not exist: {target}")
84
+ root = root.resolve()
85
+ scopes = _normalize_scopes(paths)
86
+ if root.is_file():
87
+ scopes = [root.name]
88
+ root = root.parent
89
+ history_scopes = [s for s in scopes if s] if scopes else None
90
+
91
+ files: list[FileInfo] = []
92
+ skipped: list[SkippedFile] = []
93
+ total_bytes = 0
94
+
95
+ for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
96
+ current = Path(dirpath)
97
+ rel_dir = current.relative_to(root).as_posix()
98
+ rel_dir = "" if rel_dir == "." else rel_dir
99
+
100
+ kept_dirs: list[str] = []
101
+ for d in sorted(dirnames):
102
+ rel = f"{rel_dir}/{d}" if rel_dir else d
103
+ if (current / d).is_symlink():
104
+ skipped.append(SkippedFile(path=rel + "/", reason="symlink"))
105
+ continue
106
+ reason = ignored_dir_reason(d, self.filters)
107
+ if reason:
108
+ skipped.append(SkippedFile(path=rel + "/", reason=reason))
109
+ continue
110
+ if _dir_in_scope(rel, scopes):
111
+ kept_dirs.append(d)
112
+ dirnames[:] = kept_dirs
113
+
114
+ for name in sorted(filenames):
115
+ rel = f"{rel_dir}/{name}" if rel_dir else name
116
+ if not _file_in_scope(rel, scopes):
117
+ continue
118
+ full = current / name
119
+ if full.is_symlink():
120
+ skipped.append(SkippedFile(path=rel, reason="symlink"))
121
+ continue
122
+ decision = classify_path(rel, self.filters)
123
+ if not decision.keep:
124
+ skipped.append(SkippedFile(path=rel, reason=decision.reason or "filtered"))
125
+ continue
126
+ size = full.stat().st_size
127
+ if size > self.limits.max_file_size_bytes:
128
+ skipped.append(SkippedFile(path=rel, reason="too_large"))
129
+ continue
130
+ with full.open("rb") as fh:
131
+ head = fh.read(HEAD_BYTES)
132
+ content = classify_content(rel, head, self.filters)
133
+ if not content.keep:
134
+ skipped.append(SkippedFile(path=rel, reason=content.reason or "filtered"))
135
+ continue
136
+
137
+ files.append(
138
+ FileInfo(
139
+ path=rel,
140
+ size=size,
141
+ language=detect_language(rel),
142
+ is_generated=decision.is_generated or content.is_generated,
143
+ is_vendored=decision.is_vendored,
144
+ )
145
+ )
146
+ total_bytes += size
147
+ if len(files) > self.limits.max_files:
148
+ raise LimitExceededError(
149
+ f"More than {self.limits.max_files} files after filtering; "
150
+ "restrict the analysis with 'paths'"
151
+ )
152
+ if total_bytes > self.limits.max_total_bytes:
153
+ raise LimitExceededError(
154
+ f"Workspace exceeds {self.limits.max_total_bytes} bytes after filtering"
155
+ )
156
+
157
+ return Workspace(
158
+ root=root,
159
+ source=source or str(Path(target).expanduser().resolve()),
160
+ files=files,
161
+ skipped=skipped,
162
+ git=detect_git(root, history_scopes),
163
+ )
margin_core/logging.py ADDED
@@ -0,0 +1,20 @@
1
+ """Logging helpers. All library loggers live under the ``margin`` namespace."""
2
+
3
+ import logging
4
+
5
+ LOGGER_NAME = "margin"
6
+
7
+
8
+ def get_logger(name: str | None = None) -> logging.Logger:
9
+ """Return a logger under the ``margin`` namespace."""
10
+ return logging.getLogger(f"{LOGGER_NAME}.{name}" if name else LOGGER_NAME)
11
+
12
+
13
+ def configure_logging(level: str | int = "INFO") -> None:
14
+ """Configure a simple stderr handler for the library namespace (idempotent)."""
15
+ logger = logging.getLogger(LOGGER_NAME)
16
+ logger.setLevel(level)
17
+ if not logger.handlers:
18
+ handler = logging.StreamHandler()
19
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
20
+ logger.addHandler(handler)
margin_core/models.py ADDED
@@ -0,0 +1,130 @@
1
+ """Standard Pydantic models shared by every agent.
2
+
3
+ A generic UI can render ``summary``, ``findings`` and ``evidence`` of any
4
+ :class:`AgentResult` without knowing anything about the agent that produced it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import UTC, datetime
10
+ from typing import Any, Literal
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+ ResultStatus = Literal["ok", "partial", "error"]
15
+
16
+
17
+ class _StrictModel(BaseModel):
18
+ model_config = ConfigDict(extra="forbid")
19
+
20
+
21
+ class Evidence(_StrictModel):
22
+ """A single, checkable piece of evidence supporting a finding."""
23
+
24
+ kind: str = Field(description='Evidence type, e.g. "file", "commit", "config", "metric".')
25
+ location: str | None = Field(
26
+ default=None, description='Where to look, e.g. "src/utils.py:10-42" or a commit SHA.'
27
+ )
28
+ detail: str = Field(description="Human-readable explanation.")
29
+ weight: float | None = Field(
30
+ default=None, description="Contribution to the score, if applicable."
31
+ )
32
+
33
+
34
+ class Finding(_StrictModel):
35
+ """A titled conclusion backed by evidence."""
36
+
37
+ title: str
38
+ severity_or_score: float | None = None
39
+ summary: str
40
+ evidence: list[Evidence] = Field(default_factory=list)
41
+
42
+
43
+ class TokenUsage(_StrictModel):
44
+ """Aggregated LLM usage and estimated cost."""
45
+
46
+ llm_calls: int = 0
47
+ input_tokens: int = 0
48
+ output_tokens: int = 0
49
+ cost_usd: float = 0.0
50
+
51
+ def __add__(self, other: TokenUsage) -> TokenUsage:
52
+ return TokenUsage(
53
+ llm_calls=self.llm_calls + other.llm_calls,
54
+ input_tokens=self.input_tokens + other.input_tokens,
55
+ output_tokens=self.output_tokens + other.output_tokens,
56
+ cost_usd=self.cost_usd + other.cost_usd,
57
+ )
58
+
59
+ def __sub__(self, other: TokenUsage) -> TokenUsage:
60
+ return TokenUsage(
61
+ llm_calls=self.llm_calls - other.llm_calls,
62
+ input_tokens=self.input_tokens - other.input_tokens,
63
+ output_tokens=self.output_tokens - other.output_tokens,
64
+ cost_usd=max(0.0, self.cost_usd - other.cost_usd),
65
+ )
66
+
67
+
68
+ class RunMetadata(_StrictModel):
69
+ """Execution metadata attached to every result."""
70
+
71
+ started_at: datetime | None = None
72
+ finished_at: datetime | None = None
73
+ duration_s: float | None = None
74
+ model: str | None = None
75
+ usage: TokenUsage = Field(default_factory=TokenUsage)
76
+ extra: dict[str, Any] = Field(default_factory=dict)
77
+
78
+
79
+ class AgentInput(_StrictModel):
80
+ """Base class for agent input models. Unknown fields are rejected."""
81
+
82
+
83
+ class AgentResult(_StrictModel):
84
+ """The standard result returned by every agent.
85
+
86
+ ``status`` semantics:
87
+
88
+ - ``ok``: everything requested was done. ``error`` is null.
89
+ - ``partial``: a usable result, but some requested work was skipped (a budget or time cap
90
+ was hit, some files were unreadable, an optional step was unavailable). Each skipped
91
+ part has an entry in ``warnings``. ``data`` is complete in shape but may hold fewer
92
+ items. ``error`` is null.
93
+ - ``error``: no usable result. ``data`` is empty and ``error`` holds the message.
94
+ """
95
+
96
+ agent_id: str
97
+ agent_version: str
98
+ status: ResultStatus
99
+ summary: str = Field(description="2-3 sentence human summary.")
100
+ data: dict[str, Any] = Field(
101
+ default_factory=dict, description="Agent-specific payload, validated by its OutputModel."
102
+ )
103
+ findings: list[Finding] = Field(default_factory=list)
104
+ warnings: list[str] = Field(default_factory=list)
105
+ error: str | None = Field(default=None, description="Error message when status is 'error'.")
106
+ metadata: RunMetadata = Field(default_factory=RunMetadata)
107
+
108
+
109
+ class ProgressEvent(_StrictModel):
110
+ """A progress update emitted during a run (consumed by CLI/UI)."""
111
+
112
+ stage: str
113
+ message: str = ""
114
+ fraction: float | None = Field(default=None, ge=0.0, le=1.0)
115
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
116
+
117
+
118
+ class AgentInfo(_StrictModel):
119
+ """Static description of an agent, including its JSON schemas."""
120
+
121
+ id: str
122
+ name: str
123
+ description: str
124
+ version: str
125
+ input_schema: dict[str, Any]
126
+ output_schema: dict[str, Any]
127
+ primary_input: str | None = Field(
128
+ default=None, description="Input field filled by a positional CLI argument."
129
+ )
130
+ uses_llm: bool = Field(default=False, description="Whether runs normally call a model.")
margin_core/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561
@@ -0,0 +1,111 @@
1
+ """Discover installed agents through the ``margin.agents`` entry-point group."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping
6
+ from importlib.metadata import EntryPoint, entry_points
7
+ from typing import Any
8
+
9
+ from margin_core.agent import BaseAgent
10
+ from margin_core.errors import AgentLoadError, AgentNotFoundError
11
+ from margin_core.llm.base import LLMClient
12
+ from margin_core.logging import get_logger
13
+ from margin_core.models import AgentInfo
14
+
15
+ ENTRY_POINT_GROUP = "margin.agents"
16
+
17
+ logger = get_logger("registry")
18
+
19
+
20
+ class AgentRegistry:
21
+ """Lazily discovers agents from entry points (or an explicit list, for tests).
22
+
23
+ Broken entry points never break discovery: they are recorded in :attr:`load_errors`.
24
+ """
25
+
26
+ def __init__(self, entry_points: Iterable[EntryPoint] | None = None) -> None:
27
+ self._entry_points = list(entry_points) if entry_points is not None else None
28
+ self._agents: dict[str, type[BaseAgent]] | None = None
29
+ self._manual: dict[str, type[BaseAgent]] = {}
30
+ self._errors: dict[str, str] = {}
31
+
32
+ def register(self, agent_cls: type[BaseAgent]) -> None:
33
+ """Register an agent class manually (takes precedence over entry points)."""
34
+ self._manual[agent_cls.id] = agent_cls
35
+
36
+ def refresh(self) -> None:
37
+ """Forget cached discovery results."""
38
+ self._agents = None
39
+ self._errors = {}
40
+
41
+ @property
42
+ def load_errors(self) -> dict[str, str]:
43
+ self._discover()
44
+ return dict(self._errors)
45
+
46
+ def _discover(self) -> dict[str, type[BaseAgent]]:
47
+ if self._agents is None:
48
+ eps = (
49
+ self._entry_points
50
+ if self._entry_points is not None
51
+ else list(entry_points(group=ENTRY_POINT_GROUP))
52
+ )
53
+ found: dict[str, type[BaseAgent]] = {}
54
+ for ep in eps:
55
+ try:
56
+ obj = ep.load()
57
+ except Exception as exc:
58
+ self._errors[ep.name] = f"Failed to import {ep.value}: {exc}"
59
+ logger.warning("Could not load agent entry point %s: %s", ep.name, exc)
60
+ continue
61
+ if not (isinstance(obj, type) and issubclass(obj, BaseAgent)):
62
+ self._errors[ep.name] = f"{ep.value} is not a BaseAgent subclass"
63
+ continue
64
+ if obj.id in found and found[obj.id] is not obj:
65
+ self._errors[ep.name] = f"Duplicate agent id {obj.id!r}"
66
+ continue
67
+ if obj.id != ep.name:
68
+ logger.warning("Entry point %r registers agent id %r", ep.name, obj.id)
69
+ found[obj.id] = obj
70
+ self._agents = found
71
+ return {**self._agents, **self._manual}
72
+
73
+ def get_agent_class(self, agent_id: str) -> type[BaseAgent]:
74
+ agents = self._discover()
75
+ if agent_id not in agents:
76
+ if agent_id in self._errors:
77
+ raise AgentLoadError(self._errors[agent_id])
78
+ available = ", ".join(sorted(agents)) or "none"
79
+ raise AgentNotFoundError(f"No agent {agent_id!r}. Available agents: {available}")
80
+ return agents[agent_id]
81
+
82
+ def create(
83
+ self,
84
+ agent_id: str,
85
+ *,
86
+ llm: LLMClient | None = None,
87
+ config: Mapping[str, Any] | None = None,
88
+ ) -> BaseAgent:
89
+ return self.get_agent_class(agent_id)(llm=llm, config=config)
90
+
91
+ def list_agents(self) -> list[AgentInfo]:
92
+ return [cls.info() for _, cls in sorted(self._discover().items())]
93
+
94
+ def ids(self) -> list[str]:
95
+ return sorted(self._discover())
96
+
97
+
98
+ _default_registry = AgentRegistry()
99
+
100
+
101
+ def default_registry() -> AgentRegistry:
102
+ """The process-wide registry backed by installed entry points."""
103
+ return _default_registry
104
+
105
+
106
+ def list_agents() -> list[AgentInfo]:
107
+ return _default_registry.list_agents()
108
+
109
+
110
+ def get_agent(agent_id: str) -> type[BaseAgent]:
111
+ return _default_registry.get_agent_class(agent_id)
@@ -0,0 +1,6 @@
1
+ """Report renderers for :class:`~margin_core.models.AgentResult`."""
2
+
3
+ from margin_core.reporting.json_report import to_json, write_json
4
+ from margin_core.reporting.markdown_report import to_markdown, write_markdown
5
+
6
+ __all__ = ["to_json", "to_markdown", "write_json", "write_markdown"]
@@ -0,0 +1,18 @@
1
+ """Render an :class:`AgentResult` as JSON."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from margin_core.models import AgentResult
8
+
9
+
10
+ def to_json(result: AgentResult, *, indent: int | None = 2) -> str:
11
+ return result.model_dump_json(indent=indent)
12
+
13
+
14
+ def write_json(result: AgentResult, path: str | Path, *, indent: int | None = 2) -> Path:
15
+ out = Path(path)
16
+ out.parent.mkdir(parents=True, exist_ok=True)
17
+ out.write_text(to_json(result, indent=indent) + "\n", encoding="utf-8")
18
+ return out
@@ -0,0 +1,84 @@
1
+ """Render an :class:`AgentResult` as Markdown (works for any agent)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from margin_core.models import AgentResult, Evidence
8
+
9
+ _STATUS_LABEL = {"ok": "ok", "partial": "partial", "error": "error"}
10
+
11
+
12
+ def _cell(text: object) -> str:
13
+ return str(text).replace("|", "\\|").replace("\n", " ")
14
+
15
+
16
+ def _evidence_line(ev: Evidence) -> str:
17
+ parts = [f"**{ev.kind}**"]
18
+ if ev.location:
19
+ parts.append(f"`{ev.location}`")
20
+ line = " ".join(parts) + f" - {ev.detail}"
21
+ if ev.weight is not None:
22
+ line += f" _(weight {ev.weight:+.2f})_"
23
+ return f"- {line}"
24
+
25
+
26
+ def to_markdown(result: AgentResult) -> str:
27
+ md: list[str] = [
28
+ f"# {result.agent_id} report",
29
+ "",
30
+ f"**Status:** {_STATUS_LABEL.get(result.status, result.status)} ",
31
+ f"**Agent version:** {result.agent_version}",
32
+ "",
33
+ "## Summary",
34
+ "",
35
+ result.summary,
36
+ "",
37
+ ]
38
+ if result.error:
39
+ md += ["## Error", "", "```", result.error, "```", ""]
40
+
41
+ if result.findings:
42
+ md += ["## Findings", ""]
43
+ for finding in result.findings:
44
+ title = finding.title
45
+ if finding.severity_or_score is not None:
46
+ title += f" ({finding.severity_or_score:.2f})"
47
+ md += [f"### {title}", "", finding.summary, ""]
48
+ if finding.evidence:
49
+ md += ["**Evidence**", ""]
50
+ md += [_evidence_line(ev) for ev in finding.evidence]
51
+ md.append("")
52
+
53
+ if result.warnings:
54
+ md += ["## Warnings", ""]
55
+ md += [f"- {w}" for w in result.warnings]
56
+ md.append("")
57
+
58
+ meta = result.metadata
59
+ rows: list[tuple[str, object]] = []
60
+ if meta.duration_s is not None:
61
+ rows.append(("Duration", f"{meta.duration_s:.2f}s"))
62
+ if meta.model:
63
+ rows.append(("Model", meta.model))
64
+ if meta.usage.llm_calls:
65
+ rows += [
66
+ ("LLM calls", meta.usage.llm_calls),
67
+ ("Tokens (in/out)", f"{meta.usage.input_tokens}/{meta.usage.output_tokens}"),
68
+ ("Estimated cost", f"${meta.usage.cost_usd:.4f}"),
69
+ ]
70
+ if meta.started_at:
71
+ rows.append(("Started", meta.started_at.isoformat(timespec="seconds")))
72
+ if rows:
73
+ md += ["## Run metadata", "", "| Field | Value |", "|---|---|"]
74
+ md += [f"| {_cell(k)} | {_cell(v)} |" for k, v in rows]
75
+ md.append("")
76
+
77
+ return "\n".join(md).rstrip() + "\n"
78
+
79
+
80
+ def write_markdown(result: AgentResult, path: str | Path) -> Path:
81
+ out = Path(path)
82
+ out.parent.mkdir(parents=True, exist_ok=True)
83
+ out.write_text(to_markdown(result), encoding="utf-8")
84
+ return out
margin_core/runner.py ADDED
@@ -0,0 +1,27 @@
1
+ """One-call convenience API for running an agent from Python."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ from pydantic import BaseModel
9
+
10
+ from margin_core.agent import RunContext
11
+ from margin_core.llm.base import LLMClient
12
+ from margin_core.models import AgentResult
13
+ from margin_core.registry import AgentRegistry, default_registry
14
+
15
+
16
+ async def run_agent(
17
+ agent_id: str,
18
+ input: BaseModel | Mapping[str, Any],
19
+ *,
20
+ llm: LLMClient | None = None,
21
+ config: Mapping[str, Any] | None = None,
22
+ ctx: RunContext | None = None,
23
+ registry: AgentRegistry | None = None,
24
+ ) -> AgentResult:
25
+ """Look up ``agent_id`` in the registry and execute it with ``input``."""
26
+ agent = (registry or default_registry()).create(agent_id, llm=llm, config=config)
27
+ return await agent.execute(input, ctx)
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.5
2
+ Name: margin-core
3
+ Version: 0.1.0
4
+ Summary: The shared core of margin: the agent contract, results with evidence, model clients and code loaders.
5
+ Project-URL: Homepage, https://github.com/Waddah0-0/margin
6
+ Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/packages/core
7
+ Project-URL: Issues, https://github.com/Waddah0-0/margin/issues
8
+ Project-URL: Changelog, https://github.com/Waddah0-0/margin/blob/main/packages/core/CHANGELOG.md
9
+ Author: Waddah Ali
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,evidence,framework,llm
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: httpx>=0.27.0
23
+ Requires-Dist: pydantic-settings>=2.2.0
24
+ Requires-Dist: pydantic>=2.7.0
25
+ Requires-Dist: python-dotenv>=1.0.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # margin-core
29
+
30
+ The shared core of [margin](https://github.com/Waddah0-0/margin), a collection of small AI
31
+ agents that answer with evidence. You need this package to write an agent. To use one,
32
+ install the agent (for example `margin-ai-code-detector`) together with `margin-cli` or
33
+ `margin-api`.
34
+
35
+ ```bash
36
+ pip install margin-core
37
+ ```
38
+
39
+ ## What's in it
40
+
41
+ An agent is a class with an input model, an output model and an async `run` method. You call
42
+ it through `execute()`, which validates the input, times the run, counts model usage, and
43
+ turns a crash into an error result instead of an exception. Every agent returns the same
44
+ `AgentResult`: a summary, findings, the evidence for each finding, warnings, and whatever
45
+ typed data the agent wants to add.
46
+
47
+ Agents register under the `margin.agents` entry point, so installing one is all it takes for
48
+ the CLI, the API and the web UI to find it.
49
+
50
+ The model client gives you one interface to local OpenAI-compatible servers (Ollama, LM
51
+ Studio, llama.cpp, vLLM), Anthropic and OpenAI. It retries, tracks tokens and cost, and stops
52
+ at a spending limit you set. `MockLLM` returns canned answers, which keeps tests offline.
53
+
54
+ The loaders turn a local folder or a GitHub repository into a `Workspace`: the files worth
55
+ reading, the files that were skipped and why, and the git history. A repository is
56
+ size-checked before it is cloned, and nothing in it is ever run.
57
+
58
+ ## A minimal agent
59
+
60
+ ```python
61
+ from pydantic import BaseModel
62
+ from margin_core import AgentInput, AgentResult, BaseAgent, RunContext
63
+
64
+
65
+ class GreetInput(AgentInput):
66
+ name: str
67
+
68
+
69
+ class GreetOutput(BaseModel):
70
+ greeting: str
71
+
72
+
73
+ class Greeter(BaseAgent):
74
+ id = "greeter"
75
+ name = "Greeter"
76
+ description = "Says hello."
77
+ version = "0.1.0"
78
+ InputModel = GreetInput
79
+ OutputModel = GreetOutput
80
+
81
+ async def run(self, input: GreetInput, ctx: RunContext) -> AgentResult:
82
+ greeting = f"Hello, {input.name}!"
83
+ return self.make_result(summary=greeting, output=GreetOutput(greeting=greeting))
84
+ ```
85
+
86
+ Register it in your package's `pyproject.toml`:
87
+
88
+ ```toml
89
+ [project.entry-points."margin.agents"]
90
+ greeter = "my_package.agent:Greeter"
91
+ ```
92
+
93
+ The full guide is
94
+ [docs/writing-an-agent.md](https://github.com/Waddah0-0/margin/blob/main/docs/writing-an-agent.md).
95
+
96
+ ## Settings
97
+
98
+ Model settings are read from environment variables first, then from settings saved in the
99
+ web UI, then from a `.env` file. The ones you are likely to need are `DEFAULT_LLM_PROVIDER`
100
+ (`local`, `anthropic` or `openai`), `LOCAL_LLM_BASE_URL`, `LOCAL_LLM_MODEL`,
101
+ `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and `MAX_COST_USD`.
102
+ [.env.example](https://github.com/Waddah0-0/margin/blob/main/.env.example) lists them all.
103
+
104
+ ## License
105
+
106
+ MIT