304 lines
13 KiB
Python
304 lines
13 KiB
Python
#!/usr/bin/env python3
|
||
"""C4H-R commands for local configuration, BrowserSkill and HTTP research."""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import hashlib
|
||
import json
|
||
import os
|
||
from pathlib import Path
|
||
import platform
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tarfile
|
||
import tempfile
|
||
import tomllib
|
||
from urllib.parse import urljoin, urlsplit
|
||
from zipfile import BadZipFile, ZipFile
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
MIRROR = ("https://mmsprxiaoweicos-1258344707.cos.ap-shanghai.myqcloud.com"
|
||
"/chatbot/deepsearch/downloads/browserskill/stable")
|
||
PLATFORMS = {
|
||
("Darwin", "arm64"): ("darwin-arm64", "bsk-macos-arm64.tar.gz"),
|
||
("Darwin", "x64"): ("darwin-x64", "bsk-macos-intel.tar.gz"),
|
||
("Linux", "arm64"): ("linux-arm64", "bsk-linux-arm64.tar.gz"),
|
||
("Linux", "x64"): ("linux-x64", "bsk-linux-x64.tar.gz"),
|
||
("Windows", "x64"): ("windows-x64", "bsk-windows-x64.zip"),
|
||
}
|
||
BSK = ROOT / ".c4hr" / "bin" / ("bsk.exe" if os.name == "nt" else "bsk")
|
||
REDIRECTS = {301, 302, 303, 307, 308}
|
||
|
||
|
||
def read_config(name):
|
||
path = ROOT / "config" / f"{name}.toml"
|
||
if not path.is_file():
|
||
raise ValueError(f"缺少 {path.name}。请先运行 init。")
|
||
with path.open("rb") as stream:
|
||
return tomllib.load(stream)
|
||
|
||
|
||
def init_config():
|
||
for name in ("databases", "proxies"):
|
||
source = ROOT / "config" / f"{name}.example.toml"
|
||
target = source.with_name(f"{name}.toml")
|
||
try:
|
||
with target.open("xb") as stream:
|
||
stream.write(source.read_bytes())
|
||
except FileExistsError:
|
||
print(f"使用已有配置 {target.relative_to(ROOT)}")
|
||
else:
|
||
print(f"创建 {target.relative_to(ROOT)}")
|
||
|
||
|
||
def http_url(url):
|
||
if not isinstance(url, str) or any(ord(c) <= 32 or ord(c) == 127 for c in url) or "\\" in url:
|
||
raise ValueError("请提供没有空白或反斜线的 HTTP(S) URL。")
|
||
parts = urlsplit(url)
|
||
if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username is not None:
|
||
raise ValueError("请提供不含凭证的 HTTP(S) URL。")
|
||
if parts.port == 0 or "%" in parts.hostname:
|
||
raise ValueError("URL 主机名或端口无效。")
|
||
return parts
|
||
|
||
|
||
def databases():
|
||
items = read_config("databases").get("databases", {})
|
||
if not isinstance(items, dict):
|
||
raise ValueError("databases 必须是 TOML 表。")
|
||
for key, item in items.items():
|
||
strings = ("name", "purpose", "url")
|
||
if (not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", key)
|
||
or not isinstance(item, dict)
|
||
or any(not isinstance(item.get(field), str) for field in strings)
|
||
or not isinstance(item.get("browser", ""), str)
|
||
or not isinstance(item.get("enabled"), bool)):
|
||
raise ValueError(f"数据库 {key} 的字段无效。")
|
||
http_url(item["url"])
|
||
if any(not item[field].strip() for field in ("name", "purpose")):
|
||
raise ValueError(f"数据库 {key} 缺少名称或用途。")
|
||
return items
|
||
|
||
|
||
def domain_key(value):
|
||
return value.rstrip(".").encode("idna").decode("ascii").lower()
|
||
|
||
|
||
def proxy_config():
|
||
data = read_config("proxies")
|
||
servers = data.get("servers", {})
|
||
sites = data.get("sites", {})
|
||
if not isinstance(servers, dict) or not isinstance(sites, dict):
|
||
raise ValueError("servers 和 sites 必须为 TOML 表。")
|
||
normalized = {}
|
||
for key, address in servers.items():
|
||
if key == "none" or not isinstance(address, str) or any(c.isspace() for c in address):
|
||
raise ValueError(f"代理 {key} 格式有误。")
|
||
parts = urlsplit(address)
|
||
if (parts.scheme not in {"socks5", "socks5h"} or not parts.hostname
|
||
or not parts.port or parts.path or parts.query or parts.fragment
|
||
or parts.username is not None or "\\" in address or "%" in parts.hostname):
|
||
raise ValueError(f"代理 {key} 应为 socks5h://主机:端口 或 socks5://主机:端口,且不含凭证。")
|
||
for host, server in sites.items():
|
||
key = domain_key(host)
|
||
if (not re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)*", key)
|
||
or key in normalized or not isinstance(server, str)
|
||
or (server != "none" and server not in servers)):
|
||
raise ValueError(f"站点路由 {host} 有误:请检查域名及代理名。")
|
||
normalized[key] = server
|
||
return servers, normalized
|
||
|
||
|
||
def route(url, config):
|
||
host = domain_key(http_url(url).hostname)
|
||
servers, sites = config
|
||
while host:
|
||
if host in sites:
|
||
name = sites[host]
|
||
return name, "" if name == "none" else servers[name]
|
||
host = host.partition(".")[2]
|
||
return "none", ""
|
||
|
||
|
||
def fetch(url, output):
|
||
config = proxy_config()
|
||
parent = output.parent if output else None
|
||
with tempfile.TemporaryDirectory(dir=parent) as directory:
|
||
download = Path(directory) / "response"
|
||
for _ in range(11):
|
||
_, proxy = route(url, config)
|
||
result = subprocess.run(
|
||
["curl", "-q", "--silent", "--show-error", "--globoff",
|
||
"--proto", "=http,https", "--noproxy", "", "--proxy", proxy,
|
||
"--connect-timeout", "15", "--max-time", "120",
|
||
"--output", str(download), "--write-out", "%{http_code}\n%{redirect_url}",
|
||
"--url", url],
|
||
check=True, stdout=subprocess.PIPE, text=True, encoding="utf-8",
|
||
)
|
||
status, _, location = result.stdout.partition("\n")
|
||
status = int(status)
|
||
if status in REDIRECTS and location:
|
||
next_url = urljoin(url, location)
|
||
http_url(next_url)
|
||
if urlsplit(url).scheme == "https" and urlsplit(next_url).scheme != "https":
|
||
raise ValueError("服务端重定向至明文 HTTP,请核对来源链接。")
|
||
url = next_url
|
||
continue
|
||
if not 200 <= status < 300:
|
||
raise ValueError(f"站点返回 HTTP {status}:{http_url(url).hostname}")
|
||
if output:
|
||
os.replace(download, output)
|
||
else:
|
||
with download.open("rb") as stream:
|
||
shutil.copyfileobj(stream, sys.stdout.buffer)
|
||
return
|
||
raise ValueError("请求超过 10 次重定向。")
|
||
|
||
|
||
def bsk_env():
|
||
return dict(os.environ, BSK_AUTO_UPDATE="off")
|
||
|
||
|
||
def mirror_download(filename, destination):
|
||
result = subprocess.run(
|
||
["curl", "-q", "--fail", "--silent", "--show-error", "--proto", "=https",
|
||
"--connect-timeout", "15", "--max-time", "180", "--output", str(destination),
|
||
"--write-out", "%{http_code}", "--url", f"{MIRROR}/{filename}"],
|
||
check=True, stdout=subprocess.PIPE, text=True,
|
||
)
|
||
if result.stdout != "200":
|
||
raise ValueError(f"腾讯镜像返回 HTTP {result.stdout}:{filename}")
|
||
|
||
|
||
def archive_binary(archive, binary_name, target):
|
||
with target.open("wb") as output:
|
||
if archive.suffix == ".zip":
|
||
with ZipFile(archive) as package:
|
||
member, = [entry for entry in package.infolist()
|
||
if not entry.is_dir() and Path(entry.filename).name == binary_name]
|
||
with package.open(member) as stream:
|
||
shutil.copyfileobj(stream, output)
|
||
else:
|
||
with tarfile.open(archive, "r:gz") as package:
|
||
member, = [entry for entry in package if entry.isfile()
|
||
and Path(entry.name).name == binary_name]
|
||
with package.extractfile(member) as stream:
|
||
shutil.copyfileobj(stream, output)
|
||
target.chmod(0o755)
|
||
|
||
|
||
def install_browser(harness):
|
||
cpu = platform.machine().lower()
|
||
cpu = {"amd64": "x64", "x86_64": "x64", "aarch64": "arm64"}.get(cpu, cpu)
|
||
target = PLATFORMS.get((platform.system(), cpu))
|
||
if not target:
|
||
raise ValueError(f"腾讯镜像没有对应的平台:{platform.system()} {cpu}")
|
||
manifest_key, filename = target
|
||
BSK.parent.mkdir(parents=True, exist_ok=True)
|
||
with tempfile.TemporaryDirectory(dir=BSK.parent) as directory:
|
||
temp = Path(directory)
|
||
manifest_file = temp / "version.json"
|
||
archive = temp / filename
|
||
mirror_download("version.json", manifest_file)
|
||
manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
|
||
checksum = manifest["assets"][manifest_key]["sha256"]
|
||
if not re.fullmatch(r"[0-9a-fA-F]{64}", checksum):
|
||
raise ValueError(f"腾讯发布清单没有提供有效的 {manifest_key} SHA-256。")
|
||
mirror_download(filename, archive)
|
||
with archive.open("rb") as stream:
|
||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||
if digest != checksum.lower():
|
||
raise ValueError("腾讯镜像安装包与发布清单的 SHA-256 不一致,现有安装已保留。")
|
||
staging = temp / BSK.name
|
||
archive_binary(archive, BSK.name, staging)
|
||
subprocess.run([str(staging), "--version"], check=True, env=bsk_env())
|
||
os.replace(staging, BSK)
|
||
subprocess.run([str(BSK), "install-skill", "--harness", harness, "--json"],
|
||
check=True, env=bsk_env())
|
||
print("在目标 Chrome 或 Edge 配置中安装并连接 BrowserSkill 扩展,然后用 bsk browsers --json 查看。")
|
||
|
||
|
||
def run_bsk(args, *, capture_stdout=False):
|
||
if not BSK.is_file():
|
||
raise ValueError("请先运行 install-browser 从腾讯镜像安装 BrowserSkill。")
|
||
if args and args[0] == "update":
|
||
raise ValueError("请用 install-browser 从腾讯镜像更新。")
|
||
return subprocess.run(
|
||
[str(BSK), *args], env=bsk_env(),
|
||
stdout=subprocess.PIPE if capture_stdout else None, encoding="utf-8",
|
||
)
|
||
|
||
|
||
def connected_browser():
|
||
result = run_bsk(["browsers", "--json"], capture_stdout=True)
|
||
if result.returncode:
|
||
if result.stdout:
|
||
print(result.stdout.rstrip(), file=sys.stderr)
|
||
result.check_returncode()
|
||
browsers = json.loads(result.stdout)
|
||
if not isinstance(browsers, list):
|
||
raise ValueError("BrowserSkill 返回的浏览器列表格式无效。")
|
||
if not browsers:
|
||
raise ValueError("BrowserSkill 尚未连接浏览器。请打开浏览器扩展并连接。")
|
||
if len(browsers) > 1:
|
||
raise ValueError("已连接多个浏览器。请用 bsk browsers --json 查看实例,"
|
||
"并在数据库配置中填写用户选择的 browser。")
|
||
return browsers[0]["instance_id"]
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
commands = parser.add_subparsers(dest="command", required=True)
|
||
commands.add_parser("init", help="从模板复制缺失的本地配置")
|
||
commands.add_parser("check", help="验证两份本地配置")
|
||
commands.add_parser("databases", help="列出数据库配置")
|
||
install = commands.add_parser("install-browser", help="从腾讯镜像安装或更新 BrowserSkill")
|
||
install.add_argument("--harness", default="codex")
|
||
commands.add_parser("bsk", help="调用工作区的 BrowserSkill")
|
||
database = commands.add_parser("open-db", help="用已连接的浏览器打开启用的数据库")
|
||
database.add_argument("id")
|
||
routing = commands.add_parser("route", help="查询 URL 的代理路由")
|
||
routing.add_argument("url")
|
||
request = commands.add_parser("fetch", help="按域名代理规则下载 URL")
|
||
request.add_argument("url")
|
||
request.add_argument("-o", "--output", type=Path)
|
||
args = parser.parse_args(sys.argv[1:2] if sys.argv[1:2] == ["bsk"] else None)
|
||
try:
|
||
match args.command:
|
||
case "init":
|
||
init_config()
|
||
case "check":
|
||
databases()
|
||
proxy_config()
|
||
print("数据库与代理配置均有效。")
|
||
case "databases":
|
||
print(json.dumps(databases(), ensure_ascii=False, indent=2))
|
||
case "route":
|
||
name, proxy = route(args.url, proxy_config())
|
||
print(proxy if proxy else name)
|
||
case "fetch":
|
||
fetch(args.url, args.output)
|
||
case "install-browser":
|
||
install_browser(args.harness)
|
||
case "bsk":
|
||
return run_bsk(sys.argv[2:]).returncode
|
||
case "open-db":
|
||
item = databases().get(args.id)
|
||
if not item or not item["enabled"]:
|
||
raise ValueError(f"数据库 {args.id} 未配置或未启用。")
|
||
workspace = hashlib.sha256(os.fsencode(ROOT)).hexdigest()[:12]
|
||
scope = f"c4hr-{workspace}-{args.id}"
|
||
browser = item.get("browser", "").strip() or connected_browser()
|
||
return run_bsk(["open", "--scope", scope, "--browser", browser,
|
||
"--json", item["url"]]).returncode
|
||
except (OSError, ValueError, KeyError, TypeError, BadZipFile, tarfile.TarError,
|
||
subprocess.CalledProcessError) as error:
|
||
parser.exit(1, f"{error}\n")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|