agents-bus 0.2.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_bus/__init__.py +3 -0
- agent_bus/cli.py +570 -0
- agent_bus/gate.py +30 -0
- agent_bus/mcp_server.py +186 -0
- agent_bus/remote.py +86 -0
- agent_bus/sandbox.py +126 -0
- agent_bus/store.py +212 -0
- agents_bus-0.2.0.dist-info/LICENSE +21 -0
- agents_bus-0.2.0.dist-info/METADATA +232 -0
- agents_bus-0.2.0.dist-info/RECORD +13 -0
- agents_bus-0.2.0.dist-info/WHEEL +5 -0
- agents_bus-0.2.0.dist-info/entry_points.txt +4 -0
- agents_bus-0.2.0.dist-info/top_level.txt +1 -0
agent_bus/__init__.py
ADDED
agent_bus/cli.py
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
"""agent-bus command line interface."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import platform
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import signal
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .remote import RemoteStore
|
|
16
|
+
from .sandbox import Sandbox, SandboxError
|
|
17
|
+
from .store import BusError, Store
|
|
18
|
+
|
|
19
|
+
# A task body may start with "@workdir: /path/to/project" to choose the
|
|
20
|
+
# directory the runner executes in (falls back to --dir).
|
|
21
|
+
_WORKDIR_RE = re.compile(r"^@workdir:\s*(.+?)\s*$")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _split_workdir(body):
|
|
25
|
+
"""Return (workdir or None, body without the directive line)."""
|
|
26
|
+
lines = body.splitlines()
|
|
27
|
+
if lines:
|
|
28
|
+
match = _WORKDIR_RE.match(lines[0].strip())
|
|
29
|
+
if match:
|
|
30
|
+
return match.group(1), "\n".join(lines[1:]).lstrip("\n")
|
|
31
|
+
return None, body
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _body(args):
|
|
35
|
+
if args.body is not None:
|
|
36
|
+
return args.body
|
|
37
|
+
if not sys.stdin.isatty():
|
|
38
|
+
return sys.stdin.read()
|
|
39
|
+
return ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _log(msg):
|
|
43
|
+
sys.stderr.write("[agent-bus] %s\n" % msg)
|
|
44
|
+
sys.stderr.flush()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _print_tasks(tasks):
|
|
48
|
+
if not tasks:
|
|
49
|
+
print("(no tasks)")
|
|
50
|
+
return
|
|
51
|
+
for task in tasks:
|
|
52
|
+
print("%s [%s] %s (from %s, %s)" % (
|
|
53
|
+
task["id"], task.get("status", "?"), task.get("title", ""),
|
|
54
|
+
task.get("sender", "?"), task.get("created_at", "?")))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _state_dir():
|
|
58
|
+
path = os.path.join(os.path.expanduser("~"), ".agent-bus", "worker")
|
|
59
|
+
os.makedirs(path, exist_ok=True)
|
|
60
|
+
return path
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _pid_path(me):
|
|
64
|
+
return os.path.join(_state_dir(), me + ".pid")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _default_log(me):
|
|
68
|
+
return os.path.join(_state_dir(), me + ".log")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _pid_alive(pid):
|
|
72
|
+
if not pid:
|
|
73
|
+
return False
|
|
74
|
+
if os.name == "nt":
|
|
75
|
+
try:
|
|
76
|
+
out = subprocess.run(["tasklist", "/FI", "PID eq %s" % pid, "/NH"],
|
|
77
|
+
capture_output=True, text=True,
|
|
78
|
+
encoding="utf-8", errors="replace", timeout=10)
|
|
79
|
+
return str(pid) in (out.stdout or "")
|
|
80
|
+
except Exception:
|
|
81
|
+
return False
|
|
82
|
+
try:
|
|
83
|
+
os.kill(int(pid), 0)
|
|
84
|
+
return True
|
|
85
|
+
except (OSError, ValueError):
|
|
86
|
+
return False
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _run_claude(body, extra, workdir, timeout, wrap=None):
|
|
90
|
+
argv = ["claude", "-p", body, "--output-format", "text"] + extra
|
|
91
|
+
if wrap is not None:
|
|
92
|
+
argv = wrap(argv)
|
|
93
|
+
return subprocess.run(argv, cwd=workdir, capture_output=True,
|
|
94
|
+
text=True, encoding="utf-8", errors="replace",
|
|
95
|
+
timeout=timeout)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _run_shell(body, extra, workdir, timeout, wrap=None):
|
|
99
|
+
if wrap is not None:
|
|
100
|
+
argv = wrap(["bash", "-lc", body])
|
|
101
|
+
return subprocess.run(argv, cwd=workdir, capture_output=True,
|
|
102
|
+
text=True, encoding="utf-8", errors="replace",
|
|
103
|
+
timeout=timeout)
|
|
104
|
+
return subprocess.run(body, shell=True, cwd=workdir, capture_output=True,
|
|
105
|
+
text=True, encoding="utf-8", errors="replace",
|
|
106
|
+
timeout=timeout)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def cmd_send(store, args):
|
|
110
|
+
task = store.send(args.target, args.title, _body(args), args.sender)
|
|
111
|
+
print(json.dumps(task, ensure_ascii=False) if args.json else task["id"])
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def cmd_tasks(store, args):
|
|
116
|
+
tasks = store.list_tasks(args.me, include_all=args.all)
|
|
117
|
+
if args.json:
|
|
118
|
+
print(json.dumps(tasks, ensure_ascii=False, indent=2))
|
|
119
|
+
else:
|
|
120
|
+
_print_tasks(tasks)
|
|
121
|
+
return 0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cmd_claim(store, args):
|
|
125
|
+
claimed = store.claim(args.me, args.id)
|
|
126
|
+
if args.json:
|
|
127
|
+
print(json.dumps({"id": args.id, "claimed": claimed}))
|
|
128
|
+
else:
|
|
129
|
+
print(("claimed " if claimed else "not claimable: ") + args.id)
|
|
130
|
+
return 0 if claimed else 1
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def cmd_requeue(store, args):
|
|
134
|
+
task = store.requeue(args.me, args.id)
|
|
135
|
+
if args.json:
|
|
136
|
+
print(json.dumps(task, ensure_ascii=False))
|
|
137
|
+
else:
|
|
138
|
+
print("requeued " + task["id"])
|
|
139
|
+
return 0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def cmd_done(store, args):
|
|
143
|
+
record = store.complete(args.me, args.id, args.status, _body(args))
|
|
144
|
+
if args.json:
|
|
145
|
+
print(json.dumps(record, ensure_ascii=False))
|
|
146
|
+
else:
|
|
147
|
+
print("done %s (%s)" % (record["id"], record["status"]))
|
|
148
|
+
return 0
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def cmd_show(store, args):
|
|
152
|
+
print(json.dumps(store.get_task(args.id, args.target), ensure_ascii=False, indent=2))
|
|
153
|
+
return 0
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def cmd_result(store, args):
|
|
157
|
+
print(json.dumps(store.get_result(args.id), ensure_ascii=False, indent=2))
|
|
158
|
+
return 0
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def cmd_list(store, args):
|
|
162
|
+
stats = store.stats()
|
|
163
|
+
if args.json:
|
|
164
|
+
print(json.dumps(stats, ensure_ascii=False, indent=2))
|
|
165
|
+
return 0
|
|
166
|
+
if not stats:
|
|
167
|
+
print("(empty)")
|
|
168
|
+
return 0
|
|
169
|
+
for target, counts in stats.items():
|
|
170
|
+
print("%-10s pending=%d running=%d done=%d failed=%d" % (
|
|
171
|
+
target, counts["pending"], counts["running"],
|
|
172
|
+
counts["done"], counts["failed"]))
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _detach_worker(args):
|
|
177
|
+
log_path = os.path.abspath(os.path.expanduser(args.log)) if args.log else _default_log(args.me)
|
|
178
|
+
os.makedirs(os.path.dirname(log_path) or ".", exist_ok=True)
|
|
179
|
+
raw = [a for a in getattr(args, "_raw", []) if a != "--detach"]
|
|
180
|
+
argv = [sys.executable, "-m", "agent_bus.cli"] + raw
|
|
181
|
+
logf = open(log_path, "ab")
|
|
182
|
+
kwargs = dict(stdout=logf, stderr=logf, stdin=subprocess.DEVNULL, cwd=os.getcwd())
|
|
183
|
+
if os.name == "nt":
|
|
184
|
+
kwargs["creationflags"] = (subprocess.DETACHED_PROCESS
|
|
185
|
+
| subprocess.CREATE_NEW_PROCESS_GROUP)
|
|
186
|
+
else:
|
|
187
|
+
kwargs["start_new_session"] = True
|
|
188
|
+
try:
|
|
189
|
+
proc = subprocess.Popen(argv, **kwargs)
|
|
190
|
+
finally:
|
|
191
|
+
logf.close()
|
|
192
|
+
state = {"pid": proc.pid, "me": args.me,
|
|
193
|
+
"started_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
|
194
|
+
"log": log_path, "mode": getattr(args, "_mode", "unknown")}
|
|
195
|
+
with open(_pid_path(args.me), "w", encoding="utf-8") as fh:
|
|
196
|
+
json.dump(state, fh, ensure_ascii=False, indent=2)
|
|
197
|
+
print("worker started in background: me=%s pid=%d" % (args.me, proc.pid))
|
|
198
|
+
print("log: %s" % log_path)
|
|
199
|
+
print("status: agent-bus status --me %s" % args.me)
|
|
200
|
+
print("stop: agent-bus stop --me %s" % args.me)
|
|
201
|
+
return 0
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def cmd_work(store, args):
|
|
205
|
+
if args.detach:
|
|
206
|
+
return _detach_worker(args)
|
|
207
|
+
|
|
208
|
+
workdir = os.path.abspath(os.path.expanduser(args.dir))
|
|
209
|
+
os.makedirs(workdir, exist_ok=True)
|
|
210
|
+
extra = list(args.extra or [])
|
|
211
|
+
if extra and extra[0] == "--":
|
|
212
|
+
extra = extra[1:]
|
|
213
|
+
runner = _run_claude if args.runner == "claude" else _run_shell
|
|
214
|
+
_log("mode: %s" % getattr(args, "_mode", "unknown"))
|
|
215
|
+
if not getattr(args, "_remote", False):
|
|
216
|
+
_log("NOTE: 本地模式 —— 任务只读写本地信箱,不会发往远端(用 --remote 或 AGENT_BUS_REMOTE)")
|
|
217
|
+
_log("worker up: me=%s dir=%s poll=%ss runner=%s" % (
|
|
218
|
+
args.me, workdir, args.poll, args.runner))
|
|
219
|
+
delay = 5
|
|
220
|
+
while True:
|
|
221
|
+
try:
|
|
222
|
+
tasks = store.list_tasks(args.me)
|
|
223
|
+
except BusError as exc:
|
|
224
|
+
_log("bus error: %s — retry in %ss" % (exc, delay))
|
|
225
|
+
time.sleep(delay)
|
|
226
|
+
delay = min(delay * 2, 120)
|
|
227
|
+
continue
|
|
228
|
+
delay = 5
|
|
229
|
+
for task in tasks:
|
|
230
|
+
try:
|
|
231
|
+
claimed = store.claim(args.me, task["id"])
|
|
232
|
+
except BusError as exc:
|
|
233
|
+
_log("claim failed %s: %s" % (task["id"], exc))
|
|
234
|
+
continue
|
|
235
|
+
if not claimed:
|
|
236
|
+
continue
|
|
237
|
+
_log("running %s: %s" % (task["id"], task.get("title", "")))
|
|
238
|
+
sandbox = None
|
|
239
|
+
status, output = "fail", ""
|
|
240
|
+
try:
|
|
241
|
+
body = store.get_task(task["id"]).get("body", "")
|
|
242
|
+
task_dir, body = _split_workdir(body)
|
|
243
|
+
task_dir = os.path.expanduser(task_dir) if task_dir else workdir
|
|
244
|
+
if not os.path.isdir(task_dir):
|
|
245
|
+
output = "workdir not found: %s" % task_dir
|
|
246
|
+
else:
|
|
247
|
+
sandbox = Sandbox(args.sandbox, task_dir, task["id"],
|
|
248
|
+
log=_log, keep=args.keep_worktrees,
|
|
249
|
+
image=args.docker_image,
|
|
250
|
+
network=args.docker_network)
|
|
251
|
+
_log("sandbox: %s (dir: %s)" % (sandbox.mode, sandbox.run_dir))
|
|
252
|
+
wrap = sandbox.wrap if sandbox.mode == "docker" else None
|
|
253
|
+
proc = runner(body, extra, sandbox.run_dir, args.timeout, wrap)
|
|
254
|
+
status = "ok" if proc.returncode == 0 else "fail"
|
|
255
|
+
output = proc.stdout or ""
|
|
256
|
+
if proc.stderr:
|
|
257
|
+
output += ("\n[stderr]\n" + proc.stderr) if output else ("[stderr]\n" + proc.stderr)
|
|
258
|
+
except SandboxError as exc:
|
|
259
|
+
output = "sandbox error: %s" % exc
|
|
260
|
+
except subprocess.TimeoutExpired:
|
|
261
|
+
status, output = "fail", "timeout after %ss" % args.timeout
|
|
262
|
+
except FileNotFoundError as exc:
|
|
263
|
+
status, output = "fail", "runner not found: %s" % exc
|
|
264
|
+
finally:
|
|
265
|
+
if sandbox is not None:
|
|
266
|
+
try:
|
|
267
|
+
info = sandbox.finish()
|
|
268
|
+
except Exception as exc: # noqa: BLE001
|
|
269
|
+
info = {"mode": sandbox.mode, "cleanup_error": repr(exc)}
|
|
270
|
+
if info.get("diff_stat"):
|
|
271
|
+
output += "\n\n--- sandbox (worktree) ---\n" + info["diff_stat"]
|
|
272
|
+
if info.get("diff"):
|
|
273
|
+
output += "\n" + info["diff"]
|
|
274
|
+
_log("sandbox %s finished" % info.get("mode"))
|
|
275
|
+
try:
|
|
276
|
+
store.complete(args.me, task["id"], status, output)
|
|
277
|
+
except BusError as exc:
|
|
278
|
+
_log("submit failed %s: %s (left running — use 'agent-bus reap')"
|
|
279
|
+
% (task["id"], exc))
|
|
280
|
+
else:
|
|
281
|
+
_log("finished %s -> %s" % (task["id"], status))
|
|
282
|
+
if args.once:
|
|
283
|
+
return 0
|
|
284
|
+
if args.once:
|
|
285
|
+
return 0
|
|
286
|
+
time.sleep(args.poll)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def cmd_doctor(store, args):
|
|
290
|
+
failures = 0
|
|
291
|
+
|
|
292
|
+
def check(tag, message, hint=None):
|
|
293
|
+
print("[%-4s] %s" % (tag, message))
|
|
294
|
+
if hint:
|
|
295
|
+
print(" hint: %s" % hint)
|
|
296
|
+
|
|
297
|
+
print("agent-bus doctor")
|
|
298
|
+
print("-" * 56)
|
|
299
|
+
check("PASS", "version %s" % __version__)
|
|
300
|
+
if sys.version_info >= (3, 8):
|
|
301
|
+
check("PASS", "python %s" % platform.python_version())
|
|
302
|
+
else:
|
|
303
|
+
failures += 1
|
|
304
|
+
check("FAIL", "python %s is too old" % platform.python_version(), "need >= 3.8")
|
|
305
|
+
check("INFO", "mode: %s" % getattr(args, "_mode", "unknown"))
|
|
306
|
+
|
|
307
|
+
if getattr(args, "_remote", False):
|
|
308
|
+
ssh = shutil.which("ssh")
|
|
309
|
+
if ssh:
|
|
310
|
+
check("PASS", "ssh client: %s" % ssh)
|
|
311
|
+
else:
|
|
312
|
+
failures += 1
|
|
313
|
+
check("FAIL", "ssh client not found", "install OpenSSH client")
|
|
314
|
+
key = args.remote_key or os.environ.get("AGENT_BUS_SSH_KEY")
|
|
315
|
+
if key:
|
|
316
|
+
key_path = os.path.expanduser(key)
|
|
317
|
+
if os.path.exists(key_path):
|
|
318
|
+
check("PASS", "ssh key: %s" % key_path)
|
|
319
|
+
else:
|
|
320
|
+
failures += 1
|
|
321
|
+
check("FAIL", "ssh key not found: %s" % key_path,
|
|
322
|
+
"check --remote-key / AGENT_BUS_SSH_KEY")
|
|
323
|
+
else:
|
|
324
|
+
check("WARN", "no ssh key configured", "set --remote-key or AGENT_BUS_SSH_KEY")
|
|
325
|
+
|
|
326
|
+
try:
|
|
327
|
+
stats = store.stats()
|
|
328
|
+
tasks = sum(sum(counts.values()) for counts in stats.values())
|
|
329
|
+
check("PASS", "bus reachable (%d targets, %d tasks)" % (len(stats), tasks))
|
|
330
|
+
if args.me:
|
|
331
|
+
pending = len(store.list_tasks(args.me))
|
|
332
|
+
check("PASS", "queue '%s': %d pending" % (args.me, pending))
|
|
333
|
+
except BusError as exc:
|
|
334
|
+
failures += 1
|
|
335
|
+
check("FAIL", "bus unreachable: %s" % exc, "check network, key and --remote")
|
|
336
|
+
except Exception as exc: # noqa: BLE001
|
|
337
|
+
failures += 1
|
|
338
|
+
check("FAIL", "bus error: %r" % exc)
|
|
339
|
+
|
|
340
|
+
claude = shutil.which("claude")
|
|
341
|
+
if claude:
|
|
342
|
+
try:
|
|
343
|
+
out = subprocess.run([claude, "--version"], capture_output=True, text=True,
|
|
344
|
+
encoding="utf-8", errors="replace", timeout=10)
|
|
345
|
+
first = (out.stdout or "").strip().splitlines()
|
|
346
|
+
check("PASS", "claude: %s" % (first[0] if first else claude))
|
|
347
|
+
except Exception as exc: # noqa: BLE001
|
|
348
|
+
check("WARN", "claude found but --version failed: %r" % exc)
|
|
349
|
+
else:
|
|
350
|
+
check("WARN", "claude not found (needed only for --runner claude)")
|
|
351
|
+
|
|
352
|
+
git = shutil.which("git")
|
|
353
|
+
check("PASS" if git else "WARN", "git: %s" % (
|
|
354
|
+
git or "not found (worktree sandbox disabled)"))
|
|
355
|
+
docker = shutil.which("docker")
|
|
356
|
+
check("PASS" if docker else "WARN", "docker: %s" % (
|
|
357
|
+
docker or "not found (docker sandbox disabled)"))
|
|
358
|
+
|
|
359
|
+
if args.dir:
|
|
360
|
+
target = os.path.abspath(os.path.expanduser(args.dir))
|
|
361
|
+
if os.path.isdir(target):
|
|
362
|
+
if os.access(target, os.W_OK):
|
|
363
|
+
check("PASS", "workdir: %s" % target)
|
|
364
|
+
else:
|
|
365
|
+
check("WARN", "workdir not writable: %s" % target)
|
|
366
|
+
else:
|
|
367
|
+
check("WARN", "workdir will be created: %s" % target)
|
|
368
|
+
|
|
369
|
+
print("-" * 56)
|
|
370
|
+
print("RESULT:", "OK" if failures == 0 else "FAILED")
|
|
371
|
+
return 0 if failures == 0 else 1
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def cmd_status(store, args):
|
|
375
|
+
path = _pid_path(args.me)
|
|
376
|
+
if not os.path.exists(path):
|
|
377
|
+
print("worker '%s': not running (no pid file)" % args.me)
|
|
378
|
+
return 1
|
|
379
|
+
with open(path, encoding="utf-8") as fh:
|
|
380
|
+
state = json.load(fh)
|
|
381
|
+
alive = _pid_alive(state.get("pid"))
|
|
382
|
+
print("worker '%s': %s (pid %s, started %s)" % (
|
|
383
|
+
args.me, "RUNNING" if alive else "STOPPED",
|
|
384
|
+
state.get("pid"), state.get("started_at")))
|
|
385
|
+
if state.get("mode"):
|
|
386
|
+
print("mode:", state["mode"])
|
|
387
|
+
log = state.get("log")
|
|
388
|
+
if log:
|
|
389
|
+
print("log:", log)
|
|
390
|
+
if os.path.exists(log):
|
|
391
|
+
with open(log, encoding="utf-8", errors="replace") as fh:
|
|
392
|
+
lines = fh.readlines()[-5:]
|
|
393
|
+
if lines:
|
|
394
|
+
print("--- last log lines ---")
|
|
395
|
+
print("".join(lines).rstrip())
|
|
396
|
+
return 0 if alive else 1
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def cmd_stop(store, args):
|
|
400
|
+
path = _pid_path(args.me)
|
|
401
|
+
if not os.path.exists(path):
|
|
402
|
+
print("worker '%s': not running" % args.me)
|
|
403
|
+
return 1
|
|
404
|
+
with open(path, encoding="utf-8") as fh:
|
|
405
|
+
state = json.load(fh)
|
|
406
|
+
pid = state.get("pid")
|
|
407
|
+
if _pid_alive(pid):
|
|
408
|
+
if os.name == "nt":
|
|
409
|
+
subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"],
|
|
410
|
+
capture_output=True)
|
|
411
|
+
else:
|
|
412
|
+
os.kill(int(pid), signal.SIGTERM)
|
|
413
|
+
print("stopped worker '%s' (pid %s)" % (args.me, pid))
|
|
414
|
+
else:
|
|
415
|
+
print("worker '%s' was not running (stale pid file)" % args.me)
|
|
416
|
+
try:
|
|
417
|
+
os.unlink(path)
|
|
418
|
+
except OSError:
|
|
419
|
+
pass
|
|
420
|
+
return 0
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def cmd_reap(store, args):
|
|
424
|
+
ids = store.reap(args.me, args.older * 60)
|
|
425
|
+
if args.json:
|
|
426
|
+
print(json.dumps({"reaped": ids}))
|
|
427
|
+
else:
|
|
428
|
+
print("reaped %d task(s)%s" % (len(ids), (": " + ", ".join(ids)) if ids else ""))
|
|
429
|
+
return 0
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def build_parser():
|
|
433
|
+
parser = argparse.ArgumentParser(
|
|
434
|
+
prog="agent-bus",
|
|
435
|
+
description="跨机 agent 任务信箱:SSH 为传输,文件为存储。")
|
|
436
|
+
parser.add_argument("--base", default=None,
|
|
437
|
+
help="信箱根目录(默认 $AGENT_BUS_DIR 或 ~/.agent-bus)")
|
|
438
|
+
parser.add_argument("--remote", default=os.environ.get("AGENT_BUS_REMOTE"),
|
|
439
|
+
help="远程信箱主机 user@host(默认 $AGENT_BUS_REMOTE)")
|
|
440
|
+
parser.add_argument("--remote-key", default=None,
|
|
441
|
+
help="远程 SSH 私钥(默认 $AGENT_BUS_SSH_KEY)")
|
|
442
|
+
sub = parser.add_subparsers(dest="cmd")
|
|
443
|
+
sub.required = True
|
|
444
|
+
|
|
445
|
+
p = sub.add_parser("send", help="投递任务")
|
|
446
|
+
p.add_argument("target")
|
|
447
|
+
p.add_argument("title")
|
|
448
|
+
p.add_argument("--from", dest="sender", default=None)
|
|
449
|
+
p.add_argument("--body", default=None, help="任务内容(缺省从 stdin 读)")
|
|
450
|
+
p.add_argument("--json", action="store_true")
|
|
451
|
+
p.set_defaults(func=cmd_send)
|
|
452
|
+
|
|
453
|
+
p = sub.add_parser("tasks", help="列出某台机器的待办")
|
|
454
|
+
p.add_argument("me")
|
|
455
|
+
p.add_argument("--all", action="store_true")
|
|
456
|
+
p.add_argument("--json", action="store_true")
|
|
457
|
+
p.set_defaults(func=cmd_tasks)
|
|
458
|
+
|
|
459
|
+
p = sub.add_parser("claim", help="认领任务")
|
|
460
|
+
p.add_argument("me")
|
|
461
|
+
p.add_argument("id")
|
|
462
|
+
p.add_argument("--json", action="store_true")
|
|
463
|
+
p.set_defaults(func=cmd_claim)
|
|
464
|
+
|
|
465
|
+
p = sub.add_parser("requeue", help="把卡住的任务重置为待办")
|
|
466
|
+
p.add_argument("me")
|
|
467
|
+
p.add_argument("id")
|
|
468
|
+
p.add_argument("--json", action="store_true")
|
|
469
|
+
p.set_defaults(func=cmd_requeue)
|
|
470
|
+
|
|
471
|
+
p = sub.add_parser("done", help="提交结果(缺省从 stdin 读)")
|
|
472
|
+
p.add_argument("me")
|
|
473
|
+
p.add_argument("id")
|
|
474
|
+
p.add_argument("--status", choices=["ok", "fail"], default="ok")
|
|
475
|
+
p.add_argument("--body", default=None)
|
|
476
|
+
p.add_argument("--json", action="store_true")
|
|
477
|
+
p.set_defaults(func=cmd_done)
|
|
478
|
+
|
|
479
|
+
p = sub.add_parser("show", help="查看任务详情")
|
|
480
|
+
p.add_argument("id")
|
|
481
|
+
p.add_argument("--target", default=None)
|
|
482
|
+
p.add_argument("--json", action="store_true")
|
|
483
|
+
p.set_defaults(func=cmd_show)
|
|
484
|
+
|
|
485
|
+
p = sub.add_parser("result", help="查看结果")
|
|
486
|
+
p.add_argument("id")
|
|
487
|
+
p.add_argument("--json", action="store_true")
|
|
488
|
+
p.set_defaults(func=cmd_result)
|
|
489
|
+
|
|
490
|
+
p = sub.add_parser("list", help="总览")
|
|
491
|
+
p.add_argument("--json", action="store_true")
|
|
492
|
+
p.set_defaults(func=cmd_list)
|
|
493
|
+
|
|
494
|
+
p = sub.add_parser("work", help="作为 worker 循环执行任务")
|
|
495
|
+
p.add_argument("--me", required=True, help="本机在信箱里的名字")
|
|
496
|
+
p.add_argument("--dir", default=".", help="runner 的工作目录")
|
|
497
|
+
p.add_argument("--poll", type=int, default=20, help="轮询间隔(秒)")
|
|
498
|
+
p.add_argument("--timeout", type=int, default=3600, help="单任务超时(秒)")
|
|
499
|
+
p.add_argument("--runner", choices=["claude", "shell"], default="claude",
|
|
500
|
+
help="claude: claude -p <body>;shell: 把 body 当 shell 命令")
|
|
501
|
+
p.add_argument("--sandbox", choices=["auto", "none", "worktree", "docker"],
|
|
502
|
+
default="auto", help="任务沙箱(默认 auto)")
|
|
503
|
+
p.add_argument("--keep-worktrees", action="store_true",
|
|
504
|
+
help="任务完成后保留 worktree")
|
|
505
|
+
p.add_argument("--docker-image", default=None,
|
|
506
|
+
help="docker 沙箱镜像(默认 $AGENT_BUS_DOCKER_IMAGE 或 agent-bus-worker:latest)")
|
|
507
|
+
p.add_argument("--docker-network", choices=["bridge", "none"], default="bridge")
|
|
508
|
+
p.add_argument("--once", action="store_true", help="最多处理一个任务后退出")
|
|
509
|
+
p.add_argument("--detach", action="store_true", help="后台运行(日志写入文件)")
|
|
510
|
+
p.add_argument("--log", default=None, help="后台模式的日志路径")
|
|
511
|
+
p.add_argument("extra", nargs=argparse.REMAINDER,
|
|
512
|
+
help="追加给 runner 的参数(放在 -- 之后)")
|
|
513
|
+
p.set_defaults(func=cmd_work)
|
|
514
|
+
|
|
515
|
+
p = sub.add_parser("doctor", help="环境自检")
|
|
516
|
+
p.add_argument("--me", default=None, help="检查某个目标的队列")
|
|
517
|
+
p.add_argument("--dir", default=None, help="检查作业目录")
|
|
518
|
+
p.set_defaults(func=cmd_doctor)
|
|
519
|
+
|
|
520
|
+
p = sub.add_parser("reap", help="回收超时未完成的任务")
|
|
521
|
+
p.add_argument("me")
|
|
522
|
+
p.add_argument("--older", type=int, default=60, help="超过多少分钟算超时(默认 60)")
|
|
523
|
+
p.add_argument("--json", action="store_true")
|
|
524
|
+
p.set_defaults(func=cmd_reap)
|
|
525
|
+
|
|
526
|
+
p = sub.add_parser("status", help="查看后台 worker 状态")
|
|
527
|
+
p.add_argument("--me", required=True)
|
|
528
|
+
p.set_defaults(func=cmd_status)
|
|
529
|
+
|
|
530
|
+
p = sub.add_parser("stop", help="停止后台 worker")
|
|
531
|
+
p.add_argument("--me", required=True)
|
|
532
|
+
p.set_defaults(func=cmd_stop)
|
|
533
|
+
|
|
534
|
+
return parser
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _force_utf8_stdio():
|
|
538
|
+
"""Avoid UnicodeEncodeError on legacy Windows code pages (cp1252/GBK)."""
|
|
539
|
+
for stream in (sys.stdout, sys.stderr):
|
|
540
|
+
if hasattr(stream, "reconfigure"):
|
|
541
|
+
try:
|
|
542
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
543
|
+
except Exception: # noqa: BLE001
|
|
544
|
+
pass
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def main(argv=None):
|
|
548
|
+
_force_utf8_stdio()
|
|
549
|
+
raw = list(sys.argv[1:]) if argv is None else list(argv)
|
|
550
|
+
args = build_parser().parse_args(raw)
|
|
551
|
+
if args.remote:
|
|
552
|
+
store = RemoteStore(args.remote, base=args.base, key=args.remote_key)
|
|
553
|
+
mode = "REMOTE " + args.remote
|
|
554
|
+
if args.remote_key:
|
|
555
|
+
mode += " (key: %s)" % args.remote_key
|
|
556
|
+
else:
|
|
557
|
+
store = Store(args.base)
|
|
558
|
+
mode = "LOCAL " + store.base
|
|
559
|
+
args._raw = raw
|
|
560
|
+
args._mode = mode
|
|
561
|
+
args._remote = bool(args.remote)
|
|
562
|
+
try:
|
|
563
|
+
return args.func(store, args) or 0
|
|
564
|
+
except BusError as exc:
|
|
565
|
+
sys.stderr.write("agent-bus: %s\n" % exc)
|
|
566
|
+
return 1
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
if __name__ == "__main__":
|
|
570
|
+
sys.exit(main())
|
agent_bus/gate.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""SSH restricted-command gate.
|
|
2
|
+
|
|
3
|
+
Put this as the forced command of a worker's public key in
|
|
4
|
+
``~/.ssh/authorized_keys`` on the bus host::
|
|
5
|
+
|
|
6
|
+
command="agent-bus-gate",no-port-forwarding,no-X11-forwarding,\
|
|
7
|
+
no-agent-forwarding,no-pty ssh-ed25519 AAAA... lab@worker
|
|
8
|
+
|
|
9
|
+
Then ``ssh bus "agent-bus send lab 'title'"`` works, but nothing else does.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import shlex
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv=None):
|
|
18
|
+
command = os.environ.get("SSH_ORIGINAL_COMMAND", "")
|
|
19
|
+
try:
|
|
20
|
+
parts = shlex.split(command)
|
|
21
|
+
except ValueError:
|
|
22
|
+
sys.exit("agent-bus-gate: malformed command")
|
|
23
|
+
if not parts or parts[0] != "agent-bus":
|
|
24
|
+
sys.exit("agent-bus-gate: only 'agent-bus ...' is allowed")
|
|
25
|
+
os.execv(sys.executable,
|
|
26
|
+
[sys.executable, "-m", "agent_bus.cli"] + parts[1:])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
if __name__ == "__main__":
|
|
30
|
+
main()
|