margin-cli 0.1.0__tar.gz → 0.1.1__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.
- {margin_cli-0.1.0 → margin_cli-0.1.1}/.gitignore +2 -0
- {margin_cli-0.1.0 → margin_cli-0.1.1}/CHANGELOG.md +7 -0
- {margin_cli-0.1.0 → margin_cli-0.1.1}/PKG-INFO +2 -2
- {margin_cli-0.1.0 → margin_cli-0.1.1}/pyproject.toml +2 -2
- {margin_cli-0.1.0 → margin_cli-0.1.1}/src/margin_cli/__init__.py +1 -1
- margin_cli-0.1.1/src/margin_cli/execution.py +269 -0
- {margin_cli-0.1.0 → margin_cli-0.1.1}/src/margin_cli/main.py +15 -3
- {margin_cli-0.1.0 → margin_cli-0.1.1}/tests/test_cli.py +76 -2
- margin_cli-0.1.0/src/margin_cli/execution.py +0 -98
- {margin_cli-0.1.0 → margin_cli-0.1.1}/LICENSE +0 -0
- {margin_cli-0.1.0 → margin_cli-0.1.1}/README.md +0 -0
- {margin_cli-0.1.0 → margin_cli-0.1.1}/src/margin_cli/py.typed +0 -0
- {margin_cli-0.1.0 → margin_cli-0.1.1}/src/margin_cli/render.py +0 -0
|
@@ -75,6 +75,8 @@ tmp/
|
|
|
75
75
|
|
|
76
76
|
# Private planning notes (kept locally, not published)
|
|
77
77
|
PLAN.md
|
|
78
|
+
# notes for Claude Code sessions; a CLAUDE.md in the repo is one of the detector's markers
|
|
79
|
+
CLAUDE.md
|
|
78
80
|
|
|
79
81
|
# the web UI bundled into margin-api at release time (scripts/build_release.py)
|
|
80
82
|
packages/api/src/margin_api/ui/
|
|
@@ -4,6 +4,13 @@ All notable changes to this package are documented here. The format follows
|
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
|
5
5
|
[Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## [0.1.1] - 2026-10-29
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- `margin run` asks an agent's questions in the terminal, on stderr, so the report on stdout
|
|
11
|
+
stays clean. Ctrl+C still cancels while a question is open. When input or stderr is not a
|
|
12
|
+
terminal, questions take their defaults and the report marks them as not confirmed.
|
|
13
|
+
|
|
7
14
|
## [0.1.0] - 2026-10-21
|
|
8
15
|
|
|
9
16
|
### Added
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: margin-cli
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.1
|
|
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.2
|
|
23
23
|
Requires-Dist: rich>=13.7.0
|
|
24
24
|
Requires-Dist: typer>=0.12.0
|
|
25
25
|
Description-Content-Type: text/markdown
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "margin-cli"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.1"
|
|
4
4
|
description = "The `margin` command: list, inspect and run margin agents from the terminal."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
@@ -19,7 +19,7 @@ classifiers = [
|
|
|
19
19
|
"Environment :: Console",
|
|
20
20
|
]
|
|
21
21
|
dependencies = [
|
|
22
|
-
"margin-core>=0.1.
|
|
22
|
+
"margin-core>=0.1.2,<0.2", # 0.1.2: questions (ctx.ask)
|
|
23
23
|
"typer>=0.12.0",
|
|
24
24
|
"rich>=13.7.0",
|
|
25
25
|
]
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""Running an agent from the CLI: LLM setup, progress, questions and Ctrl+C handling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Callable, Iterator
|
|
10
|
+
from typing import IO, Any
|
|
11
|
+
|
|
12
|
+
from margin_core import (
|
|
13
|
+
AgentResult,
|
|
14
|
+
BaseAgent,
|
|
15
|
+
NoAnswerError,
|
|
16
|
+
ProgressEvent,
|
|
17
|
+
Question,
|
|
18
|
+
QuestionBatch,
|
|
19
|
+
RunContext,
|
|
20
|
+
)
|
|
21
|
+
from margin_core.config import Settings
|
|
22
|
+
from margin_core.errors import LLMError
|
|
23
|
+
from margin_core.llm import LLMClient, create_llm
|
|
24
|
+
from pydantic import BaseModel
|
|
25
|
+
from rich.console import Console
|
|
26
|
+
from rich.markup import escape
|
|
27
|
+
|
|
28
|
+
CANCEL_GRACE_S = 5.0
|
|
29
|
+
"""How long a cancelled agent gets to stop on its own before its task is cancelled."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ExplicitLLMError(Exception):
|
|
33
|
+
"""The user asked for a specific provider or model, and it cannot be set up."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def make_llm(
|
|
37
|
+
provider: str | None, model: str | None, max_cost_usd: float, settings: Settings
|
|
38
|
+
) -> LLMClient | None:
|
|
39
|
+
"""Create the LLM client for a run.
|
|
40
|
+
|
|
41
|
+
Creating a client never contacts the server, so the default (local) client is always
|
|
42
|
+
created and only used if the agent asks for it. If the default provider cannot be set
|
|
43
|
+
up (e.g. a hosted provider without an API key), the run continues without an LLM and
|
|
44
|
+
agents that need one fail with a clear error. If the user chose ``--provider`` or
|
|
45
|
+
``--model`` explicitly, any problem is reported straight away.
|
|
46
|
+
"""
|
|
47
|
+
try:
|
|
48
|
+
return create_llm(provider, model, max_cost_usd=max_cost_usd, settings=settings)
|
|
49
|
+
except LLMError as exc:
|
|
50
|
+
if provider is not None or model is not None:
|
|
51
|
+
raise ExplicitLLMError(str(exc)) from exc
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def execute_cancellable(
|
|
56
|
+
agent: BaseAgent,
|
|
57
|
+
parsed_input: BaseModel,
|
|
58
|
+
ctx: RunContext,
|
|
59
|
+
*,
|
|
60
|
+
grace_s: float = CANCEL_GRACE_S,
|
|
61
|
+
) -> AgentResult | None:
|
|
62
|
+
"""Run the agent; if this task is cancelled (Ctrl+C), cancel cooperatively.
|
|
63
|
+
|
|
64
|
+
The agent gets ``grace_s`` seconds to notice the cancellation token and return its own
|
|
65
|
+
result. After that its task is cancelled and ``None`` is returned.
|
|
66
|
+
"""
|
|
67
|
+
task = asyncio.ensure_future(agent.execute(parsed_input, ctx))
|
|
68
|
+
try:
|
|
69
|
+
return await asyncio.shield(task)
|
|
70
|
+
except asyncio.CancelledError:
|
|
71
|
+
current = asyncio.current_task()
|
|
72
|
+
if current is not None:
|
|
73
|
+
current.uncancel() # we handle the cancellation ourselves
|
|
74
|
+
ctx.cancel_token.cancel()
|
|
75
|
+
try:
|
|
76
|
+
return await asyncio.wait_for(asyncio.shield(task), timeout=grace_s)
|
|
77
|
+
except (TimeoutError, asyncio.CancelledError):
|
|
78
|
+
task.cancel()
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class ProgressDisplay:
|
|
83
|
+
"""A one-line spinner on stderr, driven by the agent's progress events."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, console: Console, agent_name: str, enabled: bool) -> None:
|
|
86
|
+
self._console = console
|
|
87
|
+
self._agent_name = agent_name
|
|
88
|
+
self._enabled = enabled and console.is_terminal
|
|
89
|
+
self._status: Any = None
|
|
90
|
+
|
|
91
|
+
def __enter__(self) -> Callable[[ProgressEvent], None] | None:
|
|
92
|
+
if not self._enabled:
|
|
93
|
+
return None
|
|
94
|
+
self._status = self._console.status(f"{self._agent_name}: starting")
|
|
95
|
+
self._status.__enter__()
|
|
96
|
+
return self.update
|
|
97
|
+
|
|
98
|
+
def update(self, event: ProgressEvent) -> None:
|
|
99
|
+
text = f"{self._agent_name}: {event.stage}"
|
|
100
|
+
if event.message:
|
|
101
|
+
text += f" - {event.message}"
|
|
102
|
+
if event.fraction is not None:
|
|
103
|
+
text += f" ({event.fraction:.0%})"
|
|
104
|
+
if self._status is not None:
|
|
105
|
+
self._status.update(text)
|
|
106
|
+
|
|
107
|
+
def __exit__(self, *exc: object) -> None:
|
|
108
|
+
if self._status is not None:
|
|
109
|
+
self._status.__exit__(None, None, None)
|
|
110
|
+
self._status = None
|
|
111
|
+
|
|
112
|
+
@contextlib.contextmanager
|
|
113
|
+
def paused(self) -> Iterator[None]:
|
|
114
|
+
"""Hide the spinner while something else uses the terminal."""
|
|
115
|
+
status = self._status
|
|
116
|
+
if status is not None:
|
|
117
|
+
status.stop()
|
|
118
|
+
try:
|
|
119
|
+
yield
|
|
120
|
+
finally:
|
|
121
|
+
if status is not None and self._status is status:
|
|
122
|
+
status.start()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class TerminalQuestions:
|
|
126
|
+
"""Answers an agent's questions by asking in the terminal.
|
|
127
|
+
|
|
128
|
+
Prompts go to stderr, so stdout is still only the report. Lines are read on a daemon
|
|
129
|
+
thread, so Ctrl+C cancels the run even while a prompt is waiting.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
console: Console,
|
|
135
|
+
display: ProgressDisplay | None = None,
|
|
136
|
+
stream: IO[str] | None = None,
|
|
137
|
+
) -> None:
|
|
138
|
+
self._console = console
|
|
139
|
+
self._display = display
|
|
140
|
+
self._stream = stream
|
|
141
|
+
|
|
142
|
+
async def __call__(self, batch: QuestionBatch) -> dict[str, Any]:
|
|
143
|
+
loop = asyncio.get_running_loop()
|
|
144
|
+
future: asyncio.Future[dict[str, Any]] = loop.create_future()
|
|
145
|
+
|
|
146
|
+
def settle(answers: dict[str, Any] | None, error: BaseException | None) -> None:
|
|
147
|
+
if future.done():
|
|
148
|
+
return
|
|
149
|
+
if error is not None:
|
|
150
|
+
future.set_exception(error)
|
|
151
|
+
else:
|
|
152
|
+
future.set_result(answers or {})
|
|
153
|
+
|
|
154
|
+
def work() -> None:
|
|
155
|
+
answers: dict[str, Any] | None = None
|
|
156
|
+
error: BaseException | None = None
|
|
157
|
+
try:
|
|
158
|
+
answers = self.ask_batch(batch)
|
|
159
|
+
except BaseException as exc: # noqa: BLE001 - handed to the run
|
|
160
|
+
error = exc
|
|
161
|
+
with contextlib.suppress(RuntimeError): # the run ended and its loop is gone
|
|
162
|
+
loop.call_soon_threadsafe(settle, answers, error)
|
|
163
|
+
|
|
164
|
+
paused = self._display.paused() if self._display else contextlib.nullcontext()
|
|
165
|
+
with paused:
|
|
166
|
+
threading.Thread(target=work, name="margin-questions", daemon=True).start()
|
|
167
|
+
return await future
|
|
168
|
+
|
|
169
|
+
def ask_batch(self, batch: QuestionBatch) -> dict[str, Any]:
|
|
170
|
+
"""Ask every question in turn (blocking). Raises :class:`NoAnswerError` at end of input."""
|
|
171
|
+
out = self._console
|
|
172
|
+
out.print()
|
|
173
|
+
out.print(f"[bold]{escape(batch.title)}[/]", highlight=False)
|
|
174
|
+
if batch.detail:
|
|
175
|
+
out.print(escape(batch.detail), highlight=False)
|
|
176
|
+
answers: dict[str, Any] = {}
|
|
177
|
+
section: str | None = None
|
|
178
|
+
for question in batch.questions:
|
|
179
|
+
if question.section and question.section != section:
|
|
180
|
+
section = question.section
|
|
181
|
+
out.print(f"\n[bold underline]{escape(section)}[/]", highlight=False)
|
|
182
|
+
try:
|
|
183
|
+
answers[question.id] = self._ask(question)
|
|
184
|
+
except EOFError:
|
|
185
|
+
raise NoAnswerError("The input ended before the questions were answered.") from None
|
|
186
|
+
out.print()
|
|
187
|
+
return answers
|
|
188
|
+
|
|
189
|
+
def _ask(self, question: Question) -> Any:
|
|
190
|
+
out = self._console
|
|
191
|
+
out.print(f"\n[bold]{escape(question.prompt)}[/]", highlight=False)
|
|
192
|
+
if question.detail:
|
|
193
|
+
out.print(f" [dim]{escape(question.detail)}[/]", highlight=False)
|
|
194
|
+
for ev in question.evidence:
|
|
195
|
+
where = f"{ev.location}: " if ev.location else ""
|
|
196
|
+
out.print(
|
|
197
|
+
f" [dim]· {escape(ev.kind)}: {escape(where + ev.detail)}[/]", highlight=False
|
|
198
|
+
)
|
|
199
|
+
suggested = question.default if isinstance(question.default, list) else [question.default]
|
|
200
|
+
for n, choice in enumerate(question.choices, 1):
|
|
201
|
+
line = f" {n}) {escape(choice.label)}"
|
|
202
|
+
if choice.detail:
|
|
203
|
+
line += f" [dim]- {escape(choice.detail)}[/]"
|
|
204
|
+
if any(choice.value == s and type(choice.value) is type(s) for s in suggested):
|
|
205
|
+
line += " [cyan](suggested)[/]"
|
|
206
|
+
out.print(line, highlight=False)
|
|
207
|
+
|
|
208
|
+
while True:
|
|
209
|
+
raw = self._read(self._prompt(question)).strip()
|
|
210
|
+
try:
|
|
211
|
+
value = question.default if not raw else _parse(question, raw)
|
|
212
|
+
return question.check(value)
|
|
213
|
+
except ValueError as exc:
|
|
214
|
+
out.print(f" [red]{escape(str(exc))}[/]", highlight=False)
|
|
215
|
+
|
|
216
|
+
def _prompt(self, question: Question) -> str:
|
|
217
|
+
if question.kind == "text":
|
|
218
|
+
hint = "Your answer"
|
|
219
|
+
elif question.kind == "multi_choice":
|
|
220
|
+
hint = "Numbers, separated by commas" + ("" if question.required else ", or none")
|
|
221
|
+
else:
|
|
222
|
+
hint = f"Choose 1-{len(question.choices)}"
|
|
223
|
+
if question.allow_other:
|
|
224
|
+
hint += ", or type your own"
|
|
225
|
+
if question.default not in (None, []):
|
|
226
|
+
default = question.default if isinstance(question.default, list) else [question.default]
|
|
227
|
+
numbers = [
|
|
228
|
+
str(n)
|
|
229
|
+
for n, c in enumerate(question.choices, 1)
|
|
230
|
+
if any(c.value == d and type(c.value) is type(d) for d in default)
|
|
231
|
+
]
|
|
232
|
+
shown = ",".join(numbers) if question.choices and numbers else str(question.default)
|
|
233
|
+
hint += f" [{shown}]"
|
|
234
|
+
elif not question.required:
|
|
235
|
+
hint += " (optional)"
|
|
236
|
+
return f"[cyan]{escape(hint)}:[/] "
|
|
237
|
+
|
|
238
|
+
def _read(self, prompt: str) -> str:
|
|
239
|
+
self._console.print(prompt, end="", highlight=False)
|
|
240
|
+
line = (self._stream or sys.stdin).readline()
|
|
241
|
+
if not line:
|
|
242
|
+
raise EOFError
|
|
243
|
+
return line.rstrip("\r\n")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _parse(question: Question, raw: str) -> Any:
|
|
247
|
+
"""Turn what was typed into a value for ``question.check``."""
|
|
248
|
+
if question.kind == "text":
|
|
249
|
+
return raw
|
|
250
|
+
if question.kind == "multi_choice":
|
|
251
|
+
if raw.lower() in {"none", "-"}:
|
|
252
|
+
return []
|
|
253
|
+
return [_pick(question, part.strip()) for part in raw.split(",") if part.strip()]
|
|
254
|
+
try:
|
|
255
|
+
return _pick(question, raw)
|
|
256
|
+
except ValueError:
|
|
257
|
+
if question.allow_other:
|
|
258
|
+
return raw
|
|
259
|
+
raise
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _pick(question: Question, typed: str) -> Any:
|
|
263
|
+
"""The value of the choice ``typed`` names: by number, label or value."""
|
|
264
|
+
if typed.isdigit() and 1 <= int(typed) <= len(question.choices):
|
|
265
|
+
return question.choices[int(typed) - 1].value
|
|
266
|
+
for choice in question.choices:
|
|
267
|
+
if typed.casefold() in {choice.label.casefold(), str(choice.value).casefold()}:
|
|
268
|
+
return choice.value
|
|
269
|
+
raise ValueError(f"Type a number from 1 to {len(question.choices)}")
|
|
@@ -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,13 @@ 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
|
+
execute_cancellable,
|
|
53
|
+
make_llm,
|
|
54
|
+
)
|
|
48
55
|
from margin_cli.render import agents_table, fields_table, input_fields
|
|
49
56
|
|
|
50
57
|
|
|
@@ -249,8 +256,13 @@ def run_agent(
|
|
|
249
256
|
fail(str(exc), ExitCode.USAGE)
|
|
250
257
|
|
|
251
258
|
agent = agent_cls(llm=llm)
|
|
252
|
-
|
|
253
|
-
|
|
259
|
+
display = ProgressDisplay(stderr, agent_cls.name, enabled=not quiet)
|
|
260
|
+
# Questions are asked only when someone is at the terminal; otherwise they take their
|
|
261
|
+
# defaults, and the report marks those answers as not confirmed.
|
|
262
|
+
interactive = sys.stdin is not None and sys.stdin.isatty() and stderr.is_terminal
|
|
263
|
+
with display as on_progress:
|
|
264
|
+
responder = TerminalQuestions(stderr, display) if interactive else None
|
|
265
|
+
ctx = RunContext(progress=on_progress, max_cost_usd=budget, responder=responder)
|
|
254
266
|
try:
|
|
255
267
|
result = asyncio.run(execute_cancellable(agent, parsed, ctx))
|
|
256
268
|
except KeyboardInterrupt: # second Ctrl+C: stop immediately
|
|
@@ -14,14 +14,19 @@ from pathlib import Path
|
|
|
14
14
|
|
|
15
15
|
import pytest
|
|
16
16
|
from echo_agent import EchoAgent
|
|
17
|
+
from margin_cli import __version__
|
|
17
18
|
from margin_cli import main as cli
|
|
18
|
-
from margin_cli.execution import ProgressDisplay, execute_cancellable
|
|
19
|
+
from margin_cli.execution import ProgressDisplay, TerminalQuestions, execute_cancellable
|
|
19
20
|
from margin_core import (
|
|
20
21
|
AgentInput,
|
|
21
22
|
AgentRegistry,
|
|
22
23
|
AgentResult,
|
|
23
24
|
BaseAgent,
|
|
25
|
+
Choice,
|
|
26
|
+
NoAnswerError,
|
|
24
27
|
ProgressEvent,
|
|
28
|
+
Question,
|
|
29
|
+
QuestionBatch,
|
|
25
30
|
RunContext,
|
|
26
31
|
)
|
|
27
32
|
from margin_core.models import ResultStatus
|
|
@@ -107,7 +112,7 @@ def invoke(*args: str) -> tuple[int, str, str]:
|
|
|
107
112
|
|
|
108
113
|
def test_version() -> None:
|
|
109
114
|
code, out, _ = invoke("version")
|
|
110
|
-
assert code == 0 and out.startswith("margin-cli
|
|
115
|
+
assert code == 0 and out.startswith(f"margin-cli v{__version__} (core v")
|
|
111
116
|
|
|
112
117
|
|
|
113
118
|
def test_list_table_and_load_errors() -> None:
|
|
@@ -334,6 +339,75 @@ def test_progress_display_off_when_not_a_terminal() -> None:
|
|
|
334
339
|
assert callback is None
|
|
335
340
|
|
|
336
341
|
|
|
342
|
+
# ---- run: questions ---------------------------------------------------------------------
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def test_without_a_terminal_questions_take_their_defaults() -> None:
|
|
346
|
+
code, out, err = invoke("run", "echo", "hi", "--set", "ask=true")
|
|
347
|
+
assert code == 0 and "hi" in out
|
|
348
|
+
assert "| How should the message be echoed? | As typed | default, not confirmed |" in out
|
|
349
|
+
assert "Not confirmed: How should the message be echoed? Assumed: As typed." in err
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def test_answers_can_be_given_up_front() -> None:
|
|
353
|
+
answers = 'answers={"style": "capitals"}'
|
|
354
|
+
code, out, err = invoke("run", "echo", "hi", "-s", "ask=true", "-s", answers, "-f", "json")
|
|
355
|
+
result = json.loads(out)
|
|
356
|
+
assert code == 0 and result["data"]["echoed"] == "HI"
|
|
357
|
+
assert result["metadata"]["answers"][0]["source"] == "preset"
|
|
358
|
+
assert err == ""
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
QUESTIONS = QuestionBatch(
|
|
362
|
+
title="Check the data",
|
|
363
|
+
questions=[
|
|
364
|
+
Question(
|
|
365
|
+
id="format", prompt="Date format?", default="mdy",
|
|
366
|
+
choices=[Choice(value="mdy", label="MM/DD"), Choice(value="dmy", label="DD/MM")],
|
|
367
|
+
),
|
|
368
|
+
Question(
|
|
369
|
+
id="columns", prompt="Columns?", kind="multi_choice", section="Columns",
|
|
370
|
+
choices=[Choice(value=c, label=c) for c in ("revenue", "cost", "units")],
|
|
371
|
+
),
|
|
372
|
+
Question(id="grain", prompt="One row is?", allow_other=True,
|
|
373
|
+
choices=[Choice(value="order", label="An order")]),
|
|
374
|
+
Question(id="note", prompt="Anything else?", kind="text", required=False),
|
|
375
|
+
],
|
|
376
|
+
) # fmt: skip
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def ask_in_terminal(typed: str) -> tuple[dict[str, object], str]:
|
|
380
|
+
console = Console(file=io.StringIO(), force_terminal=False, width=200)
|
|
381
|
+
asker = TerminalQuestions(console, stream=io.StringIO(typed))
|
|
382
|
+
answers = asyncio.run(asker(QUESTIONS))
|
|
383
|
+
return answers, console.file.getvalue() # type: ignore[attr-defined]
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def test_terminal_questions_accept_numbers_labels_and_defaults() -> None:
|
|
387
|
+
answers, shown = ask_in_terminal("\n3,revenue\norder line\n\n")
|
|
388
|
+
assert answers == {
|
|
389
|
+
"format": "mdy", # Enter took the suggestion
|
|
390
|
+
"columns": ["revenue", "units"],
|
|
391
|
+
"grain": "order line", # typed text, allowed by allow_other
|
|
392
|
+
"note": None,
|
|
393
|
+
}
|
|
394
|
+
assert "Check the data" in shown and "Columns" in shown
|
|
395
|
+
assert "1) MM/DD (suggested)" in shown
|
|
396
|
+
assert "Choose 1-2 [1]:" in shown and "(optional):" in shown
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def test_terminal_questions_ask_again_after_a_bad_answer() -> None:
|
|
400
|
+
answers, shown = ask_in_terminal("7\n2\n\n1\n1\nnote\n")
|
|
401
|
+
assert answers["format"] == "dmy" and answers["columns"] == ["revenue"]
|
|
402
|
+
assert "Type a number from 1 to 2" in shown
|
|
403
|
+
assert "pick at least one" in shown # an empty answer to a required list
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def test_terminal_questions_stop_when_input_ends() -> None:
|
|
407
|
+
with pytest.raises(NoAnswerError, match="input ended"):
|
|
408
|
+
ask_in_terminal("1\n")
|
|
409
|
+
|
|
410
|
+
|
|
337
411
|
SIGINT_SCRIPT = """
|
|
338
412
|
import asyncio, sys
|
|
339
413
|
from margin_cli import main as cli
|
|
@@ -1,98 +0,0 @@
|
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|