#!/usr/bin/env python3
"""User-session candidate and translation transport. Never logs requests or HTTP errors."""
import argparse
import base64
import concurrent.futures
import ctypes
import datetime
import functools
import hashlib
import hmac
import http.client
import ipaddress
import json
import os
from pathlib import Path
import signal
import socket
import socketserver
import stat
import struct
import string
import subprocess
import sys
import sysconfig
import threading
import time
from types import SimpleNamespace
import urllib.parse
import urllib.request

from msime_provider_runtime import (
    StoppableUnixStreamServer, disables_ark_seed_thinking, open_server, volcengine_successor_model,
)
from msime_voice_provider_catalog import VOLCENGINE_SUCCESSOR_MODELS
import msime_crash_capture


# provider 用到的 host-api 入口，都是 char *f(const uint8_t *request, size_t length)；少一个就当作没有可用的库。host_library_contract.py 逐个核对它们在 msime_client.h 里的声明。
HOST_LIBRARY_SYMBOLS = (
    "msime_client_ensure_anonymous_account_with_agent",
    "msime_client_client_agent",
    "msime_client_account",
)
# 「水杉账号」释义每次请求的超时，交给 msime_client_account 的 translate 作 timeout_ms：上限是原来 Python 发 /v1/translate 时的 2.5 秒，下限是 Rust 接受的最小值 1 秒。
ACCOUNT_TRANSLATE_TIMEOUT_MS = (1000, 2500)
# 两次补注册匿名账号之间至少隔这么久（秒），与 Windows 的 account_registration_retry 相同：注册计入服务端每个出口地址每天 5 次的匿名登录额度，注册失败时不能每页候选都再试一次。
ANONYMOUS_REGISTRATION_RETRY = 600.0


class RustAccountApi:
    """经 host-api 的账号契约做账号相关的事。

    账号身份、会话选择（登录的优先，没有登录时用本机匿名账号）、令牌刷新、/v1/translate 请求和响应的逐项规范化都在 Rust 里；Python 只管什么时候问、问哪几个词，以及会话都不可用时补注册匿名账号。库延迟加载，源码树测试没有可选的宿主库时也能启动 provider。
    """

    def __init__(self, directory):
        self.directory = Path(directory).absolute()
        self._library = None
        self._responses = None
        self._load_failed = False
        self._lock = threading.Lock()
        # None 是还没拼过，空串是拼不出。
        self._client_agent = None
        # 上一次补注册的 time.monotonic()；None 是这个进程还没补注册过。
        self._registration_lock = threading.Lock()
        self._registered_at = None

    def _load(self):
        with self._lock:
            if self._library is not None or self._load_failed:
                return self._library
            candidates = []
            # 安装时 CMake 记下的库路径（相对 bin，带本版本的库名），rpm 和 Gentoo 的 lib64 都由它给出；下面按 <prefix>/lib 猜的几处只剩源码树和旧布局用得上。
            installed = installed_host_library()
            if installed is not None:
                candidates.append(installed)
            configured = os.environ.get("MSIME_HOST_LIBRARY")
            if configured:
                candidates.append(configured)
            # 安装脚本在 <prefix>/bin，匹配的库在
            # <prefix>/lib/<client-directory>。配置路径给非 full 版本和开发测试使用。
            script_root = Path(__file__).resolve().parent.parent
            candidates.extend([
                script_root / "lib" / "msime-client" / "libmsime_host_api.so",
                script_root / "lib" / "msime-client" / "libmsime_host_api_full.so",
            ])
            # 旧版 provider 或不完整安装没有可用的 msime_voice_paths.py；Debian 多架构库仍可由 Python 的标准配置定位。
            multiarch = sysconfig.get_config_var("MULTIARCH")
            if isinstance(multiarch, str) and multiarch:
                multiarch_library_directory = script_root / "lib" / multiarch / "msime-client"
                candidates.extend([
                    multiarch_library_directory / "libmsime_host_api.so",
                    multiarch_library_directory / "libmsime_host_api_full.so",
                ])
            # 源码树里脚本在 <仓库>/platforms/linux/scripts，开发构建的库在 <仓库>/target/debug。装到 /usr/bin 时往上只有三层，取第四层会抛 IndexError，整份候选表都建不起来，已安装的库也就加载不到（postinst 的 --ensure-anonymous-account 因此崩溃），所以上溯不到时没有开发构建这几项。
            script_parents = Path(__file__).resolve().parents
            development_root = script_parents[3] if len(script_parents) > 3 else None
            if development_root is not None:
                candidates.extend([
                    development_root / "target" / "debug" / "libmsime_host_api.so",
                    development_root / "target" / "debug" / "libmsime_host_api.dylib",
                ])
            installed_library_directory = script_root / "lib" / "msime-client"
            if installed_library_directory.is_dir():
                candidates.extend(sorted(installed_library_directory.glob("libmsime_host_api*.so")))
            development_library_directory = (
                development_root / "target" / "debug" / "deps" if development_root is not None else None
            )
            if development_library_directory is not None and development_library_directory.is_dir():
                candidates.extend(sorted(development_library_directory.glob("libmsime_host_api*.so")))
                candidates.extend(sorted(development_library_directory.glob("libmsime_host_api*.dylib")))
            for candidate in candidates:
                try:
                    library = ctypes.CDLL(str(candidate))
                except (OSError, TypeError):
                    continue
                try:
                    for name in HOST_LIBRARY_SYMBOLS:
                        function = getattr(library, name)
                        function.argtypes = [ctypes.c_char_p, ctypes.c_size_t]
                        function.restype = ctypes.c_void_p
                    self._library = library
                    self._responses = ResponseDecoder(library)
                    return library
                except (AttributeError, TypeError):
                    continue
            self._load_failed = True
            return None

    def _call(self, name, payload):
        library = self._load()
        if library is None:
            return None
        encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        try:
            pointer = getattr(library, name)(encoded, len(encoded))
            return self._responses.decode(pointer)
        except (OSError, UnicodeError, ValueError, TypeError):
            return None

    def client_agent(self):
        """注册匿名账号时自报的 User-Agent，由 Rust 拼出（msime_client_client_agent），服务端「我的设备」据此显示 linux 和版本。拼不出时为 None，注册照常进行，与不带 client_agent 时相同。"""
        if self._client_agent is not None:
            return self._client_agent or None
        version, edition = installed_version_and_edition()
        response = self._call("msime_client_client_agent", {
            "platform": "linux", "version": version, "device": None,
            "system": linux_system(), "edition": edition,
        })
        value = response.get("value") if isinstance(response, dict) and response.get("ok") is True else None
        self._client_agent = value if isinstance(value, str) else ""
        return self._client_agent or None

    def ensure_anonymous(self):
        payload = {"directory": str(self.directory)}
        agent = self.client_agent()
        if agent is not None:
            payload["client_agent"] = agent
        response = self._call("msime_client_ensure_anonymous_account_with_agent", payload)
        return isinstance(response, dict) and response.get("ok") is True and response.get("value") is True

    def translate(self, texts, source, target, deadline):
        """「水杉账号」释义：返回与 texts 等长的列表（没有释义的一项是 None），整批失败或 deadline（time.monotonic()）已过时返回 None。

        经 msime_client_account 的 translate，登录的账号优先，没有登录时用本机匿名账号，服务端以 401 拒绝令牌时 Rust 刷新一次、在同一个账号里重试。两种会话都不可用（account_unauthorized：安装后的注册没成功、文件被删、匿名会话被服务端吊销后已被 Rust 清掉）时补注册匿名账号再问一次，ANONYMOUS_REGISTRATION_RETRY 之内只补一次。
        """
        response = self._account_translate(texts, source, target, deadline)
        if (isinstance(response, dict) and response.get("error") == "account_unauthorized" and
                self._may_register() and self.ensure_anonymous()):
            response = self._account_translate(texts, source, target, deadline)
        value = response.get("value") if isinstance(response, dict) and response.get("ok") is True else None
        values = value.get("translations") if isinstance(value, dict) else None
        if not isinstance(values, list) or len(values) != len(texts):
            return None
        return [item if isinstance(item, str) and item else None for item in values]

    def _account_translate(self, texts, source, target, deadline):
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            return None
        low, high = ACCOUNT_TRANSLATE_TIMEOUT_MS
        payload = {"directory": str(self.directory), "action": {
            "operation": "translate", "texts": texts, "source_lang": source, "target_lang": target,
            "timeout_ms": max(low, min(high, int(remaining * 1000)))}}
        # 与注册时同一个 User-Agent：头文件要求同一个宿主的各次调用都带同一个 client_agent。
        agent = self.client_agent()
        if agent is not None:
            payload["client_agent"] = agent
        return self._call("msime_client_account", payload)

    def _may_register(self):
        with self._registration_lock:
            now = time.monotonic()
            if self._registered_at is not None and now < self._registered_at + ANONYMOUS_REGISTRATION_RETRY:
                return False
            self._registered_at = now
            return True


def installed_host_library():
    """CMake 配置进 msime_voice_paths.py 的 host 库路径；源码树里没有这个模块，返回 None。"""
    try:
        from msime_voice_paths import HOST_LIBRARY
    except ImportError:
        return None
    return Path(__file__).resolve().parent / HOST_LIBRARY


def installed_version_and_edition():
    """安装包的版本号和版本 ID，与 msime_voice_paths.py 一起由 CMake 写出；源码树里是空版本号（Rust 写成 0）和 full。"""
    try:
        from msime_voice_paths import EDITION, VERSION
    except ImportError:
        return "", "full"
    return VERSION, EDITION


def linux_system():
    """「我的设备」里系统那一栏：os-release 的 NAME 加 VERSION_ID（例如 Ubuntu 24.04）；读不到时为 None，Rust 写成 unknown。"""
    for path in ("/etc/os-release", "/usr/lib/os-release"):
        try:
            with open(path, encoding="utf-8") as handle:
                text = handle.read(16384)
        except (OSError, UnicodeError):
            continue
        fields = {}
        for line in text.splitlines():
            key, separator, value = line.strip().partition("=")
            if separator:
                fields[key] = value.strip().strip("\"'")
        system = " ".join(part for part in (fields.get("NAME", ""), fields.get("VERSION_ID", "")) if part)
        return system or None
    return None


class ResponseDecoder:
    """解码并释放 Rust host-api 分配的响应。"""

    def __init__(self, library):
        self.library = library
        self.library.msime_client_string_free.argtypes = [ctypes.c_void_p]
        self.library.msime_client_string_free.restype = None

    def decode(self, pointer):
        if not pointer:
            raise ValueError("missing native response")
        try:
            return json.loads(ctypes.string_at(pointer).decode("utf-8"))
        finally:
            self.library.msime_client_string_free(pointer)


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


http_processes = set()
http_process_lock = threading.Lock()
http_stopping = threading.Event()
MAX_AI_CACHE_ENTRIES = 4096
MAX_TRANSLATION_CACHE_ENTRIES = 4096
# 缓存不跨进程保留；随机挑战让凭据签名也只在本进程内稳定。
_CREDENTIAL_CACHE_CHALLENGE = os.urandom(32)
NEGATIVE_TRANSLATION_CACHE_TTL = 480
CLOUD_REQUEST_TIMEOUT = 2.0
# AI 推理与 Windows、client-providers 保持 8 秒总预算和 2.5 秒连接预算。
AI_REQUEST_TIMEOUT = 8.0
AI_CONNECT_TIMEOUT = 2.5
HTTP_WORKER_MAX_TIMEOUT = 10.0
# 在线查询包含再次转义的 HTTP 模板与请求头；其余请求保留原有上限。
REQUEST_LINE_LIMIT = 16384
AI_TEST_REQUEST_LINE_LIMIT = 32768
ONLINE_REQUEST_LINE_LIMIT = 131072
# 空白提示词槽位所代表的联想提示词：Windows 把它编译进 AiAssistantConfig::prompt（ime_config.h），client-providers 把同样的文本存为 ai::DEFAULT_CANDIDATE_PROMPT，供在那里构造请求的宿主使用。共享偏好让这个槽位留空，所以没有这一份时，Linux 的每个 AI 请求都带着空的 system 消息，模型回的是 JSON 解析器拒收的散文。ai_service_contract.py 保证这份副本与 client-providers 的那份相同。
DEFAULT_AI_PROMPT = "你是一个中文全拼输入法联想引擎。输入为已经切分好的拼音数组、前文上下文和候选数量。\n\n优先生成与拼音严格对应的中文候选：若有 N 段拼音，首选必须尽量为 N 个汉字，每段拼音对应一个汉字，不得随意增删或改变读音。结合上下文、常用程度、语义完整性和固定搭配排序。\n\n若去掉分词后能明显组成更合理的英文单词、缩写、产品名或技术术语，如 `deep + seek → DeepSeek`、`git + hub → GitHub`，可优先返回英文；不要生造英文或做牵强匹配。\n\n只输出合法 JSON，不要解释或输出 Markdown：\n\n{\n\"candidates\": [\n{\n\"text\": \"候选内容\",\n\"type\": \"chinese或english\",\n\"confidence\": 0.98\n}\n]\n}\n\n候选按推荐程度降序排列，数量不超过指定上限；没有合理结果时返回空数组。"
DEFAULT_TRANSLATION_PROMPT = "你是一个机器翻译服务。把用户给出的文本从 source_language 翻译成 target_language。只翻译文本本身，保留原意和标点，不要解释、注释或改写。只输出合法 JSON，不要输出 Markdown：{\"translation\":\"译文\"}。没有合适译文时输出空字符串。"


class ConnectBoundedHTTPSConnection(http.client.HTTPSConnection):
    """An HTTPS connection whose TCP, proxy tunnel and TLS handshake have their own shorter limit.

    urllib has one socket timeout, used for connecting and for every read after it. libcurl separates the two, and a model that takes five seconds to answer must not be cut off by the connect limit, so connect under the connect limit and then give the socket back the request timeout. The overall deadline stays with the worker's alarm and the parent process.
    """

    def __init__(self, *args, connect_timeout, **kwargs):
        super().__init__(*args, **kwargs)
        self.connect_timeout = connect_timeout

    def connect(self):
        request_timeout = self.timeout
        self.timeout = min(self.connect_timeout, request_timeout)
        try:
            super().connect()
        finally:
            self.timeout = request_timeout
        self.sock.settimeout(request_timeout)


class ConnectBoundedHTTPSHandler(urllib.request.HTTPSHandler):
    def __init__(self, connect_timeout):
        super().__init__()
        self.connect_timeout = connect_timeout

    def https_open(self, req):
        return self.do_open(functools.partial(ConnectBoundedHTTPSConnection,
                                              connect_timeout=self.connect_timeout),
                            req, context=self._context)


def request_opener(url, connect_timeout=None):
    handlers = [NoRedirect()]
    if connect_timeout is not None:
        handlers.append(ConnectBoundedHTTPSHandler(connect_timeout))
    # 本脚本只把明文 http 发给本机或局域网（AI 接口见 ai_endpoint_check，自定义翻译只认回环），这类请求直连、不走环境变量里的代理，否则带 Token 的请求会明文经过代理。https 照旧按环境变量用代理。
    if urllib.parse.urlsplit(url).scheme == "http":
        handlers.append(urllib.request.ProxyHandler({}))
    return urllib.request.build_opener(*handlers)


def fetch_direct(url, timeout, body=None, token=None, extra_headers=None, connect_timeout=None, max_response_bytes=65536):
    headers = {"Content-Type": "application/json", "User-Agent": "MSIME-Client"}
    if token:
        headers["Authorization"] = "Bearer " + token
    headers.update(extra_headers or {})
    payload = body if isinstance(body, bytes) else None if body is None else json.dumps(body).encode()
    request = urllib.request.Request(url, data=payload, headers=headers)
    with request_opener(url, connect_timeout).open(request, timeout=timeout) as response:
        payload = response.read(max_response_bytes + 1)
    if len(payload) > max_response_bytes:
        raise ValueError("response too large")
    return payload


def fetch(url, timeout, body=None, token=None, extra_headers=None, connect_timeout=None, max_response_bytes=65536):
    # Include DNS, TLS, upload and response reads in one deadline. Request data travels only through anonymous pipes, never command-line arguments.
    deadline = time.monotonic() + timeout
    body = body if isinstance(body, bytes) else None if body is None else json.dumps(body).encode()
    request = {"url": url, "timeout": timeout,
               "body": base64.b64encode(body).decode("ascii") if body is not None else None,
               "token": token, "extra_headers": extra_headers}
    if connect_timeout is not None:
        request["connect_timeout"] = connect_timeout
    if max_response_bytes != 65536:
        request["max_response_bytes"] = max_response_bytes
    metadata = json.dumps(request).encode()
    if len(metadata) > 262144 or timeout <= 0:
        raise ValueError("invalid HTTP request")
    with http_process_lock:
        if http_stopping.is_set():
            raise ValueError("HTTP service stopped")
        process = subprocess.Popen(
            [sys.executable, str(Path(__file__).resolve()), "--http-request"],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
            env=msime_crash_capture.worker_environment())
        http_processes.add(process)
    try:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError("HTTP request deadline exceeded")
        output, _ = process.communicate(metadata, timeout=remaining)
        if process.returncode != 0 or len(output) > max_response_bytes:
            raise ValueError("HTTP request failed")
        return json.loads(output)
    finally:
        if process.poll() is None:
            process.kill()
        process.wait()
        for stream in (process.stdin, process.stdout):
            if stream is not None:
                stream.close()
        with http_process_lock:
            http_processes.discard(process)


def stop_http_requests():
    with http_process_lock:
        http_stopping.set()
        processes = list(http_processes)
    for process in processes:
        if process.poll() is None:
            process.kill()
    for process in processes:
        process.wait()


def http_request_worker():
    try:
        raw = sys.stdin.buffer.read(262145)
        if len(raw) > 262144:
            return 1
        request = json.loads(raw)
        timeout = request.get("timeout")
        if type(timeout) not in (int, float) or not 0 < timeout <= HTTP_WORKER_MAX_TIMEOUT:
            return 1
        connect_timeout = request.get("connect_timeout")
        if connect_timeout is not None and (
                type(connect_timeout) not in (int, float) or not 0 < connect_timeout <= timeout):
            return 1
        limit = request.get("max_response_bytes", 65536)
        if type(limit) is not int or not 0 < limit <= 262144:
            return 1
        # The parent normally enforces the deadline and reaps this worker.
        # Keep a process-local limit too, so a crashed parent cannot leave DNS
        # or a slowly streaming HTTP response running indefinitely. The default
        # signal action terminates even while native code is blocked.
        signal.signal(signal.SIGALRM, signal.SIG_DFL)
        signal.setitimer(signal.ITIMER_REAL, timeout)
        body = request.get("body")
        request["body"] = base64.b64decode(body, validate=True) if body is not None else None
        response = fetch_direct(**request)
        # Validate before emitting; failures never print response text or errors.
        json.loads(response)
        sys.stdout.buffer.write(response)
        return 0
    except Exception:
        return 1


def candidate(text, source):
    if not isinstance(text, str):
        return None
    if any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in text):
        return None
    text = text.strip()
    if not text or len(text.encode()) > 4096:
        return None
    return {"text": text, "source": source}


def cloud(query):
    """只执行 Rust 的描述符；把原始 JSON 交回共享解析器，不在脚本里维护服务协议。"""
    if (query.get("ai_cache_only") or not query.get("cloud_candidates", True) or
            not query.get("cloud_eligible")):
        return None
    descriptor = query.get("cloud_request")
    if not isinstance(descriptor, dict):
        return None
    if isinstance(descriptor.get("cached_response"), str):
        return {"cloud_response": descriptor["cached_response"]}
    url = descriptor.get("url")
    method = descriptor.get("method")
    timeout_ms = descriptor.get("timeout_ms")
    connect_ms = descriptor.get("connect_timeout_ms")
    if (not isinstance(url, str) or not secure_custom_endpoint(url)
            or method not in ("GET", "POST")
            or not isinstance(timeout_ms, int) or not 100 <= timeout_ms <= 10000
            or not isinstance(connect_ms, int) or not 0 < connect_ms <= timeout_ms):
        return None
    body = descriptor.get("body_utf8", "")
    headers = descriptor.get("headers")
    if not isinstance(body, str) or len(body.encode()) > 8192 or not isinstance(headers, dict):
        return None
    result = fetch(url, timeout_ms / 1000,
                   body.encode() if method == "POST" else None,
                   extra_headers=headers, connect_timeout=connect_ms / 1000, max_response_bytes=262144)
    if result is None:
        return None
    return {"cloud_response": json.dumps(result, ensure_ascii=False)}


def ai_prompt(options):
    selected = options.get("prompt_id") or "custom_1"
    if selected not in ("custom_1", "custom_2", "custom_3"):
        return None
    prompt = options.get("prompt_" + selected, "")
    if not isinstance(prompt, str) or len(prompt.encode()) > 8192:
        return None
    # 空白表示「没有自定义」，取 client-providers 回退时用的同一份内置文本。
    return prompt if prompt.strip() else DEFAULT_AI_PROMPT


def select_ai_config(config, query):
    options = query.get("ai_assistant")
    if not isinstance(options, dict) or not options.get("enabled") or not query.get("ai_eligible"):
        return None
    provider = options.get("provider")
    if not isinstance(provider, str):
        return None
    if config.get("provider") == provider:
        return config
    return config.get("profiles", {}).get(provider)


def ai_config_matches(options, config):
    return isinstance(config, dict) and all(
        options.get(key) == config.get(key)
        for key in ("provider", "endpoint", "model"))


OLLAMA_PROVIDER = "ollama"


def ollama_config(options, require_model=True):
    """Ollama 不鉴权：设置页不显示 Token，私有文件里也就没有它的条目。接口地址和模型直接取设置页传来的值，请求不带 Authorization（token 为 None）。

    地址和模型按 load_ai_config 的规则检查：非空字符串、不含控制字符，http 仍只认本机或局域网。值原样使用、不去空白，ai_config_matches 拿设置页的值核对时才对得上。列模型时还没有选模型，`require_model` 为假时模型可以空着。
    """
    if not isinstance(options, dict) or options.get("provider") != OLLAMA_PROVIDER:
        return None
    entry = {"provider": OLLAMA_PROVIDER, "token": None}
    for key in ("endpoint", "model"):
        value = options.get(key, "")
        if not isinstance(value, str) or len(value.encode()) > 4096:
            return None
        if not value.strip() and (key == "endpoint" or require_model):
            return None
        if any(ord(character) < 32 or 127 <= ord(character) <= 159 for character in value):
            return None
        entry[key] = value
    if ai_endpoint_check(entry["endpoint"]) != "allowed":
        return None
    return entry


def credential_cache_fingerprint(value):
    # API 凭据作为 HMAC 密钥，对本进程的随机挑战签名，不创建密码验证器。
    # 长度前缀区分 HMAC 补零后可能相同的密钥，例如空串和一个 NUL。
    key = len(value).to_bytes(4, "big") + value
    return hmac.digest(key, _CREDENTIAL_CACHE_CHALLENGE, "sha256")


def ai_cache_key(query, config):
    options = query.get("ai_assistant")
    segments = query.get("pinyin_segments")
    if (not isinstance(options, dict) or not options.get("enabled") or
            not isinstance(segments, list) or not segments):
        return None
    identity = {}
    for key in ("provider", "endpoint", "model"):
        value = options.get(key)
        if not isinstance(value, str):
            return None
        identity[key] = value
    # Ollama 没有凭据，缓存只按接口、模型和请求内容区分。
    if identity["provider"] != OLLAMA_PROVIDER:
        token = config.get("token") if isinstance(config, dict) else None
        if not isinstance(token, str):
            return None
        # 凭据轮换后不能复用旧答案；内存缓存键只保留本进程的凭据指纹。
        identity["credential_hmac"] = credential_cache_fingerprint(token.encode("utf-8")).hex()
    configured_limit = options.get("candidate_limit", 3)
    identity["candidate_limit"] = (configured_limit
                                    if type(configured_limit) is int and 1 <= configured_limit <= 10
                                    else 3)
    # Prompt settings change the model request, so they partition the cache.
    # Store only digests: custom prompts can contain private text and must not
    # be retained in a cache key. Context changes the model request too, so
    # keep only its digest; session and generation remain excluded so a result
    # survives view refreshes without retaining private text.
    for key in ("prompt_id", "prompt_custom_1", "prompt_custom_2", "prompt_custom_3"):
        value = options.get(key, "")
        if not isinstance(value, str):
            return None
        identity[key + "_sha256"] = hashlib.sha256(value.encode("utf-8")).hexdigest()
    context = query.get("ai_context", "")
    if not isinstance(context, str):
        return None
    identity["ai_context_sha256"] = hashlib.sha256(context.encode("utf-8")).hexdigest()
    identity["pinyin_segments"] = segments
    return json.dumps(identity, ensure_ascii=False, sort_keys=True,
                      separators=(",", ":"))


def configured_ai(query, path, cache=None, cache_lock=None):
    # Do not touch the private file when this query cannot request AI.
    options = query.get("ai_assistant")
    if not query.get("ai_eligible") or not isinstance(options, dict) or not options.get("enabled"):
        return None
    if options.get("provider") == OLLAMA_PROVIDER:
        selected = ollama_config(options)
    elif path:
        selected = select_ai_config(load_ai_config(path), query)
    else:
        return None
    if not ai_config_matches(options, selected):
        return None
    key = ai_cache_key(query, selected)
    if key is not None and cache is not None and cache_lock is not None:
        with cache_lock:
            cached = cache.get(key)
        if cached is not None:
            return [dict(row) for row in cached]
    # Windows AiCandidateWorker shows a cached answer as soon as the input changes and spends the network request only after 650 ms of idle input. Hosts probe with this flag immediately, so a miss here must stay local.
    if query.get("ai_cache_only"):
        return None
    rows = ai(query, selected)
    # Empty and failed responses remain retryable. Bound memory exactly like
    # the Windows worker, clearing the cache before the next insertion.
    if rows and key is not None and cache is not None and cache_lock is not None:
        stored = [dict(row) for row in rows]
        with cache_lock:
            if len(cache) >= MAX_AI_CACHE_ENTRIES:
                cache.clear()
            cache[key] = stored
    return rows


def strip_code_fence(content):
    """去掉包在正文外面的 Markdown 代码块，与 client-providers 的 `strip_code_fence` 一致：不支持 `response_format` 的模型（如经网关调用的 Claude）会把 JSON 写成 ```json ... ```。"""
    trimmed = content.strip()
    if len(trimmed) < 6 or not trimmed.startswith("```") or not trimmed.endswith("```"):
        return trimmed
    fenced = trimmed[3:-3]
    # 第一行是信息串（如 `json`），只有一行时没有信息串。
    return fenced.split("\n", 1)[1] if "\n" in fenced else fenced


def ai(query, config):
    options = query.get("ai_assistant")
    if not query.get("ai_eligible") or not isinstance(options, dict) or not options.get("enabled"):
        return None
    # Bind each credential to its configured endpoint; never send it to a URL
    # supplied by a socket request or an HTTP redirect.
    if not ai_config_matches(options, config):
        return None
    segments = query.get("pinyin_segments")
    context = query.get("ai_context", "")
    limit = options.get("candidate_limit", 3)
    if (not isinstance(segments, list) or not 1 <= len(segments) <= 128 or
        any(not isinstance(s, str) or not s or len(s.encode()) > 32 for s in segments) or
        not isinstance(context, str) or len(context.encode()) > 1024 or
        type(limit) is not int or not 1 <= limit <= 10):
        return None
    prompt = ai_prompt(options)
    if prompt is None:
        return None
    body = {"model": config["model"], "stream": False, "temperature": 0.2,
            "max_tokens": 512, "response_format": {"type": "json_object"},
            "messages": [{"role": "system", "content": prompt},
                         {"role": "user", "content": json.dumps({
                             "segmented_pinyin": segments, "context": context,
                             "candidate_limit": limit, "output_format": "json"},
                             ensure_ascii=False)}]}
    if config["provider"] == "deepseek" or disables_ark_seed_thinking(
            config["provider"], config["endpoint"], config["model"]):
        body["thinking"] = {"type": "disabled"}
    result = fetch(config["endpoint"], AI_REQUEST_TIMEOUT, body, config["token"],
                   connect_timeout=AI_CONNECT_TIMEOUT)
    parsed = json.loads(strip_code_fence(result["choices"][0]["message"]["content"]))
    values = parsed.get("candidates")
    if not isinstance(values, list):
        return None
    rows = []
    seen = set()
    for value in values:
        if not isinstance(value, dict):
            continue
        row = safely(candidate, value.get("text"), 1)
        if row is None or row["text"] in seen:
            continue
        rows.append(row)
        seen.add(row["text"])
        if len(rows) == limit:
            break
    return rows


def safely(call, *args):
    try:
        return call(*args)
    except Exception:
        return None


def translation_direction(text, target):
    if (any(c in string.ascii_letters for c in text) and
        all(c in string.ascii_letters + " -'" for c in text)):
        return "en", "zh"
    # Match Windows translation_gloss.cpp: mixed text containing Han is
    # eligible, but pictographs and emoji sequence components are not.
    has_han = False
    for c in text:
        cp = ord(c)
        if (cp in (0x200D, 0xFE0E, 0xFE0F, 0x20E3) or
            0x2600 <= cp <= 0x27BF or 0x1F000 <= cp <= 0x1FAFF):
            return None
        if (0x3400 <= cp <= 0x4DBF or 0x4E00 <= cp <= 0x9FFF or
            0xF900 <= cp <= 0xFAFF or 0x20000 <= cp <= 0x2CEAF or cp == 0x3007):
            has_han = True
    return ("zh", target) if has_han else None


def translation_gloss(value):
    if not isinstance(value, str):
        return None
    value = value.replace("\t", " ").replace("\r", " ").replace("\n", " ")
    value = " ".join(part for part in value.split(" ") if part)
    return value if candidate(value, 0) and not any(127 <= ord(c) <= 159 for c in value) else None


def ai_translation(text, target, options, path):
    """使用候选栏 AI 的私有配置翻译一个候选词，不把令牌经过 provider socket。"""
    direction = translation_direction(text, target)
    if direction is None or not isinstance(options, dict) or not options.get("enabled"):
        return None
    config = None
    if options.get("provider") == OLLAMA_PROVIDER:
        config = ollama_config(options)
    elif path:
        loaded = load_ai_config(path)
        provider = options.get("provider")
        config = loaded if loaded.get("provider") == provider else loaded.get("profiles", {}).get(provider)
    if not ai_config_matches(options, config):
        return None
    source, destination = direction
    body = {"model": config["model"], "stream": False, "temperature": 0.0,
            "max_tokens": 512, "response_format": {"type": "json_object"},
            "messages": [{"role": "system", "content": DEFAULT_TRANSLATION_PROMPT},
                         {"role": "user", "content": json.dumps({
                             "source_language": source, "target_language": destination,
                             "text": text, "output_format": "json"}, ensure_ascii=False)}]}
    if config["provider"] == "deepseek" or disables_ark_seed_thinking(
            config["provider"], config["endpoint"], config["model"]):
        body["thinking"] = {"type": "disabled"}
    result = fetch(config["endpoint"], AI_REQUEST_TIMEOUT, body, config["token"],
                   connect_timeout=AI_CONNECT_TIMEOUT)
    content = result.get("choices", [{}])[0].get("message", {}).get("content")
    if not isinstance(content, str):
        return None
    value = json.loads(strip_code_fence(content)).get("translation")
    return translation_gloss(value)


def account_translation(texts, source, target, server, deadline):
    """「水杉账号」的一组释义，与 texts 等长；请求、会话和逐项规范化都在 Rust（RustAccountApi.translate）。"""
    rust_account = getattr(server, "rust_account", None)
    values = rust_account.translate(texts, source, target, deadline) if rust_account is not None else None
    return values if isinstance(values, list) and len(values) == len(texts) else [None] * len(texts)


# DeepL 官方 API 的两个主机，与 crates/client-core/src/translation.rs 的 custom_translation_request 一致：Free 密钥（以 :fx 结尾）走 api-free.deepl.com，其余走 api.deepl.com。
DEEPL_PRO_HOST = "api.deepl.com"
DEEPL_FREE_HOST = "api-free.deepl.com"
# DeepL 的 target_lang 中英文要写变体，ZH、EN 只为兼容旧调用保留。
DEEPL_TARGET_LANGUAGES = {"zh": "ZH-HANS", "en": "EN-US"}


def is_deepl_api_endpoint(endpoint):
    """https、默认端口、主机名恰好是 DeepL 官方 API 主机；只看主机名不看路径，自建 DeepLX 的 /v2/translate 不受影响。"""
    try:
        url = urllib.parse.urlsplit(endpoint)
        return (url.scheme == "https" and url.hostname in (DEEPL_PRO_HOST, DEEPL_FREE_HOST) and
                url.port in (None, 443))
    except ValueError:
        return False


def custom_translation_request(config, text, source, target):
    """返回 (url, headers, body)，DeepL 地址没有密钥时返回 None。用例在 shared/contracts/custom-translation/cases.json，与共享 Rust 实现逐条核对。"""
    endpoint = config["endpoint"]
    key = config.get("api_key") or ""
    headers = {"Content-Type": "application/json"}
    if is_deepl_api_endpoint(endpoint):
        if not key:
            return None
        headers["Authorization"] = "DeepL-Auth-Key " + key
        host = DEEPL_FREE_HOST if key.endswith(":fx") else DEEPL_PRO_HOST
        return ("https://" + host + "/v2/translate", headers,
                {"text": [text], "source_lang": source.upper(),
                 "target_lang": DEEPL_TARGET_LANGUAGES.get(target.lower(), target.upper())})
    if key:
        headers["Authorization"] = "Bearer " + key
    return endpoint, headers, {"text": text, "source_lang": source.upper(), "target_lang": target.upper()}


def custom_translation(config, text, source, target, timeout):
    request = custom_translation_request(config, text, source, target)
    if request is None:
        return None
    url, headers, body = request
    result = fetch(url, timeout, body, None, headers)
    if not isinstance(result, dict) or ("code" in result and result["code"] not in (200, "200")):
        return None
    for key in ("data", "translation", "result", "translations"):
        value = result.get(key)
        if isinstance(value, list):
            value = value[0] if value else None
        if isinstance(value, dict):
            value = next((value[k] for k in ("text", "translation", "data")
                          if isinstance(value.get(k), str)), None)
        gloss = translation_gloss(value)
        if gloss:
            return gloss
    return None


# AI 辅助接口地址的传输策略，与 crates/client-providers/src/ai/endpoint.rs 一致：https 不限主机；http 只能指向本机或局域网，公网主机必须走 https，API Token 不能明文经过互联网。不做 DNS 解析，除 localhost 和 .local 以外的域名一律按公网处理。用例在 shared/contracts/ai-endpoint/cases.json，tests/provider/ai_service_contract.py 逐条核对。
AI_LOCAL_NETWORKS = tuple(ipaddress.ip_network(network) for network in (
    "127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16",
    "100.64.0.0/10", "169.254.0.0/16", "::1/128", "fe80::/10", "fc00::/7"))


def ai_endpoint_host_is_local(host, bracketed):
    """`host` 是 urlsplit 给出的主机名（已小写，IPv6 不带方括号）。IP 字面量按地址段判断，只认规范写法；其余按域名处理。"""
    try:
        address = ipaddress.ip_address(host)
    except ValueError:
        if bracketed:
            return False
        return host == "localhost" or (
            host.endswith(".local") and len(host) > len(".local") and not host[:-len(".local")].endswith("."))
    return any(address in network for network in AI_LOCAL_NETWORKS)


def ai_endpoint_check(endpoint):
    """返回 "allowed"、"cleartext_public" 或 "invalid"，含义同 cases.json 的 result。"""
    if (not isinstance(endpoint, str) or not endpoint or len(endpoint.encode("utf-8")) > 2048 or
            any(ord(character) < 32 or 127 <= ord(character) <= 159 for character in endpoint) or
            "#" in endpoint or "\\" in endpoint):
        return "invalid"
    try:
        url = urllib.parse.urlsplit(endpoint)
        # 读 port 同时拒绝格式不对或超过 65535 的端口。
        _ = url.port
    except ValueError:
        return "invalid"
    rest = endpoint.split("://", 1)
    if (url.scheme not in ("http", "https") or len(rest) != 2 or not rest[1] or rest[1].startswith("/") or
            not url.hostname or url.username is not None or url.password is not None or "%" in url.hostname):
        return "invalid"
    bracketed = url.netloc.rsplit("@", 1)[-1].startswith("[")
    if bracketed:
        try:
            ipaddress.IPv6Address(url.hostname)
        except ValueError:
            return "invalid"
    if url.scheme == "https" or ai_endpoint_host_is_local(url.hostname, bracketed):
        return "allowed"
    return "cleartext_public"


def secure_custom_endpoint(endpoint):
    if (not isinstance(endpoint, str) or not endpoint or len(endpoint) > 2048 or
            any(ord(character) < 32 or ord(character) == 127 for character in endpoint)):
        return False
    try:
        url = urllib.parse.urlsplit(endpoint)
        # Reading port also rejects malformed port syntax before a request is built.
        _ = url.port
        return (url.hostname is not None and url.username is None and
                url.password is None and not url.fragment and
                (url.scheme == "https" or
                 (url.scheme == "http" and url.hostname in ("localhost", "127.0.0.1", "::1"))))
    except ValueError:
        return False


def niutrans_translation(config, text, source, target, timeout):
    app_id = config.get("app_id", "")
    apikey = config.get("apikey", "")
    if (not isinstance(app_id, str) or not isinstance(apikey, str) or
        not app_id.strip() or not apikey.strip() or
        len(app_id) > 4096 or len(apikey) > 4096 or
        any(ord(c) < 33 or ord(c) > 126 for c in app_id.strip()) or
        any(ord(c) < 33 or ord(c) > 126 for c in apikey.strip()) or
        app_id.lstrip().startswith(("<", "FAKESECRET_")) or
        apikey.lstrip().startswith(("<", "FAKESECRET_"))):
        return None
    app_id, apikey = app_id.strip(), apikey.strip()
    timestamp = str(int(time.time() * 1000))
    raw = ("apikey=" + apikey + "&appId=" + app_id + "&from=" + source +
           "&srcText=" + text + "&timestamp=" + timestamp + "&to=" + target)
    auth = hashlib.md5(raw.encode("utf-8")).hexdigest()
    body = urllib.parse.urlencode({"from": source, "to": target, "appId": app_id,
                                   "timestamp": timestamp, "srcText": text,
                                   "authStr": auth}).encode("utf-8")
    result = fetch("https://api.niutrans.com/v2/text/translate", timeout,
                   body, extra_headers={"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"})
    if not isinstance(result, dict) or "errorCode" in result or "errorMsg" in result:
        return None
    return translation_gloss(result.get("tgtText"))


def tencent_translation(config, texts, source, target, timeout):
    payload = json.dumps({"Source": source, "Target": target, "ProjectId": 0,
                          "SourceTextList": texts}, ensure_ascii=False, separators=(",", ":")).encode()
    timestamp = int(time.time())
    date = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc).strftime("%Y-%m-%d")
    signed_headers = "content-type;host;x-tc-action"
    canonical = ("POST\n/\n\ncontent-type:application/json; charset=utf-8\n"
                 "host:tmt.tencentcloudapi.com\nx-tc-action:texttranslatebatch\n\n" +
                 signed_headers + "\n" + hashlib.sha256(payload).hexdigest())
    scope = date + "/tmt/tc3_request"
    to_sign = "TC3-HMAC-SHA256\n" + str(timestamp) + "\n" + scope + "\n" + hashlib.sha256(canonical.encode()).hexdigest()
    key = ("TC3" + config["secret_key"]).encode()
    for value in (date, "tmt", "tc3_request"):
        key = hmac.new(key, value.encode(), hashlib.sha256).digest()
    signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
    headers = {"Content-Type": "application/json; charset=utf-8", "Host": "tmt.tencentcloudapi.com",
               "X-TC-Action": "TextTranslateBatch", "X-TC-Timestamp": str(timestamp),
               "X-TC-Version": "2018-03-21", "X-TC-Region": config.get("region") or "ap-guangzhou",
               "Authorization": "TC3-HMAC-SHA256 Credential=" + config["secret_id"] + "/" + scope +
                   ", SignedHeaders=" + signed_headers + ", Signature=" + signature}
    result = fetch("https://tmt.tencentcloudapi.com/", timeout, payload, extra_headers=headers)
    values = result["Response"]["TargetTextList"]
    if not isinstance(values, list):
        return [None] * len(texts)
    # Keep positional correspondence even when the provider returns only part
    # of the batch or an unusable entry, matching Windows TextTranslateBatch.
    return [translation_gloss(values[index]) if index < len(values) else None
            for index in range(len(texts))]


def translations(query, server):
    texts = query.get("candidates")
    target = query.get("target_language", "en")
    sentence = query.get("sentence", False)
    max_text_chars = 512 if sentence else 256
    if (not isinstance(sentence, bool) or not isinstance(texts, list) or
        len(texts) > (1 if sentence else 9) or
        any(not isinstance(text, str) or len(text.encode()) > 4096 for text in texts) or
        target not in ("en", "fr", "ja", "es", "ru", "de", "ko")):
        return []
    niutrans = query.get("niutrans")
    niutrans = niutrans if isinstance(niutrans, dict) and niutrans.get("enabled") else None
    custom = query.get("custom_translation")
    custom = custom if isinstance(custom, dict) and custom.get("enabled") else None
    # Match Windows ActiveProvider/WorkerLoop: only the service the user selected may be asked, and an unusable selection sends nothing rather than falling back to Tencent. A query without the field is malformed and sends nothing.
    selected = query.get("provider")
    account_selected = query.get("translation_account") is True and selected in ("none", "account")
    if account_selected:
        # The shared query marks this only after the user explicitly chose the
        # MSIME account and no user-owned service is usable. Keep that choice
        # visible to this process instead of falling back to Tencent.
        selected = "account"
    if (selected not in ("tencent", "niutrans", "custom", "account", "ai") or
        (selected == "niutrans" and not niutrans) or (selected == "custom" and not custom)):
        return []
    if selected == "account":
        account = getattr(server, "rust_account", None)
        provider = ("account", str(getattr(account, "directory", "")))
    elif selected == "niutrans":
        app_id = niutrans.get("app_id", "")
        apikey = niutrans.get("apikey", "")
        if (not isinstance(app_id, str) or not isinstance(apikey, str) or
            len(app_id) > 4096 or len(apikey) > 4096):
            return []
        app_id, apikey = app_id.strip(), apikey.strip()
        niutrans = {"enabled": True, "app_id": app_id, "apikey": apikey}
        provider = ("niutrans", credential_cache_fingerprint((app_id + "\0" + apikey).encode()))
    elif selected == "custom":
        endpoint = custom.get("endpoint", "")
        if not isinstance(endpoint, str) or len(endpoint) > 2048:
            return []
        endpoint = endpoint.strip(" \t\r\n")
        if not secure_custom_endpoint(endpoint):
            return []
        token = custom.get("api_key", "")
        if not isinstance(token, str) or len(token) > 4096:
            return []
        token = token.strip(" \t\r\n")
        # Match Windows ResolveCustomConfig; use one normalized snapshot for
        # requests in both directions and for cache identity, without editing
        # the incoming query or the user's persisted preferences.
        custom = {**custom, "endpoint": endpoint, "api_key": token}
        # 缓存键不保留凭据，凭据改变时隔离缓存。
        provider = (endpoint, credential_cache_fingerprint(token.encode()))
    elif selected == "ai":
        # options 要在这里先取出来：下面才赋值的话，Python 把它当成还没赋值的局部变量，这一行抛 UnboundLocalError，AI 候选翻译从来没走到请求那一步。
        options = query.get("ai_assistant")
        provider = ("ai", options.get("provider", "") if isinstance(options, dict) else "")
    else:
        # Each request keeps one credential snapshot, including both directions.
        # A removed or invalid file disables Tencent until a valid file is restored.
        path = server.tencent_config_path
        tencent_config = safely(load_tencent_config, path) if path else None
        if not tencent_config:
            return []
        scope = json.dumps(tencent_config, sort_keys=True, separators=(",", ":")).encode()
        provider = ("tencent", credential_cache_fingerprint(scope))
    deadline = time.monotonic() + 6
    if selected == "ai":
        rows = []
        for text in texts:
            if time.monotonic() >= deadline:
                break
            value = safely(ai_translation, text, target, options, server.ai_config_path)
            if value:
                rows.append({"text": text, "translation": value})
        return rows
    found = {}
    groups = {}
    for text in dict.fromkeys(texts):
        direction = (translation_direction(text, target)
                     if 0 < len(text) and len(text) <= max_text_chars else None)
        if direction is None:
            continue
        # 候选释义和 /fy 整句请求的长度上限不同，缓存也要分开，不能让
        # 合法的整句结果绕过较短的候选上限。
        key = (provider, sentence, direction, text)
        with server.translation_lock:
            cached = server.translation_cache.get(key)
        if cached and cached[0] > time.monotonic():
            found[text] = cached[1]
        else:
            groups.setdefault(direction, []).append(text)
    for (source, destination), pending in groups.items():
        if selected == "account":
            values = account_translation(pending, source, destination, server, deadline)
        elif selected == "niutrans":
            values = []
            for text in pending:
                remaining = min(2.5, deadline - time.monotonic())
                values.append(safely(niutrans_translation, niutrans, text, source, destination, remaining)
                              if remaining > 0 else None)
        elif selected == "custom":
            values = []
            for text in pending:
                remaining = min(2.5, deadline - time.monotonic())
                values.append(safely(custom_translation, custom, text, source, destination, remaining)
                              if remaining > 0 else None)
        else:
            remaining = min(2.5, deadline - time.monotonic())
            values = safely(tencent_translation, tencent_config, pending, source, destination, remaining) if remaining > 0 else None
            values = values or [None] * len(pending)
        with server.translation_lock:
            for text, value in zip(pending, values):
                found[text] = value
                if len(server.translation_cache) >= MAX_TRANSLATION_CACHE_ENTRIES:
                    server.translation_cache.pop(next(iter(server.translation_cache)))
                server.translation_cache[(provider, sentence, (source, destination), text)] = (
                    float("inf") if value else
                    time.monotonic() + NEGATIVE_TRANSLATION_CACHE_TTL, value)
    return [{"text": text, "translation": found[text]} for text in dict.fromkeys(texts) if found.get(text)]


def ai_credential_test(config, path):
    if not isinstance(config, dict):
        return False
    provider = config.get("provider")
    if provider == OLLAMA_PROVIDER:
        selected = ollama_config(config)
    elif path and isinstance(provider, str):
        private = load_ai_config(path)
        selected = private if private.get("provider") == provider else private.get("profiles", {}).get(provider)
    else:
        return False
    if (not isinstance(selected, dict) or
            any(config.get(key) != selected.get(key) for key in ("provider", "endpoint", "model"))):
        return False
    body = {"model": selected["model"], "stream": False, "max_tokens": 1,
            "messages": [{"role": "user", "content": "Reply OK"}]}
    if provider == "deepseek" or disables_ark_seed_thinking(provider, selected["endpoint"], selected["model"]):
        body["thinking"] = {"type": "disabled"}
    elif provider == "siliconflow":
        body["enable_thinking"] = False
    result = fetch(selected["endpoint"], 7.0, body, selected["token"])
    # A successful chat probe must contain at least one choice. An empty
    # choices array is a valid JSON error-shaped response from some gateways,
    # but it does not prove that the configured model can answer requests.
    return (isinstance(result, dict) and isinstance(result.get("choices"), list)
            and bool(result["choices"]))


def select_ai_profile(config, path):
    """The private entry matching the settings page's provider, or None.

    Same rule the credential test uses: the settings page names a provider and an
    endpoint, the private file holds the token, and the two have to agree before
    anything goes out. The model is deliberately not compared here - listing the
    models available at an endpoint is how a user finds out what to put in that
    field.
    """
    if not isinstance(config, dict):
        return None
    provider = config.get("provider")
    if provider == OLLAMA_PROVIDER:
        # 没有私有条目，地址和模型就是设置页的值；列模型时模型可以还没选。
        return ollama_config(config, require_model=False)
    if not path or not isinstance(provider, str):
        return None
    private = load_ai_config(path)
    selected = private if private.get("provider") == provider else private.get("profiles", {}).get(provider)
    if (not isinstance(selected, dict) or
            any(config.get(key) != selected.get(key) for key in ("provider", "endpoint"))):
        return None
    return selected


def ai_models_url(endpoint):
    """The model catalogue beside the configured chat endpoint.

    Remove a known operation suffix and append ``/models`` under the same API
    prefix, matching the desktop and mobile hosts. An endpoint of
    ``https://host/openai/v1/chat/completions`` lists at
    ``https://host/openai/v1/models``; a provider whose endpoint is
    ``https://host/chat/completions`` lists at ``https://host/models``.
    """
    parts = urllib.parse.urlsplit(endpoint)
    path = parts.path.rstrip("/")
    for suffix in ("/chat/completions", "/audio/transcriptions"):
        if path.endswith(suffix):
            path = path[: -len(suffix)]
            break
    if not path.endswith("/"):
        path += "/"
    return urllib.parse.urlunsplit((parts.scheme, parts.netloc, path + "models", "", ""))


def ai_models(query, server):
    """List the models the configured AI service offers. Names only."""
    selected = select_ai_profile(query if isinstance(query, dict) else {}, server.ai_config_path)
    if not selected:
        return {"models": []}
    document = fetch(ai_models_url(selected["endpoint"]), 7.0, None, selected["token"])
    if not isinstance(document, dict) or not isinstance(document.get("data"), list):
        return {"models": []}
    models = []
    for entry in document["data"]:
        if not isinstance(entry, dict):
            continue
        name = entry.get("id")
        if (not isinstance(name, str) or not name or len(name) > 256 or
                any(ord(character) < 32 or 127 <= ord(character) <= 159 for character in name) or
                name in models):
            continue
        models.append(name)
        if len(models) == 128:
            break
    return {"models": models}


def ai_polish_test(query, server):
    """Run one polish request through the configured service and return its text.

    The prompt and the sample text come from the settings page; the endpoint,
    model and token come from the private file. Nothing here is cached: this is a
    button the user pressed, not a candidate request.
    """
    query = query if isinstance(query, dict) else {}
    selected = select_ai_profile(query, server.ai_config_path)
    prompt = query.get("prompt", "")
    text = query.get("text")
    if (not selected or not selected.get("model") or selected.get("model") != query.get("model") or
            not isinstance(prompt, str) or len(prompt.encode()) > 8192 or
            not isinstance(text, str) or not text.strip() or len(text.encode()) > 8192):
        return {"text": ""}
    body = {"model": selected["model"], "stream": False, "temperature": 0.2,
            "messages": [{"role": "system", "content": prompt},
                         {"role": "user", "content": text}]}
    if selected["provider"] == "deepseek" or disables_ark_seed_thinking(
            selected["provider"], selected["endpoint"], selected["model"]):
        body["thinking"] = {"type": "disabled"}
    elif selected["provider"] == "siliconflow":
        body["enable_thinking"] = False
    document = fetch(selected["endpoint"], AI_REQUEST_TIMEOUT, body, selected["token"])
    if not isinstance(document, dict) or not isinstance(document.get("choices"), list):
        return {"text": ""}
    for choice in document["choices"]:
        message = choice.get("message") if isinstance(choice, dict) else None
        content = message.get("content") if isinstance(message, dict) else None
        if isinstance(content, str) and content.strip() and len(content.encode()) <= 16384:
            return {"text": content.strip()}
    return {"text": ""}


def credential_test(query, server):
    service = query.get("service")
    config = query.get("config")
    if service not in ("translation.tencent", "translation.niutrans",
                       "translation.custom", "ai.assistant") or not isinstance(config, dict):
        return {"ok": False, "message": "不支持此配置测试。"}
    try:
        if service == "translation.tencent":
            private = load_tencent_config(server.tencent_config_path) if server.tencent_config_path else None
            ok = bool(private and tencent_translation(private, ["hello"], "en", "zh", 7.0)[0])
        elif service == "translation.niutrans":
            ok = bool(niutrans_translation(config, "hello", "en", "zh", 7.0))
        elif service == "translation.custom":
            endpoint = config.get("endpoint")
            token = config.get("api_key", "")
            if (not isinstance(endpoint, str) or not isinstance(token, str) or
                    len(endpoint) > 2048 or len(token) > 4096):
                ok = False
            else:
                endpoint = endpoint.strip(" \t\r\n")
                normalized = {"endpoint": endpoint, "api_key": token.strip(" \t\r\n")}
                ok = bool(secure_custom_endpoint(endpoint) and
                          custom_translation(normalized, "hello", "en", "zh", 7.0))
        else:
            ok = ai_credential_test(config, server.ai_config_path)
    except Exception:
        ok = False
    return {"ok": ok, "message": "连接成功，当前配置有效。" if ok else
            "测试失败，请检查 provider 私有配置、当前选项和网络。"}


def read_request(rfile):
    """Read and parse one request line, or return None when it is truncated or over the limit for its kind.

    The limits count the JSON without its newline, the way client-core checks request.len() before appending the terminator.
    """
    line = rfile.readline(ONLINE_REQUEST_LINE_LIMIT + 2)
    if len(line) - 1 > ONLINE_REQUEST_LINE_LIMIT or not line.endswith(b"\n"):
        return None
    request = json.loads(line)
    if not isinstance(request, dict):
        return None
    limit = {"online": ONLINE_REQUEST_LINE_LIMIT, "ai_test": AI_TEST_REQUEST_LINE_LIMIT}.get(request.get("kind"), REQUEST_LINE_LIMIT)
    if len(line) - 1 > limit:
        return None
    return request


class Handler(socketserver.StreamRequestHandler):
    def handle(self):
        self.request.settimeout(8)
        _, uid, _ = struct.unpack("3i", self.request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
        if uid != os.getuid():
            return
        try:
            request = read_request(self.rfile)
            if request is None:
                return
            query = request["query"]
            if request.get("version") != 1 or not isinstance(query, dict):
                return
            if request.get("kind") == "ai_models":
                self.wfile.write(json.dumps(safely(ai_models, query, self.server) or {"models": []},
                                            ensure_ascii=False).encode() + b"\n")
                return
            if request.get("kind") == "ai_test":
                self.wfile.write(json.dumps(safely(ai_polish_test, query, self.server) or {"text": ""},
                                            ensure_ascii=False).encode() + b"\n")
                return
            if request.get("kind") == "credential_test":
                self.wfile.write(json.dumps(credential_test(query, self.server),
                                            ensure_ascii=False).encode() + b"\n")
                return
            if request.get("kind") == "translation":
                rows = translations(query, self.server)
                self.wfile.write(json.dumps({"translations": rows}, ensure_ascii=False).encode() + b"\n")
                return
            if request.get("kind") != "online":
                return
            # Fetch independently so a failed AI response still preserves cloud.
            with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
                jobs = [pool.submit(safely, cloud, query),
                        pool.submit(safely, configured_ai, query,
                                    self.server.ai_config_path,
                                    self.server.ai_candidate_cache,
                                    self.server.ai_candidate_cache_lock)]
                rows = []
                cloud_response = None
                seen = set()
                for job in jobs:
                    result = job.result()
                    for row in result if isinstance(result, list) else [result]:
                        if row is None:
                            continue
                        if "cloud_response" in row:
                            cloud_response = row["cloud_response"]
                            continue
                        if row["text"] in seen:
                            continue
                        proposed = rows + [row]
                        if len(json.dumps({"candidates": proposed}, ensure_ascii=False).encode()) + 1 > 16384:
                            continue
                        rows.append(row)
                        seen.add(row["text"])
            self.wfile.write(json.dumps({"candidates": rows, "cloud_response": cloud_response}, ensure_ascii=False).encode() + b"\n")
        except Exception:
            pass


class Server(StoppableUnixStreamServer):
    daemon_threads = True
    slots = threading.BoundedSemaphore(4)

    def process_request(self, request, address):
        if not self.slots.acquire(blocking=False):
            self.shutdown_request(request)
            return
        try:
            super().process_request(request, address)
        except Exception:
            self.slots.release()
            raise

    def process_request_thread(self, request, address):
        try:
            super().process_request_thread(request, address)
        finally:
            self.slots.release()

    def handle_error(self, request, address):
        pass


def load_private_config(path):
    descriptor = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC | os.O_NOFOLLOW)
    with os.fdopen(descriptor, "rb") as source:
        info = os.fstat(source.fileno())
        if info.st_uid != os.getuid() or info.st_mode & 0o077 or not stat.S_ISREG(info.st_mode):
            raise ValueError("invalid private configuration")
        raw = source.read(16385)
        after = os.fstat(source.fileno())
        identity = lambda value: (value.st_dev, value.st_ino, value.st_size,
                                  value.st_mtime_ns, value.st_ctime_ns, value.st_mode, value.st_uid)
        if len(raw) > 16384 or identity(info) != identity(after):
            raise ValueError("invalid private configuration")
    config = json.loads(raw.decode("utf-8"))
    if not isinstance(config, dict):
        raise ValueError("invalid private configuration")
    return config


def load_tencent_config(path):
    config = load_private_config(path)
    for key in ("secret_id", "secret_key"):
        value = config.get(key)
        # Match Windows CloudTranslation::TrimSecret for pasted credentials.
        # Normalize before validation, signing and cache-scope construction.
        if isinstance(value, str):
            value = value.strip(" \t\r\n")
        if (not isinstance(value, str) or not value.strip() or
            any(ord(c) < 33 or ord(c) > 126 for c in value) or
            value.startswith(("FAKESECRET_", "<"))):
            raise ValueError("invalid Tencent credential")
        config[key] = value
    region = config.get("region", "")
    if (not isinstance(region, str) or len(region) > 64 or
        any(c not in string.ascii_lowercase + string.digits + "-" for c in region)):
        raise ValueError("invalid Tencent region")
    return {"secret_id": config["secret_id"], "secret_key": config["secret_key"],
            "region": region or "ap-guangzhou"}


def load_ai_config(path):
    config = load_private_config(path)
    profiles = config.get("profiles", {})
    if not isinstance(profiles, dict) or len(profiles) > 16:
        raise ValueError("invalid AI profiles")
    entries = [config] if "provider" in config else []
    for provider, entry in profiles.items():
        if (not isinstance(provider, str) or not provider or len(provider) > 64
                or not isinstance(entry, dict) or entry.get("provider", provider) != provider
                or config.get("provider") == provider):
            raise ValueError("invalid AI profile")
        entry["provider"] = provider
        entries.append(entry)
    if not entries:
        raise ValueError("missing AI configuration")
    for entry in entries:
        if any(not isinstance(entry.get(key), str) or not entry[key].strip()
               for key in ("provider", "endpoint", "model", "token")):
            raise ValueError("invalid AI configuration")
        for key in ("provider", "endpoint", "model"):
            entry[key] = entry[key].strip(" \t\r\n")
        # 设置页保存时把密钥绑在当时的模型上；偏好读出时已把火山方舟的下线模型换成接替模型，这里照同一张表换，ai_config_matches 才对得上，请求也发接替模型。文件不改写。
        if entry["provider"] == "volcengine":
            entry["model"] = (volcengine_successor_model(
                VOLCENGINE_SUCCESSOR_MODELS, entry["endpoint"], entry["model"]) or entry["model"])
        if any(any(ord(character) < 32 or 127 <= ord(character) <= 159
                   for character in entry[key]) for key in ("provider", "endpoint", "model")):
            raise ValueError("invalid AI configuration")
        # Match the shared Windows/client credential policy for pasted tokens:
        # discard surrounding whitespace before validation and every request.
        # Keep interior whitespace untouched so the provider receives exactly
        # the configured secret after normalization.
        token = entry["token"].strip(" \t\r\n")
        entry["token"] = token
        if token.startswith(("<", "FAKESECRET_")) or any(ord(c) < 33 or ord(c) > 126 for c in token):
            raise ValueError("invalid AI credential")
        # 本机和局域网的接口（如 LM Studio）可以用 http，其余只认 https；请求不跟随重定向，局域网的 http 请求不会被转到公网主机。
        if ai_endpoint_check(entry["endpoint"]) != "allowed":
            raise ValueError("invalid AI endpoint")
    return config


def anonymous_server(config_directory):
    config_directory = config_directory.absolute()
    return SimpleNamespace(
        rust_account=RustAccountApi(config_directory),
    )


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("socket", type=Path, nargs="?", help="absolute socket path in a private runtime directory")
    parser.add_argument(
        "--ensure-anonymous-account",
        action="store_true",
        help="create or refresh this user's anonymous translation account, then exit",
    )
    parser.add_argument("--ai-config", type=Path, help="owner-only JSON: provider/endpoint/model/token and optional profiles by provider")
    parser.add_argument("--tencent-config", type=Path, help="owner-only JSON: secret_id, secret_key, optional region")
    parser.add_argument("--config-directory", type=Path,
                        help="absolute directory for optional AI/Tencent config files, read on each request")
    args = parser.parse_args()
    if args.config_directory is None:
        config_root = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
        if not Path(config_root).is_absolute():
            parser.error("config directory must be absolute")
        args.config_directory = Path(config_root) / "msime-client"
    if args.config_directory and not args.config_directory.is_absolute():
        parser.error("config directory must be absolute")
    msime_crash_capture.start("online-provider", preferences=args.config_directory)
    if args.ensure_anonymous_account:
        if args.socket is not None:
            parser.error("--ensure-anonymous-account does not take a socket")
        if not RustAccountApi(args.config_directory).ensure_anonymous():
            parser.error("anonymous account could not be created")
        return
    if args.socket is None:
        parser.error("the following arguments are required: socket")
    if args.ai_config:
        try:
            load_ai_config(args.ai_config)
        except Exception:
            parser.error("AI configuration must be valid owner-only JSON")
    if args.tencent_config:
        try:
            load_tencent_config(args.tencent_config)
        except Exception:
            parser.error("Tencent configuration must be valid owner-only JSON")
    # Explicit files retain startup validation. Directory defaults may be
    # absent or invalid until the user creates or repairs them; each request
    # still uses the existing owner-only configuration readers.
    if args.config_directory:
        args.ai_config = args.ai_config or args.config_directory / "ai-provider.json"
        args.tencent_config = args.tencent_config or args.config_directory / "tencent-provider.json"
    try:
        parent = args.socket.parent.stat()
        if (not args.socket.is_absolute() or parent.st_uid != os.getuid() or
                parent.st_mode & 0o077 or not stat.S_ISDIR(parent.st_mode)):
            raise ValueError()
    except (OSError, ValueError):
        parser.error("socket requires an absolute path in an owner-only directory")
    os.umask(0o077)
    try:
        server, service_lock = open_server(Server, args.socket, Handler)
    except (OSError, ValueError):
        parser.error("online service is already running or its socket cannot be recovered")
    server.ai_config_path = args.ai_config.absolute() if args.ai_config else None
    server.tencent_config_path = args.tencent_config.absolute() if args.tencent_config else None
    account = anonymous_server(args.config_directory) if args.config_directory else None
    server.rust_account = account.rust_account if account else None
    server.translation_cache = {}
    server.translation_lock = threading.Lock()
    server.ai_candidate_cache = {}
    server.ai_candidate_cache_lock = threading.Lock()
    identity = args.socket.stat() if service_lock is not None else None
    try:
        server.serve_until_stopped()
    finally:
        stop_http_requests()
        server.server_close()
        if service_lock is not None:
            try:
                current = args.socket.stat()
                if (current.st_dev, current.st_ino) == (identity.st_dev, identity.st_ino):
                    args.socket.unlink()
            except FileNotFoundError:
                pass
            finally:
                os.close(service_lock)


if __name__ == "__main__":
    if sys.argv[1:] == ["--http-request"]:
        msime_crash_capture.start_worker("online-http")
        sys.exit(http_request_worker())
    main()
