Go implementation of DeepSeek Harness and self-hosted personal agent.
Go
feat(deploy): add GHCR images and curl installation
xyc2eb39aa1161b
diff --git a/.dockerignore b/.dockerignoreindex c70308e..479b2fa 100644--- a/.dockerignore+++ b/.dockerignore@@ -23,6 +23,9 @@ configs/local.yaml**/controller.lock**/state.json**/*.token+**/.credentials.yaml+**/.credential-write-*+**/.install-***/.write-***/.idea**/*.imldiff --git a/.env.example b/.env.exampleindex a5c0c34..115b6c3 100644--- a/.env.example+++ b/.env.example@@ -1,18 +1,20 @@-# Run ./scripts/start.sh --init-env to create private Docker and ECI profiles.-# 运行 ./scripts/start.sh --init-env 生成 Docker 和 ECI 的私有配置文件。+# install.sh copies this template to .env; start with docker compose up -d.+# install.sh 将此模板复制为 .env;使用 docker compose up -d 启动。+# In a source checkout, scripts/start.sh --init-env creates .env and .env.eci.+# 源码目录可使用 scripts/start.sh --init-env 生成 .env 和 .env.eci。# Write literal KEY=value assignments without quotes, export, or interpolation.# 使用 KEY=value 格式填写原始值,不加引号、export,也不展开变量。-# The launcher validates explicit deployment environment overrides before saving them.-# 启动脚本会先校验显式传入的部署环境变量,再将有效覆盖值保存到配置文件。+# start.sh saves validated shell overrides; Controller also accepts explicit container overrides.+# start.sh 校验并保存 shell 覆盖值;Controller 也支持显式传入容器的环境覆盖。# Configure models and web search per account in Settings; connect services in Plugin market.# 模型和网页搜索请在设置中按账号配置;第三方服务请到插件市场连接。# Host runtime: docker for local Docker or eci for Alibaba Cloud ECI.# Host 运行模式:docker 表示本地 Docker,eci 表示阿里云弹性容器实例。HARNESS_RUNTIME=docker-# Local Host image tag. ECI initialization sets go-bot/host:eci for the build step.-# Host 镜像的本地标签。ECI 初始化将其设为 go-bot/host:eci,供构建步骤使用。-HOST_IMAGE=go-bot/host:local+# Published Host image. Docker uses its local copy; ECI cache creation and startup use this reference.+# 已发布的 Host 镜像。Docker 使用其本地副本;ECI 制作缓存和启动实例均使用此地址。+HOST_IMAGE=ghcr.io/xyc999-ai/go-bot-host:latest# Docker uses an account volume. ECI uses instance storage (container) or persistent NAS (nas).# Docker 自动挂载账号卷。ECI 可以选择实例存储(container)或持久化 NAS(nas)。HARNESS_STORAGE=container@@ -42,13 +44,3 @@ ALIBABA_CLOUD_ACCESS_KEY_ID=# Secret for the Alibaba Cloud AccessKey ID above.# 上方阿里云 AccessKey ID 对应的 Secret。ALIBABA_CLOUD_ACCESS_KEY_SECRET=--# Full, versioned registry image reference for buildeci prepare or cache.-# buildeci prepare 或 cache 使用的完整镜像仓库地址,需指定版本。-REGISTRY_PUSH_IMAGE=-# Private registry username for ECI cache creation. Set both credentials or leave both empty.-# ECI 制作缓存时使用的私有镜像仓库用户名。用户名和密码须同时填写或同时留空。-REGISTRY_USERNAME=-# Private registry password for ECI cache creation.-# ECI 制作缓存时使用的私有镜像仓库密码。-REGISTRY_PASSWORD=diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 70acf72..32c6354 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -76,4 +76,7 @@ jobs:if: github.event_name == 'workflow_dispatch'run: RUN_DOCKER_INTEGRATION=1 go test -tags webui ./tests/integration -v- name: Smoke-test Controller, Redis and Hosts with Docker Compose- run: python3 scripts/smoke-cli.py+ run: |+ make image-controller+ python3 scripts/test-install.py+ python3 scripts/smoke-cli.pydiff --git a/.github/workflows/publish-images.yml b/.github/workflows/publish-images.ymlnew file mode 100644index 0000000..89169b6--- /dev/null+++ b/.github/workflows/publish-images.yml@@ -0,0 +1,125 @@+name: Publish container images++on:+ push:+ tags: ['v*']+ workflow_dispatch:+ inputs:+ version:+ description: 'Image version to publish from the selected ref (for example v0.0.1)'+ required: true+ default: v0.0.1+ update_latest:+ description: 'Also point latest at this version (disable when republishing an older version)'+ type: boolean+ default: true++permissions:+ contents: read+ packages: write++concurrency:+ group: publish-container-images+ cancel-in-progress: false++jobs:+ build:+ name: ${{ matrix.role }} / ${{ matrix.arch }}+ strategy:+ fail-fast: false+ matrix:+ role: [controller, host]+ include:+ - arch: amd64+ runner: ubuntu-24.04+ - arch: arm64+ runner: ubuntu-24.04-arm+ arch: [amd64, arm64]+ runs-on: ${{ matrix.runner }}+ steps:+ - uses: actions/checkout@v4+ - name: Select version and namespace+ env:+ REQUESTED_VERSION: ${{ inputs.version || github.ref_name }}+ run: |+ [[ "$REQUESTED_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Use a stable vX.Y.Z version.' >&2; exit 1; }+ echo "IMAGE_VERSION=$REQUESTED_VERSION" >> "$GITHUB_ENV"+ echo "IMAGE_NAMESPACE=${GITHUB_REPOSITORY_OWNER,,}" >> "$GITHUB_ENV"+ - uses: docker/setup-buildx-action@v3+ - uses: docker/login-action@v3+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}+ - uses: docker/build-push-action@v6+ id: build+ with:+ context: .+ file: build/Dockerfile.${{ matrix.role }}+ platforms: linux/${{ matrix.arch }}+ outputs: type=image,name=ghcr.io/${{ env.IMAGE_NAMESPACE }}/go-bot-${{ matrix.role }},push-by-digest=true,name-canonical=true,push=true+ labels: |+ org.opencontainers.image.source=https://github.com/${{ github.repository }}+ org.opencontainers.image.version=${{ env.IMAGE_VERSION }}+ org.opencontainers.image.revision=${{ github.sha }}+ org.opencontainers.image.licenses=MIT+ - name: Record architecture digest+ env:+ ROLE: ${{ matrix.role }}+ ARCH: ${{ matrix.arch }}+ DIGEST: ${{ steps.build.outputs.digest }}+ run: |+ mkdir -p "$RUNNER_TEMP/digests/$ROLE"+ printf '%s\n' "$DIGEST" > "$RUNNER_TEMP/digests/$ROLE/$ARCH"+ - uses: actions/upload-artifact@v4+ with:+ name: image-digest-${{ matrix.role }}-${{ matrix.arch }}+ path: ${{ runner.temp }}/digests/+ retention-days: 1++ manifest:+ name: Publish multi-platform tags+ needs: build+ runs-on: ubuntu-24.04+ steps:+ - name: Select version and namespace+ env:+ REQUESTED_VERSION: ${{ inputs.version || github.ref_name }}+ run: |+ [[ "$REQUESTED_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || exit 1+ echo "IMAGE_VERSION=$REQUESTED_VERSION" >> "$GITHUB_ENV"+ echo "IMAGE_NAMESPACE=${GITHUB_REPOSITORY_OWNER,,}" >> "$GITHUB_ENV"+ - uses: docker/setup-buildx-action@v3+ - uses: actions/download-artifact@v4+ with:+ pattern: image-digest-*+ merge-multiple: true+ path: ${{ runner.temp }}/digests+ - uses: docker/login-action@v3+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}+ - name: Combine matching architecture builds+ env:+ UPDATE_LATEST: ${{ github.event_name == 'push' || inputs.update_latest }}+ run: |+ for role in controller host; do+ image="ghcr.io/$IMAGE_NAMESPACE/go-bot-$role"+ sources=()+ for arch in amd64 arm64; do+ read -r digest < "$RUNNER_TEMP/digests/$role/$arch"+ [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || exit 1+ sources+=("$image@$digest")+ done+ tags=(--tag "$image:$IMAGE_VERSION")+ if [[ "$UPDATE_LATEST" == true ]]; then tags+=(--tag "$image:latest"); fi+ docker buildx imagetools create "${tags[@]}" "${sources[@]}"+ done+ - name: Verify public access+ run: |+ docker logout ghcr.io+ for role in controller host; do+ # On first publication, set both GHCR packages to Public and rerun this job.+ docker buildx imagetools inspect "ghcr.io/$IMAGE_NAMESPACE/go-bot-$role:$IMAGE_VERSION"+ donediff --git a/.gitignore b/.gitignoreindex 642dd51..aa1840c 100644--- a/.gitignore+++ b/.gitignore@@ -29,6 +29,7 @@ state.json.credentials.yaml.credential-write-*.write-*+.install-*/# Private cloud deployment and replay notes/docs/eci-nas-validation.zh-CN.mddiff --git a/Makefile b/Makefileindex eac4cb5..b278d2f 100644--- a/Makefile+++ b/Makefile@@ -1,4 +1,6 @@-.PHONY: build build-web image test race vet run check+HOST_IMAGE ?= ghcr.io/xyc999-ai/go-bot-host:latest+CONTROLLER_IMAGE ?= ghcr.io/xyc999-ai/go-bot-controller:latest+.PHONY: build build-web image image-controller test race vet run checkbuild:mkdir -p bingo build -trimpath -o bin/controller ./cmd/controller@@ -12,7 +14,9 @@ build-web:go build -tags webui -trimpath -o bin/controller ./cmd/controllergo build -trimpath -o bin/prepare-env ./internal/cmd/prepare-envimage:- docker build -f build/Dockerfile.host -t go-bot/host:local .+ docker build -f build/Dockerfile.host -t $(HOST_IMAGE) .+image-controller:+ docker build -f build/Dockerfile.controller -t $(CONTROLLER_IMAGE) .test:go test ./...race:diff --git a/README.md b/README.mdindex 529503c..d2fe56b 100644--- a/README.md+++ b/README.md@@ -120,16 +120,20 @@ and a PowerPoint deck. [Stanford HAI 2026 AI Index](https://hai.stanford.edu/ai-## QuickstartInstall Docker Engine or Docker Desktop with the Docker Compose plugin-(`docker compose`). From the repository root, run:+(`docker compose`), curl and Bash. No source checkout or Go installation is needed:```sh-./scripts/start.sh --init-env-./scripts/start.sh+curl -fsSL https://raw.githubusercontent.com/xyc999-ai/go-bot/main/scripts/install.sh | bash+cd go-bot+docker compose up -d```-The first command creates private `.env` and `.env.eci` profiles and keeps-existing files. The second reads `.env`, builds the local Host image, and-starts Controller and Redis with Compose.+The installer downloads the repository's `compose.yaml`, `.env.example` and+`configs/default.yaml`, creates `.env` if missing, and pulls the published+Controller, Host and Redis images. It keeps existing configuration and does not+start services or create `.env.eci`. Compose starts Controller and Redis; each+account's Host is a separate container created by Controller. Images support+AMD64 and ARM64, selected automatically by Docker. [Source development](docs/deployment.md#source-checkout)### Web browser@@ -216,21 +220,37 @@ The mobile app connects to the same Controller from iOS or Android. It providesRun Controller and Redis with Docker Compose on a machine that can reach theECI private network, such as an ECS instance in the same VPC. Each account's-agent computer runs as its own ECI instance. Once the cloud resources and a-Ready image cache are in place, the same launcher starts the deployment.+agent computer runs as its own ECI instance. Go Bot provides the preparation+tools; you run them with your own cloud configuration and then start the services+yourself. The local-Docker Quickstart installer does not prepare ECI or create+cloud resources.++### 1. Clone the repository and prepare local tools++On the Controller machine, install Git, Docker with Compose v2, and Bash. Then run:++```sh+git clone https://github.com/xyc999-ai/go-bot.git+cd go-bot+docker pull ghcr.io/xyc999-ai/go-bot-controller:latest+docker pull redis:8-alpine+./scripts/start.sh --init-env+```++This explicitly initializes `.env` and `.env.eci` without overwriting existing+files. ECI uses `.env.eci`. The Controller image contains the cache tool; no local+Go installation or Host image download is needed. These commands do not start+Controller, Redis or an account Host.-### 1. Prepare Alibaba Cloud resources+### 2. Prepare cloud resources and fill in `.env.eci`| Resource | What to prepare || --- | --- || RAM credentials | Create a RAM user with an AccessKey ID and Secret. Grant the ECI API permissions needed to list, create and release instances, inspect caches, and create caches if you build them here. [Create an AccessKey pair](https://www.alibabacloud.com/help/en/ram/user-guide/create-an-accesskey-pair) · [Grant RAM permissions](https://www.alibabacloud.com/help/en/ram/user-guide/grant-permissions-to-the-ram-user) || Network | Choose the region, vSwitch and security group. Allow Controller to reach the ECI private IP on TCP 8080. For public registry, model and web access, configure outbound access such as NAT gateway SNAT on the ECI vSwitch. The launcher does not assign an EIP to each Host. [VPCs and vSwitches](https://www.alibabacloud.com/help/en/vpc/vpc-and-vswitch) · [Security group rules](https://www.alibabacloud.com/help/en/ecs/user-guide/security-group-rules) · [ECI internet access](https://www.alibabacloud.com/help/en/eci/user-guide/enable-internet-access) |-| NAS (optional) | Prepare a reachable NAS mount target. Before opening an account, create a writable `/go-bot/<userId>` directory on NAS for it. [Mount NAS on ECI](https://www.alibabacloud.com/help/en/eci/user-guide/mount-a-nas-volume) |-| Image cache | Reuse a Ready cache for a Linux AMD64 Host image in the selected region, or prepare a registry that the ECI cache builder can reach. [Manage ECI image caches](https://www.alibabacloud.com/help/en/eci/user-guide/manage-an-image-cache) |+| NAS (optional) | Prepare a reachable, writable NAS mount target. Each account's data uses `/go-bot/<userId>` on NAS, mounted at `/root/harness` in the Host. [Mount NAS on ECI](https://www.alibabacloud.com/help/en/eci/user-guide/mount-a-nas-volume) |+| Image cache | Create it in step 3 from the public Host image, or reuse a Ready cache for exactly the same `HOST_IMAGE` in the selected region. [Manage ECI image caches](https://www.alibabacloud.com/help/en/eci/user-guide/manage-an-image-cache) |-### 2. Fill in the ECI profile--Run `./scripts/start.sh --init-env` if you have not initialized the profiles.Edit `.env.eci`, which already selects `HARNESS_RUNTIME=eci`. Set`ECI_REGION`, `ECI_VSWITCH_ID`, `ECI_SECURITY_GROUP_ID`,`ALIBABA_CLOUD_ACCESS_KEY_ID` and `ALIBABA_CLOUD_ACCESS_KEY_SECRET`.@@ -242,26 +262,23 @@ the Host starts.### 3. Prepare the Host image cache-If you have a Ready cache containing a compatible Host image, set-`ECI_IMAGE_CACHE_ID` and go to step 4. To build a new cache, set-`REGISTRY_PUSH_IMAGE` to a versioned registry reference such as-`registry.example.com/team/go-bot-host:v0.1.0`. For a private-registry, run `docker login <registry-host>` on the build machine if publishing-requires authentication, and set both `REGISTRY_USERNAME` and-`REGISTRY_PASSWORD` so Alibaba Cloud can pull it.--On the build machine, install Go 1.26 or newer and Docker with Buildx, then run:+Leave `HOST_IMAGE` at the public image address supplied by the template. If you+already have a Ready cache for that exact image, set `ECI_IMAGE_CACHE_ID` and go+to step 4. Otherwise, explicitly create the cache:```sh-./scripts/buildeci.sh prepare --env-file .env.eci+./scripts/buildeci.sh --env-file .env.eci```-`prepare` builds the Linux AMD64 Host image, tags it locally with `HOST_IMAGE`,-pushes it to `REGISTRY_PUSH_IMAGE`, and requests an ECI image cache. If the-compatible AMD64 image has already been published, use-`./scripts/buildeci.sh cache --env-file .env.eci` to skip the local build and-push. Both commands wait for Ready and write `ECI_IMAGE_CACHE_ID` into the-selected profile. [Cache options and recovery](docs/deployment.md#eci-image-cache)+The script runs the cache tool inside the already-pulled Controller image.+Alibaba Cloud pulls the AMD64 variant of the public `HOST_IMAGE`; no local+Host build, push, Go installation or registry login is needed. It waits for+Ready and writes `ECI_IMAGE_CACHE_ID` back into `.env.eci`. Cache creation uses+billable Alibaba Cloud resources. There are no registry credentials or separate+push-address settings: the cache tool uses the public `HOST_IMAGE` directly.+This command only prepares the cache; it does not start Controller, Redis or+an account Host. A failed or timed-out run does not replace the saved cache ID.+[API parameters, cache options and recovery](docs/deployment.md#cache-api-request)### 4. Start Controller and open an account@@ -272,25 +289,33 @@ On the Controller machine, use the completed private profile:```The launcher validates the deployment profile and starts Controller and Redis-with Compose. ECI Host instances start on demand from the configured cache-when you open an account.+with Compose. Open the Controller URL in your browser and create or open an+account. Only then does Controller create that account's ECI Host, passing+`HOST_IMAGE` and `ECI_IMAGE_CACHE_ID` directly to Alibaba Cloud. Preparing a cache+alone does not create a user Host. When changing the Host image, create a new+cache and update its ID before replacing the account's instance.## Configuration and verification-`start.sh` loads the selected profile, applies explicitly set deployment-environment variables, validates the merged configuration, and saves valid-overrides to the profile before launch. An explicitly empty value overrides a-saved value. Model and web-search settings are saved per account through the UI.+Controller reads the mounted `.env` and `configs/default.yaml` and validates+them at startup, including when started directly with Compose. Edit `.env` to+change deployment settings. The source-only `start.sh` additionally saves+validated shell overrides before starting Compose; it never pulls or builds+images. Explicit container environment overrides are also validated and saved+by Controller. An explicitly empty override clears the saved value.+Model and web-search settings are saved per account through the UI.Gemini media capabilities use the API key configured in the plugin detail.For an offline configuration check or a read-only runtime check, use:```sh-go run ./cmd/controller check --env-file .env.eci-go run ./cmd/controller doctor --env-file .env.eci+docker compose run --rm --no-deps controller check --env-file /config/.env --config /runtime.yaml+docker compose run --rm --no-deps controller doctor --env-file /config/.env --config /runtime.yaml```-Use `.env` for local Docker. `check` validates configuration, including+For ECI, change `/config/.env` to `/config/.env.eci`. These commands use tools+in the existing Controller image and need no local Go or running Redis.+`check` validates configuration, includingrequired fields. `doctor` also checks the selected runtime, such as the localHost image or the Ready ECI cache. Opening an account exercises actual Hostcreation, storage and Controller-to-Host connectivity.@@ -300,11 +325,11 @@ creation, storage and Controller-to-Host connectivity.| Task | Install on the machine running it || --- | --- |-| Run the local or ECI deployment with `start.sh` | Docker, the Docker Compose plugin, and Bash. Go is optional because the launcher can run its configuration tools in Docker. |-| Prepare an ECI cache with `buildeci.sh` | Go 1.26 or newer and Bash. The `prepare` subcommand also needs Docker with Buildx. |+| Quickstart | Docker Engine or Docker Desktop, Docker Compose v2, curl and Bash. |+| Run `start.sh` or prepare a public ECI cache | Docker, Docker Compose v2 and Bash; prepare the required images first. No local Go installation is needed. || Develop outside Docker | Go 1.26 or newer for the backend, a Redis instance for a native Controller, and Node.js 22.12+ with npm for frontend development. |-Compose runs Redis and builds the frontend. Python, Node.js, Chromium and+Compose runs Redis and the published Controller with its embedded frontend. Python, Node.js, Chromium andthe general document environment are included in the Host image. Install OfficeCLI and agent-browser through the plugin market.## Develop and extenddiff --git a/README.zh-CN.md b/README.zh-CN.mdindex ef00472..06f974b 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -117,15 +117,19 @@ Go Bot 会记住与你交流的背景,持续关注你关心的事,并主动## 快速开始-安装 Docker Engine 或 Docker Desktop,并确认可以运行 `docker compose`。在仓库根目录执行:+安装 Docker Engine 或 Docker Desktop、Docker Compose v2、curl 和 Bash。无需克隆源码或安装 Go:```sh-./scripts/start.sh --init-env-./scripts/start.sh+curl -fsSL https://raw.githubusercontent.com/xyc999-ai/go-bot/main/scripts/install.sh | bash+cd go-bot+docker compose up -d```-第一条命令生成私有配置 `.env` 和 `.env.eci`,保留已有文件。第二条命令读取 `.env`,-在本机构建 Host 镜像,并通过 Compose 启动 Controller 和 Redis。+安装器下载仓库原始的 `compose.yaml`、`.env.example` 和 `configs/default.yaml`,仅在缺失时+生成 `.env`,并拉取已发布的 Controller、Host 和 Redis 镜像。已有配置保留,不启动服务,+不生成 `.env.eci`。Compose 启动 Controller 和 Redis;每个账号的 Host 由 Controller 动态创建,+是独立容器。应用镜像提供 AMD64 和 ARM64,Docker 自动选择匹配架构。+[源码开发启动](docs/deployment.md#source-checkout)### 浏览器@@ -203,20 +207,35 @@ OfficeCLI 提供 11 个原始 Skills,agent-browser 提供官方发现 Skill;在能够访问 ECI 私网的机器上通过 Docker Compose 运行 Controller 和 Redis,例如同一 VPC 内的一台 ECS。每个账号的 Agent 云电脑运行在独立的 ECI 实例中。准备好云资源和 Ready 镜像缓存后,-可通过同一个启动脚本部署。+由部署者自行启动服务。项目提供准备工具,部署者使用自己的阿里云配置执行;本地 Docker+Quickstart 的 install.sh 不承担 ECI 准备,也不会创建云资源。++### 1. 拉取仓库并准备本地工具++在 Controller 所在机器上安装 Git、带 Compose v2 的 Docker 和 Bash,然后执行:++```sh+git clone https://github.com/xyc999-ai/go-bot.git+cd go-bot+docker pull ghcr.io/xyc999-ai/go-bot-controller:latest+docker pull redis:8-alpine+./scripts/start.sh --init-env+```++显式初始化会生成 `.env` 和 `.env.eci`,保留已有文件;ECI 使用 `.env.eci`。+缓存工具已包含在 Controller 镜像中,无需在本机安装 Go 或下载 Host 镜像。+以上命令不会启动 Controller、Redis 或账号的 Host。-### 1. 准备阿里云资源+### 2. 准备云资源并填写 `.env.eci`| 资源 | 需要提前准备 || --- | --- || RAM 凭证 | 创建 RAM 用户及 AccessKey ID、Secret,授予查询、创建和释放 ECI 实例、查询镜像缓存所需的权限。如需制作缓存,再授予创建缓存权限。 [创建 AccessKey](https://www.alibabacloud.com/help/en/ram/user-guide/create-an-accesskey-pair) · [RAM 用户授权](https://www.alibabacloud.com/help/en/ram/user-guide/grant-permissions-to-the-ram-user) || 网络 | 选择地域、交换机和安全组,允许 Controller 通过私网访问 ECI 的 TCP 8080。镜像仓库、模型服务或网页需要公网访问时,可为 ECI 所在交换机配置公网 NAT 网关 SNAT。启动流程不会为每个 Host 分配 EIP。 [VPC 与交换机](https://www.alibabacloud.com/help/en/vpc/vpc-and-vswitch) · [安全组规则](https://www.alibabacloud.com/help/en/ecs/user-guide/security-group-rules) · [ECI 公网访问](https://www.alibabacloud.com/help/en/eci/user-guide/enable-internet-access) |-| NAS(可选) | 准备 ECI 可访问的 NAS 挂载点。在打开账号前,为该账号创建可写的 `/go-bot/<userId>` 目录。 [ECI 挂载 NAS](https://www.alibabacloud.com/help/en/eci/user-guide/mount-a-nas-volume) |-| 镜像缓存 | 复用所选地域中已有的 Linux AMD64 Host Ready 缓存,或者准备 ECI 缓存制作服务可访问的镜像仓库。 [管理 ECI 镜像缓存](https://www.alibabacloud.com/help/en/eci/user-guide/manage-an-image-cache) |+| NAS(可选) | 准备 ECI 可访问、可写的 NAS 挂载点。账号数据使用 NAS 上的 `/go-bot/<userId>`,挂载至 Host 的 `/root/harness`。 [ECI 挂载 NAS](https://www.alibabacloud.com/help/en/eci/user-guide/mount-a-nas-volume) |+| 镜像缓存 | 在第 3 步使用公共 Host 镜像创建,或者复用所选地域中与 `HOST_IMAGE` 完全对应的 Ready 缓存。 [管理 ECI 镜像缓存](https://www.alibabacloud.com/help/en/eci/user-guide/manage-an-image-cache) |-### 2. 填写 ECI 配置--尚未初始化时,先运行 `./scripts/start.sh --init-env`。编辑已预设 `HARNESS_RUNTIME=eci` 的+编辑已预设 `HARNESS_RUNTIME=eci` 的`.env.eci`,填写 `ECI_REGION`、`ECI_VSWITCH_ID`、`ECI_SECURITY_GROUP_ID`、`ALIBABA_CLOUD_ACCESS_KEY_ID` 和 `ALIBABA_CLOUD_ACCESS_KEY_SECRET`。@@ -226,23 +245,19 @@ OfficeCLI 提供 11 个原始 Skills,agent-browser 提供官方发现 Skill;### 3. 准备 Host 镜像缓存-已有兼容 Host 镜像的 Ready 缓存时,将 ID 填入 `ECI_IMAGE_CACHE_ID`,直接进入第 4 步。-制作新缓存时,将 `REGISTRY_PUSH_IMAGE` 设置为带版本标签的完整镜像地址,例如-`registry.example.com/team/go-bot-host:v0.1.0`。如果推送需要认证,-在构建机执行 `docker login <registry-host>`。如果阿里云从私有仓库拉取镜像,-还需成对填写 `REGISTRY_USERNAME` 和 `REGISTRY_PASSWORD`。--构建机需要 Go 1.26 或更高版本,以及带 Buildx 的 Docker。运行:+`HOST_IMAGE` 保持模板中的公共镜像地址即可。已有与该地址完全对应的 Ready 缓存时,+填写 `ECI_IMAGE_CACHE_ID` 后直接进入第 4 步;否则由部署者明确执行:```sh-./scripts/buildeci.sh prepare --env-file .env.eci+./scripts/buildeci.sh --env-file .env.eci```-`prepare` 构建 Linux AMD64 Host 镜像,用 `HOST_IMAGE` 打本地标签,推送到-`REGISTRY_PUSH_IMAGE`,再向阿里云申请镜像缓存。镜像已发布时,可用-`./scripts/buildeci.sh cache --env-file .env.eci` 跳过本地构建和推送。-两条命令都等待缓存进入 Ready,并将 ID 写回所选配置文件的 `ECI_IMAGE_CACHE_ID`。-[缓存配置与失败恢复](docs/deployment.md#eci-image-cache)+脚本使用本地 Controller 镜像中的缓存工具,让阿里云拉取公共 `HOST_IMAGE` 对应的 AMD64 镜像。+无需在本机构建、推送或下载 Host 镜像,也无需安装 Go 或登录镜像仓库。缓存进入 Ready 后,+工具自动将 ID 写回 `.env.eci` 的 `ECI_IMAGE_CACHE_ID`。制作缓存会使用阿里云计费资源。+工具直接使用公共 `HOST_IMAGE`,不需要镜像仓库凭证或额外的推送地址配置。+该命令只准备缓存,不启动 Controller、Redis 或账号 Host;失败或超时不会覆盖已有缓存 ID。+[接口参数、缓存配置与失败恢复](docs/deployment.md#cache-api-request)### 4. 启动 Controller 并打开账号@@ -252,22 +267,26 @@ OfficeCLI 提供 11 个原始 Skills,agent-browser 提供官方发现 Skill;./scripts/start.sh --env-file .env.eci```-脚本校验配置,然后用 Compose 启动 Controller 和 Redis。打开账号时,Controller 才会使用-指定缓存按需启动 ECI Host。+脚本校验配置,然后用 Compose 启动 Controller 和 Redis。随后在浏览器打开 Controller 地址,+创建或打开账号,Controller 才会直接使用 `HOST_IMAGE` 和 `ECI_IMAGE_CACHE_ID` 创建该账号的+ECI Host。仅制作缓存不会创建用户 Host。更新 Host 镜像时,先重新制作缓存并更新 ID,再替换实例。## 配置与检查-`start.sh` 读取指定配置文件,合并显式设置的部署环境变量,校验通过后才将覆盖值写回文件并启动。-显式传入空值会覆盖文件里的值。模型和网页搜索由用户在设置界面按账号配置;Gemini 生图等能力在插件详情中配置 API Key。+Controller 启动时读取并校验挂载的 `.env` 和 `configs/default.yaml`,直接用 Compose 启动也会检查。+普通部署修改 `.env` 即可。仓库中的 `start.sh` 还支持校验并保存 shell 环境覆盖,再启动 Compose;+它不会拉取或构建镜像。Controller 也会校验并保存显式传入容器的环境覆盖,显式空值会清空已保存值。+模型和网页搜索由用户在设置界面按账号配置;Gemini 生图等能力在插件详情中配置 API Key。用下面的命令检查 ECI 配置或运行环境:```sh-go run ./cmd/controller check --env-file .env.eci-go run ./cmd/controller doctor --env-file .env.eci+docker compose run --rm --no-deps controller check --env-file /config/.env --config /runtime.yaml+docker compose run --rm --no-deps controller doctor --env-file /config/.env --config /runtime.yaml```-检查本地 Docker 时把文件换成 `.env`。`check` 离线校验配置及必填项。+ECI 模式将 `/config/.env` 换成 `/config/.env.eci`。命令使用本地 Controller 镜像中的工具,+无需安装 Go 或先启动 Redis。`check` 离线校验配置及必填项。`doctor` 还会检查本地 Host 镜像或阿里云 Ready 镜像缓存。实际创建 Host、挂载存储,以及验证 Controller 到 Host 的连通性,发生在打开账号时。[配置字段](docs/configuration.md) · [故障排查](docs/troubleshooting.md)@@ -276,11 +295,11 @@ go run ./cmd/controller doctor --env-file .env.eci| 用途 | 在执行命令的机器上安装 || --- | --- |-| 用 `start.sh` 部署本地 Docker 或 ECI 模式 | Docker、Docker Compose 插件和 Bash。Go 可选,启动脚本可以在 Docker 里运行配置检查工具。 |-| 用 `buildeci.sh` 制作 ECI 缓存 | Go 1.26 或更高版本、Bash。使用 `prepare` 构建和推送镜像时还需要带 Buildx 的 Docker。 |+| Quickstart | Docker Engine 或 Docker Desktop、Docker Compose v2、curl 和 Bash。 |+| 运行 `start.sh` 或制作公共镜像的 ECI 缓存 | Docker、Docker Compose v2 和 Bash,先准备所需镜像;无需在本机安装 Go。 || 在 Docker 外开发 | 后端需要 Go 1.26 或更高版本,原生 Controller 需要 Redis,前端开发需要 Node.js 22.12+ 和 npm。 |-Compose 负责启动 Redis 并构建前端。Agent 使用的 Python、Node.js、Chromium 和通用文档环境已包含在 Host 镜像中;OfficeCLI 与 agent-browser 从插件市场安装。+Compose 负责启动 Redis 和内嵌前端的已发布 Controller。Agent 使用的 Python、Node.js、Chromium 和通用文档环境已包含在 Host 镜像中;OfficeCLI 与 agent-browser 从插件市场安装。## 开发与扩展diff --git a/build/Dockerfile.controller b/build/Dockerfile.controllerindex 33bce21..6ddfba9 100644--- a/build/Dockerfile.controller+++ b/build/Dockerfile.controller@@ -20,18 +20,20 @@ COPY --from=frontend-build /frontend/dist ./frontend/distFROM controller-source AS controller-compileARG CONTROLLER_GOOS=linux CONTROLLER_GOARCH=amd64RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \- CGO_ENABLED=0 GOOS=${CONTROLLER_GOOS} GOARCH=${CONTROLLER_GOARCH} go build -tags webui -trimpath -o /out/ ./cmd/controller ./internal/cmd/prepare-env+ CGO_ENABLED=0 GOOS=${CONTROLLER_GOOS} GOARCH=${CONTROLLER_GOARCH} go build -tags webui -trimpath -o /out/ ./cmd/controller ./internal/cmd/prepare-env ./cmd/buildeciFROM scratch AS controller-binaryCOPY --from=controller-compile /out/controller /controllerCOPY --from=controller-compile /out/prepare-env /prepare-env+COPY --from=controller-compile /out/buildeci /buildeciFROM controller-source AS controller-linuxARG TARGETARCHRUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \- CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -tags webui -trimpath -o /linux/ ./cmd/controller ./internal/cmd/prepare-env+ CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -tags webui -trimpath -o /linux/ ./cmd/controller ./internal/cmd/prepare-env ./cmd/buildeciFROM docker:29-cli AS controllerCOPY --from=controller-linux /linux/controller /usr/local/bin/controllerCOPY --from=controller-linux /linux/prepare-env /usr/local/bin/prepare-env+COPY --from=controller-linux /linux/buildeci /usr/local/bin/buildeciCOPY LICENSE THIRD_PARTY_NOTICES.md /usr/share/doc/go-bot/ENTRYPOINT ["/usr/local/bin/controller"]diff --git a/cmd/buildeci/config.go b/cmd/buildeci/config.goindex 2f1786f..d44043d 100644--- a/cmd/buildeci/config.go+++ b/cmd/buildeci/config.go@@ -7,21 +7,20 @@ import ("io""net/url""os"+ "regexp""strings""time""go-bot/internal/config"- "go-bot/internal/imagebuild""go-bot/thirdparty/aliyun""gopkg.in/yaml.v3")type options struct {- LocalImage string- Cloud aliyun.Credentials- Region string- Request aliyun.CreateImageCache- Wait time.Duration+ Cloud aliyun.Credentials+ Region string+ Request aliyun.CreateImageCache+ Wait time.Duration}type tuning struct {@@ -30,7 +29,9 @@ type tuning struct {Wait time.Duration `yaml:"wait_timeout"`}-func readOptions(profile, tuningPath string, publish bool) (options, error) {+var imageDigest = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)++func readOptions(profile, tuningPath string) (options, error) {c, err := config.Load("", profile)if err != nil {return options{}, err@@ -50,7 +51,7 @@ func readOptions(profile, tuningPath string, publish bool) (options, error) {if t.Wait <= 0 || (t.SizeGiB != 0 && t.SizeGiB < 20) || t.RetentionDays < 0 {return options{}, errors.New("buildeci requires positive wait_timeout, size_gib of at least 20 if set, and nonnegative retention_days")}- image := c.Registry.PushImage+ image := c.Runtime.Imageserver, name, qualified := strings.Cut(image, "/")last := name[strings.LastIndex(name, "/")+1:]_, tag, tagged := strings.Cut(last, ":")@@ -58,12 +59,9 @@ func readOptions(profile, tuningPath string, publish bool) (options, error) {u, urlErr := url.Parse("https://" + server)if !config.ValidImage(image) || !qualified || last == "" || urlErr != nil || u.User != nil ||u.Host != server || u.Hostname() == "" || !strings.ContainsAny(server, ".:") ||- (pinned && !imagebuild.ValidDigest(digest)) || (publish && pinned) ||- (!pinned && (!tagged || tag == "" || tag == "latest")) {- return options{}, errors.New("REGISTRY_PUSH_IMAGE must be a registry-qualified, versioned image; prepare requires an explicit tag")- }- if publish && (!config.ValidImage(c.Runtime.Image) || strings.Contains(c.Runtime.Image, "@")) {- return options{}, errors.New("HOST_IMAGE must be a valid local image tag")+ (pinned && !imageDigest.MatchString(digest)) ||+ (!pinned && (!tagged || tag == "")) {+ return options{}, errors.New("HOST_IMAGE must be a registry-qualified image with an explicit tag or SHA256 digest")}r := c.Runtime.ECIa := c.Cloud.Aliyun.Credentials@@ -75,21 +73,11 @@ func readOptions(profile, tuningPath string, publish bool) (options, error) {return options{}, fmt.Errorf("missing %s", field.name)}}- g := c.Registry- registryServer := ""- if g.Username != "" || g.Password != "" {- if strings.TrimSpace(g.Username) == "" || strings.TrimSpace(g.Password) == "" {- return options{}, errors.New("REGISTRY_USERNAME and REGISTRY_PASSWORD must both be set for a private registry")- }- registryServer = server- }return options{- LocalImage: c.Runtime.Image,- Cloud: aliyun.Credentials{AccessKeyID: a.AccessKeyID, AccessKeySecret: a.AccessKeySecret},- Region: r.Region, Wait: t.Wait,+ Cloud: aliyun.Credentials{AccessKeyID: a.AccessKeyID, AccessKeySecret: a.AccessKeySecret},+ Region: r.Region, Wait: t.Wait,Request: aliyun.CreateImageCache{Image: image, VSwitchID: r.VSwitchID, SecurityGroupID: r.SecurityGroupID,- RegistryServer: registryServer, RegistryUsername: g.Username, RegistryPassword: g.Password,SizeGiB: t.SizeGiB, RetentionDays: t.RetentionDays,},}, nildiff --git a/cmd/buildeci/main.go b/cmd/buildeci/main.goindex 64cd1fa..ea8c159 100644--- a/cmd/buildeci/main.go+++ b/cmd/buildeci/main.go@@ -13,13 +13,12 @@ import ("time""go-bot/internal/config"- "go-bot/internal/imagebuild""go-bot/thirdparty/aliyun")func run(args []string) error {- if len(args) == 0 || (args[0] != "prepare" && args[0] != "cache" && args[0] != "check") {- return errors.New("usage: buildeci prepare|cache|check [--env-file file] [--output json|cache-id]")+ if len(args) == 0 || (args[0] != "cache" && args[0] != "check") {+ return errors.New("usage: buildeci cache|check [--env-file file] [--output json|cache-id]")}command := args[0]f := flag.NewFlagSet("buildeci "+command, flag.ContinueOnError)@@ -36,7 +35,7 @@ func run(args []string) error {(*writeProfile && (*profile == "" || command == "check")) {return errors.New("invalid buildeci arguments")}- o, err := readOptions(*profile, *tuning, command == "prepare")+ o, err := readOptions(*profile, *tuning)if err != nil {return err}@@ -50,13 +49,7 @@ func run(args []string) error {}ctx, done := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)defer done()- var publish func(context.Context, string) (string, error)- if command == "prepare" {- publish = func(ctx context.Context, image string) (string, error) {- return imagebuild.PublishAMD64(ctx, o.LocalImage, image, os.Stderr)- }- }- out, err := execute(ctx, o, *state, *operation, client, publish, 3*time.Second)+ out, err := execute(ctx, o, *state, *operation, client, 3*time.Second)if err != nil {return err}diff --git a/cmd/buildeci/workflow.go b/cmd/buildeci/workflow.goindex ae70ee5..307c356 100644--- a/cmd/buildeci/workflow.go+++ b/cmd/buildeci/workflow.go@@ -14,7 +14,6 @@ import ("github.com/google/uuid""go-bot/internal/config"- "go-bot/internal/imagebuild""go-bot/internal/localstate""go-bot/thirdparty/aliyun")@@ -25,24 +24,21 @@ type cacheAPI interface {}type operation struct {- Token string `json:"clientToken"`- Image string `json:"image"`- Digest string `json:"digest,omitempty"`- CacheID string `json:"cacheId,omitempty"`- Publishing bool `json:"publishing,omitempty"`+ Token string `json:"clientToken"`+ Image string `json:"image"`+ CacheID string `json:"cacheId,omitempty"`}type result struct {- CacheID string `json:"cacheId"`- Image string `json:"image"`- Digest string `json:"digest,omitempty"`- Region string `json:"region"`- Platform string `json:"platform,omitempty"`+ CacheID string `json:"cacheId"`+ Image string `json:"image"`+ Digest string `json:"digest,omitempty"`+ Region string `json:"region"`}-func execute(ctx context.Context, o options, root, name string, api cacheAPI, publish func(context.Context, string) (string, error), interval time.Duration) (result, error) {+func execute(ctx context.Context, o options, root, name string, api cacheAPI, interval time.Duration) (result, error) {req := o.Request- identity, _ := json.Marshal([]any{o.Region, o.Cloud.AccessKeyID, req.Image, req.VSwitchID, req.SecurityGroupID, req.RegistryServer, req.SizeGiB, req.RetentionDays, name})+ identity, _ := json.Marshal([]any{o.Region, o.Cloud.AccessKeyID, req.Image, req.VSwitchID, req.SecurityGroupID, req.SizeGiB, req.RetentionDays, name})key := sha256.Sum256(identity)store, err := localstate.Open(filepath.Join(root, hex.EncodeToString(key[:16])))if err != nil {@@ -61,30 +57,9 @@ func execute(ctx context.Context, o options, root, name string, api cacheAPI, pureturn result{}, err}if _, err := uuid.Parse(op.Token); err != nil || op.Image != req.Image ||- (op.Digest != "" && !imagebuild.ValidDigest(op.Digest)) ||(op.CacheID != "" && !config.ValidImageCacheID(op.CacheID)) {return result{}, errors.New("invalid saved buildeci operation")}- if publish != nil && op.Digest == "" && op.CacheID == "" {- if op.Publishing {- return result{}, errors.New("previous image publication is uncertain; verify the registry, then use cache for a published image or choose a new version tag")- }- op.Publishing = true- if err := store.Write(filename, op); err != nil {- return result{}, err- }- digest, err := publish(ctx, req.Image)- if err != nil {- return result{}, fmt.Errorf("publish Host image: %w", err)- }- if !imagebuild.ValidDigest(digest) {- return result{}, errors.New("invalid published image digest")- }- op.Digest, op.Publishing = digest, false- if err := store.Write(filename, op); err != nil {- return result{}, err- }- }ctx, cancel := context.WithTimeout(ctx, o.Wait)defer cancel()if op.CacheID == "" {@@ -116,10 +91,8 @@ func execute(ctx context.Context, o options, root, name string, api cacheAPI, puif image != op.Image {return result{}, fmt.Errorf("image cache %s contains an unexpected image", op.CacheID)}- out := result{CacheID: op.CacheID, Image: image, Digest: op.Digest, Region: o.Region}- if op.Digest != "" {- out.Platform = "linux/amd64"- } else if _, digest, ok := strings.Cut(image, "@"); ok {+ out := result{CacheID: op.CacheID, Image: image, Region: o.Region}+ if _, digest, ok := strings.Cut(image, "@"); ok {out.Digest = digest}return out, nildiff --git a/cmd/buildeci/workflow_test.go b/cmd/buildeci/workflow_test.goindex e80f4f5..f4f2e0a 100644--- a/cmd/buildeci/workflow_test.go+++ b/cmd/buildeci/workflow_test.go@@ -5,10 +5,10 @@ import ("errors""os""path/filepath"- "strings""testing""time"+ "go-bot/internal/config""go-bot/thirdparty/aliyun")@@ -41,29 +41,20 @@ func fixture() options {}}-func TestPublishAndCacheRetryKeepsDigestAndClientToken(t *testing.T) {+func TestCacheRetryKeepsClientToken(t *testing.T) {o := fixture()api := &fakeCache{status: "Ready", loseResponse: true}dir := t.TempDir()- digest := "sha256:" + strings.Repeat("a", 64)- publishes := 0- publish := func(_ context.Context, image string) (string, error) {- publishes++- if image != o.Request.Image {- t.Fatal("wrong publication target")- }- return digest, nil- }ctx := context.Background()- if _, err := execute(ctx, o, dir, "default", api, publish, time.Millisecond); err == nil {+ if _, err := execute(ctx, o, dir, "default", api, time.Millisecond); err == nil {t.Fatal("create uncertainty should be reported")}- out, err := execute(ctx, o, dir, "default", api, publish, time.Millisecond)- if err != nil || out.CacheID != "imc-test" || out.Digest != digest || publishes != 1 ||+ out, err := execute(ctx, o, dir, "default", api, time.Millisecond)+ if err != nil || out.CacheID != "imc-test" ||len(api.tokens) != 2 || api.tokens[0] != api.tokens[1] {- t.Fatalf("retry did not reuse publication and operation: %v", err)+ t.Fatalf("retry did not reuse the cache operation: %v", err)}- if _, err := execute(ctx, o, dir, "default", api, publish, time.Millisecond); err != nil || len(api.tokens) != 2 {+ if _, err := execute(ctx, o, dir, "default", api, time.Millisecond); err != nil || len(api.tokens) != 2 {t.Fatalf("ready cache was not reused: %v", err)}}@@ -74,40 +65,31 @@ func TestWaitCanResumeAndNeverReturnsUnreadyID(t *testing.T) {api := &fakeCache{status: "Creating"}dir := t.TempDir()ctx := context.Background()- if out, err := execute(ctx, o, dir, "default", api, nil, time.Millisecond); err == nil || out.CacheID != "" {+ if out, err := execute(ctx, o, dir, "default", api, time.Millisecond); err == nil || out.CacheID != "" {t.Fatal("timed-out operation returned an unready cache")}api.status = "Failed"- if out, err := execute(ctx, o, dir, "default", api, nil, time.Millisecond); err == nil || out.CacheID != "" {+ if out, err := execute(ctx, o, dir, "default", api, time.Millisecond); err == nil || out.CacheID != "" {t.Fatal("failed operation returned a cache")}api.status = "Ready"- if out, err := execute(ctx, o, dir, "default", api, nil, time.Millisecond); err != nil || out.CacheID != "imc-test" || len(api.tokens) != 1 {+ if out, err := execute(ctx, o, dir, "default", api, time.Millisecond); err != nil || out.CacheID != "imc-test" || len(api.tokens) != 1 {t.Fatalf("resume did not reuse the saved cache: %v", err)}}-func TestBuildProfileCanOmitRuntimeOnlyCredentials(t *testing.T) {+func TestPublicCacheUsesOfficialImageWithoutRegistryCredentials(t *testing.T) {path := filepath.Join(t.TempDir(), ".env.eci")- profile := "HOST_IMAGE=go-bot/host:eci\nREGISTRY_PUSH_IMAGE=registry.example/host:v1\nECI_VSWITCH_ID=vsw-test\nECI_SECURITY_GROUP_ID=sg-test\nALIBABA_CLOUD_ACCESS_KEY_ID=fixture\nALIBABA_CLOUD_ACCESS_KEY_SECRET=fixture\n"+ profile := "ECI_VSWITCH_ID=vsw-test\nECI_SECURITY_GROUP_ID=sg-test\nALIBABA_CLOUD_ACCESS_KEY_ID=fixture\nALIBABA_CLOUD_ACCESS_KEY_SECRET=fixture\n"if err := os.WriteFile(path, []byte(profile), 0600); err != nil {t.Fatal(err)}- if _, err := readOptions(path, "", true); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(path, []byte(profile+"REGISTRY_USERNAME=user\nREGISTRY_PASSWORD=fixture\n"), 0600); err != nil {+ o, err := readOptions(path, "")+ if err != nil {t.Fatal(err)}- options, err := readOptions(path, "", true)- if err != nil || options.LocalImage != "go-bot/host:eci" ||- options.Request.Image != "registry.example/host:v1" || options.Request.RegistryServer != "registry.example" {- t.Fatalf("registry host was not derived from the push image: %v", err)- }- if err := os.WriteFile(path, []byte(profile+"REGISTRY_USERNAME=user\n"), 0600); err != nil {- t.Fatal(err)- }- if _, err := readOptions(path, "", false); err == nil {- t.Fatal("incomplete registry credentials were accepted")+ if o.Request.Image != config.DefaultHostImage {+ t.Fatal("public cache did not preserve the multi-platform image reference for anonymous pulling")}+}diff --git a/cmd/controller/main.go b/cmd/controller/main.goindex cb0ef53..7fba06d 100644--- a/cmd/controller/main.go+++ b/cmd/controller/main.go@@ -89,6 +89,11 @@ func run() error {if err := controller.ValidateWebDevOrigin(*webDevOrigin); err != nil {return err}+ if command == "serve" {+ if err := config.PrepareControllerProfile(*path, *envFile); err != nil {+ return err+ }+ }c, err := config.Load(*path, *envFile)if err != nil {return errdiff --git a/compose.yaml b/compose.yamlindex aad77ea..a39da70 100644--- a/compose.yaml+++ b/compose.yaml@@ -2,25 +2,23 @@ name: go-botservices:controller:- build:- context: .- dockerfile: build/Dockerfile.controller- image: go-bot/controller:local- command: ["serve", "--env-file", "/config/deployment.env", "--config", "/config/runtime.yaml"]+ image: ghcr.io/xyc999-ai/go-bot-controller:latest+ pull_policy: never+ command: ["serve", "--env-file", "/config/${GO_BOT_ENV_NAME:-.env}", "--config", "/runtime.yaml"]environment:REDIS_ADDR: redis:6379CONTROLLER_CONTAINER: "1"volumes:- /var/run/docker.sock:/var/run/docker.sock- type: bind- source: ${GO_BOT_ENV_FILE:-./.env}- target: /config/deployment.env- read_only: true+ # Mount the directory so valid overrides can be saved by atomic rename.+ source: ${GO_BOT_ENV_DIR:-.}+ target: /configbind:create_host_path: false- type: bindsource: ${GO_BOT_CONFIG_FILE:-./configs/default.yaml}- target: /config/runtime.yaml+ target: /runtime.yamlread_only: truebind:create_host_path: false@@ -31,11 +29,18 @@ services:depends_on:redis:condition: service_healthy+ healthcheck:+ test: ["CMD", "wget", "-q", "-T", "3", "-O", "/dev/null", "http://127.0.0.1:8080/readyz"]+ interval: 2s+ timeout: 4s+ retries: 30+ start_period: 5snetworks:- ingress- stateredis:image: redis:8-alpine+ pull_policy: nevercommand: ["redis-server", "--appendonly", "yes", "--appendfsync", "always"]ports:- "6379:6379"diff --git a/docs/configuration.md b/docs/configuration.mdindex f5ce6a3..5284691 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -1,6 +1,10 @@# Configuration-Run `./scripts/start.sh --init-env` once to create `.env` for Docker and+The [Quickstart installer](../README.md#quickstart) downloads the same Compose,+`.env.example` and `configs/default.yaml` used in the repository, creates only+`.env`, and pulls the images. Start with `docker compose up -d`.++In a source checkout, run `./scripts/start.sh --init-env` to create `.env` for Docker and`.env.eci` for ECI from [.env.example](../.env.example). Use`--docker-env-file PATH` and `--eci-env-file PATH` to customize the outputpaths. Initialization leaves existing files in place.@@ -12,8 +16,10 @@ configuration, and saves valid overrides atomically.Compose mounts the profile into Controller. Controller connects to Redis overthe internal Compose network at `redis:6379`. Compose publishes Controller onport 8080 and Redis on port 6379 on the Docker host's network interfaces.-The launcher runs the configuration tools with local Go when available, or-builds a Controller image to run them in Docker. `controller check` validates+The source launcher runs configuration tools in the existing local Controller+image. It never pulls or builds images and is independent of install.sh.+Controller also validates configuration on `serve`, so starting Compose directly+does not skip checks. `controller check` validatesthe profile offline. `controller doctor` also performs a read-only runtimepreflight. In ECI mode, `check` validates the cache ID format and `doctor`queries Alibaba Cloud for a usable cache. `buildeci` validates its own@@ -26,12 +32,24 @@ files, except for the root `.env.example` template. For other names, keepprivate profiles outside the checkout or under the ignored `.local/` directory.Create the directory first if passing a new path to `--init-env`.+Compose mounts the profile directory read/write at `/config` to allow atomic+profile replacement, and mounts `configs/default.yaml` read-only at `/runtime.yaml`.+Missing YAML fails startup. Controller reads the original profile directly;+Compose does not pass the entire profile as container environment variables.+`REDIS_ADDR` and `CONTROLLER_CONTAINER` are fixed container wiring. Compose's+automatic `.env` interpolation is not used to reconstruct application secrets.+Edit `.env` for ordinary Compose deployments, then restart Controller.+If you explicitly provide deployment variables in a container environment (for+example through a Compose override), Controller validates and persists them before+serving. The source `start.sh` similarly forwards explicit shell overrides to+its configuration tool. An explicit empty value clears the saved value.+## Runtime, storage and entry| Variable | Meaning | Default or requirement ||---|---|---|| `HARNESS_RUNTIME` | Runtime provider | `docker` or `eci`, default `docker` |-| `HOST_IMAGE` | Local Host build tag | Initialization sets `go-bot/host:local` for Docker and `go-bot/host:eci` for ECI |+| `HOST_IMAGE` | Host image reference | `ghcr.io/xyc999-ai/go-bot-host:latest`; Docker requires it locally. ECI cache creation and instance startup pass this same reference || `HARNESS_STORAGE` | Host filesystem | `container` by default. Docker automatically mounts an account volume. ECI uses the instance filesystem or can be set to `nas` || `NAS_MOUNT_TARGET` | Existing NAS mount target | Required for ECI with `nas` || `CONTROLLER_LISTEN` | Loopback address for a native Controller | `127.0.0.1:8080` |@@ -105,14 +123,18 @@ and previously published replies intact. There is no phone push requirement.|---|---|| `ALIBABA_CLOUD_ACCESS_KEY_ID` | Controller and buildeci, required for ECI || `ALIBABA_CLOUD_ACCESS_KEY_SECRET` | Controller and buildeci, required for ECI. The same pair is used with optional NAS |-| `REGISTRY_PUSH_IMAGE` | Full registry image reference for publishing or caching a Host image |-| `REGISTRY_USERNAME` | Private registry account for ECI cache creation, supplied with the password |-| `REGISTRY_PASSWORD` | Private registry password for ECI cache creation, supplied with the username |--`buildeci` takes the registry host from `REGISTRY_PUSH_IMAGE` and supplies-the username and password to Alibaba Cloud ECI to pull the private image.-The registry can be hosted by another provider. Local publication uses the-Docker CLI login.++`buildeci` passes the public `HOST_IMAGE` reference to Alibaba Cloud ECI without+registry credentials. It creates a cloud image cache, not a local image build or+registry push. Project image publication is a separate GitHub Actions workflow;+its automatic `GITHUB_TOKEN` is not a deployment credential.+When creating an ECI Host, Controller passes `HOST_IMAGE` and `ECI_IMAGE_CACHE_ID`+directly, without querying the cache to discover its image. Rebuild the cache and+update its ID when changing the image version. The explicit `doctor` command can+still inspect cache readiness as a diagnostic.+The template defaults to `latest`. A ready cache retains the image it was made+from even if that tag later moves. Use a new `buildeci --operation` name for an+intentional cache refresh; repeating the same operation resumes the old request.### Redis account storagediff --git a/docs/container-release-plan.zh-CN.md b/docs/container-release-plan.zh-CN.mdnew file mode 100644index 0000000..98a2be0--- /dev/null+++ b/docs/container-release-plan.zh-CN.md@@ -0,0 +1,237 @@+# GHCR 双镜像与 curl 安装方案++状态:代码已实现并通过本地验证;GHCR 首次发布及本次 ECI/NAS 云端验收尚未执行。保留本次收口后的职责与部署流程,验证结果见末尾。本方案替代此前「Controller 与 Host 合并成一个镜像」的设计。++## 1. 确定的部署形态++Controller、Host 分别构建和发布,保留 `build/Dockerfile.controller`、`build/Dockerfile.host`。Redis 使用官方镜像。++两种应用镜像分别发布为 GitHub Container Registry(GHCR)的两个公共容器包:go-bot-controller、go-bot-host;冒号后的标签表达版本。代码仍在现有 go-bot GitHub 仓库中,不需要另外创建两个源码仓库。[GHCR 官方说明](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)++| 镜像示例 | 包含内容 |+| --- | --- |+| `ghcr.io/xyc999-ai/go-bot-controller:latest` | Controller、内嵌 Web、prepare-env、buildeci、Docker CLI |+| `ghcr.io/xyc999-ai/go-bot-host:latest` | Go Harness Host、Node/Python/Chromium、Office/PDF 基础环境和插件资源 |+| `redis:8-alpine` | 官方 Redis |++使用当前 GitHub 账号 xyc999-ai 作为 namespace。首批镜像采用项目当前 v0.0.1 版本;新工作流需要先从审查后的源码手动发布该版本,再开放安装入口,不重打已有 Git 标签。++按当前 GitHub 官方政策,公共 Packages 免费,GHCR 容器镜像的存储与带宽当前也免费;这不包含阿里云资源费用,也不能把它理解为所有 GitHub Actions 资源都无限免费。[GitHub 计费说明](https://docs.github.com/en/billing/concepts/product-billing/github-packages)++Controller + Redis 由 Compose 启动。每个账号的 Host 仍由 Controller 动态创建,不加入该 Compose,也不嵌在 Controller 容器内部。++Docker 模式下 Controller 通过宿主机 Docker socket 管理平级 Host 容器;ECI 模式下调用阿里云 API。Host 不挂载 Docker socket,也不接收阿里云管理凭证。++## 2. 用户不需要克隆 GitHub 仓库++公开部署只需 Docker Engine / Docker Desktop、Docker Compose v2、curl 和 Bash,不要求 Git、Go、Node.js、Python。++普通 install.sh 只负责本地 Docker 安装,不包含 ECI 参数、云资源检查或镜像缓存制作。Quickstart 从 main 分支的脚本开始;URL 要在脚本合入 main 后才可使用:++```bash+curl -fsSL https://raw.githubusercontent.com/xyc999-ai/go-bot/main/scripts/install.sh | bash+cd go-bot+docker compose up -d+```++脚本默认准备当前目录下的 `go-bot/`,也允许指定 `--dir`。安装结束只完成准备,不自动启动服务、不创建用户 Host。用户直接执行 docker compose up -d,启动 Controller 和 Redis,然后打开 `http://localhost:8080` 使用 Web。该路径不调用仓库中的 start.sh,也不将其放入用户安装目录;配置校验由 Controller 启动入口负责。++脚本不下载整个源码仓库,也不拉取镜像包的全部标签。它直接下载仓库已有的部署文件,并准备所选版本、目标架构需要的镜像,不维护另一份安装专用 Compose。++## 3. 本地会生成什么++```text+go-bot/+├── compose.yaml+├── .env.example+├── .env+├── install.sh+└── configs/+ └── default.yaml+```++- `compose.yaml`:直接下载仓库根目录的同名文件,与源码目录使用完全相同的 Compose;统一调整为只使用 image、不含 build。Controller 镜像版本写明在文件中。+- `.env.example`:直接下载仓库模板,保留中英文注释和空白凭证。+- `.env`:仅在不存在时复制 .env.example 创建,权限 0600;普通安装不生成 .env.eci。+- `configs/default.yaml`:直接下载仓库的同名配置,保留 Compose 的 YAML 挂载及 Controller --config 读取行为。+- `install.sh`:留存安装脚本,供再次准备 Docker 镜像。++安装入口直接来自 main 分支,不通过 GitHub Release 附件分发。安装器从同一仓库 main 下载 compose.yaml、.env.example、configs/default.yaml,保留原始相对目录结构,普通用户不需要自己逐个下载。文件下载和校验完成后才生成缺失的 .env;下载失败时停止,不使用不完整文件继续安装。安装器选择的默认镜像版本必须是已发布并能匿名拉取的版本,不能因为 main 上有新提交就引用尚未发布的镜像。++私有 env 位于 compose.yaml 同级目录,使用现有字面 KEY=value 规则;不另建 config/.env。Compose 自动读取根目录 .env 用于插值,与 Go 直接读取该文件是不同过程:应用凭证不通过 Compose 插值重新组装。环境覆盖实现必须区分调用者显式设置的进程变量和 Compose 自动读入的文件值,不能把后者误判为覆盖值并写坏原文件。++再次安装不覆盖已有 .env、用户修改的 configs/default.yaml 或 Compose,也不删除数据卷;配置有问题时报告具体字段。涉及升级的镜像版本和部署文件需由维护者明确更新,安装器不提供隐式升级或删除操作。++普通公开部署不再要求执行 start.sh 或 start.sh --init-env;Docker 初始化由 install.sh 完成。仓库中的 scripts/start.sh 保留给维护者和源码使用者,但也统一改为消费已有镜像,不拉取、不构建。源码构建另用明确的开发命令,不再藏在启动流程中。ECI 配置初始化和准备流程放在 README 的独立 ECI 章节,不通过普通安装器承载。++### 本次同时修改的三个入口文件++install.sh 与 start.sh 是独立脚本,不互相调用,也不依赖对方执行。本次实施必须同时完成以下内容,不能只新增安装器而保留旧启动行为:++| 文件 | 本次修改职责 |+| --- | --- |+| scripts/install.sh(新增) | 下载仓库原始部署文件;由 .env.example 初始化缺失的 .env;拉取镜像并检查;不启动 Compose、不调用或分发 start.sh、不生成 .env.eci |+| scripts/start.sh(修改) | 保留仓库中的显式初始化、配置文件选择、覆盖校验、Compose 启动与就绪检查;初始化使用更新后的 .env.example;假设所需镜像已在本地,删除所有拉取及构建分支,包括无 Go 时构建 Controller 的回退,不依赖 install.sh |+| .env.example(修改) | 更新 HOST_IMAGE 为实际发布的 GHCR 引用及中英文注释;删除旧本地构建标签的默认描述;注释分别说明安装器和仓库启动脚本各自的使用方式,空白凭证规则保持不变 |++仓库 start.sh --init-env 可以保留此前明确生成 .env 和 .env.eci 的能力;普通 install.sh 只创建 .env。这是两个入口各自的行为,不要求为了安装器改变内部初始化命令的用途。start.sh 中 ECI 初始化的镜像引用也必须同步修正,不能继续硬编码旧的 go-bot/host:eci。++共用的 compose.yaml 同步改成公共 image 引用并去掉 build,继续读取 .env 与 configs/default.yaml。源码目录执行 start.sh 与安装目录直接执行 Compose,最终使用同一份 Compose 和 Controller 配置检查规则。++## 4. Docker 的默认配置++安装器完整复制 .env.example,不另行生成精简版模板。其中 Docker 默认生效的主要配置是:++```dotenv+HARNESS_RUNTIME=docker+HOST_IMAGE=ghcr.io/xyc999-ai/go-bot-host:latest+HARNESS_STORAGE=container+```++落地时同时调整仓库 .env.example 中的 HOST_IMAGE 及中英文注释、Go 默认镜像和相关启动检查,使其引用同一已发布 GHCR Host 版本,不再默认使用 go-bot/host:local。现有 ECI 初始化中硬编码 go-bot/host:eci 的替换也要更新:公共缓存路径使用同版本多架构公共引用;buildeci 不再承担自定义构建和推送。++改为 GHCR 后必须保留 ghcr.io/ 前缀,例如 ghcr.io/xyc999-ai/go-bot-host:latest;省略 registry 会指向 Docker Hub。即使镜像已经拉到本地,配置仍使用该完整引用,安装器不再生成另一套本地别名。此前省略 docker.io/ 的约定只适用于 Docker Hub。++不采用旧方案中的 `GO_BOT_IMAGE`,继续使用已有 `HOST_IMAGE`。Controller 和 Host 的默认引用均使用 latest;安装器分别准备配置所选镜像,不新增必须填写的 Controller 镜像环境变量。++其余基础配置保留在下载的 configs/default.yaml 中,用户无需编辑就能启动。它仍由 Compose 挂载并通过 --config 读取,仓库启动和安装目录启动使用相同逻辑。Go 内置默认值继续保留,但不因此删除现有 YAML 文件依赖。++模型端点、模型密钥、网页搜索和插件授权继续在用户页面配置、按现有机制存储,均不写进默认部署 env,也不编进公共镜像。++Compose 只保留 Controller、Redis 两个服务,沿用现有 8080:8080、6379:6379、Redis 数据卷和网络行为。Controller 使用匹配的角色镜像和 serve 命令,Host 使用现有 Host 入口。++## 5. 安装、检查与 Compose 启动如何配合++Docker 安装流程:++```text+检查 Docker / Compose / Docker Engine 是否可用+ → 创建目标目录,下载仓库原始 Compose、.env.example、configs/default.yaml+ → 仅在 .env 缺失时复制模板初始化,不生成 .env.eci+ → 读取配置、应用显式安装环境覆盖+ → 拉取选定版本的 Controller、Host 和 Redis 镜像+ → 使用 Controller 镜像内工具完成配置检查+ → 输出部署目录及 docker compose up -d 启动命令+```++安装脚本不执行源码构建,镜像拉取失败时明确退出,不切换为本地编译。发布 Compose 不配置 build,并对 Controller、Redis 设置 pull_policy: never,因此用户直接运行 docker compose up -d 也只使用已拉取的镜像。Controller、Redis 和 Docker Host 镜像应已由安装器拉取到本地,缺失时报错并提示重新准备。++仓库内部 start.sh 保留 --env-file、可选调优文件及配置检查、环境覆盖写回、启动和就绪检查;不运行 docker pull、docker build、compose build、up --build 或 go run。配置工具统一使用本地 Controller 镜像,不再按本机是否安装 Go 分两条路径,Compose 启动显式禁止构建和拉取。ECI 模式不检查本地 Host 镜像,但要求有效的缓存 ID;普通 start 不制作缓存。这些内部用法不进入 Docker Quickstart。++Host 不在 Compose 服务中,所以安装脚本必须单独准备 Host 镜像。Controller 创建 Host 时继续检查本地镜像并使用 `--pull=never`;缺失时提示重新运行安装器准备,避免每个账号启动都临时联网拉取。++Controller 自身启动时仍执行完整配置检查,因此即使跳过安装器直接运行 Compose,错误配置也不会被忽略。安装检查完成后,真正的服务健康状态由 Compose healthcheck / ready 检查确认,不把「镜像下载成功」称为「服务已经启动」。++目前 Controller 的 Config.Load 以指定 env 文件为准,不会自动因为 Compose 设置了某个同名环境变量就覆盖它。因此落地时在 Controller serve 的 Go 启动入口复用现有配置准备函数:读取文件 → 应用已知进程环境覆盖 → 完整校验 → 将有效覆盖原子保存 → 启动 Controller。不增加另一份配置状态,也不需要进程管理器。++仓库和安装目录共用的 Compose 默认读取同级 .env 及 configs/default.yaml,Redis 地址和容器标记由 Compose 固定提供。部署配置目录可写绑定到 /config,以支持覆盖值的原子保存;Controller 默认读取 /config/.env。configs/default.yaml 单独只读绑定到 /runtime.yaml 并通过 --config 读取。两处始终使用同一套挂载声明,不由安装器重写路径或生成不同 Compose。++共用 Compose 仅提供 REDIS_ADDR 和 CONTROLLER_CONTAINER,不使用 env_file、`${SECRET}` 或无值 environment 条目重新传入部署凭证。普通用户编辑挂载的 .env;start.sh 和 install.sh 的配置工具只转发宿主进程中显式存在的已知字段。若用户通过自定义 Compose override 或 docker run -e 显式传入 Controller 进程环境,serve 会校验并保存。不能假定 HOST_IMAGE=... docker compose up 会自动透传任意 shell 变量;这样也避免把 Compose 自动解析的 .env 值误判为显式覆盖。++用户修改磁盘上的私有文件后,显式重启 Controller 才按新配置运行;不新增配置监控或后台热更新。进程环境设置发生变化时需要重建容器,不能只用 docker compose restart 期望获得新的进程环境。++### 当前实现与新方案的配置传递区别++当前 scripts/start.sh 先用 prepare-env 读取指定 profile,将已识别的显式进程环境变量覆盖并保存到该文件,再运行 controller check;之后启动 docker compose --env-file /dev/null up -d --build --wait。GO_BOT_ENV_FILE 只告诉 Compose 要挂载哪个文件。Compose 将该文件只读挂载到 /config/deployment.env,Controller 通过 --env-file /config/deployment.env 调用 Go Config.Load 读取。部署配置没有整体注入 Controller 的进程环境,Compose environment 当前只有 REDIS_ADDR 和 CONTROLLER_CONTAINER。++新方案继续以挂载文件作为持久配置来源,并让 Controller 的启动入口自己完成环境覆盖与保存,直接运行 Compose 就具备完整启动检查,不依赖 start.sh。Compose 的 --env-file(插值来源)、服务 env_file(容器进程环境)和挂载后传给 controller --env-file(Go 读取文件)是三件不同的事;本方案采用最后一种,另显式透传允许覆盖的进程环境变量。++挂载本身声明在 compose.yaml 的 services.controller.volumes 中,由 Docker Compose 创建容器时交给 Docker Engine 执行,并非 start.sh 额外执行一条复制或挂载命令。当前 source: ${GO_BOT_ENV_FILE:-./.env}、target: /config/deployment.env 表示将宿主机选中的文件绑定到容器内路径;command 中的 --env-file /config/deployment.env 再告诉 Controller 去读取该路径。即使不设置 GO_BOT_ENV_FILE,Compose 也会使用默认来源 ./.env。统一后的 Compose 同样默认选取根目录 .env 与 configs/default.yaml,保留这两个配置来源,不依赖 start.sh 补充必填路径。++## 6. 多架构发布++Controller 和 Host 的普通版本标签均提供 `linux/amd64` 与 `linux/arm64`。Docker 会按目标 Docker Engine 的架构自动选择,用户不必手动填写平台。[Docker 多平台说明](https://docs.docker.com/build/building/multi-platform/)++不提供 ECI 专用的 -amd64 tag。各架构构建结果按 digest 暂存,全部成功后汇总成同一版本的多架构清单。ECI 使用与 Docker 相同的镜像引用,由云端的默认 AMD64 环境选择匹配产物;本机架构不会影响云端拉取。++默认安装使用 latest,Controller 与 Host 保持一致;用户可自行指定明确版本。发布流程提供版本 tag 和 latest;Git 标签触发发布时更新 latest,手动补发旧版本可关闭 update_latest。latest 不自动比较语义版本号,不会更新已有 ECI 缓存或运行容器。++main 的安装入口启用前必须完成两种角色、两种架构的首次发布及 latest 公开拉取检查。后续所有架构构建成功后才汇总版本并更新 latest。安装脚本直接从 main 获取,无需上传到 Release;普通 PR 不向 GHCR 推送镜像。++### GHCR 发布权限与公开检查++GitHub Actions 使用自动生成的 GITHUB_TOKEN 发布,并给构建任务配置 contents: read、packages: write;无需再为发布镜像维护 Docker Hub 账号、Docker Hub 推送令牌或长期个人 PAT。安装脚本分发不依赖 Release 附件任务。[GitHub 官方发布流程](https://docs.github.com/en/actions/tutorials/publish-packages/publish-docker-images)++两种镜像均关联现有 xyc999-ai/go-bot 代码仓库,并设置源码、版本、revision、MIT License 等 OCI 标签。++首次发布的容器包默认是 private,源码仓库 public 不代表容器包自动 public。首发时必须将两个包的可见性明确设为 public,再从没有登录 GHCR 的环境验证拉取成功;之后才向用户发布安装入口。[GHCR 可见性与关联规则](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)++## 7. ECI 使用公共镜像时需要什么++公共 Host 镜像可以直接用于 ECI 镜像缓存,不需要用户在本地构建或向自己的镜像仓库推送。++| 配置 | 公共镜像方案中的要求 |+| --- | --- |+| 阿里云 AccessKey ID + Secret | 需要,供查询缓存、制作缓存和管理 ECI |+| Region、vSwitch、安全组 | 需要正确的用户云资源配置,不是镜像仓库凭证 |+| ECI_IMAGE_CACHE_ID | 需要;制作缓存成功后自动写回 |+| HARNESS_STORAGE | 默认 container,可选择 nas |+| NAS_MOUNT_TARGET | 仅 nas 模式必填 |+| HOST_IMAGE | 唯一镜像地址参数,模板预填公共 Host 镜像;本地 Docker 和云端缓存共用此引用 |+| GHCR 拉取令牌 / 登录 | 公共镜像不需要 |+| GHCR 发布令牌 | 部署用户不需要,项目 Actions 使用 GITHUB_TOKEN |++不提供镜像仓库账号、密码或第二个推送地址参数。buildeci 只负责让阿里云从公共 HOST_IMAGE 制作缓存,不读取本地 Host 镜像、不构建、不推送。项目镜像的构建和发布完全交给独立 GitHub Actions;维护者的自动 GITHUB_TOKEN 不进入用户部署配置。++## 8. ECI 的用户操作流程++ECI 在中英文 README 中单独说明,不出现在普通 install.sh 的参数或 Quickstart 分支中。沿用明确初始化 ECI 配置 → 填写云资源 → 制作缓存 → 启动 Controller 的独立流程。源码目录操作示例:++```bash+./scripts/start.sh --init-env+# 在 .env.eci 中填入阿里云凭证、地域及已有网络资源,按需选择 NAS。+# 按该版本的说明准备 Controller 和 Redis 公共镜像。+./scripts/buildeci.sh cache --env-file .env.eci+./scripts/start.sh --env-file .env.eci+```++独立 ECI 流程使用现有 .env.eci 和 --env-file 选择机制;普通 Docker 安装器只从 .env.example 生成同级 .env。配置文件不存在时启动和缓存脚本都直接报错,不自动初始化。缺少必要值时明确提示具体字段,不能声称已经可以启动。++ECI 配置中的 HOST_IMAGE 默认是该发行版的公共多架构 Host 镜像。ECI 文档指导在 Controller 机器准备 Controller、Redis 镜像;云侧缓存制作过程拉取 AMD64 Host,不要求本机再下载一份大 Host 镜像。++独立 buildeci.sh cache 是显式请求创建云资源的步骤:++1. 检查缓存制作所需的阿里云凭证与网络字段;此阶段不要求已有缓存 ID。NAS 等 Host 运行配置由 Controller 启动时检查。+2. 通过 Controller 镜像内的 buildeci 工具执行缓存操作,不依赖用户本机 Go。+3. 缓存来源直接为 HOST_IMAGE,保留完整 ghcr.io 地址;将该引用交给云 API 匿名拉取,用于后续缓存核对,不请求仓库凭证。+4. 等待缓存 Ready,自动把 ECI_IMAGE_CACHE_ID 保存回 --env-file 指定文件,默认 .env.eci;沿用现有缓存操作记录目录。+5. 输出写回的缓存 ID;随后由用户启动 Controller,执行完整运行配置检查。++制作缓存时不会启动 Controller、Redis 或用户 Host。已有 Ready 缓存的部署者可以填写其 ID 后直接启动;普通安装、start.sh 和 Compose up 都不自动创建付费镜像缓存。buildeci.sh 使用已有 Controller 镜像中的 buildeci 二进制完成公共缓存流程,不再要求本机安装 Go。++ECI driver 创建实例时直接传入 HOST_IMAGE 与 ECI_IMAGE_CACHE_ID,不再从缓存详情查询镜像地址;用户修改镜像后重新制作缓存并更新 ID。保留 ImagePullPolicy=Never 和明确指定缓存,不自动退回其他镜像来源。显式 doctor 诊断命令仍可检查缓存状态。NAS / 非 NAS 挂载与数据语义不变。++buildeci 仅保留 cache 和离线 check,不提供本地构建、推送或私有镜像认证分支。用户自行更改源码或镜像变量不属于默认部署流程。++ECI 拉取公共镜像仍需要可达 GHCR 的云端网络。已有 NAT 网关时不新增强制 EIP 参数;若 GHCR 在目标网络不可达,可把同版本 AMD64 镜像复制到可达仓库后制作缓存,无需重新编译。[阿里云网络要求](https://www.alibabacloud.com/help/en/eci/user-guide/manage-an-image-cache)++项目镜像换到 GHCR 不代表所有拉取都离开 Docker Hub:Redis 仍用官方 redis:8-alpine,源码构建的基础镜像也仍可能来自 Docker Hub。++## 9. 后续重复运行与升级++重新运行安装器默认保留已有用户配置和数据。升级时明确更新共用 Compose、配置中的版本引用,并准备匹配的 Controller / Host 镜像;安装器本身不改写已有部署文件,不自动删除运行中的 Host 或清理数据卷。++Compose 重建 Controller 不会更新已经存在的独立 Host。Docker 的 stop/start 也不会切换原容器镜像;需要新版本 Host 时按既有显式删除运行实例、保留账号卷、重新创建的流程操作。ECI 则按新 Host 版本准备缓存,再切换 ID 并明确替换实例。++Redis 数据卷、每账号 Docker 卷和 NAS 路径保持现有命名。非 NAS ECI 中的数据依然按原本的临时存储语义处理,不额外承诺保留。++## 10. 实施范围与验收++- 保留两个 Dockerfile,在 Controller 镜像补齐 buildeci 和发布启动入口,不给 Host 加入 Controller 或 Redis。+- 新增从 main 直接下载的 Docker 专用 scripts/install.sh;直接下载仓库同一份 compose.yaml、.env.example、configs/default.yaml,只初始化同级 .env,不生成 .env.eci,不向安装目录分发 start.sh。仓库 Compose 统一去除 build,start.sh 另行去除构建和拉取,不要求本机 Go;保留原始 YAML 配置读取链路。+- 默认配置自动本地生成,带中英文注释;不包含仓库认证和额外推送地址字段。+- 适配缓存工具读取公共 Host 来源、配置写回和预缓存/正式启动两种检查时机。+- 更新现有 CI 的部署 smoke 与角色镜像输入,新增发版推送流程,不扩展无关严格测试,也不调用真实模型或云资源作为普通 CI。+- 更新 .env.example、Go 默认镜像、ECI 初始化引用及相应检查,避免仍指向旧本地标签。+- 独立验证两个入口:安装器从空目录下载、初始化并拉取成功;未运行安装器的源码目录也能在镜像已准备好时通过 start.sh 初始化和启动。用缺失镜像场景确认 start.sh 明确报错,不发生隐式拉取或构建。+- 更新中英文 README、GHCR 包说明;Quickstart 只讲 curl 安装 + docker compose up -d,ECI 独立说明配置、准备镜像、制作缓存和启动步骤。++验收应从没有源码、没有 Go / Node / Python 的目录开始:Docker 默认安装不填密钥即可打开 Web;AMD64/ARM64 均选择正确镜像;Host 可以动态创建;重新执行不会覆盖配置;ECI 不要求仓库凭证,缺阿里云凭证报错,缓存 Ready 后正确写回 ID。整个过程中不依赖当前开发电脑的镜像、缓存或私有文件。++## 11. 本地实施与验证结果++已完成独立安装器、共用 Compose、仓库启动脚本与模板改造;Controller 自行校验并保存显式容器环境覆盖,原子替换保留原文件归属。ECI cache 只读取 HOST_IMAGE,不拼接架构后缀;工具已纳入 Controller 镜像,旧的本地构建、推送、仓库认证参数及实现已移除。++本地通过 make test vet check、ARM64 两个完整镜像构建及 Host smoke、安装器和独立 start 的真实容器启动、双账号 Host / Redis 生命周期、Web Docker 集成、AMD64 四个 Go 入口交叉编译,以及 actionlint / Compose 静态检查。安装器测试通过本地 HTTP 文件和本地镜像模拟分发端,不冒充已发布 GHCR 的匿名下载验收。++还需在远端发布工作流运行后将两个 GHCR 包设置为 Public,并完成匿名拉取检查;ECI/NAS 本次未调用真实云服务。首发使用审查后的源码手动发布 v0.0.1,不移动既有 Git 标签。详见 [部署与首发操作](deployment.md#publishing-project-images) 与 [验证记录](validation.md#ghcr-deployment-workflow-2026-11-23)。diff --git a/docs/deployment.md b/docs/deployment.mdindex 377df8d..e401f13 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -2,30 +2,49 @@## Default local Docker-Start Docker with Docker Compose. Run from the repository root.+Install Docker with Compose v2, curl and Bash. No source checkout is required.```bash-./scripts/start.sh --init-env-./scripts/start.sh+curl -fsSL https://raw.githubusercontent.com/xyc999-ai/go-bot/main/scripts/install.sh | bash+cd go-bot+docker compose up -d```-Initialization creates `.env` and `.env.eci`. The launcher requires an-existing profile and reads `.env` by default. Every Docker launch builds the-Host image locally with the `HOST_IMAGE` tag and starts Controller and Redis-with Compose. Open http://127.0.0.1:8080 and-create an account by name and add a model endpoint in Model settings. Add a DeepSeek search API key in Web search settings to enable searching. Opening an account starts or-reconnects its Host. You can also prepare `.env`, build the Host image-with `make image` and run `docker compose up -d --build`.--The Host image, including its tools and bundled skills, is built from-`build/Dockerfile.host`. Compose builds the Controller and its embedded Web UI-from `build/Dockerfile.controller` and runs the published `redis:8-alpine` image.+Use `bash -s -- --dir /path/to/go-bot` after the pipe to select another directory.+The installer downloads the original repository Compose, `.env.example` and+`configs/default.yaml`, creates only `.env`, and pulls the Controller, Host and+Redis images. It preserves existing configuration and does not start services.+The installed Compose is identical to the repository file. Both use published+images with `pull_policy: never`; neither startup nor the source launcher+implicitly pulls or builds. Open http://localhost:8080, create an account and+configure its model endpoint in Settings. Opening an account starts or reconnects+its independent Host. Search providers and plugin credentials are configured in+the UI, not in the deployment template.++The published Host is built from `build/Dockerfile.host`; Controller and its+embedded Web UI are built from `build/Dockerfile.controller`. Both have AMD64 and+ARM64 variants selected automatically by Docker. Redis uses `redis:8-alpine`.[Host Dockerfile](../build/Dockerfile.host) · [Controller Dockerfile](../build/Dockerfile.controller) · [Compose](../compose.yaml)-Go Bot uses a separate Compose project, Redis volume, and Host storage from-Go Harness. To switch on the same machine, stop the old deployment so its-ports are free, then initialize fresh environment profiles for Go Bot. Keep-the old profiles and storage separately if you need the previous deployment.+### Source checkout++The repository launcher is independent of install.sh. First explicitly pull+the images (or deliberately build them with `make image image-controller`), then:++```bash+docker pull ghcr.io/xyc999-ai/go-bot-controller:latest+docker pull ghcr.io/xyc999-ai/go-bot-host:latest+docker pull redis:8-alpine+./scripts/start.sh --init-env+./scripts/start.sh+```++Initialization creates `.env` and `.env.eci` without overwriting either file.+`start.sh` requires an existing selected profile, defaults to `.env`, applies+validated shell overrides and starts the same Compose stack. It reports missing+local images instead of pulling or building. Checks use tools in the Controller+image, so no local Go is required. Compose also validates on Controller startup,+independently of this script.```bash./bin/controller check@@ -81,10 +100,10 @@ for RAM, VPC, security-group and NAS setup.Run `./scripts/start.sh --init-env` to create both profiles. Edit the ECIprofile and fill in the shared Alibaba AccessKey pair, region, vSwitch-and security group. For cache creation, set `REGISTRY_PUSH_IMAGE` to a registry-qualified-reference with a unique version tag. If the registry requires authentication,-set `REGISTRY_USERNAME` and `REGISTRY_PASSWORD` for the ECI pull. The registry-host is derived from the image reference. The publish command uses the current Docker login.+and security group. Pull the published Controller and Redis images first, as in+the ECI README walkthrough. The public `HOST_IMAGE` is the only image-address setting. The+cache tool preserves that multi-platform reference; Alibaba Cloud pulls it for+its default AMD64 environment.```bash./scripts/buildeci.sh@@ -93,24 +112,64 @@ host is derived from the image reference. The publish command uses the current DBefore starting Controller, set `HARNESS_RUNTIME=eci` in the same profile.Configure search per account in the Web UI after deployment. The default-`prepare` mode builds and publishes a Linux AMD64 Host image, creates the ECI+`cache` mode uses the tool inside the local Controller image, creates an ECIcache, waits for `Ready` and writes `ECI_IMAGE_CACHE_ID` into the profile.-Use `./scripts/buildeci.sh cache` for a prepublished image. Both modes use-`.env.eci` by default and accept `--env-file PATH`. The script reports an error if the selected+It does not build or push, and needs no local Go. The script uses+`.env.eci` by default and accepts `--env-file PATH`. The script reports an error if the selectedprofile is missing. Cache creation provisionsAlibaba Cloud resources. See [Alibaba Cloud cache billing](https://www.alibabacloud.com/help/en/eci/product-overview/image-caches).+There is no separate registry credential, push-address or local-publication path+in `buildeci`. The cloud pulls from the configured public reference directly.+Project image publication is handled by the GitHub Actions workflow below.++### Cache API request++The script starts a temporary tool container from the local Controller image;+it does not start the Controller service. The Go command reads the selected+profile and calls the Alibaba Cloud Go SDK's `CreateImageCache` operation+(ECI API version `2018-08-08`, endpoint `eci.<ECI_REGION>.aliyuncs.com`).++| API parameter | Source in this project |+| --- | --- |+| `RegionId` | `ECI_REGION`, default `cn-hangzhou` |+| `Image.1` | `HOST_IMAGE`; one public, multi-platform Host image reference |+| `VSwitchId` | `ECI_VSWITCH_ID` |+| `SecurityGroupId` | `ECI_SECURITY_GROUP_ID` |+| `ImageCacheName` | Generated as `go-bot-` plus the first eight characters of the operation UUID |+| `ClientToken` | Generated UUID, saved locally and reused when retrying the same operation |+| `ImageCacheSize` | Optional `size_gib` in cache tuning YAML; omitted when zero |+| `RetentionDays` | Optional `retention_days` in cache tuning YAML; omitted when zero |++The shared AccessKey ID and Secret authenticate SDK requests; they are not+image registry credentials. The tool sends no registry authentication, EIP,+NAS mount or account Host configuration in this request. With the selected+vSwitch covered by NAT, Alibaba Cloud can pull the public image directly.++Alibaba Cloud creates an intermediate ECI instance and disk, pulls the image,+and prepares the cache snapshot. The client does not run `docker build` or+upload a local Host image. The platform defaults are 20 GiB and no expiry when+size/retention are omitted. [CreateImageCache API](https://help.aliyun.com/zh/eci/developer-reference/api-eci-2018-08-08-createimagecache)++The client calls `DescribeImageCaches` with `RegionId` and `ImageCacheId` every+three seconds until Ready (up to 90 minutes by default). It then atomically+updates only `ECI_IMAGE_CACHE_ID` in the selected profile. Failure or timeout+does not replace that saved value. [DescribeImageCaches API](https://www.alibabacloud.com/help/en/eci/developer-reference/api-eci-2018-08-08-describeimagecaches)+The default wait is 90 minutes. Set `wait_timeout` in the YAML passed with`--config` to adjust it. Rerun the same operation after a timeout or lostcreate response to resume the saved cache operation.Use `./scripts/buildeci.sh cache --operation <new-name>` to-create a replacement cache for the same published image. Build and cache-outputs include the image reference and any known digest. Use a new-version tag for every publication.+create a replacement cache for the same published image. Cache output includes+the image reference and a digest when the input is digest-pinned.+This also applies after `latest` has moved: use a new operation name for an+intentional refresh. Repeating the same operation resumes or reuses its saved+cache; it is not an implicit update of the cached image.You can set an existing Ready `ECI_IMAGE_CACHE_ID` directly and start the-controller without running `buildeci`. The ECI driver resolves the cache's-single Host image and configures cache-only startup. The launcher checks+controller without running `buildeci`. Set `HOST_IMAGE` to the exact image used to+make that cache. ECI creation passes the configured image and cache ID directly,+with cache-only startup; it does not query the cache for its image address. The launcher checksconfiguration before Compose starts. Run `controller doctor --env-file .env.eci`to check Alibaba Cloud access and cache readiness before opening an account.The controller needs@@ -120,8 +179,8 @@ needs outbound internet access, cover its vSwitch with a NAT gateway SNAT rule.[Alibaba Cloud ECI networking](https://www.alibabacloud.com/help/en/eci/user-guide/enable-internet-access)For persistent NAS set `HARNESS_STORAGE=nas` and `NAS_MOUNT_TARGET` to an-existing mount target hostname. Create `/go-bot/<userId>` on NAS and allow-the Host to write to it before opening that account. The driver mounts it at+existing mount target hostname. Each account uses writable `/go-bot/<userId>`+storage on NAS. The driver mounts it at`/root/harness`. Session journals live at`<nasPath>/.dsh/sessions/<project-key>/<session-id>/session.v4.jsonl`.Schedules, attachments and user skills share that account's NAS directory.@@ -133,6 +192,43 @@ ECI container storage uses the writable layer for the lifetime of the instance.See [validation](validation.md) for real Docker coverage and the remainingcloud checks.+## Publishing project images++[Publish container images](../.github/workflows/publish-images.yml) runs only+for pushed Git tags matching `v*`, or through **Actions → Publish container+images → Run workflow** with a version such as `v0.0.1`. Normal commits and PRs+run CI validation without publishing images. Manual publication builds the+selected ref; choose the intended source commit/branch before running it.++The workflow builds each role on native AMD64 and ARM64 runners and publishes+the Controller and Host artifacts by digest. Only after all builds succeed does+it combine them into each role's multi-platform `<version>` and `latest` tags.+No architecture-specific tag is required for ECI. `latest` is a mutable alias, not an automatic Docker version calculation.+The deployment defaults use `latest` for both Controller and Host. Users can+choose version tags when they want a fixed release. Treat published version tags+as immutable; use a new version for changed source. Updating a registry tag does+not replace running containers or update an existing ECI cache.+Git-tag publication updates `latest`. For manual backfills, disable **update_latest**+to publish the chosen version without moving `latest` backwards; the workflow does+not infer semantic-version ordering.++GitHub Actions authenticates with its automatic `GITHUB_TOKEN` and+`packages: write`; maintainers do not need a Docker Hub account or additional+registry secrets. On first publication, both GHCR packages default to private:+open each package's **Package settings → Change visibility → Public**, then+rerun the manifest job's anonymous-access check. Source repository visibility+does not set package visibility. Confirm anonymous pulls before advertising the+installation command. [GHCR documentation](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)++For the initial release, manually publish `v0.0.1` from the reviewed implementation+before exposing its installer on main. Subsequent releases publish the version+and promote `latest` after all architecture builds succeed. Keep the shared+Compose, `.env.example`, Go defaults and documentation consistent when deployment+behavior changes. The installer downloads these files directly from main;+it is not a Release attachment. Existing installations keep their files on a+repeat install; upgrades require deliberately updating the files and preparing+the new images. Pulling a new image alone does not replace an existing Host.+## Plugin and image dependenciesThe base Host supplies Go, Node/npm/pnpm, Python, Chromium, LibreOffice and generaldiff --git a/docs/providers.md b/docs/providers.mdindex 4d3fbcd..6da63ed 100644--- a/docs/providers.md+++ b/docs/providers.md@@ -30,7 +30,7 @@ ECI supports neither. For ECI, the Controller attempts authenticated Hostshutdown, then deletes the instance and waits for the runtime to confirm release.For providers with a separate image preparation step, add a command under-`cmd/build<provider>`. It can reuse `internal/imagebuild` for image publication.+`cmd/build<provider>`. Keep cloud cache preparation separate from project image publication.The runtime driver consumes the prepared artifact through its own configuration.## Language modelsdiff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex fb93881..6157ac2 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -2,7 +2,7 @@| Symptom | Check/action ||---|---|-| Deployment profile is missing | Run `./scripts/start.sh --init-env`, then select `.env` for Docker or `.env.eci` for ECI |+| Deployment profile is missing | Run install.sh for Docker. In a source checkout, run `./scripts/start.sh --init-env` and select the intended profile || ECI startup lists missing credentials or cache ID | Check the selected ECI profile. An explicitly empty process environment value overrides the saved value. Use `buildeci.sh` to create a cache or supply an existing Ready cache ID || Host must be started by Controller | Open the account through Controller to start its Host || Host configuration changed | Use explicit host delete, then start; use external storage if data must survive |@@ -12,7 +12,9 @@| Browser frontend CORS blocked | Open the UI from the Controller URL. For Vite, set the Controller’s exact loopback `--web-dev-origin` || POST failed after a disconnect | Read history/events before deciding to submit again; controller intentionally does not replay uncertain sends || Stop Host could not confirm ECI release | Check the reported cloud error and retry Stop Host. ECI instance storage lasts until release |-| Docker Host image missing | Run `./scripts/start.sh` with the Docker profile to build its configured local tag |+| Docker Host or Controller image missing | Rerun install.sh or explicitly `docker pull` the configured image. Neither Compose nor start.sh builds or pulls at startup |+| `/runtime.yaml` mount fails | Ensure `configs/default.yaml` exists beside the deployment's Compose file; install.sh downloads it from the repository |+| GHCR pull is denied | Maintainers must publish both packages and set each to Public. A public source repository does not make its images public || HTTPS build fails behind private CA | Use Docker BuildKit secret build_ca with your trusted CA; certificate verification remains enabled |Use `controller check` for offline configuration validation, `controller doctor`diff --git a/docs/validation.md b/docs/validation.mdindex ca1348f..ecc13ac 100644--- a/docs/validation.md+++ b/docs/validation.md@@ -44,7 +44,7 @@ versions; these observations are not a promise to reproduce every Debian byte.## Reproduce locally```bash-make build image+make build image image-controllermake test vet checkmake race./scripts/smoke-image.sh@@ -84,6 +84,37 @@ containers.Fake cloud tests establish request construction and orchestration behavior,not Alibaba account permissions, network reachability or actual NFS guarantees.+## GHCR deployment workflow, 2026-11-23++- `make test vet check` passed. The public-cache configuration test verifies that+ the unchanged multi-platform `HOST_IMAGE` is used directly. Registry credential+ fields and local image build/push commands are no longer deployment features.+ ECI driver tests verify direct image/cache-ID forwarding with zero cache-detail+ queries during creation; the optional `doctor` path still checks cache readiness.+- Built the complete Linux ARM64 Controller and Host images. Controller contains+ Web UI, Docker CLI, `prepare-env` and `buildeci`. The Host environment/plugin+ image smoke passed. All four Go entry points cross-compiled for Linux AMD64;+ this run did not execute complete AMD64 images on native hardware.+- `scripts/test-install.py` passed using local HTTP copies of the actual repository+ files and real image tools. It covered an empty directory, byte-identical Compose+ and YAML, only `.env` initialization, mode 0600, repeat installation, literal+ credential values, shell/container overrides, preservation of file ownership,+ failed download and missing-image errors. Direct Compose and the independent+ source launcher each started real Controller/Redis containers on isolated ports.+ The test replaces registry pulls with local image checks: it does not establish+ that a public GHCR release already exists.+- `scripts/smoke-cli.py` passed with real Docker/Redis: two isolated account Hosts,+ session/model storage, Controller recreation, Redis restart, stop/resume and+ release. `TestDockerWebChatPreview` passed against the local published-name Host+ image. No paid model calls or existing service restarts were needed.+- `actionlint` and Compose configuration validation passed. The image publisher is+ separate from ordinary CI and supports Git-tag/manual publication, native+ architecture builds, digest-based manifest assembly, optional manual `latest`+ promotion and anonymous registry inspection.+- Remote workflow execution, first GHCR publication/public visibility, anonymous+ Internet pulls, and live ECI/NAS cache/startup remain release/cloud checks. The+ installer and images must be published before the main-branch Quickstart works.+## Environment profile migration, 2026-11-11- `make build test vet check` and `make race` passed.diff --git a/internal/config/config.go b/internal/config/config.goindex 725cd8d..6615b50 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -19,6 +19,7 @@ import ()const DataRoot = "/root/harness"+const DefaultHostImage = "ghcr.io/xyc999-ai/go-bot-host:latest"const DeepSeekOrigin = "https://api.deepseek.com"const HostListen = "0.0.0.0:8080"const ModelContextWindow = 1_000_000@@ -111,11 +112,6 @@ type Host struct {type Auth struct {HostToken string `json:"-"`}-type Registry struct {- PushImage string- Username string `json:"-"`- Password string `json:"-"`-}type Config struct {Version intController Controller@@ -127,7 +123,6 @@ type Config struct {Web WebCloud CloudAuth Auth- Registry Registry}func Default() Config {@@ -135,7 +130,7 @@ func Default() Config {Version: 1,Controller: Controller{Listen: "127.0.0.1:8080"},Runtime: Runtime{- Provider: "docker", Image: "go-bot/host:local", StartTimeout: 5 * time.Minute,+ Provider: "docker", Image: DefaultHostImage, StartTimeout: 5 * time.Minute,Docker: Docker{EndpointHost: "127.0.0.1"},ECI: ECI{Region: "cn-hangzhou", CPU: 2, MemoryGiB: 4},},@@ -287,13 +282,13 @@ func (c Config) validate(hostOnly, requireModel bool) error {}if !hostOnly {need(c.Runtime.StartTimeout > 0, "runtime.start_timeout must be positive")+ need(ValidImage(c.Runtime.Image), "HOST_IMAGE must be an image reference")_, listenErr := ControllerListenAddress(c.Controller.Listen)if listenErr != nil {need(false, listenErr.Error())}switch c.Runtime.Provider {case "docker":- need(ValidImage(c.Runtime.Image), "HOST_IMAGE must be an image reference")need(c.Storage.Type != "nas", "HARNESS_STORAGE=nas requires HARNESS_RUNTIME=eci")case "eci":need(c.Cloud.Aliyun.Credentials.AccessKeyID != "", "missing ALIBABA_CLOUD_ACCESS_KEY_ID")diff --git a/internal/config/config_test.go b/internal/config/config_test.goindex 746b9b3..ababb83 100644--- a/internal/config/config_test.go+++ b/internal/config/config_test.go@@ -109,7 +109,6 @@ func TestECICredentialsAndOptionalNAS(t *testing.T) {t.Fatal(err)}c.Runtime.Provider = "eci"- c.Runtime.Image = ""c.Runtime.ECI.ImageCacheID = "imc-fixture"c.Runtime.ECI.VSwitchID = "vsw-test"c.Runtime.ECI.SecurityGroupID = "sg-test"@@ -118,6 +117,11 @@ func TestECICredentialsAndOptionalNAS(t *testing.T) {t.Fatal("ECI missing credentials accepted")}c.Cloud.Aliyun.Credentials = Credentials{"id", "secret"}+ c.Runtime.Image = ""+ if e = c.Validate(false); e == nil || !strings.Contains(e.Error(), "HOST_IMAGE") {+ t.Fatal("ECI accepted an empty image reference")+ }+ c.Runtime.Image = DefaultHostImageif e = c.Validate(false); e != nil {t.Fatal(e)}@@ -159,10 +163,9 @@ func TestHostEnvironmentHasNoCloudOrPublicToken(t *testing.T) {t.Fatal(err)}c.Cloud.Aliyun.Credentials = Credentials{"cloud-id", "cloud-secret"}- c.Registry = Registry{PushImage: "registry.example/host:v1", Username: "registry-user", Password: "registry-secret"}env := c.HostEnvironment("alice", "run", "internal-token")b, _ := json.Marshal(env)- for _, secret := range []string{"cloud-id", "cloud-secret", "public-token-secret", "registry-secret", "model-secret", "search-secret"} {+ for _, secret := range []string{"cloud-id", "cloud-secret", "public-token-secret", "model-secret", "search-secret"} {if strings.Contains(string(b), secret) {t.Fatalf("Host environment exposed %s", secret)}@@ -196,7 +199,7 @@ func TestEnvironmentTemplateAndPrecedence(t *testing.T) {if err != nil {t.Fatal(err)}- for _, key := range []string{"ALIBABA_CLOUD_ACCESS_KEY_ID", "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "REGISTRY_PUSH_IMAGE", "REGISTRY_USERNAME", "REGISTRY_PASSWORD"} {+ for _, key := range []string{"ALIBABA_CLOUD_ACCESS_KEY_ID", "ALIBABA_CLOUD_ACCESS_KEY_SECRET"} {if value, exists := values[key]; !exists || value != "" {t.Errorf("%s must be present and blank in the public template", key)}@@ -204,12 +207,12 @@ func TestEnvironmentTemplateAndPrecedence(t *testing.T) {t.Chdir(t.TempDir())writeFile(t, ".env", string(template))c, err = Load("", "")- if err != nil || c.Runtime.Provider != "docker" || c.Storage.Type != "container" || c.ValidateController() != nil {+ if err != nil || c.Runtime.Provider != "docker" || c.Runtime.Image != DefaultHostImage || c.Storage.Type != "container" || c.ValidateController() != nil {t.Fatalf("template did not produce the default deployment without account credentials: %v", err)}profile := strings.NewReplacer("HARNESS_RUNTIME=docker", "HARNESS_RUNTIME=eci",- "HOST_IMAGE=go-bot/host:local", "HOST_IMAGE=registry.example/host:test",+ "HOST_IMAGE="+DefaultHostImage, "HOST_IMAGE=registry.example/host:test","ECI_VSWITCH_ID=", "ECI_VSWITCH_ID=vsw-fixture","ECI_SECURITY_GROUP_ID=", "ECI_SECURITY_GROUP_ID=sg-fixture","ECI_IMAGE_CACHE_ID=", "ECI_IMAGE_CACHE_ID=imc-fixture",@@ -340,7 +343,7 @@ func TestStartupRejectsPublicTemplateAsPrivateProfile(t *testing.T) {func TestSaveECIImageCacheIDPreservesProfile(t *testing.T) {t.Chdir(t.TempDir())const path = ".env.eci"- const initial = "# deployment\nHARNESS_RUNTIME=eci\nECI_IMAGE_CACHE_ID=imc-old\nREGISTRY_PASSWORD=literal#password=$value\n"+ const initial = "# deployment\nHARNESS_RUNTIME=eci\nECI_IMAGE_CACHE_ID=imc-old\nALIBABA_CLOUD_ACCESS_KEY_SECRET=literal#password=$value\n"if err := os.WriteFile(path, []byte(initial), 0644); err != nil {t.Fatal(err)}diff --git a/internal/config/environment.go b/internal/config/environment.goindex f8bb8e5..1a7e201 100644--- a/internal/config/environment.go+++ b/internal/config/environment.go@@ -112,9 +112,6 @@ func controllerBindings(c *Config) bindings {"ECI_IMAGE_CACHE_ID": &c.Runtime.ECI.ImageCacheID,"ALIBABA_CLOUD_ACCESS_KEY_ID": &c.Cloud.Aliyun.Credentials.AccessKeyID,"ALIBABA_CLOUD_ACCESS_KEY_SECRET": &c.Cloud.Aliyun.Credentials.AccessKeySecret,- "REGISTRY_PUSH_IMAGE": &c.Registry.PushImage,- "REGISTRY_USERNAME": &c.Registry.Username,- "REGISTRY_PASSWORD": &c.Registry.Password,})return b}diff --git a/internal/imagebuild/publish.go b/internal/imagebuild/publish.godeleted file mode 100644index 2861154..0000000--- a/internal/imagebuild/publish.go+++ /dev/null@@ -1,54 +0,0 @@-// Package imagebuild publishes Host images using the operator's Docker login.-package imagebuild--import (- "bytes"- "context"- "errors"- "io"- "os"- "os/exec"- "regexp"- "strings"-)--var digestPattern = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)-var pushDigestPattern = regexp.MustCompile(`(?m)^\S+: digest: (sha256:[0-9a-f]{64}) size: [0-9]+\s*$`)--func ValidDigest(value string) bool { return digestPattern.MatchString(value) }--func PublishAMD64(ctx context.Context, localImage, pushImage string, logs io.Writer) (string, error) {- // Registry authentication comes from the Docker CLI context. Application- // and Alibaba credentials are only read by our own commands.- env := []string{}- for _, entry := range os.Environ() {- key, _, _ := strings.Cut(entry, "=")- switch key {- case "MODEL_API_KEY", "WEB_SEARCH_API_KEY", "HOST_API_TOKEN", "CONTROLLER_API_TOKEN",- "ALIBABA_CLOUD_ACCESS_KEY_ID", "ALIBABA_CLOUD_ACCESS_KEY_SECRET",- "REGISTRY_USERNAME", "REGISTRY_PASSWORD":- default:- env = append(env, entry)- }- }- cmd := exec.CommandContext(ctx, "docker", "buildx", "build",- "--platform", "linux/amd64", "--provenance=false", "--load",- "--file", "build/Dockerfile.host", "--tag", localImage, "--tag", pushImage, ".")- cmd.Env = env- cmd.Stdout, cmd.Stderr = logs, logs- if err := cmd.Run(); err != nil {- return "", err- }- var output bytes.Buffer- push := exec.CommandContext(ctx, "docker", "image", "push", pushImage)- push.Env = env- push.Stdout, push.Stderr = io.MultiWriter(logs, &output), logs- if err := push.Run(); err != nil {- return "", err- }- match := pushDigestPattern.FindSubmatch(output.Bytes())- if len(match) != 2 {- return "", errors.New("Docker did not report a valid published image digest")- }- return string(match[1]), nil-}diff --git a/internal/imagebuild/publish_test.go b/internal/imagebuild/publish_test.godeleted file mode 100644index 8937448..0000000--- a/internal/imagebuild/publish_test.go+++ /dev/null@@ -1,43 +0,0 @@-package imagebuild--import (- "bytes"- "os"- "path/filepath"- "strings"- "testing"-)--func TestPublishAMD64(t *testing.T) {- dir := t.TempDir()- const image = "registry.example.com/agent/host:v1"- const digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"- const docker = `#!/bin/sh-set -eu-[ "${MODEL_API_KEY+x}${WEB_SEARCH_API_KEY+x}${ALIBABA_CLOUD_ACCESS_KEY_SECRET+x}${REGISTRY_PASSWORD+x}" = '' ]-[ "$DOCKER_CONFIG" = '/docker-test-config' ]-if [ "$1" = buildx ]; then- [ "$*" = 'buildx build --platform linux/amd64 --provenance=false --load --file build/Dockerfile.host --tag go-bot/host:eci --tag registry.example.com/agent/host:v1 .' ]- touch "$DOCKER_BUILD_MARKER"- printf '%s\n' 'built fixture image' >&2-else- [ "$*" = 'image push registry.example.com/agent/host:v1' ]- [ -f "$DOCKER_BUILD_MARKER" ]- printf '%s\n' 'v1: digest: ` + digest + ` size: 123'-fi-`- if err := os.WriteFile(filepath.Join(dir, "docker"), []byte(docker), 0o700); err != nil {- t.Fatal(err)- }- t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))- t.Setenv("DOCKER_CONFIG", "/docker-test-config")- t.Setenv("DOCKER_BUILD_MARKER", filepath.Join(dir, "built"))- for _, key := range []string{"MODEL_API_KEY", "WEB_SEARCH_API_KEY", "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "REGISTRY_PASSWORD"} {- t.Setenv(key, "fixture-value")- }- var logs bytes.Buffer- got, err := PublishAMD64(t.Context(), "go-bot/host:eci", image, &logs)- if err != nil || got != digest || !strings.Contains(logs.String(), "built fixture image") {- t.Fatalf("PublishAMD64 = %q, %v; logs = %q", got, err, logs.String())- }-}diff --git a/internal/localstate/store.go b/internal/localstate/store.goindex 8ef3194..0b31482 100644--- a/internal/localstate/store.go+++ b/internal/localstate/store.go@@ -7,6 +7,7 @@ import ("fmt""os""path/filepath"+ "syscall""golang.org/x/sys/unix")@@ -57,6 +58,23 @@ func WritePrivate(filename string, b []byte) error {return err}defer os.Remove(f.Name())+ // A containerized Controller may be root while the mounted profile belongs+ // to the installer user. Preserve that owner when replacing the file.+ if os.Geteuid() == 0 {+ info, statErr := os.Stat(filename)+ if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {+ f.Close()+ return statErr+ }+ if info != nil {+ if stat, ok := info.Sys().(*syscall.Stat_t); ok {+ if err := f.Chown(int(stat.Uid), int(stat.Gid)); err != nil {+ f.Close()+ return err+ }+ }+ }+ }if err = f.Chmod(0600); err == nil {_, err = f.Write(b)}diff --git a/providers/runtime/eci/driver.go b/providers/runtime/eci/driver.goindex eeee454..e105a77 100644--- a/providers/runtime/eci/driver.go+++ b/providers/runtime/eci/driver.go@@ -32,6 +32,9 @@ func (*Driver) Validate(s runtime.Spec) error {if !config.ValidImageCacheID(s.ECI.ImageCacheID) {return errors.New("ECI_IMAGE_CACHE_ID must be a valid imc- ID")}+ if !config.ValidImage(s.Image) {+ return errors.New("HOST_IMAGE must be an image reference")+ }for key, value := range s.Environment {if len(value) > 256 {return fmt.Errorf("ECI environment value for %s exceeds 256 bytes", key)@@ -48,19 +51,22 @@ func (*Driver) Validate(s runtime.Spec) error {func tags(s runtime.Spec) map[string]string {return map[string]string{"component": "go-bot-host", "deployment-id": s.DeploymentID, "run-id": s.RunID}}-func (d *Driver) image(ctx context.Context, s runtime.Spec) (string, error) {++// checkCache is used only by the explicitly requested doctor command.+// Normal instance creation passes the configured image and cache ID directly.+func (d *Driver) checkCache(ctx context.Context, s runtime.Spec) error {cache, err := d.Client.DescribeImageCache(ctx, s.ECI.ImageCacheID)if err != nil {- return "", err+ return err}image, err := cache.ReadyImage(s.ECI.ImageCacheID, s.ECI.Region, time.Now())if err != nil {- return "", err+ return err}- if !config.ValidImage(image) || image == "go-bot/host:local" {- return "", errors.New("ECI cache contains an invalid Host image reference")+ if !config.ValidImage(image) {+ return errors.New("ECI cache contains an invalid Host image reference")}- return image, nil+ return nil}func (d *Driver) Preflight(ctx context.Context, s runtime.Spec) error {@@ -76,8 +82,7 @@ func (d *Driver) Preflight(ctx context.Context, s runtime.Spec) error {return nil // Reconnecting to an existing instance does not consume its old cache.}}- _, err = d.image(ctx, s)- return err+ return d.checkCache(ctx, s)}func deploymentTags(s runtime.Spec) map[string]string {@@ -165,11 +170,7 @@ func (d *Driver) Ensure(ctx context.Context, s runtime.Spec) (runtime.Instance,}id = active.ID} else {- image, err := d.image(ctx, s)- if err != nil {- return runtime.Instance{}, err- }- req := aliyun.Create{Name: "go-bot-" + s.RunID, ClientToken: s.RunID, Image: image, ImageCacheID: s.ECI.ImageCacheID, VSwitchID: s.ECI.VSwitchID, SecurityGroupID: s.ECI.SecurityGroupID, CPU: s.ECI.CPU, MemoryGiB: s.ECI.MemoryGiB, Environment: s.Environment, Tags: tags(s)}+ req := aliyun.Create{Name: "go-bot-" + s.RunID, ClientToken: s.RunID, Image: s.Image, ImageCacheID: s.ECI.ImageCacheID, VSwitchID: s.ECI.VSwitchID, SecurityGroupID: s.ECI.SecurityGroupID, CPU: s.ECI.CPU, MemoryGiB: s.ECI.MemoryGiB, Environment: s.Environment, Tags: tags(s)}if s.Storage.Type == "nas" {req.NASMountTarget = s.Storage.MountTargetreq.NASPath = s.Storage.Pathdiff --git a/providers/runtime/eci/driver_test.go b/providers/runtime/eci/driver_test.goindex 1319911..f4b60e9 100644--- a/providers/runtime/eci/driver_test.go+++ b/providers/runtime/eci/driver_test.go@@ -63,7 +63,7 @@ func TestECIContainerUsesCacheWithoutNAS(t *testing.T) {if e != nil {t.Fatal(e)}- if out.Endpoint != "http://10.1.2.3:8080" || api.last.NASMountTarget != "" || api.last.ImageCacheID != "imc-test" || api.last.Image != "registry.example/host:v1" {+ if out.Endpoint != "http://10.1.2.3:8080" || api.last.NASMountTarget != "" || api.last.ImageCacheID != "imc-test" || api.last.Image != s.Image || api.cacheQueries != 0 {t.Fatal("unexpected endpoint, NAS or cache image")}s.Storage = runtime.Storage{Type: "nas"}@@ -137,12 +137,13 @@ func TestECIRefusesForeignRunAndMultipleActiveInstances(t *testing.T) {}}-func TestECIRejectsInvalidCacheBeforeCreating(t *testing.T) {+func TestECIDoctorValidatesCache(t *testing.T) {for _, test := range []struct {name stringchange func(*runtime.Spec, *aliyun.ImageCache)}{{"missing ID", func(s *runtime.Spec, _ *aliyun.ImageCache) { s.ECI.ImageCacheID = "" }},+ {"missing image", func(s *runtime.Spec, _ *aliyun.ImageCache) { s.Image = "" }},{"not ready", func(_ *runtime.Spec, c *aliyun.ImageCache) { c.Status = "Creating" }},{"wrong region", func(_ *runtime.Spec, c *aliyun.ImageCache) { c.Region = "cn-beijing" }},{"expired", func(_ *runtime.Spec, c *aliyun.ImageCache) { c.ExpiresAt = "2000-01-01T00:00:00Z" }},@@ -155,13 +156,25 @@ func TestECIRejectsInvalidCacheBeforeCreating(t *testing.T) {test.change(&s, &cache)api := &fakeAPI{cache: &cache}d := &Driver{Client: api}- if _, err := d.Ensure(context.Background(), s); err == nil || api.creates != 0 {+ if err := d.Preflight(context.Background(), s); err == nil || api.creates != 0 {t.Fatalf("invalid cache reached create: %v", err)}})}}+func TestECICreationDoesNotQueryCache(t *testing.T) {+ api := &fakeAPI{cache: &aliyun.ImageCache{Status: "Failed"}}+ driver := &Driver{Client: api}+ spec := testSpec()+ if _, err := driver.Ensure(t.Context(), spec); err != nil {+ t.Fatal(err)+ }+ if api.cacheQueries != 0 || api.last.Image != spec.Image || api.last.ImageCacheID != spec.ECI.ImageCacheID {+ t.Fatal("creation must pass the configured image/cache pair directly to the cloud")+ }+}+func TestECIReattachesWithoutRequiringOldCache(t *testing.T) {api := &fakeAPI{}d := &Driver{Client: api}diff --git a/scripts/buildeci.sh b/scripts/buildeci.shindex 1bda1ef..2e60410 100755--- a/scripts/buildeci.sh+++ b/scripts/buildeci.sh@@ -3,11 +3,9 @@ set -euo pipefailrepo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"cd "$repo_dir"-mode=prepareprofile=.env.eciargs=()-if [[ "${1:-}" == prepare || "${1:-}" == cache ]]; then- mode="$1"+if [[ "${1:-}" == cache ]]; thenshiftfiwhile (($#)); do@@ -15,7 +13,7 @@ while (($#)); do--env-file) profile="${2:?missing profile path}"; shift 2 ;;--config|--operation) args+=("$1" "${2:?missing option value}"); shift 2 ;;-h|--help)- echo "Usage: $0 [prepare|cache] [--env-file PATH] [--config PATH] [--operation NAME]"+ echo "Usage: $0 [cache] [--env-file PATH] [--config PATH] [--operation NAME]"exit 0;;*) echo "Unknown option: $1 (see --help)" >&2; exit 2 ;;@@ -32,10 +30,33 @@ if [[ "$profile" -ef .env.example ]]; thenexit 1fi-if ! command -v go >/dev/null 2>&1; then- echo 'buildeci.sh requires Go 1.26 or newer.' >&2+controller_image="$(docker compose --env-file /dev/null config controller | awk '+ /^ controller:/ { selected=1; next }+ selected && /^ [^ ]/ { selected=0 }+ selected && $1 == "image:" { print $2; exit }+')"+[[ -n "$controller_image" ]] || { echo 'Compose must define a Controller image.' >&2; exit 1; }+if ! docker image inspect "$controller_image" >/dev/null 2>&1; then+ echo "Required local image is missing: $controller_image. Pull it before preparing ECI." >&2exit 1fi--cache_id="$(go run ./cmd/buildeci "$mode" --env-file "$profile" --write-profile --output cache-id ${args[@]+"${args[@]}"})"+profile_dir="$(cd "$(dirname "$profile")" && pwd)"+profile_name="$(basename "$profile")"+mkdir -p .cache/buildeci+# Only the profile directory, operation state, and optional tuning are needed.+mounts=(-v "$profile_dir:/profile" -v "$repo_dir/.cache/buildeci:/state")+forwarded_args=()+for ((i=0; i<${#args[@]}; i+=2)); do+ if [[ "${args[i]}" == --config ]]; then+ tuning="$(cd "$(dirname "${args[i+1]}")" && pwd)/$(basename "${args[i+1]}")"+ mounts+=(-v "$tuning:/buildeci.yaml:ro")+ forwarded_args+=(--config /buildeci.yaml)+ else+ forwarded_args+=("${args[i]}" "${args[i+1]}")+ fi+done+cache_id="$(docker run --rm --pull=never --user "$(id -u):$(id -g)" "${mounts[@]}" \+ --entrypoint /usr/local/bin/buildeci "$controller_image" cache \+ --env-file "/profile/$profile_name" --state-dir /state --write-profile --output cache-id \+ ${forwarded_args[@]+"${forwarded_args[@]}"})"printf 'Saved ECI_IMAGE_CACHE_ID=%s to %s\n' "$cache_id" "$profile"diff --git a/scripts/install.sh b/scripts/install.shnew file mode 100755index 0000000..2c9aa62--- /dev/null+++ b/scripts/install.sh@@ -0,0 +1,87 @@+#!/usr/bin/env bash+# Install the Docker deployment without cloning the source repository.+set -euo pipefail++directory=go-bot+while (($#)); do+ case "$1" in+ --dir) directory="${2:?missing installation directory}"; shift 2 ;;+ -h|--help)+ echo 'Usage: install.sh [--dir PATH]'+ echo 'Prepare local Docker images and deployment files; start with docker compose up -d.'+ exit 0 ;;+ *) echo "Unknown option: $1" >&2; exit 2 ;;+ esac+done+for command in curl docker; do+ command -v "$command" >/dev/null || { echo "Install $command first." >&2; exit 1; }+done+docker compose version >/dev/null+docker info >/dev/null+mkdir -p "$directory"+directory="$(cd "$directory" && pwd -P)"+temporary="$(mktemp -d "$directory/.install-XXXXXX")"+trap 'rm -rf "$temporary"' EXIT+# The override is useful for mirrors and testing a branch before it reaches main.+source_url="${GO_BOT_INSTALL_SOURCE:-https://raw.githubusercontent.com/xyc999-ai/go-bot/main}"+mkdir -p "$temporary/configs" "$directory/configs"+for file in compose.yaml .env.example configs/default.yaml scripts/install.sh; do+ mkdir -p "$temporary/$(dirname "$file")"+ curl --fail --silent --show-error --location --retry 3 \+ "$source_url/$file" --output "$temporary/$file"+ [[ -s "$temporary/$file" ]] || { echo "Downloaded file is empty: $file" >&2; exit 1; }+done+for file in compose.yaml .env.example configs/default.yaml install.sh; do+ target="$directory/$file"+ if [[ -L "$target" || ( -e "$target" && ! -f "$target" ) ]]; then+ echo "Expected a regular deployment file: $target" >&2+ exit 1+ fi+ if [[ ! -f "$target" ]]; then+ from="$file"+ [[ "$file" != install.sh ]] || from=scripts/install.sh+ mv "$temporary/$from" "$target"+ chmod 644 "$target"+ [[ "$file" != install.sh ]] || chmod 755 "$target"+ else+ echo "Kept $target"+ fi+done+if [[ -L "$directory/.env" || ( -e "$directory/.env" && ! -f "$directory/.env" ) ]]; then+ echo 'Choose an installation directory with a regular private .env file.' >&2+ exit 1+fi+if [[ ! -f "$directory/.env" ]]; then+ (umask 077; cp "$directory/.env.example" "$directory/.env"; chmod 600 "$directory/.env")+fi++cd "$directory"+export GO_BOT_ENV_DIR="$directory" GO_BOT_ENV_NAME=.env GO_BOT_CONFIG_FILE="$directory/configs/default.yaml"+# Do not use Compose's interpolated .env values as application credentials.+# Controller reads the original file. Only fixed Compose wiring uses interpolation.+compose=(docker compose --env-file /dev/null)+controller_image="$("${compose[@]}" config controller | awk '+ /^ controller:/ { selected=1; next }+ selected && /^ [^ ]/ { selected=0 }+ selected && $1 == "image:" { print $2; exit }+')"+[[ -n "$controller_image" ]] || { echo 'Compose must define a Controller image.' >&2; exit 1; }+while IFS= read -r image; do+ docker pull "$image"+done < <("${compose[@]}" config --images)+mounts=(-v "$directory:/profile" -v "$directory/configs/default.yaml:/runtime.yaml:ro")+config_args=(--env-file /profile/.env --config /runtime.yaml)+forwarded=()+while IFS='=' read -r key _; do+ if [[ "$key" =~ ^[A-Z][A-Z0-9_]*$ ]]; then forwarded+=(-e "$key"); fi+done < .env.example+docker run --rm --pull=never --user "$(id -u):$(id -g)" "${mounts[@]}" ${forwarded[@]+"${forwarded[@]}"} \+ --entrypoint /usr/local/bin/prepare-env "$controller_image" "${config_args[@]}"+runtime_info="$(docker run --rm --pull=never "${mounts[@]}" "$controller_image" check --print-runtime "${config_args[@]}")"+if [[ "${runtime_info%%$'\n'*}" != docker ]]; then+ echo 'install.sh prepares Docker only. Follow the separate ECI guide for cloud deployment.' >&2+ exit 1+fi+docker pull "${runtime_info#*$'\n'}"+echo "Prepared $directory"+printf 'Start with:\n cd %q\n docker compose up -d\nThen open http://localhost:8080\n' "$directory"diff --git a/scripts/smoke-cli.py b/scripts/smoke-cli.pyindex 0e4eb86..206d447 100644--- a/scripts/smoke-cli.py+++ b/scripts/smoke-cli.py@@ -62,7 +62,9 @@ def main():work.mkdir(exist_ok=True)with tempfile.TemporaryDirectory(prefix="compose-smoke-", dir=work) as directory:profile = Path(directory) / ".env"- profile.write_text("")+ profile_text = ("HOST_IMAGE=" + os.environ.get("HARNESS_TEST_HOST_IMAGE", "ghcr.io/xyc999-ai/go-bot-host:latest") + "\n"+ "ALIBABA_CLOUD_ACCESS_KEY_SECRET=literal$not_interpolated #fixture=1\n")+ profile.write_text(profile_text)profile.chmod(0o600)ports = Path(directory) / "ports.yaml"ports.write_text(@@ -72,14 +74,15 @@ def main():' redis:\n'' ports: !override ["127.0.0.1::6379"]\n')- env = dict(os.environ, GO_BOT_ENV_FILE=str(profile))+ env = dict(os.environ, GO_BOT_ENV_DIR=str(profile.parent), GO_BOT_ENV_NAME=profile.name,+ GO_BOT_CONFIG_FILE=str(ROOT / "configs/default.yaml"))alice, bob = (f"{PROJECT}-{name}" for name in ("alice", "bob"))names = {}sessions = {}main_sessions = {}def compose(*args):- return run("docker", "compose", "--env-file", "/dev/null", "-p", PROJECT,+ return run("docker", "compose", "--project-directory", str(profile.parent), "-p", PROJECT,"-f", str(ROOT / "compose.yaml"), "-f", str(ports), *args, env=env)def redis(*args):@@ -90,9 +93,10 @@ def main():return {key: value for key, value in json.loads(raw).items() if value != ""}try:- compose("up", "-d", "--build", "--wait")+ compose("up", "-d", "--no-build", "--pull", "never", "--wait")BASE = "http://" + compose("port", "controller", "8080")wait_for(lambda: call("GET", "/readyz", expected=200) is None)+ assert profile.read_text() == profile_textassert "Go Bot" in call("GET", "/")assert redis("DBSIZE") == "0"call("POST", "/v1/host/start", "unknown", expected=404)diff --git a/scripts/smoke-image.sh b/scripts/smoke-image.shindex 37db659..30ca4e2 100755--- a/scripts/smoke-image.sh+++ b/scripts/smoke-image.sh@@ -1,6 +1,6 @@#!/usr/bin/env bashset -euo pipefail-image="${1:-go-bot/host:local}"+image="${1:-ghcr.io/xyc999-ai/go-bot-host:latest}"docker run --rm --entrypoint /bin/sh "$image" -ec 'python --versionpython -m pip --versiondiff --git a/scripts/start.sh b/scripts/start.shindex c822853..04c3d13 100755--- a/scripts/start.sh+++ b/scripts/start.sh@@ -54,7 +54,7 @@ if $init_only; thentemporary="$(mktemp "$path.tmp.XXXXXX")"trap 'unlink "$temporary"' EXITif [[ "$2" == eci ]]; then- sed -e 's/^HARNESS_RUNTIME=docker$/HARNESS_RUNTIME=eci/' -e 's/^HOST_IMAGE=.*/HOST_IMAGE=go-bot\/host:eci/' .env.example > "$temporary"+ sed 's/^HARNESS_RUNTIME=docker$/HARNESS_RUNTIME=eci/' .env.example > "$temporary"elsecat .env.example > "$temporary"fi@@ -75,36 +75,47 @@ profile_dir="$(cd "$(dirname "$profile")" && pwd)"profile_name="$(basename "$profile")"profile="$profile_dir/$profile_name"config_file="$(cd "$(dirname "$config_file")" && pwd)/$(basename "$config_file")"-export GO_BOT_ENV_FILE="$profile" GO_BOT_CONFIG_FILE="$config_file"+export GO_BOT_ENV_DIR="$profile_dir" GO_BOT_ENV_NAME="$profile_name" GO_BOT_CONFIG_FILE="$config_file"compose=(docker compose --env-file /dev/null)-prepare_args=(--env-file "$profile" --config "$config_file")--if command -v go >/dev/null 2>&1; then- go run ./internal/cmd/prepare-env "${prepare_args[@]}"- runtime_info="$(go run ./cmd/controller check --print-runtime --env-file "$profile" --config "$config_file")"-else- "${compose[@]}" build controller- profile_mounts=(-v "$profile_dir:/profile" -v "$config_file:/config.yaml:ro")- config_args=(--env-file "/profile/$profile_name" --config /config.yaml)- forwarded=()- while IFS='=' read -r key _; do- if [[ "$key" =~ ^[A-Z][A-Z0-9_]*$ ]]; then forwarded+=(-e "$key"); fi- done < .env.example- docker run --rm --user "$(id -u):$(id -g)" "${profile_mounts[@]}" "${forwarded[@]}" \- --entrypoint /usr/local/bin/prepare-env go-bot/controller:local "${config_args[@]}"- runtime_info="$(docker run --rm "${profile_mounts[@]}" go-bot/controller:local check --print-runtime "${config_args[@]}")"-fi+docker info >/dev/null+controller_image="$("${compose[@]}" config controller | awk '+ /^ controller:/ { selected=1; next }+ selected && /^ [^ ]/ { selected=0 }+ selected && $1 == "image:" { print $2; exit }+')"+[[ -n "$controller_image" ]] || { echo 'Compose must define a Controller image.' >&2; exit 1; }+while IFS= read -r image; do+ if ! docker image inspect "$image" >/dev/null 2>&1; then+ echo "Required local image is missing: $image. Prepare it with docker pull or an explicit source build first." >&2+ exit 1+ fi+done < <("${compose[@]}" config --images)+profile_mounts=(-v "$profile_dir:/profile" -v "$config_file:/config.yaml:ro")+config_args=(--env-file "/profile/$profile_name" --config /config.yaml)+forwarded=()+while IFS='=' read -r key _; do+ if [[ "$key" =~ ^[A-Z][A-Z0-9_]*$ ]]; then forwarded+=(-e "$key"); fi+done < .env.example+docker run --rm --pull=never --user "$(id -u):$(id -g)" "${profile_mounts[@]}" ${forwarded[@]+"${forwarded[@]}"} \+ --entrypoint /usr/local/bin/prepare-env "$controller_image" "${config_args[@]}"+runtime_info="$(docker run --rm --pull=never "${profile_mounts[@]}" "$controller_image" check --print-runtime "${config_args[@]}")"selected_runtime="${runtime_info%%$'\n'*}"selected_image="${runtime_info#*$'\n'}"if [[ "$selected_runtime" == docker ]]; then- docker build -f build/Dockerfile.host -t "$selected_image" .+ if ! docker image inspect "$selected_image" >/dev/null 2>&1; then+ echo "Host image is missing: $selected_image. Prepare it with docker pull or an explicit source build first." >&2+ exit 1+ fifi-"${compose[@]}" up -d --build --wait+"${compose[@]}" up -d --no-build --pull never --wait+published="$("${compose[@]}" port controller 8080)"+published="${published%%$'\n'*}"+published_port="${published##*:}"if command -v curl >/dev/null 2>&1; thenfor ((attempt = 0; attempt < 30; attempt++)); do- if curl --fail --silent --max-time 2 'http://127.0.0.1:8080/readyz' >/dev/null; then- echo 'Go Bot is ready at http://localhost:8080'+ if curl --fail --silent --max-time 2 "http://127.0.0.1:$published_port/readyz" >/dev/null; then+ echo "Go Bot is ready at http://localhost:$published_port"exit 0fisleep 1@@ -112,4 +123,4 @@ if command -v curl >/dev/null 2>&1; then"${compose[@]}" logs --tail 20 controller >&2exit 1fi-echo 'Open http://localhost:8080'+echo "Open http://localhost:$published_port"diff --git a/scripts/test-install.py b/scripts/test-install.pynew file mode 100644index 0000000..e61bf3e--- /dev/null+++ b/scripts/test-install.py@@ -0,0 +1,167 @@+#!/usr/bin/env python3+"""Test the installer and source launcher with local HTTP files and real image tools.++Registry pulls are replaced with local image checks so CI never needs a published+GHCR version. Container checks still run the actual Controller image.+"""+import functools+import http.server+import os+from pathlib import Path+import shutil+import subprocess+import tempfile+import threading+import urllib.request+import uuid++ROOT = Path(__file__).resolve().parents[1]+++class QuietHandler(http.server.SimpleHTTPRequestHandler):+ def log_message(self, *_):+ pass+++def main():+ work = ROOT / ".cache"+ work.mkdir(exist_ok=True)+ with tempfile.TemporaryDirectory(prefix="install-test-", dir=work) as directory:+ stage = Path(directory)+ source = stage / "source"+ for name in ("compose.yaml", ".env.example", "configs/default.yaml", "scripts/install.sh", "scripts/start.sh"):+ target = source / name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(ROOT / name, target)+ handler = functools.partial(QuietHandler, directory=str(source))+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ wrapper = stage / "tools"+ wrapper.mkdir()+ real_docker = shutil.which("docker")+ assert real_docker+ (wrapper / "docker").write_text(+ "#!/usr/bin/env python3\n"+ "import os,sys\n"+ "a=sys.argv[1:]\n"+ "if a[:1]==['pull']:\n"+ " with open(os.environ['PULL_LOG'],'a') as f: f.write(a[1]+'\\n')\n"+ " a=['image','inspect',a[1]]\n"+ " sys.stdout=open(os.devnull,'w'); os.dup2(sys.stdout.fileno(),1)\n"+ "os.execv(os.environ['REAL_DOCKER'],['docker',*a])\n"+ )+ (wrapper / "docker").chmod(0o755)+ log = stage / "pulls"+ env = dict(os.environ, PATH=str(wrapper) + os.pathsep + os.environ["PATH"],+ REAL_DOCKER=real_docker, PULL_LOG=str(log),+ GO_BOT_INSTALL_SOURCE=f"http://127.0.0.1:{server.server_port}")+ for line in (ROOT / ".env.example").read_text().splitlines():+ if line and not line.startswith("#"):+ env.pop(line.split("=", 1)[0], None)+ for key in ("GO_BOT_ENV_DIR", "GO_BOT_ENV_NAME", "GO_BOT_CONFIG_FILE", "COMPOSE_FILE", "COMPOSE_PROJECT_NAME"):+ env.pop(key, None)++ def run(script, *args, expected=0, overrides=None):+ result = subprocess.run(["bash", str(script), *args], cwd=stage,+ env=dict(env, **(overrides or {})), capture_output=True, text=True)+ if (result.returncode == 0) != (expected == 0):+ raise AssertionError(f"{script.name} returned {result.returncode}: {result.stderr}\n{result.stdout}")+ return result++ try:+ installed = stage / "installed"+ run(ROOT / "scripts/install.sh", "--dir", str(installed))+ assert (installed / "compose.yaml").read_bytes() == (ROOT / "compose.yaml").read_bytes()+ assert (installed / "configs/default.yaml").read_bytes() == (ROOT / "configs/default.yaml").read_bytes()+ assert (installed / ".env").read_bytes() == (ROOT / ".env.example").read_bytes()+ assert (installed / ".env").stat().st_mode & 0o777 == 0o600+ assert not (installed / ".env.eci").exists() and not (installed / "start.sh").exists()+ assert not (installed / "scripts/start.sh").exists()+ pulls = log.read_text().splitlines()+ assert len(pulls) == 3 and any("go-bot-host:" in image for image in pulls)+ controller_image = next(image for image in pulls if "go-bot-controller:" in image)+ # A root Controller must not turn a user's 0600 profile into a root-owned file.+ subprocess.run([real_docker, "run", "--rm", "--pull=never", "--entrypoint", "/bin/sh",+ controller_image, "-ec",+ 'mkdir /tmp/profile; printf "CONTROLLER_LISTEN=127.0.0.1:8080\\n" > /tmp/profile/.env; '+ 'chown 1234:1234 /tmp/profile/.env; '+ 'CONTROLLER_LISTEN=127.0.0.1:8099 prepare-env --env-file /tmp/profile/.env; '+ 'test "$(stat -c %u:%g /tmp/profile/.env)" = 1234:1234'], check=True)++ # Preserve user tuning and literal credentials, including '$' and spaces.+ profile = installed / ".env"+ text = profile.read_text().replace("ALIBABA_CLOUD_ACCESS_KEY_SECRET=", "ALIBABA_CLOUD_ACCESS_KEY_SECRET=fixture$literal #value=1")+ profile.write_text(text)+ tuning = installed / "configs/default.yaml"+ tuning.write_text(tuning.read_text().replace("start_timeout: 5m", "start_timeout: 7m"))+ saved_tuning = tuning.read_bytes()+ run(ROOT / "scripts/install.sh", "--dir", str(installed))+ assert profile.read_text() == text and tuning.read_bytes() == saved_tuning+ run(ROOT / "scripts/install.sh", "--dir", str(installed), overrides={"CONTROLLER_LISTEN": "127.0.0.1:8099"})+ assert "CONTROLLER_LISTEN=127.0.0.1:8099" in profile.read_text()+ assert "fixture$literal #value=1" in profile.read_text()++ broken = stage / "incomplete"+ run(ROOT / "scripts/install.sh", "--dir", str(broken), expected=1,+ overrides={"GO_BOT_INSTALL_SOURCE": env["GO_BOT_INSTALL_SOURCE"] + "/missing"})+ assert not (broken / ".env").exists()++ # The independent source launcher initializes without install.sh,+ # and fails for a missing Host image without trying to pull/build it.+ run(source / "scripts/start.sh", "--init-env")+ assert (source / ".env.eci").is_file()+ assert "HARNESS_RUNTIME=eci" in (source / ".env.eci").read_text()+ private = source / ".env"+ private.write_text(private.read_text().replace(+ next(line for line in private.read_text().splitlines() if line.startswith("HOST_IMAGE=")),+ "HOST_IMAGE=go-bot/missing-installer-test:never"))+ before = log.read_text()+ result = run(source / "scripts/start.sh", expected=1)+ assert "Host image is missing" in result.stderr+ assert log.read_text() == before+ run(source / "scripts/start.sh", "--init-env")+ eci = (source / ".env.eci").read_text()+ assert "HARNESS_RUNTIME=eci" in eci+ assert "HOST_IMAGE=ghcr.io/xyc999-ai/go-bot-host:latest" in eci+ # Both entry paths boot actual Controller/Redis containers on isolated+ # random ports. The installed directory has no source, Go or start.sh.+ ports = stage / "ports.yaml"+ ports.write_text('services:\n controller:\n ports: !override ["127.0.0.1::8080"]\n'+ ' environment:\n CONTROLLER_LISTEN: "127.0.0.1:8098"\n'+ ' redis:\n ports: !override ["127.0.0.1::6379"]\n')+ (source / ".env").write_bytes((ROOT / ".env.example").read_bytes())+ for deployment, source_start in ((installed, False), (source, True)):+ project = "install-qa-" + uuid.uuid4().hex[:8]+ launch_env = dict(env, COMPOSE_PROJECT_NAME=project,+ COMPOSE_FILE=str(deployment / "compose.yaml") + os.pathsep + str(ports))+ compose = [real_docker, "compose", "--project-directory", str(deployment)]+ original_owner = (deployment / ".env").stat().st_uid+ try:+ if source_start:+ result = subprocess.run(["bash", str(source / "scripts/start.sh")], env=launch_env,+ text=True, capture_output=True)+ assert result.returncode == 0, result.stderr + result.stdout+ else:+ subprocess.run([*compose, "up", "-d", "--wait"], env=launch_env, check=True,+ stdout=subprocess.DEVNULL)+ address = subprocess.check_output([*compose, "port", "controller", "8080"],+ env=launch_env, text=True).strip()+ with urllib.request.urlopen("http://" + address, timeout=10) as response:+ assert b"Go Bot" in response.read()+ saved = (deployment / ".env").read_text()+ assert (deployment / ".env").stat().st_uid == original_owner+ assert "CONTROLLER_LISTEN=127.0.0.1:8098" in saved+ if not source_start:+ assert "fixture$literal #value=1" in saved+ finally:+ subprocess.run([*compose, "down", "--volumes", "--remove-orphans"],+ env=launch_env, check=True, stdout=subprocess.DEVNULL)+ assert log.read_text() == before, "startup unexpectedly pulled an image"+ print("Install/start checks passed: shared files, private profile, literal values, repeat install, missing image and interrupted download.")+ finally:+ server.shutdown()+ server.server_close()+++if __name__ == "__main__":+ main()diff --git a/tests/integration/web_parity_docker_test.go b/tests/integration/web_parity_docker_test.goindex 4cd6ef8..37dc279 100644--- a/tests/integration/web_parity_docker_test.go+++ b/tests/integration/web_parity_docker_test.go@@ -335,7 +335,8 @@ func buildWebFixtureImage(t *testing.T, ctx context.Context, fixtureURL string)t.Helper()stage := t.TempDir()tag := "go-bot/web-parity:" + uuid.NewString()- arch, err := exec.CommandContext(ctx, "docker", "image", "inspect", "--format", "{{.Architecture}}", "go-bot/host:local").Output()+ baseImage := dockerFixtureConfig().Runtime.Image+ arch, err := exec.CommandContext(ctx, "docker", "image", "inspect", "--format", "{{.Architecture}}", baseImage).Output()if err != nil {t.Fatalf("inspect base Host image: %v", err)}@@ -345,7 +346,7 @@ func buildWebFixtureImage(t *testing.T, ctx context.Context, fixtureURL string)if output, err := cmd.CombinedOutput(); err != nil {t.Fatalf("build fixture Host: %v\n%s", err, output)}- recipe := "FROM go-bot/host:local\nCOPY host-test /usr/local/bin/host-test\n" ++ recipe := "FROM " + baseImage + "\nCOPY host-test /usr/local/bin/host-test\n" +"ENV HARNESS_TEST_WEB_FIXTURE=" + fixtureURL + "\n" +"ENTRYPOINT [\"/usr/local/bin/host-test\",\"-test.run=^TestDockerWebFixtureHost$\"]\n"if err := os.WriteFile(filepath.Join(stage, "Dockerfile"), []byte(recipe), 0o600); err != nil {diff --git a/thirdparty/aliyun/eci.go b/thirdparty/aliyun/eci.goindex 245d5c9..a6f07db 100644--- a/thirdparty/aliyun/eci.go+++ b/thirdparty/aliyun/eci.go@@ -76,7 +76,7 @@ func (c *ECI) Create(ctx context.Context, s Create) (string, error) {return "", err}if s.Image == "" || s.ImageCacheID == "" {- return "", errors.New("ECI launch requires an image from a Ready cache")+ return "", errors.New("ECI launch requires HOST_IMAGE and ECI_IMAGE_CACHE_ID")}res, err := c.SDK.CreateContainerGroup(c.request(s))if err != nil {diff --git a/thirdparty/aliyun/eci_test.go b/thirdparty/aliyun/eci_test.goindex b0482c9..f513c4b 100644--- a/thirdparty/aliyun/eci_test.go+++ b/thirdparty/aliyun/eci_test.go@@ -69,7 +69,7 @@ func TestECICacheLaunchAndOptionalNAS(t *testing.T) {}}-func TestImageCacheRegistryCredentialsAreOptional(t *testing.T) {+func TestImageCacheUsesPublicImage(t *testing.T) {c := ECI{Region: "cn-hangzhou"}s := CreateImageCache{Image: "registry.example/host:v1", ClientToken: "token", Name: "cache", VSwitchID: "vsw-test", SecurityGroupID: "sg-test"}r := c.imageCacheRequest(s)@@ -77,17 +77,7 @@ func TestImageCacheRegistryCredentialsAreOptional(t *testing.T) {value(r.ClientToken) != s.ClientToken || value(r.VSwitchId) != s.VSwitchID || value(r.SecurityGroupId) != s.SecurityGroupID {t.Fatal("incorrect image cache request")}- s.RegistryServer = "registry.example"- s.RegistryUsername = "fixture-user"- s.RegistryPassword = "fixture-password"- r = c.imageCacheRequest(s)- if len(r.ImageRegistryCredential) != 1 {- t.Fatal("private image access credentials missing")- }- auth := r.ImageRegistryCredential[0]- if *auth.Server != s.RegistryServer || *auth.UserName != s.RegistryUsername || *auth.Password != s.RegistryPassword {- t.Fatal("registry credential payload differs from the explicit settings")- }+}func TestECISearchSettingsArePassedToHost(t *testing.T) {diff --git a/thirdparty/aliyun/image_cache.go b/thirdparty/aliyun/image_cache.goindex 4712a55..ed9f27f 100644--- a/thirdparty/aliyun/image_cache.go+++ b/thirdparty/aliyun/image_cache.go@@ -13,7 +13,6 @@ var ErrImageCacheNotFound = errors.New("ECI image cache not found")type CreateImageCache struct {Name, ClientToken, Image, VSwitchID, SecurityGroupID string- RegistryServer, RegistryUsername, RegistryPassword stringSizeGiB, RetentionDays int32}@@ -47,11 +46,6 @@ func (c *ECI) imageCacheRequest(s CreateImageCache) *eci.CreateImageCacheRequestRegionId: &c.Region, ImageCacheName: &s.Name, ClientToken: &s.ClientToken,Image: []*string{&s.Image}, VSwitchId: &s.VSwitchID, SecurityGroupId: &s.SecurityGroupID,}- if s.RegistryServer != "" {- r.ImageRegistryCredential = []*eci.CreateImageCacheRequestImageRegistryCredential{- {Server: &s.RegistryServer, UserName: &s.RegistryUsername, Password: &s.RegistryPassword},- }- }if s.SizeGiB > 0 {r.ImageCacheSize = &s.SizeGiB}