源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Creator App Tests / PR Spam Gate (push) Skipped
Frontend Tests / PR Spam Gate (push) Skipped
NPM Format (website & console) / PR Spam Gate (push) Skipped
Pre-commit Checks / PR Spam Gate (push) Skipped
QwenPaw Creator Plugin Release / check-version (push) Canceled after 0s
QwenPaw Creator Plugin Release / upload-oss (push) Canceled after 0s
Tests / PR Spam Gate (push) Skipped
CodeQL / CodeQL (python) (push) Canceled after 0s
CodeQL / CodeQL (typescript) (push) Canceled after 0s
Creator App Tests / Creator Backend Tests (push) Canceled after 0s
Creator App Tests / Creator UI Build & Tests (push) Canceled after 0s
E2E Smoke Tests / Playwright UI Smoke (push) Canceled after 0s
Frontend Tests / Detect console changes (push) Canceled after 0s
NPM Format (website & console) / website format check (push) Canceled after 0s
NPM Format (website & console) / console format check (push) Canceled after 0s
Pre-commit Checks / Pre-commit (push) Canceled after 0s
QwenPaw Data Plugin Release / check-version (push) Canceled after 0s
Tests / Detect code changes (push) Canceled after 0s
Frontend Tests / Vitest Unit Tests (push) Canceled after 0s
Frontend Tests / Frontend Summary (push) Canceled after 0s
QwenPaw Data Plugin Release / upload-oss (push) Canceled after 0s
Tests / Maintainer Approval (push) Canceled after 0s
Tests / Unit Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - fallback (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p2 (push) Canceled after 0s
Tests / Coverage Report (push) Canceled after 0s
Tests / Test Summary (push) Canceled after 0s
Creator App Tests / PR Spam Gate (push) Skipped
Frontend Tests / PR Spam Gate (push) Skipped
NPM Format (website & console) / PR Spam Gate (push) Skipped
Pre-commit Checks / PR Spam Gate (push) Skipped
QwenPaw Creator Plugin Release / check-version (push) Canceled after 0s
QwenPaw Creator Plugin Release / upload-oss (push) Canceled after 0s
Tests / PR Spam Gate (push) Skipped
CodeQL / CodeQL (python) (push) Canceled after 0s
CodeQL / CodeQL (typescript) (push) Canceled after 0s
Creator App Tests / Creator Backend Tests (push) Canceled after 0s
Creator App Tests / Creator UI Build & Tests (push) Canceled after 0s
E2E Smoke Tests / Playwright UI Smoke (push) Canceled after 0s
Frontend Tests / Detect console changes (push) Canceled after 0s
NPM Format (website & console) / website format check (push) Canceled after 0s
NPM Format (website & console) / console format check (push) Canceled after 0s
Pre-commit Checks / Pre-commit (push) Canceled after 0s
QwenPaw Data Plugin Release / check-version (push) Canceled after 0s
Tests / Detect code changes (push) Canceled after 0s
Frontend Tests / Vitest Unit Tests (push) Canceled after 0s
Frontend Tests / Frontend Summary (push) Canceled after 0s
QwenPaw Data Plugin Release / upload-oss (push) Canceled after 0s
Tests / Maintainer Approval (push) Canceled after 0s
Tests / Unit Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - fallback (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p2 (push) Canceled after 0s
Tests / Coverage Report (push) Canceled after 0s
Tests / Test Summary (push) Canceled after 0s
This commit is contained in:
commit
1a3a4ccde1
4652 files changed
+1891610
No files matched your search
+207
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build QwenPaw with Tauri for macOS (PyInstaller backend)
|
||||
# Creates a self-contained desktop app with bundled Python backend
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/pack-tauri/build_macos_pyinstaller.sh
|
||||
|
||||
set -e
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
VERSION=$(sed -n 's/^__version__[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' src/qwenpaw/__version__.py)
|
||||
|
||||
echo "========================================="
|
||||
echo "QwenPaw Tauri Build - macOS (PyInstaller)"
|
||||
echo "========================================="
|
||||
echo "Version: ${VERSION}"
|
||||
echo ""
|
||||
|
||||
SIGN_MACOS_BUNDLE="${REPO_ROOT}/scripts/pack-tauri/sign_macos_bundle.sh"
|
||||
|
||||
# Step 0: Prerequisites
|
||||
echo "== Step 0: Checking Prerequisites =="
|
||||
missing=()
|
||||
|
||||
if command -v npm &>/dev/null; then
|
||||
echo " [OK] npm ($(npm --version))"
|
||||
else
|
||||
echo " [MISSING] npm"
|
||||
echo " Install Node.js: https://nodejs.org/"
|
||||
missing+=("npm")
|
||||
fi
|
||||
|
||||
if command -v rustc &>/dev/null; then
|
||||
echo " [OK] rustc ($(rustc --version))"
|
||||
else
|
||||
echo " [MISSING] rustc (Rust)"
|
||||
echo " Install: https://rustup.rs"
|
||||
missing+=("rustc")
|
||||
fi
|
||||
|
||||
if command -v uv &>/dev/null; then
|
||||
echo " [OK] uv ($(uv --version))"
|
||||
else
|
||||
echo " [MISSING] uv"
|
||||
echo " Install: https://docs.astral.sh/uv/getting-started/installation/"
|
||||
missing+=("uv")
|
||||
fi
|
||||
|
||||
if [ ${#missing[@]} -gt 0 ]; then
|
||||
echo ""
|
||||
echo "Missing prerequisites: ${missing[*]}"
|
||||
echo "Install the missing tools and re-run this script."
|
||||
exit 1
|
||||
fi
|
||||
echo ""
|
||||
|
||||
if [ ! -f "${SIGN_MACOS_BUNDLE}" ]; then
|
||||
echo "ERROR: macOS signing helper not found at ${SIGN_MACOS_BUNDLE}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "${APPLE_SIGNING_IDENTITY:-}" ] && [ -z "${APPLE_CERTIFICATE:-}" ]; then
|
||||
# The Tauri app and PyInstaller sidecar are native Mach-O executables.
|
||||
# Keep their signature state consistent with ad-hoc signatures when no
|
||||
# Developer ID certificate is configured. This matches the legacy desktop
|
||||
# package behavior: signed enough for local loading, not notarized.
|
||||
export APPLE_SIGNING_IDENTITY="-"
|
||||
echo "Using ad-hoc macOS code signing"
|
||||
fi
|
||||
if [ -z "${PYINSTALLER_CODESIGN_IDENTITY:-}" ]; then
|
||||
# PyInstaller uses the same identity as the final app for bundled Mach-O
|
||||
# files; "-" means ad-hoc signing on macOS.
|
||||
export PYINSTALLER_CODESIGN_IDENTITY="${APPLE_SIGNING_IDENTITY:-}"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Step 1: Build console static assets
|
||||
echo "== Step 1: Building Console Static Assets =="
|
||||
cd console
|
||||
npm ci
|
||||
echo "Generating Tauri icons..."
|
||||
npm exec -- tauri icon ../scripts/pack/assets/icon.svg
|
||||
echo "Syncing Tauri version..."
|
||||
node ../scripts/pack-tauri/sync_tauri_version.mjs
|
||||
echo "Building console frontend..."
|
||||
npm run build:prod
|
||||
cd ..
|
||||
echo "Console static assets built"
|
||||
echo ""
|
||||
|
||||
# Step 2: Build PyInstaller backend
|
||||
echo "== Step 2: Building PyInstaller Backend =="
|
||||
bash scripts/pack-tauri/build_pyinstaller.sh
|
||||
echo "PyInstaller backend built"
|
||||
echo ""
|
||||
|
||||
echo "== Step 2b: Signing PyInstaller Backend =="
|
||||
bash "${SIGN_MACOS_BUNDLE}" \
|
||||
"${REPO_ROOT}/console/src-tauri/binaries/qwenpaw-backend" \
|
||||
"${APPLE_SIGNING_IDENTITY}"
|
||||
echo "PyInstaller backend signed"
|
||||
echo ""
|
||||
|
||||
# Step 3: Build Tauri app
|
||||
echo "== Step 3: Building Tauri App =="
|
||||
BUNDLE_DIR="${REPO_ROOT}/console/src-tauri/target/release/bundle"
|
||||
rm -rf "${BUNDLE_DIR}/dmg" "${BUNDLE_DIR}/macos"
|
||||
cd console
|
||||
echo "Building for macOS..."
|
||||
npm exec -- tauri build \
|
||||
--config src-tauri/tauri.version.conf.json \
|
||||
--bundles app
|
||||
cd ..
|
||||
echo "Tauri app built"
|
||||
echo ""
|
||||
|
||||
APP_PATH="${BUNDLE_DIR}/macos/QwenPaw Desktop.app"
|
||||
if [ ! -d "${APP_PATH}" ]; then
|
||||
echo "ERROR: No Tauri macOS app found at ${APP_PATH}"
|
||||
exit 1
|
||||
fi
|
||||
HELPER_PATH="${APP_PATH}/Contents/MacOS/qwenpaw-computer-use-helper"
|
||||
if [ ! -x "${HELPER_PATH}" ]; then
|
||||
echo "ERROR: Computer Use helper was not bundled at ${HELPER_PATH}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "== Step 3b: Signing Final macOS App =="
|
||||
bash "${SIGN_MACOS_BUNDLE}" \
|
||||
"${APP_PATH}" \
|
||||
"${APPLE_SIGNING_IDENTITY}"
|
||||
echo "Final macOS app signed and verified"
|
||||
echo ""
|
||||
|
||||
# Step 4: Collect distribution artifacts
|
||||
echo "== Step 4: Collecting Distribution Artifacts =="
|
||||
DIST="${DIST:-dist}"
|
||||
if [[ "${DIST}" = /* ]]; then
|
||||
DIST_ROOT="${DIST}"
|
||||
else
|
||||
DIST_ROOT="${REPO_ROOT}/${DIST}"
|
||||
fi
|
||||
DIST_DIR="${DIST_ROOT}/tauri-macos"
|
||||
rm -rf "${DIST_DIR}"
|
||||
mkdir -p "${DIST_DIR}"
|
||||
|
||||
# Match the legacy macOS package shape: one zip containing one .app bundle.
|
||||
cp -R "${APP_PATH}" "${DIST_DIR}/"
|
||||
STAGED_APP_PATH="${DIST_DIR}/$(basename "${APP_PATH}")"
|
||||
echo ".app copied to ${STAGED_APP_PATH}"
|
||||
|
||||
# Create ZIP archive
|
||||
ZIP_NAME="${DIST_ROOT}/QwenPaw-Tauri-${VERSION}-macOS.zip"
|
||||
if [ -f "${ZIP_NAME}" ]; then
|
||||
rm -f "${ZIP_NAME}"
|
||||
fi
|
||||
if command -v ditto &>/dev/null; then
|
||||
ditto -c -k --sequesterRsrc --keepParent "${STAGED_APP_PATH}" "${ZIP_NAME}"
|
||||
else
|
||||
cd "${DIST_DIR}"
|
||||
zip -r "${ZIP_NAME}" "$(basename "${STAGED_APP_PATH}")"
|
||||
cd "${REPO_ROOT}"
|
||||
fi
|
||||
|
||||
if [ -f "${ZIP_NAME}" ]; then
|
||||
SIZE=$(du -sh "${ZIP_NAME}" | cut -f1)
|
||||
echo "Created ${ZIP_NAME} (${SIZE})"
|
||||
else
|
||||
echo "ERROR: Failed to create ZIP archive"
|
||||
exit 1
|
||||
fi
|
||||
echo ""
|
||||
|
||||
UPDATER_NAME="${DIST_ROOT}/QwenPaw-Tauri-${VERSION}-macOS.app.tar.gz"
|
||||
if [ -n "${TAURI_SIGNING_PRIVATE_KEY:-}" ]; then
|
||||
case "$(uname -m)" in
|
||||
arm64 | aarch64) UPDATER_TARGET="darwin-aarch64" ;;
|
||||
*) UPDATER_TARGET="darwin-x86_64" ;;
|
||||
esac
|
||||
python \
|
||||
"${REPO_ROOT}/scripts/pack-tauri/generate_update_manifest.py" \
|
||||
stage \
|
||||
--bundle-dir "${BUNDLE_DIR}/macos" \
|
||||
--pattern '*.app.tar.gz' \
|
||||
--target "${UPDATER_TARGET}" \
|
||||
--output "${UPDATER_NAME}" \
|
||||
--pubkey-config \
|
||||
"${REPO_ROOT}/console/src-tauri/tauri.version.conf.json"
|
||||
UPDATER_RESULT="${UPDATER_NAME}"
|
||||
else
|
||||
UPDATER_RESULT="not generated (updater signing key is not set)"
|
||||
echo "Skipping Tauri updater artifact staging: ${UPDATER_RESULT}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "========================================="
|
||||
echo "Build Complete!"
|
||||
echo "========================================="
|
||||
echo "App: ${APP_PATH}"
|
||||
echo "Distribution: ${DIST_DIR}"
|
||||
echo "Archive: ${ZIP_NAME}"
|
||||
echo "Updater: ${UPDATER_RESULT}"
|
||||
echo ""
|
||||
echo "Test: open \"${STAGED_APP_PATH}\""
|
||||
echo ""
|
||||
@@ -0,0 +1,281 @@
|
||||
# Build QwenPaw backend with PyInstaller for Tauri sidecar (Windows)
|
||||
# Creates an onedir backend bundle with embedded Python runtime
|
||||
#
|
||||
# Usage:
|
||||
# powershell ./scripts/pack-tauri/build_pyinstaller.ps1
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Python 3.10+ on PATH (used only to bootstrap the bundled runtime)
|
||||
# - PyInstaller 6.0+ (will be installed if not present)
|
||||
|
||||
param()
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$REPO_ROOT = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
Set-Location $REPO_ROOT
|
||||
|
||||
$DIST = if ($env:DIST) { $env:DIST } else { "dist" }
|
||||
if (-not [System.IO.Path]::IsPathRooted($DIST)) {
|
||||
$DIST = Join-Path $REPO_ROOT $DIST
|
||||
}
|
||||
$BINARIES_DIR = Join-Path $REPO_ROOT "console\src-tauri\binaries"
|
||||
$PYTHON_RUNTIME_DIR = Join-Path $BINARIES_DIR "python-runtime"
|
||||
$RUNTIME_PYTHON_DIR = Join-Path $PYTHON_RUNTIME_DIR "python"
|
||||
$NATIVE_HOST_PYTHON = Join-Path $RUNTIME_PYTHON_DIR "python.exe"
|
||||
$BUILD_VENV = Join-Path $DIST "pyinstaller-venv"
|
||||
$PYTHON_BIN = Join-Path $BUILD_VENV "Scripts\python.exe"
|
||||
$VERSION_FILE = "src\qwenpaw\__version__.py"
|
||||
|
||||
# Extract version
|
||||
if (Test-Path $VERSION_FILE) {
|
||||
$content = Get-Content $VERSION_FILE -Raw
|
||||
if ($content -match '__version__\s*=\s*"([^"]+)"') {
|
||||
$VERSION = $Matches[1]
|
||||
} else {
|
||||
throw "Failed to extract version from $VERSION_FILE"
|
||||
}
|
||||
} else {
|
||||
throw "Version file not found: $VERSION_FILE"
|
||||
}
|
||||
|
||||
Write-Host "=========================================" -ForegroundColor Cyan
|
||||
Write-Host "QwenPaw PyInstaller Build - Windows" -ForegroundColor Cyan
|
||||
Write-Host "=========================================" -ForegroundColor Cyan
|
||||
Write-Host "Version: $VERSION"
|
||||
Write-Host "Repository: $REPO_ROOT"
|
||||
Write-Host ""
|
||||
|
||||
# Check prerequisites
|
||||
Write-Host "== Checking prerequisites ==" -ForegroundColor Yellow
|
||||
|
||||
function Assert-LastExit {
|
||||
param([string]$Message)
|
||||
if ($LASTEXITCODE -ne 0) { throw $Message }
|
||||
}
|
||||
|
||||
$UV_BIN = (Get-Command uv -ErrorAction SilentlyContinue).Source
|
||||
$BOOTSTRAP_PYTHON = (Get-Command python -ErrorAction SilentlyContinue).Source
|
||||
if (-not $BOOTSTRAP_PYTHON -or -not (Test-Path $BOOTSTRAP_PYTHON)) {
|
||||
throw "Python not found on PATH; it is required to stage the bundled runtime"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $BINARIES_DIR | Out-Null
|
||||
|
||||
# The staged python-build-standalone runtime is the canonical source for both
|
||||
# the helper interpreter and the PyInstaller build environment. The PATH
|
||||
# Python only selects the X.Y version to download and runs the staging script.
|
||||
Write-Host "== Staging canonical Python runtime ==" -ForegroundColor Yellow
|
||||
& $BOOTSTRAP_PYTHON `
|
||||
(Join-Path $REPO_ROOT "scripts\pack-tauri\stage_python_runtime.py") `
|
||||
--dest $PYTHON_RUNTIME_DIR
|
||||
Assert-LastExit "Failed to stage bundled Python runtime"
|
||||
if (-not (Test-Path $NATIVE_HOST_PYTHON -PathType Leaf)) {
|
||||
throw "Bundled Python interpreter not found at $NATIVE_HOST_PYTHON"
|
||||
}
|
||||
|
||||
Write-Host "== Creating PyInstaller build environment ==" -ForegroundColor Yellow
|
||||
& $NATIVE_HOST_PYTHON -m venv --clear $BUILD_VENV
|
||||
Assert-LastExit "Failed to create PyInstaller environment from bundled Python"
|
||||
|
||||
$pythonVersion = & $PYTHON_BIN --version
|
||||
Write-Host "Python: $pythonVersion" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
function Test-PythonImport {
|
||||
param([string]$Statement)
|
||||
$previousErrorActionPreference = $ErrorActionPreference
|
||||
try {
|
||||
$ErrorActionPreference = "Continue"
|
||||
& $PYTHON_BIN -c $Statement *> $null
|
||||
return $LASTEXITCODE -eq 0
|
||||
} finally {
|
||||
$ErrorActionPreference = $previousErrorActionPreference
|
||||
}
|
||||
}
|
||||
|
||||
function Install-PythonPackages {
|
||||
param([string[]]$Packages)
|
||||
if ($UV_BIN) {
|
||||
& $UV_BIN pip install --python $PYTHON_BIN @Packages
|
||||
} else {
|
||||
& $PYTHON_BIN -m pip install @Packages
|
||||
}
|
||||
Assert-LastExit "Failed to install Python packages: $($Packages -join ', ')"
|
||||
}
|
||||
|
||||
function Uninstall-PythonPackage {
|
||||
param([string]$Package)
|
||||
$previousErrorActionPreference = $ErrorActionPreference
|
||||
try {
|
||||
$ErrorActionPreference = "Continue"
|
||||
if ($UV_BIN) {
|
||||
& $UV_BIN pip uninstall --python $PYTHON_BIN -y $Package *> $null
|
||||
} else {
|
||||
& $PYTHON_BIN -m pip uninstall -y $Package *> $null
|
||||
}
|
||||
} finally {
|
||||
$ErrorActionPreference = $previousErrorActionPreference
|
||||
}
|
||||
}
|
||||
|
||||
# Install PyInstaller if not present
|
||||
Write-Host "== Installing PyInstaller ==" -ForegroundColor Yellow
|
||||
if (Test-PythonImport "import PyInstaller") {
|
||||
Write-Host "PyInstaller already installed" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host "Installing PyInstaller..."
|
||||
Install-PythonPackages -Packages @("pyinstaller>=6.0.0")
|
||||
Write-Host "PyInstaller installed" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# Install python-dotenv if not present (required by PyInstaller collect_submodules)
|
||||
if (Test-PythonImport "import dotenv") {
|
||||
Write-Host "python-dotenv already installed" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host "Installing python-dotenv..."
|
||||
Install-PythonPackages -Packages @("python-dotenv")
|
||||
Write-Host "python-dotenv installed" -ForegroundColor Green
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
|
||||
# Install project dependencies (ensures ALL runtime deps are importable)
|
||||
Write-Host "== Installing project dependencies ==" -ForegroundColor Yellow
|
||||
# Pin setuptools <82: lark-oapi still calls pkg_resources.declare_namespace
|
||||
# at import time. A *fresh* install of setuptools >= 82 removes pkg_resources
|
||||
# wholesale, so lark-oapi's except-ImportError fallback (pkgutil.extend_path)
|
||||
# kicks in and the import works. The proven failure mode is an *in-place*
|
||||
# upgrade of a legacy setuptools (seen on the macOS CI runners, and possible
|
||||
# in any environment upgrading an existing install): it can leave a
|
||||
# half-removed pkg_resources (module present, declare_namespace gone), which
|
||||
# raises an AttributeError the fallback does not catch — crashing the Feishu
|
||||
# channel. The pin keeps every environment in the known-good state.
|
||||
Install-PythonPackages -Packages @("-e", ".[full]", "setuptools<82")
|
||||
Write-Host "Project dependencies installed with full extras" -ForegroundColor Green
|
||||
|
||||
# Fix agent-client-protocol namespace collision
|
||||
# PyPI has an empty 'acp' stub that shadows the real package
|
||||
if (-not (Test-PythonImport "from acp import Agent")) {
|
||||
Write-Host "Fixing agent-client-protocol namespace..."
|
||||
Uninstall-PythonPackage "acp"
|
||||
Install-PythonPackages -Packages @("agent-client-protocol>=0.9.0,<0.11.0")
|
||||
Write-Host "agent-client-protocol installed" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# Run PyInstaller
|
||||
Write-Host "== Running PyInstaller ==" -ForegroundColor Yellow
|
||||
Write-Host "Building onedir backend bundle..."
|
||||
|
||||
$SPEC_FILE = Join-Path $REPO_ROOT "scripts\pack-tauri\qwenpaw.spec"
|
||||
if (-not (Test-Path $SPEC_FILE)) {
|
||||
Write-Host "ERROR: Spec file not found at $SPEC_FILE" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
& $PYTHON_BIN -m PyInstaller $SPEC_FILE `
|
||||
--distpath "${DIST}\pyinstaller" `
|
||||
--workpath "${DIST}\pyinstaller-build" `
|
||||
--clean `
|
||||
--noconfirm
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "PyInstaller build failed"
|
||||
}
|
||||
|
||||
Write-Host "PyInstaller build complete" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
# Verify output
|
||||
$BACKEND_DIR = Join-Path $DIST "pyinstaller\qwenpaw-backend"
|
||||
$BACKEND_EXE = Join-Path $BACKEND_DIR "qwenpaw-backend.exe"
|
||||
$CLI_EXE = Join-Path $BACKEND_DIR "qwenpaw.exe"
|
||||
$MODEL_CATALOG = Join-Path $BACKEND_DIR `
|
||||
"_internal\qwenpaw\providers\data\model_catalog.json"
|
||||
if (-not (Test-Path $BACKEND_DIR)) {
|
||||
Write-Host "ERROR: Backend bundle directory not found at $BACKEND_DIR" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if (-not (Test-Path $BACKEND_EXE)) {
|
||||
Write-Host "ERROR: Backend executable not found at $BACKEND_EXE" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if (-not (Test-Path $CLI_EXE)) {
|
||||
Write-Host "ERROR: CLI executable not found at $CLI_EXE" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if (-not (Test-Path $MODEL_CATALOG)) {
|
||||
Write-Host "ERROR: Model catalog not found at $MODEL_CATALOG" `
|
||||
-ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "Backend bundle created: $BACKEND_DIR" -ForegroundColor Green
|
||||
|
||||
# Get size
|
||||
$bundleSize = (Get-ChildItem $BACKEND_DIR -Recurse -File | Measure-Object -Property Length -Sum).Sum / 1MB
|
||||
Write-Host "Bundle size: $([math]::Round($bundleSize, 2)) MB"
|
||||
Write-Host ""
|
||||
|
||||
# Copy to Tauri resources directory
|
||||
Write-Host "== Copying to Tauri binaries directory ==" -ForegroundColor Yellow
|
||||
$DEST = Join-Path $BINARIES_DIR "qwenpaw-backend"
|
||||
New-Item -ItemType Directory -Force -Path $DEST | Out-Null
|
||||
Get-ChildItem -LiteralPath $DEST -Force | Remove-Item -Recurse -Force
|
||||
Copy-Item -Recurse -Force (Join-Path $BACKEND_DIR "*") $DEST
|
||||
Write-Host "Copied to: $DEST" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
# The Chrome Native Messaging host runs under this standalone interpreter,
|
||||
# outside the PyInstaller backend, so its dependencies must be installed here.
|
||||
Write-Host "== Installing bundled Python helper dependencies ==" -ForegroundColor Yellow
|
||||
$NATIVE_HOST_REQUIREMENTS = Join-Path $REPO_ROOT "scripts\pack-tauri\native-host-requirements.txt"
|
||||
& $NATIVE_HOST_PYTHON -m pip install `
|
||||
--disable-pip-version-check `
|
||||
--no-input `
|
||||
--no-deps `
|
||||
--only-binary=:all: `
|
||||
-r $NATIVE_HOST_REQUIREMENTS
|
||||
Assert-LastExit "Failed to install Chrome Native Messaging host dependencies"
|
||||
& $NATIVE_HOST_PYTHON `
|
||||
(Join-Path $REPO_ROOT "plugins\bundle\chrome\assets\scripts\nm_host.py") `
|
||||
--check-runtime
|
||||
Assert-LastExit "Bundled Python runtime cannot run the Native Messaging host"
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "== Staging bundled Node runtime ==" -ForegroundColor Yellow
|
||||
& $PYTHON_BIN (Join-Path $REPO_ROOT "scripts\pack-tauri\stage_node_runtime.py") `
|
||||
--dest (Join-Path $BINARIES_DIR "node-runtime")
|
||||
Assert-LastExit "Failed to stage bundled Node runtime"
|
||||
Write-Host "== Building Computer Use helper ==" -ForegroundColor Yellow
|
||||
$CARGO_BIN = (Get-Command cargo -ErrorAction SilentlyContinue).Source
|
||||
if (-not $CARGO_BIN) {
|
||||
throw "cargo not found; Rust toolchain is required to build qwenpaw-computer-use-helper"
|
||||
}
|
||||
$TAURI_DIR = Join-Path $REPO_ROOT "console\src-tauri"
|
||||
Push-Location $TAURI_DIR
|
||||
try {
|
||||
& $CARGO_BIN build --release --bin qwenpaw-computer-use-helper
|
||||
Assert-LastExit "Failed to build qwenpaw-computer-use-helper"
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
$TARGET_DIR = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $TAURI_DIR "target" }
|
||||
if (-not [System.IO.Path]::IsPathRooted($TARGET_DIR)) {
|
||||
$TARGET_DIR = Join-Path $TAURI_DIR $TARGET_DIR
|
||||
}
|
||||
$COMPUTER_USE_HELPER_EXE = Join-Path $TARGET_DIR "release\qwenpaw-computer-use-helper.exe"
|
||||
if (-not (Test-Path $COMPUTER_USE_HELPER_EXE)) {
|
||||
throw "Computer Use helper executable not found at $COMPUTER_USE_HELPER_EXE"
|
||||
}
|
||||
$COMPUTER_USE_HELPER_DEST = Join-Path $DEST "qwenpaw-computer-use-helper.exe"
|
||||
Copy-Item -Force $COMPUTER_USE_HELPER_EXE $COMPUTER_USE_HELPER_DEST
|
||||
Write-Host "Computer Use helper staged: $COMPUTER_USE_HELPER_DEST" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "=========================================" -ForegroundColor Cyan
|
||||
Write-Host "PyInstaller Build Complete!" -ForegroundColor Green
|
||||
Write-Host "=========================================" -ForegroundColor Cyan
|
||||
Write-Host "Output:"
|
||||
Write-Host " Bundle: $BACKEND_DIR"
|
||||
Write-Host " Tauri resource: $DEST"
|
||||
Write-Host ""
|
||||
Executable
+195
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build QwenPaw backend with PyInstaller for Tauri sidecar
|
||||
# Creates an onedir backend bundle with embedded Python runtime
|
||||
#
|
||||
# Usage:
|
||||
# ./scripts/pack-tauri/build_pyinstaller.sh
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Python 3.10+ on PATH (used only to bootstrap the bundled runtime)
|
||||
# - PyInstaller 6.0+ (will be installed if not present)
|
||||
|
||||
set -e
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
DIST="${DIST:-dist}"
|
||||
BINARIES_DIR="${REPO_ROOT}/console/src-tauri/binaries"
|
||||
PYTHON_RUNTIME_DIR="${BINARIES_DIR}/python-runtime"
|
||||
RUNTIME_PYTHON_DIR="${PYTHON_RUNTIME_DIR}/python"
|
||||
NATIVE_HOST_PYTHON="${RUNTIME_PYTHON_DIR}/bin/python3"
|
||||
BUILD_VENV="${DIST}/pyinstaller-venv"
|
||||
PYTHON_BIN="${BUILD_VENV}/bin/python"
|
||||
VERSION=$(sed -n 's/^__version__[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' src/qwenpaw/__version__.py)
|
||||
|
||||
echo "========================================="
|
||||
echo "QwenPaw PyInstaller Build"
|
||||
echo "========================================="
|
||||
echo "Version: ${VERSION}"
|
||||
echo "Repository: ${REPO_ROOT}"
|
||||
echo ""
|
||||
|
||||
# Check prerequisites
|
||||
echo "== Checking prerequisites =="
|
||||
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
BOOTSTRAP_PYTHON=$(command -v python3)
|
||||
elif command -v python >/dev/null 2>&1; then
|
||||
BOOTSTRAP_PYTHON=$(command -v python)
|
||||
else
|
||||
echo "ERROR: Python not found on PATH; it is required to stage the bundled runtime"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "${BINARIES_DIR}"
|
||||
|
||||
# The staged python-build-standalone runtime is the canonical source for both
|
||||
# the helper interpreter and the PyInstaller build environment. The PATH
|
||||
# Python only selects the X.Y version to download and runs the staging script.
|
||||
echo "== Staging canonical Python runtime =="
|
||||
"$BOOTSTRAP_PYTHON" "${REPO_ROOT}/scripts/pack-tauri/stage_python_runtime.py" \
|
||||
--dest "${PYTHON_RUNTIME_DIR}"
|
||||
if [ ! -f "$NATIVE_HOST_PYTHON" ]; then
|
||||
echo "ERROR: Bundled Python interpreter not found at ${NATIVE_HOST_PYTHON}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "== Creating PyInstaller build environment =="
|
||||
"$NATIVE_HOST_PYTHON" -m venv --clear "$BUILD_VENV"
|
||||
|
||||
echo "Python: $("$PYTHON_BIN" --version)"
|
||||
echo ""
|
||||
|
||||
install_python_packages() {
|
||||
if command -v uv &>/dev/null; then
|
||||
uv pip install --python "$PYTHON_BIN" "$@"
|
||||
else
|
||||
"$PYTHON_BIN" -m pip install "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
uninstall_python_package() {
|
||||
if command -v uv &>/dev/null; then
|
||||
uv pip uninstall --python "$PYTHON_BIN" -y "$1" >/dev/null 2>&1 || true
|
||||
else
|
||||
"$PYTHON_BIN" -m pip uninstall -y "$1" >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
# Install PyInstaller if not present
|
||||
echo "== Installing PyInstaller =="
|
||||
if ! "$PYTHON_BIN" -c "import PyInstaller" 2> /dev/null; then
|
||||
echo "Installing PyInstaller..."
|
||||
install_python_packages "pyinstaller>=6.0.0"
|
||||
fi
|
||||
echo "PyInstaller installed"
|
||||
|
||||
# Install project dependencies (ensures ALL runtime deps are importable)
|
||||
echo "== Installing project dependencies =="
|
||||
# Pin setuptools <82: lark-oapi still calls pkg_resources.declare_namespace
|
||||
# at import time. A *fresh* install of setuptools >= 82 removes pkg_resources
|
||||
# wholesale, so lark-oapi's except-ImportError fallback (pkgutil.extend_path)
|
||||
# kicks in and the import works. The proven failure mode is an *in-place*
|
||||
# upgrade of a legacy setuptools (seen on the macOS CI runners, and possible
|
||||
# in any environment upgrading an existing install): it can leave a
|
||||
# half-removed pkg_resources (module present, declare_namespace gone), which
|
||||
# raises an AttributeError the fallback does not catch — crashing the Feishu
|
||||
# channel. The pin keeps every environment in the known-good state.
|
||||
install_python_packages -e ".[full]" "setuptools<82"
|
||||
echo "Project dependencies installed with full extras"
|
||||
|
||||
# Fix agent-client-protocol namespace collision
|
||||
# PyPI has an empty 'acp' stub that shadows the real package
|
||||
if ! "$PYTHON_BIN" -c "from acp import Agent" 2> /dev/null; then
|
||||
echo "Fixing agent-client-protocol namespace..."
|
||||
uninstall_python_package acp
|
||||
install_python_packages "agent-client-protocol>=0.9.0,<0.11.0"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Run PyInstaller
|
||||
echo "== Running PyInstaller =="
|
||||
echo "Building onedir backend bundle..."
|
||||
|
||||
SPEC_FILE="${REPO_ROOT}/scripts/pack-tauri/qwenpaw.spec"
|
||||
if [ ! -f "$SPEC_FILE" ]; then
|
||||
echo "ERROR: Spec file not found at ${SPEC_FILE}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
"$PYTHON_BIN" -m PyInstaller "$SPEC_FILE" \
|
||||
--distpath "${DIST}/pyinstaller" \
|
||||
--workpath "${DIST}/pyinstaller-build" \
|
||||
--clean \
|
||||
--noconfirm
|
||||
|
||||
echo "PyInstaller build complete"
|
||||
echo ""
|
||||
|
||||
# Verify output
|
||||
BACKEND_DIR="${DIST}/pyinstaller/qwenpaw-backend"
|
||||
BACKEND_EXE="${BACKEND_DIR}/qwenpaw-backend"
|
||||
CLI_EXE="${BACKEND_DIR}/qwenpaw"
|
||||
MODEL_CATALOG="${BACKEND_DIR}/_internal/qwenpaw/providers/data/model_catalog.json"
|
||||
if [ ! -d "${BACKEND_DIR}" ]; then
|
||||
echo "ERROR: Backend bundle directory not found at ${BACKEND_DIR}"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f "${BACKEND_EXE}" ]; then
|
||||
echo "ERROR: Backend executable not found at ${BACKEND_EXE}"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f "${CLI_EXE}" ]; then
|
||||
echo "ERROR: CLI executable not found at ${CLI_EXE}"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f "${MODEL_CATALOG}" ]; then
|
||||
echo "ERROR: Model catalog not found at ${MODEL_CATALOG}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Backend bundle created: ${BACKEND_DIR}"
|
||||
|
||||
# Get size
|
||||
SIZE=$(du -sh "${BACKEND_DIR}" | cut -f1)
|
||||
echo "Bundle size: ${SIZE}"
|
||||
echo ""
|
||||
|
||||
# Copy to Tauri resources directory
|
||||
echo "== Copying to Tauri binaries directory =="
|
||||
DEST="${BINARIES_DIR}/qwenpaw-backend"
|
||||
rm -rf "${DEST}"
|
||||
mkdir -p "${DEST}"
|
||||
cp -R "${BACKEND_DIR}/." "${DEST}/"
|
||||
chmod +x "${DEST}/qwenpaw-backend"
|
||||
chmod +x "${DEST}/qwenpaw"
|
||||
echo "Copied to: ${DEST}"
|
||||
echo ""
|
||||
|
||||
# The Chrome Native Messaging host runs under this standalone interpreter,
|
||||
# outside the PyInstaller backend, so its dependencies must be installed here.
|
||||
echo "== Installing bundled Python helper dependencies =="
|
||||
"$NATIVE_HOST_PYTHON" -m pip install \
|
||||
--disable-pip-version-check \
|
||||
--no-input \
|
||||
--no-deps \
|
||||
--only-binary=:all: \
|
||||
-r "${REPO_ROOT}/scripts/pack-tauri/native-host-requirements.txt"
|
||||
"$NATIVE_HOST_PYTHON" \
|
||||
"${REPO_ROOT}/plugins/bundle/chrome/assets/scripts/nm_host.py" \
|
||||
--check-runtime
|
||||
echo ""
|
||||
|
||||
echo "== Staging bundled Node runtime =="
|
||||
"$PYTHON_BIN" "${REPO_ROOT}/scripts/pack-tauri/stage_node_runtime.py" \
|
||||
--dest "${BINARIES_DIR}/node-runtime"
|
||||
echo ""
|
||||
|
||||
echo "========================================="
|
||||
echo "PyInstaller Build Complete!"
|
||||
echo "========================================="
|
||||
echo "Output:"
|
||||
echo " Bundle: ${BACKEND_DIR}"
|
||||
echo " Tauri resource: ${DEST}"
|
||||
echo ""
|
||||
@@ -0,0 +1,211 @@
|
||||
# Build QwenPaw with Tauri for Windows (PyInstaller backend)
|
||||
# Creates a self-contained desktop app with bundled Python backend
|
||||
#
|
||||
# Usage:
|
||||
# powershell ./scripts/pack-tauri/build_win_pyinstaller.ps1
|
||||
|
||||
param()
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$REPO_ROOT = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
Set-Location $REPO_ROOT
|
||||
|
||||
$DIST = if ($env:DIST) { $env:DIST } else { "dist" }
|
||||
if (-not [System.IO.Path]::IsPathRooted($DIST)) {
|
||||
$DIST = Join-Path $REPO_ROOT $DIST
|
||||
}
|
||||
$VERSION_FILE = "src\qwenpaw\__version__.py"
|
||||
|
||||
function Invoke-NativeWithRetry {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Description,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[scriptblock]$Command,
|
||||
[int]$MaxAttempts = 5,
|
||||
[int]$DelaySeconds = 20
|
||||
)
|
||||
|
||||
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
|
||||
Write-Host "$Description (attempt $attempt/$MaxAttempts)..."
|
||||
& $Command
|
||||
$exitCode = $LASTEXITCODE
|
||||
if ($exitCode -eq 0) {
|
||||
return
|
||||
}
|
||||
|
||||
if ($attempt -eq $MaxAttempts) {
|
||||
throw "$Description failed after $MaxAttempts attempts (exit code $exitCode)"
|
||||
}
|
||||
|
||||
Write-Host "$Description failed with exit code $exitCode; retrying in $DelaySeconds seconds..." -ForegroundColor Yellow
|
||||
Start-Sleep -Seconds $DelaySeconds
|
||||
}
|
||||
}
|
||||
|
||||
# Extract version
|
||||
if (Test-Path $VERSION_FILE) {
|
||||
$content = Get-Content $VERSION_FILE -Raw
|
||||
if ($content -match '__version__\s*=\s*"([^"]+)"') {
|
||||
$VERSION = $Matches[1]
|
||||
} else {
|
||||
throw "Failed to extract version from $VERSION_FILE"
|
||||
}
|
||||
} else {
|
||||
throw "Version file not found: $VERSION_FILE"
|
||||
}
|
||||
|
||||
Write-Host "=========================================" -ForegroundColor Cyan
|
||||
Write-Host "QwenPaw Tauri Build - Windows (PyInstaller)" -ForegroundColor Cyan
|
||||
Write-Host "=========================================" -ForegroundColor Cyan
|
||||
Write-Host "Version: $VERSION"
|
||||
Write-Host ""
|
||||
|
||||
# Step 0: Prerequisites
|
||||
Write-Host "== Step 0: Checking Prerequisites ==" -ForegroundColor Yellow
|
||||
$missing = @()
|
||||
|
||||
# npm
|
||||
if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {
|
||||
Write-Host " [MISSING] npm" -ForegroundColor Red
|
||||
Write-Host " Install Node.js: https://nodejs.org/" -ForegroundColor Gray
|
||||
$missing += "npm"
|
||||
} else {
|
||||
Write-Host " [OK] npm ($(npm --version))" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# rustc
|
||||
if (-not (Get-Command rustc -ErrorAction SilentlyContinue)) {
|
||||
Write-Host " [MISSING] rustc (Rust)" -ForegroundColor Red
|
||||
Write-Host " Install: https://rustup.rs" -ForegroundColor Gray
|
||||
$missing += "rustc"
|
||||
} else {
|
||||
Write-Host " [OK] rustc ($(rustc --version))" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# Visual Studio Build Tools (MSVC)
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$hasMsvc = $false
|
||||
if (Test-Path $vswhere) {
|
||||
$vsPath = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2>$null
|
||||
if ($vsPath) { $hasMsvc = $true }
|
||||
}
|
||||
if (-not $hasMsvc) {
|
||||
$hostTuple = & rustc --print host-tuple 2>$null
|
||||
if ($hostTuple -match "msvc") { $hasMsvc = $true }
|
||||
}
|
||||
if (-not $hasMsvc) {
|
||||
Write-Host " [MISSING] Visual Studio Build Tools (C++ workload)" -ForegroundColor Red
|
||||
Write-Host " Install: https://visualstudio.microsoft.com/visual-cpp-build-tools/" -ForegroundColor Gray
|
||||
Write-Host " Required workload: 'Desktop development with C++'" -ForegroundColor Gray
|
||||
$missing += "MSVC"
|
||||
} else {
|
||||
Write-Host " [OK] Visual Studio Build Tools (MSVC)" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# NSIS (makensis)
|
||||
if (-not (Get-Command makensis -ErrorAction SilentlyContinue)) {
|
||||
Write-Host " [MISSING] makensis (NSIS)" -ForegroundColor Red
|
||||
Write-Host " Install: https://nsis.sourceforge.io/Download" -ForegroundColor Gray
|
||||
$missing += "makensis"
|
||||
} else {
|
||||
$nsisInfo = makensis /version 2>$null
|
||||
Write-Host " [OK] makensis (NSIS $nsisInfo)" -ForegroundColor Green
|
||||
}
|
||||
|
||||
if ($missing.Count -gt 0) {
|
||||
Write-Host ""
|
||||
Write-Host "Missing prerequisites: $($missing -join ', ')" -ForegroundColor Red
|
||||
Write-Host "Install the missing tools and re-run this script." -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
Write-Host ""
|
||||
|
||||
# Step 1: Build console static assets
|
||||
Write-Host "== Step 1: Building Console Static Assets ==" -ForegroundColor Yellow
|
||||
Set-Location console
|
||||
|
||||
Write-Host "Installing frontend dependencies..."
|
||||
npm ci
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "npm ci failed"
|
||||
}
|
||||
|
||||
Write-Host "Generating Tauri icons..."
|
||||
npm exec -- tauri icon ../scripts/pack/assets/icon.svg
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Tauri icon generation failed"
|
||||
}
|
||||
|
||||
Write-Host "Syncing Tauri version..."
|
||||
node ../scripts/pack-tauri/sync_tauri_version.mjs
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Tauri version sync failed"
|
||||
}
|
||||
|
||||
Write-Host "Building console frontend..."
|
||||
npm run build:prod
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "console frontend build failed"
|
||||
}
|
||||
|
||||
Set-Location $REPO_ROOT
|
||||
Write-Host "Console static assets built" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
# Step 2: Build PyInstaller backend
|
||||
Write-Host "== Step 2: Building PyInstaller Backend ==" -ForegroundColor Yellow
|
||||
$PYINSTALLER_SCRIPT = Join-Path $REPO_ROOT "scripts\pack-tauri\build_pyinstaller.ps1"
|
||||
& $PYINSTALLER_SCRIPT
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "PyInstaller build failed"
|
||||
}
|
||||
Write-Host "PyInstaller backend ready" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
# Step 2b: Fetch Tauri Rust dependencies
|
||||
Write-Host "== Step 2b: Fetching Tauri Rust Dependencies ==" -ForegroundColor Yellow
|
||||
if (-not $env:CARGO_NET_RETRY) {
|
||||
$env:CARGO_NET_RETRY = "10"
|
||||
}
|
||||
if (-not $env:CARGO_HTTP_MULTIPLEXING) {
|
||||
$env:CARGO_HTTP_MULTIPLEXING = "false"
|
||||
}
|
||||
|
||||
$TAURI_MANIFEST = Join-Path $REPO_ROOT "console\src-tauri\Cargo.toml"
|
||||
Invoke-NativeWithRetry -Description "cargo fetch for Tauri dependencies" -Command {
|
||||
cargo fetch --locked --target x86_64-pc-windows-msvc --manifest-path $TAURI_MANIFEST
|
||||
}
|
||||
$env:CARGO_NET_OFFLINE = "true"
|
||||
Write-Host "Tauri Rust dependencies fetched; Cargo offline mode enabled" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
|
||||
# Step 3: Build Tauri app
|
||||
Write-Host "== Step 3: Building Tauri App ==" -ForegroundColor Yellow
|
||||
$BUNDLE_DIR = Join-Path $REPO_ROOT "console\src-tauri\target\release\bundle"
|
||||
$NSIS_DIR = Join-Path $BUNDLE_DIR "nsis"
|
||||
if (Test-Path $NSIS_DIR) {
|
||||
Remove-Item -Recurse -Force $NSIS_DIR
|
||||
}
|
||||
|
||||
Set-Location console
|
||||
|
||||
Write-Host "Building for Windows..."
|
||||
npm exec -- tauri build --config src-tauri/tauri.version.conf.json
|
||||
$tauriExit = $LASTEXITCODE
|
||||
|
||||
if ($tauriExit -ne 0) {
|
||||
throw "Tauri build failed"
|
||||
}
|
||||
|
||||
Set-Location $REPO_ROOT
|
||||
Write-Host "Tauri app built" -ForegroundColor Green
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=========================================" -ForegroundColor Cyan
|
||||
Write-Host "Build Complete!" -ForegroundColor Green
|
||||
Write-Host "=========================================" -ForegroundColor Cyan
|
||||
Write-Host "Output:"
|
||||
Write-Host " NSIS bundle directory: ${NSIS_DIR}\"
|
||||
Write-Host ""
|
||||
@@ -0,0 +1,23 @@
|
||||
// Vite preserves the source HTML filename for multi-page builds. Tauri expects
|
||||
// the bundled frontend directory to contain index.html, so rename the small
|
||||
// desktop bootstrap page after the Vite build.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(scriptDir, "../..");
|
||||
const distDir = path.join(repoRoot, "console", "dist-tauri");
|
||||
const source = path.join(distDir, "tauri.html");
|
||||
const target = path.join(distDir, "index.html");
|
||||
|
||||
if (!fs.existsSync(source)) {
|
||||
throw new Error(`Tauri bootstrap HTML not found: ${source}`);
|
||||
}
|
||||
|
||||
if (fs.existsSync(target)) {
|
||||
fs.rmSync(target);
|
||||
}
|
||||
|
||||
fs.renameSync(source, target);
|
||||
console.log(`Wrote Tauri bootstrap ${target}`);
|
||||
@@ -0,0 +1,298 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Tauri updater helper: stage per-platform artifacts and build the manifest.
|
||||
|
||||
Subcommands:
|
||||
stage Copy a Tauri-built updater archive (and its .sig) into the dist
|
||||
tree, then write a small JSON sidecar describing it.
|
||||
manifest Aggregate one or more stage-produced sidecar JSON files into the
|
||||
unified `qwenpaw-tauri-latest.json` consumed by tauri-plugin-updater.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import shutil
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from packaging.version import InvalidVersion, Version
|
||||
|
||||
|
||||
def to_semver(version: str) -> str:
|
||||
try:
|
||||
parsed = Version(version)
|
||||
except InvalidVersion as err:
|
||||
raise SystemExit(
|
||||
f"unsupported Python version for Tauri: {version}",
|
||||
) from err
|
||||
|
||||
if parsed.epoch or parsed.local is not None or len(parsed.release) != 3:
|
||||
raise SystemExit(f"unsupported Python version for Tauri: {version}")
|
||||
|
||||
major, minor, patch = parsed.release
|
||||
prerelease_map = {"a": "alpha", "b": "beta", "rc": "rc"}
|
||||
labels: list[str] = []
|
||||
if parsed.pre:
|
||||
prerelease, prerelease_n = parsed.pre
|
||||
labels.append(f"{prerelease_map[prerelease]}.{prerelease_n}")
|
||||
if parsed.dev is not None:
|
||||
labels.append(f"dev.{parsed.dev}")
|
||||
suffix = f"-{'.'.join(labels)}" if labels else ""
|
||||
post_metadata = f"+post.{parsed.post}" if parsed.post is not None else ""
|
||||
return f"{major}.{minor}.{patch}{suffix}{post_metadata}"
|
||||
|
||||
|
||||
# stage
|
||||
|
||||
|
||||
def _find_source(bundle_dir: Path, pattern: str) -> Path:
|
||||
matches = sorted(bundle_dir.glob(pattern))
|
||||
if not matches:
|
||||
raise SystemExit(
|
||||
f"no artifact matching {pattern!r} under {bundle_dir}",
|
||||
)
|
||||
return matches[0]
|
||||
|
||||
|
||||
def cmd_stage(args: argparse.Namespace) -> None:
|
||||
bundle_dir = Path(args.bundle_dir)
|
||||
source = _find_source(bundle_dir, args.pattern)
|
||||
sig_source = source.with_suffix(source.suffix + ".sig")
|
||||
if not sig_source.is_file():
|
||||
raise SystemExit(f"no updater signature found at {sig_source}")
|
||||
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, output)
|
||||
shutil.copyfile(sig_source, output.with_suffix(output.suffix + ".sig"))
|
||||
|
||||
metadata = {
|
||||
"target": args.target,
|
||||
"artifact": output.name,
|
||||
"signature": output.name + ".sig",
|
||||
}
|
||||
sidecar = output.parent / f"tauri-{args.target}-updater.json"
|
||||
sidecar.write_text(
|
||||
json.dumps(metadata, indent=2, ensure_ascii=False) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
if args.pubkey_config:
|
||||
verify_signature_key_id(
|
||||
signature_path=output.with_suffix(output.suffix + ".sig"),
|
||||
pubkey_config=Path(args.pubkey_config),
|
||||
)
|
||||
print(f"staged {output.name} ({args.target}); sidecar {sidecar.name}")
|
||||
|
||||
|
||||
# manifest
|
||||
|
||||
|
||||
def _read_metadata(path: Path) -> dict[str, str]:
|
||||
with path.open("r", encoding="utf-8-sig") as f:
|
||||
data = json.load(f)
|
||||
required = {"target", "artifact", "signature"}
|
||||
missing = required - set(data)
|
||||
if missing:
|
||||
raise SystemExit(
|
||||
f"{path} missing required keys: {', '.join(sorted(missing))}",
|
||||
)
|
||||
return {key: str(data[key]) for key in required}
|
||||
|
||||
|
||||
def _signature_text(path: Path) -> str:
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"signature file not found: {path}")
|
||||
return path.read_text(encoding="utf-8-sig").strip()
|
||||
|
||||
|
||||
def _decode_base64_minisign_text(value: str, *, kind: str) -> str:
|
||||
try:
|
||||
text = base64.b64decode(value, validate=True).decode("utf-8")
|
||||
except Exception as err:
|
||||
raise SystemExit(
|
||||
f"{kind} is not valid base64 minisign text: {err}",
|
||||
) from err
|
||||
if "untrusted comment:" not in text:
|
||||
raise SystemExit(f"{kind} is not a minisign text block")
|
||||
return text
|
||||
|
||||
|
||||
def _minisign_key_id(text: str, *, kind: str) -> str:
|
||||
lines = [
|
||||
line.strip() for line in text.strip().splitlines() if line.strip()
|
||||
]
|
||||
try:
|
||||
raw = base64.b64decode(lines[1], validate=True)
|
||||
key_id = raw[2:10]
|
||||
if len(key_id) != 8:
|
||||
raise ValueError("missing key id")
|
||||
except IndexError as err:
|
||||
raise SystemExit(f"{kind} is not a valid minisign text block") from err
|
||||
except Exception as err:
|
||||
raise SystemExit(
|
||||
f"{kind} has invalid minisign key/signature data: {err}",
|
||||
) from err
|
||||
return key_id.hex()
|
||||
|
||||
|
||||
def _pubkey_from_config(config_path: Path) -> str:
|
||||
with config_path.open("r", encoding="utf-8-sig") as f:
|
||||
config = json.load(f)
|
||||
try:
|
||||
pubkey = config["plugins"]["updater"]["pubkey"]
|
||||
except KeyError as err:
|
||||
raise SystemExit(
|
||||
f"{config_path} missing plugins.updater.pubkey: {err}",
|
||||
) from err
|
||||
if not isinstance(pubkey, str) or not pubkey.strip():
|
||||
raise SystemExit(f"{config_path} has an empty plugins.updater.pubkey")
|
||||
return _decode_base64_minisign_text(pubkey.strip(), kind=str(config_path))
|
||||
|
||||
|
||||
def verify_signature_key_id(signature_path: Path, pubkey_config: Path) -> None:
|
||||
signature_text = _decode_base64_minisign_text(
|
||||
_signature_text(signature_path),
|
||||
kind=str(signature_path),
|
||||
)
|
||||
pubkey_text = _pubkey_from_config(pubkey_config)
|
||||
signature_key_id = _minisign_key_id(
|
||||
signature_text,
|
||||
kind=str(signature_path),
|
||||
)
|
||||
pubkey_key_id = _minisign_key_id(pubkey_text, kind=str(pubkey_config))
|
||||
if signature_key_id != pubkey_key_id:
|
||||
raise SystemExit(
|
||||
"updater signature key id does not match configured pubkey: "
|
||||
f"signature={signature_key_id} pubkey={pubkey_key_id}",
|
||||
)
|
||||
print(f"verified updater signature key id: {signature_key_id}")
|
||||
|
||||
|
||||
def cmd_manifest(args: argparse.Namespace) -> None:
|
||||
target_overrides: dict[str, str] = {}
|
||||
for entry in args.target_base or []:
|
||||
target, _, url = entry.partition("=")
|
||||
if not target or not url:
|
||||
raise SystemExit(
|
||||
f"--target-base expects 'target=URL', got {entry!r}",
|
||||
)
|
||||
target_overrides[target] = url
|
||||
|
||||
platforms: dict[str, dict[str, str]] = {}
|
||||
for raw in args.metadata:
|
||||
meta_path = Path(raw)
|
||||
meta = _read_metadata(meta_path)
|
||||
workdir = meta_path.parent
|
||||
artifact_path = workdir / meta["artifact"]
|
||||
if not artifact_path.is_file():
|
||||
raise SystemExit(f"artifact file not found: {artifact_path}")
|
||||
base = target_overrides.get(meta["target"], args.base_url).rstrip(
|
||||
"/",
|
||||
)
|
||||
platforms[meta["target"]] = {
|
||||
"url": f"{base}/{quote(meta['artifact'])}",
|
||||
"signature": _signature_text(workdir / meta["signature"]),
|
||||
}
|
||||
if not platforms:
|
||||
raise SystemExit("no updater platforms were provided")
|
||||
|
||||
manifest = {
|
||||
"version": to_semver(args.version),
|
||||
"notes": args.notes,
|
||||
"pub_date": args.pub_date,
|
||||
"platforms": platforms,
|
||||
}
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with output.open("w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, indent=2, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
print(
|
||||
f"wrote manifest {output} (platforms: {', '.join(sorted(platforms))})",
|
||||
)
|
||||
|
||||
|
||||
# cli
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
p_stage = sub.add_parser(
|
||||
"stage",
|
||||
help="Copy a Tauri updater archive + .sig into dist and write a sidecar.",
|
||||
)
|
||||
p_stage.add_argument(
|
||||
"--bundle-dir",
|
||||
required=True,
|
||||
help="Tauri bundle output dir (e.g., target/release/bundle/nsis).",
|
||||
)
|
||||
p_stage.add_argument(
|
||||
"--pattern",
|
||||
required=True,
|
||||
help="Glob to find the artifact (e.g., '*-setup.exe', '*.app.tar.gz').",
|
||||
)
|
||||
p_stage.add_argument(
|
||||
"--target",
|
||||
required=True,
|
||||
help="Updater target (e.g., windows-x86_64, darwin-aarch64).",
|
||||
)
|
||||
p_stage.add_argument(
|
||||
"--output",
|
||||
required=True,
|
||||
help="Destination artifact path; .sig is staged alongside.",
|
||||
)
|
||||
p_stage.add_argument(
|
||||
"--pubkey-config",
|
||||
help=(
|
||||
"Optional tauri.conf.json path. When provided, fail if the staged "
|
||||
"signature key id does not match plugins.updater.pubkey."
|
||||
),
|
||||
)
|
||||
p_stage.set_defaults(func=cmd_stage)
|
||||
|
||||
p_manifest = sub.add_parser(
|
||||
"manifest",
|
||||
help="Aggregate per-platform sidecars into the updater manifest JSON.",
|
||||
)
|
||||
p_manifest.add_argument("--version", required=True)
|
||||
p_manifest.add_argument(
|
||||
"--base-url",
|
||||
required=True,
|
||||
help="Default URL prefix for platforms without --target-base override.",
|
||||
)
|
||||
p_manifest.add_argument(
|
||||
"--target-base",
|
||||
action="append",
|
||||
default=[],
|
||||
help=(
|
||||
"Per-target URL prefix override 'target=URL', repeatable. "
|
||||
"Used when platforms live under different paths "
|
||||
"(e.g., OSS lays win-tauri/ and mac-tauri/ separately)."
|
||||
),
|
||||
)
|
||||
p_manifest.add_argument(
|
||||
"--metadata",
|
||||
action="append",
|
||||
default=[],
|
||||
help="Path to a sidecar JSON file (repeatable).",
|
||||
)
|
||||
p_manifest.add_argument("--notes", default="")
|
||||
p_manifest.add_argument(
|
||||
"--pub-date",
|
||||
default=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
)
|
||||
p_manifest.add_argument("--output", required=True)
|
||||
p_manifest.set_defaults(func=cmd_manifest)
|
||||
|
||||
args = parser.parse_args()
|
||||
args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
websockets==15.0.1
|
||||
@@ -0,0 +1,294 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
"""
|
||||
PyInstaller spec file for QwenPaw Desktop (Tauri sidecar).
|
||||
|
||||
Shared spec for both macOS and Windows. Builds an onedir backend bundle so the
|
||||
desktop startup can load Python directly without onefile extraction. The same
|
||||
bundle also includes a qwenpaw CLI executable for the Windows installer PATH
|
||||
option.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PyInstaller.utils.hooks import (
|
||||
collect_data_files,
|
||||
collect_submodules,
|
||||
copy_metadata,
|
||||
get_package_paths,
|
||||
)
|
||||
|
||||
REPO_ROOT = Path(SPECPATH).parent.parent
|
||||
|
||||
SRC = REPO_ROOT / "src" / "qwenpaw"
|
||||
MAIL_MCP_SRC = REPO_ROOT / "packages" / "qwenpawmail-mcp" / "src"
|
||||
if sys.platform == "darwin":
|
||||
codesign_identity = os.environ.get(
|
||||
"PYINSTALLER_CODESIGN_IDENTITY"
|
||||
) or os.environ.get("APPLE_SIGNING_IDENTITY")
|
||||
if not codesign_identity:
|
||||
codesign_identity = None
|
||||
else:
|
||||
codesign_identity = None
|
||||
|
||||
def collect_tree(source_dir, target_dir):
|
||||
return [
|
||||
(str(path), str(Path(target_dir) / path.relative_to(source_dir).parent))
|
||||
for path in source_dir.rglob("*")
|
||||
if path.is_file()
|
||||
]
|
||||
|
||||
|
||||
# Match the legacy desktop package: the FastAPI backend serves the web console
|
||||
# from qwenpaw/console, so Tauri can navigate to the backend-hosted same-origin
|
||||
# console after the sidecar is ready.
|
||||
CONSOLE_DIST = REPO_ROOT / "console" / "dist"
|
||||
if not (CONSOLE_DIST / "index.html").is_file():
|
||||
raise SystemExit(
|
||||
f"console dist not found at {CONSOLE_DIST}; "
|
||||
"run npm run build:prod in console/ before PyInstaller"
|
||||
)
|
||||
|
||||
_data_dirs = [
|
||||
("agents/skills", "qwenpaw/agents/skills"),
|
||||
("agents/md_files", "qwenpaw/agents/md_files"),
|
||||
("tokenizer", "qwenpaw/tokenizer"),
|
||||
("security/tool_guard/rules", "qwenpaw/security/tool_guard/rules"),
|
||||
("security/skill_scanner/rules", "qwenpaw/security/skill_scanner/rules"),
|
||||
("security/skill_scanner/data", "qwenpaw/security/skill_scanner/data"),
|
||||
("app/channels/yuanbao/proto", "qwenpaw/app/channels/yuanbao/proto"),
|
||||
("providers/data", "qwenpaw/providers/data"),
|
||||
]
|
||||
datas = [
|
||||
(str(SRC / src), dst) for src, dst in _data_dirs if (SRC / src).is_dir()
|
||||
]
|
||||
datas += collect_tree(CONSOLE_DIST, "qwenpaw/console")
|
||||
datas.append(
|
||||
(
|
||||
str(SRC / "browser/control_link/injected/engine.js"),
|
||||
"qwenpaw/browser/control_link/injected",
|
||||
),
|
||||
)
|
||||
|
||||
# Include ReMe package data files (configs, tool yamls, plugin manifests, etc.).
|
||||
# The plugin packages are discovered through importlib.metadata entry points,
|
||||
# so PyInstaller cannot infer either their modules or their data files from
|
||||
# QwenPaw's static imports.
|
||||
datas += collect_data_files("reme")
|
||||
datas += collect_data_files("reme_auto_fin")
|
||||
datas += collect_data_files("reme_daily_paper")
|
||||
datas += collect_data_files("whisper")
|
||||
datas += collect_data_files("agentscope")
|
||||
datas += collect_data_files(
|
||||
"agentscope.tool._builtin._scripts",
|
||||
include_py_files=True,
|
||||
)
|
||||
datas += collect_data_files(
|
||||
"agentscope.workspace._mcp_gateway",
|
||||
include_py_files=True,
|
||||
)
|
||||
|
||||
# The Qoder SDK ships a platform-specific qodercli executable. Classify it as
|
||||
# a binary so PyInstaller preserves executable permissions and signs it with
|
||||
# the rest of the macOS bundle.
|
||||
_, _qoder_sdk_dir = get_package_paths("qoder_agent_sdk")
|
||||
_qoder_cli_name = "qodercli.exe" if sys.platform == "win32" else "qodercli"
|
||||
_qoder_cli = Path(_qoder_sdk_dir) / "_bundled" / _qoder_cli_name
|
||||
if not _qoder_cli.is_file():
|
||||
raise SystemExit(
|
||||
f"Qoder SDK CLI not found at {_qoder_cli}; reinstall qoder-agent-sdk"
|
||||
)
|
||||
qoder_binaries = [
|
||||
(str(_qoder_cli), "qoder_agent_sdk/_bundled"),
|
||||
]
|
||||
|
||||
# The official Codex Python SDK depends on a platform wheel that exposes a
|
||||
# stable bundled_codex_path() API. Preserve its runtime layout because Codex
|
||||
# resolves sibling hosts and resources relative to the main executable.
|
||||
_, _codex_bin_dir = get_package_paths("codex_cli_bin")
|
||||
_codex_bin_dir = Path(_codex_bin_dir)
|
||||
_codex_executable = (
|
||||
"codex.exe" if sys.platform == "win32" else "codex"
|
||||
)
|
||||
_codex_cli = _codex_bin_dir / "bin" / _codex_executable
|
||||
if not _codex_cli.is_file():
|
||||
raise SystemExit(
|
||||
f"Codex SDK CLI not found at {_codex_cli}; reinstall openai-codex"
|
||||
)
|
||||
codex_binaries = [
|
||||
(
|
||||
str(path),
|
||||
str(Path("codex_cli_bin") / path.relative_to(_codex_bin_dir).parent),
|
||||
)
|
||||
for directory_name in ("bin", "codex-path", "codex-resources")
|
||||
for path in (_codex_bin_dir / directory_name).rglob("*")
|
||||
if path.is_file()
|
||||
]
|
||||
datas.append(
|
||||
(
|
||||
str(_codex_bin_dir / "codex-package.json"),
|
||||
"codex_cli_bin",
|
||||
),
|
||||
)
|
||||
|
||||
# Collect package metadata for packages that use importlib.metadata at runtime.
|
||||
# Keep this allowlist in sync when adding runtime dependencies that query
|
||||
# importlib.metadata, otherwise packaged sidecars may fail only after install.
|
||||
_metadata_pkgs = [
|
||||
"qwenpaw",
|
||||
"fastmcp",
|
||||
"mcp",
|
||||
"httpx",
|
||||
"httpcore",
|
||||
"anyio",
|
||||
"sniffio",
|
||||
"starlette",
|
||||
"pydantic",
|
||||
"pydantic-core",
|
||||
"pydantic-settings",
|
||||
"uvicorn",
|
||||
"openai",
|
||||
"anthropic",
|
||||
"tiktoken",
|
||||
"agentscope",
|
||||
"agentscope-runtime",
|
||||
"reme-ai",
|
||||
"reme-auto-fin",
|
||||
"reme-daily-paper",
|
||||
"huggingface_hub",
|
||||
"modelscope",
|
||||
"openai-whisper",
|
||||
"openai-codex",
|
||||
"openai-codex-cli-bin",
|
||||
"qoder-agent-sdk",
|
||||
]
|
||||
for _pkg in _metadata_pkgs:
|
||||
try:
|
||||
datas += copy_metadata(_pkg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
a = Analysis(
|
||||
[
|
||||
str(SRC / "tauri" / "entry.py"),
|
||||
str(SRC / "tauri" / "cli_entry.py"),
|
||||
],
|
||||
pathex=[str(REPO_ROOT), str(REPO_ROOT / "src"), str(MAIL_MCP_SRC)],
|
||||
binaries=[*qoder_binaries, *codex_binaries],
|
||||
datas=datas,
|
||||
hiddenimports=[
|
||||
"codex_cli_bin",
|
||||
# uvicorn internals (not auto-discovered by PyInstaller)
|
||||
"uvicorn.logging",
|
||||
"uvicorn.loops",
|
||||
"uvicorn.loops.auto",
|
||||
"uvicorn.protocols",
|
||||
"uvicorn.protocols.http",
|
||||
"uvicorn.protocols.http.auto",
|
||||
"uvicorn.protocols.websockets",
|
||||
"uvicorn.protocols.websockets.auto",
|
||||
"uvicorn.lifespan",
|
||||
"uvicorn.lifespan.on",
|
||||
# All CLI sub-commands (dynamically loaded by Click)
|
||||
*collect_submodules("qwenpaw.cli"),
|
||||
# The mail MCP package lives under a second setuptools source root.
|
||||
*collect_submodules("qwenpawmail_mcp"),
|
||||
# All channel adapters (imported on-demand at runtime)
|
||||
*collect_submodules("qwenpaw.app.channels"),
|
||||
# ACP runner support is lazily imported by delegate_external_agent.
|
||||
*collect_submodules("qwenpaw.agents.acp"),
|
||||
# PawApp SDK modules are imported by installed app plugins at runtime.
|
||||
*collect_submodules("qwenpaw.pawapp"),
|
||||
# ASGI app entry points
|
||||
"qwenpaw.app._app",
|
||||
"qwenpaw.app.multi_agent_manager",
|
||||
"qwenpaw.app.chats",
|
||||
"qwenpaw.app.task_tracker",
|
||||
"qwenpaw.runtime.commands",
|
||||
# Backup modules are exposed through qwenpaw.backup.__getattr__, which
|
||||
# PyInstaller cannot discover from static imports.
|
||||
*collect_submodules("qwenpaw.backup"),
|
||||
# ReMe loads these plugin backends from plugin.yaml targets exposed by
|
||||
# distribution entry points, which are invisible to static analysis.
|
||||
*collect_submodules("reme_auto_fin"),
|
||||
*collect_submodules("reme_daily_paper"),
|
||||
# Third-party packages that use dynamic imports. Use
|
||||
# collect_submodules() for packages that load many submodules by name;
|
||||
# keep the bare package string when runtime code imports only the
|
||||
# package root or when PyInstaller needs the top-level module anchor.
|
||||
*collect_submodules("dotenv"),
|
||||
"dotenv",
|
||||
*collect_submodules("acp"),
|
||||
"acp",
|
||||
"psutil",
|
||||
"multipart",
|
||||
"websockets",
|
||||
"modelscope",
|
||||
"modelscope.hub.api",
|
||||
"modelscope.hub.snapshot_download",
|
||||
*collect_submodules("agentscope.tool._builtin._scripts"),
|
||||
*collect_submodules("agentscope.workspace._mcp_gateway"),
|
||||
*collect_submodules("whisper"),
|
||||
*collect_submodules("chromadb"),
|
||||
],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
noarchive=False,
|
||||
)
|
||||
|
||||
pyz = PYZ(a.pure)
|
||||
|
||||
def script_entry(file_name):
|
||||
for item in a.scripts:
|
||||
if Path(item[1]).name == file_name:
|
||||
return [item]
|
||||
raise SystemExit(f"script entry not found: {file_name}")
|
||||
|
||||
|
||||
backend_exe = EXE(
|
||||
pyz,
|
||||
script_entry("entry.py"),
|
||||
[],
|
||||
name="qwenpaw-backend",
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
# UPX triggers antivirus false positives and can corrupt binaries.
|
||||
upx=False,
|
||||
console=False,
|
||||
disable_windowed_traceback=True,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=codesign_identity,
|
||||
exclude_binaries=True,
|
||||
)
|
||||
|
||||
cli_exe = EXE(
|
||||
pyz,
|
||||
script_entry("cli_entry.py"),
|
||||
[],
|
||||
name="qwenpaw",
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=False,
|
||||
console=True,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=codesign_identity,
|
||||
exclude_binaries=True,
|
||||
)
|
||||
|
||||
coll = COLLECT(
|
||||
backend_exe,
|
||||
cli_exe,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
name="qwenpaw-backend",
|
||||
)
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env bash
|
||||
# Re-sign all Mach-O files in a macOS bundle/directory with one identity.
|
||||
#
|
||||
# PyInstaller collects Python frameworks and native extension libraries from
|
||||
# third-party packages. Re-signing every Mach-O file after collection keeps the
|
||||
# backend executable, Python runtime, and native dependencies in one signature
|
||||
# state before Tauri embeds them in the final app.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
TARGET="${1:?Usage: sign_macos_bundle.sh <target> [identity]}"
|
||||
IDENTITY="${2:-${APPLE_SIGNING_IDENTITY:--}}"
|
||||
|
||||
if [[ "$(uname -s)" != "Darwin" ]]; then
|
||||
echo "ERROR: macOS code signing must run on Darwin"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v codesign >/dev/null 2>&1; then
|
||||
echo "ERROR: codesign not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v file >/dev/null 2>&1; then
|
||||
echo "ERROR: file not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -e "${TARGET}" ]]; then
|
||||
echo "ERROR: signing target not found: ${TARGET}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
signing_args() {
|
||||
printf '%s\n' --force --sign "${IDENTITY}"
|
||||
if [[ "${IDENTITY}" == "-" ]]; then
|
||||
printf '%s\n' --timestamp=none
|
||||
fi
|
||||
}
|
||||
|
||||
is_macho() {
|
||||
file -b "$1" | grep -q "Mach-O"
|
||||
}
|
||||
|
||||
is_inside_framework() {
|
||||
[[ "$1" == *".framework/"* ]]
|
||||
}
|
||||
|
||||
codesign_file() {
|
||||
local path="$1"
|
||||
local args=()
|
||||
local arg
|
||||
|
||||
while IFS= read -r arg; do
|
||||
args+=("${arg}")
|
||||
done < <(signing_args)
|
||||
|
||||
codesign "${args[@]}" "${path}"
|
||||
}
|
||||
|
||||
codesign_bundle() {
|
||||
local path="$1"
|
||||
local args=()
|
||||
local arg
|
||||
|
||||
while IFS= read -r arg; do
|
||||
args+=("${arg}")
|
||||
done < <(signing_args)
|
||||
|
||||
codesign "${args[@]}" "${path}"
|
||||
}
|
||||
|
||||
echo "Signing macOS native files in ${TARGET}"
|
||||
echo "Signing identity: ${IDENTITY}"
|
||||
|
||||
signed_files=0
|
||||
while IFS= read -r -d '' path; do
|
||||
if is_inside_framework "${path}"; then
|
||||
continue
|
||||
fi
|
||||
if is_macho "${path}"; then
|
||||
codesign_file "${path}"
|
||||
signed_files=$((signed_files + 1))
|
||||
fi
|
||||
done < <(find "${TARGET}" -type f -print0)
|
||||
|
||||
# Framework directories carry their own bundle signature. Sign them after the
|
||||
# contained Mach-O files, then sign the app bundle last.
|
||||
signed_frameworks=0
|
||||
while IFS= read -r framework; do
|
||||
if [[ -n "${framework}" ]]; then
|
||||
codesign_bundle "${framework}"
|
||||
signed_frameworks=$((signed_frameworks + 1))
|
||||
fi
|
||||
done < <(find "${TARGET}" -type d -name "*.framework" | sort -r)
|
||||
|
||||
if [[ "${TARGET}" == *.app ]]; then
|
||||
codesign_bundle "${TARGET}"
|
||||
fi
|
||||
|
||||
echo "Signed ${signed_files} Mach-O files and ${signed_frameworks} frameworks"
|
||||
|
||||
if [[ "${TARGET}" == *.app ]]; then
|
||||
codesign --verify --deep --strict --verbose=2 "${TARGET}"
|
||||
else
|
||||
while IFS= read -r -d '' path; do
|
||||
if is_inside_framework "${path}"; then
|
||||
continue
|
||||
fi
|
||||
if is_macho "${path}"; then
|
||||
codesign --verify --verbose=2 "${path}"
|
||||
fi
|
||||
done < <(find "${TARGET}" -type f -print0)
|
||||
while IFS= read -r framework; do
|
||||
if [[ -n "${framework}" ]]; then
|
||||
codesign --verify --verbose=2 "${framework}"
|
||||
fi
|
||||
done < <(find "${TARGET}" -type d -name "*.framework" | sort -r)
|
||||
fi
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Stage a Node.js runtime for the Tauri desktop bundle."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import tarfile
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_NODE_VERSION = "v22.20.0"
|
||||
NODE_DIST_URL = "https://nodejs.org/dist"
|
||||
|
||||
|
||||
def _target() -> tuple[str, str, str]:
|
||||
system = platform.system()
|
||||
machine = platform.machine().lower()
|
||||
arch = {
|
||||
"amd64": "x64",
|
||||
"x86_64": "x64",
|
||||
"arm64": "arm64",
|
||||
"aarch64": "arm64",
|
||||
}.get(machine)
|
||||
if arch is None:
|
||||
raise SystemExit(f"unsupported machine architecture: {machine!r}")
|
||||
if system == "Windows":
|
||||
return "win", arch, "zip"
|
||||
if system == "Darwin":
|
||||
return "darwin", arch, "tar.xz"
|
||||
if system == "Linux":
|
||||
return "linux", arch, "tar.xz"
|
||||
raise SystemExit(f"unsupported platform: {system!r}")
|
||||
|
||||
|
||||
def _node_exe(dest: Path) -> Path:
|
||||
if platform.system() == "Windows":
|
||||
return dest / "node.exe"
|
||||
return dest / "bin" / "node"
|
||||
|
||||
|
||||
def _npx_exe(dest: Path) -> Path:
|
||||
if platform.system() == "Windows":
|
||||
return dest / "npx.cmd"
|
||||
return dest / "bin" / "npx"
|
||||
|
||||
|
||||
def _http_get(url: str) -> bytes:
|
||||
request = urllib.request.Request(url)
|
||||
request.add_header("User-Agent", "qwenpaw-build")
|
||||
with urllib.request.urlopen(request, timeout=120) as response:
|
||||
return response.read()
|
||||
|
||||
|
||||
def _extract(archive: Path, suffix: str, workdir: Path) -> Path:
|
||||
if suffix == "zip":
|
||||
with zipfile.ZipFile(archive) as zip_file:
|
||||
zip_file.extractall(workdir)
|
||||
else:
|
||||
with tarfile.open(archive, "r:xz") as tar:
|
||||
try:
|
||||
tar.extractall(workdir, filter="data")
|
||||
except TypeError:
|
||||
_validate_tar_members(tar, workdir)
|
||||
tar.extractall(workdir)
|
||||
|
||||
roots = [
|
||||
path
|
||||
for path in workdir.iterdir()
|
||||
if path.is_dir() and path.name.startswith("node-")
|
||||
]
|
||||
if len(roots) != 1:
|
||||
raise SystemExit("failed to locate extracted Node.js directory")
|
||||
return roots[0]
|
||||
|
||||
|
||||
def _validate_tar_members(tar: tarfile.TarFile, workdir: Path) -> None:
|
||||
root = workdir.resolve()
|
||||
for member in tar.getmembers():
|
||||
target = (root / member.name).resolve()
|
||||
try:
|
||||
target.relative_to(root)
|
||||
except ValueError:
|
||||
raise SystemExit(
|
||||
f"tar member escapes target: {member.name}",
|
||||
) from None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--dest", required=True)
|
||||
parser.add_argument(
|
||||
"--node-version",
|
||||
default=os.environ.get("QWENPAW_NODE_VERSION", DEFAULT_NODE_VERSION),
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
version = args.node_version
|
||||
platform_name, arch, suffix = _target()
|
||||
target = f"{platform_name}-{arch}"
|
||||
dest = Path(args.dest).resolve()
|
||||
marker = dest / ".node-runtime-version"
|
||||
|
||||
if (
|
||||
_node_exe(dest).is_file()
|
||||
and _npx_exe(dest).is_file()
|
||||
and marker.is_file()
|
||||
and marker.read_text(encoding="utf-8").strip() == f"{version}-{target}"
|
||||
):
|
||||
print(f"node-runtime already staged ({version}-{target}); skipping")
|
||||
return
|
||||
|
||||
archive_name = f"node-{version}-{target}.{suffix}"
|
||||
url = f"{NODE_DIST_URL}/{version}/{archive_name}"
|
||||
print(f"Staging Node.js {version} for {target}...")
|
||||
print(f"Downloading {url}")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmpdir = Path(tmp)
|
||||
archive = tmpdir / archive_name
|
||||
archive.write_bytes(_http_get(url))
|
||||
extracted = _extract(archive, suffix, tmpdir)
|
||||
|
||||
if dest.exists():
|
||||
shutil.rmtree(dest)
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
for item in extracted.iterdir():
|
||||
shutil.move(str(item), dest / item.name)
|
||||
|
||||
if not _node_exe(dest).is_file() or not _npx_exe(dest).is_file():
|
||||
raise SystemExit("staging failed: node or npx missing")
|
||||
marker.write_text(f"{version}-{target}", encoding="utf-8")
|
||||
print(f"Staged node-runtime at {dest}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,250 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Stage a standalone CPython runtime for the Tauri desktop bundle.
|
||||
|
||||
The Tauri backend is a PyInstaller-frozen executable, so ``sys.executable`` is
|
||||
not a usable Python interpreter. To install third-party *plugin* dependencies
|
||||
at runtime we ship a standalone CPython (python-build-standalone) whose
|
||||
``X.Y``/architecture match the frozen interpreter, and drive ``pip install``
|
||||
with it (see ``qwenpaw.plugins.loader``).
|
||||
|
||||
This script downloads the matching ``install_only`` build and extracts it to
|
||||
``<dest>/python``. The desktop build scripts use their bootstrap interpreter
|
||||
only to select the requested ``X.Y``; they then create the PyInstaller build
|
||||
environment from this staged interpreter. This makes python-build-standalone
|
||||
the shared binary source for both the frozen backend and the helper runtime.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
RELEASES_API_BASE = (
|
||||
"https://api.github.com/repos/astral-sh/"
|
||||
"python-build-standalone/releases"
|
||||
)
|
||||
DEFAULT_RELEASE = "20260623"
|
||||
RELEASE_ENV = "QWENPAW_PYTHON_BUILD_STANDALONE_RELEASE"
|
||||
HTTP_ATTEMPTS = 4
|
||||
HTTP_TIMEOUT_SECONDS = 120
|
||||
RETRYABLE_HTTP_STATUS = {408, 429, 500, 502, 503, 504}
|
||||
|
||||
|
||||
def _host_triple() -> str:
|
||||
system = platform.system()
|
||||
machine = platform.machine().lower()
|
||||
arch = {
|
||||
"amd64": "x86_64",
|
||||
"x86_64": "x86_64",
|
||||
"arm64": "aarch64",
|
||||
"aarch64": "aarch64",
|
||||
}.get(machine)
|
||||
if arch is None:
|
||||
raise SystemExit(f"unsupported machine architecture: {machine!r}")
|
||||
if system == "Windows":
|
||||
return f"{arch}-pc-windows-msvc"
|
||||
if system == "Darwin":
|
||||
return f"{arch}-apple-darwin"
|
||||
if system == "Linux":
|
||||
return f"{arch}-unknown-linux-gnu"
|
||||
raise SystemExit(f"unsupported platform: {system!r}")
|
||||
|
||||
|
||||
def _python_exe(dest: Path) -> Path:
|
||||
if platform.system() == "Windows":
|
||||
return dest / "python" / "python.exe"
|
||||
return dest / "python" / "bin" / "python3"
|
||||
|
||||
|
||||
def _http_get(url: str) -> bytes:
|
||||
request = urllib.request.Request(url)
|
||||
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
|
||||
if token:
|
||||
request.add_header("Authorization", f"Bearer {token}")
|
||||
request.add_header("User-Agent", "qwenpaw-build")
|
||||
for attempt in range(1, HTTP_ATTEMPTS + 1):
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
request,
|
||||
timeout=HTTP_TIMEOUT_SECONDS,
|
||||
) as resp:
|
||||
return resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
if (
|
||||
exc.code not in RETRYABLE_HTTP_STATUS
|
||||
or attempt == HTTP_ATTEMPTS
|
||||
):
|
||||
raise
|
||||
wait = 2 ** (attempt - 1)
|
||||
print(
|
||||
f"HTTP {exc.code} fetching {url}; "
|
||||
f"retrying in {wait}s ({attempt}/{HTTP_ATTEMPTS})",
|
||||
)
|
||||
except OSError as exc:
|
||||
if attempt == HTTP_ATTEMPTS:
|
||||
raise
|
||||
wait = 2 ** (attempt - 1)
|
||||
print(
|
||||
f"{type(exc).__name__} fetching {url}: {exc}; "
|
||||
f"retrying in {wait}s ({attempt}/{HTTP_ATTEMPTS})",
|
||||
)
|
||||
time.sleep(wait)
|
||||
raise RuntimeError(f"failed to fetch {url}")
|
||||
|
||||
|
||||
def _release_url(release: str | None) -> str:
|
||||
if release and release.lower() != "latest":
|
||||
return f"{RELEASES_API_BASE}/tags/{release}"
|
||||
return f"{RELEASES_API_BASE}/latest"
|
||||
|
||||
|
||||
def _release_data(release: str | None) -> dict[str, object]:
|
||||
return json.loads(_http_get(_release_url(release)).decode("utf-8"))
|
||||
|
||||
|
||||
def _preferred_release() -> str:
|
||||
release = os.environ.get(RELEASE_ENV, DEFAULT_RELEASE).strip()
|
||||
return release or "latest"
|
||||
|
||||
|
||||
def _asset_url_from_release(
|
||||
data: dict[str, object],
|
||||
xy: str,
|
||||
triple: str,
|
||||
) -> str | None:
|
||||
pattern = re.compile(
|
||||
rf"^cpython-{re.escape(xy)}\.\d+\+\d+-{re.escape(triple)}"
|
||||
r"-install_only\.tar\.gz$",
|
||||
)
|
||||
for asset in data.get("assets", []):
|
||||
if not isinstance(asset, dict):
|
||||
continue
|
||||
if pattern.match(str(asset.get("name", ""))):
|
||||
return str(asset["browser_download_url"])
|
||||
return None
|
||||
|
||||
|
||||
def _find_asset_url(xy: str, triple: str, release: str) -> tuple[str, str]:
|
||||
if release and release.lower() != "latest":
|
||||
try:
|
||||
data = _release_data(release)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 404:
|
||||
raise
|
||||
print(
|
||||
f"python-build-standalone release {release} not found; "
|
||||
"falling back to latest",
|
||||
)
|
||||
else:
|
||||
url = _asset_url_from_release(data, xy, triple)
|
||||
if url:
|
||||
return url, release
|
||||
print(
|
||||
f"no python-build-standalone install_only asset for "
|
||||
f"Python {xy} / {triple} in release {release}; "
|
||||
"falling back to latest",
|
||||
)
|
||||
|
||||
data = _release_data(None)
|
||||
url = _asset_url_from_release(data, xy, triple)
|
||||
if url:
|
||||
return url, str(data.get("tag_name", "latest"))
|
||||
raise SystemExit(
|
||||
f"no python-build-standalone install_only asset for "
|
||||
f"Python {xy} / {triple} in the latest release",
|
||||
)
|
||||
|
||||
|
||||
def _is_staged(dest: Path, marker: Path, marker_value: str) -> bool:
|
||||
return (
|
||||
_python_exe(dest).is_file()
|
||||
and marker.is_file()
|
||||
and marker.read_text(encoding="utf-8").strip() == marker_value
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--dest",
|
||||
required=True,
|
||||
help="Target directory (a 'python' subdir is created inside it)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--python-version",
|
||||
default=f"{sys.version_info.major}.{sys.version_info.minor}",
|
||||
help="CPython X.Y to stage (default: this interpreter's version)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
xy = args.python_version
|
||||
triple = _host_triple()
|
||||
dest = Path(args.dest).resolve()
|
||||
marker = dest / ".python-runtime-version"
|
||||
|
||||
preferred_release = _preferred_release()
|
||||
marker_value = f"{xy}-{triple}-{preferred_release}"
|
||||
# Fast path for pinned releases; latest/fallback cache hits need resolving
|
||||
# first so the marker check uses the actual release tag.
|
||||
if preferred_release.lower() != "latest" and _is_staged(
|
||||
dest,
|
||||
marker,
|
||||
marker_value,
|
||||
):
|
||||
print(f"python-runtime already staged ({marker_value}); skipping")
|
||||
return
|
||||
|
||||
print(f"Resolving standalone CPython {xy} for {triple}...")
|
||||
url, release = _find_asset_url(xy, triple, preferred_release)
|
||||
marker_value = f"{xy}-{triple}-{release}"
|
||||
if _is_staged(dest, marker, marker_value):
|
||||
print(f"python-runtime already staged ({marker_value}); skipping")
|
||||
return
|
||||
|
||||
print(f"Staging standalone CPython {xy} for {triple}...")
|
||||
print(f"Downloading {url}")
|
||||
|
||||
if dest.exists():
|
||||
import shutil
|
||||
|
||||
shutil.rmtree(dest)
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with tempfile.NamedTemporaryFile(
|
||||
suffix=".tar.gz",
|
||||
delete=False,
|
||||
) as tmp:
|
||||
tmp.write(_http_get(url))
|
||||
archive = tmp.name
|
||||
try:
|
||||
with tarfile.open(archive, "r:gz") as tar:
|
||||
# ``filter="data"`` is only available on newer CPython patch
|
||||
# releases (3.12+, backported to 3.10.12/3.11.4). Fall back to a
|
||||
# plain extract on older interpreters; the archive comes from the
|
||||
# trusted python-build-standalone release.
|
||||
try:
|
||||
tar.extractall(dest, filter="data")
|
||||
except TypeError:
|
||||
tar.extractall(dest)
|
||||
finally:
|
||||
os.unlink(archive)
|
||||
|
||||
exe = _python_exe(dest)
|
||||
if not exe.is_file():
|
||||
raise SystemExit(f"staging failed: interpreter missing at {exe}")
|
||||
marker.write_text(marker_value, encoding="utf-8")
|
||||
print(f"Staged python-runtime at {dest / 'python'}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,131 @@
|
||||
// Sync the Python PEP 440 version from src/qwenpaw/__version__.py into a
|
||||
// gitignored Tauri config override. Do not write the tracked tauri.conf.json:
|
||||
// its version would otherwise become a stale generated value after rebases.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(scriptDir, "../..");
|
||||
const versionFile = path.join(repoRoot, "src/qwenpaw/__version__.py");
|
||||
const tauriConfigFile = path.join(
|
||||
repoRoot,
|
||||
"console/src-tauri/tauri.conf.json",
|
||||
);
|
||||
const tauriVersionConfigFile = path.join(
|
||||
repoRoot,
|
||||
"console/src-tauri/tauri.version.conf.json",
|
||||
);
|
||||
|
||||
function readPythonVersion() {
|
||||
const text = fs.readFileSync(versionFile, "utf8");
|
||||
const match = text.match(/__version__\s*=\s*"([^"]+)"/);
|
||||
if (!match) {
|
||||
throw new Error(`Could not read __version__ from ${versionFile}`);
|
||||
}
|
||||
return match[1];
|
||||
}
|
||||
|
||||
function toSemver(version) {
|
||||
const match = version.match(
|
||||
/^(\d+)\.(\d+)\.(\d+)(?:(a|b|rc)(\d+))?(?:\.post(\d+))?(?:\.dev(\d+))?$/,
|
||||
);
|
||||
if (!match) {
|
||||
throw new Error(`Unsupported Python version for Tauri: ${version}`);
|
||||
}
|
||||
|
||||
const [, major, minor, patch, prerelease, prereleaseNumber, post, dev] =
|
||||
match;
|
||||
const prereleaseMap = { a: "alpha", b: "beta", rc: "rc" };
|
||||
const labels = [];
|
||||
if (prerelease)
|
||||
labels.push(`${prereleaseMap[prerelease]}.${prereleaseNumber}`);
|
||||
if (dev) labels.push(`dev.${dev}`);
|
||||
|
||||
const prereleaseSuffix = labels.length ? `-${labels.join(".")}` : "";
|
||||
const postMetadata = post ? `+post.${post}` : "";
|
||||
return `${major}.${minor}.${patch}${prereleaseSuffix}${postMetadata}`;
|
||||
}
|
||||
|
||||
function readBaseUpdaterConfig() {
|
||||
const config = JSON.parse(fs.readFileSync(tauriConfigFile, "utf8"));
|
||||
const updater = config?.plugins?.updater ?? {};
|
||||
if (!updater.pubkey) {
|
||||
throw new Error(
|
||||
`Could not read plugins.updater.pubkey from ${tauriConfigFile}`,
|
||||
);
|
||||
}
|
||||
return updater;
|
||||
}
|
||||
|
||||
function readUpdaterEndpoints(baseUpdater) {
|
||||
const raw = process.env.TAURI_UPDATER_ENDPOINTS?.trim();
|
||||
if (!raw) return baseUpdater.endpoints;
|
||||
|
||||
if (raw.startsWith("[")) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (
|
||||
!Array.isArray(parsed) ||
|
||||
parsed.some((entry) => typeof entry !== "string")
|
||||
) {
|
||||
throw new Error(
|
||||
"TAURI_UPDATER_ENDPOINTS JSON must be an array of strings",
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
return raw
|
||||
.split(/[\n,]/)
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function shouldCreateUpdaterArtifacts() {
|
||||
return Boolean(process.env.TAURI_SIGNING_PRIVATE_KEY?.trim());
|
||||
}
|
||||
|
||||
function writeTauriVersionConfig(file, version) {
|
||||
const baseUpdater = readBaseUpdaterConfig();
|
||||
const pubkey = process.env.TAURI_UPDATER_PUBKEY?.trim() || baseUpdater.pubkey;
|
||||
const endpoints = readUpdaterEndpoints(baseUpdater);
|
||||
const createUpdaterArtifacts = shouldCreateUpdaterArtifacts();
|
||||
const config = {
|
||||
version,
|
||||
...(createUpdaterArtifacts
|
||||
? {
|
||||
bundle: {
|
||||
createUpdaterArtifacts: true,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
plugins: {
|
||||
updater: {
|
||||
pubkey,
|
||||
...(endpoints?.length ? { endpoints } : {}),
|
||||
},
|
||||
},
|
||||
};
|
||||
fs.writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
|
||||
console.log(
|
||||
`Using updater pubkey from ${
|
||||
process.env.TAURI_UPDATER_PUBKEY?.trim()
|
||||
? "TAURI_UPDATER_PUBKEY"
|
||||
: "tauri.conf.json"
|
||||
}`,
|
||||
);
|
||||
if (process.env.TAURI_UPDATER_ENDPOINTS?.trim()) {
|
||||
console.log("Using updater endpoints from TAURI_UPDATER_ENDPOINTS");
|
||||
}
|
||||
console.log(
|
||||
createUpdaterArtifacts
|
||||
? "Creating Tauri updater artifacts"
|
||||
: "Skipping Tauri updater artifacts because TAURI_SIGNING_PRIVATE_KEY is not set",
|
||||
);
|
||||
}
|
||||
|
||||
const semver = toSemver(readPythonVersion());
|
||||
|
||||
writeTauriVersionConfig(tauriVersionConfigFile, semver);
|
||||
|
||||
console.log(`Wrote Tauri version override ${semver}`);
|
||||
Reference in new issue
Block a user