margin-cli 0.1.1__tar.gz → 0.1.3__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.
@@ -80,3 +80,6 @@ CLAUDE.md
80
80
 
81
81
  # the web UI bundled into margin-api at release time (scripts/build_release.py)
82
82
  packages/api/src/margin_api/ui/
83
+
84
+ # local agent plugins and state
85
+ .agents/
@@ -4,6 +4,18 @@ 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.3] - 2026-11-20
8
+
9
+ ### Fixed
10
+ - On Windows, `margin run` no longer crashes with `UnicodeEncodeError` when the report is piped
11
+ or redirected and contains characters such as `→`. The report is written as UTF-8.
12
+
13
+ ## [0.1.2] - 2026-11-02
14
+
15
+ ### Security
16
+ - Warnings, errors and progress messages can no longer carry control characters or Rich markup
17
+ from a repository or a data file, which could rewrite what a terminal shows.
18
+
7
19
  ## [0.1.1] - 2026-10-29
8
20
 
9
21
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: margin-cli
3
- Version: 0.1.1
3
+ Version: 0.1.3
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.2
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.1"
3
+ version = "0.1.3"
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.2,<0.2", # 0.1.2: questions (ctx.ask)
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.1"
3
+ __version__ = "0.1.3"
@@ -21,14 +21,20 @@ from margin_core import (
21
21
  from margin_core.config import Settings
22
22
  from margin_core.errors import LLMError
23
23
  from margin_core.llm import LLMClient, create_llm
24
+ from margin_core.reporting import strip_control
24
25
  from pydantic import BaseModel
25
26
  from rich.console import Console
26
- from rich.markup import escape
27
+ from rich.markup import escape as escape_markup
27
28
 
28
29
  CANCEL_GRACE_S = 5.0
29
30
  """How long a cancelled agent gets to stop on its own before its task is cancelled."""
30
31
 
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
+
32
38
  class ExplicitLLMError(Exception):
33
39
  """The user asked for a specific provider or model, and it cannot be set up."""
34
40
 
@@ -98,7 +104,7 @@ class ProgressDisplay:
98
104
  def update(self, event: ProgressEvent) -> None:
99
105
  text = f"{self._agent_name}: {event.stage}"
100
106
  if event.message:
101
- text += f" - {event.message}"
107
+ text += f" - {escape(event.message)}"
102
108
  if event.fraction is not None:
103
109
  text += f" ({event.fraction:.0%})"
104
110
  if self._status is not None:
@@ -1,4 +1,4 @@
1
- """The ``agents`` command: list, inspect and run installed agents.
1
+ """The ``margin`` command: list, inspect and run installed agents.
2
2
 
3
3
  Output conventions: the report (or the ``--json`` listing) goes to stdout and nothing else
4
4
  does, so ``margin run ... --format json > report.json`` always produces valid JSON. Progress,
@@ -19,6 +19,7 @@ Exit codes:
19
19
  from __future__ import annotations
20
20
 
21
21
  import asyncio
22
+ import contextlib
22
23
  import json
23
24
  import logging
24
25
  import sys
@@ -49,6 +50,7 @@ from margin_cli.execution import (
49
50
  ExplicitLLMError,
50
51
  ProgressDisplay,
51
52
  TerminalQuestions,
53
+ escape,
52
54
  execute_cancellable,
53
55
  make_llm,
54
56
  )
@@ -189,6 +191,27 @@ def _render(result: AgentResult, fmt: ReportFormat) -> str:
189
191
  return to_json(result) + "\n" if fmt is ReportFormat.json else to_markdown(result)
190
192
 
191
193
 
194
+ def _write_stdout(text: str) -> None:
195
+ """Write ``text`` to stdout as UTF-8, even when redirected with cp1252 on Windows."""
196
+ stream = sys.stdout
197
+ if stream is None:
198
+ return
199
+ reconfigure = getattr(stream, "reconfigure", None)
200
+ if callable(reconfigure):
201
+ with contextlib.suppress(OSError, ValueError, AttributeError):
202
+ reconfigure(encoding="utf-8", errors="replace")
203
+ try:
204
+ stream.write(text)
205
+ stream.flush()
206
+ except UnicodeEncodeError:
207
+ buffer = getattr(stream, "buffer", None)
208
+ if buffer is None:
209
+ raise
210
+ stream.flush()
211
+ buffer.write(text.encode("utf-8", errors="replace"))
212
+ buffer.flush()
213
+
214
+
192
215
  def _exit_code(result: AgentResult | None, cancelled: bool, strict: bool) -> ExitCode:
193
216
  if cancelled or result is None:
194
217
  return ExitCode.CANCELLED
@@ -277,11 +300,11 @@ def run_agent(
277
300
  out.write_text(report, encoding="utf-8")
278
301
  stderr.print(f"Report written to {out}", highlight=False)
279
302
  else:
280
- typer.echo(report, nl=False)
303
+ _write_stdout(report)
281
304
  for warning in result.warnings:
282
- stderr.print(f"[yellow]Warning:[/] {warning}", highlight=False)
305
+ stderr.print(f"[yellow]Warning:[/] {escape(warning)}", highlight=False)
283
306
  if result.status == "error":
284
- stderr.print(f"[bold red]Run failed:[/] {result.error}", highlight=False)
307
+ stderr.print(f"[bold red]Run failed:[/] {escape(result.error or '')}", highlight=False)
285
308
  else:
286
309
  stderr.print("[yellow]Cancelled.[/]")
287
310
  raise typer.Exit(int(_exit_code(result, cancelled, strict)))
@@ -244,6 +244,51 @@ def test_partial_exits_0_or_4_with_strict(folder: Path) -> None:
244
244
  assert invoke("run", "lister", str(folder), "--set", "mode=partial", "--strict")[0] == 4
245
245
 
246
246
 
247
+ def test_run_markdown_preserves_unicode_arrows_and_times() -> None:
248
+ code, out, err = invoke("run", "echo", "a \u2192 b \u00d7 c")
249
+ assert code == 0 and "a \u2192 b \u00d7 c" in out and err == ""
250
+
251
+
252
+ def test_write_stdout_handles_cp1252(monkeypatch: pytest.MonkeyPatch) -> None:
253
+ raw = io.BytesIO()
254
+ wrapper = io.TextIOWrapper(raw, encoding="cp1252", newline="\n")
255
+ try:
256
+ monkeypatch.setattr(sys, "stdout", wrapper)
257
+ cli._write_stdout("a \u2192 b \u00d7 c\n")
258
+ assert raw.getvalue().decode("utf-8") == "a \u2192 b \u00d7 c\n"
259
+ finally:
260
+ wrapper.detach()
261
+
262
+
263
+ def test_write_stdout_falls_back_to_buffer_when_reconfigure_fails(
264
+ monkeypatch: pytest.MonkeyPatch,
265
+ ) -> None:
266
+ raw = io.BytesIO()
267
+ wrapper = io.TextIOWrapper(raw, encoding="cp1252", newline="\n")
268
+
269
+ class NonReconfigurableStream:
270
+ def __init__(self, inner: io.TextIOWrapper) -> None:
271
+ self._inner = inner
272
+ self.buffer = inner.buffer
273
+
274
+ def reconfigure(self, **kwargs: object) -> None:
275
+ raise OSError("cannot reconfigure")
276
+
277
+ def write(self, text: str) -> int:
278
+ return self._inner.write(text)
279
+
280
+ def flush(self) -> None:
281
+ self._inner.flush()
282
+
283
+ try:
284
+ wrapper.write("prefix\n")
285
+ monkeypatch.setattr(sys, "stdout", NonReconfigurableStream(wrapper))
286
+ cli._write_stdout("a \u2192 b \u00d7 c\n")
287
+ assert raw.getvalue().decode("utf-8") == "prefix\na \u2192 b \u00d7 c\n"
288
+ finally:
289
+ wrapper.detach()
290
+
291
+
247
292
  # ---- run: LLM selection ---------------------------------------------------------------
248
293
 
249
294
 
@@ -452,3 +497,34 @@ def test_ctrl_c_cancels_and_exits_130() -> None:
452
497
  out, err = proc.communicate(timeout=30)
453
498
  assert proc.returncode == 130, err
454
499
  assert out == "" and "Cancelled" in err
500
+
501
+
502
+ CP1252_SCRIPT = """
503
+ import sys
504
+ from echo_agent import EchoAgent
505
+ from margin_cli import main as cli
506
+ from margin_core import AgentRegistry
507
+
508
+ assert (sys.stdout.encoding or "").lower() in {"cp1252", "windows-1252"}, sys.stdout.encoding
509
+ registry = AgentRegistry([])
510
+ registry.register(EchoAgent)
511
+ cli.get_registry = lambda: registry
512
+ cli.app(["run", "echo", "a \\u2192 b \\u00d7 c", "--quiet"])
513
+ """
514
+
515
+
516
+ def test_run_subprocess_cp1252_stdout_outputs_valid_utf8() -> None:
517
+ env = {**os.environ, "MARGIN_ENV_FILE": "", "PYTHONIOENCODING": "cp1252"}
518
+ env.pop("PYTHONUTF8", None)
519
+ proc = subprocess.run(
520
+ [sys.executable, "-c", CP1252_SCRIPT],
521
+ capture_output=True,
522
+ env=env,
523
+ timeout=30,
524
+ check=False,
525
+ )
526
+ assert proc.returncode == 0, proc.stderr.decode("utf-8", errors="replace")
527
+ assert proc.stderr == b""
528
+ text = proc.stdout.decode("utf-8")
529
+ assert "# echo report" in text
530
+ assert "a \u2192 b \u00d7 c" in text
File without changes