refactor: remove WebUI and launcher

删除 WebUI/launcher、专属依赖、资源及桌面和 Android bundle 打包入口。
精简 Docker、CI/发布配置和多语言文档,保留 CLI、Gateway、Pico 与联网工具。
85 个包回归、vet/lint、文档检查及本机/Linux amd64 构建通过。
This commit is contained in:
loveuer committed 2026-11-11 14:07:20 +08:00
1 parent a7dba6859b
commit 6159157e47
358 files changed
+719 -76510

No files matched your search

-9
View File
@@ -11,15 +11,6 @@ updates:
- "dependencies"
- "go"
# Frontend dependencies
- package-ecosystem: "npm"
directory: "/web/frontend"
schedule:
interval: "weekly"
labels:
- "dependencies"
- "frontend"
# GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
-71
View File
@@ -1,71 +0,0 @@
name: Create macOS DMG
on:
workflow_dispatch:
jobs:
build:
name: Build ${{ matrix.arch }}
runs-on: macos-latest
strategy:
matrix:
# This creates two parallel jobs
arch: [arm64, amd64]
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
ref: main
# 1. Install Go from go.mod
- name: Setup Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.33.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
cache-dependency-path: web/frontend/pnpm-lock.yaml
# 3. Build the application bundle
- name: Build with Make
run: make build ARCH=${{ matrix.arch }} && make build-macos-app ARCH=${{ matrix.arch }}
# 4. Apply ad-hoc signing
- name: Ad-hoc Sign
run: codesign --force --deep --sign - "build/PicoClaw Launcher.app"
# 5. Install the DMG packaging tool
- name: Install create-dmg
run: brew install create-dmg
# 6. Create the DMG
- name: Create DMG
run: |
mkdir -p dist
create-dmg \
--volname "PicoClaw Installer" \
--window-pos 200 120 \
--window-size 800 400 \
--icon-size 100 \
--icon "PicoClaw Launcher.app" 200 190 \
--hide-extension "PicoClaw Launcher.app" \
--app-drop-link 600 185 \
"dist/picoclaw-${{ matrix.arch }}.dmg" \
"build/PicoClaw Launcher.app"
# 7. Upload the DMG as a GitHub artifact
- name: Upload DMG
uses: actions/upload-artifact@v7
with:
name: macos-dmg-${{ matrix.arch }}
path: dist/*.dmg
+1 -18
View File
@@ -47,19 +47,6 @@ jobs:
with:
go-version-file: go.mod
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.33.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
cache-dependency-path: web/frontend/pnpm-lock.yaml
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
@@ -80,9 +67,6 @@ jobs:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Install zip
run: sudo apt-get install -y zip
- name: Create local tag for GoReleaser
run: git tag "${{ steps.version.outputs.version }}"
@@ -98,7 +82,6 @@ jobs:
DOCKERHUB_IMAGE_NAME: ${{ vars.DOCKERHUB_REPOSITORY }}
GOVERSION: ${{ steps.setup-go.outputs.go-version }}
GORELEASER_CURRENT_TAG: ${{ steps.version.outputs.version }}
INCLUDE_ANDROID_BUNDLE: "true"
NIGHTLY_BUILD: "true"
MACOS_SIGN_P12: ${{ secrets.MACOS_SIGN_P12 }}
MACOS_SIGN_PASSWORD: ${{ secrets.MACOS_SIGN_PASSWORD }}
@@ -132,7 +115,7 @@ jobs:
# Collect release artifacts from goreleaser dist/
ASSETS=()
for f in dist/*.tar.gz dist/*.zip dist/*.deb dist/*.rpm dist/checksums.txt build/picoclaw-android-universal.zip; do
for f in dist/*.tar.gz dist/*.zip dist/*.deb dist/*.rpm dist/checksums.txt; do
[ -f "$f" ] && ASSETS+=("$f")
done
-17
View File
@@ -53,19 +53,6 @@ jobs:
with:
go-version-file: go.mod
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.33.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
cache-dependency-path: web/frontend/pnpm-lock.yaml
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
@@ -86,9 +73,6 @@ jobs:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Install zip
run: sudo apt-get install -y zip
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v7
with:
@@ -100,7 +84,6 @@ jobs:
GITHUB_REPOSITORY_OWNER: ${{ github.repository_owner }}
DOCKERHUB_IMAGE_NAME: ${{ vars.DOCKERHUB_REPOSITORY }}
GOVERSION: ${{ steps.setup-go.outputs.go-version }}
INCLUDE_ANDROID_BUNDLE: "true"
MACOS_SIGN_P12: ${{ secrets.MACOS_SIGN_P12 }}
MACOS_SIGN_PASSWORD: ${{ secrets.MACOS_SIGN_PASSWORD }}
MACOS_NOTARY_ISSUER_ID: ${{ secrets.MACOS_NOTARY_ISSUER_ID }}
-8
View File
@@ -51,23 +51,15 @@ docs/superpowers/
# Added by goreleaser init:
dist/
*.vite/
# Windows Application Icon/Resource
*.syso
.cache/
web/frontend/.pnpm-store/
_tmp_*
web/frontend/_tmp_*
# Test telegram integration
cmd/telegram/
# Keep embedded backend dist directory placeholder in VCS
!web/backend/dist/
web/backend/dist/*
!web/backend/dist/.gitkeep
.claude/
docker/data
-71
View File
@@ -10,9 +10,6 @@ git:
before:
hooks:
- go generate ./...
- sh -c 'cd web/frontend && CI=true pnpm install --frozen-lockfile && pnpm build:backend'
- sh -c 'GOBIN="$(go env GOPATH)/bin"; mkdir -p "$GOBIN"; go install github.com/tc-hib/go-winres@v0.3.3 && "$GOBIN/go-winres" make --in web/backend/winres/winres.json --out web/backend/rsrc --product-version={{ .Version }} --file-version={{ .Version }}'
- sh -c 'if [ "${INCLUDE_ANDROID_BUNDLE:-}" = "true" ]; then make build-android-bundle; fi'
builds:
- id: picoclaw
@@ -57,49 +54,6 @@ builds:
- goos: netbsd
goarch: arm
- id: picoclaw-launcher
binary: picoclaw-launcher
env:
- CGO_ENABLED=0
tags:
- goolm
- stdjson
ldflags:
- -s -w
- -X github.com/sipeed/picoclaw/pkg/config.Version={{ .Version }}
- -X github.com/sipeed/picoclaw/pkg/config.GitCommit={{ .ShortCommit }}
- -X github.com/sipeed/picoclaw/pkg/config.BuildTime={{ .Date }}
- -X github.com/sipeed/picoclaw/pkg/config.GoVersion={{ with index .Env "GOVERSION" }}{{ . }}{{ else }}unknown{{ end }}
goos:
- linux
- windows
- darwin
- freebsd
- netbsd
goarch:
- amd64
- arm64
- riscv64
- loong64
- arm
- s390x
- mipsle
goarm:
- "6"
- "7"
gomips:
- softfloat
main: ./web/backend
ignore:
- goos: windows
goarch: arm
- goos: netbsd
goarch: s390x
- goos: netbsd
goarch: mips64
- goos: netbsd
goarch: arm
dockers_v2:
- id: picoclaw
dockerfile: docker/Dockerfile.goreleaser
@@ -118,28 +72,11 @@ dockers_v2:
- linux/arm64
- linux/riscv64
- id: picoclaw-launcher
dockerfile: docker/Dockerfile.goreleaser.launcher
ids:
- picoclaw
- picoclaw-launcher
images:
- "ghcr.io/{{ .Env.GITHUB_REPOSITORY_OWNER }}/picoclaw"
- 'docker.io/{{ .Env.DOCKERHUB_IMAGE_NAME }}'
tags:
- '{{ if isEnvSet "NIGHTLY_BUILD" }}nightly-launcher{{ else }}{{ .Tag }}-launcher{{ end }}'
- '{{ if isEnvSet "NIGHTLY_BUILD" }}nightly-launcher{{ else }}launcher{{ end }}'
platforms:
- linux/amd64
- linux/arm64
- linux/riscv64
notarize:
macos:
- enabled: '{{ isEnvSet "MACOS_SIGN_P12" }}'
ids:
- picoclaw
- picoclaw-launcher
sign:
certificate: "{{.Env.MACOS_SIGN_P12}}"
password: "{{.Env.MACOS_SIGN_PASSWORD}}"
@@ -169,7 +106,6 @@ nfpms:
- id: picoclaw
ids:
- picoclaw
- picoclaw-launcher
package_name: picoclaw
file_name_template: >-
{{ .PackageName }}_
@@ -186,11 +122,6 @@ nfpms:
- rpm
- deb
bindir: /usr/bin
contents:
- src: web/picoclaw-launcher.desktop
dst: /usr/share/applications/picoclaw-launcher.desktop
- src: web/picoclaw-launcher.png
dst: /usr/share/icons/hicolor/512x512/apps/picoclaw-launcher.png
changelog:
sort: asc
@@ -206,8 +137,6 @@ changelog:
release:
disable: '{{ isEnvSet "NIGHTLY_BUILD" }}'
extra_files:
- glob: ./build/picoclaw-android-universal.zip
footer: >-
---
+2 -65
View File
@@ -33,7 +33,6 @@ LDFLAGS=-X $(CONFIG_PKG).Version=$(VERSION) -X $(CONFIG_PKG).GitCommit=$(GIT_COM
# Go variables
GO?=go
WEB_GO?=$(GO)
CGO_ENABLED?=0
GO_BUILD_TAGS?=goolm,stdjson
GOFLAGS?=-v -tags $(GO_BUILD_TAGS)
@@ -133,7 +132,6 @@ ifeq ($(UNAME_S),Linux)
endif
else ifeq ($(UNAME_S),Darwin)
PLATFORM=darwin
WEB_GO=CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_ENABLED=1 go
ifeq ($(UNAME_M),x86_64)
ARCH?=amd64
else ifeq ($(UNAME_M),arm64)
@@ -215,27 +213,6 @@ else
endif
@echo "Build complete: $(BUILD_DIR)/$(BINARY_NAME)$(EXT)"
## build-launcher: Build the picoclaw-launcher (web console) binary
build-launcher:
@echo "Building picoclaw-launcher for $(PLATFORM)/$(ARCH)..."
ifeq ($(OS),Windows_NT)
@$(POWERSHELL) "New-Item -ItemType Directory -Force -Path '$(BUILD_DIR)' | Out-Null"
@$(MAKE) -C web build PLATFORM="$(PLATFORM)" ARCH="$(ARCH)" EXT="$(EXT)" OUTPUT="$(CURDIR)/$(BUILD_DIR)/picoclaw-launcher-$(PLATFORM)-$(ARCH)$(EXT)" GO_BUILD_TAGS="$(GO_BUILD_TAGS)"
@$(POWERSHELL) "Copy-Item -LiteralPath '$(BUILD_DIR)/picoclaw-launcher-$(PLATFORM)-$(ARCH)$(EXT)' -Destination '$(BUILD_DIR)/picoclaw-launcher$(EXT)' -Force"
else
@mkdir -p $(BUILD_DIR)
@GOOS=$(PLATFORM) GOARCH=$(ARCH) $(MAKE) -C web build \
OUTPUT="$(CURDIR)/$(BUILD_DIR)/picoclaw-launcher-$(PLATFORM)-$(ARCH)$(EXT)" \
WEB_GO='$(WEB_GO)' \
GO_BUILD_TAGS='$(GO_BUILD_TAGS)' \
LDFLAGS='$(LDFLAGS)'
@$(LNCMD) picoclaw-launcher-$(PLATFORM)-$(ARCH)$(EXT) $(BUILD_DIR)/picoclaw-launcher$(EXT)
endif
@echo "Build complete: $(BUILD_DIR)/picoclaw-launcher$(EXT)"
build-launcher-frontend:
@$(MAKE) -C web build-frontend
## build-whatsapp-native: Build with WhatsApp native (whatsmeow) support; larger binary
build-whatsapp-native: generate
## @echo "Building $(BINARY_NAME) with WhatsApp native for $(PLATFORM)/$(ARCH)..."
@@ -283,32 +260,6 @@ build-android-arm64: generate
GOOS=android GOARCH=arm64 $(GO) build -tags stdjson -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-android-arm64 ./$(CMD_DIR)
@echo "Build complete: $(BUILD_DIR)/$(BINARY_NAME)-android-arm64"
## build-launcher-android-arm64: Build launcher for Android ARM64
build-launcher-android-arm64:
@echo "Building picoclaw-launcher for android/arm64..."
@mkdir -p $(BUILD_DIR)
@$(MAKE) -C web build-android-arm64 \
OUTPUT_ANDROID_ARM64="$(CURDIR)/$(BUILD_DIR)/picoclaw-launcher-android-arm64" \
GO='$(GO)' \
LDFLAGS='$(LDFLAGS)'
@echo "Build complete: $(BUILD_DIR)/picoclaw-launcher-android-arm64"
## build-android-bundle: Build core and launcher for all Android architectures and package as universal zip
build-android-bundle: generate
@echo "Building core for all Android architectures..."
@mkdir -p $(BUILD_DIR)
GOOS=android GOARCH=arm64 $(GO) build -tags stdjson -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-android-arm64 ./$(CMD_DIR)
@echo "Building launcher for Android arm64..."
@$(MAKE) build-launcher-android-arm64
@echo "Staging JNI libs..."
@rm -rf $(BUILD_DIR)/android-staging
@mkdir -p $(BUILD_DIR)/android-staging/arm64-v8a
@cp $(BUILD_DIR)/$(BINARY_NAME)-android-arm64 $(BUILD_DIR)/android-staging/arm64-v8a/libpicoclaw.so
@cp $(BUILD_DIR)/picoclaw-launcher-android-arm64 $(BUILD_DIR)/android-staging/arm64-v8a/libpicoclaw-web.so
@cd $(BUILD_DIR)/android-staging && zip -r ../picoclaw-android-universal.zip .
@rm -rf $(BUILD_DIR)/android-staging
@echo "All Android builds complete: $(BUILD_DIR)/picoclaw-android-universal.zip"
## build-pi-zero: Build for Raspberry Pi Zero 2 W (32-bit and 64-bit)
build-pi-zero: build-linux-arm build-linux-arm64
@echo "Pi Zero 2 W builds: $(BUILD_DIR)/$(BINARY_NAME)-linux-arm (32-bit), $(BUILD_DIR)/$(BINARY_NAME)-linux-arm64 (64-bit)"
@@ -370,14 +321,11 @@ endif
## vet: Run go vet for static analysis
vet: generate
@packages="$$($(GO) list $(GOFLAGS) ./...)" && \
$(GO) vet $(GOFLAGS) $$(printf '%s\n' "$$packages" | grep -v '^github.com/sipeed/picoclaw/web/')
@cd web/backend && $(WEB_GO) vet ./...
@$(GO) vet $(GOFLAGS) ./...
## test: Test Go code
test: generate
@$(GO) test $(GOFLAGS) $$($(GO) list $(GOFLAGS) ./... | grep -v github.com/sipeed/picoclaw/web/)
@cd web && make test
@$(GO) test $(GOFLAGS) ./...
## integration-test: Run Docker-backed integration test suites
integration-test:
@@ -455,17 +403,6 @@ docker-clean:
docker compose -f docker/docker-compose.full.yml down -v
docker rmi picoclaw:latest picoclaw:full 2>/dev/null || true
## build-macos-app: Build PicoClaw macOS .app bundle (no terminal window)
build-macos-app:build-launcher
@echo "Building macOS .app bundle..."
@if [ "$(UNAME_S)" != "Darwin" ]; then \
echo "Error: This target is only available on macOS"; \
exit 1; \
fi
@./scripts/build-macos-app.sh $(PLATFORM)-$(ARCH)
@echo "macOS .app bundle created: $(BUILD_DIR)/PicoClaw.app"
## mem: Build membench, download LOCOMO data (if needed), run benchmark, and show results
mem:
@echo "Building membench..."
+61 -154
View File
@@ -64,8 +64,6 @@
</a>
</p>
2026-05-28 🚀 **v0.2.9 Released!** MCP server management in Web UI, configurable Sogou-backed web search, tool feedback animation in channels, `pretty_print` and `disable_escape_html` defaults, and numerous bug fixes across providers and channels.
2026-05-14 🚀 **v0.2.8 Released!** MCP CLI commands (`show`, `add`, `list`, `remove`, `test`, `edit`), empty object instead of null for MCP tool parameters, and build fixes.
2026-05-07 🚀 **v0.2.7 Released!** Configurable Sogou-backed web search, channel tool feedback animation, linter fixes.
@@ -74,16 +72,12 @@
2026-04-11 🚀 **v0.2.5 Released!** Zoneinfo from TZ/ZONEINFO env, Matrix CommonMark rendering alignment, `read_file` by lines.
2026-03-31 📱 **Android Support!** PicoClaw now runs on Android! Download the APK at [picoclaw.io](https://picoclaw.io/download)
2026-03-25 🚀 **v0.2.4 Released!** Agent architecture overhaul (SubTurn, Hooks, Steering, EventBus), WeChat/WeCom integration, security hardening (.security.yml, sensitive data filtering), new providers (AWS Bedrock, Azure, Xiaomi MiMo), and 35 bug fixes. PicoClaw has reached **26K Stars**!
2026-03-17 🚀 **v0.2.3 Released!** System tray UI (Windows & Linux), sub-agent status query (`spawn_status`), experimental Gateway hot-reload, Cron security gating, and 2 security fixes. PicoClaw has reached **25K Stars**!
2026-03-09 🎉 **v0.2.1 — Biggest update yet!** MCP protocol support, 4 new channels (Matrix/IRC/WeCom/Discord Proxy), 3 new providers (Kimi/Minimax/Avian), vision pipeline, JSONL memory store, model routing.
2026-02-28 📦 **v0.2.0** released with Docker Compose and Web UI Launcher support.
<details>
<summary>Earlier news...</summary>
@@ -184,8 +178,7 @@ Alternatively, download the binary for your platform from the [GitHub Releases](
Prerequisites:
- Go 1.25+
- Node.js 22+ and pnpm 10.33.0+ for Web UI / launcher builds
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -193,15 +186,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# Install frontend dependencies
(cd web/frontend && pnpm install --frozen-lockfile)
# Build the core binary for the current platform
make build
# Build the Web UI Launcher (required for WebUI mode)
make build-launcher
# Build core binaries for all Makefile-managed platforms
make build-all
@@ -218,140 +205,7 @@ make install
## 🚀 Quick Start Guide
### 🌐 WebUI Launcher (Recommended for Desktop)
The WebUI Launcher provides a browser-based interface for configuration and chat. This is the easiest way to get started — no command-line knowledge required.
**Option 1: Double-click (Desktop)**
After downloading from [picoclaw.io](https://picoclaw.io), double-click `picoclaw-launcher` (or `picoclaw-launcher.exe` on Windows). Your browser will open automatically at `http://localhost:18800`.
**Option 2: Command line**
```bash
picoclaw-launcher
# Open http://localhost:18800 in your browser
```
> [!TIP]
> **Remote access / Docker / VM:** Add the `-public` flag to listen on all interfaces:
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**Getting started:**
Open the WebUI, then: **1)** Configure a Provider (add your LLM API key) -> **2)** Configure a Channel (e.g., Telegram) -> **3)** Start the Gateway -> **4)** Chat!
For detailed WebUI documentation, see [docs.picoclaw.io](https://docs.picoclaw.io).
<details>
<summary><b>Docker (alternative)</b></summary>
```bash
# 1. Clone this repo
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. First run — auto-generates docker/data/config.json then exits
# (only triggers when both config.json and workspace/ are missing)
docker compose -f docker/docker-compose.yml --profile launcher up
# The container prints "First-run setup complete." and stops.
# 3. Set your API keys
vim docker/data/config.json
# 4. Start
docker compose -f docker/docker-compose.yml --profile launcher up -d
# Open http://localhost:18800
```
> **Docker / VM users:** The Gateway listens on `127.0.0.1` by default. Set `PICOCLAW_GATEWAY_HOST=0.0.0.0` or use the `-public` flag to make it accessible from the host.
```bash
# Check logs
docker compose -f docker/docker-compose.yml logs -f
# Stop
docker compose -f docker/docker-compose.yml --profile launcher down
# Update
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — First Launch Security Warning</b></summary>
macOS may block `picoclaw-launcher` on first launch because it is downloaded from the internet and not notarized through the Mac App Store.
**Step 1:** Double-click `picoclaw-launcher`. You will see a security warning:
<p align="center">
<img src="assets/macos-gatekeeper-warning.jpg" alt="macOS Gatekeeper warning" width="400">
</p>
> *"picoclaw-launcher" Not Opened — Apple could not verify "picoclaw-launcher" is free of malware that may harm your Mac or compromise your privacy.*
**Step 2:** Open **System Settings** → **Privacy & Security** → scroll down to the **Security** section → click **Open Anyway** → confirm by clicking **Open Anyway** in the dialog.
<p align="center">
<img src="assets/macos-gatekeeper-allow.jpg" alt="macOS Privacy & Security — Open Anyway" width="600">
</p>
After this one-time step, `picoclaw-launcher` will open normally on subsequent launches.
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android
Give your decade-old phone a second life! Turn it into a smart AI Assistant with PicoClaw.
**Option 1: APK Install**
Preview:
<table>
<tr>
<td><img src="assets/fui_main_page.jpg" width="200"></td>
<td><img src="assets/fui_web_page.jpg" width="200"></td>
<td><img src="assets/fui_log_page.jpg" width="200"></td>
<td><img src="assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
Download the APK from [picoclaw.io](https://picoclaw.io/download/) and install directly. No Termux required!
**Option 2: Termux**
For a full command-line setup checklist, see the [Android Termux Guide](docs/guides/android-termux.md).
<details>
<summary><b>Terminal Launcher (for resource-constrained environments)</b></summary>
1. Install [Termux](https://github.com/termux/termux-app) (download from [GitHub Releases](https://github.com/termux/termux-app/releases), or search in F-Droid / Google Play)
2. Run the following commands:
```bash
# Download the latest release
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot provides a standard Linux filesystem layout
```
Then follow the Terminal Launcher section below to complete configuration.
<img src="assets/termux.jpg" alt="PicoClaw on Termux" width="512">
For minimal environments where only the `picoclaw` core binary is available (no Launcher UI), you can configure everything via the command line and a JSON config file.
### CLI
**1. Initialize**
@@ -365,6 +219,7 @@ This creates `~/.picoclaw/config.json` and the workspace directory.
```json
{
"version": 3,
"agents": {
"defaults": {
"model_name": "gpt-5.4"
@@ -373,17 +228,17 @@ This creates `~/.picoclaw/config.json` and the workspace directory.
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4"
// api_key is now loaded from .security.yml
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
```
> See `config/config.example.json` in the repo for a complete configuration template with all available options.
>
> Please note: config.example.json format is version 0, with sensitive codes in it, and will be auto migrated to version 1+, then, the config.json will only store insensitive data, the sensitive codes will be stored in .security.yml, if you need manually modify the codes, please see `docs/security/security_configuration.md` for more details.
**3. Chat**
@@ -398,8 +253,60 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker (alternative)</b></summary>
```bash
# 1. Clone this repo
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. First run — auto-generates docker/data/config.json then exits
# (only triggers when both config.json and workspace/ are missing)
docker compose -f docker/docker-compose.yml --profile gateway up
# The container prints "First-run setup complete." and stops.
# 3. Set your API keys
vim docker/data/config.json
# 4. Start
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Docker / VM users:** The Gateway listens on `127.0.0.1` by default. For host access, set `PICOCLAW_GATEWAY_HOST=0.0.0.0` and publish the required ports in Compose.
```bash
# Check logs
docker compose -f docker/docker-compose.yml logs -f
# Stop
docker compose -f docker/docker-compose.yml --profile gateway down
# Update
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android (Termux)
1. Install [Termux](https://github.com/termux/termux-app) (download from [GitHub Releases](https://github.com/termux/termux-app/releases), or search in F-Droid / Google Play)
2. Run the following commands:
```bash
# Download the latest release
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot provides a standard Linux filesystem layout
```
<img src="assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](docs/guides/android-termux.md).
## 🔌 Providers (LLM)
PicoClaw supports 30+ LLM providers through the `model_list` configuration. Use the `protocol/model` format:
@@ -643,7 +550,7 @@ For detailed guides beyond this README:
| Topic | Description |
|-------|-------------|
| [Docker & Quick Start](docs/guides/docker.md) | Docker Compose setup, Launcher/Agent modes |
| [Docker & Quick Start](docs/guides/docker.md) | Docker Compose setup, Gateway/Agent modes |
| [Chat Apps](docs/guides/chat-apps.md) | All 18+ channel setup guides |
| [Configuration](docs/guides/configuration.md) | Environment variables, workspace layout, security sandbox |
| [MCP Server CLI](docs/reference/mcp-cli.md) | Add, list, test, edit, and remove MCP server entries from the CLI |
Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 449 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 233 KiB

-11
View File
@@ -1,11 +0,0 @@
FROM alpine:3.21
ARG TARGETPLATFORM
RUN apk add --no-cache ca-certificates tzdata
COPY $TARGETPLATFORM/picoclaw /usr/local/bin/picoclaw
COPY $TARGETPLATFORM/picoclaw-launcher /usr/local/bin/picoclaw-launcher
ENTRYPOINT ["picoclaw-launcher"]
CMD ["-console", "-public", "-no-browser"]
-65
View File
@@ -1,65 +0,0 @@
# ============================================================
# Stage 1: Build frontend assets (Node.js + pnpm)
# ============================================================
FROM node:24-alpine3.23 AS frontend
RUN corepack enable && corepack prepare pnpm@latest --activate
WORKDIR /src/web/frontend
# Cache frontend dependencies
COPY web/frontend/package.json web/frontend/pnpm-lock.yaml ./
RUN CI=true pnpm install --frozen-lockfile
# Build frontend
COPY web/frontend/ ./
RUN pnpm build:backend
# ============================================================
# Stage 2: Build Go binaries (picoclaw + picoclaw-launcher)
# ============================================================
FROM golang:1.25-alpine AS builder
RUN apk add --no-cache git make
WORKDIR /src
# Cache Go dependencies
COPY go.mod go.sum ./
RUN go mod download
# Copy source
COPY . .
# Copy pre-built frontend assets into the backend embed directory
COPY --from=frontend /src/web/backend/dist web/backend/dist
# Build picoclaw binary (includes go generate)
RUN make build
# Build picoclaw-launcher binary (frontend already built in stage 1)
# Mirror ldflags from web/Makefile to inject version metadata
RUN CONFIG_PKG=github.com/sipeed/picoclaw/pkg/config && \
VERSION=$(git describe --tags --always --dirty 2>/dev/null || echo dev) && \
GIT_COMMIT=$(git rev-parse --short=8 HEAD 2>/dev/null || echo dev) && \
BUILD_TIME=$(date +%FT%T%z) && \
GO_VERSION=$(go env GOVERSION) && \
CGO_ENABLED=0 go build -v -tags goolm,stdjson \
-ldflags "-X ${CONFIG_PKG}.Version=${VERSION} -X ${CONFIG_PKG}.GitCommit=${GIT_COMMIT} -X ${CONFIG_PKG}.BuildTime=${BUILD_TIME} -X ${CONFIG_PKG}.GoVersion=${GO_VERSION} -s -w" \
-o build/picoclaw-launcher ./web/backend/
# ============================================================
# Stage 3: Minimal runtime image
# ============================================================
FROM alpine:3.23
RUN apk add --no-cache ca-certificates tzdata curl
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget -q --spider http://localhost:18790/health || exit 1
COPY --from=builder /src/build/picoclaw /usr/local/bin/picoclaw
COPY --from=builder /src/build/picoclaw-launcher /usr/local/bin/picoclaw-launcher
ENTRYPOINT ["picoclaw-launcher"]
CMD ["-console", "-public", "-no-browser"]
-24
View File
@@ -38,27 +38,3 @@ services:
# - "host.docker.internal:host-gateway"
volumes:
- ./data:/root/.picoclaw
# ─────────────────────────────────────────────
# PicoClaw Launcher (Web Console + Gateway)
# docker compose -f docker/docker-compose.yml --profile launcher up
# ─────────────────────────────────────────────
picoclaw-launcher:
build:
context: ..
dockerfile: docker/Dockerfile.launcher
image: docker.io/sipeed/picoclaw:launcher
container_name: picoclaw-launcher
restart: unless-stopped
profiles:
- launcher
environment:
- PICOCLAW_GATEWAY_HOST=0.0.0.0
# Set a fixed dashboard token instead of a random one each restart.
# If not set, a random token is generated and printed to the console on startup.
#- PICOCLAW_LAUNCHER_TOKEN=your-secret-token-here
ports:
- "18800:18800"
- "18790:18790"
volumes:
- ./data:/root/.picoclaw
+2 -3
View File
@@ -83,7 +83,6 @@ Examples:
- `pkg/**/README.md`
- `cmd/**/README.md`
- `web/README.md`
- `examples/**/README.md`
These files still follow the same translation naming rules.
@@ -99,8 +98,8 @@ These files still follow the same translation naming rules.
## Examples
- New setup guide:
- `docs/guides/launcher-setup.md`
- `docs/guides/launcher-setup.zh.md`
- `docs/guides/session-guide.md`
- `docs/guides/session-guide.zh.md`
- New security guide:
- `docs/security/token-rotation.md`
- New translated package README:
-11
View File
@@ -10,7 +10,6 @@ It is the combined pipeline that decides:
3. whether the turn should use the agent's primary model or a configured light model
This document covers the runtime path in `pkg/routing` and its integration in `pkg/agent`.
It does not describe the launcher's HTTP `ServeMux` routes or the frontend's TanStack Router files under `web/`.
## Routing Layers
@@ -259,16 +258,6 @@ After a route is allocated, `pkg/agent/agent_utils.go:resolveScopeKey` preserves
That makes manual system flows, tests, and compatibility paths deterministic even when the normal routed scope would have produced a different key.
## What This Document Does Not Cover
The repository also contains two unrelated route systems:
- backend HTTP routes registered in `web/backend/api/router.go`
- frontend file routes under `web/frontend/src/routes/`
Those are launcher implementation details.
They are separate from the runtime routing system described here.
## Related Files
- `pkg/routing/route.go`
-10
View File
@@ -10,7 +10,6 @@
3. 这一轮该使用 agent 的主模型,还是配置中的轻量模型
本文覆盖 `pkg/routing` 及其在 `pkg/agent` 中的集成方式。
它不讨论 `web/` 目录下 launcher 的 HTTP `ServeMux` 路由,也不讨论前端 TanStack Router 文件路由。
## 路由分层
@@ -259,15 +258,6 @@ Agent 分发和模型路由发生在不同位置:
这样一来,手工系统流、测试和兼容路径即使在正常路由 scope 会生成不同 key 的情况下,仍然能保持确定性。
## 本文不覆盖的内容
仓库里还存在两套和这里无关的“route”系统:
- `web/backend/api/router.go` 注册的后端 HTTP 路由
- `web/frontend/src/routes/` 下的前端文件路由
它们属于 launcher 的实现细节,和本文描述的运行时路由系统是两回事。
## 相关文件
- `pkg/routing/route.go`
-2
View File
@@ -9,7 +9,6 @@ This document describes the runtime session system used by PicoClaw to:
- preserve compatibility with legacy `agent:...` session keys while the runtime uses opaque canonical keys
This document covers the core runtime path in `pkg/session`, `pkg/memory`, and `pkg/agent`.
It does not describe launcher login cookies or dashboard authentication sessions in `web/backend/middleware`.
## Responsibilities
@@ -237,7 +236,6 @@ That lets SubTurn reuse the same session-facing APIs without writing child-sessi
The session system is consumed by more than the agent loop:
- `web/backend/api/session.go` reads JSONL metadata and legacy JSON sessions to expose session history in the launcher UI.
- `pkg/agent/steering.go` can recover scope metadata for active steering flows.
- tooling and tests can still refer to legacy aliases because alias resolution is handled below the agent loop.
-2
View File
@@ -9,7 +9,6 @@
- 在运行时使用不透明 canonical key 的同时,继续兼容旧的 `agent:...` session key
本文覆盖 `pkg/session`、`pkg/memory` 和 `pkg/agent` 中的核心运行时链路。
它不讨论 `web/backend/middleware` 中 launcher 登录 Cookie 或 dashboard 鉴权 session。
## 职责
@@ -236,7 +235,6 @@ JSONL store 的设计核心是“追加优先、宁可暂时读到旧数据也
Session 系统不只被 agent loop 使用:
- `web/backend/api/session.go` 会读取 JSONL metadata 和旧 JSON session,并把历史暴露给 launcher UI。
- `pkg/agent/steering.go` 可以在 steering 场景下恢复 scope metadata。
- 因为 alias 解析发生在 agent loop 之下,测试和工具仍然可以继续使用 legacy alias。
+3 -11
View File
@@ -13,22 +13,14 @@ Ce canal remplace l'ancienne séparation `wecom`, `wecom_app` et `wecom_aibot` p
- Réponses en streaming côté canal via le protocole WeCom AI Bot
- Messages entrants : texte, voix, image, fichier, vidéo et messages mixtes
- Réponses sortantes : texte et médias (`image`, `file`, `voice`, `video`)
- Onboarding par QR code via l'interface Web ou le CLI
- Liaison par QR code via CLI
- Liste blanche partagée et routage `reasoning_channel_id`
---
## Démarrage rapide
### Option 1 : Liaison QR via l'interface Web (recommandé)
Ouvrez l'interface Web, accédez à **Channels → WeCom** et cliquez sur le bouton de liaison QR. Scannez le QR code avec WeCom et confirmez dans l'application — les identifiants sont enregistrés automatiquement.
<p align="center">
<img src="../../../assets/wecom-qr-binding.jpg" alt="Liaison QR WeCom dans l'interface Web" width="600">
</p>
### Option 2 : Connexion QR via le CLI
### Option 1 : Connexion QR via le CLI
Exécutez :
@@ -50,7 +42,7 @@ picoclaw auth wecom --timeout 10m
> ⚠️ Scanner le QR code ne suffit pas — vous devez également appuyer sur **Confirmer** dans l'application WeCom, sinon la commande expirera.
### Option 3 : Configuration manuelle
### Option 2 : Configuration manuelle
Si vous disposez déjà d'un `bot_id` et d'un `secret` depuis la plateforme WeCom AI Bot, configurez directement :
+3 -11
View File
@@ -13,22 +13,14 @@ PicoClaw は WeCom を公式 WeCom AI Bot WebSocket API に基づく単一の `c
- WeCom AI Bot プロトコルによるチャンネル側ストリーミング返信
- テキスト、音声、画像、ファイル、動画、ミックスメッセージの受信
- テキストおよびメディア返信の送信(`image`、`file`、`voice`、`video`)
- Web UI または CLI による QR コードオンボーディング
- CLI による QR コードオンボーディング
- 共有許可リストと `reasoning_channel_id` ルーティング
---
## クイックスタート
### オプション 1:Web UI QR バインディング(推奨)
Web UI を開き、**Channels → WeCom** に移動して、QR バインディングボタンをクリックします。WeCom で QR コードをスキャンし、アプリ内で確認すると、認証情報が自動的に保存されます。
<p align="center">
<img src="../../../assets/wecom-qr-binding.jpg" alt="Web UI での WeCom QR バインディング" width="600">
</p>
### オプション 2:CLI QR ログイン
### オプション 1:CLI QR ログイン
実行:
@@ -50,7 +42,7 @@ picoclaw auth wecom --timeout 10m
> ⚠️ QR コードのスキャンだけでは不十分です — WeCom アプリ内で **確認** をタップする必要があります。そうしないとコマンドがタイムアウトします。
### オプション 3:手動設定
### オプション 2:手動設定
WeCom AI Bot プラットフォームから `bot_id` と `secret` を既にお持ちの場合、直接設定できます:
+3 -11
View File
@@ -13,22 +13,14 @@ This replaces the legacy `wecom`, `wecom_app`, and `wecom_aibot` split with one
- Channel-side streaming replies over WeCom's AI Bot protocol
- Incoming text, voice, image, file, video, and mixed messages
- Outbound text and media replies (`image`, `file`, `voice`, `video`)
- QR-based onboarding via Web UI or CLI
- QR-based onboarding via CLI
- Shared allowlist and `reasoning_channel_id` routing
---
## Quick Start
### Option 1: Web UI QR Binding (Recommended)
Open the Web UI, navigate to **Channels → WeCom**, and click the QR binding button. Scan the QR code with WeCom and confirm in the app — credentials are saved automatically.
<p align="center">
<img src="../../../assets/wecom-qr-binding.jpg" alt="WeCom QR binding in Web UI" width="600">
</p>
### Option 2: CLI QR Login
### Option 1: CLI QR Login
Run:
@@ -50,7 +42,7 @@ picoclaw auth wecom --timeout 10m
> ⚠️ Scanning the QR code is not enough — you must also tap **Confirm** inside the WeCom app, otherwise the command will time out.
### Option 3: Configure Manually
### Option 2: Configure Manually
If you already have a `bot_id` and `secret` from the WeCom AI Bot platform, configure directly:
+3 -11
View File
@@ -13,22 +13,14 @@ Isso substitui a antiga separação `wecom`, `wecom_app` e `wecom_aibot` por um
- Respostas em streaming pelo protocolo WeCom AI Bot
- Mensagens recebidas: texto, voz, imagem, arquivo, vídeo e mensagens mistas
- Respostas enviadas: texto e mídia (`image`, `file`, `voice`, `video`)
- Onboarding por QR code via Web UI ou CLI
- Onboarding por QR code via CLI
- Lista de permissões compartilhada e roteamento `reasoning_channel_id`
---
## Início Rápido
### Opção 1: Vinculação QR via Web UI (Recomendado)
Abra a Web UI, navegue até **Channels → WeCom** e clique no botão de vinculação QR. Escaneie o QR code com o WeCom e confirme no aplicativo — as credenciais são salvas automaticamente.
<p align="center">
<img src="../../../assets/wecom-qr-binding.jpg" alt="Vinculação QR do WeCom na Web UI" width="600">
</p>
### Opção 2: Login QR via CLI
### Opção 1: Login QR via CLI
Execute:
@@ -50,7 +42,7 @@ picoclaw auth wecom --timeout 10m
> ⚠️ Escanear o QR code não é suficiente — você também deve tocar em **Confirmar** dentro do aplicativo WeCom, caso contrário o comando expirará.
### Opção 3: Configuração Manual
### Opção 2: Configuração Manual
Se você já possui um `bot_id` e `secret` da plataforma WeCom AI Bot, configure diretamente:
+3 -11
View File
@@ -13,22 +13,14 @@ PicoClaw cung cấp WeCom dưới dạng một kênh duy nhất `channels.wecom`
- Phản hồi streaming qua giao thức WeCom AI Bot
- Nhận tin nhắn văn bản, giọng nói, hình ảnh, tệp, video và tin nhắn hỗn hợp
- Gửi phản hồi văn bản và phương tiện (`image`, `file`, `voice`, `video`)
- Đăng ký qua mã QR bằng Web UI hoặc CLI
- Đăng ký qua mã QR bằng CLI
- Danh sách cho phép chung và định tuyến `reasoning_channel_id`
---
## Bắt đầu nhanh
### Tùy chọn 1: Liên kết QR qua Web UI (Khuyến nghị)
Mở Web UI, điều hướng đến **Channels → WeCom** và nhấp vào nút liên kết QR. Quét mã QR bằng WeCom và xác nhận trong ứng dụng — thông tin đăng nhập được lưu tự động.
<p align="center">
<img src="../../../assets/wecom-qr-binding.jpg" alt="Liên kết QR WeCom trong Web UI" width="600">
</p>
### Tùy chọn 2: Đăng nhập QR qua CLI
### Tùy chọn 1: Đăng nhập QR qua CLI
Chạy:
@@ -50,7 +42,7 @@ picoclaw auth wecom --timeout 10m
> ⚠️ Quét mã QR là chưa đủ — bạn cũng phải nhấn **Xác nhận** trong ứng dụng WeCom, nếu không lệnh sẽ hết thời gian chờ.
### Tùy chọn 3: Cấu hình thủ công
### Tùy chọn 2: Cấu hình thủ công
Nếu bạn đã có `bot_id` và `secret` từ nền tảng WeCom AI Bot, hãy cấu hình trực tiếp:
+3 -11
View File
@@ -13,22 +13,14 @@ PicoClaw 将企业微信整合为单一的 `channels.wecom` 渠道,基于腾
- 基于企业微信 AI Bot 协议的流式回复
- 接收文本、语音、图片、文件、视频及混合消息
- 发送文本及媒体消息(`image`、`file`、`voice`、`video`)
- 通过 Web UI 或 CLI 扫码绑定
- 通过 CLI 扫码绑定
- 发送者白名单和 `reasoning_channel_id` 路由
---
## 快速开始
### 方式一:Web UI 扫码绑定(推荐)
打开 Web UI,进入 **Channels → WeCom**,点击扫码绑定按钮。用企业微信扫码并在 App 内确认,凭据自动保存。
<p align="center">
<img src="../../../assets/wecom-qr-binding.jpg" alt="Web UI 企业微信扫码绑定" width="600">
</p>
### 方式二:CLI 扫码登录
### 方式一:CLI 扫码登录
运行:
@@ -50,7 +42,7 @@ picoclaw auth wecom --timeout 10m
> ⚠️ 仅扫描二维码还不够——必须在企业微信 App 内点击**确认**,否则命令会超时。
### 方式三:手动配置
### 方式二:手动配置
如果已有企业微信 AI Bot 的 `bot_id` 和 `secret`,可直接配置:
@@ -32,8 +32,6 @@
- 配置项:`tools.serial.enabled`
- Tool 注册:`pkg/agent/agent_init.go`
- Web 工具页:`/api/tools` 能展示与切换 `serial`
- 前端状态文案:新增 `requires_serial_platform`
## Serial Tool 设计
+1 -1
View File
@@ -2,7 +2,7 @@
Task-oriented guides for setup, configuration, and common PicoClaw workflows.
- [Docker & Quick Start Guide](docker.md): install and run PicoClaw with Docker or the launcher.
- [Docker & Quick Start Guide](docker.md): install and run PicoClaw with Docker or the CLI.
- [Android Termux Guide](android-termux.md): run the PicoClaw terminal binary on an ARM64 Android phone.
- [Configuration Guide](configuration.md): environment variables, workspace layout, routing, and sandbox settings.
- [Session Guide](session-guide.md): how session scope affects memory sharing, summaries, and isolation.
+1 -1
View File
@@ -2,7 +2,7 @@
> Back to [Guides](README.md)
This guide covers running the PicoClaw terminal binary on an ARM64 Android phone with Termux. Use the APK from [picoclaw.io](https://picoclaw.io/download/) if you want the Android app experience; use Termux when you want a lightweight command-line install on an older or resource-constrained device.
This guide covers running the PicoClaw terminal binary on an ARM64 Android phone with Termux for a lightweight command-line install.
## Requirements
+1 -1
View File
@@ -412,7 +412,7 @@ L'ancienne configuration `providers` est **dépréciée** et a été supprimée
Le streaming provider utilise un double opt-in et est désactivé par défaut. L'agent ne tente le streaming que lorsque le channel courant a `settings.streaming.enabled: true`, que l'entrée de modèle active a `streaming.enabled: true`, et que le provider comme le channel prennent en charge le streaming. Si une condition manque, PicoClaw utilise le chemin de requête non-streaming normal.
Pico WebUI est le premier channel entièrement câblé. Pico crée le premier message assistant avec le message wire existant `message.create`, puis met à jour ce même message avec `message.update`; aucun nouveau type de message Pico n'est introduit.
Pico est le premier channel entièrement câblé. Pico crée le premier message assistant avec le message wire existant `message.create`, puis met à jour ce même message avec `message.update`; aucun nouveau type de message Pico n'est introduit.
Laissez `streaming` absent si vous ne voulez pas de streaming. Un bloc `streaming` omis signifie désactivé; il n'est pas nécessaire d'écrire `"streaming": {"enabled": false}`.
+1 -1
View File
@@ -35,7 +35,7 @@ PICOCLAW_HOME=/srv/picoclaw PICOCLAW_CONFIG=/srv/picoclaw/main.json picoclaw gat
Lo streaming del provider usa un double opt-in ed è disattivato per impostazione predefinita. L'agent prova lo streaming solo quando il canale corrente ha `settings.streaming.enabled: true`, l'entry del modello attivo ha `streaming.enabled: true`, e sia il provider sia il canale supportano lo streaming. Se manca una qualsiasi condizione, PicoClaw usa il normale percorso di richiesta non streaming.
Pico WebUI è il primo canale completamente collegato. Pico crea il primo messaggio assistant con il wire message esistente `message.create`, poi aggiorna lo stesso messaggio con `message.update`; non viene introdotto alcun nuovo tipo di wire message Pico.
Pico è il primo canale completamente collegato. Pico crea il primo messaggio assistant con il wire message esistente `message.create`, poi aggiorna lo stesso messaggio con `message.update`; non viene introdotto alcun nuovo tipo di wire message Pico.
Lascia `streaming` assente quando non vuoi usare lo streaming. Un blocco `streaming` omesso significa disattivato; non è necessario scrivere `"streaming": {"enabled": false}`.
+1 -1
View File
@@ -413,7 +413,7 @@ HEARTBEAT_OK を返信 ユーザーが直接結果を受信
Provider ストリーミングは二重の opt-in 方式で、デフォルトでは無効です。現在の channel に `settings.streaming.enabled: true` があり、アクティブなモデルエントリに `streaming.enabled: true` があり、さらに provider と channel の両方がストリーミングをサポートしている場合にのみ、agent はストリーミングリクエストを試行します。いずれかの条件が欠ける場合、PicoClaw は通常の非ストリーミングリクエスト経路を使います。
Pico WebUI が最初に完全対応した channel です。Pico は既存の `message.create` wire message で最初の assistant メッセージを作成し、その後 `message.update` で同じメッセージを更新します。新しい Pico wire message type は追加されません。
Pico が最初に完全対応した channel です。Pico は既存の `message.create` wire message で最初の assistant メッセージを作成し、その後 `message.update` で同じメッセージを更新します。新しい Pico wire message type は追加されません。
ストリーミングを使わない場合は `streaming` を省略してください。`streaming` ブロックの省略は無効を意味するため、`"streaming": {"enabled": false}` を書く必要はありません。
+1 -14
View File
@@ -143,19 +143,6 @@ Example clean web policy:
}
```
### Web launcher dashboard
**picoclaw-launcher** serves a browser UI that requires password sign-in first. On first run, open `/launcher-setup` to create the dashboard password. Later manual sign-ins use `/launcher-login`.
- **Config file**: Same directory as `config.json` (or the file pointed to by `PICOCLAW_CONFIG`). The launcher-specific file is `launcher-config.json`.
- **Password storage**: On supported platforms, the password is stored as a bcrypt hash in `launcher-auth.db`. On platforms where the SQLite password store is unavailable, the bcrypt hash is stored in `launcher-config.json`.
- **Legacy migration**: Older `launcher_token` values are migrated once into password login and removed from saved launcher config.
- **Local auto-login**: When the launcher auto-opens a local browser after startup, it uses a one-shot loopback-only bootstrap endpoint to set the session cookie automatically.
- **Unsupported auth paths**: URL token login (`?token=...`), `PICOCLAW_LAUNCHER_TOKEN`, and `Authorization: Bearer` dashboard auth are no longer supported.
- **Sign-out**: Use **`POST /api/auth/logout`** with **`Content-Type: application/json`** (body may be `{}`). Do not rely on a GET URL for logout (CSRF-safe pattern).
- **Brute-force**: **`POST /api/auth/login`** is **rate-limited per client IP per minute** (HTTP 429 when exceeded).
- **Session lifetime**: The HttpOnly session cookie lasts about **31 days** by default, but sessions are invalidated when the launcher process restarts.
### Skill Sources
By default, skills are loaded from:
@@ -795,7 +782,7 @@ Resolution rules:
Provider streaming uses a double opt-in and is disabled by default. The agent only tries streaming when the current channel has `settings.streaming.enabled: true`, the active model entry has `streaming.enabled: true`, and both the provider and channel support streaming. If any condition is missing, PicoClaw uses the normal non-streaming request path.
Pico WebUI is the first fully wired channel. Pico creates the first assistant message with the existing `message.create` wire message, then updates that same message with `message.update`; no new Pico wire message type is introduced.
Pico is the first fully wired channel. Pico creates the first assistant message with the existing `message.create` wire message, then updates that same message with `message.update`; no new Pico wire message type is introduced.
Leave `streaming` unset when you do not want streaming. An omitted `streaming` block means disabled; you do not need to write `"streaming": {"enabled": false}`.
+1 -1
View File
@@ -35,7 +35,7 @@ PICOCLAW_HOME=/srv/picoclaw PICOCLAW_CONFIG=/srv/picoclaw/main.json picoclaw gat
Provider streaming menggunakan double opt-in dan dimatikan secara lalai. Agent hanya mencuba streaming apabila saluran semasa mempunyai `settings.streaming.enabled: true`, entry model aktif mempunyai `streaming.enabled: true`, dan kedua-dua provider serta saluran menyokong streaming. Jika mana-mana syarat tiada, PicoClaw menggunakan laluan permintaan bukan streaming biasa.
Pico WebUI ialah saluran pertama yang disambungkan sepenuhnya. Pico mencipta mesej assistant pertama dengan wire message sedia ada `message.create`, kemudian mengemas kini mesej yang sama dengan `message.update`; tiada jenis wire message Pico baharu ditambah.
Pico ialah saluran pertama yang disambungkan sepenuhnya. Pico mencipta mesej assistant pertama dengan wire message sedia ada `message.create`, kemudian mengemas kini mesej yang sama dengan `message.update`; tiada jenis wire message Pico baharu ditambah.
Biarkan `streaming` tidak ditetapkan jika anda tidak mahu streaming. Blok `streaming` yang tiada bermaksud dimatikan; anda tidak perlu menulis `"streaming": {"enabled": false}`.
+1 -1
View File
@@ -413,7 +413,7 @@ A configuração antiga `providers` está **depreciada** e foi removida no V2. C
O streaming do provider usa double opt-in e fica desativado por padrão. O agent só tenta streaming quando o canal atual tem `settings.streaming.enabled: true`, a entrada de modelo ativa tem `streaming.enabled: true`, e tanto o provider quanto o canal suportam streaming. Se qualquer condição estiver ausente, o PicoClaw usa o caminho normal de requisição sem streaming.
O Pico WebUI é o primeiro canal totalmente integrado. O Pico cria a primeira mensagem assistant com o wire message existente `message.create` e depois atualiza a mesma mensagem com `message.update`; nenhum novo tipo de wire message do Pico é introduzido.
O Pico é o primeiro canal totalmente integrado. O Pico cria a primeira mensagem assistant com o wire message existente `message.create` e depois atualiza a mesma mensagem com `message.update`; nenhum novo tipo de wire message do Pico é introduzido.
Deixe `streaming` ausente quando não quiser streaming. Um bloco `streaming` omitido significa desativado; você não precisa escrever `"streaming": {"enabled": false}`.
+1 -1
View File
@@ -413,7 +413,7 @@ Cấu hình `providers` cũ đã **bị deprecated** và đã được loại b
Provider streaming dùng cơ chế double opt-in và bị tắt theo mặc định. Agent chỉ thử streaming khi channel hiện tại có `settings.streaming.enabled: true`, entry model đang dùng có `streaming.enabled: true`, và cả provider lẫn channel đều hỗ trợ streaming. Nếu thiếu bất kỳ điều kiện nào, PicoClaw dùng đường dẫn yêu cầu không streaming thông thường.
Pico WebUI là channel đầu tiên được nối đầy đủ. Pico tạo message assistant đầu tiên bằng wire message hiện có `message.create`, sau đó cập nhật chính message đó bằng `message.update`; không thêm loại wire message Pico mới.
Pico là channel đầu tiên được nối đầy đủ. Pico tạo message assistant đầu tiên bằng wire message hiện có `message.create`, sau đó cập nhật chính message đó bằng `message.update`; không thêm loại wire message Pico mới.
Hãy để trống `streaming` khi bạn không muốn dùng streaming. Bỏ qua block `streaming` nghĩa là đã tắt; bạn không cần viết `"streaming": {"enabled": false}`.
+1 -14
View File
@@ -141,19 +141,6 @@ PicoClaw 将数据存储在您配置的工作区中(默认:`~/.picoclaw/work
}
```
### Web 启动器控制台
用 **picoclaw-launcher** 打开浏览器控制台前需要先使用密码登录。首次启动时打开 `/launcher-setup` 创建 dashboard 登录密码;后续手动登录使用 `/launcher-login`。
- **配置文件**:与 `config.json` 同一目录(若设置了 `PICOCLAW_CONFIG`,则与它所指的文件同目录)。启动器专用文件名为 `launcher-config.json`。
- **密码存储**:支持的平台会把 bcrypt 后的密码哈希存入 `launcher-auth.db`。如果当前平台不支持 SQLite 密码存储,则把 bcrypt 哈希存入 `launcher-config.json`。
- **旧配置迁移**:旧版 `launcher_token` 会一次性迁移为密码登录,并从保存后的 launcher 配置中移除。
- **本地自动登录**:launcher 启动后自动打开本地浏览器时,会使用仅允许 loopback 访问的一次性引导入口自动设置会话 Cookie。
- **不再支持的鉴权方式**:不再支持 URL token 登录(`?token=...`)、`PICOCLAW_LAUNCHER_TOKEN` 和 `Authorization: Bearer` dashboard 鉴权。
- **退出登录**:应使用 **`POST /api/auth/logout`**,且请求头为 **`Content-Type: application/json`**(请求体可为 `{}`),勿使用可被第三方页面触发的 GET 链接登出。
- **暴力尝试**:`POST /api/auth/login` 对同一远程地址有 **每分钟尝试次数上限**(超限返回 HTTP 429)。
- **会话时长**:登录后的 HttpOnly 会话 Cookie 默认约 **31 天**有效,但 launcher 进程重启后已有会话会失效。
### 技能来源 (Skill Sources)
默认情况下,技能会按以下顺序加载:
@@ -587,7 +574,7 @@ Agent 读取 HEARTBEAT.md
Provider 流式输出采用双开关,默认关闭。只有当前 channel 的 `settings.streaming.enabled` 和当前模型条目的 `streaming.enabled` 都为 `true`,并且 provider 与 channel 都支持流式能力时,Agent 才会尝试流式请求;任一条件不满足时仍使用普通非流式请求。
当前完整落地的是 Pico WebUI。Pico 使用已有的 `message.create` 创建第一条 assistant 消息,随后用 `message.update` 更新同一条消息,不新增协议消息类型。
当前完整落地的是 Pico。Pico 使用已有的 `message.create` 创建第一条 assistant 消息,随后用 `message.update` 更新同一条消息,不新增协议消息类型。
不需要流式时请省略 `streaming` 配置块。省略表示关闭,不需要写 `"streaming": {"enabled": false}`。
-13
View File
@@ -34,19 +34,6 @@ docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway
docker compose -f docker/docker-compose.yml --profile gateway down
```
### Mode Launcher (Console Web)
L'image `launcher` inclut les deux binaires (`picoclaw`, `picoclaw-launcher`) et démarre la console web par défaut, qui fournit une interface navigateur pour la configuration et le chat.
```bash
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
Ouvrez http://localhost:18800 dans votre navigateur. Le launcher gère automatiquement le processus gateway.
> [!WARNING]
> La console web est protégée par un mot de passe de connexion au dashboard. Ne l'exposez pas à des réseaux non fiables ni à Internet public.
### Mode Agent (One-shot)
```bash
-13
View File
@@ -34,19 +34,6 @@ docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway
docker compose -f docker/docker-compose.yml --profile gateway down
```
### Launcher モード (Web コンソール)
`launcher` イメージには 2 つのバイナリ(`picoclaw`、`picoclaw-launcher`)が含まれており、デフォルトで Web コンソールを起動します。ブラウザベースの設定・チャット画面を提供します。
```bash
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
ブラウザで http://localhost:18800 を開いてください。Launcher が Gateway プロセスを自動管理します。
> [!WARNING]
> Web コンソールは dashboard ログインパスワードで保護されます。信頼できないネットワークや公開インターネットには公開しないでください。
### Agent モード (ワンショット)
```bash
+1 -14
View File
@@ -27,7 +27,7 @@ docker compose -f docker/docker-compose.yml --profile gateway up -d
> **Docker Users**: By default, the Gateway listens on `127.0.0.1` which is not accessible from the host. If you need to access the health endpoints or expose ports, set `PICOCLAW_GATEWAY_HOST=0.0.0.0` in your environment or update `config.json`.
> [!NOTE]
> The `gateway` profile only serves the webhook handlers (including Pico when enabled) and health endpoints on the gateway port, so it does not expose generic REST chat endpoints such as `/chat` or `/a2a`. Launcher mode adds the browser UI plus `/api/pico/info` and an authenticated `/pico/ws` proxy on the launcher port, but `/pico/ws` is also available directly on the gateway whenever the Pico channel is enabled.
> The `gateway` profile only serves the webhook handlers (including Pico when enabled) and health endpoints on the gateway port, so it does not expose generic REST chat endpoints such as `/chat` or `/a2a`. The `/pico/ws` endpoint is available directly on the gateway whenever the Pico channel is enabled.
```bash
# 5. Check logs
@@ -37,19 +37,6 @@ docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway
docker compose -f docker/docker-compose.yml --profile gateway down
```
### Launcher Mode (Web Console)
The `launcher` image includes both binaries (`picoclaw`, `picoclaw-launcher`) and starts the web console by default, which provides a browser-based UI for configuration and chat.
```bash
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
Open http://localhost:18800 in your browser. The launcher manages the gateway process automatically.
> [!WARNING]
> The web console is protected by dashboard password login. **Do not** expose the launcher to untrusted networks or the public internet. See [Web launcher dashboard](configuration.md#web-launcher-dashboard) in the Configuration Guide.
### Agent Mode (One-shot)
```bash
-13
View File
@@ -33,19 +33,6 @@ docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway
docker compose -f docker/docker-compose.yml --profile gateway down
```
### Mod Launcher (Konsol Web)
Imej `launcher` merangkumi kedua-dua binari (`picoclaw`, `picoclaw-launcher`) dan memulakan konsol web secara lalai, yang menyediakan UI berasaskan pelayar untuk konfigurasi dan sembang.
```bash
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
Buka http://localhost:18800 dalam pelayar anda. Launcher mengurus proses gateway secara automatik.
> [!WARNING]
> Konsol web dilindungi oleh kata laluan log masuk dashboard. Jangan dedahkannya kepada rangkaian tidak dipercayai atau internet awam.
### Mod Agent (One-shot)
```bash
-13
View File
@@ -34,19 +34,6 @@ docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway
docker compose -f docker/docker-compose.yml --profile gateway down
```
### Modo Launcher (Console Web)
A imagem `launcher` inclui ambos os binários (`picoclaw`, `picoclaw-launcher`) e inicia o console web por padrão, que fornece uma interface baseada em navegador para configuração e chat.
```bash
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
Abra http://localhost:18800 no seu navegador. O launcher gerencia o processo do gateway automaticamente.
> [!WARNING]
> O console web é protegido por senha de login do dashboard. Não exponha o launcher a redes não confiáveis nem à internet pública.
### Modo Agent (One-shot)
```bash
-13
View File
@@ -34,19 +34,6 @@ docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway
docker compose -f docker/docker-compose.yml --profile gateway down
```
### Chế Độ Launcher (Web Console)
Image `launcher` bao gồm cả hai binary (`picoclaw`, `picoclaw-launcher`) và khởi động web console mặc định, cung cấp giao diện trình duyệt để cấu hình và chat.
```bash
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
Mở http://localhost:18800 trong trình duyệt. Launcher tự động quản lý tiến trình gateway.
> [!WARNING]
> Web console được bảo vệ bằng mật khẩu đăng nhập dashboard. Không để lộ launcher ra mạng không tin cậy hoặc internet công cộng.
### Chế Độ Agent (One-shot)
```bash
-13
View File
@@ -34,19 +34,6 @@ docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway
docker compose -f docker/docker-compose.yml --profile gateway down
```
### Launcher 模式 (Web 控制台)
`launcher` 镜像包含两个二进制文件(`picoclaw`、`picoclaw-launcher`),默认启动 Web 控制台,提供基于浏览器的配置和聊天界面。
```bash
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
在浏览器中打开 <http://localhost:18800>。Launcher 会自动管理 Gateway 进程。
> [!WARNING]
> Web 控制台通过 dashboard 登录密码保护。**不要**将启动器暴露到不可信网络或公网。完整说明见 [配置指南](configuration.md) 中的「Web 启动器控制台」一节。
### Agent 模式 (一次性运行)
```bash
+59 -147
View File
@@ -65,16 +65,12 @@
</a>
</p>
2026-03-31 📱 **Support Android !** PicoClaw fonctionne maintenant sur Android ! Téléchargez l'APK sur [picoclaw.io](https://picoclaw.io/download)
2026-03-25 🚀 **v0.2.4 publiée !** Refonte de l'architecture Agent (SubTurn, Hooks, Steering, EventBus), intégration WeChat/WeCom, renforcement de la sécurité (.security.yml, filtrage des données sensibles), nouveaux providers (AWS Bedrock, Azure, Xiaomi MiMo), et 35 corrections de bugs. PicoClaw a atteint **26K Stars** !
2026-03-17 🚀 **v0.2.3 publiée !** Interface system tray (Windows & Linux), requête de statut des sous-agents (`spawn_status`), rechargement à chaud expérimental du Gateway, sécurisation Cron, et 2 correctifs de sécurité. PicoClaw a atteint **25K Stars** !
2026-03-09 🎉 **v0.2.1 — Plus grande mise à jour à ce jour !** Support du protocole MCP, 4 nouveaux channels (Matrix/IRC/WeCom/Discord Proxy), 3 nouveaux providers (Kimi/Minimax/Avian), pipeline vision, stockage mémoire JSONL, routage de modèles.
2026-02-28 📦 **v0.2.0** publiée avec support Docker Compose et Web UI Launcher.
<details>
<summary>Actualités précédentes...</summary>
@@ -177,8 +173,7 @@ Vous pouvez aussi télécharger le binaire pour votre plateforme depuis la page
Prérequis :
- Go 1.25+
- Node.js 22+ et pnpm 10.33.0+ pour les builds Web UI / launcher
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -186,15 +181,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# Installer les dépendances frontend
(cd web/frontend && pnpm install --frozen-lockfile)
# Compiler le binaire principal
make build
# Compiler le Web UI Launcher (requis pour le mode WebUI)
make build-launcher
# Compiler les binaires core pour toutes les plateformes gérées par le Makefile
make build-all
@@ -209,138 +198,7 @@ make install
## 🚀 Guide de démarrage rapide
### 🌐 WebUI Launcher (Recommandé pour le bureau)
Le WebUI Launcher fournit une interface basée sur navigateur pour la configuration et le chat. C'est la façon la plus simple de démarrer — aucune connaissance de la ligne de commande requise.
**Option 1 : Double-clic (Bureau)**
Après téléchargement depuis [picoclaw.io](https://picoclaw.io), double-cliquez sur `picoclaw-launcher` (ou `picoclaw-launcher.exe` sous Windows). Votre navigateur s'ouvrira automatiquement sur `http://localhost:18800`.
**Option 2 : Ligne de commande**
```bash
picoclaw-launcher
# Ouvrez http://localhost:18800 dans votre navigateur
```
> [!TIP]
> **Accès distant / Docker / VM :** Ajoutez le flag `-public` pour écouter sur toutes les interfaces :
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**Pour commencer :**
Ouvrez le WebUI, puis : **1)** Configurez un Provider (ajoutez votre clé API LLM) -> **2)** Configurez un Channel (ex. Telegram) -> **3)** Démarrez le Gateway -> **4)** Chattez !
Pour la documentation détaillée du WebUI, voir [docs.picoclaw.io](https://docs.picoclaw.io).
<details>
<summary><b>Docker (alternative)</b></summary>
```bash
# 1. Cloner ce dépôt
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Premier lancement — génère automatiquement docker/data/config.json puis s'arrête
# (se déclenche uniquement quand config.json et workspace/ sont tous deux absents)
docker compose -f docker/docker-compose.yml --profile launcher up
# Le conteneur affiche "First-run setup complete." et s'arrête.
# 3. Définir vos clés API
vim docker/data/config.json
# 4. Démarrer
docker compose -f docker/docker-compose.yml --profile launcher up -d
# Ouvrez http://localhost:18800
```
> **Utilisateurs Docker / VM :** Le Gateway écoute sur `127.0.0.1` par défaut. Définissez `PICOCLAW_GATEWAY_HOST=0.0.0.0` ou utilisez le flag `-public` pour le rendre accessible depuis l'hôte.
```bash
# Vérifier les logs
docker compose -f docker/docker-compose.yml logs -f
# Arrêter
docker compose -f docker/docker-compose.yml --profile launcher down
# Mettre à jour
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — Avertissement de sécurité au premier lancement</b></summary>
macOS peut bloquer `picoclaw-launcher` au premier lancement car il est téléchargé depuis Internet et n'est pas notarisé via le Mac App Store.
**Étape 1 :** Double-cliquez sur `picoclaw-launcher`. Un avertissement de sécurité s'affiche :
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="Avertissement macOS Gatekeeper" width="400">
</p>
> *"picoclaw-launcher" n'a pas pu être ouvert — Apple n'a pas pu vérifier que "picoclaw-launcher" ne contient pas de logiciel malveillant susceptible de nuire à votre Mac ou de compromettre votre confidentialité.*
**Étape 2 :** Ouvrez **Réglages Système** → **Confidentialité et sécurité** → faites défiler jusqu'à la section **Sécurité** → cliquez sur **Ouvrir quand même** → confirmez en cliquant sur **Ouvrir quand même** dans la boîte de dialogue.
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS Confidentialité et sécurité — Ouvrir quand même" width="600">
</p>
Après cette étape unique, `picoclaw-launcher` s'ouvrira normalement lors des lancements suivants.
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android
Donnez une seconde vie à votre téléphone vieux de dix ans ! Transformez-le en assistant IA intelligent avec PicoClaw.
**Option 1 : Installation APK**
Aperçu :
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
Téléchargez l'APK depuis [picoclaw.io](https://picoclaw.io/download/) et installez-le directement. Pas besoin de Termux !
**Option 2 : Termux**
<details>
<summary><b>Terminal Launcher (pour les environnements à ressources limitées)</b></summary>
1. Installez [Termux](https://github.com/termux/termux-app) (téléchargez depuis [GitHub Releases](https://github.com/termux/termux-app/releases), ou cherchez dans F-Droid / Google Play)
2. Exécutez les commandes suivantes :
```bash
# Télécharger la dernière version
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot fournit une arborescence Linux standard
```
Suivez ensuite la section Terminal Launcher ci-dessous pour terminer la configuration.
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
Pour les environnements minimaux où seul le binaire principal `picoclaw` est disponible (sans Launcher UI), vous pouvez tout configurer via la ligne de commande et un fichier de configuration JSON.
### CLI
**1. Initialiser**
@@ -363,8 +221,11 @@ Cela crée `~/.picoclaw/config.json` et le répertoire workspace.
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_keys": ["sk-your-api-key"]
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
@@ -385,8 +246,59 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker (alternative)</b></summary>
```bash
# 1. Cloner ce dépôt
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Premier lancement — génère automatiquement docker/data/config.json puis s'arrête
# (se déclenche uniquement quand config.json et workspace/ sont tous deux absents)
docker compose -f docker/docker-compose.yml --profile gateway up
# Le conteneur affiche "First-run setup complete." et s'arrête.
# 3. Définir vos clés API
vim docker/data/config.json
# 4. Démarrer
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Utilisateurs Docker / VM :** Le Gateway écoute sur `127.0.0.1` par défaut. Définissez `PICOCLAW_GATEWAY_HOST=0.0.0.0` ou utilisez le flag `-public` pour le rendre accessible depuis l'hôte.
```bash
# Vérifier les logs
docker compose -f docker/docker-compose.yml logs -f
# Arrêter
docker compose -f docker/docker-compose.yml --profile gateway down
# Mettre à jour
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android (Termux)
1. Installez [Termux](https://github.com/termux/termux-app) (téléchargez depuis [GitHub Releases](https://github.com/termux/termux-app/releases), ou cherchez dans F-Droid / Google Play)
2. Exécutez les commandes suivantes :
```bash
# Télécharger la dernière version
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot fournit une arborescence Linux standard
```
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 Providers (LLM)
@@ -593,7 +505,7 @@ Pour des guides détaillés au-delà de ce README :
| Sujet | Description |
|-------|-------------|
| [Docker & Démarrage rapide](../guides/docker.fr.md) | Configuration Docker Compose, modes Launcher/Agent |
| [Docker & Démarrage rapide](../guides/docker.fr.md) | Configuration Docker Compose, modes Gateway/Agent |
| [Applications de chat](../guides/chat-apps.fr.md) | Guides de configuration pour les 17+ channels |
| [Configuration](../guides/configuration.fr.md) | Variables d'environnement, structure du workspace, sandbox de sécurité |
| [Providers & Modèles](../guides/providers.fr.md) | 30+ providers LLM, routage de modèles, configuration model_list |
+59 -146
View File
@@ -64,16 +64,12 @@
</a>
</p>
2026-03-31 📱 **Dukungan Android!** PicoClaw sekarang berjalan di Android! Unduh APK di [picoclaw.io](https://picoclaw.io/download)
2026-03-25 🚀 **v0.2.4 Dirilis!** Perombakan arsitektur Agent (SubTurn, Hooks, Steering, EventBus), integrasi WeChat/WeCom, penguatan keamanan (.security.yml, penyaringan data sensitif), provider baru (AWS Bedrock, Azure, Xiaomi MiMo), dan 35 perbaikan bug. PicoClaw telah mencapai **26K Stars**!
2026-03-17 🚀 **v0.2.3 Dirilis!** UI system tray (Windows & Linux), pelacakan status sub-agent (`spawn_status`), eksperimental Gateway hot-reload, gerbang keamanan Cron, dan 2 perbaikan keamanan. PicoClaw telah mencapai **25K Stars**!
2026-03-09 🎉 **v0.2.1 — Pembaruan terbesar sejauh ini!** Dukungan protokol MCP, 4 channel baru (Matrix/IRC/WeCom/Discord Proxy), 3 provider baru (Kimi/Minimax/Avian), pipeline visi, penyimpanan memori JSONL, perutean model.
2026-02-28 📦 **v0.2.0** dirilis dengan dukungan Docker Compose dan Web UI Launcher.
<details>
<summary>Berita sebelumnya...</summary>
@@ -174,8 +170,7 @@ Atau, unduh binary untuk platform Anda dari halaman [GitHub Releases](https://gi
Prasyarat:
- Go 1.25+
- Node.js 22+ dan pnpm 10.33.0+ untuk build Web UI / launcher
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -183,15 +178,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# Instal dependensi frontend
(cd web/frontend && pnpm install --frozen-lockfile)
# Build binary inti
make build
# Build Web UI Launcher (diperlukan untuk mode WebUI)
make build-launcher
# Build binary inti untuk semua platform yang dikelola Makefile
make build-all
@@ -206,137 +195,7 @@ make install
## 🚀 Panduan Memulai Cepat
### 🌐 WebUI Launcher (Direkomendasikan untuk Desktop)
WebUI Launcher menyediakan antarmuka berbasis browser untuk konfigurasi dan chat. Ini adalah cara termudah untuk memulai — tidak perlu pengetahuan command-line.
**Opsi 1: Klik dua kali (Desktop)**
Setelah mengunduh dari [picoclaw.io](https://picoclaw.io), klik dua kali `picoclaw-launcher` (atau `picoclaw-launcher.exe` di Windows). Browser Anda akan terbuka otomatis di `http://localhost:18800`.
**Opsi 2: Command line**
```bash
picoclaw-launcher
# Buka http://localhost:18800 di browser Anda
```
> [!TIP]
> **Akses jarak jauh / Docker / VM:** Tambahkan flag `-public` untuk mendengarkan di semua antarmuka:
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**Memulai:**
Buka WebUI, lalu: **1)** Konfigurasi Provider (tambahkan API key LLM Anda) -> **2)** Konfigurasi Channel (mis. Telegram) -> **3)** Mulai Gateway -> **4)** Chat!
Untuk dokumentasi WebUI lengkap, lihat [docs.picoclaw.io](https://docs.picoclaw.io).
<details>
<summary><b>Docker (alternatif)</b></summary>
```bash
# 1. Clone repo ini
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Jalankan pertama kali — otomatis membuat docker/data/config.json lalu keluar
# (hanya terpicu ketika config.json dan workspace/ keduanya tidak ada)
docker compose -f docker/docker-compose.yml --profile launcher up
# Container mencetak "First-run setup complete." dan berhenti.
# 3. Atur API key Anda
vim docker/data/config.json
# 4. Mulai
docker compose -f docker/docker-compose.yml --profile launcher up -d
# Buka http://localhost:18800
```
> **Pengguna Docker / VM:** Gateway mendengarkan di `127.0.0.1` secara default. Atur `PICOCLAW_GATEWAY_HOST=0.0.0.0` atau gunakan flag `-public` agar dapat diakses dari host.
```bash
# Cek log
docker compose -f docker/docker-compose.yml logs -f
# Hentikan
docker compose -f docker/docker-compose.yml --profile launcher down
# Update
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — Peringatan Keamanan saat Pertama Kali Diluncurkan</b></summary>
macOS mungkin memblokir `picoclaw-launcher` saat pertama kali diluncurkan karena diunduh dari internet dan tidak dinotarisasi melalui Mac App Store.
**Langkah 1:** Klik dua kali `picoclaw-launcher`. Anda akan melihat peringatan keamanan:
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="Peringatan macOS Gatekeeper" width="400">
</p>
> *"picoclaw-launcher" Tidak Dapat Dibuka — Apple tidak dapat memverifikasi bahwa "picoclaw-launcher" bebas dari malware yang dapat membahayakan Mac Anda atau mengancam privasi Anda.*
**Langkah 2:** Buka **Pengaturan Sistem** → **Privasi & Keamanan** → gulir ke bawah ke bagian **Keamanan** → klik **Tetap Buka** → konfirmasi dengan mengklik **Tetap Buka** pada dialog.
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS Privasi & Keamanan — Tetap Buka" width="600">
</p>
Setelah langkah satu kali ini, `picoclaw-launcher` akan terbuka secara normal pada peluncuran berikutnya.
</details>
### 📱 Android
Berikan kehidupan kedua untuk ponsel lama Anda! Ubah menjadi Asisten AI pintar dengan PicoClaw.
**Opsi 1: Instal APK**
Pratinjau:
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
Unduh APK dari [picoclaw.io](https://picoclaw.io/download/) dan instal langsung. Tanpa Termux!
**Opsi 2: Termux**
<details>
<summary><b>Terminal Launcher (untuk lingkungan dengan sumber daya terbatas)</b></summary>
1. Instal [Termux](https://github.com/termux/termux-app) (unduh dari [GitHub Releases](https://github.com/termux/termux-app/releases), atau cari di F-Droid / Google Play)
2. Jalankan perintah berikut:
```bash
# Unduh rilis terbaru
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot menyediakan tata letak filesystem Linux standar
```
Kemudian ikuti bagian Terminal Launcher di bawah untuk menyelesaikan konfigurasi.
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
Untuk lingkungan minimal di mana hanya binary inti `picoclaw` yang tersedia (tanpa Launcher UI), Anda dapat mengonfigurasi semuanya melalui command line dan file konfigurasi JSON.
### CLI
**1. Inisialisasi**
@@ -359,8 +218,11 @@ Ini membuat `~/.picoclaw/config.json` dan direktori workspace.
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_keys": ["sk-your-api-key"]
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
@@ -381,8 +243,59 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker (alternatif)</b></summary>
```bash
# 1. Clone repo ini
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Jalankan pertama kali — otomatis membuat docker/data/config.json lalu keluar
# (hanya terpicu ketika config.json dan workspace/ keduanya tidak ada)
docker compose -f docker/docker-compose.yml --profile gateway up
# Container mencetak "First-run setup complete." dan berhenti.
# 3. Atur API key Anda
vim docker/data/config.json
# 4. Mulai
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Pengguna Docker / VM:** Gateway mendengarkan di `127.0.0.1` secara default. Atur `PICOCLAW_GATEWAY_HOST=0.0.0.0` atau gunakan flag `-public` agar dapat diakses dari host.
```bash
# Cek log
docker compose -f docker/docker-compose.yml logs -f
# Hentikan
docker compose -f docker/docker-compose.yml --profile gateway down
# Update
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
### 📱 Android (Termux)
1. Instal [Termux](https://github.com/termux/termux-app) (unduh dari [GitHub Releases](https://github.com/termux/termux-app/releases), atau cari di F-Droid / Google Play)
2. Jalankan perintah berikut:
```bash
# Unduh rilis terbaru
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot menyediakan tata letak filesystem Linux standar
```
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 Providers (LLM)
PicoClaw mendukung 30+ provider LLM melalui konfigurasi `model_list`. Gunakan format `protocol/model`:
@@ -588,7 +501,7 @@ Untuk panduan lengkap di luar README ini:
| Topik | Deskripsi |
|-------|-----------|
| [Docker & Panduan Cepat](../guides/docker.md) | Pengaturan Docker Compose, mode Launcher/Agent |
| [Docker & Panduan Cepat](../guides/docker.md) | Pengaturan Docker Compose, mode Gateway/Agent |
| [Aplikasi Chat](../guides/chat-apps.md) | Semua 17+ panduan pengaturan channel |
| [Konfigurasi](../guides/configuration.md) | Variabel environment, tata letak workspace, sandbox keamanan |
| [Providers & Models](../guides/providers.md) | 30+ provider LLM, routing model, konfigurasi model_list |
+59 -146
View File
@@ -64,16 +64,12 @@
</a>
</p>
2026-03-31 📱 **Supporto Android!** PicoClaw ora funziona su Android! Scarica l'APK su [picoclaw.io](https://picoclaw.io/download)
2026-03-25 🚀 **v0.2.4 rilasciata!** Revisione dell'architettura Agent (SubTurn, Hooks, Steering, EventBus), integrazione WeChat/WeCom, rafforzamento della sicurezza (.security.yml, filtraggio dati sensibili), nuovi provider (AWS Bedrock, Azure, Xiaomi MiMo) e 35 correzioni di bug. PicoClaw raggiunge **26K Stars**!
2026-03-17 🚀 **v0.2.3 rilasciata!** Interfaccia system tray (Windows & Linux), query sullo stato dei sub-agent (`spawn_status`), hot-reload sperimentale del Gateway, gate di sicurezza per Cron e 2 correzioni di sicurezza. PicoClaw raggiunge **25K Stars**!
2026-03-09 🎉 **v0.2.1 — Il più grande aggiornamento di sempre!** Supporto al protocollo MCP, 4 nuovi canali (Matrix/IRC/WeCom/Discord Proxy), 3 nuovi provider (Kimi/Minimax/Avian), pipeline visiva, archivio memoria JSONL, routing dei modelli.
2026-02-28 📦 **v0.2.0** rilasciata con supporto Docker Compose e Web UI Launcher.
<details>
<summary>Notizie precedenti...</summary>
@@ -174,8 +170,7 @@ In alternativa, scarica il binario per la tua piattaforma dalla pagina delle [Gi
Prerequisiti:
- Go 1.25+
- Node.js 22+ e pnpm 10.33.0+ per le build Web UI / launcher
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -183,15 +178,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# Installa le dipendenze frontend
(cd web/frontend && pnpm install --frozen-lockfile)
# Compila il binario core
make build
# Compila il Web UI Launcher (necessario per la modalità WebUI)
make build-launcher
# Compila i binari core per tutte le piattaforme gestite dal Makefile
make build-all
@@ -206,137 +195,7 @@ make install
## 🚀 Guida Rapida
### 🌐 WebUI Launcher (Consigliato per Desktop)
Il WebUI Launcher fornisce un'interfaccia basata su browser per la configurazione e la chat. È il modo più semplice per iniziare — non è richiesta alcuna conoscenza della riga di comando.
**Opzione 1: Doppio clic (Desktop)**
Dopo aver scaricato da [picoclaw.io](https://picoclaw.io), fai doppio clic su `picoclaw-launcher` (o `picoclaw-launcher.exe` su Windows). Il browser si aprirà automaticamente su `http://localhost:18800`.
**Opzione 2: Riga di comando**
```bash
picoclaw-launcher
# Apri http://localhost:18800 nel browser
```
> [!TIP]
> **Accesso remoto / Docker / VM:** Aggiungi il flag `-public` per ascoltare su tutte le interfacce:
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**Per iniziare:**
Apri il WebUI, poi: **1)** Configura un Provider (aggiungi la tua API key LLM) -> **2)** Configura un Channel (es. Telegram) -> **3)** Avvia il Gateway -> **4)** Chatta!
Per la documentazione dettagliata del WebUI, vedi [docs.picoclaw.io](https://docs.picoclaw.io).
<details>
<summary><b>Docker (alternativa)</b></summary>
```bash
# 1. Clona questo repo
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Prima esecuzione — genera automaticamente docker/data/config.json poi si ferma
# (si attiva solo quando sia config.json che workspace/ sono assenti)
docker compose -f docker/docker-compose.yml --profile launcher up
# Il container stampa "First-run setup complete." e si ferma.
# 3. Imposta le tue API key
vim docker/data/config.json
# 4. Avvia
docker compose -f docker/docker-compose.yml --profile launcher up -d
# Apri http://localhost:18800
```
> **Utenti Docker / VM:** Il Gateway ascolta su `127.0.0.1` per impostazione predefinita. Imposta `PICOCLAW_GATEWAY_HOST=0.0.0.0` o usa il flag `-public` per renderlo accessibile dall'host.
```bash
# Controlla i log
docker compose -f docker/docker-compose.yml logs -f
# Ferma
docker compose -f docker/docker-compose.yml --profile launcher down
# Aggiorna
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — Avviso di sicurezza al primo avvio</b></summary>
macOS potrebbe bloccare `picoclaw-launcher` al primo avvio perché è stato scaricato da internet e non è notarizzato tramite il Mac App Store.
**Passo 1:** Fai doppio clic su `picoclaw-launcher`. Verrà visualizzato un avviso di sicurezza:
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="Avviso macOS Gatekeeper" width="400">
</p>
> *"picoclaw-launcher" Non Aperto — Apple non è riuscita a verificare che "picoclaw-launcher" sia privo di malware che potrebbe danneggiare il Mac o compromettere la privacy.*
**Passo 2:** Apri **Impostazioni di Sistema** → **Privacy e sicurezza** → scorri fino alla sezione **Sicurezza** → clicca su **Apri comunque** → conferma cliccando su **Apri comunque** nella finestra di dialogo.
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS Privacy e sicurezza — Apri comunque" width="600">
</p>
Dopo questo passaggio una tantum, `picoclaw-launcher` si aprirà normalmente ai lanci successivi.
</details>
### 📱 Android
Dai una seconda vita al tuo telefono di dieci anni fa! Trasformalo in un assistente IA intelligente con PicoClaw.
**Opzione 1: Installazione APK**
Anteprima:
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
Scarica l'APK da [picoclaw.io](https://picoclaw.io/download/) e installa direttamente. Senza Termux!
**Opzione 2: Termux**
<details>
<summary><b>Terminal Launcher (per ambienti con risorse limitate)</b></summary>
1. Installa [Termux](https://github.com/termux/termux-app) (scarica da [GitHub Releases](https://github.com/termux/termux-app/releases), o cerca su F-Droid / Google Play)
2. Esegui i seguenti comandi:
```bash
# Scarica l'ultima release
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot fornisce un layout standard del filesystem Linux
```
Poi segui la sezione Terminal Launcher qui sotto per completare la configurazione.
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
Per ambienti minimali dove è disponibile solo il binario core `picoclaw` (senza Launcher UI), puoi configurare tutto tramite riga di comando e un file di configurazione JSON.
### CLI
**1. Inizializza**
@@ -359,8 +218,11 @@ Questo crea `~/.picoclaw/config.json` e la directory workspace.
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_keys": ["sk-your-api-key"]
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
@@ -381,8 +243,59 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker (alternativa)</b></summary>
```bash
# 1. Clona questo repo
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Prima esecuzione — genera automaticamente docker/data/config.json poi si ferma
# (si attiva solo quando sia config.json che workspace/ sono assenti)
docker compose -f docker/docker-compose.yml --profile gateway up
# Il container stampa "First-run setup complete." e si ferma.
# 3. Imposta le tue API key
vim docker/data/config.json
# 4. Avvia
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Utenti Docker / VM:** Il Gateway ascolta su `127.0.0.1` per impostazione predefinita. Imposta `PICOCLAW_GATEWAY_HOST=0.0.0.0` o usa il flag `-public` per renderlo accessibile dall'host.
```bash
# Controlla i log
docker compose -f docker/docker-compose.yml logs -f
# Ferma
docker compose -f docker/docker-compose.yml --profile gateway down
# Aggiorna
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
### 📱 Android (Termux)
1. Installa [Termux](https://github.com/termux/termux-app) (scarica da [GitHub Releases](https://github.com/termux/termux-app/releases), o cerca su F-Droid / Google Play)
2. Esegui i seguenti comandi:
```bash
# Scarica l'ultima release
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot fornisce un layout standard del filesystem Linux
```
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 Provider (LLM)
PicoClaw supporta 30+ provider LLM tramite la configurazione `model_list`. Usa il formato `protocollo/modello`:
@@ -606,7 +519,7 @@ Per guide dettagliate oltre questo README:
| Argomento | Descrizione |
|-----------|-------------|
| [Docker & Avvio Rapido](../guides/docker.md) | Configurazione Docker Compose, modalità Launcher/Agent |
| [Docker & Avvio Rapido](../guides/docker.md) | Configurazione Docker Compose, modalità Gateway/Agent |
| [App di Chat](../guides/chat-apps.md) | Tutte le guide di configurazione per 17+ channel |
| [Configurazione](../guides/configuration.md) | Variabili d'ambiente, struttura del workspace, sandbox di sicurezza |
| [MCP Server CLI](../reference/mcp-cli.md) | Aggiunta, elenco, test, modifica e rimozione dei server MCP da CLI |
+60 -147
View File
@@ -64,16 +64,12 @@
</a>
</p>
2026-03-31 📱 **Android サポート!** PicoClawがAndroidで動作!APKは[picoclaw.io](https://picoclaw.io/download)からダウンロード
2026-03-25 🚀 **v0.2.4 リリース!** Agent アーキテクチャ全面刷新(SubTurn、Hooks、Steering、EventBus)、WeChat/WeCom 統合、セキュリティ強化(.security.yml、機密データフィルタリング)、新プロバイダー(AWS Bedrock、Azure、Xiaomi MiMo)、35 件のバグ修正。PicoClaw **26K ⭐** 達成!
2026-03-17 🚀 **v0.2.3 リリース!** システムトレイ UI(Windows & Linux)、サブエージェントステータス追跡(`spawn_status`)、実験的 Gateway ホットリロード、cron セキュリティゲート、セキュリティ修正 2 件。PicoClaw **25K ⭐** 達成!
2026-03-09 🎉 **v0.2.1 — 最大のアップデート!** MCP プロトコルサポート、4 つの新チャンネル (Matrix/IRC/WeCom/Discord Proxy)、3 つの新プロバイダー (Kimi/Minimax/Avian)、ビジョンパイプライン、JSONL メモリストア、モデルルーティング。
2026-02-28 📦 **v0.2.0** リリース — Docker Compose と Web UI Launcher サポート。
<details>
<summary>過去のニュース...</summary>
@@ -174,8 +170,7 @@ PicoClaw はほぼすべての Linux デバイスにデプロイできます!
前提条件:
- Go 1.25+
- Web UI / launcher のビルドには Node.js 22+ と pnpm 10.33.0+ が必要
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -183,15 +178,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# フロントエンド依存関係をインストール
(cd web/frontend && pnpm install --frozen-lockfile)
# コアバイナリをビルド
make build
# Web UI Launcher をビルド(WebUI モードに必要)
make build-launcher
# Makefile が管理するすべてのプラットフォーム向けにコアバイナリをビルド
make build-all
@@ -206,138 +195,7 @@ make install
## 🚀 クイックスタートガイド
### 🌐 WebUI Launcher(デスクトップ向け推奨)
WebUI Launcher はブラウザベースの設定・チャットインターフェースを提供します。コマンドラインの知識不要で、最も簡単に始められる方法です。
**オプション 1: ダブルクリック(デスクトップ)**
[picoclaw.io](https://picoclaw.io) からダウンロード後、`picoclaw-launcher`(Windows では `picoclaw-launcher.exe`)をダブルクリックしてください。ブラウザが自動的に `http://localhost:18800` を開きます。
**オプション 2: コマンドライン**
```bash
picoclaw-launcher
# ブラウザで http://localhost:18800 を開く
```
> [!TIP]
> **リモートアクセス / Docker / VM:** すべてのインターフェースでリッスンするには `-public` フラグを追加してください:
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**始め方:**
WebUI を開いたら:**1)** Provider を設定(LLM API キーを追加)→ **2)** Channel を設定(例:Telegram)→ **3)** Gateway を起動 → **4)** チャット!
WebUI の詳細なドキュメントは [docs.picoclaw.io](https://docs.picoclaw.io) を参照してください。
<details>
<summary><b>Docker(代替手段)</b></summary>
```bash
# 1. このリポジトリをクローン
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. 初回実行 — docker/data/config.json を自動生成して終了
# (config.json と workspace/ の両方が存在しない場合のみ実行)
docker compose -f docker/docker-compose.yml --profile launcher up
# コンテナが "First-run setup complete." を出力して停止します。
# 3. API キーを設定
vim docker/data/config.json
# 4. 起動
docker compose -f docker/docker-compose.yml --profile launcher up -d
# http://localhost:18800 を開く
```
> **Docker / VM ユーザー:** Gateway はデフォルトで `127.0.0.1` でリッスンします。ホストからアクセスできるようにするには `PICOCLAW_GATEWAY_HOST=0.0.0.0` を設定するか、`-public` フラグを使用してください。
```bash
# ログを確認
docker compose -f docker/docker-compose.yml logs -f
# 停止
docker compose -f docker/docker-compose.yml --profile launcher down
# 更新
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — 初回起動時のセキュリティ警告</b></summary>
`picoclaw-launcher` はインターネットからダウンロードされ、Mac App Store を通じて公証されていないため、macOS が初回起動時にブロックする場合があります。
**ステップ 1:** `picoclaw-launcher` をダブルクリックすると、セキュリティ警告が表示されます:
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="macOS Gatekeeper 警告" width="400">
</p>
> *"picoclaw-launcher" は開けません — "picoclaw-launcher" がMacに害を与えたりプライバシーを侵害するマルウェアを含まないことをAppleは確認できません。*
**ステップ 2:** **システム設定** → **プライバシーとセキュリティ** を開き、**セキュリティ** セクションまでスクロールして **このまま開く** をクリック → ダイアログで再度 **開く** をクリックします。
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS プライバシーとセキュリティ — このまま開く" width="600">
</p>
この操作を一度行うと、以降の起動では警告が表示されなくなります。
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android
10 年前のスマホに第二の人生を!PicoClaw でスマート AI アシスタントに変身させましょう。
**オプション 1: APK インストール**
プレビュー:
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
[picoclaw.io](https://picoclaw.io/download/) から APK をダウンロードして直接インストール。Termux 不要!
**オプション 2: Termux**
<details>
<summary><b>Terminal Launcher(リソース制約環境向け)</b></summary>
1. [Termux](https://github.com/termux/termux-app) をインストール([GitHub Releases](https://github.com/termux/termux-app/releases) からダウンロード、または F-Droid / Google Play で検索)
2. 以下のコマンドを実行:
```bash
# 最新リリースをダウンロード
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot で標準的な Linux ファイルシステムレイアウトを提供
```
その後、下記の Terminal Launcher セクションの手順に従って設定を完了してください。
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
`picoclaw` コアバイナリのみが利用可能な最小環境(Launcher UI なし)では、コマンドラインと JSON 設定ファイルですべてを設定できます。
### CLI
**1. 初期化**
@@ -360,8 +218,11 @@ picoclaw onboard
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_keys": ["sk-your-api-key"]
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
@@ -382,8 +243,60 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker(代替手段)</b></summary>
```bash
# 1. このリポジトリをクローン
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. 初回実行 — docker/data/config.json を自動生成して終了
# (config.json と workspace/ の両方が存在しない場合のみ実行)
docker compose -f docker/docker-compose.yml --profile gateway up
# コンテナが "First-run setup complete." を出力して停止します。
# 3. API キーを設定
vim docker/data/config.json
# 4. 起動
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Docker / VM:** Gateway は既定で `127.0.0.1` を使用します。ホストから接続する場合は `PICOCLAW_GATEWAY_HOST=0.0.0.0` を設定し、Compose で必要なポートを公開してください。
```bash
# ログを確認
docker compose -f docker/docker-compose.yml logs -f
# 停止
docker compose -f docker/docker-compose.yml --profile gateway down
# 更新
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android (Termux)
1. [Termux](https://github.com/termux/termux-app) をインストール([GitHub Releases](https://github.com/termux/termux-app/releases) からダウンロード、または F-Droid / Google Play で検索)
2. 以下のコマンドを実行:
```bash
# 最新リリースをダウンロード
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot で標準的な Linux ファイルシステムレイアウトを提供
```
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 Provider(LLM)
PicoClaw は `model_list` 設定を通じて 30 以上の LLM Provider をサポートしています。`protocol/model` 形式を使用してください:
@@ -589,7 +502,7 @@ PicoClaw は `cron` ツールによるスケジュールリマインダーと定
| トピック | 説明 |
|---------|------|
| [Docker & クイックスタート](../guides/docker.ja.md) | Docker Compose セットアップ、Launcher/Agent モード |
| [Docker & クイックスタート](../guides/docker.ja.md) | Docker Compose セットアップ、Gateway/Agent モード |
| [チャットアプリ](../guides/chat-apps.ja.md) | 17 以上の Channel セットアップガイド |
| [設定](../guides/configuration.ja.md) | 環境変数、ワークスペース構成、セキュリティサンドボックス |
| [Provider とモデル](../guides/providers.ja.md) | 30 以上の LLM Provider、モデルルーティング、model_list 設定 |
+60 -148
View File
@@ -64,16 +64,12 @@
</a>
</p>
2026-03-31 📱 **Android 지원!** PicoClaw가 이제 Android에서 실행됩니다! APK는 [picoclaw.io](https://picoclaw.io/download)에서 다운로드하세요.
2026-03-25 🚀 **v0.2.4 출시!** 에이전트 아키텍처 전면 개편(SubTurn, Hooks, Steering, EventBus), WeChat/WeCom 통합, 보안 강화(`.security.yml`, 민감 정보 필터링), 새 프로바이더(AWS Bedrock, Azure, Xiaomi MiMo), 그리고 35건의 버그 수정이 포함되었습니다. PicoClaw는 **26K 스타**를 달성했습니다!
2026-03-17 🚀 **v0.2.3 출시!** 시스템 트레이 UI(Windows 및 Linux), 서브에이전트 상태 조회(`spawn_status`), 실험적 게이트웨이 핫 리로드, Cron 보안 게이트, 그리고 2건의 보안 수정이 추가되었습니다. PicoClaw는 **25K 스타**를 달성했습니다!
2026-03-09 🎉 **v0.2.1 — 역대 최대 업데이트!** MCP 프로토콜 지원, 4개의 새 채널(Matrix/IRC/WeCom/Discord Proxy), 3개의 새 프로바이더(Kimi/Minimax/Avian), 비전 파이프라인, JSONL 메모리 저장소, 모델 라우팅이 추가되었습니다.
2026-02-28 📦 **v0.2.0** 이 Docker Compose 및 WebUI 런처 지원과 함께 출시되었습니다.
<details>
<summary>이전 뉴스...</summary>
@@ -174,8 +170,7 @@ PicoClaw는 사실상 거의 모든 Linux 장치에 배포할 수 있습니다!
필수 사항:
- Go 1.25+
- Web UI / launcher 빌드에는 Node.js 22+와 pnpm 10.33.0+가 필요합니다
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -183,15 +178,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# 프런트엔드 의존성 설치
(cd web/frontend && pnpm install --frozen-lockfile)
# 코어 바이너리 빌드
make build
# WebUI 런처 빌드 (WebUI 모드에 필요)
make build-launcher
# Makefile이 관리하는 모든 플랫폼용 코어 바이너리 빌드
make build-all
@@ -206,137 +195,7 @@ make install
## 🚀 빠른 시작 가이드
### 🌐 WebUI Launcher (데스크톱 권장)
WebUI Launcher는 설정과 채팅을 위한 브라우저 기반 인터페이스를 제공합니다. 명령줄을 몰라도 가장 쉽게 시작할 수 있는 방법입니다.
**옵션 1: 더블클릭(데스크톱)**
[picoclaw.io](https://picoclaw.io)에서 다운로드한 뒤 `picoclaw-launcher`를 더블클릭하세요(Windows에서는 `picoclaw-launcher.exe`). 브라우저가 자동으로 `http://localhost:18800`을 엽니다.
**옵션 2: 명령줄**
```bash
picoclaw-launcher
# 브라우저에서 http://localhost:18800 열기
```
> [!TIP]
> **원격 접속 / Docker / VM:** 모든 인터페이스에서 수신하려면 `-public` 플래그를 추가하세요.
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**시작 방법:**
WebUI를 연 뒤 다음 순서로 진행하세요. **1)** 프로바이더 설정(LLM API 키 추가) -> **2)** 채널 설정(예: Telegram) -> **3)** 게이트웨이 시작 -> **4)** 채팅!
자세한 WebUI 문서는 [docs.picoclaw.io](https://docs.picoclaw.io)를 참고하세요.
<details>
<summary><b>Docker(대안)</b></summary>
```bash
# 1. 이 저장소를 클론
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. 첫 실행 - docker/data/config.json을 자동 생성한 뒤 종료
# (config.json과 workspace/가 모두 없을 때만 실행됨)
docker compose -f docker/docker-compose.yml --profile launcher up
# 컨테이너가 "First-run setup complete."를 출력하고 종료됩니다.
# 3. API 키 설정
vim docker/data/config.json
# 4. 시작
docker compose -f docker/docker-compose.yml --profile launcher up -d
# http://localhost:18800 열기
```
> **Docker / VM 사용자:** 게이트웨이는 기본적으로 `127.0.0.1`에서 수신합니다. 호스트에서 접근 가능하게 하려면 `PICOCLAW_GATEWAY_HOST=0.0.0.0`을 설정하거나 `-public` 플래그를 사용하세요.
```bash
# 로그 확인
docker compose -f docker/docker-compose.yml logs -f
# 중지
docker compose -f docker/docker-compose.yml --profile launcher down
# 업데이트
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS - 첫 실행 보안 경고</b></summary>
macOS에서는 인터넷에서 다운로드한 앱이고 Mac App Store 공증을 거치지 않았기 때문에, 첫 실행 시 `picoclaw-launcher`가 차단될 수 있습니다.
**1단계:** `picoclaw-launcher`를 더블클릭합니다. 그러면 보안 경고가 표시됩니다.
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="macOS Gatekeeper warning" width="400">
</p>
> *"picoclaw-launcher"을(를) 열 수 없습니다. Apple에서 이 앱이 악성 소프트웨어가 없으며 Mac이나 개인 정보를 해치지 않는다고 확인할 수 없습니다.*
**2단계:** **시스템 설정** -> **개인정보 보호 및 보안** 으로 이동한 뒤 **보안** 섹션까지 스크롤하여 **그래도 열기(Open Anyway)** 를 클릭하고, 대화상자에서 다시 한 번 **그래도 열기**를 확인합니다.
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS Privacy & Security — Open Anyway" width="600">
</p>
이 과정을 한 번만 거치면 이후에는 `picoclaw-launcher`가 정상적으로 열립니다.
</details>
### 📱 Android
오래된 스마트폰에 새 생명을 불어넣어 보세요! PicoClaw를 설치하면 스마트 AI 어시스턴트로 바꿀 수 있습니다.
**옵션 1: APK 설치**
미리보기:
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
[picoclaw.io](https://picoclaw.io/download/)에서 APK를 다운로드해 바로 설치하세요. Termux가 필요 없습니다!
**옵션 2: Termux**
<details>
<summary><b>터미널 런처 (리소스 제약 환경용)</b></summary>
1. [Termux](https://github.com/termux/termux-app)를 설치합니다([GitHub Releases](https://github.com/termux/termux-app/releases)에서 다운로드하거나 F-Droid / Google Play에서 검색).
2. 다음 명령을 실행합니다.
```bash
# 최신 릴리스 다운로드
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot가 표준 Linux 파일시스템 레이아웃을 제공합니다
```
그다음 아래의 터미널 런처 섹션을 따라 설정을 마무리하세요.
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
런처 UI 없이 `picoclaw` 코어 바이너리만 있는 최소 환경에서는 명령줄과 JSON 설정 파일만으로도 모든 설정을 마칠 수 있습니다.
### CLI
**1. 초기화**
@@ -348,8 +207,9 @@ picoclaw onboard
**2. 설정** (`~/.picoclaw/config.json`)
```jsonc
```json
{
"version": 3,
"agents": {
"defaults": {
"model_name": "gpt-5.4"
@@ -358,16 +218,17 @@ picoclaw onboard
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
// api_key는 이제 .security.yml에서 로드됩니다.
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
```
> 사용 가능한 모든 옵션이 포함된 전체 설정 템플릿은 저장소의 `config/config.example.json`을 참고하세요.
>
> 참고: `config.example.json` 형식은 버전 0이며 민감 정보가 포함되어 있습니다. 실행 시 자동으로 버전 1+로 마이그레이션되며, 이후 `config.json`에는 비민감 정보만 저장되고 민감 정보는 `.security.yml`에 저장됩니다. 민감 정보를 직접 수정해야 한다면 `../security/security_configuration.md`를 참고하세요.
**3. 채팅**
@@ -382,8 +243,59 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker(대안)</b></summary>
```bash
# 1. 이 저장소를 클론
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. 첫 실행 - docker/data/config.json을 자동 생성한 뒤 종료
# (config.json과 workspace/가 모두 없을 때만 실행됨)
docker compose -f docker/docker-compose.yml --profile gateway up
# 컨테이너가 "First-run setup complete."를 출력하고 종료됩니다.
# 3. API 키 설정
vim docker/data/config.json
# 4. 시작
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Docker / VM:** 게이트웨이는 기본적으로 `127.0.0.1`에서 수신합니다. 호스트에서 접속하려면 `PICOCLAW_GATEWAY_HOST=0.0.0.0`을 설정하고 Compose에서 필요한 포트를 공개하세요.
```bash
# 로그 확인
docker compose -f docker/docker-compose.yml logs -f
# 중지
docker compose -f docker/docker-compose.yml --profile gateway down
# 업데이트
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
### 📱 Android (Termux)
1. [Termux](https://github.com/termux/termux-app)를 설치합니다([GitHub Releases](https://github.com/termux/termux-app/releases)에서 다운로드하거나 F-Droid / Google Play에서 검색).
2. 다음 명령을 실행합니다.
```bash
# 최신 릴리스 다운로드
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot가 표준 Linux 파일시스템 레이아웃을 제공합니다
```
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 프로바이더(LLM)
PicoClaw는 `model_list` 설정을 통해 30개 이상의 LLM 프로바이더를 지원합니다. 형식은 `protocol/model`입니다.
+58 -143
View File
@@ -64,16 +64,12 @@
</a>
</p>
2026-03-31 📱 **Sokongan Android!** PicoClaw sekarang berjalan di Android! Muat turun APK di [picoclaw.io](https://picoclaw.io/download)
2026-03-25 🚀 **v0.2.4 Dikeluarkan!** Penstrukturan semula seni bina Agent (SubTurn, Hooks, Steering, EventBus), integrasi WeChat/WeCom, penguatan keselamatan (.security.yml, penapisan data sensitif), penyedia baharu (AWS Bedrock, Azure, Xiaomi MiMo), dan 35 pembetulan pepijat. PicoClaw mencapai **26K Stars**!
2026-03-17 🚀 **v0.2.3 Dikeluarkan!** UI dulang sistem (Windows & Linux), pertanyaan status sub-agent (`spawn_status`), muat semula panas Gateway eksperimental, kawalan keselamatan Cron, dan 2 pembetulan keselamatan. PicoClaw mencapai **25K Stars**!
2026-03-09 🎉 **v0.2.1 — Kemas kini terbesar setakat ini!** Sokongan protokol MCP, 4 saluran baharu (Matrix/IRC/WeCom/Discord Proxy), 3 penyedia baharu (Kimi/Minimax/Avian), saluran paip visi, storan memori JSONL, penghalaan model.
2026-02-28 📦 **v0.2.0** dikeluarkan dengan sokongan Docker Compose dan Pelancar Web UI.
<details>
<summary>Berita terdahulu...</summary>
@@ -175,23 +171,16 @@ Muat turun binari untuk platform anda dari halaman [GitHub Releases](https://git
Prasyarat:
- Go 1.25+
- Node.js 22+ dan pnpm 10.33.0+ untuk binaan Web UI / launcher
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# Pasang dependensi frontend
(cd web/frontend && pnpm install --frozen-lockfile)
# Bina binari teras
make build
# Bina Pelancar Web UI (diperlukan untuk mod WebUI)
make build-launcher
# Bina binari teras untuk semua platform yang diuruskan oleh Makefile
make build-all
@@ -206,134 +195,7 @@ make install
## 🚀 Panduan Permulaan Pantas
### 🌐 Pelancar WebUI (Disyorkan untuk Desktop)
Pelancar WebUI menyediakan antara muka berasaskan pelayar untuk konfigurasi dan sembang. Ini adalah cara termudah untuk bermula — tiada pengetahuan baris arahan diperlukan.
**Pilihan 1: Klik dua kali (Desktop)**
Selepas memuat turun dari [picoclaw.io](https://picoclaw.io), klik dua kali `picoclaw-launcher` (atau `picoclaw-launcher.exe` pada Windows). Pelayar anda akan dibuka secara automatik di `http://localhost:18800`.
**Pilihan 2: Baris arahan**
```bash
picoclaw-launcher
# Buka http://localhost:18800 dalam pelayar anda
```
> [!TIP]
> **Akses jauh / Docker / VM:** Tambah bendera `-public` untuk mendengar pada semua antara muka:
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="Pelancar WebUI" width="600">
</p>
**Memulakan:** Buka WebUI, kemudian: **1)** Konfigurasikan Penyedia (tambah kunci API LLM) -> **2)** Konfigurasikan Saluran (cth. Telegram) -> **3)** Mulakan Gateway -> **4)** Sembang!
Untuk dokumentasi WebUI terperinci, lihat [docs.picoclaw.io](https://docs.picoclaw.io).
<details>
<summary><b>Docker (alternatif)</b></summary>
```bash
# 1. Klon repo ini
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Jalankan pertama kali — jana docker/data/config.json secara automatik kemudian keluar
docker compose -f docker/docker-compose.yml --profile launcher up
# 3. Tetapkan kunci API anda
vim docker/data/config.json
# 4. Mulakan
docker compose -f docker/docker-compose.yml --profile launcher up -d
# Buka http://localhost:18800
```
> **Pengguna Docker / VM:** Gateway mendengar pada `127.0.0.1` secara lalai. Tetapkan `PICOCLAW_GATEWAY_HOST=0.0.0.0` atau gunakan bendera `-public` untuk membolehkan akses dari hos.
```bash
# Semak log
docker compose -f docker/docker-compose.yml logs -f
# Henti
docker compose -f docker/docker-compose.yml --profile launcher down
# Kemas kini
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — Amaran Keselamatan Pelancaran Pertama</b></summary>
macOS mungkin menyekat `picoclaw-launcher` pada pelancaran pertama kerana ia dimuat turun dari internet dan tidak disahkan melalui Mac App Store.
**Langkah 1:** Klik dua kali `picoclaw-launcher`. Anda akan melihat amaran keselamatan:
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="Amaran macOS Gatekeeper" width="400">
</p>
> *"picoclaw-launcher" Tidak Dibuka — Apple tidak dapat mengesahkan "picoclaw-launcher" bebas daripada perisian hasad yang mungkin membahayakan Mac anda atau menjejaskan privasi anda.*
**Langkah 2:** Buka **Tetapan Sistem** → **Privasi & Keselamatan** → tatal ke bawah ke bahagian **Keselamatan** → klik **Buka Juga** → sahkan dengan mengklik **Buka Juga** dalam dialog.
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS Privasi & Keselamatan — Buka Juga" width="600">
</p>
Selepas langkah sekali ini, `picoclaw-launcher` akan dibuka secara normal pada pelancaran seterusnya.
</details>
### 📱 Android
Berikan telefon lama anda kehidupan baru! Jadikannya Pembantu AI pintar dengan PicoClaw.
**Pilihan 1: Pasang APK**
Pratonton:
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
Muat turun APK dari [picoclaw.io](https://picoclaw.io/download/) dan pasang secara langsung. Tiada Termux diperlukan!
**Pilihan 2: Termux**
<details>
<summary><b>Pelancar Terminal (untuk persekitaran terhad sumber)</b></summary>
1. Pasang [Termux](https://github.com/termux/termux-app) (muat turun dari [GitHub Releases](https://github.com/termux/termux-app/releases), atau cari di F-Droid / Google Play)
2. Jalankan arahan berikut:
```bash
# Muat turun keluaran terkini
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot menyediakan susun atur sistem fail Linux standard
```
Kemudian ikuti bahagian Pelancar Terminal di bawah untuk melengkapkan konfigurasi.
<img src="../../assets/termux.jpg" alt="PicoClaw pada Termux" width="512">
Untuk persekitaran minimal di mana hanya binari teras `picoclaw` tersedia (tiada UI Pelancar), anda boleh mengkonfigurasi semua melalui baris arahan dan fail konfigurasi JSON.
### CLI
**1. Mulakan**
@@ -347,6 +209,7 @@ Ini mencipta `~/.picoclaw/config.json` dan direktori ruang kerja.
```json
{
"version": 3,
"agents": {
"defaults": {
"model_name": "gpt-5.4"
@@ -355,13 +218,17 @@ Ini mencipta `~/.picoclaw/config.json` dan direktori ruang kerja.
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4"
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
```
> Lihat `config/config.example.json` dalam repo untuk templat konfigurasi lengkap. Nota: kunci API kini disimpan dalam `.security.yml`, bukan `config.json`.
> Lihat `config/config.example.json` dalam repo untuk templat konfigurasi lengkap.
**3. Sembang**
@@ -375,8 +242,56 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker (alternatif)</b></summary>
```bash
# 1. Klon repo ini
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Jalankan pertama kali — jana docker/data/config.json secara automatik kemudian keluar
docker compose -f docker/docker-compose.yml --profile gateway up
# 3. Tetapkan kunci API anda
vim docker/data/config.json
# 4. Mulakan
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Pengguna Docker / VM:** Gateway mendengar pada `127.0.0.1` secara lalai. Tetapkan `PICOCLAW_GATEWAY_HOST=0.0.0.0` atau gunakan bendera `-public` untuk membolehkan akses dari hos.
```bash
# Semak log
docker compose -f docker/docker-compose.yml logs -f
# Henti
docker compose -f docker/docker-compose.yml --profile gateway down
# Kemas kini
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
### 📱 Android (Termux)
1. Pasang [Termux](https://github.com/termux/termux-app) (muat turun dari [GitHub Releases](https://github.com/termux/termux-app/releases), atau cari di F-Droid / Google Play)
2. Jalankan arahan berikut:
```bash
# Muat turun keluaran terkini
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot menyediakan susun atur sistem fail Linux standard
```
<img src="../../assets/termux.jpg" alt="PicoClaw pada Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 Penyedia (LLM)
@@ -587,7 +502,7 @@ Untuk panduan terperinci melebihi README ini:
| Topik | Penerangan |
|-------|------------|
| [Docker & Permulaan Pantas](../guides/docker.ms.md) | Persediaan Docker Compose, mod Launcher/Agent |
| [Docker & Permulaan Pantas](../guides/docker.ms.md) | Persediaan Docker Compose, mod Gateway/Agent |
| [Aplikasi Sembang](../guides/chat-apps.ms.md) | Panduan persediaan 17+ saluran |
| [Konfigurasi](../guides/configuration.ms.md) | Pemboleh ubah persekitaran, susun atur ruang kerja |
| [Penyedia & Model](../guides/providers.md) | 30+ penyedia LLM, penghalaan model |
+60 -147
View File
@@ -64,16 +64,12 @@
</a>
</p>
2026-03-31 📱 **Suporte Android!** PicoClaw agora roda no Android! Baixe o APK em [picoclaw.io](https://picoclaw.io/download)
2026-03-25 🚀 **v0.2.4 Lançada!** Reformulação da arquitetura Agent (SubTurn, Hooks, Steering, EventBus), integração WeChat/WeCom, fortalecimento de segurança (.security.yml, filtragem de dados sensíveis), novos providers (AWS Bedrock, Azure, Xiaomi MiMo) e 35 correções de bugs. O PicoClaw atingiu **26K Stars**!
2026-03-17 🚀 **v0.2.3 Lançada!** UI na bandeja do sistema (Windows e Linux), consulta de status de sub-agent (`spawn_status`), hot-reload experimental do Gateway, controle de segurança do Cron e 2 correções de segurança. O PicoClaw atingiu **25K Stars**!
2026-03-09 🎉 **v0.2.1 — Maior atualização até agora!** Suporte ao protocolo MCP, 4 novos channels (Matrix/IRC/WeCom/Discord Proxy), 3 novos providers (Kimi/Minimax/Avian), pipeline de visão, armazenamento de memória JSONL, roteamento de modelos.
2026-02-28 📦 **v0.2.0** lançada com suporte a Docker Compose e Web UI Launcher.
<details>
<summary>Notícias anteriores...</summary>
@@ -174,8 +170,7 @@ Alternativamente, baixe o binário para sua plataforma na página de [GitHub Rel
Pré-requisitos:
- Go 1.25+
- Node.js 22+ e pnpm 10.33.0+ para builds do Web UI / launcher
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -183,15 +178,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# Instalar dependências do frontend
(cd web/frontend && pnpm install --frozen-lockfile)
# Compilar o binário principal
make build
# Compilar o Web UI Launcher (necessário para o modo WebUI)
make build-launcher
# Compilar os binários core para todas as plataformas gerenciadas pelo Makefile
make build-all
@@ -206,138 +195,7 @@ make install
## 🚀 Guia de Início Rápido
### 🌐 WebUI Launcher (Recomendado para Desktop)
O WebUI Launcher fornece uma interface baseada em navegador para configuração e chat. Esta é a maneira mais fácil de começar — sem necessidade de conhecimento de linha de comando.
**Opção 1: Duplo clique (Desktop)**
Após baixar de [picoclaw.io](https://picoclaw.io), dê duplo clique em `picoclaw-launcher` (ou `picoclaw-launcher.exe` no Windows). Seu navegador abrirá automaticamente em `http://localhost:18800`.
**Opção 2: Linha de comando**
```bash
picoclaw-launcher
# Abra http://localhost:18800 no seu navegador
```
> [!TIP]
> **Acesso remoto / Docker / VM:** Adicione a flag `-public` para escutar em todas as interfaces:
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**Primeiros passos:**
Abra o WebUI e então: **1)** Configure um Provider (adicione sua API key de LLM) -> **2)** Configure um Channel (ex.: Telegram) -> **3)** Inicie o Gateway -> **4)** Converse!
Para documentação detalhada do WebUI, veja [docs.picoclaw.io](https://docs.picoclaw.io).
<details>
<summary><b>Docker (alternativa)</b></summary>
```bash
# 1. Clone este repositório
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Primeira execução — gera automaticamente docker/data/config.json e encerra
# (só é acionado quando config.json e workspace/ estão ausentes)
docker compose -f docker/docker-compose.yml --profile launcher up
# O container imprime "First-run setup complete." e para.
# 3. Configure suas API keys
vim docker/data/config.json
# 4. Iniciar
docker compose -f docker/docker-compose.yml --profile launcher up -d
# Abra http://localhost:18800
```
> **Usuários de Docker / VM:** O Gateway escuta em `127.0.0.1` por padrão. Defina `PICOCLAW_GATEWAY_HOST=0.0.0.0` ou use a flag `-public` para torná-lo acessível pelo host.
```bash
# Verificar logs
docker compose -f docker/docker-compose.yml logs -f
# Parar
docker compose -f docker/docker-compose.yml --profile launcher down
# Atualizar
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — Aviso de segurança no primeiro lançamento</b></summary>
O macOS pode bloquear o `picoclaw-launcher` no primeiro lançamento porque ele foi baixado da internet e não é notarizado pela Mac App Store.
**Passo 1:** Dê um duplo clique em `picoclaw-launcher`. Você verá um aviso de segurança:
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="Aviso do macOS Gatekeeper" width="400">
</p>
> *"picoclaw-launcher" não foi aberto — A Apple não conseguiu verificar se "picoclaw-launcher" está livre de malware que possa prejudicar seu Mac ou comprometer sua privacidade.*
**Passo 2:** Abra **Configurações do Sistema** → **Privacidade e Segurança** → role até a seção **Segurança** → clique em **Abrir Mesmo Assim** → confirme clicando em **Abrir Mesmo Assim** na caixa de diálogo.
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS Privacidade e Segurança — Abrir Mesmo Assim" width="600">
</p>
Após esta etapa única, o `picoclaw-launcher` abrirá normalmente nos lançamentos seguintes.
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android
Dê uma segunda vida ao seu celular de uma década! Transforme-o em um Assistente de IA inteligente com o PicoClaw.
**Opção 1: Instalação via APK**
Pré-visualização:
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
Baixe o APK de [picoclaw.io](https://picoclaw.io/download/) e instale diretamente. Sem necessidade de Termux!
**Opção 2: Termux**
<details>
<summary><b>Terminal Launcher (para ambientes com recursos limitados)</b></summary>
1. Instale o [Termux](https://github.com/termux/termux-app) (baixe nas [GitHub Releases](https://github.com/termux/termux-app/releases), ou pesquise no F-Droid / Google Play)
2. Execute os seguintes comandos:
```bash
# Baixar a versão mais recente
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot fornece um layout padrão de sistema de arquivos Linux
```
Em seguida, siga a seção Terminal Launcher abaixo para concluir a configuração.
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
Para ambientes mínimos onde apenas o binário principal `picoclaw` está disponível (sem Launcher UI), você pode configurar tudo via linha de comando e um arquivo de configuração JSON.
### CLI
**1. Inicializar**
@@ -360,8 +218,11 @@ Isso cria `~/.picoclaw/config.json` e o diretório workspace.
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_keys": ["sk-your-api-key"]
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
@@ -382,8 +243,60 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker (alternativa)</b></summary>
```bash
# 1. Clone este repositório
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. Primeira execução — gera automaticamente docker/data/config.json e encerra
# (só é acionado quando config.json e workspace/ estão ausentes)
docker compose -f docker/docker-compose.yml --profile gateway up
# O container imprime "First-run setup complete." e para.
# 3. Configure suas API keys
vim docker/data/config.json
# 4. Iniciar
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Usuários de Docker / VM:** O Gateway escuta em `127.0.0.1` por padrão. Defina `PICOCLAW_GATEWAY_HOST=0.0.0.0` ou use a flag `-public` para torná-lo acessível pelo host.
```bash
# Verificar logs
docker compose -f docker/docker-compose.yml logs -f
# Parar
docker compose -f docker/docker-compose.yml --profile gateway down
# Atualizar
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android (Termux)
1. Instale o [Termux](https://github.com/termux/termux-app) (baixe nas [GitHub Releases](https://github.com/termux/termux-app/releases), ou pesquise no F-Droid / Google Play)
2. Execute os seguintes comandos:
```bash
# Baixar a versão mais recente
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot fornece um layout padrão de sistema de arquivos Linux
```
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 Providers (LLM)
O PicoClaw suporta mais de 30 providers de LLM através da configuração `model_list`. Use o formato `protocolo/modelo`:
@@ -589,7 +502,7 @@ Para guias detalhados além deste README:
| Tópico | Descrição |
|--------|-----------|
| [Docker & Início Rápido](../guides/docker.pt-br.md) | Configuração do Docker Compose, modos Launcher/Agent |
| [Docker & Início Rápido](../guides/docker.pt-br.md) | Configuração do Docker Compose, modos Gateway/Agent |
| [Apps de Chat](../guides/chat-apps.pt-br.md) | Guias de configuração para todos os 17+ channels |
| [Configuração](../guides/configuration.pt-br.md) | Variáveis de ambiente, layout do workspace, sandbox de segurança |
| [Providers & Models](../guides/providers.pt-br.md) | 30+ providers de LLM, roteamento de modelos, configuração de model_list |
+60 -147
View File
@@ -64,16 +64,12 @@
</a>
</p>
2026-03-31 📱 **Hỗ trợ Android!** PicoClaw giờ chạy trên Android! Tải APK tại [picoclaw.io](https://picoclaw.io/download)
2026-03-25 🚀 **v0.2.4 đã phát hành!** Tái cấu trúc kiến trúc Agent (SubTurn, Hooks, Steering, EventBus), tích hợp WeChat/WeCom, tăng cường bảo mật (.security.yml, lọc dữ liệu nhạy cảm), provider mới (AWS Bedrock, Azure, Xiaomi MiMo) và 35 bản vá lỗi. PicoClaw đã đạt **26K Stars**!
2026-03-17 🚀 **v0.2.3 đã phát hành!** Giao diện system tray (Windows & Linux), truy vấn trạng thái sub-agent (`spawn_status`), thử nghiệm Gateway hot-reload, bảo mật Cron, và 2 bản vá bảo mật. PicoClaw đã đạt **25K Stars**!
2026-03-09 🎉 **v0.2.1 — Bản cập nhật lớn nhất từ trước đến nay!** Hỗ trợ giao thức MCP, 4 Channel mới (Matrix/IRC/WeCom/Discord Proxy), 3 Provider mới (Kimi/Minimax/Avian), pipeline thị giác, bộ nhớ JSONL, định tuyến mô hình.
2026-02-28 📦 **v0.2.0** phát hành với hỗ trợ Docker Compose và Web UI Launcher.
<details>
<summary>Tin tức trước đó...</summary>
@@ -174,8 +170,7 @@ Ngoài ra, tải binary cho nền tảng của bạn từ trang [GitHub Releases
Yêu cầu:
- Go 1.25+
- Node.js 22+ và pnpm 10.33.0+ cho các bản build Web UI / launcher
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -183,15 +178,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# Cài đặt dependencies frontend
(cd web/frontend && pnpm install --frozen-lockfile)
# Build binary lõi
make build
# Build Web UI Launcher (cần cho chế độ WebUI)
make build-launcher
# Build các binary lõi cho mọi nền tảng do Makefile quản lý
make build-all
@@ -206,138 +195,7 @@ make install
## 🚀 Hướng dẫn Khởi động Nhanh
### 🌐 WebUI Launcher (Khuyến nghị cho Desktop)
WebUI Launcher cung cấp giao diện dựa trên trình duyệt để cấu hình và trò chuyện. Đây là cách dễ nhất để bắt đầu — không cần kiến thức dòng lệnh.
**Tùy chọn 1: Nhấp đúp (Desktop)**
Sau khi tải xuống từ [picoclaw.io](https://picoclaw.io), nhấp đúp vào `picoclaw-launcher` (hoặc `picoclaw-launcher.exe` trên Windows). Trình duyệt của bạn sẽ tự động mở tại `http://localhost:18800`.
**Tùy chọn 2: Dòng lệnh**
```bash
picoclaw-launcher
# Mở http://localhost:18800 trong trình duyệt của bạn
```
> [!TIP]
> **Truy cập từ xa / Docker / VM:** Thêm cờ `-public` để lắng nghe trên tất cả giao diện:
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**Bắt đầu:**
Mở WebUI, sau đó: **1)** Cấu hình Provider (thêm API key LLM của bạn) -> **2)** Cấu hình Channel (ví dụ: Telegram) -> **3)** Khởi động Gateway -> **4)** Trò chuyện!
Để biết tài liệu WebUI chi tiết, xem [docs.picoclaw.io](https://docs.picoclaw.io).
<details>
<summary><b>Docker (thay thế)</b></summary>
```bash
# 1. Clone this repo
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. First run — auto-generates docker/data/config.json then exits
# (only triggers when both config.json and workspace/ are missing)
docker compose -f docker/docker-compose.yml --profile launcher up
# The container prints "First-run setup complete." and stops.
# 3. Set your API keys
vim docker/data/config.json
# 4. Start
docker compose -f docker/docker-compose.yml --profile launcher up -d
# Open http://localhost:18800
```
> **Người dùng Docker / VM:** Gateway lắng nghe trên `127.0.0.1` theo mặc định. Đặt `PICOCLAW_GATEWAY_HOST=0.0.0.0` hoặc dùng cờ `-public` để có thể truy cập từ host.
```bash
# Check logs
docker compose -f docker/docker-compose.yml logs -f
# Stop
docker compose -f docker/docker-compose.yml --profile launcher down
# Update
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — Cảnh báo bảo mật khi khởi chạy lần đầu</b></summary>
macOS có thể chặn `picoclaw-launcher` khi khởi chạy lần đầu vì nó được tải từ internet và chưa được công chứng qua Mac App Store.
**Bước 1:** Nhấp đúp vào `picoclaw-launcher`. Bạn sẽ thấy cảnh báo bảo mật:
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="Cảnh báo macOS Gatekeeper" width="400">
</p>
> *"picoclaw-launcher" Không Mở Được — Apple không thể xác minh "picoclaw-launcher" không chứa phần mềm độc hại có thể gây hại cho Mac hoặc xâm phạm quyền riêng tư của bạn.*
**Bước 2:** Mở **Cài đặt Hệ thống** → **Quyền riêng tư & Bảo mật** → cuộn xuống phần **Bảo mật** → nhấp **Vẫn Mở** → xác nhận bằng cách nhấp **Vẫn Mở** trong hộp thoại.
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS Quyền riêng tư & Bảo mật — Vẫn Mở" width="600">
</p>
Sau bước này, `picoclaw-launcher` sẽ mở bình thường trong các lần khởi chạy tiếp theo.
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android
Hãy cho chiếc điện thoại cũ của bạn một cuộc sống mới! Biến nó thành Trợ lý AI thông minh với PicoClaw.
**Tùy chọn 1: Cài đặt APK**
Xem trước:
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
Tải APK từ [picoclaw.io](https://picoclaw.io/download/) và cài đặt trực tiếp. Không cần Termux!
**Tùy chọn 2: Termux**
<details>
<summary><b>Terminal Launcher (cho môi trường hạn chế tài nguyên)</b></summary>
1. Cài đặt [Termux](https://github.com/termux/termux-app) (tải từ [GitHub Releases](https://github.com/termux/termux-app/releases), hoặc tìm kiếm trong F-Droid / Google Play)
2. Chạy các lệnh sau:
```bash
# Download the latest release
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot provides a standard Linux filesystem layout
```
Sau đó làm theo phần Terminal Launcher bên dưới để hoàn tất cấu hình.
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
Đối với các môi trường tối giản chỉ có binary lõi `picoclaw` (không có Launcher UI), bạn có thể cấu hình mọi thứ qua dòng lệnh và tệp cấu hình JSON.
### CLI
**1. Khởi tạo**
@@ -360,8 +218,11 @@ Lệnh này tạo `~/.picoclaw/config.json` và thư mục workspace.
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_keys": ["sk-your-api-key"]
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
@@ -382,8 +243,60 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker (thay thế)</b></summary>
```bash
# 1. Clone this repo
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. First run — auto-generates docker/data/config.json then exits
# (only triggers when both config.json and workspace/ are missing)
docker compose -f docker/docker-compose.yml --profile gateway up
# The container prints "First-run setup complete." and stops.
# 3. Set your API keys
vim docker/data/config.json
# 4. Start
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Người dùng Docker / VM:** Gateway lắng nghe trên `127.0.0.1` theo mặc định. Đặt `PICOCLAW_GATEWAY_HOST=0.0.0.0` hoặc dùng cờ `-public` để có thể truy cập từ host.
```bash
# Check logs
docker compose -f docker/docker-compose.yml logs -f
# Stop
docker compose -f docker/docker-compose.yml --profile gateway down
# Update
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android (Termux)
1. Cài đặt [Termux](https://github.com/termux/termux-app) (tải từ [GitHub Releases](https://github.com/termux/termux-app/releases), hoặc tìm kiếm trong F-Droid / Google Play)
2. Chạy các lệnh sau:
```bash
# Download the latest release
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot provides a standard Linux filesystem layout
```
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 Providers (LLM)
PicoClaw hỗ trợ 30+ Provider LLM thông qua cấu hình `model_list`. Sử dụng định dạng `protocol/model`:
@@ -589,7 +502,7 @@ PicoClaw hỗ trợ nhắc nhở đã lên lịch và tác vụ định kỳ th
| Chủ đề | Mô tả |
|--------|-------|
| [Docker & Khởi động Nhanh](../guides/docker.vi.md) | Thiết lập Docker Compose, chế độ Launcher/Agent |
| [Docker & Khởi động Nhanh](../guides/docker.vi.md) | Thiết lập Docker Compose, chế độ Gateway/Agent |
| [Ứng dụng Chat](../guides/chat-apps.vi.md) | Hướng dẫn thiết lập 17+ Channel |
| [Cấu hình](../guides/configuration.vi.md) | Biến môi trường, bố cục workspace, sandbox bảo mật |
| [Providers & Models](../guides/providers.vi.md) | 30+ Provider LLM, định tuyến mô hình, cấu hình model_list |
+60 -147
View File
@@ -64,16 +64,12 @@
</a>
</p>
2026-03-31 📱 **Android 支持!** PicoClaw 现可在 Android 上运行!APK 下载地址:[picoclaw.io](https://picoclaw.io/download)
2026-03-25 🚀 **v0.2.4 发布!** Agent 架构全面重构(SubTurn、Hook、Steering、EventBus)、微信/企业微信深度集成、安全体系升级(.security.yml、敏感数据过滤)、新增 Provider(AWS Bedrock、Azure、小米 MiMo),以及 35 项 Bug 修复。PicoClaw 已达 **26K ⭐**!
2026-03-17 🚀 **v0.2.3 发布!** 系统托盘 UI(Windows & Linux)、子 Agent 状态查询 (`spawn_status`)、实验性 Gateway 热重载、Cron 安全门控,以及 2 项安全修复。PicoClaw 已达 **25K ⭐**!
2026-03-09 🎉 **v0.2.1 — 史上最大更新!** MCP 协议支持、4 个新频道 (Matrix/IRC/WeCom/Discord Proxy)、3 个新 Provider (Kimi/Minimax/Avian)、视觉管线、JSONL 记忆存储、模型路由。
2026-02-28 📦 **v0.2.0** 发布,支持 Docker Compose 和 Web UI 启动器。
<details>
<summary>更早的新闻...</summary>
@@ -174,8 +170,7 @@ PicoClaw 几乎可以部署在任何 Linux 设备上!
前置要求:
- Go 1.25+
- Node.js 22+ 和 pnpm 10.33.0+(用于 Web UI / launcher 构建)
- Go 1.25.13+
```bash
git clone https://github.com/sipeed/picoclaw.git
@@ -183,15 +178,9 @@ git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
make deps
# 安装前端依赖
(cd web/frontend && pnpm install --frozen-lockfile)
# 构建核心二进制文件
make build
# 构建 Web UI Launcher(WebUI 模式必需)
make build-launcher
# 为 Makefile 管理的所有平台构建核心二进制文件
make build-all
@@ -206,138 +195,7 @@ make install
## 🚀 快速开始
### 🌐 WebUI Launcher(推荐桌面用户)
WebUI Launcher 提供基于浏览器的配置与聊天界面,是最简单的上手方式——无需命令行知识。
**方式一:双击启动(桌面)**
从 [picoclaw.io](https://picoclaw.io) 下载后,双击 `picoclaw-launcher`(Windows 上为 `picoclaw-launcher.exe`),浏览器将自动打开 `http://localhost:18800`。
**方式二:命令行**
```bash
picoclaw-launcher
# 在浏览器中打开 http://localhost:18800
```
> [!TIP]
> **远程访问 / Docker / 虚拟机:** 添加 `-public` 参数以监听所有网络接口:
> ```bash
> picoclaw-launcher -public
> ```
<p align="center">
<img src="../../assets/launcher-webui.jpg" alt="WebUI Launcher" width="600">
</p>
**开始使用:**
打开 WebUI,然后:**1)** 配置 Provider(填入 LLM API Key)-> **2)** 配置 Channel(如 Telegram)-> **3)** 启动 Gateway -> **4)** 开始聊天!
详细 WebUI 文档请参阅 [docs.picoclaw.io](https://docs.picoclaw.io)。
<details>
<summary><b>Docker(备选方案)</b></summary>
```bash
# 1. 克隆本仓库
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. 首次运行——自动生成 docker/data/config.json 后退出
# (仅在 config.json 和 workspace/ 均不存在时触发)
docker compose -f docker/docker-compose.yml --profile launcher up
# 容器打印 "First-run setup complete." 后停止。
# 3. 填写 API Key
vim docker/data/config.json
# 4. 启动
docker compose -f docker/docker-compose.yml --profile launcher up -d
# 打开 http://localhost:18800
```
> **Docker / 虚拟机用户:** Gateway 默认监听 `127.0.0.1`。设置 `PICOCLAW_GATEWAY_HOST=0.0.0.0` 或使用 `-public` 参数以允许从宿主机访问。
```bash
# 查看日志
docker compose -f docker/docker-compose.yml logs -f
# 停止
docker compose -f docker/docker-compose.yml --profile launcher down
# 更新
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile launcher up -d
```
</details>
<details>
<summary><b>macOS — 首次启动安全警告</b></summary>
macOS 可能会在首次启动时拦截 `picoclaw-launcher`,因为它从互联网下载,未经 Mac App Store 公证。
**第一步:** 双击 `picoclaw-launcher`,会出现安全警告:
<p align="center">
<img src="../../assets/macos-gatekeeper-warning.jpg" alt="macOS Gatekeeper 警告" width="400">
</p>
> *"picoclaw-launcher" 无法打开 — Apple 无法验证 "picoclaw-launcher" 不含可能损害 Mac 或危及隐私的恶意软件。*
**第二步:** 打开**系统设置** → **隐私与安全性** → 向下滚动找到**安全性**部分 → 点击**仍要打开** → 在弹窗中再次点击**打开**。
<p align="center">
<img src="../../assets/macos-gatekeeper-allow.jpg" alt="macOS 隐私与安全性 — 仍要打开" width="600">
</p>
完成这一次操作后,后续启动 `picoclaw-launcher` 将不再弹出警告。
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android
让你十年前的旧手机焕发新生!将它变成你的 AI 助手。
**方式一:APK 安装**
预览:
<table>
<tr>
<td><img src="../../assets/fui_main_page.jpg" width="200"></td>
<td><img src="../../assets/fui_web_page.jpg" width="200"></td>
<td><img src="../../assets/fui_log_page.jpg" width="200"></td>
<td><img src="../../assets/fui_setting_page.jpg" width="200"></td>
</tr>
</table>
从 [picoclaw.io](https://picoclaw.io/download/) 下载 APK 并直接安装,无需 Termux!
**方式二:Termux**
<details>
<summary><b>Terminal Launcher(适用于资源受限环境)</b></summary>
1. 安装 [Termux](https://github.com/termux/termux-app)(可从 [GitHub Releases](https://github.com/termux/termux-app/releases) 下载,或在 F-Droid / Google Play 中搜索)
2. 执行以下命令:
```bash
# 从 Release 页面下载最新版本
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot 提供标准 Linux 文件系统布局
```
然后跟随下面的"Terminal Launcher"章节继续配置。
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
对于只有 `picoclaw` 核心二进制文件的极简环境(无 Launcher UI),可通过命令行和 JSON 配置文件完成所有配置。
### CLI
**1. 初始化**
@@ -360,8 +218,11 @@ picoclaw onboard
"model_list": [
{
"model_name": "gpt-5.4",
"model": "openai/gpt-5.4",
"api_keys": ["sk-your-api-key"]
"provider": "openai",
"model": "gpt-5.4",
"api_keys": [
"sk-your-api-key"
]
}
]
}
@@ -382,8 +243,60 @@ picoclaw agent
picoclaw gateway
```
<details>
<summary><b>Docker(备选方案)</b></summary>
```bash
# 1. 克隆本仓库
git clone https://github.com/sipeed/picoclaw.git
cd picoclaw
# 2. 首次运行——自动生成 docker/data/config.json 后退出
# (仅在 config.json 和 workspace/ 均不存在时触发)
docker compose -f docker/docker-compose.yml --profile gateway up
# 容器打印 "First-run setup complete." 后停止。
# 3. 填写 API Key
vim docker/data/config.json
# 4. 启动
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
> **Docker / 虚拟机用户:** Gateway 默认监听 `127.0.0.1`。如需从宿主机访问,请设置 `PICOCLAW_GATEWAY_HOST=0.0.0.0`,并在 Compose 中映射所需端口。
```bash
# 查看日志
docker compose -f docker/docker-compose.yml logs -f
# 停止
docker compose -f docker/docker-compose.yml --profile gateway down
# 更新
docker compose -f docker/docker-compose.yml pull
docker compose -f docker/docker-compose.yml --profile gateway up -d
```
</details>
<a id="-run-on-old-android-phones"></a>
### 📱 Android (Termux)
1. 安装 [Termux](https://github.com/termux/termux-app)(可从 [GitHub Releases](https://github.com/termux/termux-app/releases) 下载,或在 F-Droid / Google Play 中搜索)
2. 执行以下命令:
```bash
# 从 Release 页面下载最新版本
wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz
tar xzf picoclaw_Linux_arm64.tar.gz
pkg install proot
termux-chroot ./picoclaw onboard # chroot 提供标准 Linux 文件系统布局
```
<img src="../../assets/termux.jpg" alt="PicoClaw on Termux" width="512">
[Android Termux Guide](../guides/android-termux.md).
## 🔌 Providers (LLM)
PicoClaw 通过 `model_list` 配置支持 30+ LLM Provider,使用 `协议/模型` 格式:
@@ -597,7 +510,7 @@ PicoClaw 通过 `cron` 工具支持定时提醒和重复任务:
| 主题 | 说明 |
|------|------|
| 🐳 [Docker 与快速开始](../guides/docker.zh.md) | Docker Compose 配置、Launcher/Agent 模式、快速开始 |
| 🐳 [Docker 与快速开始](../guides/docker.zh.md) | Docker Compose 配置、Gateway/Agent 模式、快速开始 |
| 💬 [聊天应用配置](../guides/chat-apps.zh.md) | 全部 17+ Channel 配置指南 |
| ⚙️ [配置指南](../guides/configuration.zh.md) | 环境变量、工作区布局、安全沙箱 |
| 🔌 [提供商与模型配置](../guides/providers.zh.md) | 30+ LLM Provider、模型路由、model_list 配置 |
+2 -4
View File
@@ -3,7 +3,6 @@ module github.com/sipeed/picoclaw
go 1.25.13
require (
fyne.io/systray v1.12.2
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0
github.com/SevereCloud/vksdk/v3 v3.3.1
@@ -52,7 +51,6 @@ require (
gopkg.in/yaml.v3 v3.0.1
maunium.net/go/mautrix v0.27.0
modernc.org/sqlite v1.53.0
rsc.io/qr v0.2.0
)
require (
@@ -88,7 +86,6 @@ require (
github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/invopop/jsonschema v0.14.0 // indirect
@@ -123,6 +120,7 @@ require (
modernc.org/libc v1.73.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
rsc.io/qr v0.2.0 // indirect
)
require (
@@ -150,7 +148,7 @@ require (
golang.org/x/arch v0.24.0 // indirect
golang.org/x/crypto v0.53.0
golang.org/x/net v0.55.0
golang.org/x/sync v0.21.0
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0
)
-4
View File
@@ -3,8 +3,6 @@ aead.dev/minisign v0.2.0/go.mod h1:zdq6LdSd9TbuSxchxwhpA9zEb9YXcVGoE8JakuiGaIQ=
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
fyne.io/systray v1.12.2 h1:Y8DZxgLHsVQt6rY9Zrkkg+j67S7vv/1F2viOWKPpVeA=
fyne.io/systray v1.12.2/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 h1:CU4+EJeJi3TKYWEcYuSdWsjzw0nVsK/H0MSQOiPcymU=
@@ -135,8 +133,6 @@ github.com/go-resty/resty/v2 v2.17.1/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2m
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+2 -2
View File
@@ -513,7 +513,7 @@ func (c *PicoChannel) SendPlaceholder(ctx context.Context, chatID string) (strin
return msgID, nil
}
// BeginStream implements channels.StreamingCapable for Pico WebUI.
// BeginStream implements channels.StreamingCapable for the Pico protocol.
func (c *PicoChannel) BeginStream(ctx context.Context, chatID string) (channels.Streamer, error) {
if c == nil || c.config == nil || !c.config.Streaming.Enabled {
return nil, fmt.Errorf("streaming disabled in config")
@@ -743,7 +743,7 @@ func (s *picoStreamer) sendReasoningLocked(ctx context.Context, content string)
return nil
}
// SendMedia implements channels.MediaSender for the Pico web UI.
// SendMedia implements channels.MediaSender for the Pico protocol.
// Media is delivered as a normal assistant message carrying structured
// attachments plus an authenticated same-origin download URL.
func (c *PicoChannel) SendMedia(ctx context.Context, msg bus.OutboundMediaMessage) ([]string, error) {
+2 -3
View File
@@ -2536,8 +2536,7 @@ func TestLoadConfig_MixedKeys_NoPassphrase(t *testing.T) {
// TestSaveConfig_UsesPassphraseProvider verifies that SaveConfig encrypts plaintext
// api_keys using credential.PassphraseProvider() rather than os.Getenv directly.
// This matters for the launcher, which clears the environment variable and redirects
// PassphraseProvider to an in-memory SecureStore.
// This also supports callers that supply the passphrase from an in-memory store.
func TestSaveConfig_UsesPassphraseProvider(t *testing.T) {
dir := t.TempDir()
cfgPath := filepath.Join(dir, "config.json")
@@ -2546,7 +2545,7 @@ func TestSaveConfig_UsesPassphraseProvider(t *testing.T) {
t.Setenv("PICOCLAW_KEY_PASSPHRASE", "")
mustSetupSSHKey(t)
// Replace PassphraseProvider with an in-memory function (simulating SecureStore).
// Replace PassphraseProvider with an in-memory function (without an environment variable).
const testPassphrase = "provider-passphrase"
orig := credential.PassphraseProvider
credential.PassphraseProvider = func() string { return testPassphrase }
-5
View File
@@ -33,11 +33,6 @@ const (
// Default: <cwd>/skills
EnvBuiltinSkills = "PICOCLAW_BUILTIN_SKILLS"
// EnvBinary overrides the path to the picoclaw executable.
// Used by the web launcher when spawning the gateway subprocess.
// Default: resolved from the same directory as the current executable.
EnvBinary = "PICOCLAW_BINARY"
// EnvGatewayHost overrides the host address for the gateway server.
// Default: "localhost"
EnvGatewayHost = "PICOCLAW_GATEWAY_HOST"
-4
View File
@@ -49,10 +49,6 @@ const PassphraseEnvVar = "PICOCLAW_KEY_PASSPHRASE"
// process environment. Replace it at startup to use a different source, such as
// an in-memory SecureStore, so that all LoadConfig() calls everywhere share the
// same passphrase source without needing os.Environ.
//
// Example (launcher main.go):
//
// credential.PassphraseProvider = apiHandler.passphraseStore.Get
var PassphraseProvider func() string = func() string {
return os.Getenv(PassphraseEnvVar)
}
+1 -1
View File
@@ -233,7 +233,7 @@ func (s *JSONLStore) UpsertSessionMeta(
// Main-session aliases (e.g. "agent:main:main" or its opaque form) are
// skipped during promotion. The main session is a shared global fallback
// and promoting its history into individual sessions would attach stale
// messages to every new Web UI session (issue #2972).
// messages to every new session (issue #2972).
func (s *JSONLStore) PromoteAliasHistory(
_ context.Context,
sessionKey string,
+2 -19
View File
@@ -381,27 +381,10 @@ func finalizeProviderFromConfig(
}
func isEmptyAPIKeyAllowed(protocol string) bool {
option, ok := modelProviderOptionForName(protocol)
option, ok := providerMetadataForName(protocol)
return ok && option.EmptyAPIKeyAllowed
}
// IsEmptyAPIKeyAllowedForProtocol reports whether a protocol allows requests
// without api_key when using its default local endpoint.
func IsEmptyAPIKeyAllowedForProtocol(protocol string) bool {
protocol = strings.ToLower(strings.TrimSpace(protocol))
return isEmptyAPIKeyAllowed(protocol)
}
// IsHTTPAPIProtocol reports whether a provider uses an HTTP API base in the
// model configuration path. This excludes providers such as Bedrock, CLI
// bridges, and OAuth-only managed providers even if they do not require an
// explicit api_key field.
func IsHTTPAPIProtocol(protocol string) bool {
protocol = NormalizeProvider(protocol)
option, ok := modelProviderOptionsByName[protocol]
return ok && option.httpAPI
}
// DefaultAPIBaseForProtocol returns the configured default API base for a protocol.
// It returns empty string if the protocol has no default base.
func DefaultAPIBaseForProtocol(protocol string) string {
@@ -411,7 +394,7 @@ func DefaultAPIBaseForProtocol(protocol string) string {
// getDefaultAPIBase returns the default API base URL for a given protocol.
func getDefaultAPIBase(protocol string) string {
option, ok := modelProviderOptionForName(protocol)
option, ok := providerMetadataForName(protocol)
if !ok {
return ""
}
+1 -152
View File
@@ -1057,157 +1057,6 @@ func TestGetDefaultAPIBase_QwenUSAliases(t *testing.T) {
}
}
func TestModelProviderOptions(t *testing.T) {
options := ModelProviderOptions()
if len(options) == 0 {
t.Fatal("ModelProviderOptions() returned no options")
}
seen := make(map[string]ModelProviderOption, len(options))
for _, option := range options {
seen[option.ID] = option
}
if _, ok := seen["openai"]; !ok {
t.Fatal("openai option missing")
}
if option, ok := seen["openai"]; ok && !option.CreateAllowed {
t.Fatal("openai should be creatable")
}
if option, ok := seen["openai"]; ok && !option.SupportsFetch {
t.Fatal("openai should support upstream model listing")
} else if option.DisplayName != "OpenAI" {
t.Fatalf("openai display_name = %q, want %q", option.DisplayName, "OpenAI")
} else if len(option.CommonModels) == 0 {
t.Fatal("openai common_models should not be empty")
}
if option, ok := seen["lmstudio"]; !ok {
t.Fatal("lmstudio option missing")
} else if !option.EmptyAPIKeyAllowed {
t.Fatal("lmstudio should allow empty API keys")
}
if option, ok := seen["gpt4free"]; !ok {
t.Fatal("gpt4free option missing")
} else {
if option.DefaultAPIBase != "http://localhost:1337/v1" {
t.Fatalf("gpt4free default_api_base = %q, want %q", option.DefaultAPIBase, "http://localhost:1337/v1")
}
if !option.EmptyAPIKeyAllowed {
t.Fatal("gpt4free should allow empty API keys")
}
if !option.SupportsFetch {
t.Fatal("gpt4free should support upstream model listing")
}
}
if option, ok := seen["siliconflow"]; !ok {
t.Fatal("siliconflow option missing")
} else if option.DefaultAPIBase != "https://api.siliconflow.cn/v1" {
t.Fatalf(
"siliconflow default_api_base = %q, want %q",
option.DefaultAPIBase,
"https://api.siliconflow.cn/v1",
)
}
if option, ok := seen["nearai"]; !ok {
t.Fatal("nearai option missing")
} else {
if option.DisplayName != "NEAR AI Cloud" {
t.Fatalf("nearai display_name = %q, want %q", option.DisplayName, "NEAR AI Cloud")
}
if option.DefaultAPIBase != "https://cloud-api.near.ai/v1" {
t.Fatalf("nearai default_api_base = %q, want %q", option.DefaultAPIBase, "https://cloud-api.near.ai/v1")
}
if !option.SupportsFetch {
t.Fatal("nearai should support upstream model listing")
}
if len(option.CommonModels) == 0 {
t.Fatal("nearai common_models should not be empty")
}
}
if option, ok := seen["anthropic"]; !ok {
t.Fatal("anthropic option missing")
} else if option.DefaultAPIBase != "https://api.anthropic.com/v1" {
t.Fatalf("anthropic default_api_base = %q, want %q", option.DefaultAPIBase, "https://api.anthropic.com/v1")
}
// First-party Claude API model IDs use hyphenated formats such as
// claude-{name}-{major}-{minor} or claude-{name}-{major}-{minor}-{YYYYMMDD};
// dotted provider prefixes are for platform-specific IDs such as Bedrock.
// https://platform.claude.com/docs/en/about-claude/models/model-ids-and-versions
for _, provider := range []string{"anthropic", "anthropic-messages"} {
option, ok := seen[provider]
if !ok {
t.Fatalf("%s option missing", provider)
}
for _, model := range option.CommonModels {
if strings.Contains(model, ".") {
t.Fatalf("%s common_model %q uses dotted ID", provider, model)
}
}
}
if _, ok := seen["azure"]; !ok {
t.Fatal("azure option missing")
}
if option, ok := seen["bedrock"]; !ok {
t.Fatal("bedrock option missing")
} else if !option.CreateAllowed {
t.Fatal("bedrock should be creatable and defer credential/build errors to runtime")
}
if option, ok := seen["elevenlabs"]; !ok {
t.Fatal("elevenlabs option missing")
} else {
if option.DefaultAPIBase != "https://api.elevenlabs.io" {
t.Fatalf("elevenlabs default_api_base = %q, want %q", option.DefaultAPIBase, "https://api.elevenlabs.io")
}
if option.DefaultModelAllowed {
t.Fatal("elevenlabs should be ASR-only and therefore not allowed as a default chat model")
}
}
if option, ok := seen["antigravity"]; !ok {
t.Fatal("antigravity option missing")
} else {
if !option.CreateAllowed {
t.Fatal("antigravity should be creatable")
}
if option.DefaultAuthMethod != "oauth" {
t.Fatalf("antigravity default_auth_method = %q, want %q", option.DefaultAuthMethod, "oauth")
}
if !option.AuthMethodLocked {
t.Fatal("antigravity auth method should be locked")
}
}
if option, ok := seen["github-copilot"]; !ok {
t.Fatal("github-copilot option missing")
} else if option.DefaultAPIBase != "localhost:4321" {
t.Fatalf("github-copilot default_api_base = %q, want %q", option.DefaultAPIBase, "localhost:4321")
} else if !option.Local {
t.Fatal("github-copilot should be marked local")
}
if option, ok := seen["qwen-portal"]; !ok {
t.Fatal("qwen-portal option missing")
} else if len(option.Aliases) == 0 || option.Aliases[0] != "qwen" {
t.Fatalf("qwen-portal aliases = %#v, want to include qwen", option.Aliases)
}
for _, option := range options {
if len(option.CommonModels) > 6 {
t.Fatalf("provider %q exposes %d common_models, want at most 6", option.ID, len(option.CommonModels))
}
if option.Local && len(option.CommonModels) > 0 {
t.Fatalf("local provider %q should not expose common_models", option.ID)
}
seenModels := make(map[string]struct{}, len(option.CommonModels))
for _, model := range option.CommonModels {
if strings.TrimSpace(model) == "" {
t.Fatalf("provider %q includes an empty common_model entry", option.ID)
}
if _, exists := seenModels[model]; exists {
t.Fatalf("provider %q includes duplicate common_model %q", option.ID, model)
}
seenModels[model] = struct{}{}
}
}
}
func TestBuildModelProviderAliasMap(t *testing.T) {
aliases := buildModelProviderAliasMap()
if len(aliases) == 0 {
@@ -1215,7 +1064,7 @@ func TestBuildModelProviderAliasMap(t *testing.T) {
}
seenAliases := make(map[string]string, len(aliases))
for provider, option := range modelProviderOptionsByName {
for provider, option := range providerMetadataByName {
got, ok := aliases[provider]
if !ok {
t.Fatalf("canonical provider %q missing from alias map", provider)
+3 -41
View File
@@ -1,51 +1,13 @@
package providers
import (
"sort"
"strings"
)
import "strings"
// ModelProviderOptions returns the canonical provider catalog exposed to the Web UI.
func ModelProviderOptions() []ModelProviderOption {
options := make([]ModelProviderOption, 0, len(modelProviderOptionsByName))
for _, option := range modelProviderOptionsByName {
options = append(options, option)
}
sort.Slice(options, func(i, j int) bool {
return options[i].ID < options[j].ID
})
return options
}
// IsSupportedModelProvider reports whether provider resolves to a provider ID
// returned by ModelProviderOptions.
// IsSupportedModelProvider reports whether provider resolves to a known provider ID.
func IsSupportedModelProvider(provider string) bool {
_, ok := modelProviderOptionForName(provider)
_, ok := providerMetadataForName(provider)
return ok
}
// IsModelProviderFetchable reports whether provider supports upstream /models
// listing through the launcher fetch endpoint.
func IsModelProviderFetchable(provider string) bool {
option, ok := modelProviderOptionForName(provider)
return ok && option.SupportsFetch
}
// IsCreatableModelProvider reports whether provider can be selected for a new
// model entry from the Web UI.
func IsCreatableModelProvider(provider string) bool {
option, ok := modelProviderOptionForName(provider)
return ok && option.CreateAllowed
}
// IsDefaultModelProvider reports whether provider can be used as the default
// chat model. Some providers such as ASR-only entries are intentionally
// exposed in model_list management but cannot drive the gateway default model.
func IsDefaultModelProvider(provider string) bool {
option, ok := modelProviderOptionForName(provider)
return ok && option.DefaultModelAllowed
}
// SplitModelProviderAndID separates a legacy "provider/model" string into its
// effective provider and canonical model ID. Unknown prefixes are treated as
// part of the model ID and fall back to defaultProvider.
+75 -498
View File
@@ -2,583 +2,160 @@ package providers
import "strings"
// ModelProviderOption describes a canonical provider entry exposed to the Web UI.
// It also serves as the backend-owned source of truth for shared provider metadata.
type ModelProviderOption struct {
ID string `json:"id"`
DisplayName string `json:"display_name,omitempty"`
IconSlug string `json:"icon_slug,omitempty"`
Domain string `json:"domain,omitempty"`
DefaultAPIBase string `json:"default_api_base"`
EmptyAPIKeyAllowed bool `json:"empty_api_key_allowed"`
CreateAllowed bool `json:"create_allowed"`
DefaultModelAllowed bool `json:"default_model_allowed"`
SupportsFetch bool `json:"supports_fetch,omitempty"`
DefaultAuthMethod string `json:"default_auth_method,omitempty"`
AuthMethodLocked bool `json:"auth_method_locked,omitempty"`
Local bool `json:"local,omitempty"`
Priority float64 `json:"priority,omitempty"`
CommonModels []string `json:"common_models,omitempty"`
Aliases []string `json:"aliases,omitempty"`
httpAPI bool `json:"-"`
// providerMetadata defines the shared runtime defaults and aliases for a provider.
type providerMetadata struct {
DefaultAPIBase string
EmptyAPIKeyAllowed bool
Aliases []string
}
var modelProviderOptionsByName = map[string]ModelProviderOption{
var providerMetadataByName = map[string]providerMetadata{
"openai": {
ID: "openai",
DisplayName: "OpenAI",
IconSlug: "openai",
Domain: "openai.com",
DefaultAPIBase: "https://api.openai.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 100,
CommonModels: []string{"gpt-5.4", "gpt-5.4-mini", "gpt-5.5"},
Aliases: []string{"gpt"},
httpAPI: true,
DefaultAPIBase: "https://api.openai.com/v1",
Aliases: []string{"gpt"},
},
"anthropic": {
ID: "anthropic",
DisplayName: "Anthropic",
IconSlug: "anthropic",
Domain: "anthropic.com",
DefaultAPIBase: "https://api.anthropic.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
Priority: 95,
CommonModels: []string{"claude-opus-4-7", "claude-sonnet-4-6", "claude-haiku-4-5"},
Aliases: []string{"claude"},
httpAPI: true,
DefaultAPIBase: "https://api.anthropic.com/v1",
Aliases: []string{"claude"},
},
"anthropic-messages": {
ID: "anthropic-messages",
DisplayName: "Anthropic Messages",
IconSlug: "anthropic",
Domain: "anthropic.com",
DefaultAPIBase: "https://api.anthropic.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
Priority: 94,
CommonModels: []string{"claude-opus-4-7", "claude-sonnet-4-6", "claude-haiku-4-5"},
httpAPI: true,
DefaultAPIBase: "https://api.anthropic.com/v1",
},
"gemini": {
ID: "gemini",
DisplayName: "Google Gemini",
IconSlug: "googlegemini",
Domain: "gemini.google.com",
DefaultAPIBase: "https://generativelanguage.googleapis.com/v1beta",
CreateAllowed: true,
DefaultModelAllowed: true,
Priority: 90,
CommonModels: []string{"gemini-3.1-pro-preview", "gemini-3-flash-preview", "gemini-3.1-flash-lite"},
Aliases: []string{"google"},
httpAPI: true,
DefaultAPIBase: "https://generativelanguage.googleapis.com/v1beta",
Aliases: []string{"google"},
},
"deepseek": {
ID: "deepseek",
DisplayName: "DeepSeek",
IconSlug: "deepseek",
Domain: "deepseek.com",
DefaultAPIBase: "https://api.deepseek.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 85,
CommonModels: []string{"deepseek-v4-flash", "deepseek-v4-pro"},
httpAPI: true,
DefaultAPIBase: "https://api.deepseek.com/v1",
},
"openrouter": {
ID: "openrouter",
DisplayName: "OpenRouter",
IconSlug: "openrouter",
Domain: "openrouter.ai",
DefaultAPIBase: "https://openrouter.ai/api/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 80,
CommonModels: []string{
"openai/gpt-5.4",
"anthropic/claude-opus-4.7",
"google/gemini-3.1-pro-preview",
"qwen/qwen3-coder-next",
},
httpAPI: true,
DefaultAPIBase: "https://openrouter.ai/api/v1",
},
"qwen-portal": {
ID: "qwen-portal",
DisplayName: "Qwen",
IconSlug: "alibabacloud",
Domain: "qwenlm.ai",
DefaultAPIBase: "https://dashscope.aliyuncs.com/compatible-mode/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 75,
CommonModels: []string{"qwen3.6-max-preview", "qwen3.6-plus", "qwen3.6-flash", "qwen3-coder-next"},
Aliases: []string{"qwen"},
httpAPI: true,
DefaultAPIBase: "https://dashscope.aliyuncs.com/compatible-mode/v1",
Aliases: []string{"qwen"},
},
"qwen-intl": {
ID: "qwen-intl",
DisplayName: "Qwen International",
IconSlug: "alibabacloud",
Domain: "alibabacloud.com",
DefaultAPIBase: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 74,
CommonModels: []string{"qwen3.6-max-preview", "qwen3.6-plus", "qwen3.6-flash", "qwen3-coder-next"},
Aliases: []string{"qwen-international", "dashscope-intl"},
httpAPI: true,
DefaultAPIBase: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
Aliases: []string{"qwen-international", "dashscope-intl"},
},
"moonshot": {
ID: "moonshot",
DisplayName: "Moonshot",
Domain: "moonshot.ai",
DefaultAPIBase: "https://api.moonshot.cn/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 70,
CommonModels: []string{
"kimi-k2.5",
"kimi-k2-thinking",
"kimi-k2-thinking-turbo",
"kimi-k2-turbo-preview",
},
httpAPI: true,
DefaultAPIBase: "https://api.moonshot.cn/v1",
},
"volcengine": {
ID: "volcengine",
DisplayName: "Volcengine",
IconSlug: "bytedance",
Domain: "volcengine.com",
DefaultAPIBase: "https://ark.cn-beijing.volces.com/api/v3",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 69,
CommonModels: []string{
"doubao-seed-1-6-251015",
"doubao-seed-1-6-flash-250828",
"doubao-seed-1-6-thinking",
},
httpAPI: true,
DefaultAPIBase: "https://ark.cn-beijing.volces.com/api/v3",
},
"zhipu": {
ID: "zhipu",
DisplayName: "Zhipu AI",
IconSlug: "zhipu",
Domain: "zhipuai.cn",
DefaultAPIBase: "https://open.bigmodel.cn/api/paas/v4",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 68,
CommonModels: []string{"glm-5", "glm-4.7", "glm-4.5-air", "glm-4-flash-250414"},
Aliases: []string{"glm"},
httpAPI: true,
DefaultAPIBase: "https://open.bigmodel.cn/api/paas/v4",
Aliases: []string{"glm"},
},
"groq": {
ID: "groq",
DisplayName: "Groq",
IconSlug: "groq",
Domain: "groq.com",
DefaultAPIBase: "https://api.groq.com/openai/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 65,
CommonModels: []string{
"openai/gpt-oss-120b",
"openai/gpt-oss-20b",
"llama-3.3-70b-versatile",
"qwen/qwen3-32b",
},
httpAPI: true,
DefaultAPIBase: "https://api.groq.com/openai/v1",
},
"mistral": {
ID: "mistral",
DisplayName: "Mistral AI",
IconSlug: "mistralai",
Domain: "mistral.ai",
DefaultAPIBase: "https://api.mistral.ai/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 64,
CommonModels: []string{
"mistral-large-latest",
"mistral-medium-3-5",
"mistral-small-latest",
"devstral-latest",
},
httpAPI: true,
DefaultAPIBase: "https://api.mistral.ai/v1",
},
"nvidia": {
ID: "nvidia",
DisplayName: "NVIDIA",
IconSlug: "nvidia",
Domain: "nvidia.com",
DefaultAPIBase: "https://integrate.api.nvidia.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 63,
CommonModels: []string{
"openai/gpt-oss-120b",
"openai/gpt-oss-20b",
"qwen/qwen3-coder-480b-a35b-instruct",
"qwen/qwen3-next-80b-a3b-thinking",
},
httpAPI: true,
DefaultAPIBase: "https://integrate.api.nvidia.com/v1",
},
"cerebras": {
ID: "cerebras",
DisplayName: "Cerebras",
IconSlug: "cerebras",
Domain: "cerebras.ai",
DefaultAPIBase: "https://api.cerebras.ai/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 62,
CommonModels: []string{"gpt-oss-120b", "zai-glm-4.7"},
httpAPI: true,
DefaultAPIBase: "https://api.cerebras.ai/v1",
},
"azure": {
ID: "azure",
DisplayName: "Azure OpenAI",
IconSlug: "microsoftazure",
Domain: "azure.com",
CreateAllowed: true,
DefaultModelAllowed: true,
Priority: 61,
Aliases: []string{"azure-openai"},
httpAPI: true,
Aliases: []string{"azure-openai"},
},
"bedrock": {
ID: "bedrock",
DisplayName: "AWS Bedrock",
IconSlug: "amazonwebservices",
Domain: "aws.amazon.com",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
Priority: 60,
EmptyAPIKeyAllowed: true,
},
"github-copilot": {
ID: "github-copilot",
DisplayName: "GitHub Copilot",
IconSlug: "githubcopilot",
Domain: "github.com",
DefaultAPIBase: "localhost:4321",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
Local: true,
Priority: 55,
Aliases: []string{"copilot"},
DefaultAPIBase: "localhost:4321",
EmptyAPIKeyAllowed: true,
Aliases: []string{"copilot"},
},
"antigravity": {
ID: "antigravity",
DisplayName: "Google Code Assist",
Domain: "antigravity.google",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
DefaultAuthMethod: "oauth",
AuthMethodLocked: true,
Priority: 54,
Aliases: []string{"google-antigravity"},
EmptyAPIKeyAllowed: true,
Aliases: []string{"google-antigravity"},
},
"claude-cli": {
ID: "claude-cli",
DisplayName: "Claude CLI",
IconSlug: "anthropic",
Domain: "anthropic.com",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
Local: true,
Priority: 53,
Aliases: []string{"claudecli"},
EmptyAPIKeyAllowed: true,
Aliases: []string{"claudecli"},
},
"codex-cli": {
ID: "codex-cli",
DisplayName: "Codex CLI",
IconSlug: "openai",
Domain: "openai.com",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
Local: true,
Priority: 52,
Aliases: []string{"codexcli"},
EmptyAPIKeyAllowed: true,
Aliases: []string{"codexcli"},
},
"ollama": {
ID: "ollama",
DisplayName: "Ollama",
IconSlug: "ollama",
Domain: "ollama.com",
DefaultAPIBase: "http://localhost:11434/v1",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Local: true,
Priority: 50,
httpAPI: true,
DefaultAPIBase: "http://localhost:11434/v1",
EmptyAPIKeyAllowed: true,
},
"vllm": {
ID: "vllm",
DisplayName: "VLLM",
Domain: "vllm.ai",
DefaultAPIBase: "http://localhost:8000/v1",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Local: true,
Priority: 49,
httpAPI: true,
DefaultAPIBase: "http://localhost:8000/v1",
EmptyAPIKeyAllowed: true,
},
"lmstudio": {
ID: "lmstudio",
DisplayName: "LM Studio",
Domain: "lmstudio.ai",
DefaultAPIBase: "http://localhost:1234/v1",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Local: true,
Priority: 48,
httpAPI: true,
DefaultAPIBase: "http://localhost:1234/v1",
EmptyAPIKeyAllowed: true,
},
"gpt4free": {
ID: "gpt4free",
DisplayName: "GPT4Free",
Domain: "g4f.dev",
DefaultAPIBase: "http://localhost:1337/v1",
EmptyAPIKeyAllowed: true,
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Local: true,
Priority: 47.5,
Aliases: []string{"g4f"},
httpAPI: true,
DefaultAPIBase: "http://localhost:1337/v1",
EmptyAPIKeyAllowed: true,
Aliases: []string{"g4f"},
},
"elevenlabs": {
ID: "elevenlabs",
DisplayName: "ElevenLabs ASR",
IconSlug: "elevenlabs",
Domain: "elevenlabs.io",
DefaultAPIBase: "https://api.elevenlabs.io",
CreateAllowed: true,
DefaultModelAllowed: false,
Priority: 47,
httpAPI: true,
DefaultAPIBase: "https://api.elevenlabs.io",
},
"venice": {
ID: "venice",
DisplayName: "Venice AI",
IconSlug: "venice",
Domain: "venice.ai",
DefaultAPIBase: "https://api.venice.ai/api/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 45,
httpAPI: true,
DefaultAPIBase: "https://api.venice.ai/api/v1",
},
"nearai": {
ID: "nearai",
DisplayName: "NEAR AI Cloud",
Domain: "near.ai",
DefaultAPIBase: "https://cloud-api.near.ai/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 44.5,
CommonModels: []string{
"zai-org/GLM-5.1-FP8",
"openai/gpt-oss-120b",
"Qwen/Qwen3-30B-A3B-Instruct-2507",
"Qwen/Qwen3.6-35B-A3B-FP8",
},
Aliases: []string{"near-ai", "near-ai-cloud"},
httpAPI: true,
DefaultAPIBase: "https://cloud-api.near.ai/v1",
Aliases: []string{"near-ai", "near-ai-cloud"},
},
"shengsuanyun": {
ID: "shengsuanyun",
DisplayName: "ShengsuanYun",
Domain: "shengsuanyun.com",
DefaultAPIBase: "https://router.shengsuanyun.com/api/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 44,
httpAPI: true,
DefaultAPIBase: "https://router.shengsuanyun.com/api/v1",
},
"siliconflow": {
ID: "siliconflow",
DisplayName: "SiliconFlow",
Domain: "siliconflow.cn",
DefaultAPIBase: "https://api.siliconflow.cn/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 43.5,
httpAPI: true,
DefaultAPIBase: "https://api.siliconflow.cn/v1",
},
"vivgrid": {
ID: "vivgrid",
DisplayName: "Vivgrid",
Domain: "vivgrid.com",
DefaultAPIBase: "https://api.vivgrid.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 43,
httpAPI: true,
DefaultAPIBase: "https://api.vivgrid.com/v1",
},
"minimax": {
ID: "minimax",
DisplayName: "MiniMax",
Domain: "minimaxi.com",
DefaultAPIBase: "https://api.minimaxi.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 42,
httpAPI: true,
DefaultAPIBase: "https://api.minimaxi.com/v1",
},
"longcat": {
ID: "longcat",
DisplayName: "LongCat",
Domain: "longcat.chat",
DefaultAPIBase: "https://api.longcat.chat/openai",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 41,
httpAPI: true,
DefaultAPIBase: "https://api.longcat.chat/openai",
},
"modelscope": {
ID: "modelscope",
DisplayName: "ModelScope",
Domain: "modelscope.cn",
DefaultAPIBase: "https://api-inference.modelscope.cn/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 40,
httpAPI: true,
DefaultAPIBase: "https://api-inference.modelscope.cn/v1",
},
"mimo": {
ID: "mimo",
DisplayName: "Xiaomi MiMo",
IconSlug: "xiaomi",
Domain: "xiaomi.com",
DefaultAPIBase: "https://api.xiaomimimo.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 39,
CommonModels: []string{"mimo-v2.5", "mimo-v2.5-pro"},
httpAPI: true,
DefaultAPIBase: "https://api.xiaomimimo.com/v1",
},
"avian": {
ID: "avian",
DisplayName: "Avian",
Domain: "avian.io",
DefaultAPIBase: "https://api.avian.io/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 38,
httpAPI: true,
DefaultAPIBase: "https://api.avian.io/v1",
},
"zai": {
ID: "zai",
DisplayName: "Z.ai",
Domain: "z.ai",
DefaultAPIBase: "https://api.z.ai/api/coding/paas/v4",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 37,
CommonModels: []string{"glm-5", "glm-4.7", "glm-4.5-air", "glm-4-flash-250414"},
Aliases: []string{"z.ai", "z-ai"},
httpAPI: true,
DefaultAPIBase: "https://api.z.ai/api/coding/paas/v4",
Aliases: []string{"z.ai", "z-ai"},
},
"alibaba-coding": {
ID: "alibaba-coding",
DisplayName: "Alibaba Coding Plan",
IconSlug: "alibabacloud",
Domain: "alibabacloud.com",
DefaultAPIBase: "https://coding-intl.dashscope.aliyuncs.com/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
Priority: 36.5,
CommonModels: []string{"qwen3.6-plus", "kimi-k2.5", "glm-5", "MiniMax-M2.5"},
Aliases: []string{"coding-plan", "qwen-coding"},
httpAPI: true,
DefaultAPIBase: "https://coding-intl.dashscope.aliyuncs.com/v1",
Aliases: []string{"coding-plan", "qwen-coding"},
},
"alibaba-coding-anthropic": {
ID: "alibaba-coding-anthropic",
DisplayName: "Alibaba Coding Plan (Anthropic)",
IconSlug: "alibabacloud",
Domain: "alibabacloud.com",
DefaultAPIBase: "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic",
CreateAllowed: true,
DefaultModelAllowed: true,
Priority: 36.25,
CommonModels: []string{"qwen3.6-plus", "kimi-k2.5", "glm-5", "MiniMax-M2.5"},
Aliases: []string{"coding-plan-anthropic"},
httpAPI: true,
DefaultAPIBase: "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic",
Aliases: []string{"coding-plan-anthropic"},
},
"novita": {
ID: "novita",
DisplayName: "Novita AI",
Domain: "novita.ai",
DefaultAPIBase: "https://api.novita.ai/openai",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 36,
httpAPI: true,
DefaultAPIBase: "https://api.novita.ai/openai",
},
"litellm": {
ID: "litellm",
DisplayName: "LiteLLM",
Domain: "litellm.ai",
DefaultAPIBase: "http://localhost:4000/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
SupportsFetch: true,
Priority: 35,
httpAPI: true,
DefaultAPIBase: "http://localhost:4000/v1",
},
"qwen-us": {
ID: "qwen-us",
DisplayName: "Qwen US",
IconSlug: "alibabacloud",
Domain: "alibabacloud.com",
DefaultAPIBase: "https://dashscope-us.aliyuncs.com/compatible-mode/v1",
CreateAllowed: true,
DefaultModelAllowed: true,
Priority: 34,
CommonModels: []string{"qwen3.6-max-preview", "qwen3.6-plus", "qwen3.6-flash", "qwen3-coder-next"},
Aliases: []string{"dashscope-us"},
httpAPI: true,
DefaultAPIBase: "https://dashscope-us.aliyuncs.com/compatible-mode/v1",
Aliases: []string{"dashscope-us"},
},
}
@@ -586,12 +163,12 @@ var normalizedModelProviderAliasesByName = buildModelProviderAliasMap()
func buildModelProviderAliasMap() map[string]string {
totalAliases := 0
for _, option := range modelProviderOptionsByName {
for _, option := range providerMetadataByName {
totalAliases += len(option.Aliases)
}
aliases := make(map[string]string, len(modelProviderOptionsByName)+totalAliases)
for provider, option := range modelProviderOptionsByName {
aliases := make(map[string]string, len(providerMetadataByName)+totalAliases)
for provider, option := range providerMetadataByName {
aliases[provider] = provider
for _, alias := range option.Aliases {
normalized := strings.ToLower(strings.TrimSpace(alias))
@@ -604,11 +181,11 @@ func buildModelProviderAliasMap() map[string]string {
return aliases
}
func modelProviderOptionForName(provider string) (ModelProviderOption, bool) {
func providerMetadataForName(provider string) (providerMetadata, bool) {
normalized := NormalizeProvider(provider)
if normalized == "" {
return ModelProviderOption{}, false
return providerMetadata{}, false
}
option, ok := modelProviderOptionsByName[normalized]
option, ok := providerMetadataByName[normalized]
return option, ok
}
-108
View File
@@ -1,108 +0,0 @@
#!/bin/bash
# Build macOS .app bundle for PicoClaw Launcher
set -e
EXECUTABLE=$1
if [ -z "$EXECUTABLE" ]; then
echo "Usage: $0 <executable>"
exit 1
fi
LAUNCHER_EXECUTABLE="picoclaw-launcher-${EXECUTABLE}"
EXECUTABLE="picoclaw-${EXECUTABLE}"
echo "executable: $EXECUTABLE"
APP_NAME="PicoClaw Launcher"
APP_PATH="./build/${APP_NAME}.app"
APP_CONTENTS="${APP_PATH}/Contents"
APP_MACOS="${APP_CONTENTS}/MacOS"
APP_RESOURCES="${APP_CONTENTS}/Resources"
APP_EXECUTABLE="picoclaw-launcher"
ICON_SOURCE="./scripts/icon.icns"
# Clean up existing .app
if [ -d "$APP_PATH" ]; then
echo "Removing existing ${APP_PATH}"
rm -rf "$APP_PATH"
fi
# Create directory structure
echo "Creating .app bundle structure..."
mkdir -p "$APP_MACOS"
mkdir -p "$APP_RESOURCES"
# Copy executable
echo "Copying executable..."
if [ -f "./build/${LAUNCHER_EXECUTABLE}" ]; then
cp "./build/${LAUNCHER_EXECUTABLE}" "${APP_MACOS}/${APP_EXECUTABLE}"
else
echo "Error: ./build/${LAUNCHER_EXECUTABLE} not found. Please build the web backend first."
echo "Run: make build-launcher"
exit 1
fi
if [ -f "./build/${EXECUTABLE}" ]; then
cp "./build/${EXECUTABLE}" "${APP_MACOS}/picoclaw"
else
echo "Error: ./build/${EXECUTABLE} not found. Please build the main file first."
echo "Run: make build"
exit 1
fi
chmod +x "${APP_MACOS}/"*
# Create Info.plist
echo "Creating Info.plist..."
cat > "${APP_CONTENTS}/Info.plist" << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>picoclaw-launcher</string>
<key>CFBundleIdentifier</key>
<string>com.picoclaw.launcher</string>
<key>CFBundleName</key>
<string>PicoClaw Launcher</string>
<key>CFBundleDisplayName</key>
<string>PicoClaw Launcher</string>
<key>CFBundleIconFile</key>
<string>icon.icns</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
<key>LSUIElement</key>
<true/>
<key>LSMinimumSystemVersion</key>
<string>10.11</string>
</dict>
</plist>
EOF
#sips -z 128 128 "$ICON_SOURCE" --out "${ICONSET_PATH}/icon_128x128.png" > /dev/null 2>&1
#
## Create icns file
#iconutil -c icns "$ICONSET_PATH" -o "$ICON_OUTPUT" 2>/dev/null || {
# echo "Warning: iconutil failed"
#}
cp $ICON_SOURCE "${APP_RESOURCES}/icon.icns"
echo ""
echo "=========================================="
echo "Successfully created: ${APP_PATH}"
echo "=========================================="
echo ""
echo "To launch PicoClaw:"
echo " 1. Double-click ${APP_NAME}.app in Finder"
echo " 2. Or use: open ${APP_PATH}"
echo ""
echo "Note: The app will run in the menu bar (systray) without a terminal window."
echo ""
BIN
View File
Binary file not shown.
-65
View File
@@ -1,65 +0,0 @@
; Script generated by the Inno Setup Script Wizard.
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
#define MyAppName "PicoClaw Launcher"
#define MyAppVersion "1.0"
#define MyAppPublisher "PicoClaw"
#define MyAppURL "https://github.com/sipeed/picoclaw"
#define MyAppExeName "picoclaw-launcher.exe"
[Setup]
; NOTE: The value of AppId uniquely identifies this application. Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppId={{C8A1B4E7-D5F9-4C2A-8A6E-5F4D3C2A1B0E}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={autopf}\PicoClaw
DefaultGroupName={#MyAppName}
; "ArchitecturesAllowed=x64compatible" specifies that Setup cannot run
; on anything but x64 and Windows 11 on Arm.
ArchitecturesAllowed=x64compatible
; "ArchitecturesInstallIn64BitMode=x64compatible" requests that the
; install be done in "64-bit mode" on x64 or Windows 11 on Arm,
; meaning it should use the native 64-bit Program Files directory and
; the 64-bit view of the registry.
ArchitecturesInstallIn64BitMode=x64compatible
DisableProgramGroupPage=yes
; Remove the following line to run in administrative install mode (install for all users.)
PrivilegesRequired=lowest
OutputDir=build
OutputBaseFilename=PicoClawSetup
Compression=lzma
SolidCompression=yes
WizardStyle=modern
; SourceDir=windows
SetupIconFile=icon.ico
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
[Dirs]
[Files]
Source: "..\web\build\picoclaw-launcher.exe"; DestDir: "{app}"; DestName: "{#MyAppExeName}"; Flags: ignoreversion
Source: "..\build\picoclaw.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "..\web\backend\icon.ico"; DestDir: "{app}"; Flags: ignoreversion
; NOTE: Don't use "Flags: ignoreversion" on any shared system files
[UninstallDelete]
[Icons]
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; WorkingDir: "{app}"; IconFilename: "{app}\icon.ico"
Name: "{group}\Uninstall {#MyAppName}"; Filename: "{uninstallexe}"
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; WorkingDir: "{app}"; Tasks: desktopicon; IconFilename: "{app}\icon.ico"
[Run]
Filename:"{app}\{#MyAppExeName}"; WorkingDir: "{app}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
-209
View File
@@ -1,209 +0,0 @@
.PHONY: dev dev-frontend dev-backend build build-frontend build-dev-picoclaw test lint clean \
build-android-arm64 build-android-bundle
# Go variables
GO?=go
WEB_GO?=$(GO)
CGO_ENABLED?=0
GO_BUILD_TAGS?=goolm,stdjson
GOFLAGS?=-v -tags $(GO_BUILD_TAGS)
GOCACHE?=$(abspath ../.cache/go-build)
GOMODCACHE?=$(abspath ../.cache/go-mod)
GOTOOLCHAIN?=local
export CGO_ENABLED
export GOCACHE
export GOMODCACHE
export GOTOOLCHAIN
# Build variables
BUILD_DIR=build
EXT=
OUTPUT?=$(BUILD_DIR)/picoclaw-launcher$(EXT)
OUTPUT_ANDROID_ARM64?=$(BUILD_DIR)/picoclaw-launcher-android-arm64$(EXT)
FRONTEND_DIR=frontend
FRONTEND_INSTALL_STAMP=$(FRONTEND_DIR)/node_modules/.picoclaw-install-stamp
BACKEND_DIR=backend
BACKEND_DIST=$(BACKEND_DIR)/dist
PICOCLAW_BINARY_NAME=picoclaw
PICOCLAW_BINARY?=$(abspath ../build/$(PICOCLAW_BINARY_NAME))
LAUNCHER_GUI_LDFLAG=
ifeq ($(OS),Windows_NT)
POWERSHELL=powershell -NoProfile -Command
WINDOWS_GOARCH_RAW:=$(strip $(shell go env GOARCH 2>NUL))
endif
# Version
ifeq ($(OS),Windows_NT)
VERSION_RAW:=$(strip $(shell git describe --tags --always --dirty 2>NUL))
GIT_COMMIT_RAW:=$(strip $(shell git rev-parse --short=8 HEAD 2>NUL))
BUILD_TIME_RAW:=$(strip $(shell powershell -NoProfile -Command "Get-Date -Format 'yyyy-MM-ddTHH:mm:ssK'"))
GO_VERSION_RAW:=$(strip $(shell go env GOVERSION 2>NUL))
else
VERSION_RAW:=$(strip $(shell git describe --tags --always --dirty 2>/dev/null))
GIT_COMMIT_RAW:=$(strip $(shell git rev-parse --short=8 HEAD 2>/dev/null))
BUILD_TIME_RAW:=$(strip $(shell date +%FT%T%z))
GO_VERSION_RAW:=$(strip $(shell go env GOVERSION 2>/dev/null))
endif
VERSION?=$(if $(VERSION_RAW),$(VERSION_RAW),dev)
GIT_COMMIT=$(if $(GIT_COMMIT_RAW),$(GIT_COMMIT_RAW),dev)
BUILD_TIME=$(if $(BUILD_TIME_RAW),$(BUILD_TIME_RAW),dev)
GO_VERSION=$(if $(GO_VERSION_RAW),$(GO_VERSION_RAW),unknown)
CONFIG_PKG=github.com/sipeed/picoclaw/pkg/config
LDFLAGS=-X $(CONFIG_PKG).Version=$(VERSION) -X $(CONFIG_PKG).GitCommit=$(GIT_COMMIT) -X $(CONFIG_PKG).BuildTime=$(BUILD_TIME) -X $(CONFIG_PKG).GoVersion=$(GO_VERSION) -s -w
# OS detection
ifeq ($(OS),Windows_NT)
UNAME_S=Windows
ifeq ($(WINDOWS_GOARCH_RAW),amd64)
UNAME_M=x86_64
else ifeq ($(WINDOWS_GOARCH_RAW),arm64)
UNAME_M=arm64
else ifeq ($(WINDOWS_GOARCH_RAW),386)
UNAME_M=x86
else
UNAME_M=$(if $(WINDOWS_GOARCH_RAW),$(WINDOWS_GOARCH_RAW),x86_64)
endif
else
UNAME_S:=$(shell uname -s)
UNAME_M:=$(shell uname -m)
endif
# Platform-specific settings
ifeq ($(UNAME_S),Linux)
PLATFORM=linux
ifeq ($(UNAME_M),x86_64)
ARCH=amd64
else ifeq ($(UNAME_M),aarch64)
ARCH=arm64
else ifeq ($(UNAME_M),armv81)
ARCH=arm64
else ifeq ($(UNAME_M),loongarch64)
ARCH=loong64
else ifeq ($(UNAME_M),riscv64)
ARCH=riscv64
else ifeq ($(UNAME_M),mipsel)
ARCH=mipsle
else
ARCH=$(UNAME_M)
endif
else ifeq ($(UNAME_S),Darwin)
PLATFORM=darwin
WEB_GO=CGO_ENABLED=1 go
ifeq ($(UNAME_M),x86_64)
ARCH=amd64
else ifeq ($(UNAME_M),arm64)
ARCH=arm64
else
ARCH=$(UNAME_M)
endif
else ifeq ($(UNAME_S),Windows)
PLATFORM=windows
ifeq ($(UNAME_M),x86_64)
ARCH=amd64
else ifeq ($(UNAME_M),arm64)
ARCH=arm64
else
ARCH=$(UNAME_M)
endif
EXT=.exe
PICOCLAW_BINARY_NAME=picoclaw.exe
LAUNCHER_GUI_LDFLAG=-H=windowsgui
else
PLATFORM=$(UNAME_S)
ARCH=$(UNAME_M)
endif
LAUNCHER_LDFLAGS=$(strip $(LAUNCHER_GUI_LDFLAG) $(LDFLAGS))
# Run both frontend and backend dev servers
dev: build-dev-picoclaw
@if [ ! -f "$(BACKEND_DIST)/index.html" ]; then \
echo "Embedded frontend not found, building..."; \
$(MAKE) build-frontend; \
fi
@echo "Starting backend and frontend dev servers..."
@$(MAKE) dev-backend BACKEND_ARGS='-no-browser' & $(MAKE) dev-frontend
# Start frontend dev server (Vite, with proxy to backend)
dev-frontend:
cd $(FRONTEND_DIR) && pnpm dev
# Start backend dev server
dev-backend:
cd $(BACKEND_DIR) && PICOCLAW_BINARY="$(PICOCLAW_BINARY)" ${WEB_GO} run -ldflags "$(LAUNCHER_LDFLAGS)" . $(BACKEND_ARGS)
# Build frontend and embed into Go binary
build: build-frontend
ifeq ($(OS),Windows_NT)
@$(POWERSHELL) "New-Item -ItemType Directory -Force -Path (Split-Path -Parent '$(OUTPUT)') | Out-Null"
else
@mkdir -p "$$(dirname "$(OUTPUT)")"
endif
${WEB_GO} build $(GOFLAGS) -ldflags "$(LAUNCHER_LDFLAGS)" -o "$(OUTPUT)" ./$(BACKEND_DIR)/
# Build launcher for Android ARM64 (frontend must already be built)
build-android-arm64: build-frontend
ifeq ($(OS),Windows_NT)
@$(POWERSHELL) "New-Item -ItemType Directory -Force -Path '$(BUILD_DIR)' | Out-Null"
else
@mkdir -p $(BUILD_DIR)
endif
GOOS=android GOARCH=arm64 $(GO) build -tags stdjson -ldflags "$(LDFLAGS)" -o "$(OUTPUT_ANDROID_ARM64)" ./$(BACKEND_DIR)/
# Build launcher for all Android architectures
build-android-bundle: build-frontend
ifeq ($(OS),Windows_NT)
@$(POWERSHELL) "New-Item -ItemType Directory -Force -Path '$(BUILD_DIR)' | Out-Null"
else
@mkdir -p $(BUILD_DIR)
endif
GOOS=android GOARCH=arm64 $(GO) build -tags stdjson -ldflags "$(LDFLAGS)" -o "$(BUILD_DIR)/picoclaw-launcher-android-arm64" ./$(BACKEND_DIR)/
@echo "All Android launcher builds complete"
build-frontend:
ifeq ($(OS),Windows_NT)
@$(POWERSHELL) "if ((-not (Test-Path -LiteralPath '$(FRONTEND_DIR)/node_modules')) -or (-not (Test-Path -LiteralPath '$(FRONTEND_DIR)/node_modules/.bin/tsc')) -or (-not (Test-Path -LiteralPath '$(FRONTEND_INSTALL_STAMP)')) -or ((Get-Content -LiteralPath '$(FRONTEND_INSTALL_STAMP)' -Raw).Trim() -ne (((Get-FileHash -LiteralPath '$(FRONTEND_DIR)/package.json' -Algorithm SHA256).Hash + ':' + (Get-FileHash -LiteralPath '$(FRONTEND_DIR)/pnpm-lock.yaml' -Algorithm SHA256).Hash)))) { Write-Host 'Installing frontend dependencies...'; Push-Location '$(FRONTEND_DIR)'; try { pnpm install --frozen-lockfile } finally { Pop-Location }; Set-Content -LiteralPath '$(FRONTEND_INSTALL_STAMP)' -Value (((Get-FileHash -LiteralPath '$(FRONTEND_DIR)/package.json' -Algorithm SHA256).Hash + ':' + (Get-FileHash -LiteralPath '$(FRONTEND_DIR)/pnpm-lock.yaml' -Algorithm SHA256).Hash)) -NoNewline }"
else
@expected_stamp="$$(cat $(FRONTEND_DIR)/package.json $(FRONTEND_DIR)/pnpm-lock.yaml | cksum | awk '{print $$1 ":" $$2}')"; \
if [ ! -d $(FRONTEND_DIR)/node_modules ] || \
[ ! -x $(FRONTEND_DIR)/node_modules/.bin/tsc ] || \
[ ! -f $(FRONTEND_INSTALL_STAMP) ] || \
[ "$$(cat $(FRONTEND_INSTALL_STAMP) 2>/dev/null)" != "$$expected_stamp" ]; then \
echo "Installing frontend dependencies..."; \
(cd $(FRONTEND_DIR) && CI=true pnpm install --frozen-lockfile) && \
printf '%s\n' "$$expected_stamp" > $(FRONTEND_INSTALL_STAMP); \
fi
endif
@echo "Building frontend..."
@cd $(FRONTEND_DIR) && pnpm build:backend
build-dev-picoclaw:
@echo "Building picoclaw for launcher development..."
ifeq ($(OS),Windows_NT)
@$(POWERSHELL) "New-Item -ItemType Directory -Force -Path (Split-Path -Parent '$(PICOCLAW_BINARY)') | Out-Null"
else
@mkdir -p "$$(dirname "$(PICOCLAW_BINARY)")"
endif
@$(GO) build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o "$(PICOCLAW_BINARY)" ../cmd/picoclaw
# Run all tests
test:
cd $(BACKEND_DIR) && ${WEB_GO} test ./...
cd $(FRONTEND_DIR) && pnpm lint
# Lint and format
lint:
cd $(BACKEND_DIR) && ${WEB_GO} vet ./...
cd $(FRONTEND_DIR) && pnpm check
# Clean build artifacts
clean:
ifeq ($(OS),Windows_NT)
@$(POWERSHELL) "$$paths=@('$(FRONTEND_DIR)/dist','$(BACKEND_DIST)','$(BUILD_DIR)'); foreach($$p in $$paths){ if (Test-Path -LiteralPath $$p) { Remove-Item -LiteralPath $$p -Recurse -Force } }"
@node $(FRONTEND_DIR)/scripts/ensure-backend-gitkeep.cjs
else
rm -rf $(FRONTEND_DIR)/dist $(BACKEND_DIST) $(BUILD_DIR)
node $(FRONTEND_DIR)/scripts/ensure-backend-gitkeep.cjs
endif
-372
View File
@@ -1,372 +0,0 @@
# PicoClaw Web
`web/` contains the standalone WebUI launcher for PicoClaw.
It is not just a frontend: it is a small launcher service that bundles a React dashboard, exposes a backend API, manages launcher authentication, and starts or attaches to the `picoclaw gateway` process.
![PicoClaw Launcher](./picoclaw-launcher.png)
## What This Directory Provides
- A browser-based chat UI backed by the Pico channel WebSocket proxy.
- A dashboard for models, credentials, channels, agent tools, skills, logs, and runtime settings.
- A launcher process that can auto-open the browser, show a system tray menu, and persist launcher-specific settings.
- A controlled way to start, stop, restart, and inspect the `picoclaw gateway` subprocess.
- A single-binary deployment target where the frontend is embedded into the Go backend.
## Architecture
This directory is a small monorepo:
- `backend/`
- Go HTTP server and launcher runtime.
- Serves REST APIs, authentication endpoints, channel helper flows, and the Pico WebSocket reverse proxy.
- Embeds compiled frontend assets from `backend/dist`.
- `frontend/`
- Vite + React 19 + TanStack Router SPA.
- Provides the launcher dashboard and chat UI.
At runtime the launcher and the main PicoClaw engine are separate processes:
1. The launcher starts the web backend on port `18800` by default.
2. The launcher serves the dashboard and handles dashboard authentication.
3. When allowed, it starts or attaches to `picoclaw gateway -E`.
4. The frontend talks only to the launcher backend.
5. The launcher proxies chat traffic to the gateway through `/pico/ws`.
## Dashboard Capabilities
The current frontend exposes these major pages and flows:
- `/`
- Chat UI with session history, default model selection, and Pico channel messaging.
- `/models`
- Add, edit, delete, and set the default model.
- Supports API-key models, OAuth-backed models, and local/CLI-backed models.
- `/credentials`
- Manage provider credentials.
- Current built-in flows: OpenAI, Anthropic, and Google Antigravity.
- `/channels/*`
- Configure supported channels from a shared catalog.
- Current catalog: `weixin`, `telegram`, `discord`, `slack`, `feishu`, `dingtalk`, `line`, `qq`, `onebot`, `wecom`, `whatsapp`, `whatsapp_native`, `pico`, `maixcam`, `matrix`, `irc`, `mqtt`.
- Includes QR-based binding helpers for WeChat and WeCom.
- `/agent/skills`
- Browse built-in, global, and workspace skills.
- Import Markdown skills into the workspace and delete workspace-owned skills.
- `/agent/tools`
- View tool availability and enable or disable tool switches through config-backed APIs.
- `/config`
- Edit agent defaults, self-evolution, exec controls, cron controls, heartbeat, device monitoring, launcher networking, and launch-at-login settings.
- `/logs`
- View the in-memory gateway log buffer and clear it.
The UI currently supports English and Simplified Chinese, plus light and dark themes.
## Runtime Behavior
### Config Resolution
The launcher uses the same PicoClaw config file as the main binary.
- Default app config path: `~/.picoclaw/config.json`
- Override with environment variable: `PICOCLAW_CONFIG`
- Override with a positional CLI argument: `picoclaw-launcher /path/to/config.json`
Launcher-only settings are stored beside that app config:
- File name: `launcher-config.json`
- Default location: `~/.picoclaw/launcher-config.json`
That file currently stores:
- `port`
- `public`
- `allowed_cidrs`
- `allow_localhost_bypass`
- `trusted_proxy_cidrs`
If `-port` or `-public` are passed explicitly, the CLI flag wins for that run.
If they are omitted, stored launcher settings are used.
### First-Run Onboarding
If the target config file does not exist, the launcher tries to bootstrap it automatically by running:
```bash
picoclaw onboard
```
The launcher looks for the main PicoClaw binary in this order:
1. `PICOCLAW_BINARY`
2. A `picoclaw` binary in the same directory as the launcher
3. `picoclaw` from `PATH`
If onboarding or gateway startup cannot find the main binary, set `PICOCLAW_BINARY` explicitly.
### Gateway Management
The launcher manages `picoclaw gateway -E`.
On startup it tries to auto-start or attach to the gateway, but only when startup preconditions pass. In the current code, the main checks are:
- a default model is configured
- the default model entry is valid
- the default model has usable credentials
- local/runtime-probed models are reachable
When a gateway process is started by the launcher, the launcher:
- captures stdout and stderr into an in-memory ring buffer
- tracks transient states such as `starting`, `restarting`, and `stopping`
- marks restart-required when the default model or enabled tool set changed since boot
- ensures the Pico channel is configured before startup
### Launcher Authentication
The dashboard is protected by password login.
- First run uses `/launcher-setup` to create the dashboard password.
- Manual login uses `/launcher-login`.
- Successful login sets an HttpOnly session cookie.
- Existing sessions are invalidated when the launcher process restarts; otherwise the browser cookie expires after 31 days.
- When the launcher auto-opens a local browser after startup, it uses a one-shot loopback-only bootstrap endpoint to set the session cookie automatically.
- On supported platforms, the password is stored as a bcrypt hash in `launcher-auth.db`.
- On platforms where the SQLite password store is unavailable, the launcher stores the bcrypt hash in `launcher-config.json`.
- Legacy `launcher_token` values are migrated once into password login and are removed from saved launcher config.
- `PICOCLAW_LAUNCHER_TOKEN` is deprecated and ignored; after upgrading from env-token auth, open `/launcher-setup` to create a password.
- URL token login and `Authorization: Bearer` dashboard auth are not supported.
### Network Exposure
By default the launcher listens on:
```text
127.0.0.1:18800
```
With `-public` or `public: true`, it listens on all interfaces:
```text
0.0.0.0:18800
```
When public access is enabled:
- the launcher still protects the dashboard with password login
- optional `allowed_cidrs` can restrict which client IP ranges may connect
- `allow_localhost_bypass` defaults to `true`; set it to `false` when same-host proxies or tunnels should not bypass `allowed_cidrs`
- optional `trusted_proxy_cidrs` can trust specific reverse proxies to supply the original client IP through headers such as `X-Forwarded-For`
- trusted proxy deployments should overwrite or sanitize forwarding headers such as `X-Forwarded-For` and `X-Real-IP` instead of passing through user-supplied values
- the gateway host is overridden so remote clients can still use the launcher-managed proxy paths
## Build And Run
### Prerequisites
- Go `1.25+`
- Node.js 20.19+ or 22.13+
- `pnpm`
On macOS, the `web` Makefile enables `CGO_ENABLED=1` so tray-enabled launcher builds work as expected.
On Darwin or FreeBSD without cgo, the launcher falls back to headless mode without a tray.
If you want to prepare the frontend workspace manually, you can still install dependencies yourself:
```bash
cd frontend
pnpm install
```
### Recommended Development Workflow
From the `web/` directory:
```bash
make dev
```
This does three things:
1. Builds `../build/picoclaw` for launcher development.
2. Starts the Go backend with `PICOCLAW_BINARY` pointing at that binary.
3. Starts the Vite frontend dev server.
Use this when you want the full launcher flow during development.
### Run Frontend And Backend Separately
```bash
make dev-frontend
make dev-backend
```
Notes:
- `dev-frontend` runs the Vite server.
- `dev-backend` runs the Go backend only.
- The Vite dev server proxies `/api` to `http://localhost:18800`.
- Chat WebSocket URLs are generated by the backend, so the frontend does not hardcode gateway addresses.
- Running `dev-backend` alone is mainly useful for backend work or when `backend/dist` already contains a built frontend.
### Build The Standalone Launcher Binary
From `web/`:
```bash
make build
```
This:
1. Installs frontend dependencies when needed.
2. Builds the frontend into `backend/dist`.
3. Embeds those assets into the Go backend.
4. Produces `build/picoclaw-launcher`.
Override the output path if needed:
```bash
make build OUTPUT=/tmp/picoclaw-launcher
```
From the repository root you can also use:
```bash
make build-launcher
```
That writes the platform-specific launcher to:
```text
build/picoclaw-launcher-<platform>-<arch>
```
and refreshes the `build/picoclaw-launcher` symlink.
### Frontend-Only Builds
For frontend work there are two useful package scripts:
```bash
cd frontend
pnpm build
pnpm build:backend
```
- `pnpm build` writes a normal Vite build to `frontend/dist`
- `pnpm build:backend` writes the embeddable build to `../backend/dist`
### Run The Built Launcher
Examples:
```bash
./build/picoclaw-launcher
./build/picoclaw-launcher -console
./build/picoclaw-launcher -public
./build/picoclaw-launcher -port 19999 /path/to/config.json
```
Current launcher flags:
- `-port`
- `-public`
- `-no-browser`
- `-lang`
- `-console`
## Make Targets
From `web/`:
```bash
make dev
make dev-frontend
make dev-backend
make build
make build-frontend
make test
make lint
make clean
```
What they do today:
- `make build-frontend`
- Runs `pnpm install --frozen-lockfile` when dependencies are missing or stale.
- Builds the embeddable frontend into `backend/dist`.
- `make test`
- Runs backend Go tests.
- Runs frontend `pnpm lint`.
- `make lint`
- Runs backend `go vet`.
- Runs frontend `pnpm check`.
- `pnpm check` currently formats files with Prettier and fixes lint issues with ESLint, so this target can modify your working tree.
- `make clean`
- Removes `frontend/dist`, `backend/dist`, and `build/`, then recreates `backend/dist/.gitkeep`.
## Directory Layout
```text
web/
├── backend/
│ ├── api/ # REST API handlers and launcher runtime endpoints
│ ├── launcherconfig/ # launcher-config.json load/save/validation
│ ├── middleware/ # auth, content type, logging, CIDR allowlist
│ ├── model/ # Go data structures and logic wrappers
│ ├── utils/ # runtime helpers, onboarding, browser launch
│ ├── winres/ # Windows application resources
│ └── dist/ # embedded frontend build output
├── frontend/
│ ├── src/api/ # browser API clients
│ ├── src/components/ # UI pages and shared components
│ ├── src/features/ # feature-specific state, controllers, and protocol helpers
│ ├── src/hooks/ # shared React hooks
│ ├── src/i18n/ # internationalization language packs
│ ├── src/lib/ # generic library utilities
│ ├── src/routes/ # TanStack file routes
│ ├── src/store/ # global state management
│ └── vite.config.ts # dev server and build config
├── Makefile
└── README.md
```
## Troubleshooting
### You have to sign in again after the launcher restarts
Existing dashboard sessions do not survive launcher restarts.
That is expected: each launcher process generates a new session value, so old cookies become invalid.
Sign in again with the dashboard password on `/launcher-login`.
### "Start Gateway" stays disabled
The launcher only allows gateway startup when the configured default model is usable.
Check these in the dashboard:
- a default model is selected
- the model has credentials or OAuth state
- local models such as Ollama or vLLM are reachable
### The launcher cannot find `picoclaw`
Set the main binary explicitly:
```bash
export PICOCLAW_BINARY=/absolute/path/to/picoclaw
```
This affects onboarding and gateway subprocess startup.
### The backend starts but the UI is blank in development
Use `make dev` for the normal workflow.
If you run only `make dev-backend`, either run `make dev-frontend` alongside it or build the embedded frontend first with `make build-frontend`.
## Related Docs
- Main project overview: [`../README.md`](../README.md)
- Configuration guide: [`../docs/guides/configuration.md`](../docs/guides/configuration.md)
- Providers: [`../docs/guides/providers.md`](../docs/guides/providers.md)
- Troubleshooting: [`../docs/operations/troubleshooting.md`](../docs/operations/troubleshooting.md)
- Official docs site: [docs.picoclaw.io](https://docs.picoclaw.io)
-19
View File
@@ -1,19 +0,0 @@
# Go build output
*.exe
*.dll
*.so
*.dylib
*.test
*.out
picoclaw-web
# Frontend build artifacts (embedded by Go)
dist/*
!dist/.gitkeep
# OS
.DS_Store
# Editors
.vscode/
.idea/
-331
View File
@@ -1,331 +0,0 @@
package api
import (
"context"
"crypto/subtle"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/sipeed/picoclaw/web/backend/middleware"
)
// PasswordStore is the interface for dashboard password persistence.
// Implemented by dashboardauth.Store and launcherconfig.PasswordStore.
type PasswordStore interface {
IsInitialized(ctx context.Context) (bool, error)
SetPassword(ctx context.Context, plain string) error
VerifyPassword(ctx context.Context, plain string) (bool, error)
}
// LauncherAuthRouteOpts configures dashboard auth handlers.
type LauncherAuthRouteOpts struct {
SessionCookie string
SecureCookie func(*http.Request) bool
// PasswordStore enables password login. It must be non-nil for auth to work.
PasswordStore PasswordStore
// StoreError holds the error returned when opening the password store. When
// non-nil and PasswordStore is nil, auth endpoints fail closed with a
// recovery message.
StoreError error
}
type launcherAuthLoginBody struct {
Password string `json:"password"`
}
type launcherAuthSetupBody struct {
Password string `json:"password"`
Confirm string `json:"confirm"`
}
type launcherAuthStatusResponse struct {
Authenticated bool `json:"authenticated"`
Initialized bool `json:"initialized"`
}
// RegisterLauncherAuthRoutes registers /api/auth/login|logout|status|setup.
func RegisterLauncherAuthRoutes(mux *http.ServeMux, opts LauncherAuthRouteOpts) {
secure := opts.SecureCookie
if secure == nil {
secure = middleware.DefaultLauncherDashboardSecureCookie
}
h := &launcherAuthHandlers{
sessionCookie: opts.SessionCookie,
secureCookie: secure,
store: opts.PasswordStore,
storeErr: opts.StoreError,
loginLimit: newLoginRateLimiter(),
}
mux.HandleFunc("POST /api/auth/login", h.handleLogin)
mux.HandleFunc("POST /api/auth/logout", h.handleLogout)
mux.HandleFunc("GET /api/auth/status", h.handleStatus)
mux.HandleFunc("POST /api/auth/setup", h.handleSetup)
}
type launcherAuthHandlers struct {
sessionCookie string
secureCookie func(*http.Request) bool
store PasswordStore
storeErr error // set when the store failed to open; drives recovery messages
loginLimit *loginRateLimiter
}
// isStoreInitialized safely queries the store.
// Returns (false, err) on store errors — callers must treat this as a 5xx, not as
// "uninitialized", to keep auth fail-closed.
func (h *launcherAuthHandlers) isStoreInitialized(ctx context.Context) (bool, error) {
if h.store == nil {
if h.storeErr != nil {
return false, fmt.Errorf(
"password store unavailable (%w); "+
"to recover, stop the application, reset dashboard password storage, and restart",
h.storeErr)
}
return false, fmt.Errorf("password store not configured")
}
return h.store.IsInitialized(ctx)
}
func launcherSetupCrossSite(r *http.Request) bool {
fetchSite := strings.ToLower(strings.TrimSpace(r.Header.Get("Sec-Fetch-Site")))
if fetchSite == "cross-site" {
return true
}
if origin := strings.TrimSpace(r.Header.Get("Origin")); origin != "" {
return !sameLauncherRequestOrigin(r, origin)
}
if referer := strings.TrimSpace(r.Header.Get("Referer")); referer != "" {
return !sameLauncherRequestOrigin(r, referer)
}
return false
}
func sameLauncherRequestOrigin(r *http.Request, raw string) bool {
if strings.ContainsAny(raw, " \t\r\n") {
return false
}
u, err := url.Parse(raw)
if err != nil || u.Scheme == "" || u.Host == "" {
return false
}
wantScheme := launcherRequestScheme(r)
wantHost := r.Host
if wantHost == "" {
wantHost = r.URL.Host
}
return strings.EqualFold(u.Scheme, wantScheme) && strings.EqualFold(u.Host, wantHost)
}
func launcherRequestScheme(r *http.Request) string {
if proto := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); proto != "" {
if i := strings.IndexByte(proto, ','); i >= 0 {
proto = proto[:i]
}
proto = strings.ToLower(strings.TrimSpace(proto))
if proto == "http" || proto == "https" {
return proto
}
}
if r.TLS != nil {
return "https"
}
if r.URL != nil && r.URL.Scheme != "" {
return r.URL.Scheme
}
return "http"
}
func (h *launcherAuthHandlers) handleLogin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var body launcherAuthLoginBody
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&body); err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"invalid JSON"}`))
return
}
ip := clientIPForLimiter(r)
if !h.loginLimit.allow(ip) {
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{"error":"too many login attempts"}`))
return
}
in := strings.TrimSpace(body.Password)
initialized, initErr := h.isStoreInitialized(r.Context())
if initErr != nil {
w.WriteHeader(http.StatusServiceUnavailable)
writeErrorf(w, "%v", initErr)
return
}
if !initialized {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"error":"password has not been set"}`))
return
}
ok, err := h.store.VerifyPassword(r.Context(), in)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
writeErrorf(w, "password verification failed: %v", err)
return
}
if !ok {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"error":"invalid password"}`))
return
}
middleware.SetLauncherDashboardSessionCookie(w, r, h.sessionCookie, h.secureCookie)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
}
func (h *launcherAuthHandlers) handleLogout(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte(`{"error":"method not allowed"}`))
return
}
ct := strings.ToLower(strings.TrimSpace(r.Header.Get("Content-Type")))
if !strings.HasPrefix(ct, "application/json") {
w.WriteHeader(http.StatusUnsupportedMediaType)
_, _ = w.Write([]byte(`{"error":"Content-Type must be application/json"}`))
return
}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, logoutBodyMaxBytes))
if err := dec.Decode(&struct{}{}); err != nil && err != io.EOF {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"invalid JSON body"}`))
return
}
if err := dec.Decode(&struct{}{}); err != io.EOF {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"invalid JSON body"}`))
return
}
middleware.ClearLauncherDashboardSessionCookie(w, r, h.secureCookie)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
}
func (h *launcherAuthHandlers) handleStatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
authed := false
if c, err := r.Cookie(middleware.LauncherDashboardCookieName); err == nil {
authed = subtle.ConstantTimeCompare([]byte(c.Value), []byte(h.sessionCookie)) == 1
}
initialized, initErr := h.isStoreInitialized(r.Context())
if initErr != nil {
w.WriteHeader(http.StatusServiceUnavailable)
writeErrorf(w, "%v", initErr)
return
}
resp := launcherAuthStatusResponse{
Authenticated: authed,
Initialized: initialized,
}
enc, err := json.Marshal(resp)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
writeErrorf(w, "marshal response failed: %v", err)
return
}
_, _ = w.Write(enc)
}
// handleSetup sets or changes the dashboard password.
//
// Rules:
// - If the store has no password yet, anyone who can reach the setup endpoint
// may initialize the password.
// - If a password is already set, the caller must hold a valid session cookie.
func (h *launcherAuthHandlers) handleSetup(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if launcherSetupCrossSite(r) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"error":"cross-site setup request rejected"}`))
return
}
if h.store == nil {
w.WriteHeader(http.StatusServiceUnavailable)
if h.storeErr != nil {
writeErrorf(w, "password store unavailable: %v", h.storeErr)
} else {
_, _ = w.Write([]byte(`{"error":"password store not configured"}`))
}
return
}
initialized, initErr := h.isStoreInitialized(r.Context())
if initErr != nil {
w.WriteHeader(http.StatusServiceUnavailable)
writeErrorf(w, "%v", initErr)
return
}
// If already initialized, require an active session (change-password flow).
if initialized {
authed := false
if c, err := r.Cookie(middleware.LauncherDashboardCookieName); err == nil {
authed = subtle.ConstantTimeCompare([]byte(c.Value), []byte(h.sessionCookie)) == 1
}
if !authed {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"error":"must be authenticated to change password"}`))
return
}
}
var body launcherAuthSetupBody
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&body); err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"invalid JSON"}`))
return
}
pw := strings.TrimSpace(body.Password)
if pw == "" {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"password must not be empty"}`))
return
}
if pw != strings.TrimSpace(body.Confirm) {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"passwords do not match"}`))
return
}
if len([]rune(pw)) < 8 {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"password must be at least 8 characters"}`))
return
}
if err := h.store.SetPassword(r.Context(), pw); err != nil {
w.WriteHeader(http.StatusInternalServerError)
writeErrorf(w, "failed to save password: %v", err)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
}
// writeErrorf writes a JSON error response with a formatted message.
// json.Marshal is used to safely escape the message string.
func writeErrorf(w http.ResponseWriter, format string, args ...any) {
msg, _ := json.Marshal(fmt.Sprintf(format, args...))
_, _ = w.Write([]byte(`{"error":` + string(msg) + `}`))
}
-63
View File
@@ -1,63 +0,0 @@
package api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestLauncherAuthSetupRejectsCrossSiteFirstRun(t *testing.T) {
store := &fakePasswordStore{}
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: "session-cookie-value",
PasswordStore: store,
})
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPost,
"http://127.0.0.1:18800/api/auth/setup",
strings.NewReader(`{"password":"CrossSitePwn123!","confirm":"CrossSitePwn123!"}`),
)
req.Header.Set("Origin", "https://evil.example")
req.Header.Set("Referer", "https://evil.example/attack")
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("cross-site setup code = %d body=%s", rec.Code, rec.Body.String())
}
if store.initialized || store.password != "" {
t.Fatalf("cross-site setup mutated store: initialized=%v password=%q", store.initialized, store.password)
}
}
func TestLauncherAuthSetupAllowsSameOriginFirstRun(t *testing.T) {
store := &fakePasswordStore{}
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: "session-cookie-value",
PasswordStore: store,
})
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPost,
"http://127.0.0.1:18800/api/auth/setup",
strings.NewReader(`{"password":"LocalSetup123!","confirm":"LocalSetup123!"}`),
)
req.Header.Set("Origin", "http://127.0.0.1:18800")
req.Header.Set("Sec-Fetch-Site", "same-origin")
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("same-origin setup code = %d body=%s", rec.Code, rec.Body.String())
}
if !store.initialized || store.password != "LocalSetup123!" {
t.Fatalf("same-origin setup store: initialized=%v password=%q", store.initialized, store.password)
}
}
-59
View File
@@ -1,59 +0,0 @@
package api
import (
"net"
"net/http"
"strings"
"sync"
"time"
)
const (
loginAttemptsPerIP = 10
loginAttemptWindow = time.Minute
logoutBodyMaxBytes = 4096
)
// loginRateLimiter limits POST /api/auth/login attempts per IP per minute.
type loginRateLimiter struct {
mu sync.Mutex
now func() time.Time
byIP map[string][]time.Time
}
func newLoginRateLimiter() *loginRateLimiter {
return &loginRateLimiter{
now: time.Now,
byIP: make(map[string][]time.Time),
}
}
// allow reserves a slot for this request; false means rate limit exceeded.
func (l *loginRateLimiter) allow(ip string) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := l.now()
cutoff := now.Add(-loginAttemptWindow)
times := l.byIP[ip]
var kept []time.Time
for _, ts := range times {
if ts.After(cutoff) {
kept = append(kept, ts)
}
}
if len(kept) >= loginAttemptsPerIP {
l.byIP[ip] = kept
return false
}
kept = append(kept, now)
l.byIP[ip] = kept
return true
}
func clientIPForLimiter(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return strings.TrimSpace(r.RemoteAddr)
}
return host
}
-364
View File
@@ -1,364 +0,0 @@
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/sipeed/picoclaw/web/backend/middleware"
)
type fakePasswordStore struct {
initialized bool
password string
err error
}
func (s *fakePasswordStore) IsInitialized(context.Context) (bool, error) {
if s.err != nil {
return false, s.err
}
return s.initialized, nil
}
func (s *fakePasswordStore) SetPassword(_ context.Context, plain string) error {
if s.err != nil {
return s.err
}
s.password = plain
s.initialized = true
return nil
}
func (s *fakePasswordStore) VerifyPassword(_ context.Context, plain string) (bool, error) {
if s.err != nil {
return false, s.err
}
return s.initialized && plain == s.password, nil
}
func TestLauncherAuthLoginAndStatus(t *testing.T) {
const password = "dashboard-test-password"
const sess = "session-cookie-value"
store := &fakePasswordStore{initialized: true, password: password}
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: sess,
PasswordStore: store,
})
t.Run("status_unauthenticated", func(t *testing.T) {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/auth/status", nil))
if rec.Code != http.StatusOK {
t.Fatalf("status code = %d", rec.Code)
}
var body struct {
Authenticated bool `json:"authenticated"`
Initialized bool `json:"initialized"`
}
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if body.Authenticated {
t.Fatalf("unexpected authenticated=true: %+v", body)
}
})
t.Run("login_ok", func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(`{"password":"`+password+`"}`))
req.Header.Set("Content-Type", "application/json")
req.RemoteAddr = "127.0.0.1:12345"
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("login code = %d body=%s", rec.Code, rec.Body.String())
}
cookies := rec.Result().Cookies()
if len(cookies) != 1 || cookies[0].Name != middleware.LauncherDashboardCookieName {
t.Fatalf("cookies = %#v", cookies)
}
})
t.Run("status_authenticated", func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
req.AddCookie(&http.Cookie{Name: middleware.LauncherDashboardCookieName, Value: sess})
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status code = %d", rec.Code)
}
if !bytes.Contains(rec.Body.Bytes(), []byte(`"authenticated":true`)) {
t.Fatalf("body = %s", rec.Body.String())
}
if strings.Contains(rec.Body.String(), "token_help") {
t.Fatalf("authenticated response should omit token_help: %s", rec.Body.String())
}
})
}
func TestLauncherAuthUninitializedStoreRequiresSetup(t *testing.T) {
const sess = "session-cookie-value"
store := &fakePasswordStore{}
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: sess,
PasswordStore: store,
})
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/auth/status", nil))
if rec.Code != http.StatusOK {
t.Fatalf("status code = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Authenticated bool `json:"authenticated"`
Initialized bool `json:"initialized"`
}
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if body.Initialized {
t.Fatalf("initialized = true, want false before setup")
}
if body.Authenticated {
t.Fatalf("unexpected authenticated=true: %+v", body)
}
rec = httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(`{"password":"not-set-yet"}`))
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("login before setup code = %d body=%s", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
req = httptest.NewRequest(
http.MethodPost,
"/api/auth/setup",
strings.NewReader(`{"password":"12345678","confirm":"12345678"}`),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("setup code = %d body=%s", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(`{"password":"12345678"}`))
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("login after setup code = %d body=%s", rec.Code, rec.Body.String())
}
}
func TestLauncherAuthSetupRequiresSessionWhenInitialized(t *testing.T) {
const sess = "session-cookie-value"
store := &fakePasswordStore{initialized: true, password: "old-password"}
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: sess,
PasswordStore: store,
})
body := strings.NewReader(`{"password":"new-password","confirm":"new-password"}`)
req := httptest.NewRequest(http.MethodPost, "/api/auth/setup", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("setup without session code = %d body=%s", rec.Code, rec.Body.String())
}
body = strings.NewReader(`{"password":"new-password","confirm":"new-password"}`)
req = httptest.NewRequest(http.MethodPost, "/api/auth/setup", body)
req.Header.Set("Content-Type", "application/json")
req.AddCookie(&http.Cookie{Name: middleware.LauncherDashboardCookieName, Value: sess})
rec = httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("setup with session code = %d body=%s", rec.Code, rec.Body.String())
}
if store.password != "new-password" {
t.Fatalf("password = %q, want new-password", store.password)
}
}
func TestLauncherAuthInitialSetupAllowsDirectSetup(t *testing.T) {
store := &fakePasswordStore{}
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: "session-cookie-value",
PasswordStore: store,
})
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPost,
"/api/auth/setup",
strings.NewReader(`{"password":"12345678","confirm":"12345678"}`),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("setup without grant code = %d body=%s", rec.Code, rec.Body.String())
}
}
func TestLauncherAuthStoreUnavailableFailsClosed(t *testing.T) {
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: "session-cookie-value",
StoreError: errors.New("open auth store"),
})
for _, tc := range []struct {
name string
method string
path string
body string
}{
{name: "status", method: http.MethodGet, path: "/api/auth/status"},
{name: "login", method: http.MethodPost, path: "/api/auth/login", body: `{"password":"password"}`},
{name: "setup", method: http.MethodPost, path: "/api/auth/setup", body: `{"password":"12345678","confirm":"12345678"}`},
} {
t.Run(tc.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
if tc.body != "" {
req.Header.Set("Content-Type", "application/json")
}
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("code = %d body=%s", rec.Code, rec.Body.String())
}
})
}
}
func TestLauncherAuthLogoutRequiresPostAndJSON(t *testing.T) {
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: "session-cookie-value",
})
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/auth/logout", nil))
if rec.Code != http.StatusMethodNotAllowed && rec.Code != http.StatusNotFound {
t.Fatalf("GET logout: code = %d (expected 404 or 405)", rec.Code)
}
rec2 := httptest.NewRecorder()
req2 := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil)
req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
mux.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusUnsupportedMediaType {
t.Fatalf("wrong content-type: code = %d body=%s", rec2.Code, rec2.Body.String())
}
rec3 := httptest.NewRecorder()
req3 := httptest.NewRequest(http.MethodPost, "/api/auth/logout", strings.NewReader(`{}`))
req3.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec3, req3)
if rec3.Code != http.StatusOK {
t.Fatalf("POST json logout: code = %d", rec3.Code)
}
}
func TestLauncherAuthLoginRateLimit(t *testing.T) {
store := &fakePasswordStore{initialized: true, password: "correct-password"}
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: "session-cookie-value",
PasswordStore: store,
})
// 11 failing logins by wrong password; each consumes allow() slot after valid JSON.
wrongBody := `{"password":"wrong"}`
for i := 0; i < loginAttemptsPerIP; i++ {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(wrongBody))
req.Header.Set("Content-Type", "application/json")
req.RemoteAddr = "192.168.5.5:9999"
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("iter %d: want 401 got %d %s", i, rec.Code, rec.Body.String())
}
}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(wrongBody))
req.Header.Set("Content-Type", "application/json")
req.RemoteAddr = "192.168.5.5:9999"
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("11th attempt: want 429 got %d %s", rec.Code, rec.Body.String())
}
}
func TestLoginRateLimiterWindow(t *testing.T) {
l := newLoginRateLimiter()
t0 := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
l.now = func() time.Time { return t0 }
for i := 0; i < loginAttemptsPerIP; i++ {
if !l.allow("ip") {
t.Fatalf("want allow at %d", i)
}
}
if l.allow("ip") {
t.Fatal("want deny on 11th")
}
l.now = func() time.Time { return t0.Add(loginAttemptWindow + time.Second) }
if !l.allow("ip") {
t.Fatal("want allow after window")
}
}
func TestReferrerPolicyMiddleware(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
h := middleware.ReferrerPolicyNoReferrer(next)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if got := rec.Header().Get("Referrer-Policy"); got != "no-referrer" {
t.Fatalf("Referrer-Policy = %q", got)
}
}
func TestLauncherAuthLogoutEmptyBody(t *testing.T) {
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: "session-cookie-value",
})
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil)
req.Header.Set("Content-Type", "application/json")
req.Body = http.NoBody
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("code = %d", rec.Code)
}
}
func TestLauncherAuthLogoutRejectsTrailingJSON(t *testing.T) {
mux := http.NewServeMux()
RegisterLauncherAuthRoutes(mux, LauncherAuthRouteOpts{
SessionCookie: "session-cookie-value",
})
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", strings.NewReader(`{}{}`))
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("want 400 got %d %s", rec.Code, rec.Body.String())
}
}
-242
View File
@@ -1,242 +0,0 @@
package api
import (
"encoding/json"
"net/http"
"reflect"
"github.com/sipeed/picoclaw/pkg/config"
)
type channelCatalogItem struct {
Name string `json:"name"`
ConfigKey string `json:"config_key"`
Variant string `json:"variant,omitempty"`
}
var channelCatalog = []channelCatalogItem{
{Name: "weixin", ConfigKey: "weixin"},
{Name: "telegram", ConfigKey: "telegram"},
{Name: "discord", ConfigKey: "discord"},
{Name: "slack", ConfigKey: "slack"},
{Name: "feishu", ConfigKey: "feishu"},
{Name: "dingtalk", ConfigKey: "dingtalk"},
{Name: "line", ConfigKey: "line"},
{Name: "qq", ConfigKey: "qq"},
{Name: "onebot", ConfigKey: "onebot"},
{Name: "wecom", ConfigKey: "wecom"},
{Name: "whatsapp", ConfigKey: "whatsapp", Variant: "bridge"},
{Name: "whatsapp_native", ConfigKey: "whatsapp", Variant: "native"},
{Name: "pico", ConfigKey: "pico"},
{Name: "maixcam", ConfigKey: "maixcam"},
{Name: "matrix", ConfigKey: "matrix"},
{Name: "irc", ConfigKey: "irc"},
{Name: "mqtt", ConfigKey: "mqtt"},
}
type channelConfigResponse struct {
Config any `json:"config"`
ConfiguredSecrets []string `json:"configured_secrets"`
ConfigKey string `json:"config_key"`
Variant string `json:"variant,omitempty"`
}
// registerChannelRoutes binds read-only channel catalog endpoints to the ServeMux.
func (h *Handler) registerChannelRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/channels/catalog", h.handleListChannelCatalog)
mux.HandleFunc("GET /api/channels/{name}/config", h.handleGetChannelConfig)
}
// handleListChannelCatalog returns the channels supported by backend.
//
// GET /api/channels/catalog
func (h *Handler) handleListChannelCatalog(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"channels": channelCatalog,
})
}
// handleGetChannelConfig returns safe channel config plus secret presence metadata.
//
// GET /api/channels/{name}/config
func (h *Handler) handleGetChannelConfig(w http.ResponseWriter, r *http.Request) {
channelName := r.PathValue("name")
item, ok := findChannelCatalogItem(channelName)
if !ok {
http.Error(w, "Channel not found", http.StatusNotFound)
return
}
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, "Failed to load config", http.StatusInternalServerError)
return
}
resp := buildChannelConfigResponse(cfg, item)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
func findChannelCatalogItem(name string) (channelCatalogItem, bool) {
for _, item := range channelCatalog {
if item.Name == name {
return item, true
}
}
return channelCatalogItem{}, false
}
var channelSecretFieldMap = map[string][]string{
"weixin": {"token"},
"telegram": {"token"},
"discord": {"token"},
"slack": {"bot_token", "app_token"},
"feishu": {"app_secret", "encrypt_key", "verification_token"},
"dingtalk": {"client_secret"},
"line": {"channel_secret", "channel_access_token"},
"qq": {"app_secret"},
"onebot": {"access_token"},
"wecom": {"secret"},
"pico": {"token"},
"matrix": {"access_token"},
"irc": {"password", "nickserv_password", "sasl_password"},
"whatsapp": {},
"whatsapp_native": {},
"maixcam": {},
"mqtt": {"username", "password"},
}
func buildChannelConfigResponse(cfg *config.Config, item channelCatalogItem) channelConfigResponse {
resp := channelConfigResponse{
ConfiguredSecrets: []string{},
ConfigKey: item.ConfigKey,
Variant: item.Variant,
}
bc := cfg.Channels.Get(item.ConfigKey)
if bc == nil {
bc = defaultChannelConfig(item.ConfigKey)
if bc == nil {
resp.Config = map[string]any{}
return resp
}
}
// Detect configured secrets by checking the raw Settings JSON
secrets := detectConfiguredSecrets(bc.Settings, item.Name)
resp.ConfiguredSecrets = secrets
// Parse settings into a generic map for JSON response
settings := map[string]any{}
if len(bc.Settings) > 0 {
if err := json.Unmarshal(bc.Settings, &settings); err != nil {
resp.Config = map[string]any{}
return resp
}
}
// Remove secure fields from response
for _, key := range secrets {
delete(settings, key)
}
addChannelCommonConfig(settings, bc)
resp.Config = settings
return resp
}
func defaultChannelConfig(configKey string) *config.Channel {
return config.DefaultConfig().Channels.Get(configKey)
}
func addChannelCommonConfig(settings map[string]any, bc *config.Channel) {
settings["enabled"] = bc.Enabled
if len(bc.AllowFrom) > 0 {
settings["allow_from"] = []string(bc.AllowFrom)
}
if bc.ReasoningChannelID != "" {
settings["reasoning_channel_id"] = bc.ReasoningChannelID
}
if bc.GroupTrigger.MentionOnly || len(bc.GroupTrigger.Prefixes) > 0 {
settings["group_trigger"] = bc.GroupTrigger
}
if bc.Typing.Enabled {
settings["typing"] = bc.Typing
}
if bc.Placeholder.Enabled || len(bc.Placeholder.Text) > 0 {
settings["placeholder"] = bc.Placeholder
}
if _, exists := settings["streaming"]; !exists {
if streaming, ok := channelStreamingConfig(bc); ok {
if !streaming.IsZero() {
settings["streaming"] = streaming
}
}
}
}
func channelStreamingConfig(bc *config.Channel) (config.StreamingConfig, bool) {
if bc == nil {
return config.StreamingConfig{}, false
}
decoded, err := bc.GetDecoded()
if err != nil || decoded == nil {
return config.StreamingConfig{}, false
}
value := reflect.ValueOf(decoded)
if value.Kind() == reflect.Pointer {
if value.IsNil() {
return config.StreamingConfig{}, false
}
value = value.Elem()
}
if value.Kind() != reflect.Struct {
return config.StreamingConfig{}, false
}
field := value.FieldByName("Streaming")
if !field.IsValid() || !field.CanInterface() {
return config.StreamingConfig{}, false
}
streaming, ok := field.Interface().(config.StreamingConfig)
return streaming, ok
}
func detectConfiguredSecrets(settings config.RawNode, channelName string) []string {
var m map[string]any
if err := json.Unmarshal(settings, &m); err != nil {
return nil
}
fields, ok := channelSecretFieldMap[channelName]
if !ok {
return nil
}
var found []string
for _, key := range fields {
if val, exists := m[key]; exists {
switch v := val.(type) {
case string:
if v != "" {
found = append(found, key)
}
case map[string]any:
if s, ok := v["s"].(string); ok && s != "" {
found = append(found, key)
}
}
}
}
if found == nil {
return []string{}
}
return found
}
-285
View File
@@ -1,285 +0,0 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/sipeed/picoclaw/pkg/config"
)
func TestHandleGetChannelConfig_ReturnsSecretPresenceWithoutLeakingSecrets(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
cfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig() error = %v", err)
}
bc := cfg.Channels[config.ChannelFeishu]
bc.Enabled = true
decoded, err := bc.GetDecoded()
if err != nil {
t.Fatalf("GetDecoded() error = %v", err)
}
bcfg := decoded.(*config.FeishuSettings)
bcfg.AppID = "cli_test_app"
bcfg.AppSecret = *config.NewSecureString("feishu-secret-from-security")
bc.AllowFrom = config.FlexibleStringSlice{"ou_test_user"}
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
req := httptest.NewRequest(http.MethodGet, "/api/channels/feishu/config", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf(
"GET /api/channels/feishu/config status = %d, want %d, body=%s",
rec.Code,
http.StatusOK,
rec.Body.String(),
)
}
if strings.Contains(rec.Body.String(), "feishu-secret-from-security") {
t.Fatalf("response leaked secret value: %s", rec.Body.String())
}
var resp struct {
Config map[string]any `json:"config"`
ConfiguredSecrets []string `json:"configured_secrets"`
ConfigKey string `json:"config_key"`
Variant string `json:"variant"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("json.Unmarshal() error = %v", err)
}
if got := resp.ConfigKey; got != "feishu" {
t.Fatalf("config_key = %q, want %q", got, "feishu")
}
if got := resp.Config["app_id"]; got != "cli_test_app" {
t.Fatalf("config.app_id = %#v, want %q", got, "cli_test_app")
}
if got := resp.Config["enabled"]; got != true {
t.Fatalf("config.enabled = %#v, want true", got)
}
allowFrom, ok := resp.Config["allow_from"].([]any)
if !ok || len(allowFrom) != 1 || allowFrom[0] != "ou_test_user" {
t.Fatalf("config.allow_from = %#v, want [\"ou_test_user\"]", resp.Config["allow_from"])
}
if _, exists := resp.Config["app_secret"]; exists {
t.Fatalf("config should omit app_secret, got %#v", resp.Config["app_secret"])
}
if len(resp.ConfiguredSecrets) != 1 || resp.ConfiguredSecrets[0] != "app_secret" {
t.Fatalf("configured_secrets = %#v, want [\"app_secret\"]", resp.ConfiguredSecrets)
}
}
func TestHandleGetChannelConfig_ReturnsNotFoundForUnknownChannel(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
req := httptest.NewRequest(http.MethodGet, "/api/channels/not-a-channel/config", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("GET /api/channels/not-a-channel/config status = %d, want %d", rec.Code, http.StatusNotFound)
}
}
func TestHandleGetChannelConfig_ReturnsCommonFieldsWhenSettingsEmpty(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
cfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig() error = %v", err)
}
bc := cfg.Channels[config.ChannelFeishu]
bc.Enabled = true
bc.AllowFrom = config.FlexibleStringSlice{"ou_common_user"}
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
req := httptest.NewRequest(http.MethodGet, "/api/channels/feishu/config", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf(
"GET /api/channels/feishu/config status = %d, want %d, body=%s",
rec.Code,
http.StatusOK,
rec.Body.String(),
)
}
var resp struct {
Config map[string]any `json:"config"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("json.Unmarshal() error = %v", err)
}
if got := resp.Config["enabled"]; got != true {
t.Fatalf("config.enabled = %#v, want true", got)
}
allowFrom, ok := resp.Config["allow_from"].([]any)
if !ok || len(allowFrom) != 1 || allowFrom[0] != "ou_common_user" {
t.Fatalf("config.allow_from = %#v, want [\"ou_common_user\"]", resp.Config["allow_from"])
}
}
func TestHandleGetChannelConfig_OmitsUnconfiguredStreaming(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
req := httptest.NewRequest(http.MethodGet, "/api/channels/telegram/config", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf(
"GET /api/channels/telegram/config status = %d, want %d, body=%s",
rec.Code,
http.StatusOK,
rec.Body.String(),
)
}
var resp struct {
Config map[string]any `json:"config"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("json.Unmarshal() error = %v", err)
}
if _, ok := resp.Config["streaming"]; ok {
t.Fatalf("config.streaming = %#v, want omitted when not configured", resp.Config["streaming"])
}
}
func TestHandleGetChannelConfig_ReturnsConfiguredStreaming(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
cfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig() error = %v", err)
}
pico := cfg.Channels.Get(config.ChannelPico)
if pico == nil {
t.Fatal("missing pico channel")
}
pico.Settings = config.RawNode(`{"streaming":{"enabled":true,"throttle_seconds":2,"min_growth_chars":80}}`)
if err := config.InitChannelList(cfg.Channels); err != nil {
t.Fatalf("InitChannelList() error = %v", err)
}
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
req := httptest.NewRequest(http.MethodGet, "/api/channels/pico/config", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf(
"GET /api/channels/pico/config status = %d, want %d, body=%s",
rec.Code,
http.StatusOK,
rec.Body.String(),
)
}
var resp struct {
Config map[string]any `json:"config"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("json.Unmarshal() error = %v", err)
}
streaming, ok := resp.Config["streaming"].(map[string]any)
if !ok {
t.Fatalf("config.streaming = %#v, want object", resp.Config["streaming"])
}
if got := streaming["enabled"]; got != true {
t.Fatalf("config.streaming.enabled = %#v, want true", got)
}
if got := streaming["throttle_seconds"]; got != float64(2) {
t.Fatalf("config.streaming.throttle_seconds = %#v, want 2", got)
}
if got := streaming["min_growth_chars"]; got != float64(80) {
t.Fatalf("config.streaming.min_growth_chars = %#v, want 80", got)
}
}
func TestHandleGetChannelConfig_ReturnsDefaultShapeForMissingChannel(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
cfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig() error = %v", err)
}
delete(cfg.Channels, config.ChannelIRC)
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
req := httptest.NewRequest(http.MethodGet, "/api/channels/irc/config", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf(
"GET /api/channels/irc/config status = %d, want %d, body=%s",
rec.Code,
http.StatusOK,
rec.Body.String(),
)
}
var resp struct {
Config map[string]any `json:"config"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("json.Unmarshal() error = %v", err)
}
if got := resp.Config["server"]; got != "" {
t.Fatalf("config.server = %#v, want empty string", got)
}
if got := resp.Config["nick"]; got != "picoclaw" {
t.Fatalf("config.nick = %#v, want %q", got, "picoclaw")
}
if got := resp.Config["enabled"]; got != false {
t.Fatalf("config.enabled = %#v, want false", got)
}
}
-820
View File
@@ -1,820 +0,0 @@
package api
import (
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"regexp"
"strings"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/logger"
)
// registerConfigRoutes binds configuration management endpoints to the ServeMux.
func (h *Handler) registerConfigRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/config", h.handleGetConfig)
mux.HandleFunc("PUT /api/config", h.handleUpdateConfig)
mux.HandleFunc("PATCH /api/config", h.handlePatchConfig)
mux.HandleFunc("POST /api/config/reset", h.handleResetConfig)
mux.HandleFunc("POST /api/config/test-command-patterns", h.handleTestCommandPatterns)
}
func (h *Handler) applyRuntimeLogLevel() {
if h.debug {
logger.SetLevel(logger.DEBUG)
return
}
logger.SetLevelFromString(config.ResolveGatewayLogLevel(h.configPath))
}
// handleGetConfig returns the complete system configuration.
//
// GET /api/config
func (h *Handler) handleGetConfig(w http.ResponseWriter, r *http.Request) {
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(cfg); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
// handleUpdateConfig updates the complete system configuration.
//
// PUT /api/config
func (h *Handler) handleUpdateConfig(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var raw map[string]any
if err = json.Unmarshal(body, &raw); err != nil {
http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest)
return
}
if err = normalizeChannelArrayFields(raw); err != nil {
http.Error(w, fmt.Sprintf("Invalid channel array field: %v", err), http.StatusBadRequest)
return
}
normalizedBody, err := json.Marshal(raw)
if err != nil {
http.Error(w, "Failed to normalize config payload", http.StatusBadRequest)
return
}
var cfg config.Config
if err = json.Unmarshal(normalizedBody, &cfg); err != nil {
http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest)
return
}
cfg.Session.ApplyDmScope()
cfg.Session.DeriveDmScope()
if execAllowRemoteOmitted(body) {
cfg.Tools.Exec.AllowRemote = config.DefaultConfig().Tools.Exec.AllowRemote
}
// Load existing config and copy security credentials before validation,
// so that security-managed fields (e.g. pico token) are available.
err = cfg.SecurityCopyFrom(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to apply security config: %v", err), http.StatusInternalServerError)
return
}
applyConfigSecretsFromMap(&cfg, raw)
if errs := validateConfig(&cfg); len(errs) > 0 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]any{
"status": "validation_error",
"errors": errs,
})
return
}
if err := config.SaveConfig(h.configPath, &cfg); err != nil {
http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError)
return
}
h.applyRuntimeLogLevel()
logger.Infof("configuration updated successfully")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
func execAllowRemoteOmitted(body []byte) bool {
var raw struct {
Tools *struct {
Exec *struct {
AllowRemote *bool `json:"allow_remote"`
} `json:"exec"`
} `json:"tools"`
}
if err := json.Unmarshal(body, &raw); err != nil {
return false
}
return raw.Tools == nil || raw.Tools.Exec == nil || raw.Tools.Exec.AllowRemote == nil
}
// handlePatchConfig partially updates the system configuration using JSON Merge Patch (RFC 7396).
// Only the fields present in the request body will be updated; all other fields remain unchanged.
//
// PATCH /api/config
func (h *Handler) handlePatchConfig(w http.ResponseWriter, r *http.Request) {
patchBody, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
// Validate the patch is valid JSON
var patch map[string]any
if err = json.Unmarshal(patchBody, &patch); err != nil {
http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest)
return
}
// Load existing config and marshal to a map for merging
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
existing, err := json.Marshal(cfg)
if err != nil {
http.Error(w, "Failed to serialize current config", http.StatusInternalServerError)
return
}
var base map[string]any
if err = json.Unmarshal(existing, &base); err != nil {
http.Error(w, "Failed to parse current config", http.StatusInternalServerError)
return
}
// Recursively merge patch into base
mergeMap(base, patch)
// When the patch updates dm_scope, the old derived dimensions from the
// base must be cleared so that ApplyDmScope() can re-derive them from
// the new dm_scope value. Otherwise the stale dimensions survive the
// merge and ApplyDmScope() exits early due to its precedence guard.
if sess, ok := base["session"].(map[string]any); ok {
if patchSess, patchHasSession := patch["session"].(map[string]any); patchHasSession {
if _, hasDmScope := patchSess["dm_scope"]; hasDmScope {
if _, hasDimsInPatch := patchSess["dimensions"]; !hasDimsInPatch {
delete(sess, "dimensions")
}
}
}
}
if err = normalizeChannelArrayFields(base); err != nil {
http.Error(w, fmt.Sprintf("Invalid channel array field: %v", err), http.StatusBadRequest)
return
}
// Convert merged map back to Config struct
merged, err := json.Marshal(base)
if err != nil {
http.Error(w, "Failed to serialize merged config", http.StatusInternalServerError)
return
}
var newCfg config.Config
if err = json.Unmarshal(merged, &newCfg); err != nil {
http.Error(w, fmt.Sprintf("Merged config is invalid: %v", err), http.StatusBadRequest)
return
}
newCfg.Session.ApplyDmScope()
newCfg.Session.DeriveDmScope()
// Restore security fields (tokens/keys) from the loaded config before validation,
// because private fields are lost during JSON round-trip.
if err = newCfg.SecurityCopyFrom(h.configPath); err != nil {
http.Error(w, fmt.Sprintf("Failed to apply security config: %v", err), http.StatusInternalServerError)
return
}
applyConfigSecretsFromMap(&newCfg, base)
if errs := validateConfig(&newCfg); len(errs) > 0 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]any{
"status": "validation_error",
"errors": errs,
})
return
}
if err := config.SaveConfig(h.configPath, &newCfg); err != nil {
http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError)
return
}
h.applyRuntimeLogLevel()
logger.Infof("configuration updated successfully")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
// handleResetConfig resets the configuration to factory defaults.
// API keys and security credentials are preserved.
//
// POST /api/config/reset
func (h *Handler) handleResetConfig(w http.ResponseWriter, r *http.Request) {
if err := config.ResetToDefaults(h.configPath); err != nil {
http.Error(w, fmt.Sprintf("Failed to reset config: %v", err), http.StatusInternalServerError)
return
}
h.applyRuntimeLogLevel()
logger.Infof("configuration reset to factory defaults")
// Restart gateway if running
status := h.gatewayStatusData()
gatewayStatus, _ := status["gateway_status"].(string)
if gatewayStatus == "running" {
if _, err := h.RestartGateway(); err != nil {
logger.ErrorF("failed to restart gateway after config reset", map[string]any{"error": err.Error()})
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
// handleTestCommandPatterns tests a command against whitelist and blacklist patterns.
//
// POST /api/config/test-command-patterns
func (h *Handler) handleTestCommandPatterns(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var req struct {
AllowPatterns []string `json:"allow_patterns"`
DenyPatterns []string `json:"deny_patterns"`
Command string `json:"command"`
}
if err := json.Unmarshal(body, &req); err != nil {
http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest)
return
}
lower := strings.ToLower(strings.TrimSpace(req.Command))
type result struct {
Allowed bool `json:"allowed"`
Blocked bool `json:"blocked"`
MatchedWhitelist *string `json:"matched_whitelist,omitempty"`
MatchedBlacklist *string `json:"matched_blacklist,omitempty"`
}
resp := result{Allowed: false, Blocked: false}
// Check whitelist first
for _, pattern := range req.AllowPatterns {
re, err := regexp.Compile(pattern)
if err != nil {
continue // skip invalid patterns
}
if re.MatchString(lower) {
resp.Allowed = true
resp.MatchedWhitelist = &pattern
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
return
}
}
// Check blacklist
for _, pattern := range req.DenyPatterns {
re, err := regexp.Compile(pattern)
if err != nil {
continue
}
if re.MatchString(lower) {
resp.Blocked = true
resp.MatchedBlacklist = &pattern
break
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
// validateConfig checks the config for common errors before saving.
// Returns a list of human-readable error strings; empty means valid.
func validateConfig(cfg *config.Config) []string {
var errs []string
// Validate model_list entries
if err := cfg.ValidateModelList(); err != nil {
errs = append(errs, err.Error())
}
if err := cfg.ValidateTurnProfile(); err != nil {
errs = append(errs, err.Error())
}
// Gateway port range
if cfg.Gateway.Port != 0 && (cfg.Gateway.Port < 1 || cfg.Gateway.Port > 65535) {
errs = append(errs, fmt.Sprintf("gateway.port %d is out of valid range (1-65535)", cfg.Gateway.Port))
}
for name, bc := range cfg.Channels {
streaming, ok := channelStreamingConfig(bc)
if !ok {
continue
}
if streaming.ThrottleSeconds < 0 {
errs = append(errs, fmt.Sprintf("channel %q streaming.throttle_seconds must be >= 0", name))
}
if streaming.MinGrowthChars < 0 {
errs = append(errs, fmt.Sprintf("channel %q streaming.min_growth_chars must be >= 0", name))
}
}
// Pico channel: token required when enabled
{
bc := cfg.Channels.GetByType(config.ChannelPico)
if bc != nil && bc.Enabled {
if decoded, err := bc.GetDecoded(); err == nil && decoded != nil {
if c, ok := decoded.(*config.PicoSettings); ok && c.Token.String() == "" {
errs = append(errs, "channels.pico.token is required when pico channel is enabled")
}
}
}
}
// Telegram: token required when enabled
{
bc := cfg.Channels.GetByType(config.ChannelTelegram)
if bc != nil && bc.Enabled {
if decoded, err := bc.GetDecoded(); err == nil && decoded != nil {
if c, ok := decoded.(*config.TelegramSettings); ok && c.Token.String() == "" {
errs = append(errs, "channels.telegram.token is required when telegram channel is enabled")
}
}
}
}
// Discord: token required when enabled
{
bc := cfg.Channels.GetByType(config.ChannelDiscord)
if bc != nil && bc.Enabled {
if decoded, err := bc.GetDecoded(); err == nil && decoded != nil {
if c, ok := decoded.(*config.DiscordSettings); ok && c.Token.String() == "" {
errs = append(errs, "channels.discord.token is required when discord channel is enabled")
}
}
}
}
{
bc := cfg.Channels.GetByType(config.ChannelWeCom)
if bc != nil && bc.Enabled {
if decoded, err := bc.GetDecoded(); err == nil && decoded != nil {
if c, ok := decoded.(*config.WeComSettings); ok {
if c.BotID == "" {
errs = append(errs, "channels.wecom.bot_id is required when wecom channel is enabled")
}
if c.Secret.String() == "" {
errs = append(errs, "channels.wecom.secret is required when wecom channel is enabled")
}
}
}
}
}
if cfg.Tools.Exec.Enabled {
if cfg.Tools.Exec.EnableDenyPatterns {
errs = append(
errs,
validateRegexPatterns("tools.exec.custom_deny_patterns", cfg.Tools.Exec.CustomDenyPatterns)...)
}
errs = append(
errs,
validateRegexPatterns("tools.exec.custom_allow_patterns", cfg.Tools.Exec.CustomAllowPatterns)...)
}
return errs
}
func validateRegexPatterns(field string, patterns []string) []string {
var errs []string
for index, pattern := range patterns {
if _, err := regexp.Compile(pattern); err != nil {
errs = append(errs, fmt.Sprintf("%s[%d] is not a valid regular expression: %v", field, index, err))
}
}
return errs
}
// mergeMap recursively merges src into dst (JSON Merge Patch semantics).
// - If a key in src has a null value, it is deleted from dst.
// - If both dst and src have a nested object for the same key, merge recursively.
// - Otherwise the value from src overwrites dst.
func mergeMap(dst, src map[string]any) {
for key, srcVal := range src {
if srcVal == nil {
delete(dst, key)
continue
}
srcMap, srcIsMap := srcVal.(map[string]any)
dstMap, dstIsMap := dst[key].(map[string]any)
if srcIsMap && dstIsMap {
mergeMap(dstMap, srcMap)
} else {
dst[key] = srcVal
}
}
}
func asMapField(value map[string]any, key string) (map[string]any, bool) {
raw, exists := value[key]
if !exists {
return nil, false
}
m, isMap := raw.(map[string]any)
return m, isMap
}
var (
allowFromHiddenCharsRe = regexp.MustCompile("[\u200B\u200C\u200D\u200E\u200F\u202A-\u202E\u2060-\u2069\uFEFF]")
allowFromSplitRe = regexp.MustCompile("[,\uFF0C、;;\r\n\t]+")
conservativeSplitRe = regexp.MustCompile("[,\uFF0C\r\n\t]+")
)
type stringArrayParserOptions struct {
stripHiddenChars bool
}
func normalizeChannelArrayFields(raw map[string]any) error {
channelsMap, hasChannels := asMapField(raw, "channel_list")
if !hasChannels {
return nil
}
defaultCfg := config.DefaultConfig()
for channelName, rawChannel := range channelsMap {
chMap, ok := rawChannel.(map[string]any)
if !ok {
continue
}
if rawAllowFrom, exists := chMap["allow_from"]; exists {
normalized, err := normalizeStringArrayValue(rawAllowFrom, stringArrayParserOptions{
stripHiddenChars: true,
})
if err != nil {
return fmt.Errorf("channel_list.%s.allow_from: %w", channelName, err)
}
chMap["allow_from"] = normalized
}
if groupTrigger, ok := asMapField(chMap, "group_trigger"); ok {
if rawPrefixes, exists := groupTrigger["prefixes"]; exists {
normalized, err := normalizeStringArrayValue(rawPrefixes, stringArrayParserOptions{})
if err != nil {
return fmt.Errorf("channel_list.%s.group_trigger.prefixes: %w", channelName, err)
}
groupTrigger["prefixes"] = normalized
}
}
settingsMap, hasSettings := asMapField(chMap, "settings")
if !hasSettings {
continue
}
settingsType := channelSettingsType(defaultCfg, channelName, chMap)
if settingsType == nil {
continue
}
for i := range settingsType.NumField() {
field := settingsType.Field(i)
if !field.IsExported() || !isStringSliceType(field.Type) {
continue
}
jsonKey := strings.Split(field.Tag.Get("json"), ",")[0]
if jsonKey == "" || jsonKey == "-" {
continue
}
rawValue, exists := settingsMap[jsonKey]
if !exists {
continue
}
options := stringArrayParserOptions{}
if jsonKey == "allow_from" {
options.stripHiddenChars = true
}
normalized, err := normalizeStringArrayValue(rawValue, options)
if err != nil {
return fmt.Errorf("channel_list.%s.settings.%s: %w", channelName, jsonKey, err)
}
settingsMap[jsonKey] = normalized
}
}
return nil
}
func channelSettingsType(
defaultCfg *config.Config,
channelName string,
channelMap map[string]any,
) reflect.Type {
if channelType, _ := channelMap["type"].(string); channelType != "" {
if bc := defaultCfg.Channels.GetByType(channelType); bc != nil {
if decoded, err := bc.GetDecoded(); err == nil && decoded != nil {
return derefType(reflect.TypeOf(decoded))
}
}
}
if bc := defaultCfg.Channels.Get(channelName); bc != nil {
if decoded, err := bc.GetDecoded(); err == nil && decoded != nil {
return derefType(reflect.TypeOf(decoded))
}
}
return nil
}
func derefType(typ reflect.Type) reflect.Type {
for typ != nil && typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
return typ
}
func isStringSliceType(typ reflect.Type) bool {
typ = derefType(typ)
return typ != nil && typ.Kind() == reflect.Slice && typ.Elem().Kind() == reflect.String
}
func normalizeStringArrayValue(value any, options stringArrayParserOptions) ([]string, error) {
switch typed := value.(type) {
case nil:
return nil, nil
case string:
return parseStringArrayValue(typed, options), nil
case float64:
return normalizeStringArrayItems([]string{fmt.Sprintf("%.0f", typed)}, options), nil
case []string:
return normalizeStringArrayItems(typed, options), nil
case []any:
items := make([]string, 0, len(typed))
for _, item := range typed {
switch raw := item.(type) {
case string:
items = append(items, raw)
case float64:
items = append(items, fmt.Sprintf("%.0f", raw))
default:
return nil, fmt.Errorf("unsupported list item type %T", item)
}
}
return normalizeStringArrayItems(items, options), nil
default:
return nil, fmt.Errorf("unsupported list field type %T", value)
}
}
func parseStringArrayValue(raw string, options stringArrayParserOptions) []string {
if strings.TrimSpace(raw) == "" {
return []string{}
}
splitRe := conservativeSplitRe
if options.stripHiddenChars {
splitRe = allowFromSplitRe
}
return normalizeStringArrayItems(splitRe.Split(raw, -1), options)
}
func normalizeStringArrayItems(items []string, options stringArrayParserOptions) []string {
result := make([]string, 0, len(items))
seen := make(map[string]struct{}, len(items))
for _, item := range items {
normalized := item
if options.stripHiddenChars {
normalized = allowFromHiddenCharsRe.ReplaceAllString(normalized, "")
}
normalized = strings.TrimSpace(normalized)
if normalized == "" {
continue
}
if _, exists := seen[normalized]; exists {
continue
}
seen[normalized] = struct{}{}
result = append(result, normalized)
}
if len(result) == 0 {
return []string{}
}
return result
}
func getSecretString(m map[string]any, key string) (string, bool) {
if raw, exists := m[key]; exists {
s, isString := raw.(string)
if isString {
return s, true
}
}
if raw, exists := m["_"+key]; exists {
s, isString := raw.(string)
if isString {
return s, true
}
}
return "", false
}
func applyConfigSecretsFromMap(cfg *config.Config, raw map[string]any) {
channelsMap, hasChannels := asMapField(raw, "channel_list")
if !hasChannels {
return
}
for chName, chData := range channelsMap {
chMap, ok := chData.(map[string]any)
if !ok {
continue
}
bc := cfg.Channels.Get(chName)
if bc == nil {
continue
}
decoded, err := bc.GetDecoded()
if err != nil || decoded == nil {
continue
}
rv := reflect.ValueOf(decoded)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
continue
}
// Channel-specific settings live under the "settings" key in the raw map
settingsMap := chMap
if sm, hasSettings := asMapField(chMap, "settings"); hasSettings {
settingsMap = sm
}
applySecureStringsToStruct(rv, settingsMap)
}
// Handle tools secrets
tools, hasTools := asMapField(raw, "tools")
if !hasTools {
return
}
skills, hasSkills := asMapField(tools, "skills")
if !hasSkills {
return
}
if github, hasGithub := asMapField(skills, "github"); hasGithub {
if token, hasToken := getSecretString(github, "token"); hasToken {
cfg.Tools.Skills.Github.Token.Set(token)
}
}
if registries, hasRegistries := asMapField(skills, "registries"); hasRegistries {
for registryName, rawRegistry := range registries {
registryMap, ok := rawRegistry.(map[string]any)
if !ok {
continue
}
if authToken, hasAuthToken := getSecretString(registryMap, "auth_token"); hasAuthToken {
registryCfg, _ := cfg.Tools.Skills.Registries.Get(registryName)
registryCfg.AuthToken.Set(authToken)
cfg.Tools.Skills.Registries.Set(registryName, registryCfg)
}
}
return
}
registriesList, hasRegistries := skills["registries"].([]any)
if !hasRegistries {
return
}
for _, rawRegistry := range registriesList {
registryMap, ok := rawRegistry.(map[string]any)
if !ok {
continue
}
name, _ := registryMap["name"].(string)
if name == "" {
continue
}
if authToken, hasAuthToken := getSecretString(registryMap, "auth_token"); hasAuthToken {
registryCfg, _ := cfg.Tools.Skills.Registries.Get(name)
registryCfg.AuthToken.Set(authToken)
cfg.Tools.Skills.Registries.Set(name, registryCfg)
}
}
}
// applySecureStringsToStruct walks a struct and applies SecureString fields
// from the matching keys in rawMap. It recurses into nested maps and slices.
func applySecureStringsToStruct(rv reflect.Value, rawMap map[string]any) {
rt := rv.Type()
for jsonKey, rawVal := range rawMap {
for i := range rt.NumField() {
f := rt.Field(i)
if !f.IsExported() {
continue
}
tag := f.Tag.Get("json")
name := strings.Split(tag, ",")[0]
if name != jsonKey {
continue
}
sf := rv.Field(i)
if !sf.CanSet() {
continue
}
// Direct SecureString field
if s, ok := rawVal.(string); ok {
if f.Type == reflect.TypeOf(config.SecureString{}) {
sf.Set(reflect.ValueOf(*config.NewSecureString(s)))
} else if f.Type == reflect.TypeOf(&config.SecureString{}) {
sf.Set(reflect.ValueOf(config.NewSecureString(s)))
}
continue
}
// Recurse into nested struct
if sf.Kind() == reflect.Struct {
if nested, ok := rawVal.(map[string]any); ok {
applySecureStringsToStruct(sf, nested)
}
continue
}
// Recurse into map fields (e.g., map[string]SomeStruct)
if sf.Kind() == reflect.Map && sf.Type().Elem().Kind() == reflect.Struct {
if nestedMap, ok := rawVal.(map[string]any); ok {
for mapKey, mapVal := range nestedMap {
nested, ok := mapVal.(map[string]any)
if !ok {
continue
}
elemType := sf.Type().Elem()
// Get existing element or create a new zero value
var elem reflect.Value
existing := sf.MapIndex(reflect.ValueOf(mapKey))
if existing.IsValid() {
if existing.Kind() == reflect.Interface {
existing = existing.Elem()
}
if existing.Kind() == reflect.Ptr && !existing.IsNil() {
elem = reflect.New(elemType)
elem.Elem().Set(existing.Elem())
} else if existing.Kind() == reflect.Struct {
elem = reflect.New(elemType)
elem.Elem().Set(existing)
}
}
if !elem.IsValid() {
elem = reflect.New(elemType)
}
applySecureStringsToStruct(elem.Elem(), nested)
sf.SetMapIndex(reflect.ValueOf(mapKey), elem.Elem())
}
}
continue
}
// Recurse into slice elements that are structs
if sf.Kind() == reflect.Slice && sf.Type().Elem().Kind() == reflect.Struct {
if sliceRaw, ok := rawVal.([]any); ok {
for idx, elemRaw := range sliceRaw {
if nested, ok := elemRaw.(map[string]any); ok {
if idx < sf.Len() {
applySecureStringsToStruct(sf.Index(idx), nested)
}
}
}
}
}
}
}
}
File diff suppressed because it is too large. Load diff
-17
View File
@@ -1,17 +0,0 @@
//go:build !windows
package api
import (
"os/exec"
"github.com/sipeed/picoclaw/web/backend/utils"
)
func launcherExecCommand(name string, args ...string) *exec.Cmd {
return utils.LauncherExecCommand(name, args...)
}
func applyLauncherProcAttrs(cmd *exec.Cmd) {
utils.ApplyLauncherProcAttrs(cmd)
}
-17
View File
@@ -1,17 +0,0 @@
//go:build windows
package api
import (
"os/exec"
"github.com/sipeed/picoclaw/web/backend/utils"
)
func launcherExecCommand(name string, args ...string) *exec.Cmd {
return utils.LauncherExecCommand(name, args...)
}
func applyLauncherProcAttrs(cmd *exec.Cmd) {
utils.ApplyLauncherProcAttrs(cmd)
}
File diff suppressed because it is too large. Load diff
-252
View File
@@ -1,252 +0,0 @@
package api
import (
"net"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/netbind"
)
func (h *Handler) effectiveLauncherPublic() bool {
if h.serverHostExplicit {
// -host takes precedence over -public and launcher-config public setting.
return false
}
if h.serverPublicExplicit {
return h.serverPublic
}
cfg, err := h.loadLauncherConfig()
if err == nil {
return cfg.Public
}
return h.serverPublic
}
func (h *Handler) gatewayHostOverride() string {
if h.serverHostExplicit {
return strings.TrimSpace(h.serverHostInput)
}
if h.effectiveLauncherPublic() {
return "*"
}
return ""
}
func (h *Handler) effectiveGatewayBindHost(cfg *config.Config) string {
if override := h.gatewayHostOverride(); override != "" {
return override
}
if cfg == nil {
return ""
}
return strings.TrimSpace(cfg.Gateway.Host)
}
func gatewayProbeHost(bindHost string) string {
plan, err := netbind.BuildPlan(bindHost, netbind.DefaultLoopback)
if err != nil || strings.TrimSpace(plan.ProbeHost) == "" {
return netbind.ResolveAdaptiveLoopbackHost()
}
return plan.ProbeHost
}
func (h *Handler) gatewayProxyURL() *url.URL {
cfg, err := config.LoadConfig(h.configPath)
port := 18790
bindHost := ""
if err == nil && cfg != nil {
if cfg.Gateway.Port != 0 {
port = cfg.Gateway.Port
}
bindHost = h.effectiveGatewayBindHost(cfg)
}
return &url.URL{
Scheme: "http",
Host: net.JoinHostPort(gatewayProbeHost(bindHost), strconv.Itoa(port)),
}
}
func requestHostName(r *http.Request) string {
reqHost, _, err := net.SplitHostPort(r.Host)
if err == nil {
return reqHost
}
if strings.TrimSpace(r.Host) != "" {
return r.Host
}
return netbind.ResolveAdaptiveLoopbackHost()
}
func forwardedProtoFirst(r *http.Request) string {
raw := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto"))
if raw == "" {
raw = forwardedRFC7239Proto(r)
}
if raw == "" {
return ""
}
if i := strings.IndexByte(raw, ','); i >= 0 {
raw = strings.TrimSpace(raw[:i])
}
return strings.ToLower(raw)
}
func requestWSScheme(r *http.Request) string {
if forwarded := forwardedProtoFirst(r); forwarded != "" {
proto := strings.ToLower(strings.TrimSpace(strings.Split(forwarded, ",")[0]))
if proto == "https" || proto == "wss" {
return "wss"
}
if proto == "http" || proto == "ws" {
return "ws"
}
}
if r.TLS != nil {
return "wss"
}
return "ws"
}
// requestHTTPScheme returns http or https for URLs that are not WebSockets (e.g. SSE).
func requestHTTPScheme(r *http.Request) string {
if forwarded := forwardedProtoFirst(r); forwarded != "" {
proto := strings.ToLower(strings.TrimSpace(strings.Split(forwarded, ",")[0]))
if proto == "https" || proto == "wss" {
return "https"
}
if proto == "http" || proto == "ws" {
return "http"
}
}
if r.TLS != nil {
return "https"
}
return "http"
}
// forwardedHostFirst returns the client-visible host from reverse-proxy / tunnel headers
// (e.g. VS Code port forwarding, nginx). Empty if unset.
func forwardedHostFirst(r *http.Request) string {
raw := strings.TrimSpace(r.Header.Get("X-Forwarded-Host"))
if raw == "" {
raw = forwardedRFC7239Host(r)
}
if raw == "" {
return ""
}
if i := strings.IndexByte(raw, ','); i >= 0 {
raw = strings.TrimSpace(raw[:i])
}
return raw
}
// forwardedRFC7239Host parses host= from the first Forwarded header element (RFC 7239).
func forwardedRFC7239Host(r *http.Request) string {
return forwardedRFC7239Param(r, "host")
}
func forwardedRFC7239Proto(r *http.Request) string {
return forwardedRFC7239Param(r, "proto")
}
func forwardedRFC7239Param(r *http.Request, key string) string {
v := strings.TrimSpace(r.Header.Get("Forwarded"))
if v == "" {
return ""
}
first := strings.TrimSpace(strings.Split(v, ",")[0])
for _, part := range strings.Split(first, ";") {
part = strings.TrimSpace(part)
low := strings.ToLower(part)
if !strings.HasPrefix(low, key+"=") {
continue
}
val := strings.TrimSpace(part[strings.IndexByte(part, '=')+1:])
if len(val) >= 2 && val[0] == '"' && val[len(val)-1] == '"' {
val = val[1 : len(val)-1]
}
return val
}
return ""
}
// forwardedPortFirst returns the first X-Forwarded-Port value, or empty.
func forwardedPortFirst(r *http.Request) string {
raw := strings.TrimSpace(r.Header.Get("X-Forwarded-Port"))
if raw == "" {
return ""
}
if i := strings.IndexByte(raw, ','); i >= 0 {
raw = strings.TrimSpace(raw[:i])
}
return raw
}
// clientVisiblePort picks the TCP port the browser uses to reach this app (after proxies).
// Used by picoWebUIAddr → buildWsURL / buildPicoEventsURL / buildPicoSendURL so WebSocket and
// HTTP URLs match the dashboard page origin (cookies / token flow behind tunnels and reverse proxies).
func clientVisiblePort(r *http.Request, serverListenPort int) string {
if p := forwardedPortFirst(r); p != "" {
return p
}
if fwdHost := forwardedHostFirst(r); fwdHost != "" {
if _, port, err := net.SplitHostPort(fwdHost); err == nil && port != "" {
return port
}
}
if _, port, err := net.SplitHostPort(r.Host); err == nil && port != "" {
return port
}
if strings.TrimSpace(r.Host) == "" && forwardedHostFirst(r) == "" {
return strconv.Itoa(serverListenPort)
}
if requestHTTPScheme(r) == "https" {
return "443"
}
return "80"
}
// joinClientVisibleHostPort builds host:port for absolute URLs returned to the browser.
func joinClientVisibleHostPort(r *http.Request, host string, serverListenPort int) string {
if h, p, err := net.SplitHostPort(host); err == nil {
return net.JoinHostPort(h, p)
}
return net.JoinHostPort(host, clientVisiblePort(r, serverListenPort))
}
// picoWebUIAddr is host:port for URLs returned to the browser (/pico/ws, /pico/events, /pico/send).
// It must match the HTTP Host the client used (or X-Forwarded-*), not cfg.Gateway.Host — otherwise
// e.g. page on localhost with ws_url 127.0.0.1 omits cookies and the dashboard auth handshake fails.
func (h *Handler) picoWebUIAddr(r *http.Request) string {
wsPort := h.serverPort
if wsPort == 0 {
wsPort = 18800
}
if fwdHost := forwardedHostFirst(r); fwdHost != "" {
return joinClientVisibleHostPort(r, fwdHost, wsPort)
}
return joinClientVisibleHostPort(r, requestHostName(r), wsPort)
}
func (h *Handler) buildWsURL(r *http.Request) string {
return requestWSScheme(r) + "://" + h.picoWebUIAddr(r) + "/pico/ws"
}
func (h *Handler) buildPicoEventsURL(r *http.Request) string {
return requestHTTPScheme(r) + "://" + h.picoWebUIAddr(r) + "/pico/events"
}
func (h *Handler) buildPicoSendURL(r *http.Request) string {
return requestHTTPScheme(r) + "://" + h.picoWebUIAddr(r) + "/pico/send"
}
-330
View File
@@ -1,330 +0,0 @@
package api
import (
"crypto/tls"
"errors"
"net"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/netbind"
"github.com/sipeed/picoclaw/web/backend/launcherconfig"
)
func TestGatewayHostOverrideUsesExplicitRuntimePublic(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
launcherPath := launcherconfig.PathForAppConfig(configPath)
if err := launcherconfig.Save(launcherPath, launcherconfig.Config{
Port: 18800,
Public: false,
}); err != nil {
t.Fatalf("launcherconfig.Save() error = %v", err)
}
h := NewHandler(configPath)
h.SetServerOptions(18800, true, true, nil)
if got := h.gatewayHostOverride(); got != "*" {
t.Fatalf("gatewayHostOverride() = %q, want %q", got, "*")
}
}
func TestBuildWsURLUsesRequestHostWhenLauncherPublicSaved(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
launcherPath := launcherconfig.PathForAppConfig(configPath)
if err := launcherconfig.Save(launcherPath, launcherconfig.Config{
Port: 18800,
Public: true,
}); err != nil {
t.Fatalf("launcherconfig.Save() error = %v", err)
}
h := NewHandler(configPath)
h.SetServerOptions(18800, false, false, nil)
cfg := config.DefaultConfig()
cfg.Gateway.Host = "127.0.0.1"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "http://launcher.local/api/pico/info", nil)
req.Host = "192.168.1.9:18800"
if got := h.buildWsURL(req); got != "ws://192.168.1.9:18800/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "ws://192.168.1.9:18800/pico/ws")
}
if got := h.buildPicoEventsURL(req); got != "http://192.168.1.9:18800/pico/events" {
t.Fatalf("buildPicoEventsURL() = %q, want %q", got, "http://192.168.1.9:18800/pico/events")
}
if got := h.buildPicoSendURL(req); got != "http://192.168.1.9:18800/pico/send" {
t.Fatalf("buildPicoSendURL() = %q, want %q", got, "http://192.168.1.9:18800/pico/send")
}
}
func TestGatewayProbeHostUsesLoopbackForWildcardBind(t *testing.T) {
want := "127.0.0.1"
if got := gatewayProbeHost("0.0.0.0"); got != want {
t.Fatalf("gatewayProbeHost() = %q, want %q", got, want)
}
}
func TestGatewayProbeHostUsesPreferredLoopbackForEmptyBind(t *testing.T) {
want := netbind.ResolveAdaptiveLoopbackHost()
if got := gatewayProbeHost(""); got != want {
t.Fatalf("gatewayProbeHost(empty) = %q, want %q", got, want)
}
}
func TestGatewayProbeHostUsesPreferredLoopbackForLocalhostBind(t *testing.T) {
want := netbind.ResolveAdaptiveLoopbackHost()
if got := gatewayProbeHost("localhost"); got != want {
t.Fatalf("gatewayProbeHost(localhost) = %q, want %q", got, want)
}
}
func TestGatewayProbeHostUsesLoopbackForIPv6WildcardBind(t *testing.T) {
want := "::1"
if got := gatewayProbeHost("::"); got != want {
t.Fatalf("gatewayProbeHost(::) = %q, want %q", got, want)
}
}
func TestGatewayProbeHostUsesFirstConcreteHostForMultiHostBind(t *testing.T) {
if got := gatewayProbeHost("127.0.0.1,::1"); got != "127.0.0.1" {
t.Fatalf("gatewayProbeHost(multi) = %q, want %q", got, "127.0.0.1")
}
}
func TestGatewayProxyURLUsesConfiguredHost(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
cfg := config.DefaultConfig()
cfg.Gateway.Host = "192.168.1.10"
cfg.Gateway.Port = 18791
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
if got := h.gatewayProxyURL().String(); got != "http://192.168.1.10:18791" {
t.Fatalf("gatewayProxyURL() = %q, want %q", got, "http://192.168.1.10:18791")
}
}
func TestGetGatewayHealthUsesConfiguredHost(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
cfg := config.DefaultConfig()
cfg.Gateway.Host = "192.168.1.10"
cfg.Gateway.Port = 18791
originalHealthGet := gatewayHealthGet
t.Cleanup(func() {
gatewayHealthGet = originalHealthGet
})
var requestedURL string
gatewayHealthGet = func(url string, timeout time.Duration) (*http.Response, error) {
requestedURL = url
return nil, errors.New("probe failed")
}
_, statusCode, err := h.getGatewayHealth(cfg, time.Second)
_ = statusCode
_ = err
if requestedURL != "http://192.168.1.10:18791/health" {
t.Fatalf("health url = %q, want %q", requestedURL, "http://192.168.1.10:18791/health")
}
}
func TestGetGatewayHealthUsesProbeHostForPublicLauncher(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
h.SetServerOptions(18800, true, true, nil)
cfg := config.DefaultConfig()
cfg.Gateway.Host = "127.0.0.1"
cfg.Gateway.Port = 18791
originalHealthGet := gatewayHealthGet
t.Cleanup(func() {
gatewayHealthGet = originalHealthGet
})
var requestedURL string
gatewayHealthGet = func(url string, timeout time.Duration) (*http.Response, error) {
requestedURL = url
return nil, errors.New("probe failed")
}
_, statusCode, err := h.getGatewayHealth(cfg, time.Second)
_ = statusCode
_ = err
want := "http://" + net.JoinHostPort(netbind.ResolveAdaptiveLoopbackHost(), "18791") + "/health"
if requestedURL != want {
t.Fatalf("health url = %q, want %q", requestedURL, want)
}
}
func TestBuildWsURLUsesWSSWhenForwardedProtoIsHTTPS(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
cfg := config.DefaultConfig()
cfg.Gateway.Host = "0.0.0.0"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "http://launcher.local/api/pico/info", nil)
req.Host = "chat.example.com"
req.Header.Set("X-Forwarded-Proto", "https")
if got := h.buildWsURL(req); got != "wss://chat.example.com:443/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "wss://chat.example.com:443/pico/ws")
}
}
func TestBuildWsURLUsesWSSWhenRequestIsTLS(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
cfg := config.DefaultConfig()
cfg.Gateway.Host = "0.0.0.0"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "https://launcher.local/api/pico/info", nil)
req.Host = "secure.example.com"
req.TLS = &tls.ConnectionState{}
if got := h.buildWsURL(req); got != "wss://secure.example.com:443/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "wss://secure.example.com:443/pico/ws")
}
}
func TestBuildPicoURLsPreferXForwardedHost(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
launcherPath := launcherconfig.PathForAppConfig(configPath)
if err := launcherconfig.Save(launcherPath, launcherconfig.Config{
Port: 18800,
Public: true,
}); err != nil {
t.Fatalf("launcherconfig.Save() error = %v", err)
}
h := NewHandler(configPath)
h.SetServerOptions(18800, false, false, nil)
cfg := config.DefaultConfig()
cfg.Gateway.Host = "0.0.0.0"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "http://127.0.0.1:18800/api/pico/info", nil)
req.Host = "127.0.0.1:18800"
req.Header.Set("X-Forwarded-Host", "vscode-tunnel.example.com")
req.Header.Set("X-Forwarded-Proto", "https")
req.Header.Set("X-Forwarded-Port", "443")
if got := h.buildPicoEventsURL(req); got != "https://vscode-tunnel.example.com:443/pico/events" {
t.Fatalf("buildPicoEventsURL() = %q, want %q", got, "https://vscode-tunnel.example.com:443/pico/events")
}
if got := h.buildPicoSendURL(req); got != "https://vscode-tunnel.example.com:443/pico/send" {
t.Fatalf("buildPicoSendURL() = %q, want %q", got, "https://vscode-tunnel.example.com:443/pico/send")
}
if got := h.buildWsURL(req); got != "wss://vscode-tunnel.example.com:443/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "wss://vscode-tunnel.example.com:443/pico/ws")
}
}
func TestBuildWsURLPrefersForwardedHTTPOverTLS(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
cfg := config.DefaultConfig()
cfg.Gateway.Host = "0.0.0.0"
cfg.Gateway.Port = 18790
req := httptest.NewRequest("GET", "https://launcher.local/api/pico/info", nil)
req.Host = "chat.example.com"
req.TLS = &tls.ConnectionState{}
req.Header.Set("X-Forwarded-Proto", "http")
if got := h.buildWsURL(req); got != "ws://chat.example.com:80/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "ws://chat.example.com:80/pico/ws")
}
}
func TestBuildWsURLDoesNotTrustOriginWhenProxyOmitsForwardedProto(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
req := httptest.NewRequest("GET", "http://launcher.local/api/pico/info", nil)
req.Host = "fs-952210-xwj.picoclaw.lan.sipeed.com"
req.Header.Set("Origin", "https://fs-952210-xwj.picoclaw.lan.sipeed.com")
if got := h.buildWsURL(req); got != "ws://fs-952210-xwj.picoclaw.lan.sipeed.com:80/pico/ws" {
t.Fatalf(
"buildWsURL() = %q, want %q",
got,
"ws://fs-952210-xwj.picoclaw.lan.sipeed.com:80/pico/ws",
)
}
}
func TestBuildWsURLUsesRequestHostNotGatewayBindLoopback(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
h.SetServerOptions(18800, false, false, nil)
req := httptest.NewRequest("GET", "http://localhost:18800/api/pico/info", nil)
req.Host = "localhost:18800"
if got := h.buildWsURL(req); got != "ws://localhost:18800/pico/ws" {
t.Fatalf("buildWsURL() = %q, want %q", got, "ws://localhost:18800/pico/ws")
}
}
func TestGatewayHostOverrideWithExplicitHostAndAlignedGatewayHost(t *testing.T) {
h := NewHandler(filepath.Join(t.TempDir(), "config.json"))
h.SetServerOptions(18800, false, false, nil)
h.SetServerBindHost("0.0.0.0", true)
if got := h.gatewayHostOverride(); got != "0.0.0.0" {
t.Fatalf("gatewayHostOverride() = %q, want %q", got, "0.0.0.0")
}
}
func TestGatewayHostOverrideWithExplicitHostAndLocalhostGatewayHost(t *testing.T) {
h := NewHandler(filepath.Join(t.TempDir(), "config.json"))
h.SetServerOptions(18800, false, false, nil)
h.SetServerBindHost("::", true)
if got := h.gatewayHostOverride(); got != "::" {
t.Fatalf("gatewayHostOverride() = %q, want %q", got, "::")
}
}
func TestGatewayHostOverrideWithExplicitMultiHost(t *testing.T) {
h := NewHandler(filepath.Join(t.TempDir(), "config.json"))
h.SetServerOptions(18800, false, false, nil)
h.SetServerBindHost("127.0.0.1,::1", true)
if got := h.gatewayHostOverride(); got != "127.0.0.1,::1" {
t.Fatalf("gatewayHostOverride() = %q, want %q", got, "127.0.0.1,::1")
}
}
func TestGatewayHostExplicitIgnoresPublicFlag(t *testing.T) {
h := NewHandler(filepath.Join(t.TempDir(), "config.json"))
h.SetServerOptions(18800, true, true, nil)
h.SetServerBindHost("127.0.0.1", true)
if got := h.effectiveLauncherPublic(); got {
t.Fatalf("effectiveLauncherPublic() = %t, want false when explicit host is set", got)
}
}
File diff suppressed because it is too large. Load diff
-109
View File
@@ -1,109 +0,0 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"github.com/sipeed/picoclaw/web/backend/launcherconfig"
)
type launcherConfigPayload struct {
Port int `json:"port"`
Public bool `json:"public"`
AllowedCIDRs []string `json:"allowed_cidrs"`
AllowLocalhostBypass bool `json:"allow_localhost_bypass"`
TrustedProxyCIDRs []string `json:"trusted_proxy_cidrs"`
}
type launcherConfigUpdatePayload struct {
Port int `json:"port"`
Public bool `json:"public"`
AllowedCIDRs []string `json:"allowed_cidrs"`
AllowLocalhostBypass *bool `json:"allow_localhost_bypass"`
TrustedProxyCIDRs []string `json:"trusted_proxy_cidrs"`
}
func (h *Handler) registerLauncherConfigRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/system/launcher-config", h.handleGetLauncherConfig)
mux.HandleFunc("PUT /api/system/launcher-config", h.handleUpdateLauncherConfig)
}
func (h *Handler) launcherConfigPath() string {
return launcherconfig.PathForAppConfig(h.configPath)
}
func (h *Handler) launcherFallbackConfig() launcherconfig.Config {
port := h.serverPort
if port <= 0 {
port = launcherconfig.DefaultPort
}
return launcherconfig.Config{
Port: port,
Public: h.serverPublic,
AllowedCIDRs: append([]string(nil), h.serverCIDRs...),
AllowLocalhostBypass: h.serverAllowLocalhostBypass,
TrustedProxyCIDRs: append([]string(nil), h.serverTrustedProxyCIDRs...),
}
}
func (h *Handler) loadLauncherConfig() (launcherconfig.Config, error) {
return launcherconfig.Load(h.launcherConfigPath(), h.launcherFallbackConfig())
}
func (h *Handler) handleGetLauncherConfig(w http.ResponseWriter, r *http.Request) {
cfg, err := h.loadLauncherConfig()
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load launcher config: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(launcherConfigPayload{
Port: cfg.Port,
Public: cfg.Public,
AllowedCIDRs: append([]string(nil), cfg.AllowedCIDRs...),
AllowLocalhostBypass: cfg.AllowLocalhostBypass,
TrustedProxyCIDRs: append([]string(nil), cfg.TrustedProxyCIDRs...),
})
}
func (h *Handler) handleUpdateLauncherConfig(w http.ResponseWriter, r *http.Request) {
var payload launcherConfigUpdatePayload
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest)
return
}
cfg, err := h.loadLauncherConfig()
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load launcher config: %v", err), http.StatusInternalServerError)
return
}
cfg.Port = payload.Port
cfg.Public = payload.Public
cfg.AllowedCIDRs = append([]string(nil), payload.AllowedCIDRs...)
if payload.AllowLocalhostBypass != nil {
cfg.AllowLocalhostBypass = *payload.AllowLocalhostBypass
}
cfg.TrustedProxyCIDRs = append([]string(nil), payload.TrustedProxyCIDRs...)
cfg.LegacyLauncherToken = ""
if err := launcherconfig.Validate(cfg); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := launcherconfig.Save(h.launcherConfigPath(), cfg); err != nil {
http.Error(w, fmt.Sprintf("Failed to save launcher config: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(launcherConfigPayload{
Port: cfg.Port,
Public: cfg.Public,
AllowedCIDRs: append([]string(nil), cfg.AllowedCIDRs...),
AllowLocalhostBypass: cfg.AllowLocalhostBypass,
TrustedProxyCIDRs: append([]string(nil), cfg.TrustedProxyCIDRs...),
})
}
-236
View File
@@ -1,236 +0,0 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/sipeed/picoclaw/web/backend/launcherconfig"
)
func TestGetLauncherConfigUsesRuntimeFallback(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
h.SetServerOptions(19999, true, false, []string{"192.168.1.0/24"})
h.SetServerAccessOptions(false, []string{"10.0.0.0/8"})
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/system/launcher-config", nil)
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
var got launcherConfigPayload
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if got.Port != 19999 || !got.Public {
t.Fatalf("response = %+v, want port=19999 public=true", got)
}
if len(got.AllowedCIDRs) != 1 || got.AllowedCIDRs[0] != "192.168.1.0/24" {
t.Fatalf("response allowed_cidrs = %v, want [192.168.1.0/24]", got.AllowedCIDRs)
}
if got.AllowLocalhostBypass {
t.Fatalf("response allow_localhost_bypass = true, want false")
}
if len(got.TrustedProxyCIDRs) != 1 || got.TrustedProxyCIDRs[0] != "10.0.0.0/8" {
t.Fatalf("response trusted_proxy_cidrs = %v, want [10.0.0.0/8]", got.TrustedProxyCIDRs)
}
}
func TestPutLauncherConfigPersists(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
path := launcherconfig.PathForAppConfig(configPath)
if err := os.WriteFile(
path,
[]byte(`{"port":18800,"public":false,"dashboard_password_hash":"saved-hash","launcher_token":"legacy-token"}`),
0o600,
); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPut,
"/api/system/launcher-config",
strings.NewReader(
`{"port":18080,"public":true,"allowed_cidrs":["192.168.1.0/24"],"allow_localhost_bypass":false,"trusted_proxy_cidrs":["10.0.0.0/8"]}`,
),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
cfg, err := launcherconfig.Load(path, launcherconfig.Default())
if err != nil {
t.Fatalf("launcherconfig.Load() error = %v", err)
}
if cfg.Port != 18080 || !cfg.Public {
t.Fatalf("saved config = %+v, want port=18080 public=true", cfg)
}
if cfg.DashboardPasswordHash != "saved-hash" {
t.Fatalf("saved dashboard_password_hash = %q, want saved-hash", cfg.DashboardPasswordHash)
}
if cfg.LegacyLauncherToken != "" {
t.Fatalf("saved legacy launcher_token = %q, want empty", cfg.LegacyLauncherToken)
}
if len(cfg.AllowedCIDRs) != 1 || cfg.AllowedCIDRs[0] != "192.168.1.0/24" {
t.Fatalf("saved config allowed_cidrs = %v, want [192.168.1.0/24]", cfg.AllowedCIDRs)
}
if cfg.AllowLocalhostBypass {
t.Fatalf("saved config allow_localhost_bypass = true, want false")
}
if len(cfg.TrustedProxyCIDRs) != 1 || cfg.TrustedProxyCIDRs[0] != "10.0.0.0/8" {
t.Fatalf("saved config trusted_proxy_cidrs = %v, want [10.0.0.0/8]", cfg.TrustedProxyCIDRs)
}
}
func TestPutLauncherConfigUsesDirectAccessFields(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPut,
"/api/system/launcher-config",
strings.NewReader(
`{"port":18080,"public":false,"allowed_cidrs":["192.168.1.0/24"],"allow_localhost_bypass":true,"trusted_proxy_cidrs":["10.0.0.0/8"]}`,
),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
cfg, err := launcherconfig.Load(launcherconfig.PathForAppConfig(configPath), launcherconfig.Default())
if err != nil {
t.Fatalf("launcherconfig.Load() error = %v", err)
}
if !cfg.AllowLocalhostBypass {
t.Fatal("saved config allow_localhost_bypass = false, want true")
}
if len(cfg.TrustedProxyCIDRs) != 1 || cfg.TrustedProxyCIDRs[0] != "10.0.0.0/8" {
t.Fatalf("saved config trusted_proxy_cidrs = %v, want [10.0.0.0/8]", cfg.TrustedProxyCIDRs)
}
}
func TestPutLauncherConfigKeepsLocalhostBypassWhenOmitted(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
path := launcherconfig.PathForAppConfig(configPath)
if err := os.WriteFile(
path,
[]byte(`{"port":18800,"public":false,"allow_localhost_bypass":true,"trusted_proxy_cidrs":["10.0.0.0/8"]}`),
0o600,
); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPut,
"/api/system/launcher-config",
strings.NewReader(`{"port":18080,"public":true,"allowed_cidrs":["192.168.1.0/24"]}`),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
cfg, err := launcherconfig.Load(path, launcherconfig.Default())
if err != nil {
t.Fatalf("launcherconfig.Load() error = %v", err)
}
if !cfg.AllowLocalhostBypass {
t.Fatal("saved config allow_localhost_bypass = false, want true")
}
}
func TestPutLauncherConfigRejectsInvalidPort(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPut,
"/api/system/launcher-config",
strings.NewReader(`{"port":70000,"public":false}`),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
}
}
func TestPutLauncherConfigRejectsInvalidCIDR(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPut,
"/api/system/launcher-config",
strings.NewReader(`{"port":18080,"public":false,"allowed_cidrs":["bad-cidr"]}`),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
}
}
func TestPutLauncherConfigRejectsInvalidTrustedProxyCIDR(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPut,
"/api/system/launcher-config",
strings.NewReader(`{"port":18080,"public":false,"trusted_proxy_cidrs":["bad-cidr"]}`),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
}
}
-97
View File
@@ -1,97 +0,0 @@
package api
import "sync"
// LogBuffer is a thread-safe ring buffer that stores the most recent N log lines.
// It supports incremental reads via LinesSince and tracks a runID that increments
// whenever the buffer is reset or cleared so clients can detect log history resets.
type LogBuffer struct {
mu sync.RWMutex
lines []string
cap int
total int // total lines ever appended in current run
runID int
}
// NewLogBuffer creates a LogBuffer with the given capacity.
func NewLogBuffer(capacity int) *LogBuffer {
return &LogBuffer{
lines: make([]string, 0, capacity),
cap: capacity,
}
}
// Append adds a line to the buffer. If the buffer is full, the oldest line is evicted.
func (b *LogBuffer) Append(line string) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.lines) < b.cap {
b.lines = append(b.lines, line)
} else {
b.lines[b.total%b.cap] = line
}
b.total++
}
// Reset clears the buffer and increments the runID. Call this when starting a new gateway process.
func (b *LogBuffer) Reset() {
b.mu.Lock()
defer b.mu.Unlock()
b.lines = b.lines[:0]
b.total = 0
b.runID++
}
// Clear removes all buffered lines and increments the runID so clients treat
// subsequent reads as a new log stream.
func (b *LogBuffer) Clear() {
b.Reset()
}
// LinesSince returns lines appended after the given offset, the current total count, and the runID.
// If offset >= total, no lines are returned. If offset is too old (evicted), all buffered lines are returned.
func (b *LogBuffer) LinesSince(offset int) (lines []string, total int, runID int) {
b.mu.RLock()
defer b.mu.RUnlock()
total = b.total
runID = b.runID
if offset >= b.total {
return nil, total, runID
}
buffered := len(b.lines)
// How many new lines since offset
newCount := b.total - offset
if newCount > buffered {
newCount = buffered
}
result := make([]string, newCount)
if b.total <= b.cap {
// Buffer hasn't wrapped yet — simple slice
copy(result, b.lines[buffered-newCount:])
} else {
// Buffer has wrapped — read from ring
start := (b.total - newCount) % b.cap
for i := range newCount {
result[i] = b.lines[(start+i)%b.cap]
}
}
return result, total, runID
}
// RunID returns the current run identifier.
func (b *LogBuffer) RunID() int {
b.mu.RLock()
defer b.mu.RUnlock()
return b.runID
}
-171
View File
@@ -1,171 +0,0 @@
package api
import (
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/fileutil"
"github.com/sipeed/picoclaw/pkg/providers"
)
// CatalogModel represents a single model entry in a saved catalog.
type CatalogModel struct {
ID string `json:"id"`
OwnedBy string `json:"owned_by,omitempty"`
Extra map[string]any `json:"extra,omitempty"`
}
// CatalogEntry is a saved list of upstream models fetched for a specific provider+key combination.
type CatalogEntry struct {
ID string `json:"id"`
Provider string `json:"provider"`
APIBase string `json:"api_base"`
APIKeyMask string `json:"api_key_mask"`
Models []CatalogModel `json:"models"`
FetchedAt string `json:"fetched_at"`
}
// CatalogStore holds all saved model catalogs.
type CatalogStore struct {
Entries map[string]*CatalogEntry `json:"entries"`
}
func catalogFilePath() string {
return filepath.Join(config.GetHome(), "model_catalogs.json")
}
// generateCatalogKey creates a deterministic key for a provider+base+key combination.
func generateCatalogKey(provider, apiBase, apiKey string) string {
provider = providers.NormalizeProvider(provider)
apiBase = strings.TrimRight(strings.TrimSpace(apiBase), "/")
hash := sha256.Sum256([]byte(apiKey))
return fmt.Sprintf("%s|%s|%x", provider, apiBase, hash[:6])
}
// maskAPIKeyValue masks an API key for display.
// Keys longer than 12 chars show prefix + last 4 chars: "sk-****abcd".
// Keys 9-12 chars show prefix + last 2 chars: "sk-****cd".
// Shorter keys are fully masked as "****".
// Empty keys return empty string.
// Ensure at least 40% of the key will not be displayed.
func maskAPIKeyValue(key string) string {
key = strings.TrimSpace(key)
if key == "" {
return ""
}
if len(key) <= 8 {
return "****"
}
if len(key) <= 12 {
return key[:3] + "****" + key[len(key)-2:]
}
return key[:3] + "****" + key[len(key)-4:]
}
func loadCatalogs() (*CatalogStore, error) {
path := catalogFilePath()
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return &CatalogStore{Entries: make(map[string]*CatalogEntry)}, nil
}
return nil, err
}
var store CatalogStore
if err := json.Unmarshal(data, &store); err != nil {
return nil, err
}
if store.Entries == nil {
store.Entries = make(map[string]*CatalogEntry)
}
return &store, nil
}
func saveCatalogs(store *CatalogStore) error {
path := catalogFilePath()
data, err := json.MarshalIndent(store, "", " ")
if err != nil {
return err
}
return fileutil.WriteFileAtomic(path, data, 0o600)
}
// SaveCatalog persists a fetched model list for a given provider+key combination.
// If a catalog with the same key already exists, it is updated.
func SaveCatalog(provider, apiBase, apiKey string, models []CatalogModel) error {
store, err := loadCatalogs()
if err != nil {
return err
}
key := generateCatalogKey(provider, apiBase, apiKey)
provider = providers.NormalizeProvider(provider)
store.Entries[key] = &CatalogEntry{
ID: key,
Provider: provider,
APIBase: strings.TrimRight(strings.TrimSpace(apiBase), "/"),
APIKeyMask: maskAPIKeyValue(apiKey),
Models: models,
FetchedAt: time.Now().UTC().Format(time.RFC3339),
}
return saveCatalogs(store)
}
// handleListCatalogs returns all saved model catalogs.
//
// GET /api/models/catalog
func (h *Handler) handleListCatalogs(w http.ResponseWriter, r *http.Request) {
store, err := loadCatalogs()
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load catalogs: %v", err), http.StatusInternalServerError)
return
}
entries := make([]*CatalogEntry, 0, len(store.Entries))
for _, e := range store.Entries {
entries = append(entries, e)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"entries": entries,
"total": len(entries),
})
}
// handleDeleteCatalog deletes a saved model catalog by ID.
//
// DELETE /api/models/catalog/{id}
func (h *Handler) handleDeleteCatalog(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
store, err := loadCatalogs()
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load catalogs: %v", err), http.StatusInternalServerError)
return
}
if _, ok := store.Entries[id]; !ok {
http.Error(w, "catalog not found", http.StatusNotFound)
return
}
delete(store.Entries, id)
if err := saveCatalogs(store); err != nil {
http.Error(w, fmt.Sprintf("Failed to save catalogs: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
-87
View File
@@ -1,87 +0,0 @@
package api
import (
"strings"
"testing"
)
func TestMaskAPIKeyValue(t *testing.T) {
tests := []struct {
name string
key string
want string
}{
{
name: "empty key",
key: "",
want: "",
},
{
name: "whitespace only",
key: " ",
want: "",
},
{
name: "short key fully masked",
key: "abcd",
want: "****",
},
{
name: "length 8 boundary fully masked",
key: "12345678",
want: "****",
},
{
name: "length 9 boundary shows last 2",
key: "123456789",
want: "123****89",
},
{
name: "length 10 shows last 2",
key: "1234567890",
want: "123****90",
},
{
name: "length 12 boundary shows last 2",
key: "abcdefghijkl",
want: "abc****kl",
},
{
name: "length 13 boundary shows last 4",
key: "abcdefghijklm",
want: "abc****jklm",
},
{
name: "typical api key",
key: "sk-1234567890abcd",
want: "sk-****abcd",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := maskAPIKeyValue(tc.key)
if got != tc.want {
t.Fatalf("maskAPIKeyValue(%q) = %q, want %q", tc.key, got, tc.want)
}
if tc.key != "" {
displayed := strings.Replace(got, "****", "", 1)
if len(strings.TrimSpace(tc.key)) <= 8 {
if displayed != "" {
t.Fatalf("maskAPIKeyValue(%q) displayed part = %q, want empty", tc.key, displayed)
}
} else {
if len(displayed)*10 > len(strings.TrimSpace(tc.key))*6 {
t.Fatalf(
"maskAPIKeyValue(%q) displayed length = %d, want at most 60%% of %d",
tc.key,
len(displayed),
len(strings.TrimSpace(tc.key)),
)
}
}
}
})
}
}
-719
View File
@@ -1,719 +0,0 @@
package api
import (
"context"
"encoding/json"
"fmt"
"hash/fnv"
"net"
"net/http"
"net/url"
"os/exec"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/sync/singleflight"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/providers"
)
const (
modelProbeTimeout = 800 * time.Millisecond
modelProbeSuccessBaseInterval = 2 * time.Second
modelProbeSuccessMaxInterval = 60 * time.Second
modelProbeFailureBaseInterval = 1 * time.Second
modelProbeFailureMaxInterval = 30 * time.Second
modelProbeBackoffMaxShift = 8
modelProbeCacheMaxEntries = 1024
modelProbeCacheEntryTTL = 30 * time.Minute
modelProbeCacheTrimToEntries = modelProbeCacheMaxEntries * 8 / 10
modelProbeTTLGCInterval = 1 * time.Minute
)
const (
modelStatusAvailable = "available"
modelStatusUnconfigured = "unconfigured"
modelStatusUnreachable = "unreachable"
)
type modelConfigurationSummary struct {
Available bool
Status string
}
var (
probeTCPServiceFunc = probeTCPService
probeOllamaModelFunc = probeOllamaModel
probeOpenAICompatibleModelFunc = probeOpenAICompatibleModel
probeCommandAvailableFunc = probeCommandAvailable
modelProbeNowFunc = time.Now
modelProbeState = newModelProbeCacheState()
)
type modelProbeCacheState struct {
mu sync.RWMutex
cache map[string]*modelProbeCacheEntry
group singleflight.Group
nextTTLGCAt time.Time
}
type modelProbeCacheEntry struct {
lastResult bool
hasResult bool
successStreak int
failureStreak int
nextProbeAt time.Time
updatedAt time.Time
}
func newModelProbeCacheState() *modelProbeCacheState {
return &modelProbeCacheState{cache: map[string]*modelProbeCacheEntry{}}
}
func resetModelProbeCache() {
modelProbeState.resetForTest()
}
func (s *modelProbeCacheState) resetForTest() {
s.mu.Lock()
defer s.mu.Unlock()
s.cache = map[string]*modelProbeCacheEntry{}
s.nextTTLGCAt = time.Time{}
}
func hasModelConfiguration(m *config.ModelConfig) bool {
protocol := modelProtocol(m)
authMethod := strings.ToLower(strings.TrimSpace(m.AuthMethod))
apiKey := strings.TrimSpace(m.APIKey())
usesStoredAuth := authMethod == "oauth" || authMethod == "token"
if usesStoredAuth {
if configured, checked := hasStoredOAuthCredential(m); checked {
return configured
}
}
if authMethod == "" && providerUsesImplicitOAuth(protocol) {
if configured, checked := hasStoredOAuthCredential(m); checked {
return configured
}
}
if providerUsesAmbientCredentials(protocol) {
return true
}
if requiresRuntimeProbe(m) {
return true
}
if apiKey != "" {
return true
}
if usesStoredAuth {
return false
}
apiBase := strings.TrimSpace(m.APIBase)
if apiBase == "" {
return false
}
switch providers.NormalizeProvider(protocol) {
case "anthropic", "anthropic-messages", "alibaba-coding-anthropic":
return false
}
defaultBase := providers.DefaultAPIBaseForProtocol(protocol)
return defaultBase == "" ||
normalizeAPIBaseForCompare(apiBase) != normalizeAPIBaseForCompare(defaultBase)
}
func hasStoredOAuthCredential(m *config.ModelConfig) (bool, bool) {
provider, ok := oauthProviderForModel(m)
if !ok {
return false, false
}
cred, err := oauthGetCredential(provider)
if err != nil || cred == nil {
return false, true
}
return strings.TrimSpace(cred.AccessToken) != "" || strings.TrimSpace(cred.RefreshToken) != "", true
}
func providerUsesImplicitOAuth(protocol string) bool {
switch protocol {
case "antigravity":
return true
default:
return false
}
}
func providerUsesAmbientCredentials(protocol string) bool {
switch protocol {
case "bedrock":
// Bedrock relies on the AWS SDK credential chain instead of an explicit
// API key stored in ModelConfig. We cannot reliably preflight every AWS
// credential source here, so avoid misclassifying valid environments as
// "unconfigured" and defer concrete credential failures to runtime.
return true
default:
return false
}
}
func modelConfigurationStatus(m *config.ModelConfig) modelConfigurationSummary {
if !hasModelConfiguration(m) {
return modelConfigurationSummary{Available: false, Status: modelStatusUnconfigured}
}
if requiresRuntimeProbe(m) {
if probeLocalModelAvailability(m) {
return modelConfigurationSummary{Available: true, Status: modelStatusAvailable}
}
return modelConfigurationSummary{Available: false, Status: modelStatusUnreachable}
}
return modelConfigurationSummary{Available: true, Status: modelStatusAvailable}
}
func requiresRuntimeProbe(m *config.ModelConfig) bool {
authMethod := strings.ToLower(strings.TrimSpace(m.AuthMethod))
if authMethod == "local" {
return true
}
protocol := modelProtocol(m)
switch protocol {
case "claude-cli", "codex-cli", "github-copilot":
return true
}
if providers.IsHTTPAPIProtocol(protocol) && providers.IsEmptyAPIKeyAllowedForProtocol(protocol) {
apiBase := strings.TrimSpace(m.APIBase)
return apiBase == "" || hasLocalAPIBase(apiBase)
}
if hasLocalAPIBase(m.APIBase) {
return true
}
return false
}
func probeLocalModelAvailability(m *config.ModelConfig) bool {
cacheKey := modelProbeCacheKey(m)
return modelProbeState.probe(cacheKey, func() bool {
return runLocalModelProbe(m)
})
}
func (s *modelProbeCacheState) probe(cacheKey string, probeFunc func() bool) bool {
now := modelProbeNowFunc()
if cachedResult, ok := s.getCachedResult(cacheKey, now); ok {
return cachedResult
}
v, _, _ := s.group.Do(cacheKey, func() (any, error) {
now = modelProbeNowFunc()
if cachedResult, ok := s.getCachedResult(cacheKey, now); ok {
return cachedResult, nil
}
result := probeFunc()
s.setCachedResult(cacheKey, result, now)
return result, nil
})
result, ok := v.(bool)
if !ok {
return false
}
return result
}
func runLocalModelProbe(m *config.ModelConfig) bool {
apiBase := modelProbeAPIBase(m)
protocol, modelID := splitModel(m)
switch protocol {
case "ollama":
return probeOllamaModelFunc(apiBase, modelID)
case "vllm", "lmstudio", "gpt4free":
return probeOpenAICompatibleModelFunc(apiBase, modelID, m.APIKey())
case "github-copilot":
return probeTCPServiceFunc(apiBase)
case "claude-cli":
return probeCommandAvailableFunc("claude")
case "codex-cli":
return probeCommandAvailableFunc("codex")
default:
if hasLocalAPIBase(apiBase) {
return probeOpenAICompatibleModelFunc(apiBase, modelID, m.APIKey())
}
return false
}
}
func probeCommandAvailable(command string) bool {
_, err := exec.LookPath(command)
return err == nil
}
func modelProbeCacheKey(m *config.ModelConfig) string {
protocol, modelID := splitModel(m)
apiBaseRaw := modelProbeAPIBase(m)
apiBase := strings.ToLower(strings.TrimRight(strings.TrimSpace(apiBaseRaw), "/"))
apiKeyFingerprint := modelProbeAPIKeyFingerprint(m.APIKey())
var b strings.Builder
b.Grow(len(protocol) + len(modelID) + len(apiBase) + len(apiKeyFingerprint) + 8)
b.WriteString(protocol)
b.WriteByte('|')
b.WriteString(modelID)
b.WriteByte('|')
b.WriteString(apiBase)
b.WriteByte('|')
b.WriteString(apiKeyFingerprint)
return b.String()
}
func modelProbeAPIKeyFingerprint(raw string) string {
apiKey := strings.TrimSpace(raw)
if apiKey == "" {
return "none"
}
h := fnv.New64a()
_, _ = h.Write([]byte(apiKey))
return strconv.FormatUint(h.Sum64(), 36)
}
func (s *modelProbeCacheState) getCachedResult(cacheKey string, now time.Time) (bool, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
entry, ok := s.cache[cacheKey]
if !ok || !entry.hasResult {
return false, false
}
if now.Before(entry.nextProbeAt) {
return entry.lastResult, true
}
return false, false
}
func (s *modelProbeCacheState) setCachedResult(cacheKey string, result bool, now time.Time) {
s.mu.Lock()
entry, ok := s.cache[cacheKey]
if !ok {
entry = &modelProbeCacheEntry{}
s.cache[cacheKey] = entry
}
entry.lastResult = result
entry.hasResult = true
entry.updatedAt = now
var delay time.Duration
if result {
entry.successStreak++
entry.failureStreak = 0
delay = modelProbeBackoffDelay(
modelProbeSuccessBaseInterval,
modelProbeSuccessMaxInterval,
entry.successStreak,
)
} else {
entry.failureStreak++
entry.successStreak = 0
delay = modelProbeBackoffDelay(
modelProbeFailureBaseInterval,
modelProbeFailureMaxInterval,
entry.failureStreak,
)
}
entry.nextProbeAt = now.Add(delay)
shouldRunTTLGC := modelProbeCacheEntryTTL > 0 && (s.nextTTLGCAt.IsZero() || !now.Before(s.nextTTLGCAt))
if shouldRunTTLGC {
s.nextTTLGCAt = now.Add(modelProbeTTLGCInterval)
}
shouldRunSizeGC := len(s.cache) > modelProbeCacheMaxEntries
s.mu.Unlock()
if shouldRunTTLGC || shouldRunSizeGC {
s.gc(now, shouldRunTTLGC)
}
}
func (s *modelProbeCacheState) gc(now time.Time, runTTL bool) {
type evictionCandidate struct {
key string
updatedAt time.Time
}
var expireBefore time.Time
if runTTL && modelProbeCacheEntryTTL > 0 {
expireBefore = now.Add(-modelProbeCacheEntryTTL)
}
s.mu.RLock()
cacheLen := len(s.cache)
if cacheLen == 0 {
s.mu.RUnlock()
return
}
expiredKeys := make([]string, 0)
if !expireBefore.IsZero() {
expiredKeys = make([]string, 0, min(cacheLen/8+1, 64))
for key, entry := range s.cache {
if entry.updatedAt.Before(expireBefore) {
expiredKeys = append(expiredKeys, key)
}
}
}
effectiveLen := cacheLen - len(expiredKeys)
removeCount := max(effectiveLen-modelProbeCacheTrimToEntries, 0)
candidates := make([]evictionCandidate, 0)
if removeCount > 0 {
candidates = make([]evictionCandidate, 0, effectiveLen)
for key, entry := range s.cache {
if !expireBefore.IsZero() && entry.updatedAt.Before(expireBefore) {
continue
}
candidates = append(candidates, evictionCandidate{key: key, updatedAt: entry.updatedAt})
}
}
s.mu.RUnlock()
if len(expiredKeys) == 0 && len(candidates) == 0 {
return
}
toEvict := map[string]time.Time{}
for i := 0; i < removeCount && len(candidates) > 0; i++ {
oldest := 0
for j := 1; j < len(candidates); j++ {
if candidates[j].updatedAt.Before(candidates[oldest].updatedAt) {
oldest = j
}
}
victim := candidates[oldest]
toEvict[victim.key] = victim.updatedAt
candidates[oldest] = candidates[len(candidates)-1]
candidates = candidates[:len(candidates)-1]
}
s.mu.Lock()
defer s.mu.Unlock()
if !expireBefore.IsZero() {
for _, key := range expiredKeys {
entry, ok := s.cache[key]
if ok && entry.updatedAt.Before(expireBefore) {
delete(s.cache, key)
}
}
}
for key, victimUpdatedAt := range toEvict {
entry, ok := s.cache[key]
if ok && !entry.updatedAt.After(victimUpdatedAt) {
delete(s.cache, key)
}
}
}
func modelProbeBackoffDelay(base, maxDelay time.Duration, streak int) time.Duration {
if streak <= 0 {
streak = 1
}
shift := min(streak-1, modelProbeBackoffMaxShift)
delay := base * time.Duration(1<<shift)
if maxDelay > 0 && (delay > maxDelay || delay < 0) {
return maxDelay
}
if delay <= 0 {
return base
}
return delay
}
func modelProbeAPIBase(m *config.ModelConfig) string {
if apiBase := strings.TrimSpace(m.APIBase); apiBase != "" {
return normalizeModelProbeAPIBase(apiBase)
}
protocol := modelProtocol(m)
// Resolve the default API base for any known protocol so that probes
// work even when the config stores only a provider without an explicit api_base.
if defaultBase := providers.DefaultAPIBaseForProtocol(protocol); defaultBase != "" {
return normalizeModelProbeAPIBase(defaultBase)
}
switch protocol {
case "github-copilot":
return "localhost:4321"
default:
return ""
}
}
func normalizeModelProbeAPIBase(raw string) string {
u, err := parseAPIBase(raw)
if err != nil {
return strings.TrimSpace(raw)
}
switch strings.ToLower(u.Hostname()) {
case "0.0.0.0":
u.Host = net.JoinHostPort("127.0.0.1", u.Port())
case "::":
u.Host = net.JoinHostPort("::1", u.Port())
default:
return strings.TrimSpace(raw)
}
if u.Port() == "" {
u.Host = u.Hostname()
}
return u.String()
}
func oauthProviderForModel(m *config.ModelConfig) (string, bool) {
switch modelProtocol(m) {
case "openai":
return oauthProviderOpenAI, true
case "anthropic":
return oauthProviderAnthropic, true
case "antigravity":
return oauthProviderGoogleAntigravity, true
default:
return "", false
}
}
func modelProtocol(m *config.ModelConfig) string {
protocol, _ := splitModel(m)
return protocol
}
func splitModel(m *config.ModelConfig) (protocol, modelID string) {
protocol, modelID = providers.ExtractProtocol(m)
return strings.ToLower(strings.TrimSpace(protocol)), strings.ToLower(strings.TrimSpace(modelID))
}
func hasLocalAPIBase(raw string) bool {
raw = strings.TrimSpace(raw)
if raw == "" {
return false
}
u, err := url.Parse(raw)
if err != nil || u.Hostname() == "" {
u, err = url.Parse("//" + raw)
if err != nil {
return false
}
}
switch strings.ToLower(u.Hostname()) {
case "localhost", "127.0.0.1", "::1", "0.0.0.0":
return true
default:
return false
}
}
func probeTCPService(raw string) bool {
hostPort, err := hostPortFromAPIBase(raw)
if err != nil {
return false
}
ctx, cancel := context.WithTimeout(context.Background(), modelProbeTimeout)
defer cancel()
dialer := &net.Dialer{}
conn, err := dialer.DialContext(ctx, "tcp", hostPort)
if err != nil {
return false
}
_ = conn.Close()
return true
}
func probeOllamaModel(apiBase, modelID string) bool {
root, err := apiRootFromAPIBase(apiBase)
if err != nil {
return false
}
var resp struct {
Models []struct {
Name string `json:"name"`
Model string `json:"model"`
} `json:"models"`
}
if err := getJSON(root+"/api/tags", &resp, ""); err != nil {
return false
}
for _, model := range resp.Models {
if ollamaModelMatches(model.Name, modelID) || ollamaModelMatches(model.Model, modelID) {
return true
}
}
return false
}
func probeOpenAICompatibleModel(apiBase, modelID, apiKey string) bool {
if strings.TrimSpace(apiBase) == "" {
return false
}
var respEnvelope struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
fetchURL := strings.TrimRight(strings.TrimSpace(apiBase), "/") + "/models"
if err := getJSON(fetchURL, &respEnvelope, apiKey); err == nil {
for _, model := range respEnvelope.Data {
if strings.EqualFold(strings.TrimSpace(model.ID), modelID) {
return true
}
}
return false
}
var respArray []struct {
ID string `json:"id"`
}
if err := getJSON(fetchURL, &respArray, apiKey); err != nil {
return false
}
for _, model := range respArray {
if strings.EqualFold(strings.TrimSpace(model.ID), modelID) {
return true
}
}
return false
}
func getJSON(rawURL string, out any, apiKey string) error {
ctx, cancel := context.WithTimeout(context.Background(), modelProbeTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return err
}
if apiKey = strings.TrimSpace(apiKey); apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status %d", resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(out)
}
func apiRootFromAPIBase(raw string) (string, error) {
u, err := parseAPIBase(raw)
if err != nil {
return "", err
}
return (&url.URL{Scheme: u.Scheme, Host: u.Host}).String(), nil
}
func hostPortFromAPIBase(raw string) (string, error) {
u, err := parseAPIBase(raw)
if err != nil {
return "", err
}
if port := u.Port(); port != "" {
return u.Host, nil
}
switch strings.ToLower(u.Scheme) {
case "https":
return net.JoinHostPort(u.Hostname(), "443"), nil
default:
return net.JoinHostPort(u.Hostname(), "80"), nil
}
}
func parseAPIBase(raw string) (*url.URL, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return nil, fmt.Errorf("empty api base")
}
u, err := url.Parse(raw)
if err == nil && u.Hostname() != "" {
return u, nil
}
u, err = url.Parse("//" + raw)
if err != nil || u.Hostname() == "" {
return nil, fmt.Errorf("invalid api base %q", raw)
}
if u.Scheme == "" {
u.Scheme = "http"
}
return u, nil
}
func ollamaModelMatches(candidate, want string) bool {
candidate = strings.TrimSpace(candidate)
want = strings.TrimSpace(want)
if candidate == "" || want == "" {
return false
}
candidateBase, candidateTag := splitOllamaModel(candidate)
wantBase, wantTag := splitOllamaModel(want)
if candidateBase == "" || wantBase == "" {
return false
}
if candidateTag == "" {
candidateTag = "latest"
}
if wantTag == "" {
wantTag = "latest"
}
return strings.EqualFold(candidateBase, wantBase) && strings.EqualFold(candidateTag, wantTag)
}
func splitOllamaModel(raw string) (base, tag string) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", ""
}
base, tag, _ = strings.Cut(raw, ":")
return strings.TrimSpace(base), strings.TrimSpace(tag)
}
-460
View File
@@ -1,460 +0,0 @@
package api
import (
"fmt"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/sipeed/picoclaw/pkg/config"
)
func TestProbeLocalModelAvailability_OpenAICompatibleIncludesAPIKey(t *testing.T) {
const apiKey = "test-api-key"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/models" {
t.Fatalf("path = %q, want %q", r.URL.Path, "/v1/models")
}
if got := r.Header.Get("Authorization"); got != "Bearer "+apiKey {
http.Error(w, "missing auth", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":"custom-model"}]}`))
}))
defer srv.Close()
model := &config.ModelConfig{
Model: "openai/custom-model",
APIBase: srv.URL + "/v1",
}
model.SetAPIKey(apiKey)
if !probeLocalModelAvailability(model) {
t.Fatal("probeLocalModelAvailability() = false, want true when api_key is configured")
}
}
func TestProbeOpenAICompatibleModel_SupportsBareArrayModels(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/models" {
t.Fatalf("path = %q, want %q", r.URL.Path, "/v1/models")
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `[{"id":"gpt-4o-mini"},{"id":"deepseek-r1"}]`)
}))
defer srv.Close()
if !probeOpenAICompatibleModel(srv.URL+"/v1", "gpt-4o-mini", "") {
t.Fatal("probeOpenAICompatibleModel() = false, want true for bare array /models response")
}
}
func TestRequiresRuntimeProbe_LMStudio(t *testing.T) {
if !requiresRuntimeProbe(&config.ModelConfig{
Model: "lmstudio/openai/gpt-oss-20b",
}) {
t.Fatal("requiresRuntimeProbe(lmstudio with default base) = false, want true")
}
if requiresRuntimeProbe(&config.ModelConfig{
Model: "lmstudio/openai/gpt-oss-20b",
APIBase: "https://api.example.com/v1",
}) {
t.Fatal("requiresRuntimeProbe(lmstudio with remote base) = true, want false")
}
}
func TestRequiresRuntimeProbe_GPT4Free(t *testing.T) {
if !requiresRuntimeProbe(&config.ModelConfig{
Model: "gpt4free/gpt-4o-mini",
}) {
t.Fatal("requiresRuntimeProbe(gpt4free with default base) = false, want true")
}
if requiresRuntimeProbe(&config.ModelConfig{
Model: "gpt4free/gpt-4o-mini",
APIBase: "https://g4f.space/v1",
}) {
t.Fatal("requiresRuntimeProbe(gpt4free with remote base) = true, want false")
}
}
func TestModelProbeAPIBase_LMStudioDefault(t *testing.T) {
got := modelProbeAPIBase(&config.ModelConfig{Model: "lmstudio/openai/gpt-oss-20b"})
if got != "http://localhost:1234/v1" {
t.Fatalf("modelProbeAPIBase(lmstudio) = %q, want %q", got, "http://localhost:1234/v1")
}
}
func TestModelProbeAPIBase_GPT4FreeDefault(t *testing.T) {
got := modelProbeAPIBase(&config.ModelConfig{Model: "gpt4free/gpt-4o-mini"})
if got != "http://localhost:1337/v1" {
t.Fatalf("modelProbeAPIBase(gpt4free) = %q, want %q", got, "http://localhost:1337/v1")
}
}
func TestProbeLocalModelAvailability_LMStudioUsesOpenAICompatibleProbe(t *testing.T) {
originalProbe := probeOpenAICompatibleModelFunc
defer func() { probeOpenAICompatibleModelFunc = originalProbe }()
called := false
probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool {
called = true
if apiBase != "http://localhost:1234/v1" {
t.Fatalf("apiBase = %q, want %q", apiBase, "http://localhost:1234/v1")
}
if modelID != "openai/gpt-oss-20b" {
t.Fatalf("modelID = %q, want %q", modelID, "openai/gpt-oss-20b")
}
if apiKey != "" {
t.Fatalf("apiKey = %q, want empty", apiKey)
}
return true
}
model := &config.ModelConfig{Model: "lmstudio/openai/gpt-oss-20b"}
if !probeLocalModelAvailability(model) {
t.Fatal("probeLocalModelAvailability(lmstudio) = false, want true")
}
if !called {
t.Fatal("probeOpenAICompatibleModelFunc was not called for lmstudio")
}
}
func TestProbeLocalModelAvailability_GPT4FreeUsesOpenAICompatibleProbe(t *testing.T) {
originalProbe := probeOpenAICompatibleModelFunc
defer func() { probeOpenAICompatibleModelFunc = originalProbe }()
called := false
probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool {
called = true
if apiBase != "http://localhost:1337/v1" {
t.Fatalf("apiBase = %q, want %q", apiBase, "http://localhost:1337/v1")
}
if modelID != "gpt-4o-mini" {
t.Fatalf("modelID = %q, want %q", modelID, "gpt-4o-mini")
}
if apiKey != "" {
t.Fatalf("apiKey = %q, want empty", apiKey)
}
return true
}
model := &config.ModelConfig{Model: "gpt4free/gpt-4o-mini"}
if !probeLocalModelAvailability(model) {
t.Fatal("probeLocalModelAvailability(gpt4free) = false, want true")
}
if !called {
t.Fatal("probeOpenAICompatibleModelFunc was not called for gpt4free")
}
}
func TestModelProbeCacheKey_DifferentAPIKeysProduceDifferentKeys(t *testing.T) {
base := &config.ModelConfig{
ModelName: "local-vllm",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1",
AuthMethod: "local",
ConnectMode: "",
}
m1 := *base
m1.SetAPIKey("key-a")
m2 := *base
m2.SetAPIKey("key-b")
k1 := modelProbeCacheKey(&m1)
k2 := modelProbeCacheKey(&m2)
if k1 == k2 {
t.Fatal("modelProbeCacheKey() should differ when api key changes")
}
}
func TestModelProbeCacheKey_NormalizesTrailingSlashInAPIBase(t *testing.T) {
m1 := &config.ModelConfig{
ModelName: "local-vllm",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1",
}
m2 := &config.ModelConfig{
ModelName: "local-vllm",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1/",
}
k1 := modelProbeCacheKey(m1)
k2 := modelProbeCacheKey(m2)
if k1 != k2 {
t.Fatalf("modelProbeCacheKey() mismatch for equivalent api_base values: %q vs %q", k1, k2)
}
}
func TestModelProbeCacheKey_IgnoresDisplayAndConnectionFields(t *testing.T) {
base := &config.ModelConfig{
ModelName: "vllm-one",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1",
AuthMethod: "none",
ConnectMode: "http",
}
changed := &config.ModelConfig{
ModelName: "vllm-two",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1",
AuthMethod: "token",
ConnectMode: "ws",
}
k1 := modelProbeCacheKey(base)
k2 := modelProbeCacheKey(changed)
if k1 != k2 {
t.Fatalf("modelProbeCacheKey() should ignore non-probe fields, got %q vs %q", k1, k2)
}
}
func TestProbeLocalModelAvailability_SuccessBackoff(t *testing.T) {
resetModelProbeHooks(t)
now := time.Unix(1700000000, 0)
modelProbeNowFunc = func() time.Time { return now }
calls := 0
probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool {
calls++
return true
}
model := &config.ModelConfig{
ModelName: "local-vllm",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1",
}
if !probeLocalModelAvailability(model) {
t.Fatal("first probe result = false, want true")
}
if calls != 1 {
t.Fatalf("probe calls after first probe = %d, want 1", calls)
}
if !probeLocalModelAvailability(model) {
t.Fatal("cached probe result = false, want true")
}
if calls != 1 {
t.Fatalf("probe calls after immediate re-check = %d, want 1", calls)
}
now = now.Add(modelProbeSuccessBaseInterval)
if !probeLocalModelAvailability(model) {
t.Fatal("second probe result = false, want true")
}
if calls != 2 {
t.Fatalf("probe calls after success backoff window = %d, want 2", calls)
}
now = now.Add(modelProbeSuccessBaseInterval)
if !probeLocalModelAvailability(model) {
t.Fatal("cached result after doubled backoff = false, want true")
}
if calls != 2 {
t.Fatalf("probe calls before doubled backoff expires = %d, want 2", calls)
}
now = now.Add(modelProbeSuccessBaseInterval)
if !probeLocalModelAvailability(model) {
t.Fatal("third probe result = false, want true")
}
if calls != 3 {
t.Fatalf("probe calls after doubled backoff expires = %d, want 3", calls)
}
}
func TestProbeLocalModelAvailability_FailureBackoff(t *testing.T) {
resetModelProbeHooks(t)
now := time.Unix(1700000100, 0)
modelProbeNowFunc = func() time.Time { return now }
calls := 0
probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool {
calls++
return false
}
model := &config.ModelConfig{
ModelName: "local-vllm",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1",
}
if probeLocalModelAvailability(model) {
t.Fatal("first probe result = true, want false")
}
if calls != 1 {
t.Fatalf("probe calls after first failure = %d, want 1", calls)
}
if probeLocalModelAvailability(model) {
t.Fatal("cached failed probe result = true, want false")
}
if calls != 1 {
t.Fatalf("probe calls after immediate failed re-check = %d, want 1", calls)
}
now = now.Add(modelProbeFailureBaseInterval)
if probeLocalModelAvailability(model) {
t.Fatal("second failed probe result = true, want false")
}
if calls != 2 {
t.Fatalf("probe calls after failure backoff window = %d, want 2", calls)
}
now = now.Add(modelProbeFailureBaseInterval)
if probeLocalModelAvailability(model) {
t.Fatal("cached failure after doubled backoff = true, want false")
}
if calls != 2 {
t.Fatalf("probe calls before doubled failure backoff expires = %d, want 2", calls)
}
now = now.Add(modelProbeFailureBaseInterval)
if probeLocalModelAvailability(model) {
t.Fatal("third failed probe result = true, want false")
}
if calls != 3 {
t.Fatalf("probe calls after doubled failure backoff expires = %d, want 3", calls)
}
}
func TestProbeLocalModelAvailability_ResultFlipResetsBackoff(t *testing.T) {
resetModelProbeHooks(t)
now := time.Unix(1700000200, 0)
modelProbeNowFunc = func() time.Time { return now }
results := []bool{true, false, false}
index := 0
probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool {
if index >= len(results) {
return false
}
result := results[index]
index++
return result
}
model := &config.ModelConfig{
ModelName: "local-vllm",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1",
}
if !probeLocalModelAvailability(model) {
t.Fatal("first probe result = false, want true")
}
now = now.Add(modelProbeSuccessBaseInterval)
if probeLocalModelAvailability(model) {
t.Fatal("second probe result = true, want false")
}
now = now.Add(modelProbeFailureBaseInterval)
if probeLocalModelAvailability(model) {
t.Fatal("third probe result = true, want false")
}
if index != 3 {
t.Fatalf("probe invocations = %d, want 3", index)
}
}
func TestProbeLocalModelAvailability_DeduplicatesInflightProbe(t *testing.T) {
resetModelProbeHooks(t)
now := time.Unix(1700000300, 0)
modelProbeNowFunc = func() time.Time { return now }
var calls int32
probeStarted := make(chan struct{})
releaseProbe := make(chan struct{})
probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool {
if atomic.AddInt32(&calls, 1) == 1 {
close(probeStarted)
}
<-releaseProbe
return true
}
model := &config.ModelConfig{
ModelName: "local-vllm",
Model: "vllm/custom-model",
APIBase: "http://127.0.0.1:8000/v1",
}
const workers = 8
var wg sync.WaitGroup
results := make(chan bool, workers)
workerStarted := make(chan struct{}, workers)
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
workerStarted <- struct{}{}
results <- probeLocalModelAvailability(model)
}()
}
for range workers {
<-workerStarted
}
select {
case <-probeStarted:
case <-time.After(200 * time.Millisecond):
t.Fatal("probe did not start in time")
}
if got := atomic.LoadInt32(&calls); got != 1 {
t.Fatalf("concurrent probe calls = %d, want 1", got)
}
close(releaseProbe)
wg.Wait()
close(results)
for result := range results {
if !result {
t.Fatal("deduplicated probe result = false, want true")
}
}
if got := atomic.LoadInt32(&calls); got != 1 {
t.Fatalf("final probe calls = %d, want 1", got)
}
}
func TestOllamaModelMatches_WithTagRequiresExactTag(t *testing.T) {
if ollamaModelMatches("llama3:8b", "llama3:7b") {
t.Fatal("ollamaModelMatches() = true, want false for mismatched tags")
}
if !ollamaModelMatches("llama3:7b", "llama3:7b") {
t.Fatal("ollamaModelMatches() = false, want true for exact tagged match")
}
if ollamaModelMatches("llama3:8b", "llama3") {
t.Fatal("ollamaModelMatches() = true, want false when request omits tag (defaults to latest)")
}
if !ollamaModelMatches("llama3:latest", "llama3") {
t.Fatal("ollamaModelMatches() = false, want true when request omits tag and candidate is latest")
}
if !ollamaModelMatches("llama3", "llama3") {
t.Fatal("ollamaModelMatches() = false, want true when both candidate and request omit tag (latest)")
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-833
View File
@@ -1,833 +0,0 @@
package api
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"html"
"io"
"net/http"
"strings"
"time"
"github.com/sipeed/picoclaw/pkg/auth"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/logger"
"github.com/sipeed/picoclaw/pkg/providers"
)
const (
oauthProviderOpenAI = "openai"
oauthProviderAnthropic = "anthropic"
oauthProviderGoogleAntigravity = "google-antigravity"
oauthMethodBrowser = "browser"
oauthMethodDeviceCode = "device_code"
oauthMethodToken = "token"
oauthFlowPending = "pending"
oauthFlowSuccess = "success"
oauthFlowError = "error"
oauthFlowExpired = "expired"
)
const (
oauthBrowserFlowTTL = 10 * time.Minute
oauthDeviceCodeFlowTTL = 15 * time.Minute
oauthTerminalFlowGC = 30 * time.Minute
)
var oauthProviderOrder = []string{
oauthProviderOpenAI,
oauthProviderAnthropic,
oauthProviderGoogleAntigravity,
}
var oauthProviderMethods = map[string][]string{
oauthProviderOpenAI: {oauthMethodBrowser, oauthMethodDeviceCode, oauthMethodToken},
oauthProviderAnthropic: {oauthMethodToken},
oauthProviderGoogleAntigravity: {oauthMethodBrowser},
}
var oauthProviderLabels = map[string]string{
oauthProviderOpenAI: "OpenAI",
oauthProviderAnthropic: "Anthropic",
oauthProviderGoogleAntigravity: "Google Antigravity",
}
var (
oauthNow = time.Now
oauthGeneratePKCE = auth.GeneratePKCE
oauthGenerateState = auth.GenerateState
oauthBuildAuthorizeURL = auth.BuildAuthorizeURL
oauthRequestDeviceCode = auth.RequestDeviceCode
oauthPollDeviceCodeOnce = auth.PollDeviceCodeOnce
oauthExchangeCodeForTokens = auth.ExchangeCodeForTokens
oauthGetCredential = auth.GetCredential
oauthSetCredential = auth.SetCredential
oauthDeleteCredential = auth.DeleteCredential
oauthLoadConfig = config.LoadConfig
oauthSaveConfig = config.SaveConfig
oauthFetchAntigravityProject = providers.FetchAntigravityProjectID
oauthFetchGoogleUserEmailFunc = fetchGoogleUserEmail
)
type oauthFlow struct {
ID string
Provider string
Method string
Status string
CreatedAt time.Time
UpdatedAt time.Time
ExpiresAt time.Time
Error string
CodeVerifier string
OAuthState string
RedirectURI string
DeviceAuthID string
UserCode string
VerifyURL string
Interval int
}
type oauthProviderStatus struct {
Provider string `json:"provider"`
DisplayName string `json:"display_name"`
Methods []string `json:"methods"`
LoggedIn bool `json:"logged_in"`
Status string `json:"status"`
AuthMethod string `json:"auth_method,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
AccountID string `json:"account_id,omitempty"`
Email string `json:"email,omitempty"`
ProjectID string `json:"project_id,omitempty"`
}
type oauthFlowResponse struct {
FlowID string `json:"flow_id"`
Provider string `json:"provider"`
Method string `json:"method"`
Status string `json:"status"`
ExpiresAt string `json:"expires_at,omitempty"`
Error string `json:"error,omitempty"`
UserCode string `json:"user_code,omitempty"`
VerifyURL string `json:"verify_url,omitempty"`
Interval int `json:"interval,omitempty"`
}
// registerOAuthRoutes binds OAuth login/logout endpoints to the ServeMux.
func (h *Handler) registerOAuthRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/oauth/providers", h.handleListOAuthProviders)
mux.HandleFunc("POST /api/oauth/login", h.handleOAuthLogin)
mux.HandleFunc("GET /api/oauth/flows/{id}", h.handleGetOAuthFlow)
mux.HandleFunc("POST /api/oauth/flows/{id}/poll", h.handlePollOAuthFlow)
mux.HandleFunc("POST /api/oauth/logout", h.handleOAuthLogout)
mux.HandleFunc("GET /oauth/callback", h.handleOAuthCallback)
}
func (h *Handler) handleListOAuthProviders(w http.ResponseWriter, r *http.Request) {
providersResp := make([]oauthProviderStatus, 0, len(oauthProviderOrder))
for _, provider := range oauthProviderOrder {
cred, err := oauthGetCredential(provider)
if err != nil {
http.Error(w, fmt.Sprintf("failed to load credentials: %v", err), http.StatusInternalServerError)
return
}
item := oauthProviderStatus{
Provider: provider,
DisplayName: oauthProviderLabels[provider],
Methods: oauthProviderMethods[provider],
Status: "not_logged_in",
}
if cred != nil {
item.LoggedIn = true
item.AuthMethod = cred.AuthMethod
item.AccountID = cred.AccountID
item.Email = cred.Email
item.ProjectID = cred.ProjectID
if !cred.ExpiresAt.IsZero() {
item.ExpiresAt = cred.ExpiresAt.Format(time.RFC3339)
}
switch {
case cred.IsExpired():
item.Status = "expired"
case cred.NeedsRefresh():
item.Status = "needs_refresh"
default:
item.Status = "connected"
}
}
providersResp = append(providersResp, item)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"providers": providersResp,
})
}
func (h *Handler) handleOAuthLogin(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var req struct {
Provider string `json:"provider"`
Method string `json:"method"`
Token string `json:"token"`
}
if err = json.Unmarshal(body, &req); err != nil {
http.Error(w, fmt.Sprintf("invalid JSON: %v", err), http.StatusBadRequest)
return
}
provider, err := normalizeOAuthProvider(req.Provider)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
method := strings.ToLower(strings.TrimSpace(req.Method))
if !isOAuthMethodSupported(provider, method) {
http.Error(
w,
fmt.Sprintf("unsupported login method %q for provider %q", method, provider),
http.StatusBadRequest,
)
return
}
switch method {
case oauthMethodToken:
token := strings.TrimSpace(req.Token)
if token == "" {
http.Error(w, "token is required", http.StatusBadRequest)
return
}
cred := &auth.AuthCredential{
AccessToken: token,
Provider: provider,
AuthMethod: oauthMethodToken,
}
if err := h.persistCredentialAndConfig(provider, oauthMethodToken, cred); err != nil {
http.Error(w, fmt.Sprintf("token login failed: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"status": "ok",
"provider": provider,
"method": method,
})
return
case oauthMethodDeviceCode:
cfg := auth.OpenAIOAuthConfig()
info, err := oauthRequestDeviceCode(cfg)
if err != nil {
http.Error(w, fmt.Sprintf("failed to request device code: %v", err), http.StatusInternalServerError)
return
}
now := oauthNow()
flow := &oauthFlow{
ID: newOAuthFlowID(),
Provider: provider,
Method: method,
Status: oauthFlowPending,
CreatedAt: now,
UpdatedAt: now,
ExpiresAt: now.Add(oauthDeviceCodeFlowTTL),
DeviceAuthID: info.DeviceAuthID,
UserCode: info.UserCode,
VerifyURL: info.VerifyURL,
Interval: info.Interval,
}
h.storeOAuthFlow(flow)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"status": "ok",
"provider": provider,
"method": method,
"flow_id": flow.ID,
"user_code": flow.UserCode,
"verify_url": flow.VerifyURL,
"interval": flow.Interval,
"expires_at": flow.ExpiresAt.Format(time.RFC3339),
})
return
case oauthMethodBrowser:
cfg, err := oauthConfigForProvider(provider)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
pkce, err := oauthGeneratePKCE()
if err != nil {
http.Error(w, fmt.Sprintf("failed to generate PKCE: %v", err), http.StatusInternalServerError)
return
}
state, err := oauthGenerateState()
if err != nil {
http.Error(w, fmt.Sprintf("failed to generate state: %v", err), http.StatusInternalServerError)
return
}
redirectURI := buildOAuthRedirectURI(r)
authURL := oauthBuildAuthorizeURL(cfg, pkce, state, redirectURI)
now := oauthNow()
flow := &oauthFlow{
ID: newOAuthFlowID(),
Provider: provider,
Method: method,
Status: oauthFlowPending,
CreatedAt: now,
UpdatedAt: now,
ExpiresAt: now.Add(oauthBrowserFlowTTL),
CodeVerifier: pkce.CodeVerifier,
OAuthState: state,
RedirectURI: redirectURI,
}
h.storeOAuthFlow(flow)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"status": "ok",
"provider": provider,
"method": method,
"flow_id": flow.ID,
"auth_url": authURL,
"expires_at": flow.ExpiresAt.Format(time.RFC3339),
})
return
default:
http.Error(w, "unsupported login method", http.StatusBadRequest)
}
}
func (h *Handler) handleGetOAuthFlow(w http.ResponseWriter, r *http.Request) {
flowID := strings.TrimSpace(r.PathValue("id"))
if flowID == "" {
http.Error(w, "missing flow id", http.StatusBadRequest)
return
}
flow, ok := h.getOAuthFlow(flowID)
if !ok {
http.Error(w, "flow not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(flowToResponse(flow))
}
func (h *Handler) handlePollOAuthFlow(w http.ResponseWriter, r *http.Request) {
flowID := strings.TrimSpace(r.PathValue("id"))
if flowID == "" {
http.Error(w, "missing flow id", http.StatusBadRequest)
return
}
flow, ok := h.getOAuthFlow(flowID)
if !ok {
http.Error(w, "flow not found", http.StatusNotFound)
return
}
if flow.Method != oauthMethodDeviceCode {
http.Error(w, "flow does not support polling", http.StatusBadRequest)
return
}
if flow.Status != oauthFlowPending {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(flowToResponse(flow))
return
}
cfg := auth.OpenAIOAuthConfig()
cred, err := oauthPollDeviceCodeOnce(cfg, flow.DeviceAuthID, flow.UserCode)
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "pending") {
updated, _ := h.getOAuthFlow(flowID)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(flowToResponse(updated))
return
}
h.setOAuthFlowError(flowID, fmt.Sprintf("device code poll failed: %v", err))
updated, _ := h.getOAuthFlow(flowID)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(flowToResponse(updated))
return
}
if cred == nil {
updated, _ := h.getOAuthFlow(flowID)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(flowToResponse(updated))
return
}
if err := h.persistCredentialAndConfig(flow.Provider, oauthMethodTokenOrOAuth(flow.Method), cred); err != nil {
h.setOAuthFlowError(flowID, fmt.Sprintf("failed to save credential: %v", err))
updated, _ := h.getOAuthFlow(flowID)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(flowToResponse(updated))
return
}
h.setOAuthFlowSuccess(flowID)
updated, _ := h.getOAuthFlow(flowID)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(flowToResponse(updated))
}
func (h *Handler) handleOAuthCallback(w http.ResponseWriter, r *http.Request) {
state := strings.TrimSpace(r.URL.Query().Get("state"))
if state == "" {
renderOAuthCallbackPage(w, "", oauthFlowError, "Missing state", "missing_state")
return
}
flow, ok := h.getOAuthFlowByState(state)
if !ok {
renderOAuthCallbackPage(w, "", oauthFlowError, "OAuth flow not found", "flow_not_found")
return
}
if flow.Status != oauthFlowPending {
renderOAuthCallbackPage(w, flow.ID, flow.Status, "Flow already completed", flow.Error)
return
}
if errMsg := strings.TrimSpace(r.URL.Query().Get("error")); errMsg != "" {
if desc := strings.TrimSpace(r.URL.Query().Get("error_description")); desc != "" {
errMsg += ": " + desc
}
h.setOAuthFlowError(flow.ID, errMsg)
renderOAuthCallbackPage(w, flow.ID, oauthFlowError, "Authorization failed", errMsg)
return
}
code := strings.TrimSpace(r.URL.Query().Get("code"))
if code == "" {
h.setOAuthFlowError(flow.ID, "missing authorization code")
renderOAuthCallbackPage(w, flow.ID, oauthFlowError, "Missing authorization code", "missing_code")
return
}
cfg, err := oauthConfigForProvider(flow.Provider)
if err != nil {
h.setOAuthFlowError(flow.ID, err.Error())
renderOAuthCallbackPage(w, flow.ID, oauthFlowError, "Unsupported provider", err.Error())
return
}
cred, err := oauthExchangeCodeForTokens(cfg, code, flow.CodeVerifier, flow.RedirectURI)
if err != nil {
h.setOAuthFlowError(flow.ID, fmt.Sprintf("token exchange failed: %v", err))
renderOAuthCallbackPage(w, flow.ID, oauthFlowError, "Token exchange failed", err.Error())
return
}
if err := h.persistCredentialAndConfig(flow.Provider, oauthMethodTokenOrOAuth(flow.Method), cred); err != nil {
h.setOAuthFlowError(flow.ID, fmt.Sprintf("failed to save credential: %v", err))
renderOAuthCallbackPage(w, flow.ID, oauthFlowError, "Failed to save credential", err.Error())
return
}
h.setOAuthFlowSuccess(flow.ID)
renderOAuthCallbackPage(w, flow.ID, oauthFlowSuccess, "Authentication successful", "")
}
func (h *Handler) handleOAuthLogout(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var req struct {
Provider string `json:"provider"`
}
if err = json.Unmarshal(body, &req); err != nil {
http.Error(w, fmt.Sprintf("invalid JSON: %v", err), http.StatusBadRequest)
return
}
provider, err := normalizeOAuthProvider(req.Provider)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := oauthDeleteCredential(provider); err != nil {
http.Error(w, fmt.Sprintf("failed to delete credential: %v", err), http.StatusInternalServerError)
return
}
if err := h.syncProviderAuthMethod(provider, ""); err != nil {
http.Error(w, fmt.Sprintf("failed to update config: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"status": "ok",
"provider": provider,
})
}
func renderOAuthCallbackPage(w http.ResponseWriter, flowID, status, title, errMsg string) {
payload := map[string]string{
"type": "picoclaw-oauth-result",
"flowId": flowID,
"status": status,
}
if errMsg != "" {
payload["error"] = errMsg
}
payloadJSON, _ := json.Marshal(payload)
message := title
if errMsg != "" {
message = fmt.Sprintf("%s: %s", title, errMsg)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if status == oauthFlowSuccess {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusBadRequest)
}
_, _ = fmt.Fprintf(
w,
"<!doctype html><html><head><meta charset=\"utf-8\"><title>PicoClaw OAuth</title></head><body><script>(function(){var payload=%s;var hasOpener=false;try{if(window.opener&&!window.opener.closed){window.opener.postMessage(payload,window.location.origin);hasOpener=true}}catch(e){}var target='/credentials?oauth_flow_id='+encodeURIComponent(payload.flowId||'')+'&oauth_status='+encodeURIComponent(payload.status||'');setTimeout(function(){if(hasOpener){window.close();return}window.location.replace(target)},800)})();</script><div style=\"font-family:Inter,system-ui,sans-serif;padding:24px\"><h2>%s</h2><p>%s</p><p>You can close this window.</p></div></body></html>",
string(payloadJSON),
html.EscapeString(title),
html.EscapeString(message),
)
}
func normalizeOAuthProvider(raw string) (string, error) {
provider := strings.ToLower(strings.TrimSpace(raw))
switch provider {
case "antigravity":
return oauthProviderGoogleAntigravity, nil
case oauthProviderOpenAI, oauthProviderAnthropic, oauthProviderGoogleAntigravity:
return provider, nil
default:
return "", fmt.Errorf("unsupported provider %q", raw)
}
}
func isOAuthMethodSupported(provider, method string) bool {
methods := oauthProviderMethods[provider]
for _, m := range methods {
if m == method {
return true
}
}
return false
}
func oauthConfigForProvider(provider string) (auth.OAuthProviderConfig, error) {
switch provider {
case oauthProviderOpenAI:
return auth.OpenAIOAuthConfig(), nil
case oauthProviderGoogleAntigravity:
return auth.GoogleAntigravityOAuthConfig(), nil
default:
return auth.OAuthProviderConfig{}, fmt.Errorf("provider %q does not support browser oauth", provider)
}
}
func oauthMethodTokenOrOAuth(method string) string {
if method == oauthMethodToken {
return oauthMethodToken
}
return "oauth"
}
func buildOAuthRedirectURI(r *http.Request) string {
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwarded != "" {
scheme = strings.Split(forwarded, ",")[0]
}
return fmt.Sprintf("%s://%s/oauth/callback", scheme, r.Host)
}
func flowToResponse(flow *oauthFlow) oauthFlowResponse {
resp := oauthFlowResponse{
FlowID: flow.ID,
Provider: flow.Provider,
Method: flow.Method,
Status: flow.Status,
Error: flow.Error,
}
if !flow.ExpiresAt.IsZero() {
resp.ExpiresAt = flow.ExpiresAt.Format(time.RFC3339)
}
if flow.Method == oauthMethodDeviceCode {
resp.UserCode = flow.UserCode
resp.VerifyURL = flow.VerifyURL
resp.Interval = flow.Interval
}
return resp
}
func newOAuthFlowID() string {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
return fmt.Sprintf("oauth_%d", time.Now().UnixNano())
}
return hex.EncodeToString(buf)
}
func (h *Handler) storeOAuthFlow(flow *oauthFlow) {
now := oauthNow()
h.oauthMu.Lock()
defer h.oauthMu.Unlock()
h.gcOAuthFlowsLocked(now)
h.oauthFlows[flow.ID] = flow
if flow.OAuthState != "" {
h.oauthState[flow.OAuthState] = flow.ID
}
}
func (h *Handler) getOAuthFlow(flowID string) (*oauthFlow, bool) {
now := oauthNow()
h.oauthMu.Lock()
defer h.oauthMu.Unlock()
h.gcOAuthFlowsLocked(now)
flow, ok := h.oauthFlows[flowID]
if !ok {
return nil, false
}
cp := *flow
return &cp, true
}
func (h *Handler) getOAuthFlowByState(state string) (*oauthFlow, bool) {
now := oauthNow()
h.oauthMu.Lock()
defer h.oauthMu.Unlock()
h.gcOAuthFlowsLocked(now)
flowID, ok := h.oauthState[state]
if !ok {
return nil, false
}
flow, ok := h.oauthFlows[flowID]
if !ok {
delete(h.oauthState, state)
return nil, false
}
cp := *flow
return &cp, true
}
func (h *Handler) setOAuthFlowSuccess(flowID string) {
now := oauthNow()
h.oauthMu.Lock()
defer h.oauthMu.Unlock()
flow, ok := h.oauthFlows[flowID]
if !ok {
return
}
flow.Status = oauthFlowSuccess
flow.Error = ""
flow.UpdatedAt = now
if flow.OAuthState != "" {
delete(h.oauthState, flow.OAuthState)
}
}
func (h *Handler) setOAuthFlowError(flowID, errMsg string) {
now := oauthNow()
h.oauthMu.Lock()
defer h.oauthMu.Unlock()
flow, ok := h.oauthFlows[flowID]
if !ok {
return
}
flow.Status = oauthFlowError
flow.Error = errMsg
flow.UpdatedAt = now
if flow.OAuthState != "" {
delete(h.oauthState, flow.OAuthState)
}
}
func (h *Handler) gcOAuthFlowsLocked(now time.Time) {
for id, flow := range h.oauthFlows {
if flow.Status == oauthFlowPending && !flow.ExpiresAt.IsZero() && now.After(flow.ExpiresAt) {
flow.Status = oauthFlowExpired
flow.Error = "flow expired"
flow.UpdatedAt = now
if flow.OAuthState != "" {
delete(h.oauthState, flow.OAuthState)
}
}
if flow.Status != oauthFlowPending && now.Sub(flow.UpdatedAt) > oauthTerminalFlowGC {
if flow.OAuthState != "" {
delete(h.oauthState, flow.OAuthState)
}
delete(h.oauthFlows, id)
}
}
}
func (h *Handler) persistCredentialAndConfig(provider, authMethod string, cred *auth.AuthCredential) error {
if cred == nil {
return fmt.Errorf("empty credential")
}
cp := *cred
cp.Provider = provider
if cp.AuthMethod == "" {
cp.AuthMethod = authMethod
}
if provider == oauthProviderGoogleAntigravity {
if cp.Email == "" {
email, err := oauthFetchGoogleUserEmailFunc(cp.AccessToken)
if err != nil {
logger.ErrorC("oauth", fmt.Sprintf("oauth warning: could not fetch google email: %v", err))
} else {
cp.Email = email
}
}
if cp.ProjectID == "" {
projectID, err := oauthFetchAntigravityProject(cp.AccessToken)
if err != nil {
logger.ErrorC("oauth", fmt.Sprintf("oauth warning: could not fetch antigravity project id: %v", err))
} else {
cp.ProjectID = projectID
}
}
}
if err := oauthSetCredential(provider, &cp); err != nil {
return fmt.Errorf("saving credential: %w", err)
}
if err := h.syncProviderAuthMethod(provider, authMethod); err != nil {
return fmt.Errorf("syncing provider auth config: %w", err)
}
return nil
}
func (h *Handler) syncProviderAuthMethod(provider, authMethod string) error {
cfg, err := oauthLoadConfig(h.configPath)
if err != nil {
return err
}
found := false
for i := range cfg.ModelList {
if modelBelongsToProvider(provider, cfg.ModelList[i]) {
cfg.ModelList[i].AuthMethod = authMethod
found = true
}
}
if !found && authMethod != "" {
cfg.ModelList = append(cfg.ModelList, defaultModelConfigForProvider(provider, authMethod))
}
return oauthSaveConfig(h.configPath, cfg)
}
func modelBelongsToProvider(provider string, modelCfg *config.ModelConfig) bool {
protocol, _ := providers.ExtractProtocol(modelCfg)
switch provider {
case oauthProviderOpenAI:
return protocol == "openai"
case oauthProviderAnthropic:
return protocol == "anthropic"
case oauthProviderGoogleAntigravity:
return protocol == "antigravity"
default:
return false
}
}
func defaultModelConfigForProvider(provider, authMethod string) *config.ModelConfig {
switch provider {
case oauthProviderOpenAI:
return &config.ModelConfig{
ModelName: "gpt-5.4",
Provider: "openai",
Model: "gpt-5.4",
AuthMethod: authMethod,
}
case oauthProviderAnthropic:
return &config.ModelConfig{
ModelName: "claude-sonnet-4.6",
Provider: "anthropic",
Model: "claude-sonnet-4.6",
AuthMethod: authMethod,
}
case oauthProviderGoogleAntigravity:
return &config.ModelConfig{
ModelName: "gemini-flash",
Provider: "antigravity",
Model: "gemini-3-flash",
AuthMethod: authMethod,
}
default:
return &config.ModelConfig{}
}
}
func fetchGoogleUserEmail(accessToken string) (string, error) {
req, err := http.NewRequest(http.MethodGet, "https://www.googleapis.com/oauth2/v2/userinfo", nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("userinfo request failed: %s", string(body))
}
var userInfo struct {
Email string `json:"email"`
}
if err := json.Unmarshal(body, &userInfo); err != nil {
return "", err
}
if userInfo.Email == "" {
return "", fmt.Errorf("empty email in userinfo response")
}
return userInfo.Email, nil
}
-337
View File
@@ -1,337 +0,0 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/sipeed/picoclaw/pkg/auth"
"github.com/sipeed/picoclaw/pkg/config"
)
func TestOAuthLoginRejectsUnsupportedMethod(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
resetOAuthHooks(t)
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPost,
"/api/oauth/login",
strings.NewReader(`{"provider":"anthropic","method":"browser"}`),
)
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
}
}
func TestOAuthBrowserFlowCreatedAndQueried(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
resetOAuthHooks(t)
oauthGeneratePKCE = func() (auth.PKCECodes, error) {
return auth.PKCECodes{CodeVerifier: "verifier-1", CodeChallenge: "challenge-1"}, nil
}
oauthGenerateState = func() (string, error) { return "state-1", nil }
oauthBuildAuthorizeURL = func(cfg auth.OAuthProviderConfig, pkce auth.PKCECodes, state, redirectURI string) string {
return "https://example.com/authorize?state=" + state
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodPost,
"/api/oauth/login",
strings.NewReader(`{"provider":"openai","method":"browser"}`),
)
req.Host = "localhost:18800"
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
var loginResp map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &loginResp); err != nil {
t.Fatalf("unmarshal login response: %v", err)
}
flowID, _ := loginResp["flow_id"].(string)
if flowID == "" {
t.Fatalf("flow_id is empty: %v", loginResp)
}
if loginResp["auth_url"] != "https://example.com/authorize?state=state-1" {
t.Fatalf("unexpected auth_url: %v", loginResp["auth_url"])
}
rec2 := httptest.NewRecorder()
req2 := httptest.NewRequest(http.MethodGet, "/api/oauth/flows/"+flowID, nil)
mux.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("flow status code = %d, want %d, body=%s", rec2.Code, http.StatusOK, rec2.Body.String())
}
var flowResp oauthFlowResponse
if err := json.Unmarshal(rec2.Body.Bytes(), &flowResp); err != nil {
t.Fatalf("unmarshal flow response: %v", err)
}
if flowResp.Status != oauthFlowPending {
t.Fatalf("flow status = %q, want %q", flowResp.Status, oauthFlowPending)
}
if flowResp.Method != oauthMethodBrowser {
t.Fatalf("flow method = %q, want %q", flowResp.Method, oauthMethodBrowser)
}
}
func TestOAuthFlowExpiresWhenQueried(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
resetOAuthHooks(t)
now := time.Date(2026, 3, 6, 12, 0, 0, 0, time.UTC)
oauthNow = func() time.Time { return now }
h := NewHandler(configPath)
h.storeOAuthFlow(&oauthFlow{
ID: "expired-flow",
Provider: oauthProviderOpenAI,
Method: oauthMethodBrowser,
Status: oauthFlowPending,
CreatedAt: now.Add(-20 * time.Minute),
UpdatedAt: now.Add(-20 * time.Minute),
ExpiresAt: now.Add(-1 * time.Minute),
})
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/oauth/flows/expired-flow", nil)
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
var flowResp oauthFlowResponse
if err := json.Unmarshal(rec.Body.Bytes(), &flowResp); err != nil {
t.Fatalf("unmarshal flow response: %v", err)
}
if flowResp.Status != oauthFlowExpired {
t.Fatalf("flow status = %q, want %q", flowResp.Status, oauthFlowExpired)
}
}
func TestOAuthCallbackUnknownState(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
resetOAuthHooks(t)
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?state=unknown&code=abc", nil)
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest)
}
if !strings.Contains(rec.Body.String(), "OAuth flow not found") {
t.Fatalf("unexpected body: %s", rec.Body.String())
}
}
func TestOAuthLogoutClearsCredentialAndConfig(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
resetOAuthHooks(t)
cfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig error: %v", err)
}
cfg.ModelList = append(cfg.ModelList, &config.ModelConfig{
ModelName: "gpt-5.4",
Model: "openai/gpt-5.4",
AuthMethod: "oauth",
})
if err = config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig error: %v", err)
}
if err = auth.SetCredential(oauthProviderOpenAI, &auth.AuthCredential{
AccessToken: "token-before-logout",
Provider: oauthProviderOpenAI,
AuthMethod: "oauth",
}); err != nil {
t.Fatalf("SetCredential error: %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/oauth/logout", bytes.NewBufferString(`{"provider":"openai"}`))
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
cred, err := auth.GetCredential(oauthProviderOpenAI)
if err != nil {
t.Fatalf("GetCredential error: %v", err)
}
if cred != nil {
t.Fatalf("expected credential deleted, got %#v", cred)
}
updated, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig error: %v", err)
}
for _, m := range updated.ModelList {
if strings.HasPrefix(m.Model, "openai/") && m.AuthMethod != "" {
t.Fatalf("openai model auth_method = %q, want empty", m.AuthMethod)
}
}
}
func TestOAuthLogoutClearsAuthMethodForExplicitProviderField(t *testing.T) {
configPath, cleanup := setupOAuthTestEnv(t)
defer cleanup()
resetOAuthHooks(t)
cfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig error: %v", err)
}
cfg.ModelList = append(cfg.ModelList, &config.ModelConfig{
ModelName: "gpt-5.4",
Provider: "openai",
Model: "gpt-5.4",
AuthMethod: "oauth",
})
if err = config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig error: %v", err)
}
if err = auth.SetCredential(oauthProviderOpenAI, &auth.AuthCredential{
AccessToken: "token-before-logout",
Provider: oauthProviderOpenAI,
AuthMethod: "oauth",
}); err != nil {
t.Fatalf("SetCredential error: %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/oauth/logout", bytes.NewBufferString(`{"provider":"openai"}`))
req.Header.Set("Content-Type", "application/json")
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
updated, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig error: %v", err)
}
if got := updated.ModelList[len(updated.ModelList)-1].AuthMethod; got != "" {
t.Fatalf("auth_method = %q, want empty", got)
}
}
func setupOAuthTestEnv(t *testing.T) (string, func()) {
t.Helper()
tmp := t.TempDir()
oldHome := os.Getenv("HOME")
oldPicoHome := os.Getenv("PICOCLAW_HOME")
if err := os.Setenv("HOME", tmp); err != nil {
t.Fatalf("set HOME: %v", err)
}
if err := os.Setenv("PICOCLAW_HOME", filepath.Join(tmp, ".picoclaw")); err != nil {
t.Fatalf("set PICOCLAW_HOME: %v", err)
}
cfg := config.DefaultConfig()
cfg.ModelList = []*config.ModelConfig{{
ModelName: "custom-default",
Model: "openai/gpt-4o",
APIKeys: config.SimpleSecureStrings("sk-default"),
}}
cfg.Agents.Defaults.ModelName = "custom-default"
configPath := filepath.Join(tmp, "config.json")
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig error: %v", err)
}
cleanup := func() {
_ = os.Setenv("HOME", oldHome)
if oldPicoHome == "" {
_ = os.Unsetenv("PICOCLAW_HOME")
} else {
_ = os.Setenv("PICOCLAW_HOME", oldPicoHome)
}
}
return configPath, cleanup
}
func resetOAuthHooks(t *testing.T) {
t.Helper()
origNow := oauthNow
origGeneratePKCE := oauthGeneratePKCE
origGenerateState := oauthGenerateState
origBuildAuthorizeURL := oauthBuildAuthorizeURL
origRequestDeviceCode := oauthRequestDeviceCode
origPollDeviceCodeOnce := oauthPollDeviceCodeOnce
origExchangeCodeForTokens := oauthExchangeCodeForTokens
origGetCredential := oauthGetCredential
origSetCredential := oauthSetCredential
origDeleteCredential := oauthDeleteCredential
origLoadConfig := oauthLoadConfig
origSaveConfig := oauthSaveConfig
origFetchProject := oauthFetchAntigravityProject
origFetchGoogleEmail := oauthFetchGoogleUserEmailFunc
t.Cleanup(func() {
oauthNow = origNow
oauthGeneratePKCE = origGeneratePKCE
oauthGenerateState = origGenerateState
oauthBuildAuthorizeURL = origBuildAuthorizeURL
oauthRequestDeviceCode = origRequestDeviceCode
oauthPollDeviceCodeOnce = origPollDeviceCodeOnce
oauthExchangeCodeForTokens = origExchangeCodeForTokens
oauthGetCredential = origGetCredential
oauthSetCredential = origSetCredential
oauthDeleteCredential = origDeleteCredential
oauthLoadConfig = origLoadConfig
oauthSaveConfig = origSaveConfig
oauthFetchAntigravityProject = origFetchProject
oauthFetchGoogleUserEmailFunc = origFetchGoogleEmail
})
}
-310
View File
@@ -1,310 +0,0 @@
package api
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
"time"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/logger"
ppid "github.com/sipeed/picoclaw/pkg/pid"
)
// registerPicoRoutes binds Pico Channel management endpoints to the ServeMux.
func (h *Handler) registerPicoRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/pico/info", h.handleGetPicoInfo)
mux.HandleFunc("POST /api/pico/token", h.handleRegenPicoToken)
mux.HandleFunc("POST /api/pico/setup", h.handlePicoSetup)
// WebSocket proxy: forward /pico/ws to gateway
// This allows the frontend to connect via the same port as the web UI,
// avoiding the need to expose extra ports for WebSocket communication.
mux.HandleFunc("GET /pico/ws", h.handleWebSocketProxy())
mux.HandleFunc("GET /pico/media/{id}", h.handlePicoMediaProxy())
mux.HandleFunc("HEAD /pico/media/{id}", h.handlePicoMediaProxy())
}
// createWsProxy creates a reverse proxy to the current gateway WebSocket endpoint.
// The gateway bind host and port are resolved from the latest configuration.
func (h *Handler) createWsProxy(origProtocol string, upstreamProtocol string) *httputil.ReverseProxy {
wsProxy := &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
target := h.gatewayProxyURL()
r.SetURL(target)
r.Out.Header.Del(protocolKey)
if upstreamProtocol != "" {
r.Out.Header.Set(protocolKey, upstreamProtocol)
}
},
ModifyResponse: func(r *http.Response) error {
if prot := r.Header.Values(protocolKey); len(prot) > 0 {
r.Header.Del(protocolKey)
if origProtocol != "" {
r.Header.Set(protocolKey, origProtocol)
}
}
return nil
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
logger.Errorf("Failed to proxy WebSocket: %v", err)
http.Error(w, "Gateway unavailable: "+err.Error(), http.StatusBadGateway)
},
}
return wsProxy
}
func (h *Handler) createPicoHTTPProxy(token string) *httputil.ReverseProxy {
return &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
target := h.gatewayProxyURL()
r.SetURL(target)
r.Out.Header.Set("Authorization", "Bearer "+token)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
logger.Errorf("Failed to proxy Pico HTTP request: %v", err)
http.Error(w, "Gateway unavailable: "+err.Error(), http.StatusBadGateway)
},
}
}
func (h *Handler) gatewayAvailableForProxy() bool {
gateway.mu.Lock()
ensurePicoTokenCachedLocked(h.configPath)
cachedPID := gateway.pidData
trackedCmd := gateway.cmd
gateway.mu.Unlock()
if pidData := h.sanitizeGatewayPidData(ppid.ReadPidFileWithCheck(globalConfigDir()), nil); pidData != nil {
gateway.mu.Lock()
gateway.pidData = pidData
setGatewayRuntimeStatusLocked("running")
gateway.mu.Unlock()
return true
}
if cachedPID == nil {
return false
}
if isCmdProcessAliveLocked(trackedCmd) {
return true
}
gateway.mu.Lock()
if gateway.cmd == trackedCmd {
gateway.pidData = nil
setGatewayRuntimeStatusLocked("stopped")
}
available := gateway.pidData != nil
gateway.mu.Unlock()
return available
}
func decodePicoSettings(cfg *config.Config) (config.PicoSettings, bool) {
if cfg == nil {
return config.PicoSettings{}, false
}
bc := cfg.Channels.GetByType(config.ChannelPico)
if bc == nil {
return config.PicoSettings{}, false
}
var picoCfg config.PicoSettings
if err := bc.Decode(&picoCfg); err != nil {
return config.PicoSettings{}, false
}
return picoCfg, bc.Enabled
}
func (h *Handler) writePicoInfoResponse(
w http.ResponseWriter,
r *http.Request,
cfg *config.Config,
changed *bool,
) {
picoCfg, enabled := decodePicoSettings(cfg)
resp := map[string]any{
"ws_url": h.buildWsURL(r),
"enabled": enabled,
}
if changed != nil {
resp["changed"] = *changed
}
if picoCfg.Token.String() != "" {
resp["configured"] = true
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
// handleWebSocketProxy wraps a reverse proxy to handle WebSocket connections.
// It relies on launcher dashboard auth, then injects the raw pico token only
// on the upstream gateway request.
func (h *Handler) handleWebSocketProxy() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !h.gatewayAvailableForProxy() {
logger.Warnf("Gateway not available for WebSocket proxy")
http.Error(w, "Gateway not available", http.StatusServiceUnavailable)
return
}
upstreamProtocol := picoGatewayProtocol()
if upstreamProtocol == "" {
logger.Warn("Pico token unavailable for WebSocket proxy")
http.Error(w, "Pico channel not configured", http.StatusServiceUnavailable)
return
}
var origProtocol string
if prot := r.Header.Values(protocolKey); len(prot) > 0 {
origProtocol = prot[0]
}
h.createWsProxy(origProtocol, upstreamProtocol).ServeHTTP(w, r)
}
}
func (h *Handler) handlePicoMediaProxy() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !h.gatewayAvailableForProxy() {
logger.Warnf("Gateway not available for Pico media proxy")
http.Error(w, "Gateway not available", http.StatusServiceUnavailable)
return
}
gateway.mu.Lock()
picoToken := gateway.picoToken
gateway.mu.Unlock()
if picoToken == "" {
logger.Warnf("Missing Pico token for media proxy")
http.Error(w, "Invalid Pico token", http.StatusForbidden)
return
}
h.createPicoHTTPProxy(picoToken).ServeHTTP(w, r)
}
}
// handleGetPicoInfo returns non-secret Pico connection info for the launcher UI.
//
// GET /api/pico/info
func (h *Handler) handleGetPicoInfo(w http.ResponseWriter, r *http.Request) {
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
h.writePicoInfoResponse(w, r, cfg, nil)
}
// handleRegenPicoToken rotates the raw Pico WebSocket token and returns
// non-secret connection info for the launcher UI.
//
// POST /api/pico/token
func (h *Handler) handleRegenPicoToken(w http.ResponseWriter, r *http.Request) {
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
token := generateSecureToken()
if bc := cfg.Channels.GetByType(config.ChannelPico); bc != nil {
decoded, err := bc.GetDecoded()
if err == nil && decoded != nil {
if settings, ok := decoded.(*config.PicoSettings); ok {
settings.Token = *config.NewSecureString(token)
}
}
}
if err := config.SaveConfig(h.configPath, cfg); err != nil {
http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError)
return
}
gateway.mu.Lock()
gateway.picoToken = token
gateway.mu.Unlock()
h.writePicoInfoResponse(w, r, cfg, nil)
}
// EnsurePicoChannel enables the Pico channel with sane defaults if it isn't
// already configured. Returns true when the config was modified.
func (h *Handler) EnsurePicoChannel() (bool, error) {
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
return false, fmt.Errorf("failed to load config: %w", err)
}
changed := false
bc := cfg.Channels.GetByType(config.ChannelPico)
if bc == nil {
bc = &config.Channel{Type: config.ChannelPico}
cfg.Channels["pico"] = bc
}
if !bc.Enabled {
bc.Enabled = true
changed = true
}
if decoded, err := bc.GetDecoded(); err == nil && decoded != nil {
if picoCfg, ok := decoded.(*config.PicoSettings); ok {
if picoCfg.Token.String() == "" {
picoCfg.Token = *config.NewSecureString(generateSecureToken())
changed = true
}
}
}
if changed {
if err := config.SaveConfig(h.configPath, cfg); err != nil {
return false, fmt.Errorf("failed to save config: %w", err)
}
}
return changed, nil
}
// handlePicoSetup automatically configures everything needed for the Pico Channel to work.
//
// POST /api/pico/setup
func (h *Handler) handlePicoSetup(w http.ResponseWriter, r *http.Request) {
changed, err := h.EnsurePicoChannel()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Reload config (EnsurePicoChannel may have modified it).
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
h.writePicoInfoResponse(w, r, cfg, &changed)
}
// generateSecureToken creates a random 32-character hex string.
func generateSecureToken() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
// Fallback to something pseudo-random if crypto/rand fails
return fmt.Sprintf("%032x", time.Now().UnixNano())
}
return hex.EncodeToString(b)
}
Loaded 100 of 358 files, more files were not shown because too many files have changed in this diff. Show more