#!/usr/bin/env python3 import argparse import getpass import os from pathlib import Path import sys FIELDS = ( ("DATABASE_URL", "DobotAI PostgreSQL 连接串", "DobotAI独立数据库,不得填写WeKnora数据库。", "postgres://USER:<数据库密码>@127.0.0.1:55432/dobotai_test?sslmode=disable", True), ("WEKNORA_BASE_URL", "WeKnora 地址", "容器通过宿主网络访问测试WeKnora。", "http://127.0.0.1:8080", False), ("WEKNORA_API_KEY", "WeKnora API Key", "在WeKnora中为DobotAI创建的API密钥。", "<你的WeKnora API Key>", True), ("DOBOTAI_INGRESS_TOKEN", "DobotAI Ingress Token", "调用 /v1/qa 时使用的独立长随机令牌。", "<随机长字符串>", True), ("DOBOTAI_TENANT_KEY", "DobotAI 租户键", "必须与现有DobotAI数据和Agent绑定使用同一个租户键。", "dobotai-test", False), ("DOBOTAI_AGENT_BINDINGS", "DobotAI Agent Bindings JSON", "钉钉会话匹配到WeKnora Agent的映射。", '{"dingtalk:*":"你的Agent ID"}', False), ("DINGTALK_CLIENT_ID", "钉钉 Client ID", "钉钉应用的Client ID/AppKey。", "dingxxxxxxxx", False), ("DINGTALK_CLIENT_SECRET", "钉钉 Client Secret", "钉钉应用的Client Secret/AppSecret。", "<你的钉钉 AppSecret>", True), ) def parse_env(path: Path): lines = path.read_text(encoding="utf-8").splitlines() values = {} for line in lines: if line and not line.lstrip().startswith("#") and "=" in line: key, value = line.split("=", 1) values[key.strip()] = value return lines, values def prompt(label: str, description: str, example: str, secret: bool, configured: bool) -> str: suffix = "(已配置,直接回车保留)" if configured else "(必填)" print(f"\n{label}\n用途:{description}\n格式示例:{example}") if secret: return getpass.getpass(f"{label}{suffix}: ").strip() return input(f"{label}{suffix}: ").strip() def write_env(path: Path, lines, values): rendered = [] written = set() for line in lines: if line and not line.lstrip().startswith("#") and "=" in line: key = line.split("=", 1)[0].strip() if key in values: rendered.append(f"{key}={values[key]}") written.add(key) continue rendered.append(line) for key, value in values.items(): if key not in written: rendered.append(f"{key}={value}") temporary = path.with_name(path.name + ".new") temporary.write_text("\n".join(rendered) + "\n", encoding="utf-8") os.chmod(temporary,0o600) os.replace(temporary, path) def main(): parser = argparse.ArgumentParser(description="配置 DobotAI 容器运行环境") parser.add_argument("--env-file", required=True) parser.add_argument("--start-script", required=True) args = parser.parse_args() env_file = Path(args.env_file) if not env_file.is_file(): raise SystemExit("DobotAI 环境文件不存在,请先完成部署。") lines, values = parse_env(env_file) for key, label, description, example, secret in FIELDS: entered = prompt(label, description, example, secret, bool(values.get(key, "").strip())) if entered: values[key] = entered missing = [label for key, label, _, _, _ in FIELDS if not values.get(key, "").strip()] if missing: raise SystemExit("以下必填项未配置:" + "、".join(missing)) write_env(env_file, lines, values) os.execv(args.start_script, [args.start_script]) if __name__ == "__main__": try: main() except KeyboardInterrupt: sys.exit(130)