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/__init__.py +2 -0
- acppool/adapters.py +26 -0
- acppool/claude.py +37 -0
- acppool/client.py +136 -0
- acppool/codex.py +23 -0
- acppool/control.py +244 -0
- acppool/mcp.py +185 -0
- acppool/needs.py +66 -0
- acppool/pool.py +366 -0
- acppool/push.py +302 -0
- acppool/sessions.py +221 -0
- acppool/supervisor.py +637 -0
- acppool/tests/__init__.py +0 -0
- acppool/tests/base.py +78 -0
- acppool/tests/fake_agent.py +49 -0
- acppool/tests/test_library.py +330 -0
- acppool/tests/test_supervisor.py +222 -0
- acppool/uploads.py +64 -0
- acppool-0.1.0.dist-info/METADATA +157 -0
- acppool-0.1.0.dist-info/RECORD +22 -0
- acppool-0.1.0.dist-info/WHEEL +4 -0
- acppool-0.1.0.dist-info/licenses/LICENSE +21 -0
acppool/__init__.py
ADDED
acppool/adapters.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""An agent's ACP adapter installed with npm in a folder of the app's: Node to run it, and the package's script."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Callable
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def node(var: str = "ACPPOOL_NODE") -> str | None:
|
|
10
|
+
"""Node: the variable's, else the newest nvm install, else the PATH's or Homebrew's."""
|
|
11
|
+
if os.environ.get(var):
|
|
12
|
+
return os.environ[var]
|
|
13
|
+
nvm = sorted((Path.home() / ".nvm" / "versions" / "node").glob("v*/bin/node"),
|
|
14
|
+
key=lambda p: [int(x) for x in p.parts[-3][1:].split(".") if x.isdigit()])
|
|
15
|
+
return str(nvm[-1]) if nvm else shutil.which("node") or next(
|
|
16
|
+
(p for p in ("/opt/homebrew/bin/node", "/usr/local/bin/node") if Path(p).exists()), None)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def npm(folder: Path, package: str, script: str = "dist/index.js", var: str = "ACPPOOL_NODE") -> Callable[[], list[str]]:
|
|
20
|
+
"""The adapter's command line, found when the supervisor starts an agent: an install can come after the app."""
|
|
21
|
+
def command() -> list[str]:
|
|
22
|
+
js, exe = Path(folder) / "node_modules" / package / script, node(var)
|
|
23
|
+
if not exe or not js.exists():
|
|
24
|
+
raise RuntimeError(f"no {package}: {'no node found' if not exe else 'run npm install in ' + str(folder)}")
|
|
25
|
+
return [exe, str(js)]
|
|
26
|
+
return command
|
acppool/claude.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Claude, through Anthropic's ACP adapter (`@agentclientprotocol/claude-agent-acp`): a message into a running turn,
|
|
2
|
+
the app's MCP tools allowed without asking, Claude in Chrome when an agent has it on, and the plan's rate limits."""
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Callable
|
|
6
|
+
|
|
7
|
+
from acppool.adapters import npm
|
|
8
|
+
from acppool.supervisor import Agent, Kind
|
|
9
|
+
|
|
10
|
+
PACKAGE = "@agentclientprotocol/claude-agent-acp"
|
|
11
|
+
STEER = "_session/steering" # the adapter's extension for a message into a running turn
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def meta(agent: Agent, servers: list[dict], extra: dict | None = None) -> dict:
|
|
15
|
+
"""The session's Agent SDK options: the app's MCP tools allowed, Chrome when on, and the kind's own `extra`
|
|
16
|
+
(its allowedTools added to the MCP tools; settingSources, say, to leave the user's own settings out)."""
|
|
17
|
+
extra = dict(extra or {})
|
|
18
|
+
tools = [f"mcp__{s['name']}" for s in servers] + list(extra.pop("allowedTools", []))
|
|
19
|
+
options = {"allowedTools": tools} | ({"extraArgs": {"chrome": ""}} if agent.chrome else {}) | extra
|
|
20
|
+
return {"claudeCode": {"options": options}}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def rate(update: dict) -> tuple[str, dict] | None:
|
|
24
|
+
"""The plan's rate limit, as the adapter reports it with a usage update: its window (five-hour, seven-day, ...)."""
|
|
25
|
+
info = (update.get("_meta") or {}).get("_claude/rateLimit")
|
|
26
|
+
return (info["rateLimitType"], info) if info and info.get("rateLimitType") else None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def claude(command: Callable[[], list[str]], options: dict | None = None) -> Kind:
|
|
30
|
+
"""The kind, run by the adapter's command line: the app knows where it installed it. `options` are Agent SDK
|
|
31
|
+
options for every session."""
|
|
32
|
+
return Kind(command=command, steer=STEER, meta=lambda agent, servers: meta(agent, servers, options), chrome=True, rate=rate)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def installed(folder: Path, var: str = "ACPPOOL_NODE", options: dict | None = None) -> Kind:
|
|
36
|
+
"""The kind, with the adapter npm installed in the folder (a package.json there pins its version)."""
|
|
37
|
+
return claude(npm(folder, PACKAGE, var=var), options)
|
acppool/client.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""An app's side of the supervisor (`acppool.supervisor`): commands go over its socket, and what it knows is read
|
|
2
|
+
from the files it keeps, so a reader never waits on it."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import socket
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from acppool.sessions import unwrapped
|
|
10
|
+
|
|
11
|
+
OPS = {"status", "start", "prompt", "steer", "cancel", "answer", "reset", "resume", "chrome", "stop"}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def call(path: Path, op: str, timeout: float = 180, **args) -> dict:
|
|
15
|
+
"""One command to the supervisor; its answer, or a RuntimeError with its reason."""
|
|
16
|
+
if op not in OPS:
|
|
17
|
+
raise ValueError(f"unknown op {op}")
|
|
18
|
+
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
19
|
+
s.settimeout(timeout)
|
|
20
|
+
try:
|
|
21
|
+
s.connect(str(path))
|
|
22
|
+
except (FileNotFoundError, ConnectionRefusedError):
|
|
23
|
+
raise RuntimeError("the agents' supervisor is not running") from None
|
|
24
|
+
with s, s.makefile("rwb") as f:
|
|
25
|
+
f.write((json.dumps({"op": op, **args}) + "\n").encode())
|
|
26
|
+
f.flush()
|
|
27
|
+
line = f.readline()
|
|
28
|
+
if not line:
|
|
29
|
+
raise RuntimeError("the agents' supervisor closed the connection")
|
|
30
|
+
reply = json.loads(line)
|
|
31
|
+
if not reply.get("ok"):
|
|
32
|
+
raise RuntimeError(reply.get("error") or "failed")
|
|
33
|
+
return reply
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def agents(path: Path) -> dict[str, dict]:
|
|
37
|
+
try:
|
|
38
|
+
return json.loads(path.read_text())
|
|
39
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
40
|
+
return {}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def events(logs: Path, name: str, offset: int = 0) -> tuple[list[dict], int]:
|
|
44
|
+
"""The agent's events from a byte offset on, and the offset to read from next time."""
|
|
45
|
+
f = logs / f"{name}.jsonl"
|
|
46
|
+
if not f.exists():
|
|
47
|
+
return [], 0
|
|
48
|
+
with f.open("rb") as fh:
|
|
49
|
+
fh.seek(offset)
|
|
50
|
+
data = fh.read()
|
|
51
|
+
end = data.rfind(b"\n") + 1 # a line still being written waits for the next read
|
|
52
|
+
out = []
|
|
53
|
+
for line in data[:end].splitlines():
|
|
54
|
+
try:
|
|
55
|
+
out.append(json.loads(line))
|
|
56
|
+
except json.JSONDecodeError:
|
|
57
|
+
continue
|
|
58
|
+
return out, offset + end
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
TAIL = 65536 # the bytes of an event log its latest step is looked for in
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def last_words(logs: Path, name: str) -> str:
|
|
65
|
+
"""What the agent said last, whole: the words its latest turn ended on."""
|
|
66
|
+
f = logs / f"{name}.jsonl"
|
|
67
|
+
if not f.exists():
|
|
68
|
+
return ""
|
|
69
|
+
with f.open("rb") as fh:
|
|
70
|
+
fh.seek(max(0, f.stat().st_size - TAIL))
|
|
71
|
+
lines = fh.read().splitlines()
|
|
72
|
+
for line in reversed(lines):
|
|
73
|
+
try:
|
|
74
|
+
e = json.loads(line)
|
|
75
|
+
except json.JSONDecodeError:
|
|
76
|
+
continue
|
|
77
|
+
if e.get("kind") == "message" and e.get("text", "").strip():
|
|
78
|
+
return e["text"].strip()
|
|
79
|
+
if e.get("kind") in ("prompt", "session"):
|
|
80
|
+
return ""
|
|
81
|
+
return ""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def last_step(logs: Path, name: str) -> dict | None:
|
|
85
|
+
"""What the agent did last, from the end of its event log: a tool it ran, or the words it said."""
|
|
86
|
+
f = logs / f"{name}.jsonl"
|
|
87
|
+
if not f.exists():
|
|
88
|
+
return None
|
|
89
|
+
with f.open("rb") as fh:
|
|
90
|
+
fh.seek(max(0, f.stat().st_size - TAIL))
|
|
91
|
+
lines = fh.read().splitlines()
|
|
92
|
+
for line in reversed(lines):
|
|
93
|
+
try:
|
|
94
|
+
e = json.loads(line)
|
|
95
|
+
except json.JSONDecodeError:
|
|
96
|
+
continue
|
|
97
|
+
if e.get("kind") == "tool":
|
|
98
|
+
return {"kind": "tool", "text": tool_line(e), "at": e["at"]}
|
|
99
|
+
if e.get("kind") == "message" and e.get("text", "").strip():
|
|
100
|
+
return {"kind": "say", "text": e["text"].strip().split("\n")[0], "at": e["at"]}
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def tool_line(e: dict) -> str:
|
|
105
|
+
"""A tool event as one line: its name and its title, the title alone when it repeats the name."""
|
|
106
|
+
name, title = e.get("name") or "tool", (e.get("title") or "").strip()
|
|
107
|
+
return name if title in ("", name) else f"{name}: {title}"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _clip(text: str, n: int) -> str:
|
|
111
|
+
text = re.sub(r"\s+", " ", text or "").strip()
|
|
112
|
+
return text if len(text) <= n else text[:n] + "…"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
SYS = ("crashed", "failed", "interrupted", "resumed", "cancel") # what befalls an agent, as its log names it
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def steps(events: list[dict]) -> list[dict]:
|
|
119
|
+
"""A log's events as compact steps, each one line, in `last_step`'s kinds: what the agent was sent (human), what it
|
|
120
|
+
says, the tools it runs and what they gave back (result, error), and what befell it (sys)."""
|
|
121
|
+
out = []
|
|
122
|
+
for e in events:
|
|
123
|
+
k, at = e.get("kind"), e.get("at", "")
|
|
124
|
+
if k == "prompt":
|
|
125
|
+
out.append({"kind": "human", "text": _clip(e.get("text", ""), 400), "at": at})
|
|
126
|
+
elif k == "message" and e.get("text", "").strip():
|
|
127
|
+
out.append({"kind": "say", "text": _clip(e["text"], 600), "at": at})
|
|
128
|
+
elif k == "tool":
|
|
129
|
+
out.append({"kind": "tool", "text": _clip(tool_line(e), 260), "at": at})
|
|
130
|
+
elif k == "tool_done" and (text := _clip(unwrapped(e.get("output") or ""), 200)):
|
|
131
|
+
out.append({"kind": "error" if e.get("status") == "failed" else "result", "text": text, "at": at})
|
|
132
|
+
elif k == "permission":
|
|
133
|
+
out.append({"kind": "sys", "text": f"asks permission: {e.get('tool') or ''}".strip(": "), "at": at})
|
|
134
|
+
elif k in SYS:
|
|
135
|
+
out.append({"kind": "sys", "text": k, "at": at})
|
|
136
|
+
return out
|
acppool/codex.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Codex, through the ACP adapter `@agentclientprotocol/codex-acp` (built on the Codex App Server; it bundles the Codex
|
|
2
|
+
it runs). Each session is set to the `agent` mode, which edits the session's folder and runs commands, whatever Codex's
|
|
3
|
+
own config says; a model, when the app names one, is set the same way. Codex reviews its own risky actions ("Guardian
|
|
4
|
+
Review"), so it asks the human for fewer permissions than Claude does."""
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Callable
|
|
8
|
+
|
|
9
|
+
from acppool.adapters import npm
|
|
10
|
+
from acppool.claude import STEER
|
|
11
|
+
from acppool.supervisor import Kind
|
|
12
|
+
|
|
13
|
+
PACKAGE = "@agentclientprotocol/codex-acp"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def codex(command: Callable[[], list[str]], mode: str = "agent", model: str | None = None) -> Kind:
|
|
17
|
+
"""The kind, run by the adapter's command line; `model` one the adapter lists, else Codex's own config decides."""
|
|
18
|
+
return Kind(command=command, steer=STEER, options={"mode": mode, **({"model": model} if model else {})})
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def installed(folder: Path, var: str = "ACPPOOL_NODE", mode: str = "agent", model: str | None = None) -> Kind:
|
|
22
|
+
"""The kind, with the adapter npm installed in the folder (a package.json there pins its version)."""
|
|
23
|
+
return codex(npm(folder, PACKAGE, var=var), mode, model)
|
acppool/control.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""The human's controls over a worker: give it work, talk to it, answer it, clear, reset, hold, take its job back.
|
|
2
|
+
Each records what it did through the app and moves the worker on (`push.advance`). A refusal is a ValueError, worded
|
|
3
|
+
for the human, the supervisor's included."""
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
from acppool import pool, push
|
|
8
|
+
from acppool.push import App
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def supervisor(app: App, op: str, **args) -> dict:
|
|
12
|
+
try:
|
|
13
|
+
return app.supervisor.call(op, **args)
|
|
14
|
+
except RuntimeError as e:
|
|
15
|
+
raise ValueError(str(e)) from None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _member(app: App, name: str) -> dict:
|
|
19
|
+
w = app.store.read().get(name)
|
|
20
|
+
if not w:
|
|
21
|
+
raise ValueError(f"no worker {name}")
|
|
22
|
+
return w
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _status(app: App, w: dict) -> str:
|
|
26
|
+
return pool.status(w, app.supervisor.agents().get(w["name"]))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _stop_turn(app: App, name: str) -> None:
|
|
30
|
+
"""A turn running cancelled, and its end waited for."""
|
|
31
|
+
if (app.supervisor.agents().get(name) or {}).get("state") in ("busy", "asking"):
|
|
32
|
+
supervisor(app, "cancel", name=name)
|
|
33
|
+
for _ in range(60):
|
|
34
|
+
if (app.supervisor.agents().get(name) or {}).get("state") == "idle":
|
|
35
|
+
break
|
|
36
|
+
time.sleep(0.25)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def give(app: App, name: str, item: dict, why: str = "", said: str = "") -> int:
|
|
40
|
+
"""An item for the worker: its job now when it is free, else queued. Its brief is the item's own, else the app's.
|
|
41
|
+
Returns its place in the queue, 0 when given now. why says how it came; said, "; "-led, what the human added."""
|
|
42
|
+
w = _member(app, name)
|
|
43
|
+
extra = {k: v for k, v in item.items() if k not in ("kind", "name", "brief", "at")}
|
|
44
|
+
if pool.free(w, app.supervisor.agents().get(name)):
|
|
45
|
+
pool.assign(app.store, name, item["kind"], item["name"], item.get("brief") or app.brief(item, name), **extra)
|
|
46
|
+
app.record("assign", name, (why + said).lstrip("; "), item)
|
|
47
|
+
push.advance(app, name)
|
|
48
|
+
return 0
|
|
49
|
+
if _status(app, w) == "gone":
|
|
50
|
+
raise ValueError(f"{name} is gone; its session ended")
|
|
51
|
+
place = pool.queue(app.store, name, item["kind"], item["name"], **extra)
|
|
52
|
+
app.record("queue", name, (why + ", " if why else "") + f"{place} in its queue{said}", item)
|
|
53
|
+
return place
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def move(app: App, name: str, item: str, to: str) -> str:
|
|
57
|
+
"""A queued item, or a job given and not sent yet, to another worker."""
|
|
58
|
+
src = _member(app, name)
|
|
59
|
+
if src["job"] and src["job"]["name"] == item:
|
|
60
|
+
if src["job"].get("taken"):
|
|
61
|
+
raise ValueError(f"{name} has started {item}; stop it first, then give it")
|
|
62
|
+
found = src["job"]
|
|
63
|
+
pool.drop_job(app.store, name)
|
|
64
|
+
else:
|
|
65
|
+
found = next((x for x in src.get("queue", []) if x["name"] == item), None)
|
|
66
|
+
if not found:
|
|
67
|
+
raise ValueError(f"{name} does not hold {item}")
|
|
68
|
+
pool.unqueue(app.store, name, item)
|
|
69
|
+
dst = app.store.read().get(to)
|
|
70
|
+
if not dst or _status(app, dst) == "gone":
|
|
71
|
+
raise ValueError(f"no worker {to} to move it to")
|
|
72
|
+
give(app, to, {k: v for k, v in found.items() if k in ("kind", "name", "note", "mode")}, f"moved from {name}")
|
|
73
|
+
app.record("unqueue", name, f"{item}, moved to {to}")
|
|
74
|
+
push.advance(app, name) # its job moved away: the next queued item goes to it
|
|
75
|
+
return f"{item}: moved from {name} to {to}"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def unqueue_one(app: App, name: str, item: str) -> None:
|
|
79
|
+
pool.unqueue(app.store, name, item)
|
|
80
|
+
app.record("unqueue", name, item)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def reorder(app: App, name: str, item: str, before: str | None) -> None:
|
|
84
|
+
pool.reorder(app.store, name, item, before)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def unqueue(app: App, name: str, item: str) -> None:
|
|
88
|
+
"""The item out of the queue, and everything after it."""
|
|
89
|
+
gone = pool.cut(app.store, name, item)
|
|
90
|
+
app.record("unqueue", name, item + (f" and the {len(gone) - 1} after it" if len(gone) > 1 else ""))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def answer(app: App, name: str, text: str) -> None:
|
|
94
|
+
text = text.strip()
|
|
95
|
+
if not text:
|
|
96
|
+
raise ValueError("nothing to say")
|
|
97
|
+
pool.answer(app.store, name, text)
|
|
98
|
+
app.record("answer", name, text)
|
|
99
|
+
push.advance(app, name)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def say(app: App, name: str, text: str) -> None:
|
|
103
|
+
text = text.strip()
|
|
104
|
+
if not text:
|
|
105
|
+
raise ValueError("nothing to say")
|
|
106
|
+
_member(app, name)
|
|
107
|
+
push.deliver(app, name, text)
|
|
108
|
+
app.record("message", name, text)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def carry_on(app: App, name: str, text: str = "") -> None:
|
|
112
|
+
"""A worker stopped on its job, or waiting on a run: tell it to carry on now."""
|
|
113
|
+
w = app.store.read().get(name) or {}
|
|
114
|
+
r, job = w.get("waiting"), w.get("job") or {}
|
|
115
|
+
text = text.strip() or (f"Check on your run now: {r['what']}. If it still runs, call `wait` again and end your turn." if r
|
|
116
|
+
else "Go ahead with your job." if job.get("await") else "Carry on with your job.")
|
|
117
|
+
if r:
|
|
118
|
+
pool.mark(app.store, name, "waiting", None)
|
|
119
|
+
push.deliver(app, name, text)
|
|
120
|
+
app.record("message", name, text)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def compact(app: App, name: str) -> str:
|
|
124
|
+
"""Compact now, between jobs, or after its current job."""
|
|
125
|
+
w = _member(app, name)
|
|
126
|
+
if _status(app, w) == "idle" and not w["job"]:
|
|
127
|
+
supervisor(app, "prompt", name=name, text="/compact")
|
|
128
|
+
pool.mark(app.store, name, "compactedAt", pool.now())
|
|
129
|
+
app.record("compact", name, f"asked from {app.home}, between jobs")
|
|
130
|
+
return f"{name}: compacting now"
|
|
131
|
+
pool.mark(app.store, name, "compactDue", True)
|
|
132
|
+
app.record("compact", name, "to be compacted after its current job")
|
|
133
|
+
return f"{name}: compacts after its current job"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def clear(app: App, name: str) -> None:
|
|
137
|
+
"""A fresh session: a turn running is cancelled first, a question it waits on withdrawn; a job it held waits for the
|
|
138
|
+
human's next message, which it is sent with, to carry on from where it stands."""
|
|
139
|
+
w = _member(app, name)
|
|
140
|
+
_stop_turn(app, name)
|
|
141
|
+
supervisor(app, "reset", name=name, why="clear", run=w.get("run") or "")
|
|
142
|
+
app.record("clear", name, "")
|
|
143
|
+
if w["question"] and w["question"]["answer"] is None: # asked in the session just cleared: nobody there to read an answer
|
|
144
|
+
pool.mark(app.store, name, "question", None)
|
|
145
|
+
app.record("withdraw", name, "it went with the cleared session")
|
|
146
|
+
if w["job"] and w["job"].get("taken"):
|
|
147
|
+
# as Claude Code's /clear: nothing is sent; the job goes with the human's next message (its run is the same, so
|
|
148
|
+
# nothing clears it again)
|
|
149
|
+
with app.store.changing() as p:
|
|
150
|
+
p[name]["job"].pop("taken", None)
|
|
151
|
+
p[name]["job"]["await"] = True
|
|
152
|
+
p[name]["job"]["brief"] = app.cleared(p[name]["job"]) + p[name]["job"]["brief"]
|
|
153
|
+
push.advance(app, name)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def reset(app: App, name: str) -> str:
|
|
157
|
+
"""The worker back to a clean start and its job back to the app: a turn running cancelled, a question withdrawn,
|
|
158
|
+
the app's undoing of the attempt (`App.undo`), its queue emptied, a fresh session."""
|
|
159
|
+
w = app.store.read().get(name)
|
|
160
|
+
if not w or not w["job"]:
|
|
161
|
+
raise ValueError(f"{name} holds no job")
|
|
162
|
+
job = w["job"]
|
|
163
|
+
_stop_turn(app, name)
|
|
164
|
+
logged, said = app.undo(name, w)
|
|
165
|
+
supervisor(app, "reset", name=name, why="reset")
|
|
166
|
+
queued = [x["name"] for x in w.get("queue", [])]
|
|
167
|
+
with app.store.changing() as p:
|
|
168
|
+
m = p[name]
|
|
169
|
+
m.update(job=None, queue=[], waiting=None)
|
|
170
|
+
m.pop("run", None)
|
|
171
|
+
if m["question"] and m["question"]["answer"] is None:
|
|
172
|
+
m["question"] = None
|
|
173
|
+
app.record("reset", name, f"{job['name']} back to {app.home}" + (f", its queue emptied ({', '.join(queued)})" if queued else "") + logged)
|
|
174
|
+
push.advance(app, name)
|
|
175
|
+
return f"{name}: reset, {job['name']} back to {app.home}" + said
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def end(app: App, name: str) -> str:
|
|
179
|
+
"""A job the human ends (`App.ending` says which): over now when the worker is between turns, else once its
|
|
180
|
+
turn ends."""
|
|
181
|
+
w = app.store.read().get(name)
|
|
182
|
+
what = app.ending((w or {}).get("job"), name)
|
|
183
|
+
if not w["job"].get("taken"):
|
|
184
|
+
pool.drop_job(app.store, name)
|
|
185
|
+
else:
|
|
186
|
+
with app.store.changing() as p:
|
|
187
|
+
p[name]["job"]["ended"] = True
|
|
188
|
+
app.record("end", name, what)
|
|
189
|
+
push.advance(app, name)
|
|
190
|
+
return f"{name}: {what} ended"
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def interrupt(app: App, name: str) -> None:
|
|
194
|
+
"""Stop the turn now, and hold it: it gets nothing until released."""
|
|
195
|
+
pool.hold(app.store, name, True)
|
|
196
|
+
supervisor(app, "cancel", name=name)
|
|
197
|
+
app.record("interrupt", name, "")
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def hold(app: App, name: str, on: bool) -> None:
|
|
201
|
+
pool.hold(app.store, name, on)
|
|
202
|
+
app.record("hold" if on else "release", name, "")
|
|
203
|
+
if not on:
|
|
204
|
+
push.advance(app, name)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def takeback(app: App, name: str) -> str:
|
|
208
|
+
"""Its job back from a worker whose turn has ended (`App.give_back` says what that means for the job), the worker
|
|
209
|
+
free for its next. Its session keeps what it did."""
|
|
210
|
+
w = app.store.read().get(name)
|
|
211
|
+
if not w or not w["job"]:
|
|
212
|
+
raise ValueError(f"{name} holds no job")
|
|
213
|
+
if _status(app, w) in ("working", "reading", "approve", "starting"):
|
|
214
|
+
raise ValueError(f"{name} is mid-turn; stop it first, then take its job back")
|
|
215
|
+
job = w["job"]
|
|
216
|
+
app.give_back(name, job)
|
|
217
|
+
pool.mark(app.store, name, "waiting", None)
|
|
218
|
+
if job.get("taken"):
|
|
219
|
+
pool.finish(app.store, name)
|
|
220
|
+
else:
|
|
221
|
+
pool.drop_job(app.store, name)
|
|
222
|
+
app.record("takeback", name, "back to open, held by nobody", job)
|
|
223
|
+
push.advance(app, name)
|
|
224
|
+
return f"{job['name']}: taken back from {name}"
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def permit(app: App, name: str, option: str) -> None:
|
|
228
|
+
"""The human's answer to a permission its agent asks: one of the options it offered."""
|
|
229
|
+
perm = (app.supervisor.agents().get(name) or {}).get("permission")
|
|
230
|
+
if not perm:
|
|
231
|
+
raise ValueError(f"{name} asks no permission")
|
|
232
|
+
chosen = next((o for o in perm["options"] if o["id"] == option), None)
|
|
233
|
+
if not chosen:
|
|
234
|
+
raise ValueError(f"no option {option}")
|
|
235
|
+
supervisor(app, "answer", name=name, option=option)
|
|
236
|
+
app.record("permit", name, f"{chosen.get('name') or chosen['id']}: {perm.get('tool') or ''}".strip(": "))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def remove(app: App, name: str) -> None:
|
|
240
|
+
if name in app.supervisor.agents():
|
|
241
|
+
supervisor(app, "stop", name=name)
|
|
242
|
+
pool.leave(app.store, name)
|
|
243
|
+
app.record("leave", name, "")
|
|
244
|
+
|
acppool/mcp.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""The pool's tools for its agents, as an MCP server over stdio: `ask` the human, and `wait` on a run in the background.
|
|
2
|
+
An ACP agent starts the server itself, from the command line its session was opened with (`Config.servers`), so it
|
|
3
|
+
runs in a process of its own: it reaches the pool through a store every process can open (`SqliteStore`), and knows
|
|
4
|
+
the agent it serves from an environment variable. An app adds its own tools beside these, in one server:
|
|
5
|
+
|
|
6
|
+
serve(app_tools + pool_tools(store), "app", me_var="APP_AGENT")
|
|
7
|
+
|
|
8
|
+
Alone, for an app with no tools of its own:
|
|
9
|
+
|
|
10
|
+
python3 -m acppool.mcp --store <pool.db> [--table pool]
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import contextlib
|
|
15
|
+
import io
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Callable
|
|
22
|
+
|
|
23
|
+
from acppool import pool
|
|
24
|
+
from acppool.pool import SqliteStore, Store
|
|
25
|
+
|
|
26
|
+
def server(name: str, script: Path, env: dict[str, str], passed: tuple[str, ...] = ("HOME", "PATH")) -> dict:
|
|
27
|
+
"""An MCP server as `Config.servers` gives it: a Python script, the agent starts with these variables and those
|
|
28
|
+
passed from the supervisor's environment."""
|
|
29
|
+
env = env | {k: os.environ[k] for k in passed if k in os.environ}
|
|
30
|
+
return {"name": name, "command": sys.executable, "args": [str(script)], "env": [{"name": k, "value": v} for k, v in env.items()]}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
LIST = {"type": "array", "items": {"type": "string"}}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Tool:
|
|
38
|
+
"""One tool: its handler takes the agent's name and the call's arguments, and returns the text the agent reads; a
|
|
39
|
+
ValueError or a KeyError is a refusal the agent reads as an error."""
|
|
40
|
+
name: str
|
|
41
|
+
description: str
|
|
42
|
+
schema: dict
|
|
43
|
+
handler: Callable[[str, dict], str]
|
|
44
|
+
|
|
45
|
+
def listed(self) -> dict:
|
|
46
|
+
return {"name": self.name, "description": self.description, "inputSchema": self.schema}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _letter(rec) -> str | None:
|
|
50
|
+
return (rec or "").strip().strip("()").upper() or None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def questions(a: dict) -> tuple[str, list[str], str | None, list[dict]]:
|
|
54
|
+
"""An ask's arguments, checked: its text, options and recommended letter, and with `questions` the several asked
|
|
55
|
+
together, each {text, options, recommend}; one of them alone is asked as one."""
|
|
56
|
+
text, options, recommend = (a.get("question") or "").strip(), list(a.get("options") or []), _letter(a.get("recommend"))
|
|
57
|
+
parts = [{"text": (p.get("question") or "").strip(), "options": list(p.get("options") or []),
|
|
58
|
+
"recommend": _letter(p.get("recommend"))} for p in a.get("questions") or []]
|
|
59
|
+
for n, (opts, rec) in enumerate([(options, recommend)] + [(p["options"], p["recommend"]) for p in parts]):
|
|
60
|
+
if rec and not (len(rec) == 1 and 0 <= ord(rec) - 65 < len(opts)):
|
|
61
|
+
where = "recommend" if n == 0 else f"question {n}'s recommend"
|
|
62
|
+
raise ValueError(f"{where} {rec}: give the letter of one of its {len(opts)} options")
|
|
63
|
+
if any(not p["text"] for p in parts):
|
|
64
|
+
raise ValueError("each of the questions needs its question")
|
|
65
|
+
if parts and options:
|
|
66
|
+
raise ValueError("give the options under each of the questions, not beside them")
|
|
67
|
+
if len(parts) == 1:
|
|
68
|
+
p = parts.pop()
|
|
69
|
+
text, options, recommend = "\n\n".join(x for x in (text, p["text"]) if x), p["options"], p["recommend"]
|
|
70
|
+
if not text and not parts:
|
|
71
|
+
raise ValueError("ask what? Give the question")
|
|
72
|
+
return text, options, recommend, parts
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
ASK = ("Ask the human: a decision, or something only they can do. Put the context in the question and each choice in "
|
|
76
|
+
"its own option, and recommend one when you have a view. Several questions go in one call, under `questions`: "
|
|
77
|
+
"the human answers them together, so ask everything you need at once. Then end your turn: the answers come as "
|
|
78
|
+
"your next message.")
|
|
79
|
+
ASK_SCHEMA = {"type": "object", "properties": {
|
|
80
|
+
"question": {"type": "string", "description": "the question; with `questions`, the context they share"},
|
|
81
|
+
"options": LIST, "recommend": {"type": "string", "description": "the letter of the option you recommend: A, B, …"},
|
|
82
|
+
"questions": {"type": "array", "description": "several questions, answered together; then leave `options` out",
|
|
83
|
+
"items": {"type": "object", "properties": {
|
|
84
|
+
"question": {"type": "string"}, "options": LIST,
|
|
85
|
+
"recommend": {"type": "string", "description": "the letter of the option you recommend"}},
|
|
86
|
+
"required": ["question"]}}},
|
|
87
|
+
"required": ["question"]}
|
|
88
|
+
WAIT = ("End your turn on a run you started in the background (longer than a few minutes): you are woken when its "
|
|
89
|
+
"process ends, with the end of its output. Call it with the run's pid, then end your turn. Never plan to check "
|
|
90
|
+
"back later yourself: once your turn ends, only the pool wakes you.")
|
|
91
|
+
WAIT_SCHEMA = {"type": "object", "properties": {
|
|
92
|
+
"pid": {"type": "integer", "description": "the run's process id (`echo $!` after starting it with `nohup … &`)"},
|
|
93
|
+
"what": {"type": "string", "description": "what the run does, a few words, shown to the human"},
|
|
94
|
+
"output": {"type": "string", "description": "the file its output goes to; its last lines come with the wake-up"}},
|
|
95
|
+
"required": ["pid", "what"]}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def pool_tools(store: Store, on_ask: Callable[[str, dict], None] | None = None,
|
|
99
|
+
on_wait: Callable[[str, dict], None] | None = None) -> list[Tool]:
|
|
100
|
+
"""`ask` and `wait`, writing the agent's question and the run it waits on to the pool, where the push reads them.
|
|
101
|
+
on_ask and on_wait are told of each, with what was stored, for the app to record."""
|
|
102
|
+
|
|
103
|
+
def ask(me: str, a: dict) -> str:
|
|
104
|
+
text, options, recommend, parts = questions(a)
|
|
105
|
+
pool.ask(store, me, text, options, recommend, parts)
|
|
106
|
+
if on_ask:
|
|
107
|
+
on_ask(me, {"text": text, "options": options, "recommend": recommend, "parts": parts})
|
|
108
|
+
return "Asked. End your turn now: the answer comes as your next message."
|
|
109
|
+
|
|
110
|
+
def wait(me: str, a: dict) -> str:
|
|
111
|
+
try:
|
|
112
|
+
pid = int(a.get("pid"))
|
|
113
|
+
except (TypeError, ValueError):
|
|
114
|
+
raise ValueError("give the run's process id, as `pid`") from None
|
|
115
|
+
what, output = (a.get("what") or "").strip() or f"process {pid}", a.get("output") or ""
|
|
116
|
+
pool.wait(store, me, pid, what, output)
|
|
117
|
+
if on_wait:
|
|
118
|
+
on_wait(me, {"pid": pid, "what": what, "output": output})
|
|
119
|
+
return f"You are woken when process {pid} ends, with the end of its output. End your turn now."
|
|
120
|
+
|
|
121
|
+
return [Tool("ask", ASK, ASK_SCHEMA, ask), Tool("wait", WAIT, WAIT_SCHEMA, wait)]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def call(tool: Tool, me: str, args: dict) -> tuple[bool, str]:
|
|
125
|
+
"""A tool run, whatever it prints captured into its answer: the server's stdout is the protocol's."""
|
|
126
|
+
buf = io.StringIO()
|
|
127
|
+
try:
|
|
128
|
+
with contextlib.redirect_stdout(buf):
|
|
129
|
+
said = tool.handler(me, args)
|
|
130
|
+
return True, "\n".join(x for x in (buf.getvalue().strip(), (said or "").strip()) if x) or "ok"
|
|
131
|
+
except ValueError as e:
|
|
132
|
+
return False, (buf.getvalue() + str(e)).strip()
|
|
133
|
+
except KeyError as e:
|
|
134
|
+
return False, (buf.getvalue() + f"missing the argument {e}").strip()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def serve(tools: list[Tool], name: str, me_var: str = "ACPPOOL_AGENT", instructions: str = "",
|
|
138
|
+
stdin=None, stdout=None) -> None:
|
|
139
|
+
"""The MCP server, until its input ends: one JSON-RPC message a line, in and out."""
|
|
140
|
+
stdin, stdout = stdin or sys.stdin, stdout or sys.stdout
|
|
141
|
+
me, by = os.environ.get(me_var, ""), {t.name: t for t in tools}
|
|
142
|
+
|
|
143
|
+
def reply(mid, result=None, error=None) -> None:
|
|
144
|
+
stdout.write(json.dumps({"jsonrpc": "2.0", "id": mid, **({"error": error} if error else {"result": result})}) + "\n")
|
|
145
|
+
stdout.flush()
|
|
146
|
+
|
|
147
|
+
for line in stdin:
|
|
148
|
+
try:
|
|
149
|
+
msg = json.loads(line)
|
|
150
|
+
except json.JSONDecodeError:
|
|
151
|
+
continue
|
|
152
|
+
method, mid = msg.get("method"), msg.get("id")
|
|
153
|
+
if mid is None:
|
|
154
|
+
continue # a notification: initialized, cancelled
|
|
155
|
+
try:
|
|
156
|
+
if method == "initialize":
|
|
157
|
+
reply(mid, {"protocolVersion": (msg.get("params") or {}).get("protocolVersion", "2025-06-18"),
|
|
158
|
+
"capabilities": {"tools": {}}, "serverInfo": {"name": name, "version": "1"},
|
|
159
|
+
**({"instructions": instructions} if instructions else {})})
|
|
160
|
+
elif method == "ping":
|
|
161
|
+
reply(mid, {})
|
|
162
|
+
elif method == "tools/list":
|
|
163
|
+
reply(mid, {"tools": [t.listed() for t in tools]})
|
|
164
|
+
elif method == "tools/call":
|
|
165
|
+
p = msg.get("params") or {}
|
|
166
|
+
tool = by.get(p.get("name", ""))
|
|
167
|
+
ok, text = call(tool, me, p.get("arguments") or {}) if tool else (False, f"no tool {p.get('name')}")
|
|
168
|
+
reply(mid, {"content": [{"type": "text", "text": text}], "isError": not ok})
|
|
169
|
+
else:
|
|
170
|
+
reply(mid, error={"code": -32601, "message": f"no method {method}"})
|
|
171
|
+
except Exception as e: # noqa: BLE001 - one bad call must not end the server
|
|
172
|
+
reply(mid, error={"code": -32603, "message": f"{type(e).__name__}: {e}"})
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def main() -> None:
|
|
176
|
+
ap = argparse.ArgumentParser(prog="python3 -m acppool.mcp", description="The pool's tools, ask and wait, over stdio.")
|
|
177
|
+
ap.add_argument("--store", required=True, help="the pool's SQLite file")
|
|
178
|
+
ap.add_argument("--table", default="pool")
|
|
179
|
+
ap.add_argument("--me-var", default="ACPPOOL_AGENT", help="the variable naming the agent served")
|
|
180
|
+
a = ap.parse_args()
|
|
181
|
+
serve(pool_tools(SqliteStore(a.store, a.table)), "pool", a.me_var)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
if __name__ == "__main__":
|
|
185
|
+
main()
|