margin-cli 0.1.0__tar.gz → 0.1.2__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.
@@ -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/
@@ -0,0 +1,24 @@
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.2] - 2026-11-02
8
+
9
+ ### Security
10
+ - Warnings, errors and progress messages can no longer carry control characters or Rich markup
11
+ from a repository or a data file, which could rewrite what a terminal shows.
12
+
13
+ ## [0.1.1] - 2026-10-29
14
+
15
+ ### Added
16
+ - `margin run` asks an agent's questions in the terminal, on stderr, so the report on stdout
17
+ stays clean. Ctrl+C still cancels while a question is open. When input or stderr is not a
18
+ terminal, questions take their defaults and the report marks them as not confirmed.
19
+
20
+ ## [0.1.0] - 2026-10-21
21
+
22
+ ### Added
23
+ - `margin list`, `margin info` and `margin run`, with JSON or Markdown reports, progress on stderr, and documented exit codes.
24
+ - `--provider` and `--model` choose the model for one run.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: margin-cli
3
- Version: 0.1.0
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.0
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
- `.env`), but nothing talks to a model unless the agent needs one. Agents that don't use a
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
 
@@ -50,7 +50,7 @@ Giving the main field both ways, positionally and with `--set`, is an error.
50
50
  | `--strict` | Treat a partial result as a failure (exit code 4). |
51
51
 
52
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
53
+ the file named by `MARGIN_ENV_FILE`), but nothing talks to a model unless the agent needs one. Agents that don't use a
54
54
  model work even with no model server running. If you pass `--provider` or `--model`, that
55
55
  choice is checked before the run starts.
56
56
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "margin-cli"
3
- version = "0.1.0"
3
+ version = "0.1.2"
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.0,<0.2",
22
+ "margin-core>=0.1.3,<0.2", # 0.1.3: security fixes
23
23
  "typer>=0.12.0",
24
24
  "rich>=13.7.0",
25
25
  ]
@@ -1,3 +1,3 @@
1
1
  """CLI application for margin."""
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "0.1.2"
@@ -0,0 +1,275 @@
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 margin_core.reporting import strip_control
25
+ from pydantic import BaseModel
26
+ from rich.console import Console
27
+ from rich.markup import escape as escape_markup
28
+
29
+ CANCEL_GRACE_S = 5.0
30
+ """How long a cancelled agent gets to stop on its own before its task is cancelled."""
31
+
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
+
38
+ class ExplicitLLMError(Exception):
39
+ """The user asked for a specific provider or model, and it cannot be set up."""
40
+
41
+
42
+ def make_llm(
43
+ provider: str | None, model: str | None, max_cost_usd: float, settings: Settings
44
+ ) -> LLMClient | None:
45
+ """Create the LLM client for a run.
46
+
47
+ Creating a client never contacts the server, so the default (local) client is always
48
+ created and only used if the agent asks for it. If the default provider cannot be set
49
+ up (e.g. a hosted provider without an API key), the run continues without an LLM and
50
+ agents that need one fail with a clear error. If the user chose ``--provider`` or
51
+ ``--model`` explicitly, any problem is reported straight away.
52
+ """
53
+ try:
54
+ return create_llm(provider, model, max_cost_usd=max_cost_usd, settings=settings)
55
+ except LLMError as exc:
56
+ if provider is not None or model is not None:
57
+ raise ExplicitLLMError(str(exc)) from exc
58
+ return None
59
+
60
+
61
+ async def execute_cancellable(
62
+ agent: BaseAgent,
63
+ parsed_input: BaseModel,
64
+ ctx: RunContext,
65
+ *,
66
+ grace_s: float = CANCEL_GRACE_S,
67
+ ) -> AgentResult | None:
68
+ """Run the agent; if this task is cancelled (Ctrl+C), cancel cooperatively.
69
+
70
+ The agent gets ``grace_s`` seconds to notice the cancellation token and return its own
71
+ result. After that its task is cancelled and ``None`` is returned.
72
+ """
73
+ task = asyncio.ensure_future(agent.execute(parsed_input, ctx))
74
+ try:
75
+ return await asyncio.shield(task)
76
+ except asyncio.CancelledError:
77
+ current = asyncio.current_task()
78
+ if current is not None:
79
+ current.uncancel() # we handle the cancellation ourselves
80
+ ctx.cancel_token.cancel()
81
+ try:
82
+ return await asyncio.wait_for(asyncio.shield(task), timeout=grace_s)
83
+ except (TimeoutError, asyncio.CancelledError):
84
+ task.cancel()
85
+ return None
86
+
87
+
88
+ class ProgressDisplay:
89
+ """A one-line spinner on stderr, driven by the agent's progress events."""
90
+
91
+ def __init__(self, console: Console, agent_name: str, enabled: bool) -> None:
92
+ self._console = console
93
+ self._agent_name = agent_name
94
+ self._enabled = enabled and console.is_terminal
95
+ self._status: Any = None
96
+
97
+ def __enter__(self) -> Callable[[ProgressEvent], None] | None:
98
+ if not self._enabled:
99
+ return None
100
+ self._status = self._console.status(f"{self._agent_name}: starting")
101
+ self._status.__enter__()
102
+ return self.update
103
+
104
+ def update(self, event: ProgressEvent) -> None:
105
+ text = f"{self._agent_name}: {event.stage}"
106
+ if event.message:
107
+ text += f" - {escape(event.message)}"
108
+ if event.fraction is not None:
109
+ text += f" ({event.fraction:.0%})"
110
+ if self._status is not None:
111
+ self._status.update(text)
112
+
113
+ def __exit__(self, *exc: object) -> None:
114
+ if self._status is not None:
115
+ self._status.__exit__(None, None, None)
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)}")
@@ -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 ExplicitLLMError, ProgressDisplay, execute_cancellable, make_llm
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
- with ProgressDisplay(stderr, agent_cls.name, enabled=not quiet) as on_progress:
253
- ctx = RunContext(progress=on_progress, max_cost_usd=budget)
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)))
@@ -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 v0.1.0 (core v")
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,11 +0,0 @@
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.
@@ -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