agent-groupchat 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.
- agent_groupchat/__init__.py +2 -0
- agent_groupchat/__main__.py +3 -0
- agent_groupchat/adapters/__init__.py +77 -0
- agent_groupchat/adapters/aider.py +126 -0
- agent_groupchat/adapters/base.py +137 -0
- agent_groupchat/adapters/claude.py +164 -0
- agent_groupchat/adapters/codex.py +115 -0
- agent_groupchat/adapters/gemini.py +142 -0
- agent_groupchat/adapters/gemini_talk_policy.toml +6 -0
- agent_groupchat/adapters/openai_api.py +113 -0
- agent_groupchat/adapters/openai_stream.py +77 -0
- agent_groupchat/config.py +81 -0
- agent_groupchat/platform_support.py +159 -0
- agent_groupchat/roles.py +112 -0
- agent_groupchat/server.py +1612 -0
- agent_groupchat/skills.py +57 -0
- agent_groupchat/static/index.html +1128 -0
- agent_groupchat-0.1.0.dist-info/METADATA +231 -0
- agent_groupchat-0.1.0.dist-info/RECORD +23 -0
- agent_groupchat-0.1.0.dist-info/WHEEL +5 -0
- agent_groupchat-0.1.0.dist-info/entry_points.txt +2 -0
- agent_groupchat-0.1.0.dist-info/licenses/LICENSE +21 -0
- agent_groupchat-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""All available agent adapters, keyed by id: the built-in CLIs plus the chat APIs
|
|
2
|
+
configured in config.json ("apis"). ADAPTERS is updated in place by load_adapters(), so
|
|
3
|
+
modules that imported it see changes."""
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from .aider import AiderAdapter
|
|
9
|
+
from .base import Adapter, MissingAdapter, RunContext
|
|
10
|
+
from .claude import ClaudeAdapter
|
|
11
|
+
from .codex import CodexAdapter
|
|
12
|
+
from .gemini import GeminiAdapter
|
|
13
|
+
from .openai_api import OpenAIChatAdapter
|
|
14
|
+
|
|
15
|
+
BUILTIN = [ClaudeAdapter(), CodexAdapter(), GeminiAdapter(), AiderAdapter()]
|
|
16
|
+
ADAPTERS = {a.id: a for a in BUILTIN}
|
|
17
|
+
_loaded = {"file": None, "mtime": None}
|
|
18
|
+
|
|
19
|
+
ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,30}$")
|
|
20
|
+
URL_RE = re.compile(r"^https?://[^\s]+$")
|
|
21
|
+
ENV_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,80}$")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def parse_apis(items):
|
|
25
|
+
"""Validate config.json "apis" -> [OpenAIChatAdapter]. Raises ValueError."""
|
|
26
|
+
out, seen = [], {a.id for a in BUILTIN}
|
|
27
|
+
for it in items or []:
|
|
28
|
+
if not isinstance(it, dict):
|
|
29
|
+
raise ValueError(f"Each API must be an object: {it!r}")
|
|
30
|
+
aid = str(it.get("id") or "").strip().lower()
|
|
31
|
+
name = str(it.get("name") or "").strip()
|
|
32
|
+
url, model = str(it.get("base_url") or "").strip(), str(it.get("model") or "").strip()
|
|
33
|
+
key_env = str(it.get("key_env") or "").strip()
|
|
34
|
+
if not ID_RE.match(aid) or aid in seen:
|
|
35
|
+
raise ValueError(f"API id {aid!r}: lowercase letters, digits and -, unique, "
|
|
36
|
+
"and not claude/codex/gemini/aider.")
|
|
37
|
+
if not name or len(name) > 30:
|
|
38
|
+
raise ValueError(f"API {aid}: a name of 1-30 characters is needed.")
|
|
39
|
+
if not URL_RE.match(url):
|
|
40
|
+
raise ValueError(f"API {aid}: base_url must start with http:// or https://")
|
|
41
|
+
if not model or len(model) > 100 or any(c.isspace() for c in model):
|
|
42
|
+
raise ValueError(f"API {aid}: a model name is needed (no spaces).")
|
|
43
|
+
if key_env and not ENV_RE.match(key_env):
|
|
44
|
+
raise ValueError(f"API {aid}: key_env is the NAME of an environment variable, "
|
|
45
|
+
"like OPENAI_API_KEY (never the key itself).")
|
|
46
|
+
seen.add(aid)
|
|
47
|
+
out.append(OpenAIChatAdapter(aid, name, url, model, key_env))
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def load_adapters(config_file=None, force=False):
|
|
52
|
+
"""(Re)build ADAPTERS from the built-ins and config.json. Cheap when nothing changed.
|
|
53
|
+
A broken config keeps the built-ins and returns the error message."""
|
|
54
|
+
try:
|
|
55
|
+
mtime = os.path.getmtime(config_file) if config_file else None
|
|
56
|
+
except OSError:
|
|
57
|
+
mtime = None
|
|
58
|
+
if not force and _loaded["file"] == config_file and _loaded["mtime"] == mtime:
|
|
59
|
+
return ""
|
|
60
|
+
_loaded.update(file=config_file, mtime=mtime)
|
|
61
|
+
error, apis = "", []
|
|
62
|
+
if mtime is not None:
|
|
63
|
+
try:
|
|
64
|
+
with open(config_file, encoding="utf-8") as f:
|
|
65
|
+
apis = parse_apis(json.load(f).get("apis"))
|
|
66
|
+
except (OSError, ValueError, AttributeError) as e:
|
|
67
|
+
error = f"config.json: {e}"
|
|
68
|
+
ADAPTERS.clear()
|
|
69
|
+
ADAPTERS.update({a.id: a for a in BUILTIN + apis})
|
|
70
|
+
return error
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get(aid):
|
|
74
|
+
return ADAPTERS.get(aid) or MissingAdapter(aid)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
__all__ = ["ADAPTERS", "Adapter", "RunContext", "load_adapters", "get", "parse_apis"]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Aider (https://aider.chat), one non-interactive run per turn.
|
|
2
|
+
|
|
3
|
+
Aider has no machine-readable output and no system-prompt flag, so:
|
|
4
|
+
- the reply is read back from its chat-history file, which lives in the app's data folder
|
|
5
|
+
(one per session, restored on the next turn with --restore-chat-history);
|
|
6
|
+
- the group-chat intro goes at the top of a session's first message (like Codex).
|
|
7
|
+
Every prompt Aider could show is answered by --yes-always, so anything risky it would say
|
|
8
|
+
yes to is switched off explicitly: creating a git repo, auto-commits, editing .gitignore,
|
|
9
|
+
pip self-updates, browser pages, lint/test runs. Shell commands are never run (--yes-always
|
|
10
|
+
answers those "no", and suggesting them is off).
|
|
11
|
+
"""
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import subprocess
|
|
15
|
+
import tempfile
|
|
16
|
+
import uuid
|
|
17
|
+
|
|
18
|
+
from .base import Adapter, add_file, first_line, rel
|
|
19
|
+
|
|
20
|
+
ASK_TEXT = ("READ (Aider ask mode): you may read the files shared with you, but you can't "
|
|
21
|
+
"change anything.")
|
|
22
|
+
|
|
23
|
+
SAFE_FLAGS = ["--yes-always", "--no-pretty", "--no-stream", "--no-fancy-input",
|
|
24
|
+
"--no-check-update", "--no-show-release-notes", "--no-analytics",
|
|
25
|
+
"--no-show-model-warnings", "--no-detect-urls", "--disable-playwright",
|
|
26
|
+
"--no-suggest-shell-commands", "--no-auto-lint", "--no-auto-test",
|
|
27
|
+
"--no-gitignore", "--no-auto-commits", "--no-dirty-commits", "--timeout", "600"]
|
|
28
|
+
APPLIED_RE = re.compile(r"^Applied edit to (.+?)\s*$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def in_git_repo(folder):
|
|
32
|
+
try:
|
|
33
|
+
return subprocess.run(["git", "-C", folder, "rev-parse", "--is-inside-work-tree"],
|
|
34
|
+
capture_output=True, timeout=10).returncode == 0
|
|
35
|
+
except Exception:
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def new_reply(history_text):
|
|
40
|
+
"""The assistant's reply from the part of Aider's chat-history file written this turn:
|
|
41
|
+
'#### ' lines are the user's message, '> ' lines are Aider's own output (edits applied,
|
|
42
|
+
warnings), '# aider chat started' is a header; the rest is the reply."""
|
|
43
|
+
keep = [l for l in history_text.splitlines()
|
|
44
|
+
if not l.startswith(("#### ", "> ", "# aider chat started")) and l.strip() != "####"
|
|
45
|
+
and l.strip() != ">"]
|
|
46
|
+
return "\n".join(keep).strip()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AiderAdapter(Adapter):
|
|
50
|
+
id = "aider"
|
|
51
|
+
name = "Aider"
|
|
52
|
+
kind = "Aider, an AI pair-programming CLI"
|
|
53
|
+
color = "#14b8a6"
|
|
54
|
+
skill_syntax = "none"
|
|
55
|
+
command = ["aider"]
|
|
56
|
+
needs_model = True # without one, Aider offers a browser login
|
|
57
|
+
levels = ("talk", "read", "edit")
|
|
58
|
+
level_notes = {
|
|
59
|
+
"talk": "Aider can't be stopped from reading files: it stays in ask mode (no changes) "
|
|
60
|
+
"and is told to only discuss.",
|
|
61
|
+
"work": "Aider has no command sandbox, so it's never allowed to run commands.",
|
|
62
|
+
"auto": "Aider has no auto mode with a safety reviewer.",
|
|
63
|
+
}
|
|
64
|
+
mode_texts = {
|
|
65
|
+
"talk": "TALK ONLY (Aider ask mode): discuss only; don't ask to see or change files.",
|
|
66
|
+
"read": ASK_TEXT,
|
|
67
|
+
"edit": "EDIT (Aider code mode): you may edit files in the project folder; you can't run "
|
|
68
|
+
"commands. Edits are not committed to git.",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
def run(self, ctx, prompt, level):
|
|
72
|
+
sid = ctx.session or str(uuid.uuid4())
|
|
73
|
+
os.makedirs(ctx.state_dir, exist_ok=True)
|
|
74
|
+
hist = os.path.join(ctx.state_dir, f"aider-{sid}.chat.md")
|
|
75
|
+
inputs = os.path.join(ctx.state_dir, f"aider-{sid}.input")
|
|
76
|
+
start = os.path.getsize(hist) if os.path.exists(hist) else 0
|
|
77
|
+
text = prompt if ctx.session else ctx.system_prompt + "\n\n" + prompt
|
|
78
|
+
if text.lstrip().startswith("/"): # Aider would run it as one of its /commands
|
|
79
|
+
text = "(message) " + text
|
|
80
|
+
cmd = [*self.command, "--chat-mode", "code" if level == "edit" else "ask", *SAFE_FLAGS,
|
|
81
|
+
"--chat-history-file", hist, "--input-history-file", inputs,
|
|
82
|
+
*(["--restore-chat-history"] if ctx.session else []),
|
|
83
|
+
*([] if in_git_repo(ctx.folder) else ["--no-git"])]
|
|
84
|
+
if ctx.model:
|
|
85
|
+
cmd += ["--model", ctx.model]
|
|
86
|
+
out = {"files": [], "lines": []}
|
|
87
|
+
|
|
88
|
+
def on_event(ev): # Aider prints plain text; stream() hands over each line
|
|
89
|
+
line = ev.get("text", "") if ev.get("type") == "_text" else ""
|
|
90
|
+
if not line.strip():
|
|
91
|
+
return
|
|
92
|
+
out["lines"].append(line)
|
|
93
|
+
m = APPLIED_RE.match(line.strip())
|
|
94
|
+
if m:
|
|
95
|
+
p = rel(os.path.join(ctx.folder, m.group(1)), ctx.folder)
|
|
96
|
+
add_file(out, p)
|
|
97
|
+
ctx.step(f"✏️ editing {p}")
|
|
98
|
+
|
|
99
|
+
fd, msg = tempfile.mkstemp(suffix=".txt", prefix="gc-aider-")
|
|
100
|
+
try:
|
|
101
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
102
|
+
f.write(text)
|
|
103
|
+
ctx.step("💭 thinking")
|
|
104
|
+
code, err, why = ctx.stream([*cmd, "--message-file", msg], on_event)
|
|
105
|
+
finally:
|
|
106
|
+
os.unlink(msg)
|
|
107
|
+
meta = {"files": out["files"], "cost": None, "tokens": None}
|
|
108
|
+
if why:
|
|
109
|
+
return f"({why})", meta
|
|
110
|
+
try:
|
|
111
|
+
with open(hist, encoding="utf-8", errors="replace") as f:
|
|
112
|
+
f.seek(start)
|
|
113
|
+
reply = new_reply(f.read())
|
|
114
|
+
except OSError:
|
|
115
|
+
reply = ""
|
|
116
|
+
if not reply: # Aider exits 0 even when the model call failed: show its last words
|
|
117
|
+
tail = "\n".join(out["lines"][-6:]) or err or f"exit code {code}"
|
|
118
|
+
return f"(error) {tail[-800:]}", meta
|
|
119
|
+
ctx.save_session(sid)
|
|
120
|
+
ctx.preview(reply)
|
|
121
|
+
ctx.step(first_line(reply))
|
|
122
|
+
return reply, meta
|
|
123
|
+
|
|
124
|
+
def resume_hint(self, session):
|
|
125
|
+
return ("aider --restore-chat-history --chat-history-file "
|
|
126
|
+
f"~/.agent-groupchat/sessions/aider-{session}.chat.md")
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""The adapter interface: one adapter per AI agent.
|
|
2
|
+
|
|
3
|
+
The chat engine knows nothing about any particular CLI. It hands an adapter a
|
|
4
|
+
RunContext (folder, session, callbacks for live progress) plus the prompt and the
|
|
5
|
+
permission level, and gets back the reply text and its stats.
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Callable, Optional
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class RunContext:
|
|
16
|
+
folder: str # the chat's project folder (the agent's working dir)
|
|
17
|
+
session: Optional[str] # session id to resume, or None to start a new session
|
|
18
|
+
system_prompt: str # the group-chat intro for this agent
|
|
19
|
+
save_session: Callable[[str], None] # remember the session id (call as soon as known)
|
|
20
|
+
step: Callable[[str], None] # one line of live activity ("✏️ editing x.py")
|
|
21
|
+
preview: Callable[..., None] # preview(text, append=False): live reply text
|
|
22
|
+
stream: Callable[[list, Callable[[dict], None]], tuple]
|
|
23
|
+
# stream(cmd, on_event) runs cmd in `folder`, calls on_event for every JSON line of its
|
|
24
|
+
# stdout and returns (exit code, stderr tail, None | "stopped" | "timed out").
|
|
25
|
+
# It owns the process, so the user's Stop button and the timeout work for every agent.
|
|
26
|
+
model: Optional[str] = None # model for this agent, or None for the CLI's default
|
|
27
|
+
sandbox: bool = False # is the OS command sandbox (bubblewrap) working?
|
|
28
|
+
state_dir: str = "" # where an adapter may keep its own state (chat APIs: history)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
TALK_TEXT = "TALK ONLY: discuss only; don't open, change or run anything."
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Adapter:
|
|
35
|
+
id = "" # e.g. "claude"; also `@claude` reaches every copy of this AI in a chat
|
|
36
|
+
name = "" # default display name, e.g. "Claude"
|
|
37
|
+
kind = "" # what it is, told to the other agents, e.g. "Anthropic's Claude Code"
|
|
38
|
+
color = "#888888" # accent color on the page
|
|
39
|
+
intro_note = "" # extra agent-specific sentence appended to this agent's intro
|
|
40
|
+
# Permission levels (see roles.LEVELS) this agent can really ENFORCE, which of them need
|
|
41
|
+
# the OS sandbox, and caveats shown on the page. A level it can't enforce is never given:
|
|
42
|
+
# the agent drops to the next lower level it can enforce.
|
|
43
|
+
levels = ("talk",)
|
|
44
|
+
needs_sandbox = ()
|
|
45
|
+
level_notes = {}
|
|
46
|
+
# What this agent may do at each level, in its own words (it's told this).
|
|
47
|
+
mode_texts = {"talk": TALK_TEXT}
|
|
48
|
+
# How a /skill from the chat is invoked:
|
|
49
|
+
# "slash": the prompt starts with /name args (Claude Code)
|
|
50
|
+
# "dollar": the message mentions $name (Codex)
|
|
51
|
+
skill_syntax = "slash"
|
|
52
|
+
|
|
53
|
+
def run(self, ctx: RunContext, prompt: str, level: str):
|
|
54
|
+
"""Run one turn at permission `level`. -> (reply text, meta dict: files, cost, tokens).
|
|
55
|
+
Reply text starting with "(error)", "(stopped)" or "(timed out)" marks a failure."""
|
|
56
|
+
raise NotImplementedError
|
|
57
|
+
|
|
58
|
+
def skill_files(self, folder):
|
|
59
|
+
"""-> (SKILL.md paths, command .md paths) this agent can run from `folder`."""
|
|
60
|
+
return [], []
|
|
61
|
+
|
|
62
|
+
def mode_text(self, level):
|
|
63
|
+
return self.mode_texts.get(level) or TALK_TEXT
|
|
64
|
+
|
|
65
|
+
def available(self, level, sandbox):
|
|
66
|
+
return level in self.levels and (sandbox or level not in self.needs_sandbox)
|
|
67
|
+
|
|
68
|
+
def why_not(self, level, sandbox):
|
|
69
|
+
"""Why `level` can't be enforced right now ("" if it can)."""
|
|
70
|
+
if level not in self.levels:
|
|
71
|
+
return self.level_notes.get(level) or f"{self.name} can't enforce this level."
|
|
72
|
+
if not sandbox and level in self.needs_sandbox:
|
|
73
|
+
return "needs the command sandbox, which isn't working on this computer"
|
|
74
|
+
return ""
|
|
75
|
+
|
|
76
|
+
def resume_hint(self, session):
|
|
77
|
+
"""Terminal command that continues this session, e.g. 'claude -r <id>'."""
|
|
78
|
+
return ""
|
|
79
|
+
|
|
80
|
+
command = [] # the CLI, e.g. ["claude"] (tests point it at a fake)
|
|
81
|
+
|
|
82
|
+
def installed(self):
|
|
83
|
+
return bool(self.command) and shutil.which(self.command[0]) is not None
|
|
84
|
+
|
|
85
|
+
def detect(self):
|
|
86
|
+
"""(ok, message) for the Test button. Default: the CLI runs `--version`. No tokens spent."""
|
|
87
|
+
if not self.installed():
|
|
88
|
+
return False, f"`{self.command[0] if self.command else self.id}` isn't installed (not on PATH)."
|
|
89
|
+
from ..platform_support import resolve_command # (Windows: no .cmd via cmd.exe)
|
|
90
|
+
try:
|
|
91
|
+
r = subprocess.run(resolve_command([*self.command, "--version"]), capture_output=True,
|
|
92
|
+
text=True, encoding="utf-8", errors="replace", timeout=20,
|
|
93
|
+
stdin=subprocess.DEVNULL)
|
|
94
|
+
except Exception as e:
|
|
95
|
+
return False, f"`{self.command[0]} --version` failed: {e}"
|
|
96
|
+
out = (r.stdout or r.stderr).strip().splitlines()
|
|
97
|
+
return r.returncode == 0, (out[0] if out else f"exit code {r.returncode}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class MissingAdapter(Adapter):
|
|
101
|
+
"""Stands in for an AI that a chat uses but that isn't configured anymore."""
|
|
102
|
+
kind = "an AI that isn't configured anymore"
|
|
103
|
+
|
|
104
|
+
def __init__(self, id):
|
|
105
|
+
self.id, self.name = id, id
|
|
106
|
+
|
|
107
|
+
def installed(self):
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
def run(self, ctx, prompt, level):
|
|
111
|
+
return (f"(error) This agent's AI ({self.id}) isn't configured anymore. Add it back in "
|
|
112
|
+
"the settings, or remove the agent from this chat."), {}
|
|
113
|
+
|
|
114
|
+
def detect(self):
|
|
115
|
+
return False, f"{self.id} isn't configured."
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------------- helpers for adapters
|
|
119
|
+
def rel(path, folder):
|
|
120
|
+
"""Path relative to the project folder, or unchanged if it's outside it."""
|
|
121
|
+
if not path:
|
|
122
|
+
return ""
|
|
123
|
+
r = os.path.relpath(path, folder) if os.path.isabs(path) else path
|
|
124
|
+
return path if r.startswith("..") else r
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def add_file(out, path):
|
|
128
|
+
if path and path not in out["files"]:
|
|
129
|
+
out["files"].append(path)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def first_line(text):
|
|
133
|
+
return "💬 " + next((l for l in text.strip().splitlines() if l.strip()), "")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def error_text(text, err, code):
|
|
137
|
+
return f"(error) {(text or err or f'exit code {code}')[-800:]}"
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Claude Code (`claude -p`, stream-json output)."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import uuid
|
|
5
|
+
|
|
6
|
+
from ..skills import HOME, ancestors, scan_skill_dirs
|
|
7
|
+
from .base import TALK_TEXT, Adapter, add_file, error_text, first_line, rel
|
|
8
|
+
|
|
9
|
+
READ_TOOLS = ["Read", "Glob", "Grep", "WebSearch", "WebFetch", "Skill", "TodoWrite"]
|
|
10
|
+
EDIT_TOOLS = READ_TOOLS + ["Edit", "Write", "NotebookEdit"]
|
|
11
|
+
WORK_TOOLS = EDIT_TOOLS + ["Bash"]
|
|
12
|
+
EDIT_NAMES = ("Edit", "MultiEdit", "Write", "NotebookEdit")
|
|
13
|
+
SANDBOX = json.dumps({"sandbox": {"enabled": True, "autoAllowBashIfSandboxed": True}})
|
|
14
|
+
|
|
15
|
+
# Read-only commands a "read" agent may run (Reviewer: git diff, tests).
|
|
16
|
+
SAFE_BASH = ["Bash(git diff:*)", "Bash(git status:*)", "Bash(git log:*)", "Bash(git show:*)",
|
|
17
|
+
"Bash(ls:*)"]
|
|
18
|
+
# Test runners execute project code, so only inside the sandbox.
|
|
19
|
+
TEST_BASH = ["Bash(pytest:*)", "Bash(python -m pytest:*)", "Bash(python3 -m pytest:*)",
|
|
20
|
+
"Bash(python -m unittest:*)", "Bash(python3 -m unittest:*)", "Bash(npm test:*)",
|
|
21
|
+
"Bash(npm run test:*)", "Bash(cargo test:*)", "Bash(go test:*)"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def permissions(level, sandbox):
|
|
25
|
+
"""Permission level -> Claude Code flags."""
|
|
26
|
+
if level == "auto":
|
|
27
|
+
return ["--permission-mode", "auto"]
|
|
28
|
+
if level == "work": # only given when the sandbox works (see ClaudeAdapter.needs_sandbox)
|
|
29
|
+
return ["--permission-mode", "acceptEdits", "--settings", SANDBOX,
|
|
30
|
+
"--allowedTools", *WORK_TOOLS]
|
|
31
|
+
if level == "edit":
|
|
32
|
+
# acceptEdits auto-approves edits only inside the working folder; anything else
|
|
33
|
+
# would need a prompt, which -p can't show, so it is denied.
|
|
34
|
+
return ["--permission-mode", "acceptEdits", "--allowedTools", *READ_TOOLS,
|
|
35
|
+
"--disallowedTools", "Bash"]
|
|
36
|
+
if level == "read": # read tools + read-only checks; no edit tools at all
|
|
37
|
+
return ["--permission-mode", "dontAsk", *(["--settings", SANDBOX] if sandbox else []),
|
|
38
|
+
"--allowedTools", *READ_TOOLS, *SAFE_BASH, *(TEST_BASH if sandbox else []),
|
|
39
|
+
"--disallowedTools", *EDIT_NAMES]
|
|
40
|
+
return ["--permission-mode", "dontAsk", "--tools", ""] # talk: no tools at all
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def describe_tool(name, inp, folder):
|
|
44
|
+
path = rel(inp.get("file_path") or inp.get("notebook_path") or inp.get("path"), folder)
|
|
45
|
+
if name == "Read":
|
|
46
|
+
return f"📖 reading {path}"
|
|
47
|
+
if name in EDIT_NAMES:
|
|
48
|
+
return f"✏️ editing {path}"
|
|
49
|
+
if name == "Bash":
|
|
50
|
+
return "$ " + (inp.get("description") or (inp.get("command") or "").strip().split("\n")[0])
|
|
51
|
+
if name in ("Grep", "Glob"):
|
|
52
|
+
return f"🔎 searching for {inp.get('pattern', '')}" + (f" in {path}" if path else "")
|
|
53
|
+
if name == "WebSearch":
|
|
54
|
+
return f"🌐 searching the web: {inp.get('query', '')}"
|
|
55
|
+
if name == "WebFetch":
|
|
56
|
+
return f"🌐 reading {inp.get('url', '')}"
|
|
57
|
+
if name == "Skill":
|
|
58
|
+
return f"🧩 using skill {inp.get('skill', '')}"
|
|
59
|
+
if name in ("Agent", "Task"):
|
|
60
|
+
return f"🤖 subagent: {inp.get('description', '')}"
|
|
61
|
+
if name == "TodoWrite":
|
|
62
|
+
return "📝 updating its to-do list"
|
|
63
|
+
return f"🔧 {name}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ClaudeAdapter(Adapter):
|
|
67
|
+
id = "claude"
|
|
68
|
+
name = "Claude"
|
|
69
|
+
kind = "Anthropic's Claude Code"
|
|
70
|
+
color = "#c96442"
|
|
71
|
+
skill_syntax = "slash"
|
|
72
|
+
command = ["claude"]
|
|
73
|
+
levels = ("talk", "read", "edit", "work", "auto")
|
|
74
|
+
needs_sandbox = ("work",)
|
|
75
|
+
mode_texts = {
|
|
76
|
+
"talk": "TALK ONLY: you have no tools this turn; discuss only.",
|
|
77
|
+
"read": "READ: you may read and search files and use skills, and run read-only checks "
|
|
78
|
+
"(git diff/log/status, and the tests where allowed), but don't modify anything.",
|
|
79
|
+
"edit": "EDIT: you may edit files in the project folder but cannot run shell commands.",
|
|
80
|
+
"work": "WORK: you may edit files and run commands inside the project folder "
|
|
81
|
+
"(sandboxed).",
|
|
82
|
+
"auto": "AUTO: you run in Claude Code auto mode: you may run commands and edit "
|
|
83
|
+
"files where the user asks; a safety classifier blocks risky actions.",
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
def run(self, ctx, prompt, level):
|
|
87
|
+
sid = ctx.session
|
|
88
|
+
cmd = [*self.command, "-p", "--output-format", "stream-json", "--verbose",
|
|
89
|
+
"--include-partial-messages", "--append-system-prompt", ctx.system_prompt]
|
|
90
|
+
if sid:
|
|
91
|
+
cmd += ["--resume", sid]
|
|
92
|
+
else:
|
|
93
|
+
sid = str(uuid.uuid4())
|
|
94
|
+
cmd += ["--session-id", sid]
|
|
95
|
+
cmd += permissions(level, ctx.sandbox)
|
|
96
|
+
if ctx.model:
|
|
97
|
+
cmd += ["--model", ctx.model]
|
|
98
|
+
cmd += ["--", prompt]
|
|
99
|
+
out = {"files": [], "result": None, "started": False}
|
|
100
|
+
|
|
101
|
+
def on_event(ev):
|
|
102
|
+
t = ev.get("type")
|
|
103
|
+
if t == "system" and ev.get("subtype") == "init":
|
|
104
|
+
out["started"] = True
|
|
105
|
+
elif t == "stream_event": # token-by-token text, for the live preview
|
|
106
|
+
e = ev.get("event") or {}
|
|
107
|
+
if e.get("type") == "content_block_start" and \
|
|
108
|
+
(e.get("content_block") or {}).get("type") == "text":
|
|
109
|
+
ctx.preview("")
|
|
110
|
+
elif e.get("type") == "content_block_delta" and \
|
|
111
|
+
(e.get("delta") or {}).get("type") == "text_delta":
|
|
112
|
+
ctx.preview(e["delta"].get("text", ""), append=True)
|
|
113
|
+
elif t == "assistant":
|
|
114
|
+
for c in (ev.get("message") or {}).get("content") or []:
|
|
115
|
+
if c.get("type") == "tool_use":
|
|
116
|
+
inp = c.get("input") or {}
|
|
117
|
+
ctx.step(describe_tool(c.get("name", ""), inp, ctx.folder))
|
|
118
|
+
if c.get("name") in EDIT_NAMES:
|
|
119
|
+
add_file(out, rel(inp.get("file_path") or inp.get("notebook_path"),
|
|
120
|
+
ctx.folder))
|
|
121
|
+
elif c.get("type") == "text" and (c.get("text") or "").strip():
|
|
122
|
+
ctx.step(first_line(c["text"]))
|
|
123
|
+
elif t == "result":
|
|
124
|
+
out["result"] = ev
|
|
125
|
+
|
|
126
|
+
code, err, why = ctx.stream(cmd, on_event)
|
|
127
|
+
if out["started"]: # the session exists now (even if stopped), so keep resuming it
|
|
128
|
+
ctx.save_session(sid)
|
|
129
|
+
res = out["result"] or {}
|
|
130
|
+
u = res.get("usage") or {}
|
|
131
|
+
meta = {"files": out["files"], "cost": res.get("total_cost_usd"),
|
|
132
|
+
"tokens": [u.get("input_tokens", 0) + u.get("cache_creation_input_tokens", 0)
|
|
133
|
+
+ u.get("cache_read_input_tokens", 0), u.get("output_tokens", 0)]
|
|
134
|
+
if u else None}
|
|
135
|
+
if why:
|
|
136
|
+
return f"({why})", meta
|
|
137
|
+
text = (res.get("result") or "").strip()
|
|
138
|
+
if res and not res.get("is_error") and text:
|
|
139
|
+
return text, meta
|
|
140
|
+
return error_text(text, err, code), meta
|
|
141
|
+
|
|
142
|
+
def resume_hint(self, session):
|
|
143
|
+
return f"claude -r {session}"
|
|
144
|
+
|
|
145
|
+
def skill_files(self, folder):
|
|
146
|
+
roots = [os.path.join(HOME, ".claude", "skills")]
|
|
147
|
+
roots += [os.path.join(d, ".claude", "skills") for d in ancestors(folder) if d != HOME]
|
|
148
|
+
files = scan_skill_dirs(roots)
|
|
149
|
+
try:
|
|
150
|
+
with open(os.path.join(HOME, ".claude", "plugins", "installed_plugins.json"),
|
|
151
|
+
encoding="utf-8") as f:
|
|
152
|
+
plugins = json.load(f).get("plugins", {})
|
|
153
|
+
for entries in plugins.values():
|
|
154
|
+
for e in entries:
|
|
155
|
+
files += scan_skill_dirs([os.path.join(e["installPath"], "skills")],
|
|
156
|
+
recursive=True)
|
|
157
|
+
except Exception:
|
|
158
|
+
pass
|
|
159
|
+
cmds = []
|
|
160
|
+
for d in [os.path.join(HOME, ".claude", "commands")] + \
|
|
161
|
+
[os.path.join(a, ".claude", "commands") for a in ancestors(folder) if a != HOME]:
|
|
162
|
+
if os.path.isdir(d):
|
|
163
|
+
cmds += [os.path.join(d, n) for n in sorted(os.listdir(d)) if n.endswith(".md")]
|
|
164
|
+
return files, cmds
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""OpenAI Codex CLI (`codex exec --json`)."""
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import tempfile
|
|
5
|
+
|
|
6
|
+
from ..skills import HOME, ancestors, scan_skill_dirs
|
|
7
|
+
from .base import TALK_TEXT, Adapter, add_file, error_text, first_line, rel
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def config(level):
|
|
11
|
+
"""Permission level -> Codex `-c` settings (sandbox + approvals)."""
|
|
12
|
+
sandbox = "workspace-write" if level in ("work", "auto") else "read-only"
|
|
13
|
+
conf = ["-c", f'sandbox_mode="{sandbox}"']
|
|
14
|
+
if level == "auto":
|
|
15
|
+
# Codex's "approve for me": when the sandbox blocks something (internet, a
|
|
16
|
+
# folder outside the project...), Codex asks for escalation and its
|
|
17
|
+
# automatic reviewer (guardian) approves or denies it, like Claude's auto mode.
|
|
18
|
+
return conf + ["-c", 'approval_policy="on-request"', "-c", 'approvals_reviewer="auto_review"']
|
|
19
|
+
return conf + ["-c", 'approval_policy="never"']
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CodexAdapter(Adapter):
|
|
23
|
+
id = "codex"
|
|
24
|
+
name = "Codex"
|
|
25
|
+
kind = "OpenAI's coding agent"
|
|
26
|
+
color = "#10a37f"
|
|
27
|
+
# No "edit": Codex has no "edit files but run no commands" setting.
|
|
28
|
+
levels = ("talk", "read", "work", "auto")
|
|
29
|
+
needs_sandbox = ("work", "auto")
|
|
30
|
+
level_notes = {
|
|
31
|
+
"talk": "Codex can't be stopped from reading files; it stays read-only and is told "
|
|
32
|
+
"to only discuss.",
|
|
33
|
+
"edit": "Codex has no \"edit files but run no commands\" setting.",
|
|
34
|
+
}
|
|
35
|
+
mode_texts = {
|
|
36
|
+
"talk": TALK_TEXT,
|
|
37
|
+
"read": "READ: you may read files and run read-only commands (your sandbox is "
|
|
38
|
+
"read-only), but don't modify anything.",
|
|
39
|
+
"work": "WORK: you may edit files and run commands inside the project folder "
|
|
40
|
+
"(workspace-write sandbox).",
|
|
41
|
+
"auto": "AUTO: you may run commands and edit files where the user asks. You start "
|
|
42
|
+
"sandboxed to the project folder with no internet; if blocked, request escalated "
|
|
43
|
+
"permissions and the automatic reviewer will approve or deny. Risky actions are "
|
|
44
|
+
"blocked.",
|
|
45
|
+
}
|
|
46
|
+
intro_note = (" Note: in your workspace-write sandbox, empty read-only .git/.codex/.agents/.aws "
|
|
47
|
+
"folders can appear in the project; they are sandbox mount points, not real "
|
|
48
|
+
"files, so don't report them as project contents.")
|
|
49
|
+
skill_syntax = "dollar"
|
|
50
|
+
command = ["codex"]
|
|
51
|
+
|
|
52
|
+
def run(self, ctx, prompt, level):
|
|
53
|
+
sid = ctx.session
|
|
54
|
+
conf = config(level)
|
|
55
|
+
if ctx.model:
|
|
56
|
+
conf += ["-c", f'model="{ctx.model}"']
|
|
57
|
+
out = {"files": [], "usage": None}
|
|
58
|
+
|
|
59
|
+
def on_event(ev):
|
|
60
|
+
t, it = ev.get("type"), ev.get("item") or {}
|
|
61
|
+
kind = it.get("type")
|
|
62
|
+
if t == "thread.started" and not sid: # save right away so Stop keeps it resumable
|
|
63
|
+
ctx.save_session(ev.get("thread_id"))
|
|
64
|
+
elif t == "turn.completed":
|
|
65
|
+
out["usage"] = ev.get("usage")
|
|
66
|
+
elif t == "item.started" and kind == "command_execution":
|
|
67
|
+
cmd = it.get("command") or ""
|
|
68
|
+
m = re.fullmatch(r"/bin/(?:ba|z)?sh -lc (['\"])(.*)\1", cmd, re.S)
|
|
69
|
+
ctx.step("$ " + (m.group(2) if m else cmd).split("\n")[0])
|
|
70
|
+
elif t == "item.started" and kind == "reasoning":
|
|
71
|
+
ctx.step("💭 thinking")
|
|
72
|
+
elif t == "item.started" and kind == "web_search":
|
|
73
|
+
ctx.step(f"🌐 searching the web: {it.get('query', '')}")
|
|
74
|
+
elif t == "item.started" and kind == "mcp_tool_call":
|
|
75
|
+
ctx.step(f"🔧 {it.get('server', '')}.{it.get('tool', '')}")
|
|
76
|
+
elif t == "item.completed" and kind == "file_change":
|
|
77
|
+
for c in it.get("changes") or []:
|
|
78
|
+
p = rel(c.get("path"), ctx.folder)
|
|
79
|
+
add_file(out, p)
|
|
80
|
+
ctx.step(f"✏️ editing {p}")
|
|
81
|
+
elif t == "item.completed" and kind == "agent_message" and \
|
|
82
|
+
(it.get("text") or "").strip():
|
|
83
|
+
ctx.step(first_line(it["text"]))
|
|
84
|
+
ctx.preview(it["text"])
|
|
85
|
+
|
|
86
|
+
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as tf:
|
|
87
|
+
outfile = tf.name
|
|
88
|
+
try:
|
|
89
|
+
base = [*self.command, "exec", "--skip-git-repo-check", "--json", *conf]
|
|
90
|
+
if sid:
|
|
91
|
+
cmd = [*base, "-o", outfile, "resume", sid, prompt]
|
|
92
|
+
else: # a new session gets the group-chat intro at the top of its first prompt
|
|
93
|
+
cmd = [*base, "-C", ctx.folder, "-o", outfile,
|
|
94
|
+
ctx.system_prompt + "\n\n" + prompt]
|
|
95
|
+
code, err, why = ctx.stream(cmd, on_event)
|
|
96
|
+
with open(outfile, encoding="utf-8", errors="replace") as f:
|
|
97
|
+
text = f.read().strip()
|
|
98
|
+
finally:
|
|
99
|
+
os.unlink(outfile)
|
|
100
|
+
u = out["usage"] or {}
|
|
101
|
+
meta = {"files": out["files"], "cost": None,
|
|
102
|
+
"tokens": [u.get("input_tokens", 0), u.get("output_tokens", 0)] if u else None}
|
|
103
|
+
if why:
|
|
104
|
+
return f"({why})", meta
|
|
105
|
+
return (text or error_text(None, err, code)), meta
|
|
106
|
+
|
|
107
|
+
def resume_hint(self, session):
|
|
108
|
+
return f"codex resume {session}"
|
|
109
|
+
|
|
110
|
+
def skill_files(self, folder):
|
|
111
|
+
roots = [os.path.join(HOME, ".codex", "skills"),
|
|
112
|
+
os.path.join(HOME, ".codex", "skills", ".system"),
|
|
113
|
+
os.path.join(HOME, ".agents", "skills")]
|
|
114
|
+
roots += [os.path.join(d, ".agents", "skills") for d in ancestors(folder) if d != HOME]
|
|
115
|
+
return scan_skill_dirs(roots), []
|