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.
- coder_agent-0.1.0.dist-info/METADATA +262 -0
- coder_agent-0.1.0.dist-info/RECORD +163 -0
- coder_agent-0.1.0.dist-info/WHEEL +5 -0
- coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
- coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
- coder_agent-0.1.0.dist-info/top_level.txt +1 -0
- coderagent/__init__.py +20 -0
- coderagent/compat/__init__.py +27 -0
- coderagent/compat/cache_control.py +69 -0
- coderagent/compat/config_spec.py +60 -0
- coderagent/compat/exceptions.py +20 -0
- coderagent/compat/retry.py +27 -0
- coderagent/compat/serialize.py +31 -0
- coderagent/config/__init__.py +1 -0
- coderagent/config/defaults.yaml +103 -0
- coderagent/config/loader.py +264 -0
- coderagent/config/schema.py +548 -0
- coderagent/config/writer.py +218 -0
- coderagent/core/__init__.py +1 -0
- coderagent/core/budget.py +47 -0
- coderagent/core/capabilities.py +136 -0
- coderagent/core/checkpoint.py +164 -0
- coderagent/core/content.py +156 -0
- coderagent/core/context.py +618 -0
- coderagent/core/events.py +83 -0
- coderagent/core/history.py +56 -0
- coderagent/core/instructions.py +99 -0
- coderagent/core/loop.py +702 -0
- coderagent/core/memory.py +56 -0
- coderagent/core/mentions.py +81 -0
- coderagent/core/os_sandbox.py +191 -0
- coderagent/core/otel.py +214 -0
- coderagent/core/protocols.py +38 -0
- coderagent/core/redact.py +49 -0
- coderagent/core/sandbox.py +82 -0
- coderagent/core/schema.py +107 -0
- coderagent/core/session.py +344 -0
- coderagent/core/shell_env.py +74 -0
- coderagent/core/subagent.py +474 -0
- coderagent/core/summarize.py +312 -0
- coderagent/core/telemetry.py +209 -0
- coderagent/core/tokens.py +132 -0
- coderagent/core/trust.py +301 -0
- coderagent/environments/__init__.py +11 -0
- coderagent/environments/bubblewrap.py +150 -0
- coderagent/environments/contree.py +146 -0
- coderagent/environments/docker.py +160 -0
- coderagent/environments/local.py +110 -0
- coderagent/environments/singularity.py +138 -0
- coderagent/environments/swerex_docker.py +79 -0
- coderagent/environments/swerex_modal.py +123 -0
- coderagent/eval/__init__.py +1 -0
- coderagent/eval/compare.py +190 -0
- coderagent/eval/report.py +141 -0
- coderagent/eval/runner.py +368 -0
- coderagent/eval/task.py +194 -0
- coderagent/extensions/__init__.py +1 -0
- coderagent/extensions/hooks.py +121 -0
- coderagent/extensions/plugins.py +217 -0
- coderagent/extensions/reflect.py +342 -0
- coderagent/models/__init__.py +33 -0
- coderagent/models/backends.py +218 -0
- coderagent/models/call.py +18 -0
- coderagent/models/check.py +139 -0
- coderagent/models/gateway.py +60 -0
- coderagent/models/litellm_config.py +70 -0
- coderagent/models/provider.py +98 -0
- coderagent/models/reasoning.py +28 -0
- coderagent/models/router.py +136 -0
- coderagent/models/settings.py +172 -0
- coderagent/models/streaming.py +122 -0
- coderagent/models/verbosity.py +14 -0
- coderagent/paths.py +31 -0
- coderagent/run.py +454 -0
- coderagent/skills/__init__.py +119 -0
- coderagent/skills/errors.py +11 -0
- coderagent/skills/install.py +340 -0
- coderagent/skills/presets/code-review/SKILL.md +35 -0
- coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
- coderagent/skills/presets/data-analysis/SKILL.md +35 -0
- coderagent/skills/presets/deep-research/SKILL.md +38 -0
- coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
- coderagent/skills/presets/long-document/SKILL.md +37 -0
- coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
- coderagent/skills/presets/office-docx/SKILL.md +36 -0
- coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
- coderagent/skills/presets/office-pptx/SKILL.md +32 -0
- coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
- coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
- coderagent/skills/presets/writing/SKILL.md +31 -0
- coderagent/skills/sandbox.py +269 -0
- coderagent/skills/sites.py +177 -0
- coderagent/skills/source.py +404 -0
- coderagent/testing/__init__.py +5 -0
- coderagent/testing/factory.py +59 -0
- coderagent/testing/scripted_model.py +54 -0
- coderagent/tools/__init__.py +1 -0
- coderagent/tools/base.py +54 -0
- coderagent/tools/bash_policy.py +486 -0
- coderagent/tools/builtin/__init__.py +35 -0
- coderagent/tools/builtin/fs.py +283 -0
- coderagent/tools/builtin/patch.py +279 -0
- coderagent/tools/builtin/search.py +242 -0
- coderagent/tools/builtin/shell.py +336 -0
- coderagent/tools/builtin/skill.py +41 -0
- coderagent/tools/builtin/task.py +53 -0
- coderagent/tools/builtin/todo.py +63 -0
- coderagent/tools/executor.py +243 -0
- coderagent/tools/mcp.py +317 -0
- coderagent/tools/permissions.py +472 -0
- coderagent/tools/registry.py +83 -0
- coderagent/tools/rules.py +138 -0
- coderagent/ui/__init__.py +1 -0
- coderagent/ui/cli.py +498 -0
- coderagent/ui/commands/__init__.py +109 -0
- coderagent/ui/commands/builtin.py +778 -0
- coderagent/ui/commands/compact.py +12 -0
- coderagent/ui/commands/resume.py +26 -0
- coderagent/ui/commands/review.py +73 -0
- coderagent/ui/commands/rewind.py +28 -0
- coderagent/ui/custom_commands.py +179 -0
- coderagent/ui/notify.py +46 -0
- coderagent/ui/open_file.py +48 -0
- coderagent/ui/render.py +62 -0
- coderagent/ui/spinner.py +68 -0
- coderagent/ui/tui.py +610 -0
- coderagent/ui/widgets/__init__.py +29 -0
- coderagent/ui/widgets/approval_prompt.py +129 -0
- coderagent/ui/widgets/diff_view.py +97 -0
- coderagent/ui/widgets/file_tree.py +105 -0
- coderagent/ui/widgets/markdown_message.py +44 -0
- coderagent/ui/widgets/markup.py +10 -0
- coderagent/ui/widgets/message_block.py +61 -0
- coderagent/ui/widgets/path_suggester.py +66 -0
- coderagent/ui/widgets/session_picker.py +49 -0
- coderagent/ui/widgets/status_bar.py +44 -0
- coderagent/ui/widgets/todo_panel.py +40 -0
- coderagent/ui/widgets/tool_card.py +104 -0
- coderagent/ui/widgets/working_dots.py +26 -0
- coderagent/version.py +7 -0
- coderagent/web/__init__.py +5 -0
- coderagent/web/api.py +449 -0
- coderagent/web/app.py +113 -0
- coderagent/web/approver.py +73 -0
- coderagent/web/config_api.py +53 -0
- coderagent/web/events.py +159 -0
- coderagent/web/files.py +115 -0
- coderagent/web/i18n.py +346 -0
- coderagent/web/server.py +100 -0
- coderagent/web/sessions.py +404 -0
- coderagent/web/skills_api.py +376 -0
- coderagent/web/static/app.css +283 -0
- coderagent/web/static/app.js +1466 -0
- coderagent/web/templates/en/base.html +31 -0
- coderagent/web/templates/en/chat.html +60 -0
- coderagent/web/templates/en/macros.html +9 -0
- coderagent/web/templates/en/settings.html +80 -0
- coderagent/web/templates/en/skills.html +64 -0
- coderagent/web/templates/zh/base.html +31 -0
- coderagent/web/templates/zh/chat.html +60 -0
- coderagent/web/templates/zh/macros.html +9 -0
- coderagent/web/templates/zh/settings.html +77 -0
- coderagent/web/templates/zh/skills.html +61 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""The `/compact` command: shrink the conversation now, not when the budget says so."""
|
|
2
|
+
|
|
3
|
+
from coderagent.core.context import ContextEngine
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def compact(context: ContextEngine) -> bool:
|
|
7
|
+
"""Replace the older part of the conversation with a summary.
|
|
8
|
+
|
|
9
|
+
Returns whether anything was compacted. The compaction event is published by
|
|
10
|
+
the context engine, so the UI only has to listen for it.
|
|
11
|
+
"""
|
|
12
|
+
return context.compact()
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""The `/resume` command: pick a session again, or fork one into a new branch."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from coderagent.core.session import Session, SessionStore
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def list_sessions(store: SessionStore, cwd: Path | None = None) -> list[Session]:
|
|
9
|
+
"""The sessions of this project that are not put away, newest first."""
|
|
10
|
+
return store.list(cwd, archived=False)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def latest_session(store: SessionStore, cwd: Path | None = None) -> Session | None:
|
|
14
|
+
"""The session that was worked on last."""
|
|
15
|
+
sessions = list_sessions(store, cwd)
|
|
16
|
+
return sessions[0] if sessions else None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def resume(store: SessionStore, session_id: str) -> Session:
|
|
20
|
+
"""Load a session so the conversation can continue."""
|
|
21
|
+
return store.rebuild(session_id)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fork(store: SessionStore, session_id: str) -> Session:
|
|
25
|
+
"""Copy a session into a new one and continue there. The original stays as it was."""
|
|
26
|
+
return store.fork(session_id)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The review of the changes: the diff as the context of a review prompt.
|
|
2
|
+
|
|
3
|
+
The review is a turn of its own: the diff goes into the prompt, so the model
|
|
4
|
+
looks at the changes and not at the conversation that led to them. The prompt
|
|
5
|
+
asks for findings and nothing else — a review does not change anything.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import subprocess
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
MAX_DIFF = 60000
|
|
12
|
+
"""The characters of the diff that go into the prompt. The rest is cut."""
|
|
13
|
+
|
|
14
|
+
REVIEW_PROMPT = """You are reviewing the changes of this project. Say what is wrong with them.
|
|
15
|
+
|
|
16
|
+
Look for:
|
|
17
|
+
- a bug the changes introduce, a case they do not handle
|
|
18
|
+
- a test that is missing for what the changes do
|
|
19
|
+
- a name, a comment or a docstring that does not tell the truth
|
|
20
|
+
- something that breaks the conventions of the project
|
|
21
|
+
|
|
22
|
+
Say where every finding is (the file and the line) and why it matters. If the
|
|
23
|
+
changes are fine, say so and stop. Answer with a short summary and a bullet
|
|
24
|
+
point per finding.
|
|
25
|
+
|
|
26
|
+
Do not change any file: this is a review, not a fix.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _git(cwd: Path, *args: str) -> tuple[int, str]:
|
|
31
|
+
"""Run git and return what it says."""
|
|
32
|
+
result = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=False)
|
|
33
|
+
return result.returncode, (result.stdout or result.stderr).strip()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def changes(cwd: Path, revision: str = "") -> tuple[str, list[str], str]:
|
|
37
|
+
"""The diff of the changes, the files that are not in it, and what went wrong.
|
|
38
|
+
|
|
39
|
+
Without a revision the changes of the working tree are reviewed, with one
|
|
40
|
+
the changes of that range are (`main..HEAD`, a commit, a tag).
|
|
41
|
+
"""
|
|
42
|
+
if revision:
|
|
43
|
+
code, diff = _git(cwd, "diff", revision)
|
|
44
|
+
if code != 0:
|
|
45
|
+
return "", [], f"Git does not know '{revision}':\n{diff}"
|
|
46
|
+
else:
|
|
47
|
+
code, diff = _git(cwd, "diff", "HEAD")
|
|
48
|
+
if code != 0:
|
|
49
|
+
"""A repository without a commit yet has no HEAD to compare with."""
|
|
50
|
+
code, diff = _git(cwd, "diff")
|
|
51
|
+
if code != 0:
|
|
52
|
+
return "", [], f"Not a git repository: {cwd}"
|
|
53
|
+
return diff, _untracked(cwd), ""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _untracked(cwd: Path) -> list[str]:
|
|
57
|
+
"""The files that git does not know yet. They are part of the changes."""
|
|
58
|
+
code, status = _git(cwd, "status", "--porcelain")
|
|
59
|
+
if code != 0:
|
|
60
|
+
return []
|
|
61
|
+
return [line[3:].strip() for line in status.splitlines() if line.startswith("??")]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def prompt(diff: str, untracked: list[str], revision: str = "") -> str:
|
|
65
|
+
"""The prompt of the review: what to look for, and the changes themselves."""
|
|
66
|
+
parts = [REVIEW_PROMPT]
|
|
67
|
+
parts.append(f"The changes are the diff of `{revision}`." if revision else "The changes are the diff below.")
|
|
68
|
+
if untracked:
|
|
69
|
+
parts.append("These files are new and are not in the diff, read them when they matter: " + ", ".join(untracked))
|
|
70
|
+
if len(diff) > MAX_DIFF:
|
|
71
|
+
diff = diff[:MAX_DIFF] + "\n... the diff is cut here, read the files yourself ..."
|
|
72
|
+
parts.append("```diff\n" + diff + "\n```")
|
|
73
|
+
return "\n\n".join(parts)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""The `/rewind` command: put the files back the way they were before a change."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from coderagent.core.checkpoint import Checkpoint, CheckpointStore, restore_files
|
|
6
|
+
from coderagent.core.context import ContextEngine
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def list_checkpoints(store: CheckpointStore, session_id: str) -> list[Checkpoint]:
|
|
10
|
+
"""The checkpoints of a session, oldest first."""
|
|
11
|
+
return store.all(session_id)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def rewind(
|
|
15
|
+
context: ContextEngine, checkpoints: CheckpointStore, checkpoint_id: str, cwd: Path
|
|
16
|
+
) -> tuple[list[str], list[str]]:
|
|
17
|
+
"""Restore the files of a checkpoint and roll the conversation back to it.
|
|
18
|
+
|
|
19
|
+
Returns the paths that were changed and the paths that were left alone,
|
|
20
|
+
because their content held a secret. The conversation is not deleted but marked
|
|
21
|
+
as reverted, so the event log stays the source of truth.
|
|
22
|
+
"""
|
|
23
|
+
checkpoint = checkpoints.get(context.session.id, checkpoint_id)
|
|
24
|
+
if checkpoint is None:
|
|
25
|
+
raise ValueError(f"no checkpoint '{checkpoint_id}' in this session")
|
|
26
|
+
changed = restore_files(checkpoint, cwd)
|
|
27
|
+
context.rewind_to(checkpoint.messages)
|
|
28
|
+
return changed, list(getattr(checkpoint, "redacted", []))
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Custom commands: a markdown file per command in `.coderagent/commands`.
|
|
2
|
+
|
|
3
|
+
The commands of the user live in `commands` of the home of the coder agent,
|
|
4
|
+
`~/.coderagent/commands`.
|
|
5
|
+
|
|
6
|
+
The file starts with front matter, the way Claude Code does it:
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
description: Generate a commit message
|
|
10
|
+
argument-hint: [file]
|
|
11
|
+
allowed-tools: bash(git diff:*), read
|
|
12
|
+
---
|
|
13
|
+
Describe the change of $1 and use $ARGUMENTS for everything else.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
import shlex
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
import yaml
|
|
23
|
+
|
|
24
|
+
from coderagent.paths import config_home
|
|
25
|
+
from coderagent.tools.registry import ToolRegistry
|
|
26
|
+
|
|
27
|
+
COMMANDS_DIR = Path(".coderagent") / "commands"
|
|
28
|
+
"""The commands of the project. The ones of the user are in `commands` of the home."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class CustomCommand:
|
|
33
|
+
name: str
|
|
34
|
+
description: str = ""
|
|
35
|
+
argument_hint: str = ""
|
|
36
|
+
allowed_tools: list[str] = field(default_factory=list)
|
|
37
|
+
"""The tools the command may use. Empty means all of them."""
|
|
38
|
+
model: str = ""
|
|
39
|
+
"""The model to use for this command. Empty means the one of the session."""
|
|
40
|
+
body: str = ""
|
|
41
|
+
"""The prompt that is sent to the model."""
|
|
42
|
+
path: Path | None = None
|
|
43
|
+
|
|
44
|
+
def render(self, arguments: str) -> str:
|
|
45
|
+
"""The prompt, with the arguments filled in."""
|
|
46
|
+
parts = shlex.split(arguments) if arguments else []
|
|
47
|
+
text = self.body.replace("$ARGUMENTS", arguments)
|
|
48
|
+
return re.sub(
|
|
49
|
+
r"\$(\d+)",
|
|
50
|
+
lambda match: parts[int(match.group(1)) - 1] if int(match.group(1)) <= len(parts) else "",
|
|
51
|
+
text,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
def tool_names(self) -> list[str]:
|
|
55
|
+
"""The names of the tools the command may use."""
|
|
56
|
+
return [spec.split("(")[0].strip() for spec in self.allowed_tools]
|
|
57
|
+
|
|
58
|
+
def tool_rules(self) -> dict[str, str]:
|
|
59
|
+
"""The tools the command may use and the pattern each one is limited to.
|
|
60
|
+
|
|
61
|
+
`allowed-tools: bash(git diff:*)` means: the command may run `git diff`,
|
|
62
|
+
and nothing else.
|
|
63
|
+
"""
|
|
64
|
+
rules = {}
|
|
65
|
+
for spec in self.allowed_tools:
|
|
66
|
+
name, _, pattern = spec.partition("(")
|
|
67
|
+
pattern = pattern.rstrip(")").strip()
|
|
68
|
+
if pattern.endswith(":*"):
|
|
69
|
+
"""The `:*` says that the command may start with this."""
|
|
70
|
+
pattern = pattern[:-2].strip()
|
|
71
|
+
rules[name.strip()] = pattern or "*"
|
|
72
|
+
return rules
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_custom_commands(cwd: Path, home: Path | None = None) -> list[CustomCommand]:
|
|
76
|
+
"""The custom commands of this project and of the user.
|
|
77
|
+
|
|
78
|
+
The command of the project wins when both have the same name: it is the one
|
|
79
|
+
that belongs to the work at hand. A command of the project may not choose
|
|
80
|
+
the model: the key of the user would go to a model of the project.
|
|
81
|
+
"""
|
|
82
|
+
directories = [(Path(cwd) / COMMANDS_DIR, True), ((Path(home) if home else config_home()) / "commands", False)]
|
|
83
|
+
commands: dict[str, CustomCommand] = {}
|
|
84
|
+
for directory, of_the_project in directories:
|
|
85
|
+
if not directory.is_dir():
|
|
86
|
+
continue
|
|
87
|
+
for path in sorted(directory.glob("*.md")):
|
|
88
|
+
command = parse_custom_command(path)
|
|
89
|
+
if command is None:
|
|
90
|
+
continue
|
|
91
|
+
if of_the_project:
|
|
92
|
+
command.model = ""
|
|
93
|
+
commands.setdefault(command.name, command)
|
|
94
|
+
return list(commands.values())
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def parse_custom_command(path: Path) -> CustomCommand | None:
|
|
98
|
+
"""Read one command file. Returns None when the file cannot be used."""
|
|
99
|
+
text = path.read_text(encoding="utf-8")
|
|
100
|
+
if not text.startswith("---"):
|
|
101
|
+
return None
|
|
102
|
+
_, _, rest = text.partition("---")
|
|
103
|
+
front_matter, _, body = rest.partition("---")
|
|
104
|
+
try:
|
|
105
|
+
data: dict[str, Any] = yaml.safe_load(front_matter) or {}
|
|
106
|
+
except yaml.YAMLError:
|
|
107
|
+
return None
|
|
108
|
+
return CustomCommand(
|
|
109
|
+
name=path.stem,
|
|
110
|
+
description=str(data.get("description", "")),
|
|
111
|
+
argument_hint=_hint(data.get("argument-hint", "")),
|
|
112
|
+
allowed_tools=_split_tools(data.get("allowed-tools", "")),
|
|
113
|
+
model=str(data.get("model", "")),
|
|
114
|
+
body=body.strip(),
|
|
115
|
+
path=path,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _hint(value: Any) -> str:
|
|
120
|
+
"""The argument hint, as a string. A list becomes `[a b]`."""
|
|
121
|
+
if isinstance(value, list):
|
|
122
|
+
return "[" + " ".join(str(item) for item in value) + "]"
|
|
123
|
+
return str(value)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _split_tools(value: Any) -> list[str]:
|
|
127
|
+
if isinstance(value, list):
|
|
128
|
+
return [str(item).strip() for item in value if str(item).strip()]
|
|
129
|
+
return [item.strip() for item in str(value).split(",") if item.strip()]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def find_custom(cwd: Path, name: str, home: Path | None = None) -> CustomCommand | None:
|
|
133
|
+
"""The custom command with this name."""
|
|
134
|
+
name = name.lstrip("/").lower()
|
|
135
|
+
return next((command for command in load_custom_commands(cwd, home) if command.name.lower() == name), None)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def restricted_registry(registry: ToolRegistry, allowed: list[str]) -> ToolRegistry:
|
|
139
|
+
"""A registry with only the allowed tools, in the order they were allowed."""
|
|
140
|
+
tools = [registry.get(name.split("(")[0].strip()) for name in allowed]
|
|
141
|
+
return ToolRegistry([tool for tool in tools if tool is not None])
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def run_custom(context, command: CustomCommand, arguments: str) -> None:
|
|
145
|
+
"""Run a custom command: the prompt goes to the model, with the tools it may use."""
|
|
146
|
+
from coderagent.models.backends import LiteLLMBackend
|
|
147
|
+
|
|
148
|
+
loop = context.loop
|
|
149
|
+
original_registry = loop.executor.registry
|
|
150
|
+
original_tools = loop.tools
|
|
151
|
+
original_backend = loop.model.backend
|
|
152
|
+
policy = loop.executor.policy
|
|
153
|
+
original_restriction = policy.restriction
|
|
154
|
+
try:
|
|
155
|
+
if command.allowed_tools:
|
|
156
|
+
loop.executor.registry = restricted_registry(original_registry, command.allowed_tools)
|
|
157
|
+
loop.tools = loop.executor.registry.schemas(loop.schema_budget)
|
|
158
|
+
policy.restriction = command.tool_rules()
|
|
159
|
+
"""The pattern of a tool is a limit too: `bash(git diff:*)` runs git diff only."""
|
|
160
|
+
if command.model:
|
|
161
|
+
loop.model.backend = LiteLLMBackend(
|
|
162
|
+
command.model,
|
|
163
|
+
model_kwargs=context.config.model.model_kwargs,
|
|
164
|
+
litellm_config=context.config.model.litellm_config,
|
|
165
|
+
reasoning_effort=context.config.model.reasoning_effort,
|
|
166
|
+
max_retries=context.config.model.max_retries,
|
|
167
|
+
api_key=context.config.model.api_key,
|
|
168
|
+
api_base=context.config.model.api_base,
|
|
169
|
+
)
|
|
170
|
+
result = loop.run_turn(command.render(arguments))
|
|
171
|
+
finally:
|
|
172
|
+
policy.restriction = original_restriction
|
|
173
|
+
loop.executor.registry = original_registry
|
|
174
|
+
loop.tools = original_tools
|
|
175
|
+
loop.model.backend = original_backend
|
|
176
|
+
answer = next(
|
|
177
|
+
(message.get("content", "") for message in reversed(result.messages) if message.get("role") == "assistant"), ""
|
|
178
|
+
)
|
|
179
|
+
context.say(answer or f"The command finished with {result.stop_reason}.")
|
coderagent/ui/notify.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Tell the terminal that something happened, in the way a terminal understands."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import shlex
|
|
5
|
+
import subprocess
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger("coderagent.ui.notify")
|
|
8
|
+
|
|
9
|
+
MAX_BODY = 200
|
|
10
|
+
"""The characters of the notification. A terminal shows a line or two."""
|
|
11
|
+
|
|
12
|
+
TITLE = "coder"
|
|
13
|
+
"""The name of the program, the way the notification shows it."""
|
|
14
|
+
|
|
15
|
+
NOTIFY_TIMEOUT = 10
|
|
16
|
+
"""The seconds the program of the user may take."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def escape_sequence(title: str, body: str) -> str:
|
|
20
|
+
"""The sequence OSC 777 that a terminal turns into a notification."""
|
|
21
|
+
return f"\x1b]777;notify;{_clean(title)};{_clean(body)[:MAX_BODY]}\x07"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def run_notifier(command: str, title: str, body: str) -> None:
|
|
25
|
+
"""Tell the user with the program of their choice that the turn is over.
|
|
26
|
+
|
|
27
|
+
The program gets the title and the body as its two arguments. A program
|
|
28
|
+
that fails is a warning, never a broken session.
|
|
29
|
+
"""
|
|
30
|
+
parts = shlex.split(command)
|
|
31
|
+
if not parts:
|
|
32
|
+
return
|
|
33
|
+
try:
|
|
34
|
+
subprocess.run( # noqa: S603
|
|
35
|
+
[*parts, title, body],
|
|
36
|
+
timeout=NOTIFY_TIMEOUT,
|
|
37
|
+
check=False,
|
|
38
|
+
capture_output=True,
|
|
39
|
+
)
|
|
40
|
+
except (OSError, subprocess.SubprocessError) as error:
|
|
41
|
+
logger.warning("The notifier did not run: %s", error)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _clean(text: str) -> str:
|
|
45
|
+
"""The text without the characters that would break the sequence."""
|
|
46
|
+
return " ".join(text.split()).replace(";", ",")
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Open a file in the editor of the user.
|
|
2
|
+
|
|
3
|
+
The editor is the one the user named in `ui.file_opener`: `vscode`, `cursor`,
|
|
4
|
+
`windsurf`, or a command of his own. The file is opened in the background: the
|
|
5
|
+
agent does not wait for the editor to close.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import shlex
|
|
9
|
+
import subprocess
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
OPENERS = {
|
|
13
|
+
"vscode": "code -g {file}",
|
|
14
|
+
"cursor": "cursor -g {file}",
|
|
15
|
+
"windsurf": "windsurf -g {file}",
|
|
16
|
+
}
|
|
17
|
+
"""The editors the user may name. The file is where `{file}` says."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def opener_command(opener: str, path: Path) -> list[str]:
|
|
21
|
+
"""The command that opens the file. Empty when there is no opener."""
|
|
22
|
+
if not opener:
|
|
23
|
+
return []
|
|
24
|
+
parts = shlex.split(OPENERS.get(opener, opener))
|
|
25
|
+
if not parts:
|
|
26
|
+
return []
|
|
27
|
+
if "{file}" in parts:
|
|
28
|
+
return [str(path) if part == "{file}" else part for part in parts]
|
|
29
|
+
return [*parts, str(path)]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def open_path(path_text: str, opener: str, cwd: Path) -> str:
|
|
33
|
+
"""Open a file and say what happened."""
|
|
34
|
+
if not opener:
|
|
35
|
+
return "No file opener is configured. Set ui.file_opener: vscode, cursor or windsurf."
|
|
36
|
+
path = Path(path_text).expanduser()
|
|
37
|
+
if not path.is_absolute():
|
|
38
|
+
path = cwd / path
|
|
39
|
+
if not path.exists():
|
|
40
|
+
return f"There is no file '{path}'."
|
|
41
|
+
command = opener_command(opener, path)
|
|
42
|
+
if not command:
|
|
43
|
+
return f"'{opener}' is not a program that opens a file."
|
|
44
|
+
try:
|
|
45
|
+
subprocess.Popen(command, cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
46
|
+
except OSError as error:
|
|
47
|
+
return f"The file could not be opened: {error}"
|
|
48
|
+
return f"Opened {path} with {command[0]}."
|
coderagent/ui/render.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Rendering of a finished turn."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from coderagent.core.content import describe_message, text_of
|
|
7
|
+
from coderagent.core.loop import TurnResult
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def last_message(result: TurnResult) -> str:
|
|
11
|
+
"""The text of the last answer of the agent."""
|
|
12
|
+
for message in reversed(result.messages):
|
|
13
|
+
if message.get("role") == "assistant":
|
|
14
|
+
return text_of(message.get("content"))
|
|
15
|
+
return ""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def render(result: TurnResult, output_format: str = "text") -> str:
|
|
19
|
+
if output_format == "json":
|
|
20
|
+
return render_json(result)
|
|
21
|
+
if output_format == "text":
|
|
22
|
+
return render_text(result)
|
|
23
|
+
msg = f"Unknown output format: {output_format}"
|
|
24
|
+
raise ValueError(msg)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def render_json(result: TurnResult) -> str:
|
|
28
|
+
return json.dumps(
|
|
29
|
+
{
|
|
30
|
+
"session_id": result.session_id,
|
|
31
|
+
"messages": result.messages,
|
|
32
|
+
"cost": result.cost,
|
|
33
|
+
"session_cost": result.session_cost,
|
|
34
|
+
"stop_reason": result.stop_reason,
|
|
35
|
+
"error": result.error,
|
|
36
|
+
"output": result.output,
|
|
37
|
+
},
|
|
38
|
+
ensure_ascii=False,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def render_text(result: TurnResult) -> str:
|
|
43
|
+
lines = []
|
|
44
|
+
for message in result.messages:
|
|
45
|
+
lines.extend(_render_message(message))
|
|
46
|
+
if result.error:
|
|
47
|
+
lines.append(f"[error] {result.error}")
|
|
48
|
+
lines.append(
|
|
49
|
+
f"[stop_reason={result.stop_reason} cost={result.cost:.4f} "
|
|
50
|
+
f"session_cost={result.session_cost:.4f} session={result.session_id}]"
|
|
51
|
+
)
|
|
52
|
+
return "\n".join(lines)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _render_message(message: dict[str, Any]) -> list[str]:
|
|
56
|
+
role = message.get("role", "")
|
|
57
|
+
content = describe_message(message.get("content"))
|
|
58
|
+
if role == "tool":
|
|
59
|
+
return [f"[tool] {content.strip()}"]
|
|
60
|
+
if not content:
|
|
61
|
+
return []
|
|
62
|
+
return [content] if role == "assistant" else [f"[{role}] {content}"]
|
coderagent/ui/spinner.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""The sign that the agent is still working.
|
|
2
|
+
|
|
3
|
+
The same dots in every interface: the terminal, the terminal interface and the
|
|
4
|
+
browser show the same animation, so that the user knows what it means.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
|
|
10
|
+
FRAMES = (".", "..", "...", "..")
|
|
11
|
+
"""The dots grow and shrink, like something that breathes."""
|
|
12
|
+
|
|
13
|
+
INTERVAL = 0.4
|
|
14
|
+
"""How long one frame of the animation is shown."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def dots(step: int) -> str:
|
|
18
|
+
"""The dots of one moment of the animation."""
|
|
19
|
+
return FRAMES[step % len(FRAMES)]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TerminalDots:
|
|
23
|
+
"""The dots on a terminal that is not a window.
|
|
24
|
+
|
|
25
|
+
The dots are written again and again on the same line, and the line is
|
|
26
|
+
cleaned when the agent is done, so that the answer stands where it belongs.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, stream=None, enabled: bool = True) -> None:
|
|
30
|
+
self.stream = stream if stream is not None else sys.stdout
|
|
31
|
+
self.enabled = enabled
|
|
32
|
+
self._thread: threading.Thread | None = None
|
|
33
|
+
self._stop = threading.Event()
|
|
34
|
+
self._shown = False
|
|
35
|
+
"""Whether the dots were written: only then is there a line to clean."""
|
|
36
|
+
|
|
37
|
+
def start(self) -> None:
|
|
38
|
+
"""Show the dots, if the terminal can show them."""
|
|
39
|
+
if not self.enabled or not self.stream.isatty():
|
|
40
|
+
"""A pipe or a file gets the answer alone; the dots would be noise in it."""
|
|
41
|
+
return
|
|
42
|
+
self._shown = True
|
|
43
|
+
self._thread = threading.Thread(target=self._run, daemon=True)
|
|
44
|
+
self._thread.start()
|
|
45
|
+
|
|
46
|
+
def stop(self) -> None:
|
|
47
|
+
"""Take the dots away."""
|
|
48
|
+
if not self._shown:
|
|
49
|
+
return
|
|
50
|
+
self._stop.set()
|
|
51
|
+
if self._thread is not None:
|
|
52
|
+
self._thread.join()
|
|
53
|
+
self._thread = None
|
|
54
|
+
self._write("\r" + " " * len(max(FRAMES, key=len)) + "\r")
|
|
55
|
+
self._shown = False
|
|
56
|
+
|
|
57
|
+
def _run(self) -> None:
|
|
58
|
+
step = 0
|
|
59
|
+
while not self._stop.wait(INTERVAL):
|
|
60
|
+
self._write("\r" + dots(step))
|
|
61
|
+
step += 1
|
|
62
|
+
|
|
63
|
+
def _write(self, text: str) -> None:
|
|
64
|
+
self.stream.write(text)
|
|
65
|
+
self.stream.flush()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
__all__ = ["FRAMES", "INTERVAL", "TerminalDots", "dots"]
|