acp-demux 0.0.1__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.
- acp_demux-0.0.1/LICENSE +21 -0
- acp_demux-0.0.1/PKG-INFO +17 -0
- acp_demux-0.0.1/README.md +93 -0
- acp_demux-0.0.1/acp_demux/__init__.py +59 -0
- acp_demux-0.0.1/acp_demux/__main__.py +7 -0
- acp_demux-0.0.1/acp_demux/agent_process.py +230 -0
- acp_demux-0.0.1/acp_demux/auth.py +198 -0
- acp_demux-0.0.1/acp_demux/cli.py +232 -0
- acp_demux-0.0.1/acp_demux/config.py +164 -0
- acp_demux-0.0.1/acp_demux/errors.py +36 -0
- acp_demux-0.0.1/acp_demux/handshake.py +279 -0
- acp_demux-0.0.1/acp_demux/jsonrpc.py +207 -0
- acp_demux-0.0.1/acp_demux/multiplexer.py +640 -0
- acp_demux-0.0.1/acp_demux/py.typed +0 -0
- acp_demux-0.0.1/acp_demux/server.py +624 -0
- acp_demux-0.0.1/acp_demux/tickets.py +117 -0
- acp_demux-0.0.1/acp_demux.egg-info/PKG-INFO +17 -0
- acp_demux-0.0.1/acp_demux.egg-info/SOURCES.txt +33 -0
- acp_demux-0.0.1/acp_demux.egg-info/dependency_links.txt +1 -0
- acp_demux-0.0.1/acp_demux.egg-info/entry_points.txt +2 -0
- acp_demux-0.0.1/acp_demux.egg-info/requires.txt +11 -0
- acp_demux-0.0.1/acp_demux.egg-info/top_level.txt +1 -0
- acp_demux-0.0.1/pyproject.toml +102 -0
- acp_demux-0.0.1/setup.cfg +4 -0
- acp_demux-0.0.1/tests/test_agent_misbehaviour.py +110 -0
- acp_demux-0.0.1/tests/test_agent_requests.py +236 -0
- acp_demux-0.0.1/tests/test_auth.py +329 -0
- acp_demux-0.0.1/tests/test_cli.py +238 -0
- acp_demux-0.0.1/tests/test_framing.py +84 -0
- acp_demux-0.0.1/tests/test_lifecycle.py +224 -0
- acp_demux-0.0.1/tests/test_limits.py +143 -0
- acp_demux-0.0.1/tests/test_routing.py +139 -0
- acp_demux-0.0.1/tests/test_sessions.py +455 -0
- acp_demux-0.0.1/tests/test_subagents.py +74 -0
- acp_demux-0.0.1/tests/test_tickets.py +274 -0
acp_demux-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dave Cunningham
|
|
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.
|
acp_demux-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: acp-demux
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Host one long-lived ACP agent process behind many WebSocket clients
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: websockets>=15
|
|
8
|
+
Provides-Extra: dev
|
|
9
|
+
Requires-Dist: pyright==1.1.411; extra == "dev"
|
|
10
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
11
|
+
Requires-Dist: pytest-asyncio>=0.24.0; extra == "dev"
|
|
12
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
13
|
+
Requires-Dist: coverage; extra == "dev"
|
|
14
|
+
Requires-Dist: black==26.5.1; extra == "dev"
|
|
15
|
+
Requires-Dist: isort==8.0.1; extra == "dev"
|
|
16
|
+
Requires-Dist: pylint==4.0.6; extra == "dev"
|
|
17
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# acp-demux
|
|
2
|
+
|
|
3
|
+
One long-lived ACP agent process, shared by any number of WebSocket clients.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
acp-demux --port 4097 -- opencode acp
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Its main client is [agent-mission-control](https://github.com/sparkprime/agent-mission-control), a browser app. A WebSocket connection is disposable; behind `acp-demux`, the ACP server stays running.
|
|
10
|
+
|
|
11
|
+
## Strategy
|
|
12
|
+
|
|
13
|
+
- **One agent, many sockets.** The agent process starts with the server and outlives every socket. A reload, a closed tab or a sleeping laptop kills nothing: the session keeps running, a new connection resumes it, and two tabs can watch the same session.
|
|
14
|
+
- **Both die together.** If the agent dies the server dies, and vice versa.
|
|
15
|
+
- **The server owns the handshake.** The agent is initialized once, at start-up; every client's `initialize` is answered from that cache. One agent speaks one protocol version, so the server serves one version at a time.
|
|
16
|
+
- **Route by sessionId, nothing else.** Session-scoped traffic carries `params.sessionId`, which is the only protocol knowledge the router needs. Methods the server has no reason to intercept are forwarded byte for byte.
|
|
17
|
+
- **Ids are rewritten, everything else passes through.** N clients each choosing id `1` cannot collide on the one stdio stream; the server rewrites client request ids on the way in and restores them on the way out.
|
|
18
|
+
- **A replay belongs to the client that asked for it.** History chunks append, so replay traffic goes only to the requesting connection; a second replay of the same session waits for the first.
|
|
19
|
+
- **Pending prompts are never lost.** The agent never learns a socket died, so requests the agent sent before a tab dropped are kept and redelivered to the next attach; among several recipients the first answer wins and the others are dismissed with `$/cancel_request`.
|
|
20
|
+
- **Loopback is safe by default.** On `127.0.0.1` the server runs with no flags, no auth and no TLS, admitting only browser pages from a default origin list (localhost on any port, the hosted mission control) and non-browser clients. A non-loopback bind without both TLS and an authenticator is refused outright.
|
|
21
|
+
- **Browsers authenticate by ticket.** A browser cannot put a header on a WebSocket, but `fetch` can send any header: `POST /ticket` with the real secret returns a single-use, 15-second token the page presents as the `acp-ticket.<value>` subprotocol — never a query string. The exchange is wss-only, so a config pairing an authenticator with no TLS is refused at start-up. A spent ticket presented again is detected and the connection it created is closed.
|
|
22
|
+
- **Backpressure fails small.** A slow client's bounded outbox closes that one socket with 1013 (reconnect-and-resume is exactly the recovery ACP specifies); an oversized frame closes with 1009; the agent's stdin queue is bounded, so a slow agent pushes back on clients, not on memory.
|
|
23
|
+
- **A library with a command line.** Everything the CLI does is `ServerConfig`; the authenticator is an injected async protocol that sees the whole HTTP handshake, so OAuth, JWT or mTLS modules plug in without touching the server.
|
|
24
|
+
|
|
25
|
+
## Running it
|
|
26
|
+
|
|
27
|
+
The package is on PyPI, so running it is only:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install acp-demux # or: uv tool install acp-demux
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
To work on a checkout, use a virtualenv (typically `.venv`, managed with uv) and activate it before running anything. Install the package with its dev dependencies, then:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
./format.sh # isort + black over tests and the package
|
|
37
|
+
./lint.sh # pylint (pyright --strict is the other half of the gate)
|
|
38
|
+
pytest # the integration suite, with coverage enforced
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Serve an agent (see `acp-demux --help` for every flag):
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
acp-demux --port 4097 -- opencode acp # loopback, no setup
|
|
45
|
+
ACP_DEMUX_KEY=… acp-demux --port 4097 \
|
|
46
|
+
--tls-cert cert.pem --tls-key key.pem \
|
|
47
|
+
--allow-origin https://sparkprime.github.io -- opencode acp # secured
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Repository map
|
|
51
|
+
|
|
52
|
+
Start at `acp_demux/server.py`, which owns everything socket-shaped and hands routing to the multiplexer.
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
acp_demux/
|
|
56
|
+
server.py websockets glue: handshake, TLS, origins, auth, tickets,
|
|
57
|
+
healthz, outboxes, the both-die lifetimes, run()
|
|
58
|
+
multiplexer.py all routing state: id rewriting, session tables, replay
|
|
59
|
+
scoping, held and redelivered agent requests (no I/O)
|
|
60
|
+
agent_process.py the subprocess: framing, stderr tail, group shutdown
|
|
61
|
+
handshake.py the one initialize exchange and the cached client answer
|
|
62
|
+
auth.py the injected protocols: Authenticator, HttpEndpoints,
|
|
63
|
+
Principal, and the built-ins (NoAuth, SharedKeyAuth)
|
|
64
|
+
tickets.py the single-use ticket store behind POST /ticket
|
|
65
|
+
jsonrpc.py parse / classify / build messages, error codes
|
|
66
|
+
config.py ServerConfig, AgentCommand, Limits, the default origins
|
|
67
|
+
cli.py argparse -> ServerConfig -> run()
|
|
68
|
+
errors.py AgentExited and StartupError, the two exit statuses
|
|
69
|
+
tests/
|
|
70
|
+
fake_agent.py the scriptable ACP agent every test drives (FAKE_AGENT_*)
|
|
71
|
+
harness.py a real server on port 0, a real client, certs, HTTP
|
|
72
|
+
test_*.py one file per behaviour area; integration tests only
|
|
73
|
+
docs/decisions/ why things are the way they are, and what was rejected
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Working on the code
|
|
77
|
+
|
|
78
|
+
Documentation lives in the code, in a hierarchy: every package starts with a `__init__.py` docstring, every module opens with its contract, and symbols carry a comment only where their behaviour is not obvious. Each level assumes you have read the levels above it on the path to the thing you are changing, so it adds detail and does not repeat what a parent already says. To learn an area, read the `__init__.py` files from the root down, then the module docstring, then the symbol.
|
|
79
|
+
|
|
80
|
+
When you add or change documentation:
|
|
81
|
+
|
|
82
|
+
- Put a fact at the most specific level where it is still true, and say it once. A rule about the whole server belongs in a module docstring; a rule only one function needs belongs next to it.
|
|
83
|
+
- Write as of now. Documentation says why things are the way they are, framed as advantages in the current world, never by reference to how they used to be.
|
|
84
|
+
- Keep "why" and "what else was considered" out of the code. They go in [docs/decisions/](docs/decisions/), and the code links to the record where it helps explain behaviour.
|
|
85
|
+
- A strange decision in the code gets a line in Strategy above.
|
|
86
|
+
|
|
87
|
+
### Tests
|
|
88
|
+
|
|
89
|
+
The suite is integration-only: every test starts a real server on port 0 and drives it with a real `websockets` client against the `tests/fake_agent.py` subprocess, whose behaviour is chosen with `FAKE_AGENT_*` environment variables (see its module docstring). Coverage is enforced at 90% and reported on every `pytest` run.
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""acp-demux: one long-lived ACP agent behind many WebSockets.
|
|
2
|
+
|
|
3
|
+
An ACP agent is a subprocess speaking newline-delimited JSON-RPC on stdio;
|
|
4
|
+
this package hosts **one** such process and lets any number of WebSocket
|
|
5
|
+
clients share it. The agent, not the socket, owns session state (that is
|
|
6
|
+
ACP's own model), so a dropped or reloaded tab kills nothing: the session
|
|
7
|
+
keeps running, a new connection resumes it, and two tabs can watch the same
|
|
8
|
+
one. If the agent dies, the server dies with it — their states are one unit.
|
|
9
|
+
|
|
10
|
+
Four layers, each replaceable and testable on its own:
|
|
11
|
+
|
|
12
|
+
- :mod:`acp_demux.server` — websockets glue: handshake, TLS, origins,
|
|
13
|
+
auth, tickets, `/healthz`, ping/pong, process lifetimes.
|
|
14
|
+
- :mod:`acp_demux.multiplexer` — all routing state: id rewriting,
|
|
15
|
+
session tables, replay scoping, held and redelivered requests.
|
|
16
|
+
- :mod:`acp_demux.agent_process` — the subprocess, its framing and its
|
|
17
|
+
shutdown; knows processes, not protocol.
|
|
18
|
+
- :mod:`acp_demux.handshake` — the one `initialize` exchange with the
|
|
19
|
+
agent and the cached answer served to every client.
|
|
20
|
+
|
|
21
|
+
Configuration is frozen data (:mod:`acp_demux.config`); identity is the
|
|
22
|
+
:class:`acp_demux.auth.Principal` decided during the HTTP handshake.
|
|
23
|
+
Authentication decides who may connect, never which sessions they see: this
|
|
24
|
+
is a single-tenant tool, and every authenticated client shares the agent.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from acp_demux.auth import (
|
|
28
|
+
AuthenticationError,
|
|
29
|
+
Authenticator,
|
|
30
|
+
HandshakeRequest,
|
|
31
|
+
HttpEndpoints,
|
|
32
|
+
HttpResponse,
|
|
33
|
+
NoAuth,
|
|
34
|
+
Principal,
|
|
35
|
+
SharedKeyAuth,
|
|
36
|
+
)
|
|
37
|
+
from acp_demux.config import AgentCommand, Limits, ServerConfig
|
|
38
|
+
from acp_demux.errors import AgentExited, StartupError
|
|
39
|
+
from acp_demux.handshake import HandshakeResult
|
|
40
|
+
from acp_demux.server import AcpDemuxServer, run
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"AcpDemuxServer",
|
|
44
|
+
"AgentCommand",
|
|
45
|
+
"AgentExited",
|
|
46
|
+
"AuthenticationError",
|
|
47
|
+
"Authenticator",
|
|
48
|
+
"HandshakeRequest",
|
|
49
|
+
"HandshakeResult",
|
|
50
|
+
"HttpEndpoints",
|
|
51
|
+
"HttpResponse",
|
|
52
|
+
"Limits",
|
|
53
|
+
"NoAuth",
|
|
54
|
+
"Principal",
|
|
55
|
+
"ServerConfig",
|
|
56
|
+
"SharedKeyAuth",
|
|
57
|
+
"StartupError",
|
|
58
|
+
"run",
|
|
59
|
+
]
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""The one agent subprocess: spawn, framing, and the both-die rule.
|
|
2
|
+
|
|
3
|
+
This module knows processes, not protocol: it spawns the agent command from
|
|
4
|
+
:mod:`acp_demux.config` (:class:`AgentCommand`), frames one JSON-RPC
|
|
5
|
+
message per line on stdin and stdout, keeps a 50-line stderr ring buffer for
|
|
6
|
+
the death report, and hands each stdout line to a callback as text. The
|
|
7
|
+
process runs in its own session (process group), so shutdown can signal the
|
|
8
|
+
agent and anything it spawned; on Linux the child additionally asks for
|
|
9
|
+
``SIGKILL`` at the parent's death as a best-effort guard against agents that
|
|
10
|
+
ignore stdin EOF.
|
|
11
|
+
|
|
12
|
+
There is deliberately no restart logic here. The server's routing tables and
|
|
13
|
+
the agent's in-memory sessions die together, so a fresh start is always a
|
|
14
|
+
clean start; a supervisor restarts the whole process (see
|
|
15
|
+
`docs/decisions/one-agent-many-sockets.md`).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import signal
|
|
24
|
+
import sys
|
|
25
|
+
from collections import deque
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Any, Callable
|
|
28
|
+
|
|
29
|
+
from acp_demux.config import AgentCommand, Limits
|
|
30
|
+
from acp_demux.errors import StartupError
|
|
31
|
+
|
|
32
|
+
__all__ = ["AgentExit", "AgentProcess"]
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
agent_logger = logging.getLogger("acp_demux.agent")
|
|
36
|
+
|
|
37
|
+
_STDERR_TAIL_LINES = 50
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _apply_pdeathsig() -> None: # pragma: no cover (runs in the child)
|
|
41
|
+
"""Best-effort PR_SET_PDEATHSIG, so the agent dies with the server even
|
|
42
|
+
if it ignores stdin EOF. Best effort only; nothing depends on it."""
|
|
43
|
+
if sys.platform != "linux":
|
|
44
|
+
return
|
|
45
|
+
try:
|
|
46
|
+
import ctypes # pylint: disable=import-outside-toplevel
|
|
47
|
+
|
|
48
|
+
libc: Any = ctypes.CDLL("libc.so.6", use_errno=True)
|
|
49
|
+
libc.prctl(1, signal.SIGKILL) # PR_SET_PDEATHSIG
|
|
50
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
51
|
+
pass # stdin EOF remains the shutdown path
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, slots=True)
|
|
55
|
+
class AgentExit:
|
|
56
|
+
"""How the agent ended: exit status (None for a signal) and stderr tail."""
|
|
57
|
+
|
|
58
|
+
returncode: int | None
|
|
59
|
+
stderr_tail: str
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class AgentProcess:
|
|
63
|
+
"""The one agent subprocess; owns its stdio framing.
|
|
64
|
+
|
|
65
|
+
Lines are dispatched synchronously to the current ``on_line`` callback;
|
|
66
|
+
the callback can be swapped (:meth:`set_on_line`), which is how the
|
|
67
|
+
start-up handshake (:mod:`acp_demux.handshake`) reads the stream
|
|
68
|
+
before the multiplexer takes over. ``death`` is a future that resolves
|
|
69
|
+
once with the exit report — whether the process exited, was killed, or
|
|
70
|
+
the stdout stream desynchronised (an oversized line is fatal, because the
|
|
71
|
+
stream cannot be resynced).
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self, process: asyncio.subprocess.Process, on_line: Callable[[str], None]
|
|
76
|
+
) -> None:
|
|
77
|
+
self._process = process
|
|
78
|
+
self._on_line = on_line
|
|
79
|
+
self._stderr_tail: deque[str] = deque(maxlen=_STDERR_TAIL_LINES)
|
|
80
|
+
self._send_queue: asyncio.Queue[str] = asyncio.Queue()
|
|
81
|
+
self.death: asyncio.Future[AgentExit] = (
|
|
82
|
+
asyncio.get_running_loop().create_future()
|
|
83
|
+
)
|
|
84
|
+
self._writer = asyncio.create_task(self._write_stdin())
|
|
85
|
+
self._reader = asyncio.create_task(self._read_stdout())
|
|
86
|
+
self._stderr_reader = asyncio.create_task(self._read_stderr())
|
|
87
|
+
self._waiter = asyncio.create_task(self._wait())
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
async def start(
|
|
91
|
+
cls, command: AgentCommand, on_line: Callable[[str], None], limits: Limits
|
|
92
|
+
) -> "AgentProcess":
|
|
93
|
+
"""Spawn the agent; raises :class:`StartupError` if it cannot."""
|
|
94
|
+
try:
|
|
95
|
+
process = await asyncio.create_subprocess_exec(
|
|
96
|
+
*command.argv,
|
|
97
|
+
cwd=command.cwd,
|
|
98
|
+
env=dict(command.env) if command.env is not None else None,
|
|
99
|
+
stdin=asyncio.subprocess.PIPE,
|
|
100
|
+
stdout=asyncio.subprocess.PIPE,
|
|
101
|
+
stderr=asyncio.subprocess.PIPE,
|
|
102
|
+
limit=limits.max_message_size,
|
|
103
|
+
start_new_session=True,
|
|
104
|
+
preexec_fn=_apply_pdeathsig,
|
|
105
|
+
)
|
|
106
|
+
except (OSError, ValueError) as exc:
|
|
107
|
+
raise StartupError(
|
|
108
|
+
f"cannot start agent {command.argv[0]!r}: {exc}"
|
|
109
|
+
) from exc
|
|
110
|
+
if (
|
|
111
|
+
process.stdout is None or process.stdin is None or process.stderr is None
|
|
112
|
+
): # pragma: no cover
|
|
113
|
+
raise StartupError("agent stdio is not piped") # pragma: exclude coverage
|
|
114
|
+
return cls(process, on_line)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def pid(self) -> int | None:
|
|
118
|
+
"""The agent's process id, or None before spawn completes."""
|
|
119
|
+
return self._process.pid
|
|
120
|
+
|
|
121
|
+
def set_on_line(self, on_line: Callable[[str], None]) -> None:
|
|
122
|
+
"""Swap the stdout dispatch callback; takes effect on the next line."""
|
|
123
|
+
self._on_line = on_line
|
|
124
|
+
|
|
125
|
+
async def send(self, text: str) -> None:
|
|
126
|
+
"""Queue one message for the agent's stdin.
|
|
127
|
+
|
|
128
|
+
Awaits when the write queue is full, which is the single backpressure
|
|
129
|
+
point for everything coming from clients (see
|
|
130
|
+
:mod:`acp_demux.multiplexer`).
|
|
131
|
+
"""
|
|
132
|
+
await self._send_queue.put(text)
|
|
133
|
+
|
|
134
|
+
def exit_report(self) -> AgentExit:
|
|
135
|
+
"""A snapshot of how the agent ended (valid once death is done)."""
|
|
136
|
+
return AgentExit(self._process.returncode, self.stderr_tail())
|
|
137
|
+
|
|
138
|
+
def stderr_tail(self) -> str:
|
|
139
|
+
"""The last lines of the agent's stderr, as one string."""
|
|
140
|
+
return "".join(self._stderr_tail)
|
|
141
|
+
|
|
142
|
+
def dispose(self) -> None:
|
|
143
|
+
"""Release the transport after a failed start-up: the pipes, the
|
|
144
|
+
reader and waiter tasks and any process still left all go with it,
|
|
145
|
+
so nothing dangles until garbage collection. The transport is
|
|
146
|
+
private to asyncio's Process, and closing it is the only way to
|
|
147
|
+
release the pipes."""
|
|
148
|
+
transport = getattr(self._process, "_transport")
|
|
149
|
+
transport.close()
|
|
150
|
+
|
|
151
|
+
async def shutdown(self, grace: float) -> None:
|
|
152
|
+
"""The graceful path: stdin EOF (the ACP shutdown), then SIGTERM,
|
|
153
|
+
then SIGKILL, each to the whole process group and each given `grace`
|
|
154
|
+
seconds to finish."""
|
|
155
|
+
if self.death.done():
|
|
156
|
+
return
|
|
157
|
+
if self._process.stdin is not None:
|
|
158
|
+
self._process.stdin.close()
|
|
159
|
+
try:
|
|
160
|
+
await asyncio.wait_for(self._process.wait(), grace)
|
|
161
|
+
return
|
|
162
|
+
except (TimeoutError, asyncio.TimeoutError):
|
|
163
|
+
pass
|
|
164
|
+
await self._signal_group(signal.SIGTERM)
|
|
165
|
+
try:
|
|
166
|
+
await asyncio.wait_for(self._process.wait(), grace)
|
|
167
|
+
return
|
|
168
|
+
except (TimeoutError, asyncio.TimeoutError):
|
|
169
|
+
pass
|
|
170
|
+
await self._signal_group(signal.SIGKILL)
|
|
171
|
+
await self._process.wait()
|
|
172
|
+
|
|
173
|
+
async def _signal_group(self, sig: signal.Signals) -> None:
|
|
174
|
+
"""Signal the process group; the group may already be gone."""
|
|
175
|
+
if self._process.returncode is not None:
|
|
176
|
+
return
|
|
177
|
+
try:
|
|
178
|
+
os.killpg(self._process.pid, sig)
|
|
179
|
+
except (ProcessLookupError, PermissionError):
|
|
180
|
+
logger.debug(
|
|
181
|
+
"process group %s already gone before %s", self._process.pid, sig
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def _resolve_death(self, exit_info: AgentExit) -> None:
|
|
185
|
+
if not self.death.done():
|
|
186
|
+
self.death.set_result(exit_info)
|
|
187
|
+
|
|
188
|
+
async def _wait(self) -> None:
|
|
189
|
+
returncode = await self._process.wait()
|
|
190
|
+
self._resolve_death(AgentExit(returncode, self.stderr_tail()))
|
|
191
|
+
|
|
192
|
+
async def _read_stdout(self) -> None:
|
|
193
|
+
"""Dispatch each stdout line; an oversized or fatal stream ends the
|
|
194
|
+
server the same way an agent crash does."""
|
|
195
|
+
assert self._process.stdout is not None
|
|
196
|
+
while True:
|
|
197
|
+
try:
|
|
198
|
+
line = await self._process.stdout.readline()
|
|
199
|
+
except (asyncio.LimitOverrunError, ValueError) as exc:
|
|
200
|
+
logger.error("agent stdout line over the limit; crash: %s", exc)
|
|
201
|
+
await self._signal_group(signal.SIGKILL)
|
|
202
|
+
self._resolve_death(AgentExit(None, self.stderr_tail()))
|
|
203
|
+
return
|
|
204
|
+
if not line:
|
|
205
|
+
self._resolve_death(self.exit_report())
|
|
206
|
+
return
|
|
207
|
+
self._on_line(line.decode("utf-8", errors="replace").rstrip("\n"))
|
|
208
|
+
|
|
209
|
+
async def _read_stderr(self) -> None:
|
|
210
|
+
"""Log the agent's stderr line by line and keep the tail for the
|
|
211
|
+
death report."""
|
|
212
|
+
assert self._process.stderr is not None
|
|
213
|
+
while True:
|
|
214
|
+
line = await self._process.stderr.readline()
|
|
215
|
+
if not line:
|
|
216
|
+
return
|
|
217
|
+
text = line.decode("utf-8", errors="replace").rstrip("\n")
|
|
218
|
+
self._stderr_tail.append(text + "\n")
|
|
219
|
+
agent_logger.info("%s", text)
|
|
220
|
+
|
|
221
|
+
async def _write_stdin(self) -> None:
|
|
222
|
+
"""Drain the send queue to the agent's stdin, one line per message."""
|
|
223
|
+
assert self._process.stdin is not None
|
|
224
|
+
try:
|
|
225
|
+
while True:
|
|
226
|
+
text = await self._send_queue.get()
|
|
227
|
+
self._process.stdin.write(text.encode("utf-8") + b"\n")
|
|
228
|
+
await self._process.stdin.drain()
|
|
229
|
+
except (ConnectionResetError, BrokenPipeError):
|
|
230
|
+
pass # the agent died; the wait task reports it
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Authentication during the HTTP handshake, and the principal it yields.
|
|
2
|
+
|
|
3
|
+
A WebSocket starts as an ordinary HTTP request, and the server can look at
|
|
4
|
+
all of it before deciding to upgrade. This module is the injection point for
|
|
5
|
+
anything that knows who is calling: the :class:`Authenticator` protocol sees
|
|
6
|
+
the whole :class:`HandshakeRequest` (headers, cookies, TLS peer certificate)
|
|
7
|
+
and returns a :class:`Principal` or raises :class:`AuthenticationError`. It
|
|
8
|
+
may do I/O, so it is async. The optional :class:`HttpEndpoints` protocol
|
|
9
|
+
serves plain HTTP under the server's path (a login, an OAuth callback), which
|
|
10
|
+
is how browser-only credential flows reach the server.
|
|
11
|
+
|
|
12
|
+
The server's job ends at "who may connect"; sessions are not partitioned by
|
|
13
|
+
principal (see `docs/decisions/one-agent-many-sockets.md`). The built-in
|
|
14
|
+
implementations are :class:`NoAuth` (loopback default) and
|
|
15
|
+
:class:`SharedKeyAuth` (HTTP Basic, one shared key).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import base64
|
|
21
|
+
import hmac
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import Any, Mapping, Protocol, Sequence, runtime_checkable
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"AuthenticationError",
|
|
27
|
+
"Authenticator",
|
|
28
|
+
"HandshakeRequest",
|
|
29
|
+
"Headers",
|
|
30
|
+
"HttpEndpoints",
|
|
31
|
+
"HttpResponse",
|
|
32
|
+
"NoAuth",
|
|
33
|
+
"Principal",
|
|
34
|
+
"SharedKeyAuth",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
_WWW_AUTHENTICATE_BASIC = [
|
|
38
|
+
("WWW-Authenticate", 'Basic realm="acp-demux", charset="UTF-8"')
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class Headers:
|
|
44
|
+
"""A read-only, case-insensitive view of HTTP headers.
|
|
45
|
+
|
|
46
|
+
`get` returns the first value; `get_all` returns every value, which is
|
|
47
|
+
how repeated headers (`Sec-WebSocket-Protocol`, `Set-Cookie`) are read.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
entries: tuple[tuple[str, str], ...] = ()
|
|
51
|
+
|
|
52
|
+
def get(self, name: str, default: str | None = None) -> str | None:
|
|
53
|
+
"""The first value for `name`, or `default`."""
|
|
54
|
+
lower = name.lower()
|
|
55
|
+
for key, value in self.entries:
|
|
56
|
+
if key.lower() == lower:
|
|
57
|
+
return value
|
|
58
|
+
return default
|
|
59
|
+
|
|
60
|
+
def get_all(self, name: str) -> list[str]:
|
|
61
|
+
"""Every value for `name`, in order."""
|
|
62
|
+
lower = name.lower()
|
|
63
|
+
return [value for key, value in self.entries if key.lower() == lower]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, slots=True)
|
|
67
|
+
class HandshakeRequest:
|
|
68
|
+
"""One HTTP request as the authenticator sees it.
|
|
69
|
+
|
|
70
|
+
`body` is always empty in the first version: the WebSocket handshake
|
|
71
|
+
carries none, and the websockets server hands the request over before a
|
|
72
|
+
plain request's body has been read. Authenticators that need a request
|
|
73
|
+
body (a password login form, say) do not fit yet.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
method: str
|
|
77
|
+
path: str
|
|
78
|
+
query: Mapping[str, Sequence[str]] = field(default_factory=dict[str, Sequence[str]])
|
|
79
|
+
headers: Headers = field(default_factory=Headers)
|
|
80
|
+
body: bytes = b""
|
|
81
|
+
remote_addr: tuple[str, int] | None = None
|
|
82
|
+
peer_cert: Mapping[str, Any] | None = None
|
|
83
|
+
secure: bool = False # True on wss
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True, slots=True)
|
|
87
|
+
class Principal:
|
|
88
|
+
"""Who is connecting; the answer of an authenticator.
|
|
89
|
+
|
|
90
|
+
`subject` names the user in logs and on the connection. `expires_at`
|
|
91
|
+
(epoch seconds) closes the socket when the credential expires (close code
|
|
92
|
+
4401). `subprotocol` is echoed in the handshake when the client asked for
|
|
93
|
+
it, which is how a subprotocol-carried credential completes the
|
|
94
|
+
handshake; the ticket flow sets it itself.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
subject: str
|
|
98
|
+
claims: Mapping[str, Any] = field(default_factory=dict[str, Any])
|
|
99
|
+
expires_at: float | None = None
|
|
100
|
+
subprotocol: str | None = None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True, slots=True)
|
|
104
|
+
class HttpResponse:
|
|
105
|
+
"""A plain HTTP response for :class:`HttpEndpoints`."""
|
|
106
|
+
|
|
107
|
+
status: int
|
|
108
|
+
headers: Sequence[tuple[str, str]] = ()
|
|
109
|
+
body: bytes = b""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class AuthenticationError(Exception):
|
|
113
|
+
"""Rejected; the handshake answers with `status`, `message` and `headers`.
|
|
114
|
+
|
|
115
|
+
`headers` carry what the credential scheme needs, typically
|
|
116
|
+
`WWW-Authenticate`, or a `Location` for a redirect.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
def __init__(
|
|
120
|
+
self,
|
|
121
|
+
status: int = 401,
|
|
122
|
+
message: str = "Unauthorized",
|
|
123
|
+
headers: Sequence[tuple[str, str]] = (),
|
|
124
|
+
) -> None:
|
|
125
|
+
super().__init__(f"{status} {message}")
|
|
126
|
+
self.status = status
|
|
127
|
+
self.message = message
|
|
128
|
+
self.headers = headers
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@runtime_checkable
|
|
132
|
+
class Authenticator(Protocol):
|
|
133
|
+
"""The injection point: decide who is calling, from the whole request."""
|
|
134
|
+
|
|
135
|
+
async def authenticate(self, request: HandshakeRequest) -> Principal:
|
|
136
|
+
"""Return the principal, or raise :class:`AuthenticationError`."""
|
|
137
|
+
... # pylint: disable=unnecessary-ellipsis
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@runtime_checkable
|
|
141
|
+
class HttpEndpoints(Protocol):
|
|
142
|
+
"""Optional second interface of an authenticator: plain HTTP endpoints.
|
|
143
|
+
|
|
144
|
+
Return None for "not mine"; the server answers 404 (after its own
|
|
145
|
+
endpoints, which are served first).
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
async def handle_http(self, request: HandshakeRequest) -> HttpResponse | None:
|
|
149
|
+
"""Answer a plain HTTP request, or None when it is not one of ours."""
|
|
150
|
+
... # pylint: disable=unnecessary-ellipsis
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class NoAuth:
|
|
154
|
+
"""The loopback default: everyone is the one user this tool has."""
|
|
155
|
+
|
|
156
|
+
async def authenticate(self, request: HandshakeRequest) -> Principal:
|
|
157
|
+
"""Accept; the origin check and the bind address are the protection."""
|
|
158
|
+
del request
|
|
159
|
+
return Principal(subject="anonymous")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class SharedKeyAuth:
|
|
163
|
+
"""One shared key, HTTP Basic: the password is the key, the username is
|
|
164
|
+
ignored unless `user` is given.
|
|
165
|
+
|
|
166
|
+
Non-browser clients put the credential on the WebSocket handshake itself;
|
|
167
|
+
a browser cannot, and exchanges it for a one-time ticket at `POST /ticket`
|
|
168
|
+
(see :mod:`acp_demux.tickets`) — which is wss-only, so the server
|
|
169
|
+
refuses this authenticator without TLS. There is no `?key=` form: the
|
|
170
|
+
long-lived secret never goes in a URL, and comparisons are
|
|
171
|
+
constant-time.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
def __init__(self, key: str, user: str | None = None) -> None:
|
|
175
|
+
self._key = key
|
|
176
|
+
self._user = user
|
|
177
|
+
|
|
178
|
+
async def authenticate(self, request: HandshakeRequest) -> Principal:
|
|
179
|
+
"""Check the Basic credential; any mismatch rejects with 401."""
|
|
180
|
+
header = request.headers.get("Authorization")
|
|
181
|
+
if header is None or not header.startswith("Basic "):
|
|
182
|
+
raise AuthenticationError(401, "Unauthorized", _WWW_AUTHENTICATE_BASIC)
|
|
183
|
+
try:
|
|
184
|
+
decoded = base64.b64decode(header[6:].strip(), validate=True).decode(
|
|
185
|
+
"utf-8"
|
|
186
|
+
)
|
|
187
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
188
|
+
raise AuthenticationError(
|
|
189
|
+
401, "Unauthorized", _WWW_AUTHENTICATE_BASIC
|
|
190
|
+
) from exc
|
|
191
|
+
user, sep, password = decoded.partition(":")
|
|
192
|
+
if not sep:
|
|
193
|
+
raise AuthenticationError(401, "Unauthorized", _WWW_AUTHENTICATE_BASIC)
|
|
194
|
+
if not hmac.compare_digest(password, self._key):
|
|
195
|
+
raise AuthenticationError(401, "Unauthorized", _WWW_AUTHENTICATE_BASIC)
|
|
196
|
+
if self._user is not None and not hmac.compare_digest(user, self._user):
|
|
197
|
+
raise AuthenticationError(401, "Unauthorized", _WWW_AUTHENTICATE_BASIC)
|
|
198
|
+
return Principal(subject=user or "user")
|