coder-agent 0.1.0__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.
Files changed (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,138 @@
1
+ """Rule files: `.coderagent/rules.yaml` in the project and `~/.coderagent/rules.yaml` for the user.
2
+
3
+ Later rules win, so a user rule overrides a project rule with the same tool and pattern.
4
+ """
5
+
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import yaml
10
+
11
+ from coderagent.paths import config_home
12
+ from coderagent.tools.permissions import DECISIONS, Rule
13
+
14
+
15
+ class RuleError(ValueError):
16
+ """A rule file could not be parsed."""
17
+
18
+
19
+ def _scalar(node: yaml.ScalarNode) -> Any:
20
+ tag = node.tag
21
+ if tag == "tag:yaml.org,2002:int":
22
+ return int(node.value)
23
+ if tag == "tag:yaml.org,2002:float":
24
+ return float(node.value)
25
+ if tag == "tag:yaml.org,2002:bool":
26
+ return node.value.lower() in ("true", "yes", "on")
27
+ if tag == "tag:yaml.org,2002:null":
28
+ return None
29
+ return node.value
30
+
31
+
32
+ def _value(node: yaml.Node) -> Any:
33
+ if isinstance(node, yaml.ScalarNode):
34
+ return _scalar(node)
35
+ if isinstance(node, yaml.SequenceNode):
36
+ return [_value(item) for item in node.value]
37
+ if isinstance(node, yaml.MappingNode):
38
+ return {key.value: _value(value) for key, value in node.value}
39
+ return None
40
+
41
+
42
+ def _rule_from(node: yaml.Node, path: Path) -> Rule:
43
+ if not isinstance(node, yaml.MappingNode):
44
+ raise RuleError(f"{path}:{node.start_mark.line + 1}: each rule must be a mapping, got {type(node).__name__}")
45
+ data: dict[str, Any] = {}
46
+ lines: dict[str, int] = {}
47
+ for key, value in node.value:
48
+ data[key.value] = _value(value)
49
+ lines[key.value] = value.start_mark.line + 1
50
+ unknown = set(data) - {"tool", "pattern", "decision", "reason"}
51
+ if unknown:
52
+ name = sorted(unknown)[0]
53
+ raise RuleError(f"{path}:{lines[name]}: unknown rule keys: {', '.join(sorted(unknown))}")
54
+ decision = data.get("decision", "ask")
55
+ if decision not in DECISIONS:
56
+ line = lines.get("decision", node.start_mark.line + 1)
57
+ raise RuleError(f"{path}:{line}: invalid decision '{decision}', expected one of {', '.join(DECISIONS)}")
58
+ for key in ("tool", "pattern"):
59
+ if key in data and not isinstance(data[key], str):
60
+ raise RuleError(f"{path}:{lines[key]}: `{key}` must be a string")
61
+ return Rule(
62
+ tool=str(data.get("tool", "*")),
63
+ pattern=str(data.get("pattern", "*")),
64
+ decision=str(decision),
65
+ reason=str(data.get("reason", "")),
66
+ )
67
+
68
+
69
+ def load_rules_file(path: Path) -> list[Rule]:
70
+ """Parse one rule file. Raises `RuleError` with file and line number on bad input."""
71
+ text = path.read_text(encoding="utf-8")
72
+ try:
73
+ root = yaml.compose(text)
74
+ except yaml.YAMLError as error:
75
+ mark = getattr(error, "problem_mark", None)
76
+ line = mark.line + 1 if mark else 0
77
+ raise RuleError(f"{path}:{line}: invalid YAML: {error}") from error
78
+ if root is None:
79
+ return []
80
+ if not isinstance(root, yaml.MappingNode):
81
+ raise RuleError(f"{path}:1: the rule file must be a mapping with a `rules` key")
82
+ for key, value in root.value:
83
+ if key.value != "rules":
84
+ continue
85
+ if not isinstance(value, yaml.SequenceNode):
86
+ raise RuleError(f"{path}:{value.start_mark.line + 1}: `rules` must be a list")
87
+ return [_rule_from(item, path) for item in value.value]
88
+ return []
89
+
90
+
91
+ def load_rules(project_dir: Path, user_home: Path | None = None) -> list[Rule]:
92
+ """Project rules first, then user rules. Later entries win.
93
+
94
+ The rules of the project may only deny: a project cannot allow itself
95
+ something the user has to be asked for.
96
+ """
97
+ home = Path(user_home) if user_home else config_home()
98
+ rules: list[Rule] = []
99
+ project = Path(project_dir) / ".coderagent" / "rules.yaml"
100
+ if project.exists():
101
+ rules.extend(rule for rule in load_rules_file(project) if rule.decision == "deny")
102
+ user = home / "rules.yaml"
103
+ if user.exists():
104
+ rules.extend(load_rules_file(user))
105
+ return rules
106
+
107
+
108
+ def _document_of(path: Path) -> dict[str, Any]:
109
+ """The rule file as a mapping. A file that does not exist is an empty mapping."""
110
+ if not path.exists():
111
+ return {}
112
+ try:
113
+ document = yaml.safe_load(path.read_text(encoding="utf-8"))
114
+ except yaml.YAMLError as error:
115
+ raise RuleError(f"{path}: invalid YAML: {error}") from error
116
+ if document is None:
117
+ return {}
118
+ if not isinstance(document, dict):
119
+ raise RuleError(f"{path}: the rule file must be a mapping with a `rules` key")
120
+ return document
121
+
122
+
123
+ def add_rule(tool: str, pattern: str, decision: str = "allow", reason: str = "", user_home: Path | None = None) -> Path:
124
+ """Append a rule to the user-level rule file and read it back to confirm it landed."""
125
+ home = Path(user_home) if user_home else config_home()
126
+ home.mkdir(parents=True, exist_ok=True)
127
+ path = home / "rules.yaml"
128
+ document = _document_of(path)
129
+ rules = document.get("rules") or []
130
+ if not isinstance(rules, list):
131
+ raise RuleError(f"{path}: `rules` must be a list")
132
+ document["rules"] = rules + [{"tool": tool, "pattern": pattern, "decision": decision, "reason": reason}]
133
+ path.write_text(
134
+ yaml.safe_dump(document, sort_keys=False, default_flow_style=False, allow_unicode=True),
135
+ encoding="utf-8",
136
+ )
137
+ load_rules_file(path)
138
+ return path
@@ -0,0 +1 @@
1
+ """User interfaces."""
coderagent/ui/cli.py ADDED
@@ -0,0 +1,498 @@
1
+ """Command line interface."""
2
+
3
+ import json
4
+ import os
5
+ import shutil
6
+ import sys
7
+ import tempfile
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import typer
12
+ from pydantic import ValidationError
13
+
14
+ from coderagent.config.loader import load_config, problems
15
+ from coderagent.config.schema import Config
16
+ from coderagent.core.protocols import ModelBackend
17
+ from coderagent.core.session import Session, SessionStore, session_priced
18
+ from coderagent.models.backends import priced_name
19
+ from coderagent.run import build_loop, build_store, remember_capability, run_turn
20
+ from coderagent.ui.render import last_message, render
21
+ from coderagent.ui.spinner import TerminalDots
22
+
23
+ app = typer.Typer(rich_markup_mode="rich", invoke_without_command=True, no_args_is_help=False)
24
+
25
+
26
+ def read_config(specs: list[str], cwd: Path) -> Config:
27
+ """The configuration of the session, with a readable error when it is wrong."""
28
+ try:
29
+ return load_config(specs, cwd=cwd)
30
+ except ValidationError as error:
31
+ raise typer.BadParameter(f"the configuration is not understood: {problems(error)}") from None
32
+
33
+
34
+ def main_impl(
35
+ task: str,
36
+ config,
37
+ cwd: Path,
38
+ output_format: str = "text",
39
+ *,
40
+ model: ModelBackend | None = None,
41
+ store: SessionStore | None = None,
42
+ session: Session | None = None,
43
+ permission_mode: str | None = None,
44
+ output_schema: dict | None = None,
45
+ output_last_message: Path | None = None,
46
+ ) -> str:
47
+ """Run one turn and render the result."""
48
+ dots = TerminalDots(enabled=output_format != "json")
49
+ """The dots say that the agent is working; a machine reads the answer alone."""
50
+ dots.start()
51
+ try:
52
+ result = run_turn(
53
+ task,
54
+ config,
55
+ cwd=cwd,
56
+ model=model,
57
+ store=store,
58
+ session=session,
59
+ permission_mode=permission_mode,
60
+ output_schema=output_schema,
61
+ remember=remember_capability,
62
+ )
63
+ finally:
64
+ dots.stop()
65
+ if output_last_message is not None:
66
+ """The last answer of the agent, in a file of its own."""
67
+ output_last_message.write_text(last_message(result), encoding="utf-8")
68
+ if config.ui.notify_command and config.ui.notifications:
69
+ """The program of the user tells him that the turn is over."""
70
+ from coderagent.ui.notify import TITLE, run_notifier
71
+
72
+ run_notifier(config.ui.notify_command, TITLE, last_message(result) or "The turn is over.")
73
+ return render(result, output_format)
74
+
75
+
76
+ def read_schema(path: Path | None) -> dict | None:
77
+ """The schema the answer has to fit, when the user gave one."""
78
+ if path is None:
79
+ return None
80
+ try:
81
+ data = json.loads(path.read_text(encoding="utf-8"))
82
+ except OSError as error:
83
+ raise typer.BadParameter(f"the schema file cannot be read: {error}") from error
84
+ except json.JSONDecodeError as error:
85
+ raise typer.BadParameter(f"the schema file is not valid JSON: {error}") from error
86
+ if not isinstance(data, dict):
87
+ raise typer.BadParameter("the schema file must hold a JSON object")
88
+ return data
89
+
90
+
91
+ def pick_session(
92
+ store: SessionStore, cwd: Path, resume: str = "", continue_last: bool = False, fork: str = ""
93
+ ) -> Session | None:
94
+ """The session the turn should continue in. `None` means: start a new one."""
95
+ if resume:
96
+ return store.rebuild(resume)
97
+ if fork:
98
+ return store.fork(fork)
99
+ if continue_last:
100
+ sessions = store.list(cwd, archived=False)
101
+ return sessions[0] if sessions else None
102
+ return None
103
+
104
+
105
+ def run_command(
106
+ task: str, config, cwd: Path, store: SessionStore, session: Session | None, output_format: str = "text"
107
+ ) -> None:
108
+ """Run a slash command instead of a turn."""
109
+ from coderagent.ui.commands import CommandContext, run
110
+
111
+ loop = build_loop(config, cwd, store=store, session=session, remember=remember_capability)
112
+ context = CommandContext(
113
+ loop=loop,
114
+ session=loop.session,
115
+ store=store,
116
+ bus=loop.bus,
117
+ cwd=cwd,
118
+ config=config,
119
+ policy=loop.executor.policy,
120
+ checkpoints=loop.checkpoints,
121
+ mcp=loop.mcp,
122
+ output=typer.echo,
123
+ submit=lambda text, purpose="": _turn(loop, text, purpose, output_format),
124
+ submit_side=lambda text, session: _turn(loop, text, "side", output_format, session),
125
+ quit=lambda: None,
126
+ )
127
+ run(context, task)
128
+
129
+
130
+ def _turn(loop, text: str, purpose: str, output_format: str, session=None) -> None:
131
+ """Run a turn and say what it said; the dots say that the agent is working."""
132
+ dots = TerminalDots(enabled=output_format != "json")
133
+ dots.start()
134
+ try:
135
+ result = loop.run_turn(text, purpose, session)
136
+ finally:
137
+ dots.stop()
138
+ typer.echo(render(result, output_format))
139
+
140
+
141
+ def render_sessions(sessions: list[Session], output_format: str = "text", model: str = "") -> str:
142
+ """The session list, as text or as json."""
143
+ if output_format == "json":
144
+ import json
145
+
146
+ return json.dumps(
147
+ [
148
+ {
149
+ "id": session.id,
150
+ "name": session.name,
151
+ "summary": session.summary,
152
+ "archived": session.archived,
153
+ "cwd": str(session.cwd),
154
+ "created_at": session.created_at,
155
+ "turns": session.turn_count,
156
+ "cost": session.total_cost,
157
+ "priced": session_priced(session, model),
158
+ }
159
+ for session in sessions
160
+ ],
161
+ ensure_ascii=False,
162
+ indent=2,
163
+ )
164
+ if not sessions:
165
+ return "no sessions yet"
166
+ return "\n".join(
167
+ f"{session.summary or session.id} {session.name or '-'} {session.turn_count:>3} turns {session.cwd}"
168
+ + (" (archived)" if session.archived else "")
169
+ for session in sessions
170
+ )
171
+
172
+
173
+ # fmt: off
174
+ @app.callback(invoke_without_command=True)
175
+ def main(
176
+ ctx: typer.Context,
177
+ task: str = typer.Option("", "-t", "--task", help="Task/problem statement"),
178
+ model_name: str = typer.Option("", "-m", "--model", help="Model to use"),
179
+ config_spec: list[str] = typer.Option([], "-c", "--config", help="Config file or key=value overrides"),
180
+ profile: str = typer.Option("", "-p", "--profile", help="Named preset of the configuration"),
181
+ print_mode: bool = typer.Option(False, "--print", help="Non-interactive mode (the only mode in M0)"),
182
+ output_format: str = typer.Option("text", "--output-format", help="text|json"),
183
+ output_schema: Path | None = typer.Option(
184
+ None, "--output-schema", help="JSON file with the schema the answer of the agent has to fit"
185
+ ),
186
+ output_last_message: Path | None = typer.Option(
187
+ None, "--output-last-message", help="Write the last answer of the agent to this file"
188
+ ),
189
+ cwd: Path = typer.Option(Path("."), "--cwd", help="Working directory of the session"),
190
+ permission_mode: str = typer.Option("", "--permission-mode", help="default|acceptEdits|plan|bypass|readonly"),
191
+ resume: str = typer.Option("", "--resume", help="Continue the session with this id"),
192
+ continue_last: bool = typer.Option(False, "--continue", help="Continue the last session of this directory"),
193
+ fork: str = typer.Option("", "--fork", help="Copy the session with this id and continue in the copy"),
194
+ list_sessions: bool = typer.Option(False, "--list", help="List the sessions of this directory"),
195
+ tui: bool = typer.Option(False, "--tui", help="Start the terminal interface"),
196
+ ) -> None:
197
+ # fmt: on
198
+ if ctx.invoked_subcommand is not None:
199
+ return
200
+ config = read_config(config_spec + ([f"profile={profile}"] if profile else []), cwd)
201
+ if model_name:
202
+ config.model.model_name = model_name
203
+ store = build_store(config)
204
+ if list_sessions:
205
+ typer.echo(
206
+ render_sessions(
207
+ store.list(cwd),
208
+ output_format,
209
+ priced_name(config.model.model_name, config.model.litellm_config),
210
+ )
211
+ )
212
+ return
213
+ session = pick_session(store, cwd, resume, continue_last, fork)
214
+ if not task:
215
+ if tui or sys.stdin.isatty():
216
+ from coderagent.ui.tui import main as run_tui
217
+
218
+ run_tui(config, cwd, store=store, session=session)
219
+ return
220
+ typer.echo(f"session {session.id}" if session else "no task given")
221
+ return
222
+ if task.startswith("/"):
223
+ run_command(task, config, cwd, store, session, output_format)
224
+ return
225
+ _warn_pending(cwd)
226
+ typer.echo(
227
+ main_impl(
228
+ task,
229
+ config,
230
+ cwd,
231
+ output_format,
232
+ store=store,
233
+ session=session,
234
+ permission_mode=permission_mode or None,
235
+ output_schema=read_schema(output_schema),
236
+ output_last_message=output_last_message,
237
+ )
238
+ )
239
+
240
+
241
+ def _warn_pending(cwd: Path) -> None:
242
+ """Say that the project has code that is not used, so that it is no surprise."""
243
+ from coderagent.config.loader import pending_code
244
+
245
+ pending = pending_code(cwd)
246
+ if pending:
247
+ typer.echo(
248
+ f"The project has code that waits for a decision of the user: {', '.join(pending.values())}. "
249
+ "It is not used. Run /trust to see it.",
250
+ err=True,
251
+ )
252
+
253
+
254
+ @app.command("model")
255
+ def model_command(
256
+ name: str | None = typer.Option(None, "--name", help="The name of the model"),
257
+ api_base: str | None = typer.Option(None, "--api-base", help="The address of the provider"),
258
+ api_key: str | None = typer.Option(None, "--api-key", help="The key of the provider"),
259
+ max_retries: int | None = typer.Option(None, "--max-retries", help="How many times a call is tried at most"),
260
+ test: bool = typer.Option(False, "--test", help="Try the model out, without writing anything"),
261
+ cwd: Path = typer.Option(Path("."), "--cwd", help="The directory the settings are read from"),
262
+ ) -> None:
263
+ """Show, write down or try out the model.
264
+
265
+ The try-out and the writing are two steps: `--test` never writes, and the
266
+ writing never waits for the try-out. A configuration that does not work yet
267
+ is worth writing down, to be fixed later.
268
+
269
+ The key on the command line stays in the history of the shell: the
270
+ environment variable of the provider is the safer place for it.
271
+ """
272
+ from coderagent.config import writer
273
+ from coderagent.models import check, settings
274
+
275
+ payload = {
276
+ key: value
277
+ for key, value in (
278
+ ("model_name", name),
279
+ ("api_base", api_base),
280
+ ("api_key", api_key),
281
+ ("max_retries", max_retries),
282
+ )
283
+ if value is not None
284
+ }
285
+ if test:
286
+ report = check.test_connection(settings.effective_model(cwd, payload))
287
+ typer.echo(check.report_text(report))
288
+ if not report["ok"]:
289
+ raise typer.Exit(code=1)
290
+ return
291
+ if payload:
292
+ typer.echo(f"Wrote {writer.write_user_model(payload)}")
293
+ return
294
+ typer.echo(settings.view_text(settings.model_view(cwd), str(writer.user_config_path())))
295
+
296
+
297
+ @app.command()
298
+ def web(
299
+ cwd: Path = typer.Option(Path("."), "--cwd", help="The directory the agent works in"),
300
+ host: str = typer.Option("127.0.0.1", "--host", help="The address to listen on"),
301
+ port: int = typer.Option(8765, "--port", help="The port to listen on"),
302
+ config_spec: list[str] = typer.Option([], "-c", "--config", help="Config file or key=value overrides"),
303
+ profile: str = typer.Option("", "-p", "--profile", help="Named preset of the configuration"),
304
+ model_name: str = typer.Option("", "-m", "--model", help="Model to use"),
305
+ permission_mode: str = typer.Option("", "--permission-mode", help="default|acceptEdits|plan|bypass|readonly"),
306
+ ) -> None:
307
+ """Run the agent in the browser.
308
+
309
+ There is no authentication: everybody who can reach the address can drive the
310
+ agent in the working directory, so keep it on 127.0.0.1.
311
+ """
312
+ from coderagent.web.server import serve
313
+
314
+ spec = list(config_spec)
315
+ if model_name:
316
+ spec.append(f"model.model_name={model_name}")
317
+ if profile:
318
+ spec.append(f"profile={profile}")
319
+ serve(cwd=cwd, host=host, port=port, config_spec=spec, permission_mode=permission_mode or None)
320
+
321
+
322
+ @app.command("eval")
323
+ def eval_suite(
324
+ suite: Path = typer.Argument(..., help="The directory of the suite"),
325
+ model_name: str = typer.Option("", "-m", "--model", help="Model to use"),
326
+ config_spec: list[str] = typer.Option([], "-c", "--config", help="Config file or key=value overrides"),
327
+ only: list[str] = typer.Option([], "--only", help="Only the tasks with these ids"),
328
+ tag: list[str] = typer.Option([], "--tag", help="Only the tasks with these tags"),
329
+ output_format: str = typer.Option("text", "--format", help="text|json"),
330
+ out: str = typer.Option("", "--out", help="The file to write the report to"),
331
+ keep: bool = typer.Option(False, "--keep", help="Keep the working directories and the sessions"),
332
+ label: str = typer.Option("", "--label", help="The name of this run"),
333
+ run_dir: str = typer.Option("", "--run-dir", help="Where the working directories and the sessions live"),
334
+ permission_mode: str = typer.Option("bypass", "--permission-mode", help="default|bypass"),
335
+ ) -> None:
336
+ """Run a suite of tasks and report what the agent did.
337
+
338
+ Every task runs in its own working directory, with its own session. The
339
+ sessions and the working directories live in a temporary directory, unless
340
+ `--run-dir` or `--keep` says otherwise.
341
+ """
342
+ from coderagent.eval.report import Report, fingerprint, fingerprint_inputs
343
+ from coderagent.eval.runner import run_suite
344
+ from coderagent.eval.task import load_suite
345
+
346
+ cwd = Path.cwd()
347
+ config = read_config(config_spec, cwd)
348
+ """The configuration of the user is read before the isolation, it holds the model."""
349
+ if model_name:
350
+ config.model.model_name = model_name
351
+ tasks = [task for task in load_suite(suite) if _wanted(task, only, tag)]
352
+ root = Path(run_dir) if run_dir else Path(tempfile.mkdtemp(prefix="coderagent-eval-"))
353
+ home = root / "home"
354
+ home.mkdir(parents=True, exist_ok=True)
355
+ os.environ["MSWEA_CODER_HOME"] = str(home)
356
+ """From here on, every user level path of the agent is inside the run."""
357
+ store = SessionStore(root=home / "sessions")
358
+ started = time.time()
359
+ results = run_suite(
360
+ tasks,
361
+ config,
362
+ root=root / "work",
363
+ store=store,
364
+ permission_mode=permission_mode,
365
+ user_home=home,
366
+ )
367
+ report = Report(
368
+ label=label,
369
+ suite=str(suite),
370
+ model=config.model.model_name,
371
+ fingerprint=fingerprint(config, config.model.model_name, permission_mode, tasks),
372
+ config=fingerprint_inputs(config, config.model.model_name, permission_mode, tasks),
373
+ started_at=started,
374
+ duration_seconds=time.time() - started,
375
+ tasks=results,
376
+ )
377
+ typer.echo(report.to_json() if output_format == "json" else report.to_text())
378
+ if out:
379
+ Path(out).write_text(report.to_json(), encoding="utf-8")
380
+ typer.echo(f"Wrote {out}")
381
+ if not keep and not run_dir:
382
+ shutil.rmtree(root, ignore_errors=True)
383
+
384
+
385
+ def _wanted(task, only: list[str], tag: list[str]) -> bool:
386
+ """Whether a task is part of the run."""
387
+ if only and task.id not in only:
388
+ return False
389
+ return not tag or bool(set(tag) & set(task.tags))
390
+
391
+
392
+ @app.command("eval-compare")
393
+ def eval_compare(
394
+ after: Path = typer.Argument(..., help="The report of the run after the change"),
395
+ against: Path = typer.Option(None, "--against", help="The report of the run before the change"),
396
+ max_regressions: int = typer.Option(0, "--max-regressions", help="The regressions that are allowed"),
397
+ max_drop: float = typer.Option(0.0, "--max-drop", help="The fall of the pass rate that is allowed"),
398
+ same_config: bool = typer.Option(
399
+ False, "--same-config", help="Say nothing when the two runs did not run the same configuration"
400
+ ),
401
+ output_format: str = typer.Option("text", "--format", help="text|json"),
402
+ out: str = typer.Option("", "--out", help="The file to write the comparison to"),
403
+ ) -> None:
404
+ """Compare an eval report with the one before the change and say whether the agent got worse.
405
+
406
+ Without `--against` the report is only checked against what its tasks were
407
+ supposed to do. The exit code is the verdict: zero when the change is good,
408
+ one when a task that used to pass does not pass any more.
409
+ """
410
+ import json
411
+
412
+ from coderagent.eval.compare import check, compare, render, verdict
413
+
414
+ new = json.loads(after.read_text(encoding="utf-8"))
415
+ if against:
416
+ old = json.loads(against.read_text(encoding="utf-8"))
417
+ comparison = compare(old, new)
418
+ if same_config and comparison.config_changed:
419
+ """The numbers of two different configurations say nothing about the change."""
420
+ typer.echo(render(comparison))
421
+ typer.echo("the two runs ran a different configuration: the comparison says nothing")
422
+ return
423
+ problems = verdict(comparison, max_regressions, max_drop)
424
+ else:
425
+ comparison = compare({"tasks": []}, new)
426
+ problems = check(new)
427
+ if output_format == "json":
428
+ payload = {
429
+ "before": comparison.before_label,
430
+ "after": comparison.after_label,
431
+ "config_changed": comparison.config_changed,
432
+ "before_pass_rate": comparison.before_pass_rate,
433
+ "after_pass_rate": comparison.after_pass_rate,
434
+ "drop": comparison.drop,
435
+ "regressions": comparison.regressions,
436
+ "improvements": comparison.improvements,
437
+ "graded": comparison.graded,
438
+ "unexpected": comparison.unexpected,
439
+ "broken_guards": comparison.broken_guards,
440
+ "ungraded": comparison.ungraded,
441
+ "problems": problems,
442
+ }
443
+ typer.echo(json.dumps(payload, ensure_ascii=False, indent=2))
444
+ else:
445
+ typer.echo(render(comparison))
446
+ for problem in problems:
447
+ typer.echo(f"problem: {problem}")
448
+ if out:
449
+ Path(out).write_text(render(comparison), encoding="utf-8")
450
+ if problems:
451
+ raise typer.Exit(code=1)
452
+
453
+
454
+ @app.command()
455
+ def export(
456
+ session: str = typer.Option("", "--session", help="The id of the session. The last one when empty."),
457
+ output_format: str = typer.Option("json", "--format", help="json|otel"),
458
+ out: str = typer.Option("", "--out", help="The file to write. The standard output when empty."),
459
+ push: bool = typer.Option(False, "--push", help="Send the trace to the address of telemetry.otel_endpoint."),
460
+ cwd: Path = typer.Option(Path("."), "--cwd", help="The directory of the session"),
461
+ ) -> None:
462
+ """Write the trace of a session to a file."""
463
+ import json
464
+
465
+ from coderagent.core.otel import OtlpExporter, build_trace
466
+ from coderagent.core.telemetry import trace
467
+
468
+ store = SessionStore()
469
+ session_id = session
470
+ if not session_id:
471
+ sessions = store.list(cwd)
472
+ if not sessions:
473
+ typer.echo("No sessions yet.")
474
+ return
475
+ session_id = sessions[0].id
476
+ events = store.events(session_id)
477
+ if output_format == "json":
478
+ data = trace(events, store.rebuild(session_id))
479
+ elif output_format == "otel":
480
+ data = build_trace(events, store.rebuild(session_id))
481
+ else:
482
+ typer.echo(f"Unknown format '{output_format}'. Use json or otel.")
483
+ return
484
+ if push:
485
+ endpoint = read_config([], cwd).telemetry.otel_endpoint
486
+ if not endpoint:
487
+ typer.echo("No telemetry.otel_endpoint is configured, so there is nowhere to push the trace.")
488
+ raise typer.Exit(code=1)
489
+ if not OtlpExporter(endpoint).export(data):
490
+ typer.echo(f"The trace did not reach {endpoint}.")
491
+ raise typer.Exit(code=1)
492
+ typer.echo(f"Pushed the trace to {endpoint}.")
493
+ text = json.dumps(data, ensure_ascii=False, indent=2)
494
+ if out:
495
+ Path(out).write_text(text, encoding="utf-8")
496
+ typer.echo(f"Wrote {out}")
497
+ return
498
+ typer.echo(text)