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,68 @@
1
+ """Core foundation library for margin.
2
+
3
+ Public API::
4
+
5
+ from margin_core import BaseAgent, RunContext, AgentResult, Finding, Evidence
6
+ from margin_core import run_agent, list_agents, get_agent
7
+ """
8
+
9
+ from margin_core.agent import BaseAgent, CancellationToken, ProgressCallback, RunContext
10
+ from margin_core.errors import (
11
+ AgentLoadError,
12
+ AgentNotFoundError,
13
+ AgentsLibError,
14
+ BudgetExceededError,
15
+ InputValidationError,
16
+ InvalidTargetError,
17
+ LimitExceededError,
18
+ LLMError,
19
+ LoaderError,
20
+ RunCancelledError,
21
+ TransientLLMError,
22
+ )
23
+ from margin_core.models import (
24
+ AgentInfo,
25
+ AgentInput,
26
+ AgentResult,
27
+ Evidence,
28
+ Finding,
29
+ ProgressEvent,
30
+ RunMetadata,
31
+ TokenUsage,
32
+ )
33
+ from margin_core.registry import AgentRegistry, default_registry, get_agent, list_agents
34
+ from margin_core.runner import run_agent
35
+
36
+ __version__ = "0.1.0"
37
+
38
+ __all__ = [
39
+ "AgentInfo",
40
+ "AgentInput",
41
+ "AgentLoadError",
42
+ "AgentNotFoundError",
43
+ "AgentRegistry",
44
+ "AgentResult",
45
+ "AgentsLibError",
46
+ "BaseAgent",
47
+ "BudgetExceededError",
48
+ "CancellationToken",
49
+ "Evidence",
50
+ "Finding",
51
+ "InputValidationError",
52
+ "InvalidTargetError",
53
+ "LLMError",
54
+ "LimitExceededError",
55
+ "LoaderError",
56
+ "ProgressCallback",
57
+ "ProgressEvent",
58
+ "RunCancelledError",
59
+ "RunContext",
60
+ "RunMetadata",
61
+ "TokenUsage",
62
+ "TransientLLMError",
63
+ "__version__",
64
+ "default_registry",
65
+ "get_agent",
66
+ "list_agents",
67
+ "run_agent",
68
+ ]
margin_core/_fs.py ADDED
@@ -0,0 +1,37 @@
1
+ """Filesystem helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import stat
8
+ import sys
9
+ from collections.abc import Callable
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+
14
+ def _make_writable_and_retry(func: Callable[..., Any], path: str, _exc: object) -> None:
15
+ os.chmod(path, stat.S_IWRITE)
16
+ func(path)
17
+
18
+
19
+ def force_rmtree(path: Path) -> None:
20
+ """Remove a directory tree, including read-only files (e.g. git objects on Windows)."""
21
+ if not path.exists():
22
+ return
23
+ if sys.version_info >= (3, 12):
24
+ shutil.rmtree(path, onexc=_make_writable_and_retry)
25
+ else:
26
+ shutil.rmtree(path, onerror=_make_writable_and_retry)
27
+
28
+
29
+ def directory_size(path: Path) -> int:
30
+ """Total size in bytes of regular files under ``path`` (symlinks not followed)."""
31
+ total = 0
32
+ for dirpath, _dirnames, filenames in os.walk(path, followlinks=False):
33
+ for name in filenames:
34
+ full = os.path.join(dirpath, name)
35
+ if not os.path.islink(full):
36
+ total += os.path.getsize(full)
37
+ return total
margin_core/agent.py ADDED
@@ -0,0 +1,255 @@
1
+ """The agent contract every agent implements."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from abc import ABC, abstractmethod
8
+ from collections.abc import Callable, Mapping, Sequence
9
+ from datetime import UTC, datetime
10
+ from typing import TYPE_CHECKING, Any, ClassVar
11
+
12
+ from pydantic import BaseModel, ValidationError
13
+
14
+ from margin_core.errors import InputValidationError, LLMError, RunCancelledError
15
+ from margin_core.llm.base import LLMClient
16
+ from margin_core.logging import get_logger
17
+ from margin_core.models import (
18
+ AgentInfo,
19
+ AgentResult,
20
+ Finding,
21
+ ProgressEvent,
22
+ ResultStatus,
23
+ TokenUsage,
24
+ )
25
+
26
+ if TYPE_CHECKING:
27
+ from margin_core.loaders.base import LoaderLimits, Workspace
28
+ from margin_core.loaders.filters import FilterConfig
29
+
30
+ ProgressCallback = Callable[[ProgressEvent], None]
31
+
32
+ __all__ = ["BaseAgent", "CancellationToken", "ProgressCallback", "RunContext"]
33
+
34
+
35
+ class CancellationToken:
36
+ """Cooperative cancellation flag shared between a caller and a running agent."""
37
+
38
+ def __init__(self) -> None:
39
+ self._cancelled = False
40
+
41
+ def cancel(self) -> None:
42
+ self._cancelled = True
43
+
44
+ @property
45
+ def cancelled(self) -> bool:
46
+ return self._cancelled
47
+
48
+
49
+ class RunContext:
50
+ """Per-run services handed to :meth:`BaseAgent.run`.
51
+
52
+ During :meth:`BaseAgent.execute`, ``llm`` is a per-run :class:`LLMSession` opened from the
53
+ configured client, limited by ``max_cost_usd``. Anything added with :meth:`warn` ends up in
54
+ the result's ``warnings``.
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ *,
60
+ llm: LLMClient | None = None,
61
+ progress: ProgressCallback | None = None,
62
+ cancel_token: CancellationToken | None = None,
63
+ logger: logging.Logger | None = None,
64
+ max_cost_usd: float | None = None,
65
+ ) -> None:
66
+ self.llm = llm
67
+ self.progress = progress
68
+ self.cancel_token = cancel_token or CancellationToken()
69
+ self.logger = logger or get_logger("run")
70
+ self.max_cost_usd = max_cost_usd
71
+ self.warnings: list[str] = []
72
+
73
+ def warn(self, message: str) -> None:
74
+ """Record a warning for the result (duplicates are ignored)."""
75
+ self.logger.warning(message)
76
+ if message not in self.warnings:
77
+ self.warnings.append(message)
78
+
79
+ def report_progress(self, stage: str, message: str = "", fraction: float | None = None) -> None:
80
+ """Emit a progress event to the caller (CLI spinner, API SSE stream, ...)."""
81
+ self.logger.debug("progress stage=%s fraction=%s %s", stage, fraction, message)
82
+ if self.progress is not None:
83
+ self.progress(ProgressEvent(stage=stage, message=message, fraction=fraction))
84
+
85
+ async def load_workspace(
86
+ self,
87
+ target: str,
88
+ *,
89
+ paths: Sequence[str] | None = None,
90
+ branch: str | None = None,
91
+ limits: LoaderLimits | None = None,
92
+ filters: FilterConfig | None = None,
93
+ ) -> Workspace:
94
+ """Load ``target`` (GitHub URL or local path), reporting progress and warnings.
95
+
96
+ Use the returned workspace with ``async with`` so temporary clones are removed.
97
+ """
98
+ from margin_core.loaders import load_workspace
99
+
100
+ self.report_progress("load", f"Loading {target}")
101
+ workspace = await load_workspace(
102
+ target, paths=paths, branch=branch, limits=limits, filters=filters
103
+ )
104
+ for warning in workspace.warnings:
105
+ self.warn(warning)
106
+ return workspace
107
+
108
+ def check_cancelled(self) -> None:
109
+ """Raise :class:`RunCancelledError` if the run was cancelled. Call between steps."""
110
+ if self.cancel_token.cancelled:
111
+ raise RunCancelledError("Run was cancelled")
112
+
113
+ def require_llm(self) -> LLMClient:
114
+ """Return the LLM client or fail with a clear error if none was configured."""
115
+ if self.llm is None:
116
+ raise LLMError("This agent needs an LLM client, but none was configured")
117
+ return self.llm
118
+
119
+
120
+ class BaseAgent(ABC):
121
+ """Base class for all agents.
122
+
123
+ Subclasses set the class attributes and implement :meth:`run`. Callers normally use
124
+ :meth:`execute`, which validates input, times the run, records LLM usage, and turns
125
+ unexpected exceptions into an ``error`` result.
126
+ """
127
+
128
+ id: ClassVar[str]
129
+ name: ClassVar[str]
130
+ description: ClassVar[str]
131
+ version: ClassVar[str]
132
+ InputModel: ClassVar[type[BaseModel]]
133
+ OutputModel: ClassVar[type[BaseModel]]
134
+ primary_input: ClassVar[str | None] = None
135
+ uses_llm: ClassVar[bool] = False
136
+ """Whether runs normally call a model (the API queues these separately: one GPU)."""
137
+ """Input field filled by the CLI's positional argument (and shown first in forms)."""
138
+
139
+ def __init__(self, llm: LLMClient | None = None, config: Mapping[str, Any] | None = None):
140
+ self.llm = llm
141
+ self.config: dict[str, Any] = dict(config or {})
142
+
143
+ @classmethod
144
+ def info(cls) -> AgentInfo:
145
+ return AgentInfo(
146
+ id=cls.id,
147
+ name=cls.name,
148
+ description=cls.description,
149
+ version=cls.version,
150
+ input_schema=cls.InputModel.model_json_schema(),
151
+ output_schema=cls.OutputModel.model_json_schema(),
152
+ primary_input=cls.primary_input,
153
+ uses_llm=cls.uses_llm,
154
+ )
155
+
156
+ @classmethod
157
+ def parse_input(cls, raw: BaseModel | Mapping[str, Any]) -> BaseModel:
158
+ """Validate ``raw`` against :attr:`InputModel`."""
159
+ if isinstance(raw, cls.InputModel):
160
+ return raw
161
+ data = raw.model_dump() if isinstance(raw, BaseModel) else dict(raw)
162
+ try:
163
+ return cls.InputModel.model_validate(data)
164
+ except ValidationError as exc:
165
+ raise InputValidationError(f"Invalid input for agent {cls.id!r}:\n{exc}") from exc
166
+
167
+ @abstractmethod
168
+ async def run(self, input: Any, ctx: RunContext) -> AgentResult:
169
+ """Do the work. ``input`` is an instance of :attr:`InputModel`."""
170
+
171
+ def make_result(
172
+ self,
173
+ *,
174
+ summary: str,
175
+ output: BaseModel | None = None,
176
+ findings: Sequence[Finding] = (),
177
+ warnings: Sequence[str] = (),
178
+ status: ResultStatus = "ok",
179
+ ) -> AgentResult:
180
+ """Build an :class:`AgentResult`, validating ``output`` against :attr:`OutputModel`."""
181
+ data: dict[str, Any] = {}
182
+ if output is not None:
183
+ validated = (
184
+ output
185
+ if isinstance(output, self.OutputModel)
186
+ else self.OutputModel.model_validate(output.model_dump())
187
+ )
188
+ data = validated.model_dump(mode="json")
189
+ return AgentResult(
190
+ agent_id=self.id,
191
+ agent_version=self.version,
192
+ status=status,
193
+ summary=summary,
194
+ data=data,
195
+ findings=list(findings),
196
+ warnings=list(warnings),
197
+ )
198
+
199
+ def _error_result(self, message: str) -> AgentResult:
200
+ return AgentResult(
201
+ agent_id=self.id,
202
+ agent_version=self.version,
203
+ status="error",
204
+ summary=f"Run failed: {message}",
205
+ error=message,
206
+ )
207
+
208
+ async def execute(
209
+ self, raw_input: BaseModel | Mapping[str, Any], ctx: RunContext | None = None
210
+ ) -> AgentResult:
211
+ """Validate input, run the agent, and attach run metadata.
212
+
213
+ Raises :class:`InputValidationError` for bad input; any other failure is returned
214
+ as a result with ``status="error"`` so callers always get a structured result.
215
+ """
216
+ parsed = self.parse_input(raw_input)
217
+ ctx = ctx or RunContext()
218
+ caller_llm = ctx.llm
219
+ client = caller_llm if caller_llm is not None else self.llm
220
+ session = client.session(max_cost_usd=ctx.max_cost_usd) if client is not None else None
221
+ ctx.llm = session
222
+ started_at = datetime.now(UTC)
223
+ t0 = time.perf_counter()
224
+ try:
225
+ ctx.check_cancelled()
226
+ result = await self.run(parsed, ctx)
227
+ except RunCancelledError:
228
+ result = self._error_result("Run was cancelled")
229
+ except Exception as exc:
230
+ ctx.logger.exception("Agent %s failed", self.id)
231
+ result = self._error_result(f"{type(exc).__name__}: {exc}")
232
+ finally:
233
+ ctx.llm = caller_llm
234
+
235
+ used_model = session.model if session is not None and session.usage.llm_calls else None
236
+ warnings = _merge_unique(result.warnings, ctx.warnings, session.warnings if session else [])
237
+ metadata = result.metadata.model_copy(
238
+ update={
239
+ "started_at": started_at,
240
+ "finished_at": datetime.now(UTC),
241
+ "duration_s": round(time.perf_counter() - t0, 4),
242
+ "model": result.metadata.model or used_model,
243
+ "usage": session.usage if session else TokenUsage(),
244
+ }
245
+ )
246
+ return result.model_copy(update={"metadata": metadata, "warnings": warnings})
247
+
248
+
249
+ def _merge_unique(*groups: Sequence[str]) -> list[str]:
250
+ merged: list[str] = []
251
+ for group in groups:
252
+ for item in group:
253
+ if item not in merged:
254
+ merged.append(item)
255
+ return merged
margin_core/config.py ADDED
@@ -0,0 +1,184 @@
1
+ """Settings, from four places (highest priority first):
2
+
3
+ 1. environment variables (for deployments and CI);
4
+ 2. settings saved by the user, e.g. from the web UI, in ``settings.json`` in the user's
5
+ config folder (``MARGIN_CONFIG_FILE`` overrides the path; empty turns it off);
6
+ 3. the ``.env`` file (``MARGIN_ENV_FILE`` chooses it; empty reads no file);
7
+ 4. the defaults below.
8
+
9
+ Empty values are ignored, so ``ANTHROPIC_API_KEY=`` in a ``.env`` does not count as a key.
10
+ Secrets never have defaults, and saved secrets are never sent back to a browser.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+ from typing import Any, Literal
21
+
22
+ from dotenv import dotenv_values
23
+ from pydantic import SecretStr
24
+ from pydantic.fields import FieldInfo
25
+ from pydantic_settings import (
26
+ BaseSettings,
27
+ PydanticBaseSettingsSource,
28
+ SettingsConfigDict,
29
+ )
30
+
31
+ ENV_FILE_VAR = "MARGIN_ENV_FILE"
32
+ CONFIG_FILE_VAR = "MARGIN_CONFIG_FILE"
33
+
34
+ # What the user may save (the rest is configured by environment or .env only).
35
+ SAVEABLE = frozenset({
36
+ "default_llm_provider",
37
+ "local_llm_base_url", "local_llm_api_key", "local_llm_model",
38
+ "anthropic_api_key", "anthropic_model",
39
+ "openai_api_key", "openai_model",
40
+ "max_cost_usd",
41
+ }) # fmt: skip
42
+
43
+ Source = Literal["environment", "saved", "env_file", "default"]
44
+
45
+
46
+ def user_config_path() -> Path | None:
47
+ """Where saved settings live, or None when saving is turned off."""
48
+ override = os.environ.get(CONFIG_FILE_VAR)
49
+ if override is not None:
50
+ return Path(override) if override else None
51
+ if sys.platform == "win32":
52
+ base = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
53
+ elif sys.platform == "darwin":
54
+ base = Path.home() / "Library" / "Application Support"
55
+ else:
56
+ base = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
57
+ return base / "margin" / "settings.json"
58
+
59
+
60
+ def load_user_config() -> dict[str, Any]:
61
+ """Saved settings; an unreadable or malformed file counts as empty."""
62
+ path = user_config_path()
63
+ if path is None or not path.is_file():
64
+ return {}
65
+ try:
66
+ data = json.loads(path.read_text(encoding="utf-8"))
67
+ except (OSError, ValueError):
68
+ return {}
69
+ if not isinstance(data, dict):
70
+ return {}
71
+ return {k: v for k, v in data.items() if k in SAVEABLE and v not in (None, "")}
72
+
73
+
74
+ def save_user_config(updates: dict[str, Any]) -> Path:
75
+ """Merge ``updates`` into the saved settings. ``None`` or ``""`` removes a value.
76
+
77
+ The file is written atomically and, on POSIX systems, readable by the user only.
78
+ """
79
+ path = user_config_path()
80
+ if path is None:
81
+ raise RuntimeError(f"Saving settings is turned off ({CONFIG_FILE_VAR} is empty)")
82
+ unknown = set(updates) - SAVEABLE
83
+ if unknown:
84
+ raise ValueError(f"These settings cannot be saved: {sorted(unknown)}")
85
+ data = load_user_config()
86
+ for key, value in updates.items():
87
+ if value in (None, ""):
88
+ data.pop(key, None)
89
+ else:
90
+ data[key] = value
91
+ path.parent.mkdir(parents=True, exist_ok=True)
92
+ fd, tmp = tempfile.mkstemp(prefix=".settings-", dir=path.parent)
93
+ try:
94
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
95
+ json.dump(data, fh, indent=2, sort_keys=True)
96
+ if sys.platform != "win32":
97
+ os.chmod(tmp, 0o600)
98
+ os.replace(tmp, path)
99
+ except BaseException:
100
+ Path(tmp).unlink(missing_ok=True)
101
+ raise
102
+ return path
103
+
104
+
105
+ class _SavedSettings(PydanticBaseSettingsSource):
106
+ """The user's saved settings, as a pydantic-settings source."""
107
+
108
+ def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
109
+ return None, field_name, False # unused: __call__ returns everything at once
110
+
111
+ def __call__(self) -> dict[str, Any]:
112
+ return load_user_config()
113
+
114
+
115
+ class Settings(BaseSettings):
116
+ """Global settings for margin."""
117
+
118
+ model_config = SettingsConfigDict(
119
+ env_file=".env", env_file_encoding="utf-8", extra="ignore", env_ignore_empty=True
120
+ )
121
+
122
+ anthropic_api_key: SecretStr | None = None
123
+ openai_api_key: SecretStr | None = None
124
+ github_token: SecretStr | None = None
125
+
126
+ local_llm_base_url: str = "http://localhost:11434"
127
+ local_llm_api_key: SecretStr | None = None
128
+ local_llm_reasoning_effort: str = "none" # empty: don't send the field
129
+
130
+ default_llm_provider: str = "local"
131
+ default_llm_model: str | None = None # applies to the default provider only
132
+ # the model to use with each provider (empty: the provider's default)
133
+ local_llm_model: str | None = None
134
+ anthropic_model: str | None = None
135
+ openai_model: str | None = None
136
+
137
+ max_cost_usd: float = 1.0
138
+ log_level: str = "INFO"
139
+
140
+ @classmethod
141
+ def settings_customise_sources(
142
+ cls,
143
+ settings_cls: type[BaseSettings],
144
+ init_settings: PydanticBaseSettingsSource,
145
+ env_settings: PydanticBaseSettingsSource,
146
+ dotenv_settings: PydanticBaseSettingsSource,
147
+ file_secret_settings: PydanticBaseSettingsSource,
148
+ ) -> tuple[PydanticBaseSettingsSource, ...]:
149
+ return (
150
+ init_settings,
151
+ env_settings,
152
+ _SavedSettings(settings_cls),
153
+ dotenv_settings,
154
+ file_secret_settings,
155
+ )
156
+
157
+
158
+ def _env_file() -> str | None:
159
+ return os.environ.get(ENV_FILE_VAR, ".env") or None
160
+
161
+
162
+ def get_settings() -> Settings:
163
+ """Load settings fresh from all four places."""
164
+ return Settings(_env_file=_env_file()) # type: ignore[call-arg]
165
+
166
+
167
+ def setting_sources(fields: frozenset[str] = SAVEABLE) -> dict[str, Source]:
168
+ """Where each setting's current value comes from, so a UI can explain it."""
169
+ saved = load_user_config()
170
+ env_file = _env_file()
171
+ from_file: dict[str, str | None] = {}
172
+ if env_file and Path(env_file).is_file():
173
+ from_file = {k.lower(): v for k, v in dotenv_values(env_file).items()}
174
+ sources: dict[str, Source] = {}
175
+ for name in fields:
176
+ if os.environ.get(name.upper()):
177
+ sources[name] = "environment"
178
+ elif name in saved:
179
+ sources[name] = "saved"
180
+ elif from_file.get(name):
181
+ sources[name] = "env_file"
182
+ else:
183
+ sources[name] = "default"
184
+ return sources
margin_core/errors.py ADDED
@@ -0,0 +1,49 @@
1
+ """Exception hierarchy for margin.
2
+
3
+ Every error raised by ``margin_core`` derives from :class:`AgentsLibError`, so callers
4
+ (CLI, API) can catch one type and render a readable message.
5
+ """
6
+
7
+
8
+ class AgentsLibError(Exception):
9
+ """Base class for all margin errors."""
10
+
11
+
12
+ class AgentNotFoundError(AgentsLibError):
13
+ """No agent is registered under the requested id."""
14
+
15
+
16
+ class AgentLoadError(AgentsLibError):
17
+ """An agent entry point exists but could not be loaded."""
18
+
19
+
20
+ class InputValidationError(AgentsLibError):
21
+ """The input does not match the agent's ``InputModel``."""
22
+
23
+
24
+ class RunCancelledError(AgentsLibError):
25
+ """The run was cancelled through its cancellation token."""
26
+
27
+
28
+ class LoaderError(AgentsLibError):
29
+ """Base class for errors raised while loading a workspace."""
30
+
31
+
32
+ class InvalidTargetError(LoaderError):
33
+ """The target (URL or path) is malformed, disallowed, or does not exist."""
34
+
35
+
36
+ class LimitExceededError(LoaderError):
37
+ """A configured safety limit (size, file count, timeout) was exceeded."""
38
+
39
+
40
+ class LLMError(AgentsLibError):
41
+ """Base class for LLM client errors."""
42
+
43
+
44
+ class TransientLLMError(LLMError):
45
+ """A retryable LLM error (rate limit, 5xx, timeout, network)."""
46
+
47
+
48
+ class BudgetExceededError(LLMError):
49
+ """The run's cost budget would be exceeded by another LLM call."""
margin_core/inputs.py ADDED
@@ -0,0 +1,71 @@
1
+ """Turn command-line style input into an agent's input mapping.
2
+
3
+ Shared by the CLI and the API so both bind input the same way:
4
+
5
+ - the positional value fills the agent's ``primary_input`` field;
6
+ - ``key=value`` assignments fill any field. Values are parsed as JSON when they are valid
7
+ JSON (``3``, ``true``, ``["a"]``), except for string fields, which always take the raw text;
8
+ - a base mapping (e.g. loaded from a JSON file) supplies defaults that assignments override.
9
+
10
+ Validation against ``InputModel`` still happens in :meth:`BaseAgent.parse_input`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from collections.abc import Mapping, Sequence
17
+ from typing import Any
18
+
19
+ from margin_core.agent import BaseAgent
20
+ from margin_core.errors import InputValidationError
21
+
22
+
23
+ def _wants_raw_string(agent_cls: type[BaseAgent], key: str) -> bool:
24
+ prop = agent_cls.InputModel.model_json_schema().get("properties", {}).get(key, {})
25
+ if prop.get("type") == "string":
26
+ return True
27
+ types = {option.get("type") for option in prop.get("anyOf", [])}
28
+ return bool(types) and types <= {"string", "null"}
29
+
30
+
31
+ def parse_assignment(agent_cls: type[BaseAgent], assignment: str) -> tuple[str, Any]:
32
+ """Parse one ``key=value`` assignment for ``agent_cls``."""
33
+ key, sep, raw = assignment.partition("=")
34
+ key = key.strip()
35
+ if not sep or not key:
36
+ raise InputValidationError(f"Expected key=value, got {assignment!r}")
37
+ if _wants_raw_string(agent_cls, key):
38
+ return key, raw
39
+ try:
40
+ return key, json.loads(raw)
41
+ except json.JSONDecodeError:
42
+ return key, raw
43
+
44
+
45
+ def bind_input(
46
+ agent_cls: type[BaseAgent],
47
+ *,
48
+ positional: str | None = None,
49
+ assignments: Sequence[str] = (),
50
+ base: Mapping[str, Any] | None = None,
51
+ ) -> dict[str, Any]:
52
+ """Build the raw input mapping for ``agent_cls`` (not yet validated)."""
53
+ data: dict[str, Any] = dict(base or {})
54
+ assigned: set[str] = set()
55
+ for assignment in assignments:
56
+ key, value = parse_assignment(agent_cls, assignment)
57
+ data[key] = value
58
+ assigned.add(key)
59
+
60
+ if positional is not None:
61
+ field = agent_cls.primary_input
62
+ if field is None:
63
+ raise InputValidationError(
64
+ f"Agent {agent_cls.id!r} does not take a positional input; use key=value instead"
65
+ )
66
+ if field in assigned:
67
+ raise InputValidationError(
68
+ f"{field!r} was given both as the positional input and as {field}=..."
69
+ )
70
+ data[field] = positional
71
+ return data
@@ -0,0 +1,30 @@
1
+ """LLM abstraction: one interface, local and hosted providers, plus a deterministic mock."""
2
+
3
+ from margin_core.llm.base import (
4
+ LLMClient,
5
+ LLMClientOptions,
6
+ LLMResponse,
7
+ LLMSession,
8
+ Message,
9
+ extract_json,
10
+ )
11
+ from margin_core.llm.factory import DEFAULT_MODELS, create_llm
12
+ from margin_core.llm.local import LocalLLM
13
+ from margin_core.llm.mock import MockCall, MockLLM
14
+ from margin_core.llm.pricing import ModelPricing, lookup_pricing
15
+
16
+ __all__ = [
17
+ "DEFAULT_MODELS",
18
+ "LLMClient",
19
+ "LLMClientOptions",
20
+ "LLMResponse",
21
+ "LLMSession",
22
+ "LocalLLM",
23
+ "Message",
24
+ "MockCall",
25
+ "MockLLM",
26
+ "ModelPricing",
27
+ "create_llm",
28
+ "extract_json",
29
+ "lookup_pricing",
30
+ ]