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/needs.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""What waits on the human: each worker asking a permission, asking a question, or whose turn ended on words that wait
|
|
2
|
+
for a reply; each with a key that a new ask or reply changes, so an app notifies each once. A question's options are
|
|
3
|
+
read as a page shows them: lettered, the recommended one marked."""
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Callable
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def options(q: dict) -> tuple[list[tuple[str, str]], str | None]:
|
|
10
|
+
"""A question's lettered options and the one recommended, read as the page reads them (`questionParts` in
|
|
11
|
+
ui/core/text.ts): given by `ask --option`, else "(A) … (B) …" in its text, else one per line."""
|
|
12
|
+
if q.get("parts"):
|
|
13
|
+
return [], None
|
|
14
|
+
if q.get("options"):
|
|
15
|
+
return [(chr(65 + i), re.sub(rf"^\(?{chr(65 + i)}[).:]\s*", "", t)) for i, t in enumerate(q["options"])], q.get("recommend")
|
|
16
|
+
text = q.get("text", "")
|
|
17
|
+
|
|
18
|
+
def run(rx: str) -> list[re.Match]:
|
|
19
|
+
seq: list[re.Match] = []
|
|
20
|
+
for m in re.finditer(rx, text, re.I):
|
|
21
|
+
if ord(m.group(1).upper()) - 65 == len(seq):
|
|
22
|
+
seq.append(m)
|
|
23
|
+
return seq
|
|
24
|
+
seq = run(r"(?:^|\s)\(([A-H])\)\s")
|
|
25
|
+
if len(seq) < 2:
|
|
26
|
+
seq = run(r"(?:^|\n)[ \t]*([A-H])(?:[ \t]*\((?:recommended|rec\.?)\))?[ \t]*[:).][ \t]")
|
|
27
|
+
if len(seq) < 2:
|
|
28
|
+
return [], None
|
|
29
|
+
opts = [[m.group(1).upper(), text[m.end():seq[i + 1].start() if i + 1 < len(seq) else None].strip()] for i, m in enumerate(seq)]
|
|
30
|
+
cut = re.search(r"\s(?:I(?:'d)? recommend|Recommend(?:ation)?:?)\s", opts[-1][1], re.I)
|
|
31
|
+
tail = opts[-1][1][cut.start():] if cut else ""
|
|
32
|
+
if cut:
|
|
33
|
+
opts[-1][1] = opts[-1][1][:cut.start()].strip()
|
|
34
|
+
marked = next((m.group(1).upper() for m in seq if re.search(r"recommended|rec\b", m.group(0), re.I)), None)
|
|
35
|
+
said = re.search(r"recommend(?:ation)?:?\s+\(?([A-H])\)?(?![a-z])", tail, re.I)
|
|
36
|
+
return [(k, t) for k, t in opts], marked or (said.group(1).upper() if said else q.get("recommend"))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def plain(text: str) -> str:
|
|
40
|
+
"""Markdown's marks off, for a notification's plain text."""
|
|
41
|
+
return re.sub(r"\*\*|__|`|^#+\s*", "", text, flags=re.M)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def needs(workers: list[dict], last_words: Callable[[str], str]) -> list[dict]:
|
|
45
|
+
"""From the pool's members as `pool.workers` gives them: one need per worker waiting on the human, its kind
|
|
46
|
+
(permit, ask or turn), its key, the member, and for a permission or a question its text and options."""
|
|
47
|
+
out = []
|
|
48
|
+
for w in workers:
|
|
49
|
+
n, live = w["name"], w.get("live") or {}
|
|
50
|
+
if w["status"] == "approve":
|
|
51
|
+
perm = live.get("permission") or {}
|
|
52
|
+
out.append({"kind": "permit", "key": f"{n}|permit|{live.get('since', '')}", "worker": w, "text": perm.get("tool") or "",
|
|
53
|
+
"options": [(o["id"], o.get("name") or o["id"]) for o in perm.get("options") or []], "recommend": None})
|
|
54
|
+
elif w["status"] == "asking":
|
|
55
|
+
q = w["question"]
|
|
56
|
+
opts, rec = options(q)
|
|
57
|
+
out.append({"kind": "ask", "key": f"{n}|ask|{q.get('at', '')}", "worker": w, "text": q["text"], "options": opts, "recommend": rec})
|
|
58
|
+
elif w["status"] == "replied":
|
|
59
|
+
out.append({"kind": "turn", "key": f"{n}|turn|{(live.get('turn') or {}).get('began', '')}", "worker": w,
|
|
60
|
+
"text": last_words(n), "options": [], "recommend": None})
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def fresh(now: list[dict], seen: set[str]) -> list[dict]:
|
|
65
|
+
"""The needs not seen before, by key: what to notify."""
|
|
66
|
+
return [x for x in now if x["key"] not in seen]
|
acppool/pool.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
"""The worker pool: the app's record of each agent it started, its job, its queue, its question and the messages
|
|
2
|
+
not delivered yet. The agent itself runs under the supervisor (`acppool.supervisor`), which says whether it is idle,
|
|
3
|
+
busy or asking a permission; `acppool.push` sends it what comes next. A job is the app's: a kind and a name, and any
|
|
4
|
+
other field the app gives it, carried as given.
|
|
5
|
+
|
|
6
|
+
The pool lives in a `Store`: anything that reads it whole and changes it in one transaction. `SqliteStore` keeps it in
|
|
7
|
+
a file of its own, `JsonStore` in a JSON file, `MemoryStore` in the process; an app with a database of its own writes one over it."""
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import copy
|
|
11
|
+
import datetime
|
|
12
|
+
import fcntl
|
|
13
|
+
import json
|
|
14
|
+
import random
|
|
15
|
+
import sqlite3
|
|
16
|
+
import subprocess
|
|
17
|
+
import threading
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import ContextManager, Iterator, Protocol
|
|
20
|
+
|
|
21
|
+
from acppool.sessions import local
|
|
22
|
+
|
|
23
|
+
NAMES = ["ada", "basil", "cleo", "dax", "edda", "finn", "gus", "hana", "ivo", "juno", "kai", "lumi"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Store(Protocol):
|
|
27
|
+
def read(self) -> dict[str, dict]:
|
|
28
|
+
"""Every member, by name."""
|
|
29
|
+
|
|
30
|
+
def changing(self) -> ContextManager[dict[str, dict]]:
|
|
31
|
+
"""The pool as one dict to change, written back when the block ends, in the transaction that read it; nothing
|
|
32
|
+
written when it raises."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class MemoryStore:
|
|
36
|
+
def __init__(self):
|
|
37
|
+
self.pool: dict[str, dict] = {}
|
|
38
|
+
self.lock = threading.RLock()
|
|
39
|
+
|
|
40
|
+
def read(self) -> dict[str, dict]:
|
|
41
|
+
with self.lock:
|
|
42
|
+
return copy.deepcopy(self.pool)
|
|
43
|
+
|
|
44
|
+
@contextlib.contextmanager
|
|
45
|
+
def changing(self) -> Iterator[dict[str, dict]]:
|
|
46
|
+
with self.lock:
|
|
47
|
+
pool = copy.deepcopy(self.pool)
|
|
48
|
+
yield pool
|
|
49
|
+
self.pool = pool
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class SqliteStore:
|
|
53
|
+
"""A table, one row per member, in a SQLite file; each change one transaction, and only the rows it changed."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, path: Path, table: str = "pool"):
|
|
56
|
+
self.path, self.table = Path(path), table
|
|
57
|
+
self.ready, self.lock = False, threading.Lock()
|
|
58
|
+
|
|
59
|
+
def _prepare(self, conn) -> None:
|
|
60
|
+
"""WAL (kept by the file: readers then never wait on a writer) and the table, once, by one thread: a second
|
|
61
|
+
connection setting WAL meanwhile would find the file locked."""
|
|
62
|
+
with self.lock:
|
|
63
|
+
if not self.ready:
|
|
64
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
65
|
+
conn.execute(f"CREATE TABLE IF NOT EXISTS {self.table} (name TEXT PRIMARY KEY, data TEXT NOT NULL)")
|
|
66
|
+
self.ready = True
|
|
67
|
+
|
|
68
|
+
@contextlib.contextmanager
|
|
69
|
+
def _opened(self, write: bool):
|
|
70
|
+
conn = sqlite3.connect(self.path, timeout=30, isolation_level=None)
|
|
71
|
+
try:
|
|
72
|
+
self._prepare(conn)
|
|
73
|
+
conn.execute("BEGIN IMMEDIATE" if write else "BEGIN")
|
|
74
|
+
try:
|
|
75
|
+
yield conn
|
|
76
|
+
conn.execute("COMMIT")
|
|
77
|
+
except BaseException:
|
|
78
|
+
conn.execute("ROLLBACK")
|
|
79
|
+
raise
|
|
80
|
+
finally:
|
|
81
|
+
conn.close()
|
|
82
|
+
|
|
83
|
+
def _rows(self, conn) -> dict:
|
|
84
|
+
return {name: json.loads(data) for name, data in conn.execute(f"SELECT name, data FROM {self.table} ORDER BY name")}
|
|
85
|
+
|
|
86
|
+
def read(self) -> dict[str, dict]:
|
|
87
|
+
with self._opened(write=False) as conn:
|
|
88
|
+
return self._rows(conn)
|
|
89
|
+
|
|
90
|
+
@contextlib.contextmanager
|
|
91
|
+
def changing(self) -> Iterator[dict[str, dict]]:
|
|
92
|
+
with self._opened(write=True) as conn:
|
|
93
|
+
before = self._rows(conn)
|
|
94
|
+
pool = copy.deepcopy(before)
|
|
95
|
+
yield pool
|
|
96
|
+
conn.executemany(f"DELETE FROM {self.table} WHERE name = ?", [(n,) for n in before if n not in pool])
|
|
97
|
+
conn.executemany(f"INSERT OR REPLACE INTO {self.table} (name, data) VALUES (?, ?)",
|
|
98
|
+
[(n, json.dumps(w)) for n, w in pool.items() if before.get(n) != w])
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class JsonStore:
|
|
102
|
+
"""One JSON file, locked for each change (POSIX `flock`), so every process can open it; written whole, and only
|
|
103
|
+
when it changed."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, path: Path):
|
|
106
|
+
self.path = Path(path)
|
|
107
|
+
|
|
108
|
+
def read(self) -> dict[str, dict]:
|
|
109
|
+
try:
|
|
110
|
+
return json.loads(self.path.read_text())
|
|
111
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
112
|
+
return {}
|
|
113
|
+
|
|
114
|
+
@contextlib.contextmanager
|
|
115
|
+
def changing(self) -> Iterator[dict[str, dict]]:
|
|
116
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
117
|
+
with open(self.path.with_suffix(".lock"), "w") as lock:
|
|
118
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
119
|
+
before = self.read()
|
|
120
|
+
pool = copy.deepcopy(before)
|
|
121
|
+
yield pool
|
|
122
|
+
if pool != before:
|
|
123
|
+
tmp = self.path.with_suffix(".tmp")
|
|
124
|
+
tmp.write_text(json.dumps(pool, indent=1))
|
|
125
|
+
tmp.replace(self.path)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def now() -> str:
|
|
129
|
+
return datetime.datetime.now().isoformat(timespec="seconds")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def age(at: str) -> float:
|
|
133
|
+
return (datetime.datetime.now() - datetime.datetime.fromisoformat(at)).total_seconds()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def member(pool: dict, name: str) -> dict:
|
|
137
|
+
if name not in pool:
|
|
138
|
+
raise ValueError(f"{name or 'this agent'} is not in the pool")
|
|
139
|
+
return pool[name]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def join(store: Store, taken: set[str], cwd: str, agent: str = "claude", names: list[str] = NAMES) -> str:
|
|
143
|
+
"""A new member, under a name free in the pool and not in `taken`; the supervisor starts its agent."""
|
|
144
|
+
with store.changing() as pool:
|
|
145
|
+
free = [n for n in names if n not in pool and n not in taken]
|
|
146
|
+
name = random.choice(free) if free else f"{random.choice(names)}-{len(pool) + 2}"
|
|
147
|
+
pool[name] = {"name": name, "joined": now(), "cwd": cwd, "agent": agent, "job": None, "queue": [], "inbox": [],
|
|
148
|
+
"question": None}
|
|
149
|
+
return name
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def mark(store: Store, name: str, key: str, value) -> None:
|
|
153
|
+
with store.changing() as pool:
|
|
154
|
+
member(pool, name)[key] = value
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def leave(store: Store, name: str) -> None:
|
|
158
|
+
with store.changing() as pool:
|
|
159
|
+
member(pool, name)
|
|
160
|
+
del pool[name]
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def hold(store: Store, name: str, on: bool) -> None:
|
|
164
|
+
"""A held worker is pushed no work until released."""
|
|
165
|
+
with store.changing() as pool:
|
|
166
|
+
member(pool, name)["held"] = on
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def holders(store: Store, covers) -> list[str]:
|
|
170
|
+
"""The workers whose job covers something, as covers(job) says: the app knows what a job holds."""
|
|
171
|
+
return [w["name"] for w in store.read().values() if w["job"] and covers(w["job"])]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def ask(store: Store, name: str, text: str, options: list[str] | None = None, recommend: str | None = None,
|
|
175
|
+
parts: list[dict] | None = None) -> None:
|
|
176
|
+
"""A question for the human, or several answered together (`parts`); the agent ends its turn, and
|
|
177
|
+
the answer is its next prompt."""
|
|
178
|
+
with store.changing() as pool:
|
|
179
|
+
w = member(pool, name)
|
|
180
|
+
w["question"] = {"text": text, "at": now(), "answer": None, "options": options or [], "recommend": recommend,
|
|
181
|
+
**({"parts": parts} if parts else {})}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def born(pid: int) -> str:
|
|
185
|
+
"""When the process with this pid started, "" when none runs: with it, a pid used again later is not taken for the run."""
|
|
186
|
+
try:
|
|
187
|
+
return subprocess.run(["ps", "-o", "lstart=", "-p", str(pid)], capture_output=True, text=True, timeout=10).stdout.strip()
|
|
188
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
189
|
+
return ""
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def wait(store: Store, name: str, pid: int, what: str, output: str = "") -> None:
|
|
193
|
+
"""The agent ends its turn on a run in the background; the push wakes it when the process ends."""
|
|
194
|
+
started = born(pid)
|
|
195
|
+
if not started:
|
|
196
|
+
raise ValueError(f"no process {pid} runs: start the run, then call wait with its pid")
|
|
197
|
+
with store.changing() as pool:
|
|
198
|
+
member(pool, name)["waiting"] = {"pid": pid, "born": started, "what": what, "output": output, "at": now()}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def run_over(w: dict) -> bool:
|
|
202
|
+
r = w.get("waiting")
|
|
203
|
+
return bool(r) and born(r["pid"]) != r["born"]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def answer(store: Store, name: str, text: str) -> None:
|
|
207
|
+
with store.changing() as pool:
|
|
208
|
+
w = member(pool, name)
|
|
209
|
+
if not w["question"] or w["question"]["answer"] is not None:
|
|
210
|
+
raise ValueError(f"{name} has no question waiting")
|
|
211
|
+
w["question"]["answer"] = text
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def assign(store: Store, name: str, kind: str, target: str, brief: str, **extra) -> None:
|
|
215
|
+
"""The member's job, with the brief it is sent; extra fields the app's, those empty left out."""
|
|
216
|
+
with store.changing() as pool:
|
|
217
|
+
w = member(pool, name)
|
|
218
|
+
if w.get("held"):
|
|
219
|
+
raise ValueError(f"{name} is held; release it first")
|
|
220
|
+
if w["job"]:
|
|
221
|
+
raise ValueError(f"{name} already holds {w['job']['name']}")
|
|
222
|
+
w["job"] = {"kind": kind, "name": target, "brief": brief, "at": now(), **{k: v for k, v in extra.items() if v}}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def free(w: dict, a: dict | None = None) -> bool:
|
|
226
|
+
"""Free for work given now, rather than queued behind its current job: a member as `workers` gives it, or with its
|
|
227
|
+
agent's record."""
|
|
228
|
+
return not w["job"] and not w.get("held") and (w["status"] if "status" in w else status(w, a or {})) == "idle"
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def queue(store: Store, name: str, kind: str, target: str, first: bool = False, at: int | None = None, **extra) -> int:
|
|
232
|
+
"""Work for after the member's current job; with first, ahead of the rest, or at a given place. Returns its
|
|
233
|
+
place, from 1. Extra fields the app's, those empty left out. Whether the item keeps the session is its run's
|
|
234
|
+
say (`push.App.run_of`), not the queue's."""
|
|
235
|
+
with store.changing() as pool:
|
|
236
|
+
w = member(pool, name)
|
|
237
|
+
q = w.setdefault("queue", [])
|
|
238
|
+
if any(x["kind"] == kind and x["name"] == target for x in q) or (w["job"] and w["job"]["name"] == target):
|
|
239
|
+
raise ValueError(f"{name} already has {target}")
|
|
240
|
+
item = {"kind": kind, "name": target, "at": now(), **{k: v for k, v in extra.items() if v}}
|
|
241
|
+
if first:
|
|
242
|
+
at = 0
|
|
243
|
+
if at is not None:
|
|
244
|
+
q.insert(at, item)
|
|
245
|
+
return at + 1
|
|
246
|
+
q.append(item)
|
|
247
|
+
return len(q)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def unqueue(store: Store, name: str, target: str) -> None:
|
|
251
|
+
with store.changing() as pool:
|
|
252
|
+
w = member(pool, name)
|
|
253
|
+
w["queue"] = [x for x in w.get("queue", []) if x["name"] != target]
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def reorder(store: Store, name: str, target: str, before: str | None) -> None:
|
|
257
|
+
"""Move a queued item to just before another, or to the end with none."""
|
|
258
|
+
with store.changing() as pool:
|
|
259
|
+
w = member(pool, name)
|
|
260
|
+
q = w.get("queue", [])
|
|
261
|
+
item = next((x for x in q if x["name"] == target), None)
|
|
262
|
+
if item is None:
|
|
263
|
+
raise ValueError(f"{name} has no {target} queued")
|
|
264
|
+
rest = [x for x in q if x is not item]
|
|
265
|
+
at = next((k for k, x in enumerate(rest) if x["name"] == before), None) if before else len(rest)
|
|
266
|
+
if at is None:
|
|
267
|
+
raise ValueError(f"{name} has no {before} queued")
|
|
268
|
+
w["queue"] = rest[:at] + [item] + rest[at:]
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def cut(store: Store, name: str, target: str) -> list[dict]:
|
|
272
|
+
"""Take an item out of the member's queue with everything after it. Returns what was removed."""
|
|
273
|
+
with store.changing() as pool:
|
|
274
|
+
w = member(pool, name)
|
|
275
|
+
q = w.get("queue", [])
|
|
276
|
+
i = next((k for k, x in enumerate(q) if x["name"] == target), None)
|
|
277
|
+
if i is None:
|
|
278
|
+
raise ValueError(f"{name} has no {target} queued")
|
|
279
|
+
w["queue"], gone = q[:i], q[i:]
|
|
280
|
+
return gone
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def drop_job(store: Store, name: str) -> None:
|
|
284
|
+
"""A job given and not sent yet goes back, to be given elsewhere."""
|
|
285
|
+
with store.changing() as pool:
|
|
286
|
+
w = member(pool, name)
|
|
287
|
+
if w["job"] and not w["job"].get("taken"):
|
|
288
|
+
w["job"] = None
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def finish(store: Store, name: str) -> dict | None:
|
|
292
|
+
"""The job it was sent is over. Returns it. Its run, set when it was sent, stays: the session's."""
|
|
293
|
+
with store.changing() as pool:
|
|
294
|
+
w = member(pool, name)
|
|
295
|
+
job = w["job"] if w["job"] and w["job"].get("taken") else None
|
|
296
|
+
if job:
|
|
297
|
+
w["job"] = None
|
|
298
|
+
return job
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def pick(store: Store, name: str, judge) -> tuple[dict | None, list[dict]]:
|
|
302
|
+
"""The first queued item judge says to take, when the member holds no job.
|
|
303
|
+
judge(item) is "take", "keep" (not yet: its needs are open) or "drop" (closed
|
|
304
|
+
or taken meanwhile). Returns the item, and the items dropped."""
|
|
305
|
+
with store.changing() as pool:
|
|
306
|
+
w = member(pool, name)
|
|
307
|
+
if w["job"]:
|
|
308
|
+
return None, []
|
|
309
|
+
kept, dropped, chosen = [], [], None
|
|
310
|
+
for item in w.get("queue", []):
|
|
311
|
+
verdict = "keep" if chosen else judge(item)
|
|
312
|
+
if verdict == "take":
|
|
313
|
+
chosen = item
|
|
314
|
+
elif verdict == "drop":
|
|
315
|
+
dropped.append(item)
|
|
316
|
+
else:
|
|
317
|
+
kept.append(item)
|
|
318
|
+
w["queue"] = kept
|
|
319
|
+
return chosen, dropped
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def message(store: Store, name: str, text: str) -> None:
|
|
323
|
+
"""A message kept until it can be delivered (`push.deliver` sends it at once when it can)."""
|
|
324
|
+
with store.changing() as pool:
|
|
325
|
+
member(pool, name)["inbox"].append({"text": text, "at": now()})
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def replied(w: dict, a: dict) -> bool:
|
|
329
|
+
"""Its turn on a job it holds ended on its own words, with no question, report or run of its own: it waits for the
|
|
330
|
+
human's reply. A turn that answered the human while a run goes on counts; the one that started the run does not."""
|
|
331
|
+
t = a.get("turn") or {}
|
|
332
|
+
if not (w["job"] and w["job"].get("taken")) or t.get("stop") != "end_turn" or not t.get("began"):
|
|
333
|
+
return False
|
|
334
|
+
return not w.get("waiting") or local(t["began"]) > w["waiting"]["at"]
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def status(w: dict, a: dict | None) -> str:
|
|
338
|
+
"""What the worker is doing, from the pool's record and its agent's record in the supervisor (None: it has none)."""
|
|
339
|
+
if not a:
|
|
340
|
+
return "gone"
|
|
341
|
+
state = a.get("state")
|
|
342
|
+
if state == "failed":
|
|
343
|
+
return "failed"
|
|
344
|
+
if state in ("starting", "crashed"):
|
|
345
|
+
return "starting"
|
|
346
|
+
if a.get("permission"):
|
|
347
|
+
return "approve"
|
|
348
|
+
if w["question"]:
|
|
349
|
+
return "asking" if w["question"]["answer"] is None else "answered"
|
|
350
|
+
if state == "busy":
|
|
351
|
+
return "working" if w["job"] else "reading"
|
|
352
|
+
if replied(w, a):
|
|
353
|
+
return "replied"
|
|
354
|
+
if w.get("waiting"): # before the hold: a hold keeps new jobs away, and a run is no job; the wake still comes
|
|
355
|
+
return "running"
|
|
356
|
+
if w.get("held"):
|
|
357
|
+
return "held"
|
|
358
|
+
if w["job"]:
|
|
359
|
+
return "stopped" if w["job"].get("taken") else "cleared" if w["job"].get("await") else "assigned"
|
|
360
|
+
return "idle"
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def workers(store: Store, known: dict[str, dict]) -> list[dict]:
|
|
364
|
+
"""Each member with its agent's record (`agent` stays its kind) and its status, from the supervisor's agents."""
|
|
365
|
+
return sorted(({**w, "live": known.get(w["name"]), "status": status(w, known.get(w["name"]) or {})}
|
|
366
|
+
for w in store.read().values()), key=lambda w: w["joined"])
|