133 lines
6.2 KiB
Python
133 lines
6.2 KiB
Python
"""Run the actual 1.065 API adapter, isolated from bot/scheduler startup.
|
|
|
|
Run with the installed Hermes Python, not the relay Python. No installer code
|
|
or existing profiles are edited. Only a separate loopback listener is started.
|
|
"""
|
|
import argparse
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import os
|
|
import secrets
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def prepare_environment(install_root, profile, port, config_path):
|
|
if not profile or any(c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" for c in profile):
|
|
raise ValueError("invalid profile")
|
|
source = install_root / "hermes-agent"
|
|
home = install_root if profile == "default" else install_root / "profiles" / profile
|
|
if not (source / "gateway/platforms/api_server.py").is_file() or not (home / "config.yaml").is_file():
|
|
raise RuntimeError("installation/profile does not match installer 1.065 layout")
|
|
# Environment must be selected before importing any Hermes module (global caches).
|
|
os.environ["HERMES_HOME"] = str(home.resolve())
|
|
os.environ["API_SERVER_HOST"] = "127.0.0.1"
|
|
os.environ["API_SERVER_PORT"] = str(port)
|
|
os.environ["API_SERVER_CORS_ORIGINS"] = ""
|
|
os.environ["HERMES_SKIP_CWD_MIGRATION"] = "1"
|
|
sys.path.insert(0, str(source.resolve()))
|
|
# Use the package's own dotenv support to reuse the real profile model credentials.
|
|
from dotenv import load_dotenv
|
|
load_dotenv(install_root / ".env", override=False)
|
|
if home != install_root:
|
|
load_dotenv(home / ".env", override=True)
|
|
if config_path.exists():
|
|
data = json.loads(config_path.read_text(encoding="utf-8-sig"))
|
|
if data.get("url") != f"http://127.0.0.1:{port}" or data.get("mode") != "text-only" or len(data.get("api_key", "")) < 32:
|
|
raise ValueError("existing local adapter config does not match listener")
|
|
key = data["api_key"]
|
|
else:
|
|
key = secrets.token_hex(32)
|
|
data = {"url": f"http://127.0.0.1:{port}", "api_key": key, "mode": "text-only"}
|
|
config_path.parent.mkdir(parents=True, exist_ok=True)
|
|
with config_path.open("x", encoding="utf-8") as out:
|
|
json.dump(data, out, indent=2)
|
|
if os.name != "nt":
|
|
config_path.chmod(0o600)
|
|
os.environ["API_SERVER_KEY"] = key
|
|
return key
|
|
|
|
|
|
def restricted_adapter_class(native_class, tools_config):
|
|
original_tools = tools_config._get_platform_tools
|
|
def without_remote_tools(config, platform, **kwargs):
|
|
if platform == "api_server":
|
|
return set()
|
|
return original_tools(config, platform, **kwargs)
|
|
tools_config._get_platform_tools = without_remote_tools
|
|
|
|
class RestrictedNativeAPI(native_class):
|
|
def _wire_plugin_handlers(self, app):
|
|
# Native connect() normally appends plugin HTTP handlers after the
|
|
# route table. Do not let that reopen the restricted companion API.
|
|
return None
|
|
|
|
def _create_agent(self, *args, **kwargs):
|
|
agent = super()._create_agent(*args, **kwargs)
|
|
# Model/tool construction is native. Fail BEFORE run_conversation if
|
|
# any plugin/recovery path silently reintroduced tools.
|
|
if getattr(agent, "tools", None) or getattr(agent, "valid_tool_names", None):
|
|
raise RuntimeError("text-only relay listener refuses an Agent with tools")
|
|
return agent
|
|
|
|
def _http_route_table(self):
|
|
allowed = {("GET", "/health"), ("GET", "/v1/models"),
|
|
("GET", "/v1/capabilities"), ("POST", "/v1/chat/completions")}
|
|
return [(method, path, handler) for method, path, handler in super()._http_route_table()
|
|
if (method, path) in allowed]
|
|
|
|
async def _handle_capabilities(self, request):
|
|
response = await super()._handle_capabilities(request)
|
|
data = json.loads(response.body)
|
|
data["hainuo_relay_policy"] = {"mode": "text-only", "tools": "disabled", "contract": "hainuo-1065-v1"}
|
|
# Do not advertise native admin/session/tool operations removed above.
|
|
endpoints = data.get("endpoints", {})
|
|
data["endpoints"] = {k: v for k, v in endpoints.items() if k in {"health", "models", "capabilities", "chat_completions"}}
|
|
data["features"] = {"text_only": True, "tools": False, "streaming": False}
|
|
from aiohttp import web
|
|
return web.json_response(data)
|
|
|
|
return RestrictedNativeAPI
|
|
|
|
|
|
async def serve_native(port, key):
|
|
from gateway.config import PlatformConfig
|
|
from gateway.platforms.api_server import APIServerAdapter
|
|
from hermes_cli import tools_config
|
|
adapter_class = restricted_adapter_class(APIServerAdapter, tools_config)
|
|
adapter = adapter_class(PlatformConfig(enabled=True, extra={"host": "127.0.0.1", "port": port,
|
|
"key": key, "model_name": "hainuo-relay-text"}))
|
|
try:
|
|
if not await adapter.connect():
|
|
raise RuntimeError("native API did not start; verify port and native installation")
|
|
print(f"海诺原生API已启动:http://127.0.0.1:{port}(纯文本,无工具;凭据未回显)", flush=True)
|
|
await asyncio.Event().wait()
|
|
finally:
|
|
await adapter.disconnect()
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--install-root", type=Path, required=True)
|
|
parser.add_argument("--profile", default="hainuo")
|
|
parser.add_argument("--port", type=int, default=8643)
|
|
parser.add_argument("--config", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
if not 1024 <= args.port <= 65535:
|
|
raise ValueError("invalid port")
|
|
# Native logs can contain provider/user content; this companion emits status only.
|
|
logging.disable(logging.CRITICAL)
|
|
key = prepare_environment(args.install_root.resolve(), args.profile, args.port, args.config.resolve())
|
|
try:
|
|
asyncio.run(serve_native(args.port, key))
|
|
except KeyboardInterrupt:
|
|
print("海诺原生API已停止。")
|
|
except Exception as error:
|
|
print(f"原生API启动失败({type(error).__name__});未输出凭据。请使用安装包自带Python,并核对安装根目录与Profile。", file=sys.stderr)
|
|
raise SystemExit(1) from None
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|