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/push.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Pushing work to the pool's agents: `advance` sends an idle agent what comes next, `deliver` a message at once.
|
|
2
|
+
|
|
3
|
+
What a job is, and when it ends, is the app's: it says so through an `App`, whose every default is the simplest (a job
|
|
4
|
+
is one turn, each its own run, its brief its name). The pool's job fields this module reads and writes: `brief`,
|
|
5
|
+
`taken` (when it was sent), `await` (held through a clear for the human's next message) and `before` (what the app
|
|
6
|
+
snapshot of its tree before the first attempt). A worker's `run` is the run its session holds."""
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Callable, Protocol
|
|
12
|
+
|
|
13
|
+
from acppool import pool
|
|
14
|
+
from acppool.pool import Store
|
|
15
|
+
|
|
16
|
+
SEP = "\n\n---\n\n" # between a job prompt's preamble, its brief and the human's words sent with it
|
|
17
|
+
RECOMPACT = 20 * 60 # seconds: after a compaction, the next waits at least this long
|
|
18
|
+
LOCK = threading.Lock() # one advance at a time, so two never send one agent two prompts
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Supervisor(Protocol):
|
|
22
|
+
def call(self, op: str, **args) -> dict: ...
|
|
23
|
+
|
|
24
|
+
def agents(self) -> dict[str, dict]: ...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class App:
|
|
28
|
+
"""What the app decides about its jobs. Subclass it, and override what differs."""
|
|
29
|
+
|
|
30
|
+
home = "the pool" # where the human's messages come from, and where a job goes back to, in the agents' and the log's words
|
|
31
|
+
|
|
32
|
+
def __init__(self, store: Store, supervisor: Supervisor):
|
|
33
|
+
self.store, self.supervisor = store, supervisor
|
|
34
|
+
|
|
35
|
+
def message(self, text: str) -> str:
|
|
36
|
+
"""A message from the human, as the agent reads it."""
|
|
37
|
+
return f"Message from {self.home}: {text}"
|
|
38
|
+
|
|
39
|
+
def judge(self, item: dict) -> str:
|
|
40
|
+
"""A queued item, at its turn: "take" it, "keep" it for later, or "drop" it."""
|
|
41
|
+
return "take"
|
|
42
|
+
|
|
43
|
+
def brief(self, item: dict, worker: str) -> str:
|
|
44
|
+
"""The prompt a job is sent with, written when it is taken from the queue."""
|
|
45
|
+
return item["name"]
|
|
46
|
+
|
|
47
|
+
def job_over(self, job: dict, worker: str) -> bool:
|
|
48
|
+
"""Whether a job it was sent is over, once its turn ended."""
|
|
49
|
+
return True
|
|
50
|
+
|
|
51
|
+
def run_of(self, job: dict) -> str:
|
|
52
|
+
"""The run a job belongs to: jobs of one run share a session, a job of another begins a fresh one."""
|
|
53
|
+
return job["name"]
|
|
54
|
+
|
|
55
|
+
def resumable(self, job: dict, worker: str) -> dict | None:
|
|
56
|
+
"""An earlier session to take the job up in, as `acppool.sessions.resumable` finds one; none by default."""
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
def resumed(self, job: dict) -> str:
|
|
60
|
+
"""What a brief begins with in a session taken up again."""
|
|
61
|
+
return ""
|
|
62
|
+
|
|
63
|
+
def preamble(self, worker: str) -> str:
|
|
64
|
+
"""What each job's prompt begins with, before its brief: the app's standing instructions."""
|
|
65
|
+
return ""
|
|
66
|
+
|
|
67
|
+
def snapshot(self, w: dict) -> dict | None:
|
|
68
|
+
"""The worker's tree before a job's first attempt, kept with the job, so a reset can undo only the attempt's."""
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
def marks(self, worker: str, preamble: str) -> dict:
|
|
72
|
+
"""Fields to set on the worker once a job is sent."""
|
|
73
|
+
return {}
|
|
74
|
+
|
|
75
|
+
def compact_at(self) -> int:
|
|
76
|
+
"""The share of its context, in percent, past which a worker is compacted between jobs; 0 never."""
|
|
77
|
+
return 0
|
|
78
|
+
|
|
79
|
+
def cleared(self, job: dict) -> str:
|
|
80
|
+
"""What a job's brief begins with when the worker's context was cleared while it held the job."""
|
|
81
|
+
return "Your context was cleared while you held this job. Check where it stands, then carry on.\n\n"
|
|
82
|
+
|
|
83
|
+
def interrupted(self, job: dict, worker: str) -> str:
|
|
84
|
+
"""What a worker is sent when the turn it ran on its job was cut off (a crash, a restart, a session that could not
|
|
85
|
+
be resumed); "" leaves it stopped, for the human to carry it on."""
|
|
86
|
+
return ""
|
|
87
|
+
|
|
88
|
+
def undo(self, worker: str, w: dict) -> tuple[str, str]:
|
|
89
|
+
"""A reset's undoing of the attempt at the worker's job (its files, its item's state); what was undone, as the
|
|
90
|
+
record says it and as the reply does, each "; "- or ", "-led. Nothing by default."""
|
|
91
|
+
return "", ""
|
|
92
|
+
|
|
93
|
+
def give_back(self, worker: str, job: dict) -> None:
|
|
94
|
+
"""A job taken back from the worker: what that means for its item (open again, held by nobody)."""
|
|
95
|
+
|
|
96
|
+
def ending(self, job: dict | None, worker: str) -> str:
|
|
97
|
+
"""What ending the worker's job ends, in words; a ValueError where the human cannot end it."""
|
|
98
|
+
if not job:
|
|
99
|
+
raise ValueError(f"{worker} holds no job")
|
|
100
|
+
return job["name"]
|
|
101
|
+
|
|
102
|
+
def record(self, action: str, worker: str, text: str, item: dict | None = None) -> None:
|
|
103
|
+
"""What was done: by the push (skip, assign from the queue, woken, compact, resume, clear) or the human's
|
|
104
|
+
controls (assign, queue, message, answer, clear, withdraw, reset, end, hold, takeback, permit, ...)."""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def context(a: dict) -> dict:
|
|
108
|
+
"""How full an agent's context is, as it last reported."""
|
|
109
|
+
u = a.get("usage") or {}
|
|
110
|
+
if not u.get("size") or u.get("used") is None:
|
|
111
|
+
return {}
|
|
112
|
+
return {"used": u["used"], "window": u["size"], "pct": round(100 * u["used"] / u["size"])}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def send(app: App, name: str, text: str, job: dict | None = None) -> bool:
|
|
116
|
+
"""A prompt to an idle agent, naming the job it carries; False when it cannot take one now (busy, starting, or
|
|
117
|
+
no supervisor)."""
|
|
118
|
+
try:
|
|
119
|
+
app.supervisor.call("prompt", name=name, text=text, **({"job": job} if job else {}))
|
|
120
|
+
return True
|
|
121
|
+
except RuntimeError:
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def deliver(app: App, name: str, text: str) -> None:
|
|
126
|
+
"""A message from the app: into the turn it runs, or, idle, as its next prompt; kept while it cannot be reached."""
|
|
127
|
+
a = app.supervisor.agents().get(name) or {}
|
|
128
|
+
if a.get("state") in ("busy", "asking"):
|
|
129
|
+
try:
|
|
130
|
+
app.supervisor.call("steer", name=name, text=app.message(text))
|
|
131
|
+
return
|
|
132
|
+
except RuntimeError:
|
|
133
|
+
pass
|
|
134
|
+
pool.message(app.store, name, text)
|
|
135
|
+
advance(app, name)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def tail(path: str, cwd: str, lines: int = 30) -> str:
|
|
139
|
+
"""The last lines of a run's output file, a path given relative to the agent's folder or with ~."""
|
|
140
|
+
if not path:
|
|
141
|
+
return ""
|
|
142
|
+
f = Path(cwd, Path(path).expanduser())
|
|
143
|
+
try:
|
|
144
|
+
with f.open("rb") as h:
|
|
145
|
+
h.seek(max(0, f.stat().st_size - 6000))
|
|
146
|
+
text = h.read().decode(errors="replace")
|
|
147
|
+
except OSError:
|
|
148
|
+
return f"(its output, {path}, cannot be read)"
|
|
149
|
+
return "\n".join(text.splitlines()[-lines:]).strip() or f"({path} is empty)"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def woken(w: dict) -> str:
|
|
153
|
+
r = w["waiting"]
|
|
154
|
+
out = tail(r.get("output", ""), w.get("cwd", ""))
|
|
155
|
+
return (f"Your run ended: {r['what']} (process {r['pid']}, started {r['at'][11:16]})."
|
|
156
|
+
+ (f" The end of {r['output']}:\n```\n{out}\n```" if r.get("output") else "")
|
|
157
|
+
+ "\nCheck its result and carry on with your job.")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def compact_due(app: App, w: dict) -> bool:
|
|
161
|
+
"""Whether to compact the worker before its next job: asked for, or past the share set."""
|
|
162
|
+
if w.get("compactDue"):
|
|
163
|
+
return True
|
|
164
|
+
auto, last = app.compact_at(), w.get("compactedAt")
|
|
165
|
+
pct = context(app.supervisor.agents().get(w["name"]) or {}).get("pct", 0)
|
|
166
|
+
recent = last and pool.age(last) < RECOMPACT
|
|
167
|
+
return bool(auto) and pct >= auto and not recent
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def next_from_queue(app: App, me: str) -> None:
|
|
171
|
+
"""A member back for more takes the first queued item the app takes now, its brief written now; one it keeps
|
|
172
|
+
waits its turn in the queue, one it drops leaves it."""
|
|
173
|
+
item, dropped = pool.pick(app.store, me, app.judge)
|
|
174
|
+
for x in dropped:
|
|
175
|
+
app.record("skip", me, "closed or taken before its turn", x)
|
|
176
|
+
if item:
|
|
177
|
+
extra = {k: v for k, v in item.items() if k not in ("kind", "name", "at")}
|
|
178
|
+
pool.assign(app.store, me, item["kind"], item["name"], app.brief(item, me), **extra)
|
|
179
|
+
app.record("assign", me, "from its queue", item)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def advance(app: App, name: str) -> str:
|
|
183
|
+
"""Send an idle agent what comes next, in this order: the answer to its question, the messages kept for it, the
|
|
184
|
+
end of a run it waits on, a turn cut off carried on (`App.interrupted`), a compaction that is due, and its next job. A job of another run begins a fresh session,
|
|
185
|
+
or takes up an earlier one the app finds for it. A job not over when its turn ended stays: the human decides.
|
|
186
|
+
Returns what it sent, "" for nothing."""
|
|
187
|
+
with LOCK:
|
|
188
|
+
w, a = app.store.read().get(name), app.supervisor.agents().get(name)
|
|
189
|
+
if not w or not a or a.get("state") != "idle" or a.get("permission"):
|
|
190
|
+
return ""
|
|
191
|
+
q = w["question"]
|
|
192
|
+
if q and q["answer"] is None:
|
|
193
|
+
return ""
|
|
194
|
+
if q:
|
|
195
|
+
if q.get("parts"):
|
|
196
|
+
on = f' on "{q["text"]}"' if q["text"] else ""
|
|
197
|
+
said = f"Your questions{on}, answered in their order:\n{q['answer']}"
|
|
198
|
+
else:
|
|
199
|
+
said = f'The answer to your question "{q["text"]}": {q["answer"]}'
|
|
200
|
+
if send(app, name, said):
|
|
201
|
+
pool.mark(app.store, name, "question", None)
|
|
202
|
+
return "answer"
|
|
203
|
+
return ""
|
|
204
|
+
if w["inbox"]:
|
|
205
|
+
said = "\n\n".join(app.message(m["text"]) for m in w["inbox"])
|
|
206
|
+
if w["job"] and w["job"].get("await") and not w.get("held"): # after a clear: the job goes with what you said
|
|
207
|
+
return send_job(app, name, w, w["job"], said)
|
|
208
|
+
if send(app, name, said):
|
|
209
|
+
pool.mark(app.store, name, "inbox", [])
|
|
210
|
+
return "messages"
|
|
211
|
+
return ""
|
|
212
|
+
if w.get("waiting"): # a run in the background: nothing else until its process ends
|
|
213
|
+
if not pool.run_over(w):
|
|
214
|
+
return ""
|
|
215
|
+
if send(app, name, woken(w)):
|
|
216
|
+
pool.mark(app.store, name, "waiting", None)
|
|
217
|
+
app.record("woken", name, f"its run ended: {w['waiting']['what']}")
|
|
218
|
+
return "woken"
|
|
219
|
+
return ""
|
|
220
|
+
job = w["job"]
|
|
221
|
+
if job and job.get("taken") and (a.get("turn") or {}).get("stop") == "interrupted": # never a job's end
|
|
222
|
+
if (text := app.interrupted(job, name)) and send(app, name, text, {"kind": job["kind"], "name": job["name"],
|
|
223
|
+
"run": w.get("run") or app.run_of(job)}):
|
|
224
|
+
app.record("resume", name, "its turn was cut off; carried on", job)
|
|
225
|
+
return "resume"
|
|
226
|
+
return ""
|
|
227
|
+
if not job and not w.get("queue") and not compact_due(app, w):
|
|
228
|
+
return ""
|
|
229
|
+
if job and job.get("taken"):
|
|
230
|
+
if not app.job_over(job, name):
|
|
231
|
+
return ""
|
|
232
|
+
pool.finish(app.store, name)
|
|
233
|
+
w = app.store.read()[name]
|
|
234
|
+
if w.get("held"):
|
|
235
|
+
return ""
|
|
236
|
+
if not w["job"] and compact_due(app, w):
|
|
237
|
+
if send(app, name, "/compact"):
|
|
238
|
+
pool.mark(app.store, name, "compactDue", False)
|
|
239
|
+
pool.mark(app.store, name, "compactedAt", pool.now())
|
|
240
|
+
ctx = context(a)
|
|
241
|
+
app.record("compact", name, "between jobs" + (f", at {ctx['pct']}% of its context" if ctx else ""))
|
|
242
|
+
return "compact"
|
|
243
|
+
return ""
|
|
244
|
+
if not w["job"]:
|
|
245
|
+
next_from_queue(app, name)
|
|
246
|
+
w = app.store.read()[name]
|
|
247
|
+
job = w["job"]
|
|
248
|
+
if not job or job.get("await"): # one held through a clear waits for the human's next message
|
|
249
|
+
return ""
|
|
250
|
+
return send_job(app, name, w, job)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def run(app: Callable[[], App], every: float = 2.0, stop: threading.Event | None = None,
|
|
254
|
+
on_error: Callable[[Exception], None] | None = None) -> None:
|
|
255
|
+
"""The push, until stop is set: every few seconds each member is advanced, with an app made fresh for it (so what
|
|
256
|
+
the app reads is never stale). An error is reported and the push goes on; it runs in a thread of its own:
|
|
257
|
+
|
|
258
|
+
threading.Thread(target=push.run, args=(lambda: MyApp(store, supervisor),), daemon=True).start()
|
|
259
|
+
"""
|
|
260
|
+
stop = stop or threading.Event()
|
|
261
|
+
while not stop.wait(every):
|
|
262
|
+
try:
|
|
263
|
+
for name in app().store.read():
|
|
264
|
+
advance(app(), name)
|
|
265
|
+
except Exception as e: # noqa: BLE001 - one bad read must not stop the push
|
|
266
|
+
(on_error or (lambda e: print(f"advance: {e}", file=sys.stderr)))(e)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def send_job(app: App, name: str, w: dict, job: dict, said: str = "") -> str:
|
|
270
|
+
"""The job's brief to the agent, after a fresh session or an earlier one the app finds, where its run changes; with
|
|
271
|
+
said, the human's messages after it, in the same prompt. Returns "job", or "" when it could not be sent."""
|
|
272
|
+
run, brief = app.run_of(job), job["brief"]
|
|
273
|
+
if w.get("run") != run:
|
|
274
|
+
again = app.resumable(job, name)
|
|
275
|
+
try:
|
|
276
|
+
if again:
|
|
277
|
+
app.supervisor.call("resume", name=name, session=again["session"], run=run)
|
|
278
|
+
app.record("resume", name, f"the session {job['name']} was worked in, {again['at'][:16].replace('T', ' ')}")
|
|
279
|
+
brief = app.resumed(job) + brief
|
|
280
|
+
except RuntimeError:
|
|
281
|
+
again = None
|
|
282
|
+
try:
|
|
283
|
+
if not again and w.get("run"):
|
|
284
|
+
app.supervisor.call("reset", name=name, why="run", run=run)
|
|
285
|
+
app.record("clear", name, f"a fresh session for {run}")
|
|
286
|
+
except RuntimeError:
|
|
287
|
+
return ""
|
|
288
|
+
head = app.preamble(name)
|
|
289
|
+
before = app.snapshot(w) if "before" not in job else None
|
|
290
|
+
if not send(app, name, (head + SEP if head else "") + brief + (SEP + said if said else ""),
|
|
291
|
+
{"kind": job["kind"], "name": job["name"], "run": run, **({"mode": job["mode"]} if job.get("mode") else {})}):
|
|
292
|
+
return ""
|
|
293
|
+
with app.store.changing() as p:
|
|
294
|
+
if name in p and p[name]["job"]:
|
|
295
|
+
p[name]["job"]["taken"], p[name]["run"] = pool.now(), run
|
|
296
|
+
p[name].update(app.marks(name, head))
|
|
297
|
+
p[name]["job"].pop("await", None)
|
|
298
|
+
if before is not None:
|
|
299
|
+
p[name]["job"].setdefault("before", before)
|
|
300
|
+
if said:
|
|
301
|
+
p[name]["inbox"] = []
|
|
302
|
+
return "job"
|
acppool/sessions.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""The supervisor's event logs cut into sessions, and a session folded into its turns. A session begins at its
|
|
2
|
+
`session` line, which says why (start, clear, run, lost, resume) and the folder and agent it can be resumed in; a job's
|
|
3
|
+
prompt names the job, which is the app's: its name and anything else, as the app sent it. Each log is indexed once,
|
|
4
|
+
then only what was appended (the index beside it, in `.index/`), so an app reads one session without its log's whole
|
|
5
|
+
history. `turns_since` reads each turn's usage the same way, for an app to keep."""
|
|
6
|
+
|
|
7
|
+
import datetime
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import threading
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
ISO = "%Y-%m-%dT%H:%M:%S"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def local(at: str) -> str:
|
|
17
|
+
"""The supervisor's stamp as local time, to the second, without the offset."""
|
|
18
|
+
return datetime.datetime.fromisoformat(at).astimezone().replace(tzinfo=None).isoformat(timespec="seconds")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _mark(logs: Path, name: str) -> dict:
|
|
22
|
+
try:
|
|
23
|
+
return json.loads((logs / ".index" / f"{name}.json").read_text())
|
|
24
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
25
|
+
return {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _keep(logs: Path, name: str, mark: dict) -> None:
|
|
29
|
+
d = logs / ".index"
|
|
30
|
+
d.mkdir(exist_ok=True)
|
|
31
|
+
tmp = d / f"{name}.{os.getpid()}.{threading.get_ident()}.tmp"
|
|
32
|
+
tmp.write_text(json.dumps(mark))
|
|
33
|
+
tmp.replace(d / f"{name}.json")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def sessions(logs: Path, name: str) -> list[dict]:
|
|
37
|
+
"""The worker's sessions, oldest first: each its id, why and when it began, its folder and agent, its byte span in
|
|
38
|
+
the log (`end` None for the one still running) and the jobs prompted in it. A log from before sessions were cut
|
|
39
|
+
begins with one that says nothing of itself."""
|
|
40
|
+
f = logs / f"{name}.jsonl"
|
|
41
|
+
if not f.exists():
|
|
42
|
+
return []
|
|
43
|
+
st = f.stat()
|
|
44
|
+
mark = _mark(logs, name)
|
|
45
|
+
if mark.get("ino") != st.st_ino or st.st_size < mark["offset"]: # a log made again for a new agent of the same name
|
|
46
|
+
mark = {"offset": 0, "sessions": []}
|
|
47
|
+
size = st.st_size
|
|
48
|
+
if size == mark["offset"]:
|
|
49
|
+
return mark["sessions"]
|
|
50
|
+
with f.open("rb") as fh:
|
|
51
|
+
fh.seek(mark["offset"])
|
|
52
|
+
data = fh.read()
|
|
53
|
+
end = data.rfind(b"\n") + 1 # a line still being written waits for the next read
|
|
54
|
+
out, pos = mark["sessions"], mark["offset"]
|
|
55
|
+
for line in data[:end].split(b"\n")[:-1]:
|
|
56
|
+
at, pos = pos, pos + len(line) + 1
|
|
57
|
+
if not (b'"kind": "session"' in line or b'"kind": "resumed"' in line or (b'"kind": "prompt"' in line and b'"job": {' in line)):
|
|
58
|
+
if not out:
|
|
59
|
+
out.append({"session": "", "why": "", "at": "", "start": at, "end": None, "jobs": []})
|
|
60
|
+
continue
|
|
61
|
+
try:
|
|
62
|
+
e = json.loads(line)
|
|
63
|
+
except json.JSONDecodeError:
|
|
64
|
+
continue
|
|
65
|
+
if e["kind"] == "session":
|
|
66
|
+
if out:
|
|
67
|
+
out[-1]["end"] = at
|
|
68
|
+
out.append({"session": e.get("session") or "", "why": e.get("why") or ("lost" if e.get("lost") else "clear" if e.get("previous") else "start"),
|
|
69
|
+
"at": local(e["at"]), "cwd": e.get("cwd", ""), "agent": e.get("agent", ""), "start": at, "end": None, "jobs": []})
|
|
70
|
+
continue
|
|
71
|
+
if not out:
|
|
72
|
+
out.append({"session": "", "why": "", "at": local(e["at"]), "start": at, "end": None, "jobs": []})
|
|
73
|
+
if e["kind"] == "resumed" and not out[-1]["session"]:
|
|
74
|
+
out[-1]["session"] = e.get("session") or ""
|
|
75
|
+
elif e["kind"] == "prompt":
|
|
76
|
+
out[-1]["jobs"].append({**e["job"], "at": local(e["at"])})
|
|
77
|
+
_keep(logs, name, {"ino": st.st_ino, "offset": mark["offset"] + end, "sessions": out})
|
|
78
|
+
return out
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def read(logs: Path, name: str, s: dict) -> list[dict]:
|
|
82
|
+
"""The events of one session, from its log."""
|
|
83
|
+
f = logs / f"{name}.jsonl"
|
|
84
|
+
with f.open("rb") as fh:
|
|
85
|
+
fh.seek(s["start"])
|
|
86
|
+
data = fh.read(s["end"] - s["start"]) if s["end"] is not None else fh.read()
|
|
87
|
+
if s["end"] is None:
|
|
88
|
+
data = data[:data.rfind(b"\n") + 1]
|
|
89
|
+
out = []
|
|
90
|
+
for line in data.splitlines():
|
|
91
|
+
try:
|
|
92
|
+
out.append(json.loads(line))
|
|
93
|
+
except json.JSONDecodeError:
|
|
94
|
+
continue
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def all_sessions(logs: Path) -> list[dict]:
|
|
99
|
+
"""Every log's sessions, each with the worker whose log holds it, in the order they began."""
|
|
100
|
+
names = sorted(f.stem for f in logs.glob("*.jsonl")) if logs.exists() else []
|
|
101
|
+
return sorted(({**s, "worker": n} for n in names for s in sessions(logs, n)), key=lambda s: s["at"])
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def of_job(logs: Path, name: str) -> list[dict]:
|
|
105
|
+
"""The sessions a job, by its name, was prompted in, and those that took them up again later, oldest first."""
|
|
106
|
+
every = all_sessions(logs)
|
|
107
|
+
ids = {s["session"] for s in every if s["session"] and any(j.get("name") == name for j in s["jobs"])}
|
|
108
|
+
return [s for s in every if s["session"] in ids]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def resumable(logs: Path, job: str, worker: str, agents: dict[str, dict]) -> dict | None:
|
|
112
|
+
"""The job's latest session, when the worker can take it up again: the same folder and agent, and no agent's
|
|
113
|
+
session now (its own included, where taking it up changes nothing). Agents as the supervisor's status gives them."""
|
|
114
|
+
w = agents.get(worker) or {}
|
|
115
|
+
live = {a.get("session") for a in agents.values()}
|
|
116
|
+
worked = [s for s in of_job(logs, job) if any(j.get("name") == job for j in s["jobs"])]
|
|
117
|
+
s = worked[-1] if worked else None
|
|
118
|
+
if not s or s["session"] in live or s.get("cwd") != w.get("cwd") or s.get("agent") != w.get("agent"):
|
|
119
|
+
return None
|
|
120
|
+
return s
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def unwrapped(output: str) -> str:
|
|
124
|
+
"""An MCP result logged as JSON, before the supervisor kept its text alone: its text blocks."""
|
|
125
|
+
if not output.startswith('[{"type": "text"'):
|
|
126
|
+
return output
|
|
127
|
+
try:
|
|
128
|
+
return "\n".join(c.get("text", "") for c in json.loads(output))
|
|
129
|
+
except (json.JSONDecodeError, AttributeError):
|
|
130
|
+
return output
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _step(e: dict, at: str, calls: dict) -> dict | None:
|
|
134
|
+
"""One supervisor event as a step of its turn; a tool's end fills in the step its start made."""
|
|
135
|
+
k = e["kind"]
|
|
136
|
+
if k in ("message", "thought") and e.get("text", "").strip():
|
|
137
|
+
return {"kind": "say" if k == "message" else "thought", "text": e["text"].strip(), "at": at}
|
|
138
|
+
if k == "plan":
|
|
139
|
+
return {"kind": "plan", "text": "", "at": at, "entries": e.get("entries") or []}
|
|
140
|
+
if k == "tool":
|
|
141
|
+
calls[e["id"]] = {"kind": "tool", "at": at, "text": "", "name": e.get("name") or e.get("tool") or "tool",
|
|
142
|
+
"title": e.get("title") or "", "input": e.get("input"), "status": "running"}
|
|
143
|
+
return calls[e["id"]]
|
|
144
|
+
if k == "tool_done" and e.get("id") in calls:
|
|
145
|
+
calls[e["id"]].update(status=e.get("status"), output=unwrapped(e.get("output") or ""), diffs=e.get("diffs") or [],
|
|
146
|
+
title=e.get("title") or calls[e["id"]]["title"])
|
|
147
|
+
elif k == "permission":
|
|
148
|
+
return {"kind": "sys", "text": f"asks permission: {e.get('tool') or ''}".strip(": "), "at": at}
|
|
149
|
+
elif k in ("crashed", "failed", "interrupted", "resumed", "cancel"):
|
|
150
|
+
return {"kind": "sys", "text": k, "at": at}
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def fold(log: list[dict]) -> tuple[list[dict], list[dict]]:
|
|
155
|
+
"""A session's events as its turns (the brief a job's turn was sent, the steps it took, the words it ended on)
|
|
156
|
+
and what befell the agent between turns."""
|
|
157
|
+
turns, cur, calls, loose = [], None, {}, []
|
|
158
|
+
for e in log:
|
|
159
|
+
at = datetime.datetime.fromisoformat(e["at"]).astimezone().strftime(ISO)
|
|
160
|
+
if e["kind"] == "prompt":
|
|
161
|
+
_, _, brief = e.get("text", "").partition("\n\n---\n\n")
|
|
162
|
+
cur, calls = {"type": "turn", "at": at, "end": None, "stop": None, "brief": brief, "steps": [], "final": "", "after": []}, {}
|
|
163
|
+
turns.append(cur)
|
|
164
|
+
elif cur is not None:
|
|
165
|
+
step = _step(e, at[11:], calls) # a step shows its time of day; the turn keeps the date
|
|
166
|
+
if step and cur["end"] and step["kind"] == "sys": # a crash or a resume after the turn ended stands on its own
|
|
167
|
+
loose.append({"type": "sys", "at": at, "text": step["text"]})
|
|
168
|
+
elif step:
|
|
169
|
+
cur["steps"].append(step)
|
|
170
|
+
if e["kind"] == "turn":
|
|
171
|
+
cur["end"], cur["stop"] = at, e.get("stop")
|
|
172
|
+
if cur["steps"] and cur["steps"][-1]["kind"] == "say":
|
|
173
|
+
cur["final"] = cur["steps"].pop()["text"]
|
|
174
|
+
return turns, loose
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def tokens(e: dict) -> dict[str, list[int]]:
|
|
178
|
+
"""A turn's tokens by model, each [input, cache writes, cache reads, output]. Any ACP agent reports the turn's
|
|
179
|
+
`usage`; Claude's and Codex's adapters also split it by model, Claude's the models it runs in the background included."""
|
|
180
|
+
if e.get("models"):
|
|
181
|
+
def n(c: dict) -> list[int]: # Codex's adapter names cache writes cacheWriteInputTokens
|
|
182
|
+
return [c.get("inputTokens", 0), c.get("cachedWriteTokens", c.get("cacheWriteInputTokens", 0)),
|
|
183
|
+
c.get("cachedInputTokens", 0), c.get("outputTokens", 0)]
|
|
184
|
+
return {m["model"]: n(m.get("token_count") or {}) for m in e["models"]}
|
|
185
|
+
u = e.get("usage") or {}
|
|
186
|
+
n = [u.get(k, 0) for k in ("inputTokens", "cachedWriteTokens", "cachedReadTokens", "outputTokens")]
|
|
187
|
+
return {"?": n} if any(n) else {}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def turns_since(logs: Path, read: dict) -> tuple[list[dict], dict]:
|
|
191
|
+
"""The turns ended since the last read, oldest first per log: each its agent, when it began and ended (local),
|
|
192
|
+
its stop reason, cost and tokens by model. `read` is what the last call returned, `{}` the first time; the app
|
|
193
|
+
keeps it with the turns, in one transaction."""
|
|
194
|
+
read, out = dict(read), []
|
|
195
|
+
for log in sorted(logs.glob("*.jsonl")) if logs.exists() else []:
|
|
196
|
+
mark = dict(read.get(log.name) or {"offset": 0, "began": None})
|
|
197
|
+
size = log.stat().st_size
|
|
198
|
+
if size < mark["offset"]: # a log made again for a new agent of the same name
|
|
199
|
+
mark = {"offset": 0, "began": None}
|
|
200
|
+
if size == mark["offset"]:
|
|
201
|
+
continue
|
|
202
|
+
with log.open("rb") as f:
|
|
203
|
+
f.seek(mark["offset"])
|
|
204
|
+
data = f.read()
|
|
205
|
+
end = data.rfind(b"\n") + 1 # a line still being written waits for the next read
|
|
206
|
+
for line in data[:end].splitlines():
|
|
207
|
+
if b'"prompt"' not in line and b'"turn"' not in line:
|
|
208
|
+
continue
|
|
209
|
+
try:
|
|
210
|
+
e = json.loads(line)
|
|
211
|
+
except json.JSONDecodeError:
|
|
212
|
+
continue
|
|
213
|
+
if e.get("kind") == "prompt":
|
|
214
|
+
mark["began"] = local(e["at"])
|
|
215
|
+
elif e.get("kind") == "turn" and (models := tokens(e)):
|
|
216
|
+
at = local(e["at"])
|
|
217
|
+
out.append({"agent": log.stem, "began": mark["began"] or at, "at": at, "stop": e.get("stop"),
|
|
218
|
+
"cost": e.get("cost"), "models": models})
|
|
219
|
+
mark["began"] = None
|
|
220
|
+
read[log.name] = {**mark, "offset": mark["offset"] + end}
|
|
221
|
+
return out, read
|