margin-cli 0.1.0__py3-none-any.whl → 0.1.2__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 +1 -1
- margin_cli/execution.py +182 -5
- margin_cli/main.py +18 -5
- {margin_cli-0.1.0.dist-info → margin_cli-0.1.2.dist-info}/METADATA +3 -3
- margin_cli-0.1.2.dist-info/RECORD +10 -0
- {margin_cli-0.1.0.dist-info → margin_cli-0.1.2.dist-info}/WHEEL +1 -1
- margin_cli-0.1.0.dist-info/RECORD +0 -10
- {margin_cli-0.1.0.dist-info → margin_cli-0.1.2.dist-info}/entry_points.txt +0 -0
- {margin_cli-0.1.0.dist-info → margin_cli-0.1.2.dist-info}/licenses/LICENSE +0 -0
margin_cli/__init__.py
CHANGED
margin_cli/execution.py
CHANGED
|
@@ -1,22 +1,40 @@
|
|
|
1
|
-
"""Running an agent from the CLI: LLM setup, progress
|
|
1
|
+
"""Running an agent from the CLI: LLM setup, progress, questions and Ctrl+C handling."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
import contextlib
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Callable, Iterator
|
|
10
|
+
from typing import IO, Any
|
|
8
11
|
|
|
9
|
-
from margin_core import
|
|
12
|
+
from margin_core import (
|
|
13
|
+
AgentResult,
|
|
14
|
+
BaseAgent,
|
|
15
|
+
NoAnswerError,
|
|
16
|
+
ProgressEvent,
|
|
17
|
+
Question,
|
|
18
|
+
QuestionBatch,
|
|
19
|
+
RunContext,
|
|
20
|
+
)
|
|
10
21
|
from margin_core.config import Settings
|
|
11
22
|
from margin_core.errors import LLMError
|
|
12
23
|
from margin_core.llm import LLMClient, create_llm
|
|
24
|
+
from margin_core.reporting import strip_control
|
|
13
25
|
from pydantic import BaseModel
|
|
14
26
|
from rich.console import Console
|
|
27
|
+
from rich.markup import escape as escape_markup
|
|
15
28
|
|
|
16
29
|
CANCEL_GRACE_S = 5.0
|
|
17
30
|
"""How long a cancelled agent gets to stop on its own before its task is cancelled."""
|
|
18
31
|
|
|
19
32
|
|
|
33
|
+
def escape(text: str) -> str:
|
|
34
|
+
"""Text from a run, safe to print: agents quote file names, commit messages and cells."""
|
|
35
|
+
return escape_markup(strip_control(text))
|
|
36
|
+
|
|
37
|
+
|
|
20
38
|
class ExplicitLLMError(Exception):
|
|
21
39
|
"""The user asked for a specific provider or model, and it cannot be set up."""
|
|
22
40
|
|
|
@@ -86,7 +104,7 @@ class ProgressDisplay:
|
|
|
86
104
|
def update(self, event: ProgressEvent) -> None:
|
|
87
105
|
text = f"{self._agent_name}: {event.stage}"
|
|
88
106
|
if event.message:
|
|
89
|
-
text += f" - {event.message}"
|
|
107
|
+
text += f" - {escape(event.message)}"
|
|
90
108
|
if event.fraction is not None:
|
|
91
109
|
text += f" ({event.fraction:.0%})"
|
|
92
110
|
if self._status is not None:
|
|
@@ -96,3 +114,162 @@ class ProgressDisplay:
|
|
|
96
114
|
if self._status is not None:
|
|
97
115
|
self._status.__exit__(None, None, None)
|
|
98
116
|
self._status = None
|
|
117
|
+
|
|
118
|
+
@contextlib.contextmanager
|
|
119
|
+
def paused(self) -> Iterator[None]:
|
|
120
|
+
"""Hide the spinner while something else uses the terminal."""
|
|
121
|
+
status = self._status
|
|
122
|
+
if status is not None:
|
|
123
|
+
status.stop()
|
|
124
|
+
try:
|
|
125
|
+
yield
|
|
126
|
+
finally:
|
|
127
|
+
if status is not None and self._status is status:
|
|
128
|
+
status.start()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class TerminalQuestions:
|
|
132
|
+
"""Answers an agent's questions by asking in the terminal.
|
|
133
|
+
|
|
134
|
+
Prompts go to stderr, so stdout is still only the report. Lines are read on a daemon
|
|
135
|
+
thread, so Ctrl+C cancels the run even while a prompt is waiting.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
def __init__(
|
|
139
|
+
self,
|
|
140
|
+
console: Console,
|
|
141
|
+
display: ProgressDisplay | None = None,
|
|
142
|
+
stream: IO[str] | None = None,
|
|
143
|
+
) -> None:
|
|
144
|
+
self._console = console
|
|
145
|
+
self._display = display
|
|
146
|
+
self._stream = stream
|
|
147
|
+
|
|
148
|
+
async def __call__(self, batch: QuestionBatch) -> dict[str, Any]:
|
|
149
|
+
loop = asyncio.get_running_loop()
|
|
150
|
+
future: asyncio.Future[dict[str, Any]] = loop.create_future()
|
|
151
|
+
|
|
152
|
+
def settle(answers: dict[str, Any] | None, error: BaseException | None) -> None:
|
|
153
|
+
if future.done():
|
|
154
|
+
return
|
|
155
|
+
if error is not None:
|
|
156
|
+
future.set_exception(error)
|
|
157
|
+
else:
|
|
158
|
+
future.set_result(answers or {})
|
|
159
|
+
|
|
160
|
+
def work() -> None:
|
|
161
|
+
answers: dict[str, Any] | None = None
|
|
162
|
+
error: BaseException | None = None
|
|
163
|
+
try:
|
|
164
|
+
answers = self.ask_batch(batch)
|
|
165
|
+
except BaseException as exc: # noqa: BLE001 - handed to the run
|
|
166
|
+
error = exc
|
|
167
|
+
with contextlib.suppress(RuntimeError): # the run ended and its loop is gone
|
|
168
|
+
loop.call_soon_threadsafe(settle, answers, error)
|
|
169
|
+
|
|
170
|
+
paused = self._display.paused() if self._display else contextlib.nullcontext()
|
|
171
|
+
with paused:
|
|
172
|
+
threading.Thread(target=work, name="margin-questions", daemon=True).start()
|
|
173
|
+
return await future
|
|
174
|
+
|
|
175
|
+
def ask_batch(self, batch: QuestionBatch) -> dict[str, Any]:
|
|
176
|
+
"""Ask every question in turn (blocking). Raises :class:`NoAnswerError` at end of input."""
|
|
177
|
+
out = self._console
|
|
178
|
+
out.print()
|
|
179
|
+
out.print(f"[bold]{escape(batch.title)}[/]", highlight=False)
|
|
180
|
+
if batch.detail:
|
|
181
|
+
out.print(escape(batch.detail), highlight=False)
|
|
182
|
+
answers: dict[str, Any] = {}
|
|
183
|
+
section: str | None = None
|
|
184
|
+
for question in batch.questions:
|
|
185
|
+
if question.section and question.section != section:
|
|
186
|
+
section = question.section
|
|
187
|
+
out.print(f"\n[bold underline]{escape(section)}[/]", highlight=False)
|
|
188
|
+
try:
|
|
189
|
+
answers[question.id] = self._ask(question)
|
|
190
|
+
except EOFError:
|
|
191
|
+
raise NoAnswerError("The input ended before the questions were answered.") from None
|
|
192
|
+
out.print()
|
|
193
|
+
return answers
|
|
194
|
+
|
|
195
|
+
def _ask(self, question: Question) -> Any:
|
|
196
|
+
out = self._console
|
|
197
|
+
out.print(f"\n[bold]{escape(question.prompt)}[/]", highlight=False)
|
|
198
|
+
if question.detail:
|
|
199
|
+
out.print(f" [dim]{escape(question.detail)}[/]", highlight=False)
|
|
200
|
+
for ev in question.evidence:
|
|
201
|
+
where = f"{ev.location}: " if ev.location else ""
|
|
202
|
+
out.print(
|
|
203
|
+
f" [dim]· {escape(ev.kind)}: {escape(where + ev.detail)}[/]", highlight=False
|
|
204
|
+
)
|
|
205
|
+
suggested = question.default if isinstance(question.default, list) else [question.default]
|
|
206
|
+
for n, choice in enumerate(question.choices, 1):
|
|
207
|
+
line = f" {n}) {escape(choice.label)}"
|
|
208
|
+
if choice.detail:
|
|
209
|
+
line += f" [dim]- {escape(choice.detail)}[/]"
|
|
210
|
+
if any(choice.value == s and type(choice.value) is type(s) for s in suggested):
|
|
211
|
+
line += " [cyan](suggested)[/]"
|
|
212
|
+
out.print(line, highlight=False)
|
|
213
|
+
|
|
214
|
+
while True:
|
|
215
|
+
raw = self._read(self._prompt(question)).strip()
|
|
216
|
+
try:
|
|
217
|
+
value = question.default if not raw else _parse(question, raw)
|
|
218
|
+
return question.check(value)
|
|
219
|
+
except ValueError as exc:
|
|
220
|
+
out.print(f" [red]{escape(str(exc))}[/]", highlight=False)
|
|
221
|
+
|
|
222
|
+
def _prompt(self, question: Question) -> str:
|
|
223
|
+
if question.kind == "text":
|
|
224
|
+
hint = "Your answer"
|
|
225
|
+
elif question.kind == "multi_choice":
|
|
226
|
+
hint = "Numbers, separated by commas" + ("" if question.required else ", or none")
|
|
227
|
+
else:
|
|
228
|
+
hint = f"Choose 1-{len(question.choices)}"
|
|
229
|
+
if question.allow_other:
|
|
230
|
+
hint += ", or type your own"
|
|
231
|
+
if question.default not in (None, []):
|
|
232
|
+
default = question.default if isinstance(question.default, list) else [question.default]
|
|
233
|
+
numbers = [
|
|
234
|
+
str(n)
|
|
235
|
+
for n, c in enumerate(question.choices, 1)
|
|
236
|
+
if any(c.value == d and type(c.value) is type(d) for d in default)
|
|
237
|
+
]
|
|
238
|
+
shown = ",".join(numbers) if question.choices and numbers else str(question.default)
|
|
239
|
+
hint += f" [{shown}]"
|
|
240
|
+
elif not question.required:
|
|
241
|
+
hint += " (optional)"
|
|
242
|
+
return f"[cyan]{escape(hint)}:[/] "
|
|
243
|
+
|
|
244
|
+
def _read(self, prompt: str) -> str:
|
|
245
|
+
self._console.print(prompt, end="", highlight=False)
|
|
246
|
+
line = (self._stream or sys.stdin).readline()
|
|
247
|
+
if not line:
|
|
248
|
+
raise EOFError
|
|
249
|
+
return line.rstrip("\r\n")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _parse(question: Question, raw: str) -> Any:
|
|
253
|
+
"""Turn what was typed into a value for ``question.check``."""
|
|
254
|
+
if question.kind == "text":
|
|
255
|
+
return raw
|
|
256
|
+
if question.kind == "multi_choice":
|
|
257
|
+
if raw.lower() in {"none", "-"}:
|
|
258
|
+
return []
|
|
259
|
+
return [_pick(question, part.strip()) for part in raw.split(",") if part.strip()]
|
|
260
|
+
try:
|
|
261
|
+
return _pick(question, raw)
|
|
262
|
+
except ValueError:
|
|
263
|
+
if question.allow_other:
|
|
264
|
+
return raw
|
|
265
|
+
raise
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _pick(question: Question, typed: str) -> Any:
|
|
269
|
+
"""The value of the choice ``typed`` names: by number, label or value."""
|
|
270
|
+
if typed.isdigit() and 1 <= int(typed) <= len(question.choices):
|
|
271
|
+
return question.choices[int(typed) - 1].value
|
|
272
|
+
for choice in question.choices:
|
|
273
|
+
if typed.casefold() in {choice.label.casefold(), str(choice.value).casefold()}:
|
|
274
|
+
return choice.value
|
|
275
|
+
raise ValueError(f"Type a number from 1 to {len(question.choices)}")
|
margin_cli/main.py
CHANGED
|
@@ -21,6 +21,7 @@ from __future__ import annotations
|
|
|
21
21
|
import asyncio
|
|
22
22
|
import json
|
|
23
23
|
import logging
|
|
24
|
+
import sys
|
|
24
25
|
from enum import IntEnum, StrEnum
|
|
25
26
|
from importlib.metadata import PackageNotFoundError, version
|
|
26
27
|
from pathlib import Path
|
|
@@ -44,7 +45,14 @@ from margin_core.reporting import to_json, to_markdown
|
|
|
44
45
|
from rich.console import Console
|
|
45
46
|
|
|
46
47
|
from margin_cli import __version__
|
|
47
|
-
from margin_cli.execution import
|
|
48
|
+
from margin_cli.execution import (
|
|
49
|
+
ExplicitLLMError,
|
|
50
|
+
ProgressDisplay,
|
|
51
|
+
TerminalQuestions,
|
|
52
|
+
escape,
|
|
53
|
+
execute_cancellable,
|
|
54
|
+
make_llm,
|
|
55
|
+
)
|
|
48
56
|
from margin_cli.render import agents_table, fields_table, input_fields
|
|
49
57
|
|
|
50
58
|
|
|
@@ -249,8 +257,13 @@ def run_agent(
|
|
|
249
257
|
fail(str(exc), ExitCode.USAGE)
|
|
250
258
|
|
|
251
259
|
agent = agent_cls(llm=llm)
|
|
252
|
-
|
|
253
|
-
|
|
260
|
+
display = ProgressDisplay(stderr, agent_cls.name, enabled=not quiet)
|
|
261
|
+
# Questions are asked only when someone is at the terminal; otherwise they take their
|
|
262
|
+
# defaults, and the report marks those answers as not confirmed.
|
|
263
|
+
interactive = sys.stdin is not None and sys.stdin.isatty() and stderr.is_terminal
|
|
264
|
+
with display as on_progress:
|
|
265
|
+
responder = TerminalQuestions(stderr, display) if interactive else None
|
|
266
|
+
ctx = RunContext(progress=on_progress, max_cost_usd=budget, responder=responder)
|
|
254
267
|
try:
|
|
255
268
|
result = asyncio.run(execute_cancellable(agent, parsed, ctx))
|
|
256
269
|
except KeyboardInterrupt: # second Ctrl+C: stop immediately
|
|
@@ -267,9 +280,9 @@ def run_agent(
|
|
|
267
280
|
else:
|
|
268
281
|
typer.echo(report, nl=False)
|
|
269
282
|
for warning in result.warnings:
|
|
270
|
-
stderr.print(f"[yellow]Warning:[/] {warning}", highlight=False)
|
|
283
|
+
stderr.print(f"[yellow]Warning:[/] {escape(warning)}", highlight=False)
|
|
271
284
|
if result.status == "error":
|
|
272
|
-
stderr.print(f"[bold red]Run failed:[/] {result.error}", highlight=False)
|
|
285
|
+
stderr.print(f"[bold red]Run failed:[/] {escape(result.error or '')}", highlight=False)
|
|
273
286
|
else:
|
|
274
287
|
stderr.print("[yellow]Cancelled.[/]")
|
|
275
288
|
raise typer.Exit(int(_exit_code(result, cancelled, strict)))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: margin-cli
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: The `margin` command: list, inspect and run margin agents from the terminal.
|
|
5
5
|
Project-URL: Homepage, https://github.com/Waddah0-0/margin
|
|
6
6
|
Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/packages/cli
|
|
@@ -19,7 +19,7 @@ Classifier: Programming Language :: Python :: 3.11
|
|
|
19
19
|
Classifier: Programming Language :: Python :: 3.12
|
|
20
20
|
Classifier: Typing :: Typed
|
|
21
21
|
Requires-Python: >=3.11
|
|
22
|
-
Requires-Dist: margin-core<0.2,>=0.1.
|
|
22
|
+
Requires-Dist: margin-core<0.2,>=0.1.3
|
|
23
23
|
Requires-Dist: rich>=13.7.0
|
|
24
24
|
Requires-Dist: typer>=0.12.0
|
|
25
25
|
Description-Content-Type: text/markdown
|
|
@@ -76,7 +76,7 @@ Giving the main field both ways, positionally and with `--set`, is an error.
|
|
|
76
76
|
| `--strict` | Treat a partial result as a failure (exit code 4). |
|
|
77
77
|
|
|
78
78
|
The model comes from your settings (environment variables, settings saved in the web UI, or
|
|
79
|
-
|
|
79
|
+
the file named by `MARGIN_ENV_FILE`), but nothing talks to a model unless the agent needs one. Agents that don't use a
|
|
80
80
|
model work even with no model server running. If you pass `--provider` or `--model`, that
|
|
81
81
|
choice is checked before the run starts.
|
|
82
82
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
margin_cli/__init__.py,sha256=7uBnHZScIUiEZtPduIeUmYTZxTTEEzVwRREF2cRF7LY,57
|
|
2
|
+
margin_cli/execution.py,sha256=0grI8Yu6n0BMx7N6mmekQg-aL0KN4kdcjPp71DqO8F8,10524
|
|
3
|
+
margin_cli/main.py,sha256=e9jaoXvTgeiMoyn8tqv_4eCqGFJd7Th24neXprbzbwk,10108
|
|
4
|
+
margin_cli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
|
|
5
|
+
margin_cli/render.py,sha256=Ufd2zUwhR_TMDUsMfz7yv5VTfz96Ox4noVmKHp3ZmJw,2697
|
|
6
|
+
margin_cli-0.1.2.dist-info/METADATA,sha256=9g50LSOFxCAobowTNNl7qDK1fizuMwoIvTTmMcPSi6w,4092
|
|
7
|
+
margin_cli-0.1.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
margin_cli-0.1.2.dist-info/entry_points.txt,sha256=cVKA3g5oAcVLuozKqPrhzxsTQI3v0eNoA_lAIUbpnNA,47
|
|
9
|
+
margin_cli-0.1.2.dist-info/licenses/LICENSE,sha256=7dCPJ4m91LD52BnTk6tiuMOiQU5i6aoIfpSzGgb9mVY,1076
|
|
10
|
+
margin_cli-0.1.2.dist-info/RECORD,,
|
|
@@ -1,10 +0,0 @@
|
|
|
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,,
|
|
File without changes
|
|
File without changes
|