Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(harmony): sync HarmonyOS adaptation from develop_harmony_on_win_0716

yangzequ0e11c8b1fc70
diff --git a/jiuwenswarm/agents/harness/team/team_skill_links.py b/jiuwenswarm/agents/harness/team/team_skill_links.py
index 6283abfddf..04ef779bf5 100644
--- a/jiuwenswarm/agents/harness/team/team_skill_links.py
+++ b/jiuwenswarm/agents/harness/team/team_skill_links.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import logging
import os
+import shutil
import stat
import subprocess
import sys
@@ -120,13 +121,40 @@ def remove_skill_dir_link(target: Path) -> None:
def _create_directory_link(target_path: Path, link_path: Path) -> None:
- """Create a directory link, falling back to a junction on Windows."""
+ """Create a directory link, falling back to a junction on Windows or a copy on sandboxed runtimes."""
try:
os.symlink(str(target_path), str(link_path), target_is_directory=True)
+ return
except OSError as exc:
- if sys.platform != "win32" or getattr(exc, "winerror", None) != ERROR_PRIVILEGE_NOT_HELD:
+ errno = getattr(exc, "errno", None)
+ is_privilege_error = errno in (13, 1) # EACCES/EPERM
+ if sys.platform == "win32" and getattr(exc, "winerror", None) == ERROR_PRIVILEGE_NOT_HELD:
+ _create_windows_junction(target_path, link_path)
+ return
+ if not is_privilege_error:
raise
- _create_windows_junction(target_path, link_path)
+ # Sandboxed runtimes (e.g. HarmonyOS app sandbox) forbid symlink(2)
+ # even inside the app's own filesDir. Fall back to a real copy so
+ # team skill directories remain usable without kernel privileges.
+ logger.info(
+ "[TeamSkillLinks] symlink not permitted (%s); copying %s -> %s",
+ exc, target_path, link_path,
+ )
+ _copy_skill_directory(target_path, link_path)
+
+
+def _copy_skill_directory(target_path: Path, link_path: Path) -> None:
+ """Copy a skill directory as a fallback when symlinks are unavailable."""
+ link_path.parent.mkdir(parents=True, exist_ok=True)
+ if link_path.exists() or os.path.lexists(link_path):
+ return
+ shutil.copytree(
+ str(target_path),
+ str(link_path),
+ symlinks=False,
+ copy_function=shutil.copy2,
+ dirs_exist_ok=False,
+ )
def _create_windows_junction(target_path: Path, link_path: Path) -> None:
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index ff36703b54..38b9829436 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -20,7 +20,12 @@ from dataclasses import dataclass
from typing import Any
from dotenv import load_dotenv
-import psutil
+try:
+ import psutil as _psutil
+ _HAS_PSUTIL = True
+except ImportError:
+ _psutil = None # type: ignore[assignment]
+ _HAS_PSUTIL = False
from openjiuwen.core.common.logging import LogManager
from openjiuwen.core.foundation.llm import Model, ProviderType
from openjiuwen.core.foundation.llm.schema.config import ModelClientConfig, ModelRequestConfig
@@ -403,6 +408,31 @@ def _values_match(parsed_val: Any, resolved_val: Any) -> bool:
)
+def _read_proc_meminfo() -> tuple[float, float, float]:
+ """Fallback for platforms without psutil: read /proc/meminfo.
+
+ Returns (rss_mb, total_mb, available_mb). Returns (0, 0, 0) on failure.
+ """
+ try:
+ info: dict[str, int] = {}
+ with open("/proc/meminfo", "r") as f:
+ for line in f:
+ parts = line.split()
+ if len(parts) >= 2:
+ info[parts[0].rstrip(":")] = int(parts[1]) # kB
+ total_mb = info.get("MemTotal", 0) / 1024
+ available_mb = info.get("MemAvailable", info.get("MemFree", 0)) / 1024
+ # RSS from /proc/self/status
+ with open("/proc/self/status", "r") as f:
+ for line in f:
+ if line.startswith("VmRSS:"):
+ rss_mb = int(line.split()[1]) / 1024 # kB → MB
+ return rss_mb, total_mb, available_mb
+ return 0.0, total_mb, available_mb
+ except OSError:
+ return 0.0, 0.0, 0.0
+
+
def _serialize_reasoning_level(value: Any) -> Any:
if value is None:
return None
@@ -3885,14 +3915,15 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
await channel.send_response(ws, req_id, ok=True, payload={"chrome_path": chrome_path, "headless": headless})
async def _memory_compute(ws, req_id, params, session_id):
+ if _HAS_PSUTIL:
+ process = _psutil.Process() # type: ignore[union-attribute]
+ rss_mb = process.memory_info().rss / (1024 * 1024)
- process = psutil.Process()
- rss_bytes = process.memory_info().rss # 物理内存
- rss_mb = rss_bytes / (1024 * 1024)
-
- mem = psutil.virtual_memory()
- total_mb = mem.total / (1024 * 1024)
- available_mb = mem.available / (1024 * 1024)
+ mem = _psutil.virtual_memory() # type: ignore[union-attribute]
+ total_mb = mem.total / (1024 * 1024)
+ available_mb = mem.available / (1024 * 1024)
+ else:
+ rss_mb, total_mb, available_mb = _read_proc_meminfo()
await channel.send_response(ws, req_id, ok=True,
payload={"rss_mb": rss_mb, "total_mb": total_mb,
diff --git a/pyproject.toml b/pyproject.toml
index 7d7273373f..68cc47f82d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -53,6 +53,41 @@ dependencies = [
]
[project.optional-dependencies]
+# HarmonyOS-compatible reduced dependencies;
+# excludes packages with C extensions or system deps unavailable on HarmonyOS.
+# Usage: pip install jiuwenswarm --no-deps, then install each dep in this group manually,
+# or reference this list in a deployment script / requirements-harmony.txt.
+harmony = [
+ "a2ui-agent-sdk==0.2.1",
+ "ruamel.yaml>=0.18.0",
+ "lark-oapi>=1.5.3",
+ "loguru>=0.7.3",
+ "openjiuwen @ git+https://gitcode.com/openJiuwen/agent-core.git@develop",
+ "pgvector>=0.4.2",
+ "aiosqlite>=0.22.1",
+ "croniter>=2.0.0",
+ "python-telegram-bot>=20.0",
+ "discord.py>=2.4.0",
+ "dingtalk-stream>=0.24.3",
+ "wecom-aibot-sdk>=1.0.5",
+ "python-socks>=2.8.1",
+ "greenlet>=3.3.2",
+ "skillnet-ai==0.0.16",
+ "mutagen>=1.47.0",
+ "google-genai>=1.68.0",
+ "opentelemetry-api>=1.28.0",
+ "opentelemetry-sdk>=1.28.0",
+ "opentelemetry-exporter-otlp-proto-grpc>=1.28.0",
+ "opentelemetry-exporter-otlp-proto-http>=1.28.0",
+ "fastapi>=0.115",
+ "uvicorn[standard]>=0.30",
+ "httptools>=0.6.3",
+ "python-multipart>=0.0.9",
+ "pydantic>=2.0",
+ "pyyaml>=6.0",
+ "httpx[socks]>=0.27",
+ "json-repair>=0.30.0",
+]
a2a = ["a2a-sdk[http-server]==1.0.0"]
desktop = ["pywebview>=5.4"]
dev = ["pyinstaller>=6.0.0", "pywebview>=5.4"]
@@ -132,6 +167,7 @@ default-groups = ['dev']
[tool.uv.sources]
jiuwenswarm-tui = { path = "./packages/jiuwenswarm-tui" }
+openjiuwen = { git = "https://gitcode.com/openJiuwen/agent-core.git", branch = "develop" }
[dependency-groups]
# Testing (keep in sync with optional-dependencies.test)
diff --git a/scripts/build-harmony-hap.sh b/scripts/build-harmony-hap.sh
new file mode 100755
index 0000000000..738d13e8ab
--- /dev/null
+++ b/scripts/build-harmony-hap.sh
@@ -0,0 +1,563 @@
+#!/bin/bash
+# build-harmony-hap.sh — Manual HAP build script for JiuwenSwarm on HarmonyOS
+#
+# This script builds the .hap package WITHOUT DevEco Studio, using only CLI tools.
+# It performs the complete 5-stage build pipeline:
+# Stage 1: Resource compilation (restool)
+# Stage 2: ETS/ArkTS compilation (es2abc via ets-loader)
+# Stage 3: Native C++ NAPI compilation (cmake+ninja)
+# Stage 4: HAP packing (ohos_packing_tool)
+# Stage 5: HAP signing (hap-sign-tool with debug certificates)
+#
+# Usage:
+# ./scripts/build-harmony-hap.sh
+# ./scripts/build-harmony-hap.sh --skip-ets # Skip ETS compilation (debug only)
+# ./scripts/build-harmony-hap.sh --skip-sign # Skip signing (produce unsigned HAP)
+#
+# Prerequisites:
+# - All CLI tools in /data/service/hnp/bin/
+# - OHOS SDK at /data/service/hnp/ohos-sdk.org/ohos-sdk_26.0.0.18/
+# - HNP package at harmony_facade/hnp/arm64-v8a/jiuwen.hnp
+# - build-harmony.sh already executed (frontend + HNP + rawfile prepared)
+
+set -euo pipefail
+
+# ─── Configuration ───
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+JIUWENSWARM_REPO="$(cd "$SCRIPT_DIR/.." && pwd)"
+HARMONY_PROJECT="${JIUWENSWARM_REPO}/../harmony_facade"
+BUILD_DIR="$HOME/yangzequ/harmony_hap_build"
+SDK_ROOT="/data/service/hnp/ohos-sdk.org/ohos-sdk_26.0.0.18/ohos"
+HNPCLI="/data/service/hnp/bin/hnpcli"
+RESTOOL="/data/service/hnp/bin/restool"
+ES2ABC="${SDK_ROOT}/ets/build-tools/ets-loader/bin/ark/build/bin/es2abc"
+ETS_LOADER="${SDK_ROOT}/ets/build-tools/ets-loader"
+CMAKE="/data/service/hnp/bin/cmake"
+NINJA="/data/service/hnp/bin/ninja"
+PACK_TOOL="/data/service/hnp/bin/ohos_packing_tool"
+SIGN_TOOL="/data/service/hnp/bin/hap-sign-tool"
+LLVM_ROOT="${SDK_ROOT}/native/llvm"
+NATIVE_SYSROOT="${SDK_ROOT}/native/sysroot"
+NODE="/data/service/hnp/bin/node"
+
+BUNDLE_NAME="com.openjiuwen.harmony_facade"
+MODULE_NAME="entry"
+
+# Debug signing constants
+DEBUG_KEY_ALIAS="jiuwenswarm-debug-key"
+DEBUG_KEYSTORE_PWD="123456"
+DEBUG_KEYSTORE="$BUILD_DIR/debug-keystore.p12"
+DEBUG_APP_CERT="$BUILD_DIR/debug-app-cert.cer"
+DEBUG_PROFILE="$BUILD_DIR/debug-profile.p7b"
+SDK_P12="${SDK_ROOT}/toolchains/lib/OpenHarmony.p12"
+SDK_PROFILE_PEM="${SDK_ROOT}/toolchains/lib/OpenHarmonyProfileDebug.pem"
+SDK_APP_PEM="${SDK_ROOT}/toolchains/lib/OpenHarmonyApplication.pem"
+SDK_PROFILE_TEMPLATE="${SDK_ROOT}/toolchains/lib/UnsgnedDebugProfileTemplate.json"
+
+# Parse arguments
+SKIP_ETS=false
+SKIP_SIGN=false
+SKIP_CPP=false
+for arg in "$@"; do
+ case "$arg" in
+ --skip-ets) SKIP_ETS=true ;;
+ --skip-sign) SKIP_SIGN=true ;;
+ --skip-cpp) SKIP_CPP=true ;;
+ --help)
+ echo "Usage: $0 [--skip-ets] [--skip-sign] [--skip-cpp]"
+ exit 0
+ ;;
+ esac
+done
+
+echo "============================================"
+echo " JiuwenSwarm 鸿蒙 .hap 手动构建脚本"
+echo "============================================"
+echo ""
+echo "项目: $HARMONY_PROJECT"
+echo "构建目录: $BUILD_DIR"
+echo "SDK: $SDK_ROOT"
+echo ""
+
+# ─── Clean and create build directory ───
+rm -rf "$BUILD_DIR"
+mkdir -p "$BUILD_DIR"
+
+# ─── Helper: Convert JSON5 to JSON using Node.js ───
+json5_to_json() {
+ local srcfile="$1"
+ local destfile="$2"
+ # Use Node.js to parse JSON5 and convert to standard JSON
+ # Write converter script to temp file to avoid bash variable conflicts
+ local converter="$BUILD_DIR/json5_converter.js"
+ cat > "$converter" << 'JSEOF'
+const fs = require('fs');
+const srcFile = process.argv[2];
+const destFile = process.argv[3];
+let content = fs.readFileSync(srcFile, 'utf8');
+// Remove single-line comments (but not URLs like http://)
+content = content.replace(/\/\/[^:]*$/gm, '');
+// Remove multi-line comments
+content = content.replace(/\/\*[\s\S]*?\*\//g, '');
+// Remove trailing commas before } or ]
+content = content.replace(/,\s*([\]}])/g, '$1');
+// Try to parse as JSON, fallback to eval for JSON5
+try {
+ const obj = JSON.parse(content);
+ fs.writeFileSync(destFile, JSON.stringify(obj, null, 2));
+ console.log('JSON5 parsed as JSON successfully');
+} catch(e) {
+ try {
+ // JSON5 allows unquoted keys, trailing commas, etc.
+ const obj = (new Function('return ' + content))();
+ fs.writeFileSync(destFile, JSON.stringify(obj, null, 2));
+ console.log('JSON5 parsed via eval successfully');
+ } catch(e2) {
+ console.error('Failed to parse JSON5: ' + e2.message);
+ process.exit(1);
+ }
+}
+JSEOF
+ node "$converter" "$srcfile" "$destfile" 2>&1 || {
+ echo "ERROR: Failed to convert JSON5: $srcfile"
+ exit 1
+ }
+}
+
+# ═══════════════════════════════════════════════
+# Stage 1: Resource Compilation (restool)
+# ═══════════════════════════════════════════════
+echo "=== Stage 1: Resource Compilation (restool) ==="
+
+# 1a: Convert module.json5 to module.json
+json5_to_json "$HARMONY_PROJECT/entry/src/main/module.json5" "$BUILD_DIR/module.json"
+echo "✅ module.json5 → module.json"
+
+# 1b: Convert app.json5 to app.json
+json5_to_json "$HARMONY_PROJECT/AppScope/app.json5" "$BUILD_DIR/app.json"
+echo "✅ app.json5 → app.json"
+
+# 1c: Generate placeholder ResourceTable header for restool
+mkdir -p "$BUILD_DIR/entry/resources"
+# restool needs a ResourceTable.h path via -r flag. Create empty placeholder.
+# The actual ResourceTable.h will be generated by restool itself.
+RES_HEADER="$BUILD_DIR/ResourceTable.h"
+touch "$RES_HEADER"
+
+$RESTOOL \
+-i "$HARMONY_PROJECT/entry/src/main/resources" \
+-p "${BUNDLE_NAME}.${MODULE_NAME}" \
+-j "$BUILD_DIR/module.json" \
+-o "$BUILD_DIR/entry/resources" \
+-r "$RES_HEADER" \
+--ids "$BUILD_DIR/entry/resources/id_defined.json" \
+-f \
+2>&1 || {
+echo "ERROR: restool failed for entry resources"
+exit 1
+}
+echo "✅ Entry resources compiled"
+
+# 1d: Compile app-level resources
+mkdir -p "$BUILD_DIR/app/resources"
+APP_RES_HEADER="$BUILD_DIR/app/ResourceTable.h"
+touch "$APP_RES_HEADER"
+
+$RESTOOL \
+-i "$HARMONY_PROJECT/AppScope/resources" \
+-p "${BUNDLE_NAME}" \
+-o "$BUILD_DIR/app/resources" \
+-r "$APP_RES_HEADER" \
+--ids "$BUILD_DIR/app/resources/id_defined.json" \
+-f \
+2>&1 || {
+echo "ERROR: restool failed for app resources"
+exit 1
+}
+echo "✅ App-level resources compiled"
+
+echo ""
+
+# ═══════════════════════════════════════════════
+# Stage 2: ETS/ArkTS Compilation
+# ═══════════════════════════════════════════════
+if [ "$SKIP_ETS" = "true" ]; then
+ echo "=== Stage 2: ETS/ArkTS Compilation [SKIPPED] ==="
+ echo "⚠️ Skipping ETS compilation. The HAP will NOT have working UI!"
+ echo " This is only for testing the build pipeline."
+ echo ""
+ # Create placeholder ets directory
+ mkdir -p "$BUILD_DIR/entry/ets"
+else
+ echo "=== Stage 2: ETS/ArkTS Compilation ==="
+
+ # Set up environment for ets-loader
+ export aceModuleRoot="$HARMONY_PROJECT/entry/src/main/ets"
+ export aceModuleBuild="$BUILD_DIR/entry/ets"
+ export aceModuleJsonPath="$BUILD_DIR/module.json"
+ export compileMode="esmodule"
+ export aceCompileMode="moduleJson"
+ export buildArkMode="debug"
+ export cachePath="$BUILD_DIR/cache"
+ export sdkInfo="ohos-sdk_26"
+ export panda="$ES2ABC"
+ export NODE_OPTIONS="--expose-gc"
+ export projectRoot="$HARMONY_PROJECT"
+ export pathToResource="$BUILD_DIR/entry/resources"
+ export resourceTable="$BUILD_DIR/entry/resources/ResourceTable.index"
+
+ mkdir -p "$BUILD_DIR/cache" "$BUILD_DIR/entry/ets"
+
+ # Try to use ets-loader via rollup
+ cd "$ETS_LOADER"
+
+ # Check if node_modules are installed
+ if [ ! -d "$ETS_LOADER/node_modules" ]; then
+ echo "⚠️ ets-loader node_modules not found. Installing..."
+ npm install 2>&1 || {
+ echo "ERROR: Failed to install ets-loader dependencies"
+ echo "Falling back to --skip-ets mode"
+ SKIP_ETS=true
+ mkdir -p "$BUILD_DIR/entry/ets"
+ }
+ fi
+
+ if [ "$SKIP_ETS" = "false" ]; then
+ node "$ETS_LOADER/main.js" 2>&1 || {
+ echo "ERROR: ets-loader compilation failed"
+ echo "Falling back to --skip-ets mode"
+ SKIP_ETS=true
+ mkdir -p "$BUILD_DIR/entry/ets"
+ }
+ fi
+
+ if [ "$SKIP_ETS" = "false" ]; then
+ echo "✅ ETS/ArkTS compiled to .abc bytecode"
+ fi
+
+ cd "$JIUWENSWARM_REPO"
+ echo ""
+fi
+
+# ═══════════════════════════════════════════════
+# Stage 3: Native C++ NAPI Compilation
+# ═══════════════════════════════════════════════
+if [ "$SKIP_CPP" = "true" ]; then
+ echo "=== Stage 3: Native C++ NAPI Compilation [SKIPPED] ==="
+ echo ""
+else
+ echo "=== Stage 3: Native C++ NAPI Compilation ==="
+
+ # 3a: Generate OHOS cross-compilation toolchain file
+ cat > "$BUILD_DIR/ohos-toolchain.cmake" << 'EOF_CMAKE'
+set(CMAKE_SYSTEM_NAME OHOS)
+set(CMAKE_SYSTEM_PROCESSOR aarch64)
+set(CMAKE_C_COMPILER /data/service/hnp/ohos-sdk.org/ohos-sdk_26.0.0.18/ohos/native/llvm/bin/clang)
+set(CMAKE_CXX_COMPILER /data/service/hnp/ohos-sdk.org/ohos-sdk_26.0.0.18/ohos/native/llvm/bin/clang++)
+set(CMAKE_AR /data/service/hnp/ohos-sdk.org/ohos-sdk_26.0.0.18/ohos/native/llvm/bin/llvm-ar)
+set(CMAKE_RANLIB /data/service/hnp/ohos-sdk.org/ohos-sdk_26.0.0.18/ohos/native/llvm/bin/llvm-ranlib)
+set(CMAKE_LINKER /data/service/hnp/ohos-sdk.org/ohos-sdk_26.0.0.18/ohos/native/llvm/bin/ld.lld)
+set(CMAKE_SYSROOT /data/service/hnp/ohos-sdk.org/ohos-sdk_26.0.0.18/ohos/native/sysroot)
+set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
+set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
+set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
+set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
+# OHOS-specific flags
+set(CMAKE_C_FLAGS "--target=aarch64-linux-ohos -fdata-sections -ffunction-sections -funwind-tables -fno-rtti" CACHE STRING "" FORCE)
+set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -fno-exceptions -frtti" CACHE STRING "" FORCE)
+set(CMAKE_SHARED_LINKER_FLAGS "--target=aarch64-linux-ohos -Wl,--gc-sections -Wl,--build-id=sha1" CACHE STRING "" FORCE)
+EOF_CMAKE
+
+ echo "✅ OHOS toolchain file generated"
+
+ # 3b: Run cmake
+ mkdir -p "$BUILD_DIR/cpp-build"
+ $CMAKE \
+ -G Ninja \
+ -DCMAKE_TOOLCHAIN_FILE="$BUILD_DIR/ohos-toolchain.cmake" \
+ -DCMAKE_BUILD_TYPE=Debug \
+ -S "$HARMONY_PROJECT/entry/src/main/cpp" \
+ -B "$BUILD_DIR/cpp-build" \
+ 2>&1 || {
+ echo "ERROR: cmake configuration failed"
+ exit 1
+ }
+ echo "✅ cmake configured"
+
+ # 3c: Build with ninja
+ $NINJA -C "$BUILD_DIR/cpp-build" 2>&1 || {
+ echo "ERROR: ninja build failed"
+ exit 1
+ }
+ echo "✅ libjiuwenswarm_native.so built"
+
+ # Verify output
+ SO_FILE="$BUILD_DIR/cpp-build/libjiuwenswarm_native.so"
+ if [ ! -f "$SO_FILE" ]; then
+ echo "ERROR: .so file not found at expected path"
+ find "$BUILD_DIR/cpp-build" -name "*.so" 2>/dev/null
+ exit 1
+ fi
+ echo " .so size: $(du -sh "$SO_FILE" | cut -f1)"
+ echo ""
+fi
+
+# ═══════════════════════════════════════════════
+# Stage 4: HAP Packing
+# ═══════════════════════════════════════════════
+echo "=== Stage 4: HAP Packing ==="
+
+# Prepare the rawfile directory (copy harmony_entry.py)
+RAWFILE_DIR="$BUILD_DIR/entry/resources/rawfile"
+mkdir -p "$RAWFILE_DIR"
+
+# Copy harmony_entry.py to rawfile
+ENTRY_SCRIPT="$JIUWENSWARM_REPO/scripts/harmony_entry.py"
+if [ -f "$ENTRY_SCRIPT" ]; then
+ cp "$ENTRY_SCRIPT" "$RAWFILE_DIR/"
+ echo "✅ harmony_entry.py copied to rawfile"
+fi
+
+# Copy HNP package if available
+HNP_FILE="$HARMONY_PROJECT/hnp/arm64-v8a/jiuwen.hnp"
+if [ -f "$HNP_FILE" ]; then
+ echo "✅ HNP package available: $(du -sh "$HNP_FILE" | cut -f1)"
+fi
+
+# Prepare lib directory for the .so
+LIB_DIR="$BUILD_DIR/libs/arm64-v8a"
+mkdir -p "$LIB_DIR"
+if [ "$SKIP_CPP" = "false" ]; then
+ cp "$BUILD_DIR/cpp-build/libjiuwenswarm_native.so" "$LIB_DIR/"
+ echo "✅ libjiuwenswarm_native.so copied to libs/"
+fi
+
+# Pack HAP using ohos_packing_tool
+UNSIGNED_HAP="$BUILD_DIR/entry-default-unsigned.hap"
+
+$PACK_TOOL pack \
+ --mode hap \
+ --json-path "$BUILD_DIR/module.json" \
+ --ets-path "$BUILD_DIR/entry/ets" \
+ --res-path "$BUILD_DIR/entry/resources" \
+ --index-path "$BUILD_DIR/entry/resources/resources.index" \
+ --lib-path "$LIB_DIR" \
+ --out-path "$UNSIGNED_HAP"
+ 2>&1 || {
+ echo "ERROR: HAP packing failed"
+ echo "Trying alternative packing method (manual zip)..."
+
+ # Alternative: manual zip packing
+ # HAP is a zip file with specific structure
+ cd "$BUILD_DIR"
+
+ # Create HAP structure
+ HAP_DIR="$BUILD_DIR/hap_contents"
+ mkdir -p "$HAP_DIR"
+
+ # Copy module.json
+ cp "$BUILD_DIR/module.json" "$HAP_DIR/module.json"
+
+ # Copy resources
+ cp -a "$BUILD_DIR/entry/resources/"* "$HAP_DIR/" 2>/dev/null || true
+
+ # Copy ets bytecode
+ if [ -d "$BUILD_DIR/entry/ets" ]; then
+ mkdir -p "$HAP_DIR/ets"
+ cp -a "$BUILD_DIR/entry/ets/"* "$HAP_DIR/ets/" 2>/dev/null || true
+ fi
+
+ # Copy libs
+ if [ -d "$LIB_DIR" ] && [ "$(ls -A "$LIB_DIR")" ]; then
+ cp -a "$LIB_DIR" "$HAP_DIR/libs/" 2>/dev/null || true
+ fi
+
+ # Pack as zip (HAP format)
+ cd "$HAP_DIR"
+ zip -r "$UNSIGNED_HAP" . 2>&1 || {
+ echo "ERROR: Manual zip packing failed"
+ exit 1
+ }
+
+ echo "✅ HAP packed manually (zip method)"
+ }
+
+if [ -f "$UNSIGNED_HAP" ]; then
+ echo "✅ Unsigned HAP created: $UNSIGNED_HAP"
+ echo " HAP size: $(du -sh "$UNSIGNED_HAP" | cut -f1)"
+fi
+
+echo ""
+
+# ═══════════════════════════════════════════════
+# Stage 5: HAP Signing
+# ═══════════════════════════════════════════════
+if [ "$SKIP_SIGN" = "true" ]; then
+ echo "=== Stage 5: HAP Signing [SKIPPED] ==="
+ echo "⚠️ Unsigned HAP: $UNSIGNED_HAP"
+ echo " The HAP cannot be installed without signing."
+ echo ""
+else
+ echo "=== Stage 5: HAP Signing (debug) ==="
+
+ SIGNED_HAP="$BUILD_DIR/entry-default-signed.hap"
+
+ # 5a: Generate debug keystore
+ $SIGN_TOOL generate-keypair \
+ -keyAlias "$DEBUG_KEY_ALIAS" \
+ -keyAlg ECC \
+ -keySize NIST-P-256 \
+ -keystoreFile "$DEBUG_KEYSTORE" \
+ -keystorePwd "$DEBUG_KEYSTORE_PWD" \
+ 2>&1 || {
+ echo "ERROR: Debug keystore generation failed"
+ echo "Falling back to --skip-sign mode"
+ SKIP_SIGN=true
+ }
+
+ if [ "$SKIP_SIGN" = "false" ]; then
+ echo "✅ Debug keystore generated"
+
+ # 5b: Generate debug app certificate
+ $SIGN_TOOL generate-app-cert \
+ -keyAlias "$DEBUG_KEY_ALIAS" \
+ -issuerKeyAlias "oh-app-sign-debug-srv-ca-key-v1" \
+ -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Application Debug Signature Service CA" \
+ -subject "C=CN,O=openjiuwen,OU=OpenJiuwen,CN=JiuwenSwarm Debug" \
+ -signAlg SHA256withECDSA \
+ -keystoreFile "$SDK_P12" \
+ -keystorePwd "123456" \
+ -outFile "$DEBUG_APP_CERT" \
+ -outForm cert \
+ 2>&1 || {
+ echo "ERROR: Debug app certificate generation failed"
+ echo "Falling back to --skip-sign mode"
+ SKIP_SIGN=true
+ }
+ fi
+
+ if [ "$SKIP_SIGN" = "false" ]; then
+ echo "✅ Debug app certificate generated"
+
+ # 5c: Create and sign debug profile
+ # Modify the debug profile template for our bundle
+ if [ -f "$SDK_PROFILE_TEMPLATE" ]; then
+ # Copy and modify the template
+ cp "$SDK_PROFILE_TEMPLATE" "$BUILD_DIR/UnsgnedDebugProfileTemplate-modified.json"
+ # Replace bundle-name and add ACL permissions
+ node -e "
+ const fs = require('fs');
+ const template = JSON.parse(fs.readFileSync('$BUILD_DIR/UnsgnedDebugProfileTemplate-modified.json', 'utf8'));
+ template['bundle-name'] = '${BUNDLE_NAME}';
+ // Add ACL permissions for native code execution
+ if (template['acl']) {
+ template['acl']['allow-apex'] = true;
+ }
+ fs.writeFileSync('$BUILD_DIR/UnsgnedDebugProfileTemplate-modified.json', JSON.stringify(template, null, 2));
+ " 2>&1 || echo "⚠️ Profile template modification may have issues"
+ else
+ echo "⚠️ Debug profile template not found at: $SDK_PROFILE_TEMPLATE"
+ echo " Creating minimal profile..."
+ # Create a minimal debug profile
+ cat > "$BUILD_DIR/UnsgnedDebugProfileTemplate-modified.json" << 'EOF_PROFILE'
+{
+ "bundle-name": "com.openjiuwen.harmony_facade",
+ "developer-id": "OpenHarmony",
+ "development-cert": "",
+ "distribution-certificate": "",
+ "app-distribution-type": "debugging",
+ "debug-info": {
+ "device-ids": ["*"]
+ },
+ "feature-flags": {
+ "allow-apex": true
+ },
+ "permissions": {
+ "restricted-permissions": {}
+ }
+}
+EOF_PROFILE
+ fi
+
+ $SIGN_TOOL sign-profile \
+ -mode localSign \
+ -keyAlias "oh-profile-key-v1" \
+ -profileCertFile "$SDK_PROFILE_PEM" \
+ -inFile "$BUILD_DIR/UnsgnedDebugProfileTemplate-modified.json" \
+ -signAlg SHA256withECDSA \
+ -keystoreFile "$SDK_P12" \
+ -keystorePwd "123456" \
+ -outFile "$DEBUG_PROFILE" \
+ 2>&1 || {
+ echo "ERROR: Debug profile signing failed"
+ echo "Falling back to --skip-sign mode"
+ SKIP_SIGN=true
+ }
+ fi
+
+ if [ "$SKIP_SIGN" = "false" ]; then
+ echo "✅ Debug profile signed"
+
+ # 5d: Sign the HAP
+ $SIGN_TOOL sign-app \
+ -mode localSign \
+ -keyAlias "$DEBUG_KEY_ALIAS" \
+ -appCertFile "$DEBUG_APP_CERT" \
+ -profileFile "$DEBUG_PROFILE" \
+ -inFile "$UNSIGNED_HAP" \
+ -signAlg SHA256withECDSA \
+ -keystoreFile "$DEBUG_KEYSTORE" \
+ -keystorePwd "$DEBUG_KEYSTORE_PWD" \
+ -outFile "$SIGNED_HAP" \
+ -compatibleVersion 12 \
+ 2>&1 || {
+ echo "ERROR: HAP signing failed"
+ echo "Falling back to --skip-sign mode"
+ SKIP_SIGN=true
+ }
+ fi
+
+ if [ "$SKIP_SIGN" = "false" ]; then
+ echo "✅ Signed HAP created: $SIGNED_HAP"
+ echo " HAP size: $(du -sh "$SIGNED_HAP" | cut -f1)"
+ else
+ echo "⚠️ Unsigned HAP only: $UNSIGNED_HAP"
+ echo " The HAP cannot be installed without signing."
+ fi
+
+ echo ""
+fi
+
+# ═══════════════════════════════════════════════
+# Final Output
+# ═══════════════════════════════════════════════
+echo "============================================"
+echo " 构建完成!"
+echo "============================================"
+echo ""
+
+FINAL_HAP="$SIGNED_HAP"
+if [ "$SKIP_SIGN" = "true" ]; then
+ FINAL_HAP="$UNSIGNED_HAP"
+fi
+
+if [ -f "$FINAL_HAP" ]; then
+ echo "✅ 构建产物: $FINAL_HAP"
+ echo " 大小: $(du -sh "$FINAL_HAP" | cut -f1)"
+ echo ""
+ echo "安装方式:"
+ echo " 方式 1 (hdc): hdc install $FINAL_HAP"
+ echo " 方式 2 (手动): 将 .hap 复制到设备后通过 bm install 安装"
+ echo ""
+ if [ "$SKIP_ETS" = "true" ]; then
+ echo "⚠️ 注意: 此 HAP 缺少 ETS 编译产物,UI 将无法正常工作!"
+ echo " 需要安装 DevEco Studio 进行完整 ETS 编译。"
+ fi
+else
+ echo "❌ 构建失败 — 未生成 .hap 文件"
+ echo " 请检查上方错误信息"
+fi
+
+echo ""
+echo "构建目录: $BUILD_DIR"
+echo "清理: rm -rf $BUILD_DIR"
diff --git a/scripts/build-harmony.sh b/scripts/build-harmony.sh
new file mode 100755
index 0000000000..1ef46214a1
--- /dev/null
+++ b/scripts/build-harmony.sh
@@ -0,0 +1,216 @@
+#!/bin/bash
+# build-harmony.sh — JiuwenSwarm 鸿蒙应用打包脚本
+#
+# 与 Windows build-exe.ps1 对照:
+# Windows: uv sync → npm build → PyInstaller → Inno Setup
+# 鸿蒙: npm build → HNP 更新(嵌入前端) → rawfile 准备 → hvigorw 构建 .hap
+#
+# 用法:
+# ./scripts/build-harmony.sh
+# ./scripts/build-harmony.sh # 默认主方案
+# HARMONY_FALLBACK=true ./scripts/build-harmony.sh # Fallback 方案(rawfile 前端)
+#
+# 前置条件:
+# - 在鸿蒙 PC (aarch64-linux-ohos) 上运行
+# - hnpcli 可用 (/data/service/hnp/bin/hnpcli)
+# - Node.js / npm 可用
+# - DevEco Studio 或 hvigorw 可用(步骤4可选手动执行)
+# - ~/yangzequ/jiuwenswarm_hnp 目录存在(HNP 工作目录)
+
+set -euo pipefail
+
+# ─── 配置区 ───
+JIUWENSWARM_REPO="$(cd "$(dirname "$0")/.." && pwd)"
+FRONTEND_DIR="${JIUWENSWARM_REPO}/jiuwenswarm/channels/web/frontend"
+HNP_WORK_DIR="$HOME/yangzequ/jiuwenswarm_hnp"
+HNP_OUTPUT_DIR="$HOME/yangzequ"
+HNPCLI="/data/service/hnp/bin/hnpcli"
+HARMONY_PROJECT="${JIUWENSWARM_REPO}/../harmony_facade"
+RAWFILE_DIR="${HARMONY_PROJECT}/entry/src/main/resources/rawfile"
+HNP_DEST_DIR="${HARMONY_PROJECT}/hnp/arm64-v8a"
+HNP_NAME="jiuwen"
+HNP_VERSION="1.0"
+
+# 默认端口配置(与 harmony_entry.py 一致)
+DEFAULT_AGENTSERVER_PORT=18092
+DEFAULT_GATEWAY_PORT=19000
+DEFAULT_FRONTEND_PORT=5173
+
+# Fallback 模式检测
+FALLBACK_MODE="${HARMONY_FALLBACK:-false}"
+
+echo "============================================"
+echo " JiuwenSwarm 鸿蒙应用打包脚本"
+echo "============================================"
+if [ "$FALLBACK_MODE" = "true" ]; then
+ echo " ⚠️ Fallback 模式(rawfile 前端 + WebSocket 远程连接)"
+fi
+echo ""
+
+# ─── [1/4] 构建 Web 前端 ───
+echo "=== [1/4] 构建 Web 前端 ==="
+
+if [ ! -d "$FRONTEND_DIR" ]; then
+ echo "错误: 前端目录不存在: $FRONTEND_DIR"
+ exit 1
+fi
+
+cd "$FRONTEND_DIR"
+
+# 清理旧产物
+rm -rf dist
+
+# 安装依赖
+npm install
+
+# 构建(Fallback 模式使用 harmony mode:相对路径 + 动态 WS/API URL)
+if [ "$FALLBACK_MODE" = "true" ]; then
+ echo "⚠️ 使用 Fallback 模式构建前端 (harmony mode: relative paths + dynamic URLs)"
+ npm run build -- --mode harmony
+else
+ npm run build
+fi
+
+# 验证构建产物
+if [ ! -d "dist" ] || [ -z "$(ls -A dist)" ]; then
+ echo "错误: 前端构建失败,dist 目录为空"
+ echo "请检查 npm install 和 npm run build 的输出"
+ exit 1
+fi
+
+echo "✅ 前端构建完成: dist/ 目录已生成"
+echo " 产物大小: $(du -sh dist | cut -f1)"
+echo ""
+
+# ─── [2/4] 更新 HNP 包(嵌入前端 dist) ───
+echo "=== [2/4] 更新 HNP 包(嵌入前端 dist) ==="
+
+if [ ! -d "$HNP_WORK_DIR" ]; then
+ echo "错误: HNP 工作目录不存在: $HNP_WORK_DIR"
+ echo "请先完成 HNP 基础打包(参考 .pi/specs/hnp-packaging-plan.md)"
+ exit 1
+fi
+
+# 检查 HNP 工作目录中是否有 jiuwenswarm 包
+JWS_PKG_DIR="${HNP_WORK_DIR}/lib/python3.12/site-packages/jiuwenswarm"
+if [ ! -d "$JWS_PKG_DIR" ]; then
+ echo "错误: HNP 中未找到 jiuwenswarm 包: $JWS_PKG_DIR"
+ exit 1
+fi
+
+# 拷贝 frontend/dist 到 HNP 的 jiuwenswarm 包内
+FRONTEND_DIST_DEST="${JWS_PKG_DIR}/channels/web/frontend/dist"
+echo "目标路径: $FRONTEND_DIST_DEST"
+
+# 清理旧的 dist(如果存在)
+rm -rf "$FRONTEND_DIST_DEST"
+
+# 拷贝新的 dist
+mkdir -p "$FRONTEND_DIST_DEST"
+cp -a "${FRONTEND_DIR}/dist/"* "$FRONTEND_DIST_DEST/"
+
+# 验证拷贝
+if [ ! -d "$FRONTEND_DIST_DEST" ] || [ -z "$(ls -A "$FRONTEND_DIST_DEST")" ]; then
+ echo "错误: 前端产物拷贝到 HNP 失败"
+ exit 1
+fi
+
+echo "✅ 前端 dist 已嵌入 HNP 包"
+echo ""
+
+# 清理缓存(减小体积)
+echo "清理 HNP 包内缓存..."
+find "$HNP_WORK_DIR" -name '__pycache__' -type d -exec rm -rf {} + 2>/dev/null || true
+find "$HNP_WORK_DIR" -name '*.pyc' -delete 2>/dev/null || true
+find "$HNP_WORK_DIR" -name '*.pyo' -delete 2>/dev/null || true
+
+# 设置权限
+chmod -R 777 "$HNP_WORK_DIR"
+
+echo ""
+
+# 重新打包 HNP
+echo "重新打包 HNP..."
+if [ ! -f "$HNPCLI" ]; then
+ echo "错误: hnpcli 不存在: $HNPCLI"
+ echo "请安装 hnpcli 或确认路径"
+ exit 1
+fi
+
+"$HNPCLI" pack -i "$HNP_WORK_DIR" -o "$HNP_OUTPUT_DIR" -n "$HNP_NAME" -v "$HNP_VERSION"
+
+# 验证 HNP 包
+HNP_FILE="${HNP_OUTPUT_DIR}/${HNP_NAME}.hnp"
+if [ ! -f "$HNP_FILE" ]; then
+ echo "错误: HNP 包生成失败"
+ exit 1
+fi
+
+echo "✅ HNP 包已生成: $HNP_FILE"
+echo " 包大小: $(du -sh "$HNP_FILE" | cut -f1)"
+echo ""
+
+# 复制 HNP 包到鸿蒙项目
+echo "复制 HNP 包到鸿蒙项目..."
+mkdir -p "$HNP_DEST_DIR"
+cp "$HNP_FILE" "$HNP_DEST_DIR/"
+
+echo "✅ HNP 包已复制到: $HNP_DEST_DIR/$(basename "$HNP_FILE")"
+echo ""
+
+# ─── [3/4] 准备 rawfile ───
+echo "=== [3/4] 准备 rawfile ==="
+
+# 复制 harmony_entry.py 到 rawfile
+ENTRY_SCRIPT="${JIUWENSWARM_REPO}/scripts/harmony_entry.py"
+if [ ! -f "$ENTRY_SCRIPT" ]; then
+ echo "错误: harmony_entry.py 不存在: $ENTRY_SCRIPT"
+ echo "请先创建该脚本"
+ exit 1
+fi
+
+mkdir -p "$RAWFILE_DIR"
+cp "$ENTRY_SCRIPT" "$RAWFILE_DIR/"
+
+echo "✅ harmony_entry.py 已复制到 rawfile"
+
+# Fallback 模式:将前端 dist 也复制到 rawfile
+if [ "$FALLBACK_MODE" = "true" ]; then
+ echo "复制前端 dist 到 rawfile (Fallback 模式)..."
+ cp -a "${FRONTEND_DIR}/dist/"* "$RAWFILE_DIR/"
+ echo "✅ 前端 dist 已复制到 rawfile"
+fi
+
+echo ""
+
+# ─── [4/4] 构建鸿蒙 .hap ───
+echo "=== [4/4] 构建鸿蒙 .hap ==="
+echo ""
+echo "⚠️ 此步骤需要在 DevEco Studio 中手动执行,或通过 hvigorw 命令行执行。"
+echo ""
+echo "请在 DevEco Studio 中打开项目:"
+echo " 项目路径: $HARMONY_PROJECT"
+echo ""
+echo "然后执行:"
+echo " 1. File → Project Structure → Signing Configs → 配置签名证书"
+echo " 2. Build → Build Hap(s)/APP(s)"
+echo ""
+echo "或者通过命令行:"
+echo " cd $HARMONY_PROJECT"
+echo " ./hvigorw assembleHap --mode module -p module=entry@default"
+echo ""
+echo "构建产物位置:"
+echo " $HARMONY_PROJECT/entry/build/default/outputs/default/entry-default-signed.hap"
+echo ""
+echo "============================================"
+echo " 打包脚本执行完成!"
+echo "============================================"
+echo ""
+echo "下一步:"
+echo " 1. 在 DevEco Studio 中打开项目并构建"
+echo " 2. 连接鸿蒙 PC 设备"
+echo " 3. 点击 Run 安装并启动应用"
+echo ""
+echo "端口配置: AgentServer=${DEFAULT_AGENTSERVER_PORT} / Gateway=${DEFAULT_GATEWAY_PORT} / Frontend=${DEFAULT_FRONTEND_PORT}"
+echo ""
+echo "使用指南: .pi/specs/harmony-app-usage-guide.md"
diff --git a/scripts/harmony_entry.py b/scripts/harmony_entry.py
new file mode 100644
index 0000000000..9087bc77d7
--- /dev/null
+++ b/scripts/harmony_entry.py
@@ -0,0 +1,364 @@
+#!/usr/bin/env python3
+"""HarmonyOS entry point for JiuwenSwarm services.
+
+This script is the single orchestrator for all JiuwenSwarm services on HarmonyOS,
+similar to the Windows desktop entry (jiuwenswarm_exe_entry.py).
+
+It:
+1. Sets up environment for HarmonyOS sandbox
+2. Initializes workspace
+3. Starts AgentServer subprocess (port 18092)
+4. Starts Gateway subprocess (port 19000)
+5. Starts Web frontend service subprocess (port 5173)
+6. Waits for TCP ports to be ready
+7. Prints HARMONY_READY:url signal to stdout
+8. Monitors subprocesses
+9. On SIGTERM, terminates children and exits
+
+Output protocol (printed to stdout for ArkTS to parse):
+ HARMONY_STARTING:<service> — service is starting
+ HARMONY_PORT_READY:<service>:<port> — TCP port is ready
+ HARMONY_READY:http://localhost:<port> — all services ready, WebView URL
+ HARMONY_SERVICE_EXIT:<service>:<pid>:exitcode=<code> — a child service exited
+ HARMONY_ERROR:<message> — startup failure
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import signal
+import subprocess
+import time
+import socket
+import argparse
+from pathlib import Path
+
+# ─── Constants ───
+DEFAULT_AGENTSERVER_PORT = 18092
+DEFAULT_GATEWAY_PORT = 19000
+DEFAULT_FRONTEND_PORT = 5173
+PORT_CHECK_TIMEOUT = 120 # seconds to wait for each port
+PORT_CHECK_INTERVAL = 2 # seconds between checks
+SERVICE_MONITOR_INTERVAL = 5 # seconds between health checks
+
+
+def check_tcp_port(host: str, port: int) -> bool:
+ """Check if a TCP port is accepting connections."""
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(3)
+ s.connect((host, port))
+ return True
+ except (ConnectionRefusedError, socket.timeout, OSError):
+ return False
+
+
+def wait_for_tcp_port(host: str, port: int, timeout: int = PORT_CHECK_TIMEOUT,
+ interval: int = PORT_CHECK_INTERVAL, service_name: str = "") -> bool:
+ """Wait for a TCP port to become available, with progress output."""
+ start = time.time()
+ while time.time() - start < timeout:
+ if check_tcp_port(host, port):
+ print(f"HARMONY_PORT_READY:{service_name}:{port}")
+ sys.stdout.flush()
+ return True
+ time.sleep(interval)
+ return False
+
+
+def find_free_port(start_port: int) -> int:
+ """Find a free TCP port starting from start_port."""
+ for port in range(start_port, start_port + 100):
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind(('127.0.0.1', port))
+ return port
+ except OSError:
+ continue
+ return start_port # fallback
+
+
+# ─── Global state ───
+children: list[subprocess.Popen] = []
+service_names: dict[int, str] = {} # pid → service name
+
+
+def start_service(module_path: str, args: list[str], service_name: str) -> subprocess.Popen:
+ """Start a JiuwenSwarm Python service as a subprocess."""
+ cmd = [sys.executable, "-m", module_path] + args
+ print(f"HARMONY_STARTING:{service_name}")
+ sys.stdout.flush()
+
+ child_env = os.environ.copy()
+ child_env["PYTHONUNBUFFERED"] = "1"
+ proc = subprocess.Popen(
+ cmd,
+ stdout=None,
+ stderr=None,
+ env=child_env,
+ )
+ children.append(proc)
+ service_names[proc.pid] = service_name
+ return proc
+
+
+def handle_sigterm(signum: int, frame) -> None:
+ """SIGTERM handler: terminate all child processes gracefully."""
+ print("HARMONY_SHUTDOWN:received SIGTERM")
+ sys.stdout.flush()
+
+ for child in children:
+ try:
+ child.terminate()
+ except OSError:
+ pass
+
+ # Wait for children to exit (with timeout)
+ for child in children:
+ try:
+ child.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ try:
+ child.kill()
+ child.wait(timeout=2)
+ except OSError:
+ pass
+
+ sys.exit(0)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(
+ prog="jiuwenswarm-harmony",
+ description="JiuwenSwarm HarmonyOS service orchestrator",
+ )
+ parser.add_argument("--agentserver-port", type=int, default=DEFAULT_AGENTSERVER_PORT,
+ help=f"AgentServer TCP port (default: {DEFAULT_AGENTSERVER_PORT})")
+ parser.add_argument("--gateway-port", type=int, default=DEFAULT_GATEWAY_PORT,
+ help=f"Gateway TCP port (default: {DEFAULT_GATEWAY_PORT})")
+ parser.add_argument("--frontend-port", type=int, default=DEFAULT_FRONTEND_PORT,
+ help=f"Web frontend TCP port (default: {DEFAULT_FRONTEND_PORT})")
+ parser.add_argument("--auto-port", action="store_true",
+ help="Automatically find free ports if defaults are occupied")
+ parser.add_argument("--no-frontend", action="store_true",
+ help="Skip Web frontend service (fallback mode: rawfile frontend)")
+ parser.add_argument("--dotenv", type=str, default=None,
+ help="Path to .env file for configuration")
+ args = parser.parse_args()
+
+ # ─── Environment setup ───
+ home_dir = os.environ.get("JIUWENSWARM_HOME", os.environ.get("JWS_HOME", os.environ.get("HOME", "/storage/Users/currentUser")))
+ os.environ["HOME"] = home_dir
+ os.environ.setdefault("JIUWENSWARM_HOME", home_dir)
+
+ # Ensure UTF-8 encoding
+ os.environ.setdefault("PYTHONIOENCODING", "utf-8")
+ os.environ.setdefault("PYTHONUTF8", "1")
+
+ # ─── SSL CA certificates (HarmonyOS lacks system CA store) ───
+ # HarmonyOS has no /etc/ssl/certs/ (verified empty on-device), so Python's
+ # ssl module falls back to an empty CA bundle and rejects every chain's
+ # root CA as "self-signed certificate in certificate chain". Force-load
+ # certifi's cacert.pem so Lark/requests/httpx can verify feishu.cn etc.
+ # Use setdefault so an explicit value from .env still wins.
+ try:
+ import certifi
+ _cacert = certifi.where()
+ os.environ.setdefault("SSL_CERT_FILE", _cacert)
+ os.environ.setdefault("REQUESTS_CA_BUNDLE", _cacert)
+ os.environ.setdefault("CURL_CA_BUNDLE", _cacert)
+ print(f"HARMONY_INFO:ssl_ca_cert:{_cacert}")
+ sys.stdout.flush()
+ except ImportError:
+ print("HARMONY_WARN:certifi_not_found:ssl_ca_cert_not_set")
+ sys.stdout.flush()
+
+ # ─── dotenv parsing (before jiuwenswarm imports) ───
+ if args.dotenv:
+ dotenv_path = Path(args.dotenv)
+ if dotenv_path.exists():
+ try:
+ from dotenv import load_dotenv
+ load_dotenv(dotenv_path=dotenv_path, override=True)
+ except ImportError:
+ # Manual dotenv loading fallback
+ with open(dotenv_path) as f:
+ for line in f:
+ line = line.strip()
+ if not line or line.startswith("#"):
+ continue
+ key, _, value = line.partition("=")
+ key = key.strip()
+ value = value.strip().strip('"').strip("'")
+ os.environ[key] = value
+
+ # ─── Workspace initialization ───
+ print("HARMONY_STARTING:workspace")
+ sys.stdout.flush()
+
+ try:
+ from jiuwenswarm.common.utils import get_user_workspace_dir, prepare_workspace
+ workspace = get_user_workspace_dir()
+ config_path = workspace / "config" / "config.yaml"
+ if not config_path.exists():
+ print("HARMONY_STARTING:workspace_init")
+ sys.stdout.flush()
+ prepare_workspace(overwrite=False)
+ except Exception as e:
+ print(f"HARMONY_ERROR:workspace_init_failed:{e}")
+ sys.stdout.flush()
+ # Don't exit — services may still work with defaults
+
+ # ─── Port allocation ───
+ agentserver_port = args.agentserver_port
+ gateway_port = args.gateway_port
+ frontend_port = args.frontend_port
+
+ if args.auto_port:
+ if not check_tcp_port("127.0.0.1", agentserver_port):
+ agentserver_port = find_free_port(agentserver_port + 1)
+ print(f"HARMONY_INFO:auto_port:agentserver:{agentserver_port}")
+ if not check_tcp_port("127.0.0.1", gateway_port):
+ gateway_port = find_free_port(gateway_port + 1)
+ print(f"HARMONY_INFO:auto_port:gateway:{gateway_port}")
+ if not check_tcp_port("127.0.0.1", frontend_port):
+ frontend_port = find_free_port(frontend_port + 1)
+ print(f"HARMONY_INFO:auto_port:frontend:{frontend_port}")
+
+ # Set port environment variables for subprocesses
+ os.environ["AGENT_SERVER_PORT"] = str(agentserver_port)
+ os.environ.setdefault("JIUWENSWARM_START_MODE", "all")
+
+ # ─── Start AgentServer (port 18092) ───
+ agentserver_args = []
+ if args.dotenv:
+ agentserver_args.extend(["--dotenv", args.dotenv])
+
+ agentserver_proc = start_service(
+ "jiuwenswarm.server.app_agentserver",
+ agentserver_args,
+ "agentserver",
+ )
+
+ # ─── Wait for AgentServer port ───
+ print("HARMONY_STARTING:agentserver_wait")
+ sys.stdout.flush()
+ time.sleep(3) # Give AgentServer time to initialize
+
+ # ─── Start Gateway (port 19000) ───
+ gateway_args = []
+ if args.dotenv:
+ gateway_args.extend(["--dotenv", args.dotenv])
+
+ gateway_proc = start_service(
+ "jiuwenswarm.gateway.app_gateway",
+ gateway_args,
+ "gateway",
+ )
+
+ # ─── Wait for Gateway port ───
+ gateway_ready = wait_for_tcp_port(
+ "127.0.0.1", gateway_port,
+ timeout=PORT_CHECK_TIMEOUT,
+ interval=PORT_CHECK_INTERVAL,
+ service_name="gateway",
+ )
+
+ if not gateway_ready:
+ print(f"HARMONY_ERROR:gateway_port_timeout:{gateway_port}")
+ sys.stdout.flush()
+ if args.auto_port:
+ gateway_port = find_free_port(gateway_port + 1)
+ gateway_ready = wait_for_tcp_port(
+ "127.0.0.1", gateway_port,
+ timeout=30,
+ service_name="gateway_alt",
+ )
+ if not gateway_ready:
+ print("HARMONY_ERROR:startup_failed:gateway_not_ready")
+ sys.stdout.flush()
+ # Clean up started processes
+ for child in children:
+ if child.poll() is None:
+ child.terminate()
+ sys.exit(1)
+
+ # ─── Start Web frontend service (port 5173) ───
+ if not args.no_frontend:
+ frontend_args = []
+ if args.dotenv:
+ frontend_args.extend(["--dotenv", args.dotenv])
+
+ frontend_proc = start_service(
+ "jiuwenswarm.channels.web.app_web",
+ frontend_args,
+ "frontend",
+ )
+
+ # ─── Wait for frontend port ───
+ frontend_ready = wait_for_tcp_port(
+ "127.0.0.1", frontend_port,
+ timeout=PORT_CHECK_TIMEOUT,
+ interval=PORT_CHECK_INTERVAL,
+ service_name="frontend",
+ )
+
+ if not frontend_ready:
+ print(f"HARMONY_ERROR:frontend_port_timeout:{frontend_port}")
+ sys.stdout.flush()
+ if args.auto_port:
+ frontend_port = find_free_port(frontend_port + 1)
+ frontend_ready = wait_for_tcp_port(
+ "127.0.0.1", frontend_port,
+ timeout=30,
+ service_name="frontend_alt",
+ )
+ if not frontend_ready:
+ print("HARMONY_ERROR:startup_failed:frontend_not_ready")
+ sys.stdout.flush()
+ for child in children:
+ if child.poll() is None:
+ child.terminate()
+ sys.exit(1)
+
+ # ─── Signal readiness (frontend URL) ───
+ service_url = f"http://localhost:{frontend_port}"
+ else:
+ # Fallback mode: frontend loaded from rawfile, no frontend service needed
+ # Gateway serves API + WebSocket
+ service_url = f"http://localhost:{gateway_port}"
+ print("HARMONY_INFO:fallback_mode:no_frontend_service")
+
+ print(f"HARMONY_READY:{service_url}")
+ sys.stdout.flush()
+
+ # ─── Register SIGTERM handler ───
+ signal.signal(signal.SIGTERM, handle_sigterm)
+
+ # ─── Monitor subprocesses ───
+ while True:
+ for child in children:
+ ret = child.poll()
+ if ret is not None:
+ name = service_names.get(child.pid, "unknown")
+ print(f"HARMONY_SERVICE_EXIT:{name}:{child.pid}:exitcode={ret}")
+ sys.stdout.flush()
+
+ # If a critical service exits, terminate everything
+ if name in ("agentserver", "gateway", "frontend"):
+ print(f"HARMONY_ERROR:critical_service_exit:{name}")
+ sys.stdout.flush()
+ for other in children:
+ if other.poll() is None:
+ try:
+ other.terminate()
+ except OSError:
+ pass
+ sys.exit(1)
+
+ time.sleep(SERVICE_MONITOR_INTERVAL)
+
+
+if __name__ == "__main__":
+ main()