chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "0.3.1",
|
||||
"extension": {
|
||||
"version": "0.3.1",
|
||||
"source_commit": "da6bf4eed2dd7256567e152df8c903c87f6598c3"
|
||||
},
|
||||
"daemon": {
|
||||
"source_commit": "da6bf4eed2dd7256567e152df8c903c87f6598c3",
|
||||
"build": "cargo build --locked --release -p bsk"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
# BrowserSkill upstream integration
|
||||
|
||||
The extension and daemon are based on the official `ext-v0.3.1` tag, commit
|
||||
`da6bf4eed2dd7256567e152df8c903c87f6598c3` (including the upstream PRs #291,
|
||||
#296, #297 and #318 that Academy previously pinned from `main`). Both report
|
||||
version `0.3.1`; the exact source baseline is recorded in
|
||||
`scripts/browserskill-release.json`. The daemon is built with
|
||||
`cargo build --locked --release -p bsk` from the same commit because upstream
|
||||
has not published a matching CLI 0.3.1 binary. The store builds of extension
|
||||
0.3.1 match this baseline. Native builds
|
||||
require Rust/Cargo and a C compiler (plus CMake on Linux). Docker builds on the
|
||||
target architecture.
|
||||
|
||||
`scripts/build_browserskill.sh` builds the unmodified upstream checkout. No
|
||||
BrowserSkill patches are applied or maintained downstream.
|
||||
|
||||
Renderer read reliability is provided by upstream PR #318: snapshot/AX captures
|
||||
have a 20 s deadline, other bounded reads use 10 s, and a pending timed-out read
|
||||
blocks further guarded reads until it settles or its debugger session detaches.
|
||||
Navigation alone does not clear the gate. Errors retain
|
||||
`data.reason = renderer_read_timeout`; unavailable child frames can be omitted
|
||||
without discarding healthy frame content.
|
||||
|
||||
## Retired patches
|
||||
|
||||
| Former patch | Replacement |
|
||||
| --- | --- |
|
||||
| `01-browser-read-reliability.patch` | Upstream PR #318: bounded renderer reads, per-session read gates, capture fallback termination and debugger frame discovery. |
|
||||
| `02-gateway-task-controls.patch` | Upstream PR #296: the optional UI channel `ui.task_preview` / `ui.task_focus` (renamed from `gateway.*`). Academy calls the official methods. |
|
||||
| `03-vom-render-performance.patch` | Upstream PR #271 |
|
||||
| `04-task-popup-ownership.patch` | Upstream PR #297: popups opened by native click/key input inside the Agent Window become observed, controllable tabs that session stop preserves. |
|
||||
| `05-last-tab-lifecycle.patch` | Host side. `Manager.Call` runs `tool.tab_list` with `scope: "agent"` before `tool.tab_close`; when the target is the only tab in the Agent Window it first creates an agent-owned `about:blank` tab through `tool.tab_create`. Only official RPCs are involved. |
|
||||
| `06-navigation-response-deadline.patch` | Upstream PR #291 (daemon navigation response grace). |
|
||||
|
||||
Background execution and viewport/full-page screenshot support use upstream
|
||||
PRs #249, #250 and #253. Redirect document tracking and cancelled-navigation
|
||||
reconciliation use upstream code including PR #280. Remote authentication,
|
||||
credential storage/migration, renewal, connection settings and dedicated Agent
|
||||
Windows use upstream PR #227. Do not restore the old
|
||||
`remote-extension-connection.patch`, `shouldKeepTaskActive` callback or a second
|
||||
focus-emulation cache.
|
||||
|
||||
Retained tasks keep the official session and debugger; turn completion only
|
||||
stops preview polling in Academy. Completed tasks use native session stop.
|
||||
|
||||
## UI channel
|
||||
|
||||
The preview and focus side channel is now the official optional UI channel
|
||||
documented in the upstream
|
||||
[remote connection contract](https://github.com/Tencent/BrowserSkill/blob/da6bf4eed2dd7256567e152df8c903c87f6598c3/docs/remote-extension-connection.md#optional-ui-channel).
|
||||
Only authenticated remote sockets handle these request frames; they bypass the
|
||||
native automation queue and never start a session:
|
||||
|
||||
```json
|
||||
{"id":"wk-ui-unique","method":"ui.task_preview","params":{"session_id":"server-owned-session"}}
|
||||
```
|
||||
|
||||
- `ui.task_preview`: returns `image_base64`, `format: "jpeg"`, `tab_id`,
|
||||
`title` and `captured_at`; the frame is at most 640 pixels wide, captures are
|
||||
coalesced per task and a poll that arrives while Chrome still holds one is
|
||||
refused with `timeout` / `preview_busy`. Overlays stay visible in previews.
|
||||
- `ui.task_focus`: activates the task's owned tab and raises its window,
|
||||
returning `{ "focused": true }`.
|
||||
|
||||
Errors use the native envelope with typed codes (`not_found`, `timeout`,
|
||||
`cancelled`, `cdp_failed`) and an optional `data.reason`. Academy maps every
|
||||
error except `unknown_method` to a transient preview failure. Extensions built
|
||||
before PR #296 answer `unknown_method`;
|
||||
Academy then disables preview polling and reports the extension as outdated.
|
||||
|
||||
## Behavior of the 0.3.1 extension
|
||||
|
||||
- Remote tasks use official dedicated Agent Windows. No `tabGroups` permission.
|
||||
- Popup attribution follows upstream PR #297: only a main-frame navigation
|
||||
target from a controlled source during native click/key input, within the
|
||||
same Agent Window, becomes an observed tab. Observed tabs are readable and
|
||||
closable but never enter the agent-created set; session stop preserves them and their window. Independent
|
||||
popup windows, late or unattributed targets use `tab_borrow` and `tab_return`.
|
||||
An unowned tab that already sits in the Agent Window must be moved to a regular window before it
|
||||
can be borrowed.
|
||||
- Closing the last tab of the Agent Window through `tab_close` keeps an
|
||||
agent-owned blank tab until session stop (host-side, see above), so Chrome's
|
||||
window removal is not misreported as a human interruption. If the close is
|
||||
refused or interrupted while the target still exists, the blank tab is removed
|
||||
again. Actual user window closure still pauses the task.
|
||||
- Borrow confirmation follows the browser's preference and uses an HTTP(S) page
|
||||
in a regular user window. The integration fixture supplies such a page; neither
|
||||
extension settings nor a popup window can host the prompt. Borrowed tabs cannot
|
||||
be closed through `tab_close`. Return them with `tab_return`; if the original
|
||||
window disappeared, upstream may create a normal fallback window with a new-tab
|
||||
placeholder. These returned user pages are preserved when the task ends.
|
||||
- Human help follows the upstream focus/confirmation behavior.
|
||||
- Remote upload/download remain unsupported, as defined upstream.
|
||||
|
||||
Users need extension 0.3.1 or later, from the Chrome Web Store, Edge Add-ons or
|
||||
the bundled ZIP. Upgrade unpacked installs by replacing the existing extension
|
||||
directory and reloading it after ending active tasks. Keeping the extension ID preserves the
|
||||
migrated credentials; installing under a new ID requires pairing again.
|
||||
|
||||
## Validation
|
||||
|
||||
Use a clean pinned upstream checkout, install frozen dependencies and run:
|
||||
|
||||
```sh
|
||||
pnpm --filter @browser-skill/extension exec wxt prepare
|
||||
pnpm --filter @browser-skill/extension compile
|
||||
pnpm --filter @browser-skill/extension test
|
||||
pnpm --filter @browser-skill/vom test
|
||||
pnpm ext:build:zip
|
||||
BSK_GEOMETRY_CHROME=/path/to/test-chrome BSK_BACKGROUND_CHROME=/path/to/test-chrome \
|
||||
pnpm --filter @browser-skill/extension exec vitest run --maxWorkers=1 \
|
||||
src/tools/__tests__/background-execution.browser.test.ts \
|
||||
src/tools/__tests__/background-screenshot.browser.test.ts \
|
||||
src/tools/__tests__/background-full-page.browser.test.ts
|
||||
cargo test --locked -p bsk daemon::ipc::tests
|
||||
```
|
||||
|
||||
Run Academy's `TestRealExtension` with the built extension, pinned daemon and an
|
||||
isolated Chromium profile. It exercises actual pairing, screenshot and input RPC,
|
||||
same-window target selection/read/close, independent popup borrow/read/return and
|
||||
access revocation, the in-window borrow rejection followed by borrow
|
||||
approval/revocation of a tab moved to a regular window,
|
||||
independent preview during help waits, focus, pause/resume, retained-session
|
||||
continuity and completed-task cleanup. It separately verifies that agent
|
||||
last-tab closure permits the next turn and manual window closure blocks
|
||||
automation until explicit resume. Cleanup checks preserve the exact initial and
|
||||
returned user tab IDs, permitting only the new-tab placeholder recorded from an
|
||||
official fallback return; arbitrary extra tabs still fail the test.
|
||||
|
||||
```sh
|
||||
BROWSERSKILL_TEST_EXTENSION=/path/to/unpacked/chrome-mv3 \
|
||||
BROWSERSKILL_TEST_BINARY=/path/to/bsk \
|
||||
BROWSERSKILL_TEST_CHROMIUM=/path/to/test-chromium \
|
||||
BROWSERSKILL_TEST_PLAYWRIGHT=/path/to/playwright-core/index.mjs \
|
||||
go test ./internal/browserskill -run '^TestRealExtension$' -count=1 -v
|
||||
```
|
||||
|
||||
Upstream references: [PR #227](https://github.com/Tencent/BrowserSkill/pull/227),
|
||||
[PR #291](https://github.com/Tencent/BrowserSkill/pull/291),
|
||||
[PR #296](https://github.com/Tencent/BrowserSkill/pull/296),
|
||||
[PR #297](https://github.com/Tencent/BrowserSkill/pull/297),
|
||||
[PR #318](https://github.com/Tencent/BrowserSkill/pull/318).
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the anydoc static archive that the `anydoc` build tag links.
|
||||
#
|
||||
# The archive is a Rust build artifact (~30 MB), so it is neither committed nor
|
||||
# downloaded: this script builds it from third_party/anydoc-go, which pins the
|
||||
# published anydoc crate, and drops it where cgo looks for it.
|
||||
#
|
||||
# Usage:
|
||||
# scripts/build-anydoc-lib.sh # host platform
|
||||
# TARGET=aarch64-unknown-linux-musl scripts/build-anydoc-lib.sh
|
||||
set -euo pipefail
|
||||
|
||||
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
crate_dir="$repo_root/third_party/anydoc-go"
|
||||
|
||||
if ! command -v cargo >/dev/null 2>&1; then
|
||||
echo "error: cargo not found. Install Rust (https://rustup.rs) to build the anydoc archive." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The Rust target triple decides the archive; the directory name mirrors what
|
||||
# the cgo LDFLAGS in third_party/anydoc-go expect for that platform.
|
||||
target=${TARGET:-$(rustc -vV | sed -n 's/^host: //p')}
|
||||
case "$target" in
|
||||
x86_64-apple-darwin) lib_dir=darwin_amd64 ;;
|
||||
aarch64-apple-darwin) lib_dir=darwin_arm64 ;;
|
||||
x86_64-pc-windows-msvc) lib_dir=windows_amd64 ;;
|
||||
x86_64-unknown-linux-gnu) lib_dir=linux_amd64_gnu ;;
|
||||
aarch64-unknown-linux-gnu) lib_dir=linux_arm64_gnu ;;
|
||||
x86_64-unknown-linux-musl) lib_dir=linux_amd64_musl ;;
|
||||
aarch64-unknown-linux-musl) lib_dir=linux_arm64_musl ;;
|
||||
*)
|
||||
echo "error: unsupported target '$target'." >&2
|
||||
echo "Supported: {x86_64,aarch64}-{apple-darwin,unknown-linux-{gnu,musl}}, x86_64-pc-windows-msvc" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$target" in
|
||||
*windows-msvc) lib_name=anydoc_go.lib ;;
|
||||
*) lib_name=libanydoc_go.a ;;
|
||||
esac
|
||||
|
||||
# The crate version to patch is read from Cargo.toml rather than repeated here,
|
||||
# so an upgrade is a one-line change to the `anydoc = "=X.Y.Z"` pin.
|
||||
anydoc_version=$(sed -n 's/^anydoc = "=\([0-9][^"]*\)".*/\1/p' "$crate_dir/Cargo.toml" | head -1)
|
||||
if [ -z "$anydoc_version" ]; then
|
||||
echo "error: no pinned 'anydoc = \"=X.Y.Z\"' dependency in $crate_dir/Cargo.toml" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Include a patch revision so changes to our patches invalidate existing copies
|
||||
# even when the upstream anydoc version stays the same.
|
||||
anydoc_patch_id="$anydoc_version-zip9-v1"
|
||||
|
||||
# Copy the pinned version, expose the official serializer, and upgrade zip to
|
||||
# the fixed major version (upstream anydoc 0.2.4 still requires zip ^8.6.0).
|
||||
prepare_patched_anydoc() {
|
||||
local dest="$crate_dir/patched-anydoc"
|
||||
# The marker records the upstream version and patch revision: after a bump the
|
||||
# copy left by the previous build is the wrong crate, and reusing it would
|
||||
# fail deep inside cargo's patch resolution instead of here. Cargo.toml is
|
||||
# required too: a truncated leftover with only the marker would otherwise
|
||||
# skip the copy and fail with "failed to read .../Cargo.toml".
|
||||
if [ -f "$dest/.academy-patched" ] && [ "$(cat "$dest/.academy-patched")" = "$anydoc_patch_id" ] && [ -f "$dest/Cargo.toml" ]; then
|
||||
return
|
||||
fi
|
||||
|
||||
local src=""
|
||||
local cargo_home="${CARGO_HOME:-$HOME/.cargo}"
|
||||
src=$(find "$cargo_home/registry/src" -maxdepth 2 -type d -name "anydoc-$anydoc_version" 2>/dev/null | head -1 || true)
|
||||
|
||||
if [ -z "$src" ]; then
|
||||
local tarball="$crate_dir/.anydoc-$anydoc_version.crate"
|
||||
echo "Fetching anydoc $anydoc_version to patch document_to_markdown into the public API"
|
||||
if ! curl -fsSL "https://rsproxy.cn/api/v1/crates/anydoc/$anydoc_version/download" -o "$tarball"; then
|
||||
curl -fsSL "https://static.crates.io/crates/anydoc/anydoc-$anydoc_version.crate" -o "$tarball"
|
||||
fi
|
||||
local unpack="$crate_dir/.anydoc-unpack"
|
||||
rm -rf "$unpack"
|
||||
mkdir -p "$unpack"
|
||||
tar -xzf "$tarball" -C "$unpack"
|
||||
src=$(find "$unpack" -maxdepth 1 -type d -name "anydoc-$anydoc_version" | head -1)
|
||||
if [ -z "$src" ]; then
|
||||
echo "error: unpacked anydoc-$anydoc_version crate is missing" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
rm -rf "$dest"
|
||||
cp -R "$src" "$dest"
|
||||
if ! grep -q '^use render::markdown::document_to_markdown;$' "$dest/src/lib.rs"; then
|
||||
echo "error: anydoc $anydoc_version lib.rs no longer has the expected document_to_markdown import" >&2
|
||||
exit 1
|
||||
fi
|
||||
sed -i.bak 's/^use render::markdown::document_to_markdown;/pub use render::markdown::document_to_markdown;/' "$dest/src/lib.rs"
|
||||
rm -f "$dest/src/lib.rs.bak"
|
||||
# RUSTSEC-2026-0367/0368/0369 have no fix in zip 8.x. Only change zip's
|
||||
# version, preserving its deflate feature and disabled default features.
|
||||
# Fail on upstream manifest changes rather than silently leaving zip unpatched.
|
||||
if ! awk '
|
||||
/^\[/ { in_zip = ($0 == "[dependencies.zip]") }
|
||||
in_zip && /^version = / {
|
||||
if ($0 != "version = \"8.6.0\"") exit 1
|
||||
$0 = "version = \"9\""
|
||||
patched++
|
||||
}
|
||||
{ print }
|
||||
END { if (patched != 1) exit 1 }
|
||||
' "$dest/Cargo.toml" > "$dest/Cargo.toml.tmp"; then
|
||||
echo "error: anydoc $anydoc_version no longer has the expected zip 8.6.0 dependency" >&2
|
||||
exit 1
|
||||
fi
|
||||
mv "$dest/Cargo.toml.tmp" "$dest/Cargo.toml"
|
||||
printf '%s\n' "$anydoc_patch_id" > "$dest/.academy-patched"
|
||||
rm -rf "$crate_dir/.anydoc-unpack" "$crate_dir/.anydoc-$anydoc_version.crate"
|
||||
}
|
||||
|
||||
# version.go is what the parser reports as `anydoc_version` on every parsed
|
||||
# document, so a bump that misses it would mislabel the whole knowledge base.
|
||||
go_version=$(sed -n 's/^const Version = "\([^"]*\)".*/\1/p' "$crate_dir/version.go" | head -1)
|
||||
if [ "$go_version" != "$anydoc_version" ]; then
|
||||
echo "error: version.go says '$go_version' but Cargo.toml pins anydoc '$anydoc_version'." >&2
|
||||
echo "Bump both: the Go constant is the version Academy records for parsed documents." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Building anydoc $anydoc_version archive for $target"
|
||||
prepare_patched_anydoc
|
||||
|
||||
# --locked: build exactly the dependency versions in the committed Cargo.lock.
|
||||
# That lockfile is what pins the patched pdf-inspector/lopdf, so a silent
|
||||
# resolver drift must fail the build rather than ship an unaudited tree.
|
||||
cargo build --release --locked --manifest-path "$crate_dir/Cargo.toml" --target "$target"
|
||||
|
||||
dest="$crate_dir/lib/$lib_dir"
|
||||
mkdir -p "$dest"
|
||||
cp "$crate_dir/target/$target/release/$lib_name" "$dest/$lib_name"
|
||||
|
||||
echo "Wrote $dest/$lib_name"
|
||||
echo "Build Academy with the archive: go build -tags anydoc ./cmd/server"
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
output_dir="${1:-$repo_root/artifacts/browserskill}"
|
||||
# Offline fast-path: when artifacts/browserskill already carries a prebuilt
|
||||
# daemon + extension (e.g. extracted from a previously built image), reuse it
|
||||
# instead of cloning from GitHub — keeps air-gapped/flaky-network rebuilds
|
||||
# working. The dir is NOT part of the upstream tree, so upstream builds are
|
||||
# unaffected and keep the full clone+build path below.
|
||||
if [ -f "$repo_root/artifacts/browserskill/bsk" ] && [ -d "$repo_root/artifacts/browserskill" ]; then
|
||||
mkdir -p "$output_dir"
|
||||
cp -r "$repo_root/artifacts/browserskill/." "$output_dir/"
|
||||
echo "BrowserSkill: using prebuilt artifacts from artifacts/browserskill"
|
||||
exit 0
|
||||
fi
|
||||
# Optional Docker-style target; native builds default to the host platform.
|
||||
target_platform="${2:-}"
|
||||
case "$target_platform" in
|
||||
""|linux/amd64|linux/arm64|darwin/amd64|darwin/arm64) ;;
|
||||
*) echo "Unsupported BrowserSkill target: $target_platform" >&2; exit 1 ;;
|
||||
esac
|
||||
# Build both ends from the same pinned protocol baseline.
|
||||
source_commit="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["extension"]["source_commit"])' "$repo_root/scripts/browserskill-release.json")"
|
||||
extension_version="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["extension"]["version"])' "$repo_root/scripts/browserskill-release.json")"
|
||||
# Native builds only. Docker runs this stage on TARGETPLATFORM so C/Rust
|
||||
# dependencies and the produced daemon match the final image architecture.
|
||||
host_os="$(uname -s | tr '[:upper:]' '[:lower:]')"
|
||||
host_arch="$(uname -m)"
|
||||
case "$host_arch" in arm64|aarch64) host_arch=arm64 ;; x86_64) host_arch=amd64 ;; esac
|
||||
if [ -n "$target_platform" ] && [ "$target_platform" != "$host_os/$host_arch" ]; then
|
||||
echo "Run the BrowserSkill build on $target_platform (host is $host_os/$host_arch)" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! command -v cargo >/dev/null && [ -x "${CARGO_HOME:-$HOME/.cargo}/bin/cargo" ]; then
|
||||
export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH"
|
||||
fi
|
||||
command -v cargo >/dev/null || { echo "Rust/Cargo is required to build the matching BrowserSkill daemon" >&2; exit 1; }
|
||||
daemon_commit="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["daemon"]["source_commit"])' "$repo_root/scripts/browserskill-release.json")"
|
||||
[ "$daemon_commit" = "$source_commit" ] || { echo "BrowserSkill daemon/extension baseline mismatch" >&2; exit 1; }
|
||||
mkdir -p "$output_dir"
|
||||
output_dir="$(cd "$output_dir" && pwd)"
|
||||
build_dir="$(mktemp -d /tmp/academy-bsk-build.XXXXXX)"
|
||||
trap 'rm -rf "$build_dir"' EXIT
|
||||
|
||||
git clone --no-checkout https://github.com/Tencent/BrowserSkill.git "$build_dir/source"
|
||||
git -C "$build_dir/source" checkout --detach "$source_commit"
|
||||
(
|
||||
cd "$build_dir/source"
|
||||
npx --yes pnpm@10.17.0 install --frozen-lockfile
|
||||
npx --yes pnpm@10.17.0 ext:build:zip
|
||||
)
|
||||
cp "$build_dir/source/apps/extension/dist/browser-skillextension-${extension_version}-chrome.zip" "$output_dir/browser-skill-academy-${extension_version}.zip"
|
||||
cp "$build_dir/source/LICENSE" "$output_dir/BrowserSkill-LICENSE"
|
||||
|
||||
# Build the daemon from the same pinned source; upstream has not published a
|
||||
# matching CLI 0.3.1 binary.
|
||||
cargo_target_dir="${CARGO_TARGET_DIR:-$build_dir/target}"
|
||||
mkdir -p "$cargo_target_dir"
|
||||
cargo_target_dir="$(cd "$cargo_target_dir" && pwd)"
|
||||
(
|
||||
cd "$build_dir/source"
|
||||
# Use the installed toolchain; do not let the checkout's moving "stable"
|
||||
# override force a network update during each application build.
|
||||
RUSTUP_TOOLCHAIN="${RUSTUP_TOOLCHAIN:-stable}" cargo build --locked --release -p bsk --target-dir "$cargo_target_dir"
|
||||
)
|
||||
# Replace atomically: overwriting an executing inode can invalidate macOS code pages.
|
||||
staged_binary="$(mktemp "$output_dir/.bsk-XXXXXX")"
|
||||
install -m 755 "$cargo_target_dir/release/bsk" "$staged_binary"
|
||||
mv -f "$staged_binary" "$output_dir/bsk"
|
||||
echo "BrowserSkill $extension_version extension and daemon: $output_dir"
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build frontend static assets for Lite / desktop packaging (host-side).
|
||||
# Docker UI images use the multi-stage frontend/Dockerfile instead — no host npm.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
|
||||
if [ -z "${VITE_FRONTEND_COMMIT:-}" ]; then
|
||||
# shellcheck source=/dev/null
|
||||
eval "$("$PROJECT_ROOT/scripts/get_version.sh" env)"
|
||||
export VITE_FRONTEND_COMMIT="${COMMIT_ID:-unknown}"
|
||||
fi
|
||||
|
||||
export VITE_IS_DOCKER="${VITE_IS_DOCKER:-true}"
|
||||
|
||||
cd "$PROJECT_ROOT/frontend"
|
||||
npm ci
|
||||
npm run build
|
||||
@@ -0,0 +1,470 @@
|
||||
#!/bin/bash
|
||||
# 该脚本用于从源码构建Academy的所有Docker镜像
|
||||
|
||||
# 设置颜色
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # 无颜色
|
||||
|
||||
# 获取项目根目录(脚本所在目录的上一级)
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
|
||||
|
||||
# 启用 BuildKit
|
||||
export DOCKER_BUILDKIT=1
|
||||
|
||||
# 版本信息
|
||||
VERSION="1.0.0"
|
||||
SCRIPT_NAME=$(basename "$0")
|
||||
|
||||
# 显示帮助信息
|
||||
show_help() {
|
||||
echo -e "${GREEN}Academy 镜像构建脚本 v${VERSION}${NC}"
|
||||
echo -e "${GREEN}用法:${NC} $0 [选项]"
|
||||
echo "选项:"
|
||||
echo " -h, --help 显示帮助信息"
|
||||
echo " -a, --all 构建所有镜像(默认)"
|
||||
echo " -p, --app 仅构建应用镜像"
|
||||
echo " -d, --docreader 仅构建文档读取器镜像"
|
||||
echo " -f, --frontend 仅构建前端镜像"
|
||||
echo " -s, --sandbox 仅构建沙箱镜像"
|
||||
echo " -c, --clean 清理所有本地镜像"
|
||||
echo " -v, --version 显示版本信息"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# 显示版本信息
|
||||
show_version() {
|
||||
echo -e "${GREEN}Academy 镜像构建脚本 v${VERSION}${NC}"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# 日志函数
|
||||
log_info() {
|
||||
echo -e "${BLUE}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
echo -e "${YELLOW}[WARNING]${NC} $1"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
echo -e "${RED}[ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
echo -e "${GREEN}[SUCCESS]${NC} $1"
|
||||
}
|
||||
|
||||
# 检查Docker是否已安装
|
||||
check_docker() {
|
||||
log_info "检查Docker环境..."
|
||||
|
||||
if ! command -v docker &> /dev/null; then
|
||||
log_error "未安装Docker,请先安装Docker"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 检查Docker服务运行状态
|
||||
if ! docker info &> /dev/null; then
|
||||
log_error "Docker服务未运行,请启动Docker服务"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_success "Docker环境检查通过"
|
||||
return 0
|
||||
}
|
||||
|
||||
# 检测平台
|
||||
check_platform() {
|
||||
log_info "检测系统平台信息..."
|
||||
if [ "$(uname -m)" = "x86_64" ]; then
|
||||
export PLATFORM="linux/amd64"
|
||||
export TARGETARCH="amd64"
|
||||
elif [ "$(uname -m)" = "aarch64" ] || [ "$(uname -m)" = "arm64" ]; then
|
||||
export PLATFORM="linux/arm64"
|
||||
export TARGETARCH="arm64"
|
||||
else
|
||||
log_warning "未识别的平台类型:$(uname -m),将使用默认平台 linux/amd64"
|
||||
export PLATFORM="linux/amd64"
|
||||
export TARGETARCH="amd64"
|
||||
fi
|
||||
log_info "当前平台:$PLATFORM"
|
||||
log_info "当前架构:$TARGETARCH"
|
||||
}
|
||||
|
||||
# 获取版本信息
|
||||
get_version_info() {
|
||||
# 从VERSION文件获取版本号
|
||||
if [ -f "VERSION" ]; then
|
||||
VERSION=$(cat VERSION | tr -d '\n\r')
|
||||
else
|
||||
VERSION="unknown"
|
||||
fi
|
||||
|
||||
# 获取commit ID
|
||||
if command -v git >/dev/null 2>&1; then
|
||||
COMMIT_ID=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
|
||||
else
|
||||
COMMIT_ID="unknown"
|
||||
fi
|
||||
|
||||
# 获取构建时间
|
||||
BUILD_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
|
||||
|
||||
# 获取Go版本
|
||||
if command -v go >/dev/null 2>&1; then
|
||||
GO_VERSION=$(go version 2>/dev/null || echo "unknown")
|
||||
else
|
||||
GO_VERSION="unknown"
|
||||
fi
|
||||
|
||||
log_info "版本信息: $VERSION"
|
||||
log_info "Commit ID: $COMMIT_ID"
|
||||
log_info "构建时间: $BUILD_TIME"
|
||||
log_info "Go版本: $GO_VERSION"
|
||||
}
|
||||
|
||||
# 构建应用镜像
|
||||
build_app_image() {
|
||||
log_info "构建应用镜像 (academy-app)..."
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 获取版本信息
|
||||
get_version_info
|
||||
|
||||
docker build \
|
||||
--platform $PLATFORM \
|
||||
--build-arg GOPRIVATE_ARG=${GOPRIVATE:-""} \
|
||||
--build-arg GOPROXY_ARG=${GOPROXY:-"https://goproxy.cn,direct"} \
|
||||
--build-arg GOSUMDB_ARG=${GOSUMDB:-"off"} \
|
||||
--build-arg APK_MIRROR_ARG="${APK_MIRROR_ARG:-}" \
|
||||
--build-arg VERSION_ARG="$VERSION" \
|
||||
--build-arg COMMIT_ID_ARG="$COMMIT_ID" \
|
||||
--build-arg BUILD_TIME_ARG="$BUILD_TIME" \
|
||||
--build-arg GO_VERSION_ARG="$GO_VERSION" \
|
||||
--build-arg WITH_ANYDOC=${WITH_ANYDOC:-1} \
|
||||
-f docker/Dockerfile.app \
|
||||
-t wechatopenai/weknora-app:latest \
|
||||
.
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
log_success "应用镜像构建成功"
|
||||
return 0
|
||||
else
|
||||
log_error "应用镜像构建失败"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 构建文档读取器镜像
|
||||
build_docreader_image() {
|
||||
log_info "构建文档读取器镜像 (academy-docreader)..."
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
docker build \
|
||||
--platform $PLATFORM \
|
||||
--build-arg PLATFORM=$PLATFORM \
|
||||
--build-arg TARGETARCH=$TARGETARCH \
|
||||
--build-arg APT_MIRROR="${APT_MIRROR:-}" \
|
||||
--build-arg PLAYWRIGHT_DOWNLOAD_HOST="${PLAYWRIGHT_DOWNLOAD_HOST:-}" \
|
||||
--build-arg PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST="${PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST:-}" \
|
||||
-f docker/Dockerfile.docreader \
|
||||
-t wechatopenai/weknora-docreader:latest \
|
||||
.
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
log_success "文档读取器镜像构建成功"
|
||||
return 0
|
||||
else
|
||||
log_error "文档读取器镜像构建失败"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 构建前端镜像(多阶段:npm 在 builder 内执行,无需宿主机预构建 dist)
|
||||
build_frontend_image() {
|
||||
log_info "构建前端镜像 (academy-ui)..."
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 获取版本信息(用于注入前端 commit hash)
|
||||
get_version_info
|
||||
|
||||
docker build \
|
||||
--platform $PLATFORM \
|
||||
--build-arg VITE_FRONTEND_COMMIT="$COMMIT_ID" \
|
||||
${NPM_REGISTRY:+--build-arg NPM_REGISTRY="$NPM_REGISTRY"} \
|
||||
${NODE_MAX_OLD_SPACE_SIZE:+--build-arg NODE_MAX_OLD_SPACE_SIZE="$NODE_MAX_OLD_SPACE_SIZE"} \
|
||||
-f frontend/Dockerfile \
|
||||
-t wechatopenai/weknora-ui:latest \
|
||||
frontend/
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
log_success "前端镜像构建成功"
|
||||
return 0
|
||||
else
|
||||
log_error "前端镜像构建失败"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 构建沙箱镜像
|
||||
build_sandbox_image() {
|
||||
log_info "构建沙箱镜像 (academy-sandbox)..."
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 同时打上 main:默认镜像跟的是 main(见 sandbox.go 的 DefaultDockerImage),
|
||||
# 而 Docker 后端只在本地缺失时才去拉,本地不打这个标签就等于白构建。
|
||||
docker build \
|
||||
--platform $PLATFORM \
|
||||
--build-arg TARGETPLATFORM=$PLATFORM \
|
||||
-f docker/Dockerfile.sandbox \
|
||||
--target sandbox \
|
||||
-t wechatopenai/weknora-sandbox:latest \
|
||||
-t wechatopenai/weknora-sandbox:main \
|
||||
.
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "沙箱镜像构建失败"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Cube 从镜像直接构建模板,并以 :49983/health 探活,缺 envd 必然失败,
|
||||
# 因此 Cube 用的是注入了 envd 的变体镜像。详见 website-docs/06-development/04-sandbox-deployment.md。
|
||||
log_info "构建沙箱镜像 Cube 变体 (academy-sandbox:main-cube)..."
|
||||
|
||||
docker build \
|
||||
--platform $PLATFORM \
|
||||
--build-arg TARGETPLATFORM=$PLATFORM \
|
||||
-f docker/Dockerfile.sandbox \
|
||||
--target cube \
|
||||
-t wechatopenai/weknora-sandbox:latest-cube \
|
||||
-t wechatopenai/weknora-sandbox:main-cube \
|
||||
.
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "沙箱镜像 Cube 变体构建失败"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Desktop variant: XFCE + x11vnc + websockify. Tagged for E2B template
|
||||
# builds; the Docker backend does not consume this image yet.
|
||||
log_info "构建沙箱镜像桌面变体 (academy-sandbox:main-desktop)..."
|
||||
|
||||
docker build \
|
||||
--platform $PLATFORM \
|
||||
--build-arg TARGETPLATFORM=$PLATFORM \
|
||||
-f docker/Dockerfile.sandbox \
|
||||
--target desktop \
|
||||
-t wechatopenai/weknora-sandbox:latest-desktop \
|
||||
-t wechatopenai/weknora-sandbox:main-desktop \
|
||||
.
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "沙箱镜像桌面变体构建失败"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "构建沙箱镜像桌面 Cube 变体 (academy-sandbox:main-desktop-cube)..."
|
||||
|
||||
docker build \
|
||||
--platform $PLATFORM \
|
||||
--build-arg TARGETPLATFORM=$PLATFORM \
|
||||
-f docker/Dockerfile.sandbox \
|
||||
--target desktop-cube \
|
||||
-t wechatopenai/weknora-sandbox:latest-desktop-cube \
|
||||
-t wechatopenai/weknora-sandbox:main-desktop-cube \
|
||||
.
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
log_success "沙箱镜像构建成功"
|
||||
return 0
|
||||
else
|
||||
log_error "沙箱镜像桌面 Cube 变体构建失败"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 构建所有镜像
|
||||
build_all_images() {
|
||||
log_info "开始构建所有镜像..."
|
||||
|
||||
local app_result=0
|
||||
local docreader_result=0
|
||||
local frontend_result=0
|
||||
local sandbox_result=0
|
||||
|
||||
# 构建应用镜像
|
||||
build_app_image
|
||||
app_result=$?
|
||||
|
||||
# 构建文档读取器镜像
|
||||
build_docreader_image
|
||||
docreader_result=$?
|
||||
|
||||
# 构建前端镜像
|
||||
build_frontend_image
|
||||
frontend_result=$?
|
||||
|
||||
# 构建沙箱镜像
|
||||
build_sandbox_image
|
||||
sandbox_result=$?
|
||||
|
||||
# 显示构建结果
|
||||
echo ""
|
||||
log_info "=== 构建结果 ==="
|
||||
if [ $app_result -eq 0 ]; then
|
||||
log_success "✓ 应用镜像构建成功"
|
||||
else
|
||||
log_error "✗ 应用镜像构建失败"
|
||||
fi
|
||||
|
||||
if [ $docreader_result -eq 0 ]; then
|
||||
log_success "✓ 文档读取器镜像构建成功"
|
||||
else
|
||||
log_error "✗ 文档读取器镜像构建失败"
|
||||
fi
|
||||
|
||||
if [ $frontend_result -eq 0 ]; then
|
||||
log_success "✓ 前端镜像构建成功"
|
||||
else
|
||||
log_error "✗ 前端镜像构建失败"
|
||||
fi
|
||||
|
||||
if [ $sandbox_result -eq 0 ]; then
|
||||
log_success "✓ 沙箱镜像构建成功"
|
||||
else
|
||||
log_error "✗ 沙箱镜像构建失败"
|
||||
fi
|
||||
|
||||
if [ $app_result -eq 0 ] && [ $docreader_result -eq 0 ] && [ $frontend_result -eq 0 ] && [ $sandbox_result -eq 0 ]; then
|
||||
log_success "所有镜像构建完成!"
|
||||
return 0
|
||||
else
|
||||
log_error "部分镜像构建失败"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 清理本地镜像
|
||||
clean_images() {
|
||||
log_info "清理本地Academy镜像..."
|
||||
|
||||
# 停止相关容器
|
||||
log_info "停止相关容器..."
|
||||
docker stop $(docker ps -q --filter "ancestor=wechatopenai/weknora-app:latest" 2>/dev/null) 2>/dev/null || true
|
||||
docker stop $(docker ps -q --filter "ancestor=wechatopenai/weknora-docreader:latest" 2>/dev/null) 2>/dev/null || true
|
||||
docker stop $(docker ps -q --filter "ancestor=wechatopenai/weknora-ui:latest" 2>/dev/null) 2>/dev/null || true
|
||||
|
||||
# 删除相关容器
|
||||
log_info "删除相关容器..."
|
||||
docker rm $(docker ps -aq --filter "ancestor=wechatopenai/weknora-app:latest" 2>/dev/null) 2>/dev/null || true
|
||||
docker rm $(docker ps -aq --filter "ancestor=wechatopenai/weknora-docreader:latest" 2>/dev/null) 2>/dev/null || true
|
||||
docker rm $(docker ps -aq --filter "ancestor=wechatopenai/weknora-ui:latest" 2>/dev/null) 2>/dev/null || true
|
||||
|
||||
# 删除镜像
|
||||
log_info "删除本地镜像..."
|
||||
docker rmi wechatopenai/weknora-app:latest 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-docreader:latest 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-ui:latest 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:latest 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:latest-cube 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:latest-desktop 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:latest-desktop-cube 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:main 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:main-cube 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:main-desktop 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:main-desktop-cube 2>/dev/null || true
|
||||
|
||||
docker image prune -f
|
||||
|
||||
log_success "镜像清理完成"
|
||||
return 0
|
||||
}
|
||||
|
||||
# 解析命令行参数
|
||||
BUILD_ALL=false
|
||||
BUILD_APP=false
|
||||
BUILD_DOCREADER=false
|
||||
BUILD_FRONTEND=false
|
||||
BUILD_SANDBOX=false
|
||||
CLEAN_IMAGES=false
|
||||
|
||||
# 没有参数时默认构建所有镜像
|
||||
if [ $# -eq 0 ]; then
|
||||
BUILD_ALL=true
|
||||
fi
|
||||
|
||||
while [ "$1" != "" ]; do
|
||||
case $1 in
|
||||
-h | --help ) show_help
|
||||
;;
|
||||
-a | --all ) BUILD_ALL=true
|
||||
;;
|
||||
-p | --app ) BUILD_APP=true
|
||||
;;
|
||||
-d | --docreader ) BUILD_DOCREADER=true
|
||||
;;
|
||||
-f | --frontend ) BUILD_FRONTEND=true
|
||||
;;
|
||||
-s | --sandbox ) BUILD_SANDBOX=true
|
||||
;;
|
||||
-c | --clean ) CLEAN_IMAGES=true
|
||||
;;
|
||||
-v | --version ) show_version
|
||||
;;
|
||||
* ) log_error "未知选项: $1"
|
||||
show_help
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# 检查Docker环境
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检测平台
|
||||
check_platform
|
||||
|
||||
# 执行清理操作
|
||||
if [ "$CLEAN_IMAGES" = true ]; then
|
||||
clean_images
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# 执行构建操作
|
||||
if [ "$BUILD_ALL" = true ]; then
|
||||
build_all_images
|
||||
exit $?
|
||||
fi
|
||||
|
||||
if [ "$BUILD_APP" = true ]; then
|
||||
build_app_image
|
||||
exit $?
|
||||
fi
|
||||
|
||||
if [ "$BUILD_DOCREADER" = true ]; then
|
||||
build_docreader_image
|
||||
exit $?
|
||||
fi
|
||||
|
||||
if [ "$BUILD_FRONTEND" = true ]; then
|
||||
build_frontend_image
|
||||
exit $?
|
||||
fi
|
||||
|
||||
if [ "$BUILD_SANDBOX" = true ]; then
|
||||
build_sandbox_image
|
||||
exit $?
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/bin/bash
|
||||
# 检查开发环境配置
|
||||
|
||||
# 设置颜色
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # 无颜色
|
||||
|
||||
# 获取项目根目录
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
|
||||
|
||||
log_info() {
|
||||
printf "%b\n" "${BLUE}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
printf "%b\n" "${GREEN}[✓]${NC} $1"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
printf "%b\n" "${RED}[✗]${NC} $1"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
printf "%b\n" "${YELLOW}[!]${NC} $1"
|
||||
}
|
||||
|
||||
echo ""
|
||||
printf "%b\n" "${GREEN}========================================${NC}"
|
||||
printf "%b\n" "${GREEN} Academy 开发环境配置检查${NC}"
|
||||
printf "%b\n" "${GREEN}========================================${NC}"
|
||||
echo ""
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 检查 .env 文件
|
||||
log_info "检查 .env 文件..."
|
||||
if [ -f ".env" ]; then
|
||||
log_success ".env 文件存在"
|
||||
else
|
||||
log_error ".env 文件不存在"
|
||||
echo ""
|
||||
log_info "解决方法:"
|
||||
echo " 1. 复制示例文件: cp .env.example .env"
|
||||
echo " 2. 编辑 .env 文件并配置必要的环境变量"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
log_info "检查必要的环境变量..."
|
||||
|
||||
# 加载 .env 文件
|
||||
set -a
|
||||
source .env
|
||||
set +a
|
||||
|
||||
# 检查必要的环境变量
|
||||
errors=0
|
||||
|
||||
check_var() {
|
||||
local var_name=$1
|
||||
local var_value="${!var_name}"
|
||||
|
||||
if [ -z "$var_value" ]; then
|
||||
log_error "$var_name 未设置"
|
||||
errors=$((errors + 1))
|
||||
else
|
||||
log_success "$var_name = $var_value"
|
||||
fi
|
||||
}
|
||||
|
||||
# 数据库配置
|
||||
log_info "数据库配置:"
|
||||
check_var "DB_DRIVER"
|
||||
check_var "DB_HOST"
|
||||
check_var "DB_PORT"
|
||||
check_var "DB_USER"
|
||||
check_var "DB_PASSWORD"
|
||||
check_var "DB_NAME"
|
||||
|
||||
echo ""
|
||||
log_info "存储配置:"
|
||||
check_var "STORAGE_TYPE"
|
||||
|
||||
if [ "$STORAGE_TYPE" = "minio" ]; then
|
||||
check_var "MINIO_BUCKET_NAME"
|
||||
fi
|
||||
|
||||
if [ "$STORAGE_TYPE" = "tos" ]; then
|
||||
check_var "TOS_ENDPOINT"
|
||||
check_var "TOS_REGION"
|
||||
check_var "TOS_ACCESS_KEY"
|
||||
check_var "TOS_SECRET_KEY"
|
||||
check_var "TOS_BUCKET_NAME"
|
||||
fi
|
||||
|
||||
if [ "$STORAGE_TYPE" = "s3" ]; then
|
||||
check_var "S3_REGION"
|
||||
check_var "S3_BUCKET_NAME"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
log_info "Redis 配置:"
|
||||
check_var "REDIS_ADDR"
|
||||
|
||||
echo ""
|
||||
log_info "Ollama 配置:"
|
||||
check_var "OLLAMA_BASE_URL"
|
||||
|
||||
echo ""
|
||||
log_info "模型配置:"
|
||||
if [ -n "$INIT_LLM_MODEL_NAME" ]; then
|
||||
log_success "INIT_LLM_MODEL_NAME = $INIT_LLM_MODEL_NAME"
|
||||
else
|
||||
log_warning "INIT_LLM_MODEL_NAME 未设置(可选)"
|
||||
fi
|
||||
|
||||
if [ -n "$INIT_EMBEDDING_MODEL_NAME" ]; then
|
||||
log_success "INIT_EMBEDDING_MODEL_NAME = $INIT_EMBEDDING_MODEL_NAME"
|
||||
else
|
||||
log_warning "INIT_EMBEDDING_MODEL_NAME 未设置(可选)"
|
||||
fi
|
||||
|
||||
# 检查 Go 环境
|
||||
echo ""
|
||||
log_info "检查 Go 环境..."
|
||||
if command -v go &> /dev/null; then
|
||||
go_version=$(go version)
|
||||
log_success "Go 已安装: $go_version"
|
||||
else
|
||||
log_error "Go 未安装"
|
||||
errors=$((errors + 1))
|
||||
fi
|
||||
|
||||
# 检查 Air
|
||||
if command -v air &> /dev/null; then
|
||||
log_success "Air 已安装(支持热重载)"
|
||||
else
|
||||
log_warning "Air 未安装(可选,用于热重载)"
|
||||
log_info "安装命令: go install github.com/air-verse/air@latest"
|
||||
fi
|
||||
|
||||
# 检查 npm
|
||||
echo ""
|
||||
log_info "检查 Node.js 环境..."
|
||||
if command -v npm &> /dev/null; then
|
||||
npm_version=$(npm --version)
|
||||
log_success "npm 已安装: $npm_version"
|
||||
else
|
||||
log_error "npm 未安装"
|
||||
errors=$((errors + 1))
|
||||
fi
|
||||
|
||||
# 检查 Docker
|
||||
echo ""
|
||||
log_info "检查 Docker 环境..."
|
||||
if command -v docker &> /dev/null; then
|
||||
docker_version=$(docker --version)
|
||||
log_success "Docker 已安装: $docker_version"
|
||||
|
||||
if docker info &> /dev/null; then
|
||||
log_success "Docker 服务正在运行"
|
||||
else
|
||||
log_error "Docker 服务未运行"
|
||||
errors=$((errors + 1))
|
||||
fi
|
||||
else
|
||||
log_error "Docker 未安装"
|
||||
errors=$((errors + 1))
|
||||
fi
|
||||
|
||||
# 检查 Docker Compose
|
||||
if docker compose version &> /dev/null; then
|
||||
compose_version=$(docker compose version)
|
||||
log_success "Docker Compose 已安装: $compose_version"
|
||||
elif command -v docker-compose &> /dev/null; then
|
||||
compose_version=$(docker-compose --version)
|
||||
log_success "docker-compose 已安装: $compose_version"
|
||||
else
|
||||
log_error "Docker Compose 未安装"
|
||||
errors=$((errors + 1))
|
||||
fi
|
||||
|
||||
# 总结
|
||||
echo ""
|
||||
printf "%b\n" "${GREEN}========================================${NC}"
|
||||
if [ $errors -eq 0 ]; then
|
||||
log_success "所有检查通过!环境配置正常"
|
||||
echo ""
|
||||
log_info "下一步:"
|
||||
echo " 1. 启动开发环境: make dev-start"
|
||||
echo " 2. 启动后端: make dev-app"
|
||||
echo " 3. 启动前端: make dev-frontend"
|
||||
else
|
||||
log_error "发现 $errors 个问题,请修复后再启动开发环境"
|
||||
echo ""
|
||||
log_info "常见问题:"
|
||||
echo " - 如果 .env 文件不存在,请复制 .env.example"
|
||||
echo " - 确保 DB_DRIVER 设置为 'postgres' 或 'mysql'"
|
||||
echo " - 确保 Docker 服务正在运行"
|
||||
fi
|
||||
printf "%b\n" "${GREEN}========================================${NC}"
|
||||
echo ""
|
||||
|
||||
exit $errors
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
license_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
source_dir="${1:-}"
|
||||
if [ -n "${source_dir}" ]; then
|
||||
source_dir="$(cd "${source_dir}" && pwd)"
|
||||
fi
|
||||
cd "${license_root}"
|
||||
|
||||
# A retained build-graph dependency would bring the GPL converter back even if
|
||||
# application code no longer imported it directly.
|
||||
if grep -Eq 'github.com/(longbridgeapp/opencc|liuzl/(da|cedar-go)|adamzy/cedar-go)([[:space:]]|$)' go.mod go.sum; then
|
||||
echo "Removed conversion dependencies have reappeared in go.mod/go.sum" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
test -s licenses/sources/modules.tsv
|
||||
while read -r module_name module_version checksum; do
|
||||
[[ "${checksum}" =~ ^[0-9a-f]{64}$ ]] || { echo "Invalid source checksum for ${module_name}" >&2; exit 1; }
|
||||
actual_version="$(awk -v name="${module_name}" '$1 == name { print $2 }' go.mod)"
|
||||
if [ "${actual_version}" != "${module_version}" ]; then
|
||||
echo "Update the source manifest for ${module_name}: expected ${module_version}, got ${actual_version}" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "${source_dir}" ]; then
|
||||
archive="${module_name##*/}-${module_version}.zip"
|
||||
(
|
||||
cd "${source_dir}"
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
printf '%s %s\n' "${checksum}" "${archive}" | sha256sum -c -
|
||||
else
|
||||
printf '%s %s\n' "${checksum}" "${archive}" | shasum -a 256 -c -
|
||||
fi
|
||||
)
|
||||
fi
|
||||
done < licenses/sources/modules.tsv
|
||||
|
||||
for file in LICENSE THIRD_PARTY_NOTICES.md licenses/OpenCC-Apache-2.0.txt \
|
||||
licenses/go-sql-driver-mysql-MPL-2.0.txt licenses/go-m1cpu-MPL-2.0.txt \
|
||||
licenses/Wails-MIT.txt; do
|
||||
test -s "${file}"
|
||||
done
|
||||
@@ -0,0 +1,5 @@
|
||||
# 云镜像维护脚本
|
||||
|
||||
脚本边界、制镜像注意事项与首启排障统一维护在 [website-docs 开发指南](../../website-docs/06-development/01-dev-guide.md#cloud-image-scripts)。普通安装请使用[安装部署](../../website-docs/01-getting-started/02-installation.md)。
|
||||
|
||||
本目录保留 `prepare.sh`、`cleanup.sh`、`firstboot.sh` 及其 systemd 单元。`cleanup.sh` 会清除制作机的数据、密钥、SSH 授权与缓存并关机,只能用于专用制作机;参数和实际行为以脚本为准。
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
# cleanup.sh - 在制作云镜像前清理私密数据。
|
||||
# 警告: 本脚本会删除 SSH 公钥、清空数据库与日志,最后会自动关机。
|
||||
# 执行后请直接在云控制台「制作镜像 / 创建快照 / 创建 AMI」,不要再 SSH 进来。
|
||||
set -euo pipefail
|
||||
|
||||
ACADEMY_DIR="${ACADEMY_DIR:-/opt/Academy}"
|
||||
|
||||
if [[ "${EUID}" -ne 0 ]]; then
|
||||
echo "[cleanup] 请使用 sudo 或 root 运行" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
read -r -p "[cleanup] 该操作不可逆,确认继续? 输入 YES 继续: " ans
|
||||
if [[ "${ans}" != "YES" ]]; then
|
||||
echo "[cleanup] 已取消"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "[cleanup] 1/8 停止 Academy 容器"
|
||||
COMPOSE_PROJECT=""
|
||||
if [[ -d "${ACADEMY_DIR}" ]]; then
|
||||
cd "${ACADEMY_DIR}"
|
||||
# 优先用 compose ls 拿到真实 project 名 (默认是目录名小写, 如 academy)
|
||||
COMPOSE_PROJECT="$(docker compose ls --format json 2>/dev/null \
|
||||
| grep -oE '"Name":"[^"]+"' | head -1 | cut -d'"' -f4 || true)"
|
||||
docker compose down -v --remove-orphans || true
|
||||
fi
|
||||
|
||||
echo "[cleanup] 2/8 清空 Academy 业务数据 + 首启 marker / 日志"
|
||||
if [[ -d "${ACADEMY_DIR}" ]]; then
|
||||
rm -rf "${ACADEMY_DIR}/data"/* "${ACADEMY_DIR}/logs"/* 2>/dev/null || true
|
||||
# 故意不在这里重建 .env: 让镜像里 .env 缺失, 任何在 firstboot 之前
|
||||
# 起来的 docker compose 都会因找不到 .env 而失败, 避免明文默认密码
|
||||
# (postgres123!@# 之类) 把 postgres 数据卷初始化坏。
|
||||
# firstboot.sh 自己会从 .env.example 拷贝并替换密钥。
|
||||
rm -f "${ACADEMY_DIR}/.env" "${ACADEMY_DIR}/.firstboot.done"
|
||||
fi
|
||||
rm -f /root/academy-credentials.txt /var/log/academy-firstboot.log
|
||||
|
||||
echo "[cleanup] 3/8 清理残留 docker 卷与构建缓存"
|
||||
# 严格按 compose project 名前缀匹配, 避免误伤同宿主上其它 postgres/redis 卷。
|
||||
if [[ -n "${COMPOSE_PROJECT}" ]]; then
|
||||
docker volume ls -q --filter "label=com.docker.compose.project=${COMPOSE_PROJECT}" \
|
||||
| xargs -r docker volume rm -f || true
|
||||
fi
|
||||
# 注意: 这里只清"卷 / 已停容器 / 构建缓存", 绝对不能清镜像。
|
||||
# 此前用过 `docker system prune -af --volumes`, 会把 prepare.sh 预拉的
|
||||
# wechatopenai/weknora-* 等镜像一并清掉, 导致基于镜像建出来的新实例
|
||||
# 在 firstboot 时还要重新从 Docker Hub 拉数 GB 镜像, 完全违背预装初衷。
|
||||
docker container prune -f || true
|
||||
docker builder prune -af || true
|
||||
# 只清未挂载的 dangling 卷 (此时 compose down -v 已清掉业务卷)
|
||||
docker volume prune -f || true
|
||||
|
||||
echo "[cleanup] 4/8 清空系统日志"
|
||||
journalctl --rotate || true
|
||||
journalctl --vacuum-time=1s || true
|
||||
find /var/log -type f \( -name '*.log' -o -name '*.gz' -o -name '*.[0-9]' \) -print0 \
|
||||
| xargs -0 -r truncate -s 0 || true
|
||||
find /var/log -type f \( -name '*.gz' -o -name '*.[0-9]' \) -print0 \
|
||||
| xargs -0 -r rm -f || true
|
||||
|
||||
echo "[cleanup] 5/8 清理 SSH 历史与授权 key(执行后将无法 SSH 进来)"
|
||||
rm -f /root/.ssh/authorized_keys /root/.ssh/known_hosts /root/.bash_history
|
||||
for d in /home/*; do
|
||||
[[ -d "$d" ]] || continue
|
||||
rm -f "$d/.ssh/authorized_keys" "$d/.ssh/known_hosts" "$d/.bash_history"
|
||||
done
|
||||
find / -xdev -type f \( -name 'id_rsa*' -o -name '*.pem' -o -name '*.key' \) \
|
||||
-not -path '/etc/ssl/*' -not -path '/usr/*' -not -path '/var/lib/docker/*' 2>/dev/null \
|
||||
| tee /tmp/cleanup-secrets-found.txt || true
|
||||
echo "[cleanup] ↑ 上面是疑似遗留的密钥文件,必要时人工再核对"
|
||||
|
||||
echo "[cleanup] 6/8 重置 cloud-init / machine-id(让新实例拿到新 ID)"
|
||||
cloud-init clean --logs --seed 2>/dev/null || true
|
||||
truncate -s 0 /etc/machine-id || true
|
||||
rm -f /var/lib/dbus/machine-id || true
|
||||
|
||||
echo "[cleanup] 7/8 清理 apt / tmp"
|
||||
if command -v apt-get >/dev/null 2>&1; then
|
||||
apt-get clean
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
fi
|
||||
rm -rf /tmp/* /var/tmp/* /root/.cache /home/*/.cache 2>/dev/null || true
|
||||
|
||||
echo "[cleanup] 8/8 同步磁盘并关机"
|
||||
history -c || true
|
||||
sync
|
||||
echo
|
||||
echo " 即将关机。关机完成后请到云控制台执行「制作镜像 / 创建快照 / 创建 AMI」。"
|
||||
echo
|
||||
sleep 3
|
||||
poweroff
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env bash
|
||||
# firstboot.sh - 由 academy-firstboot.service 在新实例首次开机时自动执行。
|
||||
# 任务: 生成随机密钥写入 .env -> 启动容器 -> 输出凭证 -> 标记完成 + 自禁用。
|
||||
#
|
||||
# 幂等性策略:
|
||||
# 1) 一上来先写 ${MARKER} 标记 "已生成过密钥",
|
||||
# 之后即便 docker compose 失败导致脚本中断, 重启后由 unit 的
|
||||
# ConditionPathExists=!${MARKER} 拦住, 不会再生成新密钥覆盖 .env。
|
||||
# (旧密钥已经写进 postgres 数据卷, 二次生成会导致数据库永久无法登录)
|
||||
# 2) 失败时 unit 标记 failed, 用户可手动 docker compose up -d 恢复;
|
||||
# 凭证仍可在 ${ENV_FILE} 中查到。
|
||||
set -euo pipefail
|
||||
|
||||
ACADEMY_DIR="${ACADEMY_DIR:-/opt/Academy}"
|
||||
ENV_FILE="${ACADEMY_DIR}/.env"
|
||||
ENV_TEMPLATE="${ACADEMY_DIR}/.env.example"
|
||||
CRED_FILE="/root/academy-credentials.txt"
|
||||
LOG_FILE="/var/log/academy-firstboot.log"
|
||||
MARKER="${ACADEMY_DIR}/.firstboot.done"
|
||||
|
||||
# 提前打开 LOG_FILE, 同时把 stderr 也复制一份到 systemd journal 方便调试
|
||||
# (单纯 exec >> LOG_FILE 时, 脚本一开始的失败会因为 stderr 已被吞掉而看不到)
|
||||
mkdir -p "$(dirname "${LOG_FILE}")"
|
||||
exec > >(tee -a "${LOG_FILE}") 2>&1
|
||||
echo "==== firstboot started at $(date -Iseconds) ===="
|
||||
|
||||
if [[ -f "${MARKER}" ]]; then
|
||||
echo "marker ${MARKER} exists, skip (already initialized)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# cleanup.sh 不再保留 .env, 这里从 .env.example 拷贝模板再做替换。
|
||||
# 这样保证 firstboot 之前不会有任何含明文默认密码的 .env 让 academy.service
|
||||
# 抢先把 postgres 数据卷用错的密码初始化掉。
|
||||
if [[ ! -f "${ENV_FILE}" ]]; then
|
||||
if [[ -f "${ENV_TEMPLATE}" ]]; then
|
||||
echo "creating ${ENV_FILE} from ${ENV_TEMPLATE}"
|
||||
cp "${ENV_TEMPLATE}" "${ENV_FILE}"
|
||||
else
|
||||
echo "ERROR: neither ${ENV_FILE} nor ${ENV_TEMPLATE} found"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
DOCKER_BIN="$(command -v docker || true)"
|
||||
if [[ -z "${DOCKER_BIN}" ]]; then
|
||||
echo "ERROR: docker binary not found in PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 生成 32 字节强随机字符串(用于 AES-256 key, 必须刚好 32 字节)
|
||||
# 用 `() ... ()` 启子 shell 并关闭 pipefail: head 只读 N 字节后关闭 stdin,
|
||||
# tr 会收到 SIGPIPE (退出码 141), 在 `set -o pipefail` 下整条管道被判失败,
|
||||
# 触发顶层 `set -e` 把 firstboot.sh 8ms exit 1 干掉。
|
||||
gen32() ( set +o pipefail; LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom | head -c 32 )
|
||||
# 通用密码: 24 字符, 不含 / + = (避免出现在 URL / sed 替换时出问题)
|
||||
genpw() ( set +o pipefail; LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom | head -c 24 )
|
||||
|
||||
DB_PWD=$(genpw)
|
||||
REDIS_PWD=$(genpw)
|
||||
JWT=$(genpw)$(genpw)
|
||||
SYS_AES=$(gen32)
|
||||
|
||||
# 用 | 作 sed 分隔符避免冲突; 仅替换以 KEY= 开头的行
|
||||
replace() {
|
||||
local key="$1" val="$2"
|
||||
if grep -qE "^${key}=" "${ENV_FILE}"; then
|
||||
sed -i "s|^${key}=.*|${key}=${val}|" "${ENV_FILE}"
|
||||
else
|
||||
echo "${key}=${val}" >>"${ENV_FILE}"
|
||||
fi
|
||||
}
|
||||
|
||||
replace DB_PASSWORD "${DB_PWD}"
|
||||
replace REDIS_PASSWORD "${REDIS_PWD}"
|
||||
replace JWT_SECRET "${JWT}"
|
||||
replace SYSTEM_AES_KEY "${SYS_AES}"
|
||||
replace GIN_MODE "release"
|
||||
|
||||
# 把 prepare.sh 阶段记录在 .cloud-image-meta 里的 ACADEMY_REF 还原为 .env 的
|
||||
# ACADEMY_VERSION, 否则 docker compose 会落回 :latest 默认值, 导致镜像版本
|
||||
# 与 prepare 时拉取的版本不一致。
|
||||
META_FILE="${ACADEMY_DIR}/.cloud-image-meta"
|
||||
if [[ -f "${META_FILE}" ]]; then
|
||||
META_REF=$(grep -E '^ACADEMY_REF=' "${META_FILE}" | tail -1 | cut -d= -f2- || true)
|
||||
if [[ -n "${META_REF}" ]]; then
|
||||
replace ACADEMY_VERSION "${META_REF}"
|
||||
echo "restored ACADEMY_VERSION=${META_REF} from ${META_FILE}"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 关键: .env 改完立刻写 marker。
|
||||
# 这之后即便 docker compose up 失败, 重启也不会再次重写 .env,
|
||||
# 防止与 postgres 已经持久化的密码不一致。
|
||||
umask 077
|
||||
touch "${MARKER}"
|
||||
chmod 0600 "${MARKER}"
|
||||
|
||||
echo "env updated, marker written, starting docker compose..."
|
||||
cd "${ACADEMY_DIR}"
|
||||
"${DOCKER_BIN}" compose up -d
|
||||
|
||||
# 尝试拿公网 IP, 失败就用内网
|
||||
PUB_IP=$(curl -fsS --max-time 5 https://ifconfig.me 2>/dev/null \
|
||||
|| curl -fsS --max-time 5 https://api.ipify.org 2>/dev/null \
|
||||
|| hostname -I | awk '{print $1}')
|
||||
|
||||
cat >"${CRED_FILE}" <<INFO
|
||||
========================================
|
||||
Academy 实例初始化完成
|
||||
生成时间: $(date -Iseconds)
|
||||
========================================
|
||||
|
||||
访问地址 : http://${PUB_IP}
|
||||
|
||||
注册后如需关闭后续注册, 编辑 ${ENV_FILE}:
|
||||
DISABLE_REGISTRATION=true
|
||||
然后执行: cd ${ACADEMY_DIR} && docker compose up -d
|
||||
|
||||
下列随机凭证已写入 ${ENV_FILE}, 请妥善保存(仅 root 可读):
|
||||
DB_PASSWORD = ${DB_PWD}
|
||||
REDIS_PASSWORD = ${REDIS_PWD}
|
||||
JWT_SECRET = ${JWT}
|
||||
SYSTEM_AES_KEY = ${SYS_AES}
|
||||
|
||||
注意:
|
||||
- 本文件只反映首启时刻的密钥, 后续以 ${ENV_FILE} 为准。
|
||||
- 切勿直接对外暴露 5432 / 6379 / 9000 等基础设施端口。
|
||||
- 仅用 80 / 443 对外服务, 必要时配置反向代理 + HTTPS。
|
||||
|
||||
INFO
|
||||
|
||||
echo "credentials written to ${CRED_FILE}"
|
||||
|
||||
# 仅停掉 unit, 不删 unit 文件 (否则当前正在运行的 oneshot 可能被 systemd 标记 failed)。
|
||||
# 下次重启时, academy-firstboot.service 通过 ConditionPathExists=!${MARKER} 自动跳过。
|
||||
systemctl disable academy-firstboot.service || true
|
||||
|
||||
echo "==== firstboot finished at $(date -Iseconds) ===="
|
||||
@@ -0,0 +1,234 @@
|
||||
#!/usr/bin/env bash
|
||||
# prepare.sh - 在干净的 Linux 实例上部署 Academy 运行时, 用于制作云镜像模板。
|
||||
# 不需要 clone 整个 Academy 仓库, 只下载 4 个运行时文件 (~100KB)。
|
||||
# 兼容: Ubuntu / Debian / CentOS / Rocky / TencentOS 等带 systemd + Docker 的发行版。
|
||||
# 使用方式: sudo bash prepare.sh
|
||||
# 可调环境变量:
|
||||
# ACADEMY_REF 要拉取的 git ref (tag / branch / commit), 默认 main
|
||||
# ACADEMY_DIR 部署目录, 默认 /opt/Academy
|
||||
# ACADEMY_REPO 仓库地址, 默认 https://github.com/Tencent/WeKnora
|
||||
# ACADEMY_GH_PROXY GitHub 加速前缀, 默认空。中国大陆机器可设
|
||||
# https://gh-proxy.com/ 或 https://ghfast.top/
|
||||
# (实际下载地址变成 ${ACADEMY_GH_PROXY}${ACADEMY_REPO}/archive/...)
|
||||
# DOCKER_INSTALL_MIRROR Docker 安装包镜像源, 默认空 (走 get.docker.com)。
|
||||
# 中国大陆机器境外 CDN 不通时设为, 例如:
|
||||
# https://mirrors.tencent.com/docker-ce/linux/ubuntu
|
||||
# https://mirrors.aliyun.com/docker-ce/linux/ubuntu
|
||||
# 会改用 apt + docker-ce 官方仓库镜像安装,
|
||||
# 含 docker-ce / containerd.io / docker-compose-plugin,
|
||||
# 完全不访问 get.docker.com。仅支持 apt 系发行版。
|
||||
# DOCKER_REGISTRY_MIRROR Docker Hub 加速器, 默认空。腾讯云内网可设
|
||||
# https://mirror.ccs.tencentyun.com
|
||||
# (会写入 /etc/docker/daemon.json 并重启 docker)
|
||||
# PRUNE_OLD_IMAGES 升级场景下是否清理 dangling / 旧版本 tag 镜像,
|
||||
# 默认 false。设为 true 时在拉新镜像之后执行
|
||||
# `docker image prune -af`, 把没有容器引用的镜像
|
||||
# (含旧 ACADEMY_VERSION 的 wechatopenai/weknora-*)
|
||||
# 一次性删掉, 减少要打进云镜像的体积。
|
||||
set -euo pipefail
|
||||
|
||||
ACADEMY_REF="${ACADEMY_REF:-main}"
|
||||
ACADEMY_DIR="${ACADEMY_DIR:-/opt/Academy}"
|
||||
ACADEMY_REPO="${ACADEMY_REPO:-https://github.com/Tencent/WeKnora}"
|
||||
ACADEMY_GH_PROXY="${ACADEMY_GH_PROXY:-}"
|
||||
DOCKER_INSTALL_MIRROR="${DOCKER_INSTALL_MIRROR:-}"
|
||||
DOCKER_REGISTRY_MIRROR="${DOCKER_REGISTRY_MIRROR:-}"
|
||||
PRUNE_OLD_IMAGES="${PRUNE_OLD_IMAGES:-false}"
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
if [[ "${EUID}" -ne 0 ]]; then
|
||||
echo "[prepare] 请使用 sudo 或 root 运行" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 通过镜像源 apt 安装 docker-ce 全家桶 (含 compose-plugin)。
|
||||
# 用于中国大陆云主机直连 get.docker.com 被 RST 的场景。
|
||||
install_docker_via_apt_mirror() {
|
||||
local mirror="$1"
|
||||
if ! command -v apt-get >/dev/null 2>&1; then
|
||||
echo "[prepare] DOCKER_INSTALL_MIRROR 目前仅支持 apt 系发行版 (Ubuntu/Debian)" >&2
|
||||
return 1
|
||||
fi
|
||||
apt-get update -y
|
||||
apt-get install -y ca-certificates curl gnupg lsb-release
|
||||
install -m 0755 -d /etc/apt/keyrings
|
||||
curl -fsSL "${mirror%/}/gpg" | gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpg
|
||||
chmod a+r /etc/apt/keyrings/docker.gpg
|
||||
local arch codename
|
||||
arch="$(dpkg --print-architecture)"
|
||||
codename="$(lsb_release -cs)"
|
||||
echo "deb [arch=${arch} signed-by=/etc/apt/keyrings/docker.gpg] ${mirror%/} ${codename} stable" \
|
||||
> /etc/apt/sources.list.d/docker.list
|
||||
apt-get update -y
|
||||
apt-get install -y docker-ce docker-ce-cli containerd.io \
|
||||
docker-buildx-plugin docker-compose-plugin curl tar
|
||||
}
|
||||
|
||||
echo "[prepare] 1/6 安装 Docker 与依赖"
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
if [[ -n "${DOCKER_INSTALL_MIRROR}" ]]; then
|
||||
echo "[prepare] 通过 ${DOCKER_INSTALL_MIRROR} 走 apt 安装 docker-ce (跳过 get.docker.com)"
|
||||
install_docker_via_apt_mirror "${DOCKER_INSTALL_MIRROR}"
|
||||
else
|
||||
curl -fsSL https://get.docker.com | bash
|
||||
fi
|
||||
fi
|
||||
systemctl enable --now docker
|
||||
|
||||
if ! docker compose version >/dev/null 2>&1; then
|
||||
if command -v apt-get >/dev/null 2>&1; then
|
||||
apt-get update -y
|
||||
apt-get install -y docker-compose-plugin curl tar
|
||||
elif command -v yum >/dev/null 2>&1; then
|
||||
yum install -y docker-compose-plugin curl tar
|
||||
fi
|
||||
fi
|
||||
|
||||
# 可选: 配置 Docker Hub 加速器, 解决直连 registry-1.docker.io 超时的场景
|
||||
# (典型: 中国大陆云主机 / 内网受限环境)。仅在用户显式传入时才动 daemon.json。
|
||||
if [[ -n "${DOCKER_REGISTRY_MIRROR}" ]]; then
|
||||
echo "[prepare] 1.5/6 配置 Docker Hub 加速器: ${DOCKER_REGISTRY_MIRROR}"
|
||||
mkdir -p /etc/docker
|
||||
# 已存在的 daemon.json 走 python 合并, 避免覆盖用户其它配置
|
||||
if [[ -s /etc/docker/daemon.json ]] && command -v python3 >/dev/null 2>&1; then
|
||||
python3 - "$DOCKER_REGISTRY_MIRROR" <<'PY'
|
||||
import json, sys, pathlib
|
||||
p = pathlib.Path("/etc/docker/daemon.json")
|
||||
mirror = sys.argv[1]
|
||||
try:
|
||||
cfg = json.loads(p.read_text())
|
||||
except Exception:
|
||||
cfg = {}
|
||||
mirrors = cfg.get("registry-mirrors") or []
|
||||
if mirror not in mirrors:
|
||||
mirrors.insert(0, mirror)
|
||||
cfg["registry-mirrors"] = mirrors
|
||||
p.write_text(json.dumps(cfg, indent=2) + "\n")
|
||||
PY
|
||||
else
|
||||
cat >/etc/docker/daemon.json <<EOF
|
||||
{
|
||||
"registry-mirrors": ["${DOCKER_REGISTRY_MIRROR}"]
|
||||
}
|
||||
EOF
|
||||
fi
|
||||
systemctl restart docker
|
||||
# 给 docker daemon 一点重启时间, 避免下面 docker compose pull 立刻拿到 EOF
|
||||
for _ in 1 2 3 4 5; do
|
||||
docker info >/dev/null 2>&1 && break
|
||||
sleep 1
|
||||
done
|
||||
fi
|
||||
|
||||
echo "[prepare] 2/6 拉取 Academy 运行时文件 (ref=${ACADEMY_REF})"
|
||||
# 只下载实际需要的 4 个文件, 不 clone 整个仓库 (~MB 级 -> ~KB 级)
|
||||
mkdir -p "${ACADEMY_DIR}/config"
|
||||
|
||||
tmp=$(mktemp -d)
|
||||
trap 'rm -rf "${tmp}"' EXIT
|
||||
|
||||
tarball_url="${ACADEMY_GH_PROXY}${ACADEMY_REPO}/archive/${ACADEMY_REF}.tar.gz"
|
||||
echo "[prepare] tarball: ${tarball_url}"
|
||||
curl -fsSL "${tarball_url}" -o "${tmp}/repo.tar.gz"
|
||||
# 仅解压需要的路径, 显著加速且省空间
|
||||
tar -xzf "${tmp}/repo.tar.gz" -C "${tmp}" \
|
||||
--wildcards \
|
||||
'*/docker-compose.yml' \
|
||||
'*/.env.example' \
|
||||
'*/config/config.yaml'
|
||||
src=$(find "${tmp}" -maxdepth 1 -mindepth 1 -type d -name 'Academy-*' | head -1)
|
||||
if [[ -z "${src}" ]]; then
|
||||
echo "[prepare] 解压失败, 未找到 Academy-* 目录" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp "${src}/docker-compose.yml" "${ACADEMY_DIR}/"
|
||||
cp "${src}/.env.example" "${ACADEMY_DIR}/"
|
||||
cp "${src}/config/config.yaml" "${ACADEMY_DIR}/config/"
|
||||
|
||||
# 记录元信息, 供 firstboot / 升级时参考
|
||||
cat >"${ACADEMY_DIR}/.cloud-image-meta" <<EOF
|
||||
ACADEMY_REF=${ACADEMY_REF}
|
||||
ACADEMY_REPO=${ACADEMY_REPO}
|
||||
PREPARED_AT=$(date -Iseconds)
|
||||
EOF
|
||||
|
||||
echo "[prepare] 3/6 准备 .env (默认值, firstboot 会替换为随机密钥)"
|
||||
cd "${ACADEMY_DIR}"
|
||||
[[ -f .env ]] || cp .env.example .env
|
||||
sed -i 's/^GIN_MODE=.*/GIN_MODE=release/' .env || true
|
||||
|
||||
# 把 ACADEMY_VERSION 与 ACADEMY_REF 对齐, 让 docker compose 拉取与 ref 一致的
|
||||
# 镜像 tag。无条件覆盖, 避免 .env 残留上一次 prepare 留下的旧版本号。
|
||||
# Docker Hub 上 wechatopenai/weknora-* 的 tag 命名约定:
|
||||
# - 浮动 tag:main(持续指向最新构建)
|
||||
# - 固定 release tag:v 前缀 + semver(如 v0.7.2、v0.5.2)
|
||||
# 因此这里不剥 v、也不映射到 latest。
|
||||
ACADEMY_VERSION_VAL="${ACADEMY_REF}"
|
||||
if grep -qE '^ACADEMY_VERSION=' .env; then
|
||||
sed -i "s|^ACADEMY_VERSION=.*|ACADEMY_VERSION=${ACADEMY_VERSION_VAL}|" .env
|
||||
else
|
||||
echo "ACADEMY_VERSION=${ACADEMY_VERSION_VAL}" >>.env
|
||||
fi
|
||||
echo "[prepare] -> ACADEMY_VERSION=${ACADEMY_VERSION_VAL}"
|
||||
|
||||
echo "[prepare] 4/6 拉取并启动默认 5 个常驻容器 (frontend/app/docreader/postgres/redis)"
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
|
||||
# 提前 pull sandbox 镜像 (Agent Skills 运行时由 app 按需 docker run, 非常驻)
|
||||
# 不预拉的话, 用户首次跑 Skill 会卡在下载
|
||||
echo "[prepare] 4.5/6 预拉 sandbox 镜像 (Agent Skills 用, 非常驻)"
|
||||
docker compose --profile full pull sandbox || true
|
||||
|
||||
# 其他向量库 / 可观测组件 (qdrant, milvus, weaviate, doris, neo4j, langfuse-*, minio, dex)
|
||||
# 不预拉, 体积可省 5-15GB. 用户如需启用:
|
||||
# cd /opt/Academy && docker compose --profile <name> up -d
|
||||
|
||||
# 升级场景: 清理旧版本 tag 的 wechatopenai/weknora-* 镜像。
|
||||
# 默认关闭, 保留回滚路径; 制作镜像前显式打开以减小体积。
|
||||
#
|
||||
# 注意: 不用 `docker image prune -af`!
|
||||
# sandbox 镜像在 compose 里只 pull 不 up (Agent Skills 由 app 按需 docker run),
|
||||
# 没有任何容器引用它, 一旦 `prune -a` 会把当前版本的 sandbox 一起删掉,
|
||||
# 反而违背 prepare.sh 4.5 步预拉 sandbox 的目的。
|
||||
# 这里精确按 tag 比对, 只删 wechatopenai/weknora-* 仓库下、tag 不等于当前
|
||||
# ACADEMY_VERSION 的镜像, 基础设施镜像 (paradedb / redis) 不动。
|
||||
if [[ "${PRUNE_OLD_IMAGES,,}" == "true" || "${PRUNE_OLD_IMAGES}" == "1" ]]; then
|
||||
echo "[prepare] 4.6/6 清理 wechatopenai/weknora-* 仓库下旧版本镜像 (PRUNE_OLD_IMAGES=true, keep=${ACADEMY_VERSION_VAL})"
|
||||
docker image ls --format '{{.Repository}}:{{.Tag}}' \
|
||||
| grep -E '^wechatopenai/weknora-' \
|
||||
| grep -vE ":${ACADEMY_VERSION_VAL}\$" \
|
||||
| xargs -r docker rmi -f 2>/dev/null || true
|
||||
fi
|
||||
|
||||
echo "[prepare] 5/6 安装 systemd 单元"
|
||||
# 探测 docker 二进制路径, 不同发行版可能在 /usr/bin 或 /usr/local/bin
|
||||
DOCKER_BIN="$(command -v docker)"
|
||||
if [[ -z "${DOCKER_BIN}" ]]; then
|
||||
echo "[prepare] 未找到 docker 二进制" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "[prepare] docker binary: ${DOCKER_BIN}"
|
||||
|
||||
install -m 0644 "${SCRIPT_DIR}/systemd/academy.service" /etc/systemd/system/academy.service
|
||||
install -m 0644 "${SCRIPT_DIR}/systemd/academy-firstboot.service" /etc/systemd/system/academy-firstboot.service
|
||||
install -m 0755 "${SCRIPT_DIR}/firstboot.sh" /usr/local/sbin/academy-firstboot.sh
|
||||
|
||||
# 把 systemd 单元里的 docker 路径模板替换为实际路径
|
||||
sed -i "s|@DOCKER_BIN@|${DOCKER_BIN}|g" /etc/systemd/system/academy.service
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable academy.service
|
||||
systemctl enable academy-firstboot.service
|
||||
|
||||
echo "[prepare] 6/6 完成"
|
||||
echo
|
||||
echo " Academy 运行时已部署到 ${ACADEMY_DIR}"
|
||||
echo " docker-compose.yml / config/config.yaml / .env"
|
||||
echo " 版本: ${ACADEMY_REF} (见 ${ACADEMY_DIR}/.cloud-image-meta)"
|
||||
echo
|
||||
echo " 打开浏览器访问 http://<本机公网IP> 验证功能"
|
||||
echo
|
||||
echo " 验证通过后执行清理并制作镜像:"
|
||||
echo " sudo bash ${SCRIPT_DIR}/cleanup.sh"
|
||||
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Academy first-boot initialization (runs once)
|
||||
After=docker.service network-online.target
|
||||
Requires=docker.service
|
||||
Wants=network-online.target
|
||||
Before=academy.service
|
||||
ConditionPathExists=/usr/local/sbin/academy-firstboot.sh
|
||||
ConditionPathExists=!/opt/Academy/.firstboot.done
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/academy-firstboot.sh
|
||||
RemainAfterExit=no
|
||||
TimeoutStartSec=900
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,21 @@
|
||||
[Unit]
|
||||
Description=Academy (docker compose)
|
||||
Requires=docker.service academy-firstboot.service
|
||||
After=docker.service network-online.target academy-firstboot.service
|
||||
Wants=network-online.target
|
||||
# 关键: Requires=academy-firstboot.service 让首启 init 失败时本服务也不启动,
|
||||
# 避免 firstboot 没成功生成随机密钥就用 .env.example 默认明文密码把 postgres
|
||||
# 数据卷初始化掉。academy-firstboot.service 在已初始化的实例上由
|
||||
# ConditionPathExists=!/opt/Academy/.firstboot.done 跳过, 跳过 = 成功,
|
||||
# 不会阻塞本服务后续重启。
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
WorkingDirectory=/opt/Academy
|
||||
ExecStart=@DOCKER_BIN@ compose up -d
|
||||
ExecStop=@DOCKER_BIN@ compose down
|
||||
TimeoutStartSec=600
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Assemble notices and verified corresponding source for backend/desktop releases.
|
||||
if [ "$#" -ne 1 ] || [ -z "$1" ]; then
|
||||
echo "Usage: $0 DESTINATION_DIRECTORY" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
license_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
license_dest="$1"
|
||||
bash "${license_root}/scripts/check-license-bundle.sh"
|
||||
|
||||
# Use Go's module cache and configured GOPROXY, including offline cache hits.
|
||||
# Archives are release inputs, not files vendored in the source repository.
|
||||
source_stage="$(mktemp -d)"
|
||||
trap 'rm -rf "${source_stage}"' EXIT
|
||||
module_cache="$(cd "${license_root}" && go env GOMODCACHE)"
|
||||
while read -r module_name module_version _checksum; do
|
||||
(cd "${license_root}" && go mod download "${module_name}@${module_version}")
|
||||
cp "${module_cache}/cache/download/${module_name}/@v/${module_version}.zip" \
|
||||
"${source_stage}/${module_name##*/}-${module_version}.zip"
|
||||
done < "${license_root}/licenses/sources/modules.tsv"
|
||||
bash "${license_root}/scripts/check-license-bundle.sh" "${source_stage}"
|
||||
|
||||
mkdir -p "${license_dest}/licenses"
|
||||
cp "${license_root}/LICENSE" "${license_root}/THIRD_PARTY_NOTICES.md" "${license_dest}/"
|
||||
cp -R "${license_root}/licenses/." "${license_dest}/licenses/"
|
||||
cp "${source_stage}/"*.zip "${license_dest}/licenses/sources/"
|
||||
+599
@@ -0,0 +1,599 @@
|
||||
#!/bin/bash
|
||||
# 开发环境启动脚本 - 只启动基础设施,app 和 frontend 需要手动在本地运行
|
||||
|
||||
# 设置颜色
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # 无颜色
|
||||
|
||||
# 获取项目根目录
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
|
||||
|
||||
# 日志函数
|
||||
log_info() {
|
||||
printf "%b\n" "${BLUE}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
printf "%b\n" "${GREEN}[SUCCESS]${NC} $1"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
printf "%b\n" "${RED}[ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
printf "%b\n" "${YELLOW}[WARNING]${NC} $1"
|
||||
}
|
||||
|
||||
# 选择可用的 Docker Compose 命令
|
||||
DOCKER_COMPOSE_BIN=""
|
||||
DOCKER_COMPOSE_SUBCMD=""
|
||||
|
||||
detect_compose_cmd() {
|
||||
if docker compose version &> /dev/null; then
|
||||
DOCKER_COMPOSE_BIN="docker"
|
||||
DOCKER_COMPOSE_SUBCMD="compose"
|
||||
return 0
|
||||
fi
|
||||
if command -v docker-compose &> /dev/null; then
|
||||
if docker-compose version &> /dev/null; then
|
||||
DOCKER_COMPOSE_BIN="docker-compose"
|
||||
DOCKER_COMPOSE_SUBCMD=""
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
# 显示帮助信息
|
||||
show_help() {
|
||||
printf "%b\n" "${GREEN}Academy 开发环境脚本${NC}"
|
||||
echo "用法: $0 [命令] [选项]"
|
||||
echo ""
|
||||
echo "命令:"
|
||||
echo " start 启动基础设施服务(postgres, redis, docreader, langfuse)"
|
||||
echo " stop 停止所有服务"
|
||||
echo " restart 重启所有服务"
|
||||
echo " logs 查看服务日志"
|
||||
echo " status 查看服务状态"
|
||||
echo " app 启动后端应用(本地运行)"
|
||||
echo " frontend 启动前端开发服务器(本地运行)"
|
||||
echo " help 显示此帮助信息"
|
||||
echo ""
|
||||
echo "可选 Profile(用于 start 命令):"
|
||||
echo " --minio 启动 MinIO 对象存储"
|
||||
echo " --qdrant 启动 Qdrant 向量数据库"
|
||||
echo " --neo4j 启动 Neo4j 图数据库"
|
||||
echo " --dex 启动 Dex(OIDC 身份认证)"
|
||||
echo " --langfuse 启动 Langfuse(默认已开启)"
|
||||
echo " --no-langfuse 不启动 Langfuse"
|
||||
echo " --odl-hybrid 启动 OpenDataLoader hybrid(Docling,镜像较大,按需启用)"
|
||||
echo " --full 启动所有可选服务(不含 odl-hybrid,需另加 --odl-hybrid)"
|
||||
echo ""
|
||||
echo "示例:"
|
||||
echo " $0 start # 启动基础服务"
|
||||
echo " $0 start --qdrant # 启动基础服务 + Qdrant"
|
||||
echo " $0 start --dex # 启动基础服务 + Dex"
|
||||
echo " $0 start --odl-hybrid # 启动基础服务 + OpenDataLoader hybrid"
|
||||
echo " $0 start --full # 启动所有服务"
|
||||
echo " make dev-start DEV_ARGS=--odl-hybrid # 同上(Makefile 传参)"
|
||||
echo " $0 app # 在另一个终端启动后端"
|
||||
echo " $0 frontend # 在另一个终端启动前端"
|
||||
}
|
||||
|
||||
# 加载 .env 与可选的 .env.local(后者覆盖前者)
|
||||
# 读取时去掉行尾 \r,兼容 Windows 风格(CRLF)换行符,
|
||||
# 否则 bash source 会把残留的 \r 当成命令导致 "...: $'\r': command not found"。
|
||||
# 注意:不能用 source <(sed ...)——macOS 自带 Bash 3.2 对 process substitution
|
||||
# 的 source 不会把变量导入当前 shell;必须落到可 seek 的临时文件再 source。
|
||||
_source_env_file() {
|
||||
local src="$1"
|
||||
local tmp
|
||||
tmp="$(mktemp)" || return 1
|
||||
sed -e 's/\r$//' "$src" > "$tmp"
|
||||
set -a
|
||||
# shellcheck source=/dev/null
|
||||
source "$tmp"
|
||||
set +a
|
||||
rm -f "$tmp"
|
||||
}
|
||||
|
||||
load_env_files() {
|
||||
if [ -f ".env" ]; then
|
||||
_source_env_file .env || return 1
|
||||
else
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ -f ".env.local" ]; then
|
||||
log_info "加载 .env.local 覆盖配置..."
|
||||
_source_env_file .env.local || return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
# 检查 Docker
|
||||
check_docker() {
|
||||
if ! command -v docker &> /dev/null; then
|
||||
log_error "未安装Docker,请先安装Docker"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! detect_compose_cmd; then
|
||||
log_error "未检测到 Docker Compose"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! docker info &> /dev/null; then
|
||||
log_error "Docker服务未运行"
|
||||
return 1
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# 检查 .env 是否启用了 hybrid 模式(用于 --odl-hybrid 启动后重建 docreader)
|
||||
_should_enable_odl_hybrid_from_env() {
|
||||
local hybrid="${DOCREADER_ODL_HYBRID:-off}"
|
||||
hybrid=$(printf '%s' "$hybrid" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
|
||||
case "$hybrid" in
|
||||
off|"") return 1 ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
_enable_odl_hybrid_profile() {
|
||||
PROFILES="$PROFILES --profile odl-hybrid"
|
||||
ENABLED_SERVICES="$ENABLED_SERVICES odl-hybrid"
|
||||
}
|
||||
|
||||
# 等待 odl-hybrid HTTP 健康检查通过(compose 启动后服务可能仍在拉依赖)
|
||||
_wait_odl_hybrid_ready() {
|
||||
local port="${ODL_HYBRID_PORT:-5002}"
|
||||
local max_wait="${ODL_HYBRID_STARTUP_WAIT_SEC:-180}"
|
||||
local waited=0
|
||||
local interval=5
|
||||
|
||||
if ! command -v curl &> /dev/null; then
|
||||
log_warning "未安装 curl,跳过 odl-hybrid 就绪等待;请手动检查 http://localhost:${port}/health"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_info "等待 odl-hybrid 就绪(最多 ${max_wait}s,首次需构建镜像: docker compose ... build odl-hybrid)..."
|
||||
while [ "$waited" -lt "$max_wait" ]; do
|
||||
if curl -sf "http://127.0.0.1:${port}/health" >/dev/null 2>&1; then
|
||||
log_success "odl-hybrid 已就绪 (http://localhost:${port}/health)"
|
||||
return 0
|
||||
fi
|
||||
sleep "$interval"
|
||||
waited=$((waited + interval))
|
||||
done
|
||||
log_warning "odl-hybrid 在 ${max_wait}s 内未就绪,请查看: docker logs Academy-odl-hybrid"
|
||||
return 1
|
||||
}
|
||||
|
||||
# 启动基础设施服务
|
||||
start_services() {
|
||||
log_info "启动开发环境基础设施服务..."
|
||||
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 检查 .env 文件
|
||||
if [ ! -f ".env" ]; then
|
||||
log_error ".env 文件不存在,请先创建"
|
||||
return 1
|
||||
fi
|
||||
|
||||
load_env_files
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error ".env 文件不存在,请先创建"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ -n "${DEV_REMOTE_HOST:-}" ]; then
|
||||
log_warning "已配置 DEV_REMOTE_HOST=${DEV_REMOTE_HOST},跳过本地 Docker 基础设施启动"
|
||||
log_info "远程服务: PostgreSQL/Redis/DocReader/Langfuse → ${DEV_REMOTE_HOST}"
|
||||
log_info "接下来: make dev-app(本地后端)或 make dev-frontend(前端)"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# 解析 profile 参数
|
||||
shift # 移除 "start" 命令本身
|
||||
# 默认启动基础设施(postgres / redis / docreader)+ langfuse,
|
||||
# 其余可选服务通过 --minio / --qdrant / --neo4j / --dex / --full 按需开启。
|
||||
PROFILES="--profile langfuse"
|
||||
ENABLED_SERVICES="langfuse"
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--minio)
|
||||
PROFILES="$PROFILES --profile minio"
|
||||
ENABLED_SERVICES="$ENABLED_SERVICES minio"
|
||||
;;
|
||||
--qdrant)
|
||||
PROFILES="$PROFILES --profile qdrant"
|
||||
ENABLED_SERVICES="$ENABLED_SERVICES qdrant"
|
||||
;;
|
||||
--neo4j)
|
||||
PROFILES="$PROFILES --profile neo4j"
|
||||
ENABLED_SERVICES="$ENABLED_SERVICES neo4j"
|
||||
;;
|
||||
--dex)
|
||||
PROFILES="$PROFILES --profile dex"
|
||||
ENABLED_SERVICES="$ENABLED_SERVICES dex"
|
||||
;;
|
||||
--langfuse)
|
||||
PROFILES="$PROFILES --profile langfuse"
|
||||
ENABLED_SERVICES="$ENABLED_SERVICES langfuse"
|
||||
;;
|
||||
--no-langfuse)
|
||||
PROFILES="${PROFILES//--profile langfuse/}"
|
||||
ENABLED_SERVICES="${ENABLED_SERVICES//langfuse/}"
|
||||
;;
|
||||
--odl-hybrid)
|
||||
if [[ "$ENABLED_SERVICES" != *"odl-hybrid"* ]]; then
|
||||
_enable_odl_hybrid_profile
|
||||
fi
|
||||
;;
|
||||
--full)
|
||||
PROFILES="--profile full"
|
||||
ENABLED_SERVICES="minio qdrant neo4j dex"
|
||||
break
|
||||
;;
|
||||
*)
|
||||
log_warning "未知参数: $1"
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# 启动服务(odl-hybrid 单独 --build,避免每次重建 docreader)
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD -f docker-compose.dev.yml $PROFILES up -d
|
||||
local compose_rc=$?
|
||||
if [ "$compose_rc" -eq 0 ] && [[ "$ENABLED_SERVICES" == *"odl-hybrid"* ]]; then
|
||||
log_info "构建/更新 odl-hybrid 镜像..."
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD -f docker-compose.dev.yml $PROFILES up -d --build odl-hybrid
|
||||
_wait_odl_hybrid_ready || true
|
||||
# docreader 需读取 DOCREADER_ODL_HYBRID;若刚改 .env,强制重建以注入环境变量
|
||||
if _should_enable_odl_hybrid_from_env; then
|
||||
log_info "重建 docreader 以应用 DOCREADER_ODL_HYBRID=${DOCREADER_ODL_HYBRID} ..."
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD -f docker-compose.dev.yml up -d --force-recreate docreader
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$compose_rc" -eq 0 ]; then
|
||||
log_success "基础设施服务已启动"
|
||||
echo ""
|
||||
log_info "服务访问地址:"
|
||||
echo " - PostgreSQL: localhost:5432"
|
||||
echo " - Redis: localhost:6379"
|
||||
echo " - DocReader: localhost:50051"
|
||||
|
||||
# 根据启用的 profile 显示额外服务
|
||||
if [[ "$ENABLED_SERVICES" == *"minio"* ]]; then
|
||||
echo " - MinIO: localhost:9000 (Console: localhost:9001)"
|
||||
fi
|
||||
if [[ "$ENABLED_SERVICES" == *"qdrant"* ]]; then
|
||||
echo " - Qdrant: localhost:6333 (gRPC: localhost:6334)"
|
||||
fi
|
||||
if [[ "$ENABLED_SERVICES" == *"neo4j"* ]]; then
|
||||
echo " - Neo4j: localhost:7474 (Bolt: localhost:7687)"
|
||||
fi
|
||||
if [[ "$ENABLED_SERVICES" == *"dex"* ]]; then
|
||||
echo " - Dex: localhost:5556"
|
||||
fi
|
||||
if [[ "$ENABLED_SERVICES" == *"langfuse"* ]]; then
|
||||
echo " - Langfuse: http://localhost:${LANGFUSE_WEB_PORT:-3000}"
|
||||
fi
|
||||
if [[ "$ENABLED_SERVICES" == *"odl-hybrid"* ]]; then
|
||||
echo " - ODL Hybrid: http://localhost:${ODL_HYBRID_PORT:-5002} (health: /health)"
|
||||
echo " docreader 需 DOCREADER_ODL_HYBRID=docling-fast"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
log_info "接下来的步骤:"
|
||||
printf "%b\n" "${YELLOW}1. 在新终端运行后端:${NC} make dev-app"
|
||||
printf "%b\n" "${YELLOW}2. 在新终端运行前端:${NC} make dev-frontend"
|
||||
return 0
|
||||
else
|
||||
log_error "服务启动失败"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 停止服务
|
||||
stop_services() {
|
||||
log_info "停止开发环境服务..."
|
||||
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD -f docker-compose.dev.yml down
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
log_success "所有服务已停止"
|
||||
return 0
|
||||
else
|
||||
log_error "服务停止失败"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 重启服务
|
||||
restart_services() {
|
||||
stop_services
|
||||
sleep 2
|
||||
start_services
|
||||
}
|
||||
|
||||
# 查看日志
|
||||
show_logs() {
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD -f docker-compose.dev.yml logs -f
|
||||
}
|
||||
|
||||
# 查看状态
|
||||
show_status() {
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD -f docker-compose.dev.yml ps
|
||||
}
|
||||
|
||||
# 远程开发模式下检查基础设施端口是否可达
|
||||
check_remote_dev_connectivity() {
|
||||
local host="${DEV_REMOTE_HOST:-}"
|
||||
if [ -z "$host" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local db_port="${DB_PORT:-5432}"
|
||||
local redis_port
|
||||
redis_port="${REDIS_ADDR#*:}"
|
||||
if [ "$redis_port" = "$REDIS_ADDR" ]; then
|
||||
redis_port=6379
|
||||
fi
|
||||
local docreader_port="${DOCREADER_PORT:-50051}"
|
||||
|
||||
log_info "检查远程基础设施连通性 (${host})..."
|
||||
local failed=0
|
||||
for spec in "PostgreSQL:${host}:${db_port}" "Redis:${host}:${redis_port}" "DocReader:${host}:${docreader_port}"; do
|
||||
local name="${spec%%:*}"
|
||||
local rest="${spec#*:}"
|
||||
local h="${rest%%:*}"
|
||||
local p="${rest##*:}"
|
||||
if command -v nc &> /dev/null; then
|
||||
if nc -z -w 3 "$h" "$p" 2>/dev/null; then
|
||||
log_success "${name} ${h}:${p} 可达"
|
||||
else
|
||||
log_error "${name} ${h}:${p} 不可达 (no route / connection refused)"
|
||||
failed=1
|
||||
fi
|
||||
else
|
||||
log_warning "未安装 nc,跳过 ${name} 连通性检查"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo ""
|
||||
log_error "无法连接远程开发环境 ${host}"
|
||||
log_info "排查建议:"
|
||||
echo " 1. 确认远程机器 Docker 容器在运行 (postgres/redis/docreader)"
|
||||
echo " 2. 确认本机与 ${host} 在同一局域网 (本机: $(ipconfig getifaddr en0 2>/dev/null || echo '未知'))"
|
||||
echo " 3. 在远程检查端口映射: docker ps --format 'table {{.Names}}\t{{.Ports}}'"
|
||||
echo " 4. 检查远程防火墙是否放行 5432/6379/50051"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
# Host-platform path of the anydoc static archive (built by `make anydoc-lib`).
|
||||
anydoc_host_archive() {
|
||||
case "$(uname -s)-$(uname -m)" in
|
||||
Darwin-arm64) echo "$PROJECT_ROOT/third_party/anydoc-go/lib/darwin_arm64/libanydoc_go.a" ;;
|
||||
Darwin-x86_64) echo "$PROJECT_ROOT/third_party/anydoc-go/lib/darwin_amd64/libanydoc_go.a" ;;
|
||||
Linux-x86_64)
|
||||
if [ -f "$PROJECT_ROOT/third_party/anydoc-go/lib/linux_amd64_gnu/libanydoc_go.a" ]; then
|
||||
echo "$PROJECT_ROOT/third_party/anydoc-go/lib/linux_amd64_gnu/libanydoc_go.a"
|
||||
else
|
||||
echo "$PROJECT_ROOT/third_party/anydoc-go/lib/linux_amd64_musl/libanydoc_go.a"
|
||||
fi
|
||||
;;
|
||||
Linux-aarch64)
|
||||
if [ -f "$PROJECT_ROOT/third_party/anydoc-go/lib/linux_arm64_gnu/libanydoc_go.a" ]; then
|
||||
echo "$PROJECT_ROOT/third_party/anydoc-go/lib/linux_arm64_gnu/libanydoc_go.a"
|
||||
else
|
||||
echo "$PROJECT_ROOT/third_party/anydoc-go/lib/linux_arm64_musl/libanydoc_go.a"
|
||||
fi
|
||||
;;
|
||||
*) echo "" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Enable the in-process anydoc engine when the archive is present, unless the
|
||||
# caller already set GO_BUILD_TAGS (including empty, which opts out).
|
||||
enable_anydoc_build_tag() {
|
||||
if [ -n "${GO_BUILD_TAGS+x}" ]; then
|
||||
export GO_BUILD_TAGS
|
||||
return
|
||||
fi
|
||||
local archive
|
||||
archive="$(anydoc_host_archive)"
|
||||
if [ -n "$archive" ] && [ -f "$archive" ]; then
|
||||
export GO_BUILD_TAGS=anydoc
|
||||
log_info "检测到 anydoc 静态库,已启用 -tags anydoc"
|
||||
else
|
||||
log_info "未检测到 anydoc 静态库,解析引擎不可用。需要时先运行: make anydoc-lib"
|
||||
fi
|
||||
}
|
||||
|
||||
# 启动后端应用(本地)
|
||||
start_app() {
|
||||
log_info "启动后端应用(本地开发模式)..."
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 检查 Go 是否安装
|
||||
if ! command -v go &> /dev/null; then
|
||||
log_error "Go 未安装"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "加载环境配置..."
|
||||
if ! load_env_files; then
|
||||
log_error ".env 文件不存在,请先创建配置文件"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 本地 docker-compose.dev 模式:把容器服务名映射到宿主机回环地址
|
||||
# 远程开发模式(DEV_REMOTE_HOST 或 .env.local 已设地址)则保留 .env/.env.local 中的值
|
||||
if [ -n "${DEV_REMOTE_HOST:-}" ]; then
|
||||
log_info "远程开发模式: 基础设施 → ${DEV_REMOTE_HOST}"
|
||||
export DB_HOST="${DB_HOST:-$DEV_REMOTE_HOST}"
|
||||
export REDIS_ADDR="${REDIS_ADDR:-$DEV_REMOTE_HOST:6379}"
|
||||
export DOCREADER_ADDR="${DOCREADER_ADDR:-$DEV_REMOTE_HOST:50051}"
|
||||
export MINIO_ENDPOINT="${MINIO_ENDPOINT:-$DEV_REMOTE_HOST:9000}"
|
||||
export MILVUS_ADDRESS="${MILVUS_ADDRESS:-$DEV_REMOTE_HOST:19530}"
|
||||
export NEO4J_URI="${NEO4J_URI:-bolt://$DEV_REMOTE_HOST:7687}"
|
||||
export QDRANT_HOST="${QDRANT_HOST:-$DEV_REMOTE_HOST}"
|
||||
if [ -z "${LANGFUSE_HOST:-}" ] || [ "$LANGFUSE_HOST" = "http://langfuse-web:3000" ]; then
|
||||
export LANGFUSE_HOST="http://${DEV_REMOTE_HOST}:3000"
|
||||
fi
|
||||
else
|
||||
export DB_HOST=127.0.0.1
|
||||
export DOCREADER_ADDR=127.0.0.1:50051
|
||||
export MINIO_ENDPOINT=127.0.0.1:9000
|
||||
export REDIS_ADDR=127.0.0.1:6379
|
||||
export MILVUS_ADDRESS=127.0.0.1:19530
|
||||
export NEO4J_URI=bolt://127.0.0.1:7687
|
||||
export QDRANT_HOST=127.0.0.1
|
||||
fi
|
||||
export DOCREADER_TRANSPORT="${DOCREADER_TRANSPORT:-grpc}"
|
||||
|
||||
if ! check_remote_dev_connectivity; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# .env.example uses /data/files for the Docker app container, where a
|
||||
# volume is mounted at that path. When the backend runs directly on the
|
||||
# host via dev-app, /data is often read-only or missing, so use a repo-local
|
||||
# writable directory unless the developer explicitly configured another
|
||||
# local storage path.
|
||||
if [ -z "${LOCAL_STORAGE_BASE_DIR:-}" ] || [ "$LOCAL_STORAGE_BASE_DIR" = "/data/files" ]; then
|
||||
export LOCAL_STORAGE_BASE_DIR="$PROJECT_ROOT/.local-data/files"
|
||||
fi
|
||||
mkdir -p "$LOCAL_STORAGE_BASE_DIR"
|
||||
|
||||
# 确保必要的环境变量已设置
|
||||
if [ -z "$DB_DRIVER" ]; then
|
||||
log_error "DB_DRIVER 环境变量未设置,请检查 .env 文件"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "环境变量已设置,启动应用..."
|
||||
log_info "数据库地址: $DB_HOST:${DB_PORT:-5432}"
|
||||
|
||||
export CGO_CFLAGS="-Wno-deprecated-declarations -Wno-gnu-folding-constant"
|
||||
if [[ "$(uname)" == "Darwin" ]]; then
|
||||
export CGO_LDFLAGS="-Wl,-no_warn_duplicate_libraries"
|
||||
fi
|
||||
|
||||
enable_anydoc_build_tag
|
||||
|
||||
# 检查是否安装了 Air(热重载工具)
|
||||
if command -v air &> /dev/null; then
|
||||
log_success "检测到 Air,使用热重载模式启动..."
|
||||
log_info "修改 Go 代码后将自动重新编译和重启"
|
||||
air
|
||||
else
|
||||
log_info "未检测到 Air,使用普通模式启动"
|
||||
log_warning "提示: 安装 Air 可以实现代码修改后自动重启"
|
||||
log_info "安装命令: go install github.com/air-verse/air@latest"
|
||||
LDFLAGS="$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'"
|
||||
go run -tags "${GO_BUILD_TAGS:-}" -ldflags="$LDFLAGS" ./cmd/server
|
||||
fi
|
||||
}
|
||||
|
||||
# 启动前端(本地)
|
||||
start_frontend() {
|
||||
log_info "启动前端开发服务器..."
|
||||
|
||||
cd "$PROJECT_ROOT"
|
||||
if [ -f ".env" ] || [ -f ".env.local" ]; then
|
||||
load_env_files >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
cd "$PROJECT_ROOT/frontend"
|
||||
|
||||
# 检查 npm 是否安装
|
||||
if ! command -v npm &> /dev/null; then
|
||||
log_error "npm 未安装"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 检查依赖是否已安装
|
||||
if [ ! -d "node_modules" ]; then
|
||||
log_warning "node_modules 不存在,正在安装依赖..."
|
||||
npm install
|
||||
fi
|
||||
|
||||
log_info "启动 Vite 开发服务器..."
|
||||
log_info "前端将运行在 http://localhost:5173"
|
||||
log_info "前端 API 代理目标: ${VITE_DEV_PROXY_TARGET:-${FRONTEND_BACKEND_URL:-http://localhost:8080}}"
|
||||
|
||||
# 运行开发服务器
|
||||
npm run dev
|
||||
}
|
||||
|
||||
# 解析命令
|
||||
CMD="${1:-help}"
|
||||
case "$CMD" in
|
||||
start)
|
||||
start_services "$@"
|
||||
;;
|
||||
stop)
|
||||
stop_services
|
||||
;;
|
||||
restart)
|
||||
restart_services
|
||||
;;
|
||||
logs)
|
||||
show_logs
|
||||
;;
|
||||
status)
|
||||
show_status
|
||||
;;
|
||||
app)
|
||||
start_app
|
||||
;;
|
||||
frontend)
|
||||
start_frontend
|
||||
;;
|
||||
help|--help|-h)
|
||||
show_help
|
||||
;;
|
||||
*)
|
||||
log_error "未知命令: $CMD"
|
||||
show_help
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# ─── Fix ownership of bind-mounted directories ───
|
||||
# When users bind-mount host directories (e.g. ./data/files),
|
||||
# the mount inherits the host UID/GID which may differ from the
|
||||
# container's appuser. This entrypoint runs as root, fixes ownership,
|
||||
# then drops privileges to appuser via gosu — the same pattern used
|
||||
# by official postgres/redis images.
|
||||
|
||||
# Directories that may be bind-mounted and need appuser access
|
||||
MOUNT_DIRS=(
|
||||
/data/files
|
||||
)
|
||||
|
||||
for dir in "${MOUNT_DIRS[@]}"; do
|
||||
if [ -d "$dir" ]; then
|
||||
chown -R appuser:appuser "$dir" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
# ─── Docker socket access for the sandbox backend ───
|
||||
# The Engine API socket is typically root:docker 0660. This process then
|
||||
# drops to appuser via gosu, which calls initgroups and therefore drops
|
||||
# compose group_add. Match the socket's GID in /etc/group before gosu.
|
||||
# Never chmod the host socket: that would weaken daemon access on the host.
|
||||
grant_docker_sock_to_appuser() {
|
||||
local sock="$1"
|
||||
local gid grp
|
||||
[ -S "$sock" ] || return 0
|
||||
if gosu appuser sh -c "test -r \"$sock\" && test -w \"$sock\"" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
gid="$(stat -c '%g' "$sock" 2>/dev/null || true)"
|
||||
if [ -z "$gid" ]; then
|
||||
echo "academy: cannot stat $sock; Docker sandbox may be unable to reach the daemon" >&2
|
||||
return 0
|
||||
fi
|
||||
if [ "$gid" = "0" ]; then
|
||||
echo "academy: $sock is not writable by appuser and owned by GID 0; Docker sandbox needs a group-writable socket with a non-root GID" >&2
|
||||
return 0
|
||||
fi
|
||||
if ! getent group "$gid" >/dev/null 2>&1; then
|
||||
if ! groupadd -g "$gid" dockersock >/dev/null 2>&1; then
|
||||
echo "academy: failed to create group for $sock GID $gid; Docker sandbox may be unable to reach the daemon" >&2
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
grp="$(getent group "$gid" | cut -d: -f1)"
|
||||
if [ -z "$grp" ]; then
|
||||
echo "academy: no group name for GID $gid on $sock" >&2
|
||||
return 0
|
||||
fi
|
||||
if ! usermod -aG "$grp" appuser >/dev/null 2>&1; then
|
||||
echo "academy: failed to add appuser to $grp for $sock; Docker sandbox may be unable to reach the daemon" >&2
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
|
||||
grant_docker_sock_to_appuser /var/run/docker.sock
|
||||
case "${DOCKER_HOST:-}" in
|
||||
unix://*)
|
||||
grant_docker_sock_to_appuser "${DOCKER_HOST#unix://}"
|
||||
;;
|
||||
esac
|
||||
|
||||
# ─── Drop privileges and exec the main process ───
|
||||
exec gosu appuser "$@"
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/bin/bash
|
||||
# 统一的版本信息获取脚本
|
||||
# 支持本地构建和CI构建环境
|
||||
|
||||
# 设置默认值
|
||||
VERSION="unknown"
|
||||
EDITION="${EDITION:-standard}"
|
||||
COMMIT_ID="unknown"
|
||||
BUILD_TIME="unknown"
|
||||
GO_VERSION="unknown"
|
||||
|
||||
# 获取版本号
|
||||
if [ -f "VERSION" ]; then
|
||||
VERSION=$(cat VERSION | tr -d '\n\r')
|
||||
fi
|
||||
|
||||
# 获取commit ID
|
||||
if [ -n "$GITHUB_SHA" ]; then
|
||||
# GitHub Actions环境
|
||||
COMMIT_ID="${GITHUB_SHA:0:7}"
|
||||
elif command -v git >/dev/null 2>&1; then
|
||||
# 本地环境
|
||||
COMMIT_ID=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
|
||||
fi
|
||||
|
||||
# 获取构建时间
|
||||
if [ -n "$GITHUB_ACTIONS" ]; then
|
||||
# GitHub Actions环境,使用标准时间格式
|
||||
BUILD_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
|
||||
else
|
||||
# 本地环境
|
||||
BUILD_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
|
||||
fi
|
||||
|
||||
# 获取Go版本
|
||||
if command -v go >/dev/null 2>&1; then
|
||||
GO_VERSION=$(go version 2>/dev/null || echo "unknown")
|
||||
fi
|
||||
|
||||
# 根据参数输出不同格式
|
||||
case "${1:-env}" in
|
||||
"env")
|
||||
# 输出环境变量格式,对包含空格的值进行转义
|
||||
echo "VERSION=$VERSION"
|
||||
echo "EDITION=$EDITION"
|
||||
echo "COMMIT_ID=$COMMIT_ID"
|
||||
echo "BUILD_TIME=\"$BUILD_TIME\""
|
||||
echo "GO_VERSION=\"$GO_VERSION\""
|
||||
;;
|
||||
"json")
|
||||
# 输出JSON格式
|
||||
cat << EOF
|
||||
{
|
||||
"version": "$VERSION",
|
||||
"edition": "$EDITION",
|
||||
"commit_id": "$COMMIT_ID",
|
||||
"build_time": "$BUILD_TIME",
|
||||
"go_version": "$GO_VERSION"
|
||||
}
|
||||
EOF
|
||||
;;
|
||||
"docker-args")
|
||||
# 输出Docker构建参数格式
|
||||
echo "--build-arg VERSION_ARG=$VERSION"
|
||||
echo "--build-arg COMMIT_ID_ARG=$COMMIT_ID"
|
||||
echo "--build-arg BUILD_TIME_ARG=$BUILD_TIME"
|
||||
echo "--build-arg GO_VERSION_ARG=$GO_VERSION"
|
||||
;;
|
||||
"ldflags")
|
||||
# 输出Go ldflags格式
|
||||
echo "-X 'github.com/Tencent/WeKnora/internal/handler.Version=$VERSION' -X 'github.com/Tencent/WeKnora/internal/handler.Edition=$EDITION' -X 'github.com/Tencent/WeKnora/internal/handler.CommitID=$COMMIT_ID' -X 'github.com/Tencent/WeKnora/internal/handler.BuildTime=$BUILD_TIME' -X 'github.com/Tencent/WeKnora/internal/handler.GoVersion=$GO_VERSION'"
|
||||
;;
|
||||
"info")
|
||||
# 输出信息格式
|
||||
echo "版本信息: $VERSION"
|
||||
echo "版本类型: $EDITION"
|
||||
echo "Commit ID: $COMMIT_ID"
|
||||
echo "构建时间: $BUILD_TIME"
|
||||
echo "Go版本: $GO_VERSION"
|
||||
;;
|
||||
*)
|
||||
echo "用法: $0 [env|json|docker-args|ldflags|info]"
|
||||
echo " env - 输出环境变量格式 (默认)"
|
||||
echo " json - 输出JSON格式"
|
||||
echo " docker-args - 输出Docker构建参数格式"
|
||||
echo " ldflags - 输出Go ldflags格式"
|
||||
echo " info - 输出信息格式"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env bash
|
||||
# Shared helpers for Academy git hooks (mirrors .github/workflows and PR checklist).
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
hook_skip() {
|
||||
[[ "${SKIP_HOOKS:-}" == "1" ]]
|
||||
}
|
||||
|
||||
log_step() {
|
||||
printf '→ %s\n' "$*"
|
||||
}
|
||||
|
||||
log_ok() {
|
||||
printf '✓ %s\n' "$*"
|
||||
}
|
||||
|
||||
log_fail() {
|
||||
printf '✗ %s\n' "$*" >&2
|
||||
}
|
||||
|
||||
# File types we expect hand-edited in PRs (skip sample-data / generated blobs).
|
||||
WHITESPACE_PATHSPECS=(
|
||||
'*.go'
|
||||
'*.ts' '*.tsx' '*.vue' '*.js' '*.mjs'
|
||||
'*.yaml' '*.yml' '*.json'
|
||||
'*.sh' '*.sql'
|
||||
'Makefile'
|
||||
'frontend/package.json'
|
||||
'frontend/package-lock.json'
|
||||
)
|
||||
|
||||
# Best-effort fetch so merge-base matches CI (origin/main).
|
||||
ensure_origin_main() {
|
||||
git -C "$ROOT" fetch origin main --quiet 2>/dev/null || true
|
||||
}
|
||||
|
||||
merge_base() {
|
||||
ensure_origin_main
|
||||
local base
|
||||
base="$(git -C "$ROOT" merge-base HEAD origin/main 2>/dev/null || true)"
|
||||
if [[ -n "$base" ]]; then
|
||||
printf '%s\n' "$base"
|
||||
return
|
||||
fi
|
||||
base="$(git -C "$ROOT" merge-base HEAD main 2>/dev/null || true)"
|
||||
if [[ -n "$base" ]]; then
|
||||
printf '%s\n' "$base"
|
||||
return
|
||||
fi
|
||||
git -C "$ROOT" rev-parse HEAD~1
|
||||
}
|
||||
|
||||
# Prefer the open PR's base SHA (matches GitHub CI diff) when gh is available.
|
||||
pr_diff_base_ref() {
|
||||
ensure_origin_main
|
||||
if command -v gh >/dev/null 2>&1; then
|
||||
local base_sha
|
||||
base_sha="$(gh pr view --json baseRefOid --jq .baseRefOid 2>/dev/null || true)"
|
||||
if [[ -n "$base_sha" && "$base_sha" != "null" ]]; then
|
||||
printf '%s\n' "$base_sha"
|
||||
return
|
||||
fi
|
||||
fi
|
||||
if git -C "$ROOT" rev-parse --verify origin/main >/dev/null 2>&1; then
|
||||
printf '%s\n' "origin/main"
|
||||
return
|
||||
fi
|
||||
printf '%s\n' "main"
|
||||
}
|
||||
|
||||
check_whitespace() {
|
||||
log_step "git diff --check (source files)"
|
||||
if [[ "${1:-}" == "--cached" ]]; then
|
||||
if git -C "$ROOT" diff --cached --quiet -- "${WHITESPACE_PATHSPECS[@]}"; then
|
||||
log_ok "no staged source changes to check"
|
||||
return 0
|
||||
fi
|
||||
git -C "$ROOT" diff --check --cached -- "${WHITESPACE_PATHSPECS[@]}"
|
||||
else
|
||||
if git -C "$ROOT" diff --quiet "$@" -- "${WHITESPACE_PATHSPECS[@]}"; then
|
||||
log_ok "no changed source files to check"
|
||||
return 0
|
||||
fi
|
||||
git -C "$ROOT" diff --check "$@" -- "${WHITESPACE_PATHSPECS[@]}"
|
||||
fi
|
||||
log_ok "no whitespace errors"
|
||||
}
|
||||
|
||||
check_gofmt_files() {
|
||||
local mode="$1" # check | write
|
||||
shift
|
||||
local -a files=("$@")
|
||||
if [[ ${#files[@]} -gt 0 ]]; then
|
||||
local -a existing=()
|
||||
local f rel
|
||||
for f in "${files[@]}"; do
|
||||
if [[ -f "$f" ]]; then
|
||||
existing+=("$f")
|
||||
continue
|
||||
fi
|
||||
rel="${f#"$ROOT"/}"
|
||||
if [[ -f "$ROOT/$rel" ]]; then
|
||||
existing+=("$ROOT/$rel")
|
||||
fi
|
||||
done
|
||||
files=("${existing[@]}")
|
||||
fi
|
||||
[[ ${#files[@]} -gt 0 ]] || return 0
|
||||
|
||||
local unformatted
|
||||
if [[ "$mode" == "write" ]]; then
|
||||
log_step "gofmt (auto-format staged Go files)"
|
||||
gofmt -w "${files[@]}"
|
||||
# Re-stage formatted files.
|
||||
git -C "$ROOT" add -- "${files[@]}"
|
||||
log_ok "gofmt applied"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_step "gofmt (check)"
|
||||
unformatted="$(gofmt -l "${files[@]}")"
|
||||
if [[ -n "$unformatted" ]]; then
|
||||
log_fail "the following Go files are not gofmt-formatted:"
|
||||
printf '%s\n' "$unformatted" >&2
|
||||
log_fail "run: gofmt -w <files> (or commit again after pre-commit auto-format)"
|
||||
return 1
|
||||
fi
|
||||
log_ok "gofmt"
|
||||
}
|
||||
|
||||
run_golangci_if_available() {
|
||||
local from_rev="$1"
|
||||
if ! command -v golangci-lint >/dev/null 2>&1; then
|
||||
log_step "golangci-lint not installed; skip (install: https://golangci-lint.run)"
|
||||
return 0
|
||||
fi
|
||||
log_step "golangci-lint run --new-from-rev=$from_rev ./..."
|
||||
(
|
||||
cd "$ROOT"
|
||||
golangci-lint run --new-from-rev="$from_rev" ./...
|
||||
)
|
||||
log_ok "golangci-lint"
|
||||
}
|
||||
|
||||
run_app_vet_test() {
|
||||
# Use the same application package set as CI, including callers of changed
|
||||
# packages. Testing only directly changed packages misses contract regressions.
|
||||
(
|
||||
cd "$ROOT"
|
||||
local package_list
|
||||
package_list="$(go list ./...)"
|
||||
local -a pkgs=()
|
||||
while IFS= read -r line; do
|
||||
[[ -z "$line" || "$line" == *"/docreader/"* ]] && continue
|
||||
pkgs+=("$line")
|
||||
done <<< "$package_list"
|
||||
if [[ ${#pkgs[@]} -eq 0 ]]; then
|
||||
log_fail "no application packages found"
|
||||
exit 1
|
||||
fi
|
||||
log_step "go vet (all app packages, like CI)"
|
||||
go vet "${pkgs[@]}"
|
||||
log_ok "go vet"
|
||||
run_go_test_packages "${pkgs[@]}"
|
||||
)
|
||||
}
|
||||
|
||||
run_go_test_packages() {
|
||||
local -a pkgs=("$@")
|
||||
if [[ ${#pkgs[@]} -eq 0 ]]; then
|
||||
log_step "no Go packages; skip go test"
|
||||
return 0
|
||||
fi
|
||||
if [[ "${HOOK_SKIP_TEST:-}" == "1" ]]; then
|
||||
log_step "HOOK_SKIP_TEST=1; skip go test"
|
||||
return 0
|
||||
fi
|
||||
log_step "go test (${#pkgs[@]} app package(s), like CI)"
|
||||
(
|
||||
cd "$ROOT"
|
||||
# Match app.yml: a developer's custom log template must not alter assertions.
|
||||
ACADEMY_LOG_FORMAT="" go test -count=1 "${pkgs[@]}"
|
||||
)
|
||||
log_ok "go test"
|
||||
}
|
||||
|
||||
run_cli_checks() {
|
||||
log_step "cli: go vet && go test"
|
||||
(
|
||||
cd "$ROOT/cli"
|
||||
go vet ./...
|
||||
if [[ "${HOOK_SKIP_TEST:-}" == "1" ]]; then
|
||||
log_step "HOOK_SKIP_TEST=1; skip cli go test"
|
||||
else
|
||||
go test -count=1 ./...
|
||||
fi
|
||||
)
|
||||
log_ok "cli checks"
|
||||
}
|
||||
|
||||
run_frontend_checks() {
|
||||
log_step "frontend: verify (test, type-check, build)"
|
||||
"$ROOT/scripts/verify_frontend_pr.sh"
|
||||
log_ok "frontend checks"
|
||||
}
|
||||
|
||||
paths_match_prefix() {
|
||||
local prefix="$1"
|
||||
shift
|
||||
local p
|
||||
for p in "$@"; do
|
||||
[[ "$p" == "$prefix"* ]] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fast checks on staged files (PR checklist + gofmt). Mirrors app.yml formatting gate.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
# shellcheck source=scripts/git-hooks/common.sh
|
||||
source "$ROOT/scripts/git-hooks/common.sh"
|
||||
|
||||
if hook_skip; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
cd "$ROOT"
|
||||
|
||||
log_step "pre-commit"
|
||||
|
||||
check_whitespace --cached
|
||||
|
||||
staged_go=()
|
||||
while IFS= read -r line; do
|
||||
[[ -n "$line" ]] && staged_go+=("$line")
|
||||
done < <(git diff --cached --name-only --diff-filter=ACMR -- '*.go' ':!cli/**' || true)
|
||||
|
||||
if [[ ${#staged_go[@]} -gt 0 ]]; then
|
||||
go_files=()
|
||||
for f in "${staged_go[@]}"; do
|
||||
go_files+=("$ROOT/$f")
|
||||
done
|
||||
check_gofmt_files write "${go_files[@]}"
|
||||
|
||||
if command -v golangci-lint >/dev/null 2>&1; then
|
||||
# Lint only what differs from HEAD (staged + unstaged in those packages).
|
||||
run_golangci_if_available HEAD
|
||||
fi
|
||||
fi
|
||||
|
||||
log_ok "pre-commit passed"
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env bash
|
||||
# Pre-push checks aligned with CI (.github/workflows/app.yml, frontend.yml, cli.yml).
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
# shellcheck source=scripts/git-hooks/common.sh
|
||||
source "$ROOT/scripts/git-hooks/common.sh"
|
||||
|
||||
if hook_skip; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
cd "$ROOT"
|
||||
|
||||
remote="${1:-origin}"
|
||||
while read -r _local_ref local_sha remote_ref remote_sha; do
|
||||
if [[ "$local_sha" =~ ^0+$ ]]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
log_step "pre-push ($remote ${remote_ref#refs/heads/})"
|
||||
|
||||
ensure_origin_main
|
||||
pr_ref="$(pr_diff_base_ref)"
|
||||
pr_tip="$local_sha"
|
||||
pr_diff="${pr_ref}...${pr_tip}"
|
||||
lint_from_rev="$pr_ref"
|
||||
|
||||
if [[ "$remote_sha" =~ ^0+$ ]]; then
|
||||
push_start="$(git -C "$ROOT" merge-base "$pr_ref" "$local_sha")"
|
||||
push_range="${push_start}..${local_sha}"
|
||||
log_step "new branch; PR diff ${pr_ref}...${local_sha:0:12}"
|
||||
else
|
||||
if [[ "$remote_sha" == "$local_sha" ]]; then
|
||||
log_ok "pre-push: nothing new to push"
|
||||
continue
|
||||
fi
|
||||
push_range="${remote_sha}..${local_sha}"
|
||||
log_step "pushing ${remote_sha:0:12}..${local_sha:0:12}; PR diff ${pr_ref}...${local_sha:0:12}"
|
||||
fi
|
||||
|
||||
check_whitespace "$push_range"
|
||||
|
||||
pr_changed=()
|
||||
while IFS= read -r line; do
|
||||
[[ -n "$line" ]] && pr_changed+=("$line")
|
||||
done < <(git diff --name-only --diff-filter=ACMR "$pr_diff" || true)
|
||||
|
||||
if [[ ${#pr_changed[@]} -eq 0 ]]; then
|
||||
log_ok "pre-push: no PR diff changes"
|
||||
continue
|
||||
fi
|
||||
|
||||
pr_changed_go=()
|
||||
while IFS= read -r line; do
|
||||
[[ -n "$line" ]] && pr_changed_go+=("$line")
|
||||
done < <(git diff --name-only --diff-filter=ACMR "$pr_diff" -- '*.go' ':!cli/**' || true)
|
||||
|
||||
if [[ ${#pr_changed_go[@]} -gt 0 ]]; then
|
||||
go_files=()
|
||||
for f in "${pr_changed_go[@]}"; do
|
||||
go_files+=("$ROOT/$f")
|
||||
done
|
||||
check_gofmt_files check "${go_files[@]}"
|
||||
|
||||
run_golangci_if_available "$lint_from_rev"
|
||||
|
||||
run_app_vet_test
|
||||
|
||||
log_step "go build ./cmd/server"
|
||||
go build ./cmd/server
|
||||
log_ok "go build ./cmd/server"
|
||||
fi
|
||||
|
||||
if paths_match_prefix "cli/" "${pr_changed[@]}"; then
|
||||
run_cli_checks
|
||||
fi
|
||||
if paths_match_prefix "frontend/" "${pr_changed[@]}"; then
|
||||
run_frontend_checks
|
||||
fi
|
||||
|
||||
log_ok "pre-push passed"
|
||||
done
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install Academy git hooks (core.hooksPath -> scripts/git-hooks).
|
||||
#
|
||||
# Usage (from repo root):
|
||||
# ./scripts/install-git-hooks.sh
|
||||
#
|
||||
# Bypass hooks for one command:
|
||||
# SKIP_HOOKS=1 git commit ...
|
||||
# SKIP_HOOKS=1 git push ...
|
||||
#
|
||||
# Skip slow go test on pre-push:
|
||||
# HOOK_SKIP_TEST=1 git push ...
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
HOOKS_DIR="$ROOT/scripts/git-hooks"
|
||||
|
||||
if [[ ! -d "$HOOKS_DIR" ]]; then
|
||||
echo "hooks directory not found: $HOOKS_DIR" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
chmod +x "$HOOKS_DIR"/common.sh "$HOOKS_DIR"/pre-commit "$HOOKS_DIR"/pre-push
|
||||
|
||||
git -C "$ROOT" config core.hooksPath scripts/git-hooks
|
||||
|
||||
echo "Installed git hooks -> scripts/git-hooks"
|
||||
echo " pre-commit: whitespace, gofmt (auto-fix), golangci-lint (if installed)"
|
||||
echo " pre-push: PR gofmt + full app go vet/test/build (like CI)"
|
||||
echo ""
|
||||
echo "Optional: SKIP_HOOKS=1 or HOOK_SKIP_TEST=1 — see script header."
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Get the script directory and project root
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
|
||||
|
||||
# Load .env file if it exists (for development mode)
|
||||
if [ -f "$PROJECT_ROOT/.env" ]; then
|
||||
echo "Loading .env file from $PROJECT_ROOT/.env"
|
||||
set -a
|
||||
source "$PROJECT_ROOT/.env"
|
||||
set +a
|
||||
fi
|
||||
|
||||
# Database connection details (can be overridden by environment variables)
|
||||
DB_HOST=${DB_HOST:-localhost}
|
||||
DB_PORT=${DB_PORT:-5432}
|
||||
DB_USER=${DB_USER:-postgres}
|
||||
DB_PASSWORD=${DB_PASSWORD:-postgres}
|
||||
DB_NAME=${DB_NAME:-Academy}
|
||||
|
||||
# Use versioned migrations directory
|
||||
MIGRATIONS_DIR="${MIGRATIONS_DIR:-migrations/versioned}"
|
||||
|
||||
# Check if migrate tool is installed
|
||||
if ! command -v migrate &> /dev/null; then
|
||||
echo "Error: migrate tool is not installed"
|
||||
echo "Install it with: go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Construct the database URL
|
||||
# If DB_URL is already set in .env, use it but ensure sslmode=disable is set
|
||||
# Otherwise, construct it from individual components
|
||||
if [ -n "$DB_URL" ]; then
|
||||
# If DB_URL already exists, ensure sslmode=disable is set (unless sslmode is already specified)
|
||||
if [[ "$DB_URL" != *"sslmode="* ]]; then
|
||||
# Add sslmode=disable if not present
|
||||
if [[ "$DB_URL" == *"?"* ]]; then
|
||||
DB_URL="${DB_URL}&sslmode=disable"
|
||||
else
|
||||
DB_URL="${DB_URL}?sslmode=disable"
|
||||
fi
|
||||
elif [[ "$DB_URL" == *"sslmode=require"* ]] || [[ "$DB_URL" == *"sslmode=prefer"* ]]; then
|
||||
# Replace sslmode=require/prefer with sslmode=disable for local dev
|
||||
DB_URL="${DB_URL//sslmode=require/sslmode=disable}"
|
||||
DB_URL="${DB_URL//sslmode=prefer/sslmode=disable}"
|
||||
fi
|
||||
else
|
||||
# Use Python to properly URL encode password if it contains special characters
|
||||
# This handles special characters in passwords correctly
|
||||
if command -v python3 &> /dev/null; then
|
||||
ENCODED_PASSWORD=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$DB_PASSWORD', safe=''))")
|
||||
else
|
||||
# Fallback: try to use printf for basic encoding (may not work for all special chars)
|
||||
ENCODED_PASSWORD="$DB_PASSWORD"
|
||||
fi
|
||||
DB_URL="postgres://${DB_USER}:${ENCODED_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}?sslmode=disable"
|
||||
fi
|
||||
|
||||
# Execute migration based on command
|
||||
case "$1" in
|
||||
up)
|
||||
echo "Running migrations up..."
|
||||
echo "DB_URL: ${DB_URL}"
|
||||
echo "DB_USER: ${DB_USER}"
|
||||
echo "DB_PASSWORD: ${DB_PASSWORD}"
|
||||
echo "DB_HOST: ${DB_HOST}"
|
||||
echo "DB_PORT: ${DB_PORT}"
|
||||
echo "DB_NAME: ${DB_NAME}"
|
||||
echo "MIGRATIONS_DIR: ${MIGRATIONS_DIR}"
|
||||
migrate -path ${MIGRATIONS_DIR} -database ${DB_URL} up
|
||||
;;
|
||||
down)
|
||||
echo "Running migrations down..."
|
||||
migrate -path ${MIGRATIONS_DIR} -database ${DB_URL} down
|
||||
;;
|
||||
create)
|
||||
if [ -z "$2" ]; then
|
||||
echo "Error: Migration name is required"
|
||||
echo "Usage: $0 create <migration_name>"
|
||||
exit 1
|
||||
fi
|
||||
echo "Creating migration files for $2..."
|
||||
migrate create -ext sql -dir ${MIGRATIONS_DIR} -seq $2
|
||||
echo "Created:"
|
||||
echo " - ${MIGRATIONS_DIR}/$(ls -t ${MIGRATIONS_DIR} | head -1)"
|
||||
echo " - ${MIGRATIONS_DIR}/$(ls -t ${MIGRATIONS_DIR} | head -2 | tail -1)"
|
||||
;;
|
||||
version)
|
||||
echo "Checking current migration version..."
|
||||
migrate -path ${MIGRATIONS_DIR} -database ${DB_URL} version
|
||||
;;
|
||||
force)
|
||||
if [ -z "$2" ]; then
|
||||
echo "Error: Version number is required"
|
||||
echo "Usage: $0 force <version>"
|
||||
echo "Note: Use -1 to reset to no version (allows re-running all migrations)"
|
||||
exit 1
|
||||
fi
|
||||
VERSION="$2"
|
||||
echo "Forcing migration version to $VERSION..."
|
||||
# Use env to pass the command, avoiding shell flag parsing issues with negative numbers
|
||||
env migrate -path "${MIGRATIONS_DIR}" -database "${DB_URL}" force -- "$VERSION"
|
||||
;;
|
||||
goto)
|
||||
if [ -z "$2" ]; then
|
||||
echo "Error: Version number is required"
|
||||
echo "Usage: $0 goto <version>"
|
||||
exit 1
|
||||
fi
|
||||
echo "Migrating to version $2..."
|
||||
migrate -path ${MIGRATIONS_DIR} -database ${DB_URL} goto $2
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {up|down|create <migration_name>|version|force <version>|goto <version>}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "Migration command completed successfully"
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproducibly merge pinned model metadata and reviewed protocol overrides.
|
||||
|
||||
Network updates are intentionally separate: model_catalog_diff.py compares
|
||||
models.dev with the generated catalog, then maintainers review changes to the
|
||||
pinned source. Upstream metadata cannot silently replace wire compatibility.
|
||||
"""
|
||||
import argparse
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
HERE = Path(__file__).resolve().parent
|
||||
DATA = ROOT / "internal/models/catalog/data"
|
||||
|
||||
|
||||
def load(path):
|
||||
def unique(pairs):
|
||||
obj = {}
|
||||
for key, value in pairs:
|
||||
if key in obj:
|
||||
raise ValueError(f"{path}: duplicate JSON key {key}")
|
||||
obj[key] = value
|
||||
return obj
|
||||
return json.loads(path.read_text(), object_pairs_hook=unique)
|
||||
|
||||
|
||||
def identity(entry):
|
||||
kind = entry.get("type", "KnowledgeQA")
|
||||
if not entry.get("id") and not entry.get("match"):
|
||||
raise ValueError(f"model needs id or match: {entry}")
|
||||
return kind, entry.get("id", ""), entry.get("match", "")
|
||||
|
||||
|
||||
def generate():
|
||||
sources = load(HERE / "sources.json")
|
||||
result = {"version": 1, "providers": {}}
|
||||
for source in sources["metadata"]:
|
||||
data = load(HERE / source["path"])
|
||||
if data["version"] != 1:
|
||||
raise ValueError("unsupported metadata version")
|
||||
for provider, entries in data["providers"].items():
|
||||
if provider in result["providers"]:
|
||||
raise ValueError(f"duplicate provider {provider}")
|
||||
result["providers"][provider] = copy.deepcopy(entries)
|
||||
overrides = load(DATA / "overrides.json")
|
||||
if overrides["version"] != 1:
|
||||
raise ValueError("unsupported overrides version")
|
||||
for provider, patches in overrides["providers"].items():
|
||||
if provider not in result["providers"]:
|
||||
raise ValueError(f"override has unknown provider {provider}")
|
||||
entries = result["providers"][provider]
|
||||
index = {identity(entry): entry for entry in entries}
|
||||
seen = set()
|
||||
for patch in patches:
|
||||
key = identity(patch)
|
||||
if key in seen:
|
||||
raise ValueError(f"duplicate override {provider}/{key}")
|
||||
seen.add(key)
|
||||
# Unknown entries are explicit additions, suitable for models that
|
||||
# have no upstream metadata yet. Existing entries patch field-wise.
|
||||
if key not in index:
|
||||
entries.append(copy.deepcopy(patch))
|
||||
index[key] = entries[-1]
|
||||
else:
|
||||
index[key].update(copy.deepcopy(patch))
|
||||
for provider, entries in result["providers"].items():
|
||||
seen = set()
|
||||
for entry in entries:
|
||||
key = identity(entry)
|
||||
if key in seen:
|
||||
raise ValueError(f"duplicate model {provider}/{key}")
|
||||
seen.add(key)
|
||||
for field in ("context_window", "max_output_tokens", "dimension"):
|
||||
if field in entry and (type(entry[field]) is not int or entry[field] < 0):
|
||||
raise ValueError(f"invalid {field} in {provider}/{key}")
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true", help="fail if generated data is stale")
|
||||
args = parser.parse_args()
|
||||
result = generate()
|
||||
rendered = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
|
||||
target = DATA / "models.generated.json"
|
||||
if args.check:
|
||||
if not target.exists() or target.read_text() != rendered:
|
||||
parser.exit(1, "model catalog is stale; run scripts/model-catalog/generate.py\n")
|
||||
else:
|
||||
target.write_text(rendered)
|
||||
print(f"Verified {len(result['providers'])} providers and "
|
||||
f"{sum(map(len, result['providers'].values()))} catalog rules")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"version": 1,
|
||||
"metadata": [
|
||||
{
|
||||
"path": "../../internal/models/catalog/data/seed.json",
|
||||
"description": "Pinned migration metadata; per-entry source links point to vendor documentation."
|
||||
}
|
||||
],
|
||||
"models_dev": {
|
||||
"url": "https://models.dev/api.json",
|
||||
"provider_map": {
|
||||
"openai": "openai",
|
||||
"anthropic": "anthropic",
|
||||
"gemini": "google",
|
||||
"deepseek": "deepseek",
|
||||
"zhipu": "zhipuai",
|
||||
"aliyun": "alibaba-cn",
|
||||
"volcengine": "volcengine",
|
||||
"moonshot": "moonshotai-cn",
|
||||
"minimax": "minimax-cn",
|
||||
"mimo": "xiaomi",
|
||||
"siliconflow": "siliconflow-cn",
|
||||
"modelscope": "modelscope",
|
||||
"qiniu": "qiniu-ai",
|
||||
"longcat": "longcat",
|
||||
"novita": "novita-ai",
|
||||
"nvidia": "nvidia",
|
||||
"openrouter": "openrouter",
|
||||
"requesty": "requesty"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the built-in vendor catalogs against models.dev and print a diff.
|
||||
|
||||
Development-time helper, never run at runtime: it reports numeric facts
|
||||
(context window, max output, cost, new/retired ids) so a maintainer can update
|
||||
internal/models/catalog/data/seed.json by hand. Behavioural facts (compat,
|
||||
thinking format) are intentionally out of scope — models.dev does not carry
|
||||
them and they must come from vendor documentation.
|
||||
|
||||
Usage:
|
||||
scripts/model_catalog_diff.py # fetch https://models.dev/api.json
|
||||
scripts/model_catalog_diff.py --api api.json # use a downloaded copy
|
||||
scripts/model_catalog_diff.py --vendor deepseek
|
||||
scripts/model_catalog_diff.py --exit-code # non-zero when anything differs
|
||||
|
||||
Findings are advisory: `+` is a model upstream has and we do not, `~` is a
|
||||
numeric difference, `?` is an entry upstream does not list (often correct —
|
||||
vendor-specific aliases and China-only ids are missing from models.dev).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CATALOG = ROOT / "internal/models/catalog/data/models.generated.json"
|
||||
|
||||
# Academy vendor id -> models.dev provider id.
|
||||
PROVIDER_MAP = json.loads((ROOT / "scripts/model-catalog/sources.json").read_text())["models_dev"]["provider_map"]
|
||||
|
||||
|
||||
MODELS_DEV_URL = "https://models.dev/api.json"
|
||||
|
||||
|
||||
def load_api(path):
|
||||
"""Load the models.dev catalog from a file, or fetch it once.
|
||||
|
||||
models.dev rejects the default urllib user agent, so send a real one.
|
||||
When the network is unavailable (CI, offline dev box), download the file
|
||||
by hand and pass --api, or set MODELS_DEV_API to its path.
|
||||
"""
|
||||
path = path or os.environ.get("MODELS_DEV_API")
|
||||
if path:
|
||||
return json.loads(Path(path).read_text())
|
||||
request = urllib.request.Request(
|
||||
MODELS_DEV_URL,
|
||||
headers={"User-Agent": "Academy-model-catalog-diff/1.0 (+https://github.com/Tencent/WeKnora)"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=60) as resp:
|
||||
return json.load(resp)
|
||||
except urllib.error.URLError as err:
|
||||
raise SystemExit(
|
||||
f"failed to fetch {MODELS_DEV_URL}: {err}\n"
|
||||
"Download it manually and re-run with --api <file>, or set MODELS_DEV_API."
|
||||
) from err
|
||||
|
||||
|
||||
def load_catalog(vendor):
|
||||
entries = json.loads(CATALOG.read_text())["providers"].get(vendor, [])
|
||||
return {m["id"]: m for m in entries if m.get("id")}
|
||||
|
||||
|
||||
def compare(vendor, upstream, ours):
|
||||
lines = []
|
||||
up_models = upstream.get("models", {})
|
||||
for mid, spec in sorted(up_models.items()):
|
||||
mods = spec.get("modalities", {})
|
||||
if "text" not in mods.get("output", ["text"]):
|
||||
continue # image / audio generation, out of scope
|
||||
entry = ours.get(mid)
|
||||
limit = spec.get("limit", {})
|
||||
cost = spec.get("cost", {})
|
||||
if entry is None:
|
||||
lines.append(
|
||||
f" + {mid} (new upstream: ctx={limit.get('context')} out={limit.get('output')} "
|
||||
f"reasoning={spec.get('reasoning')} released={spec.get('release_date')})"
|
||||
)
|
||||
continue
|
||||
diffs = []
|
||||
if limit.get("context") and entry.get("context_window") != limit.get("context"):
|
||||
diffs.append(f"context_window {entry.get('context_window')} -> {limit.get('context')}")
|
||||
if limit.get("output") and entry.get("max_output_tokens") != limit.get("output"):
|
||||
diffs.append(f"max_output_tokens {entry.get('max_output_tokens')} -> {limit.get('output')}")
|
||||
if bool(entry.get("reasoning")) != bool(spec.get("reasoning")):
|
||||
diffs.append(f"reasoning {entry.get('reasoning')} -> {spec.get('reasoning')}")
|
||||
ours_cost = entry.get("cost") or {}
|
||||
for key, up_key in (("input", "input"), ("output", "output"), ("cache_read", "cache_read")):
|
||||
if cost.get(up_key) is not None and ours_cost.get(key) != cost.get(up_key):
|
||||
diffs.append(f"cost.{key} {ours_cost.get(key)} -> {cost.get(up_key)}")
|
||||
if diffs:
|
||||
lines.append(f" ~ {mid}: " + "; ".join(diffs))
|
||||
for mid in sorted(ours):
|
||||
if mid not in up_models:
|
||||
lines.append(f" ? {mid} (not in models.dev; keep if the vendor still documents it)")
|
||||
return lines
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--api", help="path to a downloaded models.dev api.json")
|
||||
parser.add_argument("--vendor", help="limit to one Academy vendor id")
|
||||
parser.add_argument(
|
||||
"--exit-code", action="store_true",
|
||||
help="exit 1 when there are findings (for a scheduled job); default always exits 0",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
api = load_api(args.api)
|
||||
vendors = [args.vendor] if args.vendor else sorted(PROVIDER_MAP)
|
||||
exit_code = 0
|
||||
for vendor in vendors:
|
||||
upstream_id = PROVIDER_MAP.get(vendor)
|
||||
if not upstream_id:
|
||||
print(f"== {vendor}: no models.dev mapping", file=sys.stderr)
|
||||
continue
|
||||
upstream = api.get(upstream_id)
|
||||
if upstream is None:
|
||||
print(f"== {vendor}: models.dev provider {upstream_id!r} missing", file=sys.stderr)
|
||||
continue
|
||||
lines = compare(vendor, upstream, load_catalog(vendor))
|
||||
print(f"== {vendor} (models.dev: {upstream_id}) — {len(lines)} finding(s)")
|
||||
for line in lines:
|
||||
print(line)
|
||||
if lines:
|
||||
exit_code = 1
|
||||
return exit_code if args.exit_code else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
#
|
||||
# 本地构建 + 打包 Academy Lite 发行包
|
||||
#
|
||||
# 用法:
|
||||
# ./scripts/package-lite.sh # 自动检测版本
|
||||
# ./scripts/package-lite.sh v0.2.0 # 指定版本号
|
||||
# SKIP_FRONTEND=1 ./scripts/package-lite.sh # 跳过前端构建(使用已有 web/)
|
||||
#
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
cd "${ROOT_DIR}"
|
||||
|
||||
# Resolve version
|
||||
if [ -n "${1:-}" ]; then
|
||||
VERSION="$1"
|
||||
elif command -v git >/dev/null 2>&1; then
|
||||
VERSION=$(git describe --tags --abbrev=0 2>/dev/null || echo "dev")
|
||||
else
|
||||
VERSION="dev"
|
||||
fi
|
||||
|
||||
GOOS=$(go env GOOS)
|
||||
GOARCH=$(go env GOARCH)
|
||||
ARCHIVE="Academy-lite_${VERSION}_${GOOS}_${GOARCH}"
|
||||
DIST_DIR="dist/${ARCHIVE}"
|
||||
|
||||
echo "=== Academy Lite Packager ==="
|
||||
echo " Version : ${VERSION}"
|
||||
echo " Platform: ${GOOS}/${GOARCH}"
|
||||
echo " Output : dist/${ARCHIVE}.tar.gz"
|
||||
echo ""
|
||||
|
||||
# ── Step 1: Build frontend (if not skipped) ──
|
||||
if [ "${SKIP_FRONTEND:-}" != "1" ]; then
|
||||
if [ -f frontend/package.json ]; then
|
||||
echo ">> Building frontend..."
|
||||
(cd frontend && npm ci --prefer-offline && npm run build)
|
||||
rm -rf web
|
||||
cp -r frontend/dist web
|
||||
else
|
||||
echo ">> No frontend/package.json found, skipping frontend build"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -f web/index.html ]; then
|
||||
echo "WARNING: web/index.html not found — package will not include frontend"
|
||||
fi
|
||||
|
||||
# ── Step 2: Build Go binary ──
|
||||
echo ">> Building Academy-lite binary..."
|
||||
export EDITION=lite
|
||||
eval "$(./scripts/get_version.sh env)"
|
||||
LDFLAGS="-w -s $(./scripts/get_version.sh ldflags)"
|
||||
export CGO_CFLAGS="-Wno-deprecated-declarations"
|
||||
if [ "$(uname)" = "Darwin" ]; then
|
||||
export CGO_LDFLAGS="-Wl,-no_warn_duplicate_libraries"
|
||||
fi
|
||||
CGO_ENABLED=1 go build -tags "sqlite_fts5" -ldflags="${LDFLAGS}" \
|
||||
-o Academy-lite ./cmd/server
|
||||
|
||||
# ── Step 3: Assemble package ──
|
||||
echo ">> Assembling package..."
|
||||
rm -rf "${DIST_DIR}"
|
||||
mkdir -p "${DIST_DIR}/web"
|
||||
|
||||
cp Academy-lite "${DIST_DIR}/"
|
||||
bash ./scripts/copy-licenses.sh "${DIST_DIR}"
|
||||
if [ -d web ] && [ -f web/index.html ]; then
|
||||
cp -r web/* "${DIST_DIR}/web/"
|
||||
fi
|
||||
cp .env.lite.example "${DIST_DIR}/"
|
||||
cp docs/LITE.md "${DIST_DIR}/README.md"
|
||||
if [ -d config ]; then
|
||||
cp -r config "${DIST_DIR}/config"
|
||||
fi
|
||||
if [ -d migrations/sqlite ]; then
|
||||
mkdir -p "${DIST_DIR}/migrations/sqlite"
|
||||
cp -r migrations/sqlite/* "${DIST_DIR}/migrations/sqlite/"
|
||||
fi
|
||||
if [ -f deploy/academy-lite.service ]; then
|
||||
cp deploy/academy-lite.service "${DIST_DIR}/"
|
||||
fi
|
||||
|
||||
# ── Step 4: Create tarball ──
|
||||
echo ">> Creating tarball..."
|
||||
(cd dist && tar czf "${ARCHIVE}.tar.gz" "${ARCHIVE}")
|
||||
(cd dist && shasum -a 256 "${ARCHIVE}.tar.gz" > "${ARCHIVE}.tar.gz.sha256")
|
||||
|
||||
echo ""
|
||||
echo "=== Done ==="
|
||||
echo " dist/${ARCHIVE}.tar.gz"
|
||||
echo " dist/${ARCHIVE}.tar.gz.sha256"
|
||||
SIZE=$(du -h "dist/${ARCHIVE}.tar.gz" | cut -f1)
|
||||
echo " Size: ${SIZE}"
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
#
|
||||
# 本地构建 + 打包 Academy macOS 桌面应用 (.app)
|
||||
#
|
||||
# 用法:
|
||||
# ./scripts/package-mac-app.sh
|
||||
# SKIP_FRONTEND=1 ./scripts/package-mac-app.sh # 跳过前端构建
|
||||
#
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
cd "${ROOT_DIR}"
|
||||
|
||||
APP_NAME="Academy Lite"
|
||||
APP_BUNDLE="${APP_NAME}.app"
|
||||
DIST_DIR="dist/${APP_BUNDLE}"
|
||||
|
||||
echo "=== Academy Mac App Packager ==="
|
||||
echo " Output: dist/${APP_BUNDLE}"
|
||||
echo ""
|
||||
|
||||
# ── Step 1: Build frontend (if not skipped) ──
|
||||
if [ "${SKIP_FRONTEND:-}" != "1" ]; then
|
||||
if [ -f frontend/package.json ]; then
|
||||
echo ">> Building frontend..."
|
||||
(cd frontend && npm ci --prefer-offline && npm run build)
|
||||
# Lite 后端从 ./web 提供 SPA(见 internal/router serveFrontendStatic),与 package-lite.sh 一致须用 dist 更新 web
|
||||
echo ">> Sync frontend/dist -> web/"
|
||||
rm -rf web
|
||||
cp -r frontend/dist web
|
||||
else
|
||||
echo ">> No frontend/package.json found, skipping frontend build"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -f web/index.html ]; then
|
||||
echo "WARNING: web/index.html not found. Lite 桌面会从 Resources/web 提供前端;请先完整构建前端(勿使用 SKIP_FRONTEND),或手动: cp -r frontend/dist web"
|
||||
fi
|
||||
|
||||
# ── Step 2: Build with Wails ──
|
||||
echo ">> Building Wails Desktop App..."
|
||||
|
||||
# 如果没有 wails 命令行工具,提醒安装
|
||||
if ! command -v wails >/dev/null 2>&1; then
|
||||
echo "Wails CLI not found. Please install it first:"
|
||||
echo "go install github.com/wailsapp/wails/v2/cmd/wails@latest"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 使用 Wails 打包 (需要先处理依赖代理问题)
|
||||
export GONOSUMDB="git.sr.ht/*"
|
||||
export GOPROXY="https://goproxy.cn,direct"
|
||||
export CGO_CFLAGS="-Wno-deprecated-declarations"
|
||||
export CGO_LDFLAGS="-Wl,-no_warn_duplicate_libraries"
|
||||
export EDITION=lite
|
||||
|
||||
# Milvus 与 Qdrant 的 gRPC 生成代码均注册名为 "common.proto" 的描述符,同一进程内会冲突。
|
||||
# -ldflags -X conflictPolicy=warn 只作用于最终链接,无法覆盖 Wails「生成绑定」时单独启动的 go 子进程。
|
||||
# 官方做法:见 https://protobuf.dev/reference/go/faq#namespace-conflict
|
||||
export GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn
|
||||
|
||||
# 获取版本号并配置 LDFLAGS
|
||||
eval "$(./scripts/get_version.sh env)"
|
||||
LDFLAGS="$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'"
|
||||
|
||||
# 默认生成 Wails 绑定(供 window.go.main.App.* 等);若加 -skipbindings 则需在 OnDomReady 注入 __ACADEMY_API_BASE__
|
||||
(cd cmd/desktop && wails build -clean -tags "sqlite_fts5" -ldflags="$LDFLAGS" -o "${APP_NAME}")
|
||||
|
||||
# ── Step 3: Copy generated .app to dist ──
|
||||
echo ">> Assembling package..."
|
||||
mkdir -p dist
|
||||
rm -rf "${DIST_DIR}"
|
||||
cp -R "cmd/desktop/build/bin/${APP_BUNDLE}" "dist/"
|
||||
|
||||
# 将配置文件和初始数据库迁移脚本塞进 .app 内部资源里
|
||||
RESOURCES_DIR="${DIST_DIR}/Contents/Resources"
|
||||
mkdir -p "${RESOURCES_DIR}/config"
|
||||
mkdir -p "${RESOURCES_DIR}/migrations/sqlite"
|
||||
bash ./scripts/copy-licenses.sh "${RESOURCES_DIR}"
|
||||
|
||||
if [ -f .env.lite.example ]; then
|
||||
cp .env.lite.example "${RESOURCES_DIR}/.env"
|
||||
fi
|
||||
if [ -d migrations/sqlite ]; then
|
||||
cp -r migrations/sqlite/* "${RESOURCES_DIR}/migrations/sqlite/"
|
||||
fi
|
||||
if [ -d config ]; then
|
||||
cp -r config/* "${RESOURCES_DIR}/config/"
|
||||
fi
|
||||
if [ -d web ]; then
|
||||
cp -r web "${RESOURCES_DIR}/"
|
||||
fi
|
||||
|
||||
# 注意:Wails build 生成的二进制文件工作目录默认是 app 的 Contents/MacOS 目录
|
||||
# 后续可能需要调整代码中对配置文件的路径读取逻辑。
|
||||
|
||||
echo ""
|
||||
echo "=== Done ==="
|
||||
echo " App generated at: dist/${APP_BUNDLE}"
|
||||
echo " You can double click it to run!"
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/bin/bash
|
||||
# 快速启动开发环境的一键脚本
|
||||
# 此脚本会在一个终端中启动所有必需的服务
|
||||
|
||||
# 设置颜色
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # 无颜色
|
||||
|
||||
# 获取项目根目录
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
|
||||
|
||||
log_info() {
|
||||
printf "%b\n" "${BLUE}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
printf "%b\n" "${GREEN}[SUCCESS]${NC} $1"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
printf "%b\n" "${RED}[ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
printf "%b\n" "${YELLOW}[WARNING]${NC} $1"
|
||||
}
|
||||
|
||||
echo ""
|
||||
printf "%b\n" "${GREEN}========================================${NC}"
|
||||
printf "%b\n" "${GREEN} Academy 快速开发环境启动${NC}"
|
||||
printf "%b\n" "${GREEN}========================================${NC}"
|
||||
echo ""
|
||||
|
||||
# 检查是否在项目根目录
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 1. 启动基础设施
|
||||
log_info "步骤 1/3: 启动基础设施服务..."
|
||||
./scripts/dev.sh start
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "基础设施启动失败"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 等待服务就绪
|
||||
log_info "等待服务启动完成..."
|
||||
sleep 5
|
||||
|
||||
# 2. 询问是否启动后端
|
||||
echo ""
|
||||
log_info "步骤 2/3: 启动后端应用"
|
||||
printf "%b" "${YELLOW}是否在当前终端启动后端? (y/N): ${NC}"
|
||||
read -r start_backend
|
||||
|
||||
if [ "$start_backend" = "y" ] || [ "$start_backend" = "Y" ]; then
|
||||
log_info "启动后端..."
|
||||
# 在后台启动后端
|
||||
nohup bash -c 'cd "'$PROJECT_ROOT'" && ./scripts/dev.sh app' > "$PROJECT_ROOT/logs/backend.log" 2>&1 &
|
||||
BACKEND_PID=$!
|
||||
echo $BACKEND_PID > "$PROJECT_ROOT/tmp/backend.pid"
|
||||
log_success "后端已在后台启动 (PID: $BACKEND_PID)"
|
||||
log_info "查看后端日志: tail -f $PROJECT_ROOT/logs/backend.log"
|
||||
else
|
||||
log_warning "跳过后端启动"
|
||||
log_info "稍后在新终端运行: make dev-app 或 ./scripts/dev.sh app"
|
||||
fi
|
||||
|
||||
# 3. 询问是否启动前端
|
||||
echo ""
|
||||
log_info "步骤 3/3: 启动前端应用"
|
||||
printf "%b" "${YELLOW}是否在当前终端启动前端? (y/N): ${NC}"
|
||||
read -r start_frontend
|
||||
|
||||
if [ "$start_frontend" = "y" ] || [ "$start_frontend" = "Y" ]; then
|
||||
log_info "启动前端..."
|
||||
# 在后台启动前端
|
||||
nohup bash -c 'cd "'$PROJECT_ROOT'/frontend" && npm run dev' > "$PROJECT_ROOT/logs/frontend.log" 2>&1 &
|
||||
FRONTEND_PID=$!
|
||||
echo $FRONTEND_PID > "$PROJECT_ROOT/tmp/frontend.pid"
|
||||
log_success "前端已在后台启动 (PID: $FRONTEND_PID)"
|
||||
log_info "查看前端日志: tail -f $PROJECT_ROOT/logs/frontend.log"
|
||||
else
|
||||
log_warning "跳过前端启动"
|
||||
log_info "稍后在新终端运行: make dev-frontend 或 ./scripts/dev.sh frontend"
|
||||
fi
|
||||
|
||||
# 显示总结
|
||||
echo ""
|
||||
printf "%b\n" "${GREEN}========================================${NC}"
|
||||
printf "%b\n" "${GREEN} 启动完成!${NC}"
|
||||
printf "%b\n" "${GREEN}========================================${NC}"
|
||||
echo ""
|
||||
|
||||
log_info "访问地址:"
|
||||
echo " - 前端: http://localhost:5173"
|
||||
echo " - 后端 API: http://localhost:8080"
|
||||
echo " - MinIO Console: http://localhost:9001"
|
||||
echo ""
|
||||
|
||||
log_info "管理命令:"
|
||||
echo " - 查看服务状态: make dev-status"
|
||||
echo " - 查看日志: make dev-logs"
|
||||
echo " - 停止所有服务: make dev-stop"
|
||||
echo ""
|
||||
|
||||
if [ -f "$PROJECT_ROOT/tmp/backend.pid" ] || [ -f "$PROJECT_ROOT/tmp/frontend.pid" ]; then
|
||||
log_warning "停止后台进程:"
|
||||
if [ -f "$PROJECT_ROOT/tmp/backend.pid" ]; then
|
||||
echo " - 停止后端: kill \$(cat $PROJECT_ROOT/tmp/backend.pid)"
|
||||
fi
|
||||
if [ -f "$PROJECT_ROOT/tmp/frontend.pid" ]; then
|
||||
echo " - 停止前端: kill \$(cat $PROJECT_ROOT/tmp/frontend.pid)"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo ""
|
||||
log_success "开发环境已就绪,开始编码吧!"
|
||||
echo ""
|
||||
|
||||
@@ -0,0 +1,789 @@
|
||||
#!/bin/bash
|
||||
# 该脚本用于按需启动/停止Ollama和docker-compose服务
|
||||
|
||||
# 设置颜色
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # 无颜色
|
||||
|
||||
# 获取项目根目录(脚本所在目录的上一级)
|
||||
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
|
||||
|
||||
# 版本信息
|
||||
VERSION="1.0.1" # 版本更新
|
||||
SCRIPT_NAME=$(basename "$0")
|
||||
|
||||
# 显示帮助信息
|
||||
show_help() {
|
||||
printf "%b\n" "${GREEN}Academy 启动脚本 v${VERSION}${NC}"
|
||||
printf "%b\n" "${GREEN}用法:${NC} $0 [选项]"
|
||||
echo "选项:"
|
||||
echo " -h, --help 显示帮助信息"
|
||||
echo " -o, --ollama 启动Ollama服务"
|
||||
echo " -d, --docker 启动Docker容器服务"
|
||||
echo " -a, --all 启动所有服务(默认)"
|
||||
echo " -s, --stop 停止所有服务"
|
||||
echo " -c, --check 检查环境并诊断问题"
|
||||
echo " -r, --restart 重新构建并重启指定容器"
|
||||
echo " -l, --list 列出所有正在运行的容器"
|
||||
echo " -p, --pull 拉取最新的Docker镜像"
|
||||
echo " --no-pull 启动时不拉取镜像(默认会拉取)"
|
||||
echo " -v, --version 显示版本信息"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# 显示版本信息
|
||||
show_version() {
|
||||
printf "%b\n" "${GREEN}Academy 启动脚本 v${VERSION}${NC}"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# 日志函数
|
||||
log_info() {
|
||||
printf "%b\n" "${BLUE}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
printf "%b\n" "${YELLOW}[WARNING]${NC} $1"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
printf "%b\n" "${RED}[ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
printf "%b\n" "${GREEN}[SUCCESS]${NC} $1"
|
||||
}
|
||||
|
||||
# Inject git short hash into the frontend image when composing from source.
|
||||
# docker-compose.yml interpolates VITE_FRONTEND_COMMIT; the build context is
|
||||
# frontend/ (no .git), so Vite cannot discover the commit on its own.
|
||||
export_frontend_build_args() {
|
||||
if [ -n "${VITE_FRONTEND_COMMIT:-}" ]; then
|
||||
export VITE_FRONTEND_COMMIT
|
||||
return 0
|
||||
fi
|
||||
# shellcheck source=/dev/null
|
||||
eval "$("$PROJECT_ROOT/scripts/get_version.sh" env)"
|
||||
export VITE_FRONTEND_COMMIT="${COMMIT_ID:-unknown}"
|
||||
log_info "VITE_FRONTEND_COMMIT=${VITE_FRONTEND_COMMIT}"
|
||||
}
|
||||
|
||||
# 选择可用的 Docker Compose 命令(优先 docker compose,其次 docker-compose)
|
||||
DOCKER_COMPOSE_BIN=""
|
||||
DOCKER_COMPOSE_SUBCMD=""
|
||||
|
||||
detect_compose_cmd() {
|
||||
# 优先使用 Docker Compose 插件
|
||||
if docker compose version &> /dev/null; then
|
||||
DOCKER_COMPOSE_BIN="docker"
|
||||
DOCKER_COMPOSE_SUBCMD="compose"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# 回退到 docker-compose (v1)
|
||||
if command -v docker-compose &> /dev/null; then
|
||||
if docker-compose version &> /dev/null; then
|
||||
DOCKER_COMPOSE_BIN="docker-compose"
|
||||
DOCKER_COMPOSE_SUBCMD=""
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# 都不可用
|
||||
return 1
|
||||
}
|
||||
|
||||
# 检查并创建.env文件
|
||||
check_env_file() {
|
||||
log_info "检查环境变量配置..."
|
||||
if [ ! -f "$PROJECT_ROOT/.env" ]; then
|
||||
log_warning ".env 文件不存在,将从模板创建"
|
||||
if [ -f "$PROJECT_ROOT/.env.example" ]; then
|
||||
cp "$PROJECT_ROOT/.env.example" "$PROJECT_ROOT/.env"
|
||||
log_success "已从 .env.example 创建 .env 文件"
|
||||
else
|
||||
log_error "未找到 .env.example 模板文件,无法创建 .env 文件"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
log_info ".env 文件已存在"
|
||||
fi
|
||||
|
||||
# 检查必要的环境变量是否已设置
|
||||
source "$PROJECT_ROOT/.env"
|
||||
local missing_vars=()
|
||||
|
||||
# 检查基础变量
|
||||
if [ -z "$DB_DRIVER" ]; then missing_vars+=("DB_DRIVER"); fi
|
||||
if [ -z "$STORAGE_TYPE" ]; then missing_vars+=("STORAGE_TYPE"); fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# 安装Ollama(根据平台不同采用不同方法)
|
||||
install_ollama() {
|
||||
# 检查是否为远程服务
|
||||
get_ollama_base_url
|
||||
|
||||
if [ $IS_REMOTE -eq 1 ]; then
|
||||
log_info "检测到远程Ollama服务配置,无需在本地安装Ollama"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_info "本地Ollama未安装,正在安装..."
|
||||
|
||||
OS=$(uname)
|
||||
if [ "$OS" = "Darwin" ]; then
|
||||
# Mac安装方式
|
||||
log_info "检测到Mac系统,使用brew安装Ollama..."
|
||||
if ! command -v brew &> /dev/null; then
|
||||
# 通过安装包安装
|
||||
log_info "Homebrew未安装,使用直接下载方式..."
|
||||
curl -fsSL https://ollama.com/download/Ollama-darwin.zip -o ollama.zip
|
||||
unzip ollama.zip
|
||||
mv ollama /usr/local/bin
|
||||
rm ollama.zip
|
||||
else
|
||||
brew install ollama
|
||||
fi
|
||||
else
|
||||
# Linux安装方式
|
||||
log_info "检测到Linux系统,使用安装脚本..."
|
||||
curl -fsSL https://ollama.com/install.sh | sh
|
||||
fi
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
log_success "本地Ollama安装完成"
|
||||
return 0
|
||||
else
|
||||
log_error "本地Ollama安装失败"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# 获取Ollama基础URL,检查是否为远程服务
|
||||
get_ollama_base_url() {
|
||||
|
||||
check_env_file
|
||||
|
||||
# 从环境变量获取Ollama基础URL
|
||||
OLLAMA_URL=${OLLAMA_BASE_URL:-"http://host.docker.internal:11434"}
|
||||
# 提取主机部分
|
||||
OLLAMA_HOST=$(echo "$OLLAMA_URL" | sed -E 's|^https?://||' | sed -E 's|:[0-9]+$||' | sed -E 's|/.*$||')
|
||||
# 提取端口部分
|
||||
OLLAMA_PORT=$(echo "$OLLAMA_URL" | grep -oE ':[0-9]+' | grep -oE '[0-9]+' || echo "11434")
|
||||
# 检查是否为localhost或127.0.0.1
|
||||
IS_REMOTE=0
|
||||
if [ "$OLLAMA_HOST" = "localhost" ] || [ "$OLLAMA_HOST" = "127.0.0.1" ] || [ "$OLLAMA_HOST" = "host.docker.internal" ]; then
|
||||
IS_REMOTE=0 # 本地服务
|
||||
else
|
||||
IS_REMOTE=1 # 远程服务
|
||||
fi
|
||||
}
|
||||
|
||||
# 启动Ollama服务
|
||||
start_ollama() {
|
||||
log_info "正在检查Ollama服务..."
|
||||
# 提取主机和端口
|
||||
get_ollama_base_url
|
||||
log_info "Ollama服务地址: $OLLAMA_URL"
|
||||
|
||||
if [ $IS_REMOTE -eq 1 ]; then
|
||||
log_info "检测到远程Ollama服务,将直接使用远程服务,不进行本地安装和启动"
|
||||
# 检查远程服务是否可用
|
||||
if curl -s "$OLLAMA_URL/api/tags" &> /dev/null; then
|
||||
log_success "远程Ollama服务可访问"
|
||||
return 0
|
||||
else
|
||||
log_warning "远程Ollama服务不可访问,请确认服务地址正确且已启动"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# 以下为本地服务的处理
|
||||
# 检查Ollama是否已安装
|
||||
if ! command -v ollama &> /dev/null; then
|
||||
install_ollama
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# 检查Ollama服务是否已运行
|
||||
if curl -s "http://localhost:$OLLAMA_PORT/api/tags" &> /dev/null; then
|
||||
log_success "本地Ollama服务已经在运行,端口:$OLLAMA_PORT"
|
||||
else
|
||||
log_info "启动本地Ollama服务..."
|
||||
# 注意:官方推荐使用 systemctl 或 launchctl 管理服务,直接后台运行仅用于临时场景
|
||||
systemctl restart ollama || (ollama serve > /dev/null 2>&1 < /dev/null &)
|
||||
|
||||
# 等待服务启动
|
||||
MAX_RETRIES=30
|
||||
COUNT=0
|
||||
while [ $COUNT -lt $MAX_RETRIES ]; do
|
||||
if curl -s "http://localhost:$OLLAMA_PORT/api/tags" &> /dev/null; then
|
||||
log_success "本地Ollama服务已成功启动,端口:$OLLAMA_PORT"
|
||||
break
|
||||
fi
|
||||
echo -ne "等待Ollama服务启动... ($COUNT/$MAX_RETRIES)\r"
|
||||
sleep 1
|
||||
COUNT=$((COUNT + 1))
|
||||
done
|
||||
echo "" # 换行
|
||||
|
||||
if [ $COUNT -eq $MAX_RETRIES ]; then
|
||||
log_error "本地Ollama服务启动失败"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
log_success "本地Ollama服务地址: http://localhost:$OLLAMA_PORT"
|
||||
return 0
|
||||
}
|
||||
|
||||
# 停止Ollama服务
|
||||
stop_ollama() {
|
||||
log_info "正在停止Ollama服务..."
|
||||
|
||||
# 检查是否为远程服务
|
||||
get_ollama_base_url
|
||||
|
||||
if [ $IS_REMOTE -eq 1 ]; then
|
||||
log_info "检测到远程Ollama服务,无需在本地停止"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# 检查Ollama是否已安装
|
||||
if ! command -v ollama &> /dev/null; then
|
||||
log_info "本地Ollama未安装,无需停止"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# 查找并终止Ollama进程
|
||||
if pgrep -x "ollama" > /dev/null; then
|
||||
# 优先使用systemctl
|
||||
if command -v systemctl &> /dev/null; then
|
||||
sudo systemctl stop ollama
|
||||
else
|
||||
pkill -f "ollama serve"
|
||||
fi
|
||||
log_success "本地Ollama服务已停止"
|
||||
else
|
||||
log_info "本地Ollama服务未运行"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# 检查Docker是否已安装
|
||||
check_docker() {
|
||||
log_info "检查Docker环境..."
|
||||
|
||||
if ! command -v docker &> /dev/null; then
|
||||
log_error "未安装Docker,请先安装Docker"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 检查并选择可用的 Docker Compose 命令
|
||||
if detect_compose_cmd; then
|
||||
if [ "$DOCKER_COMPOSE_BIN" = "docker" ]; then
|
||||
log_info "已检测到 Docker Compose 插件 (docker compose)"
|
||||
else
|
||||
log_info "已检测到 docker-compose (v1)"
|
||||
fi
|
||||
else
|
||||
log_error "未检测到 Docker Compose(既没有 docker compose 也没有 docker-compose)。请安装其中之一。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 检查Docker服务运行状态
|
||||
if ! docker info &> /dev/null; then
|
||||
log_error "Docker服务未运行,请启动Docker服务"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_success "Docker环境检查通过"
|
||||
return 0
|
||||
}
|
||||
|
||||
check_platform() {
|
||||
# 检测当前系统平台
|
||||
log_info "检测系统平台信息..."
|
||||
if [ "$(uname -m)" = "x86_64" ]; then
|
||||
export PLATFORM="linux/amd64"
|
||||
elif [ "$(uname -m)" = "aarch64" ] || [ "$(uname -m)" = "arm64" ]; then
|
||||
export PLATFORM="linux/arm64"
|
||||
else
|
||||
log_warning "未识别的平台类型:$(uname -m),将使用默认平台 linux/amd64"
|
||||
export PLATFORM="linux/amd64"
|
||||
fi
|
||||
log_info "当前平台:$PLATFORM"
|
||||
}
|
||||
|
||||
# 预拉取沙箱镜像(Agent Skills 执行所需,仅拉取不启动)
|
||||
ensure_sandbox_image() {
|
||||
local sandbox_image="wechatopenai/weknora-sandbox:${ACADEMY_VERSION:-latest}"
|
||||
|
||||
# 检查本地是否已存在沙箱镜像
|
||||
if docker image inspect "$sandbox_image" &> /dev/null; then
|
||||
log_success "沙箱镜像已就绪: $sandbox_image"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_info "沙箱镜像 ($sandbox_image) 未检测到,正在后台拉取..."
|
||||
log_info "Agent Skills 功能依赖此镜像,首次执行前需要拉取完成"
|
||||
|
||||
# 后台拉取,不阻塞主流程
|
||||
(
|
||||
if PLATFORM=$PLATFORM "$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD --profile sandbox pull sandbox 2>/dev/null; then
|
||||
log_success "沙箱镜像拉取完成: $sandbox_image"
|
||||
else
|
||||
log_warning "沙箱镜像拉取失败,Agent Skills 功能可能不可用"
|
||||
log_warning "可稍后手动拉取: $DOCKER_COMPOSE_BIN $DOCKER_COMPOSE_SUBCMD --profile sandbox pull sandbox"
|
||||
fi
|
||||
) &
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# 启动Docker容器
|
||||
start_docker() {
|
||||
log_info "正在启动Docker容器..."
|
||||
|
||||
# 检查Docker环境
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 检查.env文件
|
||||
check_env_file
|
||||
|
||||
# 读取.env文件
|
||||
source "$PROJECT_ROOT/.env"
|
||||
storage_type=${STORAGE_TYPE:-local}
|
||||
|
||||
check_platform
|
||||
|
||||
# 进入项目根目录再执行docker-compose命令
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
export_frontend_build_args
|
||||
|
||||
# 启动基本服务
|
||||
log_info "启动核心服务容器..."
|
||||
# 统一通过已检测到的 Compose 命令启动
|
||||
if [ "$NO_PULL" = true ]; then
|
||||
# 不拉取镜像,使用本地镜像
|
||||
log_info "跳过镜像拉取,使用本地镜像..."
|
||||
PLATFORM=$PLATFORM "$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD up --build -d
|
||||
else
|
||||
# 拉取最新镜像
|
||||
log_info "拉取最新镜像..."
|
||||
PLATFORM=$PLATFORM "$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD up --pull always -d
|
||||
fi
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "Docker容器启动失败"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_success "所有Docker容器已成功启动"
|
||||
|
||||
# 显示容器状态
|
||||
log_info "当前容器状态:"
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD ps
|
||||
|
||||
# 预拉取Sandbox镜像(Agent Skills 执行所需,仅拉取不启动)
|
||||
ensure_sandbox_image
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# 停止Docker容器
|
||||
stop_docker() {
|
||||
log_info "正在停止Docker容器..."
|
||||
|
||||
# 检查Docker环境
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
# 即使检查失败也尝试停止,以防万一
|
||||
log_warning "Docker环境检查失败,仍将尝试停止容器..."
|
||||
fi
|
||||
|
||||
# 进入项目根目录再执行docker-compose命令
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 停止所有容器
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD down --remove-orphans
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "Docker容器停止失败"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_success "所有Docker容器已停止"
|
||||
return 0
|
||||
}
|
||||
|
||||
# 列出所有正在运行的容器
|
||||
list_containers() {
|
||||
log_info "列出所有正在运行的容器..."
|
||||
|
||||
# 检查Docker环境
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 进入项目根目录再执行docker-compose命令
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 列出所有容器
|
||||
printf "%b\n" "${BLUE}当前正在运行的容器:${NC}"
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD ps --services | sort
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# 拉取最新的Docker镜像
|
||||
pull_images() {
|
||||
log_info "正在拉取最新的Docker镜像..."
|
||||
|
||||
# 检查Docker环境
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 检查.env文件
|
||||
check_env_file
|
||||
|
||||
# 读取.env文件
|
||||
source "$PROJECT_ROOT/.env"
|
||||
storage_type=${STORAGE_TYPE:-local}
|
||||
|
||||
check_platform
|
||||
|
||||
# 进入项目根目录再执行docker-compose命令
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 拉取所有镜像
|
||||
log_info "拉取所有服务的最新镜像..."
|
||||
PLATFORM=$PLATFORM "$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD pull
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "镜像拉取失败"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 拉取 sandbox 镜像(sandbox 在 profile 中,需要单独拉取)
|
||||
log_info "拉取沙箱镜像..."
|
||||
PLATFORM=$PLATFORM "$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD --profile sandbox pull sandbox 2>/dev/null || \
|
||||
log_warning "沙箱镜像拉取失败(非必需,跳过)"
|
||||
|
||||
log_success "所有镜像已成功拉取到最新版本"
|
||||
|
||||
# 显示拉取的镜像信息
|
||||
log_info "已拉取的镜像:"
|
||||
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.CreatedAt}}\t{{.Size}}" | head -10
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# 重启指定容器
|
||||
restart_container() {
|
||||
local container_name="$1"
|
||||
|
||||
if [ -z "$container_name" ]; then
|
||||
log_error "未指定容器名称"
|
||||
echo "可用的容器有:"
|
||||
list_containers
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "正在重新构建并重启容器: $container_name"
|
||||
|
||||
# 检查Docker环境
|
||||
check_docker
|
||||
if [ $? -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
check_platform
|
||||
|
||||
# 进入项目根目录再执行docker-compose命令
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
export_frontend_build_args
|
||||
|
||||
# 检查容器是否存在
|
||||
if ! "$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD ps --services | grep -q "^$container_name$"; then
|
||||
log_error "容器 '$container_name' 不存在或未运行"
|
||||
echo "可用的容器有:"
|
||||
list_containers
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 构建并重启容器
|
||||
log_info "正在重新构建容器 '$container_name'..."
|
||||
PLATFORM=$PLATFORM "$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD build "$container_name"
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "容器 '$container_name' 构建失败"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_info "正在重启容器 '$container_name'..."
|
||||
PLATFORM=$PLATFORM "$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD up -d --no-deps "$container_name"
|
||||
if [ $? -ne 0 ]; then
|
||||
log_error "容器 '$container_name' 重启失败"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log_success "容器 '$container_name' 已成功重新构建并重启"
|
||||
return 0
|
||||
}
|
||||
|
||||
# 检查系统环境
|
||||
check_environment() {
|
||||
log_info "开始环境检查..."
|
||||
|
||||
# 检查操作系统
|
||||
OS=$(uname)
|
||||
log_info "操作系统: $OS"
|
||||
|
||||
# 检查Docker
|
||||
check_docker
|
||||
|
||||
# 检查.env文件
|
||||
check_env_file
|
||||
|
||||
get_ollama_base_url
|
||||
|
||||
if [ $IS_REMOTE -eq 1 ]; then
|
||||
log_info "检测到远程Ollama服务配置"
|
||||
if curl -s "$OLLAMA_URL/api/tags" &> /dev/null; then
|
||||
version=$(curl -s "$OLLAMA_URL/api/tags" | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
|
||||
log_success "远程Ollama服务可访问,版本: $version"
|
||||
else
|
||||
log_warning "远程Ollama服务不可访问,请确认服务地址正确且已启动"
|
||||
fi
|
||||
else
|
||||
if command -v ollama &> /dev/null; then
|
||||
log_success "本地Ollama已安装"
|
||||
if curl -s "http://localhost:$OLLAMA_PORT/api/tags" &> /dev/null; then
|
||||
version=$(curl -s "http://localhost:$OLLAMA_PORT/api/tags" | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
|
||||
log_success "本地Ollama服务正在运行,版本: $version"
|
||||
else
|
||||
log_warning "本地Ollama已安装但服务未运行"
|
||||
fi
|
||||
else
|
||||
log_warning "本地Ollama未安装"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 检查沙箱镜像
|
||||
log_info "检查沙箱镜像..."
|
||||
local sandbox_image="wechatopenai/weknora-sandbox:${ACADEMY_VERSION:-latest}"
|
||||
if docker image inspect "$sandbox_image" &> /dev/null; then
|
||||
log_success "沙箱镜像已就绪: $sandbox_image"
|
||||
else
|
||||
log_warning "沙箱镜像未找到: $sandbox_image (Agent Skills 功能需要此镜像)"
|
||||
log_info "可通过以下命令拉取: $0 -p 或 docker pull $sandbox_image"
|
||||
fi
|
||||
|
||||
# 检查磁盘空间
|
||||
log_info "检查磁盘空间..."
|
||||
df -h | grep -E "(Filesystem|/$)"
|
||||
|
||||
# 检查内存
|
||||
log_info "检查内存使用情况..."
|
||||
if [ "$OS" = "Darwin" ]; then
|
||||
vm_stat | perl -ne '/page size of (\d+)/ and $size=$1; /Pages free:\s*(\d+)/ and print "Free Memory: ", $1 * $size / 1048576, " MB\n"'
|
||||
else
|
||||
free -h | grep -E "(total|Mem:)"
|
||||
fi
|
||||
|
||||
# 检查CPU
|
||||
log_info "CPU信息:"
|
||||
if [ "$OS" = "Darwin" ]; then
|
||||
sysctl -n machdep.cpu.brand_string
|
||||
echo "CPU核心数: $(sysctl -n hw.ncpu)"
|
||||
else
|
||||
grep "model name" /proc/cpuinfo | head -1
|
||||
echo "CPU核心数: $(nproc)"
|
||||
fi
|
||||
|
||||
# 检查容器状态
|
||||
log_info "检查容器状态..."
|
||||
if docker info &> /dev/null; then
|
||||
docker ps -a
|
||||
else
|
||||
log_warning "无法获取容器状态,Docker可能未运行"
|
||||
fi
|
||||
|
||||
log_success "环境检查完成"
|
||||
return 0
|
||||
}
|
||||
|
||||
# 解析命令行参数
|
||||
START_OLLAMA=false
|
||||
START_DOCKER=false
|
||||
STOP_SERVICES=false
|
||||
CHECK_ENVIRONMENT=false
|
||||
LIST_CONTAINERS=false
|
||||
RESTART_CONTAINER=false
|
||||
PULL_IMAGES=false
|
||||
NO_PULL=false
|
||||
CONTAINER_NAME=""
|
||||
|
||||
# 没有参数时默认启动所有服务
|
||||
if [ $# -eq 0 ]; then
|
||||
START_OLLAMA=true
|
||||
START_DOCKER=true
|
||||
fi
|
||||
|
||||
while [ "$1" != "" ]; do
|
||||
case $1 in
|
||||
-h | --help ) show_help
|
||||
;;
|
||||
-o | --ollama ) START_OLLAMA=true
|
||||
;;
|
||||
-d | --docker ) START_DOCKER=true
|
||||
;;
|
||||
-a | --all ) START_OLLAMA=true
|
||||
START_DOCKER=true
|
||||
;;
|
||||
-s | --stop ) STOP_SERVICES=true
|
||||
;;
|
||||
-c | --check ) CHECK_ENVIRONMENT=true
|
||||
;;
|
||||
-l | --list ) LIST_CONTAINERS=true
|
||||
;;
|
||||
-p | --pull ) PULL_IMAGES=true
|
||||
;;
|
||||
--no-pull ) NO_PULL=true
|
||||
START_OLLAMA=true
|
||||
START_DOCKER=true
|
||||
;;
|
||||
-r | --restart ) RESTART_CONTAINER=true
|
||||
CONTAINER_NAME="$2"
|
||||
shift
|
||||
;;
|
||||
-v | --version ) show_version
|
||||
;;
|
||||
* ) log_error "未知选项: $1"
|
||||
show_help
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# 执行环境检查
|
||||
if [ "$CHECK_ENVIRONMENT" = true ]; then
|
||||
check_environment
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# 列出所有容器
|
||||
if [ "$LIST_CONTAINERS" = true ]; then
|
||||
list_containers
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# 拉取最新镜像
|
||||
if [ "$PULL_IMAGES" = true ]; then
|
||||
pull_images
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# 重启指定容器
|
||||
if [ "$RESTART_CONTAINER" = true ]; then
|
||||
restart_container "$CONTAINER_NAME"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# 执行服务操作
|
||||
if [ "$STOP_SERVICES" = true ]; then
|
||||
# 停止服务
|
||||
stop_ollama
|
||||
OLLAMA_RESULT=$?
|
||||
|
||||
stop_docker
|
||||
DOCKER_RESULT=$?
|
||||
|
||||
# 显示总结
|
||||
echo ""
|
||||
log_info "=== 停止结果 ==="
|
||||
if [ $OLLAMA_RESULT -eq 0 ]; then
|
||||
log_success "✓ Ollama服务已停止"
|
||||
else
|
||||
log_error "✗ Ollama服务停止失败"
|
||||
fi
|
||||
|
||||
if [ $DOCKER_RESULT -eq 0 ]; then
|
||||
log_success "✓ Docker容器已停止"
|
||||
else
|
||||
log_error "✗ Docker容器停止失败"
|
||||
fi
|
||||
|
||||
log_success "服务停止完成。"
|
||||
else
|
||||
# 启动服务
|
||||
OLLAMA_RESULT=1
|
||||
DOCKER_RESULT=1
|
||||
if [ "$START_OLLAMA" = true ]; then
|
||||
start_ollama
|
||||
OLLAMA_RESULT=$?
|
||||
fi
|
||||
|
||||
if [ "$START_DOCKER" = true ]; then
|
||||
start_docker
|
||||
DOCKER_RESULT=$?
|
||||
fi
|
||||
|
||||
# 显示总结
|
||||
echo ""
|
||||
log_info "=== 启动结果 ==="
|
||||
if [ "$START_OLLAMA" = true ]; then
|
||||
if [ $OLLAMA_RESULT -eq 0 ]; then
|
||||
log_success "✓ Ollama服务已启动"
|
||||
else
|
||||
log_error "✗ Ollama服务启动失败"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$START_DOCKER" = true ]; then
|
||||
if [ $DOCKER_RESULT -eq 0 ]; then
|
||||
log_success "✓ Docker容器已启动"
|
||||
else
|
||||
log_error "✗ Docker容器启动失败"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$START_OLLAMA" = true ] && [ "$START_DOCKER" = true ]; then
|
||||
if [ $OLLAMA_RESULT -eq 0 ] && [ $DOCKER_RESULT -eq 0 ]; then
|
||||
log_success "所有服务启动完成,可通过以下地址访问:"
|
||||
printf "%b\n" "${GREEN} - 前端界面: http://localhost:${FRONTEND_PORT:-80}${NC}"
|
||||
printf "%b\n" "${GREEN} - API接口: http://localhost:${APP_PORT:-8080}${NC}"
|
||||
echo ""
|
||||
log_info "正在持续输出容器日志(按 Ctrl+C 退出日志,容器不会停止)..."
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD logs app docreader postgres --since=10s -f
|
||||
else
|
||||
log_error "部分服务启动失败,请检查日志并修复问题"
|
||||
fi
|
||||
elif [ "$START_OLLAMA" = true ] && [ $OLLAMA_RESULT -eq 0 ]; then
|
||||
log_success "Ollama服务启动完成,可通过以下地址访问:"
|
||||
printf "%b\n" "${GREEN} - Ollama API: http://localhost:$OLLAMA_PORT${NC}"
|
||||
elif [ "$START_DOCKER" = true ] && [ $DOCKER_RESULT -eq 0 ]; then
|
||||
log_success "Docker容器启动完成,可通过以下地址访问:"
|
||||
printf "%b\n" "${GREEN} - 前端界面: http://localhost:${FRONTEND_PORT:-80}${NC}"
|
||||
printf "%b\n" "${GREEN} - API接口: http://localhost:${APP_PORT:-8080}${NC}"
|
||||
echo ""
|
||||
log_info "正在持续输出容器日志(按 Ctrl+C 退出日志,容器不会停止)..."
|
||||
"$DOCKER_COMPOSE_BIN" $DOCKER_COMPOSE_SUBCMD logs app docreader postgres --since=10s -f
|
||||
fi
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# Verify that app checks cover unchanged callers and propagate failures.
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
fixture="$(mktemp -d)"
|
||||
trap 'rm -rf "$fixture"' EXIT
|
||||
mkdir -p "$fixture/scripts/git-hooks" "$fixture/bin"
|
||||
cp "$repo_root/scripts/git-hooks/common.sh" "$fixture/scripts/git-hooks/"
|
||||
export HOOK_TEST_LOG="$fixture/go.log"
|
||||
export LOG_FORMAT="legacy: %msg"
|
||||
export ACADEMY_LOG_FORMAT="developer: %msg"
|
||||
cat > "$fixture/bin/go" <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
printf '%s\n' "$*" >> "$HOOK_TEST_LOG"
|
||||
case "$1" in
|
||||
list)
|
||||
[[ "${HOOK_TEST_FAIL:-}" != list ]] || exit 1
|
||||
printf '%s\n' example/internal/agent/tools example/internal/application/service example/docreader/proto
|
||||
;;
|
||||
vet|test)
|
||||
if [[ "$1" == test && ( -n "${ACADEMY_LOG_FORMAT:-}" || "${ACADEMY_LOG_FORMAT+x}" != x ) ]]; then
|
||||
echo "App tests inherited the developer log template" >&2
|
||||
exit 1
|
||||
fi
|
||||
[[ "${HOOK_TEST_FAIL:-}" != "$1" ]] || exit 1
|
||||
;;
|
||||
*) echo "Unexpected go invocation: $*" >&2; exit 1 ;;
|
||||
esac
|
||||
EOF
|
||||
chmod +x "$fixture/bin/go"
|
||||
export PATH="$fixture/bin:$PATH"
|
||||
unset HOOK_SKIP_TEST HOOK_TEST_FAIL
|
||||
|
||||
run_checks() {
|
||||
bash -c 'source "$1"; run_app_vet_test' bash "$fixture/scripts/git-hooks/common.sh"
|
||||
}
|
||||
|
||||
run_checks
|
||||
cat > "$fixture/expected.log" <<'EOF'
|
||||
list ./...
|
||||
vet example/internal/agent/tools example/internal/application/service
|
||||
test -count=1 example/internal/agent/tools example/internal/application/service
|
||||
EOF
|
||||
diff -u "$fixture/expected.log" "$HOOK_TEST_LOG"
|
||||
|
||||
# Keep the explicit local opt-out, but it must not skip vet.
|
||||
: > "$HOOK_TEST_LOG"
|
||||
HOOK_SKIP_TEST=1 run_checks
|
||||
head -n 2 "$fixture/expected.log" > "$fixture/skip.log"
|
||||
diff -u "$fixture/skip.log" "$HOOK_TEST_LOG"
|
||||
|
||||
for phase in list vet test; do
|
||||
: > "$HOOK_TEST_LOG"
|
||||
if HOOK_TEST_FAIL="$phase" run_checks > "$fixture/failure.log" 2>&1; then
|
||||
echo "App checks accepted a failing go $phase" >&2
|
||||
exit 1
|
||||
fi
|
||||
case "$phase" in
|
||||
list) head -n 1 "$fixture/expected.log" ;;
|
||||
vet) head -n 2 "$fixture/expected.log" ;;
|
||||
test) cat "$fixture/expected.log" ;;
|
||||
esac > "$fixture/failure-expected.log"
|
||||
diff -u "$fixture/failure-expected.log" "$HOOK_TEST_LOG"
|
||||
done
|
||||
|
||||
echo 'Git hook coverage checks passed'
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
#
|
||||
# 本地测试 Homebrew Formula
|
||||
#
|
||||
# 流程:打包 → 创建本地 tap → 写入 Formula → brew install → 验证
|
||||
#
|
||||
# 用法:
|
||||
# ./scripts/test-homebrew.sh # 完整测试(含前端构建)
|
||||
# SKIP_FRONTEND=1 ./scripts/test-homebrew.sh # 跳过前端构建
|
||||
# SKIP_BUILD=1 ./scripts/test-homebrew.sh # 跳过构建(使用已有 tarball)
|
||||
#
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
cd "${ROOT_DIR}"
|
||||
|
||||
TAP_NAME="academy/test"
|
||||
FORMULA_NAME="academy-lite-test"
|
||||
VERSION="test"
|
||||
GOOS=$(go env GOOS)
|
||||
GOARCH=$(go env GOARCH)
|
||||
ARCHIVE="Academy-lite_${VERSION}_${GOOS}_${GOARCH}"
|
||||
TARBALL="${ROOT_DIR}/dist/${ARCHIVE}.tar.gz"
|
||||
|
||||
# ── Step 1: Build package ──
|
||||
if [ "${SKIP_BUILD:-}" != "1" ]; then
|
||||
echo "=== Step 1: Build local package ==="
|
||||
SKIP_FRONTEND="${SKIP_FRONTEND:-0}" ./scripts/package-lite.sh "${VERSION}"
|
||||
else
|
||||
echo "=== Step 1: Skipped (SKIP_BUILD=1) ==="
|
||||
fi
|
||||
|
||||
if [ ! -f "${TARBALL}" ]; then
|
||||
echo "Error: tarball not found at ${TARBALL}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SHA=$(shasum -a 256 "${TARBALL}" | awk '{print $1}')
|
||||
echo ""
|
||||
echo " Tarball: ${TARBALL}"
|
||||
echo " SHA256: ${SHA}"
|
||||
|
||||
# ── Step 2: Create local tap ──
|
||||
echo ""
|
||||
echo "=== Step 2: Set up local tap ==="
|
||||
|
||||
# Create tap if it doesn't exist
|
||||
TAP_DIR="$(brew --repository)/Library/Taps/academy/homebrew-test"
|
||||
if [ ! -d "${TAP_DIR}" ]; then
|
||||
mkdir -p "${TAP_DIR}/Formula"
|
||||
(cd "${TAP_DIR}" && git init -q && git commit --allow-empty -m "init" -q)
|
||||
echo " Created tap: ${TAP_NAME}"
|
||||
else
|
||||
echo " Tap already exists: ${TAP_NAME}"
|
||||
fi
|
||||
|
||||
# ── Step 3: Write Formula into tap ──
|
||||
echo ""
|
||||
echo "=== Step 3: Generate Formula ==="
|
||||
|
||||
cat > "${TAP_DIR}/Formula/${FORMULA_NAME}.rb" << RUBY
|
||||
class AcademyLiteTest < Formula
|
||||
desc "Academy Lite (local test)"
|
||||
homepage "https://github.com/Tencent/WeKnora"
|
||||
version "${VERSION}"
|
||||
license "Apache-2.0"
|
||||
|
||||
url "file://${TARBALL}"
|
||||
sha256 "${SHA}"
|
||||
|
||||
def install
|
||||
libexec.install "Academy-lite"
|
||||
pkgshare.install "web" if File.directory?("web")
|
||||
pkgshare.install "config" if File.directory?("config")
|
||||
pkgshare.install ".env.lite.example"
|
||||
if File.directory?("migrations")
|
||||
pkgshare.install "migrations"
|
||||
end
|
||||
|
||||
(bin/"academy-lite-test").write <<~SH
|
||||
#!/bin/bash
|
||||
CONFIG_DIR="\\\${ACADEMY_CONFIG_DIR:-\\\${XDG_CONFIG_HOME:-\\\$HOME/.config}/academy-test}"
|
||||
DATA_DIR="\\\${ACADEMY_DATA_DIR:-\\\${XDG_DATA_HOME:-\\\$HOME/.local/share}/academy-test}"
|
||||
|
||||
mkdir -p "\\\$DATA_DIR/files" "\\\$CONFIG_DIR/config" 2>/dev/null
|
||||
|
||||
if [ ! -f "\\\$CONFIG_DIR/config/config.yaml" ]; then
|
||||
cp -r "#{pkgshare}/config/" "\\\$CONFIG_DIR/config/"
|
||||
fi
|
||||
|
||||
if [ ! -d "\\\$CONFIG_DIR/migrations" ] && [ -d "#{pkgshare}/migrations" ]; then
|
||||
ln -sf "#{pkgshare}/migrations" "\\\$CONFIG_DIR/migrations"
|
||||
fi
|
||||
|
||||
if [ ! -f "\\\$CONFIG_DIR/.env.lite" ]; then
|
||||
cp "#{pkgshare}/.env.lite.example" "\\\$CONFIG_DIR/.env.lite"
|
||||
sed -i'' -e "s|DB_PATH=.*|DB_PATH=\\\$DATA_DIR/academy.db|" "\\\$CONFIG_DIR/.env.lite"
|
||||
sed -i'' -e "s|LOCAL_STORAGE_BASE_DIR=.*|LOCAL_STORAGE_BASE_DIR=\\\$DATA_DIR/files|" "\\\$CONFIG_DIR/.env.lite"
|
||||
echo ""
|
||||
echo "已创建配置文件: \\\$CONFIG_DIR/.env.lite"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
set -a
|
||||
source "\\\$CONFIG_DIR/.env.lite"
|
||||
set +a
|
||||
|
||||
export DB_PATH="\\\${DB_PATH:-\\\$DATA_DIR/academy.db}"
|
||||
export LOCAL_STORAGE_BASE_DIR="\\\${LOCAL_STORAGE_BASE_DIR:-\\\$DATA_DIR/files}"
|
||||
export ACADEMY_WEB_DIR="\\\${ACADEMY_WEB_DIR:-#{pkgshare}/web}"
|
||||
|
||||
cd "\\\$CONFIG_DIR"
|
||||
exec "#{libexec}/Academy-lite" "\\\$@"
|
||||
SH
|
||||
end
|
||||
|
||||
def post_install
|
||||
(var/"academy-test").mkpath
|
||||
(var/"log").mkpath
|
||||
end
|
||||
|
||||
service do
|
||||
run [bin/"academy-lite-test"]
|
||||
keep_alive true
|
||||
working_dir var/"academy-test"
|
||||
log_path var/"log/academy-lite-test.log"
|
||||
error_log_path var/"log/academy-lite-test.log"
|
||||
end
|
||||
|
||||
test do
|
||||
assert_predicate bin/"academy-lite-test", :executable?
|
||||
end
|
||||
end
|
||||
RUBY
|
||||
|
||||
(cd "${TAP_DIR}" && git add -A && git commit -m "update formula" -q --allow-empty)
|
||||
echo " Formula written to: ${TAP_DIR}/Formula/${FORMULA_NAME}.rb"
|
||||
|
||||
# ── Step 4: Install ──
|
||||
echo ""
|
||||
echo "=== Step 4: Install ==="
|
||||
brew reinstall "${TAP_NAME}/${FORMULA_NAME}" 2>&1 || brew install "${TAP_NAME}/${FORMULA_NAME}"
|
||||
|
||||
# ── Step 5: Verify ──
|
||||
echo ""
|
||||
echo "=== Step 5: Verify ==="
|
||||
echo ""
|
||||
echo " which:"
|
||||
which academy-lite-test || true
|
||||
echo ""
|
||||
echo " Installed files:"
|
||||
brew list "${TAP_NAME}/${FORMULA_NAME}"
|
||||
echo ""
|
||||
echo " Test paths (isolated from production):"
|
||||
echo " Config: ~/.config/academy-test/.env.lite"
|
||||
echo " Data: ~/.local/share/academy-test/"
|
||||
|
||||
echo ""
|
||||
echo "=== Done ==="
|
||||
echo ""
|
||||
echo "前台运行:"
|
||||
echo " academy-lite-test"
|
||||
echo ""
|
||||
echo "后台服务:"
|
||||
echo " brew services start ${TAP_NAME}/${FORMULA_NAME}"
|
||||
echo " brew services info ${TAP_NAME}/${FORMULA_NAME}"
|
||||
echo " brew services stop ${TAP_NAME}/${FORMULA_NAME}"
|
||||
echo ""
|
||||
echo "日志:"
|
||||
echo " $(brew --prefix)/var/log/academy-lite-test.log"
|
||||
echo ""
|
||||
echo "卸载测试:"
|
||||
echo " brew services stop ${FORMULA_NAME} 2>/dev/null"
|
||||
echo " brew uninstall ${FORMULA_NAME}"
|
||||
echo " brew untap ${TAP_NAME}"
|
||||
echo " rm -rf ~/.config/academy-test ~/.local/share/academy-test"
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env bash
|
||||
# Exercise packaging without network access or a populated developer module cache.
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
fixture="$(mktemp -d)"
|
||||
trap 'rm -rf "${fixture}"' EXIT
|
||||
mkdir -p "${fixture}/scripts" "${fixture}/bin" "${fixture}/licenses/sources"
|
||||
cp "${repo_root}/scripts/"{check-license-bundle,copy-licenses}.sh "${fixture}/scripts/"
|
||||
cp "${repo_root}/LICENSE" "${repo_root}/THIRD_PARTY_NOTICES.md" "${fixture}/"
|
||||
cp "${repo_root}/licenses/"*.txt "${fixture}/licenses/"
|
||||
touch "${fixture}/go.sum"
|
||||
|
||||
checksum() {
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
sha256sum "$1" | awk '{print $1}'
|
||||
else
|
||||
shasum -a 256 "$1" | awk '{print $1}'
|
||||
fi
|
||||
}
|
||||
|
||||
# Supply two deterministic stand-ins for downloaded archives. This test verifies
|
||||
# the packager's integrity gate, not Go's module download implementation.
|
||||
export LICENSE_TEST_CACHE="${fixture}/module cache"
|
||||
for pin in 'github.com/go-sql-driver/mysql v1.10.0' 'github.com/shoenig/go-m1cpu v0.1.6'; do
|
||||
read -r module version <<< "${pin}"
|
||||
cache_dir="${LICENSE_TEST_CACHE}/cache/download/${module}/@v"
|
||||
mkdir -p "${cache_dir}"
|
||||
printf 'source for %s\n' "${pin}" > "${cache_dir}/${version}.zip"
|
||||
printf '%s %s %s\n' "${module}" "${version}" "$(checksum "${cache_dir}/${version}.zip")" \
|
||||
>> "${fixture}/licenses/sources/modules.tsv"
|
||||
printf '%s\n' "${pin}" >> "${fixture}/go.mod"
|
||||
done
|
||||
cat > "${fixture}/bin/go" <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
case "$*" in
|
||||
'env GOMODCACHE') printf '%s\n' "${LICENSE_TEST_CACHE}" ;;
|
||||
'mod download '*) exit "${LICENSE_TEST_DOWNLOAD_FAILURE:-0}" ;;
|
||||
*) echo "Unexpected go invocation: $*" >&2; exit 1 ;;
|
||||
esac
|
||||
EOF
|
||||
chmod +x "${fixture}/bin/go"
|
||||
export PATH="${fixture}/bin:${PATH}"
|
||||
|
||||
bash "${fixture}/scripts/check-license-bundle.sh"
|
||||
bash "${fixture}/scripts/copy-licenses.sh" "${fixture}/release with spaces"
|
||||
for pin in 'mysql v1.10.0' 'go-m1cpu v0.1.6'; do
|
||||
read -r name version <<< "${pin}"
|
||||
test -s "${fixture}/release with spaces/licenses/sources/${name}-${version}.zip"
|
||||
done
|
||||
cmp "${fixture}/LICENSE" "${fixture}/release with spaces/LICENSE"
|
||||
cmp "${fixture}/THIRD_PARTY_NOTICES.md" "${fixture}/release with spaces/THIRD_PARTY_NOTICES.md"
|
||||
bash "${fixture}/scripts/check-license-bundle.sh" "${fixture}/release with spaces/licenses/sources"
|
||||
|
||||
if LICENSE_TEST_DOWNLOAD_FAILURE=1 bash "${fixture}/scripts/copy-licenses.sh" "${fixture}/failed download"; then
|
||||
echo 'Packaging accepted a failed source download' >&2; exit 1
|
||||
fi
|
||||
test ! -e "${fixture}/failed download"
|
||||
|
||||
printf 'tampered source\n' > "${LICENSE_TEST_CACHE}/cache/download/github.com/go-sql-driver/mysql/@v/v1.10.0.zip"
|
||||
if bash "${fixture}/scripts/copy-licenses.sh" "${fixture}/corrupt release" > "${fixture}/corrupt.log" 2>&1; then
|
||||
echo 'Packaging accepted a mismatched source checksum' >&2; exit 1
|
||||
fi
|
||||
test ! -e "${fixture}/corrupt release"
|
||||
|
||||
printf 'github.com/go-sql-driver/mysql v0.0.0\n' > "${fixture}/go.mod"
|
||||
if bash "${fixture}/scripts/check-license-bundle.sh" > "${fixture}/version.log" 2>&1; then
|
||||
echo 'Notice validation accepted a stale module version' >&2; exit 1
|
||||
fi
|
||||
echo 'License bundle packaging tests passed'
|
||||
@@ -0,0 +1,196 @@
|
||||
// Isolated real-extension test host. The parent sends a pairing link over stdin,
|
||||
// never arguments or logs. Requires a test Chromium and playwright-core.
|
||||
import { createInterface } from 'node:readline';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const lines = createInterface({ input: process.stdin });
|
||||
const first = await new Promise(resolve => lines.once('line', resolve));
|
||||
const { pairing, extension, chromium: executablePath, playwright, fixture } = JSON.parse(first);
|
||||
const { chromium } = await import(pathToFileURL(playwright).href);
|
||||
const profile = await mkdtemp('/tmp/wkb-chrome-');
|
||||
let browser;
|
||||
let closing = false;
|
||||
async function close() {
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
await browser?.close();
|
||||
await rm(profile, { recursive: true, force: true });
|
||||
lines.close();
|
||||
}
|
||||
process.on('SIGTERM', () => void close().finally(() => process.exit(0)));
|
||||
try {
|
||||
browser = await chromium.launchPersistentContext(profile, {
|
||||
executablePath, headless: process.env.BROWSERSKILL_TEST_HEADED !== '1',
|
||||
args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`],
|
||||
});
|
||||
const worker = browser.serviceWorkers()[0] ?? await browser.waitForEvent('serviceworker');
|
||||
const popup = await browser.newPage();
|
||||
await popup.goto(new URL('popup.html', worker.url()).href);
|
||||
await popup.locator('details summary').click();
|
||||
// The extension popup unifies local/remote connection settings.
|
||||
await popup.locator('[role="group"] button').nth(1).click();
|
||||
await popup.locator('#remote-pairing').fill(pairing);
|
||||
await popup.locator('form button[type="submit"]').click();
|
||||
await popup.waitForFunction(() => document.querySelector('#remote-pairing')?.value === '' || document.querySelector('form [role=alert]'));
|
||||
if (await popup.locator('form [role=alert]').count()) throw new Error('Extension authorization failed before browser tests');
|
||||
// Official borrow confirmation needs an injectable page in a normal user
|
||||
// window. Extension settings and an isolated popup cannot host that prompt.
|
||||
const confirmationPage = await browser.newPage();
|
||||
await confirmationPage.goto(fixture);
|
||||
await confirmationPage.locator('browser-skill-overlay').waitFor({state:'attached'});
|
||||
const initial = await worker.evaluate(async () => {
|
||||
const window = await chrome.windows.getLastFocused();
|
||||
const tabs = await chrome.tabs.query({windowId:window.id,active:true});
|
||||
return {windowId:window.id,tabId:tabs[0].id,tabIds:(await chrome.tabs.query({})).map(t=>t.id)};
|
||||
});
|
||||
const originalWindow = { windowId: initial.windowId, tabId: initial.tabId };
|
||||
const preservedTabs = new Set();
|
||||
let beforeReturn;
|
||||
process.stdout.write('ready\n');
|
||||
for await (const command of lines) {
|
||||
if (command === 'close') break;
|
||||
if (command === 'complete-login' || command === 'interrupt-window' || command === 'approve-borrow') {
|
||||
const selector = command === 'complete-login'
|
||||
? '[data-slot="help-request-banner"][data-display-mode="full"] [data-slot="help-continue-button"]'
|
||||
: command === 'approve-borrow' ? '[data-slot="borrow-confirmation-allow-button"]'
|
||||
: '[data-slot="control-overlay-stop-all"]';
|
||||
// Click the actual extension overlay in an isolated fixture browser.
|
||||
let clicked = false;
|
||||
const deadline = Date.now() + 5000;
|
||||
while (!clicked && Date.now() < deadline) {
|
||||
for (const page of browser.pages().filter(page => page !== popup).reverse()) {
|
||||
const button = command === 'complete-login'
|
||||
? page.locator('[data-slot="help-request-banner"][data-display-mode="full"]')
|
||||
.filter({hasText:'Confirm this fixture step'}).locator('[data-slot="help-continue-button"]').first()
|
||||
: page.locator(selector).first();
|
||||
if (!await button.isVisible()) continue;
|
||||
if (command === 'complete-login') {
|
||||
// Only synthetic fixture credentials, entered through the page UI.
|
||||
await page.locator('#login-account').fill('fixture-user');
|
||||
await page.locator('#login-password').fill('fixture-password');
|
||||
await page.locator('#login-submit').click();
|
||||
await page.waitForURL('**/login-complete');
|
||||
await button.waitFor({state:'visible',timeout:5000});
|
||||
}
|
||||
await button.click({timeout:5000});
|
||||
clicked = true;
|
||||
break;
|
||||
}
|
||||
if (!clicked) await new Promise(resolve => setTimeout(resolve, 50));
|
||||
}
|
||||
if (!clicked) throw new Error('Browser task overlay was not clickable');
|
||||
process.stdout.write(command+'-done\n');
|
||||
}
|
||||
if (command === 'check-detached') {
|
||||
// getTargets().attached includes Playwright's own debugger. Probe only
|
||||
// this extension's attachment without attaching or changing the page.
|
||||
const attached = await worker.evaluate(async () => {
|
||||
const tabs = await chrome.tabs.query({});
|
||||
const used = [];
|
||||
for (const tab of tabs) {
|
||||
try {
|
||||
await chrome.debugger.sendCommand({tabId:tab.id}, 'Runtime.evaluate', {expression:'0', returnByValue:true});
|
||||
used.push(tab.id);
|
||||
} catch (error) {
|
||||
if (!/not attached|No tab|No target|Cannot access a chrome:\/\/ URL/i.test(String(error))) throw error;
|
||||
}
|
||||
}
|
||||
return used;
|
||||
});
|
||||
process.stdout.write(JSON.stringify({detached:attached.length===0})+'\n');
|
||||
}
|
||||
if (command === 'check-cleanup') {
|
||||
const state = await worker.evaluate(async () => ({ids:(await chrome.tabs.query({})).map(t=>t.id)}));
|
||||
const expected = new Set([...initial.tabIds, ...preservedTabs]);
|
||||
const missing = [...expected].filter(id => !state.ids.includes(id));
|
||||
const unexpected = state.ids.filter(id => !expected.has(id));
|
||||
const cleaned = missing.length === 0 && unexpected.length === 0;
|
||||
process.stdout.write(JSON.stringify(cleaned ? {cleaned} : {cleaned, missing, unexpected})+'\n');
|
||||
}
|
||||
if (command.startsWith('before-tab-return ')) {
|
||||
const id = Number(command.split(' ')[1]);
|
||||
beforeReturn = await worker.evaluate(async (tabId) => ({
|
||||
tabId, tabs: await chrome.tabs.query({}), windows: await chrome.windows.getAll({}),
|
||||
}), id);
|
||||
process.stdout.write('return-recorded\n');
|
||||
}
|
||||
if (command.startsWith('expect-returned-tab ')) {
|
||||
// Admit only the returned page and the official fallback window's new-tab
|
||||
// placeholder. Never allow arbitrary extra tabs to hide task cleanup leaks.
|
||||
const returned = JSON.parse(command.slice('expect-returned-tab '.length));
|
||||
if (!beforeReturn || beforeReturn.tabId !== returned.tab_id) throw new Error('Missing return snapshot');
|
||||
const tabs = await worker.evaluate(async () => chrome.tabs.query({}));
|
||||
const target = tabs.find(tab => tab.id === returned.tab_id);
|
||||
if (!target || target.windowId !== returned.returned_to_window_id) throw new Error('Returned tab missing or misplaced');
|
||||
const added = tabs.filter(tab => !beforeReturn.tabs.some(previous => previous.id === tab.id));
|
||||
const newWindow = !beforeReturn.windows.some(window => window.id === target.windowId);
|
||||
if (added.length > 1 || added.some(tab => !returned.fallback || !newWindow ||
|
||||
tab.windowId !== target.windowId || (tab.pendingUrl ?? tab.url) !== 'chrome://newtab/')) {
|
||||
throw new Error('Unexpected tabs created during tab_return');
|
||||
}
|
||||
preservedTabs.add(target.id);
|
||||
for (const tab of added) preservedTabs.add(tab.id);
|
||||
beforeReturn = undefined;
|
||||
process.stdout.write('returned-tab-preserved\n');
|
||||
}
|
||||
if (command === 'remember-foreground') {
|
||||
const foreground = await worker.evaluate(async () => {
|
||||
const window = await chrome.windows.getLastFocused();
|
||||
const [tab] = await chrome.tabs.query({windowId:window.id,active:true});
|
||||
return {windowId:window.id,tabId:tab.id};
|
||||
});
|
||||
Object.assign(initial, foreground);
|
||||
process.stdout.write('remembered\n');
|
||||
}
|
||||
if (command === 'create-unowned-tab') {
|
||||
const createdPage = browser.waitForEvent('page', {predicate:p => p !== popup});
|
||||
const tab = await worker.evaluate(async (initialIds) => {
|
||||
const source = (await chrome.tabs.query({})).find(t => !initialIds.includes(t.id) && t.url?.startsWith('http://127.0.0.1:'));
|
||||
if (!source) throw new Error('Fixture task page unavailable');
|
||||
// Extension API creation simulates a user-created tab: no navigation
|
||||
// source event, even though it is inside the Agent Window.
|
||||
return chrome.tabs.create({windowId:source.windowId,url:source.url+'?user-tab=1',active:true});
|
||||
}, [...initial.tabIds, ...preservedTabs]);
|
||||
const page = await createdPage;
|
||||
await page.waitForURL('**/*?user-tab=1');
|
||||
await page.locator('browser-skill-overlay').waitFor({state:'attached'});
|
||||
process.stdout.write(JSON.stringify({tab_id:tab.id})+'\n');
|
||||
}
|
||||
if (command.startsWith('close-fixture-window ')) {
|
||||
const id = Number(command.split(' ')[1]);
|
||||
await worker.evaluate(async (tabId) => {
|
||||
const tab = await chrome.tabs.get(tabId);
|
||||
await chrome.windows.remove(tab.windowId);
|
||||
}, id);
|
||||
process.stdout.write('fixture-window-closed\n');
|
||||
}
|
||||
if (command.startsWith('move-fixture-tab-out ')) {
|
||||
// Upstream refuses to borrow an unowned tab that already lives in the
|
||||
// Agent Window; the user must move it to a regular window first.
|
||||
const id = Number(command.split(' ')[1]);
|
||||
await worker.evaluate(async ({tabId, windowId}) => {
|
||||
await chrome.tabs.move(tabId, {windowId, index:-1});
|
||||
}, {tabId:id, windowId:originalWindow.windowId});
|
||||
process.stdout.write('fixture-tab-moved\n');
|
||||
}
|
||||
if (command.startsWith('remove-fixture-tab ')) {
|
||||
const id = Number(command.split(' ')[1]);
|
||||
await worker.evaluate(async (tabId) => chrome.tabs.remove(tabId), id);
|
||||
preservedTabs.delete(id);
|
||||
process.stdout.write('fixture-tab-removed\n');
|
||||
}
|
||||
if (command === 'check-background') {
|
||||
const valid = await worker.evaluate(async (original) => {
|
||||
const tabs = await chrome.tabs.query({});
|
||||
const taskWindows = [...new Set(tabs.filter(t => t.windowId !== original.windowId).map(t => t.windowId))];
|
||||
return tabs.find(t => t.id === original.tabId)?.active === true &&
|
||||
taskWindows.length > 0 && taskWindows.every(id =>
|
||||
tabs.filter(t => t.windowId === id && t.active).length === 1);
|
||||
}, originalWindow);
|
||||
process.stdout.write(JSON.stringify({background:valid})+'\n');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise production embed and MCP Nginx locations with backend fixtures.
|
||||
|
||||
Requires Docker. Run: python3 scripts/test_embed_nginx.py [nginx-or-ui-image]
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
IMAGE = sys.argv[1] if len(sys.argv) > 1 else "nginx:alpine"
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(["docker", *args], text=True).strip()
|
||||
|
||||
|
||||
def check():
|
||||
with tempfile.TemporaryDirectory(prefix="academy-embed-nginx-") as folder:
|
||||
work = Path(folder)
|
||||
(work / "web").mkdir()
|
||||
(work / "web/embed.html").write_text("embed entry")
|
||||
(work / "web/index.html").write_text("main SPA")
|
||||
(work / "web/50x.html").write_text("backend unavailable")
|
||||
config = (ROOT / "frontend/nginx.conf").read_text()
|
||||
for key, value in {
|
||||
"APP_SCHEME": "http", "APP_HOST": "127.0.0.1", "APP_PORT": "18081",
|
||||
"MAX_FILE_SIZE": "50m", "MAX_SKILL_BUNDLE_SIZE": "100m",
|
||||
}.items():
|
||||
config = config.replace("${" + key + "}", value)
|
||||
config = config.replace("/usr/share/nginx/html", "/check/web")
|
||||
config = config.replace("/etc/nginx/api-proxy.conf", "/check/api-proxy.conf")
|
||||
(work / "api-proxy.conf").write_text((ROOT / "frontend/nginx-api-proxy.conf").read_text())
|
||||
# The real policy handler and token middleware are covered by Go tests.
|
||||
# Here vary its responses to verify subrequests, fallback and fail-closed serving.
|
||||
fixture = """
|
||||
server {
|
||||
listen 18081;
|
||||
location = /api/v1/embed-frame-policy {
|
||||
set $policy "frame-ancestors 'none'";
|
||||
if ($http_x_embed_page_uri ~ "^/embed/active(?:[?]|$)") {
|
||||
set $policy "frame-ancestors 'self' https://a.example";
|
||||
}
|
||||
add_header Content-Security-Policy $policy always;
|
||||
if ($http_x_embed_page_uri = "/embed/unavailable") { return 500; }
|
||||
if ($policy = "frame-ancestors 'none'") { return 403; }
|
||||
return 204;
|
||||
}
|
||||
location /api/ { return 200 "$http_host"; }
|
||||
location /mcp/ {
|
||||
default_type application/json;
|
||||
if ($http_authorization != "Bearer test-token") { return 401; }
|
||||
add_header Mcp-Session-Id "test-session";
|
||||
return 200 '{"method":"$request_method","path":"$request_uri","host":"$http_host","session":"$http_mcp_session_id","protocol":"$http_mcp_protocol_version"}';
|
||||
}
|
||||
location = /mcp/stream {
|
||||
default_type text/event-stream;
|
||||
return 200 "event: message\\ndata: test-event\\n\\n";
|
||||
}
|
||||
}
|
||||
"""
|
||||
(work / "nginx.conf").write_text(
|
||||
"events {}\nhttp {\n" + (ROOT / "frontend/nginx-http.conf").read_text() + config + fixture + "\n}"
|
||||
)
|
||||
# The Nginx worker runs as an unprivileged user in the container.
|
||||
work.chmod(0o755)
|
||||
cid = docker("create", "-p", "127.0.0.1::80",
|
||||
"--entrypoint", "nginx", IMAGE, "-c", "/check/nginx.conf", "-g", "daemon off;")
|
||||
try:
|
||||
docker("cp", str(work), cid + ":/check")
|
||||
docker("start", cid)
|
||||
info = json.loads(docker("inspect", cid))[0]
|
||||
port = info["NetworkSettings"]["Ports"]["80/tcp"][0]["HostPort"]
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
|
||||
def request(path, method="GET", headers=None):
|
||||
req = urllib.request.Request(base + path, method=method, headers=headers or {})
|
||||
try:
|
||||
return urllib.request.urlopen(req, timeout=3)
|
||||
except urllib.error.HTTPError as error:
|
||||
return error
|
||||
|
||||
for attempt in range(30):
|
||||
try:
|
||||
with request("/") as response:
|
||||
assert response.status == 200
|
||||
break
|
||||
except (urllib.error.URLError, ConnectionError):
|
||||
if attempt == 29:
|
||||
raise
|
||||
time.sleep(0.1)
|
||||
for method in ("GET", "HEAD"):
|
||||
for path in ("/embed/active", "/embed/active?token=ignored"):
|
||||
with request(path, method) as response:
|
||||
assert response.status == 200, (path, response.status)
|
||||
assert response.headers["Content-Security-Policy"] == "frame-ancestors 'self' https://a.example"
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
assert "X-Frame-Options" not in response.headers
|
||||
assert response.read() == (b"embed entry" if method == "GET" else b"")
|
||||
for path, status in (("/embed/disabled", 403), ("/embed/empty", 403),
|
||||
("/embed/unavailable", 500), ("/_embed-frame-policy", 404),
|
||||
("/embed.html", 404)):
|
||||
with request(path) as response:
|
||||
assert response.status == status, (path, response.status)
|
||||
assert b"embed entry" not in response.read()
|
||||
with request("/api/probe") as response:
|
||||
assert response.read().decode() == f"127.0.0.1:{port}", "proxy lost public port"
|
||||
for method in ("POST", "GET", "DELETE"):
|
||||
with request("/mcp/test-endpoint?probe=1", method, {
|
||||
"Authorization": "Bearer test-token",
|
||||
"Mcp-Session-Id": "test-session",
|
||||
"MCP-Protocol-Version": "2025-03-26",
|
||||
}) as response:
|
||||
assert response.status == 200, (method, response.status)
|
||||
assert response.headers["Mcp-Session-Id"] == "test-session"
|
||||
assert json.load(response) == {
|
||||
"method": method, "path": "/mcp/test-endpoint?probe=1",
|
||||
"host": f"127.0.0.1:{port}", "session": "test-session",
|
||||
"protocol": "2025-03-26",
|
||||
}
|
||||
with request("/mcp/test-endpoint") as response:
|
||||
assert response.status == 401, response.status
|
||||
with request("/mcp/stream") as response:
|
||||
assert response.headers["Content-Type"] == "text/event-stream"
|
||||
assert response.read() == b"event: message\ndata: test-event\n\n"
|
||||
print("Embed and MCP Nginx integration checks passed")
|
||||
except Exception:
|
||||
print(docker("logs", cid), file=sys.stderr)
|
||||
raise
|
||||
finally:
|
||||
docker("rm", "-f", cid)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check()
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Verify a ParadeDB patch upgrade using disposable Docker volumes and real migrations.
|
||||
|
||||
Requires Python 3 and Docker; no database credentials or running Academy needed.
|
||||
Run: python3 scripts/test_paradedb_upgrade.py [--to 0.25.11|0.22.6]
|
||||
Artifacts (snapshots, plans, logs and a synthetic-data backup) are kept in /tmp.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import pathlib
|
||||
import random
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
OUT = None
|
||||
CONTAINER = 'academy-pdb-upgrade-' + uuid.uuid4().hex[:12]
|
||||
# target pg_search version -> (image, expected vector version or None if unchanged)
|
||||
TARGETS = {
|
||||
'0.22.6': ('paradedb/paradedb:v0.22.6-pg17', None),
|
||||
'0.25.11': ('paradedb/paradedb:v0.25.11-pg17', '0.8.4'),
|
||||
}
|
||||
UPGRADES = ['000099_pg_search_0226.up.sql', '000115_pg_search_02511.up.sql']
|
||||
|
||||
def sql(query, db='academy'):
|
||||
p = subprocess.run(['docker', 'exec', '-i', CONTAINER, 'psql', '-X', '-qAt', '-U', 'postgres', '-d', db, '-v', 'ON_ERROR_STOP=1'], input=query, text=True, capture_output=True)
|
||||
if p.returncode:
|
||||
raise RuntimeError(p.stderr)
|
||||
return p.stdout.strip()
|
||||
|
||||
def quote(s):
|
||||
return "'" + s.replace("'", "''") + "'"
|
||||
|
||||
def seed():
|
||||
rng = random.Random(221226)
|
||||
topics = ['数据库 向量 检索 PostgreSQL database search', '知识库 文档 问答 人工智能 retrieval', '北京 上海 深圳 中国 城市', 'Docker 安装 部署 CPU AVX2', '备份 恢复 升级 数据完整性', '权限 租户 共享 用户 authentication']
|
||||
stmts = ['BEGIN;', 'TRUNCATE embeddings, tenants, sessions, messages, models, knowledge_bases, knowledges, chunks RESTART IDENTITY CASCADE;']
|
||||
queries = {}
|
||||
for dim in (798, 1024, 3584):
|
||||
for n in range(240):
|
||||
vector = '[' + ','.join(f'{rng.uniform(-1, 1):.5f}' for _ in range(dim)) + ']'
|
||||
if n in (1, 71, 139):
|
||||
queries[f'{dim}_{n}'] = vector
|
||||
# Vary term frequency/length; cover NULL, disabled, tags, KB and document filters.
|
||||
content = ' '.join([topics[n % 6]] * (1 + n % 7)) + ' ' + ' '.join(rng.choices(topics, k=n % 5))
|
||||
enabled = 'NULL' if n % 13 == 0 else ('false' if n % 11 == 0 else 'true')
|
||||
stmts.append(f"INSERT INTO embeddings(source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, tag_id, content, dimension, embedding, is_enabled) VALUES ('src-{dim}-{n}',{n % 3},'chunk-{dim}-{n}','doc-{n % 9}','kb-{n % 3}',{quote('tag-'+str(n % 4)) if n % 7 else 'NULL'},{quote(content)},{dim},{quote(vector)},{enabled});")
|
||||
stmts += [
|
||||
"INSERT INTO tenants(id,name,description,business) VALUES (10101,'升级验证','中文与 emoji 🧪','test');",
|
||||
"INSERT INTO sessions(id,tenant_id,title) VALUES ('upgrade-session',10101,'升级前会话');",
|
||||
"INSERT INTO messages(id,request_id,session_id,role,content,knowledge_references) VALUES ('upgrade-message','upgrade-request','upgrade-session','assistant','原始回答:数据库检索 🧪','[{\"id\":\"source\",\"score\":0.875}]');",
|
||||
"INSERT INTO models(id,tenant_id,name,type,source,parameters) VALUES ('upgrade-model',10101,'fixture','Embedding','remote','{\"dimension\":1024}');",
|
||||
"INSERT INTO knowledge_bases(id,tenant_id,name,embedding_model_id,summary_model_id) VALUES ('kb-0',10101,'验证知识库','upgrade-model','');",
|
||||
"INSERT INTO knowledges(id,tenant_id,knowledge_base_id,type,title,source,metadata) VALUES ('doc-0',10101,'kb-0','file','中文文档','upload','{\"nested\":{\"value\":42}}');",
|
||||
"INSERT INTO chunks(id,tenant_id,knowledge_base_id,knowledge_id,content,chunk_index,start_at,end_at) VALUES ('upgrade-chunk',10101,'kb-0','doc-0','原始分块',0,0,4);",
|
||||
'COMMIT; VACUUM ANALYZE embeddings;',
|
||||
]
|
||||
(OUT/'seed.sql').write_text('\n'.join(stmts))
|
||||
sql('\n'.join(stmts))
|
||||
(OUT/'vectors.json').write_text(json.dumps(queries))
|
||||
print('Seeded 720 embeddings plus tenant/model/KB/document/chunk/session/message data', flush=True)
|
||||
|
||||
def snapshot(stage):
|
||||
tables = sql("SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relkind IN ('r','p') AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid='pg_class'::regclass AND d.objid=c.oid AND d.deptype='e') ORDER BY 1").splitlines()
|
||||
data = {}
|
||||
for table in tables:
|
||||
ident = '"'+table.replace('"','""')+'"'
|
||||
rows = sql(f'SELECT to_jsonb(t)::text FROM {ident} t ORDER BY to_jsonb(t)::text')
|
||||
data[table] = {'count': int(sql(f'SELECT count(*) FROM {ident}')), 'sha256': hashlib.sha256(rows.encode()).hexdigest()}
|
||||
seq = sql("SELECT schemaname,sequencename,start_value,min_value,max_value,increment_by,cycle,last_value FROM pg_sequences WHERE schemaname='public' ORDER BY sequencename")
|
||||
schema = sql("SELECT table_name,column_name,data_type,udt_name,is_nullable,column_default FROM information_schema.columns WHERE table_schema='public' ORDER BY table_name,ordinal_position")
|
||||
indexes = sql("SELECT c.relname,i.indisvalid,i.indisready,c.relfilenode,pg_get_indexdef(i.indexrelid) FROM pg_index i JOIN pg_class c ON c.oid=i.indexrelid JOIN pg_class t ON t.oid=i.indrelid JOIN pg_namespace n ON n.oid=t.relnamespace WHERE n.nspname='public' ORDER BY c.relname")
|
||||
results = {}
|
||||
plans = {}
|
||||
keyword_queries = ['数据库', '知识库 文档', 'Docker AVX2', 'PostgreSQL database', '北京 上海', '权限 用户', '不存在的关键词xyz', '']
|
||||
filters = ['', " AND knowledge_base_id IN ('kb-0','kb-1')", " AND knowledge_base_id='kb-0' AND knowledge_id IN ('doc-0','doc-3')", " AND tag_id IN ('tag-1','tag-2')"]
|
||||
# Same |||, scoring and enabled predicate as KeywordsRetrieve. id only resolves equal-score ties.
|
||||
for q in keyword_queries:
|
||||
for j, filt in enumerate(filters):
|
||||
query = f"SELECT id,paradedb.score(id) AS score FROM embeddings WHERE content ||| {quote(q)} AND (is_enabled IS NULL OR is_enabled=true){filt} ORDER BY score DESC,id LIMIT 10"
|
||||
key = f'bm25:{q}:{j}'
|
||||
results[key] = sql(query)
|
||||
plans[key] = sql('EXPLAIN (COSTS OFF) '+query)
|
||||
vectors = json.loads((OUT/'vectors.json').read_text())
|
||||
for name, vector in vectors.items():
|
||||
dim = int(name.split('_')[0])
|
||||
for j, filt in enumerate(filters):
|
||||
# Exact production candidate expansion, halfvec expression, threshold, and ef_search.
|
||||
query = f"SELECT id,1-distance AS score FROM (SELECT id,embedding::halfvec({dim}) <=> {quote(vector)}::halfvec({dim}) AS distance FROM embeddings WHERE dimension={dim} AND (is_enabled IS NULL OR is_enabled=true){filt} ORDER BY embedding::halfvec({dim}) <=> {quote(vector)}::halfvec({dim}) LIMIT 100) candidates WHERE distance<=1.1 ORDER BY distance LIMIT 10"
|
||||
key = f'vector:{name}:{j}'
|
||||
results[key] = sql('BEGIN; SET LOCAL hnsw.ef_search=100; '+query+'; COMMIT;')
|
||||
# Force the index separately so a small fixture cannot silently test only sequential scans.
|
||||
results[key+':hnsw'] = sql('BEGIN; SET LOCAL enable_seqscan=off; SET LOCAL enable_bitmapscan=off; SET LOCAL enable_sort=off; SET LOCAL hnsw.ef_search=100; '+query+'; COMMIT;')
|
||||
plans[key] = sql('BEGIN; SET LOCAL enable_seqscan=off; SET LOCAL enable_bitmapscan=off; SET LOCAL enable_sort=off; SET LOCAL hnsw.ef_search=100; EXPLAIN (COSTS OFF) '+query+'; COMMIT;')
|
||||
assert 'Index Scan using embeddings_embedding_idx_'+str(dim) in plans[key], key+' did not use HNSW'
|
||||
assert any('Custom Scan' in p for k,p in plans.items() if k.startswith('bm25:')), 'BM25 index was not used'
|
||||
result = {'tables': data, 'sequences': seq, 'schema': schema, 'indexes': indexes, 'queries': results}
|
||||
(OUT/(stage+'.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
(OUT/(stage+'-plans.json')).write_text(json.dumps(plans, ensure_ascii=False, indent=2))
|
||||
(OUT/(stage+'-versions.txt')).write_text(sql("SELECT version(); SELECT extname,extversion FROM pg_extension ORDER BY 1; SELECT * FROM paradedb.version_info();"))
|
||||
print(f'{stage}: {len(data)} tables, {len(results)} retrieval queries captured', flush=True)
|
||||
if stage != 'before':
|
||||
baseline = json.loads((OUT/'before.json').read_text())
|
||||
differences = [key for key in result if result[key] != baseline[key]]
|
||||
if differences:
|
||||
print('Differences:', differences)
|
||||
if 'queries' in differences:
|
||||
print([key for key,value in results.items() if baseline['queries'][key] != value])
|
||||
raise SystemExit(1)
|
||||
print('PASS: rows, columns, sequences, index files, result IDs, ordering and scores unchanged', flush=True)
|
||||
|
||||
def docker(*args, **kwargs):
|
||||
return subprocess.run(['docker', *args], check=True, capture_output=True, **kwargs)
|
||||
|
||||
|
||||
def start(image, volume):
|
||||
docker('run', '-d', '--name', CONTAINER, '--network', 'none', '--shm-size=512m',
|
||||
'-e', 'POSTGRES_PASSWORD=isolated-upgrade-test', '-e', 'POSTGRES_DB=academy',
|
||||
'-v', volume+':/var/lib/postgresql/data', image)
|
||||
for _ in range(120):
|
||||
# Wait for the final server, not the bootstrap server that only uses a socket.
|
||||
ready = subprocess.run(['docker', 'exec', CONTAINER, 'pg_isready', '-h', '127.0.0.1', '-U', 'postgres', '-d', 'academy'], capture_output=True)
|
||||
if ready.returncode == 0:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError('Postgres did not start: '+docker('logs', CONTAINER).stdout.decode())
|
||||
|
||||
|
||||
def migrate(db, paths, label):
|
||||
with (OUT/(label+'.log')).open('w') as log:
|
||||
for path in paths:
|
||||
log.write(path.name+'\n')
|
||||
text = path.read_text()
|
||||
# CONCURRENTLY cannot run in a transaction block; golang-migrate does not add one either.
|
||||
sql(text if 'CONCURRENTLY' in text else 'BEGIN;\n'+text+'\nCOMMIT;', db)
|
||||
print(f'{label}: {len(paths)} SQL migrations passed', flush=True)
|
||||
|
||||
|
||||
def check_writes():
|
||||
# Committed writes must update both existing BM25 and HNSW indexes.
|
||||
vector = '['+','.join(['1']*1024)+']'
|
||||
new_id = sql("INSERT INTO embeddings(source_id,source_type,chunk_id,knowledge_id,knowledge_base_id,content,dimension,embedding,is_enabled) VALUES ('post-upgrade',0,'new-chunk','new-doc','new-kb','upgradeuniquetoken',1024,"+quote(vector)+",true) RETURNING id")
|
||||
assert sql("SELECT id FROM embeddings WHERE content ||| 'upgradeuniquetoken'") == new_id
|
||||
nearest = sql("BEGIN; SET LOCAL enable_seqscan=off; SET LOCAL enable_bitmapscan=off; SET LOCAL enable_sort=off; SELECT id FROM embeddings WHERE dimension=1024 ORDER BY embedding::halfvec(1024) <=> "+quote(vector)+"::halfvec(1024) LIMIT 1; COMMIT;")
|
||||
assert nearest == new_id, 'HNSW did not find the newly inserted vector'
|
||||
sql("UPDATE embeddings SET content='updateduniquetoken' WHERE id="+new_id)
|
||||
assert sql("SELECT count(*) FROM embeddings WHERE content ||| 'upgradeuniquetoken'") == '0'
|
||||
assert sql("SELECT id FROM embeddings WHERE content ||| 'updateduniquetoken'") == new_id
|
||||
sql('DELETE FROM embeddings WHERE id='+new_id)
|
||||
assert sql("SELECT count(*) FROM embeddings WHERE content ||| 'updateduniquetoken'") == '0'
|
||||
print('PASS: committed insert/vector lookup/update/delete on existing indexes', flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
global OUT
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output-dir', type=pathlib.Path)
|
||||
parser.add_argument('--to', choices=sorted(TARGETS), default='0.25.11', help='target pg_search version')
|
||||
args = parser.parse_args()
|
||||
OUT = args.output_dir or pathlib.Path(tempfile.mkdtemp(prefix='academy-pdb-upgrade-'))
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
if any(OUT.iterdir()):
|
||||
raise RuntimeError('Use an empty output directory')
|
||||
print('Evidence: '+str(OUT), flush=True)
|
||||
volume = CONTAINER+'-data'
|
||||
old = 'paradedb/paradedb:v0.22.2-pg17'
|
||||
target = args.to
|
||||
new, vector_target = TARGETS[target]
|
||||
paths = sorted((ROOT/'migrations/versioned').glob('*.up.sql'))
|
||||
baseline = [p for p in paths if int(p.name.split('_')[0]) < 99]
|
||||
upgrade = [ROOT/'migrations/versioned'/name for name in UPGRADES]
|
||||
upgrade_sql = '\n'.join(p.read_text() for p in upgrade)
|
||||
search_version = "SELECT extversion FROM pg_extension WHERE extname='pg_search'"
|
||||
vector_version = "SELECT extversion FROM pg_extension WHERE extname='vector'"
|
||||
# Only resources created by this invocation are ever removed.
|
||||
docker('volume', 'create', volume)
|
||||
try:
|
||||
start(old, volume)
|
||||
migrate('academy', baseline, 'old-migrations')
|
||||
assert sql(search_version) == '0.22.2'
|
||||
old_vector = sql(vector_version)
|
||||
# Older external servers without the target package must remain usable.
|
||||
migrate('academy', upgrade, 'unavailable-target')
|
||||
assert sql(search_version) == '0.22.2'
|
||||
assert sql(vector_version) == old_vector
|
||||
seed()
|
||||
snapshot('before')
|
||||
with (OUT/'before.dump').open('wb') as backup:
|
||||
subprocess.run(['docker', 'exec', CONTAINER, 'pg_dump', '-U', 'postgres', '-d', 'academy', '-Fc'], check=True, stdout=backup)
|
||||
docker('stop', '-t', '60', CONTAINER)
|
||||
docker('rm', CONTAINER)
|
||||
start(new, volume)
|
||||
# Replacing the image alone leaves the SQL catalog at the old version.
|
||||
assert sql(search_version) == '0.22.2'
|
||||
sql("BEGIN; SET LOCAL app.skip_embedding='true';\n"+upgrade_sql+"\nCOMMIT;")
|
||||
assert sql(search_version) == '0.22.2'
|
||||
migrate('academy', upgrade + upgrade, 'extension-upgrade-and-idempotence')
|
||||
assert sql(search_version) == target
|
||||
assert sql(vector_version) == (vector_target or old_vector)
|
||||
# Calls into the shared library crash the server if the catalog lags behind it.
|
||||
assert sql('SELECT version FROM paradedb.version_info()') == target
|
||||
snapshot('after')
|
||||
docker('restart', '-t', '60', CONTAINER)
|
||||
for _ in range(60):
|
||||
try:
|
||||
sql('SELECT 1')
|
||||
break
|
||||
except RuntimeError:
|
||||
time.sleep(1)
|
||||
snapshot('after-restart')
|
||||
check_writes()
|
||||
sql('CREATE DATABASE upgrade_fresh TEMPLATE template0')
|
||||
# The new migration must not install pg_search on non-search databases.
|
||||
migrate('upgrade_fresh', upgrade, 'absent-extension')
|
||||
assert sql("SELECT count(*) FROM pg_extension WHERE extname IN ('pg_search','vector')", 'upgrade_fresh') == '0'
|
||||
migrate('upgrade_fresh', paths, 'fresh-migrations')
|
||||
assert sql(search_version, 'upgrade_fresh') == target
|
||||
sql("INSERT INTO embeddings(source_id,source_type,content,dimension) VALUES ('fresh',0,'新安装检索',1024)", 'upgrade_fresh')
|
||||
assert sql("SELECT count(*) FROM embeddings WHERE content ||| '检索'", 'upgrade_fresh') == '1'
|
||||
print('PASS: fresh install and Chinese BM25 query', flush=True)
|
||||
(OUT/'PASS').write_text('Upgrade, restart, data integrity, retrieval, writes and fresh install passed.\n')
|
||||
finally:
|
||||
logs = subprocess.run(['docker', 'logs', CONTAINER], capture_output=True)
|
||||
(OUT/'postgres.log').write_bytes(logs.stdout+logs.stderr)
|
||||
subprocess.run(['docker', 'rm', '-f', CONTAINER], capture_output=True)
|
||||
docker('volume', 'rm', volume)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
#
|
||||
# 更新 Homebrew Formula 中的版本号和 sha256
|
||||
#
|
||||
# 用法:
|
||||
# ./scripts/update-homebrew-formula.sh v0.2.0
|
||||
#
|
||||
# 会自动从 GitHub Releases 下载 .sha256 文件来填充 Formula。
|
||||
# 在 CI 中被 release-lite workflow 调用。
|
||||
#
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
|
||||
VERSION="${1:?Usage: $0 <version> (e.g. v0.2.0)}"
|
||||
VERSION_BARE="${VERSION#v}"
|
||||
FORMULA="${ROOT_DIR}/Formula/academy-lite.rb"
|
||||
REPO="Tencent/WeKnora"
|
||||
BASE_URL="https://github.com/${REPO}/releases/download/${VERSION}"
|
||||
|
||||
if [ ! -f "${FORMULA}" ]; then
|
||||
echo "Error: Formula not found at ${FORMULA}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Updating Formula to version ${VERSION_BARE}..."
|
||||
|
||||
fetch_sha256() {
|
||||
local file="$1"
|
||||
local url="${BASE_URL}/${file}.sha256"
|
||||
local sha
|
||||
sha=$(curl -sSL "${url}" | awk '{print $1}')
|
||||
if [ -z "${sha}" ] || [ "${#sha}" -ne 64 ]; then
|
||||
echo "Error: Failed to fetch sha256 from ${url}" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "${sha}"
|
||||
}
|
||||
|
||||
SHA_DARWIN_ARM64=$(fetch_sha256 "Academy-lite_${VERSION}_darwin_arm64.tar.gz")
|
||||
SHA_DARWIN_AMD64=$(fetch_sha256 "Academy-lite_${VERSION}_darwin_amd64.tar.gz")
|
||||
SHA_LINUX_ARM64=$(fetch_sha256 "Academy-lite_${VERSION}_linux_arm64.tar.gz")
|
||||
SHA_LINUX_AMD64=$(fetch_sha256 "Academy-lite_${VERSION}_linux_amd64.tar.gz")
|
||||
|
||||
echo " darwin_arm64 : ${SHA_DARWIN_ARM64}"
|
||||
echo " darwin_amd64 : ${SHA_DARWIN_AMD64}"
|
||||
echo " linux_arm64 : ${SHA_LINUX_ARM64}"
|
||||
echo " linux_amd64 : ${SHA_LINUX_AMD64}"
|
||||
|
||||
# Use a temp file for portable sed
|
||||
TMP=$(mktemp)
|
||||
cp "${FORMULA}" "${TMP}"
|
||||
|
||||
# Update version
|
||||
sed -i.bak "s/^ version \".*\"/ version \"${VERSION_BARE}\"/" "${TMP}"
|
||||
|
||||
# Update sha256 values in order of appearance.
|
||||
# The formula has sha256 lines in this order:
|
||||
# 1. darwin arm64
|
||||
# 2. darwin amd64
|
||||
# 3. linux arm64
|
||||
# 4. linux amd64
|
||||
awk -v s1="${SHA_DARWIN_ARM64}" \
|
||||
-v s2="${SHA_DARWIN_AMD64}" \
|
||||
-v s3="${SHA_LINUX_ARM64}" \
|
||||
-v s4="${SHA_LINUX_AMD64}" \
|
||||
'BEGIN{n=0} /sha256 "/{n++; if(n==1) sub(/"[^"]*"$/,"\"" s1 "\""); else if(n==2) sub(/"[^"]*"$/,"\"" s2 "\""); else if(n==3) sub(/"[^"]*"$/,"\"" s3 "\""); else if(n==4) sub(/"[^"]*"$/,"\"" s4 "\"")} {print}' \
|
||||
"${TMP}" > "${FORMULA}"
|
||||
|
||||
rm -f "${TMP}" "${TMP}.bak"
|
||||
|
||||
echo "Formula updated: ${FORMULA}"
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT/frontend"
|
||||
|
||||
echo "[verify_frontend_pr] npm test"
|
||||
npm test
|
||||
|
||||
echo "[verify_frontend_pr] npm run type-check"
|
||||
npm run type-check
|
||||
|
||||
echo "[verify_frontend_pr] npm run build"
|
||||
npm run build
|
||||
|
||||
echo "[verify_frontend_pr] OK"
|
||||
@@ -0,0 +1,10 @@
|
||||
# Install torch/torchvision for the target CPU/CUDA/MPS platform separately.
|
||||
# Versions below match the WeMM model card and the validated service environment.
|
||||
transformers==5.2.0
|
||||
qwen-vl-utils==0.0.14
|
||||
accelerate>=1.1.0,<2
|
||||
fastapi>=0.115,<1
|
||||
pydantic>=2,<3
|
||||
uvicorn>=0.30,<1
|
||||
pillow>=10,<13
|
||||
httpx>=0.27,<1
|
||||
@@ -0,0 +1,367 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serve WeMM text/image embeddings with the official Transformers model code."""
|
||||
import argparse
|
||||
import base64
|
||||
import binascii
|
||||
import hmac
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt
|
||||
|
||||
log = logging.getLogger("uvicorn.error")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
model: str = "tencent/WeMM-Embedding-2B"
|
||||
served_model_name: str | None = None
|
||||
revision: str | None = None
|
||||
device: str = "auto"
|
||||
dtype: str = "auto"
|
||||
max_tokens: int = 8192
|
||||
max_pixels: int = 1048576
|
||||
max_batch_size: int = 32
|
||||
cpu_threads: int = 8
|
||||
local_files_only: bool = False
|
||||
api_key: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
if min(self.max_tokens, self.max_pixels, self.max_batch_size, self.cpu_threads) <= 0:
|
||||
raise ValueError("Resource limits and cpu_threads must be positive.")
|
||||
if self.max_pixels < 65536:
|
||||
raise ValueError("max_pixels must be at least 65536 (the model processor's minimum).")
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
if self.served_model_name:
|
||||
return self.served_model_name
|
||||
return Path(self.model).name if Path(self.model).is_dir() else self.model
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class TextPart(StrictModel):
|
||||
type: Literal["text"]
|
||||
text: str
|
||||
|
||||
|
||||
class ImageURL(StrictModel):
|
||||
url: str = Field(max_length=16 * 1024 * 1024)
|
||||
detail: Literal["auto", "low", "high"] = "auto"
|
||||
|
||||
|
||||
class ImagePart(StrictModel):
|
||||
type: Literal["image_url"]
|
||||
image_url: ImageURL
|
||||
|
||||
|
||||
class Message(StrictModel):
|
||||
role: Literal["system", "user", "assistant"]
|
||||
content: str | list[TextPart | ImagePart] = Field(min_length=1)
|
||||
|
||||
|
||||
class EmbedRequest(StrictModel):
|
||||
model: str
|
||||
input: str | list[str] | None = None
|
||||
messages: list[Message] | list[list[Message]] | None = None
|
||||
dimensions: StrictInt | None = None
|
||||
encoding_format: Literal["float", "base64"] = "float"
|
||||
user: str | None = None
|
||||
|
||||
|
||||
def bad(message):
|
||||
raise HTTPException(400, message)
|
||||
|
||||
|
||||
def parse_inputs(request, settings, dimensions, default_dimension):
|
||||
if request.model != settings.name:
|
||||
raise HTTPException(404, f"Model not found: {request.model}")
|
||||
dimension = default_dimension if request.dimensions is None else request.dimensions
|
||||
if dimension not in dimensions:
|
||||
bad(f"dimensions must be one of {dimensions}.")
|
||||
if (request.input is None) == (request.messages is None):
|
||||
bad("Supply exactly one of input or messages.")
|
||||
if request.input is not None:
|
||||
texts = [request.input] if isinstance(request.input, str) else request.input
|
||||
conversations = [[Message(role="user", content=[TextPart(type="text", text=text)])] for text in texts]
|
||||
else:
|
||||
messages = request.messages
|
||||
conversations = [messages] if messages and isinstance(messages[0], Message) else messages
|
||||
if not conversations or len(conversations) > settings.max_batch_size:
|
||||
bad(f"Supply between 1 and {settings.max_batch_size} independent inputs.")
|
||||
for conversation in conversations:
|
||||
if not conversation:
|
||||
bad("Each conversation must contain at least one message.")
|
||||
chars, images = 0, 0
|
||||
for message in conversation:
|
||||
parts = message.content
|
||||
if isinstance(parts, str):
|
||||
chars += len(parts)
|
||||
continue
|
||||
for part in parts:
|
||||
if isinstance(part, TextPart):
|
||||
chars += len(part.text)
|
||||
else:
|
||||
images += 1
|
||||
if not part.image_url.url.startswith("data:image/") or ";base64," not in part.image_url.url:
|
||||
bad("Images must be base64 data:image/... URLs; network URLs and file paths are unsupported.")
|
||||
if images > 5:
|
||||
bad("At most 5 images per conversation.")
|
||||
if chars > settings.max_tokens * 16:
|
||||
bad("Text exceeds the character guard; reduce the input size.")
|
||||
return conversations, dimension
|
||||
|
||||
|
||||
def decode_image(url):
|
||||
try:
|
||||
data = base64.b64decode(url.split(";base64,", 1)[1], validate=True)
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
if image.width * image.height > 40_000_000:
|
||||
bad("Image exceeds 40 megapixels before resizing.")
|
||||
# Preserve alpha until qwen-vl-utils composites RGBA onto white,
|
||||
# matching the official inference path instead of exposing hidden RGB.
|
||||
return image.copy()
|
||||
except (ValueError, binascii.Error, UnidentifiedImageError, OSError, Image.DecompressionBombError):
|
||||
bad("Invalid image data.")
|
||||
|
||||
|
||||
def prepare_messages(conversation, max_pixels):
|
||||
messages = []
|
||||
for message in conversation:
|
||||
parts = message.content
|
||||
if isinstance(parts, str):
|
||||
parts = [TextPart(type="text", text=parts)]
|
||||
content = []
|
||||
for part in parts:
|
||||
if isinstance(part, TextPart):
|
||||
content.append({"type": "text", "text": part.text})
|
||||
else:
|
||||
content.append({"type": "image", "image": decode_image(part.image_url.url), "max_pixels": max_pixels})
|
||||
messages.append({"role": message.role, "content": content})
|
||||
return messages
|
||||
|
||||
|
||||
def resolve_device_dtype(torch, settings):
|
||||
name = settings.device
|
||||
if name == "auto":
|
||||
name = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
||||
device = torch.device(name)
|
||||
if device.type not in ("cuda", "mps", "cpu"):
|
||||
raise ValueError("device must be auto, cpu, mps, cuda or cuda:N.")
|
||||
if device.type == "cuda":
|
||||
if not torch.cuda.is_available():
|
||||
raise ValueError("CUDA is unavailable; install a CUDA-enabled PyTorch build or select another device.")
|
||||
if device.index is not None and device.index >= torch.cuda.device_count():
|
||||
raise ValueError("The requested CUDA device does not exist.")
|
||||
with torch.cuda.device(device):
|
||||
bf16 = torch.cuda.is_bf16_supported()
|
||||
elif device.type == "mps":
|
||||
if not torch.backends.mps.is_available():
|
||||
raise ValueError("MPS is unavailable on this machine.")
|
||||
bf16 = True
|
||||
else:
|
||||
bf16 = False
|
||||
dtype = settings.dtype
|
||||
if dtype == "auto":
|
||||
dtype = "float32" if device.type == "cpu" else "bfloat16" if bf16 else "float16"
|
||||
if device.type == "cuda" and dtype == "bfloat16" and not bf16:
|
||||
raise ValueError("This CUDA device does not support bfloat16; use --dtype float16.")
|
||||
return device, getattr(torch, dtype)
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, settings):
|
||||
# Import after CLI setup so --mps-fallback takes effect before torch loads.
|
||||
import torch
|
||||
from transformers import AutoConfig, AutoModel, AutoProcessor
|
||||
self.settings, self.torch = settings, torch
|
||||
self.device, self.dtype = resolve_device_dtype(torch, settings)
|
||||
self.lock = threading.Lock()
|
||||
torch.set_num_threads(settings.cpu_threads)
|
||||
options = {"trust_remote_code": True, "local_files_only": settings.local_files_only}
|
||||
if settings.revision:
|
||||
options["revision"] = settings.revision
|
||||
config = AutoConfig.from_pretrained(settings.model, **options)
|
||||
self.dimensions = tuple(getattr(config, "matryoshka_dimensions", ()))
|
||||
self.default_dimension = config.text_config.hidden_size
|
||||
if not self.dimensions or self.default_dimension not in self.dimensions:
|
||||
raise ValueError("The model must provide WeMM matryoshka_dimensions including its hidden size.")
|
||||
self.processor = AutoProcessor.from_pretrained(settings.model, **options)
|
||||
self.model = AutoModel.from_pretrained(
|
||||
settings.model, dtype=self.dtype, attn_implementation="sdpa", **options,
|
||||
).to(self.device).eval()
|
||||
if not callable(getattr(self.model, "embedding", None)):
|
||||
raise ValueError("The model must expose WeMM's embedding() method.")
|
||||
|
||||
def encode(self, conversations, dimension):
|
||||
from qwen_vl_utils import process_vision_info
|
||||
torch = self.torch
|
||||
vectors, total_tokens = [], 0
|
||||
# WeMM's model stores rope_deltas. Keep independent conversations serialized,
|
||||
# and decode images only for the current input rather than the entire batch.
|
||||
with self.lock, torch.inference_mode():
|
||||
for conversation in conversations:
|
||||
messages = prepare_messages(conversation, self.settings.max_pixels)
|
||||
text = self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
||||
images, _ = process_vision_info(messages, image_patch_size=16)
|
||||
inputs = self.processor(text=text, images=images, return_tensors="pt")
|
||||
count = inputs["input_ids"].shape[-1]
|
||||
if count > self.settings.max_tokens:
|
||||
bad(f"Input has {count} tokens; limit is {self.settings.max_tokens}. Input was not truncated.")
|
||||
last = self.processor.tokenizer.convert_ids_to_tokens(inputs["input_ids"][0, -1].item())
|
||||
if last != "<embedding>":
|
||||
raise RuntimeError("Processor did not append the official <embedding> token.")
|
||||
inputs = inputs.to(self.device)
|
||||
# Reset explicitly as well, so older official code revisions are safe
|
||||
# when a text request follows a multimodal request.
|
||||
self.model.model.rope_deltas = None
|
||||
vector = self.model.embedding(**inputs, use_cache=False).float()
|
||||
vector = torch.nn.functional.normalize(vector[:, :dimension], dim=-1).cpu()[0]
|
||||
if vector.numel() != dimension or not torch.isfinite(vector).all() or vector.norm() < 0.99:
|
||||
raise RuntimeError("Invalid embedding output.")
|
||||
vectors.append(vector)
|
||||
total_tokens += count
|
||||
del inputs, images, messages
|
||||
return vectors, total_tokens
|
||||
|
||||
|
||||
class BodyLimit:
|
||||
"""Bound JSON bodies, including chunked requests, before parsing/base64 decoding."""
|
||||
def __init__(self, app, limit=32 * 1024 * 1024):
|
||||
self.app, self.limit = app, limit
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http" or scope["method"] != "POST":
|
||||
return await self.app(scope, receive, send)
|
||||
chunks, size = [], 0
|
||||
while True:
|
||||
message = await receive()
|
||||
if message["type"] == "http.disconnect":
|
||||
return
|
||||
chunk = message.get("body", b"")
|
||||
size += len(chunk)
|
||||
if size > self.limit:
|
||||
response = JSONResponse({"error": {"message": "Request body exceeds 32 MiB."}}, status_code=413)
|
||||
return await response(scope, receive, send)
|
||||
chunks.append(chunk)
|
||||
if not message.get("more_body", False):
|
||||
break
|
||||
body = b"".join(chunks)
|
||||
|
||||
async def replay():
|
||||
nonlocal body
|
||||
if body is not None:
|
||||
value, body = body, None
|
||||
return {"type": "http.request", "body": value, "more_body": False}
|
||||
return await receive()
|
||||
|
||||
await self.app(scope, replay, send)
|
||||
|
||||
|
||||
def create_app(settings, engine_factory=Engine):
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
started = time.monotonic()
|
||||
app.state.engine = engine_factory(settings)
|
||||
log.info("Loaded %s on %s/%s in %.1fs", settings.name, app.state.engine.device,
|
||||
app.state.engine.dtype, time.monotonic() - started)
|
||||
yield
|
||||
del app.state.engine
|
||||
|
||||
app = FastAPI(title="WeMM Transformers embedding service", lifespan=lifespan)
|
||||
app.add_middleware(BodyLimit)
|
||||
|
||||
def authorize(authorization: str | None = Header(default=None)):
|
||||
expected = "Bearer " + settings.api_key
|
||||
if settings.api_key and not hmac.compare_digest((authorization or "").encode(), expected.encode()):
|
||||
raise HTTPException(401, "Invalid API key.", headers={"WWW-Authenticate": "Bearer"})
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def api_error(_request, exc):
|
||||
return JSONResponse(status_code=exc.status_code, headers=exc.headers,
|
||||
content={"error": {"message": exc.detail, "code": exc.status_code}})
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(_request, exc):
|
||||
return JSONResponse(status_code=400, content={"error": {
|
||||
"message": "Invalid request: " + exc.errors()[0]["msg"], "code": 400,
|
||||
}})
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
engine = app.state.engine
|
||||
return {"status": "ok", "model": settings.name, "backend": "transformers",
|
||||
"device": str(engine.device), "dtype": str(engine.dtype), "revision": settings.revision,
|
||||
"dimensions": engine.dimensions, "default_dimension": engine.default_dimension,
|
||||
"max_tokens": settings.max_tokens, "max_image_pixels": settings.max_pixels}
|
||||
|
||||
@app.get("/v1/models", dependencies=[Depends(authorize)])
|
||||
def models():
|
||||
return {"object": "list", "data": [{"id": settings.name, "object": "model", "created": 0, "owned_by": "tencent"}]}
|
||||
|
||||
@app.post("/v1/embeddings", dependencies=[Depends(authorize)])
|
||||
def embeddings(request: EmbedRequest):
|
||||
engine = app.state.engine
|
||||
conversations, dimension = parse_inputs(request, settings, engine.dimensions, engine.default_dimension)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
vectors, tokens = engine.encode(conversations, dimension)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("WeMM inference failed")
|
||||
raise HTTPException(500, "WeMM inference failed; inspect the server log.") from None
|
||||
data = []
|
||||
for index, vector in enumerate(vectors):
|
||||
value = (base64.b64encode(vector.numpy().astype("<f4").tobytes()).decode()
|
||||
if request.encoding_format == "base64" else vector.tolist())
|
||||
data.append({"object": "embedding", "index": index, "embedding": value})
|
||||
log.info("Embedded %d inputs, %d tokens, %d dimensions in %.2fs", len(data), tokens,
|
||||
dimension, time.monotonic() - started)
|
||||
return {"object": "list", "data": data, "model": settings.name,
|
||||
"usage": {"prompt_tokens": tokens, "total_tokens": tokens}}
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--model", default=Settings.model, help="WeMM Hugging Face ID or model directory")
|
||||
parser.add_argument("--served-model-name", help="API model ID; defaults to the repo ID or directory basename")
|
||||
parser.add_argument("--revision", help="Hugging Face revision (prefer a commit SHA for reproducibility)")
|
||||
parser.add_argument("--device", default="auto", help="auto, cuda, cuda:N, mps or cpu")
|
||||
parser.add_argument("--dtype", choices=("auto", "bfloat16", "float16", "float32"), default="auto")
|
||||
parser.add_argument("--max-tokens", type=int, default=8192)
|
||||
parser.add_argument("--max-pixels", type=int, default=1048576)
|
||||
parser.add_argument("--max-batch-size", type=int, default=32)
|
||||
parser.add_argument("--cpu-threads", type=int, default=8)
|
||||
parser.add_argument("--local-files-only", action="store_true")
|
||||
parser.add_argument("--mps-fallback", action="store_true", help="Allow PyTorch CPU fallback for unsupported MPS ops")
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=18080)
|
||||
args = vars(parser.parse_args())
|
||||
host, port = args.pop("host"), args.pop("port")
|
||||
if args.pop("mps_fallback"):
|
||||
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
|
||||
settings = Settings(**args, api_key=os.environ.get("WEMM_API_KEY", ""))
|
||||
import uvicorn
|
||||
# A single process owns the model; do not add workers without separate GPUs.
|
||||
uvicorn.run(create_app(settings), host=host, port=port, workers=1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check a running WeMM service with actual text and image inference."""
|
||||
import argparse
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
|
||||
def dot(a, b):
|
||||
return sum(x * y for x, y in zip(a, b))
|
||||
|
||||
|
||||
def text_message(text):
|
||||
return [{"role": "user", "content": [{"type": "text", "text": text}]}]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:18080", help="Service root URL, without /v1")
|
||||
parser.add_argument("--timeout", type=float, default=180)
|
||||
args = parser.parse_args()
|
||||
headers = {"Authorization": "Bearer " + os.environ["WEMM_API_KEY"]} if os.environ.get("WEMM_API_KEY") else {}
|
||||
results = []
|
||||
with httpx.Client(base_url=args.base_url.rstrip("/"), timeout=args.timeout, headers=headers) as client:
|
||||
health_response = client.get("/health")
|
||||
health_response.raise_for_status()
|
||||
health = health_response.json()
|
||||
model = health["model"]
|
||||
default_dimension = health["default_dimension"]
|
||||
response = client.get("/v1/models")
|
||||
response.raise_for_status()
|
||||
assert model in [row["id"] for row in response.json()["data"]]
|
||||
|
||||
def run(name, **payload):
|
||||
started = time.monotonic()
|
||||
response = client.post("/v1/embeddings", json={"model": model, **payload})
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
vectors = [row["embedding"] for row in data["data"]]
|
||||
assert [row["index"] for row in data["data"]] == list(range(len(vectors)))
|
||||
for vector in vectors:
|
||||
assert len(vector) == payload.get("dimensions", default_dimension)
|
||||
assert all(math.isfinite(x) for x in vector)
|
||||
assert abs(math.sqrt(dot(vector, vector)) - 1) < 1e-4
|
||||
results.append({"test": name, "seconds": round(time.monotonic() - started, 3),
|
||||
"vectors": len(vectors), "dimension": len(vectors[0])})
|
||||
print(json.dumps(results[-1]), flush=True)
|
||||
return vectors
|
||||
|
||||
texts = ["A red square on a white background.", "A blue circle on a black background."]
|
||||
text_vectors = run("batched text messages", messages=[text_message(text) for text in texts])
|
||||
images = []
|
||||
for color, shape, background in [("red", "rectangle", "white"), ("blue", "ellipse", "black")]:
|
||||
image = Image.new("RGB", (256, 256), background)
|
||||
getattr(ImageDraw.Draw(image), shape)((40, 40, 216, 216), fill=color)
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
images.append([{"role": "user", "content": [{"type": "image_url", "image_url": {
|
||||
"url": "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode(),
|
||||
}}]}])
|
||||
image_vectors = run("batched image messages", messages=images)
|
||||
scores = [[dot(text, image) for image in image_vectors] for text in text_vectors]
|
||||
assert scores[0][0] > scores[0][1] and scores[1][1] > scores[1][0], scores
|
||||
repeated = run("text after image state isolation", messages=text_message(texts[0]))[0]
|
||||
assert dot(repeated, text_vectors[0]) > 0.9999
|
||||
dimension = min(health["dimensions"])
|
||||
short = run("Matryoshka dimensions", messages=text_message(texts[0]), dimensions=dimension)[0]
|
||||
prefix = text_vectors[0][:dimension]
|
||||
norm = math.sqrt(dot(prefix, prefix))
|
||||
assert dot(short, [value / norm for value in prefix]) > 0.9999
|
||||
raw = run("raw text compatibility", input=texts[0])[0]
|
||||
assert dot(raw, text_vectors[0]) > 0.9999
|
||||
for payload in ({"input": "hello", "dimensions": 3}, {"input": "a", "messages": []},
|
||||
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {
|
||||
"url": "https://example.com/image.png",
|
||||
}}]}]}):
|
||||
response = client.post("/v1/embeddings", json={"model": model, **payload})
|
||||
assert response.status_code == 400, response.text
|
||||
print(json.dumps({"status": "passed", "health": health, "tests": results, "text_image_scores": scores}), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Contract tests without downloading weights: python -m unittest discover -s scripts/wemm-transformers."""
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import struct
|
||||
import unittest
|
||||
from contextlib import nullcontext
|
||||
from unittest.mock import patch
|
||||
|
||||
import torch
|
||||
from fastapi import HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
from PIL import Image
|
||||
from serve import BodyLimit, Message, Settings, create_app, decode_image, prepare_messages, resolve_device_dtype
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
device, dtype = "cpu", "float32"
|
||||
|
||||
def __init__(self, settings, dimensions=(64, 128, 256, 512, 1024, 2048)):
|
||||
self.dimensions = dimensions
|
||||
self.default_dimension = dimensions[-1]
|
||||
self.calls = []
|
||||
|
||||
def encode(self, conversations, dimension):
|
||||
self.calls.append(conversations)
|
||||
vectors = []
|
||||
for index, _ in enumerate(conversations):
|
||||
vector = torch.zeros(dimension)
|
||||
vector[index] = 1
|
||||
vectors.append(vector)
|
||||
return vectors, len(conversations) * 10
|
||||
|
||||
|
||||
class ServiceTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.settings = Settings()
|
||||
self.engine = FakeEngine(self.settings)
|
||||
self.client = self.enterContext(TestClient(create_app(self.settings, lambda _: self.engine)))
|
||||
|
||||
def post(self, **payload):
|
||||
return self.client.post("/v1/embeddings", json={"model": self.settings.name, **payload})
|
||||
|
||||
def test_input_and_single_or_batched_messages(self):
|
||||
message = {"role": "user", "content": [{"type": "text", "text": "hello"}]}
|
||||
for payload, count in [({"input": "hello"}, 1), ({"input": ["a", "b"]}, 2),
|
||||
({"messages": [message]}, 1), ({"messages": [[message], [message]]}, 2)]:
|
||||
with self.subTest(payload=payload):
|
||||
response = self.post(**payload)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
data = response.json()["data"]
|
||||
self.assertEqual([x["index"] for x in data], list(range(count)))
|
||||
self.assertTrue(all(len(x["embedding"]) == 2048 for x in data))
|
||||
self.assertEqual([x["embedding"][i] for i, x in enumerate(data)], [1] * count)
|
||||
|
||||
def test_all_model_sizes_use_their_own_default_and_allowed_dimensions(self):
|
||||
for size, dimensions in [("2B", (64, 128, 256, 512, 1024, 2048)),
|
||||
("4B", (64, 128, 256, 512, 1024, 2560)),
|
||||
("9B", (64, 128, 256, 512, 1024, 2048, 4096))]:
|
||||
settings = Settings(model="tencent/WeMM-Embedding-" + size)
|
||||
with self.subTest(size=size), TestClient(create_app(settings, lambda s: FakeEngine(s, dimensions))) as client:
|
||||
for requested in (None, 1024):
|
||||
payload = {"model": settings.name, "input": "hello"}
|
||||
if requested is not None:
|
||||
payload["dimensions"] = requested
|
||||
response = client.post("/v1/embeddings", json=payload)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
self.assertEqual(len(response.json()["data"][0]["embedding"]), requested or dimensions[-1])
|
||||
payload["dimensions"] = 2049
|
||||
self.assertEqual(client.post("/v1/embeddings", json=payload).status_code, 400)
|
||||
self.assertEqual(client.get("/health").json()["default_dimension"], dimensions[-1])
|
||||
|
||||
def test_base64_is_little_endian_float32(self):
|
||||
response = self.post(input="hello", dimensions=64, encoding_format="base64")
|
||||
vector = struct.unpack("<64f", base64.b64decode(response.json()["data"][0]["embedding"]))
|
||||
self.assertEqual(vector, (1,) + (0,) * 63)
|
||||
|
||||
def test_invalid_requests_never_reach_inference(self):
|
||||
for payload in [dict(input="a", messages=[]), dict(input=[]), dict(messages=[[]]),
|
||||
dict(input="a", dimensions=True), dict(input="a", dimensions=0),
|
||||
dict(input="a", temperature=0), dict(input=["a"] * 33),
|
||||
dict(messages=[{"role": "user", "content": [{"type": "video", "video": "x"}]}]),
|
||||
dict(messages=[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "file:///etc/passwd"}}]}])]:
|
||||
with self.subTest(payload=payload):
|
||||
self.assertEqual(self.post(**payload).status_code, 400)
|
||||
self.assertEqual(self.post(model="wrong", input="a").status_code, 404)
|
||||
self.assertEqual(self.engine.calls, [])
|
||||
|
||||
def test_authentication_on_models_and_embeddings(self):
|
||||
settings = Settings(api_key="test-only-key")
|
||||
with TestClient(create_app(settings, lambda _: self.engine)) as client:
|
||||
self.assertEqual(client.get("/health").status_code, 200)
|
||||
self.assertEqual(client.get("/v1/models").status_code, 401)
|
||||
for token, status in [("Bearer wrong", 401), ("Bearer test-only-key", 200)]:
|
||||
response = client.post("/v1/embeddings", json={"model": settings.name, "input": "a"},
|
||||
headers={"Authorization": token})
|
||||
self.assertEqual(response.status_code, status)
|
||||
self.assertEqual(len(self.engine.calls), 1)
|
||||
|
||||
def test_image_decoding_and_invalid_bytes(self):
|
||||
buffer = io.BytesIO()
|
||||
Image.new("RGB", (64, 64), "red").save(buffer, format="PNG")
|
||||
uri = "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
|
||||
self.assertEqual(decode_image(uri).size, (64, 64))
|
||||
for data in ["!invalid!", base64.b64encode(b"not an image").decode()]:
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
decode_image("data:image/png;base64," + data)
|
||||
self.assertEqual(error.exception.status_code, 400)
|
||||
|
||||
def test_transparent_images_match_official_white_background(self):
|
||||
from qwen_vl_utils import process_vision_info
|
||||
image = Image.new("RGBA", (256, 256), (0, 0, 0, 0))
|
||||
image.putpixel((128, 128), (255, 0, 0, 128))
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
uri = "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
|
||||
conversation = [Message.model_validate({"role": "user", "content": [
|
||||
{"type": "image_url", "image_url": {"url": uri}},
|
||||
]})]
|
||||
actual, _ = process_vision_info(prepare_messages(conversation, 1048576), image_patch_size=16)
|
||||
expected, _ = process_vision_info([{"role": "user", "content": [
|
||||
{"type": "image", "image": image, "max_pixels": 1048576},
|
||||
]}], image_patch_size=16)
|
||||
self.assertEqual(actual[0].getpixel((0, 0)), (255, 255, 255))
|
||||
self.assertEqual(actual[0].getpixel((128, 128)), (255, 127, 127))
|
||||
self.assertEqual(actual[0].tobytes(), expected[0].tobytes())
|
||||
|
||||
def test_cpu_defaults_and_explicit_unavailable_device(self):
|
||||
with patch.object(torch.cuda, "is_available", return_value=False), patch.object(torch.backends.mps, "is_available", return_value=False):
|
||||
device, dtype = resolve_device_dtype(torch, Settings())
|
||||
self.assertEqual(str(device), "cpu")
|
||||
self.assertEqual(dtype, torch.float32)
|
||||
for requested in ("cuda", "mps"):
|
||||
with self.assertRaises(ValueError):
|
||||
resolve_device_dtype(torch, Settings(device=requested))
|
||||
|
||||
def test_cuda_auto_dtype_and_explicit_bf16_guard(self):
|
||||
with patch.object(torch.cuda, "is_available", return_value=True), patch.object(torch.cuda, "device", return_value=nullcontext()):
|
||||
for supported, expected in [(True, torch.bfloat16), (False, torch.float16)]:
|
||||
with patch.object(torch.cuda, "is_bf16_supported", return_value=supported):
|
||||
device, dtype = resolve_device_dtype(torch, Settings())
|
||||
self.assertEqual(str(device), "cuda")
|
||||
self.assertEqual(dtype, expected)
|
||||
if not supported:
|
||||
with self.assertRaises(ValueError):
|
||||
resolve_device_dtype(torch, Settings(device="cuda", dtype="bfloat16"))
|
||||
|
||||
def test_body_limit_counts_chunked_bodies(self):
|
||||
async def run(chunks):
|
||||
received, sent = [], []
|
||||
events = iter({"type": "http.request", "body": chunk, "more_body": i < len(chunks) - 1}
|
||||
for i, chunk in enumerate(chunks))
|
||||
async def receive():
|
||||
return next(events)
|
||||
async def send(event):
|
||||
sent.append(event)
|
||||
async def downstream(scope, receive, send):
|
||||
received.append((await receive())["body"])
|
||||
await BodyLimit(downstream, limit=4)({"type": "http", "method": "POST"}, receive, send)
|
||||
return received, sent
|
||||
received, _ = asyncio.run(run([b"12", b"34"]))
|
||||
self.assertEqual(received, [b"1234"])
|
||||
received, sent = asyncio.run(run([b"12", b"345"]))
|
||||
self.assertEqual(received, [])
|
||||
self.assertEqual(sent[0]["status"], 413)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user