acpw 0.0.1__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.
- acpw/__init__.py +3 -0
- acpw/__main__.py +3 -0
- acpw/check.py +67 -0
- acpw/cli.py +230 -0
- acpw/config.py +39 -0
- acpw/errors.py +5 -0
- acpw/log.py +9 -0
- acpw/models.py +84 -0
- acpw/proxy/__init__.py +5 -0
- acpw/proxy/agent.py +568 -0
- acpw/proxy/backend.py +145 -0
- acpw/store/__init__.py +5 -0
- acpw/store/db.py +228 -0
- acpw-0.0.1.dist-info/METADATA +142 -0
- acpw-0.0.1.dist-info/RECORD +18 -0
- acpw-0.0.1.dist-info/WHEEL +4 -0
- acpw-0.0.1.dist-info/entry_points.txt +2 -0
- acpw-0.0.1.dist-info/licenses/LICENSE +21 -0
acpw/__init__.py
ADDED
acpw/__main__.py
ADDED
acpw/check.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import cast
|
|
7
|
+
|
|
8
|
+
from acp import PROTOCOL_VERSION, spawn_agent_process
|
|
9
|
+
from acp.interfaces import Client
|
|
10
|
+
from acp.schema import ClientCapabilities, Implementation
|
|
11
|
+
|
|
12
|
+
from acpw.models import SilentClient, dump_model, model_option
|
|
13
|
+
|
|
14
|
+
CHECK_TIMEOUT = 30.0
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class CheckReport:
|
|
19
|
+
cmd: list[str]
|
|
20
|
+
ok: bool = False
|
|
21
|
+
agent: str | None = None
|
|
22
|
+
protocol_version: int | None = None
|
|
23
|
+
session_id: str | None = None
|
|
24
|
+
has_model_option: bool = False
|
|
25
|
+
model_count: int = 0
|
|
26
|
+
can_delete: bool = False
|
|
27
|
+
error: str | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
async def check_command(cmd: list[str], cwd: str = ".") -> CheckReport:
|
|
31
|
+
"""握手 + 新建会话 + 模型目录探测,不发 prompt,不耗后端额度。"""
|
|
32
|
+
report = CheckReport(cmd=cmd)
|
|
33
|
+
client = SilentClient()
|
|
34
|
+
cwd = os.path.abspath(cwd)
|
|
35
|
+
|
|
36
|
+
async def run() -> None:
|
|
37
|
+
async with spawn_agent_process(
|
|
38
|
+
lambda _c: cast(Client, client),
|
|
39
|
+
*cmd,
|
|
40
|
+
env=dict(os.environ),
|
|
41
|
+
transport_kwargs={"stderr": None},
|
|
42
|
+
) as (conn, _proc):
|
|
43
|
+
init = await conn.initialize(
|
|
44
|
+
PROTOCOL_VERSION,
|
|
45
|
+
ClientCapabilities(),
|
|
46
|
+
Implementation(name="acpw-check", version="0.0.1"),
|
|
47
|
+
)
|
|
48
|
+
report.protocol_version = init.protocol_version
|
|
49
|
+
info = init.agent_info
|
|
50
|
+
report.agent = f"{info.name} {info.version}".strip() if info else None
|
|
51
|
+
session = await conn.new_session(cwd=cwd)
|
|
52
|
+
report.session_id = session.session_id
|
|
53
|
+
data = dump_model(model_option(session.config_options))
|
|
54
|
+
report.has_model_option = data is not None
|
|
55
|
+
report.model_count = len(data["options"]) if data else 0
|
|
56
|
+
try:
|
|
57
|
+
await conn.delete_session(session.session_id)
|
|
58
|
+
report.can_delete = True
|
|
59
|
+
except Exception:
|
|
60
|
+
report.can_delete = False
|
|
61
|
+
|
|
62
|
+
try:
|
|
63
|
+
await asyncio.wait_for(run(), timeout=CHECK_TIMEOUT)
|
|
64
|
+
report.ok = report.session_id is not None
|
|
65
|
+
except Exception as exc:
|
|
66
|
+
report.error = str(exc) or exc.__class__.__name__
|
|
67
|
+
return report
|
acpw/cli.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import shlex
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, cast
|
|
12
|
+
|
|
13
|
+
from acp import run_agent
|
|
14
|
+
from acp.interfaces import Agent
|
|
15
|
+
|
|
16
|
+
from acpw import __version__
|
|
17
|
+
from acpw.check import check_command
|
|
18
|
+
from acpw.config import Backend, config_path, load_backends, save_backends
|
|
19
|
+
from acpw.log import log
|
|
20
|
+
from acpw.proxy import ProxyAgent
|
|
21
|
+
from acpw.store import Store, default_home
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def main(argv: list[str] | None = None) -> int:
|
|
25
|
+
parser = argparse.ArgumentParser(prog="acpw", description="ACP 会话保持代理")
|
|
26
|
+
parser.add_argument("--version", action="version", version=f"acpw {__version__}")
|
|
27
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
28
|
+
|
|
29
|
+
acp = sub.add_parser("acp", help="以 ACP agent 身份运行在 stdio 上,代理到后端")
|
|
30
|
+
acp.add_argument("--backend", default=None, help="本次使用的后端名(默认上次使用的)")
|
|
31
|
+
acp.add_argument("--home", default=None, help="数据目录(默认 $ACPW_HOME 或 XDG)")
|
|
32
|
+
|
|
33
|
+
http = sub.add_parser("http", help="以 ACP agent 身份提供 Streamable HTTP 服务")
|
|
34
|
+
http.add_argument("--host", default="127.0.0.1")
|
|
35
|
+
http.add_argument("--port", type=int, default=8000)
|
|
36
|
+
http.add_argument("--backend", default=None, help="本次使用的后端名(默认上次使用的)")
|
|
37
|
+
http.add_argument("--home", default=None, help="数据目录(默认 $ACPW_HOME 或 XDG)")
|
|
38
|
+
|
|
39
|
+
be = sub.add_parser("backend", help="管理后端配置")
|
|
40
|
+
bsub = be.add_subparsers(dest="action", required=True)
|
|
41
|
+
bsub.add_parser("list", help="列出后端")
|
|
42
|
+
badd = bsub.add_parser("add", help="添加或更新后端")
|
|
43
|
+
badd.add_argument("name")
|
|
44
|
+
badd.add_argument("--cmd", required=True, help='启动命令,如 "opencode acp"')
|
|
45
|
+
brm = bsub.add_parser("remove", help="删除后端")
|
|
46
|
+
brm.add_argument("name")
|
|
47
|
+
|
|
48
|
+
status = sub.add_parser("status", help="查看活动中的会话")
|
|
49
|
+
status.add_argument("--home", default=None, help="数据目录(默认 $ACPW_HOME 或 XDG)")
|
|
50
|
+
|
|
51
|
+
check = sub.add_parser("check", help="检查一条命令能否作为 ACP 后端被代理")
|
|
52
|
+
check.add_argument("cmd", help='backend launch command, e.g. "opencode acp"')
|
|
53
|
+
check.add_argument("--cwd", default=".", help="working directory for the probe session (default: current dir)")
|
|
54
|
+
|
|
55
|
+
args = parser.parse_args(argv)
|
|
56
|
+
if args.command == "acp":
|
|
57
|
+
return _acp(args.backend, args.home)
|
|
58
|
+
if args.command == "http":
|
|
59
|
+
return _http(args)
|
|
60
|
+
if args.command == "backend":
|
|
61
|
+
return _backend(args)
|
|
62
|
+
if args.command == "check":
|
|
63
|
+
return _check(args)
|
|
64
|
+
return _status(args.home)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _db_path(home: str | None) -> Path:
|
|
68
|
+
return (Path(home) if home else default_home()) / "acpw.db"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _acp(explicit: str | None, home: str | None) -> int:
|
|
72
|
+
if os.environ.get("ACPW_DEBUG"):
|
|
73
|
+
logging.basicConfig(level=logging.DEBUG, stream=sys.stderr)
|
|
74
|
+
store = Store(_db_path(home))
|
|
75
|
+
backends = load_backends(config_path())
|
|
76
|
+
backend = _pick_backend(backends, explicit, store.get_setting("last_backend"))
|
|
77
|
+
store.set_setting("last_backend", backend.name)
|
|
78
|
+
log(f"acp start: backend {backend.name}: {' '.join(backend.cmd)}")
|
|
79
|
+
agent = ProxyAgent(backends, store, backend_name=backend.name)
|
|
80
|
+
|
|
81
|
+
async def run() -> None:
|
|
82
|
+
try:
|
|
83
|
+
await run_agent(cast(Agent, agent))
|
|
84
|
+
finally:
|
|
85
|
+
await agent.shutdown()
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
asyncio.run(run())
|
|
89
|
+
except KeyboardInterrupt:
|
|
90
|
+
return 130
|
|
91
|
+
except Exception as exc:
|
|
92
|
+
sys.stderr.write(f"[acpw] fatal: {exc!r}\n")
|
|
93
|
+
return 1
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _http(args: argparse.Namespace) -> int:
|
|
98
|
+
try:
|
|
99
|
+
import uvicorn
|
|
100
|
+
from acp.http.asgi import create_asgi_app
|
|
101
|
+
except ImportError:
|
|
102
|
+
sys.stderr.write("[acpw] 需要 http 依赖:uv sync --extra http 或 pip install 'acpw[http]'\n")
|
|
103
|
+
return 2
|
|
104
|
+
if os.environ.get("ACPW_DEBUG"):
|
|
105
|
+
logging.basicConfig(level=logging.DEBUG, stream=sys.stderr)
|
|
106
|
+
meta = Store(_db_path(args.home))
|
|
107
|
+
backends = load_backends(config_path())
|
|
108
|
+
backend = _pick_backend(backends, args.backend, meta.get_setting("last_backend"))
|
|
109
|
+
meta.set_setting("last_backend", backend.name)
|
|
110
|
+
meta.close()
|
|
111
|
+
log(f"http start: backend {backend.name}: {' '.join(backend.cmd)} on {args.host}:{args.port}")
|
|
112
|
+
|
|
113
|
+
agents: list[ProxyAgent] = []
|
|
114
|
+
|
|
115
|
+
def factory(_conn: Any) -> Agent:
|
|
116
|
+
agent = ProxyAgent(backends, Store(_db_path(args.home)), backend_name=backend.name)
|
|
117
|
+
agents.append(agent)
|
|
118
|
+
return cast(Agent, agent)
|
|
119
|
+
|
|
120
|
+
app = create_asgi_app(factory)
|
|
121
|
+
try:
|
|
122
|
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
|
123
|
+
except KeyboardInterrupt:
|
|
124
|
+
return 130
|
|
125
|
+
finally:
|
|
126
|
+
for agent in agents:
|
|
127
|
+
try:
|
|
128
|
+
asyncio.run(agent.shutdown())
|
|
129
|
+
except Exception as exc: # 关闭阶段尽力而为,不让残留进程阻塞退出
|
|
130
|
+
log(f"shutdown failed: {exc!r}")
|
|
131
|
+
return 0
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _pick_backend(backends: list[Backend], explicit: str | None, last: str | None) -> Backend:
|
|
135
|
+
if not backends:
|
|
136
|
+
raise SystemExit('未配置任何后端。先运行: acpw backend add <name> --cmd "<command>"')
|
|
137
|
+
names = [b.name for b in backends]
|
|
138
|
+
want = explicit or last
|
|
139
|
+
if want:
|
|
140
|
+
for b in backends:
|
|
141
|
+
if b.name == want:
|
|
142
|
+
return b
|
|
143
|
+
if explicit:
|
|
144
|
+
raise SystemExit(f"未知后端 {explicit},可选: {', '.join(names)}")
|
|
145
|
+
return backends[0]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _check(args: argparse.Namespace) -> int:
|
|
149
|
+
cmd = shlex.split(args.cmd)
|
|
150
|
+
if not cmd:
|
|
151
|
+
raise SystemExit("backend command is empty")
|
|
152
|
+
report = asyncio.run(check_command(cmd, cwd=args.cwd))
|
|
153
|
+
if report.agent:
|
|
154
|
+
print(f"✓ handshake: {report.agent}, protocol v{report.protocol_version}")
|
|
155
|
+
if report.session_id:
|
|
156
|
+
print(f"✓ session/new: {report.session_id}")
|
|
157
|
+
if report.has_model_option:
|
|
158
|
+
print(f"✓ model picker: {report.model_count} models")
|
|
159
|
+
else:
|
|
160
|
+
print("- model picker: no category=model option; model switching unavailable (single backend still works)")
|
|
161
|
+
if report.can_delete:
|
|
162
|
+
print("✓ session/delete: supported (probe session removed)")
|
|
163
|
+
else:
|
|
164
|
+
print("- session/delete: unsupported (probe session may linger; harmless)")
|
|
165
|
+
if report.ok:
|
|
166
|
+
print("verdict: usable as an ACP backend")
|
|
167
|
+
return 0
|
|
168
|
+
print(f"✗ error: {report.error}")
|
|
169
|
+
print("verdict: not usable as an ACP backend")
|
|
170
|
+
return 1
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _backend(args: argparse.Namespace) -> int:
|
|
174
|
+
path = config_path()
|
|
175
|
+
backends = load_backends(path)
|
|
176
|
+
if args.action == "list":
|
|
177
|
+
last = Store(_db_path(None)).get_setting("last_backend")
|
|
178
|
+
for b in backends:
|
|
179
|
+
mark = " (上次使用)" if b.name == last else ""
|
|
180
|
+
print(f"{b.name}\t{' '.join(b.cmd)}{mark}")
|
|
181
|
+
if not backends:
|
|
182
|
+
print(f"(空) 配置位置: {path}")
|
|
183
|
+
return 0
|
|
184
|
+
if args.action == "add":
|
|
185
|
+
cmd = shlex.split(args.cmd)
|
|
186
|
+
if not cmd:
|
|
187
|
+
raise SystemExit("--cmd 不能为空")
|
|
188
|
+
if "/" in args.name:
|
|
189
|
+
raise SystemExit("后端名不能包含 /(模型值用第一个 / 分隔后端与模型)")
|
|
190
|
+
entry = Backend(args.name, cmd)
|
|
191
|
+
for i, b in enumerate(backends):
|
|
192
|
+
if b.name == args.name:
|
|
193
|
+
backends[i] = entry
|
|
194
|
+
break
|
|
195
|
+
else:
|
|
196
|
+
backends.append(entry)
|
|
197
|
+
save_backends(path, backends)
|
|
198
|
+
print(f"已保存后端 {args.name} -> {path}")
|
|
199
|
+
return 0
|
|
200
|
+
# remove
|
|
201
|
+
kept = [b for b in backends if b.name != args.name]
|
|
202
|
+
if len(kept) == len(backends):
|
|
203
|
+
raise SystemExit(f"没有名为 {args.name} 的后端")
|
|
204
|
+
save_backends(path, kept)
|
|
205
|
+
print(f"已删除后端 {args.name}")
|
|
206
|
+
return 0
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _status(home: str | None) -> int:
|
|
210
|
+
store = Store(_db_path(home))
|
|
211
|
+
rows = store.activity()
|
|
212
|
+
if not rows:
|
|
213
|
+
print("没有活动中的会话")
|
|
214
|
+
return 0
|
|
215
|
+
print(f"{'会话':<12} {'后端':<14} {'状态':<6} {'最近活动':<20} pid")
|
|
216
|
+
for vsid, backend, pid, ts in rows:
|
|
217
|
+
state = "存活" if _alive(pid) else "已退出"
|
|
218
|
+
stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
|
|
219
|
+
print(f"{vsid:<12} {backend:<14} {state:<6} {stamp:<20} {pid}")
|
|
220
|
+
return 0
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _alive(pid: int) -> bool:
|
|
224
|
+
try:
|
|
225
|
+
os.kill(pid, 0)
|
|
226
|
+
except ProcessLookupError:
|
|
227
|
+
return False
|
|
228
|
+
except PermissionError:
|
|
229
|
+
return True
|
|
230
|
+
return True
|
acpw/config.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import tomllib
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Backend:
|
|
12
|
+
name: str
|
|
13
|
+
cmd: list[str]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def config_path() -> Path:
|
|
17
|
+
override = os.environ.get("ACPW_CONFIG")
|
|
18
|
+
if override:
|
|
19
|
+
return Path(override)
|
|
20
|
+
base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
21
|
+
return Path(base) / ".acpw" / "config.toml"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load_backends(path: Path) -> list[Backend]:
|
|
25
|
+
if not path.exists():
|
|
26
|
+
return []
|
|
27
|
+
data = tomllib.loads(path.read_text())
|
|
28
|
+
return [Backend(name=b["name"], cmd=list(b["cmd"])) for b in data.get("backend", [])]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def save_backends(path: Path, backends: list[Backend]) -> None:
|
|
32
|
+
lines: list[str] = []
|
|
33
|
+
for b in backends:
|
|
34
|
+
lines.append("[[backend]]")
|
|
35
|
+
lines.append(f"name = {json.dumps(b.name)}")
|
|
36
|
+
lines.append("cmd = [" + ", ".join(json.dumps(c) for c in b.cmd) + "]")
|
|
37
|
+
lines.append("")
|
|
38
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
path.write_text("\n".join(lines))
|
acpw/errors.py
ADDED
acpw/log.py
ADDED
acpw/models.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
|
|
7
|
+
from acp import PROTOCOL_VERSION, spawn_agent_process
|
|
8
|
+
from acp.interfaces import Client
|
|
9
|
+
from acp.schema import ClientCapabilities, Implementation
|
|
10
|
+
|
|
11
|
+
from acpw.config import Backend
|
|
12
|
+
from acpw.log import log
|
|
13
|
+
|
|
14
|
+
MODEL_SEP = "/"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def join_model(backend: str, value: str) -> str:
|
|
18
|
+
return f"{backend}{MODEL_SEP}{value}"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def split_model(value: str) -> tuple[str | None, str]:
|
|
22
|
+
# 模型 value 自身也含 /(如 provider/model),只按第一个 / 切出后端前缀
|
|
23
|
+
name, sep, raw = value.partition(MODEL_SEP)
|
|
24
|
+
return (name, raw) if sep else (None, value)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def model_option(options: list[Any] | None) -> Any | None:
|
|
28
|
+
for option in options or []:
|
|
29
|
+
if getattr(option, "category", None) == "model":
|
|
30
|
+
return option
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def dump_model(option: Any) -> dict[str, Any] | None:
|
|
35
|
+
"""把后端的 model 配置项转成可缓存的纯数据(版本间 id/configId 字段差异无感)。"""
|
|
36
|
+
if option is None:
|
|
37
|
+
return None
|
|
38
|
+
data = option.model_dump(by_alias=True, exclude_none=True)
|
|
39
|
+
items: list[dict[str, Any]] = []
|
|
40
|
+
for item in data.get("options") or []:
|
|
41
|
+
items.extend(item.get("options") or [] if "groupId" in item else [item])
|
|
42
|
+
return {
|
|
43
|
+
"option_id": data.get("id") or data.get("configId") or "model",
|
|
44
|
+
"current": data.get("currentValue"),
|
|
45
|
+
"options": [{"value": i["value"], "name": i.get("name") or i["value"]} for i in items],
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class SilentClient:
|
|
50
|
+
"""探测用的最小 client:吞掉后端主动推送,不碰真实客户端。"""
|
|
51
|
+
|
|
52
|
+
def on_connect(self, conn: Any) -> None:
|
|
53
|
+
self.conn = conn
|
|
54
|
+
|
|
55
|
+
async def session_update(self, session_id: str, update: Any, **kw: Any) -> None:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
async def probe_models(backend: Backend, cwd: str, timeout: float = 8.0) -> dict[str, Any] | None:
|
|
60
|
+
"""临时建一个会话拿 model 列表,随后删除(后端不支持 delete 时容忍残留)。"""
|
|
61
|
+
|
|
62
|
+
async def run() -> dict[str, Any] | None:
|
|
63
|
+
async with spawn_agent_process(
|
|
64
|
+
lambda _c: cast(Client, SilentClient()),
|
|
65
|
+
*backend.cmd,
|
|
66
|
+
env=dict(os.environ),
|
|
67
|
+
transport_kwargs={"stderr": None},
|
|
68
|
+
) as (conn, _proc):
|
|
69
|
+
await conn.initialize(
|
|
70
|
+
PROTOCOL_VERSION, ClientCapabilities(), Implementation(name="acpw-probe", version="0.0.1")
|
|
71
|
+
)
|
|
72
|
+
session = await conn.new_session(cwd=cwd)
|
|
73
|
+
data = dump_model(model_option(session.config_options))
|
|
74
|
+
try:
|
|
75
|
+
await conn.delete_session(session.session_id)
|
|
76
|
+
except Exception:
|
|
77
|
+
pass
|
|
78
|
+
return data
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
return await asyncio.wait_for(run(), timeout=timeout)
|
|
82
|
+
except Exception as exc:
|
|
83
|
+
log(f"probe models failed for {backend.name}: {exc!r}")
|
|
84
|
+
return None
|