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/tests/base.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""A supervisor on a short socket, with one fake agent `w` started in a temporary folder: the fixture the supervisor's
|
|
2
|
+
tests run on, and an app's push tests too (`make_config` gives the app's own)."""
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import dataclasses
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import unittest
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from acppool import client, supervisor
|
|
15
|
+
from acppool.claude import claude
|
|
16
|
+
|
|
17
|
+
FAKE = Path(__file__).with_name("fake_agent.py")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SupervisorCase(unittest.TestCase):
|
|
21
|
+
def make_config(self, folder: Path) -> supervisor.Config:
|
|
22
|
+
"""The supervisor's configuration, its state in the test's folder; the fake kind and Claude's (never started
|
|
23
|
+
here, for what only Claude's has) are added to its kinds."""
|
|
24
|
+
return supervisor.Config.under(folder, kinds={})
|
|
25
|
+
|
|
26
|
+
def setUp(self):
|
|
27
|
+
self.dir = tempfile.TemporaryDirectory()
|
|
28
|
+
self.fake = supervisor.Kind(command=lambda: [sys.executable, str(FAKE)], steer="_session/steering")
|
|
29
|
+
base = self.make_config(Path(self.dir.name))
|
|
30
|
+
self.config = dataclasses.replace(base, kinds={"claude": claude(lambda: ["false"]), **base.kinds, "fake": self.fake},
|
|
31
|
+
backoff=0.05)
|
|
32
|
+
self.config.agents.unlink(missing_ok=True)
|
|
33
|
+
shutil.rmtree(self.config.logs, ignore_errors=True)
|
|
34
|
+
self.sock = Path(tempfile.mkdtemp(prefix="agentd-", dir="/tmp")) / "s.sock" # short: a Unix socket path is capped
|
|
35
|
+
self.serve()
|
|
36
|
+
self.call("start", name="w", agent="fake", cwd=self.dir.name)
|
|
37
|
+
|
|
38
|
+
def serve(self):
|
|
39
|
+
self.loop, self.stop = asyncio.new_event_loop(), asyncio.Event()
|
|
40
|
+
self.thread = threading.Thread(target=self.loop.run_until_complete,
|
|
41
|
+
args=(supervisor.Supervisor(self.config).serve(self.sock, self.stop),), daemon=True)
|
|
42
|
+
self.thread.start()
|
|
43
|
+
self.until(self.sock.exists)
|
|
44
|
+
|
|
45
|
+
def halt(self):
|
|
46
|
+
self.loop.call_soon_threadsafe(self.stop.set)
|
|
47
|
+
self.thread.join(10)
|
|
48
|
+
self.loop.close()
|
|
49
|
+
|
|
50
|
+
def tearDown(self):
|
|
51
|
+
self.halt()
|
|
52
|
+
self.dir.cleanup()
|
|
53
|
+
shutil.rmtree(self.sock.parent, ignore_errors=True)
|
|
54
|
+
|
|
55
|
+
def call(self, op, **kw):
|
|
56
|
+
return client.call(self.sock, op, 10, **kw)
|
|
57
|
+
|
|
58
|
+
def live(self) -> dict:
|
|
59
|
+
return client.agents(self.config.agents)
|
|
60
|
+
|
|
61
|
+
def until(self, ok, seconds=5):
|
|
62
|
+
end = time.time() + seconds
|
|
63
|
+
while not ok():
|
|
64
|
+
if time.time() > end:
|
|
65
|
+
self.fail(f"timed out; agents: {self.live()}")
|
|
66
|
+
time.sleep(0.02)
|
|
67
|
+
|
|
68
|
+
def state(self, s):
|
|
69
|
+
self.until(lambda: self.live().get("w", {}).get("state") == s)
|
|
70
|
+
|
|
71
|
+
def events(self, offset: int = 0):
|
|
72
|
+
return client.events(self.config.logs, "w", offset)
|
|
73
|
+
|
|
74
|
+
def log(self):
|
|
75
|
+
return self.events()[0]
|
|
76
|
+
|
|
77
|
+
def events_of(self, name: str) -> list[dict]:
|
|
78
|
+
return client.events(self.config.logs, name, 0)[0]
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""An ACP agent in miniature, for the tests: "slow" waits for a steer or a cancel, "ask" asks a permission, "die"
|
|
2
|
+
exits, "options" says the session's config options (the value "bad" is refused), a steer "late" finds its turn over; with --load-only it loads a session, replaying it, and cannot resume one; anything else is echoed, with a tool
|
|
3
|
+
call and the usage the adapter reports."""
|
|
4
|
+
import json, os, sys
|
|
5
|
+
def out(m): sys.stdout.write(json.dumps({"jsonrpc": "2.0", **m}) + "\n"); sys.stdout.flush()
|
|
6
|
+
def chunk(sid, text): out({"method": "session/update", "params": {"sessionId": sid, "update": {
|
|
7
|
+
"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}}})
|
|
8
|
+
def end(rid, stop="end_turn"): out({"id": rid, "result": {"stopReason": stop, "usage": {"totalTokens": 7}}})
|
|
9
|
+
n, slow, asking, spent, options = 0, None, None, 0.0, {}
|
|
10
|
+
LOAD_ONLY = "--load-only" in sys.argv # an agent that cannot resume a session, only load it
|
|
11
|
+
for line in sys.stdin:
|
|
12
|
+
m = json.loads(line); method, p = m.get("method"), m.get("params") or {}
|
|
13
|
+
if method == "initialize": out({"id": m["id"], "result": {"protocolVersion": 1, "agentCapabilities": {"loadSession": True}}})
|
|
14
|
+
elif method == "session/new": n += 1; out({"id": m["id"], "result": {"sessionId": f"s{os.getpid()}-{n}"}})
|
|
15
|
+
elif method == "session/resume" and LOAD_ONLY: out({"id": m["id"], "error": {"code": -32601, "message": "Method not found"}})
|
|
16
|
+
elif method == "session/load":
|
|
17
|
+
out({"method": "session/update", "params": {"sessionId": p["sessionId"], "update": {"sessionUpdate": "user_message_chunk", "content": {"type": "text", "text": "old"}}}})
|
|
18
|
+
chunk(p["sessionId"], "replayed")
|
|
19
|
+
out({"method": "session/update", "params": {"sessionId": p["sessionId"], "update": {"sessionUpdate": "usage_update", "used": 9, "size": 100}}})
|
|
20
|
+
out({"id": m["id"], "result": {}})
|
|
21
|
+
elif method == "session/resume" and p.get("sessionId") == "lost": out({"id": m["id"], "error": {"code": -32603, "message": "no transcript"}})
|
|
22
|
+
elif method in ("session/resume", "session/close"): out({"id": m["id"], "result": {}})
|
|
23
|
+
elif method == "session/set_config_option":
|
|
24
|
+
if p["value"] == "bad": out({"id": m["id"], "error": {"code": -32602, "message": "no such value"}})
|
|
25
|
+
else: options[p["sessionId"]] = {**options.get(p["sessionId"], {}), p["configId"]: p["value"]}; out({"id": m["id"], "result": {}})
|
|
26
|
+
elif method == "session/prompt":
|
|
27
|
+
sid, text = p["sessionId"], p["prompt"][0]["text"]
|
|
28
|
+
if text == "die": sys.exit(3)
|
|
29
|
+
if text == "options": chunk(sid, json.dumps(options.get(sid, {}))); end(m["id"]); continue
|
|
30
|
+
if text == "slow": slow = (m["id"], sid)
|
|
31
|
+
elif text == "ask":
|
|
32
|
+
asking = (m["id"], sid)
|
|
33
|
+
out({"id": 1000, "method": "session/request_permission", "params": {"sessionId": sid, "toolCall": {"title": "Run x"},
|
|
34
|
+
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}, {"optionId": "no", "name": "Deny", "kind": "reject_once"}]}})
|
|
35
|
+
else:
|
|
36
|
+
out({"method": "session/update", "params": {"sessionId": sid, "update": {"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Read a", "kind": "read", "status": "pending"}}})
|
|
37
|
+
out({"method": "session/update", "params": {"sessionId": sid, "update": {"sessionUpdate": "tool_call_update", "toolCallId": "t1", "status": "completed"}}})
|
|
38
|
+
spent += 0.25 # the session's cost so far, as Claude's adapter reports it
|
|
39
|
+
out({"method": "session/update", "params": {"sessionId": sid, "update": {"sessionUpdate": "usage_update", "used": 5, "size": 100,
|
|
40
|
+
"cost": {"amount": spent, "currency": "USD"},
|
|
41
|
+
"_meta": {"_claude/rateLimit": {"rateLimitType": "five_hour", "status": "allowed"}}}}})
|
|
42
|
+
chunk(sid, "echo:"); chunk(sid, text); end(m["id"])
|
|
43
|
+
elif method == "_session/steering" and p["prompt"][0]["text"] == "late" and (p.get("_meta") or {}).get("steering", {}).get("idleBehavior") == "promptRequired":
|
|
44
|
+
out({"id": m["id"], "result": {"outcome": "promptRequired", "reason": "noRunningTurn"}})
|
|
45
|
+
elif method == "_session/steering":
|
|
46
|
+
out({"id": m["id"], "result": {"outcome": "injected"}})
|
|
47
|
+
if slow: chunk(slow[1], "steered:" + p["prompt"][0]["text"]); end(slow[0]); slow = None
|
|
48
|
+
elif method == "session/cancel" and slow: end(slow[0], "cancelled"); slow = None
|
|
49
|
+
elif m.get("id") == 1000 and asking: chunk(asking[1], "allowed:" + m["result"]["outcome"].get("optionId", "-")); end(asking[0]); asking = None
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""acppool's parts on their own, with no agent running: the store, the push, the controls, the needs, the MCP tools."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import shutil
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
import time
|
|
8
|
+
import unittest
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Library(unittest.TestCase):
|
|
13
|
+
"""The library on its own: a memory or SQLite store, a fake supervisor, the simplest app."""
|
|
14
|
+
|
|
15
|
+
def test_it_imports_only_the_standard_library_and_itself(self):
|
|
16
|
+
import ast
|
|
17
|
+
for f in sorted(Path(__file__).resolve().parent.parent.glob("*.py")):
|
|
18
|
+
for node in ast.walk(ast.parse(f.read_text())):
|
|
19
|
+
names = [a.name for a in node.names] if isinstance(node, ast.Import) else \
|
|
20
|
+
[node.module] if isinstance(node, ast.ImportFrom) and node.module and not node.level else []
|
|
21
|
+
for n in names:
|
|
22
|
+
top = n.split(".")[0]
|
|
23
|
+
self.assertTrue(top == "acppool" or top in sys.stdlib_module_names, f"{f.name} imports {n}")
|
|
24
|
+
|
|
25
|
+
def test_its_mcp_server_asks_and_waits_for_the_agent_it_serves(self):
|
|
26
|
+
import io
|
|
27
|
+
import os
|
|
28
|
+
from unittest import mock
|
|
29
|
+
from acppool import mcp, pool as lib
|
|
30
|
+
store = lib.MemoryStore()
|
|
31
|
+
lib.join(store, set(), "/x", "claude", ["w"])
|
|
32
|
+
seen = []
|
|
33
|
+
tools = [mcp.Tool("echo", "says it back", {"type": "object"}, lambda me, a: print(me) or a["text"])]
|
|
34
|
+
tools += mcp.pool_tools(store, on_ask=lambda me, q: seen.append((me, q["text"])))
|
|
35
|
+
msgs = [{"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {}}, {"jsonrpc": "2.0", "method": "notifications/initialized"},
|
|
36
|
+
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}]
|
|
37
|
+
calls = [("echo", {"text": "hi"}), ("echo", {}), ("ask", {"question": "which?", "options": ["a", "b"], "recommend": "b"}),
|
|
38
|
+
("ask", {"question": "", "options": ["a"], "recommend": "C"}), ("wait", {"pid": os.getpid(), "what": "a run"}),
|
|
39
|
+
("wait", {"pid": "x", "what": "no"}), ("nope", {})]
|
|
40
|
+
msgs += [{"jsonrpc": "2.0", "id": i, "method": "tools/call", "params": {"name": n, "arguments": a}} for i, (n, a) in enumerate(calls, 2)]
|
|
41
|
+
out = io.StringIO()
|
|
42
|
+
with mock.patch.dict(os.environ, {"ACPPOOL_AGENT": "w"}):
|
|
43
|
+
mcp.serve(tools, "pool", stdin=io.StringIO("".join(json.dumps(m) + "\n" for m in msgs)), stdout=out)
|
|
44
|
+
got = [json.loads(x) for x in out.getvalue().splitlines()]
|
|
45
|
+
self.assertEqual(got[0]["result"]["serverInfo"]["name"], "pool")
|
|
46
|
+
self.assertEqual([t["name"] for t in got[1]["result"]["tools"]], ["echo", "ask", "wait"])
|
|
47
|
+
res = [(not r["result"]["isError"], r["result"]["content"][0]["text"]) for r in got[2:]]
|
|
48
|
+
self.assertEqual([ok for ok, _ in res], [True, False, True, False, True, False, False])
|
|
49
|
+
self.assertEqual(res[0][1], "w\nhi") # what a tool prints joins its answer, never the protocol's stdout
|
|
50
|
+
self.assertIn("missing the argument", res[1][1])
|
|
51
|
+
w = store.read()["w"]
|
|
52
|
+
self.assertEqual((w["question"]["text"], w["question"]["recommend"]), ("which?", "B"))
|
|
53
|
+
self.assertEqual(seen, [("w", "which?")])
|
|
54
|
+
self.assertEqual((w["waiting"]["pid"], w["waiting"]["what"]), (os.getpid(), "a run"))
|
|
55
|
+
|
|
56
|
+
def test_sessions_index_a_log_by_opaque_jobs_and_find_one_to_resume(self):
|
|
57
|
+
from acppool import sessions
|
|
58
|
+
logs = Path(tempfile.mkdtemp(prefix="acppool-"))
|
|
59
|
+
self.addCleanup(shutil.rmtree, logs, True)
|
|
60
|
+
f = logs / "w.jsonl"
|
|
61
|
+
lines = [{"kind": "session", "session": "s1", "why": "start", "cwd": "/a", "agent": "x"},
|
|
62
|
+
{"kind": "prompt", "text": "go", "job": {"kind": "anything", "name": "j1"}},
|
|
63
|
+
{"kind": "turn", "stop": "end_turn"},
|
|
64
|
+
{"kind": "session", "session": "s2", "why": "run", "cwd": "/a", "agent": "x", "previous": "s1"}]
|
|
65
|
+
f.write_text("".join(json.dumps({"at": f"2026-11-27T10:00:0{i}+00:00", **e}) + "\n" for i, e in enumerate(lines)))
|
|
66
|
+
got = sessions.sessions(logs, "w")
|
|
67
|
+
self.assertEqual([(x["session"], x["why"], [j["name"] for j in x["jobs"]]) for x in got], [("s1", "start", ["j1"]), ("s2", "run", [])])
|
|
68
|
+
self.assertTrue((logs / ".index" / "w.json").exists())
|
|
69
|
+
self.assertEqual([e["kind"] for e in sessions.read(logs, "w", got[0])], ["session", "prompt", "turn"])
|
|
70
|
+
live = {"w": {"session": "s2", "cwd": "/a", "agent": "x"}}
|
|
71
|
+
self.assertEqual(sessions.resumable(logs, "j1", "w", live)["session"], "s1")
|
|
72
|
+
self.assertIsNone(sessions.resumable(logs, "j1", "w", {**live, "v": {"session": "s1"}})) # another agent's now
|
|
73
|
+
self.assertIsNone(sessions.resumable(logs, "j1", "w", {"w": {**live["w"], "cwd": "/b"}})) # another folder
|
|
74
|
+
f.unlink()
|
|
75
|
+
f.write_text(json.dumps({"at": "2026-11-27T11:00:00+00:00", "kind": "session", "session": "s9", "why": "start"}) + "\n")
|
|
76
|
+
self.assertEqual([x["session"] for x in sessions.sessions(logs, "w")], ["s9"]) # a log made again starts afresh
|
|
77
|
+
|
|
78
|
+
def test_the_push_runs_on_any_store_and_the_simplest_app(self):
|
|
79
|
+
from acppool import pool, push
|
|
80
|
+
|
|
81
|
+
class Supervisor:
|
|
82
|
+
def __init__(self):
|
|
83
|
+
self.sent, self.state = [], {"w": {"state": "idle"}}
|
|
84
|
+
|
|
85
|
+
def call(self, op, **args):
|
|
86
|
+
self.sent.append((op, args))
|
|
87
|
+
return {}
|
|
88
|
+
|
|
89
|
+
def agents(self):
|
|
90
|
+
return self.state
|
|
91
|
+
|
|
92
|
+
sup, store = Supervisor(), pool.MemoryStore()
|
|
93
|
+
app = push.App(store, sup)
|
|
94
|
+
w = pool.join(store, set(), "/x", names=["w"])
|
|
95
|
+
pool.queue(store, w, "job", "a", note="first")
|
|
96
|
+
pool.queue(store, w, "job", "b")
|
|
97
|
+
self.assertEqual(push.advance(app, w), "job")
|
|
98
|
+
self.assertEqual(sup.sent[-1], ("prompt", {"name": "w", "text": "a", "job": {"kind": "job", "name": "a", "run": "a"}}))
|
|
99
|
+
self.assertEqual(store.read()[w]["job"]["note"], "first") # the app's own fields, carried as given
|
|
100
|
+
self.assertEqual(push.advance(app, w), "job") # one turn, its own run: the next job in a fresh session
|
|
101
|
+
self.assertEqual([op for op, _ in sup.sent], ["prompt", "reset", "prompt"])
|
|
102
|
+
self.assertEqual(store.read()[w]["run"], "b")
|
|
103
|
+
pool.message(store, w, "hi")
|
|
104
|
+
self.assertEqual(push.advance(app, w), "messages")
|
|
105
|
+
self.assertEqual(store.read()[w]["inbox"], [])
|
|
106
|
+
self.assertEqual(sup.sent[-1][1]["text"], "Message from the pool: hi")
|
|
107
|
+
# the push's loop, on its own thread: what is queued goes out without anyone calling advance
|
|
108
|
+
import threading
|
|
109
|
+
pool.queue(store, w, "job", "c")
|
|
110
|
+
stop, errors = threading.Event(), []
|
|
111
|
+
t = threading.Thread(target=push.run, args=(lambda: app, 0.01, stop, errors.append))
|
|
112
|
+
t.start()
|
|
113
|
+
self.addCleanup(stop.set)
|
|
114
|
+
for _ in range(200):
|
|
115
|
+
if store.read()[w]["run"] == "c":
|
|
116
|
+
break
|
|
117
|
+
time.sleep(0.01)
|
|
118
|
+
stop.set()
|
|
119
|
+
t.join(1)
|
|
120
|
+
self.assertEqual((store.read()[w]["run"], errors, t.is_alive()), ("c", [], False))
|
|
121
|
+
|
|
122
|
+
def test_a_turn_cut_off_is_carried_on_only_where_the_app_says_how(self):
|
|
123
|
+
from acppool import pool, push
|
|
124
|
+
|
|
125
|
+
class Supervisor:
|
|
126
|
+
def __init__(self):
|
|
127
|
+
self.sent = []
|
|
128
|
+
|
|
129
|
+
def call(self, op, **args):
|
|
130
|
+
self.sent.append((op, args))
|
|
131
|
+
return {}
|
|
132
|
+
|
|
133
|
+
def agents(self):
|
|
134
|
+
return {"w": {"state": "idle", "turn": {"began": "t", "stop": "interrupted"}}}
|
|
135
|
+
|
|
136
|
+
sup, store = Supervisor(), pool.MemoryStore()
|
|
137
|
+
app = push.App(store, sup)
|
|
138
|
+
w = pool.join(store, set(), "/x", names=["w"])
|
|
139
|
+
pool.assign(store, w, "job", "a", "do a")
|
|
140
|
+
with store.changing() as p:
|
|
141
|
+
p[w]["job"]["taken"], p[w]["run"] = pool.now(), "a"
|
|
142
|
+
self.assertEqual(push.advance(app, w), "") # by default it waits for the human
|
|
143
|
+
self.assertEqual(pool.status(store.read()[w], sup.agents()[w]), "stopped")
|
|
144
|
+
app.interrupted = lambda job, worker: f"Carry on with {job['name']}, {worker}."
|
|
145
|
+
self.assertEqual(push.advance(app, w), "resume")
|
|
146
|
+
self.assertEqual(sup.sent[-1], ("prompt", {"name": "w", "text": "Carry on with a, w.", "job": {"kind": "job", "name": "a", "run": "a"}}))
|
|
147
|
+
|
|
148
|
+
def test_what_waits_on_the_human_has_a_key_each_new_ask_changes(self):
|
|
149
|
+
from acppool.needs import fresh, needs
|
|
150
|
+
q = {"text": "Which? (A) one (B) two. I recommend B", "at": "t1", "answer": None, "options": []}
|
|
151
|
+
members = [{"name": "a", "status": "asking", "question": q, "live": {}},
|
|
152
|
+
{"name": "b", "status": "approve", "question": None, "live": {"since": "s", "permission": {"tool": "Bash", "options": [{"id": "y", "name": "Allow"}]}}},
|
|
153
|
+
{"name": "c", "status": "replied", "question": None, "live": {"turn": {"began": "b1"}}},
|
|
154
|
+
{"name": "d", "status": "working", "question": None, "live": {}}]
|
|
155
|
+
got = needs(members, lambda n: f"{n} said")
|
|
156
|
+
self.assertEqual([(x["kind"], x["key"]) for x in got], [("ask", "a|ask|t1"), ("permit", "b|permit|s"), ("turn", "c|turn|b1")])
|
|
157
|
+
self.assertEqual((got[0]["options"], got[0]["recommend"]), ([("A", "one"), ("B", "two.")], "B"))
|
|
158
|
+
self.assertEqual((got[1]["options"], got[2]["text"]), ([("y", "Allow")], "c said"))
|
|
159
|
+
self.assertEqual([x["key"] for x in fresh(got, {"a|ask|t1"})], ["b|permit|s", "c|turn|b1"])
|
|
160
|
+
|
|
161
|
+
def test_the_controls_give_clear_reset_and_end_on_the_simplest_app(self):
|
|
162
|
+
from acppool import control, pool, push
|
|
163
|
+
|
|
164
|
+
class Supervisor:
|
|
165
|
+
def __init__(self):
|
|
166
|
+
self.sent = []
|
|
167
|
+
|
|
168
|
+
def call(self, op, **args):
|
|
169
|
+
self.sent.append(op)
|
|
170
|
+
return {}
|
|
171
|
+
|
|
172
|
+
def agents(self):
|
|
173
|
+
return {"w": {"state": "idle"}}
|
|
174
|
+
|
|
175
|
+
sup, store = Supervisor(), pool.MemoryStore()
|
|
176
|
+
app = push.App(store, sup)
|
|
177
|
+
w = pool.join(store, set(), "/x", names=["w"])
|
|
178
|
+
app.job_over = lambda job, worker: bool(job.get("ended")) # a job the human ends
|
|
179
|
+
self.assertEqual(control.give(app, w, {"kind": "talk", "name": "t"}), 0)
|
|
180
|
+
self.assertEqual(control.give(app, w, {"kind": "job", "name": "j"}), 1)
|
|
181
|
+
self.assertEqual(sup.sent, ["prompt"])
|
|
182
|
+
control.clear(app, w)
|
|
183
|
+
self.assertEqual(sup.sent, ["prompt", "reset"]) # as /clear: nothing sent
|
|
184
|
+
self.assertTrue(store.read()[w]["job"]["await"])
|
|
185
|
+
self.assertTrue(store.read()[w]["job"]["brief"].startswith("Your context was cleared"))
|
|
186
|
+
control.say(app, w, "go on")
|
|
187
|
+
self.assertEqual(sup.sent[-1], "prompt") # the held job, with what the human said
|
|
188
|
+
self.assertEqual(control.end(app, w), "w: t ended")
|
|
189
|
+
self.assertEqual(store.read()[w]["job"]["name"], "j") # the next, given at the end of the turn
|
|
190
|
+
self.assertEqual(control.reset(app, w), "w: reset, j back to the pool")
|
|
191
|
+
self.assertEqual((store.read()[w]["job"], store.read()[w]["queue"]), (None, []))
|
|
192
|
+
with self.assertRaisesRegex(ValueError, "holds no job"):
|
|
193
|
+
control.takeback(app, w)
|
|
194
|
+
|
|
195
|
+
def test_a_sqlite_store_writes_a_change_whole_or_not_at_all(self):
|
|
196
|
+
from acppool import pool
|
|
197
|
+
d = Path(tempfile.mkdtemp(prefix="acppool-"))
|
|
198
|
+
self.addCleanup(shutil.rmtree, d, True)
|
|
199
|
+
store = pool.SqliteStore(d / "pool.db")
|
|
200
|
+
w = pool.join(store, set(), "/x", names=["w"])
|
|
201
|
+
with self.assertRaises(RuntimeError), store.changing() as p:
|
|
202
|
+
p[w]["held"] = True
|
|
203
|
+
raise RuntimeError
|
|
204
|
+
self.assertNotIn("held", store.read()[w])
|
|
205
|
+
pool.hold(store, w, True)
|
|
206
|
+
self.assertTrue(pool.SqliteStore(d / "pool.db").read()[w]["held"])
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def test_a_sqlite_store_first_opened_by_two_threads_at_once_prepares_its_file_once(self):
|
|
210
|
+
import threading
|
|
211
|
+
from acppool import pool
|
|
212
|
+
d = Path(tempfile.mkdtemp(prefix="acppool-"))
|
|
213
|
+
self.addCleanup(shutil.rmtree, d, True)
|
|
214
|
+
errors = []
|
|
215
|
+
for i in range(50): # unguarded, about one run in five found the file locked
|
|
216
|
+
store, go = pool.SqliteStore(d / f"{i}.db"), threading.Barrier(2)
|
|
217
|
+
|
|
218
|
+
def first(use):
|
|
219
|
+
go.wait()
|
|
220
|
+
try:
|
|
221
|
+
use()
|
|
222
|
+
except Exception as e: # noqa: BLE001
|
|
223
|
+
errors.append(e)
|
|
224
|
+
|
|
225
|
+
ts = [threading.Thread(target=first, args=(store.read,)),
|
|
226
|
+
threading.Thread(target=first, args=(lambda: pool.join(store, set(), "/x"),))]
|
|
227
|
+
for t in ts:
|
|
228
|
+
t.start()
|
|
229
|
+
for t in ts:
|
|
230
|
+
t.join(10)
|
|
231
|
+
self.assertEqual(errors, [])
|
|
232
|
+
|
|
233
|
+
def test_a_json_store_keeps_the_pool_for_every_process_and_writes_only_a_change(self):
|
|
234
|
+
from acppool import pool
|
|
235
|
+
d = Path(tempfile.mkdtemp(prefix="acppool-"))
|
|
236
|
+
self.addCleanup(shutil.rmtree, d, True)
|
|
237
|
+
store = pool.JsonStore(d / "pool.json")
|
|
238
|
+
self.assertEqual(store.read(), {})
|
|
239
|
+
w = pool.join(store, set(), "/x", names=["w"])
|
|
240
|
+
mtime = (d / "pool.json").stat().st_mtime_ns
|
|
241
|
+
with store.changing():
|
|
242
|
+
pass
|
|
243
|
+
self.assertEqual((d / "pool.json").stat().st_mtime_ns, mtime)
|
|
244
|
+
pool.hold(store, w, True)
|
|
245
|
+
self.assertTrue(pool.JsonStore(d / "pool.json").read()[w]["held"])
|
|
246
|
+
|
|
247
|
+
def test_uploads_are_kept_once_and_read_into_the_prompt(self):
|
|
248
|
+
import base64
|
|
249
|
+
from acppool.uploads import Uploads
|
|
250
|
+
d = Path(tempfile.mkdtemp(prefix="acppool-"))
|
|
251
|
+
self.addCleanup(shutil.rmtree, d, True)
|
|
252
|
+
up = Uploads(d)
|
|
253
|
+
png = up.save("shot.png", "image/png", base64.b64encode(b"\x89PNG fake").decode())
|
|
254
|
+
pdf = up.save("spec.pdf", "application/pdf", base64.b64encode(b"%PDF").decode())
|
|
255
|
+
self.assertEqual(up.save("again.png", "image/png", base64.b64encode(b"\x89PNG fake").decode())["id"], png["id"])
|
|
256
|
+
blocks = up.prompt(f"look {png['link']} and {pdf['link']} and ")
|
|
257
|
+
self.assertEqual([b["type"] for b in blocks], ["text", "image"])
|
|
258
|
+
self.assertIn(str(d / pdf["id"]), blocks[0]["text"])
|
|
259
|
+
self.assertIn("no longer kept", blocks[0]["text"])
|
|
260
|
+
self.assertEqual(len(up.prompt(png["link"], images=False)), 1) # an agent that reads no images gets the path alone
|
|
261
|
+
self.assertIsNone(up.path_of("../pool.db"))
|
|
262
|
+
with self.assertRaises(ValueError):
|
|
263
|
+
up.save("x", "", "not base64!")
|
|
264
|
+
|
|
265
|
+
def test_turns_are_read_from_the_logs_once_each(self):
|
|
266
|
+
from acppool import sessions
|
|
267
|
+
d = Path(tempfile.mkdtemp(prefix="acppool-"))
|
|
268
|
+
self.addCleanup(shutil.rmtree, d, True)
|
|
269
|
+
log = d / "w.jsonl"
|
|
270
|
+
lines = [{"kind": "prompt", "at": "2026-11-18T10:00:05+00:00", "text": "go"},
|
|
271
|
+
{"kind": "turn", "at": "2026-11-18T10:01:00+00:00", "stop": "end_turn", "cost": 0.5,
|
|
272
|
+
"usage": {"inputTokens": 3, "outputTokens": 4}}]
|
|
273
|
+
log.write_text("".join(json.dumps(e) + "\n" for e in lines) + '{"kind": "tu') # the last line still being written
|
|
274
|
+
got, read = sessions.turns_since(d, {})
|
|
275
|
+
self.assertEqual(len(got), 1)
|
|
276
|
+
self.assertEqual((got[0]["agent"], got[0]["began"], got[0]["models"]),
|
|
277
|
+
("w", sessions.local("2026-11-18T10:00:05+00:00"), {"?": [3, 0, 0, 4]}))
|
|
278
|
+
self.assertEqual(sessions.turns_since(d, read)[0], [])
|
|
279
|
+
with log.open("a") as f:
|
|
280
|
+
f.write('rn", "at": "2026-11-18T10:02:00+00:00", "models": [{"model": "m", "token_count": {"outputTokens": 9}}]}\n')
|
|
281
|
+
self.assertEqual(sessions.turns_since(d, read)[0][0]["models"], {"m": [0, 0, 0, 9]})
|
|
282
|
+
codex = {"models": [{"model": "c", "token_count": {"inputTokens": 1, "cacheWriteInputTokens": 2, "cachedInputTokens": 3, "outputTokens": 4}}]}
|
|
283
|
+
self.assertEqual(sessions.tokens(codex), {"c": [1, 2, 3, 4]})
|
|
284
|
+
|
|
285
|
+
def test_an_npm_adapter_is_found_when_an_agent_starts(self):
|
|
286
|
+
import os
|
|
287
|
+
from unittest import mock
|
|
288
|
+
from acppool import adapters, mcp
|
|
289
|
+
d = Path(tempfile.mkdtemp(prefix="acppool-"))
|
|
290
|
+
self.addCleanup(shutil.rmtree, d, True)
|
|
291
|
+
command = adapters.npm(d, "@x/agent", var="TEST_NODE")
|
|
292
|
+
with mock.patch.dict(os.environ, {"TEST_NODE": "/bin/node"}):
|
|
293
|
+
with self.assertRaisesRegex(RuntimeError, "npm install"):
|
|
294
|
+
command()
|
|
295
|
+
(d / "node_modules" / "@x" / "agent" / "dist").mkdir(parents=True)
|
|
296
|
+
(d / "node_modules" / "@x" / "agent" / "dist" / "index.js").write_text("")
|
|
297
|
+
self.assertEqual(command(), ["/bin/node", str(d / "node_modules/@x/agent/dist/index.js")])
|
|
298
|
+
with mock.patch.dict(os.environ, {"HOME": "/h"}):
|
|
299
|
+
s = mcp.server("app", d / "tools.py", {"APP_AGENT": "w"}, passed=("HOME", "NOT_SET"))
|
|
300
|
+
self.assertEqual(s["env"], [{"name": "APP_AGENT", "value": "w"}, {"name": "HOME", "value": "/h"}])
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def test_a_log_reads_as_compact_steps(self):
|
|
304
|
+
from acppool import client
|
|
305
|
+
log = [{"kind": "session", "at": "1"}, {"kind": "prompt", "at": "2", "text": "do\n it"},
|
|
306
|
+
{"kind": "tool", "at": "3", "id": "t", "name": "Bash", "title": "`ls`"},
|
|
307
|
+
{"kind": "tool_done", "at": "4", "id": "t", "status": "failed", "output": '[{"type": "text", "text": "no such"}]'},
|
|
308
|
+
{"kind": "tool_done", "at": "4", "id": "u", "status": "completed", "output": ""},
|
|
309
|
+
{"kind": "tool", "at": "4", "id": "v", "name": "ToolSearch", "title": "ToolSearch"}, {"kind": "message", "at": "5", "text": "x" * 700}, {"kind": "thought", "at": "5", "text": "hm"},
|
|
310
|
+
{"kind": "permission", "at": "6", "tool": "Write"}, {"kind": "crashed", "at": "7"}]
|
|
311
|
+
got = client.steps(log)
|
|
312
|
+
self.assertEqual([(s["kind"], s["text"][:20]) for s in got],
|
|
313
|
+
[("human", "do it"), ("tool", "Bash: `ls`"), ("error", "no such"), ("tool", "ToolSearch"), ("say", "x" * 20),
|
|
314
|
+
("sys", "asks permission: Wri"), ("sys", "crashed")])
|
|
315
|
+
self.assertEqual(len(got[4]["text"]), 601)
|
|
316
|
+
|
|
317
|
+
class AskSeveral(unittest.TestCase):
|
|
318
|
+
"""Several questions go in one ask, answered together; one alone is asked as one."""
|
|
319
|
+
|
|
320
|
+
def test_questions_parse_and_check(self):
|
|
321
|
+
from acppool.mcp import questions
|
|
322
|
+
qs = [{"question": "a?", "options": ["x", "y"], "recommend": "B"}, {"question": "b?"}]
|
|
323
|
+
text, options, rec, parts = questions({"question": "the context", "questions": qs})
|
|
324
|
+
self.assertEqual((text, options, rec), ("the context", [], None))
|
|
325
|
+
self.assertEqual(parts, [{"text": "a?", "options": ["x", "y"], "recommend": "B"}, {"text": "b?", "options": [], "recommend": None}])
|
|
326
|
+
self.assertEqual(questions({"question": "ctx", "questions": qs[:1]}), ("ctx\n\na?", ["x", "y"], "B", []))
|
|
327
|
+
with self.assertRaises(ValueError):
|
|
328
|
+
questions({"question": "", "questions": [{"question": "a?", "options": ["x"], "recommend": "C"}, {"question": "b?"}]})
|
|
329
|
+
with self.assertRaises(ValueError):
|
|
330
|
+
questions({"question": "ctx", "options": ["x"], "questions": qs})
|