acppool 0.1.0__tar.gz

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.
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ .venv/
5
+ examples/.board/
6
+ examples/acp/node_modules/
7
+ examples/acp/package-lock.json
acppool-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maksim Lunochkin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
acppool-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,157 @@
1
+ Metadata-Version: 2.5
2
+ Name: acppool
3
+ Version: 0.1.0
4
+ Summary: A worker pool for coding agents (Claude Code, Codex, any ACP agent), steered by a human.
5
+ Project-URL: Homepage, https://github.com/lunochkin/acppool
6
+ Project-URL: Issues, https://github.com/lunochkin/acppool/issues
7
+ Author-email: Maksim Lunochkin <maksim@lunochkin.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: acp,agent-client-protocol,claude-code,codex,coding-agents,human-in-the-loop
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Software Development
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+
20
+ # acppool
21
+
22
+ A worker pool for coding agents, steered by a human. You bring the jobs and the board; acppool runs the agents,
23
+ queues their work, holds their questions and permission requests until a person answers, and keeps every turn going
24
+ when your app restarts.
25
+
26
+ ![A Claude worker asks a question, gets an answer, and finishes its turn while the board is closed](https://raw.githubusercontent.com/lunochkin/acppool/main/docs/demo.gif)
27
+
28
+ It speaks the [Agent Client Protocol](https://agentclientprotocol.com) (ACP) to the agents, so Claude Code, Codex,
29
+ Goose and any other ACP agent run behind the same API. The library is standard-library Python with no packages to
30
+ install; each agent brings its own runtime (Claude's and Codex's ACP adapters need Node.js, Goose needs nothing more).
31
+
32
+ ## Why
33
+
34
+ There are SDKs that talk to one agent, and finished apps that manage many of them. acppool is the layer in between:
35
+ the part every agent board builds for itself.
36
+
37
+ - **Turns outlive your app.** A supervisor process owns the agents. Restart or redeploy the board, and running turns
38
+ carry on; restart the supervisor, and each agent resumes its session.
39
+ - **A human stays in the loop.** An agent can `ask` the human (an MCP tool acppool gives it), and a permission
40
+ request waits until someone answers it. Nothing is decided for the human by a timeout or a default policy.
41
+ - **It goes into your app.** No UI and no web server of its own: you call functions, read files, and decide what a
42
+ job is. A minimal board is 100 lines ([`examples/board.py`](examples/board.py)).
43
+
44
+ ## Try it
45
+
46
+ ```sh
47
+ git clone https://github.com/lunochkin/acppool && cd acppool
48
+ python3 examples/board.py
49
+ ```
50
+
51
+ ```
52
+ > join fake /tmp ada # a miniature agent that echoes; needs nothing installed
53
+ > give ada hello
54
+ ada > tool: Read a
55
+ ada · echo:hello
56
+ ada ends its turn
57
+ ```
58
+
59
+ To run Claude instead, install its ACP adapter once (Node.js needed) and have Claude Code signed in:
60
+
61
+ ```sh
62
+ (cd examples/acp && npm install)
63
+ python3 examples/board.py
64
+ > join claude /tmp/demo ada
65
+ > give ada Write hello.py that greets me. Use the ask tool to ask me which language I want.
66
+ ```
67
+
68
+ Leave the board with Ctrl-D while ada works, start it again, and ada's turn is still running or done. The demo above
69
+ is [`docs/demo.tape`](docs/demo.tape), recorded with [VHS](https://github.com/charmbracelet/vhs).
70
+
71
+ ## How it fits together
72
+
73
+ ```
74
+ your app ──socket + files──▶ supervisor ──ACP──▶ agent adapter ──▶ the agent (claude, codex, goose …)
75
+ │ │ │
76
+ └─ pool, push, controls └─ one event log per agent └─ MCP ──▶ acppool's ask and wait
77
+ ```
78
+
79
+ - **`supervisor`** runs as its own process and owns one adapter process per agent. It starts, prompts, steers,
80
+ cancels and resumes sessions, holds permission requests, and writes every event to `sessions/<name>.jsonl`. Your
81
+ app commands it over a Unix socket (`client.call`) and reads its state from files, so a reader never waits on it.
82
+ - **`pool`** is your record of the workers: each one's job, queue, question and undelivered messages, kept in a
83
+ `Store` (SQLite, a JSON file, memory, or your own database).
84
+ - **`push`** decides what an idle worker gets next: an answer, a message, the end of a background run it waits on,
85
+ a compaction when its context is full, or its next job. Your `App` subclass says what a job is.
86
+ - **`control`** has the human's controls: give, say, answer, permit, clear, reset, hold, take back, end.
87
+ - **`needs`** lists what waits on the human (a question, a permission, a reply), each with a key to notify it once.
88
+ - **`mcp`** is the agents' MCP server with the pool's own tools: `ask` the human, and `wait` on a background run.
89
+ Add your app's tools beside them in the same server.
90
+ - **`sessions`** cuts the event logs into sessions and turns, with each turn's tokens and cost; `client.steps` reads
91
+ a log as one line per step.
92
+
93
+ ## Writing an app
94
+
95
+ Three pieces: the supervisor's configuration, an `App`, and a loop that runs the push.
96
+
97
+ ```python
98
+ from acppool import claude, client, control, pool, push, supervisor
99
+
100
+ # agentd.py, run as its own process; servers() gives each session your MCP server (acppool's ask and wait in it)
101
+ config = supervisor.Config.under(STATE, kinds={"claude": claude.installed(ADAPTER_FOLDER)}, servers=servers)
102
+ supervisor.main(config)
103
+
104
+ # your app
105
+ class Board(push.App):
106
+ home = "the board"
107
+
108
+ def brief(self, item, worker): # the prompt a job is sent with
109
+ return f"Fix {item['name']}. Report with the done tool."
110
+
111
+ def job_over(self, job, worker): # a job ends when the agent says so, not when a turn ends
112
+ return job.get("done", False)
113
+
114
+ app = Board(pool.SqliteStore(STATE / "pool.db"), my_supervisor) # my_supervisor: call() and agents(), over client
115
+ threading.Thread(target=push.run, args=(lambda: app,), daemon=True).start()
116
+ control.give(app, "ada", {"kind": "issue", "name": "#42"})
117
+ ```
118
+
119
+ Every `App` hook has a default, so the simplest app overrides nothing: a job is one turn, and its brief is its
120
+ name. The hooks you are likely to want are `brief`, `job_over`, `judge` (take, keep or drop a queued item at its
121
+ turn), `run_of` (jobs of one run share a session), `preamble` (standing instructions) and `record` (your activity
122
+ log). [`examples/`](examples) has a complete board and its supervisor.
123
+
124
+ ## Agents
125
+
126
+ | Kind | Adapter | Steering mid-turn | After a restart | Notes |
127
+ | --- | --- | --- | --- | --- |
128
+ | `claude` | [claude-agent-acp](https://github.com/agentclientprotocol/claude-agent-acp) (npm) | yes | resumed | Agent SDK options per kind, e.g. `settingSources` |
129
+ | `codex` | [codex-acp](https://github.com/agentclientprotocol/codex-acp) (npm) | yes | resumed | sessions set to the `agent` mode |
130
+ | any ACP agent | its own, e.g. `goose acp` | if it offers it | resumed, or loaded | `Kind(command=..., options=...)` |
131
+
132
+ A `Kind` is the adapter's command line plus what it offers beyond ACP: a steering method, session options (ACP
133
+ config options set on every session), Claude-style `_meta`, a rate-limit report. Claude and Codex need Node.js for
134
+ their adapters; agents that speak ACP natively, like Goose, need nothing else. An agent that cannot resume a session
135
+ but can load one is loaded, with the history it replays kept out of the log.
136
+
137
+ ## Status
138
+
139
+ 0.x: in daily use by two boards, and the API may still change between minor versions. Python 3.10 or newer, on
140
+ macOS and Linux.
141
+
142
+ Neighbouring projects solve other parts: [acpx](https://github.com/openclaw/acpx) is a scriptable ACP client for
143
+ running one agent from a script or CI, with permissions decided by policy; the ACP adapters above translate each
144
+ agent to ACP. acppool is the pool between the agents and your board.
145
+
146
+ ## Tests
147
+
148
+ ```sh
149
+ python3 -m unittest discover -s acppool/tests -t .
150
+ ```
151
+
152
+ They run the supervisor over a miniature ACP agent ([`acppool/tests/fake_agent.py`](acppool/tests/fake_agent.py))
153
+ in a temporary folder, with no network and no agent installed.
154
+
155
+ ## License
156
+
157
+ MIT
@@ -0,0 +1,138 @@
1
+ # acppool
2
+
3
+ A worker pool for coding agents, steered by a human. You bring the jobs and the board; acppool runs the agents,
4
+ queues their work, holds their questions and permission requests until a person answers, and keeps every turn going
5
+ when your app restarts.
6
+
7
+ ![A Claude worker asks a question, gets an answer, and finishes its turn while the board is closed](https://raw.githubusercontent.com/lunochkin/acppool/main/docs/demo.gif)
8
+
9
+ It speaks the [Agent Client Protocol](https://agentclientprotocol.com) (ACP) to the agents, so Claude Code, Codex,
10
+ Goose and any other ACP agent run behind the same API. The library is standard-library Python with no packages to
11
+ install; each agent brings its own runtime (Claude's and Codex's ACP adapters need Node.js, Goose needs nothing more).
12
+
13
+ ## Why
14
+
15
+ There are SDKs that talk to one agent, and finished apps that manage many of them. acppool is the layer in between:
16
+ the part every agent board builds for itself.
17
+
18
+ - **Turns outlive your app.** A supervisor process owns the agents. Restart or redeploy the board, and running turns
19
+ carry on; restart the supervisor, and each agent resumes its session.
20
+ - **A human stays in the loop.** An agent can `ask` the human (an MCP tool acppool gives it), and a permission
21
+ request waits until someone answers it. Nothing is decided for the human by a timeout or a default policy.
22
+ - **It goes into your app.** No UI and no web server of its own: you call functions, read files, and decide what a
23
+ job is. A minimal board is 100 lines ([`examples/board.py`](examples/board.py)).
24
+
25
+ ## Try it
26
+
27
+ ```sh
28
+ git clone https://github.com/lunochkin/acppool && cd acppool
29
+ python3 examples/board.py
30
+ ```
31
+
32
+ ```
33
+ > join fake /tmp ada # a miniature agent that echoes; needs nothing installed
34
+ > give ada hello
35
+ ada > tool: Read a
36
+ ada · echo:hello
37
+ ada ends its turn
38
+ ```
39
+
40
+ To run Claude instead, install its ACP adapter once (Node.js needed) and have Claude Code signed in:
41
+
42
+ ```sh
43
+ (cd examples/acp && npm install)
44
+ python3 examples/board.py
45
+ > join claude /tmp/demo ada
46
+ > give ada Write hello.py that greets me. Use the ask tool to ask me which language I want.
47
+ ```
48
+
49
+ Leave the board with Ctrl-D while ada works, start it again, and ada's turn is still running or done. The demo above
50
+ is [`docs/demo.tape`](docs/demo.tape), recorded with [VHS](https://github.com/charmbracelet/vhs).
51
+
52
+ ## How it fits together
53
+
54
+ ```
55
+ your app ──socket + files──▶ supervisor ──ACP──▶ agent adapter ──▶ the agent (claude, codex, goose …)
56
+ │ │ │
57
+ └─ pool, push, controls └─ one event log per agent └─ MCP ──▶ acppool's ask and wait
58
+ ```
59
+
60
+ - **`supervisor`** runs as its own process and owns one adapter process per agent. It starts, prompts, steers,
61
+ cancels and resumes sessions, holds permission requests, and writes every event to `sessions/<name>.jsonl`. Your
62
+ app commands it over a Unix socket (`client.call`) and reads its state from files, so a reader never waits on it.
63
+ - **`pool`** is your record of the workers: each one's job, queue, question and undelivered messages, kept in a
64
+ `Store` (SQLite, a JSON file, memory, or your own database).
65
+ - **`push`** decides what an idle worker gets next: an answer, a message, the end of a background run it waits on,
66
+ a compaction when its context is full, or its next job. Your `App` subclass says what a job is.
67
+ - **`control`** has the human's controls: give, say, answer, permit, clear, reset, hold, take back, end.
68
+ - **`needs`** lists what waits on the human (a question, a permission, a reply), each with a key to notify it once.
69
+ - **`mcp`** is the agents' MCP server with the pool's own tools: `ask` the human, and `wait` on a background run.
70
+ Add your app's tools beside them in the same server.
71
+ - **`sessions`** cuts the event logs into sessions and turns, with each turn's tokens and cost; `client.steps` reads
72
+ a log as one line per step.
73
+
74
+ ## Writing an app
75
+
76
+ Three pieces: the supervisor's configuration, an `App`, and a loop that runs the push.
77
+
78
+ ```python
79
+ from acppool import claude, client, control, pool, push, supervisor
80
+
81
+ # agentd.py, run as its own process; servers() gives each session your MCP server (acppool's ask and wait in it)
82
+ config = supervisor.Config.under(STATE, kinds={"claude": claude.installed(ADAPTER_FOLDER)}, servers=servers)
83
+ supervisor.main(config)
84
+
85
+ # your app
86
+ class Board(push.App):
87
+ home = "the board"
88
+
89
+ def brief(self, item, worker): # the prompt a job is sent with
90
+ return f"Fix {item['name']}. Report with the done tool."
91
+
92
+ def job_over(self, job, worker): # a job ends when the agent says so, not when a turn ends
93
+ return job.get("done", False)
94
+
95
+ app = Board(pool.SqliteStore(STATE / "pool.db"), my_supervisor) # my_supervisor: call() and agents(), over client
96
+ threading.Thread(target=push.run, args=(lambda: app,), daemon=True).start()
97
+ control.give(app, "ada", {"kind": "issue", "name": "#42"})
98
+ ```
99
+
100
+ Every `App` hook has a default, so the simplest app overrides nothing: a job is one turn, and its brief is its
101
+ name. The hooks you are likely to want are `brief`, `job_over`, `judge` (take, keep or drop a queued item at its
102
+ turn), `run_of` (jobs of one run share a session), `preamble` (standing instructions) and `record` (your activity
103
+ log). [`examples/`](examples) has a complete board and its supervisor.
104
+
105
+ ## Agents
106
+
107
+ | Kind | Adapter | Steering mid-turn | After a restart | Notes |
108
+ | --- | --- | --- | --- | --- |
109
+ | `claude` | [claude-agent-acp](https://github.com/agentclientprotocol/claude-agent-acp) (npm) | yes | resumed | Agent SDK options per kind, e.g. `settingSources` |
110
+ | `codex` | [codex-acp](https://github.com/agentclientprotocol/codex-acp) (npm) | yes | resumed | sessions set to the `agent` mode |
111
+ | any ACP agent | its own, e.g. `goose acp` | if it offers it | resumed, or loaded | `Kind(command=..., options=...)` |
112
+
113
+ A `Kind` is the adapter's command line plus what it offers beyond ACP: a steering method, session options (ACP
114
+ config options set on every session), Claude-style `_meta`, a rate-limit report. Claude and Codex need Node.js for
115
+ their adapters; agents that speak ACP natively, like Goose, need nothing else. An agent that cannot resume a session
116
+ but can load one is loaded, with the history it replays kept out of the log.
117
+
118
+ ## Status
119
+
120
+ 0.x: in daily use by two boards, and the API may still change between minor versions. Python 3.10 or newer, on
121
+ macOS and Linux.
122
+
123
+ Neighbouring projects solve other parts: [acpx](https://github.com/openclaw/acpx) is a scriptable ACP client for
124
+ running one agent from a script or CI, with permissions decided by policy; the ACP adapters above translate each
125
+ agent to ACP. acppool is the pool between the agents and your board.
126
+
127
+ ## Tests
128
+
129
+ ```sh
130
+ python3 -m unittest discover -s acppool/tests -t .
131
+ ```
132
+
133
+ They run the supervisor over a miniature ACP agent ([`acppool/tests/fake_agent.py`](acppool/tests/fake_agent.py))
134
+ in a temporary folder, with no network and no agent installed.
135
+
136
+ ## License
137
+
138
+ MIT
@@ -0,0 +1,2 @@
1
+ """A pool of ACP agents run for an app: a supervisor that owns their adapter processes, so a turn outlives the app's
2
+ restart, and the client the app commands it with. Standard library only; it imports nothing of the app's."""
@@ -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
@@ -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)
@@ -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
@@ -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)