gek 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.
- gek/__init__.py +9 -0
- gek/__main__.py +3 -0
- gek/agent.py +321 -0
- gek/cli.py +112 -0
- gek/config.py +168 -0
- gek/explain.py +118 -0
- gek/gitrepo.py +270 -0
- gek/llm.py +136 -0
- gek/logs.py +146 -0
- gek/mcp_bridge.py +99 -0
- gek/prompts.py +90 -0
- gek/roles.py +135 -0
- gek/swarm.py +377 -0
- gek/tools.py +85 -0
- gek-0.1.0.dist-info/METADATA +239 -0
- gek-0.1.0.dist-info/RECORD +19 -0
- gek-0.1.0.dist-info/WHEEL +4 -0
- gek-0.1.0.dist-info/entry_points.txt +3 -0
- gek-0.1.0.dist-info/licenses/LICENSE +21 -0
gek/__init__.py
ADDED
gek/__main__.py
ADDED
gek/agent.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""An agent: one role instance, one worktree, one branch, one tool loop."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import time
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
|
|
13
|
+
from .gitrepo import CHATTER, INBOX, MAIN, Identity
|
|
14
|
+
from .llm import BudgetExceeded
|
|
15
|
+
from .mcp_bridge import MCPBridge
|
|
16
|
+
from .prompts import agent_system
|
|
17
|
+
from .roles import Role
|
|
18
|
+
from .tools import I, S, ToolBox, arr, obj
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from .swarm import Swarm
|
|
22
|
+
|
|
23
|
+
CONTEXT_SOFT_LIMIT = 250_000 # chars; older tool outputs get elided past this
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class AgentHandle:
|
|
28
|
+
id: str
|
|
29
|
+
role: Role
|
|
30
|
+
branch: str
|
|
31
|
+
worktree: Path
|
|
32
|
+
note: str = ""
|
|
33
|
+
spawned_at: float = field(default_factory=time.time)
|
|
34
|
+
task: asyncio.Task | None = None
|
|
35
|
+
status: str = "starting" # starting, running, finished, killed, failed
|
|
36
|
+
steps: int = 0
|
|
37
|
+
summary: str = ""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Agent:
|
|
41
|
+
def __init__(self, swarm: "Swarm", h: AgentHandle):
|
|
42
|
+
self.swarm = swarm
|
|
43
|
+
self.h = h
|
|
44
|
+
self.ident = Identity.for_actor(h.id)
|
|
45
|
+
self.finished: str | None = None
|
|
46
|
+
cfg = swarm.cfg.section("agents")
|
|
47
|
+
self.box = ToolBox(h.id, swarm.log, max_output=cfg.get("max_tool_output_chars", 12000))
|
|
48
|
+
self.mcp = MCPBridge(h.id, swarm.log)
|
|
49
|
+
self.messages: list[dict[str, Any]] = []
|
|
50
|
+
|
|
51
|
+
# ---------------------------------------------------------------- paths
|
|
52
|
+
def _path(self, rel: str) -> Path:
|
|
53
|
+
rel = (rel or ".").replace("\\", "/")
|
|
54
|
+
p = (self.h.worktree / rel).resolve()
|
|
55
|
+
root = self.h.worktree.resolve()
|
|
56
|
+
if p != root and root not in p.parents:
|
|
57
|
+
raise ValueError(f"path {rel!r} is outside your worktree")
|
|
58
|
+
if ".git" in p.relative_to(root).parts:
|
|
59
|
+
raise ValueError("the .git entry is off limits")
|
|
60
|
+
return p
|
|
61
|
+
|
|
62
|
+
# ---------------------------------------------------------------- tools
|
|
63
|
+
def _build_tools(self) -> None:
|
|
64
|
+
r = self.h.role
|
|
65
|
+
b = self.box
|
|
66
|
+
b.add("read_log", "Read the shared git log. refs: list of branch names "
|
|
67
|
+
"(main, swarm/chatter, swarm/roles, role/<role>/<hex>); empty = all refs. "
|
|
68
|
+
"since_minutes limits to recent commits.",
|
|
69
|
+
obj(refs=arr(), since_minutes=I, limit=I), self.t_read_log)
|
|
70
|
+
b.add("list_files", "List files in your worktree (or under a subdirectory).",
|
|
71
|
+
obj(path=S), self.t_list_files)
|
|
72
|
+
b.add("read_file", "Read a file from your worktree. Use ref to read it from another "
|
|
73
|
+
"branch instead (e.g. main, or another agent's branch).",
|
|
74
|
+
obj(["path"], path=S, ref=S), self.t_read_file)
|
|
75
|
+
if r.writes:
|
|
76
|
+
b.add("write_file", "Write a whole file in your worktree (creates directories). "
|
|
77
|
+
f"You may only commit under: {', '.join(r.writes)}.",
|
|
78
|
+
obj(["path", "content"], path=S, content=S), self.t_write_file)
|
|
79
|
+
b.add("commit", "Commit all changes in your worktree to your branch. Fails if you "
|
|
80
|
+
"changed paths outside your writes scope.",
|
|
81
|
+
obj(["message"], message=S), self.t_commit)
|
|
82
|
+
if r.powers.shell:
|
|
83
|
+
b.add("run", "Run a shell command in your worktree. Returns exit code and output.",
|
|
84
|
+
obj(["command"], command=S, timeout_s=I), self.t_run)
|
|
85
|
+
b.add("post", "Post to swarm/chatter (status, handoffs, problems, accusations). "
|
|
86
|
+
"Everyone reads it.", obj(["message"], message=S), self.t_post)
|
|
87
|
+
if r.powers.interrupt:
|
|
88
|
+
b.add("interrupt", "Post to the orchestrator's inbox. This wakes it up; use sparingly.",
|
|
89
|
+
obj(["message"], message=S), self.t_interrupt)
|
|
90
|
+
if r.powers.merge:
|
|
91
|
+
b.add("merge", "Merge a branch into main. Reports conflicts instead of merging if any.",
|
|
92
|
+
obj(["branch"], branch=S, message=S), self.t_merge)
|
|
93
|
+
b.add("diff", "Show the diff a branch would bring into main.",
|
|
94
|
+
obj(["branch"], branch=S), self.t_diff)
|
|
95
|
+
if r.powers.kill:
|
|
96
|
+
b.add("list_agents", "List live agents.", obj(), self.t_list_agents)
|
|
97
|
+
b.add("kill", f"Kill a live agent of a role you may kill ({', '.join(r.powers.kill)}). "
|
|
98
|
+
"Give a reason; it goes on the record.",
|
|
99
|
+
obj(["agent_id", "reason"], agent_id=S, reason=S), self.t_kill)
|
|
100
|
+
b.add("finish", "End yourself. Call when your work is done or you are stuck for good. "
|
|
101
|
+
"Commit first: uncommitted work is lost.", obj(["summary"], summary=S), self.t_finish)
|
|
102
|
+
b.extra_schemas = self.mcp.schemas
|
|
103
|
+
b.fallback = self._mcp_call
|
|
104
|
+
|
|
105
|
+
async def _mcp_call(self, name: str, args: dict[str, Any]) -> str:
|
|
106
|
+
if name in self.mcp.tools:
|
|
107
|
+
return await self.mcp.call(name, args)
|
|
108
|
+
return f"ERROR: no tool named {name!r}"
|
|
109
|
+
|
|
110
|
+
async def t_read_log(self, refs: list[str] | None = None, since_minutes: int | None = None,
|
|
111
|
+
limit: int = 50) -> str:
|
|
112
|
+
since = time.time() - since_minutes * 60 if since_minutes else None
|
|
113
|
+
return await self.swarm.repo.log_text(refs or None, since=since, limit=min(limit, 300))
|
|
114
|
+
|
|
115
|
+
async def t_list_files(self, path: str = "") -> str:
|
|
116
|
+
root = self._path(path)
|
|
117
|
+
out = []
|
|
118
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
119
|
+
dirnames[:] = [d for d in dirnames if d != ".git"]
|
|
120
|
+
for f in filenames:
|
|
121
|
+
if f == ".git":
|
|
122
|
+
continue
|
|
123
|
+
out.append(str((Path(dirpath) / f).relative_to(self.h.worktree)).replace("\\", "/"))
|
|
124
|
+
if len(out) > 2000:
|
|
125
|
+
out.append("...(more than 2000 files; list a subdirectory)")
|
|
126
|
+
break
|
|
127
|
+
return "\n".join(sorted(out)) or "(empty)"
|
|
128
|
+
|
|
129
|
+
async def t_read_file(self, path: str, ref: str = "") -> str:
|
|
130
|
+
if ref:
|
|
131
|
+
text = await self.swarm.repo.read_file_at(ref, path.replace("\\", "/"))
|
|
132
|
+
return text if text is not None else f"ERROR: {path} not found on {ref}"
|
|
133
|
+
p = self._path(path)
|
|
134
|
+
if not p.is_file():
|
|
135
|
+
return f"ERROR: no file {path}"
|
|
136
|
+
return p.read_text(encoding="utf-8", errors="replace")
|
|
137
|
+
|
|
138
|
+
async def t_write_file(self, path: str, content: str) -> str:
|
|
139
|
+
p = self._path(path)
|
|
140
|
+
rel = str(p.relative_to(self.h.worktree.resolve())).replace("\\", "/")
|
|
141
|
+
warn = "" if self.h.role.may_write(rel) else (
|
|
142
|
+
f" WARNING: {rel} is outside your writes scope; commit will refuse it.")
|
|
143
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
with open(p, "w", encoding="utf-8", newline="") as f:
|
|
145
|
+
f.write(content)
|
|
146
|
+
return f"wrote {rel} ({len(content)} chars).{warn}"
|
|
147
|
+
|
|
148
|
+
async def _changed_paths(self) -> list[str]:
|
|
149
|
+
out = await self.swarm.repo.git("status", "--porcelain=v1", "-z", "--untracked-files=all",
|
|
150
|
+
cwd=self.h.worktree, actor=self.h.id)
|
|
151
|
+
items = out.split("\0")
|
|
152
|
+
paths, i = [], 0
|
|
153
|
+
while i < len(items):
|
|
154
|
+
e = items[i]
|
|
155
|
+
if len(e) > 3:
|
|
156
|
+
paths.append(e[3:])
|
|
157
|
+
if e[0] in "RC":
|
|
158
|
+
i += 1
|
|
159
|
+
if i < len(items) and items[i]:
|
|
160
|
+
paths.append(items[i])
|
|
161
|
+
i += 1
|
|
162
|
+
return paths
|
|
163
|
+
|
|
164
|
+
async def t_commit(self, message: str) -> str:
|
|
165
|
+
changed = await self._changed_paths()
|
|
166
|
+
if not changed:
|
|
167
|
+
return "nothing to commit"
|
|
168
|
+
bad = [p for p in changed if not self.h.role.may_write(p)]
|
|
169
|
+
if bad:
|
|
170
|
+
return ("ERROR: refusing to commit; these paths are outside your writes scope "
|
|
171
|
+
f"({', '.join(self.h.role.writes)}): {', '.join(bad[:30])}. "
|
|
172
|
+
"Revert them (e.g. `git checkout -- <path>` or delete new files) and retry.")
|
|
173
|
+
repo = self.swarm.repo
|
|
174
|
+
await repo.git("add", "-A", cwd=self.h.worktree, actor=self.h.id)
|
|
175
|
+
trailers = f"\n\nRole: {self.h.role.name}\nInstance: {self.h.id.split('/')[-1]}"
|
|
176
|
+
await repo.git("commit", "-q", "-m", message.strip() + trailers, cwd=self.h.worktree,
|
|
177
|
+
identity=self.ident, actor=self.h.id)
|
|
178
|
+
sha = (await repo.git("rev-parse", "HEAD", cwd=self.h.worktree)).strip()
|
|
179
|
+
self.swarm.log.event("commit", self.h.id, ref=self.h.branch, sha=sha, message=message,
|
|
180
|
+
files=changed)
|
|
181
|
+
return f"committed {sha[:10]} on {self.h.branch} ({len(changed)} paths)"
|
|
182
|
+
|
|
183
|
+
async def t_run(self, command: str, timeout_s: int | None = None) -> str:
|
|
184
|
+
limit = min(timeout_s or 10**9, self.swarm.cfg.section("agents").get("shell_timeout_s", 180))
|
|
185
|
+
proc = await asyncio.create_subprocess_shell(
|
|
186
|
+
command, cwd=str(self.h.worktree), stdout=asyncio.subprocess.PIPE,
|
|
187
|
+
stderr=asyncio.subprocess.STDOUT)
|
|
188
|
+
try:
|
|
189
|
+
out, _ = await asyncio.wait_for(proc.communicate(), timeout=limit)
|
|
190
|
+
except asyncio.TimeoutError:
|
|
191
|
+
proc.kill()
|
|
192
|
+
return f"ERROR: timed out after {limit}s"
|
|
193
|
+
return f"exit {proc.returncode}\n{out.decode('utf-8', 'replace')}"
|
|
194
|
+
|
|
195
|
+
async def t_post(self, message: str) -> str:
|
|
196
|
+
sha = await self.swarm.post(CHATTER, self.h.id, message,
|
|
197
|
+
{"Role": self.h.role.name, "Instance": self.h.id.split("/")[-1],
|
|
198
|
+
"Branch": self.h.branch})
|
|
199
|
+
return f"posted {sha[:10]}"
|
|
200
|
+
|
|
201
|
+
async def t_interrupt(self, message: str) -> str:
|
|
202
|
+
sha = await self.swarm.post(INBOX, self.h.id, message, {"Role": self.h.role.name})
|
|
203
|
+
return f"sent to inbox {sha[:10]}"
|
|
204
|
+
|
|
205
|
+
async def t_merge(self, branch: str, message: str = "") -> str:
|
|
206
|
+
ok, res = await self.swarm.repo.merge_into_main(
|
|
207
|
+
branch, message or f"merge {branch}\n\nMerged-By: {self.h.id}", self.ident, self.h.id)
|
|
208
|
+
return res if ok else "ERROR: " + res
|
|
209
|
+
|
|
210
|
+
async def t_diff(self, branch: str) -> str:
|
|
211
|
+
return await self.swarm.repo.git("diff", f"refs/heads/{MAIN}...refs/heads/{branch}",
|
|
212
|
+
check=False, actor=self.h.id) or "(no diff)"
|
|
213
|
+
|
|
214
|
+
async def t_list_agents(self) -> str:
|
|
215
|
+
return self.swarm.describe_agents()
|
|
216
|
+
|
|
217
|
+
async def t_kill(self, agent_id: str, reason: str) -> str:
|
|
218
|
+
target = self.swarm.agents.get(agent_id)
|
|
219
|
+
if not target or target.status not in ("starting", "running"):
|
|
220
|
+
return f"ERROR: no live agent {agent_id}"
|
|
221
|
+
if not self.h.role.may_kill(target.role.name):
|
|
222
|
+
return f"ERROR: you may not kill role {target.role.name}"
|
|
223
|
+
if agent_id == self.h.id:
|
|
224
|
+
return "ERROR: use finish to end yourself"
|
|
225
|
+
await self.swarm.kill(agent_id, self.h.id, reason)
|
|
226
|
+
return f"killed {agent_id}"
|
|
227
|
+
|
|
228
|
+
async def t_finish(self, summary: str) -> str:
|
|
229
|
+
self.finished = summary
|
|
230
|
+
return "ok, ending"
|
|
231
|
+
|
|
232
|
+
# ----------------------------------------------------------------- loop
|
|
233
|
+
def _record(self, msg: dict[str, Any]) -> None:
|
|
234
|
+
self.messages.append(msg)
|
|
235
|
+
self.swarm.log.transcript(self.h.id, msg)
|
|
236
|
+
|
|
237
|
+
def _elide(self) -> None:
|
|
238
|
+
total = sum(len(json.dumps(m, default=str)) for m in self.messages)
|
|
239
|
+
if total <= CONTEXT_SOFT_LIMIT:
|
|
240
|
+
return
|
|
241
|
+
for m in self.messages[2:-12]:
|
|
242
|
+
if m.get("role") == "tool" and len(m.get("content", "")) > 200:
|
|
243
|
+
m["content"] = m["content"][:200] + "...(elided to save context; re-run the tool if needed)"
|
|
244
|
+
|
|
245
|
+
async def run(self) -> None:
|
|
246
|
+
sw = self.swarm
|
|
247
|
+
h = self.h
|
|
248
|
+
cfg = sw.cfg.section("agents")
|
|
249
|
+
max_steps = h.role.max_steps or cfg.get("max_steps", 60)
|
|
250
|
+
how = "max_steps"
|
|
251
|
+
try:
|
|
252
|
+
await self.mcp.connect(h.role.powers.mcp, sw.cfg.raw.get("mcp_servers", {}))
|
|
253
|
+
self._build_tools()
|
|
254
|
+
h.status = "running"
|
|
255
|
+
model = sw.cfg.model(h.role.model or None)
|
|
256
|
+
self._record({"role": "system", "content": agent_system(h.role, h.id, h.branch, sw.goal)})
|
|
257
|
+
chatter = await sw.repo.log_text([CHATTER], limit=30, max_chars=8000)
|
|
258
|
+
mainlog = await sw.repo.log_text([MAIN], limit=10, max_chars=3000)
|
|
259
|
+
self._record({"role": "user", "content": (
|
|
260
|
+
f"You have just been spawned. Note from the orchestrator: {h.note or '(none)'}\n\n"
|
|
261
|
+
f"Recent chatter:\n{chatter}\n\nRecent main:\n{mainlog}\n\nBegin.")})
|
|
262
|
+
tools = self.box.schemas()
|
|
263
|
+
for step in range(max_steps):
|
|
264
|
+
h.steps = step + 1
|
|
265
|
+
self._elide()
|
|
266
|
+
msg = await sw.llm.chat(h.id, model, self.messages, tools)
|
|
267
|
+
self._record(msg)
|
|
268
|
+
calls = msg.get("tool_calls") or []
|
|
269
|
+
if not calls:
|
|
270
|
+
self._record({"role": "user", "content": (
|
|
271
|
+
"Keep going with tools. If you are done, commit and call finish.")})
|
|
272
|
+
continue
|
|
273
|
+
for tc in calls:
|
|
274
|
+
out = await self.box.run(tc["function"]["name"], tc["function"]["arguments"])
|
|
275
|
+
self._record({"role": "tool", "tool_call_id": tc["id"], "content": out})
|
|
276
|
+
if self.finished is not None:
|
|
277
|
+
how = "finish"
|
|
278
|
+
h.summary = self.finished
|
|
279
|
+
break
|
|
280
|
+
except asyncio.CancelledError:
|
|
281
|
+
# Killed. Clear the cancellation so teardown (MCP close, exit record) runs cleanly;
|
|
282
|
+
# the task then ends normally. Nothing awaits an agent's result.
|
|
283
|
+
how = "killed"
|
|
284
|
+
task = asyncio.current_task()
|
|
285
|
+
if task is not None:
|
|
286
|
+
while task.uncancel():
|
|
287
|
+
pass
|
|
288
|
+
except BudgetExceeded as e:
|
|
289
|
+
how = "budget"
|
|
290
|
+
h.summary = str(e)
|
|
291
|
+
except Exception as e:
|
|
292
|
+
how = "error"
|
|
293
|
+
h.summary = f"{type(e).__name__}: {e}"
|
|
294
|
+
sw.log.event("note", h.id, error=h.summary)
|
|
295
|
+
finally:
|
|
296
|
+
h.status = {"finish": "finished", "killed": "killed"}.get(how, "failed" if how == "error" else how)
|
|
297
|
+
# MCP sessions must close in the task that opened them (anyio cancel scopes)
|
|
298
|
+
try:
|
|
299
|
+
await self.mcp.close()
|
|
300
|
+
except BaseException:
|
|
301
|
+
pass
|
|
302
|
+
await asyncio.shield(self._teardown(how))
|
|
303
|
+
|
|
304
|
+
async def _teardown(self, how: str) -> None:
|
|
305
|
+
sw, h = self.swarm, self.h
|
|
306
|
+
dirty = []
|
|
307
|
+
try:
|
|
308
|
+
dirty = await self._changed_paths()
|
|
309
|
+
except Exception:
|
|
310
|
+
pass
|
|
311
|
+
sw.log.event("agent_exit", h.id, how=how, steps=h.steps, summary=h.summary,
|
|
312
|
+
uncommitted_lost=dirty[:50], branch=h.branch,
|
|
313
|
+
lived_s=round(time.time() - h.spawned_at, 1))
|
|
314
|
+
try:
|
|
315
|
+
await sw.post(CHATTER, h.id, f"exit ({how}): {h.summary or 'no summary'}",
|
|
316
|
+
{"Role": h.role.name, "Instance": h.id.split("/")[-1],
|
|
317
|
+
"Branch": h.branch, "Exit": how})
|
|
318
|
+
except Exception as e:
|
|
319
|
+
sw.log.event("note", h.id, error=f"could not post exit: {e}")
|
|
320
|
+
await sw.repo.remove_worktree(h.worktree)
|
|
321
|
+
sw.on_agent_exit(h, how)
|
gek/cli.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Command line: gek init | run | inbox | explain"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .config import ENV_TEMPLATE, load_config, write_default_config
|
|
11
|
+
from .gitrepo import INBOX, Identity, Repo
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def _init(args: argparse.Namespace) -> int:
|
|
15
|
+
root = Path(args.dir).resolve()
|
|
16
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
17
|
+
cfg_path = root / "config.json"
|
|
18
|
+
if not cfg_path.exists():
|
|
19
|
+
write_default_config(cfg_path, args.goal)
|
|
20
|
+
print(f"wrote {cfg_path}")
|
|
21
|
+
else:
|
|
22
|
+
print(f"kept existing {cfg_path}")
|
|
23
|
+
env_path = root / ".env"
|
|
24
|
+
if not env_path.exists():
|
|
25
|
+
env_path.write_text(ENV_TEMPLATE, encoding="utf-8")
|
|
26
|
+
print(f"wrote {env_path} (put your API key in it)")
|
|
27
|
+
cfg = load_config(cfg_path)
|
|
28
|
+
if cfg.repo_dir.exists():
|
|
29
|
+
print(f"swarm repo already exists at {cfg.repo_dir}")
|
|
30
|
+
return 0
|
|
31
|
+
seed = Path(args.seed).resolve() if args.seed else None
|
|
32
|
+
await Repo.init(cfg.repo_dir, cfg.raw.get("goal", ""), seed, None)
|
|
33
|
+
cfg.logs_dir.mkdir(parents=True, exist_ok=True)
|
|
34
|
+
print(f"created swarm repo at {cfg.repo_dir}" + (f" (seeded from {seed})" if seed else ""))
|
|
35
|
+
print("next: edit config.json (goal, models) and .env, then `gek run`")
|
|
36
|
+
return 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def _run(args: argparse.Namespace) -> int:
|
|
40
|
+
from .logs import RunLog
|
|
41
|
+
from .swarm import Swarm
|
|
42
|
+
|
|
43
|
+
cfg = load_config(args.config)
|
|
44
|
+
if args.goal:
|
|
45
|
+
cfg.raw["goal"] = args.goal
|
|
46
|
+
if not cfg.repo_dir.exists():
|
|
47
|
+
print(f"no swarm repo at {cfg.repo_dir}; run `gek init` first", file=sys.stderr)
|
|
48
|
+
return 2
|
|
49
|
+
log = RunLog(cfg.logs_dir, echo="none" if args.quiet else ("all" if args.verbose else "feed"))
|
|
50
|
+
print(f"gek run {log.run_id}; logs in {log.dir}", file=sys.stderr)
|
|
51
|
+
swarm = Swarm(cfg, log)
|
|
52
|
+
try:
|
|
53
|
+
reason = await swarm.run()
|
|
54
|
+
finally:
|
|
55
|
+
log.close()
|
|
56
|
+
print(f"swarm stopped: {reason}", file=sys.stderr)
|
|
57
|
+
return 0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def _inbox(args: argparse.Namespace) -> int:
|
|
61
|
+
cfg = load_config(args.config)
|
|
62
|
+
repo = Repo(cfg.repo_dir)
|
|
63
|
+
who = args.sender
|
|
64
|
+
from .swarm import _message
|
|
65
|
+
|
|
66
|
+
text = _message(args.message, {"From": who})
|
|
67
|
+
sha = await repo.empty_commit(INBOX, text, Identity(who, f"{who}@outside.gek"), actor=who)
|
|
68
|
+
print(f"posted to swarm/inbox as {who}: {sha[:10]}")
|
|
69
|
+
return 0
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
async def _explain(args: argparse.Namespace) -> int:
|
|
73
|
+
from .explain import explain
|
|
74
|
+
|
|
75
|
+
cfg = load_config(args.config)
|
|
76
|
+
print(await explain(cfg, args.run, args.chatter))
|
|
77
|
+
return 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def main(argv: list[str] | None = None) -> None:
|
|
81
|
+
p = argparse.ArgumentParser(prog="gek", description="Asynchronous agent swarm harness over git.")
|
|
82
|
+
p.add_argument("--config", "-c", default=None, help="path to config.json (default ./config.json)")
|
|
83
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
84
|
+
|
|
85
|
+
s = sub.add_parser("init", help="create config.json, .env and the swarm repo")
|
|
86
|
+
s.add_argument("--dir", default=".", help="where config.json lives (default .)")
|
|
87
|
+
s.add_argument("--goal", default=None, help="goal text for a new config")
|
|
88
|
+
s.add_argument("--seed", default=None, help="existing git repo to clone as the starting main")
|
|
89
|
+
s.set_defaults(fn=_init)
|
|
90
|
+
|
|
91
|
+
s = sub.add_parser("run", help="run the swarm until halt, budget or Ctrl-C")
|
|
92
|
+
s.add_argument("--goal", default=None, help="override the goal for this run")
|
|
93
|
+
s.add_argument("--quiet", "-q", action="store_true", help="print nothing; everything still goes to the logs")
|
|
94
|
+
s.add_argument("--verbose", "-v", action="store_true", help="echo every event (the firehose) to stderr")
|
|
95
|
+
s.set_defaults(fn=_run)
|
|
96
|
+
|
|
97
|
+
s = sub.add_parser("inbox", help="send a message to the orchestrator's inbox")
|
|
98
|
+
s.add_argument("message")
|
|
99
|
+
s.add_argument("--as", dest="sender", default="human", help="sender name (default human)")
|
|
100
|
+
s.set_defaults(fn=_inbox)
|
|
101
|
+
|
|
102
|
+
s = sub.add_parser("explain", help="summarize the latest run and the repo")
|
|
103
|
+
s.add_argument("--run", default=None, help="run id (prefix ok)")
|
|
104
|
+
s.add_argument("--chatter", type=int, default=25, help="how many chatter commits to show")
|
|
105
|
+
s.set_defaults(fn=_explain)
|
|
106
|
+
|
|
107
|
+
args = p.parse_args(argv)
|
|
108
|
+
try:
|
|
109
|
+
code = asyncio.run(args.fn(args))
|
|
110
|
+
except KeyboardInterrupt:
|
|
111
|
+
code = 130
|
|
112
|
+
sys.exit(code)
|
gek/config.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Configuration: .env for secrets, config.json for everything else.
|
|
2
|
+
|
|
3
|
+
Lookup order for config.json: --config flag, then ./config.json.
|
|
4
|
+
The .env file is loaded from the same directory as config.json (and then
|
|
5
|
+
from the current directory), without overriding variables already set.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from dotenv import load_dotenv
|
|
17
|
+
|
|
18
|
+
DEFAULT_CONFIG: dict[str, Any] = {
|
|
19
|
+
"_comment": "gek config. Secrets go in .env, not here. See README.md for every key.",
|
|
20
|
+
"swarm_dir": "swarm",
|
|
21
|
+
"goal": "Describe what the swarm should work on. The orchestrator reads this every wake.",
|
|
22
|
+
"api": {
|
|
23
|
+
"api_base_env": "GEK_API_BASE",
|
|
24
|
+
"api_key_env": "GEK_API_KEY",
|
|
25
|
+
},
|
|
26
|
+
"models": {
|
|
27
|
+
"orchestrator": "openai/auto",
|
|
28
|
+
"default": "openai/auto",
|
|
29
|
+
"aliases": {
|
|
30
|
+
"smart": "openai/auto",
|
|
31
|
+
"cheap": "openai/auto",
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
"llm": {
|
|
35
|
+
"temperature": None,
|
|
36
|
+
"timeout_s": 600,
|
|
37
|
+
"num_retries": 3,
|
|
38
|
+
"extra_params": {},
|
|
39
|
+
},
|
|
40
|
+
"orchestrator": {
|
|
41
|
+
"default_sleep_s": 300,
|
|
42
|
+
"min_sleep_s": 20,
|
|
43
|
+
"max_sleep_s": 3600,
|
|
44
|
+
"debounce_s": 10,
|
|
45
|
+
"inbox_poll_s": 5,
|
|
46
|
+
"max_steps_per_wake": 30,
|
|
47
|
+
"log_chars_per_wake": 30000,
|
|
48
|
+
"wake_on_agent_exit": True,
|
|
49
|
+
},
|
|
50
|
+
"agents": {
|
|
51
|
+
"max_alive": 6,
|
|
52
|
+
"max_steps": 60,
|
|
53
|
+
"max_tool_output_chars": 12000,
|
|
54
|
+
"shell_timeout_s": 180,
|
|
55
|
+
},
|
|
56
|
+
"budget": {
|
|
57
|
+
"max_total_tokens": 5_000_000,
|
|
58
|
+
},
|
|
59
|
+
"ceiling": {
|
|
60
|
+
"_comment": "The most power the orchestrator may grant to any role.",
|
|
61
|
+
"shell": True,
|
|
62
|
+
"merge": True,
|
|
63
|
+
"interrupt": True,
|
|
64
|
+
"kill": ["*"],
|
|
65
|
+
"mcp": {},
|
|
66
|
+
},
|
|
67
|
+
"mcp_servers": {
|
|
68
|
+
"_comment": "name -> {command, args, env}. Grant them to roles via ceiling.mcp.",
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _deep_merge(base: dict, over: dict) -> dict:
|
|
74
|
+
out = dict(base)
|
|
75
|
+
for k, v in over.items():
|
|
76
|
+
if isinstance(v, dict) and isinstance(out.get(k), dict):
|
|
77
|
+
out[k] = _deep_merge(out[k], v)
|
|
78
|
+
else:
|
|
79
|
+
out[k] = v
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class Config:
|
|
85
|
+
path: Path
|
|
86
|
+
raw: dict[str, Any] = field(default_factory=dict)
|
|
87
|
+
|
|
88
|
+
# convenience accessors -------------------------------------------------
|
|
89
|
+
@property
|
|
90
|
+
def root(self) -> Path:
|
|
91
|
+
return self.path.parent
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def swarm_dir(self) -> Path:
|
|
95
|
+
p = Path(self.raw["swarm_dir"])
|
|
96
|
+
return p if p.is_absolute() else (self.root / p)
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def repo_dir(self) -> Path:
|
|
100
|
+
return self.swarm_dir / "repo.git"
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def worktrees_dir(self) -> Path:
|
|
104
|
+
return self.swarm_dir / "wt"
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def logs_dir(self) -> Path:
|
|
108
|
+
return self.swarm_dir / "logs"
|
|
109
|
+
|
|
110
|
+
def section(self, name: str) -> dict[str, Any]:
|
|
111
|
+
return self.raw.get(name, {})
|
|
112
|
+
|
|
113
|
+
def model(self, name: str | None) -> str:
|
|
114
|
+
models = self.raw["models"]
|
|
115
|
+
if not name:
|
|
116
|
+
return models["default"]
|
|
117
|
+
return models.get("aliases", {}).get(name, name)
|
|
118
|
+
|
|
119
|
+
def api_kwargs(self) -> dict[str, Any]:
|
|
120
|
+
api = self.raw.get("api", {})
|
|
121
|
+
kw: dict[str, Any] = {}
|
|
122
|
+
base = os.environ.get(api.get("api_base_env", "GEK_API_BASE"))
|
|
123
|
+
key = os.environ.get(api.get("api_key_env", "GEK_API_KEY"))
|
|
124
|
+
if base:
|
|
125
|
+
kw["api_base"] = base
|
|
126
|
+
if key:
|
|
127
|
+
kw["api_key"] = key
|
|
128
|
+
return kw
|
|
129
|
+
|
|
130
|
+
def redacted(self) -> dict[str, Any]:
|
|
131
|
+
"""Config as logged: config.json never holds secrets, but env names are noted."""
|
|
132
|
+
api = self.raw.get("api", {})
|
|
133
|
+
return {
|
|
134
|
+
**self.raw,
|
|
135
|
+
"_env_present": {
|
|
136
|
+
v: bool(os.environ.get(v)) for v in api.values() if isinstance(v, str)
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def load_config(path: str | os.PathLike | None = None) -> Config:
|
|
142
|
+
p = Path(path) if path else Path.cwd() / "config.json"
|
|
143
|
+
p = p.resolve()
|
|
144
|
+
load_dotenv(p.parent / ".env", override=False)
|
|
145
|
+
load_dotenv(Path.cwd() / ".env", override=False)
|
|
146
|
+
if not p.exists():
|
|
147
|
+
raise FileNotFoundError(
|
|
148
|
+
f"No config at {p}. Run `gek init` to create config.json and .env."
|
|
149
|
+
)
|
|
150
|
+
with open(p, encoding="utf-8") as f:
|
|
151
|
+
user = json.load(f)
|
|
152
|
+
return Config(path=p, raw=_deep_merge(DEFAULT_CONFIG, user))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def write_default_config(path: Path, goal: str | None) -> None:
|
|
156
|
+
cfg = json.loads(json.dumps(DEFAULT_CONFIG))
|
|
157
|
+
if goal:
|
|
158
|
+
cfg["goal"] = goal
|
|
159
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
160
|
+
json.dump(cfg, f, indent=2)
|
|
161
|
+
f.write("\n")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
ENV_TEMPLATE = """\
|
|
165
|
+
# gek secrets. Never commit this file.
|
|
166
|
+
GEK_API_BASE=https://app.vllm-sr.ai/v1
|
|
167
|
+
GEK_API_KEY=put-your-key-here
|
|
168
|
+
"""
|