update
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
"""Prepare a local PMS bridge without printing credentials or touching business databases."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
|
||||
@@ -11,6 +13,31 @@ sys.path.insert(0, str(PLATFORM_ROOT))
|
||||
from app.core.config import get_settings # noqa: E402
|
||||
|
||||
|
||||
def update_connection(content: str, base_url: str, key: str) -> str:
|
||||
"""Update only the connection keys, preserving other assistant settings and comments."""
|
||||
newline = "\r\n" if "\r\n" in content else "\n"
|
||||
if content and not content.endswith("\n"):
|
||||
content += newline
|
||||
sections = list(re.finditer(
|
||||
r"(?m)^assistant:[ \t]*(?:#[^\r\n]*)?\r?\n(?:(?:[ \t]+[^\r\n]*|[ \t]*)\r?\n)*",
|
||||
content,
|
||||
))
|
||||
if len(sections) > 1:
|
||||
raise ValueError("application.yml contains multiple assistant sections")
|
||||
block = sections[0].group() if sections else "assistant:" + newline
|
||||
for name, value in (("base-url", base_url), ("shared-secret", key)):
|
||||
pattern = r"(?m)^ " + re.escape(name) + r":[^\r\n]*(\r?\n)"
|
||||
replacement = " " + name + ": " + json.dumps(value) + newline
|
||||
block, count = re.subn(pattern, lambda _: replacement, block)
|
||||
if count > 1:
|
||||
raise ValueError("application.yml contains duplicate assistant." + name)
|
||||
if count == 0:
|
||||
block = block.rstrip("\r\n") + newline + replacement
|
||||
if sections:
|
||||
return content[:sections[0].start()] + block + content[sections[0].end():]
|
||||
return content.rstrip() + newline * 2 + block
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--pms-root", required=True, type=Path)
|
||||
@@ -25,14 +52,16 @@ def main() -> None:
|
||||
key = secrets.token_urlsafe(48)
|
||||
env_path = PLATFORM_ROOT / ".env"
|
||||
content = env_path.read_text(encoding="utf-8") if env_path.exists() else ""
|
||||
import re
|
||||
content = re.sub(r"(?m)^\s*WORK_ASSISTANT_SHARED_SECRET\s*=.*(?:\r?\n|$)", "", content)
|
||||
env_path.write_text(content.rstrip() + "\nWORK_ASSISTANT_SHARED_SECRET=" + key + "\n", encoding="utf-8")
|
||||
config = pms_root / ".work-assistant.properties"
|
||||
content = "assistant.base-url=" + args.base_url + "\nassistant.shared-secret=" + key + "\n"
|
||||
# Properties use ASCII; no real credential is ever committed or printed.
|
||||
config.write_text(content, encoding="ascii")
|
||||
print("Local assistant bridge configured. Credentials are stored only in ignored local files.")
|
||||
yaml_config = pms_root / "ruoyi-admin/src/main/resources/application.yml"
|
||||
with yaml_config.open(encoding="utf-8", newline="") as stream:
|
||||
content = stream.read()
|
||||
content = update_connection(content, args.base_url, key)
|
||||
with yaml_config.open("w", encoding="utf-8", newline="") as stream:
|
||||
stream.write(content)
|
||||
print("Assistant endpoint and credential written to application.yml; other settings preserved.")
|
||||
print("Credential not printed.")
|
||||
print("No business database migration is required.")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Build a standalone assistant deployment archive without requiring local Docker."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tarfile
|
||||
|
||||
from dotenv import dotenv_values
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CONFIG_PREFIXES = ("WORK_ASSISTANT_", "DIRECT_LLM_", "OPENCLAW_", "HERMES_")
|
||||
|
||||
|
||||
def runtime_config(root: Path) -> bytes:
|
||||
# Export only the bridge/model settings, not business DB credentials or the
|
||||
# unrelated full-platform API keys. Preserve the current shared secret.
|
||||
values = dotenv_values(root / ".env", encoding="utf-8")
|
||||
secret = values.get("WORK_ASSISTANT_SHARED_SECRET") or ""
|
||||
if len(secret.strip()) < 32:
|
||||
raise ValueError("请先在项目 .env 配置有效的 WORK_ASSISTANT_SHARED_SECRET(至少 32 字符)。")
|
||||
selected = {key: value for key, value in values.items()
|
||||
if key == "MODEL_PROVIDER" or key.startswith(CONFIG_PREFIXES)}
|
||||
selected.pop("WORK_ASSISTANT_STATE_URL", None) # Container path is in compose.yml.
|
||||
lines = ["# Initial assistant configuration. The deploy script preserves assistant.env."]
|
||||
for key, value in sorted(selected.items()):
|
||||
if value is not None:
|
||||
# Mount this dotenv file directly: Compose does not interpolate its
|
||||
# secrets. JSON quoting matches python-dotenv double-quoted strings.
|
||||
lines.append(f"{key}={json.dumps(value, ensure_ascii=False)}")
|
||||
return ("\n".join(lines) + "\n").encode("utf-8")
|
||||
|
||||
|
||||
def add_bytes(archive: tarfile.TarFile, name: str, data: bytes, mode: int = 0o644) -> None:
|
||||
item = tarfile.TarInfo(name)
|
||||
item.size = len(data)
|
||||
item.mode = mode
|
||||
archive.addfile(item, io.BytesIO(data))
|
||||
|
||||
|
||||
def build_package(root: Path, output: Path, version: str) -> Path:
|
||||
config = runtime_config(root)
|
||||
deployment = root / "deploy" / "assistant"
|
||||
source = io.BytesIO()
|
||||
with tarfile.open(fileobj=source, mode="w:gz") as archive:
|
||||
for path in sorted((root / "app").rglob("*")):
|
||||
if "__pycache__" in path.parts or path.suffix not in {".py", ".json"}:
|
||||
continue
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise ValueError(f"无法打包源文件:{path.relative_to(root)}")
|
||||
add_bytes(archive, path.relative_to(root).as_posix(), path.read_bytes())
|
||||
add_bytes(archive, "requirements.txt", (root / "requirements.txt").read_bytes())
|
||||
add_bytes(archive, "Dockerfile", (deployment / "Dockerfile").read_bytes())
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
target = output / f"company-ai-assistant-{version}.tar.gz"
|
||||
# Exclusive creation prevents accidentally replacing an existing release.
|
||||
with target.open("xb") as handle:
|
||||
with tarfile.open(fileobj=handle, mode="w:gz") as archive:
|
||||
for name in ("compose.yml", "deploy.sh", "README.txt"):
|
||||
data = (deployment / name).read_bytes().replace(b"\r\n", b"\n")
|
||||
add_bytes(archive, name, data, 0o755 if name == "deploy.sh" else 0o644)
|
||||
add_bytes(archive, "VERSION", (version + "\n").encode("ascii"))
|
||||
add_bytes(archive, "assistant.env.initial", config, 0o600)
|
||||
add_bytes(archive, "image-source.tar.gz", source.getvalue())
|
||||
checksum = hashlib.sha256(target.read_bytes()).hexdigest()
|
||||
target.with_name(target.name + ".sha256").write_text(
|
||||
f"{checksum} {target.name}\n", encoding="ascii")
|
||||
return target
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "dist")
|
||||
args = parser.parse_args()
|
||||
package = build_package(ROOT, args.output.resolve(), datetime.now().strftime("%Y%m%d-%H%M%S"))
|
||||
print(f"部署包已生成:{package}")
|
||||
print(f"大小:{package.stat().st_size / 1024 / 1024:.2f} MiB;旁边附有 SHA-256 校验文件。")
|
||||
print("上传并解压后执行 bash deploy.sh;更新时仍执行同一命令。")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user