acppool 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.
acppool/supervisor.py ADDED
@@ -0,0 +1,637 @@
1
+ """The agents' supervisor: it owns each agent's ACP adapter process, so the app can restart
2
+ without ending a turn. Transport only: it starts sessions, sends prompts, steers, cancels and
3
+ holds permission requests until answered; what an agent does next is the app's to decide.
4
+
5
+ Commands come over a Unix socket, one JSON line each (`acppool.client`). What it knows
6
+ goes to files: the agents' file and one event log per agent. On start it resumes every session
7
+ the agents' file names. The app runs it with its `Config`: `main(config)`.
8
+ """
9
+
10
+ import asyncio
11
+ import datetime
12
+ import json
13
+ import os
14
+ import signal
15
+ import sys
16
+ import dataclasses
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Callable
20
+
21
+ PROTOCOL = 1
22
+ OUTPUT, DIFF, DIFFS = 6000, 20000, 4 # characters of a tool's output, of each side of a diff, and diffs per call, kept in the log
23
+ QUIET = {"available_commands_update", "session_info_update", "config_option_update", "current_mode_update",
24
+ "agent_message_chunk", "agent_thought_chunk", "user_message_chunk", "usage_update"}
25
+
26
+
27
+ def text_prompt(text: str, images: bool = True) -> list[dict]:
28
+ return [{"type": "text", "text": text}]
29
+
30
+
31
+ TASKS: set[asyncio.Task] = set() # the loop keeps only weak references to tasks: these keep them alive
32
+
33
+
34
+ def spawn(coro) -> asyncio.Task:
35
+ t = asyncio.create_task(coro)
36
+ TASKS.add(t)
37
+ t.add_done_callback(TASKS.discard)
38
+ return t
39
+
40
+
41
+ @dataclass
42
+ class Kind:
43
+ """An agent kind: its adapter's command line, and what the adapter offers beyond ACP."""
44
+ command: Callable[[], list[str]]
45
+ steer: str | None = None # the extension method that sends a message into a running turn
46
+ meta: Callable[["Agent", list[dict]], dict] | None = None # a session's _meta, from the agent and its MCP servers
47
+ chrome: bool = False # whether it runs Claude in Chrome
48
+ rate: Callable[[dict], tuple[str, dict] | None] | None = None # a usage update's rate-limit report: its window and what it says
49
+ options: dict[str, str] = dataclasses.field(default_factory=dict) # session config options set on each session it opens
50
+
51
+
52
+ @dataclass
53
+ class Config:
54
+ """What an app gives the supervisor: where its state lives, the agent kinds, and the hooks it shapes sessions with."""
55
+ socket: Path
56
+ agents: Path # each agent: its session, state, pending permission, last usage
57
+ logs: Path # one event log per agent, <name>.jsonl
58
+ rates: Path | None = None # the rate limits the agents last reported, by window; none kept without it
59
+ kinds: dict[str, Kind] = dataclasses.field(default_factory=dict)
60
+ servers: Callable[[str], list[dict]] = lambda name: [] # the MCP servers each session of the named agent gets
61
+ env: Callable[[str, dict], dict] = lambda name, env: env # the adapter process's environment, from the supervisor's
62
+ prompt: Callable[[str, bool], list[dict]] = text_prompt # a message as ACP content blocks; whether images are read
63
+ restarts: int = 3 # tries in a row before an agent that keeps crashing is left failed
64
+ backoff: float = 2 # seconds before a restart, times the failures so far
65
+
66
+ @classmethod
67
+ def under(cls, state: Path, **kw) -> "Config":
68
+ """The state files in one folder: agentd.sock, agents.json, and sessions/."""
69
+ return cls(socket=state / "agentd.sock", agents=state / "agents.json", logs=state / "sessions",
70
+ rates=state / "ratelimits.json", **kw)
71
+
72
+
73
+ def clip(text: str, n: int) -> str:
74
+ return text if len(text) <= n else text[:n] + f"\n… {len(text) - n} more characters"
75
+
76
+
77
+ def clipped(value):
78
+ """A tool's input with each long string clipped: an edit's input holds whole files."""
79
+ if isinstance(value, str):
80
+ return clip(value, OUTPUT)
81
+ if isinstance(value, dict):
82
+ return {k: clipped(v) for k, v in value.items()}
83
+ if isinstance(value, list):
84
+ return [clipped(v) for v in value[:50]]
85
+ return value
86
+
87
+
88
+ def output_text(out) -> str:
89
+ """A tool's output as text: an MCP result's text blocks joined, anything else as itself or as JSON."""
90
+ if isinstance(out, list) and out and all(isinstance(c, dict) and c.get("type") == "text" for c in out):
91
+ return "\n".join(c.get("text", "") for c in out)
92
+ return out if isinstance(out, str) else json.dumps(out, ensure_ascii=False)
93
+
94
+
95
+ def now() -> str:
96
+ return datetime.datetime.now().astimezone().isoformat(timespec="seconds")
97
+
98
+
99
+ class Gone(Exception):
100
+ """The adapter process ended."""
101
+
102
+
103
+ class Connection:
104
+ """JSON-RPC 2.0 over an adapter's stdio."""
105
+
106
+ def __init__(self, on_notify, on_request, on_exit):
107
+ self.on_notify, self.on_request, self.on_exit = on_notify, on_request, on_exit
108
+ self.pending: dict[int, asyncio.Future] = {}
109
+ self.next = 0
110
+ self.proc = None
111
+
112
+ async def open(self, cmd: list[str], cwd: str, env: dict, stderr: Path) -> None:
113
+ stderr.parent.mkdir(parents=True, exist_ok=True)
114
+ with stderr.open("ab") as err:
115
+ self.proc = await asyncio.create_subprocess_exec(
116
+ *cmd, cwd=cwd, env=env, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
117
+ stderr=err, limit=64 * 1024 * 1024, start_new_session=True)
118
+ self.reader = spawn(self.read())
119
+
120
+ async def read(self) -> None:
121
+ try:
122
+ while line := await self.proc.stdout.readline():
123
+ try:
124
+ msg = json.loads(line)
125
+ except json.JSONDecodeError:
126
+ continue
127
+ if "method" not in msg:
128
+ fut = self.pending.pop(msg.get("id"), None)
129
+ if fut and not fut.done():
130
+ fut.set_result(msg)
131
+ elif "id" in msg:
132
+ spawn(self.on_request(msg))
133
+ else:
134
+ self.on_notify(msg)
135
+ finally:
136
+ for fut in self.pending.values():
137
+ if not fut.done():
138
+ fut.set_exception(Gone())
139
+ self.pending.clear()
140
+ await self.proc.wait()
141
+ self.on_exit(self.proc.returncode)
142
+
143
+ async def send(self, msg: dict) -> None:
144
+ if self.proc is None or self.proc.returncode is not None or self.proc.stdin.is_closing():
145
+ raise Gone()
146
+ self.proc.stdin.write((json.dumps({"jsonrpc": "2.0", **msg}) + "\n").encode())
147
+ await self.proc.stdin.drain()
148
+
149
+ async def call(self, method: str, params: dict, timeout: float | None = 180) -> dict:
150
+ self.next += 1
151
+ fut = asyncio.get_running_loop().create_future()
152
+ self.pending[self.next] = fut
153
+ await self.send({"id": self.next, "method": method, "params": params})
154
+ msg = await asyncio.wait_for(fut, timeout)
155
+ if "error" in msg:
156
+ raise RuntimeError(f"{method}: {msg['error'].get('message')}")
157
+ return msg.get("result") or {}
158
+
159
+ async def close(self) -> None:
160
+ if self.proc is not None and self.proc.returncode is None:
161
+ self.proc.terminate()
162
+ try:
163
+ await asyncio.wait_for(self.proc.wait(), 5)
164
+ except asyncio.TimeoutError:
165
+ self.proc.kill()
166
+
167
+
168
+ class Agent:
169
+ def __init__(self, sup: "Supervisor", name: str, kind: str, cwd: str, env: dict | None = None,
170
+ session: str | None = None, chrome: bool = False, dirs: list[str] | None = None):
171
+ self.sup, self.name, self.kind, self.cwd, self.env = sup, name, kind, cwd, env or {}
172
+ self.dirs = dirs or [] # folders beyond its own it may work in
173
+ self.chrome = chrome # Claude in Chrome: the person's own browser, so only when asked for
174
+ self.session, self.state, self.since, self.error = session, "starting", now(), None
175
+ self.permission: dict | None = None
176
+ self.images = False # whether its adapter reads images in a prompt, as it said on initialize
177
+ self.loads = False # whether its adapter loads a session, for one that cannot resume it
178
+ self.loading = False # a load replays the session's history: none of it is logged again
179
+ self.usage: dict = {}
180
+ self.spent: float | None = None # the session's cost so far, as the adapter last reported it; unknown after a resume
181
+ self.conn: Connection | None = None
182
+ self.text = {"message": [], "thought": []}
183
+ self.calls: dict[str, dict] = {}
184
+ self.stopping, self.failures = False, 0
185
+ self.last = {"began": None, "stop": None} # its latest turn: when it began and how it ended (None while it runs)
186
+
187
+ def public(self) -> dict:
188
+ return {"agent": self.kind, "cwd": self.cwd, "env": self.env, "dirs": self.dirs, "session": self.session, "state": self.state,
189
+ "chrome": self.chrome, "since": self.since, "error": self.error, "usage": self.usage, "turn": self.last,
190
+ "permission": self.permission and {k: v for k, v in self.permission.items() if k != "rpc"}}
191
+
192
+ def set(self, state: str, error: str | None = None) -> None:
193
+ self.state, self.since, self.error = state, now(), error
194
+ self.sup.save()
195
+
196
+ @property
197
+ def config(self) -> Config:
198
+ return self.sup.config
199
+
200
+ def record(self, kind: str, **data) -> None:
201
+ self.config.logs.mkdir(parents=True, exist_ok=True)
202
+ with (self.config.logs / f"{self.name}.jsonl").open("a") as f:
203
+ f.write(json.dumps({"at": now(), "kind": kind, **data}) + "\n")
204
+
205
+ def flush(self) -> None:
206
+ for kind, buf in self.text.items():
207
+ if buf:
208
+ self.record(kind, text="".join(buf))
209
+ buf.clear()
210
+
211
+ async def open(self, resume: bool) -> None:
212
+ self.set("starting")
213
+ self.conn = Connection(self.notified, self.requested, self.exited)
214
+ env = self.config.env(self.name, {**os.environ, **self.env})
215
+ await self.conn.open(self.config.kinds[self.kind].command(), self.cwd, env, self.config.logs / f"{self.name}.stderr")
216
+ init = await self.conn.call("initialize", {"protocolVersion": PROTOCOL, "clientCapabilities": {
217
+ "fs": {"readTextFile": False, "writeTextFile": False}, "terminal": False}})
218
+ self.images = bool(((init or {}).get("agentCapabilities") or {}).get("promptCapabilities", {}).get("image"))
219
+ self.loads = bool(((init or {}).get("agentCapabilities") or {}).get("loadSession"))
220
+ if resume and self.session:
221
+ try:
222
+ await self.restore(self.session)
223
+ except (RuntimeError, asyncio.TimeoutError) as e:
224
+ # a session cleared and never prompted has no transcript to resume: it held nothing. Any other is lost
225
+ # with what it held, so the turn it ran counts as interrupted: the app sends its job again
226
+ old = self.session
227
+ self.session = await self.new_session()
228
+ self.began("lost", previous=old, lost=str(e) or type(e).__name__)
229
+ self.usage, self.spent = {}, 0.0
230
+ if "Resource not found" not in str(e):
231
+ self.last = {**self.last, "stop": "interrupted"}
232
+ else:
233
+ await self.configure(self.session)
234
+ self.record("resumed", session=self.session)
235
+ self.spent = None
236
+ else:
237
+ self.session = await self.new_session()
238
+ self.began("start")
239
+ self.usage, self.spent = {}, 0.0
240
+ self.failures = 0
241
+ self.set("idle")
242
+
243
+ async def restore(self, session: str) -> None:
244
+ """An earlier session taken up in this adapter: resumed, or, by an agent that cannot resume one but loads it,
245
+ loaded, the history it replays left out of the log."""
246
+ try:
247
+ await self.conn.call("session/resume", {"sessionId": session, **self.setup()})
248
+ return
249
+ except RuntimeError as e:
250
+ if "Method not found" not in str(e) or not self.loads:
251
+ raise
252
+ self.loading = True
253
+ try:
254
+ await self.conn.call("session/load", {"sessionId": session, **self.setup()})
255
+ finally:
256
+ self.loading = False
257
+
258
+ async def new_session(self) -> str:
259
+ session = (await self.conn.call("session/new", self.setup()))["sessionId"]
260
+ await self.configure(session)
261
+ return session
262
+
263
+ async def configure(self, session: str) -> None:
264
+ """The kind's session options, set again on every session: an adapter starts each at its own defaults."""
265
+ for option, value in self.config.kinds[self.kind].options.items():
266
+ await self.conn.call("session/set_config_option", {"sessionId": session, "configId": option, "value": value}, timeout=30)
267
+
268
+ def began(self, why: str, **data) -> None:
269
+ """A session's first line in the log: it cuts the log into sessions, each with why it began (start, clear,
270
+ run, lost, resume) and the folder and agent it can be resumed in."""
271
+ self.record("session", session=self.session, why=why, cwd=self.cwd, agent=self.kind, **{k: v for k, v in data.items() if v})
272
+
273
+ def setup(self) -> dict:
274
+ """A session's folder, the app's MCP servers for this agent, and its kind's _meta."""
275
+ servers = self.config.servers(self.name)
276
+ out = {"cwd": self.cwd, "mcpServers": servers}
277
+ if self.dirs:
278
+ out["additionalDirectories"] = self.dirs
279
+ if meta := self.config.kinds[self.kind].meta:
280
+ out["_meta"] = meta(self, servers)
281
+ return out
282
+
283
+ def notified(self, msg: dict) -> None:
284
+ if msg.get("method") != "session/update":
285
+ return
286
+ u = msg["params"]["update"]
287
+ kind = u.get("sessionUpdate")
288
+ if self.loading and kind != "usage_update": # the history a load replays, already in the log
289
+ return
290
+ if kind in ("agent_message_chunk", "agent_thought_chunk"):
291
+ if u.get("content", {}).get("type") == "text":
292
+ self.text["message" if kind == "agent_message_chunk" else "thought"].append(u["content"]["text"])
293
+ return
294
+ if kind == "usage_update":
295
+ self.usage = {k: u[k] for k in ("used", "size", "cost") if k in u}
296
+ if (rate := self.config.kinds[self.kind].rate) and (got := rate(u)):
297
+ self.sup.rate(*got)
298
+ return
299
+ if kind in QUIET:
300
+ return
301
+ self.flush()
302
+ if kind in ("tool_call", "tool_call_update"):
303
+ self.tool(u)
304
+ elif kind == "plan":
305
+ self.record("plan", entries=u.get("entries"))
306
+ else:
307
+ self.record("update", update=kind)
308
+
309
+ def tool(self, u: dict) -> None:
310
+ """A tool call is logged once its input says what it does (the first event names only its kind), and again
311
+ when it ends, with its output and the diffs of what it edited."""
312
+ cid = u.get("toolCallId")
313
+ call = self.calls.setdefault(cid, {"name": u.get("name") or ((u.get("_meta") or {}).get("claudeCode") or {}).get("toolName"),
314
+ "tool": u.get("kind"), "title": None, "input": None, "output": None, "diffs": [],
315
+ "logged": False})
316
+ for key, field in (("title", "title"), ("kind", "tool"), ("rawInput", "input")):
317
+ if u.get(key):
318
+ call[field] = u[key]
319
+ if u.get("rawOutput") is not None:
320
+ call["output"] = output_text(u["rawOutput"])
321
+ for c in u.get("content") or []:
322
+ # one per file, the first: an edit is sent as the snippet it changed, then again as the whole file
323
+ if c.get("type") == "diff" and len(call["diffs"]) < DIFFS and c.get("path") not in {x["path"] for x in call["diffs"]}:
324
+ call["diffs"].append({"path": c.get("path"), "old": clip(c.get("oldText") or "", DIFF), "new": clip(c.get("newText") or "", DIFF)})
325
+ ends = u.get("status") in ("completed", "failed")
326
+ if not call["logged"] and (u.get("rawInput") or ends):
327
+ call["logged"] = True
328
+ self.record("tool", id=cid, name=call["name"], tool=call["tool"], title=call["title"], input=clipped(call["input"]))
329
+ if ends:
330
+ self.record("tool_done", id=cid, status=u["status"], title=call["title"], output=clip(call["output"] or "", OUTPUT),
331
+ diffs=call["diffs"])
332
+ self.calls.pop(cid, None)
333
+
334
+ async def requested(self, msg: dict) -> None:
335
+ if msg["method"] != "session/request_permission":
336
+ await self.conn.send({"id": msg["id"], "error": {"code": -32601, "message": "not supported"}})
337
+ return
338
+ self.flush()
339
+ p = msg["params"]
340
+ opts = [{"id": o["optionId"], "name": o.get("name"), "kind": o.get("kind")} for o in p.get("options", [])]
341
+ self.permission = {"rpc": msg["id"], "tool": (p.get("toolCall") or {}).get("title"), "options": opts}
342
+ self.record("permission", tool=self.permission["tool"], options=opts)
343
+ self.set("asking")
344
+
345
+ def exited(self, code: int | None) -> None:
346
+ self.flush()
347
+ if self.stopping:
348
+ return
349
+ if self.state in ("busy", "asking"):
350
+ self.last = {**self.last, "stop": "interrupted"}
351
+ self.permission = None
352
+ self.failures += 1
353
+ self.record("crashed", code=code)
354
+ if self.failures > self.config.restarts:
355
+ self.set("failed", f"the adapter exited ({code}) {self.config.restarts} times in a row")
356
+ return
357
+ self.set("crashed", f"the adapter exited ({code})")
358
+ spawn(self.restart())
359
+
360
+ async def restart(self) -> None:
361
+ await asyncio.sleep(self.config.backoff * self.failures)
362
+ try:
363
+ await self.open(resume=True)
364
+ except Exception as e:
365
+ self.set("failed", str(e))
366
+ if self.conn:
367
+ await self.conn.close() # a half-opened adapter would outlive the supervisor: its own process group
368
+
369
+ async def prompt(self, text: str, job: dict | None = None) -> dict:
370
+ """A turn; a job's prompt names the job, so a session's log says which work it did."""
371
+ if self.state != "idle":
372
+ raise RuntimeError(f"{self.name} is {self.state}: steer it, or wait for its turn to end")
373
+ self.record("prompt", text=text, **({"job": job} if job else {}))
374
+ self.last = {"began": now(), "stop": None}
375
+ self.set("busy")
376
+ spawn(self.turn(text))
377
+ return {}
378
+
379
+ async def turn(self, text: str) -> None:
380
+ try:
381
+ r = await self.conn.call("session/prompt", {"sessionId": self.session, "prompt": self.config.prompt(text, self.images)},
382
+ timeout=None)
383
+ except Gone:
384
+ return # exited() records it and restarts
385
+ except Exception as e:
386
+ self.flush()
387
+ self.record("turn", stop="error", error=str(e))
388
+ self.last["stop"] = "error"
389
+ self.set("idle", str(e))
390
+ return
391
+ self.flush()
392
+ models = ((r.get("_meta") or {}).get("quota") or {}).get("model_usage")
393
+ self.record("turn", stop=r.get("stopReason"), usage=r.get("usage"), models=models, cost=self.turn_cost())
394
+ self.last["stop"] = r.get("stopReason") or "end_turn"
395
+ self.permission = None
396
+ self.set("idle")
397
+
398
+ def turn_cost(self) -> float | None:
399
+ """What the turn added to the session's cost. A resumed session's first report holds its history, so it only sets the base."""
400
+ total = (self.usage.get("cost") or {}).get("amount")
401
+ if not isinstance(total, (int, float)):
402
+ return None
403
+ spent, self.spent = self.spent, total
404
+ return round(total - spent, 6) if spent is not None and total >= spent else None
405
+
406
+ async def steer(self, text: str) -> dict:
407
+ if self.state not in ("busy", "asking"):
408
+ raise RuntimeError(f"{self.name} is {self.state}: send it a prompt instead")
409
+ if not (method := self.config.kinds[self.kind].steer):
410
+ raise RuntimeError(f"{self.name} runs {self.kind}, which takes no message during a turn")
411
+ # a turn that just ended takes no steer: the adapter is told not to start one itself, and the app queues the message
412
+ r = await self.conn.call(method, {"sessionId": self.session, "prompt": self.config.prompt(text, self.images),
413
+ "_meta": {"steering": {"idleBehavior": "promptRequired"}}}, timeout=60)
414
+ if r.get("outcome") not in (None, "injected"):
415
+ raise RuntimeError(f"{self.name} took no message: {r.get('reason') or r.get('outcome')}")
416
+ self.record("steer", text=text, outcome=r.get("outcome"))
417
+ return {"outcome": r.get("outcome")}
418
+
419
+ async def cancel(self) -> dict:
420
+ if self.state not in ("busy", "asking"):
421
+ raise RuntimeError(f"{self.name} is {self.state}: nothing to cancel")
422
+ if self.permission:
423
+ await self.conn.send({"id": self.permission["rpc"], "result": {"outcome": {"outcome": "cancelled"}}})
424
+ self.permission = None
425
+ await self.conn.send({"method": "session/cancel", "params": {"sessionId": self.session}})
426
+ self.record("cancel")
427
+ return {}
428
+
429
+ async def answer(self, option: str) -> dict:
430
+ if not self.permission:
431
+ raise RuntimeError(f"{self.name} asks no permission")
432
+ if option not in {o["id"] for o in self.permission["options"]}:
433
+ raise RuntimeError(f"no option {option}")
434
+ await self.conn.send({"id": self.permission["rpc"], "result": {"outcome": {"outcome": "selected", "optionId": option}}})
435
+ self.record("answer", option=option)
436
+ self.permission = None
437
+ self.set("busy")
438
+ return {}
439
+
440
+ async def reset(self, why: str = "clear", run: str = "") -> dict:
441
+ """A fresh session in the same adapter: the context starts empty. Why: a clear asked for, or a job of another run."""
442
+ if self.state != "idle":
443
+ raise RuntimeError(f"{self.name} is {self.state}: cancel its turn first")
444
+ old = self.session
445
+ await self.close(old)
446
+ self.session = await self.new_session()
447
+ self.began(why, previous=old, run=run)
448
+ self.usage, self.spent = {}, 0.0
449
+ self.set("idle")
450
+ return {"session": self.session}
451
+
452
+ async def resume(self, session: str, run: str = "") -> dict:
453
+ """An earlier session, this agent's or another's, taken up again in place of its own; resumed before the
454
+ current one is closed, so one that cannot be leaves it as it was."""
455
+ if self.state != "idle":
456
+ raise RuntimeError(f"{self.name} is {self.state}: cancel its turn first")
457
+ if session == self.session:
458
+ return {"session": session}
459
+ await self.restore(session)
460
+ await self.configure(session)
461
+ old, self.session = self.session, session
462
+ await self.close(old)
463
+ self.began("resume", previous=old, run=run)
464
+ self.usage, self.spent = {}, None
465
+ self.set("idle")
466
+ return {"session": session}
467
+
468
+ async def close(self, session: str | None) -> None:
469
+ try:
470
+ await self.conn.call("session/close", {"sessionId": session}, timeout=30)
471
+ except Exception:
472
+ pass # closing only frees the adapter's resources
473
+
474
+ async def use_chrome(self, on: bool) -> dict:
475
+ """Claude in Chrome on or off: its adapter starts again and resumes the session, the flag set at the start."""
476
+ if not self.config.kinds[self.kind].chrome:
477
+ raise RuntimeError(f"{self.name} runs {self.kind}: Claude in Chrome is Claude's only")
478
+ if self.state != "idle":
479
+ raise RuntimeError(f"{self.name} is {self.state}: wait for its turn to end")
480
+ if on == self.chrome:
481
+ return {}
482
+ self.chrome = on
483
+ self.stopping = True
484
+ await self.conn.close()
485
+ await asyncio.gather(self.conn.reader, return_exceptions=True) # its exit seen while stopping, not as a crash
486
+ self.stopping = False
487
+ self.record("chrome", on=on)
488
+ await self.sup.opened(self, resume=True)
489
+ if self.state == "failed": # back as it was, so a flag it cannot start with leaves it working
490
+ error, self.chrome, self.stopping = self.error, not on, False
491
+ self.record("chrome", on=not on, undone=error)
492
+ await self.sup.opened(self, resume=True)
493
+ raise RuntimeError(f"it could not start with Claude in Chrome {'on' if on else 'off'}: {error}")
494
+ return {}
495
+
496
+ async def stop(self) -> None:
497
+ self.stopping = True
498
+ if self.conn:
499
+ await self.conn.close()
500
+
501
+
502
+ class Supervisor:
503
+ def __init__(self, config: Config):
504
+ self.config = config
505
+ self.agents: dict[str, Agent] = {}
506
+ self.rates: dict[str, dict] = {}
507
+
508
+ def save(self) -> None:
509
+ tmp = self.config.agents.with_suffix(".tmp")
510
+ tmp.write_text(json.dumps({n: a.public() for n, a in self.agents.items()}, indent=1))
511
+ tmp.replace(self.config.agents)
512
+
513
+ def rate(self, window: str, info: dict) -> None:
514
+ """A rate-limit report from a turn, kept by its window for the app's usage forecast."""
515
+ if not self.config.rates:
516
+ return
517
+ self.rates[window] = {**info, "at": now()}
518
+ tmp = self.config.rates.with_suffix(".tmp")
519
+ tmp.write_text(json.dumps(self.rates, indent=1))
520
+ tmp.replace(self.config.rates)
521
+
522
+ async def resume_all(self) -> None:
523
+ try:
524
+ known = json.loads(self.config.agents.read_text())
525
+ except (FileNotFoundError, json.JSONDecodeError):
526
+ known = {}
527
+ if self.config.rates:
528
+ try:
529
+ self.rates = json.loads(self.config.rates.read_text())
530
+ except (FileNotFoundError, json.JSONDecodeError):
531
+ pass
532
+ for name, a in known.items():
533
+ agent = self.agents[name] = Agent(self, name, a["agent"], a["cwd"], a.get("env"), a.get("session"), bool(a.get("chrome")),
534
+ a.get("dirs"))
535
+ agent.last = a.get("turn") or agent.last
536
+ if a.get("state") in ("busy", "asking", "crashed"):
537
+ agent.record("interrupted", state=a["state"])
538
+ agent.last = {**agent.last, "stop": "interrupted"}
539
+ spawn(self.opened(agent, resume=True))
540
+ self.save()
541
+
542
+ async def opened(self, agent: Agent, resume: bool) -> None:
543
+ try:
544
+ await agent.open(resume)
545
+ except Exception as e:
546
+ agent.record("failed", error=str(e))
547
+ agent.set("failed", str(e))
548
+ await agent.stop()
549
+
550
+ async def handle(self, req: dict) -> dict:
551
+ op, name = req.get("op"), req.get("name")
552
+ if op == "status":
553
+ return {"agents": {n: a.public() for n, a in self.agents.items()}}
554
+ if op == "start":
555
+ if not name or name in self.agents:
556
+ raise RuntimeError(f"{name} already runs" if name else "a name is needed")
557
+ kind = req.get("agent", "claude")
558
+ if kind not in self.config.kinds:
559
+ raise RuntimeError(f"unknown agent {kind}")
560
+ if not Path(req.get("cwd") or "").is_dir():
561
+ raise RuntimeError(f"no folder {req.get('cwd')}")
562
+ agent = self.agents[name] = Agent(self, name, kind, req["cwd"], req.get("env"), dirs=req.get("dirs"))
563
+ await self.opened(agent, resume=False)
564
+ if agent.state == "failed":
565
+ del self.agents[name]
566
+ self.save()
567
+ raise RuntimeError(agent.error)
568
+ return {"session": agent.session}
569
+ agent = self.agents.get(name)
570
+ if not agent:
571
+ raise RuntimeError(f"no agent {name}")
572
+ if op == "stop":
573
+ await agent.stop()
574
+ agent.record("stopped")
575
+ del self.agents[name]
576
+ self.save()
577
+ return {}
578
+ if agent.state in ("starting", "crashed", "failed"):
579
+ raise RuntimeError(f"{name} is {agent.state}" + (f": {agent.error}" if agent.error else ""))
580
+ if op == "prompt":
581
+ return await agent.prompt(req["text"], req.get("job"))
582
+ if op == "steer":
583
+ return await agent.steer(req["text"])
584
+ if op == "cancel":
585
+ return await agent.cancel()
586
+ if op == "answer":
587
+ return await agent.answer(req["option"])
588
+ if op == "reset":
589
+ return await agent.reset(req.get("why") or "clear", req.get("run") or "")
590
+ if op == "resume":
591
+ if any(a.session == req["session"] for n, a in self.agents.items() if n != name):
592
+ raise RuntimeError(f"{req['session']} is another agent's session now")
593
+ return await agent.resume(req["session"], req.get("run") or "")
594
+ if op == "chrome":
595
+ return await agent.use_chrome(bool(req.get("on")))
596
+ raise RuntimeError(f"unknown op {op}")
597
+
598
+ async def client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
599
+ try:
600
+ while line := await reader.readline():
601
+ try:
602
+ reply = {"ok": True, **await self.handle(json.loads(line))}
603
+ except Exception as e:
604
+ reply = {"ok": False, "error": str(e) or type(e).__name__}
605
+ writer.write((json.dumps(reply) + "\n").encode())
606
+ await writer.drain()
607
+ finally:
608
+ writer.close()
609
+
610
+ async def serve(self, path: Path | None = None, stop: asyncio.Event | None = None) -> None:
611
+ path = path or self.config.socket
612
+ if len(str(path)) > 100:
613
+ raise SystemExit(f"the socket path is too long for a Unix socket: {path}")
614
+ try:
615
+ _, w = await asyncio.open_unix_connection(str(path))
616
+ w.close()
617
+ raise SystemExit("another supervisor already runs")
618
+ except (FileNotFoundError, ConnectionRefusedError):
619
+ path.unlink(missing_ok=True)
620
+ server = await asyncio.start_unix_server(self.client, str(path))
621
+ os.chmod(path, 0o600) # only this user drives the agents
622
+ await self.resume_all()
623
+ if stop is None:
624
+ stop = asyncio.Event()
625
+ for sig in (signal.SIGTERM, signal.SIGINT):
626
+ asyncio.get_running_loop().add_signal_handler(sig, stop.set)
627
+ async with server:
628
+ await stop.wait()
629
+ for agent in self.agents.values():
630
+ await agent.stop() # agents.json keeps them: the next start resumes each
631
+ path.unlink(missing_ok=True)
632
+
633
+
634
+ def main(config: Config) -> None:
635
+ config.agents.parent.mkdir(parents=True, exist_ok=True)
636
+ print(f"{now()} agents' supervisor starts, pid {os.getpid()}", file=sys.stderr, flush=True)
637
+ asyncio.run(Supervisor(config).serve())
File without changes