margin-cli 0.1.0__tar.gz

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,80 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ /lib/
14
+ /lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ share/python-wheels/
20
+ *.egg-info/
21
+ .installed.cfg
22
+ *.egg
23
+
24
+ # Virtual environments
25
+ .venv/
26
+ venv/
27
+ ENV/
28
+ env/
29
+
30
+ # uv
31
+ .uv/
32
+
33
+ # Environment variables & secrets
34
+ .env
35
+ .env.local
36
+ .env.*.local
37
+ *.key
38
+ *.pem
39
+
40
+ # Testing & Coverage
41
+ .pytest_cache/
42
+ .coverage
43
+ .coverage.*
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+
51
+ # Type checking & linting
52
+ .mypy_cache/
53
+ .ruff_cache/
54
+ .dmypy.json
55
+ dmypy.json
56
+
57
+ # IDEs & Editors
58
+ .vscode/
59
+ .idea/
60
+ *.swp
61
+ *.swo
62
+ *~
63
+
64
+ # Operating System
65
+ .DS_Store
66
+ Thumbs.db
67
+ ehthumbs.db
68
+ desktop.ini
69
+
70
+ # Output / Reports
71
+ report.json
72
+ report.md
73
+ temp/
74
+ tmp/
75
+
76
+ # Private planning notes (kept locally, not published)
77
+ PLAN.md
78
+
79
+ # the web UI bundled into margin-api at release time (scripts/build_release.py)
80
+ packages/api/src/margin_api/ui/
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.0] - 2026-10-21
8
+
9
+ ### Added
10
+ - `margin list`, `margin info` and `margin run`, with JSON or Markdown reports, progress on stderr, and documented exit codes.
11
+ - `--provider` and `--model` choose the model for one run.
@@ -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.
@@ -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,76 @@
1
+ # margin-cli
2
+
3
+ The `margin` command lists, describes and runs the margin agents you have installed. Install
4
+ an agent package and it shows up here, nothing else to configure.
5
+
6
+ ```bash
7
+ pip install margin-cli margin-ai-code-detector
8
+ margin run ai-code-detector https://github.com/psf/requests
9
+ ```
10
+
11
+ ## Commands
12
+
13
+ ```bash
14
+ margin list [--json] # installed agents (and any that failed to load)
15
+ margin info <agent> [--json] # description and input fields
16
+ margin run <agent> [INPUT] [options] # run it and print the report
17
+ margin version
18
+ ```
19
+
20
+ `margin --verbose ...` (or `-v`) prints debug logs on stderr.
21
+
22
+ ## Giving an agent its input
23
+
24
+ The value after the agent's name fills its main input field, which `margin info` marks as
25
+ "positional". For the detector that's the repository URL or path.
26
+
27
+ `--set field=value` (or `-s`, as many times as you need) sets any other field. A value that
28
+ parses as JSON is read as JSON (`3`, `true`, `["a","b"]`), except in text fields, which always
29
+ take what you typed. `--input file.json` (`-i`) reads the fields from a JSON file, and `--set`
30
+ wins over it.
31
+
32
+ ```bash
33
+ margin run ai-code-detector ./my-project --set include_tests=true
34
+ margin run ai-code-detector --set target=./my-project --set 'paths=["src"]'
35
+ margin run ai-code-detector -i input.json -s max_files_for_judge=5
36
+ ```
37
+
38
+ Giving the main field both ways, positionally and with `--set`, is an error.
39
+
40
+ ## Options of `margin run`
41
+
42
+ | Option | Meaning |
43
+ |---|---|
44
+ | `--format markdown\|json`, `-f` | Report format. Default: JSON when `--out` ends in `.json`, otherwise Markdown. |
45
+ | `--out PATH`, `-o` | Write the report to a file instead of stdout. |
46
+ | `--provider NAME` | LLM provider: `local` (default), `anthropic`, `openai` or `mock`. |
47
+ | `--model NAME` | Model name, e.g. `qwen3.5:9b`. |
48
+ | `--max-cost USD` | Spending limit for this run (only matters for hosted providers). |
49
+ | `--quiet`, `-q` | No progress display. |
50
+ | `--strict` | Treat a partial result as a failure (exit code 4). |
51
+
52
+ The model comes from your settings (environment variables, settings saved in the web UI, or
53
+ `.env`), but nothing talks to a model unless the agent needs one. Agents that don't use a
54
+ model work even with no model server running. If you pass `--provider` or `--model`, that
55
+ choice is checked before the run starts.
56
+
57
+ ## Output streams
58
+
59
+ Only the report goes to stdout. Progress, warnings and errors go to stderr. This keeps
60
+ `margin run ... --format json > report.json` valid JSON.
61
+
62
+ ## Exit codes
63
+
64
+ | Code | Meaning |
65
+ |---|---|
66
+ | 0 | The run finished with status `ok`, or `partial` without `--strict`. |
67
+ | 1 | The run finished with status `error` (the report still explains why). |
68
+ | 2 | Bad usage or invalid input. |
69
+ | 3 | The agent is not installed, or failed to load. |
70
+ | 4 | The run finished with status `partial` and `--strict` was given. |
71
+ | 130 | Cancelled with Ctrl+C. |
72
+
73
+ ## Cancelling
74
+
75
+ Press Ctrl+C once to ask the agent to stop. It gets 5 seconds to finish cleanly, after which
76
+ it is stopped. Press Ctrl+C again to stop at once.
@@ -0,0 +1,41 @@
1
+ [project]
2
+ name = "margin-cli"
3
+ version = "0.1.0"
4
+ description = "The `margin` command: list, inspect and run margin agents from the terminal."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Waddah Ali" }]
10
+ keywords = ["agents", "llm", "cli"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Typing :: Typed",
19
+ "Environment :: Console",
20
+ ]
21
+ dependencies = [
22
+ "margin-core>=0.1.0,<0.2",
23
+ "typer>=0.12.0",
24
+ "rich>=13.7.0",
25
+ ]
26
+
27
+ [project.scripts]
28
+ margin = "margin_cli.main:app"
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/Waddah0-0/margin"
32
+ Source = "https://github.com/Waddah0-0/margin/tree/main/packages/cli"
33
+ Issues = "https://github.com/Waddah0-0/margin/issues"
34
+ Changelog = "https://github.com/Waddah0-0/margin/blob/main/packages/cli/CHANGELOG.md"
35
+
36
+ [build-system]
37
+ requires = ["hatchling"]
38
+ build-backend = "hatchling.build"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/margin_cli"]
@@ -0,0 +1,3 @@
1
+ """CLI application for margin."""
2
+
3
+ __version__ = "0.1.0"
@@ -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
@@ -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()
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561
@@ -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,380 @@
1
+ """CLI behaviour: commands, input binding, output streams and every exit code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import io
7
+ import json
8
+ import os
9
+ import signal
10
+ import subprocess
11
+ import sys
12
+ from importlib.metadata import EntryPoint
13
+ from pathlib import Path
14
+
15
+ import pytest
16
+ from echo_agent import EchoAgent
17
+ from margin_cli import main as cli
18
+ from margin_cli.execution import ProgressDisplay, execute_cancellable
19
+ from margin_core import (
20
+ AgentInput,
21
+ AgentRegistry,
22
+ AgentResult,
23
+ BaseAgent,
24
+ ProgressEvent,
25
+ RunContext,
26
+ )
27
+ from margin_core.models import ResultStatus
28
+ from margin_core.registry import ENTRY_POINT_GROUP
29
+ from pydantic import BaseModel
30
+ from rich.console import Console
31
+ from typer.testing import CliRunner
32
+
33
+ runner = CliRunner()
34
+
35
+
36
+ class TargetInput(AgentInput):
37
+ target: str
38
+ mode: str = "ok"
39
+
40
+
41
+ class FileCount(BaseModel):
42
+ files: int
43
+
44
+
45
+ class Lister(BaseAgent):
46
+ """A loader-based agent: counts the files of a local folder."""
47
+
48
+ id = "lister"
49
+ name = "Lister"
50
+ description = "Counts files in a folder."
51
+ version = "0.0.1"
52
+ InputModel = TargetInput
53
+ OutputModel = FileCount
54
+ primary_input = "target"
55
+
56
+ async def run(self, input: TargetInput, ctx: RunContext) -> AgentResult:
57
+ if input.mode == "crash":
58
+ raise RuntimeError("boom")
59
+ async with await ctx.load_workspace(input.target) as ws:
60
+ status: ResultStatus = "partial" if input.mode == "partial" else "ok"
61
+ warnings = ["some files skipped"] if status == "partial" else []
62
+ return self.make_result(
63
+ summary=f"{len(ws.files)} files",
64
+ output=FileCount(files=len(ws.files)),
65
+ status=status,
66
+ warnings=warnings,
67
+ )
68
+
69
+
70
+ class NoPrimary(BaseAgent):
71
+ id = "no-primary"
72
+ name = "No primary"
73
+ description = "Takes only named fields."
74
+ version = "0.0.1"
75
+ InputModel = TargetInput
76
+ OutputModel = FileCount
77
+
78
+ async def run(self, input: TargetInput, ctx: RunContext) -> AgentResult:
79
+ return self.make_result(summary="ok", output=FileCount(files=0))
80
+
81
+
82
+ @pytest.fixture(autouse=True)
83
+ def registry(monkeypatch: pytest.MonkeyPatch) -> AgentRegistry:
84
+ broken = EntryPoint(name="broken", value="no_such_module:Agent", group=ENTRY_POINT_GROUP)
85
+ reg = AgentRegistry([broken])
86
+ for agent in (EchoAgent, Lister, NoPrimary):
87
+ reg.register(agent)
88
+ monkeypatch.setattr(cli, "get_registry", lambda: reg)
89
+ return reg
90
+
91
+
92
+ @pytest.fixture
93
+ def folder(tmp_path: Path) -> Path:
94
+ (tmp_path / "src").mkdir()
95
+ (tmp_path / "a.py").write_text("x = 1\n", encoding="utf-8")
96
+ (tmp_path / "src" / "b.py").write_text("y = 2\n", encoding="utf-8")
97
+ return tmp_path
98
+
99
+
100
+ def invoke(*args: str) -> tuple[int, str, str]:
101
+ result = runner.invoke(cli.app, list(args))
102
+ return result.exit_code, result.stdout, result.stderr
103
+
104
+
105
+ # ---- list / info / version ------------------------------------------------------------
106
+
107
+
108
+ def test_version() -> None:
109
+ code, out, _ = invoke("version")
110
+ assert code == 0 and out.startswith("margin-cli v0.1.0 (core v")
111
+
112
+
113
+ def test_list_table_and_load_errors() -> None:
114
+ code, out, err = invoke("list")
115
+ assert code == 0
116
+ assert "echo" in out and "lister" in out and "Counts files" in out
117
+ assert "Could not load broken" in err and "broken" not in out
118
+
119
+
120
+ def test_list_json() -> None:
121
+ code, out, _ = invoke("list", "--json")
122
+ data = json.loads(out)
123
+ assert code == 0
124
+ assert [a["id"] for a in data["agents"]] == ["echo", "lister", "no-primary"]
125
+ assert data["agents"][0]["primary_input"] == "message"
126
+ assert "input_schema" not in data["agents"][0]
127
+ assert "broken" in data["load_errors"]
128
+
129
+
130
+ def test_info_marks_the_positional_field() -> None:
131
+ code, out, _ = invoke("info", "echo")
132
+ assert code == 0
133
+ assert "message (positional)" in out
134
+ assert "margin run echo <message>" in out
135
+
136
+
137
+ def test_info_json_has_schemas() -> None:
138
+ code, out, _ = invoke("info", "lister", "--json")
139
+ info = json.loads(out)
140
+ assert code == 0 and info["primary_input"] == "target"
141
+ assert info["input_schema"]["required"] == ["target"]
142
+
143
+
144
+ @pytest.mark.parametrize("command", [["info", "nope"], ["run", "nope", "x"], ["info", "broken"]])
145
+ def test_unknown_or_broken_agent_exits_3(command: list[str]) -> None:
146
+ code, out, err = invoke(*command)
147
+ assert code == 3 and out == "" and "Error:" in err
148
+
149
+
150
+ # ---- run: input -----------------------------------------------------------------------
151
+
152
+
153
+ def test_run_echo_markdown() -> None:
154
+ code, out, err = invoke("run", "echo", "hello", "--set", "repeat=2")
155
+ assert code == 0
156
+ assert out.startswith("# echo report") and "hello hello" in out
157
+ assert "Model" not in out # no LLM call was made
158
+ assert err == ""
159
+
160
+
161
+ def test_run_json_stdout_is_pure_json() -> None:
162
+ code, out, _ = invoke("run", "echo", "hi", "--format", "json", "--set", "repeat=3")
163
+ result = json.loads(out)
164
+ assert code == 0 and result["data"]["echoed"] == "hi hi hi"
165
+
166
+
167
+ def test_input_file_and_overrides(tmp_path: Path) -> None:
168
+ payload = tmp_path / "in.json"
169
+ payload.write_text(json.dumps({"message": "from-file", "repeat": 2}), encoding="utf-8")
170
+ code, out, _ = invoke("run", "echo", "-i", str(payload), "-s", "repeat=1", "-f", "json")
171
+ assert code == 0 and json.loads(out)["data"]["echoed"] == "from-file"
172
+
173
+
174
+ def test_string_fields_keep_raw_text() -> None:
175
+ code, out, _ = invoke("run", "echo", "--set", "message=123", "-f", "json")
176
+ assert code == 0 and json.loads(out)["data"]["echoed"] == "123"
177
+
178
+
179
+ @pytest.mark.parametrize(
180
+ ("args", "message"),
181
+ [
182
+ (["run", "echo", "hi", "--set", "repeat=99"], "Invalid input"),
183
+ (["run", "echo", "hi", "--set", "nope=1"], "Invalid input"),
184
+ (["run", "echo"], "Invalid input"),
185
+ (["run", "no-primary", "x"], "positional"),
186
+ (["run", "echo", "hi", "--set", "message=other"], "both"),
187
+ (["run", "echo", "hi", "--set", "repeat"], "key=value"),
188
+ ],
189
+ )
190
+ def test_bad_input_exits_2(args: list[str], message: str) -> None:
191
+ code, out, err = invoke(*args)
192
+ assert code == 2 and out == "" and message in err
193
+
194
+
195
+ def test_bad_input_file_exits_2(tmp_path: Path) -> None:
196
+ bad = tmp_path / "bad.json"
197
+ bad.write_text("[1, 2]", encoding="utf-8")
198
+ assert invoke("run", "echo", "-i", str(bad))[0] == 2
199
+ bad.write_text("{nope", encoding="utf-8")
200
+ assert invoke("run", "echo", "-i", str(bad))[0] == 2
201
+ assert invoke("run", "echo", "-i", str(tmp_path / "missing.json"))[0] == 2
202
+
203
+
204
+ # ---- run: output and status -----------------------------------------------------------
205
+
206
+
207
+ def test_loader_based_agent(folder: Path) -> None:
208
+ code, out, _ = invoke("run", "lister", str(folder), "-f", "json")
209
+ assert code == 0 and json.loads(out)["data"] == {"files": 2}
210
+
211
+
212
+ def test_out_file_infers_json(folder: Path, tmp_path: Path) -> None:
213
+ report = tmp_path / "reports" / "r.json"
214
+ code, out, err = invoke("run", "lister", str(folder), "--out", str(report))
215
+ assert code == 0 and out == "" and "Report written to" in err
216
+ assert json.loads(report.read_text(encoding="utf-8"))["status"] == "ok"
217
+
218
+
219
+ def test_out_markdown(folder: Path, tmp_path: Path) -> None:
220
+ report = tmp_path / "r.md"
221
+ assert invoke("run", "lister", str(folder), "-o", str(report))[0] == 0
222
+ assert report.read_text(encoding="utf-8").startswith("# lister report")
223
+
224
+
225
+ def test_error_result_exits_1(folder: Path) -> None:
226
+ code, out, err = invoke("run", "lister", str(folder), "--set", "mode=crash")
227
+ assert code == 1
228
+ assert "## Error" in out and "RuntimeError: boom" in err
229
+
230
+
231
+ def test_missing_target_is_an_error_result(tmp_path: Path) -> None:
232
+ code, _, err = invoke("run", "lister", str(tmp_path / "missing"))
233
+ assert code == 1 and "Path does not exist" in err
234
+
235
+
236
+ def test_partial_exits_0_or_4_with_strict(folder: Path) -> None:
237
+ code, _, err = invoke("run", "lister", str(folder), "--set", "mode=partial")
238
+ assert code == 0 and "Warning: some files skipped" in err
239
+ assert invoke("run", "lister", str(folder), "--set", "mode=partial", "--strict")[0] == 4
240
+
241
+
242
+ # ---- run: LLM selection ---------------------------------------------------------------
243
+
244
+
245
+ def test_explicit_provider_with_mock_llm() -> None:
246
+ code, out, _ = invoke(
247
+ "run", "echo", "ping", "-s", "use_llm=true", "--provider", "mock", "-f", "json"
248
+ )
249
+ result = json.loads(out)
250
+ assert code == 0
251
+ assert result["data"]["llm_reply"] == "ping"
252
+ assert result["metadata"]["usage"]["llm_calls"] == 1
253
+
254
+
255
+ def test_explicit_provider_that_cannot_start_exits_2() -> None:
256
+ code, _, err = invoke("run", "echo", "hi", "--provider", "anthropic")
257
+ assert code == 2 and "ANTHROPIC_API_KEY" in err
258
+
259
+
260
+ def test_unusable_default_provider_does_not_block_agents_without_llm(
261
+ monkeypatch: pytest.MonkeyPatch,
262
+ ) -> None:
263
+ monkeypatch.setenv("DEFAULT_LLM_PROVIDER", "anthropic") # no API key set
264
+ assert invoke("run", "echo", "hi")[0] == 0
265
+ code, _, err = invoke("run", "echo", "hi", "-s", "use_llm=true")
266
+ assert code == 1 and "needs an LLM client" in err
267
+
268
+
269
+ def test_max_cost_is_the_run_budget(monkeypatch: pytest.MonkeyPatch) -> None:
270
+ seen: list[float | None] = []
271
+ real = execute_cancellable
272
+
273
+ async def capture(agent: BaseAgent, parsed: BaseModel, ctx: RunContext) -> AgentResult | None:
274
+ seen.append(ctx.max_cost_usd)
275
+ return await real(agent, parsed, ctx)
276
+
277
+ monkeypatch.setattr(cli, "execute_cancellable", capture)
278
+ assert invoke("run", "echo", "hi", "--max-cost", "0.25")[0] == 0
279
+ assert invoke("run", "echo", "hi")[0] == 0
280
+ assert seen == [0.25, 1.0] # explicit value, then the MAX_COST_USD default
281
+
282
+
283
+ # ---- cancellation and progress --------------------------------------------------------
284
+
285
+
286
+ class Slow(BaseAgent):
287
+ id = "slow"
288
+ name = "Slow"
289
+ description = "Loops until cancelled."
290
+ version = "0.0.1"
291
+ InputModel = TargetInput
292
+ OutputModel = FileCount
293
+
294
+ async def run(self, input: TargetInput, ctx: RunContext) -> AgentResult:
295
+ for _ in range(500):
296
+ if input.mode == "ok":
297
+ ctx.check_cancelled()
298
+ await asyncio.sleep(0.01)
299
+ return self.make_result(summary="done", output=FileCount(files=0))
300
+
301
+
302
+ async def test_cancel_stops_a_cooperative_agent() -> None:
303
+ ctx = RunContext()
304
+ task = asyncio.create_task(execute_cancellable(Slow(), TargetInput(target="x"), ctx))
305
+ await asyncio.sleep(0.05)
306
+ task.cancel()
307
+ result = await task
308
+ assert ctx.cancel_token.cancelled
309
+ assert result is not None and result.error == "Run was cancelled"
310
+
311
+
312
+ async def test_cancel_gives_up_on_an_agent_that_ignores_it() -> None:
313
+ ctx = RunContext()
314
+ stubborn = TargetInput(target="x", mode="ignore")
315
+ task = asyncio.create_task(execute_cancellable(Slow(), stubborn, ctx, grace_s=0.05))
316
+ await asyncio.sleep(0.05)
317
+ task.cancel()
318
+ assert await task is None
319
+
320
+
321
+ def test_progress_display_text() -> None:
322
+ console = Console(file=io.StringIO(), force_terminal=True)
323
+ display = ProgressDisplay(console, "Lister", enabled=True)
324
+ with display as callback:
325
+ assert callback is not None
326
+ callback(ProgressEvent(stage="scan", message="a.py", fraction=0.5))
327
+ assert display._status is not None
328
+ assert display._status is None
329
+
330
+
331
+ def test_progress_display_off_when_not_a_terminal() -> None:
332
+ console = Console(file=io.StringIO(), force_terminal=False)
333
+ with ProgressDisplay(console, "Lister", enabled=True) as callback:
334
+ assert callback is None
335
+
336
+
337
+ SIGINT_SCRIPT = """
338
+ import asyncio, sys
339
+ from margin_cli import main as cli
340
+ from margin_core import AgentInput, AgentRegistry, AgentResult, BaseAgent, RunContext
341
+ from pydantic import BaseModel
342
+
343
+ class In(AgentInput):
344
+ target: str
345
+
346
+ class Out(BaseModel):
347
+ n: int
348
+
349
+ class Slow(BaseAgent):
350
+ id = "slow"; name = "Slow"; description = "slow"; version = "0.0.1"
351
+ InputModel = In; OutputModel = Out; primary_input = "target"
352
+ async def run(self, input, ctx):
353
+ print("started", file=sys.stderr, flush=True)
354
+ for _ in range(3000):
355
+ ctx.check_cancelled()
356
+ await asyncio.sleep(0.01)
357
+ return self.make_result(summary="done", output=Out(n=1))
358
+
359
+ registry = AgentRegistry([])
360
+ registry.register(Slow)
361
+ cli.get_registry = lambda: registry
362
+ cli.app(["run", "slow", "x", "--quiet"])
363
+ """
364
+
365
+
366
+ @pytest.mark.skipif(sys.platform == "win32", reason="SIGINT cannot be sent to a child on Windows")
367
+ def test_ctrl_c_cancels_and_exits_130() -> None:
368
+ proc = subprocess.Popen(
369
+ [sys.executable, "-c", SIGINT_SCRIPT],
370
+ stdout=subprocess.PIPE,
371
+ stderr=subprocess.PIPE,
372
+ text=True,
373
+ env={**os.environ, "MARGIN_ENV_FILE": ""},
374
+ )
375
+ assert proc.stderr is not None
376
+ assert proc.stderr.readline().strip() == "started"
377
+ proc.send_signal(signal.SIGINT)
378
+ out, err = proc.communicate(timeout=30)
379
+ assert proc.returncode == 130, err
380
+ assert out == "" and "Cancelled" in err