margin-cli 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_cli/__init__.py +3 -0
- margin_cli/execution.py +98 -0
- margin_cli/main.py +279 -0
- margin_cli/py.typed +1 -0
- margin_cli/render.py +74 -0
- margin_cli-0.1.0.dist-info/METADATA +102 -0
- margin_cli-0.1.0.dist-info/RECORD +10 -0
- margin_cli-0.1.0.dist-info/WHEEL +4 -0
- margin_cli-0.1.0.dist-info/entry_points.txt +2 -0
- margin_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
margin_cli/__init__.py
ADDED
margin_cli/execution.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Running an agent from the CLI: LLM setup, progress display and Ctrl+C handling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from margin_core import AgentResult, BaseAgent, ProgressEvent, RunContext
|
|
10
|
+
from margin_core.config import Settings
|
|
11
|
+
from margin_core.errors import LLMError
|
|
12
|
+
from margin_core.llm import LLMClient, create_llm
|
|
13
|
+
from pydantic import BaseModel
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
|
|
16
|
+
CANCEL_GRACE_S = 5.0
|
|
17
|
+
"""How long a cancelled agent gets to stop on its own before its task is cancelled."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ExplicitLLMError(Exception):
|
|
21
|
+
"""The user asked for a specific provider or model, and it cannot be set up."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def make_llm(
|
|
25
|
+
provider: str | None, model: str | None, max_cost_usd: float, settings: Settings
|
|
26
|
+
) -> LLMClient | None:
|
|
27
|
+
"""Create the LLM client for a run.
|
|
28
|
+
|
|
29
|
+
Creating a client never contacts the server, so the default (local) client is always
|
|
30
|
+
created and only used if the agent asks for it. If the default provider cannot be set
|
|
31
|
+
up (e.g. a hosted provider without an API key), the run continues without an LLM and
|
|
32
|
+
agents that need one fail with a clear error. If the user chose ``--provider`` or
|
|
33
|
+
``--model`` explicitly, any problem is reported straight away.
|
|
34
|
+
"""
|
|
35
|
+
try:
|
|
36
|
+
return create_llm(provider, model, max_cost_usd=max_cost_usd, settings=settings)
|
|
37
|
+
except LLMError as exc:
|
|
38
|
+
if provider is not None or model is not None:
|
|
39
|
+
raise ExplicitLLMError(str(exc)) from exc
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def execute_cancellable(
|
|
44
|
+
agent: BaseAgent,
|
|
45
|
+
parsed_input: BaseModel,
|
|
46
|
+
ctx: RunContext,
|
|
47
|
+
*,
|
|
48
|
+
grace_s: float = CANCEL_GRACE_S,
|
|
49
|
+
) -> AgentResult | None:
|
|
50
|
+
"""Run the agent; if this task is cancelled (Ctrl+C), cancel cooperatively.
|
|
51
|
+
|
|
52
|
+
The agent gets ``grace_s`` seconds to notice the cancellation token and return its own
|
|
53
|
+
result. After that its task is cancelled and ``None`` is returned.
|
|
54
|
+
"""
|
|
55
|
+
task = asyncio.ensure_future(agent.execute(parsed_input, ctx))
|
|
56
|
+
try:
|
|
57
|
+
return await asyncio.shield(task)
|
|
58
|
+
except asyncio.CancelledError:
|
|
59
|
+
current = asyncio.current_task()
|
|
60
|
+
if current is not None:
|
|
61
|
+
current.uncancel() # we handle the cancellation ourselves
|
|
62
|
+
ctx.cancel_token.cancel()
|
|
63
|
+
try:
|
|
64
|
+
return await asyncio.wait_for(asyncio.shield(task), timeout=grace_s)
|
|
65
|
+
except (TimeoutError, asyncio.CancelledError):
|
|
66
|
+
task.cancel()
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ProgressDisplay:
|
|
71
|
+
"""A one-line spinner on stderr, driven by the agent's progress events."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, console: Console, agent_name: str, enabled: bool) -> None:
|
|
74
|
+
self._console = console
|
|
75
|
+
self._agent_name = agent_name
|
|
76
|
+
self._enabled = enabled and console.is_terminal
|
|
77
|
+
self._status: Any = None
|
|
78
|
+
|
|
79
|
+
def __enter__(self) -> Callable[[ProgressEvent], None] | None:
|
|
80
|
+
if not self._enabled:
|
|
81
|
+
return None
|
|
82
|
+
self._status = self._console.status(f"{self._agent_name}: starting")
|
|
83
|
+
self._status.__enter__()
|
|
84
|
+
return self.update
|
|
85
|
+
|
|
86
|
+
def update(self, event: ProgressEvent) -> None:
|
|
87
|
+
text = f"{self._agent_name}: {event.stage}"
|
|
88
|
+
if event.message:
|
|
89
|
+
text += f" - {event.message}"
|
|
90
|
+
if event.fraction is not None:
|
|
91
|
+
text += f" ({event.fraction:.0%})"
|
|
92
|
+
if self._status is not None:
|
|
93
|
+
self._status.update(text)
|
|
94
|
+
|
|
95
|
+
def __exit__(self, *exc: object) -> None:
|
|
96
|
+
if self._status is not None:
|
|
97
|
+
self._status.__exit__(None, None, None)
|
|
98
|
+
self._status = None
|
margin_cli/main.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""The ``agents`` command: list, inspect and run installed agents.
|
|
2
|
+
|
|
3
|
+
Output conventions: the report (or the ``--json`` listing) goes to stdout and nothing else
|
|
4
|
+
does, so ``margin run ... --format json > report.json`` always produces valid JSON. Progress,
|
|
5
|
+
warnings and errors go to stderr.
|
|
6
|
+
|
|
7
|
+
Exit codes:
|
|
8
|
+
|
|
9
|
+
==== =====================================================================
|
|
10
|
+
0 the run finished with status ``ok`` (or ``partial`` without ``--strict``)
|
|
11
|
+
1 the run finished with status ``error``
|
|
12
|
+
2 bad usage or invalid input
|
|
13
|
+
3 the agent is not installed or failed to load
|
|
14
|
+
4 the run finished with status ``partial`` and ``--strict`` was given
|
|
15
|
+
130 cancelled with Ctrl+C
|
|
16
|
+
==== =====================================================================
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import asyncio
|
|
22
|
+
import json
|
|
23
|
+
import logging
|
|
24
|
+
from enum import IntEnum, StrEnum
|
|
25
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Annotated, Any, NoReturn
|
|
28
|
+
|
|
29
|
+
import typer
|
|
30
|
+
from margin_core import (
|
|
31
|
+
AgentLoadError,
|
|
32
|
+
AgentNotFoundError,
|
|
33
|
+
AgentRegistry,
|
|
34
|
+
AgentResult,
|
|
35
|
+
BaseAgent,
|
|
36
|
+
InputValidationError,
|
|
37
|
+
RunContext,
|
|
38
|
+
default_registry,
|
|
39
|
+
)
|
|
40
|
+
from margin_core.config import get_settings
|
|
41
|
+
from margin_core.inputs import bind_input
|
|
42
|
+
from margin_core.logging import LOGGER_NAME, configure_logging
|
|
43
|
+
from margin_core.reporting import to_json, to_markdown
|
|
44
|
+
from rich.console import Console
|
|
45
|
+
|
|
46
|
+
from margin_cli import __version__
|
|
47
|
+
from margin_cli.execution import ExplicitLLMError, ProgressDisplay, execute_cancellable, make_llm
|
|
48
|
+
from margin_cli.render import agents_table, fields_table, input_fields
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ExitCode(IntEnum):
|
|
52
|
+
OK = 0
|
|
53
|
+
RESULT_ERROR = 1
|
|
54
|
+
USAGE = 2
|
|
55
|
+
AGENT_UNAVAILABLE = 3
|
|
56
|
+
PARTIAL = 4
|
|
57
|
+
CANCELLED = 130
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ReportFormat(StrEnum):
|
|
61
|
+
markdown = "markdown"
|
|
62
|
+
json = "json"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
app = typer.Typer(
|
|
66
|
+
name="margin",
|
|
67
|
+
help="List, inspect and run the agents installed with margin.",
|
|
68
|
+
no_args_is_help=True,
|
|
69
|
+
add_completion=False,
|
|
70
|
+
pretty_exceptions_enable=False,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
stderr = Console(stderr=True)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_registry() -> AgentRegistry:
|
|
77
|
+
"""The registry used by every command (tests replace this)."""
|
|
78
|
+
return default_registry()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def fail(message: str, code: ExitCode) -> NoReturn:
|
|
82
|
+
stderr.print(f"[bold red]Error:[/] {message}", highlight=False, markup=True)
|
|
83
|
+
raise typer.Exit(int(code))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def load_agent_class(registry: AgentRegistry, agent_id: str) -> type[BaseAgent]:
|
|
87
|
+
try:
|
|
88
|
+
return registry.get_agent_class(agent_id)
|
|
89
|
+
except (AgentNotFoundError, AgentLoadError) as exc:
|
|
90
|
+
fail(str(exc), ExitCode.AGENT_UNAVAILABLE)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@app.callback()
|
|
94
|
+
def main(
|
|
95
|
+
verbose: Annotated[
|
|
96
|
+
bool, typer.Option("--verbose", "-v", help="Show debug logs on stderr.")
|
|
97
|
+
] = False,
|
|
98
|
+
) -> None:
|
|
99
|
+
"""List, inspect and run the agents installed with margin."""
|
|
100
|
+
library_logger = logging.getLogger(LOGGER_NAME)
|
|
101
|
+
if verbose:
|
|
102
|
+
configure_logging("DEBUG")
|
|
103
|
+
library_logger.propagate = False
|
|
104
|
+
elif not library_logger.handlers:
|
|
105
|
+
# Problems reach the user through the report, not as raw log lines.
|
|
106
|
+
library_logger.addHandler(logging.NullHandler())
|
|
107
|
+
library_logger.propagate = False
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@app.command("version")
|
|
111
|
+
def show_version() -> None:
|
|
112
|
+
"""Show the versions of the CLI and the core library."""
|
|
113
|
+
try:
|
|
114
|
+
core = version("margin-core")
|
|
115
|
+
except PackageNotFoundError:
|
|
116
|
+
core = "unknown"
|
|
117
|
+
typer.echo(f"margin-cli v{__version__} (core v{core})")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@app.command("list")
|
|
121
|
+
def list_agents(
|
|
122
|
+
as_json: Annotated[bool, typer.Option("--json", help="Print JSON instead of a table.")] = False,
|
|
123
|
+
) -> None:
|
|
124
|
+
"""List installed agents."""
|
|
125
|
+
registry = get_registry()
|
|
126
|
+
infos = registry.list_agents()
|
|
127
|
+
errors = registry.load_errors
|
|
128
|
+
if as_json:
|
|
129
|
+
payload = {
|
|
130
|
+
"agents": [
|
|
131
|
+
{k: v for k, v in info.model_dump().items() if not k.endswith("_schema")}
|
|
132
|
+
for info in infos
|
|
133
|
+
],
|
|
134
|
+
"load_errors": errors,
|
|
135
|
+
}
|
|
136
|
+
typer.echo(json.dumps(payload, indent=2))
|
|
137
|
+
elif infos:
|
|
138
|
+
Console().print(agents_table(infos))
|
|
139
|
+
else:
|
|
140
|
+
stderr.print("No agents are installed.")
|
|
141
|
+
for name, error in errors.items():
|
|
142
|
+
stderr.print(f"[yellow]Could not load {name}:[/] {error}", highlight=False)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@app.command("info")
|
|
146
|
+
def agent_info(
|
|
147
|
+
agent_id: Annotated[str, typer.Argument(help="Agent id, as shown by 'margin list'.")],
|
|
148
|
+
as_json: Annotated[
|
|
149
|
+
bool, typer.Option("--json", help="Print the full description and schemas as JSON.")
|
|
150
|
+
] = False,
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Describe an agent and its input fields."""
|
|
153
|
+
info = load_agent_class(get_registry(), agent_id).info()
|
|
154
|
+
if as_json:
|
|
155
|
+
typer.echo(info.model_dump_json(indent=2))
|
|
156
|
+
return
|
|
157
|
+
console = Console()
|
|
158
|
+
console.print(f"[bold]{info.name}[/] ([cyan]{info.id}[/]) v{info.version}", highlight=False)
|
|
159
|
+
console.print(info.description, highlight=False)
|
|
160
|
+
console.print()
|
|
161
|
+
console.print(fields_table(info))
|
|
162
|
+
primary = next((r for r in input_fields(info) if r["primary"]), None)
|
|
163
|
+
example = f"margin run {info.id}" + (f" <{primary['name']}>" if primary else "")
|
|
164
|
+
console.print(f"\nUsage: {example} [--set field=value ...]", highlight=False)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _read_input_file(path: Path | None) -> dict[str, Any] | None:
|
|
168
|
+
if path is None:
|
|
169
|
+
return None
|
|
170
|
+
try:
|
|
171
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
172
|
+
except OSError as exc:
|
|
173
|
+
fail(f"Cannot read {path}: {exc.strerror}", ExitCode.USAGE)
|
|
174
|
+
except json.JSONDecodeError as exc:
|
|
175
|
+
fail(f"{path} is not valid JSON: {exc}", ExitCode.USAGE)
|
|
176
|
+
if not isinstance(data, dict):
|
|
177
|
+
fail(f"{path} must contain a JSON object", ExitCode.USAGE)
|
|
178
|
+
return data
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _render(result: AgentResult, fmt: ReportFormat) -> str:
|
|
182
|
+
return to_json(result) + "\n" if fmt is ReportFormat.json else to_markdown(result)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _exit_code(result: AgentResult | None, cancelled: bool, strict: bool) -> ExitCode:
|
|
186
|
+
if cancelled or result is None:
|
|
187
|
+
return ExitCode.CANCELLED
|
|
188
|
+
if result.status == "error":
|
|
189
|
+
return ExitCode.RESULT_ERROR
|
|
190
|
+
if result.status == "partial" and strict:
|
|
191
|
+
return ExitCode.PARTIAL
|
|
192
|
+
return ExitCode.OK
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@app.command("run")
|
|
196
|
+
def run_agent(
|
|
197
|
+
agent_id: Annotated[str, typer.Argument(help="Agent id, as shown by 'margin list'.")],
|
|
198
|
+
primary: Annotated[
|
|
199
|
+
str | None,
|
|
200
|
+
typer.Argument(metavar="[INPUT]", help="Value for the agent's main input field."),
|
|
201
|
+
] = None,
|
|
202
|
+
assignments: Annotated[
|
|
203
|
+
list[str] | None,
|
|
204
|
+
typer.Option("--set", "-s", metavar="FIELD=VALUE", help="Set an input field (repeatable)."),
|
|
205
|
+
] = None,
|
|
206
|
+
input_file: Annotated[
|
|
207
|
+
Path | None, typer.Option("--input", "-i", help="JSON file with input fields.")
|
|
208
|
+
] = None,
|
|
209
|
+
fmt: Annotated[
|
|
210
|
+
ReportFormat | None,
|
|
211
|
+
typer.Option("--format", "-f", help="Report format [default: from --out, else markdown]."),
|
|
212
|
+
] = None,
|
|
213
|
+
out: Annotated[
|
|
214
|
+
Path | None, typer.Option("--out", "-o", help="Write the report to a file.")
|
|
215
|
+
] = None,
|
|
216
|
+
provider: Annotated[
|
|
217
|
+
str | None, typer.Option(help="LLM provider: local, anthropic, openai or mock.")
|
|
218
|
+
] = None,
|
|
219
|
+
model: Annotated[str | None, typer.Option(help="LLM model name.")] = None,
|
|
220
|
+
max_cost: Annotated[
|
|
221
|
+
float | None, typer.Option(help="Maximum LLM spend for this run, in USD.", min=0)
|
|
222
|
+
] = None,
|
|
223
|
+
quiet: Annotated[bool, typer.Option("--quiet", "-q", help="No progress display.")] = False,
|
|
224
|
+
strict: Annotated[
|
|
225
|
+
bool, typer.Option(help="Exit with code 4 when the result is only partial.")
|
|
226
|
+
] = False,
|
|
227
|
+
) -> None:
|
|
228
|
+
"""Run an agent and print its report."""
|
|
229
|
+
agent_cls = load_agent_class(get_registry(), agent_id)
|
|
230
|
+
base = _read_input_file(input_file)
|
|
231
|
+
try:
|
|
232
|
+
raw = bind_input(agent_cls, positional=primary, assignments=assignments or [], base=base)
|
|
233
|
+
parsed = agent_cls.parse_input(raw)
|
|
234
|
+
except InputValidationError as exc:
|
|
235
|
+
fail(str(exc), ExitCode.USAGE)
|
|
236
|
+
|
|
237
|
+
if fmt is None:
|
|
238
|
+
fmt = (
|
|
239
|
+
ReportFormat.json
|
|
240
|
+
if out is not None and out.suffix == ".json"
|
|
241
|
+
else ReportFormat.markdown
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
settings = get_settings()
|
|
245
|
+
budget = max_cost if max_cost is not None else settings.max_cost_usd
|
|
246
|
+
try:
|
|
247
|
+
llm = make_llm(provider, model, budget, settings)
|
|
248
|
+
except ExplicitLLMError as exc:
|
|
249
|
+
fail(str(exc), ExitCode.USAGE)
|
|
250
|
+
|
|
251
|
+
agent = agent_cls(llm=llm)
|
|
252
|
+
with ProgressDisplay(stderr, agent_cls.name, enabled=not quiet) as on_progress:
|
|
253
|
+
ctx = RunContext(progress=on_progress, max_cost_usd=budget)
|
|
254
|
+
try:
|
|
255
|
+
result = asyncio.run(execute_cancellable(agent, parsed, ctx))
|
|
256
|
+
except KeyboardInterrupt: # second Ctrl+C: stop immediately
|
|
257
|
+
result = None
|
|
258
|
+
ctx.cancel_token.cancel()
|
|
259
|
+
|
|
260
|
+
cancelled = ctx.cancel_token.cancelled
|
|
261
|
+
if result is not None and not cancelled:
|
|
262
|
+
report = _render(result, fmt)
|
|
263
|
+
if out is not None:
|
|
264
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
265
|
+
out.write_text(report, encoding="utf-8")
|
|
266
|
+
stderr.print(f"Report written to {out}", highlight=False)
|
|
267
|
+
else:
|
|
268
|
+
typer.echo(report, nl=False)
|
|
269
|
+
for warning in result.warnings:
|
|
270
|
+
stderr.print(f"[yellow]Warning:[/] {warning}", highlight=False)
|
|
271
|
+
if result.status == "error":
|
|
272
|
+
stderr.print(f"[bold red]Run failed:[/] {result.error}", highlight=False)
|
|
273
|
+
else:
|
|
274
|
+
stderr.print("[yellow]Cancelled.[/]")
|
|
275
|
+
raise typer.Exit(int(_exit_code(result, cancelled, strict)))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
if __name__ == "__main__":
|
|
279
|
+
app()
|
margin_cli/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Marker file for PEP 561
|
margin_cli/render.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Turn agent metadata into readable terminal output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from margin_core import AgentInfo
|
|
9
|
+
from rich.table import Table
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def schema_type(prop: dict[str, Any]) -> str:
|
|
13
|
+
"""A short, readable type for one JSON-schema property."""
|
|
14
|
+
if "enum" in prop:
|
|
15
|
+
return " | ".join(json.dumps(v) for v in prop["enum"])
|
|
16
|
+
if "$ref" in prop:
|
|
17
|
+
return str(prop["$ref"]).rsplit("/", 1)[-1]
|
|
18
|
+
if "anyOf" in prop:
|
|
19
|
+
return " | ".join(schema_type(option) for option in prop["anyOf"])
|
|
20
|
+
kind = prop.get("type")
|
|
21
|
+
if kind == "array":
|
|
22
|
+
return f"list[{schema_type(prop.get('items', {}))}]"
|
|
23
|
+
if kind == "object":
|
|
24
|
+
return "object"
|
|
25
|
+
return {"string": "text", "integer": "integer", "number": "number", "boolean": "true/false",
|
|
26
|
+
"null": "null"}.get(str(kind), str(kind or "any")) # fmt: skip
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def input_fields(info: AgentInfo) -> list[dict[str, str]]:
|
|
30
|
+
"""One row per input field: name, type, requirement/default and description."""
|
|
31
|
+
schema = info.input_schema
|
|
32
|
+
required = set(schema.get("required", []))
|
|
33
|
+
rows = []
|
|
34
|
+
for name, prop in schema.get("properties", {}).items():
|
|
35
|
+
if name in required:
|
|
36
|
+
default = "required"
|
|
37
|
+
elif "default" in prop:
|
|
38
|
+
default = json.dumps(prop["default"])
|
|
39
|
+
else:
|
|
40
|
+
default = "optional"
|
|
41
|
+
rows.append(
|
|
42
|
+
{
|
|
43
|
+
"name": name,
|
|
44
|
+
"type": schema_type(prop),
|
|
45
|
+
"default": default,
|
|
46
|
+
"description": str(prop.get("description", "")),
|
|
47
|
+
"primary": "yes" if name == info.primary_input else "",
|
|
48
|
+
}
|
|
49
|
+
)
|
|
50
|
+
rows.sort(key=lambda row: (row["primary"] != "yes", row["default"] != "required"))
|
|
51
|
+
return rows
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def agents_table(infos: list[AgentInfo]) -> Table:
|
|
55
|
+
table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
|
|
56
|
+
table.add_column("ID", style="cyan", no_wrap=True)
|
|
57
|
+
table.add_column("Name")
|
|
58
|
+
table.add_column("Version", no_wrap=True)
|
|
59
|
+
table.add_column("Description")
|
|
60
|
+
for info in infos:
|
|
61
|
+
table.add_row(info.id, info.name, info.version, info.description)
|
|
62
|
+
return table
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def fields_table(info: AgentInfo) -> Table:
|
|
66
|
+
table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
|
|
67
|
+
table.add_column("Field", style="cyan", no_wrap=True)
|
|
68
|
+
table.add_column("Type")
|
|
69
|
+
table.add_column("Default")
|
|
70
|
+
table.add_column("Description")
|
|
71
|
+
for row in input_fields(info):
|
|
72
|
+
name = row["name"] + (" (positional)" if row["primary"] else "")
|
|
73
|
+
table.add_row(name, row["type"], row["default"], row["description"])
|
|
74
|
+
return table
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: margin-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The `margin` command: list, inspect and run margin agents from the terminal.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Waddah0-0/margin
|
|
6
|
+
Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/packages/cli
|
|
7
|
+
Project-URL: Issues, https://github.com/Waddah0-0/margin/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/Waddah0-0/margin/blob/main/packages/cli/CHANGELOG.md
|
|
9
|
+
Author: Waddah Ali
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agents,cli,llm
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Environment :: Console
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: margin-core<0.2,>=0.1.0
|
|
23
|
+
Requires-Dist: rich>=13.7.0
|
|
24
|
+
Requires-Dist: typer>=0.12.0
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# margin-cli
|
|
28
|
+
|
|
29
|
+
The `margin` command lists, describes and runs the margin agents you have installed. Install
|
|
30
|
+
an agent package and it shows up here, nothing else to configure.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install margin-cli margin-ai-code-detector
|
|
34
|
+
margin run ai-code-detector https://github.com/psf/requests
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Commands
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
margin list [--json] # installed agents (and any that failed to load)
|
|
41
|
+
margin info <agent> [--json] # description and input fields
|
|
42
|
+
margin run <agent> [INPUT] [options] # run it and print the report
|
|
43
|
+
margin version
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`margin --verbose ...` (or `-v`) prints debug logs on stderr.
|
|
47
|
+
|
|
48
|
+
## Giving an agent its input
|
|
49
|
+
|
|
50
|
+
The value after the agent's name fills its main input field, which `margin info` marks as
|
|
51
|
+
"positional". For the detector that's the repository URL or path.
|
|
52
|
+
|
|
53
|
+
`--set field=value` (or `-s`, as many times as you need) sets any other field. A value that
|
|
54
|
+
parses as JSON is read as JSON (`3`, `true`, `["a","b"]`), except in text fields, which always
|
|
55
|
+
take what you typed. `--input file.json` (`-i`) reads the fields from a JSON file, and `--set`
|
|
56
|
+
wins over it.
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
margin run ai-code-detector ./my-project --set include_tests=true
|
|
60
|
+
margin run ai-code-detector --set target=./my-project --set 'paths=["src"]'
|
|
61
|
+
margin run ai-code-detector -i input.json -s max_files_for_judge=5
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Giving the main field both ways, positionally and with `--set`, is an error.
|
|
65
|
+
|
|
66
|
+
## Options of `margin run`
|
|
67
|
+
|
|
68
|
+
| Option | Meaning |
|
|
69
|
+
|---|---|
|
|
70
|
+
| `--format markdown\|json`, `-f` | Report format. Default: JSON when `--out` ends in `.json`, otherwise Markdown. |
|
|
71
|
+
| `--out PATH`, `-o` | Write the report to a file instead of stdout. |
|
|
72
|
+
| `--provider NAME` | LLM provider: `local` (default), `anthropic`, `openai` or `mock`. |
|
|
73
|
+
| `--model NAME` | Model name, e.g. `qwen3.5:9b`. |
|
|
74
|
+
| `--max-cost USD` | Spending limit for this run (only matters for hosted providers). |
|
|
75
|
+
| `--quiet`, `-q` | No progress display. |
|
|
76
|
+
| `--strict` | Treat a partial result as a failure (exit code 4). |
|
|
77
|
+
|
|
78
|
+
The model comes from your settings (environment variables, settings saved in the web UI, or
|
|
79
|
+
`.env`), but nothing talks to a model unless the agent needs one. Agents that don't use a
|
|
80
|
+
model work even with no model server running. If you pass `--provider` or `--model`, that
|
|
81
|
+
choice is checked before the run starts.
|
|
82
|
+
|
|
83
|
+
## Output streams
|
|
84
|
+
|
|
85
|
+
Only the report goes to stdout. Progress, warnings and errors go to stderr. This keeps
|
|
86
|
+
`margin run ... --format json > report.json` valid JSON.
|
|
87
|
+
|
|
88
|
+
## Exit codes
|
|
89
|
+
|
|
90
|
+
| Code | Meaning |
|
|
91
|
+
|---|---|
|
|
92
|
+
| 0 | The run finished with status `ok`, or `partial` without `--strict`. |
|
|
93
|
+
| 1 | The run finished with status `error` (the report still explains why). |
|
|
94
|
+
| 2 | Bad usage or invalid input. |
|
|
95
|
+
| 3 | The agent is not installed, or failed to load. |
|
|
96
|
+
| 4 | The run finished with status `partial` and `--strict` was given. |
|
|
97
|
+
| 130 | Cancelled with Ctrl+C. |
|
|
98
|
+
|
|
99
|
+
## Cancelling
|
|
100
|
+
|
|
101
|
+
Press Ctrl+C once to ask the agent to stop. It gets 5 seconds to finish cleanly, after which
|
|
102
|
+
it is stopped. Press Ctrl+C again to stop at once.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
margin_cli/__init__.py,sha256=RUCBSET6PeDO8EnLNJNezIDuKcUE4TYDYWO5Q4HYQJU,57
|
|
2
|
+
margin_cli/execution.py,sha256=nidYkc_ggSX0VRIQnSV326IaCfivAoKuywHbnI2xYv0,3607
|
|
3
|
+
margin_cli/main.py,sha256=gJPGcn4QDr8SeJaFf_dP25sF_xV3grfAbXWXhpi77vI,9651
|
|
4
|
+
margin_cli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
|
|
5
|
+
margin_cli/render.py,sha256=Ufd2zUwhR_TMDUsMfz7yv5VTfz96Ox4noVmKHp3ZmJw,2697
|
|
6
|
+
margin_cli-0.1.0.dist-info/METADATA,sha256=WdLZyTE3Iu9edPIKxzn8Y-AzdGMLcEiavE4WmMqc5YM,4063
|
|
7
|
+
margin_cli-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
8
|
+
margin_cli-0.1.0.dist-info/entry_points.txt,sha256=cVKA3g5oAcVLuozKqPrhzxsTQI3v0eNoA_lAIUbpnNA,47
|
|
9
|
+
margin_cli-0.1.0.dist-info/licenses/LICENSE,sha256=7dCPJ4m91LD52BnTk6tiuMOiQU5i6aoIfpSzGgb9mVY,1076
|
|
10
|
+
margin_cli-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 margin contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|